24

I want to delete a word by Ctrl+W in zsh like.

vim /foo/bar^W
vim /foo/

And found a solution for bash, but bind is not in zsh function.

Is it possible to configure ctrl-w (delete word)?

How can I configure Ctrl+W as a delete-word?

ironsand
  • 5,085
  • 12
  • 50
  • 73
  • See http://zsh.sourceforge.net/Doc/Release/User-Contributions.html#Widgets-1 and https://unix.stackexchange.com/search?q=select-word-style and – Stéphane Chazelas Dec 21 '15 at 11:37

3 Answers3

25

Here's a snippet from .zshrc i've been using:

my-backward-delete-word() {
    local WORDCHARS=${WORDCHARS/\//}
    zle backward-delete-word
}
zle -N my-backward-delete-word
bindkey '^W' my-backward-delete-word

I recall this was the original source: http://www.zsh.org/mla/users/2001/msg00870.html

Joe
  • 534
  • 4
  • 9
  • The default `emacs` key binding table in ZLE binds ^W to `backward-kill-word` rather than to `backward-delete-word`, note. – JdeBP Dec 21 '15 at 13:59
16

Just for your information, I found this solution here to be far more elegant. I quote:

Another option is to set WORDCHARS (non-alphanumeric chars treated as part of a word) to something that doesn't include /.

You can also tweak this if you'd prefer ^w to break on dot, underscore, etc. In ~/.zshrc I have:

WORDCHARS='*?_-.[]~=&;!#$%^(){}<>'

UPDATE (2/Mar/2020)

As @Patryk pointed out on the comments below, this doesn't work for ZSH >= 5.7. Here is an update that I tested and work on zsh 5.8 (x86_64-apple-darwin18.7.0).

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

export WORDCHARS='.-'
8

None of the answers so far provide all the properties that bash has. Namely:

  • CTRL-w deletes any non-space char.
  • CTRL-w puts the text in the kill ring (so it can then be pasted with CTRL-y).
  • CTRL-w appends the text to the kill ring upon subsequent kill commands (CTRL-w, alt-backspace, alt-d, etc).

Moreover, we don't want to set WORDCHARS globally as it affects other functions.

Here is a solution that satisfies all the above:

        # Ctrl-w - delete a full WORD (including colon, dot, comma, quotes...)
        my-backward-kill-word () {
            # Add colon, comma, single/double quotes to word chars
            local WORDCHARS='*?_-.[]~=/&;!#$%^(){}<>:,"'"'"
            zle -f kill # Append to the kill ring on subsequent kills.
            zle backward-kill-word
        }
        zle -N my-backward-kill-word
        bindkey '^w' my-backward-kill-word
sitaktif
  • 183
  • 1
  • 4