zsh 完成虚拟路径 [英] zsh completion with virtual path

查看:26
本文介绍了zsh 完成虚拟路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为一个带有虚拟文件树的工具创建一个 zsh 补全.例如我的文件树如下所示:

I want to create a zsh completion for a tool with a virtual file tree. e.g. my file tree looks like the following:

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

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

My tool mycmd has a subcommand for listing the current directory:

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

我实际的 zsh 完成看起来是这样的:

My actual zsh completion looks like this:

_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 错误的实用功能.实际行为是:

IMHO is _values the wrong utility function. The actual behaviour is:

$ 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 因为文件树只是虚拟的.

I can't use the utility function _files or _path_files because the file tree is only virtual.

推荐答案

我建议使用 compadd 而不是 _values 来控制附加的后缀字符.然后查看可用的选项,设置一个空的后缀字符,以防虚拟目录是结果的一部分:

I would suggest to make use of compadd rather _values to get in control of the suffix character appended. Then looking at the available choices, set an empty suffix character in case a virtual directory is part of the result:

_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
}

这篇关于zsh 完成虚拟路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆