3

I have a script called , that takes a finite set of subcommands. Let's say this set is (foo bar qux). So the following are the acceptable CLI invocations this script:

  • , foo
  • , bar
  • , qux

(Each of the above may take further optional arguments to the right).

What is the minimal zsh completion code for this script that will work on macOS? Such that when I type , followed by <TAB>, the shell will autocomplete with those three options: foo, bar, and qux.

Sridhar Ratnakumar
  • 81,433
  • 63
  • 146
  • 187

1 Answers1

7

Here are the minimal steps for adding zsh completion to your , command:

  1. Enabling compinit

    autoload -U compinit
    
  2. Enabling compdef

    compinit
    
  3. Defining a function for completing the first argument from/with a given set of values.

    _,() { _arguments -C '1: :(foo bar qux)'; }
    
  4. Setting the previous function _, as the completion function of the , command:

    compdef _, ,
    

Now if you type Comma Space Tab, zsh should output:

bar  foo  qux

ASIDE

It's possible to add further completion to each sub-command bar/foo/qux; take a look at this documented example.

Fravadona
  • 13,917
  • 1
  • 23
  • 35
  • Thanks! That "aside" is also helpful. Specifically I'd wish to *delegate* completion to the respective command. For example, `, git` should delegate to git's autocompletion. I can open a separate question for it if necessary. – Sridhar Ratnakumar Jan 08 '23 at 03:18
  • 1
    @SridharRatnakumar I tried to call the completion function of `git` from inside `_,` but it segfaults zsh!! I think it's worth to ask an other question for it. – Fravadona Jan 08 '23 at 17:27