ZSHCOMPWID(1)
π zshcompwid(1) β zsh completion widgets π
π NAME π
zshcompwid β zsh completion widgets
β¨ DESCRIPTION β¨
okay so bestie, the shellβs programmable completion mechanism can be manipulated in two ways. This page is all about the low-level features that support the newer, function-based mechanism. A whole complete set of shell functions built on these features lives in zshcompsys(1). And if you have zero interest in adding to that system β or, potentially, writing your own, see the dictionary entry for hubris π β you should skip this section. The older system based on the compctl builtin command is described in zshcompctl(1).
Completion widgets are defined by the -C option to the zle builtin command provided by the zsh/zle module (see zshzle(1)). For example:
zle -C complete expand-or-complete completer
defines a widget named complete. The second argument is the name of any of the builtin widgets that handle completions: complete-word, expand-or-complete, expand-or-complete-prefix, menu-complete, menu-expand-or-complete, reverse-menu-complete, list-choices, or delete-char-or-list. Note that this will still work even if the widget in question has been re-bound. slay.
When this newly defined widget is bound to a key using the bindkey builtin command defined in the zsh/zle module (see zshzle(1)), typing that key will call the shell function completer. This function is responsible for generating completion matches using the builtins described below. As with other ZLE widgets, the function is called with its standard input closed.
Once the function returns, the completion code takes over control again and treats the matches in the same manner as the specified builtin widget β in this case, expand-or-complete. π
π COMPLETION SPECIAL PARAMETERS π
The parameters ZLE_REMOVE_SUFFIX_CHARS and ZLE_SPACE_SUFFIX_CHARS are used by the completion mechanism, but are not special. See Parameters Used By The Shell in zshparam(1).
Inside completion widgets, and any functions called from them, some parameters have special meaning; outside these functions they are not special to the shell in any way. These parameters are used to pass information between the completion code and the completion widget. Some of the builtin commands and the condition codes use or change the current values of these parameters. Any existing values will be hidden during execution of completion widgets; except for compstate, the parameters are reset on each function exit (including nested function calls from within the completion widget) to the values they had when the function was entered. bestie, thatβs the vibe check for the whole section. π«Ά
CURRENTβ This is the number of the current word, i.e. the word the cursor is currently on in thewordsarray. Note that this value is only correct if theksharraysoption is not set.IPREFIXβ Initially this will be set to the empty string. This parameter functions likePREFIX; it contains a string which precedes the one inPREFIXand is not considered part of the list of matches. Typically, a string is transferred from the beginning ofPREFIXto the end ofIPREFIX, for example:
IPREFIX=${PREFIX%%\=*}=
PREFIX=${PREFIX#*=}
causes the part of the prefix up to and including the first equal sign not to be treated as part of a matched string. This can be done automatically by the compset builtin, see below.
ISUFFIXβ AsIPREFIX, but for a suffix that should not be considered part of the matches; note that theISUFFIXstring follows theSUFFIXstring.PREFIXβ Initially this will be set to the part of the current word from the beginning of the word up to the position of the cursor; it may be altered to give a common prefix for all matches.QIPREFIXβ This parameter is read-only and contains the quoted string up to the word being completed. E.g. when completing"foo, this parameter contains the double quote. If the-qoption ofcompsetis used (see below), and the original string was"foo barwith the cursor on thebar, this parameter contains"foo.QISUFFIXβ LikeQIPREFIX, but containing the suffix.SUFFIXβ Initially this will be set to the part of the current word from the cursor position to the end; it may be altered to give a common suffix for all matches. It is most useful when the optionCOMPLETE_IN_WORDis set, as otherwise the whole word on the command line is treated as a prefix.compstateβ This is an associative array with various keys and values that the completion code uses to exchange information with the completion widget. The keys are:all_quotesβ The-qoption of thecompsetbuiltin command (see below) allows a quoted string to be broken into separate words; if the cursor is on one of those words, that word will be completed, possibly invokingcompset -qrecursively. With this key it is possible to test the types of quoted strings which are currently broken into parts in this fashion. Its value contains one character for each quoting level. The characters are a single quote or a double quote for strings quoted with these characters, a dollars sign for strings quoted with$'...'and a backslash for strings not starting with a quote character. The first character in the value always corresponds to the innermost quoting level.contextβ This will be set by the completion code to the overall context in which completion is attempted. Possible values are:array_valueβ when completing inside the value of an array parameter assignment; in this case thewordsarray contains the words inside the parentheses.brace_parameterβ when completing the name of a parameter in a parameter expansion beginning with${. This context will also be set when completing parameter flags following${(; the full command line argument is presented and the handler must test the value to be completed to ascertain that this is the case.assign_parameterβ when completing the name of a parameter in a parameter assignment.commandβ when completing for a normal command (either in command position or for an argument of the command).conditionβ when completing inside a[[...]]conditional expression; in this case thewordsarray contains only the words inside the conditional expression.mathβ when completing in a mathematical environment such as a((...))construct.parameterβ when completing the name of a parameter in a parameter expansion beginning with$but not${.redirectβ when completing after a redirection operator.subscriptβ when completing inside a parameter subscript.valueβ when completing the value of a parameter assignment.
exactβ Controls the behaviour when theREC_EXACToption is set. It will be set toacceptif an exact match would be accepted, and will be unset otherwise.
If it was set when at least one match equal to the string on the line was generated, the match is accepted.
exact_stringβ The string of an exact match if one was found, otherwise unset.ignoredβ The number of completions that were ignored because they matched one of the patterns given with the-Foption to thecompaddbuiltin command.insertβ This controls the manner in which a match is inserted into the command line. On entry to the widget function, if it is unset the command line is not to be changed; if set tounambiguous, any prefix common to all matches is to be inserted; if set toautomenu-unambiguous, the common prefix is to be inserted and the next invocation of the completion code may start menu completion (due to theAUTO_MENUoption being set); if set tomenuorautomenumenu completion will be started for the matches currently generated (in the latter case this will happen because theAUTO_MENUis set). The value may also contain the stringtabwhen the completion code would normally not really do completion, but only insert the T<span></span>AB character.
On exit it may be set to any of the values above (where setting it to the empty string is the same as unsetting it), or to a number, in which case the match whose number is given will be inserted into the command line. Negative numbers count backward from the last match (with -1 selecting the last match) and out-of-range values are wrapped around, so that a value of zero selects the last match and a value one more than the maximum selects the first. Unless the value of this key ends in a space, the match is inserted as in a menu completion, i.e. without automatically appending a space.
Both menu and automenu may also specify the number of the match to insert, given after a colon. For example, menu:2 says to start menu completion, beginning with the second match.
Note that a value containing the substring tab makes the matches generated be ignored and only the T<span></span>AB be inserted.
Finally, it may also be set to all, which makes all matches generated be inserted into the line. πβ¨
insert_positionsβ okay so when the completion system inserts an unambiguous string into the line, there may be multiple places where characters are missing or where the character inserted differs from at least one match. The value of this key is a colon separated list of all these positions, as indexes into the command line.last_promptβ if this is set to a non-empty string for every match added, the completion code will move the cursor back to the previous prompt after the list of completions has been displayed. Initially this is set or unset according to theALWAYS_LAST_PROMPToption.listβ this controls whether or how the list of matches will be displayed. If it is unset or empty they will never be listed; if its value begins withlist, they will always be listed; if it begins withautolistorambiguous, they will be listed when theAUTO_LISTorLIST_AMBIGUOUSoptions respectively would normally cause them to be. If the substringforceappears in the value, this makes the list be shown even if there is only one match. Normally, the list would be shown only if there are at least two matches. The value contains the substringpackedif theLIST_PACKEDoption is set. If this substring is given for all matches added to a group, this group will show theLIST_PACKEDbehavior. The same is done for theLIST_ROWS_FIRSToption with the substringrows. Finally, if the value contains the stringexplanations, only the explanation strings, if any, will be listed and if it containsmessages, only the messages (added with the-xoption ofcompadd) will be listed. If it contains bothexplanationsandmessagesboth kinds of explanation strings will be listed. It will be set appropriately on entry to a completion widget and may be changed there.list_linesβ this gives the number of lines that are needed to display the full list of completions. Note that to calculate the total number of lines to display you need to add the number of lines needed for the command line to this value, this is available as the value of theBUFFERLINESspecial parameter.list_maxβ initially this is set to the value of theLISTMAXparameter. It may be set to any other value; when the widget exits this value will be used in the same way as the value ofLISTMAX.nmatchesβ the number of matches added by the completion code so far.old_insertβ on entry to the widget this will be set to the number of the match of an old list of completions that is currently inserted into the command line. If no match has been inserted, this is unset. As withold_list, the value of this key will only be used if it is the stringkeep. If it was set to this value by the widget and there was an old match inserted into the command line, this match will be kept and if the value of theinsertkey specifies that another match should be inserted, this will be inserted after the old one.old_listβ this is set toyesif there is still a valid list of completions from a previous completion at the time the widget is invoked. This will usually be the case if and only if the previous editing operation was a completion widget or one of the builtin completion functions. If there is a valid list and it is also currently shown on the screen, the value of this key is shown. After the widget has exited the value of this key is only used if it was set tokeep. In this case the completion code will continue to use this old list. If the widget generated new matches, they will not be used.parameterβ the name of the parameter when completing in a subscript or in the value of a parameter assignment.pattern_insertβ normally this is set tomenu, which specifies that menu completion will be used whenever a set of matches was generated usingpattern_match(see below). If it is set to any other non-empty string by the user and menu completion is not selected by other option settings, the code will instead insert any common prefix for the generated matches as with normal completion.pattern_matchβ locally controls the behaviour given by theGLOB_COMPLETEoption. Initially it is set to*if and only if the option is set. The completion widget may set it to this value, to an empty string (which has the same effect as unsetting it), or to any other non-empty string. If it is non-empty, unquoted metacharacters on the command line will be treated as patterns; if it is*, then additionally a wildcard*is assumed at the cursor position; if it is empty or unset, metacharacters will be treated literally. Note that the match specifications given to thecompaddbuiltin command are not used if this is set to a non-empty string.quoteβ when completing inside quotes, this contains the quotation character (i.e. either a single quote, a double quote, or a backtick). Otherwise it is unset.quotingβ when completing inside single quotes, this is set to the stringsingle; inside double quotes, the stringdouble; inside backticks, the stringbacktick. Otherwise it is unset.redirectβ the redirection operator when completing in a redirection position, i.e. one of<,>, etc.restoreβ this is set toautobefore a function is entered, which forces the special parameters mentioned above (words,CURRENT,PREFIX,IPREFIX,SUFFIX, andISUFFIX) to be restored to their previous values when the function exits. If a function unsets it or sets it to any other string, they will not be restored.to_endβ specifies the occasions on which the cursor is moved to the end of a string when a match is inserted. On entry to a widget function, it may besingleif this will happen when a single unambiguous match was inserted ormatchif it will happen any time a match is inserted (for example, by menu completion; this is likely to be the effect of theALWAYS_TO_ENDoption). On exit, it may be set tosingleas above. It may also be set toalways, or to the empty string or unset; in those cases the cursor will be moved to the end of the string always or never respectively. Any other string is treated asmatch.unambiguousβ this key is read-only and will always be set to the common (unambiguous) prefix the completion code has generated for all matches added so far.unambiguous_cursorβ this gives the position the cursor would be placed at if the common prefix in theunambiguouskey were inserted, relative to the value of that key. The cursor would be placed before the character whose index is given by this key.unambiguous_positionsβ this contains all positions where characters in the unambiguous string are missing or where the character inserted differs from at least one of the matches. The positions are given as indexes into the string given by the value of theunambiguouskey.varedβ if completion is called while editing a line using thevaredbuiltin, the value of this key is set to the name of the parameter given as an argument tovared. This key is only set while avaredcommand is active.wordsβ this array contains the words present on the command line currently being edited.
β¨ COMPLETION BUILTIN COMMANDS β¨
The synopsis is giving main-character energy, and honestly it ate:
compadd [ -akqQfenUl12C ] [ -F array ]
[-P prefix ] [ -S suffix ]
[-p hidden-prefix ] [ -s hidden-suffix ]
[-i ignored-prefix ] [ -I ignored-suffix ]
[-W file-prefix ] [ -d array ]
[-J group-name ] [ -X explanation ] [ -x message ]
[-V group-name ] [ -o [ order ] ]
[-r remove-chars ] [ -R remove-func ]
[-D array ] [ -O array ] [ -A array ]
[-E number ]
[-M match-spec ] [ -- ] [ completions ... ]
compadd is the builtin command you use to add matches directly and control all the information the completion code stores with each possible completion. The return status is zero if at least one match was added and non-zero if no matches were added.
The completion code breaks each match into seven fields in the order:
<ipre><apre><hpre><body><hsuf><asuf><isuf>
Okay so bestie, here's the field-by-field tea:
<ipre>β the first field is an ignored prefix taken from the command line, the contents of theIPREFIXparameter plus the string given with the-ioption. With the-Uoption, only the string from the-ioption is used.<apre>β an optional prefix string given with the-Poption.<hpre>β a string that is considered part of the match but that should not be shown when listing completions, given with the-poption; for example, functions that do filename generation might specify a common path prefix this way.<body>β the part of the match that should appear in the list of matches shown to the user.<hsuf>,<asuf>,<isuf>β these suffixes correspond to the prefixes<hpre>,<apre>and<ipre>and are given by the options-s,-Sand-I, respectively.
okay so the supported flags are literally these, bestie β and yes, you need to know all of them π β¨
-Pprefix β gives you a string that gets inserted before every match. The string is not considered part of the match, and any shell metacharacters in it will not be quoted when it's inserted.-Ssuffix β same energy as-P, but it inserts the string after every match.-phidden-prefix β gives a string that should be inserted before each match but should not show up in the list of matches. Unless you give the-Uoption, this string has to be matched as part of the string on the command line.-shidden-suffix β like-pbut for after each match.-iignored-prefix β gives a string to insert just before any string given with-P. If there's no-P, it gets inserted before the string given with-por directly before each match.-Iignored-suffix β like-ibut for an ignored suffix.-aβ with this flag the completions are taken as names of arrays, and the actual completions are their values. If you only need some elements of the arrays, the completions may also contain subscripts, likefoo[2,-1].-kβ with this flag the completions are taken as names of associative arrays, and the actual completions are their keys. Just like-a, the words may also contain subscripts, likefoo[(R)*bar*].-darray β adds per-completion display strings. The array should contain one element per completion given. The completion code will then display the first element instead of the first completion, and so on. The array may be given as the name of an array parameter or directly as a space-separated list of words in parentheses.
If there are fewer display strings than completions, the leftover completions will be displayed unchanged. If there are more display strings than completions, the leftover display strings will be silently ignored (they just vanish, no cap). π«Ά
-lβ this option only has an effect if used together with-d. If it's given, the display strings are listed one per line, not arrayed in columns.-o[ order ] β controls the order in which matches are sorted. order is a comma-separated list comprising the following possible values. These values can be abbreviated to their initial two or three characters. Note that the order forms part of the group name space, so matches with different orderings will not be in the same group.matchβ if given, the order of the output is determined by the match strings; otherwise it is determined by the display strings (i.e. the strings given by-d). This is the default if-ois specified but the order argument is omitted.nosortβ specifies that the completions are pre-sorted and their order should be preserved. This value only makes sense alone and cannot be combined with any others.numericβ if the matches include numbers, sort them numerically rather than lexicographically.reverseβ arrange the matches backwards by reversing the sort ordering.
-Jgroup-name β gives the name of the group that the matches should be stored in.-Vgroup-name β like-Jbut naming an unsorted group. This option is identical to the combination of-Jand-o nosort.-1β if given together with-V, makes only consecutive duplicates in the group be removed. If combined with-J, this has no visible effect. Note that groups with and without this flag are in different name spaces.-2β if given together with-Jor-V, makes all duplicates be kept. Again, groups with and without this flag are in different name spaces.-Xexplanation β the explanation string will be printed with the list of matches, above the group currently selected.
Within the explanation, the following sequences may be used to specify output attributes as described in the section EXPANSION OF PROMPT SEQUENCES in zshmisc(1): %B, %S, %U, %F, %K and their lower case counterparts, as well as %{...%}. %F, %K and %{...%} take arguments in the same form as prompt expansion. (Note that the sequence %G is not available; an argument to %{ should be used instead.) The sequence %% produces a literal %.
These sequences are most often employed by users when customising the format style (see zshcompsys(1)), but they must also be taken into account when writing completion functions, as passing descriptions with unescaped % characters to utility functions such as _arguments and _message may produce unexpected results. If arbitrary text is to be passed in a description, it can be escaped using e.g. ${my_str//\%/%%}.
-xmessage β like-X, but the message will be printed even if there are no matches in the group.-qβ the suffix given with-Swill be automatically removed if the next character typed is a blank or does not insert anything, or if the suffix consists of only one character and the next character typed is the same character.-rremove-chars β this is a more versatile form of the-qoption. The suffix given with-Sor the slash automatically added after completing directories will be automatically removed if the next character typed inserts one of the characters given in remove-chars. This string is parsed as a character class and understands the backslash sequences used by theprintcommand. For example,-r "a-z\t"removes the suffix if the next character typed inserts a lower case character or a TAB, and-r "^0-9"removes the suffix if the next character typed inserts anything but a digit. One extra backslash sequence is understood in this string:\-stands for all characters that insert nothing. Thus-S "=" -qis the same as-S "=" -r "= \t\n\-".
This option may also be used without the -S option; then any automatically added space will be removed when one of the characters in the list is typed.
-Rremove-func β this is another form of the-roption. When a match has been accepted and a suffix has been inserted, the function remove-func will be called after the next character typed. It is passed the length of the suffix as an argument and can use the special parameters available in ordinary (non-completion) zle widgets (seezshzle(1)) to analyse and modify the command line.-fβ if this flag is given, all of the matches built from the completions are marked as being the names of files. They are not required to be actual filenames, but if they are, and the optionLIST_TYPESis set, the characters describing the types of the files in the completion lists will be shown. This also forces a slash to be added when the name of a directory is completed.-eβ this flag can be used to tell the completion code that the matches added are parameter names for a parameter expansion. This will make theAUTO_PARAM_SLASHandAUTO_PARAM_KEYSoptions be used for the matches.-Wfile-prefix β this string is a pathname that will be prepended to each match together with any prefix specified by the-poption to form a complete filename for testing. Hence it is only useful if combined with the-fflag, as the tests will not otherwise be performed.-Farray β specifies an array containing patterns. Completions that match one of these patterns are ignored, that is, not considered to be matches.
The array may be the name of an array parameter or a list of literal patterns enclosed in parentheses and quoted, as in -F "(*?.o *?.h)". If the name of an array is given, the elements of the array are taken as the patterns.
-Qβ this flag instructs the completion code not to quote any metacharacters in the matches when inserting them into the command line.-Mmatch-spec β this gives local match specifications as described below in the sectionCompletion Matching Control. This option may be given more than once. In this case all match-specs given are concatenated with spaces between them to form the specification string to use. Note that they will only be used if the-Uoption is not given.-nβ specifies that matching completions are to be added to the set of matches, but are not to be listed to the user.-Uβ if this flag is given, all completions are added to the set of matches and no matching will be done by the completion code. Normally this is used in functions that do the matching themselves.-O arrayβ okay so with this one, your completions do NOT get added to the match set. Instead, the matching happens like normal and every completion that matches gets stashed in the array parameter named array. π-A arrayβ same idea as-O, except what lands in array isn't the matching completions themselves, it's the strings that the completion code generated internally. Like, example time: with a match spec of-M "L:|no=", a current word ofnof, and completions offoo, this option stores the stringnofooin the array, whereas-Ostores thefoothat you originally gave it. iykyk π«Ά-D arrayβ also like-O, completions are not added to the set of matches. Instead, whenever the nth completion doesn't match, the nth element of the array gets removed. The elements whose corresponding completion does match are retained. You can use this option more than once to remove elements from multiple arrays. β¨-Cβ this one adds a special match that expands to all the other matches when it's inserted into the line β even the ones that get added after this option is used. Paired up with the-doption, you can specify a string that should be displayed in the list for this special match. If no string is given, it'll be shown as a string containing the strings that would be inserted for the other matches, truncated to the width of the screen. the way that works is honestly iconic π-E numberβ adds number empty matches after the matching completions have been added. An empty match takes up space in completion listings, but bestie listen to me: it will never be inserted in the line and it can't be selected with menu completion or menu selection. So empty matches are only useful for formatting completion lists and for making explanatory strings show up in completion lists (since empty matches can be given display strings with the-doption). And because all but one empty string would otherwise be removed, this option implies the-Vand-2options (even if an explicit-Joption is given). This is important to note because it affects the name space into which matches are added. π§-,--β this flag ends the list of flags and options. Everything after it gets taken as the completions, even if it begins with hyphens. π
Except for the -M flag, if any of these flags is given more than once, the first one (and its argument) will be used. (yes, the first one. rude but true.)
π¦ compset β the glow-up button for your special parameters
compset -p number
compset -P [ number ] pattern
compset -s number
compset -S [ number ] pattern
compset -n begin [ end ]
compset -N beg-pat [ end-pat ]
compset -q
This command simplifies modification of the special parameters, while its return status lets you run tests on them. literally the multitasking queen π
The options are:
-p numberβ if the value of thePREFIXparameter is at least number characters long, the first number characters are removed from it and appended to the contents of theIPREFIXparameter. π-P [ number ] patternβ if the value of thePREFIXparameter begins with anything that matches the pattern, the matched portion is removed fromPREFIXand appended toIPREFIX.
Without the optional number, the longest match is taken β but if number is given, anything up to the *number*th match is moved. If the number is negative, the *number*th longest match is moved. Example time, because yes: if PREFIX contains the string a=b=c, then compset -P '*\=' will move the string a=b= into the IPREFIX parameter, but compset -P 1 '*\=' will move only the string a=. see the difference? slay π₯
-s numberβ as-p, but it transfers the last number characters from the value ofSUFFIXto the front of the value ofISUFFIX. πΈ-S [ number ] patternβ as-P, but it matches the last portion ofSUFFIXand transfers the matched portion to the front of the value ofISUFFIX.-n begin [ end ]β if the current word position as specified by the parameterCURRENTis greater than or equal to begin, anything up to the beginth word is removed from thewordsarray and the value of the parameterCURRENTis decremented by begin.
If the optional end is given, the modification is done only if the current word position is also less than or equal to end. In this case, the words from position end onwards are also removed from the words array.
Both begin and end may be negative to count backwards from the last element of the words array. counting backwards is so real of them π
-N beg-pat [ end-pat ]β if one of the elements of thewordsarray before the one at the index given by the value of the parameterCURRENTmatches the pattern beg-pat, all elements up to and including the matching one are removed from thewordsarray and the value ofCURRENTis changed to point to the same word in the changed array.
If the optional pattern end-pat is also given, and there's an element in the words array matching this pattern, the parameters are modified only if the index of this word is higher than the one given by the CURRENT parameter (so that the matching word has to be after the cursor). In this case, the words starting with the one matching end-pat are also removed from the words array. If words contains no word matching end-pat, the testing and modification is performed as if it were not given. π
-qβ the word currently being completed is split on spaces into separate words, respecting the usual shell quoting conventions. The resulting words are stored in thewordsarray, andCURRENT,PREFIX,SUFFIX,QIPREFIX, andQISUFFIXare modified to reflect the word part that is completed. β¨
In all the above cases the return status is zero if the test succeeded and the parameters were modified, and non-zero otherwise. This lets you use this builtin in tests like:
if compset -P '*\='; then ...
This forces anything up to and including the last equal sign to be ignored by the completion code. chef's kiss π
π compcall β the bridge to your old compctl era
compcall [ -TD ]
This allows the use of completions defined with the compctl builtin from within completion widgets. The list of matches will be generated as if one of the non-widget completion functions (complete-word, etc.) had been called β except that only compctls given for specific commands are used. To force the code to try completions defined with the -T option of compctl and/or the default completion (whether defined by compctl -D or the builtin default) in the appropriate places, you can pass the -T and/or -D flags to compcall.
The return status can be used to test if a matching compctl definition was found. It's non-zero if a compctl was found and zero otherwise. π (yes, backwards from what your gut says, don't come for me)
Note that this builtin is defined by the zsh/compctl module.
β¨ COMPLETION CONDITION CODES β¨
The following additional condition codes for use within the [[ ... ]] construct are available in completion widgets. These work on the special parameters. All of these tests can also be performed by the compset builtin β but with the condition codes, the contents of the special parameters are not modified. no cap, that's the whole difference π«Ά
-prefix [ number ] patternβ true if the test for the-Poption ofcompsetwould succeed.-suffix [ number ] patternβ true if the test for the-Soption ofcompsetwould succeed.-after beg-patβ true if the test of the-Noption with only the beg-pat given would succeed.-between beg-pat end-patβ true if the test for the-Noption with both patterns would succeed.
β¨ COMPLETION MATCHING CONTROL β¨
okay so when the user invokes completion, the current word on the command line (the word the cursor is currently on) is used to generate a match pattern. Only those completions that match the pattern are offered to the user as matches. π«Ά
The default match pattern is generated from the current word by either:
- appending a
*(matching any number of characters in a completion) or - if the shell option
COMPLETE_IN_WORDis set, inserting a*at the cursor position.
This narrow pattern can be broadened selectively by passing a match specification to the compadd builtin command through its -M option (see Completion Builtin Commands above). A match specification consists of one or more matchers separated by whitespace. Matchers in a match specification are applied one at a time, from left to right. Once all matchers have been applied, completions are compared to the final match pattern and non-matching ones are discarded. π
- Note that the
-Moption is ignored if the current word contains a glob pattern and the shell optionGLOB_COMPLETEis set or if thepattern_matchkey of the special associative arraycompstateis set to a non-empty value (seeCompletion Special Parametersabove). - Users of the completion system (see
zshcompsys(1)) should generally not use the-Moption directly, but rather use thematcher-listandmatcherstyles (see the subsectionStandard Stylesin the documentation forCOMPLETION SYSTEM CONFIGURATIONinzshcompsys(1)).
Each matcher consists of:
- a case-sensitive letter
- a
: - one or more patterns separated by pipes (
|) - an equals sign (
=) - another pattern.
The patterns before the = are used to match substrings of the current word. For each matched substring, the corresponding part of the match pattern is broadened with the pattern after the =, by means of a logical OR. π
Each pattern in a matcher consists of either:
- the empty string or
- a sequence of:
- literal characters (which may be quoted with a
\) - question marks (
?) - bracket expressions (
[...]; see the subsectionGlob Operatorsin the documentation forGLOB OPERATORSinzshexpn(1)) - and/or brace expressions (see below).
- literal characters (which may be quoted with a
Other shell patterns are not allowed. π
A brace expression, like a bracket expression, consists of a list of:
- literal characters
- ranges (
0-9) - and/or character classes (
[:name:]).
However, they differ from each other as follows:
- A brace expression is delimited by a pair of braces (
{...}). - Brace expressions do not support negations. That is, an initial
!or^has no special meaning and will be interpreted as a literal character. - When a character in the current word matches the nth pattern in a brace expression, the corresponding part of the match pattern is broadened only with the nth pattern of the brace expression on the other side of the
=, if there is one; if there is no brace expression on the other side, then this pattern is the empty string. However, if either brace expression has more elements than the other, then the excess entries are simply ignored. When comparing indexes, each literal character or character class counts as one element, but each range is instead expanded to the full list of literal characters it represents. Additionally, if on both sides of the=, the nth pattern is[:upper:]or[:lower:], then these are expanded as ranges, too. β¨
Heads-up, bestie: although the matching system does not yet handle multibyte characters, this is likely to be a future extension. Hence, using[:upper:]and[:lower:]is recommended overA-Zanda-z.
Below are the different forms of matchers supported. Each uppercase form behaves exactly like its lowercase counterpart, but adds an additional step after the match pattern has filtered out non-matching completions: Each of a match's substrings that was matched by a subpattern from an uppercase matcher is replaced with the corresponding substring of the current word. However, patterns from lowercase matchers have higher weight: If a substring of the current word was matched by patterns from both a lowercase and an uppercase matcher, then the lowercase matcher's pattern wins and the corresponding part of the match is not modified. π
Unless indicated otherwise, each example listed assumes COMPLETE_IN_WORD to be unset (as it is by default).
π
the m: and M: matchers β word-pat=match-pat
m:word-pat=match-pat
M:word-pat=match-pat
For each substring of the current word that matches word-pat, broaden the corresponding part of the match pattern to additionally match match-pat.
Examples:
m:{[:lower:]}={[:upper:]}lets any lower case character in the current word be completed to itself or its uppercase counterpart. So, the completionsfoo,FOOandFoowill be considered matches for the wordfo.M:_=inserts every underscore from the current word into each match, in the same relative position, determined by matching the substrings around it. So, given a completionfoo, the wordf_owill be completed to the matchf_oo, even though the latter was not present as a completion.
π¦ the b:, B:, e: and E: matchers β word-pat=match-pat
b:word-pat=match-pat
B:word-pat=match-pat
e:word-pat=match-pat
E:word-pat=match-pat
For each consecutive substring at the b:eginning or e:nd of the current word that matches word-pat, broaden the corresponding part of the match pattern to additionally match match-pat.
Examples:
b:-=+lets any number of minuses at the start of the current word be completed to a minus or a plus.B:0=adds all zeroes at the beginning of the current word to the beginning of each match.
πΈ the l:, L:, r: and R: edge matchers
l:|word-pat=match-pat
L:|word-pat=match-pat
r:word-pat|=match-pat
R:word-pat|=match-pat
If there is a substring at the l:eft or r:ight edge of the current word that matches word-pat, then broaden the corresponding part of the match pattern to additionally match match-pat.
For each l:, L:, r: and R: matcher (including the ones below), the pattern match-pat may also be a *. This matches any number of characters in a completion. π«
Examples:
r:|=*appends a*to the match pattern, even whenCOMPLETE_IN_WORDis set and the cursor is not at the end of the current word.- If the current word starts with a minus, then
L:|-=will prepend it to each match.
π the anchored l:, L:, r: and R: matchers
l:anchor|word-pat=match-pat
L:anchor|word-pat=match-pat
r:word-pat|anchor=match-pat
R:word-pat|anchor=match-pat
For each substring of the current word that matches word-pat and has on its l:eft or r:ight another substring matching anchor, broaden the corresponding part of the match pattern to additionally match match-pat.
Note that these matchers (and the ones below) modify only what is matched by word-pat; they do not change the matching behavior of what is matched by anchor (or coanchor; see the matchers below). Thus, unless its corresponding part of the match pattern has been modified, the anchor in the current word has to match literally in each completion, just like any other substring of the current word. π₯
If a matcher includes at least one anchor (which includes the matchers with two anchors, below), then match-pat may also be * or **. * can match any part of a completion that does not contain any substrings matching anchor, whereas a ** can match any part of a completion, period. (Note that this is different from the behavior of * in the anchorless forms of l: and r: and also different from * and ** in glob expressions.)
Examples:
r:|.=*makes the completioncomp.sources.unixa match for the word..uβ but not for the word.u.- Given a completion
--foo, the matcherL:--|no-=will complete the word--no-to the match--no-foo.
π§ the coanchor l:, L:, r: and R: matchers
l:anchor||coanchor=match-pat
L:anchor||coanchor=match-pat
r:coanchor||anchor=match-pat
R:coanchor||anchor=match-pat
For any two consecutive substrings of the current word that match anchor and coanchor, in the order given, insert the pattern match-pat between their corresponding parts in the match pattern.
Note that, unlike anchor, the pattern coanchor does not change what * can match. π
Examples:
r:?||[[:upper:]]=*will complete the current wordfBtofooBar, but it will not complete it tofooHooBar(because*here cannot match anything that includes a match for[[:upper:]]), nor will it completeBtofooBar(because there is no character in the current word to matchcoanchor).- Given the current word
pass.nand a completionpass.byname, the matcherL:.||[[:alpha:]]=bywill produce the matchpass.name.
π the x: matcher
x:
Ignore this matcher and all matchers to its right.
This matcher is used to mark the end of a match specification. In a single standalone list of matchers, this has no use, but where match specifications are concatenated, as is often the case when using the completion system (see zshcompsys(1)), it can allow one match specification to override another.
π§ COMPLETION WIDGET EXAMPLE π§
okay bestie, first step is to define the widget:
zle -C complete complete-word complete-files
Then the widget can be bound to a key using the bindkey builtin command:
bindkey '^X\t' complete
After that the shell function complete-files will be invoked after typing Ctrl+X and TAB. The function should then generate the matches, e.g.:
complete-files () { compadd - * }
This function will complete files in the current directory matching the current word. π
Thatβs the whole page, bestie β source/version zsh 5.9.2, date July 12, 2026, and the manual page tag is ZSHCOMPWID(1). mwah ππ
π¦ 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