Search code examples
zshzsh-completion

Zsh dependent completion with space in arguments


I'm trying to implement completion for a function, where the completion for the second argument depends on the first one.

function test_so() {
  echo "$1" "$2"
}
function _test_so() {
  local state

  _arguments '1: :->arg1' '2: :->arg2'

  case $state in
    arg1) compadd foo 'bar baz' ;;
    arg2)
      echo " - first arg: ${words[2]} - "
      if [[ ${words[2]} == 'bar baz' ]]; then
        compadd bar-1 bar-2
      else
        compadd foo-1 foo-2
      fi
    ;;
  esac
}
compdef _test_so test_so

However, it seems it's passing literal \ & 's in ${words[2]} for an argument with spaces:

$ test_so foo <tab> ... - first arg: foo -
foo-1
foo-2

$ test_so bar\ baz <tab> ... - first arg: bar\ baz - # <- Should be - first arg: bar baz -
foo-1
foo-2
# These should be bar-1 & bar-2

# Same thing for quotes
$ test_so 'bar baz' <tab> ... - first arg: 'bar baz' -
foo-1
foo-2

Solution

  • You can get rid of the \ by "unquoting" the word with the Q parameter expansion flag:

    ${(Q)words[2]}
    

    Now both bar\ baz and 'bar baz' on the command line will result in the same string in your code: bar baz.