【问题标题】:ZSH Completion based on previous flag基于先前标志的 ZSH 完成
【发布时间】:2018-02-28 21:34:04
【问题描述】:

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

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”标志。

【问题讨论】:

    标签: zsh oh-my-zsh zsh-completion


    【解决方案1】:

    我们可以检查$words:

    完成特殊参数
    ...
    在完成小部件内部,以及从它们调用的任何函数,一些参数具有特殊含义;
    ...
    words
    该数组包含当前正在编辑的命令行上的单词。

    -- 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 会很有用:

    下标标志
    如果任何下标表达式中的左括号或范围内的逗号直接后跟左括号,则匹配的右括号之前的字符串被视为标志列表,如name[(flags)exp]

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

    所以,$words[(I)-c] 意味着 I "flag" + -c 作为 $words 的 "exp",即 "数组 $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
    

    【讨论】:

    • 这太棒了!我得到了它的工作,但我不太了解第一个索引部分。你能解释一下 (I) 和 -c 是什么吗?
    • 已更新;我添加了一些示例/用法来检查带有下标标志的数组。
    猜你喜欢
    • 1970-01-01
    • 2012-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多