0

Can not figure out, how to get the bash-completion work with arguments containing "::" like that, because compgen or complete take each entry as seperate word, I guess.

cmd=./my_script
_my_options()
{
  local cur prev opts
  cur=${COMP_WORDS[COMP_CWORD]}
  prev=${COMP_WORDS[COMP_CWORD-1]}
  opts="NAMESPACE::param1 NAMESPACE::param2 NAMESPACE::param3 NAMESPACE2::param1 NAMESPACE2::param2"
  COMPREPLY=( $(compgen -W '$opts' -- $cur ) );
}
complete -F _my_options $cmd

Bash-Completion stops working here..

$ ./my_script <TAB>
$ ./my_script NAMESPACE
NAMESPACE2::param1  NAMESPACE::param1   NAMESPACE::param3
NAMESPACE2::param2  NAMESPACE::param2   

1. $ ./my_script NAMESPACE    <TAB> or <TAB><TAB> -> no effect
2. $ ./my_script NAMESPACE:   <TAB> or <TAB><TAB> -> no effect
3. $ ./my_script NAMESPACE::  <TAB> or <TAB><TAB> -> no effect
4. $ ./my_script NAMESPACE::p <TAB> or <TAB><TAB> -> no effect

COMP_WORDS are NAMESPACE, :: and param1 instead of only one string NAMESPACE::param1.

With quotes the autocomplete works, but I do not want to pass those quotes.

5. $ ./my_script "<TAB>
   $ ./my_script "NAMESPACE
   $ ./my_script "NAMESPACE:<TAB>
   $ ./my_script "NAMESPACE::param
   $ ./my_script "NAMESPACE::param1"
john s.
  • 476
  • 9
  • 21
  • 1
    for personal use the easy way is to remove char `:` from `$COMP_WORDBREAKS`. – pynexj May 01 '18 at 14:48
  • Thx @pynexj changing either `$COMP_WORDBREAKS` or using `_get_comp_words_by_ref` and `__ltrim_colon_completions` solved my problem. https://stackoverflow.com/a/12495480/5473325 – john s. May 02 '18 at 14:49

1 Answers1

0

I was having the same issue. It looks like the problem is that COMPREPLY is doing some mambojambo with the expansion of the colons.

To avoid that I have found two solutions:

  1. single-quote the completions
  2. escape the special characters (: in your case)

single-quote the completions

just wrap the output of compgen with single-quotes. Like this:

COMPREPLY=( $(compgen -W "$opts" -- $cur | awk '{ print "'\''"$0"'\''" }') );

Now, just hitting TAB will start the auto-complete with single-quotes. This is slightly better than having to insert the " before hitting TAB.

escape the special characters

just find the special characters and add an escape beforehand. Like so:

COMPREPLY=( $(compgen -W "$opts" -- $cur | sed 's/:/\\:/g' );

Now, you'll get ride of any quotes. But you'll pay the prise of having that \ before each colon.

NOTE

Note that both solution rely on the fact that the shell will interpret the argument and get rid of either the quotes or escapings.

SbiN
  • 83
  • 1
  • 7