Chapter 6: Completion, old and new

Completion of command arguments is something zsh is particularly good at. The simplest case is that you hit <TAB>, and the shell guesses what has to go there and fills it in for you:

  % ls
  myfile  theirfile  yourfile
  % cat t<TAB>
expands the command line to
  % cat theirfile
and you only had to type the initial letter, then TAB.

In the early days when this feature appeared in the C shell, only filenames could be completed; there were no clever tricks to help you if the name was ambiguous, it simply printed the unambiguous part and beeped so that you had to decide what to do next. You could also list possible completions; for some reason this became attached to the ^D key in csh, which in later shells with Emacs-like bindings also deletes the next character, so that history has endowed zsh, like other shells, with the slightly odd combined behaviour:

  % cat yx 
Now move the cursor back one character onto the x and hit ^D twice and you see: yourfile. That doesn't work if you use vi-like bindings, or, obviously, if you've rebound ^D.

Next, it became possible to complete other items such as names of users, commands or hosts. Then zsh weighed in with menu completion, so you could keep on blindly hitting <TAB> until the right answer appeared, and never had to type an extra character yourself.

The next development was tcsh's, and then zsh's, programmable completion system; you could give instructions to the shell that in certain contexts, only certain items should be completed; for example, after cd, you would only want directories. In tcsh, there was a command called complete; each `complete ...' statement defined the completion for the arguments of a particular command, such as cd; the equivalent in zsh is compctl, which was inspired by complete but is different in virtually every significant detail. There is a perl script lete2ctl in the Misc directory of the shell distribution to help you convert from the tcsh to the zsh formats. You put a whole series of compctl commands into .zshrc, and everything else is done by the shell.

Zsh's system has become more and more sophisticated, and in version 3.1.6 a new completion system appeared which is supposed to do everything for you: you simply call a function, compinit, from an initialization file, after which zsh knows, for example, that gunzip should be followed by files ending in .gz. The new system is based on shell functions, an added bonus since they are extremely flexible and you already know the syntax. However, given the complexity it's quite difficult to get started writing your own completions now, and hard enough to know what to do to change the settings the way you like. The rest of the chapter should help.

I shall concentrate on the new completion system, which seems destined to take over completely from the old one eventually, now that the 3.1 release series has become the 4.0 production release. The old compctl command is still available, and old completion definitions will remain working in future versions of zsh --- in fact, on most operating systems which support dynamically linked libraries the old completion system is in a different file, which the shell loads when necessary, so there's very little overhead for this.

The big difference in the new system is that, instead of everything being set up once and for all when the shell starts, various bits of shell code are called after you hit <TAB>, to generate the completions there and then. There's enough new in the shell that all those unmemorable options to compctl (`-f' for files `-v' for variables and so on) can be replaced by commands that produce the list of completions directly; the key command in this case is called `compadd', which is passed this list and decides what to use to complete the word on the command line. So the simplest possible form of new completion looks roughly like this:

  # tell the shell that the function mycompletion can do completion
  # when called by the widget name my-completion-widget, and that
  # it behaves like the existing widget complete-word
  zle -C my-completion-widget .complete-word mycompletion
  
  # define a key that calls the completion widget
  bindkey '^x^i' my-completion-widget
  
  # define the function that will be called
  mycompletion() {
    # add a list of completions
    compadd alpha bravo charlie delta
  }
That's very roughly what the completion system is doing, except that the function is called _main_complete and calls a lot of other functions to do its dirty work based on the context where completion was called (all the things that compctl used to do), and the widgets are just the old completion widgets (`expand-or-complete' etc.) redefined and still bound to all the original keys. But, in case you hadn't guessed, there's more to it than that.

Here's a plan for the sections of this chapter.

  1. A broad description of completion and expansion, applying equally to old and new completion.
  2. How to configure completion using shell options. Most of this section applies to old completion, too, although I won't explicitly flag up any differences. After this, I shall leave the compctl world behind.
  3. How to start up new completion.
  4. The basics of how the new completion system works.
  5. How to configure it using the new `zstyle' builtin.
  6. Separate commands which do something other than the usual completion system, as well as some other editing widgets that have to do with completion.
  7. Matching control, a powerful way of deciding such things as whether to complete case-insensitively, to allow insertion of extra parts of words before punctuation characters, or to ignore certain characters in the word on the command line.
  8. How to write your own completion functions; you won't need to have too solid an understanding of all the foregoing just to do simple completions, but I will gradually introduce the full baroque splendour of how to make tags and styles work in your own functions, and how to make completion do the work of handling command arguments and options.
  9. Ends the chapter gracefully, on the old `beginning, middle, end' principle.

6.1: Completion and expansion

More things than just completion happen when you hit tab. The first thing that zsh tries to do is expand the line. Expansion was covered in a previous chapter: basically all the things described there are possible candidates for expanding in-line by the editor. In other words, history substitutions with bangs, the various expansions using `$' or backquote, and filename generation (globbing) can all take place, with the result replacing what was there on the command line:

  % echo $PWD<TAB>
    ->    echo /home/pws/zsh/projects/zshguide
  % echo `print $ZSH_VERSION`<TAB>
    ->    echo 3.1.7
  % echo !!<TAB>
    ->    echo echo 3.1.7
  % echo ~/.z*<TAB>
    ->    echo /home/pws/.zcompdump /home/pws/.zlogout
          /home/pws/.zshenv /home/pws/.zshrc                   
Note that the `~' also gets expanded in this case.

This is often a good time to remember the `undo' key, `^_' or `^Xu'; typing this will restore what was there before the expansion if you don't like the result. Many keyboards have a quirk that what's described as `^_' should be typed as control with slash, which you'd write `^/' except unfortunately that does something else; this is not zsh's fault. There's another half-exception, namely filename generation: paths like `~/file' don't get expanded, because you usually know what they refer to and it's usually convenient to leave them for use in completion. However, the `=cmdname' form does get expanded, unless you have NO_EQUALS set.

In fact, deciding whether expansion or completion takes place can sometimes be tricky, since things that would be expanded if they were complete, may need to be completed first; for example $PAT should probably be completed to $PATH, but it's quite possible there is a parameter $PAT too. You can decide which, if you prefer. First, the commands expand-word, bound to `^X*', and the corresponding command for listing what would be expanded, list-expand, bound to `^Xg', do expansion only --- all possible forms except alias expansion, including turning `~/file' into a full path.

From the other point of view, you can use commands other than expand-or-complete, the one bound by default to <TAB>, to perform only completion. The basic command for this is complete-word, which is not bound by default. It is quite sensible to bind this to `^I' (i.e. <TAB>) if you are happy to use the separate commands for expansion, i.e.

  # Now tab does only completion, not expansion
  bindkey '^i' complete-word
Furthermore, if you do this and use the new completion system, then as we shall see there is a way of making the completion system perform expansion --- see the description of the _expand completer below. In this case you have much more control over what forms of expansion are tried, and at what point, but you have to make sure you use complete-word, not expand-or-complete, else the standard expansion system will take over.

There's a close relative of expand-or-complete, expand-or-complete-prefix, not bound by default. The only difference is that it will ignore everything under and to the right of the cursor when completing. It's as if there was a space where the cursor was, with everything to be ignored shifted to the right (guess how it's implemented). Use this if you habitually type new words in the line before other words, and expect them to complete or expand on their own even before you've typed the space after them. Some other shells work this way all the time. To be more explicit:

  % ls
  filename1
  % ls filex
Move the cursor to the x and hit tab. With expand-or-complete nothing happens; it's trying to complete a file called `filex' --- or, with the option COMPLETE_IN_WORD set, it's trying to find a file whose name starts with `file' and ends with `x'. If you do
  bindkey '^i' expand-or-complete-prefix
and try the same experiment, you will find the whole thing is completed to `filename1x', so that the `x' was ignored, but not removed.

One possible trap is that the listing commands, both delete-char-or-list, bound by default to `^D' in emacs mode, and list-options, bound by default to `^D' in vi insert mode and the basic command for listing completions as it doesn't have the delete-character behaviour, do not show possible expansions, so with the default bindings you can use `^D' to list, then hit <TAB> and find that the line has been completely rewritten by some expansion. Using complete-word instead of expand-or-complete will of course fix this. If you know how to write new editor widgets (chapter 4), you can make up a function which tries list-expand, and if that fails tries list-options.

There are four completion commands I haven't mentioned yet: three are menu-complete, menu-expand-or-complete and reverse-menu-complete, which perform menu completion, where you can cycle through all possible completions by hitting the same key. The first two correspond to complete-word and expand-or-complete respectively, while the third has no real equivalent as it takes you backwards through a completion list. The effect of the third can't be reached just by setting options for menu completion, so it's a useful one to bind separately. I have it bound to `\M-\C-i', i.e. tab with the Meta key pressed down, but it's not bound by default.

The fourth is menu-select, which performs an enhanced form of menu completion called `menu selection' which I'll describe below when I talk about options. You have to make sure the zsh/complist module is loaded to use this zle command. If you use the style, zsh should be able to load this automatically when needed, as long as you have dynamic loading, which you probably do these days.

6.2: Configuring completion using shell options

There are two main ways of altering the behaviour of completion without writing or rewriting shell functions: shell options, as introduced in chapter 2, and styles, as introduced above. I shall first discuss the shell options, although as you will see some of these refer to the styles mechanism. Setting shell options affects every single completion, unless special care has been taken (using a corresponding style for the context, or setting an option locally) to avoid that.

In addition to the options which directly affect the completion system, completion is sensitive to various other options which describe shell behaviour. For example, if the option MAGIC_EQUAL_SUBST is set, so that arguments of all commands looking like `foo=~/file' have the `~' expanded as if it was at the start of an argument, then the default completion for arguments of commands not specially handled will try to complete filenames after the `='.

Needless to say, if you write completion functions you will need to worry about a lot of other options which can affect shell syntax. The main starting point for completion chosen by context (everything except the commands for particular completions bound separately to keystrokes) is the function _main_complete, which includes the effect of the following lines to make sure that at least the basic options are set up within completion functions:

  setopt glob bareglobqual nullglob rcexpandparam extendedglob unset
  unsetopt markdirs globsubst shwordsplit shglob ksharrays cshnullglob
  unsetopt allexport aliases errexit octalzeroes
but that by no means exhausts the possibilities. Actually, it doesn't include those lines: the options to set are stored in the array $_comp_options, with NO_ in front if they are to be turned off. You can modify this if you find you need to (and maybe tell the maintainers, too).

By the way, if you are wondering whether you can re-use the function _main_complete, by binding it to a different key with slightly different completion definitions, look instead at the description of the _generic command widget below. It's just a front-end to _main_complete which allows you to have a different set of styles in effect.

6.2.1: Ambiguous completions

The largest group of options deals with what happens when a completion is ambiguous, in other words there is more than one possible completion. The seven relevant options are as follows, as copied from the FAQ; many different combinations are possible:

  • with NO_BEEP set, that annoying beep goes away,
  • with NO_LIST_BEEP, beeping is only turned off for ambiguous completions,
  • with AUTO_LIST set, when the completion is ambiguous you get a list without having to type ^D,
  • with BASH_AUTO_LIST set, the list only happens the second time you hit tab on an ambiguous completion,
  • with LIST_AMBIGUOUS, this is modified so that nothing is listed if there is an unambiguous prefix or suffix to be inserted --- this can be combined with BASH_AUTO_LIST, so that where both are applicable you need to hit tab three times for a listing,
  • with REC_EXACT, if the string on the command line exactly matches one of the possible completions, it is accepted, even if there is another completion (i.e. that string with something else added) that also matches,
  • with MENU_COMPLETE set, one completion is always inserted completely, then when you hit TAB it changes to the next, and so on until you get back to where you started,
  • with AUTO_MENU, you only get the menu behaviour when you hit TAB again on the ambiguous completion.
  • 6.2.2: ALWAYS_LAST_PROMPT

    The option ALWAYS_LAST_PROMPT is set by default, and has been since an earlier 3.1 release of zsh; after listing a completion, the cursor is taken back to the line it was on before, instead of reprinting it underneath. The downside of this is that the listing will be obscured when you execute the command or produce a different listing, so you may want to unset the option. ALWAYS_LAST_PROMPT behaviour is required for menu selection to work, which is why I mention it now instead of in the ragbag below.

    When you're writing your own editor functions which invoke completion, you can actually cancel the effect of this with the widget end-of-list, which you would call as zle end-of-list (it's a normal editing function, not a completion function). You can also bind it to a key to use to preserve the existing completion list. On the other hand, if you want to control the behaviour within a completion function, i.e. to decide whether completion will try to return to the prompt above the list, you can manipulate it with the last_prompt element of the $compstate associative array, so for example:

      compstate[last_prompt]=''
    
    will turn off the behaviour for the completion in progress. $compstate is the place to turn if you find yourself wanting to control completion behaviour in this much detail; see the zshcompwid manual page.

    6.2.3: Menu completion and menu selection

    The most significant matter decided by the options above is whether or not you are using menu completion. If you are not, you will need to type the next character explicitly when completion is ambiguous; if you are, you just need to keep hitting tab until the completion you want appears. In the second case, of course, this works best if there are not too many possibilities. Use of AUTO_MENU or binding the menu-complete widget to a separate key-stroke gives you something of both worlds.

    A new variant of menu completion appeared in 3.1.6; in fact, it deserves the name menu completion rather more than the original form, but since that name was taken it is called `menu selection'. This allows you to move the cursor around the list of completions to select one. It is implemented by a separate module, zsh/complist; you can make sure this is loaded by putting `zmodload -i zsh/complist' in .zshrc, although it should be loaded automatically when the style menu is set as below. For it to be useful, you need two other things. The first is ALWAYS_LAST_PROMPT behaviour; this is suppressed if the whole completion list won't appear on the screen, since there's no line on the screen to go back to. However, menu selection does still work, by allowing you to scroll the list up and down. The second thing is that you need to start menu completion in any of the usual ways; menu selection is an addition to menu completion, not a replacement.

    Now you should set the following style:

      zstyle ':completion:*' menu select=<NUM>
    
    If an ambiguous completion produces at least <NUM> possibilities, menu selection is started. You can understand this best by trying it. One of the completions in the list, initially the top-leftmost, is highlighted and inserted into the line. By moving the cursor in the obvious directions (with wraparound at the edges), you change both the value highlighted and the value inserted into the line. When you have the value you want, hit return, which removes the list and leaves the inserted value. Hitting ^G (the editor function send-break) aborts menu selection, removes the list and restores the command line.

    Internally, zsh actually uses the parameter $MENUSELECT to supply the number and hence start menu selection. However, this is always initialised from the style as defined above, so you shouldn't set $MENUSELECT directly (unless you are using compctl, which will happily use menu selection). As with other styles, you can specify different values for different contexts; the default tag is checked if the current context does not produce a value for the style with whatever the current tag is. Note that the menu style also allows you to control whether menu completion is started at all, with or without selection; in other words, it is a style corresponding to the MENU_COMPLETE option.

    There is one other additional feature when using menu selection. The zle command accept-and-infer-next-history has a different meaning here; it accepts a completion, and then tries to complete again using menu selection. This is very useful with directory hierarchies, and in combination with undo gives you a simple file browser. You need to bind it in the special keymap menuselect; for example, I use

      bindkey -M menuselect '^o' accept-and-infer-next-history
    
    because the behaviour reminds me of what is usually bound to ^O in emacs modes, namely accept-line-and-down-history. Binding it like this has no effect on ^O in the normal keymaps. Try it out by entering menu selection on a set of files including directories, and typing ^O on one of the directories. You should immediately have the contents of that directory presented for the next selection, while undo is smart enough not only to remove that selection but return to completion on the parent directory.

    You can choose the manner in which the currently selected value in the completion list is highlighted using exactly the same mechanism as for specifying colours for particular types of matches; see the description of the list-colors style below.

    6.2.4: Other ways of changing completion behaviour

    COMPLETE_ALIASES

    If you set an alias such as

      alias pu=pushd
    
    then the alias `pu' will be expanded when the completion system is looking for the name of the command, so that it will instead find the command name `pushd'. This is quite useful to avoid having to define extra completions for all your aliases. However, it's possible you may want to define something different for the alias than for the command it expands to. In that case, you will need to set COMPLETE_ALIASES, and to make arrangements for completing after every alias which does not already match the name of a command. Hence `alias zcat="myzcat -dc"' will work with the option set, even if you haven't told the system about `myzcat', while `alias myzcat="gzip -dc"' will not work unless you do define a completion for myzcat: here `compdef _gzip myzcat' would probably be good enough. Without the option set, it would be the other way around: the first alias would not work without the extra compdef, but the second would.

    AUTO_REMOVE_SLASH

    This option is turned on by default. If you complete a directory name and a slash is added --- which it usually is, both to tell you that you have completed a directory and to allow you to complete files inside it without adding a `/' by hand --- and the next thing you type is not something which would insert or complete part of a file in that directory, then the slash is removed. Hence:

     % rmdir my<TAB>
       ->  rmdir mydir/
     % rmdir mydir/<RETURN>
       ->  `rmdir mydir' executed
     
    
    This example shows why this behaviour was added: some versions of `rmdir' baulk at having the slash after the directory name. On the other hand, if you continued typing after the slash, or hit tab again to complete inside mydir, then the slash would remain.

    This is at worst harmless under most circumstances. However, you can unset the option AUTO_REMOVE_SLASH if you don't like that behaviour. One thing that may cause slight confusion, although it is the same as with other suffixes (i.e. bits which get added automatically but aren't part of the value being completed), is that the slash is added straight away if the value is being inserted by menu completion. This might cause you to think wrongly that the completion is finished, and hence is unique when in fact it isn't.

    Note that some forms of completion have this type of behaviour built in, not necessarily with a slash, when completing lists of arguments. For example, enter `typeset ZSH_V<TAB>' and you will see `ZSH_VERSION=' appear, in case you want to assign something to the parameter; hitting space, which is not a possible value, makes the `=' disappear. This is not controlled by the AUTO_REMOVE_SLASH option, which applies only to directories inserted by the standard filename completion system.

    AUTO_PARAM_SLASH, AUTO_PARAM_KEYS

    These options come into effect when completing expressions with parameter substitutions. If AUTO_PARAM_SLASH is set, then any parameter expression whose value is the name of a directory will have a slash appended when completed, just as if the value itself had been inserted by the completion system.

    The behaviour for AUTO_PARAM_KEYS is a bit more complicated. Try this:

      print ${ZSH_V<TAB>
    
    You will find that you get the complete word `${ZSH_VERSION}', with the closing brace and (assuming there are no other matching parameters) a space afterwards. However, often after you have completed a parameter in this fashion you want to type something immediately after it, such as a subscript. With AUTO_PARAM_KEYS, if you type something at this point which seems likely to have to go after the parameter name, it will immediately be put there without you having to delete the intervening characters --- try it with `[', for example. Note that this only happens if the parameter name and any extra bits were added by completion; if you type everything by hand, typing `[' will not have this magic effect.

    COMPLETE_IN_WORD

    If this is set, completion always takes place at the cursor position in the word. For example if you typed `Mafile', went back over the `f', and hit tab, the shell would complete `Makefile', instead of its usual behaviour of going to the end of the word and trying to find a completion there, i.e. something matching `Mafile*'. Some sorts of new completion (such as filename completion) seem to implement this behaviour regardless of the option setting; some other features (such as the `_prefix' completer described below) require it, so it's a good thing to set and get used to, unless you really need to complete only at the end of the word.

    ALWAYS_TO_END

    If this is set, the cursor is always moved to the end of the word after it is completed, even if completion took place in the middle. This also happens with menu completion.

    6.2.5: Changing the way completions are displayed

    LIST_TYPES

    This is like the -F option to ls; files which appear in the completion listing have a trailing `/' for a directory, `*' for a regular file executable by the current process, `@' for a link, `|' for a named pipe, `%' for a character device and `#' for a block device. This option is on by default.

    Note that the identifiers only appear if the completion system knows that the item is supposed to be a file. This is automatic if the usual filename completion commands are used. There is also an option -f to the builtin compadd if you write your own completion function and want to tell the shell that the values may be existing files to apply LIST_TYPES to (though no harm is caused if no such files exist).

    LIST_PACKED, LIST_ROWS_FIRST

    These affect the arrangement of the completion listing. With LIST_PACKED, completion lists are made as compact as possible by varying the widths of the columns, instead of formatting them into a completely regular grid. With LIST_ROWS_FIRST, the listing order is changed so that adjacent items appear along rows instead of down columns, rather like ls's -x option.

    It is possible to alter both these for particular contexts using the styles list-packed and list-rows-first. The styles in such cases always override the option; the option setting is used if no corresponding style is found.

    Note also the discussion of completion groups later on: it is possible to have different types of completion appear in separate lists, which may then be formatted differently using these tag-sensitive styles.

    6.3: Getting started with new completion

    Before I go into any detail about new completion, here's how to set it up so that you can try it out. As I said above, the basic objects that do completions are shell functions. These are all autoloaded, so the shell needs to know where to find them via the $fpath array. If the shell was installed properly, and nothing in the initialization files has removed the required bits from $fpath, this should happen automatically. It's even possible your system sets up completion for you (Mandrake Linux 6.1 is the first system known to do this out of the box), in which case type `which compdef' and you should see a complete shell function --- actually the one which allows you to define additional completion functions. Then you can skip the next paragraph.

    If you want to load completion, try this at the command line:

      autoload -U compinit
      compinit
    
    which should work silently. If not, you need to ask your system administrator what has happened to the completion functions or find them yourself, and then add all the required directories to your $fpath. Either they will all be in one big directory, or in a set of subdirectories with the names AIX, BSD, Base, Debian, Redhat, Unix, X and Zsh; in the second case, all the directories need to be in $fpath. When this works, you can add the same lines, including any modification of $fpath you needed, to your .zshrc.

    You can now see if it's actually working. Type `cd ', then ^D, and you should be presented with a list of directories only, no regular files. If you have $cdpath set, you may see directories that don't appear with ls. As this suggests, the completion system is supplied with completions for many common (and some quite abstruse) commands. Indeed, the idea is that for most users completion just works without intervention most of the time. If you think it should when it doesn't, it may be a bug or an oversight, and you should report it.

    Another example on the theme of `it just works':

      tar xzf archive.tar.gz ^D
    
    will look inside the gzipped tar archive --- assuming the GNU version of tar, for which the `z' in the first set of arguments reports that the archive has been compressed with gzip --- and give you a list of files or directories you can extract. This is done in a very similar way to normal file completion; although there are differences, you can do completion down to any directory depth within the archive. (At this point, you're supposed to be impressed.)

    The completion system knows about more than just commands and their arguments, it also understands some of the shell syntax. For example, there's an associative array called $_comps which stores the names of commands as keys and the names of completion functions as the corresponding values. Try typing:

      print ${_comps[
    
    and then ^D. You'll probably get a message asking if you really want to see all the possible completions, i.e. the keys for $_comps; if you say `y' you'll see a list. If you insert any of those keys, then close the braces so you have e.g. `${_comps[mozilla]}' and hit return, you'll see the completion function which handles that command; in this case (at the time of writing) it's _webbrowser. This is one way of finding out what function is handling a particular command. If there is no entry --- i.e. the `print ${_comps[mycmd]}' gives you a blank line --- then the command is not handled specially and will simply use whatever function is defined for the `-default-' context, usually _default. Usually this will just try to complete file names. You can customize _default, if you like.

    Apart from -default-, some other of those keys for _comps also look like -this-: they are special contexts, places other than the arguments of a command. We were using the context called -subscript-; you'll find that the function in this case is called _subscript. Many completion functions have names which are simply an underscore followed by the command or context name, minus any hyphens. If you want a taster of how a completion function looks, try `which _subscript'; you may well find there are a lot of other commands in there that you don't know yet.

    It's important to remember that the function found in this way is at the root of how a completion is performed. No amount of fiddling with options or styles --- the stuff I'm going to be talking about for the next few sections --- will change that; if you want to change the basic completion, you will just have to write your own function.

    By the way, you may have old-style completions you want to mix-in --- or maybe you specifically don't want to mix them in so that you can make sure everything is working with the new format. By default, the new completion system will first try to find a specific new-style completion, and if it can't it will try to find a compctl-defined completion for the command in question. If all that fails, it will try the usual new-style default completion, probably just filename completion. Note that specific new-style completions take precedence, which is fair enough, since if you've added them you almost certainly don't want to go back and use the old form. However, if you don't ever want to try old-style completion, you can put the following incantation in your .zshrc:

      zstyle ':completion:*' use-compctl false
    
    For now, that's just black magic, but later I will explain the `style' mechanism in more detail and you will see that this fits in with the normal way of turning things off in new-style completion.

    6.4: How the shell finds the right completions

    6.4.1: Contexts

    The examples above show that the completion system is highly context-sensitive, so it's important to know how these contexts are described. This system evolved gradually, but everything I say applies to all versions of zsh with the major version 4.

    state we are at in completion, and is given as a sort of colon-separated path, starting with the least specific part. There's an easy way of finding out what context you are in: at the point where you want to complete something, instead type `^Xh', and it will tell you. In the case of the $_comps example, you will find,

      :completion::complete:-subscript-::
    
    plus a list of so-called `tags' and completion functions, which I'll talk about later. The full form is:
      :completion:<func>:<completer>:<command>:<argument>:<tag>
    
    where the elements may be missing if they are not set, but the colons will always be there to make pattern matching easier. Here's what the bits of the context mean after the :completion: part, which is common to the whole completion system.

    <func>
    is the name of a function from which completion is called --- this is blank if it was started from the standard completion system, and only appears in a few special cases, listed in section six of this chapter.

    <completer>
    is called `complete' in this case: this refers to the fact that the completion system can do more than just simple completion; for example, it can do a more controlled form of expansion (as I mentioned), spelling correction, and completing words with spelling mistakes. I'll introduce the other completers later; `complete' is the simplest one, which just does basic completion.

    <command>
    is the name of a command or other similar context as described above, here `-subscript-'.

    <argument>
    is most useful when <command> is the name of a real command; it describes where in the arguments to that command we are. You'll see how it works in a moment. Many of the simpler completions don't use this; only the ones with complicated option and argument combinations. You just have to find out with ^Xh if you need to know.

    <tag>
    describes the type of a completion, essentially a way of discriminating between the different things which can be completed at the same point on the command line.

    Now look at the context for a more normal command-argument completion, e.g. after cd; here you'll see the context `:completion::complete:cd::'. Here the command-name part of the context is a real command.

    For something more complicated, try after `cvs add' (it doesn't matter for this if you don't have the cvs command). You'll see a long and repetitive list of tags, for two possible contexts,

      :completion::complete:cvs:argument-rest:
      :completion::complete:cvs-add:argument-rest:
    
    The reason you have both is that the `add' is not only an argument to cvs, as the first context would suggest, it's also a subcommand in its own right, with its own arguments, and that's what the second context is for. The first context implies there might be more subcommands after `add' and its arguments which are completely separate from them --- though in fact CVS doesn't work that way, so that form won't give you any completions here.

    In both, `argument-rest' shows that completion is looking for another argument, the `rest' indicating that it is the list of arguments at the end of the line; if position were important (see `cvs import' for an example), the context would contain `argument-1', or whatever. The `cvs-add' shows how subcommands are handled, by separating with a hyphen instead of a colon, so as not to confuse the different bits of the context.

    Apart from arguments to commands and subcommands, arguments to options are another frequent possibility; for an example of this, try typing ^Xh after `dvips -o' and you will see the context `:completion::complete:dvips:option-o-1:'; this shows you are completing the first argument to dvips's -o option, (it only takes one argument) which happens to be the name of a file for output.

    6.4.2: Tags

    Now on to the other matter to do with contexts, tags. Let's go back and look at the output from the ^Xh help test after the cd command in full:

      tags in context :completion::complete:cd::
        local-directories path-directories  (_alternative _cd)
    
    Unlike the contexts considered so far, which tell you how completion arrived at the point it did, the tags describe the things it can complete here. In this case, there are three: directory-stack refers to entries such as `+1'; the directory stack is the set of directories defined by using the pushd command, which you can see by using the dirs command. Next, local-directories refers to subdirectories of the current working directory, while path-directories refers to any directories found by searching the $cdpath array. Each of the possible completions which the system offers belongs to one of those classes.

    In parentheses, you see the names of the functions which were called to generate the completions; these are what you need to change or replace if you want to alter the basic completion behaviour. Calling functions appear on the right and called functions on the left, so that in this case the function `_cd' was the function first called to handle arguments for the cd command, fitting the usual convention. Some standard completion functions have been filtered out of this list --- it wouldn't help you to know it had been through _main_complete and _complete, for example.

    Maybe it's already obvious that having the system treat different types of completion in different ways is useful, but here's an example, which gives you a preview of the `styles' mechanism, discussed later. Styles are a sort of glorified shell parameter; they are defined with the zstyle command, using a style name and possible values which may be an array; you can always define a style as an array, but some styles may simply use it as a string, joining together the arguments you gave it with spaces. You can also use the zstyle command, with different arguments, to retrieve their value, which is what the completion system itself does; there's no actual overlap with parameters and their values, so they don't get in the way of normal shell programming.

    Where styles differ from parameters is that they can take different values in different contexts. The first argument to the zstyle command gives a context; when you define a style, this argument is actually a pattern which will be matched against the current context to see if the style applies. The rule for finding out what applies is: exact string matches are preferred before patterns, and longer patterns are preferred before shorter patterns. Here's that example:

      zstyle ':completion:*:cd:*' tag-order local-directories \ 
        path-directories
    
    From the discussion of contexts above, the pattern will match any time an argument to the cd command is being completed. The style being set is called tag-order, and the values are the two tags valid for directories in cd.

    The tag-order style determines the order in which tags are tried. The value given above means that first local-directories will be completed; only if none can be completed will path-directories be tried. You can enter the command and try this; if you don't have $cdpath set up you can assign `cdpath=(~)', which will allow `cd foo' to change to a directory `~/foo' and allow completion of directories accordingly. Go to a directory other than ~; completion for cd will only show subdirectories of where you are, not those of ~, unless you type a string which is the prefix of a directory under ~ but not your current directory. For example,

      % cdpath=(~)
      % ls -F ~
      foo/    bar/
      % ls -F
      rod/    stick/
      # Without that tag-order zstyle command, you would get...
      % cd ^D
      bar/    foo/    rod/    stick/
      % zstyle ':completion:*:cd:*' tag-order local-directories \ 
         path-directories
      # now you just get the local directories, if there are any...
      % cd ^D
      rod/    stick/
    

    There's more you can do with the tag-order style: if you put the tags into the same word by quoting, for example "local-directories path-directories", then they would be tried at the same time, which in this case gives you the effect of the default. In fact, since it's too much work to know what tags are going to be available for every single possible completion, the default when there is no appropriate tag-order is simply to try all the tags available in the context at once; this was of course what was originally happening for completion after cd.

    Even if there is a tag-order specification, any tags not specified will usually be tried all together at the end, so you could actually have missed out path-directories from the end of the original example and the effect would have been the same. If you don't want that to happen, you can specify a `-' somewhere in the list of tags, which is not used as a tag but tells completion that only the tags in the list should be tried, not any others that may be available. Also, if you don't want a particular tag to be shown you can include `!tagname' in the values, and all the others but this will be included. For example, you may have noticed that when completing in command position you are offered parameters to set as well as commands etc.:

      Completing external command
      tex             texhash         texi2pdf        text2sf
      texconfig       texi2dvi        texindex        textmode
      texdoc          texi2dvi4a2ps   texlinks        texutil
      texexec         texi2html       texshow         texview
      Completing parameter
      TEXINPUTS                               texinputs
    
    (I haven't told you how to produce those descriptions, or how to make the completions for different tags appear separately, but I will --- see the descriptions of the `format' and `group-name' styles below.) If you set
      zstyle ':completion:*:-command-:*' tag-order '!parameters'
    
    then the last two lines will disappear from the completion. Of course, your completion list probably looks completely different from mine anyway. By the way, one good thing about styles is that it doesn't matter whether they're defined before or after completion is loaded, since styles are stored and retrieved by another part of the shell.

    To exclude more than one tag name, you need to include the names in the same word. For example, to exclude both parameters and reserved words the value would be '!parameters reserved-words', and not '!parameters' '!reserved-words', which would try completion once with parameters excluded, then again with reserved words excluded. Furthermore, tags can actually be patterns, or more precisely any word in one of the arguments to tag-order may contain a pattern, which will then be tried against all the valid tags to see if it matches. It's sometimes even useful to use `*' to match all tags, if you are specifying a special form of one of the tags --- maybe using a label, as described next --- in the same word. See the manual for all the tag names understood by the supplied functions.

    The tag-order style allows you to give tags `labels', which are a sort of alias, instructing the completion system to use a tag under a different name. You arrange this by giving the tag followed by a colon, followed by the label. The label can also have a hyphen in front, which means that the original tag name should be put in front when the label is looked up; this is really just a way of making the names look neater. The upshot is that by using contexts with the label name in, rather than the tag name, you can arrange for special behaviour. Furthermore, you can give an alternative description for the labelled tag; these show up with the format style which I'll describe below (and which I personally find very useful). You put the description after another colon, with any spaces quoted. It would look like this:

      zstyle ':completion:*:aliens:*' tag-order \ 
      'frooble:-funny:funny\ frooble' frooble
    
    which is used when you're completing for the command aliens, which presumably has completions tagged as `frooble' (if not, you're very weird). Then completion will first look up styles for that tag under the name frooble-funny, and if it finds completions using those styles it will list them with a description (if you are using format) of `funny frooble'. Otherwise, it will look up the styles for the tag under its usual name and try completion again. It's presumably obvious that if you don't have different styles for the two labels of the tag, you get the same completions each time.

    Rather than overload you with information on tags by giving examples of how to use tag labels now, I'll reserve this for the description of the ignored-patterns style below, which is one neat use for labels. In fact, it's the one for which it was invented; there are probably lots of other ones we haven't thought of yet.

    One important note about tag-order which I may not have made as explicit as I should have: it doesn't change which tags are actually valid in that completion. Just putting a tag name into the list doesn't mean that tag name will be used; that's determined entirely by the completion functions for a particular context. The tag-order style simply alters the order in which the tags which are valid are examined. Come back and read this paragraph again when you can't work out why tag-order isn't doing what you want.

    Note that the rule for testing patterns means that you can always specify a catch-all worst case by `zstyle "*" style ...', which will always be tried last --- not just in completion, in fact, since other parts of the shell use the styles mechanism, and without the `:completion:' at the start of the context this style definition will be picked up there, too.

    Styles like tag-order are the most important case where tags are used on their own. In other cases, they can be added to the end of the context; this is useful for styles which can give different results for different sets of completions, in particular styles that determine how the list of completions is displayed, or how a completion is to be inserted into the command line. The tag is the final element, so is not followed by a colon. A full context then looks something like `:completion::complete:cd::path-directories'. Later, you'll see some styles which can usefully be different for different tag contexts. Remember, however, that the tags part of the context, like other parts, may be empty if the completion system hasn't figured out what it should be yet.

    6.5: Configuring completion using styles

    You now know how to define a style for a particular context, using

      zstyle <context> <style> <value...>
    
    and some of the cases where it's useful. Before introducing other styles, here's some more detailed information. I already said that styles could take an array value, i.e. a set of values at the end of the zstyle command corresponding to the array elements, and you've already seen one case (tag-order) where that is useful. Many styles only use one value, however. There is a particularly common case, where you simply want to turn a value on or off, i.e. a boolean value. In this case, you can use any of `true', `yes', `on' or `1' for on and `false', `no', `off' or `0' for off. You define all styles the same way; only when they're used is it decided whether they should be a scalar, an array, or a boolean, nor is the name of a style checked to see if it is valid, since the shell doesn't know what styles might later be looked up. The same obviously goes for contexts.

    You can list existing styles (not individually, only as a complete list) using either `zstyle' or `zstyle -L'. In the second case, they are output as the set of zstyle commands which would regenerate the styles currently defined. This is also useful with grep, since you can easily check all possible contexts for a particular style.

    The most powerful way of using zstyle is with the option -e. This says that the words you supply are to be evaluated as if as arguments to eval. This should set the array $reply to the words to be used. So

      zstyle '*' days 'Monday Tuesday'
    
    and
      zstyle -e '*' days 'reply=(Monday Tuesday)'
    
    are equivalent --- but the intention, of course, is that in the second case the argument can return a different value each time so that the style can vary. It will usually be evaluated in the heat of completion, hence picking up all the editing parameters; so for example
      zstyle -e ':completion:*' mystyles 'reply=(${NUMERIC:-0})'
    
    will make the style return a non-zero integer (possibly indicating true) if you entered a non-zero prefix argument to the command, as described in chapter 4. However, the argument can contain any zsh code whatsoever, not just a simple assignment. Remember to quote it to prevent it from being turned into something else when the zstyle command line is run.

    Finally, you can delete a context for a style or a list of styles by

      zstyle -d [ <context-pattern> [ <style> ] ] ...
    
    --- note that although the first argument is a pattern, in this case it is treated exactly, so if you give the pattern `:completion:*:cd:*', only values given with exactly that pattern will be deleted, not other values whose context begins with `:completion:' and contains `:cd:'. The pattern and the style are optional when deleting; if omitted, all styles for the context, or all styles of any sort, are deleted. The completion system has its own defaults, but these are builtin, so anything you specify takes precedence.

    By the way, I did mention in passing in chapter 4 that you could use styles in just the same way in ordinary zle widgets (the ones created with `zle -N'), but you probably forgot about that straight away. All the instructions about defining styles and using them in your own functions from this chapter apply to zle functions. The only difference is that in that case the convention for contexts is that the context is set to `:zle:widget-name' for executing the widget widget-name.

    The rest of this section describes some useful styles. It's up to you to experiment with contexts if you want the style's values to be different in different places, or just use `*' if you don't care.

    6.5.1: Specifying completers and their options

    `Completers' are the behind-the-scenes functions that decide what sort of completion is being done. You set what completers to use with the `completer' style, which takes an array of completers to try in order. For example,

      zstyle ':completion:*' completer _complete _correct _approximate
    
    specifies that first normal completion will be tried (`_complete'), then spelling correction (`_correct'), and finally approximate completion (`_approximate'), which is essentially the combined effect of the previous two, i.e. complete the word typed but allow for spelling mistakes. All completers set the context, so inside _complete you will usually find `:completion::complete:...', inside correction `:completion::correct:..', and so on.

    There's a labelling feature for completers, rather like the one for tags described, but not illustrated in detail, above. You can put a completer in a list like this:

      zstyle ':completion:*' completer ... _complete:comp-label ...
    
    which calls the completer _complete, but pretends its name is comp-label when looking things up in styles, so you can try completers more than once with different features enabled. As with tags, you can write it like `_complete:-label', and the normal name will be prepended to get the name `complete-label' --- just a shortcut, it doesn't introduce anything new. I'll defer an example until you know what the completers do.

    Here is a more detailed description of the existing completers; they are all functions, so you can simply copy and modify one to make your own completer.

    _complete

    This is the basic completion behaviour, which we've been assuming up to now. Its major use is simply to check the context --- here meaning whether we are completing a normal command argument or one of the special `-context-' places --- and call the appropriate completion function. It's possible to trick it by setting the parameter `compcontext' which will be used instead of the one generated automatically; this can be useful if you write your own completion commands for special cases. If you do this, you should make the parameter local to your function.

    _approximate

    This does approximate completion: it's actually written as a wrapper for the _complete completer, so it does all the things that does, but it also sets up the system to allow completions with misspellings. Typically, you would want to try to complete without misspellings first, so this completer usually appears after _complete in the completers style.

    The main means of control is via the max-errors style. You can set this to the maximum number of errors to allow. An error is defined as described in the manual for approximate pattern matching: a character missing such as `rhythm' / `rhytm', an extra character such as `rhythm' / `rhythms', an incorrect character such as `rhythm' / `rhxthm', or a pair of characters transposed such as `rhythm' `rhyhtm' each count as one error. Approximation will first try to find a match or matches with one error, then two errors, and so on, up to and including the value of max-errors; the set of matches with the lowest number of errors is chosen, so that even if you set max-errors large, matches with a lower number of errors will always be preferred. The real problems with setting a large max-errors are that it will be slower, and is more likely to generate matches completely unlike what you want --- with typing errors, two or three are probably the most you need. Otherwise, there's always Mavis Beacon. Hence:

      % zstyle ':completion:*' max-errors 2
      # just for the sake of example...
      % zstyle ':completion:*' completer _approximate
      % ls
      ashes    sackcloth
      % echo siccl<TAB>
        -> echo sackcloth
      % echo zicc<TAB>
        <Beep.>
    
    because `s[i/a]c[k]cloth' is only two errors, while `[z/s][i/a]c[k]cloth' would be three, so doesn't complete.

    There's another way to give a maximum number of errors, using the numeric prefix specified with ESC-<digit> in Emacs mode, directly with number keys in vi command mode, or with universal-argument. To enable this, you have to include the string numeric as one of the values for max-errors --- hence this can actually be an array, e.g.

      zstyle ':completion:*:approximate:*' max-errors 2 numeric
    
    allows up to two errors automatically, but you can specify a higher maximum by giving a prefix to the completion command. So to continue the example above, enter the new zstyle and:
      % echo zicc<ESC-3><TAB>
        -> echo sackcloth
    
    because we've allowed three errors. You can start to see the problems with allowing too many errors: if you had the file `zucchini', that would be only one error away, and would be found and inserted before `sackcloth' was even considered.

    Note that the context is examined straightaway in the completer, so at this stage it is simply `:completion::approximate:::'; no more detailed contextual information is available, so it is not possible to specify different max-errors for different commands or tags.

    The final possibility as a value for the style is `not-numeric': that means if any numeric prefix is given, approximation will not be done at all. In the last example, completion would have to find a file beginning `zicc'.

    Other minor styles also control approximation. The style original, if true means the original value is always treated as a possible completion, even if it doesn't match anything and even if nothing else matched. Completing the original and the corrections use different tags, unimaginatively called original and corrections, so you can organise this with the tag-order style.

    Because the completions in this case usually don't match what's already on the command line, and may well not match each other, menu completion is entered straight away for you to pick a completion. You can arrange that this doesn't happen if there is an unambiguous piece at the start to insert first by setting the boolean style insert-unambiguous.

    Those last two styles (original and insert-unambiguous) are looked up quite early on, when the context for generating corrections is being set up, so that only the context up to the completer name is available. The completer name will be followed by a hyphen and the number of errors currently being accepted. So for trying approximation with one error the context is `:completion::approximate-1:::'; if that fails and the system needs to look for completion with two errors, the context will be `:completion::approximate-2:::', and so on; the same happens with correction and `correct-1', etc., for the completer described next.

    _correct

    This is very similar to _approximate, except that the context is `:completion::correct:*' (or `:completion::correct-<num>:*' when generating corrections, as described immediately above) and it won't perform completion, just spelling correction, so extra characters which the completer has to add at the end of the word on the line now count as extra errors instead of completing in the ordinary way: zicc is woefully far from sackcloth, seven errors, but ziccloth only counts three again. The _correct completer is controlled in just the same way as _approximate.

    There is a separate command which only does correction and nothing else, usually bound to `^Xc', so if you are happy using that you don't need to include _correct in the list of completers. If you do include it, and you also have _approximate, _correct should come earlier; _approximate is bound to generate all the matches _correct does, and probably more. Like other separate completion commands, it has its own context, here beginning `:completion:correct-word:', so it's easy to make this command behave differently from the normal completers.

    Old-timers will remember that there is another form of spelling correction built into the shell, called with `ESC-$' or `ESC-s'. This only corrects filenames and doesn't understand anything about the new completion mechanism; the only reason for using it is that it may well be faster. However, if you use the CORRECT or CORRECT_ALL shell options, you will be using the old filename correction mechanism; it's not yet possible to alter this.

    _expand

    This actually performs expansion, not completion; the difference was explained at the start of the chapter. If you use it, you should bind tab to complete-word, not expand-or-complete, since otherwise expansion will be performed before the completion mechanism is started up. As expansion should still usually be attempted before completion, this completer should appear before _complete and its relatives in the list of values for the completers style.

    The reason for using this completer instead of normal expansion is that you can control which expansions are performed using styles in the `:completion:*:expand:*' context. Here are the relevant styles:

    glob
    expands glob expressions, in other words does filename generation using wildcards.

    substitute
    expands expressions including and active `$' or backquotes.

    But remember that you need

      bindkey '^i' complete-word
    
    when using this completer as otherwise the built-in expansion mechanism which is run by the normal binding expand-or-complete will take over.

    You can also control how expansions are inserted. The tags for adding expansions are original (presumably self-explanatory), all-expansions, which refers to adding a single string containing all the possible expansions (the default, just like the editor function expand-word), and expansions, which refers to the results added one by one. By changing the order in which the tags are tried, as described for the tag-order style above, you can decide how this happens. For example,

      zstyle ':completion:*' completer _expand _complete
      zstyle ':completion::expand:*' tag-order expansions
    
    sets up for performing glob expansion via completion, with the expansions being presented one by one (usually via menu completion, since there is no common prefix). Altering expansions to all-expansions would insert the list, as done by the normal expansion mechanism, while altering it to `expansions original' would keep the one-at-a-time entry but also present the original string as a possibility. You can even have all three, i.e. the entire list as a single string becomes just one of the set of possibilities.

    There is also a sort style, which determines whether the expansions generated will be sorted in the way completions usually are, or left just as the shell produced them from the expansion (for example, expansion of an array parameter would produce the elements in order). If it is true, they will always be sorted, if false or unset never, and if it is menu they will be sorted for the expansions tag, but not for the all-expansions tag which will be a single string of the values in the original order.

    There is a slight problem when you try just to generate glob expansions, without substitute. In fact, it doesn't take much thought to see that an expression like `$PWD/*.c' doesn't mean anything if substitute is inactive; it must be active to make sense of such expressions. However, this is annoying if there are no matches: you end up being offered a completion with the expanded $PWD, but `*.c' still tacked on the end, which isn't what you want. If you use _expand mainly for globbing, you might therefore want to set the style subst-globs-only to true: if a completion just expands the parameters, and globbing does nothing, then the expansion is rejected and the line left untouched.

    The _expand completer will also use the styles

    accept-exact
    applies to words beginning with a `$' or `~'. Suppose there is a parameter `$foo' and a parameter `$foobar' and you have `$foo' on the line. Normally the completion system will perform completion at this point. However, with accept-exact set, `$foo' will be expanded since it matches a parameter.

    add-space
    means add a space after the expansion, as with a successful completion --- although directories are given a `/' instead. For finer control, it can be set to the word file, which means the space is only added if the expanded word matches a file that already exists (the idea being that, if it doesn't, you may want to complete further). Both true and file may be combined with subst, which prevents the adding of a space after expanding a substitution of the form `${...}' or `$(...)'.

    keep_prefix
    also addresses the question of whether a `~' or `$' should be expanded. If set, the prefix will be retained, so expanding `~/f*' to `~/foo' doesn't turn the `~' into `/home/pws'. The default is the value `changed', which is a half-way house been false and true: it means that if there was no other change in the word, i.e. no other possible expansion was found, the `~' or `$' will be expanded. If the effect of this style is that the expansion is the same as the unexpanded word, the next completer in the list after _expand will be tried.

    suffix
    is similar to keep_prefix. The `suffix' referred to is something after an expression beginning `~' or `$' that wouldn't be part of that expansion. If this style is set, and such a suffix exists, the expansion is not performed. So, for example, `~pw<TAB>' can be expanded to `~pws', but `~pw/' is not eligible for expansion; likewise `$fo' and `$fo/'. This style defaults to true --- so if you want _expand always to expand such expressions, you will need to set it to false yourself.

    An easier way of getting the sort of control over expansion which the _expand completer provides is with the _expand_word function, usually bound to \C-xe, which does all the things described above without getting mixed up with the other completers. In this case the context string starts `:completion:expand-word', so you can have different styles for this than for the _expand completer.

    Setting different priorities for expansion is one good use for completer labels, for example

      zstyle ':completion:*' completer _expand:-glob _expand:-subst
      zstyle ':completion:*:expand-glob:*' glob yes
      zstyle ':completion:*:expand-subst:*' substitute yes
    
    is the basic set up to make _expand try glob completions and failing that do substitutions, presenting the results as an expansion. You would almost certainly want to add details to help this along.

    _history

    This completes words from the shell's history, in other words everything you typed or had completed or expanded on previous lines. There are three styles that affect it, sort and remove-all-dups; they are described for the command widget _history_complete_word below. That widget essentially performs the work of this completer as a special keystroke.

    _prefix

    Strictly, this completer doesn't do completion itself, and should hence be in the group below starting with _match. However, it seems to do completion... Let me explain.

    Many shells including zsh have the facility to complete only the word before the cursor, which zsh completion jargon refers to as the `prefix'. I explained this above when I talked about expand-or-complete-prefix; when you use that instead of the normal completion functions, the word as it's finally completed looks like `<prefix><completion><suffix>' where the completion has changed `<prefix>' to `<prefix><completion>', ignoring <suffix> throughout.

    The _prefix completer lets you do this as part of normal completion. What happens is that the completers are evaluated as normal, from left to right, until a completion is found. If _prefix is reached, completion is then attempted just on the prefix. So if your completers are `_complete _prefix', the shell will first try completion on the whole word, prefix and suffix, then just on the prefix. Only the first `real' completer (_complete, _approximate, _correct, _expand, _history) is used.

    You can try prefix completion more than once simply by including _prefix more than once in the list of completers; the second time, it will try the second `real' completer in the list; so if they are `_complete _prefix _correct _prefix', you will get first ordinary completion, then the same for the prefix only, then ordinary correction, then the same for the prefix only. You can move either of the _prefix completers to the point in the sequence where you want the prefix-only version to be tried.

    The _prefix completer will re-look up the completer style. This means that you can use a non-default set of completers for use just with _prefix. Here, as described in the manual, is how to force _prefix only to be used as a last resort, and only with normal completion:

      zstyle ':completion:::::' completer _complete \ 
        <other-completers> _prefix
      zstyle ':completion::prefix:::' completer _complete
    
    The full contexts are shown, just to emphasise the form; as always, you can use wildcards if you don't care. In a case like this, you can use only _prefix as the completer, and completion including the suffix would never be tried; you then have to make sure you have the completer style for the prefix context, however, or no completion at all will be done.

    The completer labelling trick is again useful here: you can call _prefix more than once, wherever you choose in your list of completers, and force it to look up in a different context each time.

      zstyle ':completion:*' completer _complete _prefix:-complete \ 
        _approximate _prefix:-approximate
      zstyle ':completion:*:prefix-complete:*' completer _complete
      zstyle ':completion:*:prefix-approximate:*' completer _approximate
    
    This tries ordinary completion, then the same for the prefix only, then approximation, then the same for the prefix only. As mentioned in the previous paragraph, it is perfectly legitimate to leave out the raw _complete and _approximate completers and just use the forms with the _prefix prefix.

    One gotcha with the _prefix completer: you have to make sure the option COMPLETE_IN_WORD is set. That may sound counter-intuitive: after all, _prefix forces completion not to complete inside a word. The point is that without that option, completion is only ever tried at the end of the word, so when you type <TAB> in the middle of <prefix><suffix>, the cursor is moved to after the end of the suffix before the completion system has a chance to see what's there, and hence the whole thing is regarded as a prefix, with no suffix.

    There's one more style used with _prefix: `add-space'. This makes _prefix add a real, live space when it completes the prefix, instead of just pretending there was one there, hence separating the completed word from the original suffix; otherwise it would simply leave the resulting word all joined together, as expand-or-complete-prefix usually does.

    _ignored

    Like _prefix this is a bit of a hybrid, mopping up after completions which have already been generated. It allows you to have completions which have already been rejected by the style `ignored-patterns'. I'll describe that below, but it's effect is very simple: for the context given, the list of patterns you specify are matched against possible completions, and any that match are removed from the list. The _ignored completer allows you to retrieve those removed completions later in your completer list, in case nothing else matched.

    This is used by the $fignore mechanism --- a list of suffixes of files not normally to be completed --- which is actually built on top of ignored-patterns, so if you use that in the way familiar to current zsh users, where the ignored matches are shown if there are no unignored matches, you need the _ignored completer in your completer list.

    One slightly annoying feature with _ignored is if there is only a single possible completion, since it will then be unconditionally inserted. Hardly a surprise, but it can be annoying if you really don't want that choice. There is a style single-ignored which you can set to show --- just show the single ignored match, don't insert it --- or to menu --- go to menu completion so that TAB cycles you between the completion which _ignored produced and what you originally typed. The latter gives a very natural way of handling ignored files; it's sort of saying `well, I found this but you might not like it, so hit tab again if you want to go back to what you had before'.

    I said this was like _prefix, and indeed you can specify which completers are called for the _ignored completer in just the same way, by giving the completer style in the context `:completion:*:ignored:*'. That means my description has been a little over-simplified: _ignored doesn't really use the completions which were ignored before; rather, when it's called it generates a list of possibilities where the choices matched by ignore-patterns --- or internally using $fignore --- are not ignored. So it should really be called `_not_ignored', but it isn't.

    _match

    This and the remaining completers are utilities, which affect the main completers given above when put into the completion list rather than doing completion themselves.

    The _match completer should appear after _complete; it is a more flexible form of the GLOB_COMPLETE option. In other words, if _complete didn't succeed, it will try to match the word on the line as a pattern, not just a fixed string, against the possible completions. To make it work like normal completion, it usually acts as if a `*' was inserted at the cursor position, even if the word already contains wildcards.

    You can control the addition of `*' with the `match-original' style; the normal behaviour occurs if this is unset. If it is set to `only', the `*' is not inserted, and if it is `true', or actually any other string, it will try first without the `*', then with. For example, consider typing `setopt c*ect<TAB>' with the _match completer in use. Normally this will produce two possibilities, `correct' and `correctall'. After setting the style,

      zstyle ':completion::match:*' original only
    
    no `*' would be inserted at the place where you hit `TAB', so that `correct' is the only possible match.

    The _match completer uses the style insert-unambiguous in just the same way as does _approximate.

    _all_matches

    This has a similar effect to performing expansion instead of completion: all the possible completions are inserted onto the command line. However, it uses the results of ordinary contextual completion to achieve this. The normal way that the completion system achieves this is by influencing the behaviour of any subsequent completers which are called --- hence you will need to put _all_matches in the list of completers before any which you would like to have this behaviour.

    You're unlikely to want to do this with every type of completion, so there are two ways of limiting its effect. First, there is the avoid-completer style: you can set this to a list of completers which should not insert all matches, and they will be handled normally.

    Then there is the style old-matches. This forces _all_matches to use an existing list of matches, if it exists, rather than what would be generated this time round. You can set the style to only instead of true; in this case _all_matches will never apply to the completions which would be generated this time round, it will only use whatever list of completions already exists.

    This can be a nuisance if applied to normal completion generation --- the usual list would never be generated, since _all_matches would just insert the non-existent list from last time --- so the manual recommends two other ways of using the completer with this style. First, you can add a condition to the use of the style:

      zstyle -e ':completion:*' old-matches 'reply=(${NUMERIC:-false})'
    
    This returns false unless there is a non-zero numeric argument; if you type <ESC>1 in emacs mode, or just 1 in vi mode, before completion, it will insert all the values generated by the immediately preceding completion.

    Otherwise, you can bind _all_matches separately. This is probably the more useful; copying the manual entry:

      zle -C all-matches complete-word _generic
      bindkey '^Xa' all-matches
      zstyle ':completion:all-matches:*' completer _all_matches
      zstyle ':completion:all-matches:*' old-matches only
    
    Here we generate ourselves a new completion based on the complete-word widget, called all-matches --- this name is arbitrary but convenient. We bind that to the keystroke ^Xa, and give it two special styles which normal completion won't see. For the completer we set just _all_matches, and for old-matches we set only; the effect is that ^Xa will only ever have the effect of inserting all the completions which were generated by the last completion, whatever that was --- it does not have to be an ordinary contextual completion, it may be the result of any completion widget.

    _list

    If you have this in the list of completers (at the beginning is as good as anything), then the first time you try completion, you only get a list; nothing changes, not even a common prefix is inserted. The second time, completion continues as normal. This is like typing ^D, then tab, but using just the one key. This differs from the usual AUTO_LIST behaviour in that is entirely irrespective of whether the completion is ambiguous; you always get the list the first time, and it always does completion in the usual way the second time.

    The _list completer also uses the condition style, which works a bit like the styles for the _expand completer: it must be set to one of the values corresponding to `true' for the _list delaying behaviour to take effect. You can test for a particular value of $NUMERIC or any other condition by using the -e option of zstyle when defining the style.

    Finally, the boolean style word is also relevant. If false or unset, _list examines the whole line when deciding if it has changed, and hence completion should be delayed until the next keypress. If true, it just examines the current word. Note that _list has no knowledge of what happens between those completion calls; looking at the command line is its only resource.

    _menu

    This just implements menu completion in shell code; it should come before the `real' completion generators in the completers style. It ignores the MENU_COMPLETION option and other related options and the normal menu-completion widgets don't work well with it. However, you can copy it and write your own completers.

    _oldlist

    This completer is most useful when you are in the habit of using special completion functions, i.e. commands other than the standard completion system. It is able to hang onto an old completion list which would otherwise be replaced with a newly generated one. There are two aspects to this.

    First, listing. Suppose you try to complete something from the shell history, using the command bound to `ESC-/'. For example, I typed `echo ma<ESC-/>' and got `max-errors'. At this point you might want to list the possible completions. Unfortunately, if you type ^D, it will simply list all the usual contextual completions --- for the echo command, which is not handled specially, these are simply files. So it doesn't work. By putting the _oldlist completer into the completers style before _complete, it does work, because the old list of matches is kept for ^D to use.

    In this case, you can force old-listing on or off by setting the old-list style to always or never; usually it shows the listing for the current set of completions if that isn't already displayed, and otherwise generates the standard listing. You can even set the value of old-list to a list of completers which will always have their list kept in this way.

    The other place where _oldlist is useful is in menu completion, where exactly the same problem occurs: if you generate a menu from a special command, then try to cycle through by hitting tab, completion will look for normal contextual matches instead. There's a way round this time --- use the special command key repeatedly instead of tab. This is rather tedious with multiple key sequences. Again, _oldlist cures this, and again you can control the behaviour with a style, old-menu, which takes a boolean value (it is on by default). As Orwell put it, oldlisters unbellyfeel menucomp.

    Ordering completers

    I've given various suggestions about the order in which completers should come in, which might be confusing. Here, therefore, is a suggested order; just miss out any completers you don't want to use:

      _all_matches _list _oldlist _menu _expand _complete _match
        _ignored _correct _approximate _prefix 
    
    Other orders are certainly possible and maybe even useful: for example, the _all_matches completer applies to all the completers following not listed in the avoid-completer style, so you might have good reason to shift it further down the list.

    Here's my example of labels for completers, which I mentioned just above the list of different completers, whereby completers can be looked up under different names.

      zstyle ':completion:*' completer _complete _approximate:-one \ 
        _complete:-extended _approximate:-four
      zstyle ':completion:*:approximate-one:*' max-errors 1
      zstyle ':completion:*:complete-extended:*' \ 
        matcher 'r:|[.,_-]=* r:|=*'
      zstyle ':completion:*:approximate-four:*' max-errors 4
    
    This tries the following in order.
    1. Ordinary, no-frills completion.
    2. Approximation with one error, as given by the second style.
    3. Ordinary completion with extended completion turned on, as given by the third style. Sorry, this will be a black box until I talk about the matcher style later on; for now, you'll just have to take my word for it that this style allows the characters in the square brackets to have a wildcard in front, so `a-b' can complete to `able-baker', and so on.
    4. Approximation with up to four errors, as given by the final style.
    Here's a rather bogus example. You have a directory containing:
      foobar  fortified-badger  frightfully-barbaric
    
    Actually, it's not bogus at all, since I just created one. First try `echo foo<TAB>'; no surprise, you get `foobar'. Now try completing with `fo-b<TAB>' after the `echo': basic completion fails, it gets to `_approximate:-one' and finds that it's allowed one error, so accepts the completion `foobar' again. Now try `fort-ba<TAB>'. This time nothing kicks in until the third completion, which effectively allows it to match `fort*-ba*<TAB>', so you see `fortified-badger' (no, I've never seen one myself, but they're nocturnal, you know). Finally, try `fortfully-ba<TAB>'; the last entry, which allows up to four errors, thoughtfully corrects `or' to `righ', and you get `frightfully-barbaric'. All right, the example is somewhat unhinged, but I think you can see the features are useful. If it makes you feel better, it took me four or five attempts to get the styles right for this.

    6.5.2: Changing the format of listings: groups etc.

    format

    You can use this style if you want to find out where the completions in a completion listing come from. The most basic use is to set it for the descriptions tag in any completion context. It takes a string value in which `%d' should appear; this will be replaced by a description of whatever is being completed. For example, I use:

      zstyle ':completion:*:descriptions' format 'Completing %d'
    
    and if I type cd^D, I see a listing like this (until I define the group-name style, that is):
      Completing external command
      Completing builtin command
      Completing shell function
      cd                cddbsubmit        cdp               cdrecord
      cdctrl            cdecl             cdparanoia        cdswap
      cdda2wav          cdmatch           cdparanoia-yaf
      cddaslave         cdmatch.newer     cdplay
      cddbslave         cdot              cdplayer_applet
    
    The descriptions at the top are related to the tag names --- usually there's a unique correspondence --- but are in a more readable form; to get the tag names, you need to use ^Xh. You will no doubt see something different, but the point is that the completions listed are a mixture of external commands (e.g. cdplay), builtin commands (cd) and shell functions (cdmatch, which happens to be a leftover from old-style completion, showing you how often I clean out my function directory), and it's often quite handy to know what you have.

    You can use some prompt escapes in the description, specifically those that turn on or off standout mode (`%S', `%s'), bold text (`%B', `%b'), and underlined text (`%U', `%u'), to make the descriptions stand out from the completion lists.

    You can set this for some other tag than descriptions and the format thus defined will be used only for completions of that tag.

    group-name, group-order

    In the format example just above, you may have wondered if it is possible to make the different types of completion appear separately, together with the description. You can do this using groups. They are also related to tags, although as you can define group names via the group-name style it is possible to give different names for completion in any context. However, to start off with it is easiest to give the value of the style an empty string, which means that group names are just the names of the tags. In other words,

      zstyle ':completion:*' group-name ''
    
    assigns a different group name for each tag. Later, you can fine-tune this with more specific patterns, if you decide you want various tags to have the same group name. If no group name is defined, the group used is called `-default-', so this is what was happening before you issued the zstyle command above; all matches were in that group.

    The reason for groups is this: matches in the same group are shown together, matches in different groups are shown separately. So the completion list from the previous example, with both the format and group-name styles set, becomes:

      Completing external command
      cdctrl            cddbsubmit        cdparanoia        cdrecord
      cdda2wav          cdecl             cdparanoia-yaf
      cddaslave         cdot              cdplay
      cddbslave         cdp               cdplayer_applet
      Completing builtin command
      cd
      Completing shell function
      cdmatch                 cdmatch.newer           cdswap
    
    which you may find more helpful, or you may find messier, depending on deep psychological factors outside my control.

    If (and only if) you are using group-name, you can also use group-order. As its name suggests, it determines the order in which the different completion groups are displayed. It's a little like tag-order, which I described when tags were first introduced: the value is just a set of names of groups, in the order you want to see them. The example from the manual is relevant to the listing I just showed:

      zstyle ':completion:*:-command-' group-order \ 
          builtins functions commands
    
    --- remember that the `-command-' context is used when the names of commands, rather than their arguments, are being completed. Not surprisingly, that listing now becomes:
      Completing builtin command
      cd
      Completing shell function
      cdmatch                 cdmatch.newer           cdswap
      Completing external command
      cdctrl            cddbsubmit        cdparanoia        cdrecord
      cdda2wav          cdecl             cdparanoia-yaf
      cddaslave         cdot              cdplay
      cddbslave         cdp               cdplayer_applet
    
    and if you investigate the tags available by using ^Xh, you'll see that there are others such as aliases whose order we haven't defined. These appear after the ones for which you have defined the order and in some order decided by the function which generated the matches.

    tag-order

    As I already said, I've already described this, but it's here again for completeness.

    verbose, auto-description

    These are relatives of format as they add helpful messages to the listing. If verbose is true, the function generating the matches may, at its discretion, decide to show more information about them. The most common case is when describing options; the standard function _describe that handles descriptions for a whole lot of options tests the verbose style and will print information about the options it is completing.

    You can also set the string style auto-description; it too is useful for options, in the case that they don't have a special description, but they do have a single following argument, which completion already knows about. Then the description of the argument for verbose printing will be available as `%d' in auto-describe, so that something like the manual recommendation `specify: %d' will document the option itself. So if a command takes `-o <output-file>' and the argument has the description `output file', the `-o', when it appears as a possible completion, will have the description `specify: output file' if it does not have its own description. In fact, most options recognized by the standard completion functions already have their own descriptions supplied, and this is more subtlety than most people will probably need.

    list-colors

    This is used to display lists of matches for files in different colours depending on the file type. It is based on the syntax of the $LS_COLORS environment variable, used by the GNU version of ls. You will need a terminal which is capable of displaying colour such as a colour xterm, and should make sure the zsh/complist library is loaded, (it should be automatically if you are using menu selection set up with the menu style, or if you use this style). But you can make sure explicitly:

      zmodload -i zsh/complist
    
    The -i keeps it quiet if the module was already loaded. To install a standard set of default colours, you can use:
      zstyle ':completion:*' list-colors ''
    
    --- note the use of the `default' tag --- since a null string sets the value to the default.

    If that's not good enough for you, here are some more detailed instructions. The parameter $ZLS_COLORS is the lowest-level part of the system used by zsh/complist. There is a simple builtin default, while having the style set to the empty string is equivalent to:

      ZLS_COLORS="no=00:fi=00:di=01;34:ln=01;36:\ 
      pi=40;33:so=01;35:bd=40;33;01:cd=40;33;01:\ 
      ex=01;32:lc=\e[:rm=m:tc=00:sp=00:ma=07:hi=00:du=00
    
    It has essentially the same format as $LS_COLORS, and indeed you can get a more useful set of values by using the dircolors command which comes with ls:
      ZLS_COLORS="no=00:fi=00:di=01;34:ln=01;36:\ 
      pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:\ 
      or=40;31;01:ex=01;32:*.tar=01;31:*.tgz=01;31:\ 
      *.arj=01;31:*.taz=01;31:*.lzh=01;31:*.zip=01;31:\ 
      *.z=01;31:*.Z=01;31:*.gz=01;31:*.deb=01;31:\ 
      *.jpg=01;35:*.gif=01;35:*.bmp=01;35:*.ppm=01;35:\ 
      *.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:\ 
      *.mpg=01;37:*.avi=01;37:*.gl=01;37:*.dl=01;37:"
    
    You should see the manual for the zsh/complist module for details, but note in particular the addition of the type `ma', which specifies how the current match in menu selection is displayed. The default for that is to use standout mode --- the same effect as the sequence %S in a prompt, which you can display with `print -P %Sfoo'.

    However, you need to define the style directly, since the completion always uses that to set $ZLS_COLORS; otherwise it doesn't know whether the value it has found has come from the user or is a previous value taken from some style. That takes this format:

      zstyle ':completion:*' list-colors "no=00" "fi=00" ...
    
    You can use an already defined $LS_COLORS:
      zstyle ':completion:*' list-colors ${(s.:.)LS_COLORS}
    
    (which splits the parameter to an array on colons) as $LS_COLORS is still useful for ls, even though it's not worth setting $ZLS_COLORS directly. This should mean GNU ls and zsh produce similar-looking lists.

    There are some special effects allowed. You can use patterns to tell how filenames are matched: that's part of the default behaviour, in fact, for example '*.tar=01;31' forces tar files to be coloured red. In that case, you are limited to `*' followed by a string. However, there's a way of specifying colouring for any match, not just files, and for any pattern: use =<pat>=<col>. Here are two ways of getting jobs coloured red in process listings for the `kill' command.

      zstyle ':completion:*:*:kill:*' list-colors '=%*=01;31'
    
    This uses the method just described; jobs begin with `%'.
      zstyle ':completion:*:*:kill:*:jobs' list-colors 'no=01;31'
    
    This uses the tag, rather than the pattern, to match the jobs lines. It has various advantages. Because you are using the tag, it's much easier to alter this for all commands using jobs, not just kill --- just miss out `kill' from the string. That wasn't practical with the other method because it would have matched too many other things you didn't want. You're not dependent on using a particular pattern, either. And finally, if you try it with a `format' description you'll see that that gets the colour, too, since it matched the correct tag. Note the use of the `no' to specify that this is to apply for a normal match; the other two-letter codes for file types aren't useful here.

    However, there is one even more special effect you can use with the general pattern form. By turning on `backreferences' with `(#b)' inside the pattern, parentheses are active and the bits they match can be coloured separately. You do this by extending the list of colours, each code preceded by an `=' sign, and the extra elements will be used to colour what the parenthesis matched. Here's another example for `kill', which turns the process number red, but leaves the rest alone.

      zstyle ':completion:*:*:kill:*:processes' list-colors \ 
        '=(#b) #([0-9]#)*=0=01;31'
    
    The hieroglyphics are extended globbing patterns. You should note that the EXTENDED_GLOB option is always on inside styles --- it's required for the `#b' to take effect. In particular, `#' means `zero or more repetitions of the previous bit of the pattern' with extended glob patterns; see the globbing manual page for full details.

    ignored-patterns

    Many shells, including zsh, have a parameter $fignore, which gives a list of suffixes; filenames ending in any of these are not to be used in completion. A typical value is:

      fignore=(.o \~ .dvi)
    
    so that normal file completion will not produce object files, EMACS backup files, or TeX DVI files.

    The ignored-patterns style is an extension of this. It takes an array value, like fignore, but with various differences. Firstly, these values are patterns which should match the whole value to be completed, including prefixes (such as the directory part of a filename) as well as suffixes. Secondly, they apply to all completions, not just files, since you can use the style mechanism to tune it to apply wherever you want, down to particular tags.

    Hence you can replace the use of $fignore above with the following:

      zstyle ':completion:*:files' ignored-patterns '*?.o' '*?~' '*?.dvi'
    
    for completion contexts where the tag `files' is in use. The extra `?'s are because $fignore was careful only to apply to real suffixes, i.e. strings which had something in front of them, and the `?' forces there to be at least one character present.

    Actually, this isn't quite the same as $fignore, since there are other file tags than files; apart from those for directories, which you've already met, there are globbed-files and all-files. The former is for cases where a pattern is specified by the completion function, for example `*.dvi' for files following the command name dvips. These don't use this style, because the pattern was already sufficiently specified. This follows the behaviour for $fignore in the old completion system. Another slight difference, as I said above when discussing the _ignored completer, is that you get to choose whether you want to see those ignored files if the normal completions fail, by having _ignored in the completer list or not.

    The other tag, all-files, applies when a globbed-files tag failed, and says any old file is good enough in that case; you can arrange how this happens with the tag-order style. In this example,

      zstyle ':completion:*:*:dvips:argument*' \ 
        tag-order globbed-files all-files
    
    is enough to say that you want to see all files if no files were produced from the pattern, i.e. if there were no `*.dvi' files in the directory. Finally the point of this ramble: as the all-files tag is separate from the files tag, in this case you really would see all files (except for those beginning with a `.', as usual). You might find this useful, but you can easily make the all-files tag behave the same way as files:
      zstyle ':completion:*:(all-|)files' ignored-patterns ...
    

    Here's the example of using tag labels I promised earlier; it's simply taken from the manual. To refresh your memory: tag labels are a way of saying that tags should be looked up under a different name. Here we'll do:

      zstyle ':completion:*:*:-command-:*' tag-order 'functions:-non-comp'
    
    This applies in command position, from the special `-command-' context, the place where functions occur most often, along with other types of command which have their own tags. This says that when functions are first looked up, they are to be looked up with the name `functions-non-comp' --- remember that with a hyphen as the first character of the label part, the bit after the colon, the functions tag name itself, the bit before the colon, is to be stuck in front to give the full label name `functions-non-comp'. We can use it as follows:
      zstyle ':completion:*:functions-non-comp' ignored-patterns '_*'
    
    In the context of this tag label, we have told completion to ignore any patterns --- i.e. any function names --- beginning with an underscore. What happens is this: when we try completion in command position, tag-order is looked up and finds we want to try functions first, but under the name functions-non-comp; this completes functions apart from ones beginning with an underscore (presumably completion functions you don't want to run interactively). Since tag-order normally tries all the other tags, unless it was told not to, in this case all the normal command completions will appear, including functions under their normal tag name, so this just acts as a sort of filter for the first attempt at completion. This is typically what tag labels are intended for --- though maybe you can think up a lot of other uses, since the idea is quite powerful, being backed up by the style mechanism.

    You way wonder why you would want to ignore such functions at this point. After all, you're only likely to be doing completion when you've already typed the first character, which either is `_' or it isn't. It becomes useful with correction and approximation --- particularly since many completion functions are similar to the names of the commands for which they handle completion. You don't want to be offered `_zmodload' as a completion if you really want `zmodload'. The combination of labels and ignored patterns does this for you.

    You can generalise this using another feature: tags can actually be patterns, which I mentioned but didn't demonstrate. Here's a more sophisticated version of the previous example, adapted from the manual:

      zstyle ':completion:*:*:-command-:*' tag-order \ 
      'functions:-non-comp:non-completion\ functions *' functions
    
    It's enhanced so that completion tries all other possible tags at the same time as the labelled functions. However, it only ever tries a tag once at each step, so the `*' doesn't put back functions as you might expect --- that's still tried under the label `functions-non-comp', and the ignored-patterns style we set will still work. In the final word, we try all possible functions, so that those beginning with an underscore will be restored.

    Use of the `_ignored' completer can allow you to play tricks without having to label your tags:

      zstyle ':completion:*' completer _complete _ignored
      zstyle ':completion:*:functions' ignored-patterns '_*'
    
    Now anywhere the functions tag is valid, functions matching `_*' aren't shown until completion reaches the `_ignored' in the completer list. Of course, you should manipulate the completer list the way you want; this just shows the bare bones.

    prefix-hidden, prefix-needed

    You will know that when the shell lists matches for files, the directory part is removed. The boolean style prefix-hidden extends this idea to various other types of matches. The prefixes referred to are not just any old common prefix to matches, but only some places defined in the completion system: the - prefix to options, the `%' prefix to jobs, the - or + prefix to directory stack entries are the most commonly used.

    The prefix-needed applies not to listings, but instead to what the user types on the command line. It says that matches will only be generated if the user has typed the prefix common to them. It applies on broadly the same occasions as prefix-hidden.

    list-packed, list-rows-first, accept-exact, last-prompt, menu

    The first two of these have already been introduced, and correspond to the LIST_PACKED and LIST_ROWS_FIRST options. The accept-exact and last-prompt styles correspond essentially to the REC_EXACT and ALWAYS_LAST_PROMPT options in the same way.

    The style menu roughly corresponds to the MENU_COMPLETE option, but there is also the business of deciding whether to use menu selection, as described above. These two uses don't interfere with each other --- except that, as I explained, menu completion must be started to use menu selection --- so a value like `true select=6' is valid; it turns on menu completion for the context, and also activates menu selection if there are at least 6 choices.

    There are some other, slightly more obscure, choices for menu:

    yes=num
    turn on menu completion only if there are at least num matches;

    no=num
    turn off menu completion if there are as many as num matches;

    yes=long
    turn on menu completion if the list does not fit on the screen, and completion was attempted;

    yes=long-list
    the same, but do it even if listing, not completion, was attempted;

    select=long
    like yes=long, but this time turn on menu selection, too;

    select=long-list
    like yes=long-list, but turn on menu selection, too.
    In case your eyes glazed over before the end, here's a full description of the last one, select=long-list, which is quite useful: if you are attempting completion or even just listing completions, and the list of matches would be too long to fit on the screen, then menu selection is turned on, so that you can use the cursor keys (and other selection keys) to move up and down the list. Generally, the above possibilities can be combined, unless the combined effect wouldn't work.

    As always, yes and true are equivalent, as are no and false. It just hurts the eyes of programmers to read something which appears to assign a value to true.

    hidden

    This is a little obscure for most users. Its context should be restricted to specific tags; any corresponding matches will not be shown in completion listings, but will be available for inserting into the command line. If its value is `true', then the description for the tag may still appear; if the value is `all', even that is suppressed. If you don't want the completions even to be available for insertion, use the tag-order style.

    6.5.3: Styles affecting particular completions

    The styles listed here are for use only with certain completions as noted. I have not included the styles used by particular completers, which are described with the completer in question in the subsection `Specifying completers and their options'. I have also not described styles used only in separate widgets that do completion; the relevant information is all together in the next section.

    Filenames (1): patterns: file-patterns

    It was explained above for the tag-order style that when a function uses pattern matching to generate file completions, such as all *.ps files or all *.gz files, the three tags globbed-files, directories and all-files are tried, in that order.

    The file-patterns style allows you to specify a pattern to override whatever would be completed, even in what would otherwise be a simple file completion with no pattern. Since this can easily get out of hand, the best way of using this style is to make sure that you specify it for a narrowly enough defined context. In particular, you probably want to restrict it to completions for a single command and for a particular one of the tags usually applying to files. As always, you can use ^Xh to find out what the context is. It has a labelling mechanism --- you can specify a tag with a pattern for use in looking up other styles. Hence `*.o:object-files' gives a pattern `*.o' and a tag name `object-files' by which to refer to these.

    The patterns you specify are tried in order; you don't need to use tag-order. In fact file-patterns replicates its behaviour in that you can put patterns in the same word to say they should be tried together, before going on to the pattern(s) in the next word. Also, you can give a description after a second colon in the same way. Indeed, since file-patterns gets its hands on the tags first, any ordering defined there can't be overridden by tag-order.

    So, for example, after

      zstyle ':completion:*:*:foo:*:*' file-patterns \ 
        '*.yo:yodl-files:yodl\ files *(-/):directories'
    
    the command named `foo' will complete files ending in `.yo', as well as directories. For once, you don't have to change the completer to alter what's completed: `foo' isn't specially handled, so it causes default completion, and that means completing files, so that file-patterns is active anyway.

    Here's a slightly enhanced example; it shows how file-patterns can be used instead of tag-order to offer the tags in the order you want.

      zstyle ':completion:*:*:foo:*:*' file-patterns \ 
        '*.yo:yodl-files:yodl\ files' '*(-/):directories:directories' \ 
        '^*.yo(-^/):other-files:other\ files'
    
    Completion will first try to show you only `.yo' files, if there are any; otherwise it will show you directories, if there are any; otherwise it will show you any other files: `^*.yo(-^/)' is an extended glob to match any file which doesn't end in `.yo' and which isn't a directory and doesn't link to a directory. As always, you can cycle through the sets of possibilities using the `_next_tag' completion command.

    Note that file-patterns is an exception to the general rule that styles don't determine which tags are called only where they're called, or what their behaviour is: this time, you actually get to specify the set of tags which will be used. This means it doesn't use the the standard file tags (unless you use those names yourself, of course), just `files' if you don't specify one. Hence it's good style to add the tags, following colons, although it'll work without.

    Another thing to watch out for is that if there is already a completion which handles a file type --- for example, if we had tried to alter the effect of file completion for the `yodl' command instead of the fictitious `foo' --- the results may well not be quite what you want.

    Another feature is that `%p' in the pattern inserts the pattern which would usually be used. That means that the following is essentially the same as what file completion normally does:

      zstyle ':completion:*' file-patterns '%p:globbed-files' \ 
        '*(-/):directories' '*:all-files'
    
    You can turn completion for a command that usually doesn't use a pattern into one that does. Another example taken from the manual:
      zstyle ':completion:*:*:rm:*:globbed-files' file-patterns \ 
        '*.o:object-files' '%p:all-files'
    
    So if there are any *.o files around, completion for rm will just complete those, even if arguments to rm are otherwise found by default file completion (which they usually are). The %p will use whatever file completion normally would have; probably any file at all. You can change this, if you like; there may be files you don't ever want automatically completed after rm.

    Remember that using explicit patterns overrides the effect of $fignore; this is obviously useful with rm, since the files you want to delete are often those you usually don't want to complete.

    Filenames (2): paths: ambiguous, expand, file-sort, special-dirs, ignore-parents, list-suffixes, squeeze-slashes

    Filename completion is powerful enough to complete all parts of a path at once, for example `/h/p/z' will complete to `/home/pws/zsh'. This can cause problems when the match is ambiguous; since several components of the path may well be ambiguous, how much should the completion system complete, and where should it leave the cursor? This facility is associated with all these styles affecting filenames.

    With ordinary completion, the usual answer is that the completion is halted as soon as a path component matches more than one possibility, and the cursor is moved to that point, with the remainder of the string left unaltered. With menu completion, you can simply cycle through the possibilities with the cursor moved to the end as usual. If you set the style ambiguous, then the system will leave the cursor at the point of the first ambiguity even if menu completion is in use. Note that this is always used with the `paths' tag, i.e. the context ends in `...:paths'.

    The style expand is similar and is also applied with the `paths' tag. It can include either or both of the strings prefix and suffix. Be careful when setting both --- they have to be separate words, for example

      zstyle ':completion:*' expand prefix suffix
    
    Don't put quotes around `prefix suffix' as it won't work.

    With prefix, expand tells the completion system always to expand unambiguous prefixes in a path (such as `/u/i' to `/usr/in', which matches both /usr/include and /usr/info) --- even if the remainder of the string on the command line doesn't match any file. So this expansion will now happen even if you try this on `/u/i/ALoadOfOldCodswallop', which it otherwise wouldn't.

    Including suffix in the value of expand extends path completion in another way: it allows extra unambiguous parts to be added even after the first ambiguous one. So if `/home/p/.pr' would match `/home/pws/.procmailrc' or `/home/patricia/.procmailrc', and nothing else, the last word would be expanded. Set up like this, you will always get the longest unambiguous match for all parts of the path.

    In older versions of the completion system, suffix wasn't used if you had menu completion active by default, although it was if menu completion was only started by the AUTO_MENU option. However, in recent versions, the setting is always respected. This means that setting the expand style to include the value suffix allows menu completion to cycle through all possible completions, as if there were a `*' after each part of the path, so `/u/i/k' will offer all matches for `/u*/i*/k*'.

    The file-sort style allows files to be sorted in a way other than by alphabetical order: sorting applies both to the list of files, and to the order in which menu completion presents them. The value should include one of the following: `size', `links', `modification' (same as `time', `date'), `access', `inode' (same as `change'). These pick the obvious properties for sorting: file size, number of hard links, modification time, access time, inode change time. You can also add the string `reverse' to the value, which reverses the order. In this case the tag is always `files'.

    The special-dirs style controls completion of the special directories `.' and `..'. Given that you usually need to type an initial dot to complete anything at all beginning with one, the idea of `completing' `.' is a little odd; it simply means that the directory is accepted when the completion is started on it. You can set the style to true to allow completion to both of the two, or to `..' to complete `..' but not `.'. Like ambiguous, this is used with the tag set to `paths'.

    The style ignore-parents is used with the files tag, since it applies to paths, but not necessarily completion of multiple path names at once; it can be used when completing just the last element. There are two main uses, which can be combined. The first case is to include the string `parent' in the style. This means that when you complete after (say) foo/../, the string foo won't appear as a choice, since it already appeared in the string. Secondly, you can include `pwd' in the value; this means don't complete the current working directory after `../' --- you can see the sense in that: if you wanted to complete there, you wouldn't have typed the `..' to get out if it.

    Actually, the function performs both those tests on the directories in question even if the string `..' itself hasn't been typed. That might be more confusing, and you can make sure that the tests for parent and pwd are only made when you typed the `..' by including a `..' in the style's value. Finally, you can include the string `directory' in the values: that means the tests will only be performed when directories are being completed, while if some other sort of file, or any file, can be completed, the special behaviour doesn't occur. You may have to read that through a couple of times before deciding if you need it or not.

    Next, there is list-suffixes. It applies when expanding out earlier parts of the filename path, not just the last part. In this case, it is possible that early parts of the path were ambiguous. Normally completion stops at the point where it finds the ambiguity, and leaves the rest of the path alone. When list-suffixes is set, it will list all the possible values of all ambiguous components from the point of ambiguity onward.

    Lastly, there is the style squeeze-slashes. This is rather simpler. You probably already know that in a UNIX filename multiple slashes are treated just like a single slash (with a few minor exceptions on some systems). However, path completion usually assumes that multiple slashes mean multiple directories to be completed: `//termc' completes to `/etc/termcap' because of this rule. If you want to stick with the ordinary UNIX rule you can set squeeze-slashes to true. Then in this example only files in the root d