参数中带有 space 的 Zsh 依赖补全

Zsh dependent completion with space in arguments

我正在尝试实现一个函数的完成,其中第二个参数的完成取决于第一个。

function test_so() {
  echo "" ""
}
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

但是,对于带空格的参数,它似乎在 ${words[2]} 中传递文字 \ & 's:

$ 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

您可以通过使用 Q parameter expansion flag:

“取消引号”来摆脱 \
${(Q)words[2]}

现在命令行上的 bar\ baz'bar baz' 将在您的代码中产生相同的字符串:bar baz.