【问题标题】:Bash completion broken on short optionsBash 补全因空头选项而中断
【发布时间】:2015-03-12 16:29:42
【问题描述】:

我创建了自己的 bash 完成函数。我做了几次编辑。完成本身适合我,但我在短选项-a-p-h 之后打破了自动空间。

意思是,当我输入editcfg -filTAB 时,它会自动完成到editcfg -file -file 后面的空格)。 但是,如果我键入 editcfg -pTAB,它不会在 -p 之后自动空格。

功能:

_editcfg () 
{ 
    local cur prev opts presets u_opts;
    COMPREPLY=();
    cur="${COMP_WORDS[COMP_CWORD]}";
    prev="${COMP_WORDS[COMP_CWORD-1]}";
    opts=("-n" "-p" "-file" "-a" "-verbose" "-version" "-h");
    presets=("default" "empty");
    u_opts=();
    for i in "${opts[@]}";
    do
        for j in "${COMP_WORDS[@]}";
        do
            if [[ "$i" == "$j" ]]; then
                continue 2;
            fi;
        done;
        u_opts+=("$i");
    done;
    case ${prev} in 
        -p)
            COMPREPLY=($(compgen -W "${presets[*]}" -- ${cur}));
            return 0
        ;;
        -file)
            COMPREPLY=($(compgen -fd -- ${cur} 2>/dev/null));
            return 0
        ;;
        -h | -version)
            u_opts=();
            return 0
        ;;
    esac;
    COMPREPLY=($(compgen -W "${u_opts[*]}" -- ${cur}));
    return 0
}

我错过了什么?

谢谢

【问题讨论】:

  • 如果您在continue 2 之后 将当前选项添加到u_opts 是否可以解决问题? editcfg -file<TAB> 加空格吗?
  • 添加 continue 2 并不能解决问题。 editcfg -file<TAB> 也没有完成。似乎仅在给出部分选项时。

标签: bash bash-completion


【解决方案1】:

我更新了第二个for 循环,它运行良好:

_editcfg () 
{ 
    local cur prev opts presets u_opts;
    COMPREPLY=();
    cur="${COMP_WORDS[COMP_CWORD]}";
    prev="${COMP_WORDS[COMP_CWORD-1]}";
    opts=("-n" "-p" "-file" "-a" "-verbose" "-version" "-h");
    presets=("default" "empty");
    u_opts=();
    for i in "${opts[@]}"; do
        for ((j = 0; j < COMP_CWORD; ++j)) do
            if [[ "$i" == "${COMP_WORDS[j]}" ]]; then
                continue 2;
            fi;
        done;
        u_opts+=("$i");
    done;
    case ${prev} in 
        -p)
            COMPREPLY=($(compgen -W "${presets[*]}" -- ${cur}));
            return 0
        ;;
        -file)
            COMPREPLY=($(compgen -fd -- ${cur} 2>/dev/null));
            return 0
        ;;
        -h | -version)
            u_opts=();
            return 0
        ;;
    esac;
    COMPREPLY=($(compgen -W "${u_opts[*]}" -- ${cur}));
    return 0
}

【讨论】:

  • 绝对有效。不明白为什么:(。还有for j in "!${COMP_WORDS[@]}" ...
  • 当你输入 -p&lt;TAB&gt; 时,数组 COMPREPLY 不会包含 -p,那么 Bash 会认为 当前单词 (-p) 无法自动完成COMPREPLY 中的任何字符串,因此 Bash 根本不会更改 当前单词。使用我的代码,COMPREPLY 将包含 -p,因此 Bash 会知道 当前单词 (-p) 可以自动完成到 COMPREPLY 中的字符串 (-p) 明确,所以它会自动补全字符串(从-p-p)并插入空格。
  • 用英语解释这种事情对我来说有点挑战。 :)
  • 我明白会发生什么,只是不知道为什么你的代码会发生而我的不会:) 没关系。至少它有效:) 谢谢!
猜你喜欢
  • 2011-12-14
  • 2015-02-15
  • 2014-12-18
  • 1970-01-01
  • 2013-04-09
  • 2012-08-12
  • 1970-01-01
  • 1970-01-01
  • 2011-10-10
相关资源
最近更新 更多