Zsh – Make ALT+BACKSPACE Stop at Non-Alphanumeric Characters

command linekeyboard shortcutszsh

In zsh by default, CTRL+w and ALT+Backspace seem to have exactly same effect.

How can I keep CTRL+w as it is, and change ALT+Backspace so that it stops at non-alphanumeric characters.

ie, when the cursor is at the end of following command: echo /aaa/bbb/ccc, pressing CTRL+w should leave echo, while pressing ALT+Backspace should leave echo /aaa/bbb/.

UPDATE

based on answer from @Thomas Dickey, I have added the following to my .zshrc:

 my-backward-delete-word () {
    local WORDCHARS='~!#$%^&*(){}[]<>?+;'
    zle backward-delete-word
 }
 zle -N my-backward-delete-word

 bindkey    '\e^?' my-backward-delete-word

Now the command line editor behaves differently than I expected.

For example, the single quote character ' is not enumerated in my WORDCHARS, so when I press Alt+BackSpace, the backward-delete-word should stop at '.

This works in in first example, but not in the second:

$ echo 'asdf'
$ echo '

$ echo '=asdf'
$ echo '=
$

in the second example, I had echo '= left on the commandline. After I have pressed Alt+BackSpace second time, everything was eaten, including echo. I would have expected only = should have been eaten, because it should have stopped at '.

Why is this not working as expected?

Best Answer

Actually I don't see this listed in zsh bindings, but if bindkey shows it for you, then it's configurable by binding to a function that you define.

Working from my answer in

    i use this bit contributed by someone on the list (Oliver Kiddle); check
    the archives from Mon, Oct. 8 for more info on this:

    tcsh-backward-delete-word () {
      local WORDCHARS="${WORDCHARS:s#/#}"
      zle backward-delete-word
    }

    i have it bound to control-W with:
    bindkey '^W' tcsh-backward-delete-word

    but you can change that obviously.

    i think that's what you're looking for, no?

    the '$WORDCHARS' variable is how zsh determines word boundaries so you
    could add '/' to that globally, however this might affect other things
    you want to leave it for, so i prefer this function.

So: you can use $WORDCHARS as a local variable in your own function, defining words as you want, and binding it to an arbitrary key.

When you define your function, don't forget to add it as a keymap:

zle -N tcsh-backward-delete-word
Related Question