Search code examples
macosshellzshzsh-completion

macOS zsh completion for subcommands


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.


Solution

  • 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.