Subject: backward-kill-shell-word widget
From: Daniel Shahaf <[email-masked]>
To: [email-masked]
Date: Sun, Jan 01 2016 00:37:58 +0000
List-Id: Zsh Workers List <zsh-workers.zsh.org>

[ I mentioned this to IRC some weeks ago and Valodim told me about
select-word-style so I didn't post this to the list; but now, I'll post it
anyway in case there's a subtle difference that I'm overlooking.
Perhaps the interactive_comments test is such a difference? ]

This widget is like ^W but for "shell words" rather than
whitespace-separated words, so

    % echo foo "bar baz" <CURSOR>^W
    becomes
    % echo foo <CURSOR>

If you use zsh 5.1.1 or older, comment the 'zle -f' line.  (Without that
line, using this widget followed by another kill followed by a yank
won't include the text this widget killed in the yank.)

---

backward-kill-shell-word() {
  local MATCH; integer MBEGIN MEND
  integer start end_of_word end_of_cut=$CURSOR

  # Walk backwards to an end-of-word
  [[ $LBUFFER =~ '[[:space:]]*$' ]] || : # sets $MATCH
  (( end_of_word = CURSOR - $#MATCH ))

  # Find the start of the shell word ending at $BUFFER[end_of_word]
  () {
    local l="$PREBUFFER$LBUFFER[1,end_of_word]"
    local -a a
    if [[ -o interactive_comments ]]; then
      a=( ${(zZ+c+)l} )
    else
      a=( ${(z)l} )
    fi
    (( start = end_of_word - ${#a[-1]} + 1 ))
  }

  # Standard kill-widget behaviour
  zle -f 'kill'
  if [[ $LASTWIDGET == *'kill'* ]]; then
    CUTBUFFER=${BUFFER[start,end_of_cut]}$CUTBUFFER
  else
    zle copy-region-as-kill -- "${BUFFER[start,end_of_cut]}"
  fi

  # Delete the last shell word from $LBUFFER
  LBUFFER[start,end_of_cut]=""
}
zle -N backward-kill-shell-word
bindkey '^T' backward-kill-shell-word