ZSHCOMPSYS(1)
π¦ zshcompsys β zsh completion system π¦
okay so welcome to zshcompsys, bestie β this is the manual page for the zsh completion system, and we're about to get into it π
β¨ DESCRIPTION β¨
This page describes the shell code for the new completion system, which everyone calls compsys. It's written in shell functions, and those functions are built on the features described over in zshcompwid(1).
The whole thing is contextual β meaning it's sensitive to the exact point at which completion is started. And like, a ton of completions are already provided for you. Which is why a user can do a great many tasks without knowing any details beyond how to initialize the system (that's the INITIALIZATION section, coming up below π«Ά).
The context that decides what completion is gonna be performed can be:
- an argument or option position β these describe the position on the command line at which completion is requested. For example,
first argument to rmdir, the word being completed names a directory; - a special context, denoting an element in the shell's syntax. For example
a word in command positionoran array subscript.
A full context specification contains other elements too, as we shall describe. β¨
Besides command names and contexts, the system employs two more concepts: styles and tags. These are the ways you, the user, get to configure how the system behaves.
π·οΈ tags, the dual-role icons
Tags play a dual role, no cap:
- They serve as a classification system for the matches, typically indicating a class of object that the user may need to distinguish. For example, when completing arguments of the
lscommand, the user may prefer to try files before directories, so both of these are tags. - They also appear as the rightmost element in a context specification.
π styles, the vibe-setters
Styles modify various operations of the completion system β output formatting, but also what kinds of completers are used (and in what order), or which tags are examined. Styles may accept arguments, and you manipulate them using the zstyle command described in zshmodules(1).
πΈ the summary, because you deserve one
In summary: tags describe what the completion objects are, and styles describe how they are to be completed. At various points of execution, the completion system checks what styles and/or tags are defined for the current context, and uses that to modify its behavior. The full description of context handling β which determines how tags and other elements of the context influence the behaviour of styles β is described below in COMPLETION SYSTEM CONFIGURATION.
π§ the dispatcher, main character energy
When a completion is requested, a dispatcher function gets called. See the description of _main_complete in the list of control functions below. This dispatcher decides which function should be called to produce the completions, and calls it. The result is then passed to one or more completers β functions that implement individual completion strategies: simple completion, error correction, completion with error correction, menu selection, etc. It's giving assembly line, honestly π₯
π the two flavors of shell function
More generally, the shell functions contained in the completion system are of two types:
- those beginning
compare to be called directly; there are only a few of these; - those beginning
_are called by the completion code. The shell functions of this set, which implement completion behaviour and may be bound to keystrokes, are referred to aswidgets. These proliferate as new completions are required.
π INITIALIZATION π
If the system was installed completely, it should be enough to call the shell function compinit from your initialization file β see the next section. However, the function compinstall can be run by a user to configure various aspects of the completion system.
Usually, compinstall will insert code into .zshrc, although if that is not writable it will save it in another file and tell you that file's location. Note that it is up to you to make sure that the lines added to .zshrc are actually run; you may, for example, need to move them to an earlier place in the file if .zshrc usually returns early. So long as you keep them all together (including the comment lines at the start and finish), you can rerun compinstall and it will correctly locate and modify these lines. Note, however, that any code you add to this section by hand is likely to be lost if you rerun compinstall β although lines using the command zstyle should be gracefully handled. π
The new code will take effect next time you start the shell, or run .zshrc by hand; there is also an option to make them take effect immediately. However, if compinstall has removed definitions, you will need to restart the shell to see the changes.
To run compinstall you will need to make sure it is in a directory mentioned in your fpath parameter, which should already be the case if zsh was properly configured β as long as your startup files do not remove the appropriate directories from fpath. Then it must be autoloaded (autoload -U compinstall is recommended). You can abort the installation any time you are being prompted for information, and your .zshrc will not be altered at all; changes only take place right at the end, where you are specifically asked for confirmation. π
β Use of compinit
This section describes the use of compinit to initialize completion for the current session when called directly; if you have run compinstall it will be called automatically from your .zshrc.
To initialize the system, the function compinit should be in a directory mentioned in the fpath parameter, and should be autoloaded (autoload -U compinit is recommended), and then run simply as compinit. This will define a few utility functions, arrange for all the necessary shell functions to be autoloaded, and will then re-define all widgets that do completion to use the new system.
If you use the menu-select widget, which is part of the zsh/complist module, you should make sure that that module is loaded before the call to compinit so that that widget is also re-defined. And if completion styles (see below) are set up to perform expansion as well as completion by default, and the Tab key is bound to expand-or-complete, compinit will rebind it to complete-word β this is necessary to use the correct form of expansion. β¨
Should you need to use the original completion commands, you can still bind keys to the old widgets by putting a . in front of the widget name, e.g. .expand-or-complete.
π₯ the dump file situation
To speed up the running of compinit, it can be made to produce a dumped configuration that will be read in on future invocations. This is the default, but can be turned off by calling compinit with the option -D.
The dumped file is .zcompdump in the same directory as the startup files (i.e. $ZDOTDIR or $HOME); alternatively, an explicit file name can be given by compinit -d dumpfile. The next invocation of compinit will read the dumped file instead of performing a full initialization.
If the number of completion files changes, compinit will recognise this and produce a new dump file. However, if the name of a function or the arguments in the first line of a #compdef function (as described below) change, it is easiest to delete the dump file by hand so that compinit will re-create it the next time it is run. The check performed to see if there are new functions can be omitted by giving the option -C. In this case the dump file will only be created if there isn't one already. Use option -w to explain why a dump file isn't loaded and/or why it's regenerated. π«Ά
The dumping is actually done by another function, compdump, but you will only need to run this yourself if you change the configuration (e.g. using compdef) and then want to dump the new one. The name of the old dumped file will be remembered for this purpose.
If the parameter _compdir is set, compinit uses it as a directory where completion functions can be found; this is only necessary if they are not already in the function search path.
π the security check, bestie, listen
For security reasons compinit also checks if the completion system would use files not owned by root or by the current user, or files in directories that are world- or group-writable or that are not owned by root or by the current user. If such files or directories are found, compinit will ask if the completion system should really be used.
- To avoid these tests and make all files found be used without asking, use the option
-u. - To make
compinitsilently ignore all insecure files and directories, use the option-i.
This security check is skipped entirely when the -C option is given, provided the dumpfile exists.
The security check can be retried at any time by running the function compaudit. This is the same check used by compinit, but when it is executed directly any changes to fpath are made local to the function so they do not persist. The directories to be checked may be passed as arguments; if none are given, compaudit uses fpath and _compdir to find completion system directories, adding missing ones to fpath as necessary. To force a check of exactly the directories currently named in fpath, set _compdir to an empty string before calling compaudit or compinit.
π bash compatibility era
The function bashcompinit provides compatibility with bash's programmable completion system. When run it will define the functions compgen and complete which correspond to the bash builtins with the same names. It will then be possible to use completion specifications and functions written for bash. iconic, honestly π
π Autoloaded files
The convention for autoloaded functions used in completion is that they start with an underscore; as already mentioned, the fpath/FPATH parameter must contain the directory in which they are stored. If zsh was properly installed on your system, then fpath/FPATH automatically contains the required directories for the standard functions.
For incomplete installations, if compinit does not find enough files beginning with an underscore (fewer than twenty) in the search path, it will try to find more by adding the directory _compdir to the search path. If that directory has a subdirectory named Base, all subdirectories will be added to the path. Furthermore, if the subdirectory Base has a subdirectory named Core, compinit will add all subdirectories of the subdirectories to the path: this allows the functions to be in the same format as in the zsh source distribution.
When compinit is run, it searches all such files accessible via fpath/FPATH and reads the first line of each of them. This line should contain one of the tags described below. Files whose first line does not start with one of these tags are not considered to be part of the completion system and will not be treated specially.
The tags are:
#compdef name ... [ -{p|P} pattern ... [ -N name ... ] ]
okay so this tag is the moment a file becomes β¨autoloadableβ¨ and the function living inside it gets called when you're completing any of those names β and a name is either a command whose arguments you want completed, or one of the special -context- things listed further down. both valid, both iconic. π
each name can also be written as cmd=service. what that means: when you complete the command cmd, the function acts like it's completing the command (or special context) service instead. it's giving "alter the behaviour of functions that do many different completions" energy. how's it implemented? it sets the parameter $service when the function is called β the function can do whatever it wants with that, and honestly the simpler functions will probably just ignore it π
if your #compdef line has -p or -P in it, everything after is taken as a pattern. so the function fires when completion happens for a command or context matching one of those patterns. -p = patterns tried before other completions, -P = patterns tried after. so -P is literally how you set up default actions, no cap π«Ά
then -N comes after a -p/-P list and says "okay bestie, the rest of these words aren't patterns anymore." and you can toggle between all three options as many times as you need β go off π₯
#compdef -k style key-sequence ...
this one makes a widget that behaves like the builtin widget style and binds it to the given key-sequences (if any). the style has to be one of the builtin completion widgets, and the list is:
complete-worddelete-char-or-listexpand-or-completeexpand-or-complete-prefixlist-choicesmenu-completemenu-expand-or-completereverse-menu-complete
and if the zsh/complist module is loaded (peep zshmodules(1)) then menu-select is available too πΈ
type one of those key-sequences and the function in the file gets invoked to generate matches. heads up though: a key will not be re-bound if it already was β meaning if it was bound to anything other than undefined-key. π the widget created gets the same name as the file, and you can bind it to any other keys with bindkey like usual π
#compdef -K widget-name style key-sequence [ name style seq ... ]
basically -k's sibling, except it only takes one key-sequence per widget-name style pair. but the whole trio of arguments can be repeated with different sets. note the important bit: widget-name must be distinct in each set. if it doesn't start with _, the _ gets added for you. and widget-name shouldn't clash with any existing widget β names based on the function's name are the most useful move π
for example:
#compdef -K _foo_complete complete-word "^X^C" \
_foo_list list-choices "^X^D"
(all on one line, bestie) defines _foo_complete, a widget for completion bound to ^X^C, plus _foo_list, a widget for listing bound to ^X^D. two widgets, one tag, absolutely ate β
#autoload [ options ]
functions tagged #autoload get marked for autoloading but are otherwise not treated specially. usually they're meant to be called from inside one of your completion functions. any options you hand over get passed to the autoload builtin β the classic use case is +X to force the function to load immediately. and ngl, -U and -z are always added implicitly, so don't even worry about them π¦
the # is genuinely part of the tag name, and no white space is allowed after it β fr fr, not even one space π the #compdef tags use the compdef function described below; the main difference is that the function name is supplied implicitly. cute shortcut, honestly.
π§ the special contexts π§
these are the contexts you can define completion functions for:
-array-value-β the right hand side of an array assignment (name=(...)) π-assign-parameter-β the name of a parameter in an assignment, i.e. the left side of an=-brace-parameter-β the name of a parameter expansion inside braces (${...})-command-β a word in command position β¨-condition-β a word inside a condition ([[...]])-default-β any word with no other completion defined (the fallback bestie π )-equal-β a word starting with an equals sign-first-β tried before any other completion function π₯ see below, it's kinda special-math-β inside mathematical contexts, like((...))-parameter-β the name of a parameter expansion ($...)-redirect-β the word after a redirection operator-subscript-β the contents of a parameter subscript-tilde-β after an initial tilde (~), but before the first slash in the word π-value-β the right hand side of an assignment
about -first-: the function called there may set the _compskip parameter to one of several values:
allβ no further completion is attempted, periodt- a string containing the substring
patternsβ none of the pattern completion functions get called - a string containing
defaultβ the function for the-default-context won't be called, but functions defined for commands still will be π
default implementations ship for every single one of these contexts. in most cases the context -context- is implemented by a matching function _context β for example the context -tilde- and the function _tilde π
the -redirect- and -value- contexts get to carry extra context-specific info. (internally this is handled by each context's function calling the _dispatch function.) the extra info is tacked on, separated by commas.
for -redirect-, the extra info looks like -redirect-,op,command, where op is the redirection operator and command is the name of the command on the line. if there's no command on the line yet, the command field is just empty, no drama π«Ά
for -value-, the form is -value-,name,command, where name is the name of the parameter on the left side of the assignment. for elements of an associative array β say assoc=(key <TAB> β name gets expanded to name-key. and in certain special contexts, like completing after make CFLAGS=, the command part gives you the command's name (here: make); otherwise it's empty π
you do not have to define fully specific completions, because the functions provided will try to generate completions by progressively swapping elements out for -default-. for example, when completing after foo=<TAB>, _value tries these names in order:
-value-,foo,(note the empty command part)-value-,foo,-default--value-,-default-,-default-
β¦until it finds a function that can handle the context. slay, honestly π₯
as an example:
compdef '_files -g "*.log"' '-redirect-,2>,-default-'
completes files matching *.log after 2> <TAB> for any command with no more specific handler defined. also:
compdef _foo -value-,-default-,-default-
says _foo provides completions for the values of parameters that have no special function defined. (usually _value itself handles that one.) π
and the same lookup rules apply when looking up styles (described below); for example
zstyle ':completion:*:*:-redirect-,2>,*:*' file-patterns '*.log'
is just another way to make completion after 2> <TAB> complete files matching *.log. two roads, same destination, we love to see it π
π Functions π
this next one is defined by compinit and you can call it directly:
compdef [ -ane ] function name ... [ -{p|P} pattern ... [ -N name ...]]
compdef -d name ...
compdef -k [ -an ] function style key-sequence [ key-sequence ... ]
compdef -K [ -an ] function name style key-seq [ name style seq ... ]
first form: defines the function to call for completion in the given contexts, exactly as described for the #compdef tag above π
alternatively, all the arguments can be in the form cmd=service. here service should already have been defined by cmd1=service lines in #compdef files (as described above), and then the argument for cmd gets completed the same way service does. cute inheritance situation π
the function argument can also be a string containing almost any shell code β like, wild. if that string contains an equal sign, the cmd=service reading above wins. the -e option exists to say "no bestie, evaluate the first argument as shell code even if it has an equal sign in it." the string gets run through the eval builtin command to generate completions, which is a whole way of avoiding defining a new completion function at all β¨ for example, to complete files ending in .h as arguments to the command foo:
compdef '_files -g "*.h"' foo
-n stops any completions already defined for that command or context from being overwritten π
ββοΈ and -d deletes any completion defined for the commands or contexts you list β the opposite vibe entirely π
the names can also carry -p, -P and -N options just like the #compdef tag. the effect on the argument list is identical: it switches between definitions of patterns tried initially, patterns tried finally, and normal commands and contexts. toggle away, queen π
one more thing: $_compskip can be set by any function defined for a pattern context. if it's set to a value containing the substring patterns, none of the pattern-functions get called; if it's set to a value containing the substring all, no other function gets called at all. setting $_compskip like this is especially useful with the -p option β because otherwise the dispatcher moves on to additional functions (probably the default one) after calling the pattern-context one, which can mangle how completion possibilities display if you don't handle it properly. so handle it properly, bestie π€
okay so the -k form is literally the moment a widget gets named after the function thatβll be called for each of the key-sequences β think of it like the #compdef -k tag wearing a little matching outfit. π
The function is supposed to generate the completions it needs, and otherwise it behaves like the builtin widget whose name is passed as the style argument. The builtin widgets you can use here are: complete-word, delete-char-or-list, expand-or-complete, expand-or-complete-prefix, list-choices, menu-complete, menu-expand-or-complete, and reverse-menu-complete, plus menu-select if the zsh/complist module is loaded. The -n option is the tiny bodyguard that stops a key from being bound if itβs already bound to something other than undefined-key.
The -K form is similar and defines multiple widgets based on the same function, and each one needs the set of three arguments name, style and key-sequence β the last two work like they do for -k, and the first has to be a unique widget name beginning with an underscore.
Wherever applicable, the -a option makes the function autoloadable, which is equivalent to autoload -U function. β¨
The compdef function can also associate existing completion functions with new commands. For example,
compdef _pids foo
uses the function _pids to complete process IDs for the command foo.
Also note the _gnu_generic function described below β it can complete options for commands that understand the --help option. π«Ά
π COMPLETION SYSTEM CONFIGURATION π
β¨ Overview β¨
This section gives a short overview of how the completion system works, and then gets into more detail on how users can configure how and when matches are generated.
When completion is attempted somewhere on the command line, the completion system begins building the context. The context represents everything the shell knows about the meaning of the command line and the significance of the cursor position. This takes account of a number of things, including the command word (such as grep or zsh) and options to which the current word may be an argument (such as the -o option to zsh, which takes a shell option as an argument).
The context starts out very generic ("we are beginning a completion") and becomes more specific as more is learned ("the current word is in a position that is usually a command name" or "the current word might be a variable name" and so on). Therefore the context will vary during the same call to the completion system.
This context information is condensed into a string consisting of multiple fields separated by colons, referred to simply as the context in the remainder of the documentation. Note that a user of the completion system rarely needs to compose a context string, unless, for example, a new function is being written to perform completion for a new command. What a user may need to do is compose a style pattern, which is matched against a context when needed to look up context-sensitive options that configure the completion system.
The next few paragraphs explain how a context is composed within the completion function suite. Following that is discussion of how styles are defined. Styles determine such things as how the matches are generated, similarly to shell options but with much more control. They are defined with the zstyle builtin command (see zshmodules(1)).
The context string always consists of a fixed set of fields, separated by colons and with a leading colon before the first. Fields which are not yet known are left empty, but the surrounding colons appear anyway. The fields are always in the order
:completion:function:completer:command:argument:tag
These have the following meaning:
completionβ the literal stringcompletion, saying that this style is used by the completion system. This distinguishes the context from those used by, for example, zle widgets and ZFTP functions.functionβ the function, if completion is called from a named widget rather than through the normal completion system. Typically this is blank, but it is set by special widgets such aspredict-onand the various functions in theWidgetdirectory of the distribution to the name of that function, often in an abbreviated form.completerβ the completer currently active, the name of the function without the leading underscore and with other underscores converted to hyphens. Acompleteris in overall control of how completion is to be performed;completeis the simplest, but other completers exist to perform related tasks such as correction, or to modify the behaviour of a later completer. See the sectionControl Functionsbelow for more information.commandβ the command or a special-context-, just as it appears following the#compdeftag or thecompdeffunction. Completion functions for commands that have sub-commands usually modify this field to contain the name of the command followed by a minus sign and the sub-command. For example, the completion function for thecvscommand sets this field tocvs-addwhen completing arguments to theaddsubcommand.argumentβ this indicates which command line or option argument we are completing. For command arguments this generally takes the formargument-n, wherenis the number of the argument, and for arguments to options the formoption-opt-nwherenis the number of the argument to optionopt. However, this is only the case if the command line is parsed with standard UNIX-style options and arguments, so many completions do not set this.tagβ the tag. As described previously, tags are used to discriminate between the types of matches a completion function can generate in a certain context. Any completion function may use any tag name it likes, but a list of the more common ones is given below.
The context is gradually put together as the functions are executed, starting with the main entry point, which adds :completion: and the function element if necessary. The completer then adds the completer element. The contextual completion adds the command and argument options. Finally, the tag is added when the types of completion are known. For example, the context name
:completion::complete:dvips:option-o-1:files
says that normal completion was attempted as the first argument to the option -o of the command dvips:
dvips -o ...
and the completion function will generate filenames.
Usually completion will be tried for all possible tags in an order given by the completion function. However, this can be altered by using the tag-order style. Completion is then restricted to the list of given tags in the given order.
The _complete_help bindable command shows all the contexts and tags available for completion at a particular point. This provides an easy way of finding information for tag-order and other styles. It is described in the section Bindable Commands below.
When looking up styles the completion system uses full context names, including the tag. Looking up the value of a style therefore consists of two things: the context, which is matched to the most specific (best fitting) pattern, and the name of the style itself, which must be matched exactly. The following examples demonstrate that patterns may be loosely defined for styles that apply broadly, or as tightly defined as desired for styles that apply in narrower circumstances.
For example, many completion functions can generate matches in a simple and a verbose form and use the verbose style to decide which form should be used. To make all such functions use the verbose form, put
zstyle ':completion:*' verbose yes
in a startup file (probably .zshrc). This gives the verbose style the value yes in every context inside the completion system, unless that context has a more specific definition. It is best to avoid giving the pattern as * in case the style has some meaning outside the completion system.
Many such general purpose styles can be configured simply by using the compinstall function.
A more specific example of the use of the verbose style is by the completion for the kill builtin. If the style is set, the builtin lists full job texts and process command lines; otherwise it shows the bare job numbers and PIDs. To turn the style off for this use only:
zstyle ':completion:*:*:kill:*:*' verbose no
For even more control, the style can use one of the tags jobs or processes. To turn off verbose display only for jobs:
zstyle ':completion:*:*:kill:*:jobs' verbose no
The -e option to zstyle even allows completion function code to appear as the argument to a style; this requires some understanding of the internals of completion functions (see zshcompwid(1)). For example,
zstyle -e ':completion:*' hosts 'reply=($myhosts)'
This forces the value of the hosts style to be read from the variable myhosts each time a host name is needed; this is useful if the value of myhosts can change dynamically. For another useful example, see the example in the description of the file-list style below. This form can be slow and should be avoided for commonly examined styles such as menu and list-rows-first.
Note that the order in which styles are defined does not matter; the style mechanism uses the most specific possible match for a particular style to determine the set of values. Strings are preferred over patterns (for example, :completion::complete:::foo is more specific than :completion::complete:::*), and longer patterns are preferred over the pattern *. See zmodules(1) for details.
Context patterns that use something other than a wildcard (*) to match the middle parts of the context β the completer, command, and argument in :completion:function:completer:command:argument:tag β should include all six colons (:) explicitly. Without this, a pattern such as :completion:*:foo:* could match foo against a component other than the intended one (for example, against completer when a match against command was intended).
Style names like those of tags are arbitrary and depend on the completion function. However, the following two sections list some of the most common tags and styles.
π Standard Tags π
Some of the following are only used when looking up particular styles and do not refer to a type of match.
accountsβ used to look up theusers-hostsstyleall-expansionsβ used by the_expandcompleter when adding the single string containing all possible expansionsall-filesβ for the names of all files, like, every single one β¨ (as distinct from a particular subset β peep theglobbed-filestag for that vibe)argumentsβ for arguments to a command, bestiearraysβ for names of array parametersassociation-keysβ for keys of associative arrays; this one gets used when you're completing inside a subscript to a parameter of this type πbookmarksβ when completing bookmarks (e.g. for URLs and thezftpfunction suite)builtinsβ for names of builtin commandscharactersβ for single characters in arguments of commands such asstty. Also used when completing character classes after an opening bracketcolormapidsβ for X colormap idscolorsβ for color names πcommandsβ for names of external commands. Also used by complex commands such ascvswhen completing names of subcommands.contextsβ for contexts in arguments to thezstylebuiltin commandcorrectionsβ used by the_approximateand_correctcompleters for possible correctionscursorsβ for cursor names used by X programsdefaultβ used in some contexts to provide a way of supplying a default when more specific tags are also valid. Note that this tag is used when only the function field of the context name is setdescriptionsβ used when looking up the value of theformatstyle to generate descriptions for types of matchesdevicesβ for names of device special filesdirectoriesβ for names of directories --local-directoriesis used instead when completing arguments ofcdand related builtin commands when thecdpatharray is setdirectory-stackβ for entries in the directory stackdisplaysβ for X display namesdomainsβ for network domainsemail-pluginβ for email addresses from the_email-pluginbackend of_email_addressesexpansionsβ used by the_expandcompleter for individual words (as opposed to the complete set of expansions) resulting from the expansion of a word on the command lineextensionsβ for X server extensionsfile-descriptorsβ for numbers of open file descriptorsfilesβ the generic file-matching tag used by functions completing filenamesfontsβ for X font namesfstypesβ for file system types (e.g. for themountcommand)functionsβ names of functions -- normally shell functions, although certain commands may understand other kinds of functionglobbed-filesβ for filenames when the name has been generated by pattern matchinggroupsβ for names of user groupshistory-wordsβ for words from the history πhostsβ for hostnamesindexesβ for array indexesinterfacesβ for network interfacesjobsβ for jobs (as listed by the ``jobs'' builtin)keymapsβ for names of zsh keymapskeysymsβ for names of X keysymslibrariesβ for names of system librarieslimitsβ for system limitslocal-directoriesβ for names of directories that are subdirectories of the current working directory when completing arguments ofcdand related builtin commands (comparepath-directories) -- when thecdpatharray is unset,directoriesis used insteadmailboxesβ for e-mail folders π¬manualsβ for names of manual pagesmapsβ for map names (e.g. NIS maps)messagesβ used to look up theformatstyle for messagesmodifiersβ for names of X modifiersmodulesβ for modules (e.g. zsh modules)my-accountsβ used to look up theusers-hostsstylenamed-directoriesβ for named directories (you wouldn't have guessed that, would you? π)namesβ for all kinds of namesnewsgroupsβ for USENET groupsnicknamesβ for nicknames of NIS mapsoptionsβ for command optionsoriginalβ used by the_approximate,_correctand_expandcompleters when offering the original string as a matchother-accountsβ used to look up theusers-hostsstylepackagesβ for packages (e.g.rpmor installed Debian packages)parametersβ for names of parameterspath-directoriesβ for names of directories found by searching thecdpatharray when completing arguments ofcdand related builtin commands (comparelocal-directories)pathsβ used to look up the values of theexpand,ambiguousandspecial-dirsstylespodsβ for perl pods (documentation files)portsβ for communication portsprefixesβ for prefixes (like those of a URL)printersβ for print queue names π¨οΈprocessesβ for process identifiersprocesses-namesβ used to look up thecommandstyle when generating the names of processes forkillallsequencesβ for sequences (e.g.mhsequences)sessionsβ for sessions in thezftpfunction suitesignalsβ for signal namesstringsβ for strings (e.g. the replacement strings for thecdbuiltin command)stylesβ for styles used by thezstylebuiltin commandsuffixesβ for filename extensionstagsβ for tags (e.g.rpmtags)targetsβ formakefiletargetstime-zonesβ for time zones (e.g. when setting theTZparameter) πtypesβ for types of whatever (e.g. address types for thexhostcommand)urlsβ used to look up theurlsandlocalstyles when completing URLsusersβ for usernamesvaluesβ for one of a set of values in certain listsvariantβ used by_pick_variantto look up the command to run when determining what program is installed for a particular command name.visualsβ for X visualswarningsβ used to look up theformatstyle for warningswidgetsβ for zsh widget nameswindowsβ for IDs of X windowszsh-optionsβ for shell options
π Standard Styles π
Okay so heads up bestie β the values of several of these styles are, like, boolean, and here's the tea on what counts as what β
Any of the strings true, on, yes, and 1 can be used for the value true and any of the strings false, off, no, and 0 for the value false. The behavior for any other value is undefined except where explicitly mentioned π (so like, don't go being creative with it). The default value may be either true or false if the style is not set.
Some of these styles get tested first for every possible tag corresponding to a type of match, and if no style was found, then for the default tag. The most notable styles of this type are menu, list-colors and styles controlling completion listing such as list-packed and last-prompt. When tested for the default tag, only the function field of the context will be set so that a style using the default tag will normally be defined along the lines of:
zstyle ':completion:*:default' menu ...
accept-exactβ This is tested for thedefaulttag in addition to the tags valid for the current context. If it is set totrueand any of the trial matches is the same as the string on the command line, this match will immediately be accepted (even if it would otherwise be considered ambiguous) β¨
When completing pathnames (where the tag used is paths) this style accepts any number of patterns as the value in addition to the boolean values. Pathnames matching one of these patterns will be accepted immediately even if the command line contains some more partially typed pathname components and these match no file under the directory accepted.
This style is also used by the _expand completer to decide if words beginning with a tilde or parameter expansion should be expanded. For example, if there are parameters foo and foobar, the string $foo will only be expanded if accept-exact is set to true; otherwise the completion system will be allowed to complete $foo to $foobar. If the style is set to continue, _expand will add the expansion as a match and the completion system will also be allowed to continue.
accept-exact-dirsβ This is used by filename completion. Unlikeaccept-exactit is a boolean. By default, filename completion examines all components of a path to see if there are completions of that component, even if the component matches an existing directory. For example, when completion after/usr/bin/, the function examines possible completions to/usr.
When this style is true, any prefix of a path that matches an existing directory is accepted without any attempt to complete it further. Hence, in the given example, the path /usr/bin/ is accepted immediately and completion tried in that directory.
This style is also useful when completing after directories that magically appear when referenced, such as ZFS .zfs directories or NetApp .snapshot directories πͺ When the style is set the shell does not check for the existence of the directory within the parent directory.
If you wish to inhibit this behaviour entirely, set the path-completion style (see below) to false.
add-spaceβ This style is used by the_expandcompleter. If it istrue(the default), a space will be inserted after all words resulting from the expansion, or a slash in the case of directory names. If the value isfile, the completer will only add a space to names of existing files. Either a booleantrueor the valuefilemay be combined withsubst, in which case the completer will not add a space to words generated from the expansion of a substitution of the form$(...)or${...}.
The _prefix completer uses this style as a simple boolean value to decide if a space should be inserted before the suffix.
ambiguousβ This applies when completing non-final components of filename paths, in other words those with a trailing slash. If it is set, the cursor is left after the first ambiguous component, even if menu completion is in use. The style is always tested with thepathstag.
πΈ assign-list
ok so picture this: you're completing after an equals sign that's being treated as an assignment, right? Normally the completion system is like "one filename, that's it, that's the vibe" π
. But sometimes the value can literally be a list of filenames separated by colons β PATH and friends are exactly that girl. So you set this style to a list of patterns that match the names of those parameters. π
The default? It completes lists when the word already on the line has a colon in it. Simple as.
π¦ auto-description
If you set this, its value becomes the description for options that the completion functions didn't describe β but only the ones that have exactly one argument, no more no less. The sequence %d inside the value gets swapped out for the description of that argument. Depending on how your brain works, setting this to something like specify: %d might be your new fave. π Just a heads-up: this may not work for some commands, so don't come for me if a couple of them act brand new.
β¨ avoid-completer
This one's for _all_matches β it uses it to decide whether that big string made of all the matches should get added to the list currently being generated. The value is a list of completer names, and if any of them is the completer that generated the matches this time around, then nope, the string doesn't get added. π«
Default value is _expand _oldlist _correct _approximate β aka the completers where a string with all the matches is almost never what you want, fr fr.
π cache-path
This style defines where the cache files holding your dumped completion data live. Defaults to $ZDOTDIR/.zcompcache, or $HOME/.zcompcache if $ZDOTDIR isn't defined. π Just know that the completion cache will not be used unless the use-cache style is set β it's giving "invited but only shows up if you RSVP".
π cache-policy
This one defines the function that decides whether a cache needs rebuilding. Head down to the section on the _cache_invalid function below for the full tea. π«
π₯ call-command
Used in the functions for commands like make and ant, where calling the command directly to generate matches suffers problems β like being slow, or, in the case of make, potentially causing actions in the makefile to actually get executed π (yeah, not the vibe). If this is set to true, the command is called to generate matches. The default value is false.
β command
So in lots of places, completion functions need to call external commands to generate the completion list. This style lets you override the command that gets called in some of those cases. The elements of the value get joined with spaces to form a command line to execute. And plot twist: the value can also start with a hyphen, in which case the usual command gets added onto the end β super useful for putting builtin or command up front to make sure the right version of a command gets called, like when you're avoiding a shell function that has the same name as an external command. π§
Example time: the completion function for process IDs uses this style with the processes tag to generate the IDs to complete and the list of processes to display (if the verbose style is true). The list produced by the command should look like the output of the ps command. The first line isn't displayed, but it gets searched for the string PID (or pid) to find where the process IDs sit in the following lines. If that line doesn't contain PID, then the first numbers in each of the other lines are taken as the process IDs to complete.
β οΈ Careful, bestie: the completion function generally has to call the specified command on every attempt to generate the completion list. So only specify commands that run fast, and especially avoid anything that might never terminate π.
π command-path
A list of directories to search for commands to complete. The default for this style is the value of the special parameter path. Slay.
πΈ commands
This is used by the function completing sub-commands for the system initialisation scripts (the ones hanging out in /etc/init.d or somewhere not too far from there). Its values give the default commands to complete for those commands where the completion function can't figure them out automatically. The default for this style is two strings: start and stop.
π¦ complete
Used by the _expand_alias function when it's invoked as a bindable command. If it's set to true and the word on the command line is not the name of an alias, then matching alias names get completed. Iconic behaviour honestly.
β¨ complete-options
This one's used by the completer for cd, chdir and pushd. For these commands a - introduces a directory stack entry, and completing those is way more common than completing options. So unless this style's value is true, options won't be completed β even after an initial -. If it is true, options get completed after an initial - unless there's a preceding -- on the command line. π―
π completer
The strings you give as the value here are the names of the completer functions to use. The available completer functions are described in the section Control Functions below. π
Each string can be either the name of a completer function, or a string of the form function:name. In the first case, the completer field of the context will contain the name of the completer without the leading underscore, and with all other underscores replaced by hyphens. In the second case, the function is the name of the completer to call, but the context will contain the user-defined name in the completer field of the context. And if that name starts with a hyphen, the string for the context gets built from the name of the completer function as in the first case, with the name appended to it. For example:
zstyle ':completion:*' completer _complete _complete:-foo
Here, completion will call the _complete completer twice β once using complete and once using complete-foo in the completer field of the context. Normally, using the same completer more than once only makes sense when you're using the functions:name form, because otherwise the context name is gonna be the same in all the calls to the completer. Possible exceptions to this rule are the _ignored and _prefix completers. π
The default value for this style is _complete _ignored: only completion gets done, first using the ignored-patterns style and the $fignore array, and then without ignoring matches.
π condition
This style is used by the _list completer function to decide if inserting matches should be delayed unconditionally. The default is true.
π₯ delimiters
This one kicks in when adding a delimiter for use with history modifiers or glob qualifiers that have delimited arguments. It's an array of preferred delimiters to add. Non-special characters are preferred, because otherwise the completion system may get confused π΅βπ«. The default list is :, +, /, -, %. The list may be empty to force a delimiter to actually be typed. Periodt.
β disabled
If this is set to true, the _expand_alias completer and bindable command will try to expand disabled aliases too. The default is false.
π domains
A list of names of network domains for completion. If this isn't set, domain names get taken from the file /etc/resolv.conf. π¦
πΈ environ
The environ style is used when completing for sudo. It's set to an array of VAR=value assignments that get exported into the local environment before the completion for the target command is invoked. Like so:
zstyle ':completion:*:sudo::' environ \
PATH="/sbin:/usr/sbin:$PATH" HOME="/root"
π¦ expand
This style is used when completing strings that consist of multiple parts β path names being the classic example.
If one of its values is the string prefix, the partially typed word from the line gets expanded as far as possible, even if the trailing parts can't be completed. β¨
If one of its values is the string suffix, matching names for components after the first ambiguous one also get added. That means the resulting string is the longest unambiguous string possible. However β and this is the save β menu completion can be used to cycle through all the matches. π
π extra-verbose
If this style is set to true, the completion listing gets still more verbose. Right now it's used for the commands and parameters tags. If it's true for the commands (or parameters) tag, short descriptions of the commands (or the values of the parameters) get displayed alongside the command (or parameter) names. Extra? Yes. Iconic? Also yes. π
π fake
This style may be set for any completion context, and it specifies additional strings that will always be completed in that context. The form of each string is value:description β the colon and description may be omitted, but any literal colons in value have to be quoted with a backslash. Any description you provide gets shown alongside the value in completion listings. π«Ά
Use a sufficiently restrictive context when you're specifying fake strings, bestie. Note that the stylesfake-filesandfake-parametersprovide additional features when completing files or parameters.
π₯ fake-always
This works identically to the fake style, except that the ignored-patterns style is not applied to it. That's what makes it possible to override a whole set of matches completely by setting the ignored patterns to *. Main character energy, honestly π
β¨
okay so here's a way to supplement any tag with arbitrary data while still having it behave, for display purposes, like a separate tag. π
In this example we're using the features of the tag-order style to split the named-directories tag into two when completing with the standard completer complete for arguments of cd. The tag named-directories-normal behaves as normal, but named-directories-mine contains a fixed set of directories. The effect? It adds the match group extra directories with the given completions. β¨
zstyle ':completion::complete:cd:*' tag-order \
'named-directories:-mine:extra\ directories
named-directories:-normal:named\ directories *'
zstyle ':completion::complete:cd:*:named-directories-mine' \
fake-always mydir1 mydir2
zstyle ':completion::complete:cd:*:named-directories-mine' \
ignored-patterns '*'
fake-files β π this style is used when completing files and looked up without a tag. Its values are of the form dir:names.... It adds the names (strings separated by spaces) as possible matches when completing in the directory dir, even if no such files actually exist. The dir may be a pattern; pattern characters or colons in dir should be quoted with a backslash to be treated literally.
This can be useful on systems that support special file systems whose top-level pathnames can not be listed or generated with glob patterns (but see accept-exact-dirs for a more general way of dealing with this problem). It can also be used for directories for which one does not have read permission.
The pattern form can be used to add a certain magic entry to all directories on a particular file system. πͺ
fake-parameters β π§ this is used by the completion function for parameter names. Its values are names of parameters that might not yet be set but should be completed nonetheless. Each name may also be followed by a colon and a string specifying the type of the parameter (like scalar, array or integer). If the type is given, the name will only be completed if parameters of that type are required in the particular context. Names for which no type is specified will always be completed.
file-list β π this style controls whether files completed using the standard builtin mechanism are to be listed with a long list similar to ls -l. Note that this feature uses the shell module zsh/stat for file information; this loads the builtin stat which will replace any external stat executable. To avoid this the following code can be included in an initialization file:
zmodload -i zsh/stat
disable stat
The style may either be set to a true value (or all), or one of the values insert or list, indicating that files are to be listed in long format in all circumstances, or when attempting to insert a file name, or when listing file names without attempting to insert one.
More generally, the value may be an array of any of the above values, optionally followed by =num. If num is present it gives the maximum number of matches for which long listing style will be used. For example,
zstyle ':completion:*' file-list list=20 insert=10
specifies that long format will be used when listing up to 20 files or inserting a file with up to 10 matches (assuming a listing is to be shown at all, for example on an ambiguous completion), else short format will be used.
zstyle -e ':completion:*' file-list \
'(( ${+NUMERIC} )) && reply=(true)'
specifies that long format will be used any time a numeric argument is supplied, else short format. π
file-patterns β πΈ this is used by the standard function for completing filenames, _files. If the style is unset up to three tags are offered, globbed-files,directories and all-files, depending on the types of files expected by the caller of _files. The first two (globbed-files and directories) are normally offered together to make it easier to complete files in sub-directories.
The file-patterns style provides alternatives to the default tags, which are not used. Its value consists of elements of the form pattern:tag; each string may contain any number of such specifications separated by spaces.
The pattern is a pattern that is to be used to generate filenames. Any occurrence of the sequence %p is replaced by any pattern(s) passed by the function calling _files. Colons in the pattern must be preceded by a backslash to make them distinguishable from the colon before the tag. If more than one pattern is needed, the patterns can be given inside braces, separated by commas.
The tags of all strings in the value will be offered by _files and used when looking up other styles. Any tags in the same word will be offered at the same time and before later words. If no :tag is given the files tag will be used.
The tag may also be followed by an optional second colon and a description, which will be used for the %d in the value of the format style (if that is set) instead of the default description supplied by the completion function. The inclusion of a description also gives precedence to associated options such as for completion grouping so it can be used where files should be separated.
For example, to make the rm command first complete only names of object files and then the names of all files if there is no matching object file:
zstyle ':completion:*:*:rm:*:*' file-patterns \
'*.o:object-files' '%p:all-files'
To alter the default behaviour of file completion β offer files matching a pattern and directories on the first attempt, then all files β to offer only matching files on the first attempt, then directories, and finally all files:
zstyle ':completion:*' file-patterns \
'%p:globbed-files' '*(-/):directories' '*:all-files'
This works even where there is no special pattern: _files matches all files using the pattern * at the first step and stops when it sees this pattern. Note also it will never try a pattern more than once for a single completion attempt.
To separate directories into a separate group from the files but still complete them at the first attempt, a description needs to be given. Note that directories need to be explicitly excluded from the globbed-files because * will match directories. For grouping, it is also necessary to set the group-name style.
zstyle ':completion:*' file-patterns \
'%p(^-/):globbed-files *(-/):directories:location'
During the execution of completion functions, the EXTENDED_GLOB option is in effect, so the characters #, ~ and ^ have special meanings in the patterns. π₯
file-sort β π§ the standard filename completion function uses this style without a tag to determine in which order the names should be listed; menu completion will cycle through them in the same order. The possible values are: size to sort by the size of the file; links to sort by the number of links to the file; modification (or time or date) to sort by the last modification time; access to sort by the last access time; and inode (or change) to sort by the last inode change time. If the style is set to any other value, or is unset, files will be sorted alphabetically by name. If the value contains the string reverse, sorting is done in the opposite order. If the value contains the string follow, timestamps are associated with the targets of symbolic links; the default is to use the timestamps of the links themselves.
file-split-chars β βοΈ a set of characters that will cause all file completions for the given context to be split at the point where any of the characters occurs. A typical use is to set the style to :; then everything up to and including the last : in the string so far is ignored when completing files. As this is quite heavy-handed, it is usually preferable to update completion functions for contexts where this behaviour is useful.
filter β π§ the ldap plugin of email address completion (see _email_addresses) uses this style to specify the attributes to match against when filtering entries. So for example, if the style is set to sn, matching is done against surnames. Standard LDAP filtering is used so normal completion matching is bypassed. If this style is not set, the LDAP plugin is skipped. You may also need to set the command style to specify how to connect to your LDAP server.
force-list β π this forces a list of completions to be shown at any point where listing is done, even in cases where the list would usually be suppressed. For example, normally the list is only shown if there are at least two different matches. By setting this style to always, the list will always be shown, even if there is only a single match that will immediately be accepted. The style may also be set to a number. In this case the list will be shown if there are at least that many matches, even if they would all insert the same string.
This style is tested for the default tag as well as for each tag valid for the current completion. Hence the listing can be forced only for certain types of match.
format β π if this is set for the descriptions tag, its value is used as a string to display above matches in completion lists. The sequence %d in this string will be replaced with a short description of what these matches are. This string may also contain the output attribute sequences understood by compadd -X (see zshcompwid(1)). π
...and honestly the whole format-string lookup is a whole situation, so let's walk it π
The style gets tested with each tag valid for the current completion before it's tested for the descriptions tag. Which means β yup β you can define totally different format strings for different types of match. Different vibes for different tags, we love to see it β¨
Also note: some completer functions define their own extra %-sequences. Those are described over with the completer functions that actually use them, so no spoilers here π«Ά
Some completion functions display messages that you can customise by setting this style for the messages tag. In that case, the %d gets replaced with a message given by the completion function. π
And finally β the format string gets looked up with the warnings tag, for when no matches could be generated at all π In this case the %d is replaced with the descriptions for the matches that were expected, separated by spaces. The sequence %D is replaced with the same descriptions, separated by newlines. Two flavours, same tea π
Oh and bestie, you can use printf-style field width specifiers with %d and similar escape sequences π₯ That's handled by the zformat builtin command from the zsh/zutil module β see zshmodules(1).
gain-privilegesβ set it to true and this style enables the use of commands likesudoordoasto gain extra privileges when retrieving information for completion. It only does this when a command such assudoshows up on the command-line. And if you want to force the use of, say,sudo, or override any prefix that might get added because ofgain-privileges, you can use thecommandstyle with a value that begins with a hyphen. Iconic little loophole πglobβ this one's used by the_expandcompleter. If it's set totrue(the default), globbing will be attempted on the words resulting from a previous substitution (see thesubstitutestyle) or else the original string from the line. Default behaviour, but make it yours π«globalβ if this is set totrue(the default), the_expand_aliascompleter and bindable command will try to expand global aliases. Global girlies rise πgroup-nameβ okay so the completion system can group different types of matches, and those groups appear in separate lists. This style lets you give the names of groups for particular tags. For example, in command position the completion system generates names of builtin and external commands, names of aliases, shell functions and parameters, and reserved words as possible completions. To have the external commands and shell functions listed separately:
zstyle ':completion:*:*:-command-:*:commands' \
group-name commands
zstyle ':completion:*:*:-command-:*:functions' \
group-name functions
As a consequence, any match with the same tag will be displayed in the same group. Matching tags stay together, no cap π§²
If the name you give is the empty string, the name of the tag for the matches gets used as the name of the group. So, to have all the different types of matches displayed separately, you can just set:
zstyle ':completion:*' group-name ''
All matches for which no group name is defined get put in a group named -default-. The default group is literally called default, she's doing her best π
To display the group name in the output, see the format style (q.v.) under the descriptions tag.
group-orderβ this one's additional to thegroup-namestyle, and it specifies the order for display of the groups defined by that style (comparetag-order, which determines which completions appear at all β different job, bestie). The groups you name are shown in the given order; any other groups are shown in the order defined by the completion function. π
For example, to have names of builtin commands, shell functions and external commands appear in that order when completing in command position:
zstyle ':completion:*:*:-command-:*:*' group-order \
builtins functions commands
Sequencing slay β¨
groupsβ a list of names of UNIX groups. If this isn't set, group names are taken from the YP database or the file/etc/group. She'll find them herself, don't worry πhiddenβ if this is set totrue, matches for the given context won't be listed, although any description for the matches set with theformatstyle will still be shown. If it's set toall, not even the description gets displayed. Ghost mode π»
Note that the matches will still be completed β they're just not shown in the list. So they're lurking, ready, just invisible. To avoid having matches considered as possible completions at all, the tag-order style can be modified as described below.
hostsβ a list of names of hosts that should be completed. If this isn't set, hostnames are taken from the file/etc/hosts. π₯οΈhosts-portsβ this style is used by commands that need or accept hostnames and network ports. The strings in the value should be of the formhost:port. Valid ports are determined by the presence of hostnames; multiple ports for the same host may appear. Colon separating, ports multiplying, we love a duo πignore-lineβ this is tested for each tag valid for the current completion. If it's set totrue, none of the words that are already on the line will be considered as possible completions. If it's set tocurrent, the word the cursor is on won't be considered as a possible completion. The valuecurrent-shownis similar but only applies if the list of completions is currently shown on the screen. And finally, if the style is set toother, all words on the line except for the current one get excluded from the possible completions. π ββοΈ
The values current and current-shown are a bit like the opposite of the accept-exact style: only strings with missing characters will be completed. Flip the script, love that for us π
Note: you almost certainly don't want to set this totrueorotherfor a general context such as:completion:*. This is because it would disallow completion of, for example, options multiple times even if the command in question accepts the option more than once. So like... don't do that π
ignore-parentsβ this style is tested without a tag by the function completing pathnames, in order to determine whether to ignore the names of directories already mentioned in the current word, or the name of the current working directory. The value must include one or both of the following strings: πΈparentβ the name of any directory whose path is already contained in the word on the line is ignored. For example, when completing afterfoo/../, the directoryfoowill not be considered a valid completion. No going backwards, bestie.pwdβ the name of the current working directory will not be completed; hence, for example, completion after../will not use the name of the current directory.
In addition, the value may include one or both of:
..β ignore the specified directories only when the word on the line contains the substring../.directoryβ ignore the specified directories only when names of directories are completed, not when completing names of files.
Excluded values act in a similar fashion to values of the ignored-patterns style, so they can be restored to consideration by the _ignored completer. Second chances, we stan π«Ά
ignored-patternsβ a list of patterns; any trial completion matching one of the patterns will be excluded from consideration. The_ignoredcompleter can appear in the list of completers to restore the ignored matches. This is a more configurable version of the shell parameter$fignore. Fancy fignore, basically π
Note: theEXTENDED_GLOBoption is set during the execution of completion functions, so the characters#,~and^have special meanings in the patterns. Watch out for those, they're doing stuff π
insertβ this style is used by the_all_matchescompleter to decide whether to insert the list of all matches unconditionally instead of adding the list as another match. All in, or just another option β your call πinsert-idsβ when completing process IDs β for example as arguments to thekillandwaitbuiltins β the name of a command may be converted to the appropriate process ID. A problem arises when the process name typed is not unique π¬ By default (or if this style is set explicitly tomenu), the name will be converted immediately to a set of possible IDs, and menu completion will be started to cycle through them.
If the value of the style is single, the shell will wait until the user has typed enough to make the command unique before converting the name to an ID; attempts at completion will be unsuccessful until that point. If the value is any other string, menu completion will be started when the string typed by the user is longer than the common prefix to the corresponding IDs. Patience is a virtue, apparently π§ββοΈ
insert-sectionsβ this style is used with tags of the formmanuals.Xwhen completing names of manual pages. If set and theXin the tag name matches the section number of the page being completed, the section number is inserted along with the page name. For example, given:
zstyle ':completion:*:manuals.*' insert-sections true
man ssh_<TAB> may be completed to man 5 ssh_config. Section numbers going where they belong π₯
The value may also be set to one of prepend, or suffix. prepend behaves the same as true β as in the above example β while suffix would complete man ssh_<TAB> as man ssh_config.5. Front or back, pick your fighter β¨
This is especially useful in conjunction with separate-sections, as it ensures that the page requested of man corresponds to the one displayed in the completion listing when there are multiple pages with the same name (e.g., printf(1) and printf(3)). No more "wait, which printf did I mean" π
The default for this style is false.
insert-tabβ if this is set totrue, the completion system will insert a TAB character (assuming that was used to start completion) instead of performing completion when there is no non-blank character to the left of the cursor. If it's set tofalse, completion will be done even there. Sometimes you just want a literal tab, and honestly? Valid π
...the value can also have pending or pending=val hiding in it, and that's actually so useful π
β what it means is: when there's unprocessed input still pending, your typed character just gets inserted straight in instead of kicking off completion. And if you hand it a val, completion literally won't happen while there are at least that many characters of unprocessed input sitting there. Big one for pasting stuff into a terminal, fr fr. But β οΈ β lowkey a caveat: it depends on the $PENDING special parameter from the zsh/zle module being set properly, and that is not guaranteed on all platforms. So like... it's giving "works on my machine" energy, iykyk.
Default value of this style is true π β except for completion inside the vared builtin command, where it's false.
insert-unambiguousβ this one's used by the_matchand_approximatecompleters, and those two are usually hanging out with menu completion since the word you typed might bear basically zero resemblance to the final completion (no cap). But if this style istrue, the completer starts menu completion only if it couldn't find an unambiguous initial string at least as long as the original string you typed. Picky, but make it fashion β¨
For the _approximate completer, the completer field in the context will already be set to one of correct-num or approximate-num, where num is the number of errors that got accepted. π
For the _match completer, you can also set the style to the string pattern β then the pattern on the line is left untouched if it doesn't match unambiguously.
keep-prefixβ_expandcompleter's bestie. If it'strue, the completer tries to keep a prefix that contains a tilde or parameter expansion. Example so it clicks: the string~/f*expands to~/fooinstead of/home/user/foo. π If the style is set tochanged(that's the default, btw), the prefix is only left unchanged if there were other changes between the expanded words and the original word from the command line. Any other value forces the prefix to be expanded unconditionally β no vibes check, just do it.
When this style is true, _expand gives up when a single expansion with the restored prefix is the same as the original β which means any remaining completers get their moment. π
known-hosts-filesβ should contain a list of files to search for host names and (if theuse-ipstyle is set) IP addresses, in a format compatible with sshknown_hostsfiles. Not set? Then/etc/ssh/ssh_known_hostsand~/.ssh/known_hostsget used by default. π¦last-promptβ this is likeALWAYS_LAST_PROMPTbut β¨flexibleβ¨. Iftrue, the completion system tries to return the cursor to the previous command line after showing a completion list. It's tested for all tags valid for the current completion, then the default tag. Cursor moves back to the previous line if this style istruefor all types of match. Heads up though: unlike theALWAYS_LAST_PROMPToption, this is independent of the numeric argument. πlistβ used by the_history_complete_wordbindable command. Set it totrueand it does nothing at all (iconic laziness). Set it tofalseand matches won't be listed. This overrides the options controlling listing behaviour,AUTO_LISTespecially. The context always starts with:completion:history-words.list-colorsβ if thezsh/complistmodule is loaded, you can use this style to set color specifications. π¨ This mechanism replaces the use of theZLS_COLORSandZLS_COLOURSparameters described in the sectionThe zsh/complist Moduleinzshmodules(1)β but the syntax is the same, so no need to panic.
Set it for the default tag and the strings in the value get taken as specifications used everywhere. Set it for other tags and the specifications apply only to matches of the type that tag describes. For this to work best, the group-name style must be set to an empty string.
Besides setting styles for specific tags, you can also use group names specified explicitly by the group-name tag together with the (group) syntax allowed by the ZLS_COLORS and ZLS_COLOURS parameters, and just use the default tag. Slay, options within options. π
You can even reuse any color specifications already set up for the GNU version of the ls command:
zstyle ':completion:*:default' list-colors \
${(s.:.)LS_COLORS}
Default colors are the same as for GNU ls, and you get them by setting the style to an empty string (i.e. ''). β
list-dirs-firstβ used by file completion, and it corresponds to a particular setting of thefile-patternsstyle. If set, the default directories to be completed get listed separately from β and before β completion for other files. Order matters, bestie. πlist-groupedβ iftrue(which is the default), the completion system tries to make certain completion listings more compact by grouping matches. Example: options for commands that have the same description (shown whenverboseis set totrue) appear as a single entry. And don't worry β menu selection can still cycle through all the matches. π«Άlist-packedβ tested for each tag valid in the current context plus the default tag.truemeans the corresponding matches show up in listings as if theLIST_PACKEDoption were set.falsemeans they're listed normally. Simple as that.list-promptβ set it for the default tag and completion lists that don't fit on screen become scrollable (see the description of thezsh/complistmodule inzshmodules(1)). The value, if it's not the empty string, gets displayed after every screenful and the shell prompts you for a key press; if the style is the empty string, a default prompt is used.
The value can contain these escape sequences:
%lor%Lβ replaced by the number of the last line displayed and the total number of lines%mor%Mβ the number of the last match shown and the total number of matches%pand%PβTopwhen at the beginning of the list,Bottomwhen at the end, and the position shown as a percentage of the total length otherwise
In each case the uppercase form gets replaced by a string of fixed width, padded to the right with spaces, while the lowercase form is a variable-width string. And like in other prompt strings, you've also got %S, %s, %B, %b, %U, %u for entering and leaving the display modes standout, bold and underline, plus %F, %f, %K, %k for changing the foreground and background colour, and the %{...%} form for enclosing escape sequences that display with zero (or, with a numeric argument, some other) width. Prompt game: immaculate. π§
After deleting this prompt, the variable LISTPROMPT should be unset for the removal to take effect. Don't skip this step bestie, or the ghost of the prompt will haunt you π
list-rows-firstβ tested the same way aslist-packed, and it decides whether matches get listed rows-first, as if theLIST_ROWS_FIRSToption were set.list-separatorβ its value is used in completion listing to separate the string to complete from a description when possible (like when completing options). Defaults to--(two hyphens). πlist-suffixesβ used by the function that completes filenames. Iftrueand you attempt completion on a string containing multiple partially typed pathname components, all ambiguous components get shown. Otherwise, completion stops at the first ambiguous component. Like, it just gives up there πlocalβ for functions that complete URLs where the corresponding files are available directly from the file system. Its value should be three strings: a hostname, the path to the default web pages for the server, and the directory name used by a user placing web pages within their home area.
Example time:
zstyle ':completion:*' local toast \
/var/http/public/toast public_html
So completion after http://toast/stuff/ looks for files in the directory /var/http/public/toast/stuff, while completion after http://toast/~yousir/ looks for files in the directory ~yousir/public_html. πΈ
mail-directoryβ if set, zsh assumes mailbox files live in the directory you specify. Defaults to~/Mail. οΏ½οΏ½match-originalβ used by the_matchcompleter. Set it toonlyand_matchtries to generate matches without inserting a*at the cursor position. Set it to any other non-empty value and it first tries without the*, then β if that yields no matches β tries again with the*inserted. Unset or empty string? Then matching only happens with the*inserted. π₯matcherβ tested separately for each tag valid in the current context. Its value gets placed before any match specifications given by thematcher-liststyle, so it can override them via anx:specification. The value should be in the form described in the sectionCompletion Matching Controlinzshcompwid(1). For examples, see the description of thetag-orderstyle. (And for notes comparing this againstmatcher-list, look undertag-ordertoo π)matcher-listβ set this to a list of match specifications applied everywhere. Match specifications are described in the sectionCompletion Matching Controlinzshcompwid(1). The completion system tries them one after another for each completer selected. Example β try simple completion first and, if that generates no matches, case-insensitive completion:
zstyle ':completion:*' matcher-list '' 'm:{a-zA-Z}={A-Za-z}'
πβ¨
Okay bestie, so here's the next bit β we're still deep in style territory and it gets so good π
By default, every specification you give replaces the one before it. But if you slap a + on the front, it gets added to the existing list instead. Which means you can build increasingly general specifications without repeating yourself β iconic, honestly:
zstyle ':completion:*' matcher-list \
'' '+m:{a-z}={A-Z}' '+m:{A-Z}={a-z}'
It's also possible to create match specifications that are only valid for particular completers, by using the third field of the context. Watch out though β this only applies to completers that override the global matcher-list, which as of this writing includes only _prefix and _ignored. So like, for example, to use the completers _complete and _prefix but allow case-insensitive completion only with _complete:
zstyle ':completion:*' completer _complete _prefix
zstyle ':completion:*:complete:*:*:*' matcher-list \
'' 'm:{a-zA-Z}={A-Za-z}'
User-defined names (the ones we explained for the completer style) are available too β¨ This makes it possible to try the same completer more than once with different match specifications each time. Example: try normal completion without a match specification, then normal completion with case-insensitive matching, then correction, and finally partial-word completion:
zstyle ':completion:*' completer \
_complete _correct _complete:foo
zstyle ':completion:*:complete:*:*:*' matcher-list \
'' 'm:{a-zA-Z}={A-Za-z}'
zstyle ':completion:*:foo:*:*:*' matcher-list \
'm:{a-zA-Z}={A-Za-z} r:|[-_./]=* r:|=*'
If the style is unset in any context, no match specification is applied. Also note (lowkey important) that some completers, like _correct and _approximate, don't use the match specifications at all β though these completers will only ever be called once even if the matcher-list contains more than one element.
Where multiple specifications are useful, keep in mind that the entire completion is done for each element of matcher-list, which can quickly tank your shell's performance π Rough rule of thumb: one to three strings gives acceptable performance. On the flip side, putting multiple space-separated values into the same string doesn't have an appreciable impact on performance. Slay.
And one more thing: if there's no current matcher, or it's empty, and the option NO_CASE_GLOB is in effect, then the matching for files is performed case-insensitively in any case. But any matcher must explicitly specify case-insensitive matching if that's what you need.
For notes comparing the use of this and the matcher style, see under the description of the tag-order style π
max-errors
This one's used by the _approximate and _correct completer functions to figure out the maximum number of errors to allow. The completer tries to generate completions by first allowing one error, then two errors, and so on, until either a match (or matches!) were found or the maximum number of errors given by this style has been reached.
If the value for this style contains the string numeric, the completer function will take any numeric argument as the maximum number of errors allowed. For example, with:
zstyle ':completion:*:approximate:::' max-errors 2 numeric
...two errors are allowed if no numeric argument is given, but with a numeric argument of six (as in ESC-6 TAB), up to six errors are accepted. Hence with a value of 0 numeric, no correcting completion will be attempted unless a numeric argument is given.
If the value contains the string not-numeric, the completer won't try to generate corrected completions when given a numeric argument, so in this case the number given should be greater than zero. For example, 2 not-numeric specifies that correcting completion with two errors will usually be performed, but if a numeric argument is given, correcting completion will not be performed.
The default value for this style is 2 numeric. π
max-matches-width
This style decides the trade-off between the width of the display used for matches and the width used for their descriptions β specifically when the verbose style is in effect. The value gives the number of display columns to reserve for the matches. Default? Half the width of the screen.
This has the most impact when several matches share the same description and therefore get grouped together. Increase the style β more matches can be grouped together. Decrease it β more of the description stays visible. Balance, bestie π§
menu
If this is true in the context of any of the tags defined for the current completion, menu completion will be used. The value for a specific tag takes precedence over the one for the default tag.
If none of the values found this way is true but at least one is set to auto, the shell behaves as if the AUTO_MENU option is set.
If one of the values is explicitly set to false, menu completion is explicitly turned off, overriding the MENU_COMPLETE option and other settings π₯
In the form yes=num, where yes may be any of the true values (yes, true, on and 1), menu completion will be turned on if there are at least num matches. In the form yes=long, menu completion will be turned on if the list does not fit on the screen. This does not activate menu completion if the widget normally only lists completions β but menu completion can still be activated in that case with the value yes=long-list. (Typically the value select=long-list, described later, is more useful since it gives you control over scrolling.)
Similarly, with any of the false values (as in no=10), menu completion will not be used if there are num or more matches.
The value of this widget also controls menu selection, as implemented by the zsh/complist module. The following values may appear either alongside or instead of the values above.
If the value contains the string select, menu selection will be started unconditionally.
In the form select=num, menu selection will only be started if there are at least num matches. If the values for more than one tag provide a number, the smallest number is taken.
Menu selection can be turned off explicitly by defining a value containing the string no-select.
It's also possible to start menu selection only if the list of matches doesn't fit on the screen, using the value select=long. And to start menu selection even if the current widget only performs listing, use the value select=long-list.
To turn on menu completion or menu selection when there are a certain number of matches or the list of matches doesn't fit on the screen, both of yes= and select= may be given twice β once with a number and once with long or long-list β¨
Finally, you can activate two special modes of menu selection. The word interactive in the value causes interactive mode to be entered immediately when menu selection is started β see the description of the zsh/complist module in zshmodules(1) for what interactive mode actually does. Including the string search does the same for incremental search mode. And to select backward incremental search, include the string search-backward. π
muttrc
If set, this gives the location of the mutt configuration file. Defaults to ~/.muttrc π¦
numbers
This is used with the jobs tag. If it's true, the shell will complete job numbers instead of the shortest unambiguous prefix of the job command text. If the value is a number, job numbers will only be used if that many words from the job descriptions are required to resolve ambiguities. For example, if the value is 1, strings will only be used if all jobs differ in the first word on their command lines π
old-list
Used by the _oldlist completer. If it's set to always, then standard widgets which perform listing will retain the current list of matches, however they were generated β and this can be turned off explicitly with the value never, giving the behaviour you'd get without the _oldlist completer. If the style is unset, or set to any other value, then the existing list of completions is displayed if it's not already; otherwise, the standard completion list is generated. That's the default behaviour of _oldlist. But! If there's an old list and this style contains the name of the completer function that generated the list, then the old list will be used even if it was generated by a widget which doesn't do listing.
For example, suppose you type ^Xc to use the _correct_word widget, which generates a list of corrections for the word under the cursor. Usually, typing ^D would generate a standard list of completions for the word on the command line and show that. With _oldlist, it'll show the list of corrections already generated instead π
As another example, consider the _match completer: with the insert-unambiguous style set to true, it inserts only a common prefix string, if there is any. But this may remove parts of the original pattern, so that further completion could produce more matches than on the first attempt. By using the _oldlist completer and setting this style to _match, the list of matches generated on the first attempt will be used again. Chef's kiss π«Ά
old-matches
This one's used by the _all_matches completer to decide whether an old list of matches should be used if one exists. It's selected by one of the true values or by the string only. If the value is only, _all_matches will only use an old list and won't have any effect on the list of matches currently being generated.
If this style is set, it's generally unwise to call the_all_matchescompleter unconditionally. One possible use is for either this style or thecompleterstyle to be defined with the-eoption tozstyle, to make the style conditional. β
okay bestie, more styles incoming β these are the ones that control old lists, paths, packages, and display behavior, and yes, every detail is staying π
old-menuβ this one is used by the_oldlistcompleter. It decides how menu completion acts when a completion has already been inserted and you hit a standard completion key likeTAB. The default behavior of_oldlistis that menu completion always keeps going with the existing list of completions. But if this style is set tofalse, a new completion is started when the old list came from a different completion command β that's the behavior without the_oldlistcompleter.
For example, say you type ^Xc to generate a list of corrections, and menu completion starts in one of the usual ways. Normally, or with this style set to false, typing TAB at that point would start trying to complete the line as it now appears. With _oldlist, it instead keeps cycling through the list of corrections. slay π
originalβ used by the_approximateand_correctcompleters to decide whether the original string should be added as a possible completion. Normally this only happens if there are at least two possible corrections, but if this style is set totrue, it is always added. Note that the style is examined with thecompleterfield in the context name set tocorrect-numorapproximate-num, wherenumis the number of errors that were accepted.packagesetβ used when completing arguments of the Debiandpkgprogram. It contains an override for the default package set for a given context. For example:
zstyle ':completion:*:complete:dpkg:option--status-1:*' \
packageset avail
causes available packages, rather than only installed packages, to be completed for dpkg --status. periodt π
pathβ the function that completes color names uses this style with thecolorstag. The value should be the pathname of a file containing color names in the format of an X11rgb.txtfile. If the style is not set but this file is found in one of various standard locations, it will be used as the default.path-completionβ used by filename completion. By default, filename completion examines all components of a path to see if there are completions of that component. For example,/u/b/zcan be completed to/usr/bin/zsh. Explicitly setting this style tofalseinhibits this behavior for path components up to the/before the cursor; this overrides the setting ofaccept-exact-dirs.
Even with the style set to false, it is still possible to complete multiple paths by setting the option COMPLETE_IN_WORD and moving the cursor back to the first component in the path to be completed. For example, /u/b/z can be completed to /usr/bin/zsh if the cursor is after the /u. iykyk π¦
pine-directoryβ if set, specifies the directory containing PINE mailbox files. There is no default, since recursively searching this directory is inconvenient for anyone who doesn't use PINE. no cap, it's giving consideration πΈportsβ a list of Internet service names (network ports) to complete. If this is not set, service names are taken from the file/etc/services.prefix-hiddenβ used for certain completions which share a common prefix, for example command options beginning with dashes. If it istrue, the prefix will not be shown in the list of matches.
The default value for this style is false.
prefix-neededβ also relevant for matches with a common prefix. If it is set totrue, this common prefix must be typed by the user to generate the matches.
The style is applicable to the options, signals, jobs, functions, and parameters completion tags.
For command options, this means that the initial -, +, or -- must be typed explicitly before option names will be completed.
For signals, an initial - is required before signal names will be completed.
For jobs, an initial % is required before job names will be completed.
For function and parameter names, an initial _ or . is required before function or parameter names starting with those characters will be completed.
The default value for this style is false for function and parameter completions, and true otherwise. bestie, type the prefix or perish π₯
preserve-prefixβ used when completing path names. Its value should be a pattern matching an initial prefix of the word to complete that should be left unchanged under all circumstances. For example, on some Unices an initial//(double slash) has a special meaning; setting this style to the string//will preserve it. As another example, setting this style to?:/under Cygwin would allow completion aftera:/...and so on. iconic behavior honestly πrangeβ used by the_historycompleter and the_history_complete_wordbindable command to decide which words should be completed.
If it is a single number, only the last N words from the history will be completed.
If it is a range of the form max:slice, the last slice words will be completed; then if that yields no matches, the slice words before those will be tried and so on. This process stops either when at least one match has been found, or max words have been tried.
The default is to complete all words from the history at once.
recursive-filesβ if this style is set, its value is an array of patterns to be tested against$PWD/: note the trailing slash, which allows directories in the pattern to be delimited unambiguously by including slashes on both sides. If an ordinary file completion fails and the word on the command line does not yet have a directory part to its name, the style is retrieved using the same tag as for the completion just attempted, then the elements are tested against$PWD/in turn. If one matches, then the shell reattempts completion by prepending the word on the command line with each directory in the expansion of**/*(/)in turn. Typically the elements of the style will be set to restrict the number of directories beneath the current one to a manageable number, for example*/.git/*.
For example:
zstyle ':completion:*' recursive-files '*/zsh/*'
If the current directory is /home/pws/zsh/Src, then zle_tr<TAB> can be completed to Zle/zle_tricky.c. literally so satisfying π
regularβ used by the_expand_aliascompleter and bindable command. If set totrue(the default), regular aliases will be expanded but only in command position. If it is set tofalse, regular aliases will never be expanded. If it is set toalways, regular aliases will be expanded even if not in command position.rehashβ if this is set when completing external commands, the internal list (hash) of commands will be updated for each search by issuing therehashcommand. There is a speed penalty for this which is only likely to be noticeable when directories in the path have slow file access. ngl, convenience tax πremote-accessβ if set tofalse, certain commands will be prevented from making Internet connections to retrieve remote information. This includes the completion for the CVS command.
It is not always possible to know if connections are in fact to a remote site, so some may be prevented unnecessarily.
remove-all-dupsβ the_history_complete_wordbindable command and the_historycompleter use this to decide if all duplicate matches should be removed, rather than just consecutive duplicates.select-promptβ if this is set for thedefaulttag, its value will be displayed during menu selection (see themenustyle above) when the completion list does not fit on the screen as a whole. The same escapes as for thelist-promptstyle are understood, except that the numbers refer to the match or line the mark is on. A default prompt is used when the value is the empty string.select-scrollβ this style is tested for thedefaulttag and determines how a completion list is scrolled during a menu selection (see themenustyle above) when the completion list does not fit on the screen as a whole. If the value is0(zero), the list is scrolled by half-screenfuls; if it is a positive integer, the list is scrolled by the given number of lines; if it is a negative number, the list is scrolled by a screenful minus the absolute value of the given number of lines. The default is to scroll by single lines. scroll behavior but make it fashion πseparate-sectionsβ used with themanualstag when completing names of manual pages. If it istrue, entries for different sections are added separately using tag names of the formmanuals.X, whereXis the section number. When thegroup-namestyle is also in effect, pages from different sections will appear separately. This style is also used similarly with thewordsstyle when completing words for thedictcommand. It allows words from different dictionary databases to be added separately. See alsoinsert-sections.
The default for this style is false.
show-ambiguityβ if thezsh/complistmodule is loaded, this style can be used to highlight the first ambiguous character in completion lists. The value is either a color indication such as those supported by thelist-colorsstyle or, with a value oftrue, a default of underlining is selected. The highlighting is only applied if the completion display strings correspond to the actual matches.show-completerβ tested whenever a new completer is tried. If it istrue, the completion system outputs a progress message in the listing area showing what completer is being tried. The message will be overwritten by any output when completions are found and is removed after completion is finished. main character progress bar energy β¨single-ignoredβ this one's for the_ignoredcompleter, and it only kicks in when there's literally one match. If it'sshow, that lonely match gets displayed but not inserted (tease π ). If it'smenu, then both the single match and the original string you typed get added as matches, and menu completion starts up β so you can pick whichever one you want, easy peasy.sortβ lets you override the standard ordering of matches. Iconic.
If it's true or false, sorting is on or off respectively. You can also list the values that go with the -o option to compadd: match, nosort, numeric, reverse. And if it's not set for the context, the standard behaviour of the calling widget is used.
The style gets tested first against the full context including the tag, and if that doesn't produce a value, it's tested against the context without the tag.
Heads up though: in lots of cases where a calling widget explicitly picks a particular ordering instead of the default, a value of true is not honoured. An example where it is honoured? Command history, where the default of sorting matches chronologically can be overridden by setting the style to true. π«Ά
In the _expand completer, if it's set to true, the expansions generated will always be sorted. If it's set to menu, then expansions are only sorted when they're offered as single strings β not in the string containing all possible expansions.
special-dirsβ normally, the completion code will not produce the directory names.and..as possible completions. If this style istrue, it adds both.and..as possible completions; if it's.., only..gets added.
Check out this example β it sets special-dirs to .. when the current prefix is empty, is a single ., or consists only of a path beginning with ../. Otherwise the value is false.
zstyle -e ':completion:*' special-dirs \
'[[ $PREFIX = (../)#(|.|..) ]] && reply=(..)'
squeeze-slashesβ if set totrue, sequences of slashes in filename paths (like infoo//bar) get treated as a single slash. That's the usual behaviour of UNIX paths, bestie. But by default the file completion function behaves as if there were a*between the slashes. πstopβ if set totrue, the_history_complete_wordbindable command will stop once when reaching the beginning or end of the history. Invoking_history_complete_wordwill then wrap around to the opposite end of the history. If it's set tofalse(that's the default),_history_complete_wordwill loop immediately, like in a menu completion.strip-commentsβ if set totrue, this style causes non-essential comment text to be removed from completion matches. Currently it's only used when completing e-mail addresses, where it removes any display name from the addresses, cutting them down to plainuser@hostform. So clean β¨subst-globs-onlyβ used by the_expandcompleter. If it'strue, the expansion will only be used if it resulted from globbing. So like β if expansions resulted from the use of thesubstitutestyle described below, but those weren't further changed by globbing, the expansions get rejected. π«
The default for this style is false.
substituteβ this boolean style controls whether the_expandcompleter will first try to expand all substitutions in the string (stuff like$(...)and${...}).
The default is true.
suffixβ used by the_expandcompleter if the word starts with a tilde or contains a parameter expansion. If it'strue, the word will only be expanded if it doesn't have a suffix, i.e. if it's something like~fooor$foorather than~foo/or$foo/barβ unless that suffix itself contains characters eligible for expansion. The default for this style istrue.tag-orderβ okay this one is a whole situation. It gives you a mechanism for sorting how the tags available in a particular context will be used. Main character energy honestly π
The values for the style are sets of space-separated lists of tags. The tags in each value get tried at the same time; if no match is found, the next value is used. (See the file-patterns style for an exception to this behavior.)
For example:
zstyle ':completion:*:complete:-command-:*:*' tag-order \
'commands functions'
specifies that completion in command position first offers external commands and shell functions. Remaining tags get tried if no completions are found.
In addition to tag names, each string in the value may take one of the following forms:
- If any value consists of only a hyphen, then only the tags specified in the other values are generated. Normally all tags not explicitly selected are tried last if the specified tags fail to generate any matches. Which means β a single value consisting only of a single hyphen turns off completion. π
! tags...β a string starting with an exclamation mark specifies names of tags that are not to be used. The effect is the same as if all other possible tags for the context had been listed.tag:label ...β here, tag is one of the standard tags and label is an arbitrary name. Matches are generated as normal, but the name label is used in contexts instead of tag. This is not useful in words starting with!.
If the label starts with a hyphen, the tag is prepended to the label to form the name used for lookup. This can be used to make the completion system try a certain tag more than once, supplying different style settings for each attempt; see below for an example. π
tag:label:descriptionβ as before, but description will replace the%din the value of theformatstyle instead of the default description supplied by the completion function. Spaces in the description must be quoted with a backslash. A%dappearing in description is replaced with the description given by the completion function.
In any of the forms above the tag may be a pattern, or several patterns in the form {pat1,pat2...}. In this case all matching tags will be used, except for any given explicitly in the same string.
One use of these features is to try one tag more than once, setting other styles differently on each attempt, but still use all the other tags without having to repeat them all. For example, to make completion of function names in command position ignore all the completion functions starting with an underscore the first time completion is tried:
zstyle ':completion:*:*:-command-:*:*' tag-order \
'functions:-non-comp *' functions
zstyle ':completion:*:functions-non-comp' \
ignored-patterns '_*'
On the first attempt, all tags will be offered, but the functions tag will be replaced by functions-non-comp. The ignored-patterns style is set for this tag to exclude functions starting with an underscore. If there are no matches, the second value of the tag-order style is used, which completes functions using the default tag β this time presumably including all function names. Slay.
The matches for one tag can be split into different groups. For example:
zstyle ':completion:*' tag-order \
'options:-long:long\ options
options:-short:short\ options
options:-single-letter:single\ letter\ options'
zstyle ':completion:*:options-long' \
ignored-patterns '[-+](|-|[^-]*)'
zstyle ':completion:*:options-short' \
ignored-patterns '--*' '[-+]?'
zstyle ':completion:*:options-single-letter' \
ignored-patterns '???*'
With the group-names style set, options beginning with --, options beginning with a single - or + but containing multiple characters, and single-letter options will be displayed in separate groups with different descriptions. Obsessed with the organization ngl.
Another use of patterns is to try multiple match specifications one after another. The matcher-list style offers something similar, but it's tested very early in the completion system and hence can't be set for single commands nor for more specific contexts. Here's how to try normal completion without any match specification and, if that generates no matches, try again with case-insensitive matching, restricting the effect to arguments of the command foo:
zstyle ':completion:*:*:foo:*:*' tag-order '*' '*:-case'
zstyle ':completion:*-case' matcher 'm:{a-z}={A-Z}'
First, all the tags offered when completing after foo are tried using the normal tag name. If that generates no matches, the second value of tag-order is used, which tries all tags again β except that this time each has -case appended to its name for lookup of styles. Hence this time the value for the matcher style from the second call to zstyle in the example is used to make completion case-insensitive. Chef's kiss π₯
And you can use the -e option of the zstyle builtin command to specify conditions for the use of particular tags. Like:
zstyle -e '*:-command-:*' tag-order '
if [[ -n $PREFIX$SUFFIX ]]; then
reply=( )
else
reply=( - )
fi'
(still on the tag-order tea, bestie, we're not done yet π
) If we're sitting in command position, completion is only attempted when the string you've typed so far isn't empty. That check runs through the PREFIX special parameter β zshcompwid has the whole scoop on which parameters are special inside completion widgets. Set reply to an empty array and you get the default behaviour of trying all the tags at once; set it to an array holding just a single hyphen and that disables the use of all tags, which means it disables all completions. Periodt.
And if no tag-order style has been defined for a context, the strings (|*-)argument-* (|*-)option-* values and options β plus every tag the completion function offers β get used to give you a sensible default behaviour that makes arguments (whether they're normal command arguments or arguments of options) complete before option names for most commands. Slay.
urls π¦
This one works together with the urls tag, in the hands of functions that complete URLs.
- If the value consists of more than one string, or if the only string doesn't name a file or directory, then the strings are used as the URLs to complete.
- If the value contains only one string which is the name of a normal file, the URLs are taken from that file (where the URLs may be separated by white space or newlines).
- Finally, if the only string in the value names a directory, the directory hierarchy rooted at that directory gives the completions. The top level directory should be the file access method, such as
http,ftp,bookmarkand so on. In many cases the next level of directories will be a filename. The directory hierarchy can descend as deep as necessary.
For example:
zstyle ':completion:*' urls ~/.urls
mkdir -p ~/.urls/ftp/ftp.zsh.org/pub
allows completion of all the components of the URL ftp://ftp.zsh.org/pub after suitable commands such as netscape or lynx. Note, however, that access methods and files are completed separately, so if the hosts style is set, hosts can be completed without reference to the urls style.
See the description in the function _urls itself for more information (e.g. more $^fpath/_urls(N)). iykyk β¨
use-cache π
If this is set, the completion caching layer is activated for any completions which use it (via the _store_cache, _retrieve_cache, and _cache_invalid functions). The directory containing the cache files can be changed with the cache-path style.
use-compctl πΈ
If this style is set to a string not equal to false, 0, no, and off, the completion system may use any completion specifications defined with the compctl builtin command. If the style is unset, this is done only if the zsh/compctl module is loaded. The string may also contain the substring first to use completions defined with compctl -T, and the substring default to use the completion defined with compctl -D.
Note that this is only intended to smooth the transition from compctl to the new completion system and may disappear in the future. π
Note also that the definitions from compctl will only be used if there is no specific completion function for the command in question. For example, if there is a function _foo to complete arguments to the command foo, compctl will never be invoked for foo. However, the compctl version will be tried if foo only uses default completion.
use-ip π«Ά
By default, the function _hosts that completes host names strips IP addresses from entries read from host databases such as NIS and ssh files. If this style is true, the corresponding IP addresses can be completed as well. This style is not use in any context where the hosts style is set; note also it must be set before the cache of host names is generated (typically the first completion attempt).
users π
This may be set to a list of usernames to be completed. If it is not set all usernames will be completed. Note that if it is set only that list of users will be completed; this is because on some systems querying all users can take a prohibitive amount of time.
users-hosts π₯
The values of this style should be of the form user@host or user:host. It is used for commands that need pairs of user- and hostnames. These commands will complete usernames from this style (only), and will restrict subsequent hostname completion to hosts paired with that user in one of the values of the style.
It is possible to group values for sets of commands which allow a remote login, such as rlogin and ssh, by using the my-accounts tag. Similarly, values for sets of commands which usually refer to the accounts of other people, such as talk and finger, can be grouped by using the other-accounts tag. More ambivalent commands may use the accounts tag.
users-hosts-ports π
Like users-hosts but used for commands like telnet and containing strings of the form user@host:port.
verbose β
If set, as it is by default, the completion listing is more verbose. In particular many commands show descriptions for options if this style is true.
word π
This is used by the _list completer, which prevents the insertion of completions until a second completion attempt when the line has not changed. The normal way of finding out if the line has changed is to compare its entire contents between the two occasions. If this style is true, the comparison is instead performed only on the current word. Hence if completion is performed on another word with the same contents, completion will not be delayed.
π CONTROL FUNCTIONS π
The initialization script compinit redefines all the widgets which perform completion to call the supplied widget function _main_complete. This function acts as a wrapper calling the so-called completer functions that generate matches. If _main_complete is called with arguments, these are taken as the names of completer functions to be called in the order given. If no arguments are given, the set of functions to try is taken from the completer style. For example, to use normal completion and correction if that doesn't generate any matches:
zstyle ':completion:*' completer _complete _correct
after calling compinit. The default value for this style is _complete _ignored, i.e. normally only ordinary completion is tried, first with the effect of the ignored-patterns style and then without it. The _main_complete function uses the return status of the completer functions to decide if other completers should be called. If the return status is zero, no other completers are tried and the _main_complete function returns.
If the first argument to _main_complete is a single hyphen, the arguments will not be taken as names of completers. Instead, the second argument gives a name to use in the completer field of the context and the other arguments give a command name and arguments to call to generate the matches.
The following completer functions are contained in the distribution, although users may write their own. Note that in contexts the leading underscore is stripped, for example basic completion is performed in the context :completion::complete:....
_all_matches π
This completer can be used to add a string consisting of all other matches. As it influences later completers it must appear as the first completer in the list. The list of all matches is affected by the avoid-completer and old-matches styles described above.
It may be useful to use the _generic function described below to bind _all_matches to its own keystroke, for example:
zle -C all-matches complete-word _generic
bindkey '^Xa' all-matches
zstyle ':completion:all-matches:*' old-matches only
zstyle ':completion:all-matches::::' completer _all_matches
Note that this does not generate completions by itself: first use any of the standard ways of generating a list of completions, then use ^Xa to show all matches. It is possible instead to add a standard completer to the list and request that the list of all matches should be directly inserted:
zstyle ':completion:all-matches::::' completer \
_all_matches _complete
zstyle ':completion:all-matches:*' insert true
In this case the old-matches style should not be set.
_approximate π
This is similar to the basic _complete completer but allows the completions to undergo corrections. The maximum number of errors can be specified by the max-errors style; see the description of approximate matching in zshexpn(1) for how errors are counted. Normally this completer will only be tried after the normal _complete completer:
zstyle ':completion:*' completer _complete _approximate
This will give correcting completion if and only if normal completion yields no possible completions. When corrected completions are found, the completer will normally start menu completion allowing you to cycle through these strings.
This completer uses the tags corrections and original when generating the possible corrections and the original string. The format style for the former may contain the additional sequences %e and %o which will be replaced by the number of errors accepted to generate the corrections and the original string, respectively.
The completer progressively increases the number of errors allowed up to the limit by the max-errors style, hence if a completion is found with one error, no completions with two errors will be shown, and so on. It modifies the completer name in the context to indicate the number of errors being tried: on the first try the completer field contains approximate-1, on the second try approximate-2, and so on.
When _approximate is called from another function, the number of errors to accept may be passed with the -a option. The argument is in the same format as the max-errors style, all in one string.
Like, quick heads-up before we go: this completer (and _correct, which we're getting to) is kind of expensive to call, especially if you're letting a whole bunch of errors slide. πΈ One way to dodge that is to set up the completer style using the -e option to zstyle so some completers only kick in when completion gets attempted a second time on the same string, like:
zstyle -e ':completion:*' completer '
if [[ $_last_try != "$HISTNO$BUFFER$CURSOR" ]]; then
_last_try="$HISTNO$BUFFER$CURSOR"
reply=(_complete _match _prefix)
else
reply=(_ignored _correct _approximate)
fi'
The way this works is it uses the HISTNO parameter plus the BUFFER and CURSOR special parameters that exist inside zle and completion widgets to figure out whether the command line has actually changed since the last time you tried to complete. Only when it hasn't changed do _ignored, _correct and _approximate get called. slay π
β¨ _canonical_paths β¨
_canonical_paths [ -A var ] [ -N ] [ -MJV12nfX ] tag descr [ paths ... ]
This one completes every path you hand it, and also tries to offer you completions that point at the same file as one of the paths you gave β like, a relative path when you gave an absolute one, and vice versa; when there are ..'s hanging out in the word being completed; and some paths it got from symlinks. π¦
-Aβ if you specify it, it takes the paths from the array variable you named. Paths can also just be given on the command line like shown above, ngl.-Nβ if specified, stops the paths you gave from being canonicalized before being used for completion, in case they're already canonical. π-M,-J,-V,-1,-2,-n,-F,-Xβ all of these get passed straight through tocompadd.
See _description for the whole deal on tag and descr.
π«Ά _cmdambivalent π«Ά
Completes the remaining positional arguments as an external command. The external command and its arguments get completed as separate arguments (in a manner appropriate for completing /usr/bin/env) if there are two or more remaining positional arguments on the command line, and as a quoted command string (in the manner of system(...)) otherwise. See also _cmdstring and _precommand.
This function takes no arguments. fr fr, none. β¨
π _cmdstring π
Completes an external command as a single argument, as for system(...).
π _complete π
This completer generates all possible completions in a context-sensitive manner, i.e. using the settings defined with the compdef function explained above and the current settings of all special parameters. This is the one giving you the normal completion behaviour β the main character of the completer lineup. π
To complete arguments of commands, _complete uses the utility function _normal, which is in turn responsible for finding the particular function; it's described below. Various contexts of the form -context- are handled specifically. These are all mentioned above as possible arguments to the #compdef tag.
Before trying to find a function for a specific context, _complete checks if the parameter compcontext is set. Setting compcontext lets you override the usual completion dispatching, which is genuinely useful in places like a function that uses vared for input. So:
- If it's set to an array, the elements are taken to be the possible matches, which get completed using the tag
valuesand the descriptionvalue. - If it's set to an associative array, the keys are used as the possible completions and the values (if non-empty) are used as descriptions for the matches.
- If
compcontextis set to a string containing colons, it should be of the formtag:descr:action. In this case the tag and descr give the tag and description to use, and the action indicates what should be completed, in one of the forms accepted by the_argumentsutility function described below. - Finally, if
compcontextis set to a string without colons, the value is taken as the name of the context to use and the function defined for that context will be called. For this purpose there's a special context named-command-line-that completes whole command lines (commands and their arguments). This isn't used by the completion system itself but is nonetheless handled when explicitly called. π
π
_correct π
Generates corrections, but not completions, for the current word. It's similar to _approximate but it won't allow any number of extra characters at the cursor the way that completer does. The effect is like spell-checking, lowkey. It's based on _approximate, but the completer field in the context name is correct.
For example, with:
zstyle ':completion:::::' completer \
_complete _correct _approximate
zstyle ':completion:*:correct:::' max-errors 2 not-numeric
zstyle ':completion:*:approximate:::' max-errors 3 numeric
correction will accept up to two errors. If a numeric argument is given, correction will not be performed, but correcting completion will be, and it'll accept as many errors as the numeric argument says. Without a numeric argument, first correction and then correcting completion get tried, with the first one accepting two errors and the second one accepting three errors. π
When _correct is called as a function, the number of errors to accept may be given following the -a option. The argument is in the same form as values to the accept style, all in one string.
This completer function is meant to be used without the_approximatecompleter or, as in the example, just before it. Using it after_approximateis useless since_approximatewill at least generate the corrected strings generated by_correctβ and probably more. π
πΈ _expand πΈ
Okay so this completer function doesn't really perform completion, bestie. Instead it checks if the word on the command line is eligible for expansion and, if it is, gives you detailed control over how that expansion is done. For this to happen, the completion system needs to be invoked with complete-word, not expand-or-complete (the default binding for TAB), because otherwise the string gets expanded by the shell's internal mechanism before the completion system even starts. Also note this completer should be called before the _complete completer function. β
The tags used when generating expansions are all-expansions for the string containing all possible expansions, expansions when adding the possible expansions as single matches, and original when adding the original string from the line. The order these strings get generated in, if at all, can be controlled by the group-order and tag-order styles, as usual.
The format string for all-expansions and for expansions may contain the sequence %o, which gets replaced by the original string from the line. π¦
The kind of expansion to try is controlled by the substitute, glob and subst-globs-only styles.
It's also possible to call _expand as a function, in which case the different modes may be selected with options:
-sβ for substitute-gβ for glob-oβ for subst-globs-only
π§ _expand_alias π§
If the word the cursor is on is an alias, it gets expanded and no other completers are called. The types of aliases to be expanded can be controlled with the regular, global and disabled styles.
This function is also a bindable command, see the section Bindable Commands below. π
π _extensions π
If the cursor follows the string *., filename extensions get completed. The extensions are taken from files in the current directory or a directory specified at the beginning of the current word. For exact matches, completion continues to allow other completers such as _expand to expand the pattern. The standard add-space and prefix-hidden styles are observed. π
π _external_pwds π
Completes current directories of other zsh processes belonging to the current user.
This is intended to be used via _generic, bound to a custom key combination. Note that pattern matching is enabled, so matching is performed similar to how it works with the _match completer. β¨
π _history π
Completes words from the shell's command history. This completer can be controlled by the remove-all-dups and sort styles as for the _history_complete_word bindable command β see the section Bindable Commands below and the section Completion System Configuration above. π¦
π _ignored π
The ignored-patterns style can be set to a list of patterns which get compared against possible completions; matching ones are removed. With this completer those matches can be reinstated, as if no ignored-patterns style were set. The completer actually generates its own list of matches; which completers get invoked is determined in the same way as for the _prefix completer. The single-ignored style is also available as described above. π
β _list β
This completer lets you delay the insertion of matches until completion is attempted a second time without the word on the line being changed. On the first attempt, only the list of matches will be shown. It's affected by the condition and word styles β see the section Completion System Configuration above. π
π₯ _match π₯
This completer is intended to be used after the _complete completer. It behaves similarly, but the string on the command line may be a pattern to match against trial completions. This gives you the effect of the GLOB_COMPLETE option. π
Normally completion is performed by taking the pattern from the line, inserting a * at the cursor position and comparing the resulting pattern with the possible completions generated. This can be modified with the match-original style described above.
The generated matches will be offered in a menu completion unless the insert-unambiguous style is set to true; see the description above for other options for this style. π
Not me dropping this here but like β heads up bestie: matcher specs you define globally, or the ones the completion functions use (the styles matcher-list and matcher), will not be used here. π
Like, they simply do not get an invite to this party.
_menuβ okay so this completer is literally just a lil demo function someone wrote to show how you can turn on menu completion from shell code β¨. But it has one iconic side effect: it disables menu selection, which is genuinely useful when you're working with_genericbased widgets. Put it as the first completer in the list, bestie. And ngl, this is independent of whatever theMENU_COMPLETEoption is set to β and it does not work with the other menu completion widgets such asreverse-menu-complete, oraccept-and-menu-complete. Not compatible, no cap π«Ά._oldlistβ this one is the vibe manager for how the standard completion widgets behave when there's already a list of completions hanging around, possibly generated by a special completion (i.e. a separately-bound completion command) π. What it does: it lets the ordinary completion keys keep using that already-generated list instead of cooking up a brand new list of ordinary contextual completions. Put it in the list of completers before any of the widgets which generate matches, okay? It works with two styles:old-listandold-menuβ peep the sectionCompletion System Configurationabove π₯._precommandβ completes an external command in word-separated arguments, exactly like forexecand/usr/bin/envπ. Short and sweet, we love her._prefixβ this completer tries completion with the suffix (everything after the cursor) ignored π¦. Like, the suffix is not considered part of the word to complete at all. The effect is similar to theexpand-or-complete-prefixcommand. Obsessed.
The completer style decides which other completers get called to generate matches. If that style is unset, the list of completers set for the current context is used β except, of course, the _prefix completer itself π. And also: if this completer shows up more than once in the list of completers, only those completers not already tried by the last invocation of _prefix will be called. She remembers. She keeps receipts.
For example, consider this global completer style:
zstyle ':completion:*' completer \
_complete _prefix _correct _prefix:foo
So here, the _prefix completer tries normal completion but ignoring the suffix. If that doesn't generate any matches, and neither does the call to the _correct completer after it, _prefix gets called a second time and, now, only tries correction with the suffix ignored β¨. On the second invocation the completer part of the context appears as foo β iykyk.
To use _prefix as the last resort and try only normal completion when it's invoked:
zstyle ':completion:*' completer _complete ... _prefix
zstyle ':completion::prefix:*' completer _complete
The add-space style is also respected, bestie. If it's set to true then _prefix will insert a space between the matches generated (if any) and the suffix π.
Ngl there's a catch: this completer is only useful if the COMPLETE_IN_WORD option is set. Otherwise the cursor gets moved to the end of the current word before the completion code is even called, and hence there will be no suffix π. Like... nothing to ignore. Sad.
_user_expandβ behaves similarly to the_expandcompleter but instead performs expansions defined by users πΈ. The stylesadd-spaceandsortthat are specific to the_expandcompleter are usable with_user_expandtoo, on top of the other styles handled more generally by the completion system. The tagall-expansionsis also available π.
The expansion depends on the array style user-expand being defined for the current context. Remember that the context for completers is less specific than the context for contextual completion, since the full context has not yet been determined π. Elements of the array may have one of the following forms:
$hash
hash is the name of an associative array. And note β this is not a full parameter expression, merely a $, suitably quoted to prevent immediate expansion, followed by the name of an associative array. If the trial expansion word matches a key in hash, the resulting expansion is the corresponding value π.
_func
_func is the name of a shell function whose name must begin with _ but is not otherwise special to the completion system. The function is called with the trial word as an argument. If the word is to be expanded, the function should set the array reply to a list of expansions π«. Optionally, it can set REPLY to a word that will be used as a description for the set of expansions. The return status of the function is irrelevant β we don't care, live your truth π.
π BINDABLE COMMANDS π
okay so bestie, here's the tea: besides all the context-dependent completions you already get (the ones that just intuitively do the right thing, no notes), there are a handful of widgets that implement special behaviour, and you can bind those to keys separately. here's the list of them plus their default bindings π
_bash_completionsβ so this function is used by two widgets,_bash_complete-wordand_bash_list-choices, and it exists purely to give you compatibility with the completion bindings from bash. the last character of the binding is what decides what gets completed:!means command names;$means environment variables;@means host names;/means file names; and~means user names. in bash, the binding preceded by\egives you completion, and preceded by^Xlists the options. but here's the thing β some of these bindings clash with standard zsh bindings, so only\e~and^X~are bound by default. to add the rest, drop this into.zshrcaftercompinithas been run:
for key in '!' '$' '@' '/' '~'; do
bindkey "\e$key" _bash_complete-word
bindkey "^X$key" _bash_list-choices
done
this includes the bindings for ~ just in case they were already bound to something else β because the completion code does not override user bindings, periodt π
_correct_filename(^XC) β corrects the filename path at the cursor position. allows up to six errors in the name π iconic leniency. you can also call it with an argument to correct a filename path independently of zle, and the correction gets printed on standard output._correct_word(^Xc) β performs correction of the current argument, using the usual contextual completions as the possible choices. this stores the stringcorrect-wordin the function field of the context name and then calls the_correctcompleter._expand_alias(^Xa) β this one can be used both as a completer and as a bindable command. it expands the word the cursor is on, but only if it's an alias. the types of alias expanded can be controlled with the stylesregular,globalanddisabled. when used as a bindable command there's one additional feature you can select by setting thecompletestyle totrue: in that case, if the word is not the name of an alias,_expand_aliastries to complete the word to a full alias name without expanding it. it leaves the cursor directly after the completed word so that invoking_expand_aliasonce more will expand the now-complete alias name π¦_expand_word(^Xe) β performs expansion on the current word: same energy as the standardexpand-wordcommand, but using the_expandcompleter. before calling it, the function field of the context is set toexpand-word._genericβ not defined as a widget and not bound by default. however, you can use it to define a widget, and it will then store the name of the widget in the function field of the context and call the completion system. this lets you define custom completion widgets with their own set of style settings, easily. for example, to define a widget that performs normal completion and starts menu selection:
zle -C foo complete-word _generic
bindkey '...' foo
zstyle ':completion:foo:*' menu yes select=1
note in particular that the completer style may be set for the context in order to change the set of functions used to generate possible matches. and if _generic is called with arguments, those are passed through to _main_complete as the list of completers in place of those defined by the completer style π
_history_complete_word(\e/) β completes words from the shell's command history. this uses thelist,remove-all-dups,sort, andstopstyles._most_recent_file(^Xm) β completes the name of the most recently modified file matching the pattern on the command line (which may be blank). if given a numeric argument N, it completes the *N*th most recently modified file. note that the completion, if any, is always unique._next_tags(^Xn) β this command alters the set of matches used to that for the next tag, or set of tags, either as given by thetag-orderstyle or as set by default; those matches would otherwise not be available. successive invocations of the command cycle through all the possible sets of tags π_read_comp(^X^R) β prompts you for a string, and uses that to perform completion on the current word. there are two possibilities for the string. first, it can be a set of words beginning_, for example_files -/, in which case the function with any arguments will be called to generate the completions. unambiguous parts of the function name will be completed automatically (normal completion is not available at this point) until a space is typed. second, any other string will be passed as a set of arguments tocompaddand should hence be an expression specifying what should be completed. a very restricted set of editing commands is available when reading the string:DELand^Hdelete the last character;^Udeletes the line, and^Cand^Gabort the function, whileRETaccepts the completion. note the string is used verbatim as a command line, so arguments must be quoted in accordance with standard shell rules π once a string has been read, the next call to_read_compwill use the existing string instead of reading a new one. to force a new string to be read, call_read_compwith a numeric argument._complete_debug(^X?) β this widget performs ordinary completion, but captures a trace of the shell commands executed by the completion system in a temporary file. each completion attempt gets its own file. a command to view each of these files is pushed onto the editor buffer stack π«Ά_complete_help(^Xh) β this widget displays information about the context names, the tags, and the completion functions used when completing at the current cursor position. if given a numeric argument other than 1 (as inESC-2 ^Xh), then the styles used and the contexts for which they are used will be shown, too. note that the information about styles may be incomplete; it depends on the information available from the completion functions called, which in turn is determined by your own styles and other settings._complete_help_genericβ unlike the other commands listed here, this one must be created as a normal ZLE widget rather than a completion widget (i.e. withzle -N). it's used for generating help with a widget bound to the_genericwidget described above. if this widget is created using the name of the function, as it is by default, then when executed it will read a key sequence. this is expected to be bound to a call to a completion function that uses the_genericwidget. that widget will be executed, and information provided in the same format that the_complete_helpwidget displays for contextual completion. if the widget's name containsdebug, for example if it is created aszle -N _complete_debug_generic _complete_help_generic, it will read and execute the keystring for a generic widget as before, but then generate debugging information as done by_complete_debugfor contextual completion. if the widget's name containsnoread, it will not read a keystring but instead arrange that the next use of a generic widget run in the same shell will have the effect as described above. the widget works by setting the shell parameterZSH_TRACE_GENERIC_WIDGETwhich is read by_generic. unsetting the parameter cancels any pending effect of thenoreadform. for example, after executing the following:
zle -N _complete_debug_generic _complete_help_generic
bindkey '^x:' _complete_debug_generic
typing C-x : followed by the key sequence for a generic widget will cause trace output for that widget to be saved to a file β¨
_complete_tag(^Xt) β this widget completes symbol tags created by theetagsorctagsprogrammes (note there's no connection with the completion system's tags) stored in a fileTAGS, in the format used byetags, ortags, in the format created byctags. it will look back up the path hierarchy for the first occurrence of either file; if both exist, the fileTAGSis preferred. you can specify the full path to aTAGSortagsfile by setting the parameter$TAGSFILEor$tagsfilerespectively. the corresponding completion tags used areetagsandvtags, after emacs and vi respectively π§
πΈ UTILITY FUNCTIONS πΈ
descriptions follow for utility functions that may be useful when you're 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_labelfunction below, implementing the loop shown in the_next_labelexample. 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're put directly after the command, but if one of the args is a single hyphen, they're 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_labelsto be used in almost all cases where the matches can be generated by a single call to thecompaddbuiltin command or by a call to one of the utility functions. for example:
β¦and the example just keeps rolling, like:
local expl
...
if _requested foo; then
...
_all_labels foo expl '...' compadd ... - $matches
fi
That last bit? It completes the strings from the matches parameter, using compadd with extra options that will take precedence over whatever _all_labels generated on its own. So your vibes override the default vibes, basically. π
π¦ _alternative π¦
_alternative [ -O name ] [ -C name ] spec ...
This one is your bestie for the simple cases where you've got multiple tags sitting around. Fr fr, it basically implements a loop just like the one described for the _tags function further down. π
So the tags you want to use, plus what to do when one of them gets requested, are described using the specs, which look like this:
`tag:descr:action'
The tags get offered up via _tags, and if a tag is actually requested, the action runs, with the given description descr. The actions are exactly those accepted by the _arguments function (yes, that one, it's coming right up), with these two exceptions, so pay attention bestie:
- The
->stateand=...forms are not supported. Not a vibe. π - The
((a\:bar b\:baz))form doesn't need the colon to be escaped, because these specs have no colon-separated fields after the action. Slay, less escaping.
So like, for example, the action can just be a simple function call:
_alternative \
'users:user:_users' \
'hosts:host:_hosts'
and boom, that offers usernames and hostnames as possible matches, generated by the _users and _hosts functions respectively. Iconic behaviour. β¨
Just like _arguments, this function uses _all_labels to execute the actions, which will loop over all sets of tags. You only need special handling if there's an additional valid tag β for example inside a function that's called from _alternative, iykyk.
The -O name option does the same thing here as it does in the _arguments function. In other words: the elements of the name array get passed to compadd when an action is executed. π«Ά
And like _tags, this function supports the -C option, which gives a different name for the argument context field.
π
_arguments π
_arguments [ -nswWCRS ] [ -A pat ] [ -O name ] [ -M matchspec ]
[ : ] spec ...
_arguments [ opt ... ] -- [ -l ] [ -i pats ] [ -s pair ]
[ helpspec ...]
Okay so this is the big one. This function gives you a complete specification for completion of a command whose arguments follow standard UNIX option and argument conventions. It's giving main character energy of the completion system, honestly. π
β Options Overview β
Options to _arguments itself must be in separate words β that means -s -w, not -sw. Write that down. π The options are then followed by specs that describe the options and arguments of the command being analyzed. To avoid any 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 it's 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. Yes, both. At the same time. Stay with me. π
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. Very handy, no cap.
The options of _arguments have the following meanings:
-nβ With this option,_argumentssets the parameterNORMARGto the position of the first normal argument in the$wordsarray, i.e. the position after the end of the options. If that argument has not been reached,NORMARGis set to-1. The caller should declareinteger NORMARGif the-noption 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-xand-ymay be combined into a single word-xy. By default, every word corresponds to a single option name (-xyis a single option namedxy). Options beginning with a single hyphen or plus sign are eligible for stacking; words beginning with two hyphens are not. π₯
Heads up:-safter--has a different meaning, documented down in the segment titledDeriving 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-xtakes an argument: with no-s,-xyis considered as a single (unhandled) option; with-s,-xyis an option with the argumenty; with both-sand-w,-xyis the option-xand the option-y, with arguments to-x(and to-y, if it takes arguments) still to come in subsequent words. β¨-Wβ This option takes-wa stage further: it's 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_guardas part of the action. π₯-Cβ Modify thecurcontextparameter for an action of the form->state. This is discussed in detail below.-Rβ Return status300instead of zero when a$stateis to be handled, in the->stringsyntax.-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. Neither! It's just vibing there. π
-Apat β 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_argumentsstop completing options after the first normal argument, but ignoring all strings starting with a hyphen even if they're not described by one of the optspecs, the form is-A "-*". π-Oname β Pass the elements of the array name as arguments to functions called to execute actions. This is discussed in detail below.-Mmatchspec β Use the match specification matchspec for completing option names and values. The default matchspec allows partial word completion after_and-, such as completing-f-bto-foo-bar. The default matchspec is:
r:|[_-]=* r:|=*
-0β When populating values of theopt_argsassociative array, don't backslash-escape colons and backslashes, and useNULrather 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. Let's go through them one by one, bestie:
n:message:actionn::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. And 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. And if all arguments are specified in this form in the correct order, the numbers are unnecessary. Convenient much? π
*: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're modified to refer only to the normal arguments covered by this description. Three colons! It's giving escalating commitment. π
optspecoptspec:...
This describes an option. The colon indicates handling for one or more arguments to the option; if it's 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-+optnameand+-optnamecan be used to specify that-optnameand+optnameare both valid. And in all the remaining forms, the leading-may be replaced by or paired with+in this way. β
-optname-β the first argument of the option has to come directly after the option name in the same word. So-foo-:...means the completed option + argument will literally look like-fooarg. No space, no gap, bestie.-optname+β the first argument can appear immediately after optname in the same word, or it can show up as a separate word after the option. Example:-foo+:...means the completed thing looks like either-fooargor-foo arg. Flexible icon behavior.-optname=β the argument can appear as the next word, or in the same word as the option name as long as thereβs an equals sign separating them. Example:-foo=argor-foo arg. Slay.-optname=-β the argument to the option must appear after an equals sign in the same word, and it may not be given in the next argument. Thatβs the rule, no cap.optspec[explanation]β you can append an explanation string to any of the preceding forms of optspec by wrapping it in brackets, like-q[query operation].
The verbose style is what decides whether explanation strings get displayed with the option in a completion listing.
If thereβs no bracketed explanation string, but the auto-description style is set and only one argument is described for this optspec, then the value of the style gets 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βs possible for options with a literal + or = to appear, but that character must be quoted, for example -\+. Do not forget the quote, bestie, itβs giving necessary.
Each optarg following an optspec must take one of these forms:
:message:action/::message:actionβ an argument to the option;messageandactionare treated as for ordinary arguments. In the first form, the argument is mandatory; in the second form, itβs optional.
This group may be repeated for options that take multiple arguments. In other words, :message1:action1:message2:action2 specifies that the option takes two arguments. Two-for-one vibes.
:*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 theaction; otherwise, all the words up to and including a word matching the pattern are to be completed using theaction.
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. Colon math, but make it fashion. π
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. And (-foo):... specifies an ordinary argument completion; -foo will not be completed if that argument is already present. Exclusion list ate.
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; - 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βs 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. Reuse era. β¨
π¬ 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. Lowkey elegant.
The forms for action are as follows:
- A 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. Tiny space, big job.
(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. Cute and informative.
->stringβ in this form,_argumentsprocesses 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. Main character energy.
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. Protect your globals, bestie. π‘οΈ
{eval-string}β a string in braces is evaluated as shell code to generate matches. This is similar to theword ...action described below, but isnβt limited to a single command. Braces = little code pocket.= actionβ if theactionstarts with=(an equals sign followed by a space),_argumentswill insert the contents of theargumentfield of the current context as the new first element in thewordsspecial array and increment the value of theCURRENTspecial 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. Sneaky little dummy-word moment, but make it legit. πword ...(like, the whole "just words" situation, both flavours) β this covers all forms other than the ones above π . If the action starts with a space, the remaining list of words gets invoked unchanged, no notes. Otherwise it's invoked with some extra strings dropped in after the first word β those get passed down as options to thecompaddbuiltin. They're the ones that make sure the state_argumentsset up (specifically the descriptions of options and arguments, bestie) is correctly passed to the completion command. These additional arguments are taken from the array parameterexpl; it gets set up before the action runs, so you can refer to it inside the action, typically in an expansion shaped like$expl[@]β which, iconic detail, 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 β that's 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 (like, for example, when you're using an optspec of the form *optspec), they get joined with (unescaped) colons. But if the -0 option was passed, no backslash escaping happens and multiple values are joined with NUL bytes instead. So 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's 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 nth argument of the option -opt, or a string of the form argument-n for the nth argument. For rest arguments β that's the ones in the list at the end that aren't handled by position β n is the string rest. So, 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's argument-2.
Furthermore, during the evaluation of the action, the context name in the curcontext parameter is altered to append the same string that's stored in the context parameter. Slay, the context is contexting π₯.
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, okurr) 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's just 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 super 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's 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.
Heads up bestie: the completion code has to parse the command line separately for each set. That 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-fooswallows 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, because 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's also possible to provide hints by examining the help text of the command and adding a 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 do 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 don't need to be given explicitly, although it is possible to override the use of these patterns. A typical help text that 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, iykyk π§).
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 π
.
Okay so, continuing our little journey through _arguments...
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 (read these, bestie, they matter)
Finally β and this is the big one β 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's 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. Let me break it down for you:
- The first takes one argument described as
left borderfor which no completion will be offered because of the empty action. Its argument may come directly after the-lor it may be given as the next word on the line. - The
-formatoption takes one argument in the next word, described aspaper size, for which only the stringsletterandA4will be completed. - The
-copyoption 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 descriptionresolution) and will be completed from the strings300and600.
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. That style 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 which 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 the 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.
π still here, still slaying β more functions coming right up, don't you dare scroll away
-t lets you specify a tag. Default is values β or options if you passed -o. Slay.
The options -1, -2, -J, -V, -x get passed straight through to _next_label. Chain of command, love that for them.
If the list-grouped style picks it up, strings with the same description show up together in the list. Grouped. Iconic.
Also bestie β _describe uses the _all_labels function to generate the matches, so you do not need to wrap it in a loop over tag labels. It handles that itself. No cap.
β¨ _description β¨
_description [ -x ] [ -12VJ ] tag name descr [ spec ... ]
Okay so do not confuse this with the previous one, fr fr. This is a helper function for building options that get handed to compadd. It's buried inside sooo many of the higher-level completion functions that you'll usually never need to call it yourself. It's giving backstage crew.
Here's the vibe: the styles listed below get tested in the current context using the tag you give it. The resulting compadd options get stuffed into the array named name (traditionally expl, but that's just a convention β nobody's enforcing it π
). The description for the matching set of matches goes in via descr.
The styles it tests are: format, hidden, matcher, ignore-line, ignored-patterns, group-name and sort. The format style gets tested first for the tag you gave, and then for the descriptions tag if nothing turned up β but the rest are only tested for the tag passed as the first argument. The function also calls _setup, which checks a few more styles. Multitasking queen.
The string that the format style returns (if there is one) gets modified so that every %d becomes the descr from the third argument, with any leading or trailing whitespace stripped. And if, after all that whitespace removal, descr is just an empty string? Then the format style doesn't get used at all, and the options placed into the name array won't contain an explanation string to show above the matches. Empty is empty, we move.
If you call _description with more than three arguments, those extra specs should look like char:str. They supply escape sequence replacements for the format style: every appearance of %char gets swapped for string. Cute.
And if you give no extra specs but your descr happens to conform to a common form, then extra escape sequences get set for the elements of that description. Those elements are: the default value (%o), the units (%m), the range of acceptable values (%r), and whatever's left of the initial part of the description (%h). The form is β units and range in parentheses, default value in square brackets. Example time:
_description times expl 'timeout (seconds) (0-60) [20]'
Obsessed. π
Oh and you can use zformat conditional expressions when styling these elements. So, say, if you want to add default: as a tag but only when there's actually a default value to show, your format style could include:
%(o.default: %o.)
Chef's kiss.
If you pass -x, the description gets handed to compadd with the -x option instead of the default -X. Translation: the description will be displayed even when there are no matching matches. Main character energy β shows up regardless.
The options put in the name array take the group-name style into account, so matches land in their own separate group when needed. That group normally has its elements sorted (by passing -J to compadd), but if you pass an option starting with -V, -J, -1, or -2 to _description, that option gets included in the array instead. So yeah β you can make the completion group unsorted by giving -V, -1V, or -2V. You have the power. Use it wisely. π¦
In most cases you'll use it like this:
local expl
_description files expl file
compadd "$expl[@]" - "$files[@]"
Note the parameter expl, the hyphen, and the list of matches. Almost every compadd call inside the completion system uses a similar format β that's what makes sure your user-specified styles get correctly passed down to the builtins that actually implement the internals of completion. Teamwork, babes. π«Ά
πΈ _dir_list πΈ
_dir_list [ -s sep ] [ -S ]
Completes a list of directory names separated by colons β same format as $PATH. Directory road trip.
-ssep β use sep as the separator between items. sep defaults to a colon (:).-Sβ add sep instead of a slash (/) as an autoremoveable suffix. Fancy.
π¦ _dispatch π¦
_dispatch context string ...
This sets the current context to context and then goes hunting for completion functions to handle it β it rummages through the list of command names or special contexts (like the ones described above for compdef) that you give it as *string*s. The first completion function that's defined for one of those contexts in the list is the one used to generate matches. Detective work, honestly.
Typically the last string is -default-, which makes the function for default completion your fallback. Backup plan, always.
The function sets the parameter $service to the string it's currently trying, and sets the context/command field (the fourth one) of the $curcontext parameter to the context you gave as the first argument. Very thorough.
π _email_addresses π
_email_addresses [ -c ] [ -n plugin ]
Completes email addresses. The addresses are provided by plugins β very modular of them.
-cβ complete barelocalhost@domain.tldaddresses, with no name part and no comment. Without this option, RFC822Firstname Lastname <address>strings are completed instead. Glow-up format vs. plain format.-nplugin β complete aliases from plugin.
These plugins come 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. A whole little squad. π
Addresses from the _email-foo plugin get added under the tag email-foo. Consistent naming, we love to see it.
π Writing plugins
Plugins are written as separate functions with names starting with _email-. They get invoked with the -c option plus 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 get picked up and run automatically β no registration form, no cover letter, they just show up and work. β¨
π§ _files π§
_files is a wrapper around _path_files. It supports all the same functionality, with some enhancements β notably it respects the list-dirs-first style, and it lets users override the behaviour of the -g and -/ options with the file-patterns style. So like... _files should be preferred over _path_files in most cases. It's the upgraded version. The glow-up is real.
This function accepts the full set of options allowed by _path_files, described below. Go read that bit, bestie.
π _gnu_generic π
This function is a simple wrapper around the _arguments function described above. It can automatically figure out the long options that a command understands, for commands that spit out a list when you pass them the --help option. Sneaky but effective.
It's meant to be used as a top-level completion function in its own right. So for example, to enable option completion for the commands foo and bar, you'd do:
compdef _gnu_generic foo bar
...after your call to compinit. Easy.
The completion system as supplied is conservative in its use of this function, because it's genuinely important to be sure the command actually understands the --help option. Don't just assume, okay? π
π _guard π
_guard [ options ] pattern descr
This function displays descr if pattern matches the string that's about to be completed. It's intended to be used in the action for the specifications passed to _arguments and similar functions. It's the bouncer at the club. πͺ
The return status is zero if the message was displayed and the word to complete isn't empty, and non-zero otherwise. Both conditions, no exceptions.
The pattern may be preceded by any of the options that compadd understands and that get passed down from _description β namely -M, -J, -V, -1, -2, -n, -F and -X. All of these options will be ignored. Yep, ignored. But that fits in super conveniently with the argument-passing conventions of actions for _arguments, so it's actually a feature. Trust the process.
As an example: imagine a command that takes 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'
...you can make _arguments both display the message numeric value and complete options after -n<TAB>. If the -n is already followed by one or more digits (that's the pattern passed to _guard), then only the message gets displayed. But if the -n is followed by another character, then only options get completed. Situational awareness, we stan. β
π _message π
_message [ -r12 ] [ -VJ group ] descr
_message -e [ tag ] descr
The descr is used 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. Which is genuinely useful for displaying a help message in places where no completions can even be generated. Emotional support message. π
The format style is examined with the messages tag to find a message; the usual tag, descriptions, is only used if the style isn't set with the former. Fallback chain, very demure.
If you pass -r, no style is used at all β descr is taken literally as the string to display. This is most useful when descr comes from a pre-processed argument list that already contains an expanded description. Note that this option does not disable the %-sequence parsing that compadd does, though. Careful.
The -12VJ options and the group get passed to compadd, and therefore determine which group the message string gets 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. _arguments calls this form when there's no action for an option specification. The tag can be omitted β and if you do omit it, the tag comes from the parameter $curtag, which the completion system maintains and so is usually correct. Team player.
Heads up bestie: if there are no matches at the time this function is called, compstate[insert] is cleared. So any additional matches generated later will not be inserted on the command line. That's just how it is. π
π
_multi_parts [ -i ] sep array
okay so bestie, sep is a separator character, and array can be either the name of an array parameter or a literal array written like (foo bar) β a parenthesised list of words separated by whitespace. β¨ The possible completions are just the strings from that array. But here's the slay part: each chunk delimited by sep gets completed separately. For example, the _tar function literally uses _multi_parts / patharray to complete partial file paths out of a given array of complete file paths. iconic. π
The -i option makes _multi_parts insert a unique match even if that means inserting multiple separators. Ngl this is not usually the expected behaviour with filenames, but certain other types of completion β like ones with a fixed set of possibilities β may be way more suited to this form. π¦
Like other utility functions, this one accepts the -V, -J, -1, -2, -n, -f, -X, -M, -P, -S, -r, -R, and -q options and passes them straight to the compadd builtin. π
π― _next_label [ -x ] [ -12VJ ] tag name descr [ option ... ]
This function is how you implement the loop over different tag labels for a particular tag, as described above for the tag-order style. On each call it checks whether there are any more tag labels β if there is, it returns status zero, otherwise non-zero. π« Since it needs a current tag to be set, it must always follow a call to _tags or _requested. no cap.
The -x12VJ options plus the first three arguments get passed to the _description function. Where appropriate, the tag gets replaced by a tag label in this call. Any description given in the tag-order style wins over the descr passed to _next_label. π
The options given after descr get 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's a typical use of this function for the tag foo β the call to _requested determines if tag foo is required at all, and 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's called both to complete the command word and to complete the arguments for a command. In that second case, _normal looks for a special completion for that command, and if there isn't one 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? nohup cmd ... gets treated in the same way as cmd .... π
-Pβ Reset the list of precommands. Use this if you're 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. Use this in nearly all cases in which-Pis 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's set, completion is terminated at that point even if no matches have been found. Same effect as in the -first- context. π
π’ _numbers [ option ... ] [ description ] [ suffix ... ]
Use this 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:
-t tagβ Specify a tag to use instead of the default ofnumbers.-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's typically helpful for units to be presented in order of magnitude when completed. To facilitate this, the order in which they're 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 one completes 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 β so for example, glob, noglob, and NO_GLOB are all completed. π Any arguments get propagated to the compadd builtin.
π§ _options_set and _options_unset
These functions complete only set or unset options, using the same matching specification as the _options function.
Heads up bestie: you need to uncomment a few lines in the _main_complete function for these 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
Used to complete the names of shell parameters.
The option -g pattern limits 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. literally so satisfying. π₯
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 thecompaddbuiltin. It gives direct control over which filenames should be ignored. If the option is not present, theignored-patternsstyle 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 expand, ambiguous, special-dirs, list-suffixes and file-sort styles described above.
π΅οΈ _pick_variant [ -b builtin-label ] [ -c command ] [ -r name ] label=pattern ... label [ arg ... ]
This function resolves situations where a single command name requires more than one type of handling β either because it has more than one variant, or because there's 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. π
still vibing in the utility-functions era of this page, bestie, don't worry β we're picking up right where we left off π
-bbuiltin-label β if you pass this, the command gets tested to see whether it's actually provided as a shell builtin (possibly autoloaded, no big deal), and if it is, then builtin-label is the label that gets picked for the variant β¨-rname β if you give this, the label that got picked gets stashed in the parameter named name, so you can grab it later π
The results are also cached in the _cmd_variant associative array, indexed by the name of the command that was run. Caching queen behavior, honestly π
_regex_arguments</p> name spec ...
Okay so this one is iconic β it generates a completion function called name that matches the specifications specs, which are a whole set of regular expressions, described below. After you run _regex_arguments, that function name should just be called like a normal completion function, no special casing needed π¦
The pattern to be matched is given by the contents of the words array up to the current cursor position, all joined together with null characters. And ngl, no quotation is applied β it's raw like that π
Here's how the arguments get grouped, because this part is a lot:
The arguments are grouped as sets of alternatives separated by |, and those get tried one after the other until one of them matches. Each alternative is made of one or more specifications which are tried left to right, with each pattern that matches getting stripped in turn from the command line being tested β and this keeps going until all of the group succeeds or until one of them fails. If one fails? Next alternative gets tried, periodt. And you can repeat this whole structure to arbitrary depth using parentheses; matching proceeds from the inside to the outside, like a lil onion π§
Now here's the special little procedure that kicks in: if no test succeeds, but the remaining command line string contains no null character (which implies the remaining word is the one you actually want completions for), then the completion target is restricted to that remaining word, and any actions for the corresponding patterns get executed. In this case, nothing gets stripped from the command line string, okay? The order of evaluation of the actions can be determined by the tag-order style, and the various formats supported by _alternative can be used in action. The descr is used for setting up the array parameter expl. Very demure, very mindful πΈ
The specification arguments take one of the following forms β and heads up, metacharacters like (, ), # 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 it does, guard gets evaluated and its return status is examined to figure out whether the test actually succeeded. The pattern string[]is guaranteed to never ever match, like ever. And the lookahead is not stripped from the command line before the next pattern gets examined β it stays put π«Ά
The argument starting with : is used in the exact same manner as an argument to _alternative.
So a component gets used like this: pattern is tested to see if the component already exists on the command line. If it does, then any following specifications are examined to find something to complete. But if a component is reached and no such pattern exists yet on the command line, then the string containing the action is used to generate matches to insert at that point. Slay, honestly β¨
/pattern/+ [%lookahead%] [-guard] [:tag:descr:action]β basically the same as/pattern/ ..., except the left part of the command line string (aka the part already matched by previous patterns) is also considered part of the completion target π/pattern/- [%lookahead%] [-guard] [:tag:descr:action]β also 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 can group specs together, but real talk: each parenthesis is a single argument to_regex_arguments, so don't get cute with it πspec #β this lets you have any number of repetitions of spec. Infinite vibes π₯spec specβ the two specs get matched one after the other, just like described above βspec | specβ either of the two specs can be matched, dealer's choice π
Oh and btw, 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. Teamwork makes the dream work π«Ά
Examples:</p> (yes we're doing these, they're good for you)
_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 β and yes, it works, but it's not recommended in normal use, so don't come for me π The first component matches the command word, which is arbitrary; the second matches any argument. And since the argument is also arbitrary, any following component would not depend on aaa being present. It's giving "no thoughts, head empty" π
_regex_arguments _tst /$'[^\0]#\0'/ \
/$'aaa\0'/ :'compadd aaa'
This one's a more typical use. It's similar, but any following patterns would only match if aaa was present as the first argument. See the difference? We love context π
_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 get completed as aaa and even arguments as bbb (alternating besties, we love to see it π¦). Completion fails unless the set of aaa and bbb arguments before the current one is matched correctly β so it's strict, no cutting corners β¨
_regex_arguments _tst /$'[^\0]#\0'/ \
\( /$'aaa\0'/ :'compadd aaa' \| \
/$'bbb\0'/ :'compadd bbb' \) \#
Similar again, but now either aaa or bbb may be completed for any argument. And in this case, _regex_words could be used to generate a suitable expression for the arguments. Convenient much? π
_regex_words</p> tag description spec ...
This function generates arguments for the _regex_arguments command, and those can be inserted at any point where a set of rules is expected. The tag and description give a standard tag and description that pertain to the current context. Each spec contains two or three arguments separated by a colon β and important note: there's 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. So it's roughly equivalent to the _arguments function when used in normal (non-regex) completion. Same energy, different outfit π
Here's the breakdown of the spec, bestie:
- 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*, gets completed, but only the text before the*is required for the context to be matched. That way, further arguments can still be completed after the abbreviated form. Sneaky but genius πΈ - 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 gets evaluated in order to avoid problems with quoting β which means that typically it contains a reference to an array containing previously generated regex arguments. iykyk π§
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. Cute, right? π
The result of the processing by _regex_words is placed in the array reply, which should be made local to the calling function. And if the set of words and arguments may be matched repeatedly, a # should be appended to the generated array at that point. Don't forget the #, or it's over for you π
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. Look at us, chaining functions like a whole ecosystem π
_requested</p> [ -x ] [ -12VJ ] tag [ name descr [ command [ arg ... ] ] ]
This function is called to decide whether a tag that's already been registered by a call to _tags (see below, bestie) has actually been requested by the user β and hence whether completion should be performed for it. It returns status zero if the tag is requested, and non-zero otherwise. Very straightforward, no cap β¨
Typically it's used as part of a loop over different tags, like this:
_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
And a lil heads up: the test for whether matches were generated is not performed until the end of the _tags loop. Why? So that the user can set the tag-order style to specify a set of tags to be completed at the same time. Big brain design decision, honestly π§ π
If name and descr are given, _requested calls the _description function with those arguments, together with the options that were passed to _requested. Passing the vibes along π«Ά
If command is given, the _all_labels function gets 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. Efficiency icon β 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
And finally β if the command is not compadd, it must nevertheless be prepared to handle the same options. No exceptions, bestie, them's the rules π
π«Ά _retrieve_cache cache_identifier
This one pulls completion info back out of the cache file named by cache_identifier, bestie. The file lives in the directory set by the cache-path style, which defaults to ~/.zcompcache. Return status is zero if the retrieval actually worked. It only even tries to retrieve when the use-cache style is set, so you can call this function without stressing about whether the user wanted the caching layer at all.
See _store_cache below for more deets.
β¨ _sep_parts
You pass this function alternating arrays and separators as arguments. The arrays specify completions for parts of strings that get separated by the separators. Those arrays can 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 is a wrapper around other functions for completing items in a separated list. The same function completes each item in the list. The separator is set with -s; if you omit -s, it uses ,. Duplicate values are not matched unless you pass -d. If the list has a fixed or maximum number of items, say so with the -n option.
Common compadd options get passed on to the function. You can use compadd directly with _sequence, though _values might be the more appropriate vibe in that situation.
π
_setup tag [ group ]
This function sets up the special parameters used by the completion system appropriately for the tag you give 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 where matches will be placed. If you don't give it, the tag gets used as the group name.
This function is called automatically from _description, so normally you do not call it explicitly. Iconic behaviour, honestly.
π¦ _store_cache cache_identifier param ...
This function, together with _retrieve_cache and _cache_invalid, implements a caching layer you can use in any completion function. Data obtained by costly operations gets stored in parameters; this function then dumps the values of those parameters to a file. That data can later be retrieved quickly from the file via _retrieve_cache, even in different instances of the shell.
The cache_identifier specifies the file 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 only attempts storage if the use-cache style is set, so you can call it without worrying about whether the user wanted 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 caching layer in action.
πΈ _tags [ [ -C name ] tag ... ]
If you call it with arguments, those 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 gets 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 whether a particular tag is to be tried, call the _requested function (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 lets _tags use a more specific context without having to change and reset the curcontext parameter (which does the same thing).
π§ _tilde_files
Like _files, but it resolves 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. Cute and practical, honestly.
π _values [ -O name ] [ -s sep ] [ -S sep ] [ -wC ] desc spec ...
This is used to complete arbitrary keywords (values) and their arguments, or lists of those 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...
okay so this is the shape of the _wanted call, bestie β iconic little helper behavior. π
See also the use of _wanted in the example function in the subsection Dynamic named directories in zshexpn(1).
Important note: as for _requested, the command must be able to accept options to be passed down to compadd. No cap.
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 the section Widgets in zshzle(1)). The pattern, if present, is matched against values of the $widgets special parameter, documented in the section The zsh/zleparameter Module in zshmodules(1).
β¨ COMPLETION SYSTEM VARIABLES β¨
There are some standard variables, initialised by the _main_complete function and then used from other functions.
The standard variables are:
_comp_caller_optionsβ the completion system usessetoptto set a number of options. This allows functions to be written without concern for compatibility with every possible combination of user options. However, sometimes completion needs to know what the user's option preferences are. These are saved in the_comp_caller_optionsassociative array. Option names, spelled in lowercase without underscores, are mapped to one or other of the stringsonandoff._comp_priv_prefixβ completion functions such as_sudocan set the_comp_priv_prefixarray to a command prefix that may then be used by_call_programto match the privileges when calling programs to generate matches.
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.
ποΈ COMPLETION DIRECTORIES ποΈ
okay so in the source distribution, the files are contained in various subdirectories of the Completion directory. They may have been installed in the same structure, or into one single function directory.
The following is a description of the files found in the original directory structure. If you wish to alter an installed file, you will need to copy it to some directory which appears earlier in your fpath than the standard directory where it appears.
Baseβ the core functions and special completion widgets automatically bound to keys. You will certainly need most of these, though will probably not need to alter them. Many of these are documented above.Zshβ functions for completing arguments of shell builtin commands and utility functions for this. Some of these are also used by functions from theUnixdirectory.Unixβ functions for completing arguments of external commands and suites of commands. They may need modifying for your system, although in many cases some attempt is made to decide which version of a command is present. For example, completion for themountcommand tries to determine the system it is running on, while completion for many other utilities try to decide whether the GNU version of the command is in use, and hence whether the--helpoption is supported.X,AIX,BSD, ... β completion and utility function for commands available only on some systems. These are not arranged hierarchically, so, for example, both the Linux and Debian directories, as well as theXdirectory, may be useful on your system.
β¨ Thatβs a wrap on ZSHCOMPSYS(1), bestie β this page is from zsh 5.9.2, dated July 12, 2026. πππ«Ά
π¦ where this page comes from
- arch rolling: zsh 5.9.2-1 Β· custom
- nixpkgs unstable: zsh 5.9.2
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms