Zsh completion arguments

From wikinotes
Revision as of 21:48, 24 July 2021 by Will (talk | contribs) (→‎Basics)

Arguments Params

Basics

arguments \
  '( ${excludes} )${param}:${message}:${action}'


# here ${excludes} is an array of param ${state_descr}s
#    arguments \
#      '1::one:_normal' \
#      '2::two:_normal' \
#      '(one)::value:(foo bar baz)'   
#
# don't complete 'value' if 'one' has been defined


# here ${param} has different formats depending on the param type:
#    ex: '-h[show help]'  # flag
#    ex: '1'              # positional
#    ex: '1:'             # optional-positional
#    ex: ''               # optional

Flag Arguments

_arguments \
   {-h,--help}'[show help]' \
       # param:   -h/--help
       # desc:    show help
       # action:  (none)
   '-o[output file]:::_files \
       # param:   -o
       # desc:    output file
       # action:  (complete any file)

Positional Arguments

# ex: ${position}:${state_descr}:${action}

_arguments \
    '1:user:_users' \              # 1st positional arg (required)
    '2:priority:(low med high)' \  # 2nd positional arg (required) (complete to low/med/high)
    '3::group:_groups' \           # 3nd positional arg (optional)

The argument-name is bound to $state_descr.

Value for last defined Param

:${message}:${action}   # reqd completion for prev command
::${message}:${action}  # optional completion for prev command
_arguments \
    {-h,--help}'[show help]' \
    '*::extra:(foo bar baz)' \  # any extra parameters, (complete to (foo bar baz))
    ':value:(foo bar baz)'      # after prev param (extra), always complete one of these words

Rest Arguments

Any arguments not consumed earlier use this completer.

*:${message}:${action}    # 
*::${message}:${action}   # 
*:::${message}:${action}  #

State Setting/Parsing

The -C argument enables state-setting.
This lets you determine the parser that gets used based on the state you set.

local state               # scope state locally

_arguments -C \
    '*:extra:->my-state'  # sets `$state='my-state'`

case $state in
    (my-state)
        _arguments '1:foo:(one two three four)'
        ;;
esac