我正在尝试创建一个补全,其中我的补全之一将根据其他标志的值动态生成。例如
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 inname[(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/