ZSH 完成基于之前的标志

标签 zsh oh-my-zsh zsh-completion

我正在尝试创建一个补全,其中我的补全之一将根据其他标志的值动态生成。例如

local state

_arguments \
  '-f[fabric]:fabric:->fabrics' \
  '-c[containers/application where log resides]:container:->containers' \
  '-l[name of log file]:log:->logs'

case "$state" in
    (fabrics)
        _values 'fabrics' \
          'fab1' \
          'fab2'
    ;;
(containers)
    _values 'containers' \
      'container1' \
      'container2'
    ;;
(logs)
    # show A B C if "-c container1" was entered
    # show D E F if "-c container2" was entered
    # show G if "-c" was not provided yet
esac

我无法动态生成“-l”标志。

最佳答案

我们可以检查$words:

Completion Special Parameters
...
Inside completion widgets, and any functions called from them, some parameters have special meaning;
...
words
This array contains the words present on the command line currently being edited.

-- zshcompwid(1): Completion Special Parameters, Completion Widgets

我们可以这样做:

(logs)
    local -i index=${words[(I)-c]}
    local -i ret=0
    if ((index == 0)); then
        _values 'logs' F
        ret=$?
    elif [[ "$words[index+1]" == container1 ]]; then
        _values 'logs' A B C
        ret=$?
    elif [[ "$words[index+1]" == container2 ]]; then
        _values 'logs' D E F
        ret=$?
    fi
    return ret

要检查数组,使用数组 Subscript Flags 很有用:

Subscript Flags
If the opening bracket, or the comma in a range, in any subscript expression is directly followed by an opening parenthesis, the string up to the matching closing one is considered to be a list of flags, as in name[(flags)exp].

-- zshparam(1), Subscript Flags, Array Subscripts, Array Parameters

所以,$words[(I)-c] 表示 I "flag"+ -c as "exp"for $words 是“数组 $word 中“-c”的最后一个匹配元素的索引”。例如:

 $ tmp=(my-test-command -f flag -c container1 -l)
 $ echo $tmp[(I)-c]
 4
 $ echo $tmp[(I)container1]
 5
 $ tmp=(my-test-command -f flag -c container1 -c container2 -l)
 $ echo $tmp[(I)-c]
 6

关于ZSH 完成基于之前的标志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46311615/

相关文章:

arrays - Zsh:将文件中的行读入数组

shell - 如何在没有 Ohmyzsh 的情况下完成不区分大小写的完成?

plugins - 错误 : you need to resolve your current index first plugins/macos/spotify: needs merge

bash - 如何在 Zsh 缩写后移动光标?

linux - 在 Linux 上哪里放置 zsh 自动完成脚本?

10.9 : widgets can only be called when ZLE is active 上的 ZSH

zsh 类似 iPython 的补全?

zsh - vi模式下绑定(bind)删除键

bash - zsh 或 bash 可以扩展引用目录的历史表达式吗?

zsh - 将 eval $(pyenv init -) 从 zsh 移动到 xonsh