ZSH补全与虚拟路径

5

我希望为一个具有虚拟文件树的工具创建zsh补全功能。 例如,我的文件树如下所示:

/
|- foo/
|  |- bar
|  |- baz/
|     |- qux
|- foobar

我的工具mycmd有一个子命令,可以列出当前目录:

$ mycmd ls
foo/
foobar
$ mycmd ls foo/
bar
baz/

我的实际zsh自动完成看起来像这样:

_mycmd_ls() {
    if [ ! -z "$words[-1]" ]; then
        dir=$(dirname /$words[-1])
        lastpart=$(basename $words[-1])
        items=$(mycmd ls $dir | grep "^$lastpart")
    else
        items=$(mycmd ls)
    fi
    _values -s ' ' 'items' ${(uozf)items}
}


_mycmd() {
    local -a commands

    commands=(
        'ls:list items in directory'
    )

    _arguments -C -s -S -n \
        '(- 1 *)'{-v,--version}"[Show program\'s version number and exit]: :->full" \
        '(- 1 *)'{-h,--help}'[Show help message and exit]: :->full' \
        '1:cmd:->cmds' \
        '*:: :->args' \

    case "$state" in
        (cmds)
            _describe -t commands 'commands' commands
            ;;
        (args)
            _mycmd_ls
            ;;
        (*)
            ;;
    esac
}

_mycmd

在我看来,_values 是错误的实用程序函数。其实际行为是:

$ mycmd ls<TAB>
foo/    foobar
$ mycmd ls foo/<TAB>  ## <- it inserts automatically a space before <TAB> and so $words[-1] = ""
foo/    foobar

由于文件树只是虚拟的,所以我无法使用实用函数_files_path_files


我非常好奇是否有办法这样做。我也面临着同样类型的问题。 - Lery
1个回答

2

我建议使用compadd而不是_values来控制附加的后缀字符。然后查看可用的选择,在结果中包含虚拟目录的情况下设置一个空的后缀字符:

_mycmd_ls() {
    if [ ! -z "$words[-1]" ]; then
        dir=$(dirname /$words[-1])
        lastpart=$(basename $words[-1])
        items=$(mycmd ls $dir | grep "^$lastpart")
    else
        items=$(mycmd ls)
    fi

    local suffix=' ';
    # do not append space to word completed if it is a directory (ends with /)
    for val in $items; do
        if [ "${val: -1:1}" = '/' ]; then
            suffix=''
            break
        fi
    done

    compadd -S "$suffix" -a items
}

谢谢!我曾经苦于理解所有的完成工具函数和样式,而这段代码恰好做到了我想要的。 - Thomas K

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接