0

My script foo takes directories in given path /foo/path as argument, plus it has one optional argument -l.

I have this completion file:

#compdef foo

 _arguments : \
    '-l' \
    '*: :->directory'

 case $state in
    directory)
        _directories -W /foo/path
 ;;
 esac

I am having followng issues with the completion:

When I use a wrong (non-existent) optional argument, for example -c, and then press tab

foo -c <TAB>

then it automatically completes the existent option -l, as if the directory completion has been eliminated bu the non-existent option -c.

This is strange, because I would have at least expected it will again offer both the directories, and -l.

But anyway, if wrong/non-existent option is provided, how can I stop the completions completely, to make clear that it cannot continue with wrong options?

1
  • With this code, I can't reproduce the behavior you decribe. After foo -c , if I press TAB, the completions offered are the directories. Commented Aug 20, 2021 at 20:55

1 Answer 1

2

With this code, I can't reproduce the behavior you decribe. After foo -c , if I press Tab, the completions offered are the directories.

Note that when you use states with _arguments, you should declare the variables it uses as local variables in the function. I don't think it matters in this simple case if there are no global variables with the same name.


I don't think there's a way to specify a behavior for all arguments beginning with -. To disable completions if there's an unrecognized option, I can't think of a better way than iterating over the arguments, i.e. the elements of words between 1 (command name, exclusive) and $CURRENT (word being completed, exclusive).

local context state state_descr line
typeset -A opt_args

 _arguments : \
  '-l' \
  '*: :->directory'

 local i
 for ((i = 2; i < CURRENT; i++)); do
   if [[ $words[$i] = -* && $words[$i] != -l ]]; then
     state=nothing
     break
   fi
 done

 case $state in
   directory)
     _directories -W /usr
   ;;
 esac
3
  • why are you declaring local context state state_descr line, when only state appears in the code? The other variables are not used at all. Commented Aug 21, 2021 at 3:57
  • and same with opt_args. Commented Aug 21, 2021 at 3:59
  • 1
    @400theCat They're used inside _arguments. See the documentation of _arguments. Commented Aug 21, 2021 at 8:33

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .