2

I want kill-word to turn ls Dir\ A/Long\ File\ Name into ls Dir\ A/ if I call it at the end of the line. I know I can delete to / by modifying $WORDCHARS, but I found no way to ignore escaped spaces.

2
  • @StéphaneChazelas I thought about that, but it doesn't appear to have a way to stop at a slash. Mar 9, 2021 at 14:08
  • @Gilles. Oops, I had overlooked that part of the requirements. Mar 9, 2021 at 15:08

2 Answers 2

3

There's no way to tell the built-in widget backward-kill-word (which kills the next word to the left of the cursor) to do that, but you can just roll your own:

backward-kill-word() { 
  # LBUFFER -- all text left of the cursor
  # (z)     -- split into shell words
  # (A)     -- force the resulting words into an array
  # [-1]    -- take the right-most element
  # :t      -- strip all path ancestors from it
  # %       -- remove the shortest matching substring from the right
  LBUFFER=${LBUFFER%${${(zA)LBUFFER}[-1]:t}*} 
  zle -f kill  # Tell the Zsh Line Editor that we've killed text.
}
zle -N backward-kill-word  # Replace the default widget.

Replacing kill-word (which kills the next word to the right of the cursor) is pretty similar:

kill-word() { 
  # RBUFFER -- all text to the right of the cursor
  # [1]     -- take the left-most element
  # :h1     -- strip all path descendants from it
  # #       -- remove the shortest matching substring from the left
  RBUFFER=${RBUFFER#*${${(zA)RBUFFER}[1]:h1}} 
  zle -f kill
}
zle -N kill-word
0

If you don't mind typing multiple keys, you can use ^R / ^K to go back to the previous slash then kill to the end of the line. If there are more words after the cursor initially, you can use ^@ ^R / ESC-x kill-region RET (unfortunately kill-region is not bound to a key by default; the Emacs binding of ^W is given to backward-kill-word instead for compatibility with standard cooked tty bindings).

In vi mode, starting in command mode and ending in insert mode, you can use something like T/C to delete to the end of the line, or vT/s or dT/s to delete until the original cursor location inclusive.


select-word-style shell may be of interest to you: it causes word motion to use shell syntax.

autoload -Uz select-word-style
select-word-style shell

Unfortunately it doesn't solve your problem because a slash is part of the word. I can't see a way to leverage it to stop at certain characters within words without changing the code of match-words-by-style.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .