如何让 bash 为我的别名执行制表符补全?

dst*_*arh 51 bash tab-completion

我设置了一堆 bash 完成脚本(主要使用 bash-it 和一些手动设置)。

我还为诸如gcofor 之类的常见任务设置了一堆别名git checkout。现在我可以输入git checkout dTabdevelop为我完成,但是当我输入时gco dTab它没有完成。

我假设这是因为完成脚本正在完成git并且它看不到gco.

有没有办法以通用/编程方式让我的所有完成脚本与我的别名一起使用?使用别名类时无法完成就违背了别名的目的。

kop*_*hke 47

以下代码改编自此 Stack Overflow 答案和此Ubuntu 论坛讨论主题,将为您定义的所有别名添加补全:

# Automatically add completion for all aliases to commands having completion functions
function alias_completion {
    local namespace="alias_completion"

    # parse function based completion definitions, where capture group 2 => function and 3 => trigger
    local compl_regex='complete( +[^ ]+)* -F ([^ ]+) ("[^"]+"|[^ ]+)'
    # parse alias definitions, where capture group 1 => trigger, 2 => command, 3 => command arguments
    local alias_regex="alias ([^=]+)='(\"[^\"]+\"|[^ ]+)(( +[^ ]+)*)'"

    # create array of function completion triggers, keeping multi-word triggers together
    eval "local completions=($(complete -p | sed -Ene "/$compl_regex/s//'\3'/p"))"
    (( ${#completions[@]} == 0 )) && return 0

    # create temporary file for wrapper functions and completions
    rm -f "/tmp/${namespace}-*.tmp" # preliminary cleanup
    local tmp_file; tmp_file="$(mktemp "/tmp/${namespace}-${RANDOM}XXX.tmp")" || return 1

    local completion_loader; completion_loader="$(complete -p -D 2>/dev/null | sed -Ene 's/.* -F ([^ ]*).*/\1/p')"

    # read in "<alias> '<aliased command>' '<command args>'" lines from defined aliases
    local line; while read line; do
        eval "local alias_tokens; alias_tokens=($line)" 2>/dev/null || continue # some alias arg patterns cause an eval parse error
        local alias_name="${alias_tokens[0]}" alias_cmd="${alias_tokens[1]}" alias_args="${alias_tokens[2]# }"

        # skip aliases to pipes, boolean control structures and other command lists
        # (leveraging that eval errs out if $alias_args contains unquoted shell metacharacters)
        eval "local alias_arg_words; alias_arg_words=($alias_args)" 2>/dev/null || continue
        # avoid expanding wildcards
        read -a alias_arg_words <<< "$alias_args"

        # skip alias if there is no completion function triggered by the aliased command
        if [[ ! " ${completions[*]} " =~ " $alias_cmd " ]]; then
            if [[ -n "$completion_loader" ]]; then
                # force loading of completions for the aliased command
                eval "$completion_loader $alias_cmd"
                # 124 means completion loader was successful
                [[ $? -eq 124 ]] || continue
                completions+=($alias_cmd)
            else
                continue
            fi
        fi
        local new_completion="$(complete -p "$alias_cmd")"

        # create a wrapper inserting the alias arguments if any
        if [[ -n $alias_args ]]; then
            local compl_func="${new_completion/#* -F /}"; compl_func="${compl_func%% *}"
            # avoid recursive call loops by ignoring our own functions
            if [[ "${compl_func#_$namespace::}" == $compl_func ]]; then
                local compl_wrapper="_${namespace}::${alias_name}"
                    echo "function $compl_wrapper {
                        (( COMP_CWORD += ${#alias_arg_words[@]} ))
                        COMP_WORDS=($alias_cmd $alias_args \${COMP_WORDS[@]:1})
                        (( COMP_POINT -= \${#COMP_LINE} ))
                        COMP_LINE=\${COMP_LINE/$alias_name/$alias_cmd $alias_args}
                        (( COMP_POINT += \${#COMP_LINE} ))
                        $compl_func
                    }" >> "$tmp_file"
                    new_completion="${new_completion/ -F $compl_func / -F $compl_wrapper }"
            fi
        fi

        # replace completion trigger by alias
        new_completion="${new_completion% *} $alias_name"
        echo "$new_completion" >> "$tmp_file"
    done < <(alias -p | sed -Ene "s/$alias_regex/\1 '\2' '\3'/p")
    source "$tmp_file" && rm -f "$tmp_file"
}; alias_completion
Run Code Online (Sandbox Code Playgroud)

对于简单的(仅命令,无参数)别名,它会将原始完成功能分配给别名;对于带参数的别名,它创建一个包装函数,将额外的参数插入到原始完成函数中。

与它演变而来的脚本不同,该函数尊重别名命令及其参数的引号(但前者必须与完成命令匹配,并且不能嵌套),并且它应该可靠地过滤掉命令列表的别名和管道(它们被跳过,因为如果不重新创建完整的 shell 命令行解析逻辑,就不可能找出要在其中完成的内容)。

用法

将代码另存为 shell 脚本文件并在其中获取源代码,或者将函数批发复制到.bashrc(或您的相关点文件)中。重要的是在设置 bash 完成和别名定义之后调用该函数(上面的代码在定义后立即调用该函数,本着“源代码和忘记”的精神,但是如果那样的话,您可以将调用移动到下游的任何位置更适合你)。如果您不希望该函数退出后在您的环境中,您可以unset -f alias_completion在调用它后添加。

笔记

如果您使用bash4.1 或更高版本并使用动态加载的完成,脚本将尝试加载所有别名命令的完成,以便它可以为您的别名构建包装函数。


Cyk*_*ker 5

有没有办法以通用/编程方式让我的所有完成脚本与我的别名一起使用?

是的,这是完全别名项目,它可以准确地解决您的问题。它提供了通用和程序化的别名补全,而无需使用eval.


wis*_*cky 5

这是手动方式,对于那些正在寻找它的人。

首先,查找原始完成命令。例子:

$ complete | grep git

complete -o bashdefault -o default -o nospace -F __git_wrap__git_main git
Run Code Online (Sandbox Code Playgroud)

现在将这些添加到您的启动脚本中(例如 ~/.bashrc):

# load dynamically loaded completion functions (may not be required)
_completion_loader git

# copy the original statement, but replace the last command (git) with your alias (g)
complete -o bashdefault -o default -o nospace -F __git_wrap__git_main g
Run Code Online (Sandbox Code Playgroud)

来源:https : //superuser.com/a/1004334