Completion Functions (zsh)

### 20.6 Utility Functions ¶

Descriptions follow for utility functions that may be useful when writing completion functions. If functions are installed in subdirectories, most of these reside in the `Base` subdirectory. Like the example functions for commands in the distribution, the utility functions generating matches all follow the convention of returning status zero if they generated completions and non-zero if no matching completions could be added.

`_absolute_command_paths` ¶

  This function completes external commands as absolute paths (unlike `_command_names -e` which completes their basenames). It takes no arguments.

`_all_labels` [ `-x` ] [ `-12VJ` ] tag name descr [ command arg ... ] ¶

  This is a convenient interface to the `_next_label` function below, implementing the loop shown in the `_next_label` example. The command and its arguments are called to generate the matches. The options stored in the parameter name will automatically be inserted into the args passed to the command. Normally, they are put directly after the command, but if one of the args is a single hyphen, they are inserted directly before that. If the hyphen is the last argument, it will be removed from the argument list before the command is called. This allows `_all_labels` to be used in almost all cases where the matches can be generated by a single call to the `compadd` builtin command or by a call to one of the utility functions.

  For example:

      local expl
      ...
      if _requested foo; then
        ...
        _all_labels foo expl '...' compadd ... - $matches
      fi

  Will complete the strings from the `matches` parameter, using `compadd` with additional options which will take precedence over those generated by `_all_labels`.

`_alternative` [ `-O` name ] [ `-C` name ] spec ... ¶

  This function is useful in simple cases where multiple tags are available. Essentially it implements a loop like the one described for the `_tags` function below.

  The tags to use and the action to perform if a tag is requested are described using the specs which are of the form: ‘tag`:`descr`:`action’. The tags are offered using `_tags` and if the tag is requested, the action is executed with the given description descr. The actions are those accepted by the `_arguments` function (described below), with the following exceptions:

  - The ‘`->`state’ and ‘`=`...’ forms are not supported.
  - The ‘`((a\:bar b\:baz``))`’ form does not need the colon to be escaped, since the specs have no colon-separated fields after the action.

  For example, the action may be a simple function call:

      _alternative \
          'users:user:_users' \
          'hosts:host:_hosts'

  offers usernames and hostnames as possible matches, generated by the `_users` and `_hosts` functions respectively.

  Like `_arguments`, this function uses `_all_labels` to execute the actions, which will loop over all sets of tags. Special handling is only required if there is an additional valid tag, for example inside a function called from `_alternative`.

  The option ‘`-O` name’ is used in the same way as by the `_arguments` function. In other words, the elements of the name array will be passed to `compadd` when executing an action.

  Like `_tags` this function supports the `-C` option to give a different name for the argument context field.

`_arguments` [ `-nswWCRS` ] [ `-A` pat ] [ `-O` name ] [ `-M` matchspec ]
`` [ `:` ] spec ...
`_arguments` [ opt ... ] `-``-` [ `-l` ] [ `-i` pats ] [ `-s` pair ]
`` [ helpspec ...]

  This function can be used to give a complete specification for completion for a command whose arguments follow standard UNIX option and argument conventions.

  Options Overview

  Options to `_arguments` itself must be in separate words, i.e. `-s -w`, not `-sw`. The options are followed by specs that describe options and arguments of the analyzed command. To avoid ambiguity, all options to `_arguments` itself may be separated from the spec forms by a single colon.

  The ‘`-``-`’ form is used to intuit spec forms from the help output of the command being analyzed, and is described in detail below. The opts for the ‘`-``-`’ form are otherwise the same options as the first form. Note that ‘`-s`’ following ‘`-``-`’ has a distinct meaning from ‘`-s`’ preceding ‘`-``-`’, and both may appear.

  The option switches `-s`, `-S`, `-A`, `-w`, and `-W` affect how `_arguments` parses the analyzed command line’s options. These switches are useful for commands with standard argument parsing.

  The options of `_arguments` have the following meanings:

  `-n`

    With this option, `_arguments` sets the parameter `NORMARG` to the position of the first normal argument in the `$words` array, i.e. the position after the end of the options. If that argument has not been reached, `NORMARG` is set to `-1`. The caller should declare ‘`integer NORMARG`’ if the `-n` option is passed; otherwise the parameter is not used.

  `-s`

    Enable option stacking for single-letter options, whereby multiple single-letter options may be combined into a single word. For example, the two options ‘`-x`’ and ‘`-y`’ may be combined into a single word ‘`-xy`’. By default, every word corresponds to a single option name (‘`-xy`’ is a single option named ‘`xy`’).

    Options beginning with a single hyphen or plus sign are eligible for stacking; words beginning with two hyphens are not.

    Note that `-s` after `-``-` has a different meaning, which is documented in the segment entitled ‘Deriving spec forms from the help output’.

  `-w`

    In combination with `-s`, allow option stacking even if one or more of the options take arguments. For example, if `-x` takes an argument, with no `-s`, ‘`-xy`’ is considered as a single (unhandled) option; with `-s`, `-xy` is an option with the argument ‘`y`’; with both `-s` and `-w`, `-xy` is the option `-x` and the option `-y` with arguments to `-x` (and to `-y`, if it takes arguments) still to come in subsequent words.

  `-W`

    This option takes `-w` a stage further: it is possible to complete single-letter options even after an argument that occurs in the same word. However, it depends on the action performed whether options will really be completed at this point. For more control, use a utility function like `_guard` as part of the action.

  `-C`

    Modify the `curcontext` parameter for an action of the form ‘`->`state’. This is discussed in detail below.

  `-R`

    Return status 300 instead of zero when a `$state` is to be handled, in the ‘`->`string’ syntax.

  `-S`

    Do not complete options after a ‘`-``-`’ appearing on the line, and ignore the ‘`-``-`’. For example, with `-S`, in the line

        foobar -x -- -y

    the ‘`-x`’ is considered an option, the ‘`-y`’ is considered an argument, and the ‘`-``-`’ is considered to be neither.

  `-A` pat

    Do not complete options after the first non-option argument on the line. pat is a pattern matching all strings which are not to be taken as arguments. For example, to make `_arguments` stop completing options after the first normal argument, but ignoring all strings starting with a hyphen even if they are not described by one of the optspecs, the form is ‘`-A "-*"`’.

  `-O` name

    Pass the elements of the array name as arguments to functions called to execute actions. This is discussed in detail below.

  `-M` matchspec

    Use the match specification matchspec for completing option names and values. The default matchspec allows partial word completion after ‘`_`’ and ‘`-`’, such as completing ‘`-f-b`’ to ‘`-foo-bar`’. The default matchspec is:

        r:|[_-]=* r:|=*

  `-0`

    When populating values of the ‘`opt_args`’ associative array, don’t backslash-escape colons and backslashes and use NUL rather than colon for joining multiple values. This option is described in more detail below, under the heading specs: actions.

  specs: overview

  Each of the following forms is a spec describing individual sets of options or arguments on the command line being analyzed.

  n`:`message`:`action
  n`::`message`:`action

    This describes the n’th normal argument. The message will be printed above the matches generated and the action indicates what can be completed in this position (see below). If there are two colons before the message the argument is optional. If the message contains only white space, nothing will be printed above the matches unless the action adds an explanation string itself.

  `:`message`:`action
  `::`message`:`action

    Similar, but describes the next argument, whatever number that happens to be. If all arguments are specified in this form in the correct order the numbers are unnecessary.

  `*:`message`:`action
  `*::`message`:`action
  `*:::`message`:`action

    This describes how arguments (usually non-option arguments, those not beginning with `-` or `+`) are to be completed when neither of the first two forms was provided. Any number of arguments can be completed in this fashion.

    With two colons before the message, the `words` special array and the `CURRENT` special parameter are modified to refer only to the normal arguments when the action is executed or evaluated. With three colons before the message they are modified to refer only to the normal arguments covered by this description.

  optspec
  optspec`:`...

    This describes an option. The colon indicates handling for one or more arguments to the option; if it is not present, the option is assumed to take no arguments.

    The following forms are available for the initial optspec, whether or not the option has arguments.

    `*`optspec

      Here optspec is one of the remaining forms below. This indicates the following optspec may be repeated. Otherwise if the corresponding option is already present on the command line to the left of the cursor it will not be offered again.

    `-`optname
    `+`optname

      In the simplest form the optspec is just the option name beginning with a minus or a plus sign, such as ‘`-foo`’. The first argument for the option (if any) must follow as a separate word directly after the option.

      Either of ‘`-+`optname’ and ‘`+-`optname’ can be used to specify that `-`optname and `+`optname are both valid.

      In all the remaining forms, the leading ‘`-`’ may be replaced by or paired with ‘`+`’ in this way.

    `-`optname`-`

      The first argument of the option must come directly after the option name in the same word. For example, ‘`-foo-:`...’ specifies that the completed option and argument will look like ‘`-foo`arg’.

    `-`optname`+`

      The first argument may appear immediately after optname in the same word, or may appear as a separate word after the option. For example, ‘`-foo+:`...’ specifies that the completed option and argument will look like either ‘`-foo`arg’ or ‘`-foo` arg’.

    `-`optname`=`

      The argument may appear as the next word, or in same word as the option name provided that it is separated from it by an equals sign, for example ‘`-foo=`arg’ or ‘`-foo` arg’.

    `-`optname`=-`

      The argument to the option must appear after an equals sign in the same word, and may not be given in the next argument.

    optspec`[`explanation`]`

      An explanation string may be appended to any of the preceding forms of optspec by enclosing it in brackets, as in ‘`-q[query operation]`’.

      The `verbose` style is used to decide whether the explanation strings are displayed with the option in a completion listing.

      If no bracketed explanation string is given but the `auto-description` style is set and only one argument is described for this optspec, the value of the style is displayed, with any appearance of the sequence ‘`%d`’ in it replaced by the message of the first optarg that follows the optspec; see below.

    It is possible for options with a literal ‘`+`’ or ‘`=`’ to appear, but that character must be quoted, for example ‘`-\+`’.

    Each optarg following an optspec must take one of the following forms:

    `:`message`:`action
    `::`message`:`action

      An argument to the option; message and action are treated as for ordinary arguments. In the first form, the argument is mandatory, and in the second form it is optional.

      This group may be repeated for options which take multiple arguments. In other words, `:`message1`:`action1`:`message2`:`action2 specifies that the option takes two arguments.

    `:*`pattern`:`message`:`action
    `:*`pattern`::`message`:`action
    `:*`pattern`:::`message`:`action

      This describes multiple arguments. Only the last optarg for an option taking multiple arguments may be given in this form. If the pattern is empty (i.e. `:*:`), all the remaining words on the line are to be completed as described by the action; otherwise, all the words up to and including a word matching the pattern are to be completed using the action.

      Multiple colons are treated as for the ‘`*:`...’ forms for ordinary arguments: when the message is preceded by two colons, the `words` special array and the `CURRENT` special parameter are modified during the execution or evaluation of the action to refer only to the words after the option. When preceded by three colons, they are modified to refer only to the words covered by this description.

  Any literal colon in an optname, message, or action must be preceded by a backslash, ‘`\:`’.

  Each of the forms above may be preceded by a list in parentheses of option names and argument numbers. If the given option is on the command line, the options and arguments indicated in parentheses will not be offered. For example, ‘`(-two -three 1)-one:`...’ completes the option ‘`-one`’; if this appears on the command line, the options `-two` and `-three` and the first ordinary argument will not be completed after it. ‘`(-foo):`...’ specifies an ordinary argument completion; `-foo` will not be completed if that argument is already present.

  Other items may appear in the list of excluded options to indicate various other items that should not be applied when the current specification is matched: a single star (`*`) for the rest arguments (i.e. a specification of the form ‘`*:`...’); a colon (`:`) for all normal (non-option-) arguments; and a hyphen (`-`) for all options. For example, if ‘`(*)`’ appears before an option and the option appears on the command line, the list of remaining arguments (those shown in the above table beginning with ‘`*:`’) will not be completed.

  To aid in reuse of specifications, it is possible to precede any of the forms above with ‘`!`’; then the form will no longer be completed, although if the option or argument appears on the command line they will be skipped as normal. The main use for this is when the arguments are given by an array, and `_arguments` is called repeatedly for more specific contexts: on the first call ‘`_arguments $global_options`’ is used, and on subsequent calls ‘`_arguments !$^global_options`’.

  specs: actions

  In each of the forms above the action determines how completions should be generated. Except for the ‘`->`string’ form below, the action will be executed by calling the `_all_labels` function to process all tag labels. No special handling of tags is needed unless a function call introduces a new one.

  The functions called to execute actions will be called with the elements of the array named by the ‘`-O` name’ option as arguments. This can be used, for example, to pass the same set of options for the `compadd` builtin to all actions.

  The forms for action are as follows.

  `` (single unquoted space)

    This is useful where an argument is required but it is not possible or desirable to generate matches for it. The message will be displayed but no completions listed. Note that even in this case the colon at the end of the message is needed; it may only be omitted when neither a message nor an action is given.

  `(`item1 item2 ...`)`

    One of a list of possible matches, for example:

        :foo:(foo bar baz)

  `((item1\:desc1 ...))`

    Similar to the above, but with descriptions for each possible match. Note the backslash before the colon. For example,

        :foo:((a\:bar b\:baz))

    The matches will be listed together with their descriptions if the `description` style is set with the `values` tag in the context.

  `->`string ¶

    In this form, `_arguments` processes the arguments and options and then returns control to the calling function with parameters set to indicate the state of processing; the calling function then makes its own arrangements for generating completions. For example, functions that implement a state machine can use this type of action.

    Where `_arguments` encounters action in the ‘`->`string’ format, it will strip all leading and trailing whitespace from string and set the array `state` to the set of all strings for which an action is to be performed. The elements of the array `state_descr` are assigned the corresponding message field from each optarg containing such an action.

    By default and in common with all other well behaved completion functions, _arguments returns status zero if it was able to add matches and non-zero otherwise. However, if the `-R` option is given, `_arguments` will instead return a status of 300 to indicate that `$state` is to be handled.

    In addition to `$state` and `$state_descr`, `_arguments` also sets the global parameters ‘`context`’, ‘`line`’ and ‘`opt_args`’ as described below, and does not reset any changes made to the special parameters such as `PREFIX` and `words`. This gives the calling function the choice of resetting these parameters or propagating changes in them.

    A function calling `_arguments` with at least one action containing a ‘`->`string’ must therefore declare appropriate local parameters:

        local context state state_descr line
        typeset -A opt_args

    to prevent `_arguments` from altering the global environment.

  `{`eval-string`}` ¶

    A string in braces is evaluated as shell code to generate matches. If the eval-string itself does not begin with an opening parenthesis or brace it is split into separate words before execution.

  `=` action

    If the action starts with ‘`=` ’ (an equals sign followed by a space), `_arguments` will insert the contents of the argument field of the current context as the new first element in the `words` special array and increment the value of the `CURRENT` special parameter. This has the effect of inserting a dummy word onto the completion command line while not changing the point at which completion is taking place.

    This is most useful with one of the specifiers that restrict the words on the command line on which the action is to operate (the two- and three-colon forms above). One particular use is when an action itself causes `_arguments` on a restricted range; it is necessary to use this trick to insert an appropriate command name into the range for the second call to `_arguments` to be able to parse the line.

  `` word...
  word...

    This covers all forms other than those above. If the action starts with a space, the remaining list of words will be invoked unchanged.

    Otherwise it will be invoked with some extra strings placed after the first word; these are to be passed down as options to the `compadd` builtin. They ensure that the state specified by `_arguments`, in particular the descriptions of options and arguments, is correctly passed to the completion command. These additional arguments are taken from the array parameter ‘`expl`’; this will be set up before executing the action and hence may be referred to inside it, typically in an expansion of the form ‘`$expl[@]`’ which preserves empty elements of the array.

  During the performance of the action the array ‘`line`’ will be set to the normal arguments from the command line, i.e. the words from the command line after the command name excluding all options and their arguments. Options are stored in the associative array ‘`opt_args`’ with option names as keys and their arguments as the values. By default, all colons and backslashes in the value are escaped with backslashes, and if an option has multiple arguments (for example, when using an optspec of the form ‘`*`optspec’), they are joined with (unescaped) colons. However, if the `-0` option was passed, no backslash escaping is performed, and multiple values are joined with NUL bytes. For example, after ‘`zsh -o foo:foo -o bar:bar -o <TAB>`’, the contents of ‘`opt_args`’ would be

      typeset -A opt_args=( [-o]='foo\:foo:bar\:bar:' )

  by default, and

      typeset -A opt_args=( [-o]=$'foo:foo\x00bar:bar\x00' )

  if `_arguments` had been called with the `-0` option.

  The parameter ‘`context`’ is set when returning to the calling function to perform an action of the form ‘`->`string’. It is set to an array of elements corresponding to the elements of `$state`. Each element is a suitable name for the argument field of the context: either a string of the form ‘`option`-opt`-`n’ for the n’th argument of the option -opt, or a string of the form ‘`argument-`n’ for the n’th argument. For ‘rest’ arguments, that is those in the list at the end not handled by position, n is the string ‘`rest`’. For example, when completing the argument of the `-o` option, the name is ‘`option-o-1`’, while for the second normal (non-option-) argument it is ‘`argument-2`’.

  Furthermore, during the evaluation of the action the context name in the `curcontext` parameter is altered to append the same string that is stored in the `context` parameter.

  The option `-C` tells `_arguments` to modify the `curcontext` parameter for an action of the form ‘`->`state’. This is the standard parameter used to keep track of the current context. Here it (and not the `context` array) should be made local to the calling function to avoid passing back the modified value and should be initialised to the current value at the start of the function:

      local curcontext="$curcontext"

  This is useful where it is not possible for multiple states to be valid together.

  Grouping Options

  Options can be grouped to simplify exclusion lists. A group is introduced with ‘`+`’ followed by a name for the group in the subsequent word. Whole groups can then be referenced in an exclusion list or a group name can be used to disambiguate between two forms of the same option. For example:

      _arguments \
          '(group2--x)-a' \
        + group1 \
          -m \
          '(group2)-n' \
        + group2 \
          -x -y

  If the name of a group is specified in the form ‘`(`name`)`’ then only one value from that group will ever be completed; more formally, all specifications are mutually exclusive to all other specifications in that group. This is useful for defining options that are aliases for each other. For example:

      _arguments \
          -a -b \
        + '(operation)' \
          {-c,--compress}'[compress]' \
          {-d,--decompress}'[decompress]' \
          {-l,--list}'[list]'

  If an option in a group appears on the command line, it is stored in the associative array ‘`opt_args`’ with ’group`-`option’ as a key. In the example above, a key ‘`operation--c`’ is used if the option ‘`-c`’ is present on the command line.

  Specifying Multiple Sets of Arguments

  It is possible to specify multiple sets of options and arguments with the sets separated by single hyphens. This differs from groups in that sets are considered to be mutually exclusive of each other.

  Specifications before the first set and from any group are common to all sets. For example:

      _arguments \
          -a \
        - set1 \
          -c \
        - set2 \
          -d \
          ':arg:(x2 y2)'

  This defines two sets. When the command line contains the option ‘`-c`’, the ‘`-d`’ option and the argument will not be considered possible completions. When it contains ‘`-d`’ or an argument, the option ‘`-c`’ will not be considered. However, after ‘`-a`’ both sets will still be considered valid.

  As for groups, the name of a set may appear in exclusion lists, either alone or preceding a normal option or argument specification.

  The completion code has to parse the command line separately for each set. This can be slow so sets should only be used when necessary. A useful alternative is often an option specification with rest-arguments (as in ‘`-foo:*:...`’); here the option `-foo` swallows up all remaining arguments as described by the optarg definitions.

  Deriving spec forms from the help output

  The option ‘`-``-`’ allows `_arguments` to work out the names of long options that support the ‘`-``-help`’ option which is standard in many GNU commands. The command word is called with the argument ‘`-``-help`’ and the output examined for option names. Clearly, it can be dangerous to pass this to commands which may not support this option as the behaviour of the command is unspecified.

  In addition to options, ‘`_arguments -``-`’ will try to deduce the types of arguments available for options when the form ‘`-``-`opt`=`val’ is valid. It is also possible to provide hints by examining the help text of the command and adding helpspec of the form ‘pattern`:`message`:`action’; note that other `_arguments` spec forms are not used. The pattern is matched against the help text for an option, and if it matches the message and action are used as for other argument specifiers. The special case of ‘`*:`’ means both message and action are empty, which has the effect of causing options having no description in the help output to be ordered in listings ahead of options that have a description.

  For example:

      _arguments -- '*\*:toggle:(yes no)' \
                    '*=FILE*:file:_files' \
                    '*=DIR*:directory:_files -/' \
                    '*=PATH*:directory:_files -/'

  Here, ‘`yes`’ and ‘`no`’ will be completed as the argument of options whose description ends in a star; file names will be completed for options that contain the substring ‘`=FILE`’ in the description; and directories will be completed for options whose description contains ‘`=DIR`’ or ‘`=PATH`’. The last three are in fact the default and so need not be given explicitly, although it is possible to override the use of these patterns. A typical help text which uses this feature is:

        -C, --directory=DIR          change to directory DIR

  so that the above specifications will cause directories to be completed after ‘`-``-directory`’, though not after ‘`-C`’.

  Note also that `_arguments` tries to find out automatically if the argument for an option is optional. This can be specified explicitly by doubling the colon before the message.

  If the pattern ends in ‘`(-)`’, this will be removed from the pattern and the action will be used only directly after the ‘`=`’, not in the next word. This is the behaviour of a normal specification defined with the form ‘`=-`’.

  By default, the command (with the option ‘`--help`’) is run after resetting all the locale categories (except for `LC_CTYPE`) to ‘`C`’. If the localized help output is known to work, the option ‘`-l`’ can be specified after the ‘`_arguments -``-`’ so that the command is run in the current locale.

  The ‘`_arguments -``-`’ can be followed by the option ‘`-i` patterns’ to give patterns for options which are not to be completed. The patterns can be given as the name of an array parameter or as a literal list in parentheses. For example,

      _arguments -- -i \
          "(--(en|dis)able-FEATURE*)"

  will cause completion to ignore the options ‘`-``-enable-FEATURE`’ and ‘`-``-disable-FEATURE`’ (this example is useful with GNU `configure`).

  The ‘`_arguments -``-`’ form can also be followed by the option ‘`-s` pair’ to describe option aliases. The pair consists of a list of alternating patterns and corresponding replacements, enclosed in parens and quoted so that it forms a single argument word in the `_arguments` call.

  For example, some `configure`-script help output describes options only as ‘`-``-enable-foo`’, but the script also accepts the negated form ‘`-``-disable-foo`’. To allow completion of the second form:

      _arguments -- -s "((#s)--enable- --disable-)"

  Miscellaneous notes

  Finally, note that `_arguments` generally expects to be the primary function handling any completion for which it is used. It may have side effects which change the treatment of any matches added by other functions called after it. To combine `_arguments` with other functions, those functions should be called either before `_arguments`, as an action within a spec, or in handlers for ‘`->`state’ actions.

  Here is a more general example of the use of `_arguments`:

      _arguments '-l+:left border:' \
                 '-format:paper size:(letter A4)' \
                 '*-copy:output file:_files::resolution:(300 600)' \
                 ':postscript file:_files -g \*.\(ps\|eps\)' \
                 '*:page number:'

  This describes three options: ‘`-l`’, ‘`-format`’, and ‘`-copy`’. The first takes one argument described as ‘left border’ for which no completion will be offered because of the empty action. Its argument may come directly after the ‘`-l`’ or it may be given as the next word on the line.

  The ‘`-format`’ option takes one argument in the next word, described as ‘paper size’ for which only the strings ‘`letter`’ and ‘`A4`’ will be completed.

  The ‘`-copy`’ option may appear more than once on the command line and takes two arguments. The first is mandatory and will be completed as a filename. The second is optional (because of the second colon before the description ‘resolution’) and will be completed from the strings ‘`300`’ and ‘`600`’.

  The last two descriptions say what should be completed as arguments. The first describes the first argument as a ‘postscript file’ and makes files ending in ‘`ps`’ or ‘`eps`’ be completed. The last description gives all other arguments the description ‘page number’ but does not offer completions.

`_as_if` command [arg ... ] ¶

  This function is useful when one command should be completed as if it were another command with particular arguments. For example to complete `foo` as if it were `bar --baz`, use

      compdef '_as_if bar --baz' foo

`_cache_invalid` cache_identifier ¶

  This function returns status zero if the completions cache corresponding to the given cache identifier needs rebuilding. It determines this by looking up the `cache-policy` style for the current context. This should provide a function name which is run with the full path to the relevant cache file as the only argument.

  Example:

      _example_caching_policy () {
          # rebuild if cache is more than a week old
          local -a oldp
          oldp=( "$1"(Nm+7) )
          (( $#oldp ))
      }

`_call_function` return name [ arg ... ] ¶

  If a function name exists, it is called with the arguments args. The return argument gives the name of a parameter in which the return status from the function name should be stored; if return is empty or a single hyphen it is ignored.

  The return status of `_call_function` itself is zero if the function name exists and was called and non-zero otherwise.

`_call_program` [ `-l` ] [ `-p` ] tag string ... ¶

  This function provides a mechanism for the user to override the use of an external command. It looks up the `command` style with the supplied tag. If the style is set, its value is used as the command to execute. The strings from the call to `_call_program`, or from the style if set, are concatenated with spaces between them and the resulting string is evaluated. The return status is the return status of the command called.

  By default, the command is run in an environment where all the locale categories (except for `LC_CTYPE`) are reset to ‘`C`’ by calling the utility function `_comp_locale` (see below). If the option ‘`-l`’ is given, the command is run with the current locale.

  If the option ‘`-p`’ is supplied it indicates that the command output is influenced by the permissions it is run with. If the `gain-privileges` style is set to true, `_call_program` will make use of commands such as `sudo`, if present on the command-line, to match the permissions to whatever the final command is likely to run under. When looking up the `gain-privileges` and `command` styles, the command component of the zstyle context will end with a slash (‘`/`’) followed by the command that would be used to gain privileges.

`_combination` [ `-s` pattern ] tag style spec ... field opts ... ¶

  This function is used to complete combinations of values, for example pairs of hostnames and usernames. The style argument gives the style which defines the pairs; it is looked up in a context with the tag specified.

  The style name consists of field names separated by hyphens, for example ‘`users-hosts-ports`’. For each field for a value is already known, a spec of the form ‘field`=`pattern’ is given. For example, if the command line so far specifies a user ‘`pws`’, the argument ‘`users=pws`’ should appear.

  The next argument with no equals sign is taken as the name of the field for which completions should be generated (presumably not one of the fields for which the value is known).

  The matches generated will be taken from the value of the style. These should contain the possible values for the combinations in the appropriate order (users, hosts, ports in the example above). The values for the different fields are separated by colons. This can be altered with the option `-s` to `_combination` which specifies a pattern. Typically this is a character class, as for example ‘`-s "[:@]"`’ in the case of the `users-hosts` style. Each ‘field`=`pattern’ specification restricts the completions which apply to elements of the style with appropriately matching fields.

  If no style with the given name is defined for the given tag, or if none of the strings in style’s value match, but a function name of the required field preceded by an underscore is defined, that function will be called to generate the matches. For example, if there is no ‘`users-hosts-ports`’ or no matching hostname when a host is required, the function ‘`_hosts`’ will automatically be called.

  If the same name is used for more than one field, in both the ‘field`=`pattern’ and the argument that gives the name of the field to be completed, the number of the field (starting with one) may be given after the fieldname, separated from it by a colon.

  All arguments after the required field name are passed to `compadd` when generating matches from the style value, or to the functions for the fields if they are called.

`_command_names` [ `-e` | `-` ] ¶

  This function completes words that are valid at command position: names of aliases, builtins, hashed commands, functions, and so on. With the `-e` flag, only hashed commands are completed. The `-` flag is ignored.

`_comp_locale` ¶

  This function resets all the locale categories other than `LC_CTYPE` to ‘`C`’ so that the output from external commands can be easily analyzed by the completion system. `LC_CTYPE` retains the current value (taking `LC_ALL` and `LANG` into account), ensuring that non-ASCII characters in file names are still handled properly.

  This function should normally be run only in a subshell, because the new locale is exported to the environment. Typical usage would be ‘`$(_comp_locale;` command ...`)`’.

`_completers` [ `-p` ] ¶

  This function completes names of completers.

  `-p`

    Include the leading underscore (‘`_`’) in the matches.

`_default` ¶

  This function corresponds to the `-default-` special context which is applied where no completion is defined. It is useful to call it under certain error conditions such as completion after an unrecognised subcommand. This applies the concept of graceful degradation to the completion system, allowing it to fallback on basic completion of commonly useful things like filenames.

`_describe` [`-12JVx`] [ `-oO` | `-t` tag ] descr name1 [ name2 ] [ opt ... ]
`` [ `-``-` name1 [ name2 ] [ opt ... ] ... ]

  This function associates completions with descriptions. Multiple groups separated by `-``-` can be supplied, potentially with different completion options opts.

  The descr is taken as a string to display above the matches if the `format` style for the `descriptions` tag is set.

  This is followed by one or two names of arrays. Alternatively, the arrays may be given inline, following the rules described below, using the syntax `(`item ...`)`. (There is no separate `((`...`))` form as with `_arguments`.)

  The array name1 contains the possible completions with their (optional) descriptions in the form ‘completion`:`description’. Any literal colons in completion must be quoted with a backslash. If a name2 is given, it should have the same number of elements as name1; in this case the corresponding elements are added as possible completions instead of the completion strings from name1. The completion list will retain the descriptions from name1.

  Finally, a set of options to pass to `compadd` can appear.

  If the option ‘`-o`’ appears before the first argument, the matches added will be treated as names of command options (N.B. not shell options), typically following a ‘`-`’, ‘`-``-`’ or ‘`+`’ on the command line. In this case `_describe` uses the `prefix-hidden`, `prefix-needed` and `verbose` styles to find out if the strings should be added as completions and if the descriptions should be shown. Without the ‘`-o`’ option, only the `verbose` style is used to decide how descriptions are shown. If ‘`-O`’ is used instead of ‘`-o`’, command options are completed as above but `_describe` will not handle the `prefix-needed` style.

  With the `-t` option a tag can be specified. The default is ‘`values`’ or, if the `-o` option is given, ‘`options`’.

  The options `-1`, `-2`, `-J`, `-V`, `-x` are passed to `_next_label`.

  If selected by the `list-grouped` style, strings with the same description will appear together in the list.

  `_describe` uses the `_all_labels` function to generate the matches, so it does not need to appear inside a loop over tag labels.

`_description` [ `-x` ] [ `-12VJ` ] tag name descr [ spec ... ] ¶

  This function is not to be confused with the previous one; it is used as a helper function for creating options to `compadd`. It is buried inside many of the higher level completion functions and so often does not need to be called directly.

  The styles listed below are tested in the current context using the given tag. The resulting options for `compadd` are put into the array named name (this is traditionally ‘`expl`’, but this convention is not enforced). The description for the corresponding set of matches is passed to the function in descr.

  The styles tested are: `format`, `hidden`, `matcher`, `ignore-line`, `ignored-patterns`, `group-name` and `sort`. The `format` style is first tested for the given tag and then for the `descriptions` tag if no value was found, while the remainder are only tested for the tag given as the first argument. The function also calls `_setup` which tests some more styles.

  The string returned by the `format` style (if any) will be modified so that the sequence ‘`%d`’ is replaced by the descr given as the third argument without any leading or trailing white space. If, after removing the white space, the descr is the empty string, the format style will not be used and the options put into the name array will not contain an explanation string to be displayed above the matches.

  If `_description` is called with more than three arguments, the additional specs should be of the form ‘char`:`str’. These supply escape sequence replacements for the `format` style: every appearance of ‘`%`char’ will be replaced by string. If no additional specs are given but the description in descr conforms to a common form then further escape sequences are set for elements of that description. These elements correspond to a default value (‘`%o`’), the units (‘`%m`’) range of acceptable values (‘`%r`’) and the remaining initial part of the description (‘`%h`’). The form the description takes consists of specifying the units and range in parentheses and the default value in square brackets, for example:

      _description times expl 'timeout (seconds) (0-60) [20]'

  It is possible to use `zformat` conditional expressions when styling these elements. So, for example, to add ‘`default:`’ as a tag but only when there is a default value to show, the `format` style might include ‘`%(o.default: %o.)`’.

  If the `-x` option is given, the description will be passed to `compadd` using the `-x` option instead of the default `-X`. This means that the description will be displayed even if there are no corresponding matches.

  The options placed in the array name take account of the `group-name` style, so matches are placed in a separate group where necessary. The group normally has its elements sorted (by passing the option `-J` to `compadd`), but if an option starting with ‘`-V`’, ‘`-J`’, ‘`-1`’, or ‘`-2`’ is passed to `_description`, that option will be included in the array. Hence it is possible for the completion group to be unsorted by giving the option ‘`-V`’, ‘`-1V`’, or ‘`-2V`’.

  In most cases, the function will be used like this:

      local expl
      _description files expl file
      compadd "$expl[@]" - "$files[@]"

  Note the use of the parameter `expl`, the hyphen, and the list of matches. Almost all calls to `compadd` within the completion system use a similar format; this ensures that user-specified styles are correctly passed down to the builtins which implement the internals of completion.

`_dir_list` [ `-s` sep ] [ `-S` ] ¶

  Complete a list of directory names separated by colons (the same format as `$PATH`).

  `-s` sep

    Use sep as separator between items. sep defaults to a colon (‘`:`’).

  `-S`

    Add sep instead of slash (‘`/`’) as an autoremoveable suffix.

`_dispatch` context string ... ¶

  This sets the current context to context and looks for completion functions to handle this context by hunting through the list of command names or special contexts (as described above for `compdef`) given as strings. The first completion function to be defined for one of the contexts in the list is used to generate matches. Typically, the last string is `-default-` to cause the function for default completion to be used as a fallback.

  The function sets the parameter `$service` to the string being tried, and sets the context/command field (the fourth) of the `$curcontext` parameter to the context given as the first argument.

`_email_addresses` [ `-c` ] [ `-n` plugin ] ¶

  Complete email addresses. Addresses are provided by plugins.

  `-c`

    Complete bare `localhost@domain.tld` addresses, without a name part or a comment. Without this option, RFC822 ‘Firstname Lastname `<`address`>`’ strings are completed.

  `-n` plugin

    Complete aliases from plugin.

  The following plugins are available by default: `_email-ldap` (see the `filter` style), `_email-local` (completes user`@`hostname Unix addresses), `_email-mail` (completes aliases from `~/.mailrc`), `_email-mush`, `_email-mutt`, and `_email-pine`.

  Addresses from the `_email-`foo plugin are added under the tag ‘`email-`foo’.

  Writing plugins

  Plugins are written as separate functions with names starting with ‘`_email-`’. They are invoked with the `-c` option and `compadd` options. They should either do their own completion or set the `$reply` array to a list of ‘alias`:`address’ elements and return `300`. New plugins will be picked up and run automatically.

`_files` ¶

  The function `_files` is a wrapper around `_path_files`. It supports all of the same functionality, with some enhancements — notably, it respects the `list-dirs-first` style, and it allows users to override the behaviour of the `-g` and `-/` options with the `file-patterns` style. `_files` should therefore be preferred over `_path_files` in most cases.

  This function accepts the full set of options allowed by `_path_files`, described below.

`_gnu_generic` ¶

  This function is a simple wrapper around the `_arguments` function described above. It can be used to determine automatically the long options understood by commands that produce a list when passed the option ‘`-``-help`’. It is intended to be used as a top-level completion function in its own right. For example, to enable option completion for the commands `foo` and `bar`, use

      compdef _gnu_generic foo bar

  after the call to `compinit`.

  The completion system as supplied is conservative in its use of this function, since it is important to be sure the command understands the option ‘`-``-help`’.

`_guard` [ options ] pattern descr ¶

  This function displays descr if pattern matches the string to be completed. It is intended to be used in the action for the specifications passed to `_arguments` and similar functions.

  The return status is zero if the message was displayed and the word to complete is not empty, and non-zero otherwise.

  The pattern may be preceded by any of the options understood by `compadd` that are passed down from `_description`, namely `-M`, `-J`, `-V`, `-1`, `-2`, `-n`, `-F` and `-X`. All of these options will be ignored. This fits in conveniently with the argument-passing conventions of actions for `_arguments`.

  As an example, consider a command taking the options `-n` and `-none`, where `-n` must be followed by a numeric value in the same word. By using:

      _arguments '-n-: :_guard "[0-9]#" "numeric value"' '-none'

  `_arguments` can be made to both display the message ‘`numeric value`’ and complete options after ‘`-n<TAB>`’. If the ‘`-n`’ is already followed by one or more digits (the pattern passed to `_guard`) only the message will be displayed; if the ‘`-n`’ is followed by another character, only options are completed.

`_message` [ `-r12` ] [ `-VJ` group ] descr ¶
`_message -e` [ tag ] descr

  The descr is used in the same way as the third argument to the `_description` function, except that the resulting string will always be shown whether or not matches were generated. This is useful for displaying a help message in places where no completions can be generated.

  The `format` style is examined with the `messages` tag to find a message; the usual tag, `descriptions`, is used only if the style is not set with the former.

  If the `-r` option is given, no style is used; the descr is taken literally as the string to display. This is most useful when the descr comes from a pre-processed argument list which already contains an expanded description. Note that this option does not disable the ‘`%`’-sequence parsing done by `compadd`.

  The `-12VJ` options and the group are passed to `compadd` and hence determine the group the message string is added to.

  The second `-e` form gives a description for completions with the tag tag to be shown even if there are no matches for that tag. This form is called by `_arguments` in the event that there is no action for an option specification. The tag can be omitted and if so the tag is taken from the parameter `$curtag`; this is maintained by the completion system and so is usually correct. Note that if there are no matches at the time this function is called, `compstate[insert]` is cleared, so additional matches generated later are not inserted on the command line.

`_multi_parts` [ `-i` ] sep array ¶

  The argument sep is a separator character. The array may be either the name of an array parameter or a literal array in the form ‘`(foo bar``)`’, a parenthesised list of words separated by whitespace. The possible completions are the strings from the array. However, each chunk delimited by sep will be completed separately. For example, the `_tar` function uses ‘`_multi_parts` `/` patharray’ to complete partial file paths from the given array of complete file paths.

  The `-i` option causes `_multi_parts` to insert a unique match even if that requires multiple separators to be inserted. This is not usually the expected behaviour with filenames, but certain other types of completion, for example those with a fixed set of possibilities, may be more suited to this form.

  Like other utility functions, this function accepts the ‘`-V`’, ‘`-J`’, ‘`-1`’, ‘`-2`’, ‘`-n`’, ‘`-f`’, ‘`-X`’, ‘`-M`’, ‘`-P`’, ‘`-S`’, ‘`-r`’, ‘`-R`’, and ‘`-q`’ options and passes them to the `compadd` builtin.

`_next_label` [ `-x` ] [ `-12VJ` ] tag name descr [ option ... ] ¶

  This function is used to implement the loop over different tag labels for a particular tag as described above for the `tag-order` style. On each call it checks to see if there are any more tag labels; if there is it returns status zero, otherwise non-zero. As this function requires a current tag to be set, it must always follow a call to `_tags` or `_requested`.

  The `-x12VJ` options and the first three arguments are passed to the `_description` function. Where appropriate the tag will be replaced by a tag label in this call. Any description given in the `tag-order` style is preferred to the descr passed to `_next_label`.

  The options given after the descr are set in the parameter given by name, and hence are to be passed to `compadd` or whatever function is called to add the matches.

  Here is a typical use of this function for the tag `foo`. The call to `_requested` determines if tag `foo` is required at all; the loop over `_next_label` handles any labels defined for the tag in the `tag-order` style.

      local expl ret=1
      ...
      if _requested foo; then
        ...
        while _next_label foo expl '...'; do
          compadd "$expl[@]" ... && ret=0
        done
        ...
      fi
      return ret

`_normal` [ `-P` | `-p` precommand ] ¶

  This is the standard function called to handle completion outside any special `-`context`-`. It is called both to complete the command word and also the arguments for a command. In the second case, `_normal` looks for a special completion for that command, and if there is none it uses the completion for the `-default-` context.

  A second use is to reexamine the command line specified by the `$words` array and the `$CURRENT` parameter after those have been modified. For example, the function `_precommand`, which completes after precommand specifiers such as `nohup`, removes the first word from the `words` array, decrements the `CURRENT` parameter, then calls ‘`_normal -p $service`’. The effect is that ‘`nohup` cmd ...’ is treated in the same way as ‘cmd ...’.

  `-P`

    Reset the list of precommands. This option should be used if completing a command line which allows internal commands (e.g. builtins and functions) regardless of prior precommands (e.g. ‘`zsh -c`’).

  `-p` precommand

    Append precommand to the list of precommands. This option should be used in nearly all cases in which `-P` is not applicable.

  If the command name matches one of the patterns given by one of the options `-p` or `-P` to `compdef`, the corresponding completion function is called and then the parameter `_compskip` is checked. If it is set completion is terminated at that point even if no matches have been found. This is the same effect as in the `-first-` context.

`_numbers` [ option ... ] [ description ] [ suffix ... ] ¶

  This can be used where a number is followed by a suffix to indicate the units. The unit suffixes are completed and can also be included in the description used when completion is invoked for the preceding number.

  In addition to common `compadd` options, `_numbers` accepts the following options:

  `-t` tag

    Specify a tag to use instead of the default of `numbers`.

  `-u` units

    Indicate the default units for the number, e.g. `bytes`.

  `-l` min

    Specify the lowest possible value for the number.

  `-m` max

    Specify the highest possible value for the number.

  `-d` default

    Specify the default value.

  `-N`

    Allow negative numbers. This is implied if the range includes a negative.

  `-f`

    Allow decimal numbers.

  Where a particular suffix represents the default units for a number, it should be prefixed with a colon. Additionally, suffixes can be followed by a colon and a description. So for example, the following allows the age of something to be specified, either in seconds or with an optional suffix with a longer unit of time:

      _numbers -u seconds age :s:seconds m:minutes h:hours d:days

  It is typically helpful for units to be presented in order of magnitude when completed. To facilitate this, the order in which they are given is preserved.

  When the `format` style is looked up with the `descriptions` tag or the tag specified with `-t`, the list of suffixes is available as a ‘`%x`’ escape sequence. This is in addition to the usual sequences documented under the `format` style. The form this list takes can also be configured. To this end, the `format` style is first looked up with the tag `unit-suffixes`. The retrieved format is applied to each suffix in turn and the results are then concatenated to form the completed list. For the `unit-suffixes` format, ‘`%x`’ expands to the individual suffix and ‘`%X`’ to its description. `%d`’ indicates a default suffix and can be used in a condition. The index and reverse index are set in ‘`%i`’ and ‘`%r`’ respectively and are useful for text included only with the first and last suffixes in the list. So for example, the following joins the suffixes together as a comma-separated list:

      zstyle ':completion:*:unit-suffixes' format '%x%(r::,)'

`_options` ¶

  This can be used to complete the names of shell options. It provides a matcher specification that ignores a leading ‘`no`’, ignores underscores and allows upper-case letters to match their lower-case counterparts (for example, ‘`glob`’, ‘`noglob`’, ‘`NO_GLOB`’ are all completed). Any arguments are propagated to the `compadd` builtin.

`_options_set` and `_options_unset` ¶

  These functions complete only set or unset options, with the same matching specification used in the `_options` function.

  Note that you need to uncomment a few lines in the `_main_complete` function for these functions to work properly. The lines in question are used to store the option settings in effect before the completion widget locally sets the options it needs. Hence these functions are not generally used by the completion system.

`_parameters` ¶

  This is used to complete the names of shell parameters.

  The option ‘`-g` pattern’ limits the completion to parameters whose type matches the pattern. The type of a parameter is that shown by ‘`print ${(t)`param`}`’, hence judicious use of ‘`*`’ in pattern is probably necessary.

  All other arguments are passed to the `compadd` builtin.

`_path_files` ¶

  This function is used throughout the completion system to complete filenames. It allows completion of partial paths. For example, the string ‘`/u/i/s/sig`’ may be completed to ‘`/usr/include/sys/signal.h`’.

  The options accepted by both `_path_files` and `_files` are:

  `-f`

    Complete all filenames. This is the default.

  `-/`

    Specifies that only directories should be completed.

  `-g` pattern

    Specifies that only files matching the pattern should be completed.

  `-W` paths

    Specifies path prefixes that are to be prepended to the string from the command line to generate the filenames but that should not be inserted as completions nor shown in completion listings. Here, paths may be the name of an array parameter, a literal list of paths enclosed in parentheses or an absolute pathname.

  `-F` ignored-files

    This behaves as for the corresponding option to the `compadd` builtin. It gives direct control over which filenames should be ignored. If the option is not present, the `ignored-patterns` style is used.

  Both `_path_files` and `_files` also accept the following options which are passed to `compadd`: ‘`-J`’, ‘`-V`’, ‘`-1`’, ‘`-2`’, ‘`-n`’, ‘`-X`’, ‘`-M`’, ‘`-P`’, ‘`-S`’, ‘`-q`’, ‘`-r`’, and ‘`-R`’.

  Finally, the `_path_files` function uses the styles `expand`, `ambiguous`, `special-dirs`, `list-suffixes` and `file-sort` described above.

`_pick_variant` [ `-b` builtin-label ] [ `-c` command ] [ `-r` name ]
`` label`=`pattern ... label [ arg ... ]

  This function is used to resolve situations where a single command name requires more than one type of handling, either because it has more than one variant or because there is a name clash between two different commands.

  The command to run is taken from the first element of the array `words` unless this is overridden by the option `-c`. This command is run and its output is compared with a series of patterns. Arguments to be passed to the command can be specified at the end after all the other arguments. The patterns to try in order are given by the arguments label`=`pattern; if the output of ‘command arg ...’ contains pattern, then label is selected as the label for the command variant. If none of the patterns match, the final command label is selected and status 1 is returned.

  If the ‘`-b` builtin-label’ is given, the command is tested to see if it is provided as a shell builtin, possibly autoloaded; if so, the label builtin-label is selected as the label for the variant.

  If the ‘`-r` name’ is given, the label picked is stored in the parameter named name.

  The results are also cached in the `_cmd_variant` associative array indexed by the name of the command run.

`_regex_arguments` name spec ... ¶

  This function generates a completion function name which matches the specifications specs, a set of regular expressions as described below. After running `_regex_arguments`, the function name should be called as a normal completion function. The pattern to be matched is given by the contents of the `words` array up to the current cursor position joined together with null characters; no quotation is applied.

  The arguments are grouped as sets of alternatives separated by ‘`|`’, which are tried one after the other until one matches. Each alternative consists of a one or more specifications which are tried left to right, with each pattern matched being stripped in turn from the command line being tested, until all of the group succeeds or until one fails; in the latter case, the next alternative is tried. This structure can be repeated to arbitrary depth by using parentheses; matching proceeds from inside to outside.

  A special procedure is applied if no test succeeds but the remaining command line string contains no null character (implying the remaining word is the one for which completions are to be generated). The completion target is restricted to the remaining word and any actions for the corresponding patterns are executed. In this case, nothing is stripped from the command line string. The order of evaluation of the actions can be determined by the `tag-order` style; the various formats supported by `_alternative` can be used in action. The descr is used for setting up the array parameter `expl`.

  Specification arguments take one of following forms, in which metacharacters such as ‘`(`’, ‘`)`’, ‘`#`’ and ‘`|`’ should be quoted.

  `/`pattern`/` [`%`lookahead`%`] [`-`guard] [`:`tag`:`descr`:`action]

    This is a single primitive component. The function tests whether the combined pattern ‘`(#b)((#B)`pattern`)`lookahead`*`’ matches the command line string. If so, ‘guard’ is evaluated and its return status is examined to determine if the test has succeeded. The pattern string ‘`[]`’ is guaranteed never to match. The lookahead is not stripped from the command line before the next pattern is examined.

    The argument starting with `:` is used in the same manner as an argument to `_alternative`.

    A component is used as follows: pattern is tested to see if the component already exists on the command line. If it does, any following specifications are examined to find something to complete. If a component is reached but no such pattern exists yet on the command line, the string containing the action is used to generate matches to insert at that point.

  `/`pattern`/+` [`%`lookahead`%`] [`-`guard] [`:`tag`:`descr`:`action]

    This is similar to ‘`/`pattern`/` ...’ but the left part of the command line string (i.e. the part already matched by previous patterns) is also considered part of the completion target.

  `/`pattern`/-` [`%`lookahead`%`] [`-`guard] [`:`tag`:`descr`:`action]

    This is similar to ‘`/`pattern`/` ...’ but the actions of the current and previously matched patterns are ignored even if the following ‘pattern’ matches the empty string.

  `(` spec `)`

    Parentheses may be used to groups specs; note each parenthesis is a single argument to `_regex_arguments`.

  spec `#`

    This allows any number of repetitions of spec.

  spec spec

    The two specs are to be matched one after the other as described above.

  spec `|` spec

    Either of the two specs can be matched.

  The function `_regex_words` can be used as a helper function to generate matches for a set of alternative words possibly with their own arguments as a command line argument.

  Examples:

      _regex_arguments _tst /$'[^\0]#\0'/ \
          /$'[^\0]#\0'/ :'compadd aaa'

  This generates a function `_tst` that completes `aaa` as its only argument. The tag and description for the action have been omitted for brevity (this works but is not recommended in normal use). The first component matches the command word, which is arbitrary; the second matches any argument. As the argument is also arbitrary, any following component would not depend on `aaa` being present.

      _regex_arguments _tst /$'[^\0]#\0'/ \
          /$'aaa\0'/ :'compadd aaa'

  This is a more typical use; it is similar, but any following patterns would only match if `aaa` was present as the first argument.

      _regex_arguments _tst /$'[^\0]#\0'/ \( \
          /$'aaa\0'/ :'compadd aaa' \
          /$'bbb\0'/ :'compadd bbb' \) \#

  In this example, an indefinite number of command arguments may be completed. Odd arguments are completed as `aaa` and even arguments as `bbb`. Completion fails unless the set of `aaa` and `bbb` arguments before the current one is matched correctly.

      _regex_arguments _tst /$'[^\0]#\0'/ \
          \( /$'aaa\0'/ :'compadd aaa' \| \
          /$'bbb\0'/ :'compadd bbb' \) \#

  This is similar, but either `aaa` or `bbb` may be completed for any argument. In this case `_regex_words` could be used to generate a suitable expression for the arguments.

`_regex_words` tag description spec ... ¶

  This function can be used to generate arguments for the `_regex_arguments` command which may be inserted at any point where a set of rules is expected. The tag and description give a standard tag and description pertaining to the current context. Each spec contains two or three arguments separated by a colon: note that there is no leading colon in this case.

  Each spec gives one of a set of words that may be completed at this point, together with arguments. It is thus roughly equivalent to the `_arguments` function when used in normal (non-regex) completion.

  The part of the spec before the first colon is the word to be completed. This may contain a `*`; the entire word, before and after the `*` is completed, but only the text before the `*` is required for the context to be matched, so that further arguments may be completed after the abbreviated form.

  The second part of spec is a description for the word being completed.

  The optional third part of the spec describes how words following the one being completed are themselves to be completed. It will be evaluated in order to avoid problems with quoting. This means that typically it contains a reference to an array containing previously generated regex arguments.

  The option `-t` term specifies a terminator for the word instead of the usual space. This is handled as an auto-removable suffix in the manner of the option `-s` sep to `_values`.

  The result of the processing by `_regex_words` is placed in the array `reply`, which should be made local to the calling function. If the set of words and arguments may be matched repeatedly, a `#` should be appended to the generated array at that point.

  For example:

      local -a reply
      _regex_words mydb-commands 'mydb commands' \
        'add:add an entry to mydb:$mydb_add_cmds' \
        'show:show entries in mydb'
      _regex_arguments _mydb "$reply[@]"
      _mydb "$@"

  This shows a completion function for a command `mydb` which takes two command arguments, `add` and `show`. `show` takes no arguments, while the arguments for `add` have already been prepared in an array `mydb_add_cmds`, quite possibly by a previous call to `_regex_words`.

`_requested` [ `-x` ] [ `-12VJ` ] tag [ name descr [ command [ arg ... ] ] ¶

  This function is called to decide whether a tag already registered by a call to `_tags` (see below) has been requested by the user and hence completion should be performed for it. It returns status zero if the tag is requested and non-zero otherwise. The function is typically used as part of a loop over different tags as follows:

      _tags foo bar baz
      while _tags; do
        if _requested foo; then
          ... # perform completion for foo
        fi
        ... # test the tags bar and baz in the same way
        ... # exit loop if matches were generated
      done

  Note that the test for whether matches were generated is not performed until the end of the `_tags` loop. This is so that the user can set the `tag-order` style to specify a set of tags to be completed at the same time.

  If name and descr are given, `_requested` calls the `_description` function with these arguments together with the options passed to `_requested`.

  If command is given, the `_all_labels` function will be called immediately with the same arguments. In simple cases this makes it possible to perform the test for the tag and the matching in one go. For example:

      local expl ret=1
      _tags foo bar baz
      while _tags; do
        _requested foo expl 'description' \
            compadd foobar foobaz && ret=0
        ...
        (( ret )) || break
      done

  If the command is not `compadd`, it must nevertheless be prepared to handle the same options.

`_retrieve_cache` cache_identifier ¶

  This function retrieves completion information from the file given by cache_identifier, stored in a directory specified by the `cache-path` style which defaults to `~/.zcompcache`. The return status is zero if retrieval was successful. It will only attempt retrieval if the `use-cache` style is set, so you can call this function without worrying about whether the user wanted to use the caching layer.

  See `_store_cache` below for more details.

`_sep_parts` ¶

  This function is passed alternating arrays and separators as arguments. The arrays specify completions for parts of strings to be separated by the separators. The arrays may be the names of array parameters or a quoted list of words in parentheses. For example, with the array ‘`hosts=(ftp news)`’ the call ‘`_sep_parts '(foo bar)' @ hosts`’ will complete the string ‘`f`’ to ‘`foo`’ and the string ‘`b@n`’ to ‘`bar@news`’.

  This function accepts the `compadd` options ‘`-V`’, ‘`-J`’, ‘`-1`’, ‘`-2`’, ‘`-n`’, ‘`-X`’, ‘`-M`’, ‘`-P`’, ‘`-S`’, ‘`-r`’, ‘`-R`’, and ‘`-q`’ and passes them on to the `compadd` builtin used to add the matches.

`_sequence` [ `-s` sep ] [ `-n` max ] [ `-d` ] function [ `-` ] ... ¶

  This function is a wrapper to other functions for completing items in a separated list. The same function is used to complete each item in the list. The separator is specified with the `-s` option. If `-s` is omitted it will use ‘`,`’. Duplicate values are not matched unless `-d` is specified. If there is a fixed or maximum number of items in the list, this can be specified with the `-n` option.

  Common `compadd` options are passed on to the function. It is possible to use `compadd` directly with `_sequence`, though `_values` may be more appropriate in this situation.

`_setup` tag [ group ] ¶

  This function sets up the special parameters used by the completion system appropriately for the tag given as the first argument. It uses the styles `list-colors`, `list-packed`, `list-rows-first`, `last-prompt`, `accept-exact`, `menu` and `force-list`.

  The optional group supplies the name of the group in which the matches will be placed. If it is not given, the tag is used as the group name.

  This function is called automatically from `_description` and hence is not normally called explicitly.

`_store_cache` cache_identifier param ... ¶

  This function, together with `_retrieve_cache` and `_cache_invalid`, implements a caching layer which can be used in any completion function. Data obtained by costly operations are stored in parameters; this function then dumps the values of those parameters to a file. The data can then be retrieved quickly from that file via `_retrieve_cache`, even in different instances of the shell.

  The cache_identifier specifies the file which the data should be dumped to. The file is stored in a directory specified by the `cache-path` style which defaults to `~/.zcompcache`. The remaining params arguments are the parameters to dump to the file.

  The return status is zero if storage was successful. The function will only attempt storage if the `use-cache` style is set, so you can call this function without worrying about whether the user wanted to use the caching layer.

  The completion function may avoid calling `_retrieve_cache` when it already has the completion data available as parameters. However, in that case it should call `_cache_invalid` to check whether the data in the parameters and in the cache are still valid.

  See the _perl_modules completion function for a simple example of the usage of the caching layer.

`_tags` [ [ `-C` name ] tag ... ] ¶

  If called with arguments, these are taken to be the names of tags valid for completions in the current context. These tags are stored internally and sorted by using the `tag-order` style.

  Next, `_tags` is called repeatedly without arguments from the same completion function. This successively selects the first, second, etc. set of tags requested by the user. The return status is zero if at least one of the tags is requested and non-zero otherwise. To test if a particular tag is to be tried, the `_requested` function should be called (see above).

  If ‘`-C` name’ is given, name is temporarily stored in the argument field (the fifth) of the context in the `curcontext` parameter during the call to `_tags`; the field is restored on exit. This allows `_tags` to use a more specific context without having to change and reset the `curcontext` parameter (which has the same effect).

`_tilde_files` ¶

  Like `_files`, but resolve leading tildes according to the rules of filename expansion, so the suggested completions don’t start with a ‘`~`’ even if the filename on the command-line does.

`_values` [ `-O` name ] [ `-s` sep ] [ `-S` sep ] [ `-wC` ] desc spec ... ¶

  This is used to complete arbitrary keywords (values) and their arguments, or lists of such combinations.

  If the first argument is the option ‘`-O` name’, it will be used in the same way as by the `_arguments` function. In other words, the elements of the name array will be passed to `compadd` when executing an action.

  If the first argument (or the first argument after ‘`-O` name’) is ‘`-s`’, the next argument is used as the character that separates multiple values. This character is automatically added after each value in an auto-removable fashion (see below); all values completed by ‘`_values -s`’ appear in the same word on the command line, unlike completion using `_arguments`. If this option is not present, only a single value will be completed per word.

  Normally, `_values` will only use the current word to determine which values are already present on the command line and hence are not to be completed again. If the `-w` option is given, other arguments are examined as well.

  The first non-option argument, desc, is used as a string to print as a description before listing the values.

  All other arguments describe the possible values and their arguments in the same format used for the description of options by the `_arguments` function (see above). The only differences are that no minus or plus sign is required at the beginning, values can have only one argument, and the forms of action beginning with an equal sign are not supported.

  The character separating a value from its argument can be set using the option `-S` (like `-s`, followed by the character to use as the separator in the next argument). By default the equals sign will be used as the separator between values and arguments.

  Example:

      _values -s , 'description' \
              '*foo[bar]' \
              '(two)*one[number]:first count:' \
              'two[another number]::second count:(1 2 3)'

  This describes three possible values: ‘`foo`’, ‘`one`’, and ‘`two`’. The first is described as ‘`bar`’, takes no argument and may appear more than once. The second is described as ‘`number`’, may appear more than once, and takes one mandatory argument described as ‘`first count`’; no action is specified, so it will not be completed. The ‘`(two)`’ at the beginning says that if the value ‘`one`’ is on the line, the value ‘`two`’ will no longer be considered a possible completion. Finally, the last value (‘`two`’) is described as ‘`another number`’ and takes an optional argument described as ‘`second count`’ for which the completions (to appear after an ‘`=`’) are ‘`1`’, ‘`2`’, and ‘`3`’. The `_values` function will complete lists of these values separated by commas.

  Like `_arguments`, this function temporarily adds another context name component to the arguments element (the fifth) of the current context while executing the action. Here this name is just the name of the value for which the argument is completed.

  The style `verbose` is used to decide if the descriptions for the values (but not those for the arguments) should be printed.

  The associative array `val_args` is used to report values and their arguments; this works similarly to the `opt_args` associative array used by `_arguments`. Hence the function calling `_values` should declare the local parameters `state`, `state_descr`, `line`, `context` and `val_args`:

      local context state state_descr line
      typeset -A val_args

  when using an action of the form ‘`->`string’. With this function the `context` parameter will be set to the name of the value whose argument is to be completed. Note that for `_values`, the `state` and `state_descr` are scalars rather than arrays. Only a single matching state is returned.

  Note also that `_values` normally adds the character used as the separator between values as an auto-removable suffix (similar to a ‘`/`’ after a directory). However, this is not possible for a ‘`->`string’ action as the matches for the argument are generated by the calling function. To get the usual behaviour, the calling function can add the separator x as a suffix by passing the options ‘`-qS` x’ either directly or indirectly to `compadd`.

  The option `-C` is treated in the same way as it is by `_arguments`. In that case the parameter `curcontext` should be made local instead of `context` (as described above).

`_wanted` [ `-x` ] [ `-C` name ] [ `-12VJ` ] tag name descr command [ arg ...] ¶

  In many contexts, completion can only generate one particular set of matches, usually corresponding to a single tag. However, it is still necessary to decide whether the user requires matches of this type. This function is useful in such a case.

  The arguments to `_wanted` are the same as those to `_requested`, i.e. arguments to be passed to `_description`. However, in this case the command is not optional; all the processing of tags, including the loop over both tags and tag labels and the generation of matches, is carried out automatically by `_wanted`.

  Hence to offer only one tag and immediately add the corresponding matches with the given description:

      local expl
      _wanted tag expl 'description' \
          compadd -- match1 match2...

  See also the use of `_wanted` in the example function in Dynamic named directories.

  Note that, as for `_requested`, the command must be able to accept options to be passed down to `compadd`.

  Like `_tags` this function supports the `-C` option to give a different name for the argument context field. The `-x` option has the same meaning as for `_description`.

`_widgets` [ `-g` pattern ] ¶

  This function completes names of zle widgets (see Zle Widgets). The pattern, if present, is matched against values of the `$widgets` special parameter, documented in The zsh/zleparameter Module.