Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: How to make tab add quotes on expansion?

On Oct 25,  1:00am, Hisham Muhammad wrote:
} I'd like to have tab-completion to add double quotes to words when the
} completed word has spaces in it (instead of having it add a backslash
} on each space).
} I know there's probably something simple I am missing

No, actually, there isn't anything simple.

The builtins that update the command line don't modify the part to the
left of the cursor unless they have explicitly been told to (by, e.g.
"compadd -U").  A side-effect is that this preserves the quoting that's
already in use on the line.  So if you type

hisham@aria ~] mpg123 "01<TAB>

you'll get

hisham@aria ~] mpg123 "01 - Tom Sawyer.mp3"

but if you start with no quotes at all, you'll get backslashes.

Rather than try to convince the completion system to rewrite every word,
I suggest creating a normal (not completion, i.e., "zle -N" rather than
"zle -C") widget which first inserts the double quote and then calls a
completion widget.  Of course your widget will have to test whether any
quote is already there, etc.  This would best be accomplished by getting
the latest 4.1.x-dev from SourceForge, and using match-words-by-style to
parse the command line for you.  (I *think* m-w-b-s could be backported
to 4.0.7, but I'm not sure.)

As an alternative, you could use something like this completer:

  function _force_quote {
    [[ -z $compstate[quoting] ]] &&
    compstate[to_end]='' &&
    compadd -U -S "$SUFFIX" -I "$ISUFFIX"\" -i \""$IPREFIX" "$PREFIX"

Plus this widget:

  function quote-and-complete-word {
    setopt localoptions unset noksharrays noshwordsplit
    local lbuf=$LBUFFER rbuf=$RBUFFER last=$LASTWIDGET
    if [[ $last != $WIDGET ]]
      local oldcontext="$curcontext"
      local curcontext="$WIDGET:${${curcontext:-:::}#*:}"
      zle complete-word
    zle complete-word
    local ret=$?
    if [[ $_lastcomp[nmatches] -eq 0 && $last != $WIDGET ]]
      LBUFFER=$lbuf RBUFFER=$rbuf
    return ret
  zle -N quote-and-complete-word

Plus this zstyle:

  zstyle ':completion:quote-and-complete-word:*' completer _force_quote

And finally

  bindkey '^I' quote-and-complete-word

However, this seems to confuse zsh's "undo" mechanism pretty badly, so
use at your own risk.

Messages sorted by: Reverse Date, Date, Thread, Author