(zsh.info.gz) Completion Functions
Info Catalog
(zsh.info.gz) Bindable Commands
(zsh.info.gz) Completion System
(zsh.info.gz) Completion Directories
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.
Two more features are offered by the _main_complete function. The
arrays compprefuncs and comppostfuncs may contain names of functions
that are to be called immediately before or after completion has been
tried. A function will only be called once unless it explicitly
reinserts itself into the array.
_all_labels [ -x ] [ -12VJ ] TAG NAME DESCR [ COMMAND ARGS ... ]
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), excluding the '->STATE' and '=...' forms.
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 [ -nswWACRS ] [ -O NAME ] [ -M MATCHSPEC ] [ : ] SPEC ...
This function can be used to give a complete specification for
completion for a command whose arguments follow standard UNIX
option and argument conventions. The following forms specify
individual sets of options and arguments; to avoid ambiguity, these
may be separated from the options to _arguments itself by a single
colon. Options to _arguments itself must be in separate words,
i.e. -s -w, not -sw.
With the option -n, _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.
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.
By default, options are multi-character name, one '-WORD' per
option. With -s, options may be single characters, with more
than one option per word, although words starting with two
hyphens, such as '--prefix', are still considered complete
option names. This is suitable for standard GNU options.
The combination of -s with -w allows single-letter options to
be combined in a single word even if one or more of the
options take arguments. For example, if -a takes an argument,
with no -s '-ab' is considered as a single (unhandled) option;
with -s -ab is an option with the argument 'b'; with both -s
and -w, -ab may be the option -a and the option -b with
arguments still to come.
The option -W takes this 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.
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 '-fooARG'.
-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
'-fooARG' 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'.
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 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 command name and normal arguments from the command line,
i.e. the words from the command line 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. For options that have more than one argument these are
given as one string, separated by colons. All colons in the
original arguments are preceded with backslashes.
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.
It is possible to specify multiple sets of options and arguments
with the sets separated by single hyphens. The specifications
before the first hyphen (if any) are shared by all the remaining
sets. The first word in every other set provides a name for the
set which may appear in exclusion lists in specifications, either
alone or before one of the possible values described above. In the
second case a '-' should appear between this name and the
remainder.
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.
If the name given for one of the mutually exclusive sets is of the
form '(NAME)' then only one value from each set will ever be
completed; more formally, all specifications are mutually exclusive
to all other specifications in the same set. This is useful for
defining multiple sets of options which are mutually exclusive and
in which the options are aliases for each other. For example:
_arguments \
-a -b \
- '(compress)' \
{-c,--compress}'[compress]' \
- '(uncompress)' \
{-d,--decompress}'[decompress]'
As the completion code has to parse the command line separately for
each set this form of argument is slow and 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.
The options -S and -A are available to simplify the specifications
for commands with standard option parsing. With -S, no option will
be completed after a '--' appearing on its own on the line; this
argument will otherwise be ignored; hence in the line
foobar -a -- -b
the '-a' is considered an option but the '-b' is considered an
argument, while the '--' is considered to be neither.
With -A, no options will be completed after the first non-option
argument on the line. The -A must be followed by 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 "-*"'.
The option '-O NAME' specifies the name of an array whose elements
will be passed as arguments to functions called to execute ACTIONS.
For example, this can be used to pass the same set of options for
the compadd builtin to all ACTIONs.
The option '-M SPEC' sets a match specification to use to
completion option names and values. It must appear before the
first argument specification. The default is 'r:|[_-]=* r:|=*':
this allows partial word completion after '_' and '-', for example
'-f-b' can be completed to '-foo-bar'.
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.
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 specifiers of the form
'PATTERN:MESSAGE:ACTION'; note that normal _arguments specifiers
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. 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 '=-'.
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. Each PAIR consists of a pattern
and a replacement. For example, some configure-scripts describe
options only as '--enable-foo', but also accept '--disable-foo'.
To allow completion of the second form:
_arguments -- -s "(#--enable- --disable-)"
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
NUMBERS' but does not offer completions.
_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 [ ARGS ... ]
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 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.
_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 different fields 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.
_describe [ -oO | -t TAG ] DESCR NAME1 [ NAME2 ] OPTS ... -- ...
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 followed by options to pass to compadd.
The first array contains the possible completions with their
descriptions in the form 'COMPLETION:DESCRIPTION'. Any literal
colons in COMPLETION must be quoted with a backslash. If a second
array is given, it should have the same number of elements as the
first; in this case the corresponding elements are added as
possible completions instead of the COMPLETION strings from the
first array. The completion list will retain the descriptions from
the first array. Finally, a set of completion options 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'.
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, ignored-patterns
and group-name. 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 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.
_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 STRING .... 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.
_files
The function _files calls _path_files with all the arguments it was
passed except for -g and -/. The use of these two options depends
on the setting of the file-patterns style.
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 is intended to be used in the ACTION for the
specifications passed to _arguments and similar functions. It
returns immediately with a non-zero return status if the string to
be completed does not match the PATTERN. If the pattern matches,
the DESCR is displayed; the function then returns status zero if
the word to complete is not empty, 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.
The -12VJ options and the GROUP are passed to compadd and hence
determine the group the message string is added to.
The second form gives a description for completions with the tag
TAG to be shown even if there are no matches for that tag. 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.
_multi_parts 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 [ OPTIONS ... ]
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
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 pre-command specifiers such as nohup, removes the first word
from the words array, decrements the CURRENT parameter, then calls
_normal again. The effect is that 'nohup CMD ...' is treated in
the same way as 'CMD ...'.
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.
_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 [ ARGS ... ]
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
ARGS ...' 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 SPEC ..., 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 ARGS ... ] ]
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.
_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 PARAMS ...
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 ] TAGS ... ]
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).
_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 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 ARGS ...
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 matches...
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.
Info Catalog
(zsh.info.gz) Bindable Commands
(zsh.info.gz) Completion System
(zsh.info.gz) Completion Directories
automatically generated by
info2html