gpt4 book ai didi

ZSH 完成基于之前的标志

转载 作者:行者123 更新时间:2023-12-04 03:09:35 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com