How can I have two keystrokes to delete to either a slash or a word in zsh?

A similar question was asked here: zsh: stop backward-kill-word on directory delimiter

and a workable solution given: add these settings to your zshrc:

autoload -U select-word-style
select-word-style bash

Edit: The next google result after your question was this one with same solution : zsh: make ALT+BACKSPACE stop at non-alphanumeric characters

This answer was provided by /nick FoH from #zsh on freenode.

backward-kill-dir () {
    local WORDCHARS=${WORDCHARS/\/}
    zle backward-kill-word
}
zle -N backward-kill-dir
bindkey '^[^?' backward-kill-dir

This way you can use ctrl+w for deleting a Word (in vim lingo) and alt+bkspc to delete a word


Expanding on JunkMechanic's answer, I wanted that

  • existing zsh shortcuts (CtrlW, Ctrl and Ctrl) works as in zsh defaults
  • Alt-based shortcuts (AltW, Alt and Alt) work similarly, but "finer grained", e.g. up to the closest /

Here's what I use now:

# Alt+Backspace
backward-kill-dir () {
    local WORDCHARS=${WORDCHARS/\/}
    zle backward-kill-word
}
zle -N backward-kill-dir
bindkey '^[^?' backward-kill-dir


# Alt+Left
backward-word-dir () {
    local WORDCHARS=${WORDCHARS/\/}
    zle backward-word
}
zle -N backward-word-dir
bindkey "^[[1;3D" backward-word-dir

# Alt+Right
forward-word-dir () {
    local WORDCHARS=${WORDCHARS/\/}
    zle forward-word
}
zle -N forward-word-dir
bindkey "^[[1;3C" forward-word-dir

Tags:

Zsh