Bash Command-Line Tab Completion Colon Character

2019-04-27 03:32发布

问题:

I have successfully implemented bash completions for my custom commands when the parameters contained no special characters in them, with the compgen mechanism:

    current=${COMP_WORDS[COMP_CWORD]}
    all=$(_get_all_items)
    COMPREPLY=( $(compgen -W "$all" -- $current) )
    ...
    complete -F _prog_compl prog

I use the same approach to complete items which start with a colon character: :first, :second, ... But it fails to show me / autocomplete them. I tried escaping colons with backslashes which didn't work either. How should I escape colons in completion?

The items are starting with colon, let's say: :first, :second. If I write progname and start with a colon like this:

$ progname :<Tab here after colon>

I see no completion but two colons ("::") - one of them automatically added to the line I type. If I convert the colon to an ordinary character (let's say 'b') I get completion exactly like I want: bfirst, bsecond...

It is relevant to note that when I press tab it places another ":" next to my previously inserted colon and it becomes "::".

$ bash --version
GNU bash, version 4.1.10(2)-release (i486-slackware-linux-gnu)
Copyright (C) 2009 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Additionally, I have made some experiments in the shell which yield:

$ compgen -W ":aaaa5 :gb2 :cd3" -- ":"
:aaaa5
:gb2
:cd3

Yet it strangely puts another ":" to my sole ":" and makes it "::" after I type : on the command line.

$ complete
complete -F _alp_compl alp.sh
complete -o nospace -F __dbus_send dbus-send
complete -F _myprog_compl myprog
complete -o nospace -F __gdbus gdbus
complete -o nospace -F __gsettings gsettings

回答1:

After consulting help-bash@gnu.org I got an answer:

The colon breaks words for the completion system (look at the description of the COMP_WORDBREAKS shell variable), so when you type

progname :[TAB]

the completion system gets an empty word to complete. If all of the possible completions have `:' as the longest common prefix, then the completion system will insert the colon into the line.

And my COMP_WORDBREAKS search yield me an answer from stackoverflow.

After fixing (my missing) /etc/bash_completion file from debian bash completion page, now, my colon-initiated completion is working as my will.