\input texinfo   @c -*-texinfo-*-
@c %**start of header
@setfilename zsh.info
@documentencoding UTF-8
@ifinfo
@*Generated by Sphinx 7.4.7.@*
@end ifinfo
@settitle The Z Shell Manual
@defindex ge
@paragraphindent 0
@exampleindent 4
@finalout
@dircategory Software Development
@direntry
* zsh: (zsh.info). the Z shell
@end direntry

@c %**end of header

@copying
@quotation
Zsh 5.9.999.3-test, Aug 08, 2026

Zsh Development Group

Copyright @copyright{} 1990–2026, Zsh Development Group
@end quotation

@end copying

@titlepage
@title The Z Shell Manual
@insertcopying
@end titlepage
@contents

@c %** start of user preamble

@c %** end of user preamble

@ifnottex
@node Top
@top The Z Shell Manual
@insertcopying
@end ifnottex

@c %**start of body
@anchor{manual doc}@anchor{0}
Texinfo / Info entry point for the Z shell manual (Yodl @code{zsh.info} chapter
order). Man-page wrappers (@code{Zsh/zsh}, @code{Zsh/zshall}, @code{Zsh/misc}) and the
separate @code{intro_zsh} tutorial are not part of this book.

@c historic nodename: Introduction

@menu
* Introduction:: 
* Roadmap:: 
* Invocation:: 
* Files:: 
* Shell Grammar:: 
* Redirection:: 
* Command Execution:: 
* Functions:: 
* Jobs & Signals:: 
* Arithmetic Evaluation:: 
* Conditional Expressions:: 
* Prompt Expansion:: 
* Expansion:: 
* Parameters:: 
* Options: Options<2>. 
* Shell Builtin Commands:: 
* Zsh Line Editor:: 
* Completion Widgets:: 
* Completion System:: 
* Completion Using compctl:: 
* Zsh Modules:: 
* Calendar Function System:: 
* TCP Function System:: 
* Zftp Function System:: 
* User Contributions:: 
* Index:: 

@detailmenu
 --- The Detailed Node Listing ---

Introduction

* Author:: 
* Availability:: 
* Mailing Lists:: 
* The Zsh FAQ:: 
* The Zsh Web Page:: 
* The Zsh Userguide:: 
* See Also:: 

Roadmap

* When the shell starts:: 
* Interactive Use:: 
* Options:: 
* Pattern Matching:: 
* General Comments on Syntax:: 
* Programming:: 

Interactive Use

* Completion:: 
* Extending the Line Editor:: 

Invocation

* Invocation: Invocation<2>. 
* Compatibility:: 

Files

* Startup/Shutdown Files:: 
* Files: Files<2>. 

Shell Grammar

* Simple Commands & Pipelines:: 
* Precommand Modifiers:: 
* Complex Commands:: 
* Alternate Forms For Complex Commands:: 
* Reserved Words:: 
* Errors:: 
* Comments:: 
* Aliasing:: 
* Quoting:: 

Aliasing

* Alias Difficulties:: 

Redirection

* Multios:: 
* Redirections with no command:: 

Functions

* Autoloading Functions:: 
* Anonymous Functions:: 
* Special Functions:: 

Special Functions

* Hook Functions:: 
* Trap Functions:: 

Jobs & Signals

* Jobs:: 
* Signals:: 

Prompt Expansion

* Expansion of Prompt Sequences:: 
* Simple Prompt Escapes:: 
* Conditional Substrings in Prompts:: 

Simple Prompt Escapes

* Special Characters:: 
* Login Information:: 
* Shell State:: 
* Date and Time:: 
* Visual Effects:: 

Expansion

* Description:: 
* History Expansion:: 
* Process Substitution:: 
* Parameter Expansion:: 
* Command Substitution:: 
* Arithmetic Expansion:: 
* Brace Expansion:: 
* Filename Expansion:: 
* Filename Generation:: 

History Expansion

* Overview:: 
* Event Designators:: 
* Word Designators:: 
* Modifiers:: 

Parameter Expansion

* Parameter Expansion Flags:: 
* Named References:: 
* Rules:: 
* Examples:: 

Filename Expansion

* Dynamic Named Directories:: 
* Static Named Directories:: 
* `=’ Expansion:: 
* Notes:: 

Filename Generation

* Glob Operators:: 
* ksh-like Glob Operators:: 
* Precedence:: 
* Globbing Flags:: 
* Approximate Matching:: 
* Recursive Globbing:: 
* Glob Qualifiers:: 

Parameters

* Description: Description<2>. 
* Array Parameters:: 
* Positional Parameters:: 
* Local Parameters:: 
* Named References: Named References<2>. 
* Parameters Set by the Shell:: 
* Parameters Used by the Shell:: 

Array Parameters

* Array Subscripts:: 
* Array Element Assignment:: 
* Subscript Flags:: 
* Subscript Parsing:: 

Options

* Specifying Options:: 
* Description of Options:: 
* Option Aliases:: 
* Single Letter Options:: 

Description of Options

* Changing Directories:: 
* Completion: Completion<2>. 
* Expansion and Globbing:: 
* History:: 
* Initialisation:: 
* Input/Output:: 
* Job Control:: 
* Prompting:: 
* Scripts and Functions:: 
* Shell Emulation:: 
* Shell State: Shell State<2>. 
* Zle:: 

Single Letter Options

* Default Set:: 
* sh/ksh Emulation Set:: 
* Also Note:: 

Zsh Line Editor

* Description: Description<3>. 
* Keymaps:: 
* Zle Builtins:: 
* Zle Widgets:: 
* User-Defined Widgets:: 
* Standard Widgets:: 
* Terminal Extensions:: 
* Character Highlighting:: 
* Cursor Shape and Color:: 

Keymaps

* Reading Commands:: 
* Local Keymaps:: 

User-Defined Widgets

* Special Widgets:: 

Standard Widgets

* Movement:: 
* History Control:: 
* Modifying Text:: 
* Arguments:: 
* Completion: Completion<3>. 
* Miscellaneous:: 
* Text Objects:: 

Completion Widgets

* Description: Description<4>. 
* Completion Special Parameters:: 
* Completion Builtin Commands:: 
* Completion Condition Codes:: 
* Completion Matching Control:: 
* Completion Widget Example:: 

Completion System

* Description: Description<5>. 
* Initialization:: 
* Completion System Configuration:: 
* Control Functions:: 
* Bindable Commands:: 
* Utility Functions:: 
* Completion System Variables:: 
* Completion Directories:: 

Initialization

* Use of compinit:: 
* Autoloaded Files:: 
* Functions: Functions<2>. 

Completion System Configuration

* Overview: Overview<2>. 
* Standard Tags:: 
* Standard Styles:: 

Completion Using compctl

* Types of completion:: 
* Command Flags:: 
* Option Flags:: 
* Alternative Completion:: 
* Extended Completion:: 
* Example:: 

Option Flags

* Simple Flags:: 
* Flags with Arguments:: 
* Control Flags:: 

Zsh Modules

* Description: Description<6>. 
* The zsh/attr Module:: 
* The zsh/cap Module:: 
* The zsh/clone Module:: 
* The zsh/compctl Module:: 
* The zsh/complete Module:: 
* The zsh/complist Module:: 
* The zsh/computil Module:: 
* The zsh/curses Module:: 
* The zsh/datetime Module:: 
* The zsh/db/gdbm Module:: 
* The zsh/deltochar Module:: 
* The zsh/example Module:: 
* The zsh/files Module:: 
* The zsh/hlgroup Module:: 
* The zsh/langinfo Module:: 
* The zsh/ksh93 Module:: 
* The zsh/mapfile Module:: 
* The zsh/mathfunc Module:: 
* The zsh/nearcolor Module:: 
* The zsh/newuser Module:: 
* The zsh/parameter Module:: 
* The zsh/pcre Module:: 
* The zsh/param/private Module:: 
* The zsh/regex Module:: 
* The zsh/random Module:: 
* The zsh/sched Module:: 
* The zsh/net/socket Module:: 
* The zsh/stat Module:: 
* The zsh/system Module:: 
* The zsh/net/tcp Module:: 
* The zsh/termcap Module:: 
* The zsh/terminfo Module:: 
* The zsh/watch Module:: 
* The zsh/zftp Module:: 
* The zsh/zle Module:: 
* The zsh/zleparameter Module:: 
* The zsh/zprof Module:: 
* The zsh/zpty Module:: 
* The zsh/zselect Module:: 
* The zsh/zutil Module:: 

The zsh/complist Module

* Colored Completion Listings:: 
* Scrolling in Completion Listings:: 
* Menu Selection:: 

The zsh/curses Module

* Builtin:: 
* Parameters: Parameters<2>. 

The zsh/ksh93 Module

* Ksh Builtins:: 
* Ksh Parameters:: 
* Future Compatibility:: 
* Other Differences:: 

The zsh/mapfile Module

* Limitations:: 

The zsh/random Module

* Parameters: Parameters<3>. 
* Math Functions:: 

The zsh/net/socket Module

* Outbound Connections:: 
* Inbound Connections:: 

The zsh/system Module

* Builtins:: 
* Math Functions: Math Functions<2>. 
* Parameters: Parameters<4>. 

The zsh/net/tcp Module

* Outbound Connections: Outbound Connections<2>. 
* Inbound Connections: Inbound Connections<2>. 
* Closing Connections:: 
* Example: Example<2>. 

The zsh/zftp Module

* Subcommands:: 
* Parameters: Parameters<5>. 
* Functions: Functions<3>. 
* Problems:: 

Calendar Function System

* Description: Description<7>. 
* File and Date Formats:: 
* User Functions:: 
* Styles:: 
* Utility functions:: 
* Bugs:: 

File and Date Formats

* Calendar File Format:: 
* Date Format:: 
* Relative Time Format:: 
* Example: Example<3>. 

User Functions

* Calendar System Functions:: 
* Glob Qualifiers: Glob Qualifiers<2>. 

TCP Function System

* Description: Description<8>. 
* TCP User Functions:: 
* TCP User-defined Functions:: 
* TCP Utility Functions:: 
* TCP User Parameters:: 
* TCP User-defined Parameters:: 
* TCP Utility Parameters:: 
* TCP Examples:: 
* TCP Bugs:: 

TCP User Functions

* Basic I/O:: 
* Session Management:: 
* Advanced I/O:: 
* `One-shot’ File Transfer:: 

Zftp Function System

* Description: Description<9>. 
* Installation:: 
* Functions: Functions<4>. 
* Miscellaneous Features:: 

Functions

* Opening a Connection:: 
* Directory Management:: 
* Status Commands:: 
* Retrieving Files:: 
* Sending Files:: 
* Closing the Connection:: 
* Session Management: Session Management<2>. 
* Bookmarks:: 
* Other Functions:: 

Miscellaneous Features

* Configuration:: 
* Remote Globbing:: 
* Automatic and Temporary Reopening:: 
* Completion: Completion<4>. 

User Contributions

* Description: Description<10>. 
* Utilities:: 
* Remembering Recent Directories:: 
* Abbreviated dynamic references to directories:: 
* Gathering information from version control systems:: 
* Prompt Themes:: 
* ZLE Functions:: 
* Exception Handling:: 
* MIME Functions:: 
* Mathematical Functions:: 
* User Configuration Functions:: 
* Other Functions: Other Functions<2>. 

Utilities

* Accessing On-Line Help:: 
* Recompiling Functions:: 
* Keyboard Definition:: 
* Dumping Shell State:: 
* Manipulating Hook Functions:: 

Remembering Recent Directories

* Installation: Installation<2>. 
* Use:: 
* Options: Options<3>. 
* Configuration: Configuration<2>. 
* Use with Dynamic Directory Naming:: 
* Details of Directory Handling:: 

Abbreviated dynamic references to directories

* Usage:: 
* Configuration: Configuration<3>. 
* Complete Example:: 

Gathering information from version control systems

* Quickstart:: 
* Configuration: Configuration<4>. 
* Oddities:: 
* Quilt Support:: 
* Function Descriptions (Public API): Function Descriptions Public API. 
* Variable Description:: 
* Hooks in vcs_info:: 
* Examples: Examples<2>. 

Prompt Themes

* Installation: Installation<3>. 
* Theme Selection:: 
* Utility Themes:: 
* Writing Themes:: 

ZLE Functions

* Widgets:: 
* Utility Functions: Utility Functions<2>. 
* Styles: Styles<2>. 

Other Functions

* Descriptions:: 
* Styles: Styles<3>. 

@end detailmenu
@end menu

@node Introduction,Roadmap,Top,Top
@anchor{Zsh/intro doc}@anchor{1}@anchor{Zsh/intro introduction}@anchor{2}@anchor{Zsh/intro the-z-shell-manual}@anchor{3}
@chapter Introduction


@geindex introduction; Command


Zsh is a UNIX command interpreter (shell) usable as an interactive
login shell and as a shell script command processor.  Of the standard shells,
zsh most closely resembles `ksh' but includes many enhancements.  It
does not provide compatibility with POSIX or other shells in its
default operating mode:  see
`Compatibility'.

Zsh has command line editing, builtin spelling correction, programmable
command completion, shell functions (with autoloading), a history
mechanism, and a host of other features.

@c historic nodename: Author

@menu
* Author:: 
* Availability:: 
* Mailing Lists:: 
* The Zsh FAQ:: 
* The Zsh Web Page:: 
* The Zsh Userguide:: 
* See Also:: 

@end menu

@node Author,Availability,,Introduction
@anchor{Zsh/intro author}@anchor{4}
@section Author


@geindex author; Command

Zsh was originally written by Paul Falstad.  Zsh is now maintained by
the members of the zsh-workers mailing list @code{<zsh-workers@@zsh.org>}.
The development is currently coordinated by Peter Stephenson
@code{<pws@@zsh.org>}.  The coordinator can be contacted at
@code{<coordinator@@zsh.org>}, but matters relating to the code should
generally go to the mailing list.

@c historic nodename: Availability

@node Availability,Mailing Lists,Author,Introduction
@anchor{Zsh/intro availability}@anchor{5}
@section Availability


Zsh is available from the following HTTP and anonymous FTP site.

@geindex FTP sites for zsh; Command

@geindex acquiring zsh by FTP; Command

@geindex availability of zsh; Command

@example
ftp://ftp.zsh.org/pub/
https://www.zsh.org/pub/
@end example

The up-to-date source code is available via Git from Sourceforge.  See
@indicateurl{https://sourceforge.net/projects/zsh/} for details.  A summary of
instructions for the archive can be found at
@indicateurl{https://zsh.sourceforge.io/}.

@c historic nodename: Mailing Lists

@node Mailing Lists,The Zsh FAQ,Availability,Introduction
@anchor{Zsh/intro mailing-lists}@anchor{6}
@section Mailing Lists


@geindex mailing lists; Command

Zsh has several mailing lists:

@code{<zsh-announce@@zsh.org>}

@quotation

Announcements about releases, major changes in the shell and the
monthly posting of the Zsh FAQ.  (moderated)
@end quotation

@code{<zsh-users@@zsh.org>}

@quotation

User discussions.
@end quotation

@code{<zsh-workers@@zsh.org>}

@quotation

Hacking, development, bug reports and patches.
@end quotation

@code{<zsh-security@@zsh.org>}

@quotation

Private mailing list (the general public cannot subscribe to it) for discussing
bug reports with security implications, i.e., potential vulnerabilities.

If you find a security problem in zsh itself, please mail this address.
@end quotation

To subscribe or unsubscribe, send mail
to the associated administrative address for the mailing list.

@quotation


@itemize *

@item 
@code{<zsh-announce-subscribe@@zsh.org>}

@item 
@code{<zsh-users-subscribe@@zsh.org>}

@item 
@code{<zsh-workers-subscribe@@zsh.org>}

@item 
@code{<zsh-announce-unsubscribe@@zsh.org>}

@item 
@code{<zsh-users-unsubscribe@@zsh.org>}

@item 
@code{<zsh-workers-unsubscribe@@zsh.org>}
@end itemize
@end quotation

YOU ONLY NEED TO JOIN ONE OF THE MAILING LISTS AS THEY ARE NESTED.
All submissions to `zsh-announce' are automatically forwarded to
`zsh-users'.  All submissions to `zsh-users' are automatically
forwarded to `zsh-workers'.

If you have problems subscribing/unsubscribing to any of the mailing
lists, send mail to @code{<listmaster@@zsh.org>}.

The mailing lists are archived; the archives can be accessed via the
administrative addresses listed above.  There is also a hypertext
archive available at
@indicateurl{https://www.zsh.org/mla/}.

@c historic nodename: The Zsh FAQ

@node The Zsh FAQ,The Zsh Web Page,Mailing Lists,Introduction
@anchor{Zsh/intro the-zsh-faq}@anchor{7}
@section The Zsh FAQ


Zsh has a list of Frequently Asked Questions (FAQ), maintained by
Peter Stephenson @code{<pws@@zsh.org>}.  It is regularly posted to the
newsgroup `comp.unix.shell' and the `zsh-announce' mailing list.
The latest version can be found at any of the Zsh FTP sites, or at
@indicateurl{https://www.zsh.org/FAQ/}.  The contact address for FAQ-related matters
is @code{<faqmaster@@zsh.org>}.

@c historic nodename: The Zsh Web Page

@node The Zsh Web Page,The Zsh Userguide,The Zsh FAQ,Introduction
@anchor{Zsh/intro the-zsh-web-page}@anchor{8}
@section The Zsh Web Page


Zsh has a web page which is located at @indicateurl{https://www.zsh.org/}.
The contact address for web-related matters is @code{<webmaster@@zsh.org>}.

@c historic nodename: The Zsh Userguide

@node The Zsh Userguide,See Also,The Zsh Web Page,Introduction
@anchor{Zsh/intro the-zsh-userguide}@anchor{9}
@section The Zsh Userguide


A userguide is currently in preparation.  It is intended to complement the
manual, with explanations and hints on issues where the manual can be
cabbalistic, hierographic, or downright mystifying (for example, the word
`hierographic’ does not exist).  It can be viewed in its current state at
@indicateurl{https://zsh.sourceforge.io/Guide/}.  At the time of writing, chapters
dealing with startup files and their contents and the new completion system
were essentially complete.

@c historic nodename: See Also

@node See Also,,The Zsh Userguide,Introduction
@anchor{Zsh/intro see-also}@anchor{a}
@section See Also


@code{sh(1)},
@code{csh(1)},
@code{tcsh(1)},
@code{rc(1)},
@code{bash(1)},
@code{ksh(1)}

`IEEE Standard for information Technology -
Portable Operating System Interface (POSIX) -
Part 2: Shell and Utilities',
IEEE Inc, 1993, ISBN 1-55937-255-9.

@c historic nodename: Roadmap

@node Roadmap,Invocation,Introduction,Top
@anchor{Zsh/roadmap doc}@anchor{b}@anchor{Zsh/roadmap roadmap}@anchor{c}
@chapter Roadmap


@geindex roadmap; Command

The Zsh Manual, like the shell itself, is large and often complicated.
This section of the manual provides some pointers to areas of the shell
that are likely to be of particular interest to new users, and indicates
where in the rest of the manual the documentation is to be found.

@menu
* When the shell starts:: 
* Interactive Use:: 
* Options:: 
* Pattern Matching:: 
* General Comments on Syntax:: 
* Programming:: 

@end menu

@node When the shell starts,Interactive Use,,Roadmap
@anchor{Zsh/roadmap when-the-shell-starts}@anchor{d}
@section When the shell starts


When it starts, the shell reads commands from various files.  These can
be created or edited to customize the shell.  See
@ref{e,,Startup/Shutdown Files}.

If no personal initialization files exist for the current user, a function
is run to help you change some of the most common settings.  It won’t
appear if your administrator has disabled the @code{zsh/newuser} module.
The function is designed to be self-explanatory.  You can run it by hand
with @code{autoload -Uz zsh-newuser-install; zsh-newuser-install -f}.
See also @ref{f,,User Configuration Functions}.

@node Interactive Use,Options,When the shell starts,Roadmap
@anchor{Zsh/roadmap interactive-use}@anchor{10}
@section Interactive Use


Interaction with the shell uses the builtin Zsh Line Editor, ZLE.  This is
described in detail in @code{zshzle}.

The first decision a user must make is whether to use the Emacs or Vi
editing mode as the keys for editing are substantially different.  Emacs
editing mode is probably more natural for beginners and can be selected
explicitly with the command @code{bindkey -e}.

A history mechanism for retrieving previously typed lines (most simply
with the Up or Down arrow keys) is available; note that, unlike other
shells, zsh will not save these lines when the shell exits unless you
set appropriate variables, and the number of history lines retained by
default is quite small (30 lines).  See the description of the shell
variables (referred to in the documentation as parameters) @code{HISTFILE},
@code{HISTSIZE} and @code{SAVEHIST} in
@ref{11,,Parameters Used by the Shell}. Note that it’s
currently only possible to read and write files saving history
when the shell is interactive, i.e. it does not work from scripts.

The shell now supports the UTF-8 character set (and also others if
supported by the operating system).  This is (mostly) handled transparently
by the shell, but the degree of support in terminal emulators is variable.
There is some discussion of this in the shell FAQ,
@indicateurl{https://www.zsh.org/FAQ/}.  Note in particular that for combining
characters to be handled the option @code{COMBINING_CHARS} needs to be set.
Because the shell is now more sensitive to the definition of the
character set, note that if you are upgrading from an older version of
the shell you should ensure that the appropriate variable, either
@code{LANG} (to affect all aspects of the shell’s operation) or
@code{LC_CTYPE} (to affect only the handling of character sets) is set to
an appropriate value.  This is true even if you are using a
single-byte character set including extensions of ASCII such as
@code{ISO-8859-1} or @code{ISO-8859-15}.  See the description of @code{LC_CTYPE}
in @ref{11,,Parameters Used by the Shell}.

@menu
* Completion:: 
* Extending the Line Editor:: 

@end menu

@node Completion,Extending the Line Editor,,Interactive Use
@anchor{Zsh/roadmap completion}@anchor{12}
@subsection Completion


Completion is a feature present in many shells. It allows the user to
type only a part (usually the prefix) of a word and have the shell fill
in the rest.  The completion system in zsh is programmable.  For
example, the shell can be set to complete email addresses in
arguments to the mail command from your @code{~/.abook/addressbook};
usernames, hostnames, and even remote paths in arguments to scp, and so
on.  Anything that can be written in or glued together with zsh can be
the source of what the line editor offers as possible completions.

Zsh has two completion systems, an old, so called @code{compctl} completion
(named after the builtin command that serves as its complete and only
user interface), and a new one, referred to as @code{compsys},
organized as library of builtin and user-defined functions.
The two systems differ in their interface for specifying the completion
behavior.  The new system is more customizable and is supplied with
completions for many commonly used commands; it is therefore to be
preferred.

The completion system must be enabled explicitly when the shell starts.
For more information see @code{zshcompsys}.

@node Extending the Line Editor,,Completion,Interactive Use
@anchor{Zsh/roadmap extending-the-line-editor}@anchor{13}
@subsection Extending the Line Editor


Apart from completion, the line editor is highly extensible by means of
shell functions.  Some useful functions are provided with the shell; they
provide facilities such as:

@code{insert-composed-char}

@quotation

composing characters not found on the keyboard
@end quotation

@code{match-words-by-style}

@quotation

configuring what the line editor considers a word when moving or
deleting by word
@end quotation

@code{history-beginning-search-backward-end}, etc.

@quotation

alternative ways of searching the shell history
@end quotation

@code{replace-string}, @code{replace-pattern}

@quotation

functions for replacing strings or patterns globally in the command line
@end quotation

@code{edit-command-line}

@quotation

edit the command line with an external editor.
@end quotation

See @ref{14,,ZLE Functions} for descriptions of these.

@node Options,Pattern Matching,Interactive Use,Roadmap
@anchor{Zsh/roadmap options}@anchor{15}
@section Options


The shell has a large number of options for changing its behaviour.
These cover all aspects of the shell; browsing the full documentation is
the only good way to become acquainted with the many possibilities.  See
@code{zshoptions}.

@node Pattern Matching,General Comments on Syntax,Options,Roadmap
@anchor{Zsh/roadmap pattern-matching}@anchor{16}
@section Pattern Matching


The shell has a rich set of patterns which are available for file matching
(described in the documentation as `filename generation’ and also known for
historical reasons as `globbing’) and for use when programming.  These are
described in @ref{17,,Filename Generation}.

Of particular interest are the following patterns that are not commonly
supported by other systems of pattern matching:

@code{**}

@quotation

for matching over multiple directories
@end quotation

@code{|}

@quotation

for matching either of two alternatives
@end quotation

@code{~}, @code{^}

@quotation

the ability to exclude patterns from matching when the @code{EXTENDED_GLOB}
option is set
@end quotation

@code{(}@var{…}@code{)}

@quotation

glob qualifiers, included in parentheses at the end of the pattern,
which select files by type (such as directories) or attribute (such as
size).
@end quotation

@node General Comments on Syntax,Programming,Pattern Matching,Roadmap
@anchor{Zsh/roadmap general-comments-on-syntax}@anchor{18}
@section General Comments on Syntax


Although the syntax of zsh is in ways similar to the Korn shell, and
therefore more remotely to the original UNIX shell, the Bourne shell,
its default behaviour does not entirely correspond to those shells.
General shell syntax is introduced in @ref{19,,Shell Grammar}.

One commonly encountered difference is that variables substituted onto the
command line are not split into words.  See the description of the shell option
@code{SH_WORD_SPLIT} in @ref{1a,,Parameter Expansion}.
In zsh, you can either explicitly request the splitting (e.g. @code{$@{=foo@}})
or use an array when you want a variable to expand to more than one word.  See
@ref{1b,,Array Parameters}.

@node Programming,,General Comments on Syntax,Roadmap
@anchor{Zsh/roadmap programming}@anchor{1c}
@section Programming


The most convenient way of adding enhancements to the shell is typically
by writing a shell function and arranging for it to be autoloaded.
Functions are described in @ref{1d,,Functions}.
Users changing from the C shell and its
relatives should notice that aliases are less used in zsh as they don’t
perform argument substitution, only simple text replacement.

A few general functions, other than those for the line editor described
above, are provided with the shell and are described in
@code{zshcontrib}.  Features include:

@code{promptinit}

@quotation

a prompt theme system for changing prompts easily, see
@ref{1e,,Prompt Themes}
@end quotation

@code{zsh-mime-setup}

@quotation

a MIME-handling system which dispatches commands according to the suffix of
a file as done by graphical file managers
@end quotation

@code{zcalc}

@quotation

a calculator
@end quotation

@code{zargs}

@quotation

a version of @code{xargs} that makes the @code{find} command redundant
@end quotation

@code{zmv}

@quotation

a command for renaming files by means of shell patterns.
@end quotation

@c historic nodename: Invocation

@node Invocation,Files,Roadmap,Top
@anchor{Zsh/invoke doc}@anchor{1f}@anchor{Zsh/invoke invocation}@anchor{20}
@chapter Invocation


@geindex invocation; Command

@menu
* Invocation: Invocation<2>. 
* Compatibility:: 

@end menu

@node Invocation<2>,Compatibility,,Invocation
@anchor{Zsh/invoke id1}@anchor{21}
@section Invocation


@geindex shell options; Command

@geindex options@comma{} shell; Command

@geindex shell flags; Command

@geindex flags@comma{} shell; Command

The following flags are interpreted by the shell when invoked to determine
where the shell will read commands from:

@code{-c}

@quotation

Take the first argument as a command to execute, rather than reading commands
from a script or standard input.  If any further arguments are given, the
first one is assigned to @code{$0}, rather than being used as a positional
parameter.
@end quotation

@code{-i}

@quotation

Force shell to be interactive.  It is still possible to specify a
script to execute.
@end quotation

@code{-s}

@quotation

Force shell to read commands from the standard input.
If the @code{-s} flag is not present and an argument is given,
the first argument is taken to be the pathname of a script to
execute.
@end quotation

If there are any remaining arguments after option processing, and neither
of the options @code{-c} or @code{-s} was supplied, the first argument is taken
as the file name of a script containing shell commands to be executed.  If
the option @code{PATH_SCRIPT} is set, and the file name does not contain a
directory path (i.e. there is no @code{/} in the name), first the current
directory and then the command path given by the variable @code{PATH} are
searched for the script.  If the option is not set or the file name
contains a @code{/} it is used directly.

After the first one or two arguments have been appropriated as described above,
the remaining arguments are assigned to the positional parameters.

For further options, which are common to invocation and the @code{set}
builtin, see @code{zshoptions}.

The long option @code{--emulate} followed (in a separate word) by an
emulation mode may be passed to the shell.
The emulation modes are those described for the @code{emulate} builtin,
see @code{zshbuiltins}.
The @code{--emulate} option must precede any other options (which might
otherwise be overridden), but following options are honoured, so
may be used to modify the requested emulation mode.  Note that certain
extra steps are taken to ensure a smooth emulation when this option
is used compared with the @code{emulate} command within the shell: for
example, variables that conflict with POSIX usage such as @code{path} are
not defined within the shell.

Options may be specified by name using the @code{-o} option.  @code{-o} acts like
a single-letter option, but takes a following string as the option name.
For example,

@example
 zsh -x -o shwordsplit scr
@end example

runs the script @code{scr}, setting the @code{XTRACE} option by the corresponding
letter @code{-x} and the @code{SH_WORD_SPLIT} option by name.
Options may be turned `off' by name by using @code{+o} instead of @code{-o}.
@code{-o} can be stacked up with preceding single-letter options, so for example
@code{-xo shwordsplit} or @code{-xoshwordsplit} is equivalent to
@code{-x -o shwordsplit}.

@geindex long option; Command

Options may also be specified by name in GNU long option style,
@code{--}@var{option-name}.  When this is done, @code{-} characters in the
option name are permitted: they are translated into @code{_}, and thus ignored.
So, for example, @code{zsh --sh-word-split} invokes zsh with the
@code{SH_WORD_SPLIT} option turned on.  Like other option syntaxes, options can
be turned off by replacing the initial @code{-} with a @code{+}; thus
@code{+-sh-word-split} is equivalent to @code{--no-sh-word-split}.
Unlike other option syntaxes, GNU-style long options cannot be stacked with
any other options, so for example @code{-x-shwordsplit} is an error,
rather than being treated like @code{-x --shwordsplit}.

@geindex --version; Command

@geindex --help; Command

The special GNU-style option @code{--version} is handled; it sends to
standard output the shell’s version information, then exits successfully.
@code{--help} is also handled; it sends to standard output a list of
options that can be used when invoking the shell, then exits successfully.

Option processing may be finished, allowing following arguments that start with
@code{-} or @code{+} to be treated as normal arguments, in two ways.
Firstly, a lone @code{-} (or @code{+}) as an argument by itself ends
option processing.  Secondly, a special option @code{--} (or
@code{+-}), which may be specified on its own (which is the standard
POSIX usage) or may be stacked with preceding options (so @code{-x-} is
equivalent to @code{-x --}).  Options are not permitted to be stacked
after @code{--} (so @code{-x-f} is an error), but note the GNU-style
option form discussed above, where @code{--shwordsplit} is permitted
and does not end option processing.

Except when the `sh'/`ksh' emulation single-letter options are in effect,
the option @code{-b} (or @code{+b}) ends option processing.
@code{-b} is like @code{--}, except that further single-letter options
can be stacked after the @code{-b} and will take effect as normal.

@c historic nodename: Compatibility

@node Compatibility,,Invocation<2>,Invocation
@anchor{Zsh/invoke compatibility}@anchor{22}
@section Compatibility


@geindex compatibility; Command

@geindex sh compatibility; Command

@geindex ksh compatibility; Command

Zsh tries to emulate `sh' or `ksh' when it is invoked as
@code{sh} or @code{ksh} respectively; more precisely, it looks at the first
letter of the name by which it was invoked, and if that is @code{b}, @code{s} or @code{k} it
will emulate `sh' or `ksh'.  Furthermore, if invoked as @code{su} (which
happens on certain systems when the shell is executed by the @code{su}
command), the shell will try to find an alternative name from the @code{SHELL}
environment variable and perform emulation based on that.

In `sh' and `ksh' compatibility modes the following
parameters are not special and not initialized by the shell:
@code{ARGC},
@code{argv},
@code{cdpath},
@code{fignore},
@code{fpath},
@code{HISTCHARS},
@code{mailpath},
@code{MANPATH},
@code{manpath},
@code{path},
@code{prompt},
@code{PROMPT},
@code{PROMPT2},
@code{PROMPT3},
@code{PROMPT4},
@code{psvar},
@code{status}.

@geindex ENV@comma{} use of; Variable

The usual zsh startup/shutdown scripts are not executed.  Login shells
source @code{/etc/profile} followed by @code{$HOME/.profile}.  If the
@code{ENV} environment variable is set on invocation, @code{$ENV} is sourced
after the profile scripts.  The value of @code{ENV} is subjected to
parameter expansion, command substitution, and arithmetic expansion
before being interpreted as a pathname.  Note that the @code{PRIVILEGED}
option also affects the execution of startup files.

The following options are set if the shell is invoked as @code{sh} or
@code{ksh}:
@code{NO_BAD_PATTERN},
@code{NO_BANG_HIST},
@code{NO_BG_NICE},
@code{NO_EQUALS},
@code{NO_FUNCTION_ARGZERO},
@code{GLOB_SUBST},
@code{NO_GLOBAL_EXPORT},
@code{NO_HUP},
@code{INTERACTIVE_COMMENTS},
@code{KSH_ARRAYS},
@code{NO_MULTIOS},
@code{NO_NOMATCH},
@code{NO_NOTIFY},
@code{POSIX_BUILTINS},
@code{NO_PROMPT_PERCENT},
@code{RM_STAR_SILENT},
@code{SH_FILE_EXPANSION},
@code{SH_GLOB},
@code{SH_OPTION_LETTERS},
@code{SH_WORD_SPLIT}.
Additionally the @code{BSD_ECHO} and @code{IGNORE_BRACES}
options are set if zsh is invoked as @code{sh}.
Also, the
@code{KSH_OPTION_PRINT},
@code{LOCAL_OPTIONS},
@code{PROMPT_BANG},
@code{PROMPT_SUBST}
and
@code{SINGLE_LINE_ZLE}
options are set if zsh is invoked as @code{ksh}.

Please note that, whilst reasonable efforts are taken to address
incompatibilities when they arise, zsh does not guarantee complete
emulation of other shells, nor POSIX compliance. For more information on
the differences between zsh and other shells, please refer to chapter 2
of the shell FAQ, @indicateurl{https://www.zsh.org/FAQ/}.

@c historic nodename: Files

@node Files,Shell Grammar,Invocation,Top
@anchor{Zsh/files doc}@anchor{23}@anchor{Zsh/files files}@anchor{24}
@chapter Files


@menu
* Startup/Shutdown Files:: 
* Files: Files<2>. 

@end menu

@node Startup/Shutdown Files,Files<2>,,Files
@anchor{Zsh/files id1}@anchor{25}@anchor{Zsh/files startup-shutdown-files}@anchor{e}
@section Startup/Shutdown Files


@geindex files@comma{} startup; Command

@geindex startup files; Command

@geindex files@comma{} shutdown; Command

@geindex shutdown files; Command

@geindex RCS@comma{} use of; Program

@geindex GLOBAL_RCS@comma{} use of; Program

@geindex NO_RCS@comma{} use of; Program

@geindex NO_GLOBAL_RCS@comma{} use of; Program

@geindex ZDOTDIR@comma{} use of; Variable

@geindex zshenv; Command

Commands are first read from @code{/etc/zshenv}; this cannot be overridden.
Subsequent behaviour is modified by the @code{RCS} and
@code{GLOBAL_RCS} options; the former affects all startup files, while the
second only affects global startup files (those shown here with a
path starting with a @code{/}).  If one of the options
is unset at any point, any subsequent startup file(s)
of the corresponding
type will not be read.  It is also possible for a file in @code{$ZDOTDIR} to
re-enable @code{GLOBAL_RCS}. Both @code{RCS} and @code{GLOBAL_RCS} are set by
default.

Commands are then read from @code{$ZDOTDIR/.zshenv}.
.. index:: single: LOGIN, use of; Program

@geindex zprofile; Command

If the shell is a login shell, commands
are read from @code{/etc/zprofile} and then @code{$ZDOTDIR/.zprofile}.
.. index:: single: zshrc; Command

Then, if the shell is interactive,
commands are read from @code{/etc/zshrc} and then @code{$ZDOTDIR/.zshrc}.
.. index:: single: zlogin; Command

Finally, if the shell is a login shell, @code{/etc/zlogin} and
@code{$ZDOTDIR/.zlogin} are read.

@geindex zlogout; Command

When a login shell exits, the files @code{$ZDOTDIR/.zlogout} and then
@code{/etc/zlogout} are read.  This happens with either an explicit exit
via the @code{exit} or @code{logout} commands, or an implicit exit by reading
end-of-file from the terminal.  However, if the shell terminates due
to @code{exec}’ing another process, the logout files are not read.
These are also affected by the @code{RCS} and @code{GLOBAL_RCS} options.
Note also that the @code{RCS} option affects the saving of history files,
i.e. if @code{RCS} is unset when the shell exits, no history file will be
saved.

@geindex HOME@comma{} use of; Variable

If @code{ZDOTDIR} is unset, @code{HOME} is used instead.
Files listed above as being in @code{/etc} may be in another
directory, depending on the installation.

As @code{/etc/zshenv} is run for all instances of zsh, it is important that
it be kept as small as possible.  In particular, it is a good idea to
put code that does not need to be run for every single shell behind
a test of the form @code{if [[ -o rcs ]]; then ...} so that it will not
be executed when zsh is invoked with the @code{-f} option.

Any of these files may be pre-compiled with the @code{zcompile} builtin
command (see @code{zshbuiltins}).
If a compiled file exists (named for the original file plus the
@code{.zwc} extension) and it is newer than the original file, the compiled
file will be used instead.

@node Files<2>,,Startup/Shutdown Files,Files
@anchor{Zsh/files id2}@anchor{26}
@section Files


@c historic nodename: Shell Grammar

@node Shell Grammar,Redirection,Files,Top
@anchor{Zsh/grammar doc}@anchor{27}@anchor{Zsh/grammar shell-grammar}@anchor{28}
@chapter Shell Grammar


@geindex shell grammar; Command

@geindex grammar@comma{} shell; Command

@c historic nodename: Simple Commands & Pipelines

@menu
* Simple Commands & Pipelines:: 
* Precommand Modifiers:: 
* Complex Commands:: 
* Alternate Forms For Complex Commands:: 
* Reserved Words:: 
* Errors:: 
* Comments:: 
* Aliasing:: 
* Quoting:: 

@end menu

@node Simple Commands & Pipelines,Precommand Modifiers,,Shell Grammar
@anchor{Zsh/grammar simple-commands-pipelines}@anchor{29}
@section Simple Commands & Pipelines


@geindex simple commands; Command

@geindex commands@comma{} simple; Command

A `simple command' is a sequence of optional parameter
assignments followed by blank-separated words,
with optional redirections interspersed.  For a description
of assignment, see the beginning of @code{zshparam}.

The first word is the command to be executed, and the remaining
words, if any, are arguments to the command.
If a command name is given, the parameter assignments modify
the environment of the command when it is executed.
The value of a simple command is its exit status,
or 128 plus the signal number if terminated by a signal.
For example,

@example
 echo foo
@end example

is a simple command with arguments.

@geindex pipeline; Command

A `pipeline' is either a simple command, or a sequence of two or more
simple commands where each command is separated from the next by @code{|}
or @code{|&}.  Where commands are separated by @code{|}, the standard
output of the first command is connected to the
standard input of the next.  @code{|&} is shorthand for @code{2>&1 |}, which
connects both the standard output and the standard error of the
command to the standard input of the next.  The value of a pipeline
is the value of the last command, unless the pipeline is preceded by
@code{!} in which case the value is the logical inverse of the value of the
last command.
For example,

@example
 echo foo | sed 's/foo/bar/'
@end example

is a pipeline, where the output (@code{foo} plus a newline) of the first
command will be passed to the input of the second.

@geindex coproc; Function

@geindex coprocess; Command

If a pipeline is preceded by @code{coproc}, it is executed as a coprocess;
a two-way pipe is established between it and the parent shell.  The
shell can read from or write to the coprocess by means of the @code{>&p}
and @code{<&p} redirection operators or with @code{print -p} and @code{read -p}.
A pipeline cannot be preceded by both @code{coproc} and @code{!}.
If job control is active, the coprocess can be treated in other than input
and output as an ordinary background job.

@geindex sublist; Command

A `sublist' is either a single pipeline, or a sequence of two or more
pipelines separated by @code{&&} or @code{||}.  If two pipelines are separated
by @code{&&}, the second pipeline is executed only if the first succeeds
(returns a zero status).  If two pipelines are separated by @code{||}, the
second is executed only if the first fails (returns a nonzero status).
Both operators have equal precedence and are left associative.
The value of the sublist is the value of the last pipeline executed.
For example,

@example
 dmesg | grep panic && print yes
@end example

is a sublist consisting of two pipelines, the second just a simple command
which will be executed if and only if the @code{grep} command returns a zero
status.  If it does not, the value of the sublist is that return status, else
it is the status returned by the @code{print} (almost certainly zero).

@geindex list; Command

A `list' is a sequence of zero or more sublists, in which each sublist
is terminated by @code{;}, @code{&}, @code{&|}, @code{&!}, or a newline.
This terminator
may optionally be omitted from the last sublist in the list when the
list appears as a complex command inside @code{(...)}
or @code{@{...@}}.  When a
sublist is terminated by @code{;} or newline, the shell waits for it to
finish before executing the next sublist.  If a sublist is terminated
by a @code{&}, @code{&|}, or @code{&!},
the shell executes the last pipeline in it in the background, and
does not wait for it to finish (note the difference from other shells
which execute the whole sublist in the background).
A backgrounded pipeline returns a status of zero.

More generally, a list can be seen as a set of any shell commands
whatsoever, including the complex commands below; this is implied wherever
the word `list’ appears in later descriptions.  For example, the commands
in a shell function form a special sort of list.

@c historic nodename: Precommand Modifiers

@node Precommand Modifiers,Complex Commands,Simple Commands & Pipelines,Shell Grammar
@anchor{Zsh/grammar precommand-modifiers}@anchor{2a}
@section Precommand Modifiers


@geindex precommand modifiers; Command

@geindex modifiers@comma{} precommand; Command

With the exception of @code{nocorrect}, which is a reserved word that
affects further parsing when it is found in command position, each
of the following builtin commands is a `precommand modifier' which
may precede a simple command to alter how that command is interpreted.

@geindex -; Function

@code{-}

@quotation

The command is executed with a @code{-} prepended to its
@code{argv[0]} string.
@end quotation

@geindex builtin; Function

@code{builtin}

@quotation

The command word is taken to be the name of a builtin command,
rather than a shell function or external command.
@end quotation

@geindex command; Function

@code{command} [ @code{-pvV} ]

@quotation

The command word is taken to be the name of an external command,
rather than a shell function or builtin.   If the @code{POSIX_BUILTINS} option
is set, builtins will also be executed but certain special properties
of them are suppressed. The @code{-p} flag causes a default path to be
searched instead of that in @code{$path}. With the @code{-v} flag, @code{command}
is similar to @code{whence} and with @code{-V}, it is equivalent to @code{whence
-v}.
@end quotation

@geindex exec; Function

@code{exec} [ @code{-cl} ] [ @code{-a} @var{argv0} ]

@quotation

The following command together with any arguments is run in place
of the current process, rather than as a sub-process.  The shell does not
fork and is replaced.  The shell does not invoke @code{TRAPEXIT}, nor does it
source @code{zlogout} files.
The options are provided for compatibility with other shells.

The @code{-c} option clears the environment.

The @code{-l} option is equivalent to the @code{-} precommand modifier, to
treat the replacement command as a login shell; the command is executed
with a @code{-} prepended to its @code{argv[0]} string.  This flag has no effect
if used together with the @code{-a} option.

The @code{-a} option is used to specify explicitly the @code{argv[0]} string
(the name of the command as seen by the process itself) to be used by the
replacement command and is directly equivalent to setting a value
for the @code{ARGV0} environment variable.
@end quotation

@geindex nocorrect; Function

@code{nocorrect}

@quotation

Spelling correction is not done on any of the words.  This must appear
before any other precommand modifier, as it is interpreted immediately,
before any parsing is done.  It has no effect in non-interactive shells.
@end quotation

@geindex noglob; Function

@code{noglob}

@quotation

Filename generation (globbing) is not performed on any of the words.
@end quotation

@c historic nodename: Complex Commands

@node Complex Commands,Alternate Forms For Complex Commands,Precommand Modifiers,Shell Grammar
@anchor{Zsh/grammar complex-commands}@anchor{2b}
@section Complex Commands


@geindex complex commands; Command

@geindex commands@comma{} complex; Command

A `complex command' in zsh is one of the following:

@geindex if; Function

@geindex if construct; Command

@code{if} @var{list} @code{then} @var{list} [ @code{elif} @var{list} @code{then} @var{list} ] … [ @code{else} @var{list} ] @code{fi}

@quotation

The @code{if} @var{list} is executed, and if it returns a zero exit status,
the @code{then} @var{list} is executed.
Otherwise, the @code{elif} @var{list} is executed and if its status is zero,
the @code{then} @var{list} is executed.
If each @code{elif} @var{list} returns nonzero status, the @code{else} @var{list}
is executed.
@end quotation

@geindex for; Function

@geindex for loops; Command

@geindex loops@comma{} for; Command

@code{for} @var{name} … [ @code{in} @var{word} … ] @var{term} @code{do} @var{list} @code{done}

@quotation

Expand the list of @var{word}s, and set the parameter
@var{name} to each of them in turn, executing @var{list}
each time.  If the @code{in} @var{word} is omitted,
use the positional parameters instead of the @var{word}s.
If any @var{name} has been declared as a named reference,
the corresponding @var{word} is treated as the name of a
parameter and @var{name} is made a reference to that.
Note that for the positional parameters, this treats the
value of each positional as parameter name rather than
creating a reference to the position.

The @var{term} consists of one or more newline or @code{;}
which terminate the @var{word}s, and are optional when the
@code{in} @var{word} is omitted.

More than one parameter @var{name} can appear before the list of
@var{word}s.  If @var{N} @var{name}s are given, then on each execution of the
loop the next @var{N} @var{word}s are assigned to the corresponding
parameters.  If there are more @var{name}s than remaining @var{word}s, the
remaining parameters are each set to the empty string.  Execution of the
loop ends when there is no remaining @var{word} to assign to the first
@var{name}.  It is only possible for @code{in} to appear as the first @var{name}
in the list, else it will be treated as marking the end of the list.
@end quotation

@code{for ((} [@var{expr1}] @code{;} [@var{expr2}] @code{;} [@var{expr3}] @code{)) do} @var{list} @code{done}

@quotation

The arithmetic expression @var{expr1} is evaluated first (see
`Arithmetic Evaluation').  The arithmetic expression
@var{expr2} is repeatedly evaluated until it evaluates to zero and
when non-zero, @var{list} is executed and the arithmetic expression
@var{expr3} evaluated.  If any expression is omitted, then it behaves
as if it evaluated to 1.
@end quotation

@geindex while; Function

@geindex while loops; Command

@geindex loops@comma{} while; Command

@code{while} @var{list} @code{do} @var{list} @code{done}

@quotation

Execute the @code{do} @var{list} as long as the @code{while} @var{list}
returns a zero exit status.
@end quotation

@geindex until; Function

@geindex until loops; Command

@geindex loops@comma{} until; Command

@code{until} @var{list} @code{do} @var{list} @code{done}

@quotation

Execute the @code{do} @var{list} as long as @code{until} @var{list}
returns a nonzero exit status.
@end quotation

@geindex repeat; Function

@geindex repeat loops; Command

@geindex loops@comma{} repeat; Command

@code{repeat} @var{word} @code{do} @var{list} @code{done}

@quotation

@var{word} is expanded and treated as an arithmetic expression,
which must evaluate to a number @var{n}.
@var{list} is then executed @var{n} times.

The @code{repeat} syntax is disabled by default when the
shell starts in a mode emulating another shell.  It can be enabled
with the command @code{enable -r repeat}
@end quotation

@geindex case; Function

@geindex case selection; Command

@geindex selection@comma{} case; Command

@code{case} @var{word} @code{in} [ [@code{(}] @var{pattern} [ @code{|} @var{pattern} ] … @code{)} @var{list} (@code{;;|;&|;|}) ] … @code{esac}

@quotation

Execute the @var{list} associated with the first @var{pattern}
that matches @var{word}, if any.  The form of the patterns
is the same as that used for filename generation.  See
@ref{17,,Filename Generation}.

Note further that, unless the @code{SH_GLOB} option is set, the whole
pattern with alternatives is treated by the shell as equivalent to a
group of patterns within parentheses, although white space may appear
about the parentheses and the vertical bar and will be stripped from the
pattern at those points.  White space may appear elsewhere in the
pattern; this is not stripped.  If the @code{SH_GLOB} option is set, so
that an opening parenthesis can be unambiguously treated as part of the
case syntax, the expression is parsed into separate words and these are
treated as strict alternatives (as in other shells).

If the @var{list} that is executed is terminated with @code{;&} rather than
@code{;;}, the following list is also executed.  The rule for
the terminator of the following list @code{;;}, @code{;&} or @code{;|} is
applied unless the @code{esac} is reached.

If the @var{list} that is executed is terminated with @code{;|} the
shell continues to scan the @var{pattern}s looking for the next match,
executing the corresponding @var{list}, and applying the rule for
the corresponding terminator @code{;;}, @code{;&} or @code{;|}.
Note that @var{word} is not re-expanded; all applicable @var{pattern}s
are tested with the same @var{word}.
@end quotation

@geindex select; Function

@geindex user selection; Command

@geindex selection@comma{} user; Command

@code{select} @var{name} [ @code{in} @var{word} … @var{term} ] @code{do} @var{list} @code{done}

@quotation

where @var{term} is one or more newline or @code{;} to terminate the @var{word}s.
.. index:: single: REPLY, use of; Variable

Print the set of @var{word}s, each preceded by a number.
If the @code{in} @var{word} is omitted, use the positional parameters.
The @code{PROMPT3} prompt is printed and a line is read from the line editor
if the shell is interactive and that is active, or else standard input.
If this line consists of the
number of one of the listed @var{word}s, then the parameter @var{name}
is set to the @var{word} corresponding to this number.
If this line is empty, the selection list is printed again.
Otherwise, the value of the parameter @var{name} is set to null.
The contents of the line read from standard input is saved
in the parameter @code{REPLY}.  @var{list} is executed
for each selection until a break or end-of-file is encountered.
@end quotation

@geindex subshell; Command

@code{(} @var{list} @code{)}

@quotation

Execute @var{list} in a subshell.  Traps set by the @code{trap} builtin
are reset to their default values while executing @var{list}; an
exception is that ignored signals will continue to be ignored
if the option @code{POSIXTRAPS} is set.
@end quotation

@code{@{} @var{list} @code{@}}

@quotation

Execute @var{list}.
@end quotation

@geindex always; Function

@geindex always blocks; Command

@geindex try blocks; Command

@code{@{} @var{try-list} @code{@} always @{} @var{always-list} @code{@}}

@quotation

First execute @var{try-list}.  Regardless of errors, or @code{break} or
@code{continue} commands encountered within @var{try-list},
execute @var{always-list}.  Execution then continues from the
result of the execution of @var{try-list}; in other words, any error,
or @code{break} or @code{continue} command is treated in the
normal way, as if @var{always-list} were not present.  The two
chunks of code are referred to as the `try block’ and the `always block’.

Optional newlines or semicolons may appear after the @code{always};
note, however, that they may `not' appear between the preceding
closing brace and the @code{always}.

An `error’ in this context is a condition such as a syntax error which
causes the shell to abort execution of the current function, script, or
list.  Syntax errors encountered while the shell is parsing the
code do not cause the @var{always-list} to be executed.  For example,
an erroneously constructed @code{if} block in @var{try-list} would cause the
shell to abort during parsing, so that @var{always-list} would not be
executed, while an erroneous substitution such as @code{$@{*foo*@}} would
cause a run-time error, after which @var{always-list} would be executed.

An error condition can be tested and reset with the special integer
variable @code{TRY_BLOCK_ERROR}.  Outside an @var{always-list} the value is
irrelevant, but it is initialised to @code{-1}.  Inside @var{always-list}, the
value is 1 if an error occurred in the @var{try-list}, else 0.  If
@code{TRY_BLOCK_ERROR} is set to 0 during the @var{always-list}, the error
condition caused by the @var{try-list} is reset, and shell execution
continues normally after the end of @var{always-list}.  Altering the value
during the @var{try-list} is not useful (unless this forms part of an
enclosing @code{always} block).

Regardless of @code{TRY_BLOCK_ERROR}, after the end of @var{always-list} the
normal shell status @code{$?} is the value returned from @var{try-list}.
This will be non-zero if there was an error, even if @code{TRY_BLOCK_ERROR}
was set to zero.

The following executes the given code, ignoring any errors it causes.
This is an alternative to the usual convention of protecting code by
executing it in a subshell.

@example
 @{
     # code which may cause an error
   @} always @{
     # This code is executed regardless of the error.
     (( TRY_BLOCK_ERROR = 0 ))
 @}
 # The error condition has been reset.
@end example

When a @code{try} block occurs outside of any function,
a @code{return} or a @code{exit} encountered in @var{try-list} does `not' cause
the execution of @var{always-list}.  Instead, the shell exits immediately
after any @code{EXIT} trap has been executed.
Otherwise, a @code{return} command encountered in @var{try-list} will cause the
execution of @var{always-list}, just like @code{break} and @code{continue}.
@end quotation

@geindex function; Function

@code{function} [ @code{-T} ] @var{word} … [ @code{()} ] [ @var{term} ] @code{@{} @var{list} @code{@}}

@var{word} … @code{()} [ @var{term} ] @code{@{} @var{list} @code{@}}

@var{word} … @code{()} [ @var{term} ] @var{command}

@quotation

where @var{term} is one or more newline or @code{;}.
Define a function which is referenced by any one of @var{word}.
Normally, only one @var{word} is provided; multiple @var{word}s
are usually only useful for setting traps.
The body of the function is the @var{list} between
the @code{@{} and @code{@}}.  See `Functions'.

The options of @code{function} have the following meanings:


@table @option

@item @w{-}T

Enable tracing for this function, as though with @code{functions -T}.  See the
documentation of the @code{-f} option to the @code{typeset} builtin, in
@ref{2c,,Shell Builtin Commands}.
@end table

If the option @code{SH_GLOB} is set for compatibility with other shells, then
whitespace may appear between the left and right parentheses when
there is a single @var{word};  otherwise, the parentheses will be treated as
forming a globbing pattern in that case.

In any of the forms above, a redirection may appear outside the
function body, for example

@example
 func() @{ ... @} 2>&1
@end example

The redirection is stored with the function and applied whenever the
function is executed.  Any variables in the redirection are expanded
at the point the function is executed, but outside the function scope.
@end quotation

@geindex timing; Command

@geindex time; Function

@code{time} [ @var{pipeline} ]

@quotation

The @var{pipeline} is executed, and timing statistics are
reported on the standard error in the form specified
by the @code{TIMEFMT} parameter.
If @var{pipeline} is omitted, print statistics about the
shell process and its children.
@end quotation

@geindex conditional expression; Command

@geindex [[; Function

@code{[[} @var{exp} @code{]]}

@quotation

Evaluates the conditional expression @var{exp}
and return a zero exit status if it is true.
See `Conditional Expressions'
for a description of @var{exp}.
@end quotation

@c historic nodename: Alternate Forms For Complex Commands

@node Alternate Forms For Complex Commands,Reserved Words,Complex Commands,Shell Grammar
@anchor{Zsh/grammar alternate-forms-for-complex-commands}@anchor{2d}
@section Alternate Forms For Complex Commands


@geindex alternate forms for complex commands; Command

@geindex commands@comma{} alternate forms for complex; Command

Many of zsh’s complex commands have alternate forms.  These are
non-standard and are likely not to be obvious even to seasoned shell
programmers; they should not be used anywhere that portability of shell
code is a concern.

The short versions below only work if @var{sublist} is of the form @code{@{}
@var{list} @code{@}} or if the @code{SHORT_LOOPS} option is set.  For the @code{if},
@code{while} and @code{until} commands, in both these cases the test part of the
loop must also be suitably delimited, such as by @code{[[} @var{…} @code{]]} or
@code{((} @var{…} @code{))},
else the end of the test will not be recognized.  For the
@code{for}, @code{repeat}, @code{case} and @code{select} commands no such special form
for the arguments is necessary, but the other condition (the special form
of @var{sublist} or use of the @code{SHORT_LOOPS} option) still applies.
The @code{SHORT_REPEAT} option is available to enable the short version only
for the @code{repeat} command.

@code{if} @var{list} @code{@{} @var{list} @code{@}} [ @code{elif} @var{list} @code{@{} @var{list} @code{@}} ] … [ @code{else @{} @var{list} @code{@}} ]

@quotation

An alternate form of @code{if}.  The rules mean that

@example
 if [[ -o ignorebraces ]] @{
   print yes
 @}
@end example

works, but

@example
 if true @{  # Does not work!
   print yes
 @}
@end example

does `not', since the test is not suitably delimited.
@end quotation

@code{if} @var{list} @var{sublist}

@quotation

A short form of the alternate @code{if}.  The same limitations on the form of
@var{list} apply as for the previous form.
@end quotation

@code{for} @var{name} … @code{(} @var{word} … @code{)} @var{sublist}

@quotation

A short form of @code{for}.
@end quotation

@code{for} @var{name} … [ @code{in} @var{word} … ] @var{term} @var{sublist}

@quotation

where @var{term} is at least one newline or @code{;}.
Another short form of @code{for}.
@end quotation

@code{for ((} [@var{expr1}] @code{;} [@var{expr2}] @code{;} [@var{expr3}] @code{))} @var{sublist}

@quotation

A short form of the arithmetic @code{for} command.
@end quotation

@geindex foreach; Function

@code{foreach} @var{name} … @code{(} @var{word} … @code{)} @var{list} @code{end}

@quotation

Another form of @code{for}.
@end quotation

@code{while} @var{list} @code{@{} @var{list} @code{@}}

@quotation

An alternative form of @code{while}.  Note the limitations on the form of
@var{list} mentioned above.
@end quotation

@code{until} @var{list} @code{@{} @var{list} @code{@}}

@quotation

An alternative form of @code{until}.  Note the limitations on the form of
@var{list} mentioned above.
@end quotation

@code{repeat} @var{word} @var{sublist}

@quotation

This is a short form of @code{repeat}.
@end quotation

@code{case} @var{word} @code{@{} [ [@code{(}] @var{pattern} [ @code{|} @var{pattern} ] … @code{)} @var{list} (@code{;;|;&|;|}) ] … @code{@}}

@quotation

An alternative form of @code{case}.
@end quotation

@code{select} @var{name} [ @code{in} @var{word} … @var{term} ] @var{sublist}

@quotation

where @var{term} is at least one newline or @code{;}.
A short form of @code{select}.
@end quotation

@code{function} @var{word} … [ @code{()} ] [ @var{term} ] @var{sublist}

@quotation

This is a short form of @code{function}.
@end quotation

@c historic nodename: Reserved Words

@node Reserved Words,Errors,Alternate Forms For Complex Commands,Shell Grammar
@anchor{Zsh/grammar reserved-words}@anchor{2e}
@section Reserved Words


@geindex reserved words; Command

@geindex disable@comma{} use of; Function

The following words are recognized as reserved words when used as the first
word of a command unless quoted or disabled using @code{disable -r}:

@code{do done esac then elif else fi for case
if while function repeat time until
select coproc nocorrect foreach end ! [[ @{ @}
declare export float integer local readonly typeset}

Additionally, @code{@}} is recognized in any position if neither the
@code{IGNORE_BRACES} option nor the @code{IGNORE_CLOSE_BRACES} option is set.

@c historic nodename: Errors

@node Errors,Comments,Reserved Words,Shell Grammar
@anchor{Zsh/grammar errors}@anchor{2f}
@section Errors


@geindex errors@comma{} handling of; Command

Certain errors are treated as fatal by the shell: in an interactive
shell, they cause control to return to the command line, and in a
non-interactive shell they cause the shell to be aborted.  In older
versions of zsh, a non-interactive shell running a script would not
abort completely, but would resume execution at the next command to be
read from the script, skipping the remainder of any functions or
shell constructs such as loops or conditions; this somewhat illogical
behaviour can be recovered by setting the option @code{CONTINUE_ON_ERROR}.

Fatal errors found in non-interactive shells include:

@quotation


@itemize *

@item 
Failure to parse shell options passed when invoking the shell

@item 
Failure to change options with the @code{set} builtin

@item 
Parse errors of all sorts, including failures to parse
@end itemize

mathematical expressions
* Failures to set or modify variable behaviour with @code{typeset},
@code{local}, @code{declare}, @code{export}, @code{integer}, @code{float}
* Execution of incorrectly positioned loop control structures
(@code{continue}, @code{break})
* Attempts to use regular expression with no regular expression
module available
* Failure to create a pipe needed for a pipeline
* Failure to create a multio
* Failure to autoload a module needed for a declared shell feature
* Errors creating command or process substitutions
* Syntax errors in glob qualifiers
* File generation errors where not caught by the option @code{BAD_PATTERN}
* All bad patterns used for matching within case statements
* File generation failures where not caused by @code{NOMATCH} or
similar options
* All file generation errors where the pattern was used to create a
multio
* Memory errors where detected by the shell
* Invalid subscripts to shell variables
* Attempts to assign read-only variables
* Logical errors with variables such as assignment to the wrong type
* Use of invalid variable names
* Errors in variable substitution syntax
* Failure to convert characters in @code{$'...'} expressions
@end quotation

If the @code{POSIX_BUILTINS} option is set, more errors associated with
shell builtin commands are treated as fatal, as specified by the POSIX
standard.

@c historic nodename: Comments

@node Comments,Aliasing,Errors,Shell Grammar
@anchor{Zsh/grammar comments}@anchor{30}
@section Comments


@geindex comments; Command

@geindex INTERACTIVE_COMMENTS@comma{} use of; Program

@geindex histchars@comma{} use of; Variable

In non-interactive shells, or in interactive shells with the
@code{INTERACTIVE_COMMENTS} option set, a word beginning
with the third character of the @code{histchars} parameter
(@code{#} by default) causes that word and all the following
characters up to a newline to be ignored.

@c historic nodename: Aliasing

@node Aliasing,Quoting,Comments,Shell Grammar
@anchor{Zsh/grammar aliasing}@anchor{31}
@section Aliasing


@geindex aliasing; Command

Every eligible `word' in the shell input is checked to see if there
is an alias defined for it.
If so, it is replaced by the text of the alias if it is in command
position (if it could be the first word of a simple command),
or if the alias is global.
If the replacement text ends with a space, the next word in the shell input
is always eligible for purposes of alias expansion.

It is an error for the function name, @var{word}, in the sh-compatible function
definition syntax @var{word} @code{()} … to be a word that resulted
from alias expansion, unless the @code{ALIAS_FUNC_DEF} option is set.

@geindex alias@comma{} use of; Function

@geindex aliases@comma{} global; Command

An alias is defined using the @code{alias} builtin; global aliases
may be defined using the @code{-g} option to that builtin.

A `word' is defined as:

@quotation


@itemize *

@item 
Any plain string or glob pattern

@item 
Any quoted string, using any quoting method (note that the quotes
@end itemize

must be part of the alias definition for this to be eligible)
* Any parameter reference or command substitution
* Any series of the foregoing, concatenated without whitespace or
other tokens between them
* Any reserved word (@code{case}, @code{do}, @code{else}, etc.)
* With global aliasing, any command separator, any redirection
operator, and @code{(} or @code{)} when not part of a glob pattern
@end quotation

Alias expansion is done on the shell input before any other expansion
except history expansion.  Therefore, if an alias is defined for the
word @code{foo}, alias expansion may be avoided by quoting part of the
word, e.g. @code{\foo}.  Any form of quoting works, although there is
nothing to prevent an alias being defined for the quoted form such as
@code{\foo} as well.

In particular, note that quoting must be used when using @code{unalias} to remove
global aliases:

@example
 % alias -g foo=bar
 % unalias foo
 unalias: no such hash table element: bar
 % unalias \foo
 %
@end example

When @code{POSIX_ALIASES} is set, only plain unquoted strings are eligible
for aliasing.  The @code{alias} builtin does not reject ineligible aliases,
but they are not expanded.

For use with completion, which would remove an initial backslash followed
by a character that isn’t special, it may be more convenient to quote the
word by starting with a single quote, i.e. @code{'foo}; completion will
automatically add the trailing single quote.

@menu
* Alias Difficulties:: 

@end menu

@node Alias Difficulties,,,Aliasing
@anchor{Zsh/grammar alias-difficulties}@anchor{32}
@subsection Alias Difficulties


Although aliases can be used in ways that bend normal shell syntax, not
every string of non-white-space characters can be used as an alias.

Any set of characters not listed as a word above is not a word, hence no
attempt is made to expand it as an alias, no matter how it is defined
(i.e. via the builtin or the special parameter @code{aliases} described in
@ref{33,,The zsh/parameter Module}).
However, as noted in the case of @code{POSIX_ALIASES} above, the shell does
not attempt to deduce whether the string corresponds to a word at the
time the alias is created.

For example, an expression containing an @code{=} at the start of
a command line is an assignment and cannot be expanded as an alias;
a lone @code{=} is not an assignment but can only be set as an alias
using the parameter, as otherwise the @code{=} is taken part of the
syntax of the builtin command.

It is not presently possible to alias the @code{((} token that
introduces arithmetic expressions, because until a full statement has been
parsed, it cannot be distinguished from two consecutive @code{(}
tokens introducing nested subshells.
Also, if a separator such as @code{&&} is aliased,
@code{\&&} turns into the two tokens @code{\&} and @code{&}, each of which may
have been aliased separately.  Similarly for @code{\<<}, @code{\>|}, etc.

There is a commonly encountered problem with aliases
illustrated by the following code:

@example
 alias echobar='echo bar'; echobar
@end example

This prints a message that the command @code{echobar} could not be found.
This happens because aliases are expanded when the code is read in;
the entire line is read in one go, so that when @code{echobar} is executed it
is too late to expand the newly defined alias.  This is often
a problem in shell scripts, functions, and code executed with @code{source}
or @code{.}.  Consequently, use of functions rather than aliases is
recommended in non-interactive code.

@c historic nodename: Quoting

@node Quoting,,Aliasing,Shell Grammar
@anchor{Zsh/grammar quoting}@anchor{34}
@section Quoting


@geindex quoting; Command

A character may be `quoted' (that is, made
to stand for itself) by preceding it with a @code{\}.
@code{\} followed by a newline is ignored.

A string enclosed between @code{$}’ and >>`@w{`}<<@code{' is
processed the same way as the string arguments of the
`@w{`}print} builtin, and the resulting string is considered to be
entirely quoted.  A literal >>`@w{`}<<@code{' character can be included in the
string by using the `@w{`}\}’ escape.

@geindex RC_QUOTES@comma{} use of; Program

All characters enclosed between a pair of single quotes (@code{'@w{'}}) that
is not preceded by a @code{$} are quoted.  A single quote cannot appear
within single quotes unless the option @code{RC_QUOTES} is set, in which case
a pair of single quotes are turned into a single quote.  For example,

@example
 print '@w{'}'@w{'}
@end example

outputs nothing apart from a newline if @code{RC_QUOTES} is not set, but one
single quote if it is set.

Inside double quotes (@code{""}), parameter and
command substitution occur, and @code{\} quotes the characters
@code{\}, @code{`\}`’, @code{"}, @code{$}, and the first character
of @code{$histchars} (default @code{!}).

@c historic nodename: Redirection

@node Redirection,Command Execution,Shell Grammar,Top
@anchor{Zsh/redirect doc}@anchor{35}@anchor{Zsh/redirect redirection}@anchor{36}
@chapter Redirection


@geindex redirection; Command


@geindex file descriptors; Command

@geindex descriptors@comma{} file; Command

If a command is followed by @code{&}
and job control is not active,
then the default standard input
for the command is the empty file @code{/dev/null}.
Otherwise, the environment for the execution of a command contains the
file descriptors of the invoking shell as modified by
input/output specifications.

The following may appear anywhere in a simple command
or may precede or follow a complex command.
Expansion occurs before @var{word} or @var{digit}
is used except as noted below.
If the result of substitution on @var{word}
produces more than one filename,
redirection occurs for each
separate filename in turn.

@code{<} @var{word}

@quotation

Open file @var{word} for reading as standard input.
It is an error to open a file in this fashion if it does not exist.
@end quotation

@code{<>} @var{word}

@quotation

Open file @var{word} for reading and writing as standard input.
If the file does not exist then it is created.
@end quotation

@code{>} @var{word}

@quotation

Open file @var{word} for writing as standard output.
If the file does not exist then it is created.
If the file exists, and the @code{CLOBBER} option is unset,
this causes an error;
otherwise, it is truncated to zero length.
@end quotation

@code{>|} @var{word}

@code{>!} @var{word}

@quotation

Same as @code{>}, except that the file is truncated to zero length
if it exists, regardless of @code{CLOBBER}.
@end quotation

@code{>>} @var{word}

@quotation

Open file @var{word} for writing in append mode as standard output.
If the file does not exist, and the @code{CLOBBER} and @code{APPEND_CREATE}
options are both unset, this causes an error;
otherwise, the file is created.
@end quotation

@code{>>|} @var{word}

@code{>>!} @var{word}

@quotation

Same as @code{>>}, except that the file is created if it does not
exist, regardless of @code{CLOBBER} and @code{APPEND_CREATE}.
@end quotation

@code{<<[-}] @var{word}

@quotation

The shell input is read up to a line that is the same as
@var{word}, or to an end-of-file.
No parameter expansion, command substitution or
filename generation is performed on @var{word}.
The resulting document, called a
`here-document', becomes the standard input.

If any character of @var{word} is quoted with
single or double quotes or a @code{\},
no interpretation is placed upon the characters of the document.
Otherwise, parameter and command substitution
occurs, @code{\} followed by a newline is removed,
and @code{\} must be used to quote the characters
@code{\}, @code{$}, @code{`\}`’ and the first character of @var{word}.

Note that @var{word} itself does not undergo shell expansion.  Backquotes
in @var{word} do not have their usual effect; instead they behave
similarly to double quotes, except that the backquotes themselves are
passed through unchanged.  (This information is given for completeness
and it is not recommended that backquotes be used.)  Quotes in the form
@code{$'}@var{…}@code{'} have their standard effect of expanding backslashed
references to special characters.

If @code{<<-} is used, then all leading
tabs are stripped from @var{word} and from the document.
@end quotation

@code{<<<} @var{word}

@quotation

Perform shell expansion on @var{word} and pass the result
to standard input.  This is known as a `here-string'.
Compare the use of @var{word} in here-documents above, where @var{word}
does not undergo shell expansion.  The result will have a trailing newline
after it.
@end quotation

@code{<&} @var{number}

@code{>&} @var{number}

@quotation

The standard input/output is duplicated from file descriptor
@var{number} (see @code{dup2(2)}).
@end quotation

@code{<& -}

@code{>& -}

@quotation

Close the standard input/output.
@end quotation

@code{<& p}

@code{>& p}

@quotation

The input/output from/to the coprocess is moved to the standard input/output.
@end quotation

@code{>&} @var{word}

@code{&>} @var{word}

@quotation

(Except where @code{>&} @var{word} matches one of the above syntaxes;
@code{&>} can always be used to avoid this ambiguity.)
Redirects both standard output and standard error (file descriptor 2)
in the manner of @code{>} @var{word}.
Note that this does `not' have the same effect as @code{>} @var{word} @code{2>&1}
in the presence of multios (see the section below).
@end quotation

@code{>&|} @var{word}

@code{>&!} @var{word}

@code{&>|} @var{word}

@code{&>!} @var{word}

@quotation

Redirects both standard output and standard error (file descriptor 2)
in the manner of @code{>|} @var{word}.
@end quotation

@code{>>&} @var{word}

@code{&>>} @var{word}

@quotation

Redirects both standard output and standard error (file descriptor 2)
in the manner of @code{>>} @var{word}.
@end quotation

@code{>>&|} @var{word}

@code{>>&!} @var{word}

@code{&>>|} @var{word}

@code{&>>!} @var{word}

@quotation

Redirects both standard output and standard error (file descriptor 2)
in the manner of @code{>>|} @var{word}.
@end quotation

If one of the above is preceded by a digit, then the file
descriptor referred to is that specified by the digit
instead of the default 0 or 1.
The order in which redirections are specified is significant.
The shell evaluates each redirection in terms of the
(`file descriptor', `file')
association at the time of evaluation.
For example:


@quotation

… @code{1>}@var{fname} @code{2>&1}
@end quotation

first associates file descriptor 1 with file @var{fname}.
It then associates file descriptor 2 with the file associated with file
descriptor 1 (that is, @var{fname}).
If the order of redirections were reversed,
file descriptor 2 would be associated
with the terminal (assuming file descriptor 1 had been)
and then file descriptor 1 would be associated with file @var{fname}.

The @code{|&} command separator described in
@ref{37,,Simple Commands & Pipelines}
is a shorthand for @code{2>&1 |}.

The various forms of process substitution, @code{<(}@var{list}@code{)},
and @code{=(}@var{list}@code{)} for input and
@code{>(}@var{list}@code{)} for output, are often used together with
redirection.  For example, if @var{word} in an output redirection is of the
form @code{>(}@var{list}@code{)} then the output is piped to the
command represented by @var{list}.  See @ref{38,,Process Substitution}.
Opening file descriptors using parameters
——————————————————————————–
.. index:: single: file descriptors, use with parameters; Command

@geindex parameters@comma{} for using file descriptors; Command

When the shell is parsing arguments to a command, and the shell option
@code{IGNORE_BRACES} is not set, a different form of redirection is allowed:
instead of a digit before the operator there is a valid shell identifier
enclosed in braces.  The shell will open a new file descriptor that
is guaranteed to be at least 10 and set the parameter named by the
identifier to the file descriptor opened.  No whitespace is allowed
between the closing brace and the redirection character.  For example:


@quotation

… @code{@{myfd@}>&1}
@end quotation

This opens a new file descriptor that is a duplicate of file descriptor
1 and sets the parameter @code{myfd} to the number of the file descriptor,
which will be at least 10.  The new file descriptor can be written to using
the syntax @code{>&$myfd}.  The file descriptor remains open in subshells
and forked external executables.

The syntax @code{@{}@var{varid}@code{@}>&-}, for example @code{@{myfd@}>&-}, may be used
to close a file descriptor opened in this fashion.  Note that the
parameter given by @var{varid} must previously be set to a file descriptor
in this case.

It is an error to open or close a file descriptor in this fashion when the
parameter is readonly.  However, it is not an error to read or write a file
descriptor using @code{<&$}@var{param} or @code{>&$}@var{param} if @var{param} is
readonly.

If the option @code{CLOBBER} is unset, it is an error to open a file
descriptor using a parameter that is already set to an open file descriptor
previously allocated by this mechanism.  Unsetting the parameter before
using it for allocating a file descriptor avoids the error.

Note that this mechanism merely allocates or closes a file descriptor; it
does not perform any redirections from or to it.  It is usually convenient
to allocate a file descriptor prior to use as an argument to @code{exec}.
The syntax does not in any case work when used around complex commands
such as parenthesised subshells or loops, where the opening brace is
interpreted as part of a command list to be executed in the current shell.

The following shows a typical sequence of allocation, use, and closing of a
file descriptor:

@example
 integer myfd
 exec @{myfd@}>~/logs/mylogfile.txt
 print This is a log message. >&$myfd
 exec @{myfd@}>&-
@end example

Note that the expansion of the variable in the expression @code{>&$myfd}
occurs at the point the redirection is opened.  This is after the expansion
of command arguments and after any redirections to the left on the command
line have been processed.

@menu
* Multios:: 
* Redirections with no command:: 

@end menu

@node Multios,Redirections with no command,,Redirection
@anchor{Zsh/redirect id2}@anchor{39}@anchor{Zsh/redirect multios}@anchor{3a}
@section Multios


@geindex multios; Command

@geindex MULTIOS@comma{} use of; Program

If the user tries to open a file descriptor for writing more than once,
the shell opens the file descriptor as a pipe to a process that copies
its input to all the specified outputs, similar to `tee',
provided the @code{MULTIOS} option is set, as it is by default.  Thus:

@example
 date >foo >bar
@end example

writes the date to two files, named @code{foo} and @code{bar}.
Note that a pipe is an implicit redirection; thus

@example
 date >foo | cat
@end example

writes the date to the file @code{foo}, and also pipes it to cat.

Note that the shell opens all the files to be used in the multio process
immediately, not at the point they are about to be written.

Note also that redirections are always expanded in order.  This happens
regardless of the setting of the @code{MULTIOS} option, but with the option
in effect there are additional consequences. For example,
the meaning of the expression @code{>&1} will change after a previous
redirection:

@example
 date >&1 >output
@end example

In the case above, the @code{>&1} refers to the standard output at the
start of the line; the result is similar to the @code{tee} command.
However, consider:

@example
 date >output >&1
@end example

As redirections are evaluated in order, when the @code{>&1} is encountered
the standard output is set to the file @code{output} and another copy of
the output is therefore sent to that file.  This is unlikely to be what
is intended.

If the @code{MULTIOS}
option is set, the word after a redirection operator is also subjected
to filename generation (globbing).  Thus

@example
 : > *
@end example

will truncate all files in the current directory,
assuming there’s at least one.  (Without the @code{MULTIOS}
option, it would create an empty file called @code{*}.)
Similarly, you can do

@example
 echo exit 0 >> *.sh
@end example

If the user tries to open a file descriptor for reading more than once,
the shell opens the file descriptor as a pipe to a process that copies
all the specified inputs to its output in the order specified, provided
the @code{MULTIOS} option is set.  It should be noted that each file is
opened immediately, not at the point where it is about to be read:
this behaviour differs from @code{cat}, so if strictly standard behaviour
is needed, @code{cat} should be used instead.

Thus

@example
 sort <foo <fubar
@end example

or even

@example
 sort <f@{oo,ubar@}
@end example

is equivalent to @code{cat foo fubar | sort}.

Expansion of the redirection argument occurs at the point the redirection
is opened, at the point described above for the expansion of the variable
in @code{>&$myfd}.

Note that a pipe is an implicit redirection; thus

@example
 cat bar | sort <foo
@end example

is equivalent to @code{cat bar foo | sort} (note the order of the inputs).

If the @code{MULTIOS} option is `un'set,
each redirection replaces the previous redirection for that file descriptor.
However, all files redirected to are actually opened, so

@example
 echo Hello > bar > baz
@end example

when @code{MULTIOS} is unset will truncate @code{bar}, and write @code{Hello}
into @code{baz}.

There is a problem when an output multio is attached to an external
program.  A simple example shows this:

@example
 cat file >file1 >file2
 cat file1 file2
@end example

Here, it is possible that the second @code{cat} will not display the full
contents of @code{file1} and @code{file2} (i.e. the original contents of
@code{file} repeated twice).

The reason for this is that the multios are spawned after the @code{cat}
process is forked from the parent shell, so the parent shell does not
wait for the multios to finish writing data.  This means the command as
shown can exit before @code{file1} and @code{file2} are completely written.
As a workaround, it is possible to run the @code{cat} process as part of a
job in the current shell:

@example
 @{ cat file @} >file >file2
@end example

Here, the @code{@{}@var{…}@code{@}} job will pause to wait for both files to be
written.

@node Redirections with no command,,Multios,Redirection
@anchor{Zsh/redirect redirections-with-no-command}@anchor{3b}
@section Redirections with no command


When a simple command consists of one or more redirection operators
and zero or more parameter assignments, but no command name, zsh can
behave in several ways.

@geindex NULLCMD@comma{} use of; Variable

@geindex CSH_NULLCMD@comma{} use of; Program

If the parameter @code{NULLCMD} is not set or the option @code{CSH_NULLCMD} is
set, an error is caused.  This is the `csh' behavior and @code{CSH_NULLCMD}
is set by default when emulating `csh'.

@geindex SH_NULLCMD@comma{} use of; Program

If the option @code{SH_NULLCMD} is set, the builtin @code{:} is inserted as a
command with the given redirections.  This is the default when emulating
`sh' or `ksh'.

@geindex READNULLCMD@comma{} use of; Variable

Otherwise, if the parameter @code{NULLCMD} is set, its value will be used as a
command with the given redirections.  If both @code{NULLCMD} and
@code{READNULLCMD} are set, then the value of the latter will be used instead
of that of the former when the redirection is an input.  The default for
@code{NULLCMD} is @code{cat} and for @code{READNULLCMD} is @code{more}. Thus

@example
 < file
@end example

shows the contents of @code{file} on standard output, with paging if that is a
terminal.  @code{NULLCMD} and @code{READNULLCMD} may refer to shell functions.

@c historic nodename: Command Execution

@node Command Execution,Functions,Redirection,Top
@anchor{Zsh/exec doc}@anchor{3c}@anchor{Zsh/exec command-execution}@anchor{3d}
@chapter Command Execution



@geindex command execution; Command

@geindex execution@comma{} of commands; Command

@geindex command not found@comma{} handling of; Command

@geindex command_not_found_handler; Function

If a command name contains no slashes, the shell attempts to locate
it.  If there exists a shell function by that name, the function
is invoked as described in `Functions'.  If there exists
a shell builtin by that name, the builtin is invoked.

@geindex path@comma{} use of; Variable

Otherwise, the shell searches each element of @code{$path} for a
directory containing an executable file by that name.

If execution fails: an error message is printed, and one of the
following values is returned.


@table @asis

@item 127

The search was unsuccessful.  The error message is
@code{command not found:} @var{cmd}.

@item 126

The executable file has insufficient permissions, is a
directory or special file, or is not a script and is in a format
unrecognized by the operating system.  The exact conditions and error
message are operating system-dependent; see
@code{execve(2)}.
@end table

If execution fails because the file is not in executable format,
and the file is not a directory, it is assumed to be a shell
script.  @code{/bin/sh} is spawned to execute it.  If the program
is a file beginning with @code{#!}, the remainder of the first line
specifies an interpreter for the program.  The shell will
execute the specified interpreter on operating systems that do
not handle this executable format in the kernel.

If no external command is found but a function @code{command_not_found_handler}
exists the shell executes this function with all
command line arguments.  The return status of the function becomes the
status of the command.  Note that the handler is executed in a
subshell forked to execute an external command, hence changes to
directories, shell parameters, etc. have no effect on the main shell.

@c historic nodename: Functions

@node Functions,Jobs & Signals,Command Execution,Top
@anchor{Zsh/func doc}@anchor{3e}@anchor{Zsh/func functions}@anchor{3f}
@chapter Functions



@geindex functions; Command

@geindex function@comma{} use of; Function

Shell functions are defined with the @code{function} reserved word or the
special syntax @var{funcname} @code{()}.
Shell functions are read in and stored internally.
Alias names are resolved when the function is read.
Functions are executed like commands with the arguments
passed as positional parameters.
(See Command Execution.)

Parameters declared by any of the @code{typeset} family of commands
during the execution of a function become `local' to the function
unless the @code{-g} option is used.  This is the `scope' of the
parameter, which extends dynamically to any other functions called by
the declaring function.  In most cases, local parameters take the
place of any other parameter having the same name that was assigned or
declared in an earlier function scope.
(See @ref{40,,Local Parameters}.)

A named parameter declared with the @code{-n} option to any of the
@code{typeset} acts as a reference to another parameter, which may
be at a different call level than the declaring function.  When the
@code{-u} option is also given, the referenced parameter is always
found at a call level above the function where the reference is
declared, otherwise the reference scope is dynamic.  For this reason,
it is good practice to declare a named reference as soon as the
referent parameter is in scope, and as early as possible in the
function if the reference is to a parameter in a calling scope.

A typical use of named references is to pass the name
of the referent as a positional parameter.  In this case it is
good practice to use the @code{-u} option to reference the calling
scope.  For example,

@example
 pop() @{
   local -nu ref=$1
   local last=$ref[$#ref]
   ref[$#ref]=()
   print -r -- $last
 @}
 array=( a list of five values )
 pop array
@end example

prints the word @code{values} and shortens @code{$array} to
@code{( a list of five )}.  With @code{-nu}, @code{ref} becomes a
reference to @code{array} in the caller.  There are no local parameters in
@code{pop} at the time @code{ref=$1} is assigned, so in this example @code{-u}
could have been omitted, but it makes the intention clear.

Functions execute in the same process as the caller and
share all files
and present working directory with the
caller.  A trap on @code{EXIT} set inside a function
is executed after the function completes in the environment
of the caller.

@geindex return@comma{} use of; Function

The @code{return} builtin is used to return from function calls.

@geindex functions@comma{} use of; Function

Function identifiers can be listed with the @code{functions} builtin.
.. index:: single: unfunction, use of; Function

Functions can be undefined with the @code{unfunction} builtin.

@menu
* Autoloading Functions:: 
* Anonymous Functions:: 
* Special Functions:: 

@end menu

@node Autoloading Functions,Anonymous Functions,,Functions
@anchor{Zsh/func autoloading-functions}@anchor{41}@anchor{Zsh/func id2}@anchor{42}
@section Autoloading Functions


@geindex autoloading functions; Command

@geindex functions@comma{} autoloading; Command

@geindex autoload@comma{} use of; Function

@geindex fpath@comma{} use of; Variable

A function can be marked as `undefined' using the @code{autoload} builtin
(or @code{functions -u} or @code{typeset -fu}).  Such a function has no
body.  When the function is first executed, the shell searches for its
definition using the elements of the @code{fpath} variable.  Thus to define
functions for autoloading, a typical sequence is:

@example
 fpath=(~/myfuncs $fpath)
 autoload myfunc1 myfunc2 ...
@end example

The usual alias expansion during reading will be suppressed if the
@code{autoload} builtin or its equivalent is given the option @code{-U}. This is
recommended for the use of functions supplied with the zsh distribution.
.. index:: single: zcompile, use of; Function

Note that for functions precompiled with the @code{zcompile} builtin command
the flag @code{-U} must be provided when the @code{.zwc} file is created, as the
corresponding information is compiled into the latter.

For each @var{element} in @code{fpath}, the shell looks for three possible
files, the newest of which is used to load the definition for the function:

@var{element}@code{.zwc}

@quotation

A file created with the @code{zcompile} builtin command, which is expected to
contain the definitions for all functions in the directory named
@var{element}.  The file is treated in the same manner as a directory
containing files for functions and is searched for the definition of the
function.   If the definition is not found, the search for a definition
proceeds with the other two possibilities described below.

If @var{element} already includes a @code{.zwc} extension (i.e. the extension
was explicitly given by the user), @var{element} is searched for the
definition of the function without comparing its age to that of other
files; in fact, there does not need to be any directory named @var{element}
without the suffix.  Thus including an element such as
@code{/usr/local/funcs.zwc} in @code{fpath} will speed up the search for
functions, with the disadvantage that functions included must be explicitly
recompiled by hand before the shell notices any changes.
@end quotation

@var{element}@code{/}@var{function}@code{.zwc}

@quotation

A file created with @code{zcompile}, which is expected to contain the
definition for @var{function}.  It may include other function definitions
as well, but those are neither loaded nor executed; a file found in this
way is searched `only' for the definition of @var{function}.
@end quotation

@var{element}@code{/}@var{function}

@quotation

A file of zsh command text, taken to be the definition for @var{function}.
@end quotation

In summary, the order of searching is, first, in the `parents of'
directories in @code{fpath} for the newer of either a compiled directory or
a directory in @code{fpath}; second, if more than one of these contains a
definition for the function that is sought, the leftmost in the @code{fpath}
is chosen; and third, within a directory, the newer of either a compiled
function or an ordinary function definition is used.

@geindex KSH_AUTOLOAD@comma{} use of; Program

If the @code{KSH_AUTOLOAD} option is set, or the file contains only a
simple definition of the function, the file’s contents will be executed.
This will normally define the function in question, but may also perform
initialization, which is executed in the context of the function execution,
and may therefore define local parameters.  It is an error if the function
is not defined by loading the file.

Otherwise, the function body (with no surrounding @var{funcname}@code{()
@{}@var{…`}`@}`@w{`}) is taken to be the complete contents of the file.  This
form allows the file to be used directly as an executable shell script.  If
processing of the file results in the function being re-defined, the
function itself is not re-executed.  To force the shell to perform
initialization and then call the function defined, the file should contain
initialization code (which will be executed then discarded) in addition to
a complete function definition (which will be retained for subsequent calls
to the function), and a call to the shell function, including any
arguments, at the end.

For example, suppose the autoload file @code{func} contains

@example
 func() @{ print This is func; @}
 print func is initialized
@end example

then @code{func; func} with @code{KSH_AUTOLOAD} set will produce both messages
on the first call, but only the message @code{This is func} on the second
and subsequent calls.  Without @code{KSH_AUTOLOAD} set, it will produce
the initialization message on the first call, and the other message on the
second and subsequent calls.

It is also possible to create a function that is not marked as autoloaded,
but which loads its own definition by searching @code{fpath}, by using
@code{autoload -X} within a shell function.  For example, the following are
equivalent:

@example
 myfunc() @{
   autoload -X
 @}
 myfunc args...
@end example

and

@example
 unfunction myfunc   # if myfunc was defined
 autoload myfunc
 myfunc args...
@end example

In fact, the @code{functions} command outputs @code{builtin autoload -X} as
the body of an autoloaded function.  This is done so that

@example
 eval "$(functions)"
@end example

produces a reasonable result.  A true autoloaded function can be
identified by the presence of the comment @code{# undefined} in the body,
because all comments are discarded from defined functions.

To load the definition of an autoloaded function @code{myfunc} without
executing @code{myfunc}, use:

@example
 autoload +X myfunc
@end example

@node Anonymous Functions,Special Functions,Autoloading Functions,Functions
@anchor{Zsh/func anonymous-functions}@anchor{43}
@section Anonymous Functions


@geindex anonymous functions; Command

@geindex functions@comma{} anonymous; Command

If no name is given for a function, it is `anonymous’ and is handled
specially.  Either form of function definition may be used: a @code{()} with
no preceding name, or a @code{function} with an immediately following open
brace.  The function is executed immediately at the point of definition and
is not stored for future use.  The function name is set to @code{(anon)}.

Arguments to the function may be specified as words following the
closing brace defining the function, hence if there are none no
arguments (other than @code{$0}) are set.  This is a difference from the
way other functions are parsed: normal function definitions may be
followed by certain keywords such as @code{else} or @code{fi}, which will
be treated as arguments to anonymous functions, so that a newline or
semicolon is needed to force keyword interpretation.

Note also that the argument list of any enclosing script or function is
hidden (as would be the case for any other function called at this
point).

Redirections may be applied to the anonymous function in the same manner as
to a current-shell structure enclosed in braces.  The main use of anonymous
functions is to provide a scope for local variables.  This is particularly
convenient in start-up files as these do not provide their own local
variable scope.

For example,

@example
 variable=outside
 function @{
   local variable=inside
   print "I am $variable with arguments $*"
 @} this and that
 print "I am $variable"
@end example

outputs the following:

@example
 I am inside with arguments this and that
 I am outside
@end example

Note that function definitions with arguments that expand to nothing,
for example @code{name=; function $name @{} @var{…} @code{@}}, are not
treated as anonymous functions.  Instead, they are treated as normal
function definitions where the definition is silently discarded.

@node Special Functions,,Anonymous Functions,Functions
@anchor{Zsh/func id3}@anchor{44}@anchor{Zsh/func special-functions}@anchor{45}
@section Special Functions


Certain functions, if defined, have special meaning to the shell.

@menu
* Hook Functions:: 
* Trap Functions:: 

@end menu

@node Hook Functions,Trap Functions,,Special Functions
@anchor{Zsh/func hook-functions}@anchor{46}
@subsection Hook Functions


@geindex functions@comma{} hook; Function

@geindex hook functions; Function

For the functions below, it is possible to define an array that has the
same name as the function with @code{_functions} appended.  Any element in
such an array is taken as the name of a function to execute; it is executed
in the same context and with the same arguments and same initial value of @code{$?}
as the basic function.  For
example, if @code{$chpwd_functions} is an array containing the values
@code{mychpwd}, @code{chpwd_save_dirstack}, then the shell attempts to
execute the functions @code{chpwd}, @code{mychpwd} and
@code{chpwd_save_dirstack}, in that order.  Any function that does not exist
is silently ignored.  A function found by this mechanism is referred to
elsewhere as a `hook function'.  An error in any function causes subsequent
functions not to be run.  Note further that an error in a @code{precmd} hook
causes an immediately following @code{periodic} function not to run (though
it may run at the next opportunity).

@geindex chpwd; Function

@geindex chpwd_functions; Variable

@code{chpwd}

@quotation

Executed whenever the current working directory is changed.
@end quotation

@geindex periodic; Function

@geindex periodic_functions; Variable

@code{periodic}

@quotation

@geindex PERIOD; Variable

If the parameter @code{PERIOD}
is set, this function is executed every @code{$PERIOD}
seconds, just before a prompt.  Note that if multiple functions
are defined using the array @code{periodic_functions} only one
period is applied to the complete set of functions, and the
scheduled time is not reset if the list of functions is altered.
Hence the set of functions is always called together.
@end quotation

@geindex precmd; Function

@geindex precmd_functions; Variable

@code{precmd}

@quotation

Executed before each prompt.  Note that precommand functions are not
re-executed simply because the command line is redrawn, as happens, for
example, when a notification about an exiting job is displayed.
@end quotation

@geindex preexec; Function

@geindex preexec_functions; Variable

@code{preexec}

@quotation

Executed just after a command has been read and is about to be
executed.  If the history mechanism is active (regardless of whether the
line was discarded from the history buffer), the string that the user
typed is passed as the first argument, otherwise it is an empty string.
The actual command that will be executed (including expanded aliases) is
passed in two different forms: the second argument is a single-line,
size-limited version of the command (with things like function bodies
elided); the third argument contains the full text that is being
executed.
@end quotation

@geindex zshaddhistory; Function

@geindex zshaddhistory_functions; Variable

@code{zshaddhistory}

@quotation

@geindex history@comma{} hook when line is saved; Command

Executed when a history line has been read interactively, but
before it is executed.  The sole argument is the complete history
line (so that any terminating newline will still be present).

If any of the hook functions returns status 1 (or any non-zero value
other than 2, though this is not guaranteed for future versions of the
shell) the history line will not be saved, although it lingers in the
history until the next line is executed, allowing you to reuse or edit
it immediately.

If any of the hook functions returns status 2 the history line
will be saved on the internal history list, but not written to
the history file.  In case of a conflict, the first non-zero status
value is taken.

A hook function may call @code{fc -p} @var{…} to switch the history
context so that the history is saved in a different file from
that in the global @code{HISTFILE} parameter.  This is handled specially:
the history context is automatically restored after the processing
of the history line is finished.

The following example function works with one of the options
@code{INC_APPEND_HISTORY} or @code{SHARE_HISTORY} set, in order that the line
is written out immediately after the history entry is added.  It first
adds the history line to the normal history with the newline stripped,
which is usually the correct behaviour.  Then it switches the history
context so that the line will be written to a history file in the
current directory.

@example
 zshaddhistory() @{
   print -sr -- $@{1%%$'\n'@}
   fc -p .zsh_local_history
 @}
@end example
@end quotation

@geindex zshexit; Function

@geindex zshexit_functions; Variable

@code{zshexit}

@quotation

Executed at the point where the main shell is about to exit normally.
This is not called by exiting subshells, nor when the @code{exec}
precommand modifier is used before an external command.  Also, unlike
@code{TRAPEXIT}, it is not called when functions exit.
@end quotation

@node Trap Functions,,Hook Functions,Special Functions
@anchor{Zsh/func trap-functions}@anchor{47}
@subsection Trap Functions


The functions below are treated specially but do not have corresponding
hook arrays.

@code{TRAP}@var{NAL}

@quotation

@geindex signals@comma{} trapping; Command

@geindex trapping signals; Command

If defined and non-null,
this function will be executed whenever the shell
catches a signal @code{SIG}@var{NAL}, where @var{NAL} is a signal
name as specified for the @code{kill} builtin.
The signal number will be passed as the first parameter to the function.

If a function of this form is defined and null,
the shell and processes spawned by it will ignore @code{SIG}@var{NAL}.

The return status from the function is handled specially.  If it is
zero, the signal is assumed to have been handled, and execution continues
normally.  Otherwise, the shell will behave as interrupted except that
the return status of the trap is retained.

Programs terminated by uncaught signals typically return the status 128
plus the signal number.  Hence the following causes the handler for
@code{SIGINT} to print a message, then mimic the usual effect of the signal.

@example
 TRAPINT() @{
   print "Caught SIGINT, aborting."
   return $(( 128 + $1 ))
 @}
@end example

The functions @code{TRAPZERR}, @code{TRAPDEBUG} and @code{TRAPEXIT} are never
executed inside other traps.
@end quotation

@geindex TRAPDEBUG; Function

@code{TRAPDEBUG}

@quotation

If the option @code{DEBUG_BEFORE_CMD} is set (as it is by default), executed
before each command; otherwise executed after each command.  See
the description of the @code{trap} builtin in
@code{zshbuiltins}
for details of additional features provided
in debug traps.
@end quotation

@geindex TRAPEXIT; Function

@code{TRAPEXIT}

@quotation

Executed when the shell exits,
or when the current function exits if defined inside a function.
The value of @code{$?} at the start of execution is the exit status of the
shell or the return status of the function exiting.
@end quotation

@geindex TRAPZERR; Function

@geindex TRAPERR; Function

@code{TRAPZERR}

@quotation

Executed whenever a command has a non-zero exit status.  However, the
function is not executed if the command occurred in a sublist followed by
@code{&&} or @code{||}; only the final command in a sublist of this type
causes the trap to be executed.  The function @code{TRAPERR} acts the same as
@code{TRAPZERR} on systems where there is no @code{SIGERR} (this is the usual
case).
@end quotation

@geindex trap@comma{} use of; Function

The functions beginning @code{TRAP} may alternatively be defined with the
@code{trap} builtin:  this may be preferable for some uses.  Setting a trap
with one form removes any trap of the other form for the same signal;
removing a trap in either form removes all traps for the same signal.
The forms

@example
 TRAPNAL() @{
  # code
 @}
@end example

(‘function traps’) and

@example
 trap '
  # code
 ' NAL
@end example

(‘list traps’) are equivalent in most ways, the exceptions being the
following:

@quotation


@itemize *

@item 
Function traps have all the properties of normal functions,
@end itemize

appearing in the list of functions and being called with their own
function context rather than the context where the trap was triggered.
* The return status from function traps is special, whereas a return
from a list trap causes the surrounding context to return with the given
status.
* Function traps are not reset within subshells, in accordance with
zsh behaviour; list traps are reset, in accordance with POSIX
behaviour.
@end quotation

@c historic nodename: Jobs & Signals

@node Jobs & Signals,Arithmetic Evaluation,Functions,Top
@anchor{Zsh/jobs doc}@anchor{48}@anchor{Zsh/jobs jobs-signals}@anchor{49}
@chapter Jobs & Signals


@menu
* Jobs:: 
* Signals:: 

@end menu

@node Jobs,Signals,,Jobs & Signals
@anchor{Zsh/jobs jobs}@anchor{4a}
@section Jobs


@geindex jobs; Command

@geindex MONITOR@comma{} use of; Program

If the @code{MONITOR} option is set,
an interactive shell associates a `job' with each pipeline.
It keeps a table of current jobs, printed by the @code{jobs}
command, and assigns them small integer numbers.
When a job is started asynchronously with @code{&},
the shell prints a line to standard error which looks like:

@example
 [1] 1234
@end example

indicating that the job which was started asynchronously was job number
1 and had one (top-level) process, whose process ID was 1234.

If a job is started with @code{&|} or @code{&!},
then that job is immediately disowned.  After startup, it
does not have a place in the job table, and is not subject
to the job control features described here.

If you are running a job and wish to do something else you may hit the key
^Z (control-Z) which sends a @code{TSTP} signal to the current job:  this key
may be redefined by the @code{susp} option of the external @code{stty} command.
.. index:: single: jobs, suspending; Command

@geindex suspending jobs; Command

The shell will then normally indicate that the job has been `suspended’,
and print another prompt.  You can then manipulate the state of this job,
.. index:: single: bg, use of; Function

putting it in the background with the @code{bg} command, or run some other
commands and then eventually bring the job back into the foreground with
.. index:: single: fg, use of; Function

the foreground command @code{fg}.  A ^Z takes effect immediately and
is like an interrupt in that pending output and unread input are discarded
when it is typed.

A job being run in the background will suspend if it tries to read
from the terminal.

Note that if the job running in the foreground is a shell function,
then suspending it will have the effect of causing the shell to fork.
This is necessary to separate the function’s state from that of the
parent shell performing the job control, so that the latter can return
to the command line prompt.  As a result, even if @code{fg} is
used to continue the job the function will no longer be part of the
parent shell, and any variables set by the function will not be visible
in the parent shell.  Thus the behaviour is different from the case
where the function was never suspended.  Zsh is different from many
other shells in this regard.

One additional side effect is that use of @code{disown} with a job
created by suspending shell code in this fashion is delayed: the
job can only be disowned once any process started from the parent
shell has terminated.  At that point, the disowned job disappears
silently from the job list.

The same behaviour is found when the shell is executing code as the
right hand side of a pipeline or any complex shell construct such as
@code{if}, @code{for}, etc., in order that the entire block of code
can be managed as a single job.
.. index:: single: background jobs, I/O; Command

@geindex jobs@comma{} background@comma{} I/O; Command

Background jobs are normally allowed to produce output,
but this can be disabled by giving the command @code{stty tostop}.
If you set this
tty option, then background jobs will suspend when they try to produce
output like they do when they try to read input.

When a command is suspended and continued later with the @code{fg} or
@code{wait} builtins, zsh restores tty modes that were in effect when it was
suspended.  This (intentionally) does not apply if the command is
continued via @code{kill -CONT}, nor when it is continued with @code{bg}.

@geindex jobs@comma{} referring to; Command

@geindex referring to jobs; Command

There are several ways to refer to jobs in the shell.
A job can be referred to by the process ID of any process of the job
or by one of the following:


@table @asis

@item @code{%}@var{number}

The job with the given number.

@item @code{%}@var{string}

The last job whose command line begins with @var{string}.

@item @code{%?}@var{string}

The last job whose command line contains @var{string}.

@item @code{%%}

Current job.

@item @code{%+}

Equivalent to @code{%%}.

@item @code{%-}

Previous job.
@end table

The shell learns immediately whenever a process changes state.
.. index:: single: NOTIFY, use of; Program

It normally informs you whenever a job becomes blocked so that
no further progress is possible.  If the @code{NOTIFY} option is not set,
it waits until just before it prints a prompt before it informs you.
All such notifications are sent directly to the terminal, not to
the standard output or standard error.

When the monitor mode is on, each background job that completes
triggers any trap set for @code{CHLD}.

When you try to leave the shell while jobs are running or suspended, you will
be warned that `You have suspended (running) jobs’.
You may use the @code{jobs} command to see what they are.
If you do this or immediately try to
exit again, the shell will not warn you a second time; the suspended
jobs will be terminated, and the running jobs will be sent
a @code{SIGHUP} signal, if the @code{HUP} option is set.
.. index:: single: HUP, use of; Program

@geindex jobs@comma{} disowning; Command

@geindex disowning jobs; Command

@geindex disown@comma{} use of; Function

To avoid having the shell terminate the running jobs, either
use the @code{nohup(1)} command
or the @code{disown} builtin.

@node Signals,,Jobs,Jobs & Signals
@anchor{Zsh/jobs id1}@anchor{4b}@anchor{Zsh/jobs signals}@anchor{4c}
@section Signals


The @code{INT} and @code{QUIT} signals for an invoked
command are ignored if the command is followed by
@code{&} and the @code{MONITOR} option is not active.
The shell itself always ignores the @code{QUIT} signal.
Otherwise, signals have the values
inherited by the shell from its parent
(but see the @code{TRAP}@var{NAL} special functions in Functions).

@geindex exiting shell@comma{} and asynchronous jobs; Command

@geindex asynchronous jobs@comma{} and exiting shell; Command

@geindex jobs@comma{} asynchronous@comma{} and exiting shell; Command

Certain jobs are run asynchronously by the shell other than those
explicitly put into the background; even in cases where the shell
would usually wait for such jobs, an explicit @code{exit} command
or exit due to the option @code{ERR_EXIT} will cause the shell to
exit without waiting.  Examples of such asynchronous jobs are
process substitution, see
@ref{38,,Process Substitution}, and the handler processes for
multios, see @ref{4d,,Multios}.

@c historic nodename: Arithmetic Evaluation

@node Arithmetic Evaluation,Conditional Expressions,Jobs & Signals,Top
@anchor{Zsh/arith doc}@anchor{4e}@anchor{Zsh/arith arithmetic-evaluation}@anchor{4f}
@chapter Arithmetic Evaluation



@geindex arithmetic evaluation; Command

@geindex evaluation@comma{} arithmetic; Command

@geindex let@comma{} use of; Function

The shell can perform integer and floating point arithmetic, either using
the builtin @code{let}, or via a substitution of the form
@code{$((}@var{…}@code{))}.  For
integers, the shell is usually compiled to use 8-byte precision where this
is available, otherwise precision is 4 bytes.  This can be tested, for
example, by giving the command @code{print - $(( 12345678901 ))}; if the
number appears unchanged, the precision is at least 8 bytes.  Floating
point arithmetic always uses the `double’ type with whatever corresponding
precision is provided by the compiler and the library.

The @code{let} builtin command takes arithmetic expressions as arguments; each
is evaluated separately.  Since many of the arithmetic operators, as well
as spaces, require quoting, an alternative form is provided: for any
command which begins with a @code{((}, all the characters until a
matching @code{))} are treated as a double-quoted expression and
arithmetic expansion performed as for an argument of @code{let}.  More
precisely, @code{((}@var{…}@code{))} is equivalent to
@code{let "}@var{…}@code{"}.  The return status is 0 if the arithmetic value
of the expression is non-zero, 1 if it is zero, and 2 if an error occurred.
Floating point exceptions (division by zero, overflow, etc.) are ignored and
not considered as errors.

For example, the following statement

@example
 (( val = 2 + 1 ))
@end example

is equivalent to

@example
 let "val = 2 + 1"
@end example

both assigning the value 3 to the shell variable @code{val} and returning a
zero status.

@geindex arithmetic base; Command

@geindex bases@comma{} in arithmetic; Command

Integers can be in bases other than 10.
A leading @code{0x} or @code{0X} denotes hexadecimal and a leading
@code{0b} or @code{0B} binary.
Integers may also be of the form @var{base}@code{#}@var{n},
where @var{base} is a decimal number between two and thirty-six
representing the arithmetic base and @var{n}
is a number in that base (for example, @code{16#ff} is 255 in hexadecimal).
The @var{base}@code{#} may also be omitted, in which case
base 10 is used.  For backwards compatibility the form
@code{[}@var{base}@code{]}@var{n} is also accepted.

An integer expression or a base given in the form
@var{base}@code{#}@var{n} may contain underscores (@code{_}) after the
leading digit for visual guidance; these are ignored in computation.
Examples are @code{1_000_000} or @code{0xffff_ffff} which are equivalent to
@code{1000000} and @code{0xffffffff} respectively.

It is also possible to specify a base to be used for output in the form
@code{[#}@var{base}@code{]}, for example @code{[#16]}.  This is used when
outputting arithmetical substitutions or when assigning to scalar
parameters, but an explicitly defined integer or floating point parameter
will not be affected.  If an integer variable is implicitly defined by an
arithmetic expression, any base specified in this way will be set as the
variable’s output arithmetic base as if the option @code{-i} @var{base} to
the @code{typeset} builtin had been used.  The expression has no precedence
and if it occurs more than once in a mathematical expression, the last
encountered is used.  For clarity it is recommended that it appear at the
beginning of an expression.  As an example:

@example
 typeset -i 16 y
 print $(( [#8] x = 32, y = 32 ))
 print $x $y
@end example

outputs first @code{8#40}, the rightmost value in the given output base, and
then @code{8#40 16#20}, because @code{y} has been explicitly declared to
have output base 16, while @code{x} (assuming it does not already exist) is
implicitly typed by the arithmetic evaluation, where it acquires the output
base 8.

The @var{base} may be replaced or followed by an underscore, which may
itself be followed by a positive integer (if it is missing the value 3
is used).  This indicates that underscores should be inserted into the
output string, grouping the number for visual clarity.  The following
integer specifies the number of digits to group together.  For example:

@example
 setopt cbases
 print $(( [#16_4] 65536 ** 2 ))
@end example

outputs @code{0x1_0000_0000}.

The feature can be used with floating
point numbers, in which case the base must be omitted; grouping
is away from the decimal point.  For example,

@example
 zmodload zsh/mathfunc
 print $(( [#_] sqrt(1e7) ))
@end example

outputs @code{3_162.277_660_168_379_5} (the number of decimal places
shown may vary).

@geindex C_BASES@comma{} use of; Program

@geindex OCTAL_ZEROES@comma{} use of; Program

If the @code{C_BASES} option is set, hexadecimal numbers are output in the standard C
format, for example @code{0xFF} instead of the usual @code{16#FF}.  If the
option @code{OCTAL_ZEROES} is also set (it is not by default), octal numbers
will be treated similarly and hence appear as @code{077} instead of
@code{8#77}.  This option has no effect on the output of bases other than
hexadecimal and octal, and these formats are always understood on input.

When an output base is specified using the @code{[#}@var{base}@code{]} syntax,
an appropriate base prefix will be output if necessary, so that the value
output is valid syntax for input.  If the @code{#} is doubled, for example
@code{[##16]}, then no base prefix is output.

Floating point constants are recognized by the presence of a decimal point
or an exponent.  The decimal point may be the first character of the
constant, but the exponent character @code{e} or @code{E} may not, as it will be
taken for a parameter name.  All numeric parts (before and after the
decimal point and in the exponent) may contain underscores after the
leading digit for visual guidance; these are ignored in computation.

The special floating point values NaN (not a number) and infinity are
fully supported in floating point arithmetic.  They may be produced by
certain operations, such as division by zero, or referenced explicitly in
arithmetic constructs and float assignments using the case-insensitive
constants @code{NaN} and @code{Inf}.  Expansion syntax must be used to
reference a parameter with one of these names in these contexts:

@example
 % nan=123 INF=456
 % print $(( nan )) $(( INF ))
 NaN Inf
 % print $(( $nan )) $(( $INF ))
 123 456
 % typeset -F f=nan && typeset -p f
 typeset -F f=NaN
 % typeset -F f=$nan && typeset -p f
 typeset -F f=123.0000000000
@end example

To check whether a value is NaN, either use the @code{isnan} function
provided by the @code{zsh/mathfunc} module
or compare it to the string @code{NaN}:

@example
 % zmodload zsh/mathfunc
 % (( isnan(0.0 / 0) )) && print is nan
 is nan
 % typeset -F f=nan && [[ $f == NaN ]] && print is nan
 is nan
@end example

@geindex arithmetic operators; Command

@geindex operators@comma{} arithmetic; Command

An arithmetic expression uses nearly the same syntax and
associativity of expressions as in C.

In the native mode of operation, the following operators are supported
(listed in decreasing order of precedence):


@table @asis

@item @code{+ - ! ~ ++ --}

unary plus/minus, logical NOT, complement, @{pre,post@}@{in,de@}crement

@item @code{<< >>}

bitwise shift left, right

@item @code{&}

bitwise AND

@item @code{^}

bitwise XOR

@item @code{|}

bitwise OR

@item @code{**}

exponentiation

@item @code{* / %}

multiplication, division, modulus (remainder)

@item @code{+ -}

addition, subtraction

@item @code{< > <= >=}

comparison

@item @code{== !=}

equality and inequality

@item @code{&&}

logical AND

@item @code{|| ^^}

logical OR, XOR

@item @code{? :}

ternary operator

@item @code{= += -= *= /= %= &= ^= |= <<= >>= &&= ||= ^^= **=}

assignment

@item @code{,}

comma operator
@end table

The operators @code{&&}, @code{||}, @code{&&=}, and @code{||=} are
short-circuiting, and only one of the latter two expressions in a ternary
operator is evaluated.  Note the precedence of the bitwise AND, OR,
and XOR operators.

With the option @code{C_PRECEDENCES} the precedences (but no other
properties) of the operators are altered to be the same as those in
most other languages that support the relevant operators:


@table @asis

@item @code{+ - ! ~ ++ --}

unary plus/minus, logical NOT, complement, @{pre,post@}@{in,de@}crement

@item @code{**}

exponentiation

@item @code{* / %}

multiplication, division, modulus (remainder)

@item @code{+ -}

addition, subtraction

@item @code{<< >>}

bitwise shift left, right

@item @code{< > <= >=}

comparison

@item @code{== !=}

equality and inequality

@item @code{&}

bitwise AND

@item @code{^}

bitwise XOR

@item @code{|}

bitwise OR

@item @code{&&}

logical AND

@item @code{^^}

logical XOR

@item @code{||}

logical OR

@item @code{? :}

ternary operator

@item @code{= += -= *= /= %= &= ^= |= <<= >>= &&= ||= ^^= **=}

assignment

@item @code{,}

comma operator
@end table

Note the precedence of exponentiation in both cases is below
that of unary operators, hence @code{-3**2} evaluates as @code{9}, not
@code{-9}.  Use parentheses where necessary: @code{-(3**2)}.  This is
for compatibility with other shells.

@geindex mathematical functions@comma{} use of; Command

@geindex functions@comma{} math@comma{} use of; Command

Mathematical functions can be called with the syntax
@var{func}@code{(}@var{args}@code{)}, where the function decides
if the @var{args} is used as a string or a comma-separated list of
arithmetic expressions. The shell currently defines no mathematical
functions by default, but the module @code{zsh/mathfunc} may be loaded with
the @code{zmodload} builtin to provide standard floating point mathematical
functions.

An expression of the form @code{##}@var{x} where @var{x} is any character
sequence such as @code{a}, @code{^A}, or @code{\M-\C-x} gives the value of
this character and an expression of the form @code{#}@var{name} gives the
value of the first character of the contents of the parameter @var{name}.
Character values are according to the character set used in the current
locale; for multibyte character handling the option @code{MULTIBYTE} must be
set.  Note that this form is different from @code{$#}@var{name}, a standard
parameter substitution which gives the length of the parameter @var{name}.
@code{#\} is accepted instead of @code{##}, but its use is deprecated.

Named parameters and subscripted arrays can be referenced by name within an
arithmetic expression without using the parameter expansion syntax.  For
example,

@example
 ((val2 = val1 * 2))
@end example

assigns twice the value of @code{$val1} to the parameter named @code{val2}.
If the expansion of @code{$val1} is text rather than a number, then when
@code{val1} is referenced that text is itself evaluated as a math expression
as if surrounded by parentheses @code{($val1)}.  Expansion
continues until there are no more parameter references, a number has
resulted, or an expression error occurs.

An internal integer representation of a named parameter
can be specified with the @code{integer} builtin.
.. index:: single: parameters, integer; Command

@geindex integer parameters; Command

@geindex integer@comma{} use of; Function

Arithmetic evaluation is performed on the value of each
assignment to a named parameter declared integer
in this manner.  Assigning a floating point number to an integer results in
rounding towards zero.

@geindex parameters@comma{} floating point; Command

@geindex floating point parameters; Command

@geindex float@comma{} use of; Function

Likewise, floating point numbers can be declared with the @code{float}
builtin; there are two types, differing only in their output format, as
described for the @code{typeset} builtin.  The output format can be bypassed
by using arithmetic substitution instead of the parameter substitution,
i.e. @code{$@{}@var{float}@code{@}} uses the defined format, but
@code{$((}@var{float}@code{))} uses a generic floating point
format.

Promotion of integer to floating point values is performed where
necessary.  In addition, if any operator which requires an integer
(@code{&}, @code{|}, @code{^}, @code{<<}, @code{>>} and their equivalents with
assignment) is given a floating point argument, it will be silently rounded
towards zero except for @code{~} which rounds down.

Users should beware that, in common with many other programming
languages but not software designed for calculation, the evaluation of
an expression in zsh is taken a term at a time and promotion of integers
to floating point does not occur in terms only containing integers.  A
typical result of this is that a division such as @code{6/8} is truncated,
in this being rounded towards 0.  The @code{FORCE_FLOAT} shell option can
be used in scripts or functions where floating point evaluation is
required throughout.

Scalar variables can hold integer or floating point values at different
times; there is no memory of the numeric type in this case.

If a variable is first assigned in a numeric context without previously
being declared, it will be implicitly typed as @code{integer} or @code{float} and
retain that type either until the type is explicitly changed or until the
end of the scope.  This can have unforeseen consequences.  For example, in
the loop

@example
 for (( f = 0; f < 1; f += 0.1 )); do
 # use $f
 done
@end example

if @code{f} has not already been declared, the first assignment will cause it
to be created as an integer, and consequently the operation @code{f += 0.1}
will always cause the result to be truncated to zero, so that the loop will
fail.  A simple fix would be to turn the initialization into @code{f = 0.0}.
It is therefore best to declare numeric variables with explicit types.

@c historic nodename: Conditional Expressions

@node Conditional Expressions,Prompt Expansion,Arithmetic Evaluation,Top
@anchor{Zsh/cond doc}@anchor{50}@anchor{Zsh/cond conditional-expressions}@anchor{51}
@chapter Conditional Expressions



@geindex conditional expressions; Command

@geindex expressions@comma{} conditional; Command

A `conditional expression' is used with the @code{[[}
compound command to test attributes of files and to compare strings.
Each expression can be constructed from one or more
of the following unary or binary expressions:

@code{-a} @var{file}

@quotation

true if @var{file} exists.
@end quotation

@code{-b} @var{file}

@quotation

true if @var{file} exists and is a block special file.
@end quotation

@code{-c} @var{file}

@quotation

true if @var{file} exists and is a character special file.
@end quotation

@code{-d} @var{file}

@quotation

true if @var{file} exists and is a directory.
@end quotation

@code{-e} @var{file}

@quotation

true if @var{file} exists.
@end quotation

@code{-f} @var{file}

@quotation

true if @var{file} exists and is a regular file.
@end quotation

@code{-g} @var{file}

@quotation

true if @var{file} exists and has its setgid bit set.
@end quotation

@code{-h} @var{file}

@quotation

true if @var{file} exists and is a symbolic link.
@end quotation

@code{-k} @var{file}

@quotation

true if @var{file} exists and has its sticky bit set.
@end quotation

@code{-n} @var{string}

@quotation

true if length of @var{string} is non-zero.
@end quotation

@code{-o} @var{option}

@quotation

true if option named @var{option} is on.  @var{option}
may be a single character, in which case it is a single letter option name.
(See @ref{52,,Specifying Options}.)

When no option named @var{option} exists, and the @code{POSIX_BUILTINS} option
hasn’t been set, return 3 with a warning.  If that option is set, return 1
with no warning.
@end quotation

@code{-p} @var{file}

@quotation

true if @var{file} exists and is a FIFO special file (named pipe).
@end quotation

@code{-r} @var{file}

@quotation

true if @var{file} exists and is readable by current process.
@end quotation

@code{-s} @var{file}

@quotation

true if @var{file} exists and has size greater than zero.
@end quotation

@code{-t} @var{fd}

@quotation

true if file descriptor number @var{fd}
is open and associated with a terminal device.
(note: @var{fd} is not optional)
@end quotation

@code{-u} @var{file}

@quotation

true if @var{file} exists and has its setuid bit set.
@end quotation

@code{-v} @var{varname}

@quotation

true if shell variable @var{varname} is set.
@end quotation

@code{-w} @var{file}

@quotation

true if @var{file} exists and is writable by current process.
@end quotation

@code{-x} @var{file}

@quotation

true if @var{file} exists and is executable by current process.
If @var{file} exists and is a directory, then the current process
has permission to search in the directory.
@end quotation

@code{-z} @var{string}

@quotation

true if length of @var{string} is zero.
@end quotation

@code{-L} @var{file}

@quotation

true if @var{file} exists and is a symbolic link.
@end quotation

@code{-O} @var{file}

@quotation

true if @var{file} exists and is owned by the effective user ID of this process.
@end quotation

@code{-G} @var{file}

@quotation

true if @var{file} exists and its group matches
the effective group ID of this process.
@end quotation

@code{-S} @var{file}

@quotation

true if @var{file} exists and is a socket.
@end quotation

@code{-N} @var{file}

@quotation

true if @var{file} exists and its access time is
not newer than its modification time.
@end quotation

@var{file1} @code{-nt} @var{file2}

@quotation

true if @var{file1} exists and is newer than @var{file2}.
@end quotation

@var{file1} @code{-ot} @var{file2}

@quotation

true if @var{file1} exists and is older than @var{file2}.
@end quotation

@var{file1} @code{-ef} @var{file2}

@quotation

true if @var{file1} and @var{file2} exist and refer to the same file.
@end quotation

@var{string} @code{=} @var{pattern}

@var{string} @code{==} @var{pattern}

@quotation

true if @var{string} matches @var{pattern}.
The two forms are exactly equivalent.  The @code{=} form is
the traditional shell syntax (and hence the only one generally used
with the @code{test} and @code{[} builtins); the @code{==} form provides
compatibility with other sorts of computer language.
@end quotation

@var{string} @code{!=} @var{pattern}

@quotation

true if @var{string} does not match @var{pattern}.
@end quotation

@var{string} @code{=~} @var{regexp}

@quotation

true if @var{string} matches the regular expression
@var{regexp}.  If the option @code{RE_MATCH_PCRE} is set
@var{regexp} is tested as a PCRE regular expression using
the @code{zsh/pcre} module, else it is tested as a POSIX
extended regular expression using the @code{zsh/regex} module.
Upon successful match, some variables will be updated; no variables
are changed if the matching fails.

If the option @code{BASH_REMATCH} is not set the scalar parameter
@code{MATCH} is set to the substring that matched the pattern and
the integer parameters @code{MBEGIN} and @code{MEND} to the index of the start
and end, respectively, of the match in @var{string}, such that if
@var{string} is contained in variable @code{var} the expression
@code{$@{var[$MBEGIN,$MEND]@}} is identical to @code{$MATCH}.  The setting
of the option @code{KSH_ARRAYS} is respected.  Likewise, the array
@code{match} is set to the substrings that matched parenthesised
subexpressions and the arrays @code{mbegin} and @code{mend} to the indices of
the start and end positions, respectively, of the substrings within
@var{string}.  The arrays are not set if there were no parenthesised
subexpressions.  For example, if the string @code{a short string} is matched
against the regular expression @code{s(...)t}, then (assuming the
option @code{KSH_ARRAYS} is not set) @code{MATCH}, @code{MBEGIN}
and @code{MEND} are @code{short}, @code{3} and @code{7}, respectively, while @code{match},
@code{mbegin} and @code{mend} are single entry arrays containing
the strings @code{hor}, @code{4} and @code{6}, respectively.

If the option @code{BASH_REMATCH} is set the array
@code{BASH_REMATCH} is set to the substring that matched the pattern
followed by the substrings that matched parenthesised
subexpressions within the pattern.
@end quotation

@var{string1} @code{<} @var{string2}

@quotation

true if @var{string1} comes before @var{string2}
based on ASCII value of their characters.
@end quotation

@var{string1} @code{>} @var{string2}

@quotation

true if @var{string1} comes after @var{string2}
based on ASCII value of their characters.
@end quotation

@var{exp1} @code{-eq} @var{exp2}

@quotation

true if @var{exp1} is numerically equal to @var{exp2}.
Note that for purely numeric comparisons use of the
@code{((}@var{…}@code{))} builtin described in
`Arithmetic Evaluation' is more convenient than
conditional expressions.
@end quotation

@var{exp1} @code{-ne} @var{exp2}

@quotation

true if @var{exp1} is numerically not equal to @var{exp2}.
@end quotation

@var{exp1} @code{-lt} @var{exp2}

@quotation

true if @var{exp1} is numerically less than @var{exp2}.
@end quotation

@var{exp1} @code{-gt} @var{exp2}

@quotation

true if @var{exp1} is numerically greater than @var{exp2}.
@end quotation

@var{exp1} @code{-le} @var{exp2}

@quotation

true if @var{exp1} is numerically less than or equal to @var{exp2}.
@end quotation

@var{exp1} @code{-ge} @var{exp2}

@quotation

true if @var{exp1} is numerically greater than or equal to @var{exp2}.
@end quotation

@code{(} @var{exp} @code{)}

@quotation

true if @var{exp} is true.
@end quotation

@code{!} @var{exp}

@quotation

true if @var{exp} is false.
@end quotation

@var{exp1} @code{&&} @var{exp2}

@quotation

true if @var{exp1} and @var{exp2} are both true.
@end quotation

@var{exp1} @code{||} @var{exp2}

@quotation

true if either @var{exp1} or @var{exp2} is true.
@end quotation

For compatibility, if there is a single argument that is not
syntactically significant, typically a variable, the condition is
treated as a test for whether the expression expands as a string of
non-zero length.  In other words, @code{[[ $var ]]} is the same as @code{[[ -n
$var ]]}.  It is recommended that the second, explicit, form be used
where possible.

Normal shell expansion is performed on the @var{file}, @var{string} and
@var{pattern} arguments, but the result of each expansion is constrained to
be a single word, similar to the effect of double quotes.

Filename generation is not performed on any form of argument to
conditions.  However, it can be forced in any case where normal shell
expansion is valid and when the option @code{EXTENDED_GLOB} is in effect by
using an explicit glob qualifier of the form @code{(#q)} at the
end of the string.  A normal glob qualifier expression may appear
between the @code{q} and the closing parenthesis; if none appears the
expression has no effect beyond causing filename generation.  The
results of filename generation are joined together to form a single
word, as with the results of other forms of expansion.

This special use of filename generation is only available with the
@code{[[} syntax.  If the condition occurs within the @code{[} or @code{test}
builtin commands then globbing occurs instead as part of normal command
line expansion before the condition is evaluated.  In this case it may
generate multiple words which are likely to confuse the syntax of the
test command.

For example,

@example
 [[ -n file*(#qN) ]]
@end example

produces status zero if and only if there is at least one file in the
current directory beginning with the string @code{file}.  The globbing
qualifier @code{N} ensures that the expression is empty if there is
no matching file.

Pattern metacharacters are active for the @var{pattern} arguments;
the patterns are the same as those used for filename generation, see
@ref{17,,Filename Generation}, but there is no special behaviour
of @code{/} nor initial dot, and the patterns @code{**/} and @code{***/} behave
the same as @code{*/}, in which the @code{*} has its standard behaviour
but may also match further @code{/} characters.  Also, no bare glob
qualifiers are allowed, though the form ((#q):var:@cite{…}) is allowed as
shown above.

In each of the above expressions, if
@var{file} is of the form @code{/dev/fd/}@var{n},
where @var{n} is an integer,
then the test applied to the open file whose
descriptor number is @var{n},
even if the underlying system does not support
the @code{/dev/fd} directory.

In the forms which do numeric comparison, the expressions @var{exp}
undergo arithmetic expansion as if they were enclosed in
@code{$((}@var{…}@code{))}.

For example, the following:

@example
 [[ ( -f foo || -f bar ) && $report = y* ]] && print File exists.
@end example

tests if either file @code{foo} or file @code{bar} exists, and if so, if the
value of the parameter @code{report} begins with @code{y}; if the complete
condition is true, the message @code{File exists.} is printed.

@c historic nodename: Prompt Expansion

@node Prompt Expansion,Expansion,Conditional Expressions,Top
@anchor{Zsh/prompt doc}@anchor{53}@anchor{Zsh/prompt prompt-expansion}@anchor{54}
@chapter Prompt Expansion


@menu
* Expansion of Prompt Sequences:: 
* Simple Prompt Escapes:: 
* Conditional Substrings in Prompts:: 

@end menu

@node Expansion of Prompt Sequences,Simple Prompt Escapes,,Prompt Expansion
@anchor{Zsh/prompt expansion-of-prompt-sequences}@anchor{55}@anchor{Zsh/prompt id1}@anchor{56}
@section Expansion of Prompt Sequences


@geindex prompt expansion; Command

@geindex expansion@comma{} prompt; Command

Prompt sequences undergo a special form of expansion.  This type of expansion
is also available using the @code{-P} option to the @code{print} builtin.

@geindex PROMPT_SUBST@comma{} use of; Program

If the @code{PROMPT_SUBST} option is set, the prompt string is first subjected to
`parameter expansion',
`command substitution' and
`arithmetic expansion'.
See


Expansion.

Certain escape sequences may be recognised in the prompt string.

@geindex PROMPT_BANG@comma{} use of; Program

If the @code{PROMPT_BANG} option is set, a @code{!} in the prompt is replaced
by the current history event number.  A literal @code{!} may then be
represented as @code{!!}.

@geindex PROMPT_PERCENT@comma{} use of; Program

If the @code{PROMPT_PERCENT} option is set, certain escape sequences that
start with @code{%} are expanded.
Many escapes (see @ref{57,,Simple Prompt Escapes})
are followed by a single character, although some of these
take an optional integer argument that
should appear between the @code{%} and the next character of the
sequence.  More complicated escape sequences
(see @ref{58,,Conditional Substrings in Prompts})
are available to provide conditional expansion.

@node Simple Prompt Escapes,Conditional Substrings in Prompts,Expansion of Prompt Sequences,Prompt Expansion
@anchor{Zsh/prompt id2}@anchor{59}@anchor{Zsh/prompt simple-prompt-escapes}@anchor{57}
@section Simple Prompt Escapes


@menu
* Special Characters:: 
* Login Information:: 
* Shell State:: 
* Date and Time:: 
* Visual Effects:: 

@end menu

@node Special Characters,Login Information,,Simple Prompt Escapes
@anchor{Zsh/prompt special-characters}@anchor{5a}
@subsection Special Characters


@code{%%}

@quotation

A @code{%}.
@end quotation

@code{%)}

@quotation

A @code{)}.
@end quotation

@node Login Information,Shell State,Special Characters,Simple Prompt Escapes
@anchor{Zsh/prompt login-information}@anchor{5b}
@subsection Login Information


@code{%l}

@quotation

The line (tty) the user is logged in on, without @code{/dev/} prefix.
If the name starts with @code{/dev/tty}, that prefix is stripped.
@end quotation

@code{%M}

@quotation

The full machine hostname.
@end quotation

@code{%m}

@quotation

The hostname up to the first @code{.}.
An integer may follow the @code{%} to specify
how many components of the hostname are desired.  With a negative integer,
trailing components of the hostname are shown.
@end quotation

@code{%n}

@quotation

@code{$USERNAME}.
@end quotation

@code{%y}

@quotation

The line (tty) the user is logged in on, without @code{/dev/} prefix.
This does not treat @code{/dev/tty} names specially.
@end quotation

@node Shell State,Date and Time,Login Information,Simple Prompt Escapes
@anchor{Zsh/prompt shell-state}@anchor{5c}
@subsection Shell State


@code{%#}

@quotation

A @code{#} if the shell is running with privileges, a @code{%} if not.
Equivalent to @code{%(!.#.%%)}.
The definition of `privileged’, for these purposes, is that either the
effective user ID is zero, or, if POSIX.1e capabilities are supported, that
at least one capability is raised in either the Effective or Inheritable
capability vectors.
@end quotation

@code{%?}

@quotation

The return status of the last command executed just before the prompt.
@end quotation

@code{%_}

@quotation

The status of the parser, i.e. the shell constructs (like @code{if} and
@code{for}) that have been started on the command line. If given an integer
number that many strings will be printed; zero or negative or no integer means
print as many as there are.  This is most useful in prompts @code{PS2} for
continuation lines and @code{PS4} for debugging with the @code{XTRACE} option; in
the latter case it will also work non-interactively.
@end quotation

@code{%^}

@quotation

The status of the parser in reverse. This is the same as @code{%_} other than
the order of strings.  It is often used in @code{RPS2}.
@end quotation

@code{%d}

@code{%/}

@quotation

Current working directory.  If an integer follows the @code{%},
it specifies a number of trailing components of the current working
directory to show; zero means the whole path.  A negative integer
specifies leading components, i.e. @code{%-1d} specifies the first component.
@end quotation

@code{%~}

@quotation

As @code{%d} and @code{%/}, but if the current working directory starts with
@code{$HOME}, that part is replaced by a @code{~}. Furthermore, if it has a named
directory as its prefix, that part is replaced by a @code{~} followed by
the name of the directory, but only if the result is shorter than
the full path; see `Dynamic' and `Static Named Directories' in
@ref{5d,,Filename Expansion}.
@end quotation

@code{%e}

@quotation

Evaluation depth of the current sourced file, shell function, or @code{eval}.
This is incremented or decremented every time the value of @code{%N} is
set or reverted to a previous value, respectively.  This is most useful
for debugging as part of @code{$PS4}.
@end quotation

@code{%h}

@code{%!}

@quotation

Current history event number.
@end quotation

@code{%i}

@quotation

The line number currently being executed in the script, sourced file, or
shell function given by @code{%N}.  This is most useful for debugging as part
of @code{$PS4}.
@end quotation

@code{%I}

@quotation

The line number currently being executed in the file @code{%x}.  This is
similar to @code{%i}, but the line number is always a line number in the
file where the code was defined, even if the code is a shell function.
@end quotation

@code{%j}

@quotation

The number of jobs.
@end quotation

@code{%L}

@quotation

The current value of @code{$SHLVL}.
@end quotation

@code{%N}

@quotation

The name of the script, sourced file, or shell function that zsh is
currently executing, whichever was started most recently.  If there is
none, this is equivalent to the parameter @code{$0}.  An integer may follow
the @code{%} to specify a number of trailing path components to show; zero
means the full path.  A negative integer specifies leading components.
@end quotation

@code{%x}

@quotation

The name of the file containing the source code currently being
executed.  This behaves as @code{%N} except that function and eval command
names are not shown, instead the file where they were defined.
@end quotation

@code{%c}

@code{%.}

@code{%C}

@quotation

Trailing component of the current working directory.
An integer may follow the @code{%} to get more than one component.
Unless @code{%C} is used, tilde contraction is performed first.  These are
deprecated as @code{%c} and @code{%C} are equivalent to @code{%1~} and @code{%1/},
respectively, while explicit positive integers have the same effect as for
the latter two sequences.
@end quotation

@node Date and Time,Visual Effects,Shell State,Simple Prompt Escapes
@anchor{Zsh/prompt date-and-time}@anchor{5e}
@subsection Date and Time


@code{%D}

@quotation

The date in @var{yy}@code{-}@var{mm}@code{-}@var{dd} format.
@end quotation

@code{%T}

@quotation

Current time of day, in 24-hour format.
@end quotation

@code{%t}

@code{%@@}

@quotation

Current time of day, in 12-hour, am/pm format.
@end quotation

@code{%*}

@quotation

Current time of day in 24-hour format, with seconds.
@end quotation

@code{%w}

@quotation

The date in @var{day}@code{-}@var{dd} format.
@end quotation

@code{%W}

@quotation

The date in @var{mm}@code{/}@var{dd}@code{/}@var{yy} format.
@end quotation

@code{%D@{}@var{string}@code{@}}

@quotation

@var{string} is formatted using the @code{strftime} function.
See @code{strftime(3)} for more details.  Various zsh
extensions provide numbers with no leading zero or space
if the number is a single digit:


@table @asis

@item @code{%f}

a day of the month

@item @code{%K}

the hour of the day on the 24-hour clock

@item @code{%L}

the hour of the day on the 12-hour clock
@end table

In addition, if the system supports the POSIX @code{clock_gettime}
or @code{gettimeofday} system
call, @code{%.} provides decimal fractions of a second since the epoch with
leading zeroes.  By default three decimal places are provided, but a
number of digits up to 9 may be given following the @code{%}; hence @code{%6.}
outputs microseconds, and @code{%9.} outputs nanoseconds.  (The latter
requires a nanosecond-precision @code{clock_gettime}; systems lacking this
will return a value multiplied by the appropriate power of 10.)  A typical
example of this is the format @code{%D@{%H:%M:%S.%.@}}.

The GNU extension @code{%N} is handled as a synonym for @code{%9.}.

Additionally, the GNU extension that a @code{-} between the @code{%} and the
format character causes a leading zero or space to be stripped
is handled directly by the shell for the format characters @code{d}, @code{f},
@code{H}, @code{k}, @code{l}, @code{m}, @code{M}, @code{S} and @code{y}; any other format
characters are provided to the system’s strftime(3)
with any leading @code{-} present, so the handling is system dependent.
Further GNU (or other) extensions are also passed to strftime(3)
and may work if the system supports them.
@end quotation

@node Visual Effects,,Date and Time,Simple Prompt Escapes
@anchor{Zsh/prompt visual-effects}@anchor{5f}
@subsection Visual Effects


@code{%B} (@code{%b})

@quotation

Start (stop) boldface mode.
@end quotation

@code{%E}

@quotation

Clear to end of line.
@end quotation

@code{%U} (@code{%u})

@quotation

Start (stop) underline mode.
@end quotation

@code{%S} (@code{%s})

@quotation

Start (stop) standout mode.
@end quotation

@code{%F} (@code{%f})

@quotation

Start (stop) using a different foreground colour, if supported
by the terminal.  The colour may be specified two ways: either
as a numeric argument, as normal, or by a sequence in braces
following the @code{%F}, for example @code{%F@{red@}}.  In the latter case
the values allowed are as described for the @code{fg} @code{zle_highlight}
attribute; see @ref{60,,Character Highlighting}.
This means that numeric
colours are allowed in the second format also.
@end quotation

@code{%K} (@code{%k})

@quotation

Start (stop) using a different bacKground colour.  The syntax is
identical to that for @code{%F} and @code{%f}.
@end quotation

@code{%H}

@quotation

Change all character visual attributes using a highlighting specification from
the @code{.zle.hlgroups} associative array. The key is specified in following
braces so, for example @code{%H@{error@}} will use the highlighting specification
for the `error’ group.  If the key is not found in the associative array then
it has no effect.  Highlighting specifications are in the same format as for
the @code{zle_highlight} parameter.
If the following braces are absent, attributes are reset to the defaults.
@end quotation

@code{%@{...%@}}

@quotation

Include a string as a literal escape sequence.
The string within the braces should not change the cursor
position.  Brace pairs can nest.

A positive numeric argument between the @code{%} and the @code{@{} is treated as
described for @code{%G} below.
@end quotation

@code{%G}

@quotation

Within a @code{%@{...%@}} sequence, include a `glitch’: that is, assume
that a single character width will be output.  This is useful when
outputting characters that otherwise cannot be correctly handled by the
shell, such as the alternate character set on some terminals.
The characters in question can be included within a @code{%@{...%@}}
sequence together with the appropriate number of @code{%G} sequences to
indicate the correct width.  An integer between the @code{%} and @code{G}
indicates a character width other than one.  Hence @code{%@{}@var{seq}@code{%2G%@}}
outputs @var{seq} and assumes it takes up the width of two standard
characters.

Multiple uses of @code{%G} accumulate in the obvious fashion; the position
of the @code{%G} is unimportant.  Negative integers are not handled.

Note that when prompt truncation is in use it is advisable to divide up
output into single characters within each @code{%@{...%@}} group so that
the correct truncation point can be found.
@end quotation

@node Conditional Substrings in Prompts,,Simple Prompt Escapes,Prompt Expansion
@anchor{Zsh/prompt conditional-substrings-in-prompts}@anchor{58}@anchor{Zsh/prompt id3}@anchor{61}
@section Conditional Substrings in Prompts


@code{%v}

@quotation

@geindex psvar@comma{} use of; Variable

The value of the first element of the @code{psvar} array parameter.  Following
the @code{%} with an integer gives that element of the array.  Negative
integers count from the end of the array.
@end quotation

@code{%(}@var{x}@code{.}@var{true-text}@code{.}@var{false-text}@code{)}

@quotation

Specifies a ternary expression.  The character following the @var{x} is
arbitrary; the same character is used to separate the text for the
`true’ result from that for the `false’ result.
This separator may not appear in the @var{true-text}, except as part of a
%-escape
sequence.  A @code{)} may appear in the @var{false-text} as @code{%)}.
@var{true-text}
and @var{false-text} may both contain arbitrarily-nested escape
sequences, including further ternary expressions.

The left parenthesis may be preceded or followed by a positive integer @var{n},
which defaults to zero.  A negative integer will be multiplied by -1, except
as noted below for @code{l}.
The test character @var{x} may be any of the following:


@table @asis

@item @code{!}

True if the shell is running with privileges.

@item @code{#}

True if the effective uid of the current process is @var{n}.

@item @code{?}

True if the exit status of the last command was @var{n}.

@item @code{_}

True if at least @var{n} shell constructs were started.
@end table

@code{C}


@table @asis

@item @code{/}

True if the current absolute path has at least @var{n} elements
relative to the root directory, hence @code{/} is counted as 0 elements.
@end table

@code{c}

@code{.}


@table @asis

@item @code{~}

True if the current path, with prefix replacement, has at
least @var{n} elements relative to the root directory, hence @code{/} is
counted as 0 elements.

@item @code{D}

True if the month is equal to @var{n} (January = 0).

@item @code{d}

True if the day of the month is equal to @var{n}.

@item @code{e}

True if the evaluation depth is at least @var{n}.

@item @code{g}

True if the effective gid of the current process is @var{n}.

@item @code{j}

True if the number of jobs is at least @var{n}.

@item @code{L}

True if the @code{SHLVL} parameter is at least @var{n}.

@item @code{l}

True if at least @var{n} characters have already been
printed on the current line.  When @var{n} is negative, true if at least
@code{abs(}@var{n}@code{)} characters remain before the opposite
margin (thus the left margin for @code{RPROMPT}).

@item @code{S}

True if the @code{SECONDS} parameter is at least @var{n}.

@item @code{T}

True if the time in hours is equal to @var{n}.

@item @code{t}

True if the time in minutes is equal to @var{n}.

@item @code{v}

True if the array @code{psvar} has at least @var{n} elements.

@item @code{V}

True if element @var{n} of the array @code{psvar} is set and
non-empty.

@item @code{w}

True if the day of the week is equal to @var{n} (Sunday = 0).
@end table
@end quotation

@code{%<}@var{string}@code{<}

@code{%>}@var{string}@code{>}

@code{%[}@var{xstring}@code{]}

@quotation

Specifies truncation behaviour for the remainder of the prompt string.
The third, deprecated, form is equivalent to @code{%}@var{xstringx},
i.e. @var{x} may be @code{<} or @code{>}.
The @var{string} will be displayed in
place of the truncated portion of any string; note this does not
undergo prompt expansion.

The numeric argument, which in the third form may appear immediately
after the @code{[}, specifies the maximum permitted length of
the various strings that can be displayed in the prompt.
In the first two forms, this numeric argument may be negative, in which
case the truncation length is determined by subtracting the absolute
value of the numeric argument from the number of character positions
remaining on the current prompt line.  If this results in a zero or
negative length, a length of 1 is used.  In other words, a negative
argument arranges that after truncation at least @var{n} characters
remain before the right margin (left margin for @code{RPROMPT}).

The forms with @code{<} truncate at the left of the string,
and the forms with @code{>} truncate at the right of the string.
For example, if the current directory is @code{/home/pike},
the prompt @code{%8<..<%/} will expand to @code{..e/pike}.
In this string, the terminating character (@code{<}, @code{>} or @code{]}),
or in fact any character, may be quoted by a preceding @code{\}; note
when using @code{print -P}, however, that this must be doubled as the
string is also subject to standard @code{print} processing, in addition
to any backslashes removed by a double quoted string:  the worst case
is therefore @code{print -P "%<\\\\<<..."}.

If the @var{string} is longer than the specified truncation length,
it will appear in full, completely replacing the truncated string.

The part of the prompt string to be truncated runs to the end of the
string, or to the end of the next enclosing group of the @code{%(}
construct, or to the next truncation encountered at the same grouping
level (i.e. truncations inside a @code{%(} are separate), which
ever comes first.  In particular, a truncation with argument zero
(e.g., @code{%<<}) marks the end of the range of the string to be
truncated while turning off truncation from there on. For example, the
prompt @code{%10<...<%~%<<%#}  will print a truncated representation of the
current directory, followed by a @code{%} or @code{#}, followed by a
space.  Without the @code{%<<}, those two characters would be included
in the string to be truncated.  Note that @code{%-0<<} is not equivalent
to @code{%<<} but specifies that the prompt is truncated at the right margin.

Truncation applies only within each individual line of the prompt, as
delimited by embedded newlines (if any).  If the total length of any line
of the prompt after truncation is greater than the terminal width, or if
the part to be truncated contains embedded newlines, truncation behavior
is undefined and may change in a future version of the shell.  Use
@code{%-}@var{n}@code{(l.}@var{true-text}@code{.}@var{false-text}@code{)} to remove parts
of the prompt when the available space is less than @var{n}.
@end quotation

@c historic nodename: Expansion

@node Expansion,Parameters,Prompt Expansion,Top
@anchor{Zsh/expn doc}@anchor{62}@anchor{Zsh/expn expansion}@anchor{63}
@chapter Expansion


@menu
* Description:: 
* History Expansion:: 
* Process Substitution:: 
* Parameter Expansion:: 
* Command Substitution:: 
* Arithmetic Expansion:: 
* Brace Expansion:: 
* Filename Expansion:: 
* Filename Generation:: 

@end menu

@node Description,History Expansion,,Expansion
@anchor{Zsh/expn description}@anchor{64}
@section Description


@geindex expansion; Command

The following types of expansions are performed in the indicated order in
five steps:

`History Expansion'

@quotation

This is performed only in interactive shells.
@end quotation

`Alias Expansion'

@quotation

Aliases are expanded immediately before the command line is parsed as
explained in @ref{65,,Aliasing}.
@end quotation

`Process Substitution'

`Parameter Expansion'

`Command Substitution'

`Arithmetic Expansion'

`Brace Expansion'

@quotation

These five are performed in left-to-right fashion.  On each argument,
any of the five steps that are needed are performed one after the other.
Hence, for example, all the parts of parameter expansion are completed
before command substitution is started.  After these expansions, all
unquoted occurrences of the characters @code{\,}’ and @code{"} are
removed.
@end quotation

`Filename Expansion'

@quotation

If the @code{SH_FILE_EXPANSION} option is set, the order of expansion is
modified for compatibility with `sh' and `ksh'.  In that case
`filename expansion' is performed immediately after `alias expansion',
preceding the set of five expansions mentioned above.
@end quotation

@geindex globbing; Command

`Filename Generation'

@quotation

This expansion, commonly referred to as `globbing', is always done last.
@end quotation

The following sections explain the types of expansion in detail.

@c historic nodename: History Expansion

@node History Expansion,Process Substitution,Description,Expansion
@anchor{Zsh/expn history-expansion}@anchor{66}
@section History Expansion


@geindex history; Command

@geindex history expansion; Command

@geindex expansion@comma{} history; Command

History expansion allows you to use words from previous command
lines in the command line you are typing.  This simplifies spelling
corrections and the repetition of complicated commands or arguments.

@geindex HISTSIZE@comma{} use of; Variable

Immediately before execution, each command is saved in the history list,
the size of which is controlled by the @code{HISTSIZE} parameter.  The one
most recent command is always retained in any case.  Each saved command in
the history list is called a history `event' and is assigned a number,
beginning with 1 (one) when the shell starts up.  The history number that
you may see in your prompt (see
@code{%h} or @code{%!} prompt escape described in
@ref{67,,Simple Prompt Escapes})
is the number that is to be assigned to the `next' command.

@c historic nodename: Overview

@menu
* Overview:: 
* Event Designators:: 
* Word Designators:: 
* Modifiers:: 

@end menu

@node Overview,Event Designators,,History Expansion
@anchor{Zsh/expn overview}@anchor{68}
@subsection Overview


@geindex histchars@comma{} use of; Variable

A history expansion begins with the first character of the @code{histchars}
parameter, which is @code{!} by default, and may occur anywhere on the
command line, including inside double quotes (but not inside single quotes
@code{'...'} or C-style quotes @code{$'...'} nor when escaped with a backslash).

The first character is followed by an optional event designator
(see @ref{69,,Event Designators})
and then an optional word designator (@ref{6a,,Word Designators});
if neither of these designators is
present, no history expansion occurs.

Input lines containing history expansions are echoed after being expanded,
but before any other expansions take place and before the command is
executed.  It is this expanded form that is recorded as the history event
for later references.

History expansions do not nest.

By default, a history reference with no event designator refers to the
same event as any preceding history reference on that command line; if it
is the only history reference in a command, it refers to the previous
command.
.. index:: single: CSH_JUNKIE_HISTORY, use of; Program

However, if the option @code{CSH_JUNKIE_HISTORY} is set, then every history
reference with no event specification `always' refers to the previous
command.

For example, @code{!} is the event designator for the previous command, so
@code{!!:1} always refers to the first word of the previous command, and
@code{!!$} always refers to the last word of the previous command.  With
@code{CSH_JUNKIE_HISTORY} set, then @code{!:1} and @code{!$} function in the
same manner as @code{!!:1} and @code{!!$}, respectively.  Conversely, if
@code{CSH_JUNKIE_HISTORY} is unset, then @code{!:1} and @code{!$} refer to the
first and last words, respectively, of the same event referenced by the
nearest other history reference preceding them on the current command
line, or to the previous command if there is no preceding reference.

The character sequence @code{^}@var{foo}@code{^}@var{bar} (where @code{^} is
actually the second character of the @code{histchars} parameter)
repeats the last command, replacing the string @var{foo} with @var{bar}.
More precisely, the sequence @code{^}@var{foo}@code{^}@var{bar}@code{^} is
synonymous with @code{!!:s^}@var{foo}@code{^}@var{bar}@code{^}, hence other
modifiers (see @ref{6b,,Modifiers}) may follow the final @code{^}.
In particular, @code{^}@var{foo}@code{^}@var{bar}@code{^:G} performs a global
substitution.

If the shell encounters the character sequence @code{!"}
in the input, the history mechanism is temporarily disabled until
the current list (see @code{zshmisc})
is fully parsed.  The @code{!"} is removed from the input, and any
subsequent @code{!} characters have no special significance.

@geindex fc@comma{} use of; Function

A less convenient but more comprehensible form of command history support
is provided by the @code{fc} builtin.

@c historic nodename: Event Designators

@node Event Designators,Word Designators,Overview,History Expansion
@anchor{Zsh/expn event-designators}@anchor{69}
@subsection Event Designators


@geindex history event designators; Command

@geindex event designators@comma{} history; Command

An event designator is a reference to a command-line entry in the history
list.  In the list below, remember that the initial @code{\`!'} in each item
may be changed to another character by setting the @code{histchars}
parameter.

@code{!}

@quotation

Start a history expansion, except when followed by a blank, newline,
@code{=} or @code{(}.  If followed immediately by a word designator
(
.. only:: man

@quotation

see
@end quotation

@ref{6a,,Word Designators}), this forms a history reference
with no event designator (
.. only:: man

@quotation

see
@end quotation

@ref{68,,Overview}).
@end quotation

@code{!!}

@quotation

Refer to the previous command.
By itself, this expansion
repeats the previous command.
@end quotation

@code{!}@var{n}

@quotation

Refer to command-line @var{n}.
@end quotation

@code{!-}@var{n}

@quotation

Refer to the current command-line minus @var{n}.
@end quotation

@code{!}@var{str}

@quotation

Refer to the most recent command starting with @var{str}.
@end quotation

@code{!?}@var{str}[@code{?}]

@quotation

Refer to the most recent command containing @var{str}.  The trailing
@code{?} is necessary if this reference is to be followed by a modifier or
followed by any text that is not to be considered part of @var{str}.
@end quotation

@code{!#}

@quotation

Refer to the current command line typed in so far.  The line is
treated as if it were complete up to and including the word before the
one with the @code{!#} reference.
@end quotation

@code{!@{...@}}

@quotation

Insulate a history reference from adjacent characters (if necessary).
@end quotation

@c historic nodename: Word Designators

@node Word Designators,Modifiers,Event Designators,History Expansion
@anchor{Zsh/expn word-designators}@anchor{6a}
@subsection Word Designators


@geindex history word designators; Command

@geindex word designators@comma{} history; Command

A word designator indicates which word or words of a given command line are
to be included in a history reference.  A @code{:} usually
separates the event specification from the word designator.
It may be omitted only if the word designator begins with a
@code{^}, @code{$}, @code{*}, @code{-} or @code{%}.
Word designators include:


@table @asis

@item @code{0}

The first input word (command).

@item @var{n}

The @var{n}th argument.

@item @code{^}

The first argument.  That is, @code{1}.

@item @code{$}

The last argument.

@item @code{%}

The word matched by (the most recent) @code{?}@var{str} search.

@item @var{x}@code{-}@var{y}

A range of words; @var{x} defaults to @code{0}.

@item @code{*}

All the arguments, or a null value if there are none.

@item @var{x}@code{*}

Abbreviates @var{x}@code{-$}.

@item @var{x}@code{-}

Like @var{x}@code{*} but omitting word @code{$}.
@end table

Note that a @code{%} word designator works only when used in one of
@code{!%}, @code{!:%} or @code{!?}@var{str}@code{?:%}, and only when used after a
@code{!?} expansion (possibly in an earlier command).  Anything else results
in an error, although the error may not be the most obvious one.

@c historic nodename: Modifiers

@node Modifiers,,Word Designators,History Expansion
@anchor{Zsh/expn modifiers}@anchor{6b}
@subsection Modifiers


@geindex modifiers; Command

@geindex colon modifiers; Command

@geindex history modifiers; Command

@geindex globbing modifiers; Command

@geindex parameter modifiers; Command

After the optional word designator, you can add
a sequence of one or more of the following modifiers,
each preceded by a @code{:}.  These modifiers also work on the result
of `filename generation' and `parameter expansion', except where
noted.

@code{a}

@quotation

Turn a file name into an absolute path:  prepends the current directory,
if necessary; remove @code{.} path segments; and remove @code{..} path segments
and the segments that immediately precede them.

This transformation is agnostic about what is in the filesystem, i.e. is
on the logical, not the physical directory.  It takes place in the same
manner as when changing directories when neither of the options
@code{CHASE_DOTS} or @code{CHASE_LINKS} is set.  For example,
@code{/before/here/../after} is always transformed to
@code{/before/after}, regardless of whether @code{/before/here} exists or what
kind of object (dir, file, symlink, etc.) it is.
@end quotation

@code{A}

@quotation

Turn a file name into an absolute path as the @code{a} modifier does, and
`then' pass the result through the @code{realpath(3)} library
function to resolve symbolic links.

Note: on systems that do not have a @code{realpath(3)} library
function, symbolic links are not resolved, so on those systems @code{a} and
@code{A} are equivalent.

Note: @code{foo:A} and @code{realpath(foo)} are different on some inputs.
For @code{realpath(foo)} semantics, see the @code{`P}` modifier.
@end quotation

@code{c}

@quotation

Resolve a command name into an absolute path by searching the command
path given by the @code{PATH} variable.  This does not work for commands
containing directory parts.  Note also that this does not usually work as
a glob qualifier unless a file of the same name is found in the
current directory.
@end quotation

@code{e}

@quotation

Remove all but the part of the filename extension following the @code{.};
see the definition of the filename extension in the description of the
@code{r} modifier below.  Note that according to that definition the result
will be empty if the string ends with a @code{.}.
@end quotation

@code{h} [ @var{digits} ]

@quotation

Remove a trailing pathname component, shortening the path by one
directory level: this is the `head’ of the pathname.  This works like
@code{dirname}.  If the @code{h} is followed immediately (with no spaces or
other separator) by any number of decimal digits, and the value of the
resulting number is non-zero, that number of leading components is
preserved instead of the final component being removed.  In an
absolute path the leading @code{/} is the first component, so,
for example, if @code{var=/my/path/to/something}, then @code{$@{var:h3@}}
substitutes @code{/my/path}.  Consecutive `/’s are treated the same as
a single `/’.  In parameter substitution, digits may only be
used if the expression is in braces, so for example the short form
substitution @code{$var:h2} is treated as @code{$@{var:h@}2}, not as
@code{$@{var:h2@}}.  No restriction applies to the use of digits in history
substitution or globbing qualifiers.  If more components are requested
than are present, the entire path is substituted (so this does not
trigger a `failed modifier’ error in history expansion).
@end quotation

@code{l}

@quotation

Convert the words to all lowercase.
@end quotation

@code{p}

@quotation

Print the new command but do not execute it.  Only works with history
expansion.
@end quotation

@code{P}

@quotation

Turn a file name into an absolute path, like @code{realpath(3)}.
The resulting path will be absolute,
will refer to the same directory entry as the input filename,
and none of its components will be symbolic links or equal to
@code{.} or @code{..}.

Unlike @code{realpath(3)}, non-existent trailing components are
permitted and preserved.
@end quotation

@code{q}

@quotation

Quote the substituted words, escaping further substitutions.  Works
with history expansion and parameter expansion, though for parameters
it is only useful if the resulting text is to be re-evaluated such as
by @code{eval}.
@end quotation

@code{Q}

@quotation

Remove one level of quotes from the substituted words.
@end quotation

@code{r}

@quotation

Remove a filename extension leaving the root name.  Strings with no
filename extension are not altered.  A filename
extension is a @code{.} followed by any number of characters (including
zero) that are neither @code{.} nor @code{/} and that continue to the end
of the string.  For example, the extension of
@code{foo.orig.c} is @code{.c}, and @code{dir.c/foo} has no extension.
@end quotation

@code{s/}@var{l}@code{/}@var{r}[@code{/}]

@code{S/}@var{l}@code{/}@var{r}[@code{/}]

@quotation

Substitute @var{r} for @var{l} as described below.
The substitution is done only for the
first string that matches @var{l}.  For arrays and for filename
generation, this applies to each word of the expanded text.  See
below for further notes on substitutions.

The forms @code{gs/}@var{l}@code{/}@var{r} and @code{s/}@var{l}@code{/}@var{r}@code{/:G}
perform global substitution, i.e. substitute every occurrence of @var{r}
for @var{l}.  Note that the @code{g} or @code{:G} must appear in exactly the
position shown.

The use of @code{S} instead of @code{s} is identical except that
the source is treated as a pattern, just as if the option
@code{HIST_SUBST_PATTERN} were set.

See further notes on this form of substitution below.
@end quotation

@code{&}

@quotation

Repeat the previous @code{s} or @code{S} substitution, whichever was most
recent.  Like @code{s} and @code{S}, may be preceded immediately by a @code{g}.
In parameter expansion the @code{&} must appear inside braces, and in
filename generation it must be quoted with a backslash.
@end quotation

@code{t} [ @var{digits} ]

@quotation

Remove all leading pathname components, leaving the final component (tail).
This works like @code{basename}.  Any trailing slashes are first removed.
Decimal digits are handled as described above for (h), but in this
case that number of trailing components is preserved instead of
the default 1; 0 is treated the same as 1.
@end quotation

@code{u}

@quotation

Convert the words to all uppercase.
@end quotation

@code{x}

@quotation

Like @code{q}, but break into words at whitespace.  Does not work with
parameter expansion.
@end quotation

The @code{s/}@var{l}@code{/}@var{r}@code{/} substitution works as follows.  By
default the left-hand side of substitutions are not patterns, but
character strings.  Any character can be used as the delimiter in place
of @code{/}.  A backslash quotes the delimiter character.  The character
@code{&}, in the right-hand-side @var{r}, is replaced by the text from the
left-hand-side @var{l}.  The @code{&} can be quoted with a backslash.  A
null @var{l} uses the previous string either from the previous @var{l} or
from the contextual scan string @var{s} from @code{!?}@var{s}.  You can
omit the rightmost delimiter if a newline immediately follows @var{r};
the rightmost @code{?} in a context scan can similarly be omitted.  Note
the same record of the last @var{l} and @var{r} is maintained across all
forms of expansion.

Note that if a @code{&} is used within glob qualifiers an extra backslash
is needed as a @code{&} is a special character in this case.

Also note that the order of expansions affects the interpretation of
@var{l} and @var{r}.  When used in a history expansion, which occurs before
any other expansions, @var{l} and @var{r} are treated as literal strings
(except as explained for @code{HIST_SUBST_PATTERN} below).  When used in
parameter expansion, the replacement of @var{r} into the parameter’s value
is done first, and then any additional process, parameter, command,
arithmetic, or brace references are applied, which may evaluate those
substitutions and expansions more than once if @var{l} appears more than
once in the starting value.  When used in a glob qualifier, any
substitutions or expansions are performed once at the time the qualifier
is parsed, even before the @code{:s} expression itself is divided into
@var{l} and @var{r} sides.

If the option @code{HIST_SUBST_PATTERN} is set or the original substitution
was started with a capital @code{S}, @var{l} is treated as
a pattern of the usual form described in @ref{17,,Filename Generation}.
This can be used in
all the places where modifiers are available; note, however, that
in globbing qualifiers parameter substitution has already taken place,
so parameters in the replacement string should be quoted to ensure
they are replaced at the correct time.
Note also that complicated patterns used in globbing qualifiers may
need the extended glob qualifier notation
@code{(#q:s/}@var{…}@code{/}@var{…}@code{/)} in order for the
shell to recognize the expression as a glob qualifier.  Further,
note that bad patterns in the substitution are not subject to
the @code{NO_BAD_PATTERN} option so will cause an error.

When @code{HIST_SUBST_PATTERN} is set, @var{l} may start with a @code{#}
to indicate that the pattern must match at the start of the string
to be substituted, and a @code{%} may appear at the start or after an @code{#}
to indicate that the pattern must match at the end of the string
to be substituted.  The @code{%} or @code{#} may be quoted with two
backslashes.

For example, the following piece of filename generation code
with the @code{EXTENDED_GLOB} option:

@example
 print -r -- *.c(#q:s/#%(#b)s(*).c/'S$@{match[1]@}.C'/)
@end example

takes the expansion of @code{*.c} and applies the glob qualifiers in the
@code{(#q}@var{…}@code{)} expression, which consists of a substitution
modifier anchored to the start and end of each word (@code{#%}).  This
turns on backreferences (@code{(#b)}), so that the parenthesised
subexpression is available in the replacement string as @code{$@{match[1]@}}.
The replacement string is quoted so that the parameter is not substituted
before the start of filename generation.

The following @code{f}, @code{F}, @code{w} and @code{W} modifiers work only with
parameter expansion and filename generation.  They are listed here to
provide a single point of reference for all modifiers.

@code{f}

@quotation

Repeats the immediately (without a colon) following modifier until the
resulting word doesn’t change any more.
@end quotation

@code{F:}@var{expr}@code{:}

@quotation

Like @code{f}, but repeats only @var{n} times if the expression
@var{expr} evaluates to @var{n}.  Any character can be used instead of
the @code{:}; if @code{(}, @code{[}, or @code{@{}
is used as the opening delimiter,
the closing delimiter should be ‘@code{)}’, @code{]}, or @code{@}},
respectively.
@end quotation

@code{w}

@quotation

Makes the immediately following modifier work on each word in the
string.
@end quotation

@code{W:}@var{sep}@code{:}

@quotation

Like @code{w} but words are considered to be the parts of the string
that are separated by @var{sep}. Any character can be used instead of
the @code{:}; opening parentheses are handled specially, see above.
@end quotation

@c historic nodename: Process Substitution

@node Process Substitution,Parameter Expansion,History Expansion,Expansion
@anchor{Zsh/expn process-substitution}@anchor{38}
@section Process Substitution


@geindex process substitution; Command

@geindex substitution@comma{} process; Command

Each part of a command argument that takes the form
@code{<(}@var{list}@code{)},
@code{>(}@var{list}@code{)} or
@code{=(}@var{list}@code{)}
is subject to process substitution.  The expression may be preceded
or followed by other strings except that, to prevent clashes with
commonly occurring strings and patterns, the last
form must occur at the start of a command argument, and the forms
are only expanded when first parsing command or assignment arguments.
Process substitutions may be used following redirection operators; in this
case, the substitution must appear with no trailing string.

Note that @code{<<(}@var{list}@code{)} is not a special syntax; it
is equivalent to @code{< <(}@var{list}@code{)}, redirecting
standard input from the result of process substitution.  Hence all
the following documentation applies.  The second form (with the space)
is recommended for clarity.

In the case of the @code{<} or @code{>} forms, the shell runs the commands in
@var{list} as a subprocess of the job executing the shell command line.
If the system supports the @code{/dev/fd}
mechanism, the command argument is the name of the device file
corresponding to a file descriptor; otherwise, if the system supports named
pipes (FIFOs), the command argument will be a named pipe.  If the form with
@code{>} is selected then writing on this special file will provide input for
@var{list}.  If @code{<} is used, then the file passed as an argument will
be connected to the output of the @var{list} process.  For example,

@example
 @code{paste <(cut -f1} @var{file1}@code{) <(cut -f3} @var{file2}@code{) |
 tee >(}@var{process1`}`) >(@code{:var:`process2}`) >/dev/null`@w{`}
@end example

cuts fields 1 and 3 from the files @var{file1} and @var{file2} respectively,
pastes the results together, and sends it to the processes
@var{process1} and @var{process2}.

If @code{=(}@var{…}@code{)} is used instead of
@code{<(}@var{…}@code{)},
then the file passed as an argument will be the name
of a temporary file containing the output of the @var{list}
process.  This may be used instead of the @code{<}
form for a program that expects to lseek (see @code{lseek(2)})
on the input file.

There is an optimisation for substitutions of the form
@code{=(<<<}@var{arg}@code{)}, where @var{arg} is a single-word argument
to the here-string redirection @code{<<<}.  This form produces a file name
containing the value of @var{arg} after any substitutions have been
performed.  This is handled entirely within the current shell.  This is
effectively the reverse of the special form @code{$(<}@var{arg}@code{)}
which treats @var{arg} as a file name and replaces it with the file’s
contents.

The @code{=} form is useful as both the @code{/dev/fd} and the named pipe
implementation of @code{<(}@var{…}@code{)} have drawbacks.  In
the former case, some programmes may automatically close the file
descriptor in question before examining the file on the command line,
particularly if this is necessary for security reasons such as when the
programme is running setuid.  In the second case, if the
programme does not actually open the file, the subshell attempting to read
from or write to the pipe will (in a typical implementation, different
operating systems may have different behaviour) block for ever and have to
be killed explicitly.  In both cases, the shell actually supplies the
information using a pipe, so that programmes that expect to lseek
(see @code{lseek(2)}) on the file will not work.

Also note that the previous example can be more compactly and
efficiently written (provided the @code{MULTIOS} option is set) as:

@example
 @code{paste <(cut -f1} @var{file1}@code{) <(cut -f3} @var{file2}@code{)}
 @code{> >(}@var{process1}@code{) > >(}@var{process2}@code{)}
@end example

The shell uses pipes instead of FIFOs to implement the latter
two process substitutions in the above example.

There is an additional problem with @code{>(}@var{process}@code{)}; when
this is attached to an external command, the parent shell does not wait
for @var{process} to finish and hence an immediately following command
cannot rely on the results being complete.  The problem and solution are
the same as described in the section @ref{6c,,Multios}.
Hence in a simplified
version of the example above:

@example
 @code{paste <(cut -f1} @var{file1}@code{) <(cut -f3} @var{file2}@code{)} @code{> >(}@var{process}@code{)}
@end example

(note that no @code{MULTIOS} are involved), @var{process} will be run
asynchronously as far as the parent shell is concerned.  The workaround is:

@example
 @code{@{ paste <(cut -f1} @var{file1}@code{) <(cut -f3} @var{file2}@code{) @}} @code{> >(}@var{process}@code{)}
@end example

The extra processes here are
spawned from the parent shell which will wait for their completion.

Another problem arises any time a job with a substitution that requires
a temporary file is disowned by the shell, including the case where
@code{&!} or @code{&|} appears at the end of a command containing a
substitution.  In that case the temporary file will not be cleaned up as
the shell no longer has any memory of the job.  A workaround is to use
a subshell, for example,

@example
 (mycmd =(myoutput)) &!
@end example

as the forked subshell will wait for the command to finish then remove
the temporary file.

A general workaround to ensure a process substitution endures for
an appropriate length of time is to pass it as a parameter to
an anonymous shell function (a piece of shell code that is run
immediately with function scope).  For example, this code:

@example
 () @{
    print File $1:
    cat $1
 @} =(print This be the verse)
@end example

outputs something resembling the following

@example
 File /tmp/zsh6nU0kS:
 This be the verse
@end example

The temporary file created by the process substitution will be deleted
when the function exits.

@c historic nodename: Parameter Expansion

@node Parameter Expansion,Command Substitution,Process Substitution,Expansion
@anchor{Zsh/expn parameter-expansion}@anchor{1a}
@section Parameter Expansion


@geindex parameter expansion; Command

@geindex expansion@comma{} parameter; Command

The character @code{$} is used to introduce parameter expansions.
See @code{zshparam}
for a description of parameters, including arrays, associative arrays,
and subscript notation to access individual array elements.

Note in particular the fact that words of unquoted parameters are not
automatically split on whitespace unless the option @code{SH_WORD_SPLIT} is
set; see references to this option below for more details.  This is an
important difference from other shells.  However, as in other shells,
null words are elided from unquoted parameters’ expansions.

With default options, after the assignments:

@example
 array=("first word" "" "third word")
 scalar="only word"
@end example

then @code{$array} substitutes two words, @code{first word} and @code{third
word}, and`@w{`} $scalar @code{substitutes a single word} only word`@w{`}.  Note
that second element of @code{array} was elided.  Scalar parameters can
be elided too if their value is null (empty).  To avoid elision, use quoting as
follows: @code{"$scalar"} for scalars and @code{"$@{array[@@]@}"} or @code{"$@{(@@)array@}"}
for arrays.  (The last two forms are equivalent.)

Parameter expansions can involve `flags', as in @code{$@{(@@kv)aliases@}},
and other operators, such as @code{$@{PREFIX:-"/usr/local"@}}.  Parameter
expansions can also be nested.  These topics will be introduced below.
The full rules are complicated and are noted at the end.

@geindex namespace; Command

Parameter expansions may optionally include a `namespace' prefix in
the format @code{.}@var{identifier}@code{.} This currently has no special
meaning to the shell, but provides a convenient means of grouping
related parameters.  Expansions using a namespace `must' include
braces (@code{@{} and @code{@}}) as shown in the descriptions below, and
only one namespace prefix is allowed.

In the expansions discussed below that require a pattern, the form of
the pattern is the same as that used for filename generation;
see @ref{17,,Filename Generation}.  Note that these patterns, along with
the replacement text of any substitutions, are themselves subject to
parameter expansion, command substitution, and arithmetic expansion.

In addition to the following operations, the colon modifiers described in
@ref{6b,,Modifiers} in @ref{66,,History Expansion} can be
applied:  for example, @code{$@{i:s/foo/bar/@}} performs string
substitution on the expansion of parameter @code{$i}.

In the following descriptions, @var{word} refers to a single word
substituted on the command line, not necessarily a space delimited word.
The reference to @var{name} in each description presumes any optional
namespace prefix.

@code{$@{}@var{name}@code{@}}

@quotation

The value, if any, of the parameter @var{name} is substituted.
The braces are required if the expansion is to be followed by
a letter, digit, or underscore that is not to be interpreted
as part of @var{name}.  In addition, more complicated forms of substitution
usually require the braces to be present; exceptions, which only apply if
the option @code{KSH_ARRAYS} is not set, are a single subscript or any colon
modifiers appearing after the name, or any of the characters @code{^},
@code{=}, @code{~}, @code{#} or @code{+} appearing before the name, all of
which work with or without braces.

If @var{name} is an array parameter, and the @code{KSH_ARRAYS} option is not
set, then the value of each
element of @var{name} is substituted, one element per word.  Otherwise, the
expansion results in one word only; with @code{KSH_ARRAYS}, this is the first
element of an array.  No field splitting is done on the result unless the
@code{SH_WORD_SPLIT} option is set.
See also the flags @code{=} and @code{s:}@var{string}@code{:}.
@end quotation

@code{$@{+}@var{name}@code{@}}

@quotation

If @var{name} is the name of a set parameter @code{1} is substituted,
otherwise @code{0} is substituted.
@end quotation

@code{$@{}@var{name}@code{-}@var{word}@code{@}}

@code{$@{}@var{name}@code{:-}@var{word}@code{@}}

@quotation

If @var{name} is set, or in the second form is non-null, then substitute
its value; otherwise substitute @var{word}.  In the second form @var{name}
may be omitted, in which case @var{word} is always substituted.
@end quotation

@code{$@{}@var{name}@code{+}@var{word}@code{@}}

@code{$@{}@var{name}@code{:+}@var{word}@code{@}}

@quotation

If @var{name} is set, or in the second form is non-null, then substitute
@var{word}; otherwise substitute nothing.
@end quotation

@code{$@{}@var{name}@code{=}@var{word}@code{@}}

@code{$@{}@var{name}@code{:=}@var{word}@code{@}}

@code{$@{}@var{name}@code{::=}@var{word}@code{@}}

@quotation

In the first form, if @var{name} is unset then set it to @var{word}; in the
second form, if @var{name} is unset or null then set it to @var{word}; and
in the third form, unconditionally set @var{name} to @var{word}.  In all
forms, the value of @var{name} is then substituted.
@end quotation

@code{$@{}@var{name}@code{?}@var{word}@code{@}}

@code{$@{}@var{name}@code{:?}@var{word}@code{@}}

@quotation

In the first form, if @var{name} is set, or in the second form if @var{name}
is both set and non-null, then substitute its value; otherwise, print
@var{word} and exit from the shell.  Interactive shells instead return to
the prompt.  If @var{word} is omitted, then a standard message is
printed.  Note that @var{word} is expanded even though its value
is not substituted onto the command line.
@end quotation

In any of the above expressions that test a variable and substitute an
alternate @var{word}, note that you can use standard shell quoting in the
@var{word} value to selectively override the splitting done by the
@code{SH_WORD_SPLIT} option and the @code{=} flag, but not splitting by the
@code{s:}@var{string}@code{:} flag.

In the following expressions, when @var{name} is an array and
the substitution is not quoted, or if the @code{(@@)} flag or the
@var{name}@code{[@@]} syntax is used, matching and replacement is
performed on each array element separately.

@code{$@{}@var{name}@code{#}@var{pattern}@code{@}}

@code{$@{}@var{name}@code{##}@var{pattern}@code{@}}

@quotation

If the @var{pattern} matches the beginning of the value of
@var{name}, then substitute the value of @var{name} with
the matched portion deleted; otherwise, just
substitute the value of @var{name}.  In the first
form, the smallest matching pattern is preferred;
in the second form, the largest matching pattern is
preferred.
@end quotation

@code{$@{}@var{name}@code{%}@var{pattern}@code{@}}

@code{$@{}@var{name}@code{%%}@var{pattern}@code{@}}

@quotation

If the @var{pattern} matches the end of the value of
@var{name}, then substitute the value of @var{name} with
the matched portion deleted; otherwise, just
substitute the value of @var{name}.  In the first
form, the smallest matching pattern is preferred;
in the second form, the largest matching pattern is
preferred.
@end quotation

@code{$@{}@var{name}@code{:#}@var{pattern}@code{@}}

@quotation

If the @var{pattern} matches the value of @var{name}, then substitute
the empty string; otherwise, just substitute the value of @var{name}.
If @var{name} is an array
the matching array elements are removed (use the @code{(M)} flag to
remove the non-matched elements).
@end quotation

@code{$@{}@var{name}@code{:|}@var{arrayname}@code{@}}

@quotation

If @var{arrayname} is the name (N.B., not contents) of an array
variable, then any elements contained in @var{arrayname} are removed
from the substitution of @var{name}.  If the substitution is scalar,
either because @var{name} is a scalar variable or the expression is
quoted, the elements of @var{arrayname} are instead tested against the
entire expression.
@end quotation

@code{$@{}@var{name}@code{:*}@var{arrayname}@code{@}}

@quotation

Similar to the preceding substitution, but in the opposite sense,
so that entries present in both the original substitution and as
elements of @var{arrayname} are retained and others removed.
@end quotation

@code{$@{}@var{name}@code{:^}@var{arrayname}@code{@}}

@code{$@{}@var{name}@code{:^^}@var{arrayname}@code{@}}

@quotation

Zips two arrays, such that the output array is twice as long as the
shortest (longest for @code{:^^}) of @code{name} and @code{arrayname}, with
the elements alternatingly being picked from them. For @code{:^}, if one
of the input arrays is longer, the output will stop when the end of the
shorter array is reached.  Thus,

@example
 a=(1 2 3 4); b=(a b); print $@{a:^b@}
@end example

will output @code{1 a 2 b}.  For @code{:^^}, then the input is repeated
until all of the longer array has been used up and the above will output
@code{1 a 2 b 3 a 4 b}.

Either or both inputs may be a scalar, they will be treated as an array
of length 1 with the scalar as the only element. If either array is empty,
the other array is output with no extra elements inserted.

Currently the following code will output @code{a b} and @code{1} as two separate
elements, which can be unexpected. The second print provides a workaround which
should continue to work if this is changed.

@example
 a=(a b); b=(1 2); print -l "$@{a:^b@}"; print -l "$@{$@{a:^b@}@}"
@end example
@end quotation

@code{$@{}@var{name}@code{:}@var{offset}@code{@}}

@code{$@{}@var{name}@code{:}@var{offset}@code{:}@var{length}@code{@}}

@quotation

This syntax gives effects similar to parameter subscripting
in the form @code{$}@var{name}@code{[}@var{start}@code{,}@var{end}@code{]}, but is
compatible with other shells; note that both @var{offset} and @var{length}
are interpreted differently from the components of a subscript.

If @var{offset} is non-negative, then if the variable @var{name} is a
scalar substitute the contents starting @var{offset} characters from the
first character of the string, and if @var{name} is an array substitute
elements starting @var{offset} elements from the first element.  If
@var{length} is given, substitute that many characters or elements,
otherwise the entire rest of the scalar or array.

A positive @var{offset} is always treated as the offset of a character or
element in @var{name} from the first character or element of the array
(this is different from native zsh subscript notation).  Hence 0
refers to the first character or element regardless of the setting of
the option @code{KSH_ARRAYS}.

A negative offset counts backwards from the end of the scalar or array,
so that -1 corresponds to the last character or element, and so on.

When positive, @var{length} counts from the @var{offset} position
toward the end of the scalar or array.  When negative, @var{length}
counts back from the end.  If this results in a position smaller
than @var{offset}, a diagnostic is printed and nothing is substituted.

The option @code{MULTIBYTE} is obeyed, i.e. the offset and length
count multibyte characters where appropriate.

@var{offset} and @var{length} undergo the same set of shell substitutions
as for scalar assignment; in addition, they are then subject to arithmetic
evaluation.  Hence, for example

@example
 print $@{foo:3@}
 print $@{foo: 1 + 2@}
 print $@{foo:$(( 1 + 2))@}
 print $@{foo:$(echo 1 + 2)@}
@end example

all have the same effect, extracting the string starting at the fourth
character of @code{$foo} if the substitution would otherwise return a scalar,
or the array starting at the fourth element if @code{$foo} would return an
array.  Note that with the option @code{KSH_ARRAYS} @code{$foo} always returns
a scalar (regardless of the use of the offset syntax) and a form
such as @code{$@{foo[*]:3@}} is required to extract elements of an array named
@code{foo}.

If @var{offset} is negative, the @code{-} may not appear immediately
after the @code{:} as this indicates the
@code{$@{}@var{name}@code{:-}@var{word}@code{@}} form of substitution.  Instead, a space
may be inserted before the @code{-}.  Furthermore, neither @var{offset} nor
@var{length} may begin with an alphabetic character or @code{&} as these are
used to indicate history-style modifiers.  To substitute a value from a
variable, the recommended approach is to precede it with a @code{$} as this
signifies the intention (parameter substitution can easily be rendered
unreadable); however, as arithmetic substitution is performed, the
expression @code{$@{var: offs@}} does work, retrieving the offset from
@code{$offs}.

For further compatibility with other shells there is a special case
for array offset 0.  This usually accesses the
first element of the array.  However, if the substitution refers to the
positional parameter array, e.g. @code{$@@} or @code{$*}, then offset 0
instead refers to @code{$0}, offset 1 refers to @code{$1}, and so on.  In
other words, the positional parameter array is effectively extended by
prepending @code{$0}.  Hence @code{$@{*:0:1@}} substitutes @code{$0} and
@code{$@{*:1:1@}} substitutes @code{$1}.
@end quotation

@code{$@{}@var{name}@code{/}@var{pattern}@code{/}@var{repl}@code{@}}

@code{$@{}@var{name}@code{//}@var{pattern}@code{/}@var{repl}@code{@}}

@code{$@{}@var{name}@code{:/}@var{pattern}@code{/}@var{repl}@code{@}}

@quotation

Replace the longest possible match of @var{pattern} in the expansion of
parameter @var{name} by string @var{repl}.  The first form
replaces just the first occurrence, the second form all occurrences,
and the third form replaces only if @var{pattern} matches the entire string.
Both @var{pattern} and @var{repl} are subject to double-quoted substitution,
so that expressions like @code{$@{name/$opat/$npat@}} will work, but obey the
usual rule that pattern characters in @code{$opat} are not treated specially
unless either the option @code{GLOB_SUBST} is set, or @code{$opat} is instead
substituted as @code{$@{~opat@}}.

The @var{pattern} may begin with a @code{#}, in which case the
@var{pattern} must match at the start of the string, or @code{%}, in
which case it must match at the end of the string, or @code{#%} in which
case the @var{pattern} must match the entire string.  The @var{repl} may
be an empty string, in which case the final @code{/} may also be omitted.
To quote the final @code{/} in other cases it should be preceded by a
single backslash; this is not necessary if the
@code{/} occurs inside a substituted parameter.  Note also that the @code{#},
@code{%} and @code{`#%} are not active if they occur inside a substituted
parameter, even at the start.

If, after quoting rules apply, @code{$@{}@var{name}@code{@}} expands to an array,
the replacements act on each element individually.  Note also the
effect of the @code{I} and @code{S} parameter expansion flags below; however,
the flags @code{M}, @code{R}, @code{B}, @code{E} and @code{N} are not useful.

For example,

@example
 foo="twinkle twinkle little star" sub="t*e" rep="spy"
 print $@{foo//$@{~sub@}/$rep@}
 print $@{(S)foo//$@{~sub@}/$rep@}
@end example

Here, the @code{~} ensures that the text of @code{$sub} is treated as a
pattern rather than a plain string.  In the first case, the longest
match for @code{t*e} is substituted and the result is @code{spy star},
while in the second case, the shortest matches are taken and the
result is @code{spy spy lispy star}.
@end quotation

@code{$@{#}@var{spec}@code{@}}

@quotation

If @var{spec} is one of the above substitutions, substitute
the length in characters of the result instead of
the result itself.  If @var{spec} is an array expression,
substitute the number of elements of the result.
This has the side-effect that joining is skipped even in quoted
forms, which may affect other sub-expressions in @var{spec}.
Note that @code{^}, @code{=}, and @code{~}, below, must appear
to the left of @code{#} when these forms are combined.

If the option @code{POSIX_IDENTIFIERS} is not set, and @var{spec} is a
simple name, then the braces are optional; this is true even
for special parameters so e.g. @code{$#-} and @code{$#*} take the length
of the string @code{$-} and the array @code{$*} respectively.  If
@code{POSIX_IDENTIFIERS} is set, then braces are required for
the @code{#} to be treated in this fashion.
@end quotation

@code{$@{^}@var{spec}@code{@}}

@code{$@{^^}@var{spec}@code{@}}

@quotation

@geindex RC_EXPAND_PARAM@comma{} toggle; Program

@geindex array expansion style@comma{} rc; Command

@geindex rc@comma{} array expansion style; Command

Turn on the @code{RC_EXPAND_PARAM} option for the
evaluation of @var{spec}; if the @code{^} is doubled, turn it off.
When this option is set, array expansions of the form
@var{foo}@code{$@{}@var{xx}@code{@}}@var{bar},
where the parameter @var{xx}
is set to @code{(}@var{a b c}@code{)}, are substituted with
@var{fooabar foobbar foocbar} instead of the default
@var{fooa b cbar}.  Note that an empty array will therefore cause
all arguments to be removed.

Internally, each such expansion is converted into the
equivalent list for brace expansion.  E.g., @code{$@{^var@}} becomes
@code{@{$var[1],$var[2],...@}}, and is processed as described in
Brace Expansion below: note, however, the expansion
happens immediately, with any explicit brace expansion
happening later.  If word splitting is also in effect the
@code{$var[}@var{N}@code{]} may themselves be split into different list
elements.
@end quotation

@code{$@{=}@var{spec}@code{@}}

@code{$@{==}@var{spec}@code{@}}

@quotation

@geindex SH_WORD_SPLIT@comma{} toggle; Program

@geindex field splitting@comma{} sh style@comma{} parameter; Command

@geindex sh@comma{} field splitting style@comma{} parameter; Command

Perform word splitting using the rules for @code{SH_WORD_SPLIT} during the
evaluation of @var{spec}, but regardless of whether the parameter appears in
double quotes; if the @code{=} is doubled, turn it off.
.. index:: single: IFS, use of; Variable

This forces parameter expansions to be split into
separate words before substitution, using @code{IFS} as a delimiter.
This is done by default in most other shells.

Note that splitting is applied to @var{word} in the assignment forms
of @var{spec} `before' the assignment to @var{name} is performed.
This affects the result of array assignments with the @code{A} flag.
@end quotation

@code{$@{~}@var{spec}@code{@}}

@code{$@{~~}@var{spec}@code{@}}

@quotation

@geindex GLOB_SUBST@comma{} toggle; Program

Turn on the @code{GLOB_SUBST} option for the evaluation of
@var{spec}; if the @code{~} is doubled, turn it off.  When this option is
set, the string resulting from the expansion will be interpreted as a
pattern anywhere that is possible, such as in filename expansion and
filename generation and pattern-matching contexts like the right
hand side of the @code{=} and @code{!=} operators in conditions.

In nested substitutions, note that the effect of the @code{~} applies to the
result of the current level of substitution.  A surrounding pattern
operation on the result may cancel it.  Hence, for example, if the
parameter @code{foo} is set to @code{*}, @code{$@{~foo//\*/*.c@}} is substituted by
the pattern @code{*.c}, which may be expanded by filename generation, but
@code{$@{$@{~foo@}//\*/*.c@}} substitutes to the string @code{*.c}, which will not
be further expanded.
@end quotation

If a @code{$@{...@}} type parameter expression or a
@code{$(...)} type command substitution is used in place of
@var{name} above, it is expanded first and the result is used as if
it were the value of @var{name}.  Thus it is
possible to perform nested operations:  @code{$@{$@{foo#head@}%tail@}}
substitutes the value of @code{$foo} with both @code{head} and @code{tail}
deleted.  The form with @code{$(...)} is often useful in
combination with the flags described next; see the examples below.
Each @var{name} or nested @code{$@{...@}} in a parameter expansion may
also be followed by a subscript expression as described in
@ref{1b,,Array Parameters}.

Note that double quotes may appear around nested expressions, in which
case only the part inside is treated as quoted; for example,
@code{$@{(f)"$(foo)"@}} quotes the result of @code{$(foo)}, but the flag @code{(f)}
(see below) is applied using the rules for unquoted expansions.  Note
further that quotes are themselves nested in this context; for example, in
@code{"$@{(@@f)"$(foo)"@}"}, there are two sets of quotes, one surrounding the
whole expression, the other (redundant) surrounding the @code{$(foo)} as
before.

@menu
* Parameter Expansion Flags:: 
* Named References:: 
* Rules:: 
* Examples:: 

@end menu

@node Parameter Expansion Flags,Named References,,Parameter Expansion
@anchor{Zsh/expn id1}@anchor{6d}@anchor{Zsh/expn parameter-expansion-flags}@anchor{6e}
@subsection Parameter Expansion Flags


@geindex parameter expansion flags; Command

@geindex flags@comma{} parameter expansion; Command

@geindex substitution@comma{} parameter@comma{} flags; Command

If the opening brace is directly followed by an opening parenthesis,
the string up to the matching closing parenthesis will be taken as a
list of flags.  In cases where repeating a flag is meaningful, the
repetitions need not be consecutive; for example, (@code{q%q%q})
means the same thing as the more readable (@code{%%qqq}).  The
following flags are supported:

@code{!}

@quotation

When the parameter being expanded is a named reference, the reference
itself is examined and thus is `not' resolved to its referent.  In
ksh emulation, the parens around this flag are optional.
@end quotation

@code{#}

@quotation

Evaluate the resulting words as numeric expressions and interpret
these as character codes.  Output the corresponding characters.  Note
that this form is entirely distinct from use of the @code{#} without
parentheses.

If the @code{MULTIBYTE} option is set and the number is greater than 127
(i.e. not an ASCII character) it is treated as a Unicode character.
@end quotation

@code{%}

@quotation

Expand all @code{%} escapes in the resulting words in the same way as in
prompts (see
@ref{6f,,Expansion of Prompt Sequences}). If this flag is given twice,
full prompt expansion is done on the resulting words, depending on the
setting of the @code{PROMPT_PERCENT}, @code{PROMPT_SUBST} and @code{PROMPT_BANG}
options.
@end quotation

@code{@@}

@quotation

In double quotes, array elements are put into separate words.
E.g., @code{"$@{(@@)foo@}"} is equivalent to @code{"$@{foo[@@]@}"} and
@code{"$@{(@@)foo[1,2]@}"} is the same as @code{"$foo[1]" "$foo[2]"}.
This is distinct from `field splitting' by the @code{f}, @code{s}
or @code{z} flags, which still applies within each array element.
@end quotation

@code{A}

@quotation

Convert the substitution into an array expression, even if it otherwise
would be scalar.  This has lower precedence than subscripting, so one
level of nested expansion is required in order that subscripts apply
to array elements.  Thus @code{$@{$@{(A)}@var{name}@code{@}[1]@}}
yields the full value of @var{name} when @var{name} is scalar.

This assigns an array parameter with @code{$@{...=...@}},
@code{$@{...:=...@}} or @code{$@{...::=...@}}.
If this flag is repeated (as in @code{AA}), assigns an associative
array parameter.  Assignment is made before sorting or padding;
if field splitting is active, the @var{word} part is split before
assignment.  The @var{name} part may be a subscripted range for
ordinary arrays; when assigning an associative array, the @var{word}
part `must' be converted to an array, for example by using
@code{$@{(AA)=}@var{name}@code{=...@}} to activate field splitting.

Surrounding context such as additional nesting or use of the value
in a scalar assignment may cause the array to be joined back into
a single string again.
@end quotation

@code{a}

@quotation

Sort in array index order; when combined with @code{O} sort in reverse
array index order.  Note that @code{a} is therefore equivalent to the
default but @code{Oa} is useful for obtaining an array’s elements in reverse
order.
@end quotation

@code{b}

@quotation

Quote with backslashes only characters that are special to pattern
matching. This is useful when the contents of the variable are to be
tested using @code{GLOB_SUBST}, including the @code{$@{~}@var{…}@code{@}} switch.

Quoting using one of the @code{q} family of flags does not work
for this purpose since quotes are not stripped from non-pattern
characters by @code{GLOB_SUBST}.  In other words,

@example
 pattern=$@{(q)str@}
 [[ $str = $@{~pattern@} ]]
@end example

works if @code{$str} is @code{a*b} but not if it is @code{a b}, whereas

@example
 pattern=$@{(b)str@}
 [[ $str = $@{~pattern@} ]]
@end example

is always true for any possible value of @code{$str}.
@end quotation

@code{c}

@quotation

With @code{$@{#}@var{name}@code{@}}, count the total number of characters in an array,
as if the elements were concatenated with spaces between them.  This is not
a true join of the array, so other expressions used with this flag may have
an effect on the elements of the array before it is counted.
@end quotation

@code{C}

@quotation

Capitalize the resulting words.  `Words’ in this case refers to sequences
of alphanumeric characters separated by non-alphanumerics, `not' to words
that result from field splitting.
@end quotation

@code{D}

@quotation

Assume the string or array elements contain directories and attempt
to substitute the leading part of these by names.  The remainder of
the path (the whole of it if the leading part was not substituted)
is then quoted so that the whole string can be used as a shell
argument.  This is the reverse of @code{~} substitution:  see
@ref{5d,,Filename Expansion}.
@end quotation

@code{e}

@quotation

Perform single word shell expansions, namely `parameter expansion',
`command substitution' and `arithmetic expansion', on the
result. Such expansions can be nested but too deep recursion may have
unpredictable effects.
@end quotation

@code{f}

@quotation

Split the result of the expansion at newlines. This is a shorthand
for @code{ps:\n:}.
@end quotation

@code{F}

@quotation

Join the words of arrays together using newline as a separator.
This is a shorthand for @code{pj:\n:}.
@end quotation

@code{g:}@var{opts}@code{:}

@quotation

Process escape sequences like the echo builtin when no options are given
(@code{g::}).  With the @code{o} option, octal escapes don’t take a leading
zero.  With the @code{c} option, sequences like @code{^X} are also processed.
With the @code{e} option, processes @code{\M-t} and similar sequences like the
print builtin.  With both of the @code{o} and @code{e} options, behaves like the
print builtin except that in none of these modes is @code{\c} interpreted.
@end quotation

@code{i}

@quotation

Sort case-insensitively.  May be combined with @code{n} or @code{O}.
@end quotation

@code{k}

@quotation

If @var{name} refers to an associative array, substitute the `keys'
(element names) rather than the values of the elements.  Used with
subscripts (including ordinary arrays), force indices or keys to be
substituted even if the subscript form refers to values.  However,
this flag may not be combined with subscript ranges.  With the
@code{KSH_ARRAYS} option a subscript @code{[*]} or @code{[@@]} is needed
to operate on the whole array, as usual.
@end quotation

@code{L}

@quotation

Convert all letters in the result to lower case, like @code{typeset -l}.
@end quotation

@code{n}

@quotation

Sort decimal integers numerically; if the first differing
characters of two test strings are not digits, sorting
is lexical.  @code{+} and @code{-} are not treated specially; they are treated as
any other non-digit.  Integers with more initial zeroes
are sorted before those with fewer or none.  Hence the array @code{foo+24 foo1 foo02
foo2 foo3 foo20 foo23} is sorted into the order shown.
May be combined with @code{i} or @code{O}.
@end quotation

@code{-}

@quotation

As @code{n}, but a leading minus sign indicates a negative decimal
integer.  A leading minus sign not followed by an integer does not trigger
numeric sorting.
Note that @code{+} signs are not handled specially (this may change in the
future).
@end quotation

@code{o}

@quotation

Sort the resulting words in ascending order; if this appears on its
own the sorting is lexical and case-sensitive (unless the locale
renders it case-insensitive).  Sorting in ascending order is the
default for other forms of sorting, so this is ignored if combined
with @code{a}, @code{i}, @code{n} or @code{-}.
@end quotation

@code{O}

@quotation

Sort the resulting words in descending order; @code{O} without @code{a},
@code{i}, @code{n} or @code{-} sorts in reverse lexical order.  May be
combined with @code{a}, @code{i}, @code{n} or @code{-} to reverse the
order of sorting.
@end quotation

@code{P}

@quotation

This forces the value of the parameter @var{name} to be interpreted as a
further parameter name, whose value will be used where appropriate.
Note that flags set with one of the @code{typeset} family of commands
(in particular case transformations) are not applied to the value of
@var{name} used in this fashion.

If used with a nested parameter or command substitution, the result of that
will be taken as a parameter name in the same way.  For example, if you
have @code{foo=bar} and @code{bar=baz}, the strings @code{$@{(P)foo@}},
@code{$@{(P)$@{foo@}@}}, and @code{$@{(P)$(echo bar)@}} will be expanded to
@code{baz}.

Likewise, if the reference is itself nested, the expression with the
flag is treated as if it were directly replaced by the parameter name.
It is an error if this nested substitution produces an array with more
than one word.  For example, if @code{name=assoc} where the parameter
@code{assoc} is an associative array, then
@code{$@{$@{(P)name@}[elt]@}} refers to the element of the associative
subscripted @code{elt}.
@end quotation

@code{q}

@quotation

Quote characters that are special to the shell in the resulting words with
backslashes; unprintable or invalid characters are quoted using the
@code{$'\}@var{NNN}@code{'} form, with separate quotes for each octet.

If this flag is given twice, the resulting words are quoted in single
quotes and if it is given three times, the words are quoted in double
quotes; in these forms no special handling of unprintable or invalid
characters is attempted.  If the flag is given four times, the words are
quoted in single quotes preceded by a @code{$}.  Note that in all three of
these forms quoting is done unconditionally, even if this does not change
the way the resulting string would be interpreted by the shell.

If a @code{q-} is given (only a single @code{q} may appear), a minimal
form of single quoting is used that only quotes the string if needed to
protect special characters.  Typically this form gives the most readable
output.

If a @code{q+} is given, an extended form of minimal quoting is used that
causes unprintable characters to be rendered using @code{$'}@var{…}@code{'}.
This quoting is similar to that used by the output of values by the
@code{typeset} family of commands.
@end quotation

@code{Q}

@quotation

Remove one level of quotes from the resulting words.
@end quotation

@code{t}

@quotation

Use a string describing the type of the parameter where the value
of the parameter would usually appear. This string consists of keywords
separated by hyphens (@code{-}). The first keyword in the string describes
the main type, it can be one of @code{scalar}, @code{array}, @code{integer},
@code{float} or @code{association}. The other keywords describe the type in
more detail, in most cases corresponding to options of the @code{typeset}
command:

@code{local}

@quotation

for local parameters
@end quotation

@code{left}

@quotation

for left justified parameters (@code{-L})
@end quotation

@code{right_blanks}

@quotation

for right justified parameters with leading blanks (@code{-R})
@end quotation

@code{right_zeros}

@quotation

for right justified parameters with leading zeros (@code{-Z})
@end quotation

@code{lower}

@quotation

for parameters whose value is converted to all lower case when it is
expanded (@code{-l})
@end quotation

@code{upper}

@quotation

for parameters whose value is converted to all upper case when it is
expanded (@code{-u})
@end quotation

@code{readonly}

@quotation

for readonly parameters (@code{-r})
@end quotation

@code{tag}

@quotation

for tagged parameters (@code{-t})
@end quotation

@code{tied}

@quotation

for parameters tied to another parameter in the manner of @code{PATH}
(colon-separated list) and @code{path} (array), whether these are
special parameters or user-defined with @code{typeset -T}
@end quotation

@code{export}

@quotation

for exported parameters (@code{-x} or @code{export})
@end quotation

@code{unique}

@quotation

for arrays which keep only the first occurrence of duplicated values (@code{-U})
@end quotation

@code{hide}

@quotation

for parameters with the `hide’ flag (@code{-h})
@end quotation

@code{hideval}

@quotation

for parameters with the `hideval’ flag (@code{-H})
@end quotation

@code{nameref}

@quotation

for named references (@code{typeset -n}) either having an empty value or
when combined with @code{!} as in @code{$@{(!t):var:`rname`@}}
@end quotation

@code{special}

@quotation

for special parameters defined by the shell
@end quotation
@end quotation

@code{u}

@quotation

Expand only the first occurrence of each unique word, like @code{typeset -U}.
@end quotation

@code{U}

@quotation

Convert all letters in the result to upper case, like @code{typeset -u}.
@end quotation

@code{v}

@quotation

Used with @code{k}, substitute (as two consecutive words) both the key
and the value of each associative array element.  Used with subscripts,
force values to be substituted even if the subscript form refers to
indices or keys.
@end quotation

@code{V}

@quotation

Make any special characters in the resulting words visible.
@end quotation

@code{w}

@quotation

With @code{$@{#}@var{name}@code{@}}, count words in arrays or strings; the @code{s}
flag may be used to set a word delimiter.
@end quotation

@code{W}

@quotation

Similar to @code{w} with the difference that empty words between
repeated delimiters are also counted.
@end quotation

@code{X}

@quotation

With this flag, parsing errors occurring with the @code{Q}, @code{e} and @code{#}
flags or the pattern matching forms such as
@code{$@{}@var{name}@code{#}@var{pattern}@code{@}} are reported.  Without the flag,
errors are silently ignored.
@end quotation

@code{z}

@quotation

Split the result of the expansion into words using shell parsing to
find the words, i.e. taking into account any quoting in the value.
Comments are not treated specially but as ordinary strings, similar
to interactive shells with the @code{INTERACTIVE_COMMENTS} option unset
(however, see the @code{Z} flag below for related options)

Note that this is done very late, even later than the @code{(s)} flag. So to
access single words in the result use nested expansions as
in @code{$@{$@{(z)foo@}[2]@}}. Likewise, to remove the quotes in the
resulting words use @code{$@{(Q)$@{(z)foo@}@}}.
@end quotation

@code{0}

@quotation

Split the result of the expansion on null bytes.  This is a shorthand
for @code{ps:\0:}.
@end quotation

The following flags (except @code{p}) are followed by one or more arguments
as shown.  Any character, or the matching pairs @code{(...)},
@code{@{...@}}, @code{[...]}, or @code{<...>}, may be used in place
of a colon as delimiters, but note that when a flag takes more than one
argument, a matched pair of delimiters must surround each argument.

@code{p}

@quotation

Recognize the same escape sequences as the @code{print} builtin
in string arguments to any of the flags described below that
follow this argument.

Alternatively, with this option string arguments may be in the form
@code{$}@var{var} in which case the value of the variable is substituted.
Note this form is strict; the string argument does not undergo general
parameter expansion.

For example,

@example
 sep=:
 val=a:b:c
 print $@{(ps.$sep.)val@}
@end example

splits the variable on a @code{:}.
@end quotation

@code{~}

@quotation

Strings inserted into the expansion by any of the flags below are to
be treated as patterns.  This applies to the string arguments of flags
that follow @code{~} within the same set of parentheses.  Compare with @code{~}
outside parentheses, which forces the entire substituted string to
be treated as a pattern.  Hence, for example,

@example
 [[ "?" = $@{(~j.|.)array@} ]]
@end example

treats @code{|} as a pattern and succeeds if and only if @code{$array}
contains the string @code{?} as an element.  The @code{~} may be
repeated to toggle the behaviour; its effect only lasts to the
end of the parenthesised group.
@end quotation

@code{j:}@var{string}@code{:}

@quotation

Join the words of arrays together using @var{string} as a separator.
.. index:: single: SH_WORD_SPLIT, use of; Program

Note that this occurs before field splitting by the @code{s:}@var{string}@code{:}
flag or the @code{SH_WORD_SPLIT} option.
@end quotation

@code{l:}@var{expr}@code{::}@var{string1}@code{::}@var{string2}@code{:}

@quotation

Pad the resulting words on the left.  Each word will be truncated if
required and placed in a field @var{expr} characters wide.

The arguments @code{:}@var{string1}@code{:} and @code{:}@var{string2}@code{:} are
optional; neither, the first, or both may be given.  Note that the same
pairs of delimiters must be used for each of the three arguments.  The
space to the left will be filled with @var{string1} (concatenated as
often as needed) or spaces if @var{string1} is not given.  If both
@var{string1} and @var{string2} are given, @var{string2} is inserted once
directly to the left of each word, truncated if necessary, before
@var{string1} is used to produce any remaining padding.

If either of @var{string1} or @var{string2} is present but empty,
i.e. there are two delimiters together at that point, the first
character of @code{$IFS} is used instead.

If the @code{MULTIBYTE} option is in effect, the flag @code{m} may also
be given, in which case widths will be used for the calculation of
padding; otherwise individual multibyte characters are treated as occupying
one unit of width.

If the @code{MULTIBYTE} option is not in effect, each byte in the string is
treated as occupying one unit of width.

Control characters are always assumed to be one unit wide; this allows the
mechanism to be used for generating repetitions of control characters.
@end quotation

@code{m}

@quotation

Only useful together with one of the flags @code{l} or @code{r} or with the
@code{#} length operator when the @code{MULTIBYTE} option
is in effect.  Use the character width reported by the system in
calculating how much of the string it occupies or the overall
length of the string.  Most printable characters have a width of one
unit, however certain Asian character sets and certain special effects
use wider characters; combining characters have zero width.
Non-printable characters are arbitrarily counted as zero width; how they
would actually be displayed will vary.

If the @code{m} is repeated, the character either counts zero (if it has
zero width), else one.  For printable character strings this has the
effect of counting the number of glyphs (visibly separate characters),
except for the case where combining characters themselves have non-zero
width (true in certain alphabets).
@end quotation

@code{r:}@var{expr}@code{::}@var{string1}@code{::}@var{string2}@code{:}

@quotation

As @code{l}, but pad the words on the right and insert @var{string2}
immediately to the right of the string to be padded.

Left and right padding may be used together.  In this case the strategy
is to apply left padding to the first half width of each of the resulting
words, and right padding to the second half.  If the string to be
padded has odd width the extra padding is applied on the left.
@end quotation

@code{s:}@var{string}@code{:}

@quotation

Force field splitting at the
separator @var{string}.  Note that a @var{string} of two or more
characters means that all of them must match in sequence; this differs from
the treatment of two or more characters in the @code{IFS} parameter.
See also the @code{=} flag and the @code{SH_WORD_SPLIT} option.  An empty
string may also be given in which case every character will be a separate
element.

For historical reasons, the usual behaviour that empty array elements
are retained inside double quotes is disabled for arrays generated
by splitting; hence the following:

@example
 line="one::three"
 print -l "$@{(s.:.)line@}"
@end example

produces two lines of output for @code{one} and @code{three} and elides the
empty field.  To override this behaviour, supply the @code{(@@)} flag as well,
i.e.  @code{"$@{(@@s.:.)line@}"}.
@end quotation

@code{Z:}@var{opts}@code{:}

@quotation

As @code{z} but takes a combination of option letters between a following
pair of delimiter characters.  With no options the effect is identical
to @code{z}.  The following options are available:

@code{(Z+c+)}

@quotation

causes comments to be parsed as a string and retained; any field in the
resulting array beginning with an unquoted comment character is a
comment.
@end quotation

@code{(Z+C+)}

@quotation

causes comments to be parsed
and removed.  The rule for comments is standard: anything between a word
starting with the third character of @code{$HISTCHARS}, default @code{#}, up to
the next newline is a comment.
@end quotation

@code{(Z+n+)}

@quotation

causes
unquoted newlines to be treated as ordinary whitespace, else they are
treated as if they are shell code delimiters and converted to
semicolons.
@end quotation

Options are combined within the same set of delimiters,
e.g. @code{(Z+Cn+)}.
@end quotation

@code{_:}@var{flags}@code{:}

@quotation

The underscore (@code{_}) flag is reserved for future use.  As of this
revision of zsh, there are no valid @var{flags}; anything following an
underscore, other than an empty pair of delimiters, is treated as an
error, and the flag itself has no effect.
@end quotation

The following flags are meaningful with the @code{$@{...#...@}} or
@code{$@{...%...@}} forms.  The @code{S}, @code{I}, and @code{*} flags may also be
used with the @code{$@{.../...@}} forms.

@code{S}

@quotation

With @code{#} or @code{##}, search for the match that starts closest to the start of
the string (a `substring match’). Of all matches at a particular position,
@code{#} selects the shortest and @code{##} the longest:

@example
 % str="aXbXc"
 % echo $@{(S)str#X*@}
 abXc
 % echo $@{(S)str##X*@}
 a
 %
@end example

With @code{%} or @code{%%}, search for the match that starts closest to the end of
the string:

@example
 % str="aXbXc"
 % echo $@{(S)str%X*@}
 aXbc
 % echo $@{(S)str%%X*@}
 aXb
 %
@end example

(Note that @code{%} and @code{%%} don’t search for the match that ends closest to the
end of the string, as one might expect.)

With substitution via @code{$@{.../...@}} or
@code{$@{...//...@}}, specifies non-greedy matching, i.e. that the
shortest instead of the longest match should be replaced:

@example
 % str="abab"
 % echo $@{str/*b/_@}
 _
 % echo $@{(S)str/*b/_@}
 _ab
 %
@end example
@end quotation

@code{I:}@var{expr}@code{:}

@quotation

Search the @var{expr}th match (where @var{expr} evaluates to a number).
This only applies when searching for substrings, either with the @code{S}
flag, or with @code{$@{.../...@}} (only the @var{expr}th match is
substituted) or @code{$@{...//...@}} (all matches from the
@var{expr}th on are substituted).  The default is to take the first match.

The @var{expr}th match is counted such that there is either one or zero
matches from each starting position in the string, although for global
substitution matches overlapping previous replacements are ignored.  With
the @code{$@{...%...@}} and @code{$@{...%%...@}} forms, the starting
position for the match moves backwards from the end as the index increases,
while with the other forms it moves forward from the start.

Hence with the string

@example
 which switch is the right switch for Ipswich?
@end example

substitutions of the form
@code{$@{(SI:}@var{N}@code{:)string#w*ch@}} as @var{N} increases
from 1 will match and remove @code{which}, @code{witch}, @code{witch} and
@code{wich}; the form using @code{##} will match and remove @code{which switch
is the right switch for Ipswich},`@w{`} witch is the right switch for
Ipswich`@w{`},`@w{`} witch for Ipswich @code{and} wich`@w{`}. The form using`@w{`} %`@w{`}
will remove the same matches as for @code{#}, but in reverse order, and the
form using @code{%%} will remove the same matches as for @code{##} in reverse
order.
@end quotation

@code{*}

@quotation

@geindex EXTENDED_GLOB@comma{} enable; Program

Enable @code{EXTENDED_GLOB} for substitution via @code{$@{.../...@}} or
@code{$@{...//...@}}.  Note that @code{**} does not disable extendedglob.
@end quotation

@code{B}

@quotation

Include the index of the beginning of the match in the result.
@end quotation

@code{E}

@quotation

Include the index one character past the end of the match in the result
(note this is inconsistent with other uses of parameter index).
@end quotation

@code{M}

@quotation

Include the matched portion in the result.
@end quotation

@code{N}

@quotation

Include the length of the match in the result.
@end quotation

@code{R}

@quotation

Include the unmatched portion in the result (the `R'est).
@end quotation

@node Named References,Rules,Parameter Expansion Flags,Parameter Expansion
@anchor{Zsh/expn named-references}@anchor{70}
@subsection Named References


@geindex named references; Command

@geindex namerefs; Command

@geindex reference variables; Command

@geindex parameters@comma{} nameref; Command

The command


@quotation

@code{typeset -n} @var{pname}@code{=}@var{rname}
@end quotation

initializes a parameter @var{pname} as a reference to a second
parameter @var{rname}.  The @var{rname} may also be omitted, in which
case @var{pname} is a placeholder which, the first time it is assigned,
is initialized to an active reference to the assigned @var{rname}. See
@ref{71,,Named References}
.. only:: not man

@quotation

under Parameters
@end quotation

for more about placeholders.

With the few exceptions described here, when
@var{pname} is used in any of the expansion forms described above, the
parameter @var{rname} is expanded instead.  This is similar to the
action of the @code{(P)} expansion flag, but when @var{rname} has itself
been declared a named reference, that third parameter referenced by
@var{pname} is also expanded, and so on.  With @code{(P)} this must be
done explicitly, so for example
@code{$@{(P)$@{(P)}@var{name}@code{@}@}}.

Unlike @code{(P)}, named references in substitutions that perform
assignment, such as @code{$@{}@var{pname}@code{::=}@var{word}@code{@}}, do not
create new arrays when @var{rname} is in the form of an array element
or slice and no such array (or associative array) is presently set.
This includes arrays declared, but not initialized, when the option
@code{TYPESET_TO_UNSET} is in effect.  The @var{word} is substituted but
no assignment occurs.

Also unlike @code{(P)} named references always expand parameters at the
scope in which @var{rname} exists when @var{pname} is initialized.  This
can be used to expand or assign parameters from an earlier scope even
if a local of the same name has been declared at a later scope.
Example:

@example
 caller=OUTER
 func () @{
   print before local: $caller
   typeset -n outer=$1
   local caller=INNER
   print by reference: $outer
   outer=RESULT
 @}
 func caller
 print after func: $caller
@end example

displays the output

@example
 before local: OUTER
 by reference: OUTER
 after func: RESULT
@end example

To force a named reference to refer to the outer scope, even if a
local has already been declared, add the @code{-u} option when declaring
the named reference.  In this case @var{rname} should already exist in
the outer scope before @var{pname} is initialized, otherwise the
behavior of assignment through @var{pname} is not defined and may
change the scope of the reference or fail with a status of 1.  Example
of correct usage:

@example
 caller=OUTER
 func () @{
   print before local: $caller
   local caller=INNER
   print after local: $caller
   typeset -n -u outer=$1
   print by reference: $outer
   outer=RESULT
 @}
 func caller
 print after func: $caller
@end example

Note, however, that named references to `special' parameters acquire
the behavior of the special parameter, regardless of the scope where
the reference is declared.

In the event that the local @var{pname} goes out of scope (its declaring
function returns) before the reference @var{rname} goes out of scope,
the reference may change to another parameter having the same name as
@var{pname}, or assignments may fail as described above.  Keep the
declaration of @var{rname} as close as possible to its initialization
to @var{pname} to avoid confusion.

When @var{rname} includes an array subscript, the subscript expression
is interpreted at the time @code{$@{}@var{pname}@code{@}} is expanded.  Any
form of subscript is allowed, including those that select individual
elements, substrings of scalar strings, or multiple elements as with
array slices or the @code{(i)}, @code{(I)}, @code{(r)}, @code{(R)} and
@code{(w)} subscript flags.  However, the subscript is evaluated with
the @code{NO_EXEC} option in effect, so command substitution and other
similar constructs produce no output, although are not syntactically
excluded.

When @var{rname} is an array (but not an array element or slice), the
named reference may also be used in substitutions requiring an
@var{arrayname}, so these are equivalent:

@example
 @code{$@{}@var{name}@code{:|}@var{rname}@code{@}}
 @code{$@{}@var{name}@code{:|}@var{pname}@code{@}}
@end example

Expansions of the form @code{$@{(t)}@var{pname}@code{@}} expand
the type information of @var{rname}, unless @var{rname} is empty, in which
case the expansion is @code{nameref}, or when no variable @var{rname}
exists, in which case the expansion is empty.

See also @code{zshparam}.

@node Rules,Examples,Named References,Parameter Expansion
@anchor{Zsh/expn rules}@anchor{72}
@subsection Rules


@geindex parameter expansion rules; Command

@geindex rules@comma{} parameter expansion; Command

@geindex substitution@comma{} parameter@comma{} rules; Command

Here is a summary of the rules for substitution; this assumes that braces
are present around the substitution, i.e. @code{$@{}@var{…}@code{@}}.  Some particular
examples are given below.  Note that the Zsh Development Group accepts
`no responsibility' for any brain damage which may occur during the
reading of the following rules.

@code{1.} `Nested substitution'

@quotation

If multiple nested @code{$@{}@var{…}@code{@}} forms are present, substitution is
performed from the inside outwards.  At each level, the substitution takes
account of whether the current value is a scalar or an array, whether the
whole substitution is in double quotes, and what flags are supplied to the
current level of substitution, just as if the nested substitution were the
outermost.  The flags are not propagated up to enclosing
substitutions; the nested substitution will return either a scalar or an
array as determined by the flags, possibly adjusted for quoting.  All the
following steps take place where applicable at all levels of substitution.

Note that, unless the @code{(P)} flag or a named reference is present,
the flags and any
subscripts apply directly to the value of the nested substitution; for
example, the expansion @code{$@{$@{foo@}@}} behaves exactly the same as
@code{$@{foo@}}.  When a named reference or the @code{(P)} flag is used in a
nested substitution,
the other substitution rules are applied to the value `before' it is
interpreted as a name, so @code{$@{$@{(P)foo@}@}} may differ from @code{$@{(P)foo@}}.
When both a named reference and the @code{(P)} flag appear, the named
reference is resolved before @code{(P)} is applied.

At each nested level of substitution, the substituted words undergo all
forms of single-word substitution (i.e. not filename generation), including
command substitution, arithmetic expansion and filename expansion
(i.e. leading @code{~} and @code{=}).  Thus, for example, @code{$@{$@{:-=cat@}:h@}}
expands to the directory where the @code{cat} program resides.  (Explanation:
the internal substitution has no parameter but a default value @code{=cat},
which is expanded by filename expansion to a full path; the outer
substitution then applies the modifier @code{:h} and takes the directory part
of the path.)
@end quotation

@code{2.} `Internal parameter flags'

@quotation

Any parameter flags set by one of the @code{typeset} family of commands, in
particular the @code{-L}, @code{-R}, @code{-Z}, @code{-u} and @code{-l} options for
padding and capitalization, are applied directly to the parameter value.
Note these flags are options to the command, e.g. @code{typeset -Z}; they
are not the same as the flags used within parameter substitutions.

At the outermost level of substitution, the @code{(P)} flag (rule @code{4.})
ignores these transformations and uses the unmodified value of the
parameter as the name to be replaced.  This is usually the desired
behavior because padding may make the value syntactically invalid as a
parameter name, but if capitalization changes are desired, use the
@code{$@{$@{(P)foo@}@}} form (rule @code{25.}).
@end quotation

@code{3.} `Parameter subscripting'

@quotation

If the value is a raw parameter reference with a subscript, such as
@code{$@{}@var{var}@code{[3]@}}, the effect of subscripting is applied directly to
the parameter.  Subscripts are evaluated left to right; subsequent
subscripts apply to the scalar or array value yielded by the previous
subscript.  Thus if @code{var} is an array, @code{$@{var[1][2]@}} is the second
character of the first word, but @code{$@{var[2,4][2]@}} is the entire third
word (the second word of the range of words two through four of the
original array).  Any number of subscripts may appear.  Flags such as
@code{(k)} and @code{(v)} which alter the result of subscripting are applied.
@end quotation

@code{4.} `Parameter name replacement'

@quotation

At the outermost level of nesting only, the @code{(P)} flag is applied.  This
treats the value so far as a parameter name (which may include a subscript
expression) and replaces that with the corresponding value.  This
replacement occurs later if the @code{(P)} flag appears in a nested
substitution.

If the value so far names a parameter that has internal flags (rule @code{2.}),
those internal flags are applied to the new value after replacement.
@end quotation

@code{5.} `Double-quoted joining'

@quotation

If the value after this process is an array, and the substitution
appears in double quotes, and neither an @code{(@@)} flag nor a @code{#}
length operator is present at the current level, then words of the
value are joined with the first character of the parameter @code{$IFS},
by default a space, between each word (single word arrays are not
modified).  If the @code{(j)} flag is present, that is used for joining
instead of @code{$IFS}.
@end quotation

@code{6.} `Nested subscripting'

@quotation

Any remaining subscripts (i.e. of a nested substitution) are evaluated at
this point, based on whether the value is an array or a scalar.  As with
@code{3.}, multiple subscripts can appear.  Note that @code{$@{foo[2,4][2]@}} is
thus equivalent to @code{$@{$@{foo[2,4]@}[2]@}} and also to
@code{"$@{$@{(@@)foo[2,4]@}[2]@}"} (the nested substitution returns an array in
both cases), but not to @code{"$@{$@{foo[2,4]@}[2]@}"} (the nested substitution
returns a scalar because of the quotes).
@end quotation

@code{7.} `Modifiers'

@quotation

Any modifiers, as specified by a trailing @code{#}, @code{%}, @code{/}
(possibly doubled) or by a set of modifiers of the form @code{:...} (see
@ref{6b,,Modifiers} in @ref{66,,History Expansion}), are applied to the words
of the value at this level.
@end quotation

@code{8.} `Character evaluation'

@quotation

Any @code{(#)} flag is applied, evaluating the result so far numerically
as a character.
@end quotation

@code{9.} `Length'

@quotation

Any initial @code{#} modifier, i.e. in the form @code{$@{#}@var{var}@code{@}}, is
used to evaluate the length of the expression so far.
@end quotation

@code{10.} `Forced joining'

@quotation

If the @code{(j)} flag is present, or no @code{(j)} flag is present but
the string is to be split as given by rule @code{11.}, and joining
did not take place at rule @code{5.}, any words in the value are joined
together using the given string or the first character of @code{$IFS} if none.
Note that the @code{(F)} flag implicitly supplies a string for joining in this
manner.
@end quotation

@code{11.} `Simple word splitting'

@quotation

If one of the @code{(s)} or @code{(f)} flags are present, or the @code{=}
specifier was present (e.g. @code{$@{=}@var{var}@code{@}}), the word is split on
occurrences of the specified string, or (for @code{=} with neither of the two
flags present) any of the characters in @code{$IFS}.

If no @code{(s)}, @code{(f)} or @code{=} was given, but the word is not
quoted and the option @code{SH_WORD_SPLIT} is set, the word is split on
occurrences of any of the characters in @code{$IFS}.  Note this step, too,
takes place at all levels of a nested substitution.
@end quotation

@code{12.} `Case modification'

@quotation

Any case modification from one of the flags @code{(L)}, @code{(U)} or @code{(C)}
is applied.
@end quotation

@code{13.} `Escape sequence replacement'

@quotation

First any replacements from the @code{(g)} flag are performed, then any
prompt-style formatting from the @code{(%)} family of flags is applied.
@end quotation

@code{14.} `Quote application'

@quotation

Any quoting or unquoting using @code{(q)} and @code{(Q)} and related flags
is applied.
@end quotation

@code{15.} `Directory naming'

@quotation

Any directory name substitution using @code{(D)} flag is applied.
@end quotation

@code{16.} `Visibility enhancement'

@quotation

Any modifications to make characters visible using the @code{(V)} flag
are applied.
@end quotation

@code{17.} `Lexical word splitting'

@quotation

If the ‘@code{(z)}’ flag or one of the forms of the ‘@code{(Z)}’ flag is
present, the word is split as if it were a shell command line, so that
quotation marks and other metacharacters are used to decide what
constitutes a word.  Note this form of splitting is entirely distinct
from that described by rule @code{11.}: it does not use @code{$IFS}, and
does not cause forced joining.
@end quotation

@code{18.} `Uniqueness'

@quotation

If the result is an array and the @code{(u)} flag was present, duplicate
elements are removed from the array.
@end quotation

@code{19.} `Ordering'

@quotation

If the result is still an array and one of the @code{(o)} or @code{(O)} flags
was present, the array is reordered.
@end quotation

@code{20.} @code{RC_EXPAND_PARAM}

@quotation

At this point the decision is made whether any resulting array elements
are to be combined element by element with surrounding text, as given
by either the @code{RC_EXPAND_PARAM} option or the @code{^} flag.
@end quotation

@code{21.} `Re-evaluation'

@quotation

Any @code{(e)} flag is applied to the value, forcing it to be re-examined
for new parameter substitutions, but also for command and arithmetic
substitutions.
@end quotation

@code{22.} `Padding'

@quotation

Any padding of the value by the @code{(l.}@var{fill}@code{.)} or
@code{(r.}@var{fill}@code{.)} flags is applied.
@end quotation

@code{23.} `Semantic joining'

@quotation

In contexts where expansion semantics requires a single word to
result, all words are rejoined with the first character of @code{IFS}
between.  So in @code{$@{(P)$@{(f)lines@}@}}
the value of @code{$@{lines@}} is split at newlines, but then must be
joined again before the @code{(P)} flag can be applied.

If a single word is not required, this rule is skipped.
@end quotation

@code{24.} `Empty argument removal'

@quotation

If the substitution does not appear in double quotes, any resulting
zero-length argument, whether from a scalar or an element of an array,
is elided from the list of arguments inserted into the command line.

Strictly speaking, the removal happens later as the same happens with
other forms of substitution; the point to note here is simply that
it occurs after any of the above parameter operations.
@end quotation

@code{25.} `Nested parameter name replacement'

@quotation

If the @code{(P)} flag is present and rule @code{4.} has not applied, the
value so far is treated as a parameter name (which may include a subscript
expression) and replaced with the corresponding value, with internal flags
(rule @code{2.}) applied to the new value.
@end quotation

@node Examples,,Rules,Parameter Expansion
@anchor{Zsh/expn examples}@anchor{73}
@subsection Examples


@geindex parameter expansion@comma{} examples; Command

The flag @code{f} is useful to split a double-quoted substitution line by
line.  For example, @code{$@{(f)"$(<}@var{file}@code{)"@}}
substitutes the contents of @var{file} divided so that each line is
an element of the resulting array.  Compare this with the effect of
@code{$(<}@var{file}@code{)} alone, which divides the file
up by words, or the same inside double quotes, which makes the entire
content of the file a single string.

The following illustrates the rules for nested parameter expansions.
Suppose that @code{$foo} contains the array @code{(bar baz)}:

@code{"$@{(@@)$@{foo@}[1]@}"}

@quotation

This produces the result @code{b}.  First, the inner substitution
@code{"$@{foo@}"}, which has no array (@code{@@}) flag, produces a single word
result @code{"bar baz"}.  The outer substitution @code{"$@{(@@)...[1]@}"} detects
that this is a scalar, so that (despite the @code{(@@)} flag) the subscript
picks the first character.
@end quotation

@code{"$@{$@{(@@)foo@}[1]@}"}

@quotation

This produces the result @code{bar}.  In this case, the inner substitution
@code{"$@{(@@)foo@}"} produces the array @code{(bar baz)}.  The outer
substitution @code{"$@{...[1]@}"} detects that this is an array and picks the
first word.  This is similar to the simple case @code{"$@{foo[1]@}"}.
@end quotation

As an example of the rules for word splitting and joining, suppose @code{$foo}
contains the array @code{(ax1 bx1)}.  Then

@code{$@{(s/x/)foo@}}

@quotation

produces the words @code{a}, @code{1 b} and @code{1}.
@end quotation

@code{$@{(j/x/s/x/)foo@}}

@quotation

produces @code{a}, @code{1}, @code{b} and @code{1}.
@end quotation

@code{$@{(s/x/)foo%%1*@}}

@quotation

produces @code{a} and  @code{b} (note the extra space).  As substitution
occurs before either joining or splitting, the operation  first generates
the modified array @code{(ax bx)}, which is joined to give
@code{"ax bx"}, and then split to give @code{a},  @code{b} and >>`<<’.  The final
empty string will then be elided, as it is not in double quotes.
@end quotation

@c historic nodename: Command Substitution

@node Command Substitution,Arithmetic Expansion,Parameter Expansion,Expansion
@anchor{Zsh/expn command-substitution}@anchor{74}
@section Command Substitution


@geindex command substitution; Command

@geindex substitution@comma{} command; Command

A command enclosed in parentheses preceded by a dollar sign, like
@code{$(...)}, or quoted with grave accents, like
@code{...\`', is executed in a subshell and replaced by its
standard output, with any trailing newlines deleted.  If the
substitution is not enclosed in double quotes, the output is broken
into words using the `@w{`}IFS} parameter.
.. index:: single: IFS, use of; Variable

The substitution @code{$(cat} @var{foo}@code{)} may be replaced
by the faster $(<@var{foo}@code{)}.  In this case @var{foo}
undergoes single word shell expansions (`parameter expansion',
`command substitution' and `arithmetic expansion'), but not
filename generation.  No subshell is created.

If the option @code{GLOB_SUBST} is set, the result of any unquoted command
substitution, including the special form just mentioned, is eligible for
filename generation.

A command with a leading pipe character, enclosed in braces prefixed by
a dollar sign, as in $@{>>|<<…@}, is executed in the current shell
context, rather than in a subshell, and is replaced by the value of the
parameter @code{REPLY} at the end of the command.  There `must not' be
any whitespace between the opening brace and the pipe character.  Any
prior value of @code{$REPLY} is saved and restored around this substitution,
in the manner of a function local parameter.  Other parameters declared
within the substitution also behave as locals, as if in a function,
unless @code{typeset -g} is used.  Trailing newlines are `not' deleted
from the final replacement in this case, and it is subject to filename
generation in the same way as $(…) but is `not'
split on @code{IFS} unless the @code{SH_WORD_SPLIT} option is set.

@geindex substitution@comma{} command@comma{} current shell; Command

@geindex substitution@comma{} command@comma{} non forking; Command

@geindex substitution@comma{} nofork; Command

Substitutions of the form $@{@{@var{param}@code{@}} …@} are similar,
except that the substitution is replaced by the value of the parameter
named by @var{param}.  No implicit save or restore applies to @var{param}
and @var{param} should `not' be declared within the command.  No space
is allowed within $@{@{ and space or newline is required after
@{@var{param}@code{@}}.  The @var{param} may include a subscript, and if,
after evaluating the expression, @var{param} names an array, then array
expansion rules apply to the final substitution.

A command enclosed in braces preceded by a dollar sign, and set off from
the braces by whitespace, like @code{$@{} … @code{@}}, is replaced by its
standard output.  Like $@{>>|<<…@} and unlike
$(…), the command executes in the current shell
context with function local behaviors and does not create a subshell.
Word splitting does not apply unless @code{SH_WORD_SPLIT} is set, but a
single trailing newline is stripped unless the substitution is enclosed
in double quotes.

Note that because $@{>>|<<…@} and the two related substitutions
must be parsed at once as both string tokens and commands, all other
braces (@{ or @}) within the command either must be quoted,
or must appear in syntactically valid pairs, such as around complex
commands, function bodies, or parameter references.  Furthermore,
comments are always recognized, even when @code{NO_INTERACTIVE_COMMENTS}
is in effect.

@c historic nodename: Arithmetic Expansion

@node Arithmetic Expansion,Brace Expansion,Command Substitution,Expansion
@anchor{Zsh/expn arithmetic-expansion}@anchor{75}
@section Arithmetic Expansion


@geindex arithmetic expansion; Command

@geindex expansion@comma{} arithmetic; Command

A string of the form $[@var{exp}@code{]} or
$((@var{exp}@code{))} is substituted
with the value of the arithmetic expression @var{exp}.  @var{exp} is
subjected to `parameter expansion', `command substitution'
and `arithmetic expansion' before it is evaluated.
See @ref{76,,Arithmetic Evaluation}.

@c historic nodename: Brace Expansion

@node Brace Expansion,Filename Expansion,Arithmetic Expansion,Expansion
@anchor{Zsh/expn brace-expansion}@anchor{77}
@section Brace Expansion


@geindex brace expansion; Command

@geindex expansion@comma{} brace; Command

A string of the form
@var{foo}@code{@{}@var{xx}@code{,}@var{yy}@code{,}@var{zz}@code{@}}@var{bar}
is expanded to the individual words
@var{fooxxbar}, @var{fooyybar} and @var{foozzbar}.
Left-to-right order is preserved.  This construct
may be nested.  Commas may be quoted in order to
include them literally in a word.

An expression of the form @{@var{n1}@code{..}@var{n2}@code{@}},
where @var{n1} and @var{n2} are integers,
is expanded to every number between
@var{n1} and @var{n2} inclusive.  If either number begins with a
zero, all the resulting numbers will be padded with leading zeroes to
that minimum width, but for negative numbers the - character is also
included in the width.  If the numbers are in decreasing order the
resulting sequence will also be in decreasing order.

An expression of the form @{@var{n1}@code{..}@var{n2}@code{..}@var{n3}@code{@}},
where @var{n1}, @var{n2}, and @var{n3} are integers,
is expanded as above, but only every @var{n3}th number starting from @var{n1}
is output.  If @var{n3} is negative the numbers are output in reverse order,
this is slightly different from simply swapping @var{n1} and @var{n2} in the case
that the step @var{n3} doesn’t evenly divide the range.  Zero padding can be
specified in any of the three numbers, specifying it in the third can be useful
to pad for example @code{@{-99..100..01@}} which is not possible to specify by putting a
0 on either of the first two numbers (i.e. pad to two characters).

An expression of the form @{@var{c1}@code{..}@var{c2}@code{@}}, where
@var{c1} and @var{c2} are single characters (which may be multibyte
characters), is expanded to every character in the range from @var{c1} to
@var{c2} in whatever character sequence is used internally.  For
characters with code points below 128 this is US ASCII (this is the only
case most users will need).  If any intervening character is not
printable, appropriate quotation is used to render it printable.
If the character sequence is reversed, the output is in reverse
order, e.g. @code{@{d..a@}} is substituted as @code{d c b a}.

If a brace expression matches none of the above forms, it is left
unchanged, unless the option @code{BRACE_CCL} (an abbreviation for `brace
character class’) is set.
.. index:: single: BRACE_CCL, use of; Program

In that case, it is expanded to a list of the individual
characters between the braces sorted into the order of the characters
in the ASCII character set (multibyte characters are not currently
handled).  The syntax is similar to a
[…] expression in filename generation:
- is treated specially to denote a range of characters, but ^ or
! as the first character is treated normally.  For example,
@code{@{abcdef0-9@}} expands to 16 words @code{0 1 2 3 4 5 6 7 8 9 a b c d e f}.

Note that brace expansion is not part of filename generation (globbing); an
expression such as @code{*/@{foo,bar@}} is split into two separate words
@code{*/foo} and @code{*/bar} before filename generation takes place.  In
particular, note that this is liable to produce a `no match’ error if
`either' of the two expressions does not match; this is to be contrasted
with @code{*/(foo|bar)}, which is treated as a single pattern but otherwise
has similar effects.

To combine brace expansion with array expansion, see the
$@{^:var:@cite{spec}@code{@}} form described
in @ref{1a,,Parameter Expansion} above.

@c historic nodename: Filename Expansion

@node Filename Expansion,Filename Generation,Brace Expansion,Expansion
@anchor{Zsh/expn filename-expansion}@anchor{5d}
@section Filename Expansion


@geindex filename expansion; Command

@geindex expansion@comma{} filename; Command

Each word is checked to see if it begins with an unquoted ~.
If it does, then the word up to a /,
or the end of the word if there is no /,
is checked to see if it can be substituted in one of the ways
described here.  If so, then the ~ and the checked portion are
replaced with the appropriate substitute value.

A ~ by itself is replaced by the value of @code{$HOME}.
A ~ followed by a + or a - is replaced by current
or previous working directory, respectively.

A ~ followed by a number is replaced by the directory at that
position in the directory stack.
@code{~0} is equivalent to ~+,
and @code{~1} is the top of the stack.
~+ followed by a number is replaced by the directory at that
position in the directory stack.
@code{~+0} is equivalent to ~+,
and @code{~+1} is the top of the stack.
~- followed by a number is replaced by the directory that
many positions from the bottom of the stack.
@code{~-0} is the bottom of the stack.
.. index:: single: PUSHD_MINUS, use of; Program

The @code{PUSHD_MINUS}
option exchanges the effects of ~+ and ~- where they are
followed by a number.

@c historic nodename: Dynamic Named Directories

@menu
* Dynamic Named Directories:: 
* Static Named Directories:: 
* `=’ Expansion:: 
* Notes:: 

@end menu

@node Dynamic Named Directories,Static Named Directories,,Filename Expansion
@anchor{Zsh/expn dynamic-named-directories}@anchor{78}
@subsection Dynamic Named Directories


@geindex directories@comma{} named@comma{} dynamic; Command

@geindex named directories@comma{} dynamic; Command

@geindex dynamic named directories; Command

If the function @code{zsh_directory_name} exists, or the shell variable
@code{zsh_directory_name_functions} exists and contains an array of
function names, then the functions are used to implement dynamic
directory naming.  The functions are tried in order until one returns
status zero, so it is important that functions test whether they can
handle the case in question and return an appropriate status.

A ~ followed by a string @var{namstr} in unquoted square brackets is
treated specially as a dynamic directory name.  Note that the first
unquoted closing square bracket always terminates @var{namstr}.  The shell
function is passed two arguments: the string @code{n} (for name) and
@var{namstr}.  It should either set the array @code{reply} to a single element
which is the directory corresponding to the name and return status zero
(executing an assignment as the last statement is usually sufficient), or
it should return status non-zero.  In the former case the element of reply
is used as the directory; in the latter case the substitution is deemed to
have failed.  If all functions fail and the option @code{NOMATCH} is set,
an error results.

The functions defined as above are also used to see if a directory can
be turned into a name, for example when printing the directory stack or
when expanding %~ in prompts.  In this case each function is passed two
arguments: the string @code{d} (for directory) and the candidate for dynamic
naming.  The function should either return non-zero status, if the
directory cannot be named by the function, or it should set the array reply
to consist of two elements: the first is the dynamic name for the directory
(as would appear within ~[@var{…}@code{]}), and the second is the
prefix length of the directory to be replaced.  For example, if the trial
directory is @code{/home/myname/src/zsh} and the dynamic name for
@code{/home/myname/src} (which has 16 characters) is @code{s}, then the function
sets

@example
 reply=(s 16)
@end example

The directory name so returned is compared with possible static names for
parts of the directory path, as described below; it is used if the prefix
length matched (16 in the example) is longer than that matched by any
static name.

It is not a requirement that a function implements both
@code{n} and @code{d} calls; for example, it might be appropriate for certain
dynamic forms of expansion not to be contracted to names.  In that case
any call with the first argument @code{d} should cause a non-zero status to
be returned.

The completion system calls @code{zsh_directory_name c} followed by
equivalent calls to elements of the array
@code{zsh_directory_name_functions}, if it exists, in order to
complete dynamic names for directories.  The code for this should be
as for any other completion function as described in
@code{zsycompsys}.

As a working example, here is a function that expands any dynamic names
beginning with the string @code{p:} to directories below
@code{/home/pws/perforce}.  In this simple case a static name for the
directory would be just as effective.

@example
 zsh_directory_name() @{
   emulate -L zsh -o extendedglob
   local -a match mbegin mend
   local base=/home/pws/perforce
   case $1 in
   ( d )  # Turn the directory into a name.
     [[ $2 == (#b)($base/)([^/]##)* ]] &&
         reply=( p:$match[2] $(( $#match[1] + $#match[2] )) )
   ;;
   ( n )  # Turn the name into a directory.
     [[ $2 == (#b)p:(?*) ]] &&
         reply=( $base/$match[1] )
   ;;
   ( c )  # Complete names.
     local -a dirs=( $base/*(/:t) )
     # Completion system populates $expl with flags for compadd.
     compadd "$expl[@@]" p:$^dirs
   ;;
   esac
 @}
@end example

@c historic nodename: Static Named Directories

@node Static Named Directories,`=’ Expansion,Dynamic Named Directories,Filename Expansion
@anchor{Zsh/expn static-named-directories}@anchor{79}
@subsection Static Named Directories


@geindex directories@comma{} named@comma{} static; Command

@geindex named directories@comma{} static; Command

@geindex static named directories; Command

A ~ followed by anything not already covered consisting
of any number of alphanumeric characters or underscore (@code{_}),
hyphen (-), or dot (.) is looked up as a
named directory, and replaced by the value of that named directory if found.
Named directories are typically home directories for users on the system.
They may also be defined if the text after the ~ is the name
of a string shell parameter whose value begins with a /.
Note that trailing slashes will be removed from the path to the directory
(though the original parameter is not modified).

It is also possible to define directory names using the @code{-d} option to the
@code{hash} builtin.

When the shell prints a path (e.g. when expanding %~ in prompts or when
printing the directory stack), the path is checked to see if it has a named
directory as its prefix.  If so, then the prefix portion is replaced with a
~ followed by the name of the directory.
The shorter of the two ways of referring to the directory is used,
i.e. either the directory name or the full path; the name is used
if they are the same length.
The parameters @code{$PWD} and @code{$OLDPWD} are never abbreviated in this fashion.

@c historic nodename: \`=' Expansion

@node `=’ Expansion,Notes,Static Named Directories,Filename Expansion
@anchor{Zsh/expn id10}@anchor{7a}
@subsection `=’ Expansion


If a word begins with an unquoted =
and the @code{EQUALS} option is set,
the remainder of the word is taken as the
name of a command.  If a command
exists by that name, the word is replaced
by the full pathname of the command.

@c historic nodename: Notes

@node Notes,,`=’ Expansion,Filename Expansion
@anchor{Zsh/expn notes}@anchor{7b}
@subsection Notes


@geindex filename expansion@comma{} notes; Command

Filename expansion is performed on the right hand side of a parameter
assignment, including those appearing after commands of the
@code{typeset} family.  In this case, the right hand side will be treated
as a colon-separated list in the manner of the @code{PATH} parameter,
so that a ~ or an = following a : is eligible for expansion.
All such behaviour can be
disabled by quoting the ~, the =, or the whole expression (but not
simply the colon); the @code{EQUALS} option is also respected.

If the option @code{MAGIC_EQUAL_SUBST} is set, any unquoted shell
argument in the form @var{identifier}@code{=}@var{expression} becomes eligible
for file expansion as described in the previous paragraph.  Quoting the
first = also inhibits this.

@c historic nodename: Filename Generation

@node Filename Generation,,Filename Expansion,Expansion
@anchor{Zsh/expn filename-generation}@anchor{17}
@section Filename Generation


@geindex filename generation; Command

If a word contains an unquoted instance of one of the characters
>>*<<, (, >>|<<, <, [, or ?, it is regarded
as a pattern for filename generation, unless the @code{GLOB} option is unset.
.. index:: single: GLOB, use of; Program

If the @code{EXTENDED_GLOB} option is set,
.. index:: single: EXTENDED_GLOB, use of; Program

the ^ and # characters also denote a pattern; otherwise
they are not treated specially by the shell.

The word is replaced with a list of sorted filenames that match
the pattern.  If no matching pattern is found, the shell gives
an error message, unless the @code{NULL_GLOB} option is set,
.. index:: single: NULL_GLOB, use of; Program

in which case the word is deleted; or unless the @code{NOMATCH}
option is unset, in which case the word is left unchanged.
.. index:: single: NOMATCH, use of; Program

In filename generation,
the character / must be matched explicitly;
also, a . must be matched
explicitly at the beginning of a pattern or after a /, unless the
@code{GLOB_DOTS} option is set.
.. index:: single: GLOB_DOTS, use of; Program

No filename generation pattern
matches the files . or …  In other instances of pattern
matching, the / and . are not treated specially.

@menu
* Glob Operators:: 
* ksh-like Glob Operators:: 
* Precedence:: 
* Globbing Flags:: 
* Approximate Matching:: 
* Recursive Globbing:: 
* Glob Qualifiers:: 

@end menu

@node Glob Operators,ksh-like Glob Operators,,Filename Generation
@anchor{Zsh/expn glob-operators}@anchor{7c}@anchor{Zsh/expn id15}@anchor{7d}
@subsection Glob Operators


@geindex glob operators; Command


@itemize *

@item 
Matches any string, including the null string.
@end itemize

?

@quotation

Matches any character.
@end quotation

[…]

@quotation

Matches any of the enclosed characters.  Ranges of characters
can be specified by separating two characters by a -.
A - or ] may be matched by including it as the
first character in the list.
.. index:: single: character classes; Command

There are also several named classes of characters, in the form
[:@var{name}@code{:]} with the following meanings.
The first set use the macros provided by
the operating system to test for the given character combinations,
including any modifications due to local language settings, see
@code{ctype(3)}:

@code{[:alnum:]}

@quotation

The character is alphanumeric
@end quotation

@code{[:alpha:]}

@quotation

The character is alphabetic
@end quotation

@code{[:ascii:]}

@quotation

The character is 7-bit, i.e. is a single-byte character without
the top bit set.
@end quotation

@code{[:blank:]}

@quotation

The character is a blank character
@end quotation

@code{[:cntrl:]}

@quotation

The character is a control character
@end quotation

@code{[:digit:]}

@quotation

The character is a decimal digit
@end quotation

@code{[:graph:]}

@quotation

The character is a printable character other than whitespace
@end quotation

@code{[:lower:]}

@quotation

The character is a lowercase letter
@end quotation

@code{[:print:]}

@quotation

The character is printable
@end quotation

@code{[:punct:]}

@quotation

The character is printable but neither alphanumeric nor whitespace
@end quotation

@code{[:space:]}

@quotation

The character is whitespace
@end quotation

@code{[:upper:]}

@quotation

The character is an uppercase letter
@end quotation

@code{[:xdigit:]}

@quotation

The character is a hexadecimal digit
@end quotation

Another set of named classes is handled internally by the shell and
is not sensitive to the locale:

@code{[:IDENT:]}

@quotation

The character is allowed to form part of a shell identifier, such
as a parameter name; this test respects the @code{POSIX_IDENTIFIERS}
option
@end quotation

@code{[:IFS:]}

@quotation

The character is used as an input field separator, i.e. is contained in the
@code{IFS} parameter
@end quotation

@code{[:IFSSPACE:]}

@quotation

The character is an IFS white space character; see the documentation
for @code{IFS} in
@ref{11,,Parameters Used by the Shell}.
@end quotation

@code{[:INCOMPLETE:]}

@quotation

Matches a byte that starts an incomplete multibyte character.
Note that there may be a sequence of more than one bytes that
taken together form the prefix of a multibyte character.  To
test for a potentially incomplete byte sequence, use the pattern
@code{[[:INCOMPLETE:]]*}.  This will never match a sequence starting
with a valid multibyte character.
@end quotation

@code{[:INVALID:]}

@quotation

Matches a byte that does not start a valid multibyte character.
Note this may be a continuation byte of an incomplete multibyte
character as any part of a multibyte string consisting of invalid and
incomplete multibyte characters is treated as single bytes.
@end quotation

@code{[:WORD:]}

@quotation

The character is treated as part of a word; this test is sensitive
to the value of the @code{WORDCHARS} parameter
@end quotation

Note that the square brackets are additional
to those enclosing the whole set of characters, so to test for a
single alphanumeric character you need @code{[[:alnum:]]}.  Named
character sets can be used alongside other types,
e.g. @code{[[:alpha:]0-9]}.
@end quotation

[^…]

[!…]

@quotation

Like […], except that it matches any character which is
not in the given set.
@end quotation

<[@var{x}]-[@var{y}]>

@quotation

Matches any number in the range @var{x} to @var{y}, inclusive.
Either of the numbers may be omitted to make the range open-ended;
hence <-> matches any number.  To match individual digits, the
[…] form is more efficient.

Be careful when using other wildcards adjacent to patterns of this form;
for example, @code{<0-9>*} will actually match any number whatsoever at the
start of the string, since the @code{<0-9>} will match the first digit, and
the * will match any others.  This is a trap for the unwary, but is
in fact an inevitable consequence of the rule that the longest possible
match always succeeds.  Expressions such as @code{<0-9>[^[:digit:]]*} can be
used instead.
@end quotation

(…)

@quotation

Matches the enclosed pattern.  This is used for grouping.
If the @code{KSH_GLOB} option is set, then a
@@, >>*<<, +, ? or ! immediately preceding
the ( is treated specially, as detailed below. The option
@code{SH_GLOB} prevents bare parentheses from being used in this way, though
the @code{KSH_GLOB} option is still available.

Note that grouping cannot extend over multiple directories: it is an error
to have a / within a group (this only applies for patterns used in
filename generation).  There is one exception:  a group of the form
(@var{pat}@code{/)#} appearing as a complete path segment can
match a sequence of directories.  For example, @code{foo/(a*/)#bar} matches
@code{foo/bar}, @code{foo/any/bar}, @code{foo/any/anyother/bar}, and so on.
@end quotation

@var{x}@code{|}@var{y}

@quotation

Matches either @var{x} or @var{y}.
This operator has lower precedence than any other.
The | character
must be within parentheses, to avoid interpretation as a pipeline.
The alternatives are tried in order from left to right.
@end quotation

^:var:@cite{x}

@quotation

(Requires @code{EXTENDED_GLOB} to be set.)
Matches anything except the pattern @var{x}.
This has a higher precedence than /, so @code{^foo/bar}
will search directories in . except @code{./foo}
for a file named @code{bar}.
@end quotation

@var{x}@code{~}@var{y}

@quotation

(Requires @code{EXTENDED_GLOB} to be set.)
Match anything that matches the pattern @var{x} but does not match @var{y}.
This has lower precedence than any operator except >>|<<, so
@code{*/*~foo/bar} will search for all files in all directories in .
and then exclude @code{foo/bar} if there was such a match.
Multiple patterns can be excluded by
@var{foo}@code{~}@var{bar}@code{~}@var{baz}.
In the exclusion pattern (@var{y}), / and . are not treated
specially the way they usually are in globbing.
@end quotation

@var{x}@code{#}

@quotation

(Requires @code{EXTENDED_GLOB} to be set.)
Matches zero or more occurrences of the pattern @var{x}.
This operator has high precedence; @code{12#} is equivalent to @code{1(2#)},
rather than @code{(12)#}.  It is an error for an unquoted # to follow
something which cannot be repeated; this includes an empty string, a
pattern already followed by ##, or parentheses when part of a
@code{KSH_GLOB} pattern (for example, !(@var{foo}@code{)#} is
invalid and must be replaced by
>>*<<(!(@var{foo}@code{))}).
@end quotation

@var{x}@code{##}

@quotation

(Requires @code{EXTENDED_GLOB} to be set.)
Matches one or more occurrences of the pattern @var{x}.
This operator has high precedence; @code{12##} is equivalent to @code{1(2##)},
rather than @code{(12)##}.  No more than two active # characters may
appear together.  (Note the potential clash with glob qualifiers in the
form @code{1(2##)} which should therefore be avoided.)
@end quotation

@node ksh-like Glob Operators,Precedence,Glob Operators,Filename Generation
@anchor{Zsh/expn ksh-like-glob-operators}@anchor{7e}
@subsection ksh-like Glob Operators


@geindex KSH_GLOB@comma{} use of; Program

If the @code{KSH_GLOB} option is set, the effects of parentheses can be
modified by a preceding @@, >>*<<, +, ? or !.
This character need not be unquoted to have special effects,
but the ( must be.

@@(…)

@quotation

Match the pattern in the parentheses.  (Like (…).)
@end quotation

>>*<<(…)

@quotation

Match any number of occurrences.  (Like (…)#,
except that recursive directory searching is not supported.)
@end quotation

+(…)

@quotation

Match at least one occurrence.  (Like (…)##,
except that recursive directory searching is not supported.)
@end quotation

?(…)

@quotation

Match zero or one occurrence.  (Like (>>|<<…).)
@end quotation

!(…)

@quotation

Match anything but the expression in parentheses.
(Like (^(…)).)
@end quotation

@node Precedence,Globbing Flags,ksh-like Glob Operators,Filename Generation
@anchor{Zsh/expn precedence}@anchor{7f}
@subsection Precedence


@geindex precedence of glob operators; Command

The precedence of the operators given above is (highest) ^, /,
~, | (lowest); the
remaining operators are simply treated from left to right as part of a
string, with # and ## applying to the shortest possible
preceding unit (i.e. a character, ?, […],
<…>, or a parenthesised expression).  As mentioned
above, a / used as a directory separator may not appear inside
parentheses, while a | must do so; in patterns used in other contexts
than filename generation (for example, in @code{case} statements and tests
within [[…]]), a / is not special; and / is also
not special after a ~ appearing outside parentheses in a filename
pattern.

@node Globbing Flags,Approximate Matching,Precedence,Filename Generation
@anchor{Zsh/expn globbing-flags}@anchor{80}@anchor{Zsh/expn id28}@anchor{81}
@subsection Globbing Flags


@geindex globbing flags; Command

@geindex glob flags; Command

There are various flags which affect any text to their right up to the
end of the enclosing group or to the end of the pattern; they require
the @code{EXTENDED_GLOB} option. All take the form
(#:var:@cite{X}@code{)} where @var{X} may have one of the following
forms:

@code{i}

@quotation

Case insensitive:  upper or lower case characters in the pattern match
upper or lower case characters.
@end quotation

@code{l}

@quotation

Lower case characters in the pattern match upper or lower case
characters; upper case characters in the pattern still only match
upper case characters.
@end quotation

@code{I}

@quotation

Case sensitive:  locally negates the effect of @code{i} or @code{l} from
that point on.
@end quotation

@geindex match; Variable

@geindex mbegin; Variable

@geindex mend; Variable

@code{b}

@quotation

Activate backreferences for parenthesised groups in the pattern;
this does not work in filename generation.  When a pattern with a set of
active parentheses is matched, the strings matched by the groups are
stored in the array @code{$match}, the indices of the beginning of the matched
parentheses in the array @code{$mbegin}, and the indices of the end in the array
@code{$mend}, with the first element of each array corresponding to the first
parenthesised group, and so on.  These arrays are not otherwise special to
the shell.  The indices use the same convention as does parameter
substitution, so that elements of @code{$mend} and @code{$mbegin} may be used in
subscripts; the @code{KSH_ARRAYS} option is respected.  Sets of globbing flags
are not considered parenthesised groups; only the first nine active
parentheses can be referenced.

For example,

@example
 foo="a_string_with_a_message"
 if [[ $foo = (a|an)_(#b)(*) ]]; then
   print $@{foo[$mbegin[1],$mend[1]]@}
 fi
@end example

prints @code{string_with_a_message}.
Note that the first set of parentheses is before the
@code{(#b)} and does not create a backreference.

Backreferences work with all forms of pattern matching other than filename
generation, but note that when performing matches on an entire array, such
as $@{@var{array}@code{#}@var{pattern}@code{@}}, or a global substitution, such
as $@{@var{param}@code{//}@var{pat}@code{/}@var{repl}@code{@}}, only the data for the
last match remains available.  In the case of global replacements this may
still be useful.  See the example for the @code{m} flag below.

The numbering of backreferences strictly follows the order of the opening
parentheses from left to right in the pattern string, although sets of
parentheses may be nested.  There are special rules for parentheses followed
by # or ##.  Only the last match of the parenthesis is
remembered: for example, in @code{[[ abab = (#b)([ab])# ]]}, only the final
@code{b} is stored in @code{match[1]}.  Thus extra parentheses may be necessary
to match the complete segment: for example, use
@code{X((ab|cd)#)Y} to match
a whole string of either @code{ab} or @code{cd} between @code{X} and @code{Y},
using the value of @code{$match[1]} rather than @code{$match[2]}.

If the match fails none of the parameters is altered, so in some cases it
may be necessary to initialise them beforehand.  If some of the
backreferences fail to match – which happens if they are in an alternate
branch which fails to match, or if they are followed by # and matched
zero times – then the matched string is set to the empty string, and the
start and end indices are set to -1.

Pattern matching with backreferences is slightly slower than without.
@end quotation

@code{B}

@quotation

Deactivate backreferences, negating the effect of the @code{b} flag from that
point on.
@end quotation

@code{c}@var{N}@code{,}@var{M}

@quotation

The flag @code{(#c}@var{N}@code{,}@var{M}@code{)} can be used anywhere
that the # or ## operators can be used except in the expressions
(`/)# and ('/)## in filename generation, where /
has special meaning; it cannot be combined with other globbing flags and
a bad pattern error occurs if it is misplaced.  It is equivalent to the
form @{@var{N}@code{,}@var{M}@code{@}} in regular expressions.  The previous
character or group is required to match between @var{N} and @var{M} times,
inclusive.  The form @code{(#c}@var{N}@code{)} requires exactly @code{N}
matches; @code{(#c,}@var{M}@code{)} is equivalent to specifying @var{N}
as 0; @code{(#c}@var{N}@code{,)} specifies that there is no maximum
limit on the number of matches.
@end quotation

@geindex MATCH; Variable

@geindex MBEGIN; Variable

@geindex MEND; Variable

@code{m}

@quotation

Set references to the match data for the entire string matched; this is
similar to backreferencing and does not work in filename generation.  The
flag must be in effect at the end of the pattern, i.e. not local to a
group. The parameters @code{$MATCH},  @code{$MBEGIN} and @code{$MEND} will be set to
the string matched and to the indices of the beginning and end of the
string, respectively.  This is most useful in parameter substitutions, as
otherwise the string matched is obvious.

For example,

@example
 arr=(veldt jynx grimps waqf zho buck)
 print $@{arr//(#m)[aeiou]/$@{(U)MATCH@}@}
@end example

forces all the matches (i.e. all vowels) into uppercase, printing
@code{vEldt jynx grImps wAqf zhO bUck}.

Unlike backreferences, there is no speed penalty for using match
references, other than the extra substitutions required for the
replacement strings in cases such as the example shown.
@end quotation

@code{M}

@quotation

Deactivate the @code{m} flag, hence no references to match data will be
created.
@end quotation

@code{a}@var{num}

@quotation

Approximate matching: @var{num} errors are allowed in the string matched by
the pattern.  The rules for this are described in the next subsection.
@end quotation

@code{s}, @code{e}

@quotation

Unlike the other flags, these have only a local effect, and each must
appear on its own:  @code{(#s)} and @code{(#e)} are the only valid forms.
The @code{(#s)} flag succeeds only at the start of the test string, and the
@code{(#e)} flag succeeds only at the end of the test string; they
correspond to ^ and $ in standard regular expressions.  They
are useful for matching path segments in patterns other than those in
filename generation (where path segments are in any case treated
separately).  For example, @code{*((#s)|/)test((#e)|/)*} matches
a path segment @code{test} in any of the following strings: @code{test},
@code{test/at/start}, @code{at/end/test}, @code{in/test/middle}.

Another use is in parameter substitution; for example
@code{$@{array/(#s)A*Z(#e)@}} will remove only elements of an
array which
match the complete pattern @code{A*Z}.  There are other ways of performing
many operations of this type, however the combination of the substitution
operations / and // with the @code{(#s)} and @code{(#e)} flags
provides a single simple and memorable method.

Note that assertions of the form @code{(^(#s))} also work, i.e. match
anywhere except at the start of the string, although this actually means
`anything except a zero-length portion at the start of the string’; you
need to use @code{(""~(#s))} to match a zero-length portion of the string
not at the start.
@end quotation

@code{q}

@quotation

A @code{q} and everything up to the closing parenthesis of the globbing
flags are ignored by the pattern matching code.  This is intended to
support the use of glob qualifiers, see below.  The result is that
the pattern @code{(#b)(*).c(#q.)} can be used both for globbing
and for
matching against a string.  In the former case, the @code{(#q.)} will be
treated as a glob qualifier and the @code{(#b)} will not be useful, while in
the latter case the @code{(#b)} is useful for backreferences and the
@code{(#q.)} will be ignored.  Note that colon modifiers in the glob
qualifiers are also not applied in ordinary pattern matching.
@end quotation

@code{u}

@quotation

Respect the current locale in determining the presence of multibyte
characters in a pattern, provided the shell was compiled with
@code{MULTIBYTE_SUPPORT}.  This overrides the @code{MULTIBYTE}
option; the default behaviour is taken from the option.  Compare @code{U}.
(Mnemonic: typically multibyte characters are from Unicode in the UTF-8
encoding, although any extension of ASCII supported by the system
library may be used.)
@end quotation

@code{U}

@quotation

All characters are considered to be a single byte long.  The opposite
of @code{u}.  This overrides the @code{MULTIBYTE} option.
@end quotation

For example, the test string @code{fooxx} can be matched by the pattern
@code{(#i}@code{)FOOXX}, but not by @code{(#l}@code{)FOOXX},
@code{(#i}@code{)FOO}@code{(#I}@code{)XX} or
@code{((#i}@code{)FOOX}@code{)X}.  The string
@code{(#ia2}@code{)readme} specifies case-insensitive matching of
@code{readme} with up to two errors.

When using the ksh syntax for grouping both @code{KSH_GLOB} and
@code{EXTENDED_GLOB} must be set and the left parenthesis should be
preceded by @@.  Note also that the flags do not affect letters
inside […] groups, in other words @code{(#i}@code{)[a-z]}
still matches only lowercase letters.  Finally, note that when
examining whole paths case-insensitively every directory must be
searched for all files which match, so that a pattern of the form
@code{(#i}@code{)/foo/bar/...} is potentially slow.

@node Approximate Matching,Recursive Globbing,Globbing Flags,Filename Generation
@anchor{Zsh/expn approximate-matching}@anchor{82}@anchor{Zsh/expn id29}@anchor{83}
@subsection Approximate Matching


@geindex approximate matching; Command

@geindex matching@comma{} approximate; Command

When matching approximately, the shell keeps a count of the errors found,
which cannot exceed the number specified in the
@code{(#a}@var{num}@code{)} flags.  Four types of error are recognised:


@enumerate 

@item 
Different characters, as in @code{fooxbar} and @code{fooybar}.

@item 
Transposition of characters, as in @code{banana} and @code{abnana}.

@item 
A character missing in the target string, as with the pattern @code{road} and
target string @code{rod}.

@item 
An extra character appearing in the target string, as with @code{stove}
and @code{strove}.
@end enumerate

Thus, the pattern @code{(#a3}@code{)abcd} matches @code{dcba}, with the
errors occurring by using the first rule twice and the second once,
grouping the string as @code{[d][cb][a]} and @code{[a][bc][d]}.

Non-literal parts of the pattern must match exactly, including characters
in character ranges: hence @code{(#a1})???  matches strings of
length four, by applying rule 4 to an empty part of the pattern, but not
strings of length two, since all the ? must match.  Other characters
which must match exactly are initial dots in filenames (unless the
@code{GLOB_DOTS} option is set), and all slashes in filenames, so that
@code{a/bc} is two errors from @code{ab/c} (the slash cannot be transposed with
another character).  Similarly, errors are counted separately for
non-contiguous strings in the pattern, so that @code{(ab|cd}@code{)ef}
is two errors from @code{aebf}.

When using exclusion via the ~ operator, approximate matching is
treated entirely separately for the excluded part and must be activated
separately.  Thus, @code{(#a1}@code{)README~READ_ME} matches
@code{READ.ME} but not @code{READ_ME}, as the trailing @code{READ_ME} is matched
without approximation.  However,
@code{(#a1}@code{)README~(#a1}@code{)READ_ME}
does not match any pattern of the form @code{READ}@var{?}@code{ME} as all
such forms are now excluded.

Apart from exclusions, there is only one overall error count; however, the
maximum errors allowed may be altered locally, and this can be delimited by
grouping.  For example,
@code{(#a1}@code{)cat}@code{((#a0}@code{)dog}@code{)fox}
allows one error in total, which may not occur in the @code{dog} section, and
the pattern
@code{(#a1}@code{)cat}@code{(#a0}@code{)dog}@code{(#a1}@code{)fox}
is equivalent.  Note that the point at which an error is first found is the
crucial one for establishing whether to use approximation; for example,
@code{(#a1)abc(#a0)xyz} will not match @code{abcdxyz}, because the
error occurs at the @code{x}, where approximation is turned off.

Entire path segments may be matched approximately, so that
@code{(#a1)/foo/d/is/available/at/the/bar} allows one error in any path
segment.  This is much less efficient than without the @code{(#a1)}, however,
since every directory in the path must be scanned for a possible
approximate match.  It is best to place the @code{(#a1)} after any path
segments which are known to be correct.

@node Recursive Globbing,Glob Qualifiers,Approximate Matching,Filename Generation
@anchor{Zsh/expn recursive-globbing}@anchor{84}
@subsection Recursive Globbing


@geindex recursive globbing; Command

@geindex globbing@comma{} recursive; Command

A pathname component of the form (@var{foo}@code{/)#}
matches a path consisting of zero or more directories
matching the pattern @var{foo}.

As a shorthand, >>**<</ is equivalent to (>>*<</)#; note that this
therefore matches files in the current directory as well as
subdirectories.
Thus:

@example
 ls -ld -- (*/)#bar
@end example

or

@example
 ls -ld -- **/bar
@end example

does a recursive directory search for files named @code{bar} (potentially
including the file @code{bar} in the current directory).  This form does not
follow symbolic links; the alternative form >>**<<>>*<</ does, but is
otherwise identical.  Neither of these can be combined with other forms of
globbing within the same path segment; in that case, the *
operators revert to their usual effect.

Even shorter forms are available when the option @code{GLOB_STAR_SHORT} is
set.  In that case if no / immediately follows a ** or >>**<<*
they are treated as if both a / plus a further * are present.
Hence:

@example
 setopt GLOBSTARSHORT
 ls -ld -- **.c
@end example

is equivalent to

@example
 ls -ld -- **/*.c
@end example

@node Glob Qualifiers,,Recursive Globbing,Filename Generation
@anchor{Zsh/expn glob-qualifiers}@anchor{85}
@subsection Glob Qualifiers


@geindex globbing@comma{} qualifiers; Command

@geindex qualifiers@comma{} globbing; Command

Patterns used for filename generation may end in a
list of qualifiers enclosed in parentheses.
The qualifiers specify which filenames that otherwise match the given pattern
will be inserted in the argument list.

@geindex BARE_GLOB_QUAL@comma{} use of; Program

If the option @code{BARE_GLOB_QUAL} is set, then a trailing set of parentheses
containing no unquoted | or ( characters (or ~ if
it is special due to @code{EXTENDED_GLOB}) is taken as a set of
glob qualifiers.  A glob subexpression that would normally be taken as glob
qualifiers, for example @code{(^x)}, can be forced to be treated as part of
the glob pattern by doubling the parentheses, in this case producing
@code{((^x))}.

If the option @code{EXTENDED_GLOB} is set, a different syntax for glob
qualifiers is available, namely @code{(#q}@var{x}@code{)}
where @var{x} is any of the same
glob qualifiers used in the other format.  The qualifiers must still appear
at the end of the pattern.  However, with this syntax multiple glob
qualifiers may be chained together.  They are treated as a logical AND of
the individual sets of flags.  Also, as the syntax is unambiguous, the
expression will be treated as glob qualifiers just as long any parentheses
contained within it are balanced; appearance of >>|<<, ( or
~ does not negate the effect.  Note that qualifiers will be
recognised in this form even if a bare glob qualifier exists at the end of
the pattern, for example @code{*(#q*)(.)} will recognise executable regular
files if both options are set; however, mixed syntax should probably be
avoided for the sake of clarity.  Note that within conditions using the
[[ form the presence of a parenthesised expression
@code{(#q}@var{…}@code{)} at the end of a string indicates that globbing
should be performed; the expression may include glob qualifiers, but
it is also valid if it is simply @code{(#q)}.  This does
not apply to the right hand side of pattern match operators as the
syntax already has special significance.

With either syntax, normal quoting and expansion rules apply to the list
of qualifiers, so that the forms >>*<<(.), @code{*(#q".")}, and
@code{qual=.;} @var{…} @code{*(#q$qual)} are generally equivalent.

A qualifier may be any one of the following:

/

@quotation

directories
@end quotation

@code{F}

@quotation

`full’ (i.e. non-empty) directories.  Note that the
opposite sense @code{(^F}) expands to empty directories
and all non-directories.  Use @code{(/^F}) for
empty directories.
@end quotation

.

@quotation

plain files
@end quotation

@@

@quotation

symbolic links
@end quotation

=

@quotation

sockets
@end quotation

@code{p}

@quotation

named pipes (FIFOs)
@end quotation


@itemize *

@item 
executable plain files (0100 or 0010 or 0001)
@end itemize

%

@quotation

device files (character or block special)
@end quotation

@code{%b}

@quotation

block special files
@end quotation

@code{%c}

@quotation

character special files
@end quotation

@code{r}

@quotation

owner-readable files (0400)
@end quotation

@code{w}

@quotation

owner-writable files (0200)
@end quotation

@code{x}

@quotation

owner-executable files (0100)
@end quotation

@code{A}

@quotation

group-readable files (0040)
@end quotation

@code{I}

@quotation

group-writable files (0020)
@end quotation

@code{E}

@quotation

group-executable files (0010)
@end quotation

@code{R}

@quotation

world-readable files (0004)
@end quotation

@code{W}

@quotation

world-writable files (0002)
@end quotation

@code{X}

@quotation

world-executable files (0001)
@end quotation

@code{s}

@quotation

setuid files (04000)
@end quotation

@code{S}

@quotation

setgid files (02000)
@end quotation

@code{t}

@quotation

files with the sticky bit (01000)
@end quotation

@code{f}@var{spec}

@quotation

files with access rights matching @var{spec}. This @var{spec} may be a
octal number optionally preceded by a =, a +, or a
-. If none of these characters is given, the behavior is the
same as for =. The octal number describes the mode bits to be
expected, if combined with a =, the value given must match the
file-modes exactly, with a +, at least the bits in the
given number must be set in the file-modes, and with a -, the
bits in the number must not be set. Giving a ? instead of a
octal digit anywhere in the number ensures that the corresponding bits
in the file-modes are not checked, this is only useful in combination
with =.

If the qualifier @code{f} is followed by any other character anything
up to the next matching character ([, @{, and < match
], @}, and > respectively, any other character
matches itself) is taken as a list of comma-separated
@var{sub-spec}s. Each @var{sub-spec} may be either an octal number as
described above or a list of any of the characters @code{u}, @code{g},
@code{o}, and @code{a}, followed by a =, a +, or a
-, followed by a list of any of the characters @code{r}, @code{w},
@code{x}, @code{s}, and @code{t}, or an octal digit. The first list of
characters specify which access rights are to be checked. If a @code{u}
is given, those for the owner of the file are used, if a @code{g} is
given, those of the group are checked, a @code{o} means to test those
of other users, and the @code{a} says to test all three groups. The
=, +, and - again says how the modes are to be
checked and have the same meaning as described for the first form
above. The second list of characters finally says which access rights
are to be expected: @code{r} for read access, @code{w} for write access,
@code{x} for the right to execute the file (or to search a directory),
@code{s} for the setuid and setgid bits, and @code{t} for the sticky
bit.

Thus, @code{*(f70?)} gives the files for which the owner has read,
write, and execute permission, and for which other group members have
no rights, independent of the permissions for other users. The pattern
@code{*(f-100)} gives all files for which the owner does not have
execute permission, and @code{*(f:gu+w,o-rx:)} gives the files for which
the owner and the other members of the group have at least write
permission, and for which other users don’t have read or execute
permission.
@end quotation

@code{e}@var{string}

+:var:@cite{cmd}

@quotation

The @var{string} or @var{cmd} will be executed as shell code.  The
filename will be
included in the list if and only if the code returns a zero status (usually
the status of the last command).

In the first form, the first character after the @code{e}
will be used as a separator and anything up to the next matching separator
will be taken  as the @var{string}; (, [, @{, and
< match ), ], @}, and >, respectively,
while any other character matches itself.
As with glob qualifiers in general, normal quoting and expansion rules
apply to the entire @var{string}.  Thus expansions must be quoted to
prevent them from being expanded before globbing is done, and quoting
does not normally protect the end separator if it appears in the code.
However, if an unquoted metacharacter is used as the separator, its
quoted/expanded form is protected.

@var{string} is then executed as shell code.  The string @code{globqual}
is appended to the array @code{zsh_eval_context} the duration of
execution.

@geindex REPLY@comma{} use of; Variable

@geindex reply@comma{} use of; Variable

During the execution of @var{string} the filename currently being tested is
available in the parameter @code{REPLY}; the parameter may be altered to
a string to be inserted into the list instead of the original
filename.  In addition, the parameter @code{reply} may be set to an array or a
string, which overrides the value of @code{REPLY}.  If set to an array, the
latter is inserted into the command line word by word.

For example, suppose a directory contains a single file @code{lonely}.  Then
the expression @code{*(e:reply=($@{REPLY@}@{1,2@})':)}’ will cause the words
@code{lonely1} and @code{lonely2} to be inserted into the command line.  Note
the quoting of @var{string}.

The form +:var:@cite{cmd} has the same effect, but no delimiters appear
around @var{cmd}.  Instead, @var{cmd} is taken as the longest sequence of
characters following the + that are alphanumeric or underscore.
Typically @var{cmd} will be the name of a shell function that contains the
appropriate test.  For example,

@example
 nt() @{ [[ $REPLY -nt $NTREF ]] @}
 NTREF=reffile
 ls -ld -- *(+nt)
@end example

lists all files in the directory that have been modified more recently than
@code{reffile}.
@end quotation

@code{d}@var{dev}

@quotation

files on the device @var{dev}
@end quotation

@code{l}[->>|<<+]:var:@cite{ct}

@quotation

files having a link count less than @var{ct} (-), greater than
@var{ct} (+), or equal to @var{ct}
@end quotation

@code{U}

@quotation

files owned by the effective user ID
@end quotation

@code{G}

@quotation

files owned by the effective group ID
@end quotation

@code{u}@var{id}

@quotation

files owned by user ID @var{id} if that is a number.  Otherwise,
@var{id} specifies a user name: the
character after the @code{u} will be taken as a separator and the string
between it and the next matching separator will be taken as a user name.
The starting separators [, @{, and <
match the final separators ], @}, and >, respectively;
any other character matches itself.  The selected files are those
owned by this user.  For example, @code{u:foo:} or @code{u[foo]} selects
files owned by user @code{foo}.
@end quotation

@code{g}@var{id}

@quotation

like @code{u}@var{id} but with group IDs or names
@end quotation

@code{a}[@code{Mwhms}][->>|<<+]:var:@cite{n}

@quotation

files accessed exactly @var{n} days ago.  Files accessed within the last
@var{n} days are selected using a negative value for @var{n} (-@var{n}).
Files accessed more than @var{n} days ago are selected by a positive @var{n}
value (+:var:@cite{n}).  Optional unit specifiers @code{M}, @code{w},
@code{h}, @code{m} or @code{s} (e.g. @code{ah5}) cause the check to be
performed with months (of 30 days), weeks, hours, minutes or seconds
instead of days, respectively.  An explicit @code{d} for days is also
allowed.

Any fractional part of the difference between the access time and the
current part in the appropriate units is ignored in the comparison.  For
instance, @code{echo *(ah-5)} would echo files accessed within the last
five hours, while @code{echo *(ah+5)} would echo files accessed at least
six hours ago, as times strictly between five and six hours are treated
as five hours.
@end quotation

@code{m}[@code{Mwhms}][->>|<<+]:var:@cite{n}

@quotation

like the file access qualifier, except that it uses the file modification
time.
@end quotation

@code{c}[@code{Mwhms}][->>|<<+]:var:@cite{n}

@quotation

like the file access qualifier, except that it uses the file inode change
time.
@end quotation

@code{L}[+|-]:var:@cite{n}

@quotation

files less than @var{n} bytes (-), more than @var{n} bytes (+), or
exactly @var{n} bytes in length.

If this flag is directly followed by a `size specifier' @code{k} (@code{K}),
@code{m} (@code{M}), or @code{p} (@code{P}) (e.g. @code{Lk-50}) the check is
performed with kilobytes, megabytes, or blocks (of 512 bytes) instead.
(On some systems additional specifiers are available for gigabytes,
@code{g} or @code{G}, and terabytes, @code{t} or @code{T}.) If a size specifier
is used a file is regarded as “exactly” the size if the file size rounded up
to the next unit is equal to the test size.  Hence @code{*(Lm1)}
matches files from 1 byte up to 1 Megabyte inclusive.  Note also that
the set of files “less than” the test size only includes files that would
not match the equality test; hence @code{*(Lm-1)} only matches
files of zero size.
@end quotation

^

@quotation

negates all qualifiers following it
@end quotation


@itemize -

@item 
toggles between making the qualifiers work on symbolic links (the
default) and the files they point to, if any; any symbolic link for
whose target the @code{stat} system call fails (whatever the cause of the
failure) is treated as a file in its own right
@end itemize

@code{M}

@quotation

sets the @code{MARK_DIRS} option for the current pattern
.. index:: single: MARK_DIRS, setting in pattern; Program
@end quotation

@code{T}

@quotation

appends a trailing qualifier mark to the filenames, analogous to the
@code{LIST_TYPES} option, for the current pattern (overrides @code{M})
@end quotation

@code{N}

@quotation

sets the @code{NULL_GLOB} option for the current pattern
.. index:: single: NULL_GLOB, setting in pattern; Program
@end quotation

@code{D}

@quotation

sets the @code{GLOB_DOTS} option for the current pattern
.. index:: single: GLOB_DOTS, setting in pattern; Program
@end quotation

@code{n}

@quotation

sets the @code{NUMERIC_GLOB_SORT} option for the current pattern
.. index:: single: NUMERIC_GLOB_SORT, setting in pattern; Program
@end quotation

@code{Y}@var{n}

@quotation

enables short-circuit mode: the pattern will expand to at most @var{n}
filenames.  If more than @var{n} matches exist, only the first @var{n}
matches in directory traversal order will be considered.

Any sorting specified with an @code{o}@var{c} or @code{O}@var{c} qualifier is
applied `after' the @var{n} matches are returned; @code{oN} is implied
otherwise.
@end quotation

@code{o}@var{c}

@quotation

specifies how the names of the files should be sorted. The following values
of @var{c} sort in the following ways:


@table @asis

@item @code{n}

By name.

@item @code{L}

By the size (length) of the files.

@item @code{l}

By number of links.

@item @code{a}

By time of last access, youngest first.

@item @code{m}

By time of last modification, youngest first.

@item @code{c}

By time of last inode change, youngest first.

@item @code{d}

By directories: files in subdirectories appear before
those in the current directory at each level of the search – this is best
combined with other criteria, for example @code{odon} to sort on names for
files within the same directory.

@item @code{N}

No sorting is performed.
@end table

@code{e}@var{string}


@table @asis

@item +:var:@cite{cmd}

Sort by shell code (see below).
@end table

Note that the modifiers ^ and - are used,
so @code{*(^-oL)} gives a list of all files sorted by file size in descending
order, following any symbolic links.  Unless @code{oN} is used, multiple order
specifiers may occur to resolve ties.

The default sorting is @code{n} (by name) unless the @code{Y} glob qualifier is used,
in which case it is @code{N} (unsorted).

@code{oe} and @code{o+} are special cases; they are each followed by shell code,
delimited as for the @code{e} glob qualifier and the + glob qualifier
respectively (see above).  The code is executed for each matched file with
the parameter @code{REPLY} set to the name of the file on entry and
@code{globsort} appended to @code{zsh_eval_context}.  The code
should modify the parameter @code{REPLY} in some fashion.  On return, the
value of the parameter is used instead of the file name as the string on
which to sort.  Unlike other sort operators, @code{oe} and @code{o+} may be
repeated, but note that the maximum number of sort operators of any kind
that may appear in any glob expression is 12.
@end quotation

@code{O}@var{c}

@quotation

like @code{o}, but sorts in descending order; i.e. @code{*(^o}@var{c}@code{)} is the
same as @code{*(O}@var{c}@code{)} and @code{*(^O}@var{c}@code{)} is the same as @code{*(o}@var{c}@code{)}; @code{Od}
puts files in the current directory before those in subdirectories at each
level of the search.
@end quotation

[@var{beg}[,:var:@cite{end}]]

@quotation

specifies which of the matched filenames should be included in the
returned list. The syntax is the same as for array
subscripts. @var{beg} and the optional @var{end} may be mathematical
expressions. As in parameter subscripting they may be negative to make
them count from the last match backward. E.g.: @code{*(-OL[1,3])}
gives a list of the names of the three largest files.
@end quotation

@code{P}@var{string}

@quotation

The @var{string} will be prepended to each glob match as a separate
word.  @var{string} is delimited in the same way as arguments to the
@code{e} glob qualifier described above.  The qualifier can be repeated;
the words are prepended separately so that the resulting command
line contains the words in the same order they were given in the
list of glob qualifiers.

A typical use for this is to prepend an option before all occurrences
of a file name; for example, the pattern @code{*(P:-f:)} produces the
command line arguments @code{-f} @var{file1} @code{-f} @var{file2} …

If the modifier ^ is active, then @var{string} will be appended
instead of prepended.  Prepending and appending is done independently
so both can be used on the same glob expression; for example by writing
@code{*(P:foo:^P:bar:^P:baz:)} which produces the command line arguments
@code{foo} @code{baz} @var{file1} @code{bar} …
@end quotation

Multiple consecutive qualifiers are joined into a list by implicit logical AND.
More than one of these lists can be combined using comma , as logical OR.
The whole list matches if at least one of the sublists matches.
Some qualifiers,
however, affect all matches generated, independent of the sublist in
which they are given.  These are the qualifiers @code{M}, @code{T},
@code{N}, @code{D}, @code{n}, @code{o}, @code{O} and the subscripts given
in brackets ([@var{…}@code{]}).

If a : appears in a qualifier list, the remainder of the expression in
parenthesis is interpreted as a modifier (see @ref{6b,,Modifiers}
in @ref{66,,History Expansion}).  Each modifier must be introduced by a
separate :.  Note also that the result after modification does not
have to be an existing file.  The name of any existing file can be followed
by a modifier of the form (:@var{…}@code{)}
even if no actual filename generation
is performed, although note that the presence of the parentheses
causes the entire expression to be subjected to any global pattern matching
options such as @code{NULL_GLOB}. Thus:

@example
 ls -ld -- *(-/)
@end example

lists all directories and symbolic links that point to directories,
and

@example
 ls -ld -- *(-@@)
@end example

lists all broken symbolic links, and

@example
 ls -ld -- *(%W)
@end example

lists all world-writable device files in the current directory, and

@example
 ls -ld -- *(W,X)
@end example

lists all files in the current directory that are
world-writable or world-executable, and

@example
 print -rC1 /tmp/foo*(u0^@@:t)
@end example

outputs the basename of all root-owned files beginning with the string
@code{foo} in @code{/tmp}, ignoring symlinks, and

@example
 ls -ld -- *.*~(lex|parse).[ch](^D^l1)
@end example

lists all files having a link count of one whose names contain a dot
(but not those starting with a dot, since @code{GLOB_DOTS} is explicitly
switched off) except for @code{lex.c}, @code{lex.h}, @code{parse.c} and @code{parse.h}.

@example
 print -rC1 b*.pro(#q:s/pro/shmo/)(#q.:s/builtin/shmiltin/)
@end example

demonstrates how colon modifiers and other qualifiers may be chained
together.  The ordinary qualifier . is applied first, then the colon
modifiers in order from left to right.  So if @code{EXTENDED_GLOB} is set and
the base pattern matches the regular file @code{builtin.pro}, the shell will
print @code{shmiltin.shmo}.

@c historic nodename: Parameters

@node Parameters,Options<2>,Expansion,Top
@anchor{Zsh/params doc}@anchor{86}@anchor{Zsh/params parameters}@anchor{87}
@chapter Parameters


@geindex parameters; Command

@geindex variables; Command

@menu
* Description: Description<2>. 
* Array Parameters:: 
* Positional Parameters:: 
* Local Parameters:: 
* Named References: Named References<2>. 
* Parameters Set by the Shell:: 
* Parameters Used by the Shell:: 

@end menu

@node Description<2>,Array Parameters,,Parameters
@anchor{Zsh/params description}@anchor{88}
@section Description


A parameter has a name, a value, and a number of attributes.
User-assignable parameter names may contain alphanumeric characters,
underscores, and (per the description of namespaces below) dots.
They may not begin with a number, except for positional parameters
(@code{$1}, @code{$2}, etc.), whose names consist `only' of numbers.  There
are also special shell parameters with single-character names such as
@code{*}, @code{@@}, @code{#}, @code{?}, @code{-}, @code{$}, and @code{!}.
These are described below.
A parameter whose name begins with an alphanumeric or underscore is also
referred to as a `variable'.

@geindex scalar; Command

@geindex parameters@comma{} scalar; Command

@geindex parameters@comma{} array; Command

@geindex parameters@comma{} associative array; Command

@geindex hash; Command

The attributes of a parameter determine the `type' of its value, often
referred to as the parameter type or variable type, and also control
other processing that may be applied to the value when it is referenced.
The value type may be a `scalar' (a string, an integer, or a floating
point number), an array (indexed numerically), or an `associative'
array (an unordered set of name-value pairs, indexed by name, also
referred to as a `hash').

@geindex export; Command

@geindex environment; Command

@geindex environment variables; Command

@geindex variables@comma{} environment; Command

Named scalar parameters may have the `exported', @code{-x}, attribute, to
copy them into the process environment, which is then passed from the
shell to any new processes that it starts.  Exported parameters are called
`environment variables'. The shell also `imports' environment variables
at startup time and automatically marks the corresponding parameters as
exported.  Some environment variables are not imported for reasons of
security or because they would interfere with the correct operation of
other shell features.

@geindex special parameters; Command

@geindex parameters@comma{} special; Command

Parameters may also be `special', that is, they have a predetermined
meaning to the shell.  Special parameters cannot have their type changed
or their readonly attribute turned off, and if a special parameter is
unset, then later recreated, the special properties will be retained.

To declare the type of a parameter, or to assign a string or numeric value
to a scalar parameter, use the @code{typeset} builtin.
.. index:: single: typeset, use of; Function

The value of a scalar parameter may also be assigned by writing:
.. index:: single: assignment; Command


@quotation

@var{name}@code{=}@var{value}
@end quotation

@geindex namespace; Command

The @var{name} in an assignment may optionally include a `namespace'
prefix:


@quotation

@code{.}@var{namespace}@code{.}@var{parameter}@code{=}@var{value}
@end quotation

Namespaces have no special meaning to the shell except that parameters
with a @code{.} prefix are not listed by the @code{set} builtin, nor
shown by the @code{typeset} builtin unless explicitly named or the
@code{-m} option is used.  They provide a convenient way to group
related variables.  Note that, for support of possible future features,
the first @code{.} is optional, but omitting it is discouraged.  Note also
that a name starting with a @code{.} does not refer to the same parameter
as one that does not, eg, @code{.foo.bar} and @code{foo.bar} are distinct
parameters.  Unlike ksh, a namespace need not be declared before it
is referenced.

In scalar assignment, @var{value} is expanded as a single string, in
which the elements of arrays are joined together; filename expansion is
not performed unless the option @code{GLOB_ASSIGN} is set.

When the integer attribute, @code{-i}, or a floating point attribute, @code{-E}
or @code{-F}, is set for @var{name}, the @var{value} is subject to arithmetic
evaluation.  Furthermore, by replacing @code{=} with @code{+=}, a parameter
can be incremented or appended to.  See @ref{1b,,Array Parameters} and
@ref{89,,Arithmetic Evaluation}
for additional forms of assignment.

Note that assignment may implicitly change the attributes of a parameter.
For example, assigning a number to a variable in arithmetic evaluation may
change its type to integer or float, and with @code{GLOB_ASSIGN} assigning a
pattern to a variable may change its type to an array.

To reference the value of a parameter, write @code{$}@var{name} or
@code{$@{}@var{name}@code{@}}.  The latter form is required when @var{name}
includes a namespace prefix.  See @ref{1a,,Parameter Expansion}
for complete details.  That section also explains the effect
of the difference between scalar and array assignment on parameter
expansion.

@c historic nodename: Array Parameters

@geindex array parameters; Command

@geindex parameters@comma{} array; Command

@node Array Parameters,Positional Parameters,Description<2>,Parameters
@anchor{Zsh/params array-parameters}@anchor{1b}
@section Array Parameters


To assign an array value, write one of:
.. index:: single: set, use of; Function

@geindex array assignment; Command


@quotation

@code{set -A} @var{name} @var{value} …
@end quotation


@quotation

@var{name}@code{=(}@var{value} …`@w{`})`@w{`}
@end quotation


@quotation

@var{name}@code{=([}@var{key}@code{]=}@var{value} …`@w{`})`@w{`}
@end quotation

If no parameter @var{name} exists, an ordinary array parameter is created.
If the parameter @var{name} exists and is a scalar, it is replaced by a new
array.

In the third form, @var{key} is an expression that will be evaluated in
arithmetic context (in its simplest form, an integer) that gives the
index of the element to be assigned with @var{value}.  In this form any
elements not explicitly mentioned that come before the largest index to
which a value is assigned are assigned an empty string.  The indices
may be in any order.  Note that this syntax is strict: @code{[} and @code{]=} must
not be quoted, and @var{key} may not consist of the unquoted string
@code{]=}, but is otherwise treated as a simple string.  The enhanced forms
of subscript expression that may be used when directly subscripting a
variable name, described in @ref{8a,,Array Subscripts}, are not
available.

The syntaxes with and without the explicit key may be mixed.  An implicit
@var{key} is deduced by incrementing the index from the previously
assigned element.  Note that it is not treated as an error
if latter assignments in this form overwrite earlier assignments.

For example, assuming the option @code{KSH_ARRAYS} is not set, the following:

@example
 array=(one [3]=three four)
@end example

causes the array variable @code{array} to contain four elements @code{one},
an empty string, @code{three} and @code{four}, in that order.

In the forms where only @var{value} is specified, full command
line expansion is performed.

In the @code{[}@var{key}@code{]=}@var{value} form,
both @var{key} and @var{value} undergo all forms of expansion
allowed for single word shell expansions (this does not include filename
generation); these are as performed by the parameter expansion flag
@code{(e)} as described in
@ref{6e,,Parameter Expansion Flags}.
Nested parentheses may surround @var{value} and are included as part of the
value, which is joined into a plain string; this differs from ksh which
allows the values themselves to be arrays.  A future version of zsh may
support that.  To cause the brackets to be interpreted as a character
class for filename generation, and therefore to treat the resulting list
of files as a set of values, quote the equal sign using any form of quoting.
Example:


@quotation

@var{name}@code{=([a-z]'='*)}
@end quotation

To append to an array without changing the existing values, use
one of the following:


@quotation

@var{name}@code{+=(}@var{value} …`@w{`})`@w{`}
@end quotation


@quotation

@var{name}@code{+=([}@var{key}@code{]=}@var{value} …`@w{`})`@w{`}
@end quotation

In the second form @var{key} may specify an existing index as well as an
index off the end of the old array; any existing value is overwritten by
@var{value}.  Also, it is possible to use @code{[}@var{key}@code{]+=}@var{value}
to append to the existing value at that index.

Within the parentheses on the right hand side of either form of the
assignment, newlines and semicolons are treated the same as white space,
separating individual @var{value}s.  Any consecutive sequence of such
characters has the same effect.

Ordinary array parameters may also be explicitly declared with:
.. index:: single: typeset, use of; Function


@quotation

@code{typeset -a} @var{name}
@end quotation

Associative arrays `must' be declared before assignment, by using:


@quotation

@code{typeset -A} @var{name}
@end quotation

When @var{name} refers to an associative array, the list in an assignment
is interpreted as alternating keys and values:


@quotation

@code{set -A} @var{name} @var{key} @var{value} …
@end quotation


@quotation

@var{name}@code{=(}@var{key} @var{value} …`@w{`})`@w{`}
@end quotation


@quotation

@var{name}@code{=([}@var{key}@code{]=}@var{value} …`@w{`})`@w{`}
@end quotation

Note that only one of the two syntaxes above may be used in any
given assignment; the forms may not be mixed.  This is unlike the case
of numerically indexed arrays.

Every @var{key} must have a @var{value} in this case.  Note that this
assigns to the entire array, deleting any elements that do not appear in
the list.  The append syntax may also be used with an associative array:


@quotation

@var{name}@code{+=(}@var{key} @var{value} …`@w{`})`@w{`}
@end quotation


@quotation

@var{name}@code{+=([}@var{key}@code{]=}@var{value} …`@w{`})`@w{`}
@end quotation

This adds a new key/value pair if the key is not already present, and
replaces the value for the existing key if it is.  In the second
form it is also possible to use @code{[}@var{key}@code{]+=}@var{value} to
append to the existing value at that key.  Expansion is performed
identically to the corresponding forms for normal arrays, as
described above.

To create an empty array (including associative arrays), use one of:


@quotation

@code{set -A} @var{name}
@end quotation


@quotation

@var{name}@code{=()}
@end quotation

@menu
* Array Subscripts:: 
* Array Element Assignment:: 
* Subscript Flags:: 
* Subscript Parsing:: 

@end menu

@node Array Subscripts,Array Element Assignment,,Array Parameters
@anchor{Zsh/params array-subscripts}@anchor{8a}@anchor{Zsh/params id1}@anchor{8b}
@subsection Array Subscripts


@geindex subscripts; Command

Individual elements of an array may be selected using a subscript.  A
subscript of the form @code{[}@var{exp}@code{]} selects the single element
@var{exp}, where @var{exp} is an arithmetic expression which will be subject
to arithmetic expansion as if it were surrounded by
@code{$((...))}.  The elements are numbered
beginning with 1, unless the @code{KSH_ARRAYS} option is set in which case
they are numbered from zero.
.. index:: single: KSH_ARRAYS, use of; Program

Subscripts may be used inside braces used to delimit a parameter name, thus
@code{$@{foo[2]@}} is equivalent to @code{$foo[2]}.  If the @code{KSH_ARRAYS}
option is set, the braced form is the only one that works, as bracketed
expressions otherwise are not treated as subscripts.

If the @code{KSH_ARRAYS} option is not set, then by default accesses to
an array element with a subscript that evaluates to zero return an
empty string, while an attempt to write such an element is treated as
an error.  For backward compatibility the @code{KSH_ZERO_SUBSCRIPT}
option can be set to cause subscript values 0 and 1 to be equivalent; see
the description of the option in @code{zshoptions}.

The same subscripting syntax is used for associative arrays, except that
no arithmetic expansion is applied to @var{exp}.  However, the parsing
rules for arithmetic expressions still apply, which affects the way that
certain special characters must be protected from interpretation.  See
`Subscript Parsing' below for details.

A subscript of the form @code{[*]} or @code{[@@]} evaluates to all elements
of an array; there is no difference between the two except when they
appear within double quotes.
@code{"$foo[*]"} evaluates to @code{"$foo[1] $foo[2] ..."}, whereas
@code{"$foo[@@]"} evaluates to @code{"$foo[1]" "$foo[2]"} ….  For
associative arrays, @code{[*]} or @code{[@@]} evaluate to all the values,
in no particular order.  Note that this does not substitute
the keys; see the documentation for the @code{k} flag under
@ref{6e,,Parameter Expansion Flags}
for complete details.
When an array parameter is referenced as @code{$}@var{name} (with no
subscript) it evaluates to @code{$}@var{name}@code{[*]}, unless the @code{KSH_ARRAYS}
option is set in which case it evaluates to @code{$@{}@var{name}@code{[0]@}} (for
an associative array, this means the value of the key @code{0}, which may
not exist even if there are values for other keys).

A subscript of the form @code{[}@var{exp1}@code{,}@var{exp2}@code{]}
selects all elements in the range @var{exp1} to @var{exp2},
inclusive. (Associative arrays are unordered, and so do not support
ranges.) If one of the subscripts evaluates to a negative number,
say @code{-}@var{n}, then the @var{n}th element from the end
of the array is used.  Thus @code{$foo[-3]} is the third element
from the end of the array @code{foo}, and
@code{$foo[1,-1]} is the same as @code{$foo[*]}.

Subscripting may also be performed on non-array values, in which
case the subscripts specify a substring to be extracted.
For example, if @code{FOO} is set to @code{foobar}, then
@code{echo $FOO[2,5]} prints @code{ooba}.  Note that
some forms of subscripting described below perform pattern matching,
and in that case the substring extends from the start of the match
of the first subscript to the end of the match of the second
subscript.  For example,

@example
 string="abcdefghijklm"
 print $@{string[(r)d?,(r)h?]@}
@end example

prints @code{defghi}.  This is an obvious generalisation of the
rule for single-character matches.  For a single subscript,
only a single character is referenced (not the range of characters
covered by the match).

Note that in substring operations the second subscript is handled
differently by the @code{r} and @code{R} subscript flags: the former takes the
shortest match as the length and the latter the longest match.  Hence
in the former case a @code{*} at the end is redundant while in
the latter case it matches the whole remainder of the string.  This
does not affect the result of the single subscript case as here the
length of the match is irrelevant.

@node Array Element Assignment,Subscript Flags,Array Subscripts,Array Parameters
@anchor{Zsh/params array-element-assignment}@anchor{8c}
@subsection Array Element Assignment


A subscript may be used on the left side of an assignment like so:


@quotation

@var{name}@code{[}@var{exp}@code{]=}@var{value}
@end quotation

In this form of assignment the element or range specified by @var{exp}
is replaced by the expression on the right side.  An array (but not an
associative array) may be created by assignment to a range or element.
Arrays do not nest, so assigning a parenthesized list of values to an
element or range changes the number of elements in the array, shifting the
other elements to accommodate the new values.  (This is not supported for
associative arrays.)

This syntax also works as an argument to the @code{typeset} command:


@quotation

@code{typeset} @code{"}@var{name}@code{[}@var{exp}@code{]"=}@var{value}
@end quotation

The @var{value} may `not' be a parenthesized list in this case; only
single-element assignments may be made with @code{typeset}.  Note that quotes
are necessary in this case to prevent the brackets from being interpreted
as filename generation operators.  The @code{noglob} precommand modifier
could be used instead.

To delete an element of an ordinary array, assign @code{()} to
that element.  To delete an element of an associative array, use the
@code{unset} command:


@quotation

@code{unset} @code{"}@var{name}@code{[}@var{exp}@code{]"}
@end quotation

@node Subscript Flags,Subscript Parsing,Array Element Assignment,Array Parameters
@anchor{Zsh/params subscript-flags}@anchor{8d}
@subsection Subscript Flags


@geindex subscript flags; Command

If the opening bracket, or the comma in a range, in any subscript
expression is directly followed by an opening parenthesis, the string up
to the matching closing one is considered to be a list of flags, as in
@var{name}@code{[(}@var{flags}@code{)}@var{exp}@code{]}.

The flags @code{s}, @code{n} and @code{b} take an argument; the delimiter
is shown below as @code{:}, but any character, or the matching pairs
@code{(...)}, @code{@{...@}}, @code{[...]}, or
@code{<...>}, may be used, but note that @code{<...>} can only be
used if the subscript is inside a double quoted expression or a
parameter substitution enclosed in braces as otherwise the expression is
interpreted as a redirection.

The flags currently understood are:

@code{w}

@quotation

If the parameter subscripted is a scalar then this flag makes
subscripting work on words instead of characters.  The default word
separator is whitespace.  When combined with the @code{i} or @code{I} flag,
the effect is to produce the index of the first character of the
first/last word which matches the given pattern; note that a failed
match in this case always yields 0.
@end quotation

@code{s:}@var{string}@code{:}

@quotation

This gives the @var{string} that separates words (for use with the
@code{w} flag).  The delimiter character @code{:} is arbitrary; see above.
@end quotation

@code{p}

@quotation

Recognize the same escape sequences as the @code{print} builtin in
the string argument of a subsequent @code{s} flag.
@end quotation

@code{f}

@quotation

If the parameter subscripted is a scalar then this flag makes
subscripting work on lines instead of characters, i.e. with elements
separated by newlines.  This is a shorthand for @code{pws:\n:}.
@end quotation

@code{r}

@quotation

Reverse subscripting: if this flag is given, the @var{exp} is taken as a
pattern and the result is the first matching array element, substring or
word (if the parameter is an array, if it is a scalar, or if it is a
scalar and the @code{w} flag is given, respectively).  The subscript used
is the number of the matching element, so that pairs of subscripts such as
@code{$foo[(r)??,3]} and @code{$foo[(r)??,(r)f*]} are
possible if the parameter is not an associative array.  If the
parameter is an associative array, only the value part of each pair is
compared to the pattern, and the result is that value.

If a search through an ordinary array failed, the search sets the
subscript to one past the end of the array, and hence
@code{$@{array[(r)}@var{pattern}@code{]@}} will substitute the empty string.  Thus the
success of a search can be tested by using the @code{(i)} flag, for
example (assuming the option @code{KSH_ARRAYS} is not in effect):

@example
 [[ $@{array[(i)pattern]@} -le $@{#array@} ]]
@end example

If @code{KSH_ARRAYS} is in effect, the @code{-le} should be replaced by @code{-lt}.
@end quotation

@code{R}

@quotation

Like @code{r}, but gives the last match.  For associative arrays, gives
all possible matches. May be used for assigning to ordinary array
elements, but not for assigning to associative arrays.  On failure, for
normal arrays this has the effect of returning the element corresponding to
subscript 0; this is empty unless one of the options @code{KSH_ARRAYS} or
@code{KSH_ZERO_SUBSCRIPT} is in effect.

Note that in subscripts with both @code{r} and @code{R} pattern characters
are active even if they were substituted for a parameter (regardless of the
setting of @code{GLOB_SUBST} which controls this feature in normal pattern
matching).  The flag @code{e} can be added to inhibit pattern matching.  As
this flag does not inhibit other forms of substitution, care is still
required; using a parameter to hold the key has the desired effect:

@example
 key2='original key'
 print $@{array[(Re)$key2]@}
@end example
@end quotation

@code{i}

@quotation

Like @code{r}, but gives the index of the match instead; this may not be
combined with a second argument.  On the left side of an assignment,
behaves like @code{r}.  For associative arrays, the key part of each pair
is compared to the pattern, and the first matching key found is the
result.  On failure substitutes the length of the array plus one, as
discussed under the description of @code{r}, or the empty string for an
associative array.

Note: Although @code{i} may be applied to a scalar substitution to find
the offset of a substring, the results are likely to be misleading when
searching within substitutions that yield an empty string, or when
searching for the empty substring.
@end quotation

@code{I}

@quotation

Like @code{i}, but gives the index of the last match, or all possible
matching keys in an associative array.  On failure substitutes 0, or
the empty string for an associative array.  This flag is best when
testing for values or keys that do not exist.

Note: If the option @code{KSH_ARRAYS} is in effect and no match is found, the
result is indistinguishable from the case when the first element of the array
matches.
@end quotation

@code{k}

@quotation

If used in a subscript on an associative array, this flag causes the keys
to be interpreted as patterns, and returns the value for the first key
found where @var{exp} is matched by the key.  Note this could be any
such key as no ordering of associative arrays is defined.
This flag does not work on the left side of an assignment to an associative
array element.  If used on another type of parameter, this behaves like @code{r}.
@end quotation

@code{K}

@quotation

On an associative array this is like @code{k} but returns all values where
@var{exp} is matched by the keys.  On other types of parameters this has
the same effect as @code{R}.
@end quotation

@code{n:}@var{expr}@code{:}

@quotation

If combined with @code{r}, @code{R}, @code{i} or @code{I}, makes them give
the @var{n}th or @var{n}th last match (if @var{expr} evaluates to
@var{n}).  This flag is ignored when the array is associative.
The delimiter character @code{:} is arbitrary; see above.
@end quotation

@code{b:}@var{expr}@code{:}

@quotation

If combined with @code{r}, @code{R}, @code{i} or @code{I}, makes them begin
at the @var{n}th or @var{n}th last element, word, or character (if @var{expr}
evaluates to @var{n}).  This flag is ignored when the array is associative.
The delimiter character @code{:} is arbitrary; see above.
@end quotation

@code{e}

@quotation

This flag causes any pattern matching that would be performed on the
subscript to use plain string matching instead.  Hence
@code{$@{array[(re)*]@}} matches only the array element whose value is @code{*}.
Note that other forms of substitution such as parameter substitution are
not inhibited.

This flag can also be used to force @code{*} or @code{@@} to be interpreted as
a single key rather than as a reference to all values.  It may be used
for either purpose on the left side of an assignment.
@end quotation

See @ref{6e,,Parameter Expansion Flags}
for additional ways to manipulate the results of array subscripting.

@node Subscript Parsing,,Subscript Flags,Array Parameters
@anchor{Zsh/params subscript-parsing}@anchor{8e}
@subsection Subscript Parsing


This discussion applies mainly to associative array key strings and to
patterns used for reverse subscripting (the @code{r}, @code{R}, @code{i},
etc. flags), but it may also affect parameter substitutions that appear
as part of an arithmetic expression in an ordinary subscript.

To avoid subscript parsing limitations in assignments to associative array
elements, use the append syntax:

@example
 aa+=('key with "*strange*" characters' 'value string')
@end example

The basic rule to remember when writing a subscript expression is that all
text between the opening @code{[} and the closing @code{]} is interpreted
`as if' it were in double quotes (see @ref{8f,,Quoting}).
However, unlike double quotes which normally cannot nest, subscript
expressions may appear inside double-quoted strings or inside other
subscript expressions (or both!), so the rules have two important
differences.

The first difference is that brackets (@code{[} and @code{]}) must appear as
balanced pairs in a subscript expression unless they are preceded by a
backslash (@code{\}).  Therefore, within a subscript expression (and unlike
true double-quoting) the sequence @code{\[} becomes @code{[}, and similarly
@code{\]} becomes @code{]}.  This applies even in cases where a backslash is
not normally required; for example, the pattern @code{[^[]} (to match any
character other than an open bracket) should be written @code{[^\[]} in a
reverse-subscript pattern.  However, note that @code{\[^\[\]} and even
@code{\[^[]} mean the `same' thing, because backslashes are always
stripped when they appear before brackets!

The same rule applies to parentheses (@code{(} and @code{)}) and
braces (@code{@{} and @code{@}}): they must appear either in balanced pairs or
preceded by a backslash, and backslashes that protect parentheses or
braces are removed during parsing.  This is because parameter expansions
may be surrounded by balanced braces, and subscript flags are introduced by
balanced parentheses.

The second difference is that a double-quote (@code{"}) may appear as part
of a subscript expression without being preceded by a backslash, and
therefore that the two characters @code{\"} remain as two characters in the
subscript (in true double-quoting, @code{\"} becomes @code{"}).  However,
because of the standard shell quoting rules, any double-quotes that appear
must occur in balanced pairs unless preceded by a backslash.  This makes
it more difficult to write a subscript expression that contains an odd
number of double-quote characters, but the reason for this difference is
so that when a subscript expression appears inside true double-quotes, one
can still write @code{\"} (rather than @code{\\\"}) for @code{"}.

To use an odd number of double quotes as a key in an assignment, use the
@code{typeset} builtin and an enclosing pair of double quotes; to refer to
the value of that key, again use double quotes:

@example
 typeset -A aa
 typeset "aa[one\"two\"three\"quotes]"=QQQ
 print "$aa[one\"two\"three\"quotes]"
@end example

It is important to note that the quoting rules do not change when a
parameter expansion with a subscript is nested inside another subscript
expression.  That is, it is not necessary to use additional backslashes
within the inner subscript expression; they are removed only once, from
the innermost subscript outwards.  Parameters are also expanded from the
innermost subscript first, as each expansion is encountered left to right
in the outer expression.

A further complication arises from a way in which subscript parsing is
`not' different from double quote parsing.  As in true double-quoting,
the sequences @code{\*}, and @code{\@@} remain as two characters when they
appear in a subscript expression.  To use a literal @code{*} or @code{@@} as
an associative array key, the @code{e} flag must be used:

@example
 typeset -A aa
 aa[(e)*]=star
 print $aa[(e)*]
@end example

A last detail must be considered when reverse subscripting is performed.
Parameters appearing in the subscript expression are first expanded and
then the complete expression is interpreted as a pattern.  This has two
effects: first, parameters behave as if @code{GLOB_SUBST} were on (and it
cannot be turned off); second, backslashes are interpreted twice, once
when parsing the array subscript and again when parsing the pattern.  In a
reverse subscript, it’s necessary to use `four' backslashes to cause a
single backslash to match literally in the pattern.  For complex patterns,
it is often easiest to assign the desired pattern to a parameter and then
refer to that parameter in the subscript, because then the backslashes,
brackets, parentheses, etc., are seen only when the complete expression is
converted to a pattern.  To match the value of a parameter literally in a
reverse subscript, rather than as a pattern,
use @code{$@{(q)}@var{name}@code{@}} (@ref{1a,,Parameter Expansion}) to quote the expanded value.

Note that the @code{k} and @code{K} flags are reverse subscripting for an
ordinary array, but are `not' reverse subscripting for an associative
array!  (For an associative array, the keys in the array itself are
interpreted as patterns by those flags; the subscript is a plain string
in that case.)

One final note, not directly related to subscripting: the numeric names
of positional parameters (
.. only:: man

@quotation

described below
@end quotation

Positional Parameters

) are parsed specially, so for example @code{$2foo} is equivalent to
@code{$@{2@}foo}.  Therefore, to use subscript syntax to extract a substring
from a positional parameter, the expansion must be surrounded by braces;
for example, @code{$@{2[3,5]@}} evaluates to the third through fifth
characters of the second positional parameter, but @code{$2[3,5]} is the
entire second parameter concatenated with the filename generation pattern
@code{[3,5]}.

@c historic nodename: Positional Parameters

@geindex positional parameters; Command

@geindex parameters@comma{} positional; Command

@node Positional Parameters,Local Parameters,Array Parameters,Parameters
@anchor{Zsh/params positional-parameters}@anchor{90}
@section Positional Parameters


The positional parameters provide access to the command-line arguments
of a shell function, shell script, or the shell itself; see
@ref{91,,Invocation}, and also @ref{92,,Functions}.
The parameter @var{n}, where @var{n} is a number,
is the @var{n}th positional parameter.
The parameter @code{$0} is a special case, see
@ref{93,,Parameters Set by the Shell}.

The parameters @code{*}, @code{@@} and @code{argv} are
arrays containing all the positional parameters;
thus @code{$argv[}@var{n}@code{]}, etc., is equivalent to simply @code{$}@var{n}.
Note that the options @code{KSH_ARRAYS} or @code{KSH_ZERO_SUBSCRIPT} apply
to these arrays as well, so with either of those options set,
@code{$@{argv[0]@}} is equivalent to @code{$1} and so on.

Positional parameters may be changed after the shell or function starts by
using the @code{set} builtin, by assigning to the @code{argv} array, or by direct
assignment of the form @var{n}@code{=}@var{value} where @var{n} is the number of
the positional parameter to be changed.  This also creates (with empty
values) any of the positions from 1 to @var{n} that do not already have
values.  Note that, because the positional parameters form an array, an
array assignment of the form @var{n}@code{=(}@var{value} …`@w{`})`@w{`} is
allowed, and has the effect of shifting all the values at positions greater
than @var{n} by as many positions as necessary to accommodate the new values.

@c historic nodename: Local Parameters

@geindex local parameters; Command

@geindex parameters@comma{} local; Command

@node Local Parameters,Named References<2>,Positional Parameters,Parameters
@anchor{Zsh/params local-parameters}@anchor{40}
@section Local Parameters


Shell function executions delimit scopes for shell parameters.
(Parameters are dynamically scoped.)  The @code{typeset} builtin, and its
alternative forms @code{declare}, @code{integer}, @code{local} and @code{readonly}
(but not @code{export}), can be used to declare a parameter as being local
to the innermost scope.

When a parameter is read or assigned to, the
innermost existing parameter of that name is used.  (That is, the
local parameter hides any less-local parameter.)  However, assigning
to a non-existent parameter, or declaring a new parameter with @code{export},
causes it to be created in the `outer'most scope.

Local parameters disappear when their scope ends.
@code{unset} can be used to delete a parameter while it is still in scope;
any outer parameter of the same name remains hidden.

Special parameters may also be made local; they retain their special
attributes unless either the existing or the newly-created parameter
has the @code{-h} (hide) attribute.  This may have unexpected effects:
there is no default value, so if there is no assignment at the
point the variable is made local, it will be set to an empty value (or zero
in the case of integers).
The following:

@example
 typeset PATH=/new/directory:$PATH
@end example

is valid for temporarily allowing the shell or programmes called from it to
find the programs in @code{/new/directory} inside a function.

Note that the restriction in older versions of zsh that local parameters
were never exported has been removed.

@c historic nodename: Named References

@geindex named references; Command

@geindex references@comma{} named; Command

@node Named References<2>,Parameters Set by the Shell,Local Parameters,Parameters
@anchor{Zsh/params named-references}@anchor{71}
@section Named References


Zsh supports two different mechanisms for indirect parameter referencing:

@example
 @code{typeset} @var{name}@code{=}@var{rname}
 @code{print -r -- $@{(P)}@var{name}@code{@}}
@end example

@example
 @code{typeset -n} @var{pname}@code{=}@var{rname}
 @code{print -r -- $@{}@var{pname}@code{@}}
@end example

The @code{(P)} flag method is older and should be used when a script
needs to be backwards-compatible.  This is described fully in
@ref{6e,,Parameter Expansion Flags}. Zsh
versions `greater than' @code{5.9.0} are required for @code{typeset -n}.
This manual was generated with Zsh  @code{|release|} .

When a `named reference' is created with @code{typeset -n}, all uses
of @var{pname} in assignments and expansions instead assign to or
expand @var{rname}.  This also applies to @code{unset} @var{pname} and to
most subsequent uses of @code{typeset} with the exceptions of declaring
a local in a called function, or updating a current-scope parameter with
@code{typeset -n} or @code{typeset +n}. Thus to remove a named reference,
use either @code{unset -n} @var{pname} (preferred) or one of:

@example
 @code{typeset -n} @var{pname=}
 @code{typeset +n} @var{pname}
@end example

followed by


@quotation

@code{unset} @var{pname}
@end quotation

An empty reference such as one of

@example
 @code{typeset -n} @var{pname}
 @code{typeset -n} @var{pname}@code{=}
@end example

acts as a placeholder.  The first non-empty assignment to @var{pname}
initializes the reference, and subsequently any expansions of, or
assignments to, @var{pname} act on the referenced parameter.  This
is explained in @ref{70,,Named References}.

A placeholder @var{pname} in a calling function may be initialized in a
called function to reference a local parameter @var{rname}.  In this
case, when the called function returns, @var{pname} is no longer
associated with that local.  However, the initializer @var{rname}
continues to be substituted when @code{$}@var{pname} is used, and
therefore may become a reference to another parameter in the calling
function.  It is recommended that placeholders be initialized soon
after they are declared, to make it clear what they reference.

@c historic nodename: Parameters Set by the Shell

@node Parameters Set by the Shell,Parameters Used by the Shell,Named References<2>,Parameters
@anchor{Zsh/params parameters-set-by-the-shell}@anchor{93}
@section Parameters Set by the Shell


In the parameter lists that follow, the mark `<S>’ indicates that the
parameter is special.  `<Z>’ indicates that the parameter does not exist
when the shell initializes in @code{sh} or @code{ksh} emulation mode.

The parameters @code{!}, @code{#}, @code{*}, @code{-}, @code{?}, @code{@@},
@code{$}, @code{ARGC}, @code{HISTCMD}, @code{LINENO}, @code{PPID},
@code{status}, @code{TTYIDLE}, @code{zsh_eval_context},
@code{ZSH_EVAL_CONTEXT}, and @code{ZSH_SUBSHELL} are read-only and thus
cannot be restored by the user, so they are not output by
@code{typeset -p}.  This also applies to many read-only parameters loaded
from modules.

The following parameters are automatically set by the shell:

@geindex !; Variable

@code{!} <S>

@quotation

The process ID of the last command started in the background with @code{&},
put into the background with the @code{bg} builtin, or spawned with @code{coproc}.
@end quotation

@geindex #; Variable

@code{#} <S>

@quotation

The number of positional parameters in decimal.  Note that some confusion
may occur with the syntax @code{$#}@var{param} which substitutes the length of
@var{param}.  Use @code{$@{#@}} to resolve ambiguities.  In particular, the
sequence @code{$#-}@var{…} in an arithmetic expression is interpreted as
the length of the parameter @code{-}, q.v.
@end quotation

@geindex ARGC; Variable

@code{ARGC} <S> <Z>

@quotation

Same as @code{#}.
@end quotation

@geindex $; Variable

@code{$} <S>

@quotation

The process ID of this shell, set when the shell initializes.  Processes
forked from the shell without executing a new program, such as command
substitutions and commands grouped with @code{(}@var{…}@code{)},
are subshells that duplicate the current shell, and thus substitute the
same value for @code{$$} as their parent shell.
@end quotation

@geindex -; Variable

@code{-} <S>

@quotation

Flags supplied to the shell on invocation or by the @code{set}
or @code{setopt} commands.
@end quotation

@geindex *; Variable

@code{*} <S>

@quotation

An array containing the positional parameters.
@end quotation

@geindex argv; Variable

@code{argv} <S> <Z>

@quotation

Same as @code{*}.  Assigning to @code{argv} changes the local positional
parameters, but @code{argv} is `not' itself a local parameter.
Deleting @code{argv} with @code{unset} in any function deletes it everywhere.
This can be avoided by declaring @code{local +h argv} before unsetting.
Even when not so declared, only the innermost positional parameter
array is deleted (so @code{*} and @code{@@} in other scopes are not affected).

A named reference to @code{argv} `does not' permit a called function to
access the positional parameters of its caller.
@end quotation

@geindex @@; Variable

@code{@@} <S>

@quotation

Same as @code{argv[@@]}, even when @code{argv} is not set.
@end quotation

@geindex ?; Variable

@code{?} <S>

@quotation

The exit status returned by the last command.
@end quotation

@geindex 0; Variable

@code{0} <S>

@quotation

The name used to invoke the current shell, or as set by the @code{-c} command
line option upon invocation.  If the @code{FUNCTION_ARGZERO} option is set,
@code{$0} is set upon entry to a shell function to the name of the function,
and upon entry to a sourced script to the name of the script, and reset to
its previous value when the function or script returns.
@end quotation

@geindex status; Variable

@code{status} <S> <Z>

@quotation

Same as @code{?}.
@end quotation

@geindex pipestatus; Variable

@code{pipestatus} <S> <Z>

@quotation

An array containing the exit statuses returned by all commands in the
last pipeline.
@end quotation

@geindex _; Variable

@code{_} <S>

@quotation

Initially, if @code{_} exists in the environment, then this parameter is set to
its value. This value may be the full pathname of the current zsh
executable or the script command file.
Later, this parameter is set to the last argument of the previous command.
Also, this parameter is set in the environment of every command
executed to the full pathname of the command.
@end quotation

@geindex CPUTYPE; Variable

@code{CPUTYPE}

@quotation

The machine type (microprocessor class or machine model),
as determined at run time.
@end quotation

@geindex EGID; Variable

@code{EGID} <S>

@quotation

The effective group ID of the shell process.  If you have sufficient
privileges, you may change the effective group ID of the shell
process by assigning to this parameter.  Also (assuming sufficient
privileges), you may start a single command with a different
effective group ID by @code{(EGID=}@var{gid}@code{; command)}

If this is made local, it is not implicitly set to 0, but may be
explicitly set locally.
@end quotation

@geindex EUID; Variable

@code{EUID} <S>

@quotation

The effective user ID of the shell process.  If you have sufficient
privileges, you may change the effective user ID of the shell process
by assigning to this parameter.  Also (assuming sufficient privileges),
you may start a single command with a different
effective user ID by @code{(EUID=}@var{uid}@code{; command)}

If this is made local, it is not implicitly set to 0, but may be
explicitly set locally.
@end quotation

@geindex ERRNO; Variable

@code{ERRNO} <S>

@quotation

The value of @code{errno} (see @code{errno(3)})
as set by the most recently failed system call.
This value is system dependent and is intended for debugging
purposes.  It is also useful with the @code{zsh/system} module which
allows the number to be turned into a name or message.

To use this parameter, it must first be assigned a value (typically
0 (zero)).  It is initially unset for scripting compatibility.
@end quotation

@geindex FUNCNEST; Variable

@code{FUNCNEST} <S>

@quotation

Integer.  If greater than or equal to zero, the maximum nesting depth of
shell functions.  When it is exceeded, an error is raised at the point
where a function is called.  The default value is determined when
the shell is configured, but is typically 500.  Increasing
the value increases the danger of a runaway function recursion
causing the shell to crash.  Setting a negative value turns off
the check.
@end quotation

@geindex GID; Variable

@code{GID} <S>

@quotation

The real group ID of the shell process.  If you have sufficient privileges,
you may change the group ID of the shell process by assigning to this
parameter.  Also (assuming sufficient privileges), you may start a single
command under a different
group ID by @code{(GID=}@var{gid}@code{; command)}

If this is made local, it is not implicitly set to 0, but may be
explicitly set locally.
@end quotation

@geindex HISTCMD; Variable

@code{HISTCMD}

@quotation

The current history event number in an interactive shell, in other
words the event number for the command that caused @code{$HISTCMD}
to be read.  If the current history event modifies the history,
@code{HISTCMD} changes to the new maximum history event number.
@end quotation

@geindex HOST; Variable

@code{HOST}

@quotation

The current hostname.
@end quotation

@geindex LINENO; Variable

@code{LINENO} <S>

@quotation

The line number of the current line within the current script, sourced
file, or shell function being executed, whichever was started most
recently.  Note that in the case of shell functions the line
number refers to the function as it appeared in the original definition,
not necessarily as displayed by the @code{functions} builtin.
@end quotation

@geindex LOGNAME; Variable

@code{LOGNAME}

@quotation

If the corresponding variable is not set in the environment of the
shell, it is initialized to the login name corresponding to the
current login session. This parameter is exported by default but
this can be disabled using the @code{typeset} builtin.  The value
is set to the string returned by the @code{getlogin(3)} system call
if that is available.
@end quotation

@geindex MACHTYPE; Variable

@code{MACHTYPE}

@quotation

The machine type (microprocessor class or machine model),
as determined at compile time.
@end quotation

@geindex OLDPWD; Variable

@code{OLDPWD}

@quotation

The previous working directory.  This is set when the shell initializes
and whenever the directory changes.
@end quotation

@geindex OPTARG; Variable

@code{OPTARG} <S>

@quotation

The value of the last option argument processed by the @code{getopts}
command.
@end quotation

@geindex OPTIND; Variable

@code{OPTIND} <S>

@quotation

The index of the last option argument processed by the @code{getopts}
command.
@end quotation

@geindex OSTYPE; Variable

@code{OSTYPE}

@quotation

The operating system, as determined at compile time.
@end quotation

@geindex PPID; Variable

@code{PPID} <S>

@quotation

The process ID of the parent of the shell, set when the shell initializes.
As with @code{$$}, the value does not change in subshells created as a
duplicate of the current shell.
@end quotation

@geindex PWD; Variable

@code{PWD}

@quotation

The present working directory.  This is set when the shell initializes
and whenever the directory changes.
@end quotation

@geindex RANDOM; Variable

@code{RANDOM} <S>

@quotation

A pseudo-random integer from 0 to 32767, newly generated each time
this parameter is referenced.  The random number generator
can be seeded by assigning a numeric value to @code{RANDOM}.

The values of @code{RANDOM} form an intentionally-repeatable pseudo-random
sequence; subshells that reference @code{RANDOM} will result
in identical pseudo-random values unless the value of @code{RANDOM} is
referenced or seeded in the parent shell in between subshell invocations.

@code{RANDOM} uses the system’s library function @code{rand(3)}.
If higher degree of randomness is required, please consider using
the autoloadable parameter @code{SRANDOM} from


@ref{94,,The zsh/random Module}

.
@end quotation

@geindex SECONDS; Variable

@code{SECONDS} <S>

@quotation

The number of seconds since shell invocation.  On most platforms, this
is a monotonic value, so it is not affected by NTP time jumps or other
clock changes (though it may be affected by slewing).  If this parameter
is assigned a value, then the value returned upon reference
will be the value that was assigned plus the number of seconds
since the assignment.

Unlike other special parameters, the type of the @code{SECONDS} parameter can
be changed using the @code{typeset} command.  The type may be changed only
to one of the floating point types or back to integer.  For example,
@code{typeset -F SECONDS}
causes the value to be reported as a floating point number.  The
value is nominally available to nanosecond precision, although this
varies by platform (and probably isn’t accurate to 1 ns regardless),
and the shell may show more or fewer digits depending on the
use of @code{typeset}.  See
the documentation for the builtin @code{typeset} in
@code{zshbuiltins} for more details.
@end quotation

@geindex SHLVL; Variable

@code{SHLVL} <S>

@quotation

Incremented by one each time a new shell is started.
@end quotation

@geindex signals; Variable

@code{signals}

@quotation

An array containing the names of the signals.  Note that with
the standard zsh numbering of array indices, where the first element
has index 1, the signals are offset by 1 from the signal number
used by the operating system.  For example, on typical Unix-like systems
@code{HUP} is signal number 1, but is referred to as @code{$signals[2]}.  This
is because of @code{EXIT} at position 1 in the array, which is used
internally by zsh but is not known to the operating system. On many systems
there is a block of reserved or unused signal numbers before the POSIX
real-time signals so the array index can’t be used as an accurate indicator
of their signal number. Use, for example, @code{kill -l SIGRTMIN} instead.
@end quotation

@geindex .term.cursor; Variable

@code{.term.cursor}

@quotation

The default color of the cursor.

See also the @code{.term.extensions} parameter.
@end quotation

@geindex .term.bg; Variable

@code{.term.bg}

@quotation

The background color of the terminal if the terminal supports the
necessary interface for retrieving this information.

See also the @code{.term.extensions} parameter.
@end quotation

@geindex .term.fg; Variable

@code{.term.fg}

@quotation

Like @code{.term.bg} but for the foreground color.
@end quotation

@geindex .term.id; Variable

@code{.term.id}

@quotation

Like the @code{TERM} parameter, this identifies the terminal but is obtained by
querying the terminal.  Many terminals name a different common terminal in
@code{TERM} that they then emulate, often imperfectly.  This allows them to work
without the need to distribute updates to terminal capability databases.  The
more accurate identification in this parameter may be useful when configuring
aspects of the shell differently for specific terminals.

See also the @code{.term.extensions} parameter.
@end quotation

@geindex .term.version; Variable

@code{.term.version}

@quotation

The version number of the terminal application, set in conjunction with
@code{.term.id}.
@end quotation

@geindex .term.mode; Variable

@code{.term.mode}

@quotation

Either @code{light} or @code{dark}.  In cases where the terminal background color is
detected and set in @code{.term.bg}, this is set to provide a basic indication of
how light that color is.  This may help with configuring readable color
combinations.
@end quotation

@geindex TRY_BLOCK_ERROR; Variable

@code{TRY_BLOCK_ERROR} <S>

@quotation

In an @code{always} block, indicates whether the preceding list of code
caused an error.  The value is 1 to indicate an error, 0 otherwise.
It may be reset, clearing the error condition.  See
@ref{95,,Complex Commands}
@end quotation

@geindex TRY_BLOCK_INTERRUPT; Variable

@code{TRY_BLOCK_INTERRUPT} <S>

@quotation

This variable works in a similar way to @code{TRY_BLOCK_ERROR}, but
represents the status of an interrupt from the signal SIGINT, which
typically comes from the keyboard when the user types @code{^C}.  If set to
0, any such interrupt will be reset; otherwise, the interrupt is
propagated after the @code{always} block.

Note that it is possible that an interrupt arrives during the execution
of the @code{always} block; this interrupt is also propagated.
@end quotation

@geindex TTY; Variable

@code{TTY}

@quotation

The name of the tty associated with the shell, if any.
@end quotation

@geindex TTYIDLE; Variable

@code{TTYIDLE} <S>

@quotation

The idle time of the tty associated with the shell in seconds or -1 if there
is no such tty.
@end quotation

@geindex UID; Variable

@code{UID} <S>

@quotation

The real user ID of the shell process.  If you have sufficient privileges,
you may change the user ID of the shell by assigning to this parameter.
Also (assuming sufficient privileges), you may start a single command
under a different
user ID by @code{(UID=}@var{uid}@code{; command)}

If this is made local, it is not implicitly set to 0, but may be
explicitly set locally.
@end quotation

@geindex USERNAME; Variable

@code{USERNAME} <S>

@quotation

The username corresponding to the real user ID of the shell process.  If you
have sufficient privileges, you may change the username (and also the
user ID and group ID) of the shell by assigning to this parameter.
Also (assuming sufficient privileges), you may start a single command
under a different username (and user ID and group ID)
by @code{(USERNAME=}@var{username}@code{; command)}
@end quotation

@geindex VENDOR; Variable

@code{VENDOR}

@quotation

The vendor, as determined at compile time.
@end quotation

@geindex zsh_eval_context; Variable

@geindex ZSH_EVAL_CONTEXT; Variable

@code{zsh_eval_context} <S> <Z> (@code{ZSH_EVAL_CONTEXT} <S>)

@quotation

An array (colon-separated list) indicating the context of shell
code that is being run.  Each time a piece of shell code that
is stored within the shell is executed a string is temporarily appended to
the array to indicate the type of operation that is being performed.
Read in order the array gives an indication of the stack of
operations being performed with the most immediate context last.

Note that the variable does not give information on syntactic context such
as pipelines or subshells.  Use @code{$ZSH_SUBSHELL} to detect subshells.

The context is one of the following:

@code{cmdarg}

@quotation

Code specified by the @code{-c} option to the command line that invoked
the shell.
@end quotation

@code{cmdsubst}

@quotation

Command substitution using the >>`@w{`}<<@code{\`:var:`...`\ `@w{`}},
@code{$(}@var{…}@code{)}, @code{$@{@{}@var{name}@code{@}} @var{…}@code{@}},
@code{$@{|}@var{…}@code{@}}, or @code{$@{} @var{…} @code{@}} constructs.
@end quotation

@code{equalsubst}

@quotation

The @code{=(}@var{…}@code{)} form of process substitution.
@end quotation

@code{eval}

@quotation

Code executed by the @code{eval} builtin.
@end quotation

@code{evalautofunc}

@quotation

Code executed with the @code{KSH_AUTOLOAD} mechanism in order to define
an autoloaded function.
@end quotation

@code{fc}

@quotation

Code from the shell history executed by the @code{-e} option to the @code{fc}
builtin.
@end quotation

@code{file}

@quotation

Lines of code being read directly from a file, for example by
the @code{source} builtin.
@end quotation

@code{filecode}

@quotation

Lines of code being read from a @code{.zwc} file instead of directly
from the source file.
@end quotation

@code{globqual}

@quotation

Code executed by the @code{e} or @code{+} glob qualifier.
@end quotation

@code{globsort}

@quotation

Code executed to order files by the @code{o} glob qualifier.
@end quotation

@code{insubst}

@quotation

The @code{>(}@var{…}@code{)} form of process substitution.
@end quotation

@code{loadautofunc}

@quotation

Code read directly from a file to define an autoloaded function.
@end quotation

@code{math}

@quotation

Code executed in the @code{$((}@var{…}@code{))} or
@code{((}@var{…}@code{))} constructs,
by the @code{let} builtin, in an array subscript, or in
another arithmetic context.
@end quotation

@code{outsubst}

@quotation

The @code{<(}@var{…}@code{)} form of process substitution.
@end quotation

@code{sched}

@quotation

Code executed by the @code{sched} builtin.
@end quotation

@code{shfunc}

@quotation

A shell function.
@end quotation

@code{stty}

@quotation

Code passed to @code{stty} by the @code{STTY} environment variable.
Normally this is passed directly to the systems @code{stty} command,
so this value is unlikely to be seen in practice.
@end quotation

@code{style}

@quotation

Code executed as part of a style retrieved by the @code{zstyle} builtin
from the @code{zsh/zutil} module.
@end quotation

@code{toplevel}

@quotation

The highest execution level of a script or interactive shell.
@end quotation

@code{trap}

@quotation

Code executed as a trap defined by the @code{trap} builtin.  Traps
defined as functions have the context @code{shfunc}.  As traps are
asynchronous they may have a different hierarchy from other
code.
@end quotation

@code{zpty}

@quotation

Code executed by the @code{zpty} builtin from the @code{zsh/zpty} module.
@end quotation

@code{zregexparse-guard}

@quotation

Code executed as a guard by the @code{zregexparse} command from the
@code{zsh/zutil} module.
@end quotation

@code{zregexparse-action}

@quotation

Code executed as an action by the @code{zregexparse} command from the
@code{zsh/zutil} module.
@end quotation
@end quotation

@geindex ZSH_ARGZERO; Variable

@code{ZSH_ARGZERO}

@quotation

If zsh was invoked to run a script, this is the name of the script.
Otherwise, it is the name used to invoke the current shell.  This is
the same as the value of @code{$0} when the @code{POSIX_ARGZERO} option is
set, but is always available.
@end quotation

@geindex ZSH_EXECUTION_STRING; Variable

@code{ZSH_EXECUTION_STRING}

@quotation

If the shell was started with the option @code{-c}, this contains
the argument passed to the option.  Otherwise it is not set.
@end quotation

@geindex ZSH_EXEPATH; Variable

@code{ZSH_EXEPATH}

@quotation

Full pathname of the executable file of the current zsh process.
This value should be accurate on Linux, macOS, FreeBSD, DragonflyBSD,
NetBSD, Solaris, Cygwin, and their derivatives.  On other systems, it is
determined from @code{argv[0]}, which is not always accurate.
@end quotation

@geindex ZSH_NAME; Variable

@code{ZSH_NAME}

@quotation

Expands to the basename of the command used to invoke this instance
of zsh.
@end quotation

@geindex ZSH_PATCHLEVEL; Variable

@code{ZSH_PATCHLEVEL}

@quotation

The output of @code{git describe --tags --long} for the zsh repository
used to build the shell.  This is most useful in order to keep
track of versions of the shell during development between releases;
hence most users should not use it and should instead rely on
@code{$ZSH_VERSION}.
@end quotation

@code{zsh_scheduled_events}

@quotation

See @ref{96,,The zsh/sched Module}.
@end quotation

@geindex ZSH_SCRIPT; Variable

@code{ZSH_SCRIPT}

@quotation

If zsh was invoked to run a script, this is the name of the script,
otherwise it is unset.
@end quotation

@geindex ZSH_SUBSHELL <S>; Variable

@code{ZSH_SUBSHELL}

@quotation

Readonly integer.  Initially zero, incremented each time the shell forks
to create a subshell for executing code.  Hence @code{(print $ZSH_SUBSHELL)}
and @code{print $(print $ZSH_SUBSHELL)} output 1, while
@code{( (print $ZSH_SUBSHELL) )} outputs 2.
@end quotation

@geindex ZSH_VERSION; Variable

@code{ZSH_VERSION}

@quotation

The version number of the release of zsh.
@end quotation

@c historic nodename: Parameters Used by the Shell

@node Parameters Used by the Shell,,Parameters Set by the Shell,Parameters
@anchor{Zsh/params parameters-used-by-the-shell}@anchor{11}
@section Parameters Used by the Shell


The following parameters are used by the shell.  Again, `<S>’ indicates
that the parameter is special and `<Z>’ indicates that the parameter does
not exist when the shell initializes in @code{sh} or @code{ksh} emulation mode.

In cases where there are two parameters with an upper- and lowercase
form of the same name, such as @code{path} and @code{PATH}, the lowercase form
is an array and the uppercase form is a scalar with the elements of the
array joined together by colons.  These are similar to tied parameters
created via @code{typeset -T}.  The normal use for the colon-separated
form is for exporting to the environment, while the array form is easier
to manipulate within the shell.  Note that unsetting either of the pair
will unset the other; they retain their special properties when
recreated, and recreating one of the pair will recreate the other.

@geindex ARGV0; Variable

@code{ARGV0}

@quotation

If exported, its value is used as the @code{argv[0]} of external commands.
Usually used in constructs like @code{ARGV0=emacs nethack}.
@end quotation

@geindex editing over slow connection; Command

@geindex slow connection@comma{} editing over; Command

@geindex BAUD; Variable

@code{BAUD}

@quotation

The rate in bits per second at which data reaches the terminal.
The line editor will use this value in order to compensate for a slow
terminal by delaying updates to the display until necessary.  If the
parameter is unset or the value is zero the compensation mechanism is
turned off.  The parameter is not set by default.

This parameter may be profitably set in some circumstances, e.g.
for slow modems dialing into a communications server, or on a slow wide
area network.  It should be set to the baud
rate of the slowest part of the link for best performance.
@end quotation

@geindex cdpath; Variable

@geindex CDPATH; Variable

@code{cdpath} <S> <Z> (@code{CDPATH} <S>)

@quotation

An array (colon-separated list)
of directories specifying the search path for the @code{cd} command.
@end quotation

@geindex COLUMNS; Variable

@code{COLUMNS} <S>

@quotation

The number of columns for this terminal session.
Used for printing select lists and for the line editor.
If the shell is non-interactive and a legal value is imported from the
environment, it is preserved.  Otherwise, the value is reset on start-up
and in response to certain events such as the receipt of a @code{SIGWINCH}
signal.  Explicitly setting it to an illegal value such as @code{0} also
resets it.  (Unsetting the parameter does not have this effect; it
simply `hides’ the value that the shell is tracking internally.)
@end quotation

@geindex CORRECT_IGNORE; Variable

@code{CORRECT_IGNORE}

@quotation

If set, is treated as a pattern during spelling correction.  Any
potential correction that matches the pattern is ignored.  For example,
if the value is @code{_*} then completion functions (which, by
convention, have names beginning with @code{_}) will never be offered
as spelling corrections.  The pattern does not apply to the correction
of file names, as applied by the @code{CORRECT_ALL} option (so with the
example just given files beginning with @code{_} in the current
directory would still be completed).
@end quotation

@geindex CORRECT_IGNORE_FILE; Variable

@code{CORRECT_IGNORE_FILE}

@quotation

If set, is treated as a pattern during spelling correction of file names.
Any file name that matches the pattern is never offered as a correction.
For example, if the value is @code{.*} then dot file names will never be
offered as spelling corrections.  This is useful with the
@code{CORRECT_ALL} option.
@end quotation

@geindex DIRSTACKSIZE; Variable

@code{DIRSTACKSIZE}

@quotation

The maximum size of the directory stack, by default there is no limit.  If the
stack gets larger than this, it will be truncated automatically.
This is useful with the @code{AUTO_PUSHD} option.
.. index:: single: AUTO_PUSHD, use of; Program
@end quotation

@geindex ENV; Variable

@code{ENV}

@quotation

If the @code{ENV} environment variable is set when zsh is invoked as @code{sh}
or @code{ksh}, @code{$ENV} is sourced after the profile scripts.  The value of
@code{ENV} is subjected to parameter expansion, command substitution, and
arithmetic expansion before being interpreted as a pathname.  Note that
@code{ENV} is `not' used unless the shell is interactive and zsh is
emulating `sh' or `ksh'.
@end quotation

@geindex FCEDIT; Variable

@code{FCEDIT}

@quotation

The default editor for the @code{fc} builtin.  If @code{FCEDIT} is not set,
the parameter @code{EDITOR} is used; if that is not set either, a builtin
default, usually @code{vi}, is used.
@end quotation

@geindex fignore; Variable

@geindex FIGNORE; Variable

@code{fignore} <S> <Z> (@code{FIGNORE} <S>)

@quotation

An array (colon separated list)
containing the suffixes of files to be ignored
during filename completion.  However, if completion only generates files
with suffixes in this list, then these files are completed anyway.
@end quotation

@geindex fpath; Variable

@geindex FPATH; Variable

@code{fpath} <S> <Z> (@code{FPATH} <S>)

@quotation

An array (colon separated list)
of directories specifying the search path for
function definitions.  This path is searched when a function
with the @code{-u} attribute is referenced.  If an executable
file is found, then it is read and executed in the current environment.
@end quotation

@geindex histchars; Variable

@code{histchars} <S>

@quotation

Three characters used by the shell’s history and lexical analysis
mechanism.  The first character signals the start of a history
expansion (default @code{!}).  The second character signals the
start of a quick history substitution (default @code{^}).  The third
character is the comment character (default @code{#}).

The characters must be in the ASCII character set; any attempt to set
@code{histchars} to characters with a locale-dependent meaning will be
rejected with an error message.
@end quotation

@geindex HISTCHARS; Variable

@code{HISTCHARS} <S> <Z>

@quotation

Same as @code{histchars}.  (Deprecated.)
@end quotation

@geindex HISTFILE; Variable

@code{HISTFILE}

@quotation

The file to save the history in when an interactive shell exits.
If unset, the history is not saved.
@end quotation

@geindex HISTORY_IGNORE; Variable

@code{HISTORY_IGNORE}

@quotation

If set, is treated as a pattern at the time history files are written.
Any potential history entry that matches the pattern is skipped.  For
example, if the value is @code{fc *} then commands that invoke the
interactive history editor are never written to the history file.

Note that @code{HISTORY_IGNORE} defines a single pattern: to
specify alternatives use the
@code{(}@var{first}@code{|}@var{second}@code{|}@var{…}@code{)} syntax.

Compare the @code{HIST_NO_STORE} option or the @code{zshaddhistory} hook,
either of which would prevent such commands from being added to the
interactive history at all.  If you wish to use @code{HISTORY_IGNORE} to
stop history being added in the first place, you can define the
following hook:

@example
 zshaddhistory() @{
   emulate -L zsh
   ## uncomment if HISTORY_IGNORE
   ## should use EXTENDED_GLOB syntax
   # setopt extendedglob
   [[ $1 != $@{~HISTORY_IGNORE@} ]]
 @}
@end example
@end quotation

@geindex HISTSIZE; Variable

@code{HISTSIZE} <S>

@quotation

The maximum number of events stored in the internal history list.
If you use the @code{HIST_EXPIRE_DUPS_FIRST} option, setting this value
larger than the @code{SAVEHIST} size will give you the difference as a
cushion for saving duplicated history events.

If this is made local, it is not implicitly set to 0, but may be
explicitly set locally.
@end quotation

@geindex HOME; Variable

@code{HOME} <S>

@quotation

The default argument for the @code{cd} command.  This is not set automatically
by the shell in @code{sh}, @code{ksh} or @code{csh} emulation, but it is typically
present in the environment anyway, and if it becomes set it has its usual
special behaviour.
@end quotation

@geindex IFS; Variable

@code{IFS} <S>

@quotation

Internal field separators (by default space, tab, newline and NUL), that
are used to separate words which result from
command or parameter expansion and words read by
the @code{read} builtin.  Any characters from the set space, tab and
newline that appear in the @code{IFS} are called `IFS white space'.
One or more IFS white space characters or one non-IFS white space
character together with any adjacent IFS white space character delimit
a field.  If an IFS white space character appears twice consecutively
in the @code{IFS}, this character is treated as if it were not an IFS white
space character.

If the parameter is unset, the default is used.  Note this has
a different effect from setting the parameter to an empty string.

If @code{MULTIBYTE} option is on and @code{IFS} contains invalid characters in
the current locale, it is reset to the default.
@end quotation

@geindex KEYBOARD_HACK; Variable

@code{KEYBOARD_HACK}

@quotation

This variable defines a character to be removed from the end of the
command line before interpreting it (interactive shells only). It is
intended to fix the problem with keys placed annoyingly close to return
and replaces the @code{SUNKEYBOARDHACK} option which did this for
backquotes only.  Should the chosen character be one of singlequote,
doublequote or backquote, there must also be an odd number of them
on the command line for the last one to be removed.

For backward compatibility, if the @code{SUNKEYBOARDHACK} option is
explicitly set, the value of @code{KEYBOARD_HACK} reverts to backquote.
If the option is explicitly unset, this variable is set to empty.
@end quotation

@geindex KEYTIMEOUT; Variable

@code{KEYTIMEOUT}

@quotation

The time the shell waits, in hundredths of seconds, for another key to
be pressed when reading bound multi-character sequences.
@end quotation

@geindex LANG; Variable

@code{LANG} <S>

@quotation

This variable determines the locale category for any category not
specifically selected via a variable starting with @code{LC_}.
@end quotation

@geindex LC_ALL; Variable

@code{LC_ALL} <S>

@quotation

This variable overrides the value of the @code{LANG} variable and the value
of any of the other variables starting with @code{LC_}.
@end quotation

@geindex LC_COLLATE; Variable

@code{LC_COLLATE} <S>

@quotation

This variable determines the locale category for character collation
information within ranges in glob brackets and for sorting.
@end quotation

@geindex LC_CTYPE; Variable

@code{LC_CTYPE} <S>

@quotation

This variable determines the locale category for character handling
functions.  If the @code{MULTIBYTE} option is in effect this variable or
@code{LANG} should contain a value that reflects the character set in
use, even if it is a single-byte character set, unless only the
7-bit subset (ASCII) is used.  For example, if the character set
is ISO-8859-1, a suitable value might be @code{en_US.iso88591} (certain
Linux distributions) or @code{en_US.ISO8859-1} (MacOS).
@end quotation

@geindex LC_MESSAGES; Variable

@code{LC_MESSAGES} <S>

@quotation

This variable determines the language in which messages should be
written.  Note that zsh does not use message catalogs.
@end quotation

@geindex LC_NUMERIC; Variable

@code{LC_NUMERIC} <S>

@quotation

This variable affects the decimal point character and thousands
separator character for the formatted input/output functions
and string conversion functions.  Note that zsh ignores this
setting when parsing floating point mathematical expressions.
@end quotation

@geindex LC_TIME; Variable

@code{LC_TIME} <S>

@quotation

This variable determines the locale category for date and time
formatting in prompt escape sequences.
@end quotation

@geindex LINES; Variable

@code{LINES} <S>

@quotation

The number of lines for this terminal session.
Used for printing select lists and for the line editor.
See @code{COLUMNS}.
@end quotation

@geindex LISTMAX; Variable

@code{LISTMAX}

@quotation

In the line editor, the number of matches to list without asking
first. If the value is negative, the list will be shown if it spans at
most as many lines as given by the absolute value.
If set to zero, the shell asks only if the top of the listing would scroll
off the screen.
@end quotation

@geindex MAIL; Variable

@code{MAIL}

@quotation

If this parameter is set and @code{mailpath} is not set,
the shell looks for mail in the specified file.
@end quotation

@geindex MAILCHECK; Variable

@code{MAILCHECK}

@quotation

The interval in seconds between checks for new mail.
@end quotation

@geindex mailpath; Variable

@geindex MAILPATH; Variable

@code{mailpath} <S> <Z> (@code{MAILPATH} <S>)

@quotation

An array (colon-separated list) of filenames to check for
new mail.  Each filename can be followed by a @code{?} and a
message that will be printed.  The message will undergo
parameter expansion, command substitution and arithmetic
expansion with the variable @code{$_} defined as the name
of the file that has changed.  The default message is
@code{You have new mail}.  If an element is a directory
instead of a file the shell will recursively check every
file in every subdirectory of the element.
@end quotation

@geindex manpath; Variable

@geindex MANPATH; Variable

@code{manpath} <S> <Z> (@code{MANPATH} <S> <Z>)

@quotation

An array (colon-separated list)
whose value is not used by the shell.  The @code{manpath}
array can be useful, however, since setting it also sets
@code{MANPATH}, and vice versa.
@end quotation

@code{match}

@code{mbegin}

@code{mend}

@quotation

Arrays set by the shell when the @code{b} globbing flag is used in pattern
matches.  See @ref{80,,Globbing Flags}.
@end quotation

@code{MATCH}

@code{MBEGIN}

@code{MEND}

@quotation

Set by the shell when the @code{m} globbing flag is used in pattern
matches.  See @ref{80,,Globbing Flags}.
@end quotation

@geindex module_path; Variable

@geindex MODULE_PATH; Variable

@code{module_path} <S> <Z> (@code{MODULE_PATH} <S>)

@quotation

An array (colon-separated list)
of directories that @code{zmodload}
searches for dynamically loadable modules.
This is initialized to a standard pathname,
usually @code{/usr/local/lib/zsh/$ZSH_VERSION}.
(The @code{/usr/local/lib} part varies from installation to installation.)
For security reasons, any value set in the environment when the shell
is started will be ignored.

These parameters only exist if the installation supports dynamic
module loading.
@end quotation

@geindex NULLCMD; Variable

@geindex null command style; Command

@geindex csh@comma{} null command style; Command

@geindex ksh@comma{} null command style; Command

@code{NULLCMD} <S>

@quotation

The command name to assume if a redirection is specified
with no command.  Defaults to @code{cat}.  For `sh'/`ksh'
behavior, change this to @code{:}.  For `csh'-like
behavior, unset this parameter; the shell will print an
error message if null commands are entered.
@end quotation

@geindex path; Variable

@geindex PATH; Variable

@code{path} <S> <Z> (@code{PATH} <S>)

@quotation

An array (colon-separated list)
of directories to search for commands.
When this parameter is set, each directory is scanned
and all files found are put in a hash table.
Directories named by relative path are not scanned for hashing.
@end quotation

@geindex POSTEDIT; Variable

@code{POSTEDIT} <S>

@quotation

This string is output whenever the line editor exits.
It usually contains termcap strings to reset the terminal.
@end quotation

@geindex PROMPT; Variable

@code{PROMPT} <S> <Z>

@geindex PROMPT2; Variable

@code{PROMPT2} <S> <Z>

@geindex PROMPT3; Variable

@code{PROMPT3} <S> <Z>

@geindex PROMPT4; Variable

@code{PROMPT4} <S> <Z>

@quotation

Same as @code{PS1}, @code{PS2}, @code{PS3} and @code{PS4},
respectively.
@end quotation

@geindex prompt; Variable

@code{prompt} <S> <Z>

@quotation

Same as @code{PS1}.
@end quotation

@geindex PROMPT_EOL_MARK; Variable

@code{PROMPT_EOL_MARK}

@quotation

When the @code{PROMPT_CR} and @code{PROMPT_SP} options are set, the
@code{PROMPT_EOL_MARK} parameter can be used to customize how the end of
partial lines are shown.  This parameter undergoes prompt expansion, with
the @code{PROMPT_PERCENT} option set.  If not set, the default behavior is
equivalent to the value @code{%B%S%#%s%b}.
@end quotation

@geindex PS1; Variable

@code{PS1} <S>

@quotation

The primary prompt string, printed before a command is read.
It undergoes a special form of expansion
before being displayed; see @ref{97,,Expansion of Prompt Sequences}.
The default is @code{%m%#} .
@end quotation

@geindex PS2; Variable

@code{PS2} <S>

@quotation

The secondary prompt, printed when the shell needs more information
to complete a command.
It is expanded in the same way as @code{PS1}.
The default is @code{%_>} , which displays any shell constructs or quotation
marks which are currently being processed.
@end quotation

@geindex PS3; Variable

@code{PS3} <S>

@quotation

Selection prompt used within a @code{select} loop.
It is expanded in the same way as @code{PS1}.
The default is @code{?#} .
@end quotation

@geindex PS4; Variable

@code{PS4} <S>

@quotation

The execution trace prompt.  Default is @code{+%N:%i>} , which displays
the name of the current shell structure and the line number within it.
In sh or ksh emulation, the default is @code{+} .
@end quotation

@geindex psvar; Variable

@geindex PSVAR; Variable

@code{psvar} <S> <Z> (@code{PSVAR} <S>)

@quotation

An array (colon-separated list) whose elements can be used in
@code{PROMPT} strings.  Setting @code{psvar} also sets @code{PSVAR}, and
vice versa.
@end quotation

@geindex READNULLCMD; Variable

@code{READNULLCMD} <S>

@quotation

The command name to assume if a single input redirection
is specified with no command.  Defaults to @code{more}.
@end quotation

@geindex REPORTMEMORY; Variable

@code{REPORTMEMORY}

@quotation

If nonnegative, commands whose maximum resident set size (roughly
speaking, main memory usage) in kilobytes is greater than this
value have timing statistics reported.  The format used to output
statistics is the value of the @code{TIMEFMT} parameter, which is the same
as for the @code{REPORTTIME} variable and the @code{time} builtin; note that
by default this does not output memory usage.  Appending
@code{" max RSS %M"} to the value of @code{TIMEFMT} causes it to output the
value that triggered the report.  If @code{REPORTTIME} is also in use,
at most a single report is printed for both triggers.  This feature
requires the @code{getrusage()} system call, commonly supported by
modern Unix-like systems.
@end quotation

@geindex REPORTTIME; Variable

@code{REPORTTIME}

@quotation

If nonnegative, commands whose combined user and system execution times
(measured in seconds) are greater than this value have timing
statistics printed for them.  Output is suppressed for commands
executed within the line editor, including completion; commands
explicitly marked with the @code{time} keyword still cause the summary
to be printed in this case.
@end quotation

@geindex REPLY; Variable

@code{REPLY}

@quotation

This parameter is reserved by convention to pass string values between
shell scripts and shell builtins in situations where a function call or
redirection are impossible or undesirable.  The @code{read} builtin and the
@code{select} complex command may set @code{REPLY}, and filename generation both
sets and examines its value when evaluating certain expressions.  Some
modules also employ @code{REPLY} for similar purposes.
@end quotation

@geindex reply; Variable

@code{reply}

@quotation

As @code{REPLY}, but for array values rather than strings.
@end quotation

@geindex RPROMPT; Variable

@code{RPROMPT} <S>

@geindex RPS1; Variable

@code{RPS1} <S>

@quotation

This prompt is displayed on the right-hand side of the screen
when the primary prompt is being displayed on the left.
This does not work if the @code{SINGLE_LINE_ZLE} option is set.
It is expanded in the same way as @code{PS1}.
@end quotation

@geindex RPROMPT2; Variable

@code{RPROMPT2} <S>

@geindex RPS2; Variable

@code{RPS2} <S>

@quotation

This prompt is displayed on the right-hand side of the screen
when the secondary prompt is being displayed on the left.
This does not work if the @code{SINGLE_LINE_ZLE} option is set.
It is expanded in the same way as @code{PS2}.
@end quotation

@geindex SAVEHIST; Variable

@code{SAVEHIST}

@quotation

The maximum number of history events to save in the history file.

If this is made local, it is not implicitly set to 0, but may be
explicitly set locally.
@end quotation

@geindex SPROMPT; Variable

@code{SPROMPT} <S>

@quotation

The prompt used for spelling correction.  The sequence
@code{%R} expands to the string which presumably needs spelling
correction, and @code{%r} expands to the proposed correction.
All other prompt escapes are also allowed.

The actions available at the prompt are @code{[nyae]}:


@table @asis

@item @code{n} (`no’) (default)

Discard the correction.
If there are no more corrections, accept the command line, else (with
@code{CORRECT_ALL}) prompt for the next.

@item @code{y} (`yes’)

Make the correction. If there are no more
corrections, accept the command line.

@item @code{a} (`abort’)

Place the entire command line in the
history for later edit, but without accepting it.

@item @code{e} (`edit’)

Resume editing the command line.
@end table
@end quotation

@geindex STTY; Variable

@code{STTY}

@quotation

If this parameter is set in a command’s environment, the shell runs the
@code{stty} command with the value of this parameter as arguments in order to
set up the terminal before executing the command. The modes apply only to the
command, and are reset when it finishes or is suspended. If the command is
suspended and continued later with the @code{fg} or @code{wait} builtins it will
see the modes specified by @code{STTY}, as if it were not suspended.  This
(intentionally) does not apply if the command is continued via @code{kill
-CONT}.`@w{`}  STTY`@w{`} is ignored if the command is run in the background, or
if it is in the environment of the shell but not explicitly assigned to in
the input line. This avoids running stty at every external command by
accidentally exporting it. Also note that @code{STTY} should not be used for
window size specifications; these will not be local to the command.

If the parameter is set and empty, all of the above applies except
that @code{stty} is not run. This can be useful as a way to freeze the tty
around a single command, blocking its changes to tty settings,
similar to the @code{ttyctl} builtin.
@end quotation

@geindex TERM; Variable

@code{TERM} <S>

@quotation

The type of terminal in use.  This is used when looking up termcap
sequences.  An assignment to @code{TERM} causes zsh to re-initialize the
terminal, even if the value does not change (e.g., @code{TERM=$TERM}).  It
is necessary to make such an assignment upon any change to the terminal
definition database or terminal type in order for the new settings to
take effect.
@end quotation

@geindex TERMINFO; Variable

@code{TERMINFO} <S>

@quotation

A reference to your terminfo database, used by the `terminfo’ library when the
system has it; see @code{terminfo(5)}.
If set, this causes the shell to reinitialise the terminal, making the
workaround @code{TERM=$TERM} unnecessary.
@end quotation

@geindex TERMINFO_DIRS; Variable

@code{TERMINFO_DIRS} <S>

@quotation

A colon-seprarated list of terminfo databases, used by the `terminfo’ library
when the system has it; see @code{terminfo(5)}. This variable is only
used by certain terminal libraries, in particular ncurses; see
@code{terminfo(5)} to check support on your system.  If set, this
causes the shell to reinitialise the terminal, making the workaround
@code{TERM=$TERM} unnecessary.  Note that unlike other colon-separated
arrays this is not tied to a zsh array.
@end quotation

@geindex .term.extensions; Variable

@code{.term.extensions}

@quotation

An array containing a list of extension features of the terminal.
See @ref{98,,Terminal Extensions}.
@end quotation

@geindex .term.querywait; Variable

@code{.term.querywait}

@quotation

The time the shell waits, in hundredths of seconds, for the response to
terminal queries.  A value of @code{\`0'} disables the timeout and the shell will
wait indefinitely.  If not set, a default of @code{\`50'} or half a second is
used.
@end quotation

@geindex TIMEFMT; Variable

@code{TIMEFMT}

@quotation

The format of process time reports with the @code{time} keyword.
The default is @code{%J  %U user %S system %P cpu %*E total}.
Recognizes the following escape sequences, although not all
may be available on all systems, and some that are available
may not be useful:


@table @asis

@item @code{%%}

A @code{%}.

@item @code{%U}

CPU seconds spent in user mode.

@item @code{%S}

CPU seconds spent in kernel mode.

@item @code{%E}

Elapsed time in seconds.

@item @code{%P}

The CPU percentage, computed as
100*(@code{%U+%S)/%E}.

@item @code{%W}

Number of times the process was swapped.

@item @code{%X}

The average amount in (shared) text space used in kilobytes.

@item @code{%D}

The average amount in (unshared) data/stack space used in
kilobytes.

@item @code{%K}

The total space used (@code{%X+%D}) in kilobytes.

@item @code{%M}

The  maximum memory the process had in use at any time in
kilobytes.

@item @code{%F}

The number of major page faults (page needed to be brought
from disk).

@item @code{%R}

The number of minor page faults.

@item @code{%I}

The number of input operations.

@item @code{%O}

The number of output operations.

@item @code{%r}

The number of socket messages received.

@item @code{%s}

The number of socket messages sent.

@item @code{%k}

The number of signals received.

@item @code{%w}

Number of voluntary context switches (waits).

@item @code{%c}

Number of involuntary context switches.

@item @code{%J}

The name of this job.
@end table

A star may be inserted between the percent sign and flags printing time
(e.g., @code{%*E}); this causes the time to be printed in
@var{hh}@code{:}@var{mm}@code{:}@var{ss}@code{.}@var{ttt}
format (hours and minutes are only printed if they are not zero).
Alternatively, @code{m}, @code{u}, or @code{n} may be used (e.g.,
@code{%mE}) to produce time output in milliseconds, microseconds, or
nanoseconds, respectively. Note that some timings on some platforms
are not actually nanosecond-precise (nor accurate to 1 ns when
they are); in fact on many systems user and kernel times are not
even microsecond-precise.
@end quotation

@geindex TMOUT; Variable

@code{TMOUT}

@quotation

If this parameter is nonzero, the shell will receive an @code{ALRM}
signal if a command is not entered within the specified number of
seconds after issuing a prompt. If there is a trap on @code{SIGALRM}, it
will be executed and a new alarm is scheduled using the value of the
@code{TMOUT} parameter after executing the trap.  If no trap is set, and
the idle time of the terminal is not less than the value of the
@code{TMOUT} parameter, zsh terminates.  Otherwise a new alarm is
scheduled to @code{TMOUT} seconds after the last keypress.
@end quotation

@geindex TMPPREFIX; Variable

@code{TMPPREFIX}

@quotation

A pathname prefix which the shell will use for all temporary files.
Note that this should include an initial part for the file name as
well as any directory names.  The default is @code{/tmp/zsh}.
@end quotation

@geindex TMPSUFFIX; Variable

@code{TMPSUFFIX}

@quotation

A filename suffix which the shell will use for temporary files created
by process substitutions (e.g., @code{=(}@var{list}@code{)}).
Note that the value should include a leading dot @code{.} if intended
to be interpreted as a file extension.  The default is not to append
any suffix, thus this parameter should be assigned only when needed
and then unset again.
@end quotation

@geindex WORDCHARS; Variable

@code{WORDCHARS} <S>

@quotation

A list of non-alphanumeric characters considered part of a word
by the line editor.
@end quotation

@geindex ZBEEP; Variable

@code{ZBEEP}

@quotation

If set, this gives a string of characters, which can use all the same codes
as the @code{bindkey} command as described in
@ref{99,,The zsh/zle Module}, that will be output to the terminal
instead of beeping.  This may have a visible instead of an audible effect;
for example, the string @code{\e[?5h\e[?5l} on a vt100 or xterm will have
the effect of flashing reverse video on and off (if you usually use reverse
video, you should use the string @code{\e[?5l\e[?5h} instead).  This takes
precedence over the @code{NOBEEP} option.
@end quotation

@geindex ZDOTDIR; Variable

@code{ZDOTDIR}

@quotation

The directory to search for shell startup files (.zshrc, etc),
if not @code{$HOME}.
@end quotation

@geindex zle_bracketed_paste; Variable

@geindex bracketed paste; Command

@geindex enabling bracketed paste; Command

@code{zle_bracketed_paste}

@quotation

This two-element array contains the terminal escape sequences for enabling and
disabling the bracketed paste feature which allows ZLE to discern text that is
pasted into the terminal.  These escape sequences are used to enable bracketed
paste when ZLE is active and disable it at other times.  Unsetting the
parameter has the effect of ensuring that bracketed paste remains disabled.
However, see also the @code{.term.extensions} parameter which provides a single
place to enable or disable terminal features.
@end quotation

@geindex zle_cursorform; Variable

@code{zle_cursorform}

@quotation

An array describing contexts in which ZLE should change the shape and color
of the cursor.
See
.. only:: man

@quotation

`Cursor Shape and Color' in @code{zshzle(1)}
@end quotation

Cursor Shape and Color

.
@end quotation

@geindex zle_highlight; Variable

@code{zle_highlight}

@quotation

An array describing contexts in which ZLE should highlight the input text.
See @ref{60,,Character Highlighting}.
@end quotation

@geindex ZLE_LINE_ABORTED; Variable

@code{ZLE_LINE_ABORTED}

@quotation

This parameter is set by the line editor when an error occurs.  It
contains the line that was being edited at the point of the error.
@code{print -zr -- $ZLE_LINE_ABORTED} can be used to recover the line.
Only the most recent line of this kind is remembered.
@end quotation

@geindex ZLE_REMOVE_SUFFIX_CHARS; Variable

@geindex ZLE_SPACE_SUFFIX_CHARS; Variable

@code{ZLE_REMOVE_SUFFIX_CHARS}

@code{ZLE_SPACE_SUFFIX_CHARS}

@quotation

These parameters are used by the line editor.  In certain circumstances
suffixes (typically space or slash) added by the completion system
will be removed automatically, either because the next editing command
was not an insertable character, or because the character was marked
as requiring the suffix to be removed.

These variables can contain the sets of characters that will cause the
suffix to be removed.  If @code{ZLE_REMOVE_SUFFIX_CHARS} is set, those
characters will cause the suffix to be removed; if
@code{ZLE_SPACE_SUFFIX_CHARS} is set, those characters will cause the
suffix to be removed and replaced by a space.

If @code{ZLE_REMOVE_SUFFIX_CHARS} is not set, the default behaviour is
equivalent to:

@example
 ZLE_REMOVE_SUFFIX_CHARS=$' \t\n;&|'
@end example

If @code{ZLE_REMOVE_SUFFIX_CHARS} is set but is empty, no characters have this
behaviour.  @code{ZLE_SPACE_SUFFIX_CHARS} takes precedence, so that the
following:

@example
 ZLE_SPACE_SUFFIX_CHARS=$'&|'
@end example

causes the characters @code{&} and @code{|} to remove the suffix but to
replace it with a space.

To illustrate the difference, suppose that the option @code{AUTO_REMOVE_SLASH}
is in effect and the directory @code{DIR} has just been completed, with an
appended @code{/}, following which the user types @code{&}.  The default result
is @code{DIR&}.  With @code{ZLE_REMOVE_SUFFIX_CHARS} set but without including
@code{&} the result is @code{DIR/&}.  With @code{ZLE_SPACE_SUFFIX_CHARS} set to
include @code{&} the result is @code{DIR &}.

Note that certain completions may provide their own suffix removal
or replacement behaviour which overrides the values described here.
See the completion system documentation in
@code{zshcompsys}.
@end quotation

@geindex ZLE_RPROMPT_INDENT; Variable

@code{ZLE_RPROMPT_INDENT} <S>

@quotation

If set, used to give the indentation between the right hand side of
the right prompt in the line editor as given by @code{RPS1} or @code{RPROMPT}
and the right hand side of the screen.  If not set, the value 1 is used.

Typically this will be used to set the value to 0 so that the prompt
appears flush with the right hand side of the screen.  This is not the
default as many terminals do not handle this correctly, in particular
when the prompt appears at the extreme bottom right of the screen.
Recent virtual terminals are more likely to handle this case correctly.
Some experimentation is necessary.
@end quotation

@c historic nodename: Options

@node Options<2>,Shell Builtin Commands,Parameters,Top
@anchor{Zsh/options doc}@anchor{9a}@anchor{Zsh/options options}@anchor{9b}
@chapter Options


@geindex options; Command

@c historic nodename: Specifying Options

@menu
* Specifying Options:: 
* Description of Options:: 
* Option Aliases:: 
* Single Letter Options:: 

@end menu

@node Specifying Options,Description of Options,,Options<2>
@anchor{Zsh/options specifying-options}@anchor{52}
@section Specifying Options


@geindex options@comma{} specifying; Command

Options are primarily referred to by name.
These names are case insensitive and underscores are ignored.
For example, @code{allexport} is equivalent to @code{A__lleXP_ort}.

The sense of an option name may be inverted by preceding it with
@code{no}, so @code{setopt No_Beep} is equivalent to @code{unsetopt beep}.
This inversion can only be done once, so @code{nonobeep} is `not'
a synonym for @code{beep}.  Similarly, @code{tify} is not a synonym for
@code{nonotify} (the inversion of @code{notify}).

Some options also have one or more single letter names.
There are two sets of single letter options: one used by default,
and another used to emulate `sh'/`ksh' (used when the
@code{SH_OPTION_LETTERS} option is set).
The single letter options can be used on the shell command line,
or with the @code{set}, @code{setopt} and @code{unsetopt}
builtins, as normal Unix options preceded by @code{-}.

The sense of the single letter options may be inverted by using
@code{+} instead of @code{-}.
Some of the single letter option names refer to an option being off,
in which case the inversion of that name refers to the option being on.
For example, @code{+n} is the short name of @code{exec}, and
@code{-n} is the short name of its inversion, @code{noexec}.

In strings of single letter options supplied to the shell at startup,
trailing whitespace will be ignored; for example the string @code{-f}
will be treated just as @code{-f}, but the string @code{-f i} is an error.
This is because many systems which implement the @code{#!} mechanism for
calling scripts do not strip trailing whitespace.

It is possible for options to be set within a function scope.  See the
description of the option @code{LOCAL_OPTIONS} below.

@c historic nodename: Description of Options

@node Description of Options,Option Aliases,Specifying Options,Options<2>
@anchor{Zsh/options description-of-options}@anchor{9c}
@section Description of Options


@geindex options@comma{} description; Command

In the following list, options set by default in all emulations are marked
<D>; those set by default only in csh, ksh, sh, or zsh emulations are marked
<C>, <K>, <S>, <Z> as appropriate.  When listing options (by @code{setopt},
@code{unsetopt}, @code{set -o} or @code{set +o}), those turned on by default
appear in the list prefixed with @code{no}.  Hence (unless
@code{KSH_OPTION_PRINT} is set), @code{setopt} shows all options whose settings
are changed from the default.

@menu
* Changing Directories:: 
* Completion: Completion<2>. 
* Expansion and Globbing:: 
* History:: 
* Initialisation:: 
* Input/Output:: 
* Job Control:: 
* Prompting:: 
* Scripts and Functions:: 
* Shell Emulation:: 
* Shell State: Shell State<2>. 
* Zle:: 

@end menu

@node Changing Directories,Completion<2>,,Description of Options
@anchor{Zsh/options changing-directories}@anchor{9d}
@subsection Changing Directories


@geindex AUTO_CD; Program

@geindex NO_AUTO_CD; Program

@geindex AUTOCD; Program

@geindex NOAUTOCD; Program

@geindex cd@comma{} automatic; Command

@code{AUTO_CD} (@code{-J})

@quotation

If a command is issued that can’t be executed as a normal command,
and the command is the name of a directory, perform the @code{cd}
command to that directory.
This option is only applicable if the option @code{SHIN_STDIN} is set,
i.e. if commands are being read from standard input.  The option
is designed for interactive use; it is recommended that @code{cd}
be used explicitly in scripts to avoid ambiguity.
@end quotation

@geindex AUTO_PUSHD; Program

@geindex NO_AUTO_PUSHD; Program

@geindex AUTOPUSHD; Program

@geindex NOAUTOPUSHD; Program

@geindex cd@comma{} behaving like pushd; Command

@geindex pushd@comma{} making cd behave like; Command

@code{AUTO_PUSHD} (@code{-N})

@quotation

Make @code{cd} push the old directory onto the directory stack.
@end quotation

@geindex CDABLE_VARS; Program

@geindex NO_CDABLE_VARS; Program

@geindex CDABLEVARS; Program

@geindex NOCDABLEVARS; Program

@geindex cd@comma{} to parameter; Command

@code{CDABLE_VARS} (@code{-T})

@quotation

If the argument to a @code{cd} command (or an implied @code{cd} with the
@code{AUTO_CD} option set) is not a directory, and does not begin with a
slash, try to expand the expression as if it were preceded by a @code{~} (see
@ref{5d,,Filename Expansion}).
@end quotation

@geindex CD_SILENT; Program

@geindex NO_CD_SILENT; Program

@geindex CDSILENT; Program

@geindex NOCDSILENT; Program

@geindex cd@comma{} silencing; Command

@geindex autocd@comma{} silencing; Command

@code{CD_SILENT}

@quotation

Never print the working directory after a @code{cd} (whether explicit or
implied with the @code{AUTO_CD} option set). @code{cd} normally prints the
working directory when the argument given to it was @code{-}, a stack entry, or
the name of a directory found under @code{CDPATH}. Note that this is distinct
from @code{pushd}’s stack-printing behaviour, which is controlled by
@code{PUSHD_SILENT}. This option overrides the printing-related effects of
@code{POSIX_CD}.
@end quotation

@geindex CHASE_DOTS; Program

@geindex NO_CHASE_DOTS; Program

@geindex CHASEDOTS; Program

@geindex NOCHASEDOTS; Program

@geindex cd@comma{} with .. in argument; Command

@code{CHASE_DOTS}

@quotation

When changing to a directory containing a path segment @code{..} which would
otherwise be treated as canceling the previous segment in the path (in
other words, @code{foo/..} would be removed from the path, or if @code{..} is
the first part of the path, the last part of the current working directory
would be removed), instead resolve the path to the physical directory.
This option is overridden by @code{CHASE_LINKS}.

For example, suppose @code{/foo/bar} is a link to the directory @code{/alt/rod}.
Without this option set, @code{cd /foo/bar/..} changes to @code{/foo}; with it
set, it changes to @code{/alt}.  The same applies if the current directory
is @code{/foo/bar} and @code{cd ..} is used.  Note that all other symbolic
links in the path will also be resolved.
@end quotation

@geindex CHASE_LINKS; Program

@geindex NO_CHASE_LINKS; Program

@geindex CHASELINKS; Program

@geindex NOCHASELINKS; Program

@geindex links@comma{} symbolic; Command

@geindex symbolic links; Command

@code{CHASE_LINKS} (@code{-w})

@quotation

Resolve symbolic links to their true values when changing directory.
This also has the effect of @code{CHASE_DOTS}, i.e. a @code{..} path segment
will be treated as referring to the physical parent, even if the preceding
path segment is a symbolic link.
@end quotation

@geindex POSIX_CD; Program

@geindex POSIXCD; Program

@geindex NO_POSIX_CD; Program

@geindex NOPOSIXCD; Program

@geindex CDPATH@comma{} order of checking; Command

@code{POSIX_CD} <K> <S>

@quotation

Modifies the behaviour of @code{cd}, @code{chdir} and @code{pushd} commands
to make them more compatible with the POSIX standard. The behaviour with
the option unset is described in the documentation for the @code{cd}
builtin in @code{zshbuiltins}.
If the option is set, the shell does not test for directories beneath
the local directory (@code{.}) until after all directories in @code{cdpath}
have been tested, and the @code{cd} and @code{chdir} commands do not recognise
arguments of the form @{@code{+|-}@}:var:@cite{n} as directory stack entries.

Also, if the option is set, the conditions under which the shell
prints the new directory after changing to it are modified.  It is
no longer restricted to interactive shells (although printing of
the directory stack with @code{pushd} is still limited to interactive
shells); and any use of a component of @code{CDPATH}, including a @code{.} but
excluding an empty component that is otherwise treated as @code{.}, causes
the directory to be printed.
@end quotation

@geindex PUSHD_IGNORE_DUPS; Program

@geindex NO_PUSHD_IGNORE_DUPS; Program

@geindex PUSHDIGNOREDUPS; Program

@geindex NOPUSHDIGNOREDUPS; Program

@geindex directory stack@comma{} ignoring duplicates; Command

@code{PUSHD_IGNORE_DUPS}

@quotation

Don’t push multiple copies of the same directory onto the directory stack.
@end quotation

@geindex PUSHD_MINUS; Program

@geindex NO_PUSHD_MINUS; Program

@geindex PUSHDMINUS; Program

@geindex NOPUSHDMINUS; Program

@geindex directory stack@comma{} controlling syntax; Command

@code{PUSHD_MINUS}

@quotation

Exchanges the meanings of @code{+} and @code{-}
when used with a number to specify a directory in the stack.
@end quotation

@geindex PUSHD_SILENT; Program

@geindex NO_PUSHD_SILENT; Program

@geindex PUSHDSILENT; Program

@geindex NOPUSHDSILENT; Program

@geindex directory stack@comma{} silencing; Command

@code{PUSHD_SILENT} (@code{-E})

@quotation

Do not print the directory stack after @code{pushd} or @code{popd}.
@end quotation

@geindex PUSHD_TO_HOME; Program

@geindex NO_PUSHD_TO_HOME; Program

@geindex PUSHDTOHOME; Program

@geindex NOPUSHDTOHOME; Program

@geindex pushd@comma{} to home; Command

@code{PUSHD_TO_HOME} (@code{-D})

@quotation

Have @code{pushd} with no arguments act like @code{pushd $HOME}.
@end quotation

@node Completion<2>,Expansion and Globbing,Changing Directories,Description of Options
@anchor{Zsh/options completion}@anchor{9e}
@subsection Completion


@geindex ALWAYS_LAST_PROMPT; Program

@geindex NO_ALWAYS_LAST_PROMPT; Program

@geindex ALWAYSLASTPROMPT; Program

@geindex NOALWAYSLASTPROMPT; Program

@code{ALWAYS_LAST_PROMPT} <D>

@quotation

If unset, key functions that list completions try to return to the last
prompt if given a numeric argument. If set these functions try to
return to the last prompt if given `no' numeric argument.
@end quotation

@geindex ALWAYS_TO_END; Program

@geindex NO_ALWAYS_TO_END; Program

@geindex ALWAYSTOEND; Program

@geindex NOALWAYSTOEND; Program

@code{ALWAYS_TO_END}

@quotation

If a completion is performed with the cursor within a word, and a
full completion is inserted, the cursor is moved to the end of the
word.  That is, the cursor is moved to the end of the word if either
a single match is inserted or menu completion is performed.
@end quotation

@geindex AUTO_LIST; Program

@geindex NO_AUTO_LIST; Program

@geindex AUTOLIST; Program

@geindex NOAUTOLIST; Program

@geindex completion@comma{} listing choices; Command

@code{AUTO_LIST} (@code{-9}) <D>

@quotation

Automatically list choices on an ambiguous completion.
@end quotation

@geindex AUTO_MENU; Program

@geindex NO_AUTO_MENU; Program

@geindex AUTOMENU; Program

@geindex NOAUTOMENU; Program

@geindex completion@comma{} menu; Command

@code{AUTO_MENU} <D>

@quotation

Automatically use menu completion after the second consecutive request for
completion, for example by pressing the tab key repeatedly. This option
is overridden by @code{MENU_COMPLETE}.
@end quotation

@geindex AUTO_NAME_DIRS; Program

@geindex NO_AUTO_NAME_DIRS; Program

@geindex AUTONAMEDIRS; Program

@geindex NOAUTONAMEDIRS; Program

@geindex directories@comma{} named; Command

@code{AUTO_NAME_DIRS}

@quotation

Any global parameter that is set to the absolute name of a directory
immediately becomes a name for that directory, that will be used
by the @code{%~}
and related prompt sequences, and will be available when completion
is performed on a word starting with @code{~}.
(Otherwise, the parameter must be used in the form @code{~}@var{param} first.)
@end quotation

@geindex AUTO_PARAM_KEYS; Program

@geindex NO_AUTO_PARAM_KEYS; Program

@geindex AUTOPARAMKEYS; Program

@geindex NOAUTOPARAMKEYS; Program

@code{AUTO_PARAM_KEYS} <D>

@quotation

If a parameter name was completed and a following character
(normally a space) automatically
inserted, and the next character typed is one
of those that have to come directly after the name (like @code{@}}, @code{:},
etc.), the automatically added character is deleted, so that the character
typed comes immediately after the parameter name.
Completion in a brace expansion is affected similarly: the added character
is a @code{,}, which will be removed if @code{@}} is typed next.
@end quotation

@geindex AUTO_PARAM_SLASH; Program

@geindex NO_AUTO_PARAM_SLASH; Program

@geindex AUTOPARAMSLASH; Program

@geindex NOAUTOPARAMSLASH; Program

@code{AUTO_PARAM_SLASH} <D>

@quotation

If a parameter is completed whose content is the name of a directory,
then add a trailing slash instead of a space.
@end quotation

@geindex AUTO_REMOVE_SLASH; Program

@geindex NO_AUTO_REMOVE_SLASH; Program

@geindex AUTOREMOVESLASH; Program

@geindex NOAUTOREMOVESLASH; Program

@geindex slash@comma{} removing trailing; Command

@code{AUTO_REMOVE_SLASH} <D>

@quotation

When the last character resulting from a completion is a slash and the next
character typed is a word delimiter, a slash, or a character that ends
a command (such as a semicolon or an ampersand), remove the slash.
@end quotation

@geindex BASH_AUTO_LIST; Program

@geindex NO_BASH_AUTO_LIST; Program

@geindex BASHAUTOLIST; Program

@geindex NOBASHAUTOLIST; Program

@geindex completion@comma{} listing choices@comma{} bash style; Command

@code{BASH_AUTO_LIST}

@quotation

On an ambiguous completion, automatically list choices when the
completion function is called twice in succession.  This takes
precedence over @code{AUTO_LIST}.  The setting of @code{LIST_AMBIGUOUS} is
respected.  If @code{AUTO_MENU} is set, the menu behaviour will then start
with the third press.  Note that this will not work with
@code{MENU_COMPLETE}, since repeated completion calls immediately cycle
through the list in that case.
@end quotation

@geindex COMPLETE_ALIASES; Program

@geindex NO_COMPLETE_ALIASES; Program

@geindex COMPLETEALIASES; Program

@geindex NOCOMPLETEALIASES; Program

@geindex aliases@comma{} completion of; Command

@code{COMPLETE_ALIASES}

@quotation

Prevents aliases on the command line from being internally substituted
before completion is attempted.  The effect is to make the alias a
distinct command for completion purposes.
@end quotation

@geindex COMPLETE_IN_WORD; Program

@geindex NO_COMPLETE_IN_WORD; Program

@geindex COMPLETEINWORD; Program

@geindex NOCOMPLETEINWORD; Program

@code{COMPLETE_IN_WORD}

@quotation

If unset, the cursor is set to the end of the word if completion is
started. Otherwise it stays there and completion is done from both ends.
@end quotation

@geindex GLOB_COMPLETE; Program

@geindex NO_GLOB_COMPLETE; Program

@geindex GLOBCOMPLETE; Program

@geindex NOGLOBCOMPLETE; Program

@code{GLOB_COMPLETE}

@quotation

When the current word has a glob pattern, do not insert all the words
resulting from the expansion but generate matches as for completion and
cycle through them like @code{MENU_COMPLETE}. The matches are generated as if
a @code{*} was added to the end of the word, or inserted at the cursor when
@code{COMPLETE_IN_WORD} is set.  This actually uses pattern matching, not
globbing, so it works not only for files but for any completion, such as
options, user names, etc.

Note that when the pattern matcher is used, matching control (for example,
case-insensitive or anchored matching) cannot be used.  This limitation
only applies when the current word contains a pattern; simply turning
on the @code{GLOB_COMPLETE} option does not have this effect.
@end quotation

@geindex HASH_LIST_ALL; Program

@geindex NO_HASH_LIST_ALL; Program

@geindex HASHLISTALL; Program

@geindex NOHASHLISTALL; Program

@code{HASH_LIST_ALL} <D>

@quotation

Whenever a command completion or spelling correction is attempted, make
sure the entire command path is hashed first.  This makes the first
completion slower but avoids false reports of spelling errors.
@end quotation

@geindex LIST_AMBIGUOUS; Program

@geindex NO_LIST_AMBIGUOUS; Program

@geindex LISTAMBIGUOUS; Program

@geindex NOLISTAMBIGUOUS; Program

@geindex ambiguous completion; Command

@geindex completion@comma{} ambiguous; Command

@code{LIST_AMBIGUOUS} <D>

@quotation

This option works when @code{AUTO_LIST} or @code{BASH_AUTO_LIST} is also
set.  If there is an unambiguous prefix to insert on the command line,
that is done without a completion list being displayed; in other
words, auto-listing behaviour only takes place when nothing would be
inserted.  In the case of @code{BASH_AUTO_LIST}, this means that the list
will be delayed to the third call of the function.
@end quotation

@geindex LIST_BEEP; Program

@geindex NO_LIST_BEEP; Program

@geindex LISTBEEP; Program

@geindex NOLISTBEEP; Program

@geindex beep@comma{} ambiguous completion; Command

@geindex completion@comma{} beep on ambiguous; Command

@code{LIST_BEEP} <D>

@quotation

Beep on an ambiguous completion.  More accurately, this forces the
completion widgets to return status 1 on an ambiguous completion, which
causes the shell to beep if the option @code{BEEP} is also set; this may
be modified if completion is called from a user-defined widget.
@end quotation

@geindex LIST_PACKED; Program

@geindex NO_LIST_PACKED; Program

@geindex LISTPACKED; Program

@geindex NOLISTPACKED; Program

@geindex completion@comma{} listing; Command

@code{LIST_PACKED}

@quotation

Try to make the completion list smaller (occupying less lines) by
printing the matches in columns with different widths.
@end quotation

@geindex LIST_ROWS_FIRST; Program

@geindex NO_LIST_ROWS_FIRST; Program

@geindex LISTROWSFIRST; Program

@geindex NOLISTROWSFIRST; Program

@geindex completion@comma{} listing order; Command

@code{LIST_ROWS_FIRST}

@quotation

Lay out the matches in completion lists sorted horizontally, that is,
the second match is to the right of the first one, not under it as
usual.
@end quotation

@geindex LIST_TYPES; Program

@geindex NO_LIST_TYPES; Program

@geindex LISTTYPES; Program

@geindex NOLISTTYPES; Program

@geindex marking file types; Command

@geindex files@comma{} marking type of; Command

@code{LIST_TYPES} (@code{-X}) <D>

@quotation

When listing files that are possible completions, show the
type of each file with a trailing identifying mark.
@end quotation

@geindex MENU_COMPLETE; Program

@geindex NO_MENU_COMPLETE; Program

@geindex MENUCOMPLETE; Program

@geindex NOMENUCOMPLETE; Program

@geindex completion@comma{} menu; Command

@code{MENU_COMPLETE} (@code{-Y})

@quotation

On an ambiguous completion, instead of listing possibilities or beeping,
insert the first match immediately.  Then when completion is requested
again, remove the first match and insert the second match, etc.
When there are no more matches, go back to the first one again.
@code{reverse-menu-complete} may be used to loop through the list
in the other direction. This option overrides @code{AUTO_MENU}.
@end quotation

@geindex REC_EXACT; Program

@geindex NO_REC_EXACT; Program

@geindex RECEXACT; Program

@geindex NORECEXACT; Program

@geindex completion@comma{} exact matches; Command

@code{REC_EXACT} (@code{-S})

@quotation

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.
@end quotation

@node Expansion and Globbing,History,Completion<2>,Description of Options
@anchor{Zsh/options expansion-and-globbing}@anchor{9f}
@subsection Expansion and Globbing


@geindex BAD_PATTERN; Program

@geindex NO_BAD_PATTERN; Program

@geindex BADPATTERN; Program

@geindex NOBADPATTERN; Program

@geindex globbing@comma{} bad pattern; Command

@geindex filename generation@comma{} bad pattern; Command

@code{BAD_PATTERN} (@code{+2}) <C> <Z>

@quotation

If a pattern for filename generation is badly formed, print an error message.
(If this option is unset, the pattern will be left unchanged.)
@end quotation

@geindex BARE_GLOB_QUAL; Program

@geindex NO_BARE_GLOB_QUAL; Program

@geindex BAREGLOBQUAL; Program

@geindex NOBAREGLOBQUAL; Program

@geindex globbing qualifiers@comma{} enable; Command

@geindex enable globbing qualifiers; Command

@code{BARE_GLOB_QUAL} <Z>

@quotation

In a glob pattern, treat a trailing set of parentheses as a qualifier
list, if it contains no unquoted @code{|}, @code{(} or (if special) @code{~}
characters.  See @ref{17,,Filename Generation}.
@end quotation

@geindex BRACE_CCL; Program

@geindex NO_BRACE_CCL; Program

@geindex BRACECCL; Program

@geindex NOBRACECCL; Program

@geindex brace expansion@comma{} extending; Command

@geindex expansion@comma{} brace@comma{} extending; Command

@code{BRACE_CCL}

@quotation

Expand expressions in braces which would not otherwise undergo brace
expansion to a lexically ordered list of all the characters.  See
@ref{77,,Brace Expansion}.
@end quotation

@geindex CASE_GLOB; Program

@geindex NO_CASE_GLOB; Program

@geindex CASEGLOB; Program

@geindex NOCASEGLOB; Program

@geindex case-insensitive globbing@comma{} option; Command

@code{CASE_GLOB} <D>

@quotation

Make globbing (filename generation) sensitive to case.  Note that other
uses of patterns are always sensitive to case.  If the option is unset,
the presence of any character which is special to filename generation
will cause case-insensitive matching.  For example, @code{cvs(/)}
can match the directory @code{CVS} owing to the presence of the globbing flag
(unless the option @code{BARE_GLOB_QUAL} is unset).
@end quotation

@geindex CASE_MATCH; Program

@geindex NO_CASE_MATCH; Program

@geindex CASEMATCH; Program

@geindex NOCASEMATCH; Program

@geindex case-insensitive regular expression matches@comma{} option; Command

@geindex regular expressions@comma{} case-insensitive matching@comma{} option; Command

@code{CASE_MATCH} <D>

@quotation

Make regular expressions using the @code{zsh/regex} module (including
matches with @code{=~}) sensitive to case.
@end quotation

@geindex CASE_PATHS; Program

@geindex NO_CASE_PATHS; Program

@geindex CASEPATHS; Program

@geindex NOCASEPATHS; Program

@geindex case-sensitive globbing@comma{} option; Command

@code{CASE_PATHS}

@quotation

If @code{CASE_PATHS} is not set (the default), @code{CASE_GLOB} affects the
interpretation of `every' path component, whenever a special
character appears in `any' component.  When @code{CASE_PATHS} is set,
file path components that do `not' contain special filename
generation characters are always sensitive to case, thus restricting
@code{NO_CASE_GLOB} to components that contain globbing characters.

Note that if the filesystem itself is not sensitive to case, then
@code{CASE_PATHS} has no effect.
@end quotation

@geindex CSH_NULL_GLOB; Program

@geindex NO_CSH_NULL_GLOB; Program

@geindex CSHNULLGLOB; Program

@geindex NOCSHNULLGLOB; Program

@geindex csh@comma{} null globbing style; Command

@geindex null globbing style@comma{} csh; Command

@geindex globbing@comma{} null@comma{} style@comma{} csh; Command

@code{CSH_NULL_GLOB} <C>

@quotation

If a pattern for filename generation has no matches,
delete the pattern from the argument list;
do not report an error unless all the patterns
in a command have no matches.
Overrides @code{NOMATCH}.
@end quotation

@geindex EQUALS; Program

@geindex NO_EQUALS; Program

@geindex NOEQUALS; Program

@geindex filename expansion@comma{} =; Command

@code{EQUALS} <Z>

@quotation

Perform @code{=} filename expansion.
(See @ref{5d,,Filename Expansion}.)
@end quotation

@geindex EXTENDED_GLOB; Program

@geindex NO_EXTENDED_GLOB; Program

@geindex EXTENDEDGLOB; Program

@geindex NOEXTENDEDGLOB; Program

@geindex globbing@comma{} extended; Command

@code{EXTENDED_GLOB}

@quotation

Treat the @code{#}, @code{~} and @code{^} characters as part of patterns
for filename generation, etc.  (An initial unquoted @code{~}
always produces named directory expansion.)
@end quotation

@geindex FORCE_FLOAT; Program

@geindex NO_FORCE_FLOAT; Program

@geindex FORCEFLOAT; Program

@geindex NOFORCEFLOAT; Program

@geindex floating point@comma{} forcing use of; Command

@geindex forcing use of floating point; Command

@code{FORCE_FLOAT}

@quotation

Constants in arithmetic evaluation will be treated as
floating point even without the use of a decimal point; the
values of integer variables will be converted to floating point when
used in arithmetic expressions.  Integers in any base will be converted.
@end quotation

@geindex GLOB; Program

@geindex NO_GLOB; Program

@geindex NOGLOB; Program

@geindex globbing@comma{} enabling; Command

@geindex enabling globbing; Command

@code{GLOB} (@code{+F}, ksh: @code{+f}) <D>

@quotation

Perform filename generation (globbing).
(See @ref{17,,Filename Generation}.)
@end quotation

@geindex GLOB_ASSIGN; Program

@geindex NO_GLOB_ASSIGN; Program

@geindex GLOBASSIGN; Program

@geindex NOGLOBASSIGN; Program

@code{GLOB_ASSIGN} <C>

@quotation

If this option is set, filename generation (globbing) is
performed on the right hand side of scalar parameter assignments of
the form @cite{:var:`name}@code{=}@var{pattern} (e.g. @code{foo=*}).
If the result has more than one word the parameter will become an array
with those words as arguments. This option is provided for backwards
compatibility only: globbing is always performed on the right hand side
of array assignments of the form @var{name}@code{=(}@var{value}@code{)}
(e.g. @code{foo=(*)}) and this form is recommended for clarity;
with this option set, it is not possible to predict whether the result
will be an array or a scalar.
@end quotation

@geindex GLOB_DOTS; Program

@geindex NO_GLOB_DOTS; Program

@geindex GLOBDOTS; Program

@geindex NOGLOBDOTS; Program

@geindex globbing@comma{} of . files; Command

@code{GLOB_DOTS} (@code{-4})

@quotation

Do not require a leading @code{.} in a filename to be matched explicitly.
@end quotation

@geindex GLOB_STAR_SHORT; Program

@geindex NO_GLOB_STAR_SHORT; Program

@geindex GLOBSTARSHORT; Program

@geindex NOGLOBSTARSHORT; Program

@geindex globbing@comma{} short forms; Command

@geindex globbing@comma{} ** special; Command

@code{GLOB_STAR_SHORT}

@quotation

When this option is set and the default zsh-style globbing is in
effect, the pattern @code{**/*} can be abbreviated to @code{**} and the
pattern @code{***/*} can be abbreviated to @code{***}.  Hence @code{**.c}
finds a file ending in @code{.c} in any subdirectory, and @code{***.c} does
the same while also following symbolic links.  A @code{/} immediately
after the @code{**} or @code{***} forces the pattern to be treated as the
unabbreviated form.
@end quotation

@geindex GLOB_SUBST; Program

@geindex NO_GLOB_SUBST; Program

@geindex GLOBSUBST; Program

@geindex NOGLOBSUBST; Program

@code{GLOB_SUBST} <C> <K> <S>

@quotation

Treat any characters resulting from parameter expansion as being
eligible for filename expansion and filename generation, and any
characters resulting from command substitution as being eligible for
filename generation.  Braces (and commas in between) do not become eligible
for expansion.
@end quotation

@geindex HIST_SUBST_PATTERN; Program

@geindex NO_HIST_SUBST_PATTERN; Program

@geindex HISTSUBSTPATTERN; Program

@geindex NOHISTSUBSTPATTERN; Program

@code{HIST_SUBST_PATTERN}

@quotation

Substitutions using the @code{:s} and @code{:&} history modifiers are performed
with pattern matching instead of string matching.  This occurs wherever
history modifiers are valid, including glob qualifiers and parameters.
See @ref{6b,,Modifiers}.
@end quotation

@geindex IGNORE_BRACES; Program

@geindex NO_IGNORE_BRACES; Program

@geindex IGNOREBRACES; Program

@geindex NOIGNOREBRACES; Program

@geindex disabling brace expansion; Command

@geindex brace expansion@comma{} disabling; Command

@geindex expansion@comma{} brace@comma{} disabling; Command

@code{IGNORE_BRACES} (@code{-I}) <S>

@quotation

Do not perform brace expansion.  For historical reasons this
also includes the effect of the @code{IGNORE_CLOSE_BRACES} option.
@end quotation

@geindex IGNORE_CLOSE_BRACES; Program

@geindex NO_IGNORE_CLOSE_BRACES; Program

@geindex IGNORECLOSEBRACES; Program

@geindex NOIGNORECLOSEBRACES; Program

@code{IGNORE_CLOSE_BRACES}

@quotation

When neither this option nor @code{IGNORE_BRACES} is set, a sole
close brace character @code{@}} is syntactically significant at any
point on a command line.  This has the effect that no semicolon
or newline is necessary before the brace terminating a function
or current shell construct.  When either option is set, a closing brace
is syntactically significant only in command position.  Unlike
@code{IGNORE_BRACES}, this option does not disable brace expansion.

For example, with both options unset a function may be defined
in the following fashion:

@example
 args() @{ echo $# @}
@end example

while if either option is set, this does not work and something
equivalent to the following is required:

@example
 args() @{ echo $#; @}
@end example
@end quotation

@geindex KSH_GLOB; Program

@geindex NO_KSH_GLOB; Program

@geindex KSHGLOB; Program

@geindex NOKSHGLOB; Program

@code{KSH_GLOB} <K>

@quotation

In pattern matching, the interpretation of parentheses is affected by
a preceding @code{@@}, @code{*}, @code{+}, @code{?} or @code{!}.
See @ref{17,,Filename Generation}.
@end quotation

@geindex MAGIC_EQUAL_SUBST; Program

@geindex NO_MAGIC_EQUAL_SUBST; Program

@geindex MAGICEQUALSUBST; Program

@geindex NOMAGICEQUALSUBST; Program

@code{MAGIC_EQUAL_SUBST}

@quotation

All unquoted arguments of the form @var{anything}@code{=}@var{expression}
appearing after the command name have filename expansion (that is,
where @var{expression} has a leading @code{~} or @code{=}) performed on
@var{expression} as if it were a parameter assignment.  The argument is
not otherwise treated specially; it is passed to the command as a single
argument, and not used as an actual parameter assignment.  For example, in
@code{echo foo=~/bar:~/rod}, both occurrences of @code{~} would be replaced.
Note that this happens anyway with @code{typeset} and similar statements.

This option respects the setting of the @code{KSH_TYPESET} option.  In other
words, if both options are in effect, arguments looking like
assignments will not undergo word splitting.
@end quotation

@geindex MARK_DIRS; Program

@geindex NO_MARK_DIRS; Program

@geindex MARKDIRS; Program

@geindex NOMARKDIRS; Program

@geindex directories@comma{} marking; Command

@geindex marking directories; Command

@code{MARK_DIRS} (@code{-8}, ksh: @code{-X})

@quotation

Append a trailing @code{/} to all directory
names resulting from filename generation (globbing).
@end quotation

@geindex MULTIBYTE; Program

@geindex NO_MULTIBYTE; Program

@geindex NOMULTIBYTE; Program

@geindex characters@comma{} multibyte@comma{} in expansion and globbing; Command

@geindex multibyte characters@comma{} in expansion and globbing; Command

@code{MULTIBYTE} <D>

@quotation

Respect multibyte characters when found in strings.
When this option is set, strings are examined using the
system library to determine how many bytes form a character, depending
on the current locale.  This affects the way characters are counted in
pattern matching, parameter values and various delimiters.

The option is on by default if the shell was compiled with
@code{MULTIBYTE_SUPPORT}; otherwise it is off by default and has no effect
if turned on.

If the option is off a single byte is always treated as a single
character.  This setting is designed purely for examining strings
known to contain raw bytes or other values that may not be characters
in the current locale.  It is not necessary to unset the option merely
because the character set for the current locale does not contain multibyte
characters.

The option does not affect the shell’s editor,  which always uses the
locale to determine multibyte characters.  This is because
the character set displayed by the terminal emulator is independent of
shell settings.
@end quotation

@geindex NOMATCH; Program

@geindex NO_NOMATCH; Program

@geindex NONOMATCH; Program

@geindex globbing@comma{} no matches; Command

@code{NOMATCH} (@code{+3}) <C> <Z>

@quotation

If a pattern for filename generation has no matches,
print an error, instead of
leaving it unchanged in the argument list.
This also applies to file expansion
of an initial @code{~} or @code{=}.
@end quotation

@geindex NULL_GLOB; Program

@geindex NO_NULL_GLOB; Program

@geindex NULLGLOB; Program

@geindex NONULLGLOB; Program

@geindex globbing@comma{} no matches; Command

@code{NULL_GLOB} (@code{-G})

@quotation

If a pattern for filename generation has no matches,
delete the pattern from the argument list instead
of reporting an error.  Overrides @code{NOMATCH}.
@end quotation

@geindex NUMERIC_GLOB_SORT; Program

@geindex NO_NUMERIC_GLOB_SORT; Program

@geindex NUMERICGLOBSORT; Program

@geindex NONUMERICGLOBSORT; Program

@geindex globbing@comma{} sorting numerically; Command

@code{NUMERIC_GLOB_SORT}

@quotation

If numeric filenames are matched by a filename generation pattern,
sort the filenames numerically rather than lexicographically.
@end quotation

@geindex RC_EXPAND_PARAM; Program

@geindex NO_RC_EXPAND_PARAM; Program

@geindex RCEXPANDPARAM; Program

@geindex NORCEXPANDPARAM; Program

@geindex rc@comma{} parameter expansion style; Command

@geindex parameter expansion style@comma{} rc; Command

@code{RC_EXPAND_PARAM} (@code{-P})

@quotation

Array expansions of the form
@var{foo}@code{$@{}@var{xx}@code{@}}@var{bar}, where the parameter
@var{xx} is set to @code{(}@var{a b c}@code{)}, are substituted with
@var{fooabar foobbar foocbar} instead of the default
@var{fooa b cbar}.  Note that an empty array will therefore cause
all arguments to be removed.
@end quotation

@geindex REMATCH_PCRE; Program

@geindex NO_REMATCH_PCRE; Program

@geindex REMATCHPCRE; Program

@geindex NOREMATCHPCRE; Program

@geindex regexp@comma{} PCRE; Command

@geindex PCRE@comma{} regexp; Command

@code{REMATCH_PCRE}

@quotation

If set, regular expression matching with the @code{=~} operator will use
Perl-Compatible Regular Expressions from the PCRE library.
(The @code{zsh/pcre} module must be available.)
If not set, regular expressions will use the extended regexp syntax
provided by the system libraries.
@end quotation

@geindex SH_GLOB; Program

@geindex NO_SH_GLOB; Program

@geindex SHGLOB; Program

@geindex NOSHGLOB; Program

@geindex sh@comma{} globbing style; Command

@geindex globbing style@comma{} sh; Command

@code{SH_GLOB} <K> <S>

@quotation

Disables the special meaning of @code{(}, @code{|}, @code{)}
and ‘@code{<}’ for globbing the result of parameter and command substitutions,
and in some other places where
the shell accepts patterns.  If @code{SH_GLOB} is set but @code{KSH_GLOB} is
not, the shell allows the interpretation of
subshell expressions enclosed in parentheses in some cases where there
is no space before the opening parenthesis, e.g. @code{!(true)}
is interpreted as if there were a space after the @code{!}.  This option is
set by default if zsh is invoked as @code{sh} or @code{ksh}.
@end quotation

@geindex UNSET; Program

@geindex NO_UNSET; Program

@geindex NOUNSET; Program

@geindex parameters@comma{} substituting unset; Command

@geindex unset parameters@comma{} substituting; Command

@code{UNSET} (@code{+u}, ksh: @code{+u}) <K> <S> <Z>

@quotation

Treat unset parameters as if they were empty when substituting, and as if
they were zero when reading their values in arithmetic expansion and
arithmetic commands.
Otherwise they are treated as an error.
@end quotation

@geindex WARN_CREATE_GLOBAL; Program

@geindex NO_WARN_CREATE_GLOBAL; Program

@geindex WARNCREATEGLOBAL; Program

@geindex NOWARNCREATEGLOBAL; Program

@geindex parameters@comma{} warning when created globally; Command

@code{WARN_CREATE_GLOBAL}

@quotation

Print a warning message when a global parameter is created in a function
by an assignment or in math context.
This often indicates that a parameter has not been
declared local when it should have been.  Parameters explicitly declared
global from within a function using @code{typeset -g} do not cause a warning.
Note that there is no warning when a local parameter is assigned to in
a nested function, which may also indicate an error.
@end quotation

@geindex WARN_NESTED_VAR; Program

@geindex NO_WARN_NESTED_VAR; Program

@geindex WARNNESTEDVAR; Program

@geindex NO_WARNNESTEDVAR; Program

@geindex parameters@comma{} warning when setting in enclosing scope; Command

@code{WARN_NESTED_VAR}

@quotation

Print a warning message when an existing parameter from an
enclosing function scope, or global, is set in a function
by an assignment or in math context.  Assignment to shell
special parameters does not cause a warning.  This is the companion
to @code{WARN_CREATE_GLOBAL} as in this case the warning is only
printed when a parameter is `not' created.  Where possible,
use of @code{typeset -g} to set the parameter suppresses the error,
but note that this needs to be used every time the parameter is set.
To restrict the effect of this option to a single function scope,
use @code{functions -W}.

For example, the following code produces a warning for the assignment
inside the function @code{nested} as that overrides the value within
@code{toplevel}

@example
 toplevel() @{
   local foo="in fn"
   nested
 @}
 nested() @{
      foo="in nested"
 @}
 setopt warn_nested_var
 toplevel
@end example
@end quotation

@node History,Initialisation,Expansion and Globbing,Description of Options
@anchor{Zsh/options history}@anchor{a0}
@subsection History


@geindex APPEND_HISTORY; Program

@geindex NO_APPEND_HISTORY; Program

@geindex APPENDHISTORY; Program

@geindex NOAPPENDHISTORY; Program

@geindex history@comma{} appending to a file; Command

@code{APPEND_HISTORY} <D>

@quotation

If this is set, zsh sessions will append their history list to
the history file, rather than replace it. Thus, multiple parallel
zsh sessions will all have the new entries from their history lists
added to the history file, in the order that they exit.
The file will still be periodically re-written to trim it when the
number of lines grows 20% beyond the value specified by
@code{$SAVEHIST} (see also the @code{HIST_SAVE_BY_COPY} option).
@end quotation

@geindex BANG_HIST; Program

@geindex NO_BANG_HIST; Program

@geindex BANGHIST; Program

@geindex NOBANGHIST; Program

@geindex history@comma{} enable substitution; Command

@geindex enable history substitution; Command

@code{BANG_HIST} (@code{+K}) <C> <Z>

@quotation

Perform textual history expansion, `csh'-style,
treating the character @code{!} specially.
@end quotation

@geindex EXTENDED_HISTORY; Program

@geindex NO_EXTENDED_HISTORY; Program

@geindex EXTENDEDHISTORY; Program

@geindex NOEXTENDEDHISTORY; Program

@geindex history@comma{} timestamping; Command

@code{EXTENDED_HISTORY} <C>

@quotation

Save each command’s beginning timestamp (in seconds since the epoch)
and the duration (in seconds) to the history file.  The format of
this prefixed data is:

@code{:} @var{<beginning time>}@code{:}@var{<elapsed seconds>}@code{;}@var{<command>}.
@end quotation

@geindex HIST_ALLOW_CLOBBER; Program

@geindex NO_HIST_ALLOW_CLOBBER; Program

@geindex HISTALLOWCLOBBER; Program

@geindex NOHISTALLOWCLOBBER; Program

@code{HIST_ALLOW_CLOBBER}

@quotation

Add @code{|} to output redirections in the history.  This allows history
references to clobber files even when @code{CLOBBER} is unset.
@end quotation

@geindex HIST_BEEP; Program

@geindex NO_HIST_BEEP; Program

@geindex HISTBEEP; Program

@geindex NOHISTBEEP; Program

@geindex history beeping; Command

@geindex beep@comma{} history; Command

@code{HIST_BEEP} <D>

@quotation

Beep in ZLE when a widget attempts to access a history entry which
isn’t there.
@end quotation

@geindex HIST_EXPIRE_DUPS_FIRST; Program

@geindex NO_HIST_EXPIRE_DUPS_FIRST; Program

@geindex HISTEXPIREDUPSFIRST; Program

@geindex NOHISTEXPIREDUPSFIRST; Program

@geindex history@comma{} expiring duplicates; Command

@code{HIST_EXPIRE_DUPS_FIRST}

@quotation

If the internal history needs to be trimmed to add the current command line,
setting this option will cause the oldest history event that has a duplicate
to be lost before losing a unique event from the list.
You should be sure to set the value of @code{HISTSIZE} to a larger number
than @code{SAVEHIST} in order to give you some room for the duplicated
events, otherwise this option will behave just like
@code{HIST_IGNORE_ALL_DUPS} once the history fills up with unique events.
@end quotation

@geindex HIST_FCNTL_LOCK; Program

@geindex NO_HIST_FCNTL_LOCK; Program

@geindex HISTFCNTLLOCK; Program

@geindex NOHISTFCNTLLOCK; Program

@code{HIST_FCNTL_LOCK}

@quotation

When writing out the history file, by default zsh uses ad-hoc file locking
to avoid known problems with locking on some operating systems.  With this
option locking is done by means of the system’s @code{fcntl} call, where
this method is available.  On recent operating systems this may
provide better performance, in particular avoiding history corruption when
files are stored on NFS.
@end quotation

@geindex HIST_FIND_NO_DUPS; Program

@geindex NO_HIST_FIND_NO_DUPS; Program

@geindex HISTFINDNODUPS; Program

@geindex NOHISTFINDNODUPS; Program

@geindex history@comma{} ignoring duplicates in search; Command

@code{HIST_FIND_NO_DUPS}

@quotation

When searching for history entries in the line editor, do not display
duplicates of a line previously found, even if the duplicates are not
contiguous.
@end quotation

@geindex HIST_IGNORE_ALL_DUPS; Program

@geindex NO_HIST_IGNORE_ALL_DUPS; Program

@geindex HISTIGNOREALLDUPS; Program

@geindex NOHISTIGNOREALLDUPS; Program

@geindex history@comma{} ignoring all duplicates; Command

@code{HIST_IGNORE_ALL_DUPS}

@quotation

If a new command line being added to the history list duplicates an
older one, the older command is removed from the list (even if it is
not the previous event).
@end quotation

@geindex HIST_IGNORE_DUPS; Program

@geindex NO_HIST_IGNORE_DUPS; Program

@geindex HISTIGNOREDUPS; Program

@geindex NOHISTIGNOREDUPS; Program

@geindex history@comma{} ignoring duplicates; Command

@code{HIST_IGNORE_DUPS} (@code{-h})

@quotation

Do not enter command lines into the history list
if they are duplicates of the previous event.
@end quotation

@geindex HIST_IGNORE_SPACE; Program

@geindex NO_HIST_IGNORE_SPACE; Program

@geindex HISTIGNORESPACE; Program

@geindex NOHISTIGNORESPACE; Program

@geindex history@comma{} ignoring spaces; Command

@code{HIST_IGNORE_SPACE} (@code{-g})

@quotation

Remove command lines from the history list when the first character on
the line is a space, or when one of the expanded aliases contains a
leading space.  Only normal aliases (not global or suffix aliases)
have this behaviour.
Note that the command lingers in the internal history until the next
command is entered before it vanishes, allowing you to briefly reuse
or edit the line.  If you want to make it vanish right away without
entering another command, type a space and press return.
@end quotation

@geindex HIST_LEX_WORDS; Program

@geindex NO_HIST_LEX_WORDS; Program

@geindex HISTLEXWORDS; Program

@geindex NOHISTLEXWORDS; Program

@code{HIST_LEX_WORDS}

@quotation

By default, shell history that is read in from files is split into
words on all white space.  This means that arguments with quoted
whitespace are not correctly handled, with the consequence that
references to words in history lines that have been read from a file
may be inaccurate.  When this option is set, words read in from a
history file are divided up in a similar fashion to normal shell
command line handling.  Although this produces more accurately delimited
words, if the size of the history file is large this can be slow.  Trial
and error is necessary to decide.
@end quotation

@geindex HIST_NO_FUNCTIONS; Program

@geindex NO_HIST_NO_FUNCTIONS; Program

@geindex HISTNOFUNCTIONS; Program

@geindex NOHISTNOFUNCTIONS; Program

@code{HIST_NO_FUNCTIONS}

@quotation

Remove function definitions from the history list.
Note that the function lingers in the internal history until the next
command is entered before it vanishes, allowing you to briefly reuse
or edit the definition.
@end quotation

@geindex HIST_NO_STORE; Program

@geindex NO_HIST_NO_STORE; Program

@geindex HISTNOSTORE; Program

@geindex NOHISTNOSTORE; Program

@code{HIST_NO_STORE}

@quotation

Remove the @code{history} (@code{fc -l}) command from the history list
when invoked.
Note that the command lingers in the internal history until the next
command is entered before it vanishes, allowing you to briefly reuse
or edit the line.
@end quotation

@geindex HIST_REDUCE_BLANKS; Program

@geindex NO_HIST_REDUCE_BLANKS; Program

@geindex HISTREDUCEBLANKS; Program

@geindex NOHISTREDUCEBLANKS; Program

@code{HIST_REDUCE_BLANKS}

@quotation

Remove superfluous blanks from each command line
being added to the history list.
@end quotation

@geindex HIST_SAVE_BY_COPY; Program

@geindex NO_HIST_SAVE_BY_COPY; Program

@geindex HISTSAVEBYCOPY; Program

@geindex NOHISTSAVEBYCOPY; Program

@code{HIST_SAVE_BY_COPY} <D>

@quotation

When the history file is re-written, we normally write out a copy of
the file named @code{$HISTFILE.new} and then rename it over the old one.
However, if this option is unset, we instead truncate the old
history file and write out the new version in-place.  If one of the
history-appending options is enabled, this option only has an effect
when the enlarged history file needs to be re-written to trim it
down to size.  Disable this only if you have special needs, as doing
so makes it possible to lose history entries if zsh gets interrupted
during the save.

When writing out a copy of the history file, zsh preserves the old
file’s permissions and group information, but will refuse to write
out a new file if it would change the history file’s owner.
@end quotation

@geindex HIST_SAVE_NO_DUPS; Program

@geindex NO_HIST_SAVE_NO_DUPS; Program

@geindex HISTSAVENODUPS; Program

@geindex NOHISTSAVENODUPS; Program

@code{HIST_SAVE_NO_DUPS}

@quotation

When writing out the history file, older commands that duplicate
newer ones are omitted.
@end quotation

@geindex HIST_VERIFY; Program

@geindex NO_HIST_VERIFY; Program

@geindex HISTVERIFY; Program

@geindex NOHISTVERIFY; Program

@geindex history@comma{} verifying substitution; Command

@code{HIST_VERIFY}

@quotation

Whenever the user enters a line with history expansion,
don’t execute the line directly; instead, perform
history expansion and reload the line into the editing buffer.
@end quotation

@geindex INC_APPEND_HISTORY; Program

@geindex NO_INC_APPEND_HISTORY; Program

@geindex INCAPPENDHISTORY; Program

@geindex NOINCAPPENDHISTORY; Program

@geindex history@comma{} incremental appending to a file; Command

@code{INC_APPEND_HISTORY}

@quotation

This option works like @code{APPEND_HISTORY} except that new history lines
are added to the @code{$HISTFILE} incrementally (as soon as they are
entered), rather than waiting until the shell exits.
The file will still be periodically re-written to trim it when the
number of lines grows 20% beyond the value specified by
@code{$SAVEHIST} (see also the @code{HIST_SAVE_BY_COPY} option).
@end quotation

@geindex INC_APPEND_HISTORY_TIME; Program

@geindex NO_INC_APPEND_HISTORY_TIME; Program

@geindex INCAPPENDHISTORYTIME; Program

@geindex NOINCAPPENDHISTORYTIME; Program

@geindex history@comma{} incremental appending to a file with time; Command

@code{INC_APPEND_HISTORY_TIME}

@quotation

This option is a variant of @code{INC_APPEND_HISTORY} in which, where
possible, the history entry is written out to the file after the
command is finished, so that the time taken by the command is recorded
correctly in the history file in @code{EXTENDED_HISTORY} format.  This
means that the history entry will not be available immediately from
other instances of the shell that are using the same history file.

This option is only useful if @code{INC_APPEND_HISTORY} and
@code{SHARE_HISTORY} are turned off.  The three options should be
considered mutually exclusive.
@end quotation

@geindex SHARE_HISTORY; Program

@geindex NO_SHARE_HISTORY; Program

@geindex SHAREHISTORY; Program

@geindex NOSHAREHISTORY; Program

@geindex share history; Command

@geindex history@comma{} sharing; Command

@code{SHARE_HISTORY} <K>

@quotation

This option both imports new commands from the history file, and also
causes your typed commands to be appended to the history file (the
latter is like specifying @code{INC_APPEND_HISTORY}, which should be turned
off if this option is in effect).  The history lines are also output
with timestamps ala @code{EXTENDED_HISTORY} (which makes it easier to find
the spot where we left off reading the file after it gets re-written).

By default, history movement commands visit the imported lines as
well as the local lines, but you can toggle this on and off with the
set-local-history zle binding.  It is also possible to create a zle
widget that will make some commands ignore imported commands, and
some include them.

If you find that you want more control over when commands
get imported, you may wish to turn @code{SHARE_HISTORY} off,
@code{INC_APPEND_HISTORY} or @code{INC_APPEND_HISTORY_TIME} (see above) on,
and then manually import commands whenever you need them using @code{fc
-RI}.
@end quotation

@node Initialisation,Input/Output,History,Description of Options
@anchor{Zsh/options initialisation}@anchor{a1}
@subsection Initialisation


@geindex ALL_EXPORT; Program

@geindex NO_ALL_EXPORT; Program

@geindex ALLEXPORT; Program

@geindex NOALLEXPORT; Program

@geindex export@comma{} automatic; Command

@code{ALL_EXPORT} (@code{-a}, ksh: @code{-a})

@quotation

All parameters subsequently defined are automatically exported.
@end quotation

@geindex GLOBAL_EXPORT; Program

@geindex NO_GLOBAL_EXPORT; Program

@geindex GLOBALEXPORT; Program

@geindex NOGLOBALEXPORT; Program

@geindex environment@comma{} and local parameters; Command

@code{GLOBAL_EXPORT} <Z>

@quotation

If this option is set, passing the @code{-x} flag to the builtins @code{declare},
@code{float}, @code{integer}, @code{readonly} and @code{typeset} (but not @code{local})
will also set the @code{-g} flag;  hence parameters exported to
the environment will not be made local to the enclosing function, unless
they were already or the flag @code{+g} is given explicitly.  If the option is
unset, exported parameters will be made local in just the same way as any
other parameter.

This option is set by default for backward compatibility; it is not
recommended that its behaviour be relied upon.  Note that the builtin
@code{export} always sets both the @code{-x} and @code{-g} flags, and hence its
effect extends beyond the scope of the enclosing function; this is the
most portable way to achieve this behaviour.
@end quotation

@geindex exporting@comma{} and local parameters; Command

@geindex GLOBAL_RCS; Program

@geindex NO_GLOBAL_RCS; Program

@geindex GLOBALRCS; Program

@geindex NOGLOBALRCS; Program

@geindex startup files@comma{} global@comma{} inhibiting; Command

@geindex files@comma{} global startup@comma{} inhibiting; Command

@code{GLOBAL_RCS} (@code{+d}) <D>

@quotation

If this option is unset, the startup files @code{/etc/zprofile},
@code{/etc/zshrc}, @code{/etc/zlogin} and @code{/etc/zlogout} will not be run.  It
can be disabled and re-enabled at any time, including inside local startup
files (@code{.zshrc}, etc.).
@end quotation

@geindex RCS; Program

@geindex NO_RCS; Program

@geindex NORCS; Program

@geindex startup files@comma{} sourcing; Command

@code{RCS} (@code{+f}) <D>

@quotation

After @code{/etc/zshenv} is sourced on startup, source the
@code{.zshenv}, @code{/etc/zprofile}, @code{.zprofile},
@code{/etc/zshrc}, @code{.zshrc}, @code{/etc/zlogin}, @code{.zlogin}, and @code{.zlogout}
files, as described in @ref{e,,Startup/Shutdown Files}.
If this option is unset, the @code{/etc/zshenv} file is still sourced, but any
of the others will not be; it can be set at any time to prevent the
remaining startup files after the currently executing one from
being sourced.
@end quotation

@node Input/Output,Job Control,Initialisation,Description of Options
@anchor{Zsh/options input-output}@anchor{a2}
@subsection Input/Output


@geindex ALIASES; Program

@geindex NO_ALIASES; Program

@geindex NOALIASES; Program

@geindex aliases@comma{} expansion; Command

@code{ALIASES} <D>

@quotation

Expand aliases.
@end quotation

@geindex CLOBBER; Program

@geindex NO_CLOBBER; Program

@geindex NOCLOBBER; Program

@geindex clobbering@comma{} of files; Command

@geindex file clobbering@comma{} allowing; Command

@code{CLOBBER} (@code{+C}, ksh: @code{+C}) <D>

@quotation

Allows @code{>} redirection to truncate existing files.
Otherwise @code{>!} or @code{>|} must be used to truncate a file.

If the option is not set, and the option @code{APPEND_CREATE} is also
not set, @code{>>!} or @code{>>|} must be used to create a file.
If either option is set, @code{>>} may be used.
@end quotation

@geindex CLOBBER_EMPTY; Program

@geindex NO_CLOBBER_EMPTY; Program

@geindex CLOBBEREMPTY; Program

@geindex NOCLOBBEREMPTY; Program

@geindex clobbering@comma{} of empty files; Command

@geindex file clobbering@comma{} of empty files; Command

@code{CLOBBER_EMPTY}

@quotation

This option is only used if the option @code{CLOBBER} is not set: note that
it is set by default.

If this option is set, then regular files of zero length may be
overwritten (`clobbered’).  Note that it is possible another process
has written to the file between this test and use of the file by
the current process.  This option should therefore not be used in
cases where files to be clobbered may be written to asynchronously.
@end quotation

@geindex CORRECT; Program

@geindex NO_CORRECT; Program

@geindex NOCORRECT; Program

@geindex correction@comma{} spelling; Command

@geindex spelling correction; Command

@code{CORRECT} (@code{-0})

@quotation

Try to correct the spelling of commands.
Note that, when the @code{HASH_LIST_ALL} option is not set or when some
directories in the path are not readable, this may falsely report spelling
errors the first time some commands are used.

Refer to the shell variable @code{SPROMPT} for an explanation of the
@code{[nyae]} (no/yes/abort/edit) prompt that is offered.

The shell variable @code{CORRECT_IGNORE} may be set to a pattern to
match words that will never be offered as corrections.
@end quotation

@geindex CORRECT_ALL; Program

@geindex NO_CORRECT_ALL; Program

@geindex CORRECTALL; Program

@geindex NOCORRECTALL; Program

@code{CORRECT_ALL} (@code{-O})

@quotation

Try to correct the spelling of all arguments in a line, in order from
left to right, treating each as a file name.  Answering @code{a} or
@code{e} at any prompt stops all corrections, otherwise every correction
is prompted for.

The shell variable @code{CORRECT_IGNORE_FILE} may be set to a pattern to
match file names that will never be offered as corrections.
@end quotation

@geindex DVORAK; Program

@geindex NO_DVORAK; Program

@geindex NODVORAK; Program

@code{DVORAK}

@quotation

Use the Dvorak keyboard instead of the standard qwerty keyboard as a basis
for examining spelling mistakes for the @code{CORRECT} and @code{CORRECT_ALL}
options and the @code{spell-word} editor command.
@end quotation

@geindex FLOW_CONTROL; Program

@geindex NO_FLOW_CONTROL; Program

@geindex FLOWCONTROL; Program

@geindex NOFLOWCONTROL; Program

@geindex flow control; Command

@code{FLOW_CONTROL} <D>

@quotation

If this option is unset,
output flow control via start/stop characters (usually assigned to
^S/^Q) is disabled in the shell’s editor.
@end quotation

@geindex IGNORE_EOF; Program

@geindex NO_IGNORE_EOF; Program

@geindex IGNOREEOF; Program

@geindex NOIGNOREEOF; Program

@geindex EOF@comma{} ignoring; Command

@code{IGNORE_EOF} (@code{-7})

@quotation

Do not exit on end-of-file.  Require the use
of @code{exit} or @code{logout} instead.
However, ten consecutive EOFs will cause the shell to exit anyway,
to avoid the shell hanging if its tty goes away.

Also, if this option is set and the Zsh Line Editor is used, widgets
implemented by shell functions can be bound to EOF (normally
Control-D) without printing the normal warning message.  This works
only for normal widgets, not for completion widgets.
@end quotation

@geindex INTERACTIVE_COMMENTS; Program

@geindex NO_INTERACTIVE_COMMENTS; Program

@geindex INTERACTIVECOMMENTS; Program

@geindex NOINTERACTIVECOMMENTS; Program

@geindex comments@comma{} in interactive shells; Command

@code{INTERACTIVE_COMMENTS} (@code{-k}) <K> <S>

@quotation

Allow comments even in interactive shells.
@end quotation

@geindex HASH_CMDS; Program

@geindex NO_HASH_CMDS; Program

@geindex HASHCMDS; Program

@geindex NOHASHCMDS; Program

@geindex hashing@comma{} of commands; Command

@geindex command hashing; Command

@code{HASH_CMDS} <D>

@quotation

Note the location of each command the first time it is executed.
Subsequent invocations of the same command will use the
saved location, avoiding a path search.
If this option is unset, no path hashing is done at all.
However, when @code{CORRECT} is set, commands whose names do not appear in
the functions or aliases hash tables are hashed in order to avoid
reporting them as spelling errors.
@end quotation

@geindex HASH_DIRS; Program

@geindex NO_HASH_DIRS; Program

@geindex HASHDIRS; Program

@geindex NOHASHDIRS; Program

@geindex hashing@comma{} of directories; Command

@geindex directories@comma{} hashing; Command

@code{HASH_DIRS} <D>

@quotation

Whenever a command name is hashed, hash the directory containing it,
as well as all directories that occur earlier in the path.
Has no effect if neither @code{HASH_CMDS} nor @code{CORRECT} is set.
@end quotation

@geindex HASH_EXECUTABLES_ONLY; Program

@geindex NO_HASH_EXECUTABLES_ONLY; Program

@geindex HASHEXECUTABLESONLY; Program

@geindex NOHASHEXECUTABLESONLY; Program

@geindex hashing@comma{} of executables; Command

@geindex executables@comma{} hashing; Command

@code{HASH_EXECUTABLES_ONLY}

@quotation

When hashing commands because of @code{HASH_CMDS}, check that the
file to be hashed is actually an executable.  This option
is unset by default as if the path contains a large number of commands,
or consists of many remote files, the additional tests can take
a long time.  Trial and error is needed to show if this option is
beneficial.
@end quotation

@geindex MAIL_WARNING; Program

@geindex NO_MAIL_WARNING; Program

@geindex MAILWARNING; Program

@geindex NOMAILWARNING; Program

@geindex mail@comma{} warning of reading; Command

@code{MAIL_WARNING} (@code{-U})

@quotation

Print a warning message if a mail file has been
accessed since the shell last checked.
@end quotation

@geindex PATH_DIRS; Program

@geindex NO_PATH_DIRS; Program

@geindex PATHDIRS; Program

@geindex NOPATHDIRS; Program

@geindex path search@comma{} extended; Command

@code{PATH_DIRS} (@code{-Q})

@quotation

Perform a path search even on command names with slashes in them.
Thus if @code{/usr/local/bin} is in the user’s path, and he or she types
@code{X11/xinit}, the command @code{/usr/local/bin/X11/xinit} will be executed
(assuming it exists).
Commands explicitly beginning with @code{/}, @code{./} or @code{../}
are not subject to the path search.
This also applies to the @code{.} and @code{source} builtins.

Note that subdirectories of the current directory are always searched for
executables specified in this form.  This takes place before any search
indicated by this option, and regardless of whether @code{.} or the current
directory appear in the command search path.
@end quotation

@geindex PATH_SCRIPT; Program

@geindex NO_PATH_SCRIPT; Program

@geindex PATHSCRIPT; Program

@geindex NOPATHSCRIPT; Program

@geindex path search@comma{} for script argument to shell; Command

@code{PATH_SCRIPT} <K> <S>

@quotation

If this option is not set, a script passed as the first non-option argument
to the shell must contain the name of the file to open.  If this
option is set, and the script does not specify a directory path,
the script is looked for first in the current directory, then in the
command path.  See @ref{a3,,Invocation}.
@end quotation

@geindex PRINT_EIGHT_BIT; Program

@geindex NO_PRINT_EIGHT_BIT; Program

@geindex PRINTEIGHTBIT; Program

@geindex NOPRINTEIGHTBIT; Program

@geindex eight bit characters@comma{} printing; Command

@code{PRINT_EIGHT_BIT}

@quotation

Print eight bit characters literally in completion lists, etc.
This option is not necessary if your system correctly returns the
printability of eight bit characters (see @code{ctype(3)}).
@end quotation

@geindex PRINT_EXIT_VALUE; Program

@geindex NO_PRINT_EXIT_VALUE; Program

@geindex PRINTEXITVALUE; Program

@geindex NOPRINTEXITVALUE; Program

@geindex exit status@comma{} printing; Command

@code{PRINT_EXIT_VALUE} (@code{-1})

@quotation

Print the exit value of programs with non-zero exit status.
This is only available at the command line in interactive shells.
@end quotation

@geindex RC_QUOTES; Program

@geindex NO_RC_QUOTES; Program

@geindex RCQUOTES; Program

@geindex NORCQUOTES; Program

@geindex rc@comma{} quoting style; Command

@geindex quoting style@comma{} rc; Command

@code{RC_QUOTES}

@quotation

Allow the character sequence @code{'}’ to signify a single quote
within singly quoted strings.  Note this does not apply in quoted strings
using the format @code{$'}@var{…}@code{'}, where a backslashed single quote can
be used.
@end quotation

@geindex RM_STAR_SILENT; Program

@geindex NO_RM_STAR_SILENT; Program

@geindex RMSTARSILENT; Program

@geindex NORMSTARSILENT; Program

@geindex rm *@comma{} querying before; Command

@geindex querying before rm *; Command

@code{RM_STAR_SILENT} (@code{-H}) <K> <S>

@quotation

Do not query the user before executing @code{rm *} or @code{rm path/*}.
@end quotation

@geindex RM_STAR_WAIT; Program

@geindex NO_RM_STAR_WAIT; Program

@geindex RMSTARWAIT; Program

@geindex NORMSTARWAIT; Program

@geindex rm *@comma{} waiting before; Command

@geindex waiting before rm *; Command

@code{RM_STAR_WAIT}

@quotation

If querying the user before executing @code{rm *} or @code{rm path/*},
first wait ten seconds and ignore anything typed in that time.
This avoids the problem of reflexively answering `yes’ to the query
when one didn’t really mean it.  The wait and query can always be
avoided by expanding the @code{*} in ZLE (with tab).
@end quotation

@geindex SHORT_LOOPS; Program

@geindex NO_SHORT_LOOPS; Program

@geindex SHORTLOOPS; Program

@geindex NOSHORTLOOPS; Program

@code{SHORT_LOOPS} <C> <Z>

@quotation

Allow the short forms of @code{for}, @code{repeat}, @code{select},
@code{if}, and @code{function} constructs.
@end quotation

@geindex SHORT_REPEAT; Program

@geindex NO_SHORT_REPEAT; Program

@geindex SHORTREPEAT; Program

@geindex NOSHORTREPEAT; Program

@code{SHORT_REPEAT}

@quotation

Allow the short form @code{repeat} as @code{SHORT_LOOPS} but without enabling
it for the other constructs.
@end quotation

@geindex SUN_KEYBOARD_HACK; Program

@geindex NO_SUN_KEYBOARD_HACK; Program

@geindex SUNKEYBOARDHACK; Program

@geindex NOSUNKEYBOARDHACK; Program

@geindex sun keyboard@comma{} annoying; Command

@geindex annoying keyboard@comma{} sun; Command

@code{SUN_KEYBOARD_HACK} (@code{-L})

@quotation

If a line ends with a backquote, and there are an odd number
of backquotes on the line, ignore the trailing backquote.
This is useful on some keyboards where the return key is
too small, and the backquote key lies annoyingly close to it.
As an alternative the variable @code{KEYBOARD_HACK} lets you choose the
character to be removed.
@end quotation

@node Job Control,Prompting,Input/Output,Description of Options
@anchor{Zsh/options job-control}@anchor{a4}
@subsection Job Control


@geindex AUTO_CONTINUE; Program

@geindex NO_AUTO_CONTINUE; Program

@geindex AUTOCONTINUE; Program

@geindex NOAUTOCONTINUE; Program

@geindex jobs@comma{} continuing automatically; Command

@geindex continuing jobs automatically; Command

@code{AUTO_CONTINUE}

@quotation

With this option set, stopped jobs that are removed from the job table
with the @code{disown} builtin command are automatically sent a @code{CONT}
signal to make them running.
@end quotation

@geindex AUTO_RESUME; Program

@geindex NO_AUTO_RESUME; Program

@geindex AUTORESUME; Program

@geindex NOAUTORESUME; Program

@geindex jobs@comma{} resuming automatically; Command

@geindex resuming jobs automatically; Command

@code{AUTO_RESUME} (@code{-W})

@quotation

Treat single word simple commands without redirection
as candidates for resumption of an existing job.
@end quotation

@geindex BG_NICE; Program

@geindex NO_BG_NICE; Program

@geindex BGNICE; Program

@geindex NOBGNICE; Program

@geindex jobs@comma{} background priority; Command

@geindex background jobs@comma{} priority of; Command

@geindex priority of background jobs; Command

@code{BG_NICE} (@code{-6}) <C> <Z>

@quotation

Run all background jobs at a lower priority.  This option
is set by default.
@end quotation

@geindex CHECK_JOBS; Program

@geindex NO_CHECK_JOBS; Program

@geindex CHECKJOBS; Program

@geindex NOCHECKJOBS; Program

@geindex exiting@comma{} checking jobs when; Command

@geindex logging out@comma{} checking jobs when; Command

@code{CHECK_JOBS} <Z>

@quotation

Report the status of background and suspended jobs before exiting a shell
with job control; a second attempt to exit the shell will succeed.
@code{NO_CHECK_JOBS} is best used only in combination with @code{NO_HUP}, else
such jobs will be killed automatically.

The check is omitted if the commands run from the previous command line
included a @code{jobs} command, since it is assumed the user is aware that
there are background or suspended jobs.  A @code{jobs} command run from one
of the hook functions defined in @ref{a5,,Special Functions}
is not counted for this purpose.
@end quotation

@geindex CHECK_RUNNING_JOBS; Program

@geindex NO_CHECK_RUNNING_JOBS; Program

@geindex CHECKRUNNINGJOBS; Program

@geindex NOCHECKRUNNINGJOBS; Program

@geindex exiting@comma{} checking running jobs when; Command

@geindex logging out@comma{} checking running jobs when; Command

@code{CHECK_RUNNING_JOBS} <Z>

@quotation

Check for both running and suspended jobs when @code{CHECK_JOBS} is enabled.
When this option is disabled, zsh checks only for suspended jobs, which
matches the default behavior of bash.

This option has no effect unless @code{CHECK_JOBS} is set.
@end quotation

@geindex HUP; Program

@geindex NO_HUP; Program

@geindex NOHUP; Program

@geindex jobs@comma{} HUP; Command

@code{HUP} <Z>

@quotation

Send the @code{HUP} signal to running jobs when the
shell exits.
@end quotation

@geindex LONG_LIST_JOBS; Program

@geindex NO_LONG_LIST_JOBS; Program

@geindex LONGLISTJOBS; Program

@geindex NOLONGLISTJOBS; Program

@geindex jobs@comma{} list format; Command

@code{LONG_LIST_JOBS} (@code{-R})

@quotation

Print job notifications in the long format by default.
@end quotation

@geindex MONITOR; Program

@geindex NO_MONITOR; Program

@geindex NOMONITOR; Program

@geindex job control@comma{} allowing; Command

@code{MONITOR} (@code{-m}, ksh: @code{-m})

@quotation

Allow job control.  Set by default in interactive shells.
@end quotation

@geindex NOTIFY; Program

@geindex NO_NOTIFY; Program

@geindex NONOTIFY; Program

@geindex background jobs@comma{} notification; Command

@geindex notification of background jobs; Command

@code{NOTIFY} (@code{-5}, ksh: @code{-b}) <Z>

@quotation

Report the status of background jobs immediately, rather than
waiting until just before printing a prompt.
@end quotation

@geindex POSIX_JOBS; Program

@geindex POSIXJOBS; Program

@geindex NO_POSIX_JOBS; Program

@geindex NOPOSIXJOBS; Program

@geindex bg@comma{} output in POSIX format; Command

@geindex fg@comma{} output in POSIX format; Command

@geindex job control@comma{} in subshell; Command

@geindex jobs@comma{} output in subshell; Command

@code{POSIX_JOBS} <K> <S>

@quotation

This option makes job control more compliant with the POSIX standard.

When the option is not set, the @code{MONITOR} option is unset on entry to
subshells, so that job control is no longer active.  When the option is
set, the @code{MONITOR} option and job control remain active in the
subshell, but note that the subshell has no access to jobs in the parent
shell.

When the option is not set, jobs put in the background or foreground
with @code{bg} or @code{fg} are displayed with the same information that would
be reported by @code{jobs}.  When the option is set, only the text is
printed.  The output from @code{jobs} itself is not affected by the option.

When the option is not set, job information from the parent
shell is saved for output within a subshell (for example, within a
pipeline).  When the option is set, the output of @code{jobs} is empty
until a job is started within the subshell.

In previous versions of the shell, it was necessary to enable
@code{POSIX_JOBS} in order for the builtin command @code{wait} to return the
status of background jobs that had already exited.  This is no longer
the case.
@end quotation

@node Prompting,Scripts and Functions,Job Control,Description of Options
@anchor{Zsh/options prompting}@anchor{a6}
@subsection Prompting


@geindex PROMPT_BANG; Program

@geindex NO_PROMPT_BANG; Program

@geindex PROMPTBANG; Program

@geindex NOPROMPTBANG; Program

@geindex prompt@comma{} ! expansion; Command

@code{PROMPT_BANG} <K>

@quotation

If set, @code{!} is treated specially in prompt expansion.
See @ref{a7,,Expansion of Prompt Sequences}.
@end quotation

@geindex PROMPT_CR; Program

@geindex NO_PROMPT_CR; Program

@geindex PROMPTCR; Program

@geindex NOPROMPTCR; Program

@geindex prompt@comma{} with CR; Command

@code{PROMPT_CR} (@code{+V}) <D>

@quotation

Print a carriage return just before printing
a prompt in the line editor.  This is on by default as multi-line editing
is only possible if the editor knows where the start of the line appears.
@end quotation

@geindex PROMPT_SP; Program

@geindex NO_PROMPT_SP; Program

@geindex PROMPTSP; Program

@geindex NOPROMPTSP; Program

@geindex prompt@comma{} save partial lines; Command

@code{PROMPT_SP} <D>

@quotation

Attempt to preserve a partial line (i.e. a line that did not end with a
newline) that would otherwise be covered up by the command prompt due to
the @code{PROMPT_CR} option.  This works by outputting some cursor-control
characters, including a series of spaces, that should make the terminal
wrap to the next line when a partial line is present (note that this is
only successful if your terminal has automatic margins, which is typical).

When a partial line is preserved, by default you will see an inverse+bold
character at the end of the partial line:  a @code{%} for a normal user or
a @code{#} for root.  If set, the shell parameter @code{PROMPT_EOL_MARK} can be
used to customize how the end of partial lines are shown.

NOTE: if the @code{PROMPT_CR} option is not set, enabling this option will
have no effect.  This option is on by default.
@end quotation

@geindex PROMPT_PERCENT; Program

@geindex NO_PROMPT_PERCENT; Program

@geindex PROMPTPERCENT; Program

@geindex NOPROMPTPERCENT; Program

@geindex prompt@comma{} % expansion; Command

@code{PROMPT_PERCENT} <C> <Z>

@quotation

If set, @code{%} is treated specially in prompt expansion.
See @ref{a7,,Expansion of Prompt Sequences}.
@end quotation

@geindex PROMPT_SUBST; Program

@geindex NO_PROMPT_SUBST; Program

@geindex PROMPTSUBST; Program

@geindex NOPROMPTSUBST; Program

@geindex prompt@comma{} parameter expansion; Command

@code{PROMPT_SUBST} <K> <S>

@quotation

If set, `parameter expansion', `command substitution' and
`arithmetic expansion' are performed in prompts.  Substitutions
within prompts do not affect the command status.
@end quotation

@geindex TRANSIENT_RPROMPT; Program

@geindex NO_TRANSIENT_RPROMPT; Program

@geindex TRANSIENTRPROMPT; Program

@geindex NOTRANSIENTRPROMPT; Program

@code{TRANSIENT_RPROMPT}

@quotation

Remove any right prompt from display when accepting a command
line.  This may be useful with terminals with other cut/paste methods.
@end quotation

@node Scripts and Functions,Shell Emulation,Prompting,Description of Options
@anchor{Zsh/options scripts-and-functions}@anchor{a8}
@subsection Scripts and Functions


@geindex ALIAS_FUNC_DEF; Program

@geindex NO_ALIAS_FUNC_DEF; Program

@geindex ALIASFUNCDEF; Program

@geindex NOALIASFUNCDEF; Program

@geindex functions@comma{} defining with expanded aliases; Command

@geindex aliases@comma{} expanding in function definition; Command

@code{ALIAS_FUNC_DEF} <S>

@quotation

By default, zsh does not allow the definition of functions using
the @var{name} @code{()} syntax if @var{name} was expanded as an
alias: this causes an error.  This is usually the desired behaviour, as
otherwise the combination of an alias and a function based on the same
definition can easily cause problems.

When this option is set, aliases can be used for defining functions.

For example, consider the following definitions as they might
occur in a startup file.

@example
 alias foo=bar
 foo() @{
   print This probably does not do what you expect.
 @}
@end example

Here, @code{foo} is expanded as an alias to @code{bar} before the
@code{()} is encountered, so the function defined would be named
@code{bar}.  By default this is instead an error in native mode.  Note that
quoting any part of the function name, or using the keyword
@code{function}, avoids the problem, so is recommended when the function
name can also be an alias.
@end quotation

@geindex C_BASES; Program

@geindex NO_C_BASES; Program

@geindex CBASES; Program

@geindex NOCBASES; Program

@geindex bases@comma{} output in C format; Command

@geindex hexadecimal@comma{} output in C format; Command

@geindex octal@comma{} output in C format; Command

@code{C_BASES}

@quotation

Output hexadecimal numbers in the standard C format, for example @code{0xFF}
instead of the usual @code{16#FF}.  If the option @code{OCTAL_ZEROES} is also
set (it is not by default), octal numbers will be treated similarly and
hence appear as @code{077} instead of @code{8#77}.  This option has no effect
on the choice of the output base, nor on the output of bases other than
hexadecimal and octal.  Note that these formats will be understood on input
irrespective of the setting of @code{C_BASES}.
@end quotation

@geindex C_PRECEDENCES; Program

@geindex NO_C_PRECEDENCES; Program

@geindex CPRECEDENCES; Program

@geindex NOCPRECEDENCES; Program

@geindex precedence@comma{} operator; Command

@geindex operator precedence; Command

@code{C_PRECEDENCES}

@quotation

This alters the precedence of arithmetic operators to be more
like C and other programming languages;
@ref{a9,,Arithmetic Evaluation}
has an explicit list.
@end quotation

@geindex DEBUG_BEFORE_CMD; Program

@geindex NO_DEBUG_BEFORE_CMD; Program

@geindex DEBUGBEFORECMD; Program

@geindex NODEBUGBEFORECMD; Program

@geindex traps@comma{} DEBUG@comma{} before or after command; Command

@geindex DEBUG trap@comma{} before or after command; Command

@code{DEBUG_BEFORE_CMD} <D>

@quotation

Run the @code{DEBUG} trap before each command; otherwise it is run after
each command.  Setting this option mimics the behaviour of ksh 93; with
the option unset the behaviour is that of ksh 88.
@end quotation

@geindex ERR_EXIT; Program

@geindex NO_ERR_EXIT; Program

@geindex ERREXIT; Program

@geindex NOERREXIT; Program

@geindex exit status@comma{} trapping; Command

@code{ERR_EXIT} (@code{-e}, ksh: @code{-e})

@quotation

If a command has a non-zero exit status, execute the @code{ZERR}
trap, if set, and exit.

The option is ignored when executing the commands following @code{while},
@code{until}, @code{if}, or @code{elif}, a pipeline beginning with @code{!}, or
any command other than the last in command list containing @code{&&} or
@code{||}.  Hence neither @code{if foo; then true; fi}, nor @code{foo &&
true `@w{`}trigger exit when} foo`@w{`} returns with a non-zero exit status.
Note that if @code{foo} is a function, the option is also ignored during
its whole execution.

The option is also ignored when executing a complex command (@code{if},
@code{for}, @code{while}, @code{until}, @code{repeat}, @code{case}, @code{select},
@code{always}, or a list in braces) if its exit status comes from a
command executed while the option is ignored. Hence, the @code{if}
command in @code{if true; then false && true; fi} does not trigger
exit.

Finally, the option is also ignored while running initialization
scripts and inside @code{DEBUG} traps.  In the latter case, the option is
handled specially: it is unset on entry to the trap.  If the option
@code{DEBUG_BEFORE_CMD} is set, as it is by default, and the option
@code{ERR_EXIT} is found to have been set on exit, then the command for
which the @code{DEBUG} trap is being executed is skipped.  The option is
restored after the trap exits.

Exiting due to @code{ERR_EXIT} has certain interactions with asynchronous
jobs noted in @ref{aa,,Signals}.

Note this behaviour is not disabled in interactive shells —
a non-zero status on the command line causes the shell to exit.
@end quotation

@geindex ERR_RETURN; Program

@geindex NO_ERR_RETURN; Program

@geindex ERRRETURN; Program

@geindex NOERRRETURN; Program

@geindex function return@comma{} on error; Command

@geindex return from function@comma{} on error; Command

@code{ERR_RETURN}

@quotation

If a command has a non-zero exit status, return immediately from the
enclosing function. Except as explained below, an implicit @code{return}
statement is executed following the same logic described for
@code{ERR_EXIT}. This will trigger an exit at the outermost level of a
non-interactive script.  At the top level of an interactive shell, it
will trigger a return to the command prompt; in other words, the
sequence of commands typed by the user may be thought of as a function
for this purpose.

Unlike for @code{ERR_EXIT}, when a function is called while the option is
being ignored, the option is NOT ignored during the execution of the
function.  Hence, if @code{foo} in @code{foo && true} is a function, code
inside it is considered separately: it may force a return from @code{foo}
(assuming the option remains set within @code{foo}).

Like for @code{ERR_EXIT}, the option is ignored inside @code{DEBUG} traps
but it’s not unset on entry to the trap and setting or unsetting it
inside the trap has no special effect.

If @code{ERR_RETURN} and @code{ERR_EXIT} are both set, it may happen that
both exit and return should be triggered. In that case only exit is
triggered.
@end quotation

@geindex EVAL_LINENO; Program

@geindex NO_EVAL_LINENO; Program

@geindex EVALLINENO; Program

@geindex NOEVALLINENO; Program

@geindex line number@comma{} in evaluated expression; Command

@code{EVAL_LINENO} <Z>

@quotation

If set, line numbers of expressions evaluated using the builtin @code{eval}
are tracked separately of the enclosing environment.  This applies both
to the parameter @code{LINENO} and the line number output by the prompt
escape @code{%i}.  If the option is set, the prompt escape @code{%N} will output
the string @code{(eval)} instead of the script or function name as an
indication.   (The two prompt escapes are typically used in the parameter
@code{PS4} to be output when the option @code{XTRACE} is set.)  If
@code{EVAL_LINENO} is unset, the line number of the surrounding script or
function is retained during the evaluation.
@end quotation

@geindex EXEC; Program

@geindex NO_EXEC; Program

@geindex NOEXEC; Program

@geindex command execution@comma{} enabling; Command

@code{EXEC} (@code{+n}, ksh: @code{+n}) <D>

@quotation

Do execute commands.  Without this option, commands are
read and checked for syntax errors, but not executed.
This option cannot be turned off in an interactive shell,
except when @code{-n} is supplied to the shell at startup.
@end quotation

@geindex FUNCTION_ARGZERO; Program

@geindex NO_FUNCTION_ARGZERO; Program

@geindex FUNCTIONARGZERO; Program

@geindex NOFUNCTIONARGZERO; Program

@geindex $0@comma{} setting; Command

@code{FUNCTION_ARGZERO} <C> <Z>

@quotation

When executing a shell function or sourcing a script, set @code{$0}
temporarily to the name of the function/script.  Note that toggling
@code{FUNCTION_ARGZERO} from on to off (or off to on) does not change the
current value of @code{$0}.  Only the state upon entry to the function or
script has an effect.  Compare @code{POSIX_ARGZERO}.
@end quotation

@geindex LOCAL_LOOPS; Program

@geindex NO_LOCAL_LOOPS; Program

@geindex LOCALLOOPS; Program

@geindex NOLOCALLOOPS; Program

@geindex break@comma{} inside function; Command

@geindex continue@comma{} inside function; Command

@geindex function@comma{} scope of break and continue; Command

@code{LOCAL_LOOPS}

@quotation

When this option is not set, the effect of @code{break} and @code{continue}
commands may propagate outside function scope, affecting loops in
calling functions.  When the option is set in a calling function, a
@code{break} or a @code{continue} that is not caught within a called function
(regardless of the setting of the option within that function)
produces a warning and the effect is cancelled.
@end quotation

@geindex LOCAL_OPTIONS; Program

@geindex NO_LOCAL_OPTIONS; Program

@geindex LOCALOPTIONS; Program

@geindex NOLOCALOPTIONS; Program

@code{LOCAL_OPTIONS} <K>

@quotation

If this option is set at the point of return from a shell function,
most options (including this one) which were in force upon entry to
the function are restored; the @code{PRIVILEGED} option is not restored.
Otherwise, only this option,
and the @code{LOCAL_LOOPS}, @code{XTRACE} and @code{PRINT_EXIT_VALUE} options are
restored.  Hence if this is explicitly unset by a shell function the
other options in force at the point of return will remain so.
A shell function can also guarantee itself a known shell configuration
with a formulation like @code{emulate -L zsh}; the @code{-L} activates
@code{LOCAL_OPTIONS}.
@end quotation

@geindex LOCAL_PATTERNS; Program

@geindex NO_LOCAL_PATTERNS; Program

@geindex LOCALPATTERNS; Program

@geindex NOLOCALPATTERNS; Program

@code{LOCAL_PATTERNS}

@quotation

If this option is set at the point of return from a shell function,
the state of pattern disables, as set with the builtin command
@code{disable -p}, is restored to what it was when the function was
entered.  The behaviour of this option is similar to the effect
of @code{LOCAL_OPTIONS} on options; hence @code{emulate -L sh} (or
indeed any other emulation with the @code{-L} option) activates
@code{LOCAL_PATTERNS}.
@end quotation

@geindex LOCAL_TRAPS; Program

@geindex NO_LOCAL_TRAPS; Program

@geindex LOCALTRAPS; Program

@geindex NOLOCALTRAPS; Program

@code{LOCAL_TRAPS} <K>

@quotation

If this option is set when a signal trap is set inside a function, then the
previous status of the trap for that signal will be restored when the
function exits.  Note that this option must be set `prior' to altering the
trap behaviour in a function; unlike @code{LOCAL_OPTIONS}, the value on exit
from the function is irrelevant.  However, it does not need to be set
before any global trap for that to be correctly restored by a function.
For example,

@example
 unsetopt localtraps
 trap - INT
 fn() @{ setopt localtraps; trap '@w{'} INT; sleep 3; @}
@end example

will restore normal handling of @code{SIGINT} after the function exits.
@end quotation

@geindex MULTI_FUNC_DEF; Program

@geindex NO_MULTI_FUNC_DEF; Program

@geindex MULTIFUNCDEF; Program

@geindex NOMULTIFUNCDEF; Program

@code{MULTI_FUNC_DEF} <Z>

@quotation

Allow definitions of multiple functions at once in the form @code{fn1
fn2}@var{…`}`()`@w{`}; if the option is not set, this causes
a parse error.  Definition of multiple functions with the @code{function}
keyword is always allowed.  Multiple function definitions are not often
used and can cause obscure errors.

Note that no error is raised if multiple functions are defined as a
result of a set of names that were originally read as a single word on
the command line, for example @code{TRAP@{INT,QUIT@}}.  Although there are
no plans to change this behaviour at present, it is not guaranteed.
@end quotation

@geindex MULTIOS; Program

@geindex NO_MULTIOS; Program

@geindex NOMULTIOS; Program

@code{MULTIOS} <Z>

@quotation

Perform implicit `tee's or `cat's when multiple
redirections are attempted (see @ref{ab,,Redirection}).
@end quotation

@geindex OCTAL_ZEROES; Program

@geindex NO_OCTAL_ZEROES; Program

@geindex OCTALZEROES; Program

@geindex NOOCTALZEROES; Program

@geindex octal@comma{} arithmetic expressions; Command

@code{OCTAL_ZEROES} <S>

@quotation

Interpret any integer constant beginning with a 0 as octal, per IEEE Std
1003.2-1992 (ISO 9945-2:1993).  This is not enabled by default as it
causes problems with parsing of, for example, date and time strings with
leading zeroes.

Sequences of digits indicating a numeric base such as the @code{08}
component in @code{08#77} are always interpreted as decimal, regardless
of leading zeroes.
@end quotation

@geindex PIPE_FAIL; Program

@geindex NO_PIPE_FAIL; Program

@geindex PIPEFAIL; Program

@geindex NOPIPEFAIL; Program

@geindex exit status from pipeline; Command

@geindex status@comma{} on exit from pipeline; Command

@geindex pipeline@comma{} exit status from; Command

@code{PIPE_FAIL}

@quotation

By default, when a pipeline exits the exit status recorded by the shell
and returned by the shell variable @code{$?} reflects that of the
rightmost element of a pipeline.  If this option is set, the exit status
instead reflects the status of the rightmost element of the pipeline
that was non-zero, or zero if all elements exited with zero status.
@end quotation

@geindex SOURCE_TRACE; Program

@geindex NO_SOURCE_TRACE; Program

@geindex SOURCETRACE; Program

@geindex NOSOURCETRACE; Program

@code{SOURCE_TRACE}

@quotation

If set, zsh will print an informational message announcing the name of
each file it loads.  The format of the output is similar to that
for the @code{XTRACE} option, with the message @code{<sourcetrace>}.
A file may be loaded by the shell itself when it
starts up and shuts down (@code{Startup/Shutdown Files}) or by the use of
the @code{source} and @code{dot} builtin commands.
@end quotation

@geindex TYPESET_SILENT; Program

@geindex NO_TYPESET_SILENT; Program

@geindex TYPESETSILENT; Program

@geindex NOTYPESETSILENT; Program

@code{TYPESET_SILENT}

@quotation

If this is unset, executing any of the @code{typeset} family of
commands with no options and a list of parameters that have no values
to be assigned but already exist will display the value of the parameter.
If the option is set, they will only be shown when parameters are selected
with the @code{-m} option.  The option @code{-p} is available whether or not
the option is set.
@end quotation

@geindex TYPESET_TO_UNSET; Program

@geindex NO_TYPESET_TO_UNSET; Program

@geindex TYPESETTOUNSET; Program

@geindex NOTYPESETTOUNSET; Program

@code{TYPESET_TO_UNSET} <K> <S>

@quotation

When declaring a new parameter with any of the @code{typeset} family of
related commands, the parameter remains unset unless and until a
value is explicitly assigned to it, either in the @code{typeset} command
itself or as a later assignment statement.
@end quotation

@geindex VERBOSE; Program

@geindex NO_VERBOSE; Program

@geindex NOVERBOSE; Program

@geindex tracing@comma{} of input lines; Command

@geindex input@comma{} tracing; Command

@code{VERBOSE} (@code{-v}, ksh: @code{-v})

@quotation

Print shell input lines as they are read.
@end quotation

@geindex XTRACE; Program

@geindex NO_XTRACE; Program

@geindex NOXTRACE; Program

@geindex tracing@comma{} of commands; Command

@geindex commands@comma{} tracing; Command

@code{XTRACE} (@code{-x}, ksh: @code{-x})

@quotation

Print commands and their arguments as they are executed.  The
output is preceded by the value of @code{$PS4}, formatted as described
in @ref{a7,,Expansion of Prompt Sequences}.
@end quotation

@node Shell Emulation,Shell State<2>,Scripts and Functions,Description of Options
@anchor{Zsh/options shell-emulation}@anchor{ac}
@subsection Shell Emulation


@geindex APPEND_CREATE; Program

@geindex NO_APPEND_CREATE; Program

@geindex APPENDCREATE; Program

@geindex NOAPPENDCREATE; Program

@geindex clobbering@comma{} POSIX compatibility; Command

@geindex file clobbering@comma{} POSIX compatibility; Command

@geindex no clobber@comma{} POSIX compatible; Command

@code{APPEND_CREATE} <K> <S>

@quotation

This option only applies when @code{NO_CLOBBER} (-@code{C}) is in effect.

If this option is not set, the shell will report an error when a
append redirection (@code{>>}) is used on a file that does not already
exists (the traditional zsh behaviour of @code{NO_CLOBBER}).  If the option
is set, no error is reported (POSIX behaviour).
@end quotation

@geindex BASH_REMATCH; Program

@geindex NO_BASH_REMATCH; Program

@geindex BASHREMATCH; Program

@geindex NOBASHREMATCH; Program

@geindex bash@comma{} BASH_REMATCH variable; Command

@geindex regexp@comma{} bash BASH_REMATCH variable; Command

@code{BASH_REMATCH}

@quotation

When set, matches performed with the @code{=~} operator will set the
@code{BASH_REMATCH} array variable, instead of the default @code{MATCH} and
@code{match} variables.  The first element of the @code{BASH_REMATCH} array
will contain the entire matched text and subsequent elements will contain
extracted substrings.  This option makes more sense when @code{KSH_ARRAYS} is
also set, so that the entire matched portion is stored at index 0 and the
first substring is at index 1.  Without this option, the @code{MATCH} variable
contains the entire matched text and the @code{match} array variable contains
substrings.
@end quotation

@geindex BSD_ECHO; Program

@geindex NO_BSD_ECHO; Program

@geindex BSDECHO; Program

@geindex NOBSDECHO; Program

@geindex echo@comma{} BSD compatible; Command

@code{BSD_ECHO} <S>

@quotation

Make the @code{echo} builtin compatible with the BSD @code{echo(1)} command.
This disables backslashed escape sequences in echo strings unless the
@code{-e} option is specified.
@end quotation

@geindex CONTINUE_ON_ERROR; Program

@geindex NO_CONTINUE_ON_ERROR; Program

@geindex CONTINUEONERROR; Program

@geindex NOCONTINUEONERROR; Program

@geindex error@comma{} option to continue script on; Command

@code{CONTINUE_ON_ERROR}

@quotation

If a fatal error is encountered (see @ref{ad,,Errors}),
and the code is running
in a script, the shell will resume execution at the next statement
in the script at the top level, in other words outside all functions
or shell constructs such as loops and conditions.  This mimics the
behaviour of interactive shells, where the shell returns to the
line editor to read a new command; it was the normal behaviour in versions
of zsh before 5.0.1.
@end quotation

@geindex CSH_JUNKIE_HISTORY; Program

@geindex NO_CSH_JUNKIE_HISTORY; Program

@geindex CSHJUNKIEHISTORY; Program

@geindex NOCSHJUNKIEHISTORY; Program

@geindex csh@comma{} history style; Command

@geindex history style@comma{} csh; Command

@code{CSH_JUNKIE_HISTORY} <C>

@quotation

A history reference without an event specifier will always refer to the
previous command.  Without this option, such a history reference refers
to the same event as the previous history reference on the current
command line, defaulting to the previous command.
@end quotation

@geindex CSH_JUNKIE_LOOPS; Program

@geindex NO_CSH_JUNKIE_LOOPS; Program

@geindex CSHJUNKIELOOPS; Program

@geindex NOCSHJUNKIELOOPS; Program

@geindex csh@comma{} loop style; Command

@geindex loop style@comma{} csh; Command

@code{CSH_JUNKIE_LOOPS} <C>

@quotation

Allow loop bodies to take the form @var{list}@code{; end} instead of
@code{do} @var{list}@code{; done}.
@end quotation

@geindex CSH_JUNKIE_QUOTES; Program

@geindex NO_CSH_JUNKIE_QUOTES; Program

@geindex CSHJUNKIEQUOTES; Program

@geindex NOCSHJUNKIEQUOTES; Program

@geindex csh@comma{} quoting style; Command

@geindex quoting style@comma{} csh; Command

@code{CSH_JUNKIE_QUOTES} <C>

@quotation

Changes the rules for single- and double-quoted text to match that of
`csh'.  These require that embedded newlines be preceded by a backslash;
unescaped newlines will cause an error message.
In double-quoted strings, it is made impossible to escape @code{$}, @code{`\}`’
or @code{"} (and @code{\} itself no longer needs escaping).
Command substitutions are only expanded once, and cannot be nested.
@end quotation

@geindex CSH_NULLCMD; Program

@geindex NO_CSH_NULLCMD; Program

@geindex CSHNULLCMD; Program

@geindex NOCSHNULLCMD; Program

@geindex NULLCMD@comma{} ignoring; Variable

@geindex READNULLCMD@comma{} ignoring; Variable

@geindex redirections with no command@comma{} csh; Command

@geindex csh@comma{} redirections with no command; Command

@code{CSH_NULLCMD} <C>

@quotation

Do not use the values of @code{NULLCMD} and @code{READNULLCMD}
when running redirections with no command.  This make
such redirections fail (see @ref{ab,,Redirection}).
@end quotation

@geindex KSH_ARRAYS; Program

@geindex NO_KSH_ARRAYS; Program

@geindex KSHARRAYS; Program

@geindex NOKSHARRAYS; Program

@geindex arrays@comma{} ksh style; Command

@geindex array style@comma{} ksh; Command

@geindex ksh@comma{} array style; Command

@code{KSH_ARRAYS} <K> <S>

@quotation

Emulate `ksh' array handling as closely as possible.  If this option
is set, array elements are numbered from zero, an array parameter
without subscript refers to the first element instead of the whole array,
and braces are required to delimit a subscript (@code{$@{path[2]@}} rather
than just @code{$path[2]}) or to apply modifiers to any parameter
(@code{$@{PWD:h@}} rather than @code{$PWD:h}).
@end quotation

@geindex KSH_AUTOLOAD; Program

@geindex NO_KSH_AUTOLOAD; Program

@geindex KSHAUTOLOAD; Program

@geindex NOKSHAUTOLOAD; Program

@code{KSH_AUTOLOAD} <K> <S>

@quotation

Emulate `ksh' function autoloading.  This means that when a function is
autoloaded, the corresponding file is merely executed, and must define
the function itself.  (By default, the function is defined to the contents
of the file.  However, the most common `ksh'-style case - of the file
containing only a simple definition of the function - is always handled
in the `ksh'-compatible manner.)
@end quotation

@geindex KSH_OPTION_PRINT; Program

@geindex NO_KSH_OPTION_PRINT; Program

@geindex KSHOPTIONPRINT; Program

@geindex NOKSHOPTIONPRINT; Program

@geindex option printing@comma{} ksh style; Command

@geindex option printing style@comma{} ksh; Command

@geindex ksh@comma{} option printing style; Command

@code{KSH_OPTION_PRINT} <K>

@quotation

Alters the way options settings are printed: instead of separate lists of
set and unset options, all options are shown, marked `on’ if
they are in the non-default state, `off’ otherwise.
@end quotation

@geindex KSH_TYPESET; Program

@geindex NO_KSH_TYPESET; Program

@geindex KSHTYPESET; Program

@geindex NOKSHTYPESET; Program

@geindex argument splitting@comma{} in typeset etc.; Command

@geindex ksh@comma{} argument splitting in typeset; Command

@code{KSH_TYPESET}

@quotation

This option is now obsolete: a better approximation to the behaviour of
other shells is obtained with the reserved word interface to
@code{declare}, @code{export}, @code{float}, @code{integer}, @code{local}, @code{readonly}
and @code{typeset}.  Note that the option is only applied when the reserved
word interface is `not' in use.

Alters the way arguments to the @code{typeset} family of commands, including
@code{declare}, @code{export}, @code{float}, @code{integer}, @code{local} and
@code{readonly}, are processed.  Without this option, zsh will perform normal
word splitting after command and parameter expansion in arguments of an
assignment; with it, word splitting does not take place in those cases.
@end quotation

@geindex KSH_ZERO_SUBSCRIPT; Program

@geindex NO_KSH_ZERO_SUBSCRIPT; Program

@geindex KSHZEROSUBSCRIPT; Program

@geindex NOKSHZEROSUBSCRIPT; Program

@geindex arrays@comma{} behaviour of index zero; Command

@code{KSH_ZERO_SUBSCRIPT}

@quotation

Treat use of a subscript of value zero in array or string expressions as a
reference to the first element, i.e. the element that usually has the
subscript 1.  Ignored if @code{KSH_ARRAYS} is also set.

If neither this option nor @code{KSH_ARRAYS} is set, accesses to an element of
an array or string with subscript zero return an empty element or string,
while attempts to set element zero of an array or string are treated as an
error.  However, attempts to set an otherwise valid subscript range that
includes zero will succeed.  For example, if @code{KSH_ZERO_SUBSCRIPT} is not
set,

@example
 array[0]=(element)
@end example

is an error, while

@example
 array[0,1]=(element)
@end example

is not and will replace the first element of the array.

This option is for compatibility with older versions of the shell and
is not recommended in new code.
@end quotation

@geindex POSIX_ALIASES; Program

@geindex NO_POSIX_ALIASES; Program

@geindex POSIXALIASES; Program

@geindex NOPOSIXALIASES; Program

@code{POSIX_ALIASES} <K> <S>

@quotation

When this option is set, reserved words are not candidates for
alias expansion:  it is still possible to declare any of them as an alias,
but the alias will never be expanded.  Reserved words are described in
@ref{ae,,Reserved Words}.

Alias expansion takes place while text is being read; hence when this
option is set it does not take effect until the end of any function or
other piece of shell code parsed as one unit.  Note this may
cause differences from other shells even when the option is in
effect.  For example, when running a command with @code{zsh -c},
or even @code{zsh -o posixaliases -c}, the entire command argument is parsed
as one unit, so aliases defined within the argument are not available even
in later lines.  If in doubt, avoid use of aliases in non-interactive
code.
@end quotation

@geindex POSIX_ARGZERO; Program

@geindex NO_POSIX_ARGZERO; Program

@geindex POSIXARGZERO; Program

@geindex NOPOSIXARGZERO; Program

@geindex $0@comma{} using; Command

@code{POSIX_ARGZERO}

@quotation

This option may be used to temporarily disable @code{FUNCTION_ARGZERO} and
thereby restore the value of @code{$0} to the name used to invoke the shell
(or as set by the @code{-c} command line option).  For compatibility with
previous versions of the shell, emulations use @code{NO_FUNCTION_ARGZERO}
instead of @code{POSIX_ARGZERO}, which may result in unexpected scoping of
@code{$0} if the emulation mode is changed inside a function or script.
To avoid this, explicitly enable @code{POSIX_ARGZERO} in the @code{emulate}
command:

@example
 emulate sh -o POSIX_ARGZERO
@end example

Note that @code{NO_POSIX_ARGZERO} has no effect unless @code{FUNCTION_ARGZERO}
was already enabled upon entry to the function or script.
@end quotation

@geindex POSIX_BUILTINS; Program

@geindex NO_POSIX_BUILTINS; Program

@geindex POSIXBUILTINS; Program

@geindex NOPOSIXBUILTINS; Program

@code{POSIX_BUILTINS} <K> <S>

@quotation

When this option is set the @code{command} builtin can be used to execute
shell builtin commands.  Parameter assignments specified before shell
functions and special builtins are kept after the command completes unless
the special builtin is prefixed with the @code{command} builtin.  Special
builtins are
@code{.},
@code{:},
@code{break},
@code{continue},
@code{declare},
@code{eval},
@code{exit},
@code{export},
@code{integer},
@code{local},
@code{readonly},
@code{return},
@code{set},
@code{shift},
@code{source},
@code{times},
@code{trap} and
@code{unset}.

In addition, various error conditions associated with the above builtins
or @code{exec} cause a non-interactive shell to exit and an interactive
shell to return to its top-level processing.

Furthermore, functions and shell builtins are not executed after
an @code{exec} prefix; the command to be executed must be an external
command found in the path.

Moreover, the warning and special exit code from
@code{[[ -o} @var{non_existent_option} @code{]]} are suppressed.

Other builtins may be affected as described in


Shell Builtin Commands

.
@end quotation

@geindex POSIX_IDENTIFIERS; Program

@geindex NO_POSIX_IDENTIFIERS; Program

@geindex POSIXIDENTIFIERS; Program

@geindex NOPOSIXIDENTIFIERS; Program

@geindex identifiers@comma{} non-portable characters in; Command

@geindex parameter names@comma{} non-portable characters in; Command

@code{POSIX_IDENTIFIERS} <K> <S>

@quotation

When this option is set, only the ASCII characters @code{a} to @code{z}, @code{A} to
@code{Z}, @code{0} to @code{9} and @code{_} may be used in identifiers (names
of shell parameters and modules).

In addition, setting this option limits the effect of parameter
substitution with no braces, so that the expression @code{$#} is treated as
the parameter @code{$#} even if followed by a valid parameter name.
When it is unset, zsh allows expressions of the form @code{$#}@var{name}
to refer to the length of @code{$}@var{name}, even for special variables,
for example in expressions such as @code{$#-} and @code{$#*}.

Another difference is that with the option set assignment to an
unset variable in arithmetic context causes the variable to be created
as a scalar rather than a numeric type.  So after @code{unset t; (( t = 3
))}, without`@w{`} POSIX_IDENTIFIERS @code{set} t`@w{`} has integer type, while with
it set it has scalar type.

When the option is unset and multibyte character support is enabled (i.e. it
is compiled in and the option @code{MULTIBYTE} is set), then additionally any
alphanumeric characters in the local character set may be used in
identifiers.  Note that scripts and functions written with this feature are
not portable, and also that both options must be set before the script
or function is parsed; setting them during execution is not sufficient
as the syntax @var{variable}@code{=}@var{value} has already been parsed as
a command rather than an assignment.

If multibyte character support is not compiled into the shell this option is
ignored; all octets with the top bit set may be used in identifiers.
This is non-standard but is the traditional zsh behaviour.
@end quotation

@geindex POSIX_STRINGS; Program

@geindex NO_POSIX_STRINGS; Program

@geindex POSIXSTRINGS; Program

@geindex NOPOSIXSTRINGS; Program

@geindex discarding embedded nulls in $'...'; Command

@geindex embedded nulls@comma{} in $'...'; Command

@geindex nulls@comma{} embedded in $'...'; Command

@code{POSIX_STRINGS} <K> <S>

@quotation

This option affects processing of quoted strings.  Currently it only
affects the behaviour of null characters, i.e. character 0 in the
portable character set corresponding to US ASCII.

When this option is not set, null characters embedded within strings
of the form @code{$'}@var{…}@code{'} are treated as ordinary characters. The
entire string is maintained within the shell and output to files where
necessary, although owing to restrictions of the library interface
the string is truncated at the null character in file names, environment
variables, or in arguments to external programs.

When this option is set, the @code{$'}@var{…}@code{'} expression is truncated at
the null character.  Note that remaining parts of the same string
beyond the termination of the quotes are not truncated.

For example, the command line argument @code{a$'b\0c'd} is treated with
the option off as the characters @code{a}, @code{b}, null, @code{c}, @code{d},
and with the option on as the characters @code{a}, @code{b}, @code{d}.
@end quotation

@geindex POSIX_TRAPS; Program

@geindex NO_POSIX_TRAPS; Program

@geindex POSIXTRAPS; Program

@geindex NOPOSIXTRAPS; Program

@geindex traps@comma{} on function exit; Command

@geindex traps@comma{} POSIX compatibility; Command

@code{POSIX_TRAPS} <K> <S>

@quotation

When this option is set, the usual zsh behaviour of executing
traps for @code{EXIT} on exit from shell functions is suppressed.
In that case, manipulating @code{EXIT} traps always alters the global
trap for exiting the shell; the @code{LOCAL_TRAPS} option is
ignored for the @code{EXIT} trap.

Also, a @code{return} statement executed in a trap with no argument passes
back from the function the value from the surrounding context, not from
code executed within the trap.

Furthermore, if a trap is set to be ignored, this state persists when
a subshell is entered.  Without the option, the trap would be reset to
its default state at this point.
@end quotation

@geindex SH_FILE_EXPANSION; Program

@geindex NO_SH_FILE_EXPANSION; Program

@geindex SHFILEEXPANSION; Program

@geindex NOSHFILEEXPANSION; Program

@geindex sh@comma{} expansion style; Command

@geindex expansion style@comma{} sh; Command

@code{SH_FILE_EXPANSION} <K> <S>

@quotation

Perform filename expansion (e.g., @code{~} expansion) `before'
parameter expansion, command substitution, arithmetic expansion
and brace expansion.
If this option is unset, it is performed `after'
brace expansion, so things like @code{~$USERNAME} and
@code{~@{pfalstad,rc@}} will work.
@end quotation

@geindex SH_NULLCMD; Program

@geindex NO_SH_NULLCMD; Program

@geindex SHNULLCMD; Program

@geindex NOSHNULLCMD; Program

@geindex NULLCMD@comma{} ignoring; Variable

@geindex READNULLCMD@comma{} ignoring; Variable

@geindex sh@comma{} redirections with no command; Command

@geindex ksh@comma{} redirections with no command; Command

@geindex redirections with no command@comma{} sh; Command

@geindex redirections with no command@comma{} ksh; Command

@code{SH_NULLCMD} <K> <S>

@quotation

Do not use the values of @code{NULLCMD} and @code{READNULLCMD}
when doing redirections, use @code{:} instead (see @ref{ab,,Redirection}).
@end quotation

@geindex SH_OPTION_LETTERS; Program

@geindex NO_SH_OPTION_LETTERS; Program

@geindex SHOPTIONLETTERS; Program

@geindex NOSHOPTIONLETTERS; Program

@geindex sh@comma{} single letter options style; Command

@geindex ksh@comma{} single letter options style; Command

@geindex single letter options@comma{} ksh style; Command

@geindex options@comma{} single letter@comma{} ksh style; Command

@code{SH_OPTION_LETTERS} <K> <S>

@quotation

If this option is set the shell tries to interpret single letter options
(which are used with @code{set} and @code{setopt}) like `ksh' does.
This also affects the value of the @code{-} special parameter.
@end quotation

@geindex SH_WORD_SPLIT; Program

@geindex NO_SH_WORD_SPLIT; Program

@geindex SHWORDSPLIT; Program

@geindex NOSHWORDSPLIT; Program

@geindex field splitting@comma{} sh style; Command

@geindex sh@comma{} field splitting style; Command

@code{SH_WORD_SPLIT} (@code{-y}) <K> <S>

@quotation

Causes field splitting to be performed on unquoted parameter expansions.
Note that this option has nothing to do with word splitting.
(See @ref{1a,,Parameter Expansion}.)
@end quotation

@geindex TRAPS_ASYNC; Program

@geindex NO_TRAPS_ASYNC; Program

@geindex TRAPSASYNC; Program

@geindex NOTRAPSASYNC; Program

@geindex traps@comma{} asynchronous; Command

@code{TRAPS_ASYNC}

@quotation

While waiting for a program to exit, handle signals and run traps
immediately.  Otherwise the trap is run after a child process has exited.
Note this does not affect the point at which traps are run for any case
other than when the shell is waiting for a child process.
@end quotation

@node Shell State<2>,Zle,Shell Emulation,Description of Options
@anchor{Zsh/options shell-state}@anchor{af}
@subsection Shell State


@geindex INTERACTIVE; Program

@geindex NO_INTERACTIVE; Program

@geindex NOINTERACTIVE; Program

@code{INTERACTIVE} (@code{-i}, ksh: @code{-i})

@quotation

This is an interactive shell.  This option is set upon initialisation if
the standard input is a tty and commands are being read from standard input.
(See the discussion of @code{SHIN_STDIN}.)
This heuristic may be overridden by specifying a state for this option
on the command line.
The value of this option can only be changed via flags supplied at
invocation of the shell.
It cannot be changed once zsh is running.
@end quotation

@geindex LOGIN; Program

@geindex NO_LOGIN; Program

@geindex NOLOGIN; Program

@code{LOGIN} (@code{-l}, ksh: @code{-l})

@quotation

This is a login shell.
If this option is not explicitly set, the shell becomes a login shell if
the first character of the @code{argv[0]} passed to the shell is a @code{-}.
@end quotation

@geindex PRIVILEGED; Program

@geindex NO_PRIVILEGED; Program

@geindex NOPRIVILEGED; Program

@geindex privileged mode; Command

@geindex mode@comma{} privileged; Command

@code{PRIVILEGED} (@code{-p}, ksh: @code{-p})

@quotation

Turn on privileged mode. Typically this is used when script is to be run
with elevated privileges. This should be done as follows directly with
the @code{-p} option to zsh so that it takes effect during startup.

@example
 #!/bin/zsh -p
@end example

The option is enabled automatically on startup if the effective user
(group) ID is not equal to the real user (group) ID. In this case,
turning the option off causes the effective user and group IDs to be set
to the real user and group IDs. Be aware that if that fails the shell may
be running with different IDs than was intended so a script should check
for failure and act accordingly, for example:

@example
 unsetopt privileged || exit
@end example

The @code{PRIVILEGED} option disables sourcing user startup files.
If zsh is invoked as @code{sh} or @code{ksh} with this option set,
@code{/etc/suid_profile} is sourced (after @code{/etc/profile} on interactive
shells). Sourcing @code{~/.profile} is disabled and the contents of the
@code{ENV} variable is ignored. This option cannot be changed using the
@code{-m} option of @code{setopt} and @code{unsetopt}, and changing it inside a
function always changes it globally regardless of the @code{LOCAL_OPTIONS}
option.
@end quotation

@geindex SHIN_STDIN; Program

@geindex NO_SHIN_STDIN; Program

@geindex SHINSTDIN; Program

@geindex NOSHINSTDIN; Program

@code{SHIN_STDIN} (@code{-s}, ksh: @code{-s})

@quotation

Commands are being read from the standard input.
Commands are read from standard input if no command is specified with
@code{-c} and no file of commands is specified.  If @code{SHIN_STDIN}
is set explicitly on the command line,
any argument that would otherwise have been
taken as a file to run will instead be treated as a normal positional
parameter.
Note that setting or unsetting this option on the command line does not
necessarily affect the state the option will have while the shell is
running - that is purely an indicator of whether or not commands are
`actually' being read from standard input.
The value of this option can only be changed via flags supplied at
invocation of the shell.
It cannot be changed once zsh is running.
@end quotation

@geindex SINGLE_COMMAND; Program

@geindex NO_SINGLE_COMMAND; Program

@geindex SINGLECOMMAND; Program

@geindex NOSINGLECOMMAND; Program

@geindex single command; Command

@geindex INTERACTIVE@comma{} use of; Program

@code{SINGLE_COMMAND} (@code{-t}, ksh: @code{-t})

@quotation

If the shell is reading from standard input, it exits after a single command
has been executed.  This also makes the shell non-interactive, unless the
@code{INTERACTIVE} option is explicitly set on the command line.
The value of this option can only be changed via flags supplied at
invocation of the shell.
It cannot be changed once zsh is running.
@end quotation

@node Zle,,Shell State<2>,Description of Options
@anchor{Zsh/options zle}@anchor{b0}
@subsection Zle


@geindex BEEP; Program

@geindex NO_BEEP; Program

@geindex NOBEEP; Program

@geindex beep@comma{} enabling; Command

@geindex enabling the beep; Command

@code{BEEP} (@code{+B}) <D>

@quotation

Beep on error in ZLE.
@end quotation

@geindex COMBINING_CHARS; Program

@geindex NO_COMBINING_CHARS; Program

@geindex COMBININGCHARS; Program

@geindex NOCOMBININGCHARS; Program

@geindex characters@comma{} (Unicode) combining; Command

@geindex combining characters (Unicode); Command

@geindex Unicode combining characters; Command

@code{COMBINING_CHARS}

@quotation

Assume that the terminal displays combining characters correctly.
Specifically, if a base alphanumeric character is followed by one or more
zero-width punctuation characters, assume that the zero-width characters
will be displayed as modifications to the base character within the
same width.  Not all terminals handle this.  If this option is not
set, zero-width characters are displayed separately with special
mark-up.

If this option is set, the pattern test @code{[[:WORD:]]} matches a
zero-width punctuation character on the assumption that it will be
used as part of a word in combination with a word character.
Otherwise the base shell does not handle combining characters specially.
@end quotation

@geindex EMACS; Program

@geindex NO_EMACS; Program

@geindex NOEMACS; Program

@code{EMACS}

@quotation

If ZLE is loaded, turning on this option has the equivalent effect
of @code{bindkey -e}.  In addition, the @code{VI} option is unset.
Turning it off has no effect.  The option setting is
not guaranteed to reflect the current keymap, and the @code{LOCALOPTIONS}
option does not work correctly. This option is provided only for
compatibility, and its use is highly discouraged.  @code{bindkey} is the
recommended interface.
@end quotation

@geindex OVERSTRIKE; Program

@geindex NO_OVERSTRIKE; Program

@geindex NOOVERSTRIKE; Program

@geindex editor@comma{} overstrike mode; Command

@geindex overstrike mode@comma{} of editor; Command

@code{OVERSTRIKE}

@quotation

Start up the line editor in overstrike mode.
@end quotation

@geindex SINGLE_LINE_ZLE; Program

@geindex NO_SINGLE_LINE_ZLE; Program

@geindex SINGLELINEZLE; Program

@geindex NOSINGLELINEZLE; Program

@geindex editor@comma{} single line mode; Command

@code{SINGLE_LINE_ZLE} (@code{-M}) <K>

@quotation

Use single-line command line editing instead of multi-line.

Note that although this is on by default in ksh emulation it only
provides superficial compatibility with the ksh line editor and
reduces the effectiveness of the zsh line editor.  As it has no
effect on shell syntax, many users may wish to disable this option
when using ksh emulation interactively.
@end quotation

@geindex VI; Program

@geindex NO_VI; Program

@geindex NOVI; Program

@code{VI}

@quotation

If ZLE is loaded, turning on this option has the equivalent effect
of @code{bindkey -v}.  In addition, the @code{EMACS} option is unset.
Turning it off has no effect.  The option setting is
not guaranteed to reflect the current keymap, and the @code{LOCALOPTIONS}
option does not work correctly. This option is provided only for
compatibility, and its use is highly discouraged.  @code{bindkey} is the
recommended interface.
@end quotation

@geindex ZLE; Program

@geindex NO_ZLE; Program

@geindex NOZLE; Program

@geindex editor@comma{} enabling; Command

@geindex enabling the editor; Command

@code{ZLE} (@code{-Z})

@quotation

Use the zsh line editor.  Set by default in interactive shells connected to
a terminal.
@end quotation

@c historic nodename: Option Aliases

@node Option Aliases,Single Letter Options,Description of Options,Options<2>
@anchor{Zsh/options option-aliases}@anchor{b1}
@section Option Aliases


@geindex options@comma{} aliases; Command

Some options have alternative names.  These aliases are never used for
output, but can be used just like normal option names when specifying
options to the shell.

@geindex BRACE_EXPAND; Program

@geindex NO_BRACE_EXPAND; Program

@geindex BRACEEXPAND; Program

@geindex NOBRACEEXPAND; Program

@code{BRACE_EXPAND}

@quotation

`NO_'@code{IGNORE_BRACES}
(ksh and bash compatibility)
@end quotation

@geindex DOT_GLOB; Program

@geindex NO_DOT_GLOB; Program

@geindex DOTGLOB; Program

@geindex NODOTGLOB; Program

@code{DOT_GLOB}

@quotation

@code{GLOB_DOTS}
(bash compatibility)
@end quotation

@geindex HASH_ALL; Program

@geindex NO_HASH_ALL; Program

@geindex HASHALL; Program

@geindex NOHASHALL; Program

@code{HASH_ALL}

@quotation

@code{HASH_CMDS}
(bash compatibility)
@end quotation

@geindex HIST_APPEND; Program

@geindex NO_HIST_APPEND; Program

@geindex HISTAPPEND; Program

@geindex NOHISTAPPEND; Program

@code{HIST_APPEND}

@quotation

@code{APPEND_HISTORY}
(bash compatibility)
@end quotation

@geindex HIST_EXPAND; Program

@geindex NO_HIST_EXPAND; Program

@geindex HISTEXPAND; Program

@geindex NOHISTEXPAND; Program

@code{HIST_EXPAND}

@quotation

@code{BANG_HIST}
(bash compatibility)
@end quotation

@geindex LOG; Program

@geindex NO_LOG; Program

@geindex NOLOG; Program

@code{LOG}

@quotation

`NO_'@code{HIST_NO_FUNCTIONS}
(ksh compatibility)
@end quotation

@geindex MAIL_WARN; Program

@geindex NO_MAIL_WARN; Program

@geindex MAILWARN; Program

@geindex NOMAILWARN; Program

@code{MAIL_WARN}

@quotation

@code{MAIL_WARNING}
(bash compatibility)
@end quotation

@geindex ONE_CMD; Program

@geindex NO_ONE_CMD; Program

@geindex ONECMD; Program

@geindex NOONECMD; Program

@code{ONE_CMD}

@quotation

@code{SINGLE_COMMAND}
(bash compatibility)
@end quotation

@geindex PHYSICAL; Program

@geindex NO_PHYSICAL; Program

@geindex NOPHYSICAL; Program

@code{PHYSICAL}

@quotation

@code{CHASE_LINKS}
(ksh and bash compatibility)
@end quotation

@geindex PROMPT_VARS; Program

@geindex NO_PROMPT_VARS; Program

@geindex PROMPTVARS; Program

@geindex NOPROMPTVARS; Program

@code{PROMPT_VARS}

@quotation

@code{PROMPT_SUBST}
(bash compatibility)
@end quotation

@geindex STDIN; Program

@geindex NO_STDIN; Program

@geindex NOSTDIN; Program

@code{STDIN}

@quotation

@code{SHIN_STDIN}
(ksh compatibility)
@end quotation

@geindex TRACK_ALL; Program

@geindex NO_TRACK_ALL; Program

@geindex TRACKALL; Program

@geindex NOTRACKALL; Program

@code{TRACK_ALL}

@quotation

@code{HASH_CMDS}
(ksh compatibility)
@end quotation

@c historic nodename: Single Letter Options

@node Single Letter Options,,Option Aliases,Options<2>
@anchor{Zsh/options single-letter-options}@anchor{b2}
@section Single Letter Options


@geindex options@comma{} single letter; Command

@geindex single letter options; Command

@menu
* Default Set:: 
* sh/ksh Emulation Set:: 
* Also Note:: 

@end menu

@node Default Set,sh/ksh Emulation Set,,Single Letter Options
@anchor{Zsh/options default-set}@anchor{b3}
@subsection Default Set



@table @asis

@item @code{-0}

CORRECT

@item @code{-1}

PRINT_EXIT_VALUE

@item @code{-2}

`NO_'BAD_PATTERN

@item @code{-3}

`NO_'NOMATCH

@item @code{-4}

GLOB_DOTS

@item @code{-5}

NOTIFY

@item @code{-6}

BG_NICE

@item @code{-7}

IGNORE_EOF

@item @code{-8}

MARK_DIRS

@item @code{-9}

AUTO_LIST

@item @code{-B}

`NO_'BEEP

@item @code{-C}

`NO_'CLOBBER

@item @code{-D}

PUSHD_TO_HOME

@item @code{-E}

PUSHD_SILENT

@item @code{-F}

`NO_'GLOB

@item @code{-G}

NULL_GLOB

@item @code{-H}

RM_STAR_SILENT

@item @code{-I}

IGNORE_BRACES

@item @code{-J}

AUTO_CD

@item @code{-K}

`NO_'BANG_HIST

@item @code{-L}

SUN_KEYBOARD_HACK

@item @code{-M}

SINGLE_LINE_ZLE

@item @code{-N}

AUTO_PUSHD

@item @code{-O}

CORRECT_ALL

@item @code{-P}

RC_EXPAND_PARAM

@item @code{-Q}

PATH_DIRS

@item @code{-R}

LONG_LIST_JOBS

@item @code{-S}

REC_EXACT

@item @code{-T}

CDABLE_VARS

@item @code{-U}

MAIL_WARNING

@item @code{-V}

`NO_'PROMPT_CR

@item @code{-W}

AUTO_RESUME

@item @code{-X}

LIST_TYPES

@item @code{-Y}

MENU_COMPLETE

@item @code{-Z}

ZLE

@item @code{-a}

ALL_EXPORT

@item @code{-e}

ERR_EXIT

@item @code{-f}

`NO_'RCS

@item @code{-g}

HIST_IGNORE_SPACE

@item @code{-h}

HIST_IGNORE_DUPS

@item @code{-i}

INTERACTIVE

@item @code{-k}

INTERACTIVE_COMMENTS

@item @code{-l}

LOGIN

@item @code{-m}

MONITOR

@item @code{-n}

`NO_'EXEC

@item @code{-p}

PRIVILEGED

@item @code{-r}

RESTRICTED

@item @code{-s}

SHIN_STDIN

@item @code{-t}

SINGLE_COMMAND

@item @code{-u}

`NO_'UNSET

@item @code{-v}

VERBOSE

@item @code{-w}

CHASE_LINKS

@item @code{-x}

XTRACE

@item @code{-y}

SH_WORD_SPLIT
@end table

@node sh/ksh Emulation Set,Also Note,Default Set,Single Letter Options
@anchor{Zsh/options sh-ksh-emulation-set}@anchor{b4}
@subsection sh/ksh Emulation Set



@table @asis

@item @code{-C}

`NO_'CLOBBER

@item @code{-T}

TRAPS_ASYNC

@item @code{-X}

MARK_DIRS

@item @code{-a}

ALL_EXPORT

@item @code{-b}

NOTIFY

@item @code{-e}

ERR_EXIT

@item @code{-f}

`NO_'GLOB

@item @code{-i}

INTERACTIVE

@item @code{-l}

LOGIN

@item @code{-m}

MONITOR

@item @code{-n}

`NO_'EXEC

@item @code{-p}

PRIVILEGED

@item @code{-r}

RESTRICTED

@item @code{-s}

SHIN_STDIN

@item @code{-t}

SINGLE_COMMAND

@item @code{-u}

`NO_'UNSET

@item @code{-v}

VERBOSE

@item @code{-x}

XTRACE
@end table

@node Also Note,,sh/ksh Emulation Set,Single Letter Options
@anchor{Zsh/options also-note}@anchor{b5}
@subsection Also Note



@table @asis

@item @code{-A}

Used by @code{set} for setting arrays

@item @code{-b}

Used on the command line to specify end of option processing

@item @code{-c}

Used on the command line to specify a single command

@item @code{-m}

Used by @code{setopt} for pattern-matching option setting

@item @code{-o}

Used in all places to allow use of long option names

@item @code{-s}

Used by @code{set} to sort positional parameters
@end table

@c historic nodename: Shell Builtin Commands

@node Shell Builtin Commands,Zsh Line Editor,Options<2>,Top
@anchor{Zsh/builtins doc}@anchor{b6}@anchor{Zsh/builtins shell-builtin-commands}@anchor{2c}
@chapter Shell Builtin Commands



@geindex builtin commands; Command

@geindex commands@comma{} builtin; Command

Some shell builtin commands take options as described in individual
entries; these are often referred to in the list below as @code{flags} to
avoid confusion with shell options, which may also have an effect on the
behaviour of builtin commands.  In this introductory section,
@code{option} always has the meaning of an option to a command that should
be familiar to most command line users.

Typically, options are single letters preceded by a hyphen (@code{-}).
Options that take an argument accept it either immediately following the
option letter or after white space, for example @code{print -C3 @{1..9@}} or
@code{print -C 3 @{1..9@}} are equivalent.  Arguments to options are not the
same as arguments to the command; the documentation indicates which is
which.  Options that do not take an argument may be combined in a single
word, for example @code{print -rca -- *} and @code{print -r -c -a -- *} are
equivalent.

Some shell builtin commands also take options that begin with @code{+}
instead of @code{-}.  The list below makes clear which commands these
are.

Options (together with their individual arguments, if any) must appear
in a group before any non-option arguments; once the first non-option
argument has been found, option processing is terminated.

All builtin commands other than @code{echo} and precommand modifiers,
even those that have no options, can be given the argument @code{--}
to terminate option processing.  This indicates that the following words
are non-option arguments, but is otherwise ignored.  This is useful in
cases where arguments to the command may begin with @code{-}.  For
historical reasons, most builtin commands (including @code{echo}) also
recognize a single @code{-} in a separate word for this purpose; note
that this is less standard and use of @code{--} is recommended.

@code{-} @var{simple command}

@quotation

See @ref{b7,,Precommand Modifiers}.
@end quotation

@geindex .; Function

@code{.} @var{file} [ @var{arg} … ]

@quotation

Read commands from @var{file} and execute them in the current shell
environment.

If @var{file} does not contain a slash, or if @code{PATH_DIRS} is set,
the shell looks in the components of @code{$path} to find the directory
containing @var{file}.  Files in the current directory are not read
unless @code{.} appears somewhere in @code{$path}.  If a file named
@var{file}@code{.zwc} is found, is newer than @var{file}, and is the
compiled form (created with the @code{zcompile} builtin) of @var{file},
then commands are read from that file instead of @var{file}.

If any arguments @var{arg} are given,
they become the positional parameters; the old positional
parameters are restored when the @var{file} is done executing.
However, if no arguments are given,
the positional parameters remain those of the calling context,
and no restoring is done.

If @var{file} was not found the return status is 127; if @var{file} was found
but contained a syntax error the return status is 126; else the return
status is the exit status of the last command executed.
@end quotation

@geindex ;; Function

@geindex expanding parameters; Command

@geindex parameters@comma{} expanding; Command

@geindex doing nothing; Command

@code{:} [ @var{arg} … ]

@quotation

This command does nothing, although normal argument expansions is performed
which may have effects on shell parameters.  A zero exit status is returned.
@end quotation

@geindex alias; Function

@geindex aliases@comma{} defining; Command

@geindex aliases@comma{} listing; Command

@code{alias} [ @{@code{+|-@}gmrsL} ] [ @var{name}[@code{=}@var{value}] … ]

@quotation

For each @var{name} with a corresponding @var{value}, define an alias
with that value.  A trailing space in @var{value} causes the next word
to be checked for alias expansion.  If the @code{-g} flag is present,
define a global alias; global aliases are expanded even if they do not
occur in command position:

@example
 % perldoc --help 2>&1 | grep 'built-in functions'
     -f   Search Perl built-in functions
 % alias -g HG='--help 2>&1 | grep'
 % perldoc HG 'built-in functions'
     -f   Search Perl built-in functions
@end example

If the @code{-s} flag is present, define a suffix alias: if the command
word on a command line is in the form @var{text}@code{.}@var{name}, where
@var{text} is any non-empty string, it is replaced by the text
@var{value} @var{text}@code{.}@var{name}.  Note that @var{name} is treated as
a literal string, not a pattern.  A trailing space in @var{value} is not
special in this case.  For example,

@example
 alias -s ps='gv --'
@end example

will cause the command @code{*.ps} to be expanded to @code{gv -- *.ps}.  As
alias expansion is carried out earlier than globbing, the @code{*.ps} will
then be expanded.  Suffix aliases constitute a different name space from
other aliases (so in the above example it is still possible
to create an alias for the command @code{ps}) and the two sets are never
listed together.

For each @var{name} with no @var{value},
print the value of @var{name}, if any.  With no arguments, print all
currently defined aliases other than suffix aliases.  If the @code{-m} flag
is given the arguments are taken as patterns (they should be quoted to
preserve them from being interpreted as glob patterns), and the aliases
matching these patterns are printed.  When printing aliases and one of
the @code{-g}, @code{-r} or @code{-s} flags is present, restrict the printing to
global, regular or suffix aliases, respectively; a regular alias is one
which is neither a global nor a suffix alias.   Using @code{+}
instead of @code{-}, or ending the option list with a single
@code{+}, prevents the values of the aliases from being printed.

If the @code{-L} flag is present, then print each
alias in a manner suitable for putting in a startup script.  The exit
status is nonzero if a @var{name} (with no @var{value}) is given for
which no alias has been defined.

For more on aliases, including common problems,
see @ref{b8,,Aliasing}.
@end quotation

@geindex autoload; Function

@geindex functions@comma{} autoloading; Command

@geindex autoloading functions; Command

@code{autoload} [ @{@code{+|-@}RTUXdkmrtWz} ] [ @code{-w} ] [ @var{name} … ]

@quotation

@geindex fpath@comma{} searching; Variable

See @ref{b9,,Autoloading Functions}
for full details.  The @code{fpath} parameter
will be searched to find the function definition when the function is
first referenced.

If @var{name} consists of an absolute path, the function is defined to
load from the file given (searching as usual for dump files in the given
location).  The name of the function is the basename (non-directory
part) of the file.  It is normally an error if the function is not found
in the given location; however, if the option @code{-d} is given, searching
for the function defaults to @code{$fpath}.  If a function is loaded by
absolute path, any functions loaded from it that are marked for
@code{autoload} without an absolute path have the load path of the parent
function temporarily prepended to @code{$fpath}.

If the option @code{-r} or @code{-R} is given, the function is searched for
immediately and the location is recorded internally for use when the
function is executed; a relative path is expanded using the value of
@code{$PWD}.  This protects against a change to @code{$fpath} after the call
to @code{autoload}.  With @code{-r}, if the function is not found, it is
silently left unresolved until execution; with @code{-R}, an error message
is printed and command processing aborted immediately the search fails,
i.e. at the @code{autoload} command rather than at function execution..

The flag @code{-X} may be used only inside a shell function.  It causes the
calling function to be marked for autoloading and then immediately
loaded and executed, with the current array of positional parameters as
arguments.  This replaces the previous definition of the function.  If
no function definition is found, an error is printed and the function
remains undefined and marked for autoloading.  If an argument is given,
it is used as a directory (i.e. it does not include the name of the
function) in which the function is to be found; this may be combined
with the @code{-d} option to allow the function search to default to @code{$fpath}
if it is not in the given location.

The flag @code{+X} attempts to load each @var{name} as an autoloaded function,
but does `not' execute it.  The exit status is zero (success) if the
function was not previously defined `and' a definition for it was found.
This does `not' replace any existing definition of the function.  The
exit status is nonzero (failure) if the function was already defined or
when no definition was found.  In the latter case the function remains
undefined and marked for autoloading.  If ksh-style autoloading is
enabled, the function created will contain the contents of the file
plus a call to the function itself appended to it, thus giving normal
ksh autoloading behaviour on the first call to the function.
If the @code{-m} flag is also given each @var{name} is treated as a
pattern and all functions already marked for autoload that match the
pattern are loaded.

With the @code{-t} flag, turn on execution tracing; with @code{-T}, turn on
execution tracing only for the current function, turning it off on entry
to any called functions that do not also have tracing enabled.

With the @code{-U} flag, alias expansion is suppressed when the function is
loaded.

With the @code{-w} flag, the @var{name}s are taken as names of files compiled
with the @code{zcompile} builtin, and all functions defined in them are
marked for autoloading.

The flags @code{-z} and @code{-k} mark the function to be autoloaded using the
zsh or ksh style, as if the option @code{KSH_AUTOLOAD} were unset or were
set, respectively.  The flags override the setting of the option at the
time the function is loaded.

Note that the @code{autoload} command makes no attempt to ensure the
shell options set during the loading or execution of the file have
any particular value.  For this, the @code{emulate} command can be used:

@example
 emulate zsh -c 'autoload -Uz @var{func}'
@end example

arranges that when @var{func} is loaded the shell is in native @code{zsh}
emulation, and this emulation is also applied when @var{func} is run.

Some of the functions of @code{autoload} are also provided by @code{functions
-u `@w{`}or} functions -U`@w{`}, but`@w{`} autoload`@w{`} is a more comprehensive
interface.
@end quotation

@geindex bg; Function

@geindex jobs@comma{} backgrounding; Command

@code{bg} [ @var{job} … ]

@var{job} … @code{&}

@quotation

Put each specified @var{job} in the background,
or the current job if none is specified.
@end quotation

@code{bindkey}

@quotation

See @ref{ba,,Zle Builtins}.
@end quotation

@geindex break; Function

@geindex exiting loops; Command

@geindex loops@comma{} exiting; Command

@code{break} [ @var{n} ]

@quotation

Exit from an enclosing @code{for}, @code{while},
@code{until}, @code{select} or @code{repeat} loop. If an arithmetic expression @var{n}
is specified, then break @var{n} levels instead of just one.
@end quotation

@geindex builtin; Function

@code{builtin} @var{name} [ @var{args} … ]

@quotation

Executes the builtin @var{name}, with the given @var{args}.
@end quotation

@geindex bye; Function

@code{bye}

@quotation

Same as @code{exit}.
@end quotation

@code{cap}

@quotation

See @ref{bb,,The zsh/cap Module}.
@end quotation

@geindex cd; Function

@geindex directories@comma{} changing; Command

@code{cd} [ @code{-qsLP} ] [ @var{arg} ]

@code{cd} [ @code{-qsLP} ] @var{old} @var{new}

@code{cd} [ @code{-qsLP} ] @{@code{+|-}@}:var:@cite{n}

@quotation

Change the current directory.  In the first form, change the
current directory to @var{arg}, or to the value of @code{$HOME} if
@var{arg} is not specified.  If @var{arg} is @code{-}, change to the
previous directory.

Otherwise, if @var{arg} begins with a slash, attempt to change to the
directory given by @var{arg}.

If @var{arg} does not begin with a slash, the behaviour depends on whether
the current directory @code{.} occurs in the list of directories contained
in the shell parameter @code{cdpath}.  If it does not, first attempt to change
to the directory @var{arg} under the current directory, and if that fails
but @code{cdpath} is set and contains at least one element attempt to change
to the directory @var{arg} under each component of @code{cdpath} in turn until
successful.  If @code{.} occurs in @code{cdpath}, then @code{cdpath} is searched
strictly in order so that @code{.} is only tried at the appropriate point.

The order of testing @code{cdpath} is modified if the option @code{POSIX_CD}
is set, as described in the documentation for the option.

If no directory is found, the option @code{CDABLE_VARS} is set, and a
parameter named @var{arg} exists whose value begins with a slash, treat its
value as the directory.  In that case, the parameter is added to the named
directory hash table.

The second form of @code{cd} substitutes the string @var{new}
for the string @var{old} in the name of the current directory,
and tries to change to this new directory.

The third form of @code{cd} extracts an entry from the directory
stack, and changes to that directory.  An argument of the form
@code{+}@var{n} identifies a stack entry by counting from the left
of the list shown by the @code{dirs} command, starting with zero.
An argument of the form @code{-}@var{n} counts from the right.
If the @code{PUSHD_MINUS} option is set, the meanings of @code{+}
and @code{-} in this context are swapped.
If the @code{POSIX_CD} option is set, this form of @code{cd} is not recognised
and will be interpreted as the first form.

If the @code{-q} (quiet) option is specified, the hook function @code{chpwd}
and the functions in the array @code{chpwd_functions} are not called.
This is useful for calls to @code{cd} that do not change the environment
seen by an interactive user.

If the @code{-s} option is specified, @code{cd} refuses to change the current
directory if the given pathname contains symlinks.  If the @code{-P} option
is given or the @code{CHASE_LINKS} option is set, symbolic links are resolved
to their true values.  If the @code{-L} option is given symbolic links are
retained in the directory (and not resolved) regardless of the state of
the @code{CHASE_LINKS} option.
@end quotation

@geindex chdir; Function

@code{chdir}

@quotation

Same as @code{cd}.
@end quotation

@code{clone}

@quotation

See @ref{bc,,The zsh/clone Module}.
@end quotation

@geindex command; Function

@code{command} [ @code{-pvV} ] @var{simple command}

@quotation

The simple command argument is taken as an external command instead of
a function or builtin and is executed. If the @code{POSIX_BUILTINS} option
is set, builtins will also be executed but certain special properties
of them are suppressed. The @code{-p} flag causes a default path to be
searched instead of that in @code{$path}. With the @code{-v} flag, @code{command}
is similar to @code{whence} and with @code{-V}, it is equivalent to @code{whence
-v}.

See also @ref{b7,,Precommand Modifiers}.
@end quotation

@code{comparguments}

@quotation

See @ref{bd,,The zsh/computil Module}.
@end quotation

@code{compcall}

@quotation

See @ref{be,,The zsh/compctl Module}.
@end quotation

@code{compctl}

@quotation

See @ref{be,,The zsh/compctl Module}.
@end quotation

@code{compdescribe}

@quotation

See @ref{bd,,The zsh/computil Module}.
@end quotation

@code{compfiles}

@quotation

See @ref{bd,,The zsh/computil Module}.
@end quotation

@code{compgroups}

@quotation

See @ref{bd,,The zsh/computil Module}.
@end quotation

@code{compquote}

@quotation

See @ref{bd,,The zsh/computil Module}.
@end quotation

@code{comptags}

@quotation

See @ref{bd,,The zsh/computil Module}.
@end quotation

@code{comptry}

@quotation

See @ref{bd,,The zsh/computil Module}.
@end quotation

@code{compvalues}

@quotation

See @ref{bd,,The zsh/computil Module}.
@end quotation

@geindex continue; Function

@geindex loops@comma{} continuing; Command

@geindex continuing loops; Command

@code{continue} [ @var{n} ]

@quotation

Resume the next iteration of the enclosing
@code{for}, @code{while}, @code{until}, @code{select} or
@code{repeat} loop. If an arithmetic expression @var{n} is specified, break out of
@var{n}-1 loops and resume at the @var{n}th enclosing loop.
@end quotation

@geindex declare; Function

@code{declare}

@quotation

Same as @code{typeset}.
@end quotation

@geindex dirs; Function

@geindex directory stack@comma{} printing; Command

@code{dirs} [ @code{-c} ] [ @var{arg} … ]

@code{dirs} [ @code{-lpv} ]

@quotation

With no arguments, print the contents of the directory stack.
Directories are added to this stack with the @code{pushd} command,
and removed with the @code{cd} or @code{popd} commands.
If arguments are specified, load them onto the directory stack,
replacing anything that was there, and push the current directory
onto the stack.

@code{-c}

@quotation

clear the directory stack.
@end quotation

@code{-l}

@quotation

print directory names in full instead of using @code{~} expressions
(see @ref{5d,,Filename Expansion}).
@end quotation

@code{-p}

@quotation

print directory entries one per line.
@end quotation

@code{-v}

@quotation

number the directories in the stack when printing.
@end quotation
@end quotation

@geindex disable; Function

@geindex disabling commands; Command

@geindex commands@comma{} disabling; Command

@code{disable} [ @code{-afmprs} ] @var{name} …

@quotation

Temporarily disable the @var{name}d hash table elements or patterns.  The default
is to disable builtin commands.  This allows you to use an external
command with the same name as a builtin command.  The @code{-a} option
causes @code{disable} to act on regular or global aliases.  The @code{-s}
option causes @code{disable} to act on suffix aliases.  The @code{-f} option causes
@code{disable} to act on shell functions.  The @code{-r} options causes
@code{disable} to act on reserved words.  Without arguments all disabled
hash table elements from the corresponding hash table are printed.
With the @code{-m} flag the arguments are taken as patterns (which should be
quoted to prevent them from undergoing filename expansion), and all hash
table elements from the corresponding hash table matching these patterns
are disabled.  Disabled objects can be enabled with the @code{enable}
command.

With the option @code{-p}, @var{name} … refer to elements of the
shell’s pattern syntax as described in @ref{17,,Filename Generation}.
Certain elements can be disabled separately, as given below.

Note that patterns
not allowed by the current settings for the options @code{EXTENDED_GLOB},
@code{KSH_GLOB} and @code{SH_GLOB} are never enabled, regardless of the
setting here.  For example, if @code{EXTENDED_GLOB} is not active,
the pattern @code{^} is ineffective even if @code{disable -p "^"} has
not been issued.  The list below indicates any option settings
that restrict the use of the pattern.  It should be noted that
setting @code{SH_GLOB} has a wider effect than merely disabling patterns
as certain expressions, in particular those involving parentheses,
are parsed differently.

The following patterns may be disabled; all
the strings need quoting on the command line to prevent them from
being interpreted immediately as patterns and the patterns are
shown below in single quotes as a reminder.

@code{'?'}

@quotation

The pattern character @code{?} wherever it occurs, including when preceding
a parenthesis with @code{KSH_GLOB}.
@end quotation

@code{'*'}

@quotation

The pattern character @code{*} wherever it occurs, including recursive
globbing and when preceding a parenthesis with @code{KSH_GLOB}.
@end quotation

@code{'['}

@quotation

Character classes.
@end quotation

@code{'<'} (@code{NO_SH_GLOB})

@quotation

Numeric ranges.
@end quotation

@code{'|'} (@code{NO_SH_GLOB})

@quotation

Alternation in grouped patterns, case statements, or KSH_GLOB
parenthesised expressions.
@end quotation

@code{'('} (@code{NO_SH_GLOB})

@quotation

Grouping using single parentheses.  Disabling this does not disable the
use of parentheses for @code{KSH_GLOB} where they are introduced by a
special character, nor for glob qualifiers (use @code{setopt
NO_BARE_GLOB_QUAL} to disable glob qualifiers that use parentheses
only).
@end quotation

@code{'~'} (@code{EXTENDED_GLOB})

@quotation

Exclusion in the form @var{A}@code{~}@var{B}.
@end quotation

@code{'^'} (@code{EXTENDED_GLOB})

@quotation

Exclusion in the form @var{A}@code{^}@var{B}.
@end quotation

@code{'#'} (@code{EXTENDED_GLOB})

@quotation

The pattern character @code{#} wherever it occurs, both for
repetition of a previous pattern and for indicating globbing flags.
@end quotation

@code{'?('} (@code{KSH_GLOB})

@quotation

The grouping form @code{?(}@var{…}@code{)}.  Note this is also
disabled if @code{'?'} is disabled.
@end quotation

@code{'*('} (@code{KSH_GLOB})

@quotation

The grouping form @code{*(}@var{…}@code{)}.  Note this is also
disabled if @code{'*'} is disabled.
@end quotation

@code{'+('} (@code{KSH_GLOB})

@quotation

The grouping form @code{+(}@var{…}@code{)}.
@end quotation

@code{'!('} (@code{KSH_GLOB})

@quotation

The grouping form @code{!(}@var{…}@code{)}.
@end quotation

@code{'@@('} (@code{KSH_GLOB})

@quotation

The grouping form @code{@@(}@var{…}@code{)}.
@end quotation
@end quotation

@geindex disown; Function

@geindex jobs@comma{} disowning; Command

@code{disown} [ @code{-a} | @var{job} … ]

@var{job} … @code{&|}

@var{job} … @code{&!}

@quotation

Remove the specified @var{job}s from the job table; the shell will
no longer report their status, and will not complain if you
try to exit an interactive shell with them running or stopped.
If no @var{job} is specified, disown the current job.
With @code{-a}, disown all jobs.

If the @var{job}s are currently stopped and the @code{AUTO_CONTINUE} option
is not set, a warning is printed containing information about how to
make them running after they have been disowned.  If one of the latter
two forms is used, the @var{job}s will automatically be made running,
independent of the setting of the @code{AUTO_CONTINUE} option.
@end quotation

@geindex echo; Function

@code{echo} [ @code{-neE} ] [ @var{arg} … ]

@quotation

Write each @var{arg} on the standard output, with a space separating
each one.
If the @code{-n} flag is not present, print a newline at the end.
@code{echo} recognizes the following escape sequences:


@table @asis

@item @code{\a}

bell character

@item @code{\b}

backspace

@item @code{\c}

suppress subsequent characters and final newline

@item @code{\e}

escape

@item @code{\f}

form feed

@item @code{\n}

linefeed (newline)

@item @code{\r}

carriage return

@item @code{\t}

horizontal tab

@item @code{\v}

vertical tab

@item @code{\\}

backslash

@item @code{\0}@var{NNN}

character code in octal

@item @code{\x}@var{NN}

character code in hexadecimal

@item @code{\u}@var{NNNN}

unicode character code in hexadecimal

@item @code{\U}@var{NNNNNNNN}

unicode character code in hexadecimal
@end table

@geindex BSD_ECHO@comma{} use of; Program

The @code{-E} flag, or the @code{BSD_ECHO} option, can be used to disable
these escape sequences.  In the latter case, @code{-e} flag can be used to
enable them.

Note that for standards compliance a double dash does not terminate
option processing; instead, it is printed directly.  However, a
single dash does terminate option processing, so the first dash,
possibly following options, is not printed, but everything following it
is printed as an argument.  The single dash behaviour is different
from other shells.  For a more portable way of printing text, see
@code{printf}, and for a more controllable way of printing text within zsh,
see @code{print}.
@end quotation

@code{echotc}

@quotation

See @ref{bf,,The zsh/termcap Module}.
@end quotation

@code{echoti}

@quotation

See @ref{c0,,The zsh/terminfo Module}.
@end quotation

@geindex emulate; Function

@geindex compatibility@comma{} sh; Command

@geindex compatibility@comma{} ksh; Command

@geindex compatibility@comma{} csh; Command

@geindex sh@comma{} compatibility; Command

@geindex ksh@comma{} compatibility; Command

@geindex csh@comma{} compatibility; Command

@code{emulate} [ @code{-lLR} ] [ @{@code{zsh|sh|ksh|csh}@} [ @var{flags} … ] ]

@quotation

Without any argument print current emulation mode.

With single argument set up zsh options to emulate the specified shell
as much as possible.
`csh' will never be fully emulated.
If the argument is not one of the shells listed above, @code{zsh}
will be used as a default; more precisely, the tests performed on the
argument are the same as those used to determine the emulation at startup
based on the shell name, see @ref{c1,,Compatibility}.
In addition to setting shell options, the command also restores
the pristine state of pattern enables, as if all patterns had been
enabled using @code{enable -p}.

If the @code{emulate} command occurs inside a function that has been
marked for execution tracing with @code{functions -t} then the @code{xtrace}
option will be turned on regardless of emulation mode or other options.
Note that code executed inside the function by the @code{.}, @code{source}, or
@code{eval} commands is not considered to be running directly from the
function, hence does not provoke this behaviour.

If the @code{-R} switch is given, all settable options
are reset to their default value corresponding to the specified emulation
mode, except for certain options describing the interactive
environment; otherwise, only those options likely to cause portability
problems in scripts and functions are altered.  If the @code{-L} switch is given,
the options @code{LOCAL_OPTIONS}, @code{LOCAL_PATTERNS} and @code{LOCAL_TRAPS}
will be set as
well, causing the effects of the @code{emulate} command and any @code{setopt},
@code{disable -p} or @code{enable -p}, and @code{trap} commands to be local to
the immediately surrounding shell
function, if any; normally these options are turned off in all emulation
modes except @code{ksh}. The @code{-L} switch is mutually exclusive with the
use of @code{-c} in @var{flags}.

If there is a single argument and the @code{-l} switch is given, the
options that would be set or unset (the latter indicated with the prefix
@code{no}) are listed.  @code{-l} can be combined with @code{-L} or @code{-R} and
the list will be modified in the appropriate way.  Note the list does
not depend on the current setting of options, i.e. it includes all
options that may in principle change, not just those that would actually
change.

The @var{flags} may be any of the invocation-time flags described in
@ref{c2,,Invocation},
except that @code{-o EMACS} and @code{-o VI} may not be used.

If @code{-c} @var{arg} appears in @var{flags}, @var{arg} is evaluated while the
requested emulation is temporarily in effect.  In this case the emulation
mode and all options are restored to their previous values before
@code{emulate} returns.  The @code{-R} switch may precede the name of the shell
to emulate; note this has a meaning distinct from including @code{-R} in
@var{flags}.

Use of @code{-c} enables `sticky’ emulation mode for functions defined
within the evaluated expression:  the emulation mode is associated
thereafter with the function so that whenever the function is executed
the emulation (respecting the @code{-R} switch, if present) and all
options are set (and pattern disables cleared)
before entry to the function, and the state is restored after exit.
If the function is called when the sticky emulation is already in
effect, either within an @code{emulate} @var{shell} @code{-c} expression or
within another function with the same sticky emulation, entry and exit
from the function do not cause options to be altered (except due to
standard processing such as the @code{LOCAL_OPTIONS} option).  This also
applies to functions marked for autoload within the sticky emulation;
the appropriate set of options will be applied at the point the
function is loaded as well as when it is run.

For example:

@example
 emulate sh -c 'fni() @{ setopt cshnullglob; @}
 fno() @{ fni; @}'
 fno
@end example

The two functions @code{fni} and @code{fno} are defined with sticky @code{sh}
emulation.  @code{fno} is then executed, causing options associated
with emulations to be set to their values in @code{sh}.  @code{fno} then
calls @code{fni}; because @code{fni} is also marked for sticky @code{sh}
emulation, no option changes take place on entry to or exit from it.
Hence the option @code{cshnullglob}, turned off by @code{sh} emulation, will
be turned on within @code{fni} and remain on return to @code{fno}.  On exit
from @code{fno}, the emulation mode and all options will be restored to the
state they were in before entry to the temporary emulation.

The documentation above is typically sufficient for the intended
purpose of executing code designed for other shells in a suitable
environment.  More detailed rules follow.


@enumerate 

@item 
The sticky emulation environment provided by @code{emulate}
@var{shell} @code{-c} is identical to that provided by entry to
a function marked for sticky emulation as a consequence of being
defined in such an environment.  Hence, for example, the sticky
emulation is inherited by subfunctions defined within functions
with sticky emulation.

@item 
No change of options takes place on entry to or exit from
functions that are not marked for sticky emulation, other than those
that would normally take place, even if those functions are called
within sticky emulation.

@item 
No special handling is provided for functions marked for
@code{autoload} nor for functions present in wordcode created by
the @code{zcompile} command.

@item 
The presence or absence of the @code{-R} switch to @code{emulate}
corresponds to different sticky emulation modes, so for example
@code{emulate sh -c}, @code{emulate -R sh -c} and @code{emulate csh -c}
are treated as three distinct sticky emulations.

@item 
Difference in shell options supplied in addition to the
basic emulation also mean the sticky emulations are different, so for
example @code{emulate zsh -c} and @code{emulate zsh -o cbases -c} are
treated as distinct sticky emulations.
@end enumerate
@end quotation

@geindex enable; Function

@geindex enabling commands; Command

@geindex commands@comma{} enabling; Command

@code{enable} [ @code{-afmprs} ] @var{name} …

@quotation

Enable the @var{name}d hash table elements, presumably disabled
earlier with @code{disable}.  The default is to enable builtin commands.
The @code{-a} option causes @code{enable} to act on regular or global aliases.
The @code{-s} option causes @code{enable} to act on suffix aliases.
The @code{-f} option causes @code{enable} to act on shell functions.  The @code{-r}
option causes @code{enable} to act on reserved words.  Without arguments
all enabled hash table elements from the corresponding hash table are
printed.  With the @code{-m} flag the arguments are taken as patterns
(should be quoted) and all hash table elements from the corresponding
hash table matching these patterns are enabled.  Enabled objects can be
disabled with the @code{disable} builtin command.

@code{enable -p} reenables patterns disabled with @code{disable -p}.  Note
that it does not override globbing options; for example, @code{enable -p
"~" `@w{`}does not cause the pattern character} ~`@w{`} to be active unless
the @code{EXTENDED_GLOB} option is also set.  To enable all possible
patterns (so that they may be individually disabled with @code{disable -p}),
use @code{setopt EXTENDED_GLOB KSH_GLOB NO_SH_GLOB}.
@end quotation

@geindex eval; Function

@geindex evaluating arguments as commands; Command

@code{eval} [ @var{arg} … ]

@quotation

Read the arguments as input to the shell and execute the resulting
command(s) in the current shell process.  The return status is
the same as if the commands had been executed directly by the shell;
if there are no @var{args} or they contain no commands (i.e. are
an empty string or whitespace) the return status is zero.
@end quotation

@geindex exec; Function

@code{exec} [ @code{-cl} ] [ @code{-a} @var{argv0} ] [ @var{command} [ @var{arg} … ] ]

@quotation

Replace the current shell with @var{command} rather than forking.
If @var{command} is a shell builtin command or a shell function,
the shell executes it, and exits when the command is complete.

With @code{-c} clear the environment; with @code{-l} prepend @code{-} to the
@code{argv[0]} string of the command executed (to simulate a login shell);
with @code{-a} @var{argv0} set the @code{argv[0]} string of the command
executed.
See @ref{b7,,Precommand Modifiers}.

If the option @code{POSIX_BUILTINS} is set, @var{command} is never
interpreted as a shell builtin command or shell function.  This
means further precommand modifiers such as @code{builtin} and
@code{noglob} are also not interpreted within the shell.  Hence
@var{command} is always found by searching the command path.

@geindex redirection@comma{} current shell's I/O; Command

If @var{command} is omitted but any redirections are specified,
then the redirections will take effect in the current shell.
@end quotation

@geindex exit; Function

@code{exit} [ @var{n} ]

@quotation

Exit the shell with the exit status specified by an arithmetic
expression @var{n}; if none
is specified, use the exit status from the last command executed.
.. index:: single: IGNORE_EOF, use of; Program

An EOF condition will also cause the shell to exit, unless
the @code{IGNORE_EOF} option is set.

See notes at the end of @ref{c3,,Signals}
for some possibly unexpected interactions
of the @code{exit} command with jobs.
@end quotation

@geindex export; Function

@code{export} [ @var{name}[@code{=}@var{value}] … ]

@quotation

The specified @var{name}s are marked for automatic export
to the environment of subsequently executed commands.
Equivalent to @code{typeset -gx}.
If a parameter specified does not
already exist, it is created in the global scope.
@end quotation

@geindex false; Function

@geindex doing nothing@comma{} unsuccessfully; Command

@code{false} [ @var{arg} … ]

@quotation

Do nothing and return an exit status of 1.
@end quotation

@geindex fc; Function

@geindex history@comma{} editing; Command

@geindex editing history; Command

@code{fc} [ @code{-e} @var{ename} ] [ @code{-s} ] [ @code{-LI} ] [ @code{-m} @var{match} ] [ @var{old}@code{=}@var{new} … ] [ @var{first} [ @var{last} ] ]

@code{fc -l} [ @code{-LI} ] [ @code{-nrdfEiD} ] [ @code{-t} @var{timefmt} ] [ @code{-m} @var{match} ]

@quotation

[ @var{old}@code{=}@var{new} … ] [ @var{first} [ @var{last} ] ]
@end quotation

@code{fc -p} [ @code{-a} ] [ @var{filename} [ @var{histsize} [ @var{savehistsize} ] ] ]

@code{fc} @code{-P}

@code{fc} @code{-ARWI} [ @var{filename} ]

@quotation

The @code{fc} command controls the interactive history mechanism.  Note
that reading and writing of history options is only performed if the
shell is interactive.  Usually this is detected automatically, but
it can be forced by setting the @code{interactive} option when starting the
shell.

The first two forms of this command select a range of events from
@var{first} to @var{last} from the history list.  The arguments @var{first}
and @var{last} may be specified as a number or as a string.  A negative
number is used as an offset to the current history event number.  A string
specifies the most recent event beginning with the given string.  All
substitutions @var{old}@code{=}@var{new}, if any, are then performed on the
text of the events.

The range of events selected by numbers can be narrowed further by the
following flags.


@table @asis

@item @code{-I}

restricts to only internal events (not from @code{$HISTFILE})

@item @code{-L}

restricts to only local events (not from other shells, see
@code{SHARE_HISTORY} in
@code{zshoptions} – note that @code{$HISTFILE} is
considered local when read at startup)

@item @code{-m}

takes the first argument as a pattern (which should be
quoted) and only the history events matching this pattern are considered
@end table

If @var{first} is not specified, it will be set to -1 (the most recent
event), or to -16 if the @code{-l} flag is given.
If @var{last} is not specified, it will be set to @var{first},
or to -1 if the @code{-l} flag is given.
However, if the current event has added entries to the history with
@code{print -s} or @code{fc -R}, then the default @var{last} for @code{-l}
includes all new history entries since the current event began.

When the @code{-l} flag is given, the resulting events are listed on
standard output.  Otherwise the editor program specified by @code{-e} @var{ename}
is invoked on a file containing these history events.  If @code{-e} is not given, the
value of the parameter @code{FCEDIT} is used; if that is not set the value of
the parameter @code{EDITOR} is used; if that is not set a builtin default,
usually @code{vi} is used.  If @var{ename} is @code{-}, no editor is invoked.
When editing is complete, the edited command is executed.

The flag @code{-s} is equivalent to @code{-e -}.
The flag @code{-r} reverses the order of the events and the
flag @code{-n} suppresses event numbers when listing.

Also when listing,


@table @asis

@item @code{-d}

prints timestamps for each event

@item @code{-f}

prints full time-date stamps in the US
@var{MM}@code{/}@var{DD}@code{/}@var{YY} @var{hh}@code{:}@var{mm} format

@item @code{-E}

prints full time-date stamps in the European
@var{dd}@code{.}@var{mm}@code{.}@var{yyyy} @var{hh}@code{:}@var{mm} format

@item @code{-i}

prints full time-date stamps in ISO8601
@var{yyyy}@code{-}@var{mm}@code{-}@var{dd} @var{hh}@code{:}@var{mm} format

@item @code{-t} @var{fmt}

prints time and date stamps in the given format;
@var{fmt} is formatted with the strftime function with the zsh extensions
described for the @code{%D@{}@var{string}@code{@}} prompt format in
@ref{c4,,Simple Prompt Escapes}.
The resulting formatted string must be
no more than 256 characters or will not be printed

@item @code{-D}

prints elapsed times; may be combined with one of the
options above
@end table

@geindex history@comma{} stack; Command

@geindex stack@comma{} history; Command

@code{fc -p} pushes the current history list onto a stack and switches to a
new history list.  If the @code{-a} option is also specified, this history list
will be automatically popped when the current function scope is exited, which
is a much better solution than creating a trap function to call @code{fc -P}
manually.  If no arguments are specified, the history list is left empty,
@code{$HISTFILE} is unset, and @code{$HISTSIZE} & @code{$SAVEHIST} are set to their
default values.  If one argument is given, @code{$HISTFILE} is set to that
filename, @code{$HISTSIZE} & @code{$SAVEHIST} are left unchanged, and the history
file is read in (if it exists) to initialize the new list.  If a second
argument is specified, @code{$HISTSIZE} & @code{$SAVEHIST} are instead set to the
single specified numeric value.  Finally, if a third argument is specified,
@code{$SAVEHIST} is set to a separate value from @code{$HISTSIZE}.  You are free to
change these environment values for the new history list however you desire
in order to manipulate the new history list.

@code{fc -P} pops the history list back to an older list saved by @code{fc -p}.
The current list is saved to its @code{$HISTFILE} before it is destroyed
(assuming that @code{$HISTFILE} and @code{$SAVEHIST} are set appropriately, of
course).  The values of @code{$HISTFILE}, @code{$HISTSIZE}, and @code{$SAVEHIST} are
restored to the values they had when @code{fc -p} was called.  Note that this
restoration can conflict with making these variables “local”, so your best
bet is to avoid local declarations for these variables in functions that use
@code{fc -p}.  The one other guaranteed-safe combination is declaring these
variables to be local at the top of your function and using the automatic
option (@code{-a}) with @code{fc -p}.  Finally, note that it is legal to manually
pop a push marked for automatic popping if you need to do so before the
function exits.

@geindex history@comma{} file; Command

@geindex file@comma{} history; Command

@code{fc -R} reads the history from the given file,
@code{fc -W} writes the history out to the given file,
and @code{fc -A} appends the history out to the given file.
If no filename is specified, the @code{$HISTFILE} is assumed.
If the @code{-I} option is added to @code{-R}, only those events that are
not already contained within the internal history list are added.
If the @code{-I} option is added to @code{-A} or @code{-W}, only those
events that are new since last incremental append/write to
the history file are appended/written.
In any case, the created file will have no more than @code{$SAVEHIST}
entries.
@end quotation

@geindex fg; Function

@geindex jobs@comma{} foregrounding; Command

@geindex jobs@comma{} resuming; Command

@code{fg} [ @var{job} … ]

@var{job} …

@quotation

Bring each specified @var{job} in turn to the foreground.
If no @var{job} is specified, resume the current job.
@end quotation

@geindex float; Function

@code{float} [ @{@code{+|-@}Hghlprtux} ] [ @{@code{+|-@}EFLRZ} [ @var{n} ] ] [ @var{name}[@code{=}@var{value}] … ]

@quotation

Equivalent to @code{typeset -E}, except that options irrelevant to floating
point numbers are not permitted.
@end quotation

@geindex functions; Function

@code{functions} [ @{@code{+|-@}UkmtTuWz} ] [ @code{-x} @var{num} ] [ @var{name} … ]

@code{functions -c} @var{oldfn} @var{newfn}

@code{functions -M} [@code{-s}] @var{mathfn} [ @var{min} [ @var{max} [ @var{shellfn} ] ] ]

@code{functions -M} [ @code{-m} @var{pattern} … ]

@code{functions +M} [ @code{-m} ] @var{mathfn} …

@quotation

Equivalent to @code{typeset -f}, with the exception of the @code{-c}, @code{-x},
@code{-M} and @code{-W} options.  For @code{functions -u} and @code{functions -U},
see @code{autoload}, which provides additional options.  For @code{functions -t}
and @code{functions -T}, see @code{typeset -f}.

The @code{-x} option indicates that any functions output will have
each leading tab for indentation, added by the shell to show syntactic
structure, expanded to the given number @var{num} of spaces.  @var{num}
can also be 0 to suppress all indentation.

The @code{-W} option turns on the option @code{WARN_NESTED_VAR} for the named
function or functions only.  The option is turned off at the start of
nested functions (apart from anonymous functions) unless the called
function also has the @code{-W} attribute.

The @code{-c} option causes @var{oldfn} to be copied to @var{newfn}.  The
copy is efficiently handled internally by reference counting.  If
@var{oldfn} was marked for autoload it is first loaded and if this
fails the copy fails.  Either function may subsequently be redefined
without affecting the other.  A typical idiom is that @var{oldfn} is the
name of a library shell function which is then redefined to call
@code{newfn}, thereby installing a modified version of the function.

`The `@w{`}'-M`@w{`}:emphasis:` and @cite{`@w{`}+M`}:emphasis:` flags`
.. index:: single: defining mathematical functions; Command

@geindex functions@comma{} defining mathematical; Command

Use of the @code{-M} option may not be combined with any of the options
handled by @code{typeset -f}.

@code{functions -M} @var{mathfn} defines @var{mathfn} as the name of
a mathematical function recognised in all forms of arithmetical expressions;
see @ref{c5,,Arithmetic Evaluation}.
By default @var{mathfn} may take
any number of comma-separated arguments.  If @var{min} is given,
it must have exactly @var{min} args; if @var{min} and @var{max} are
both given, it must have at least @var{min} and at most @var{max}
args.  @var{max} may be -1 to indicate that there is no upper limit.

By default the function is implemented by a shell function of the same
name; if @var{shellfn} is specified it gives the name of the corresponding
shell function while @var{mathfn} remains the name used in arithmetical
expressions.  The name of the function in @code{$0} is @var{mathfn} (not
@var{shellfn} as would usually be the case), provided the option
@code{FUNCTION_ARGZERO} is in effect.  The positional parameters in the shell
function correspond to the arguments of the mathematical function call.

The result of the last arithmetical expression evaluated inside the shell
function gives the result of the mathematical function.  This is not limited to
arithmetic substitutions of the form @code{$((}@var{…}@code{))},
but also includes arithmetical expressions evaluated in any other way, including
by the @code{let} builtin,
by @code{((}@var{…}@code{))} statements,
and even
by the @code{return} builtin
and
by array subscripts.
Therefore, care must be taken not to use syntactical constructs that perform
arithmetic evaluation after evaluating what is to be the result of the function.
For example:

@geindex zmath_cube; Function

@geindex cube; Function

@example
 # WRONG
 zmath_cube() @{
   (( $1 * $1 * $1 ))
   return 0
 @}
 functions -M cube 1 1 zmath_cube
 print $(( cube(3) ))
@end example

This will print @code{0} because of the @code{return}.

Commenting the @code{return} out would lead to a different problem: the
@code{((}@var{…}@code{))} statement would become
the last statement in the function, so the `return status' (@code{$?}) of the
function would be non-zero (indicating failure) whenever the `arithmetic
result' of the function would happen to be zero (numerically):

@example
 # WRONG
 zmath_cube() @{
   (( $1 * $1 * $1 ))
 @}
 functions -M cube 1 1 zmath_cube
 print $(( cube(0) ))
@end example

Instead, the @code{true} builtin can be used:

@example
 # RIGHT
 zmath_cube() @{
   (( $1 * $1 * $1 ))
   true
 @}
 functions -M cube 1 1 zmath_cube
 print $(( cube(3) ))
@end example

If the additional option @code{-s} is given to @code{functions -M}, the
argument to the function is a single string: anything between the
opening and matching closing parenthesis is passed to the function as a
single argument, even if it includes commas or white space.  The minimum
and maximum argument specifiers must therefore be 1 if given.  An empty
argument list is passed as a zero-length string.
Thus, the following string function takes a single argument, including
the commas, and prints 11:

@example
 stringfn() @{ (( $#1 )); true @}
 functions -Ms stringfn
 print $(( stringfn(foo,bar,rod) ))
@end example

@code{functions -M} with no arguments lists all such user-defined functions in
the same form as a definition.  With the additional option @code{-m} and
a list of arguments, all functions whose @var{mathfn} matches one of
the pattern arguments are listed.

@code{function +M} removes the list of mathematical functions; with the
additional option @code{-m} the arguments are treated as patterns and
all functions whose @var{mathfn} matches the pattern are removed.  Note
that the shell function implementing the behaviour is not removed
(regardless of whether its name coincides with @var{mathfn}).
@end quotation

@code{getcap}

@quotation

See @ref{bb,,The zsh/cap Module}.
@end quotation

@geindex getln; Function

@geindex line@comma{} reading; Command

@geindex reading a line; Command

@code{getln} [ @code{-AclneE} ] @var{name} …

@quotation

Read the top value from the buffer stack and put it in
the shell parameter @var{name}.  Equivalent to
@code{read -zr}.
@end quotation

@geindex getopts; Function

@geindex options@comma{} processing; Command

@code{getopts} [ @code{-p} ] @var{optstring} @var{name} [ @var{arg} … ]

@quotation

Checks the @var{arg}s for legal options.  If the @var{arg}s are omitted,
the positional parameters are used.  A valid option argument
begins with a @code{+} or a @code{-}.  An argument not beginning with
a @code{+} or a @code{-}, or the argument @code{--}, ends the options.
Note that a single @code{-} is not considered a valid option argument.
@var{optstring} contains the letters that @code{getopts}
recognizes.  If a letter is followed by a @code{:}, that option
requires an argument.  The argument may appear either immediately
following the option in the same word, or in the next word.

Each time it is invoked, @code{getopts} places the option letter it finds
in the shell parameter @var{name}, prepended with a @code{+} when
@var{arg} begins with a @code{+}.  The index of the next @var{arg}
is stored in @code{OPTIND}.  The option argument, if any,
is stored in @code{OPTARG}.
.. index:: single: OPTIND, use of; Variable

@geindex OPTARG@comma{} use of; Variable

When the terminator @code{--} is encountered, @code{OPTIND} is
incremented such that it can be @code{shift}ed away with the options.  This
is not true of other non-option arguments, including a single @code{-}.

The first option to be examined may be changed by explicitly assigning
to @code{OPTIND}.  @code{OPTIND} has an initial value of @code{1}, and is
normally set to @code{1} upon entry to a shell function and restored
upon exit.  @code{OPTARG} is not reset and retains its value from the most
recent call to @code{getopts}.  If either of @code{OPTIND} or @code{OPTARG} is
explicitly unset, it remains unset, and the index or option argument is
not stored.  The option itself is still stored in @var{name} in this case.

A leading @code{:} in @var{optstring} causes @code{getopts} to store the
letter of any invalid option in @code{OPTARG}, and to set @var{name} to
@code{?} for an unknown option and to @code{:} when a required argument is
missing.  Otherwise, @code{getopts} sets @var{name} to @code{?} and prints
an error message when an option is invalid.  The exit status is
nonzero when there are no more options.

When either the @code{POSIX_BUILTINS} option is enabled or the @code{-p}
option is given to @code{getopts} itself, @code{getopts} behaves in a more
POSIX-compatible manner.  Specifically, handling of
@code{+}-prefixed options is disabled (they are treated as
non-options) and the value of @code{OPTIND} is calculated differently.
Additionally, with @code{POSIX_BUILTINS} (but not with @code{-p}), the value
of @code{OPTIND} is not kept local to the calling function.
@end quotation

@geindex hash; Function

@code{hash} [ @code{-Ldfmrv} ] [ @var{name}[@code{=}@var{value}] ] …

@quotation

@code{hash} can be used to directly modify the contents of the command
hash table, and the named directory hash table.  Normally one would
modify these tables by modifying one’s @code{PATH}
(for the command hash table) or by creating appropriate shell parameters
(for the named directory hash table).
The choice of hash table to work on is determined by the @code{-d} option;
without the option the command hash table is used, and with the option the
named directory hash table is used.

A command @var{name} starting with a @code{/} or with a relative path
starting with @code{./} or @code{../} is never executed by lookup in
the command hash table, and these can only be added to the table by
explicit use of the @code{hash} command.  Such a command is always
found by direct look up in the file system.

Given no arguments, and neither the @code{-r} or @code{-f} options,
the selected hash table will be listed in full.

The @code{-r} option causes the selected hash table to be emptied.
It will be subsequently rebuilt in the normal fashion.
The @code{-f} option causes the selected hash table to be fully
rebuilt immediately.  For the command hash table this hashes
all (and `only') the absolute directories in the @code{PATH},
and for the named directory hash table this adds all users’ home
directories.
These two options cannot be used with any arguments.
Both options remove any explicitly-added elements.

The @code{-m} option causes the arguments to be taken as patterns
(which should be quoted) and the elements of the hash table
matching those patterns are printed.  This is the only way to display
a limited selection of hash table elements.

For each @var{name} with a corresponding @var{value}, put @var{name} in
the selected hash table, associating it with the pathname @var{value}.
In the command hash table, this means that
whenever @var{name} is used as a command argument, the shell will try
to execute the file given by @var{value}.
In the named directory hash table, this means
that @var{value} may be referred to as @code{~}@var{name}.

For each @var{name} with no
corresponding @var{value}, attempt to add @var{name} to the hash table,
checking what the appropriate @code{value} is in the normal manner for
that hash table.  If an appropriate @code{value} can’t be found, then
the hash table will be unchanged.

The @code{-v} option causes hash table entries to be listed as they are
added by explicit specification.  If has no effect if used with @code{-f}.

If the @code{-L} flag is present, then each hash table entry is printed in
the form of a call to hash.
@end quotation

@geindex history; Function

@code{history}

@quotation

Same as @code{fc -l}.
@end quotation

@geindex integer; Function

@code{integer} [ @{@code{+|-@}Hghlprtux} ] [ @{@code{+|-@}LRZi} [ @var{n} ] ] [ @var{name}[@code{=}@var{value}] … ]

@quotation

Equivalent to @code{typeset -i}, except that options irrelevant to
integers are not permitted.
@end quotation

@geindex jobs; Function

@code{jobs} [ @code{-dlprs} ] [ @var{job} … ]

@code{jobs -Z} @var{string}

@quotation

Lists information about each given job, or all jobs
if @var{job} is omitted.  The @code{-l} flag lists process
IDs, and the @code{-p} flag lists process groups.
If the @code{-r} flag is specified only running jobs will be listed
and if the @code{-s} flag is given only stopped jobs are shown.
If the @code{-d} flag is given, the directory from which the job was
started (which may not be the current directory of the job) will also
be shown.

The @code{-Z} option replaces the shell’s argument and environment space with
the given string, truncated if necessary to fit.  This will normally be
visible in @code{ps} (@code{ps(1)}) listings.  This feature is typically
used by daemons, to indicate their state.

Full job control is only available in the top-level interactive shell,
not in commands run in the left hand side of pipelines or within
the @code{(}@var{…}@code{)} construct.  However, a snapshot
of the job state at that point is taken, so it is still possible
to use the @code{jobs} builtin, or any parameter providing job information.
This gives information about the state of jobs at the point the subshell
was created.  If background processes are created within the subshell,
then instead information about those processes is provided.

For example,

@example
 sleep 10 &    # Job in background
 (             # Shell forks
 jobs          # Shows information about "sleep 10 &"
 sleep 5 &     # Process in background (no job control)
 jobs          # Shows information about "sleep 5 &"
 )
@end example
@end quotation

@geindex kill; Function

@geindex killing jobs; Command

@geindex jobs@comma{} killing; Command

@code{kill} [ @code{-s} @var{signal_name} | @code{-n} @var{signal_number} | @code{-}@var{sig} ] [ @code{-q} @var{value} ] @var{job} …

@code{kill} @code{-l} [ @var{sig} … ]

@code{kill} @code{-L}

@quotation

Sends either @code{SIGTERM} or the specified signal to the given
jobs or processes.
Signals are given by number or by names, with or without the @code{SIG}
prefix.
If the signal being sent is not @code{KILL} or @code{CONT}, then the job
will be sent a @code{CONT} signal if it is stopped.
The argument @var{job} can be the process ID of a job
not in the job list.
In the second form, @code{kill -l}, if @var{sig} is not
specified the signal names are listed.  Otherwise, for each
@var{sig} that is a name, the corresponding signal number is
listed.  For each @var{sig} that is a signal number or a number
representing the exit status of a process which was terminated or
stopped by a signal the name of the signal is printed.  The final
form with @code{-L} lists each signal name with its corresponding number.

On some systems, alternative signal names are allowed for a few signals.
Typical examples are @code{SIGCHLD} and @code{SIGCLD} or @code{SIGPOLL} and
@code{SIGIO}, assuming they correspond to the same signal number.  @code{kill
-l `@w{`}will only list the preferred form, however} kill -l`@w{`} @var{alt} will
show if the alternative form corresponds to a signal number.  For example,
under Linux @code{kill -l IO} and @code{kill -l POLL} both output 29, hence
@code{kill -IO} and @code{kill -POLL} have the same effect.

Many systems will allow process IDs to be negative to kill a process
group or zero to kill the current process group.

The @code{-q} option allows an integer value to be sent with the signal
on systems that support @code{sigqueue()}.
@end quotation

@geindex let; Function

@code{let} @var{arg} …

@quotation

Evaluate each @var{arg} as an arithmetic expression.
See @ref{c5,,Arithmetic Evaluation}
for a description of arithmetic expressions.  The exit status is 0 if the
value of the last expression is nonzero, 1 if it is zero, and 2 if
an error occurred.
@end quotation

@geindex limit; Function

@geindex resource limits; Command

@geindex limits@comma{} resource; Command

@code{limit} [ @code{-hs} ] [ @var{resource} [ @var{limit} ] ] …

@quotation

Set or display resource limits.  Unless the @code{-s} flag is given,
the limit applies only the children of the shell.  If @code{-s} is
given without other arguments, the resource limits of the current
shell is set to the previously set resource limits of the children.

If @var{limit} is not specified, print the current limit placed
on @var{resource}, otherwise
set the limit to the specified value.  If the @code{-h} flag
is given, use hard limits instead of soft limits.
If no @var{resource} is given, print all limits.

When looping over multiple resources, the shell will abort immediately if
it detects a badly formed argument.  However, if it fails to set a limit
for some other reason it will continue trying to set the remaining limits.

@var{resource} can be one of:


@table @asis

@item @code{addressspace}

Maximum amount of address space used.

@item @code{aiomemorylocked}

Maximum amount of memory locked in RAM for AIO operations.

@item @code{aiooperations}

Maximum number of AIO operations.

@item @code{cachedthreads}

Maximum number of cached threads.

@item @code{coredumpsize}

Maximum size of a core dump.

@item @code{cputime}

Maximum CPU seconds per process.

@item @code{datasize}

Maximum data size (including stack) for each process.

@item @code{descriptors}

Maximum value for a file descriptor.

@item @code{filesize}

Largest single file allowed.

@item @code{kqueues}

Maximum number of kqueues allocated.

@item @code{maxfilelocks}

Maximum number of file locks.

@item @code{maxproc}

Maximum number of processes.

@item @code{maxpthreads}

Maximum number of threads per process.

@item @code{memorylocked}

Maximum amount of memory locked in RAM.

@item @code{memoryuse}

Maximum resident set size.

@item @code{msgqueue}

Maximum number of bytes in POSIX message queues.

@item @code{nice}

Maximum nice value.

@item @code{pipebuf}

Maximum size of buffers for pipes/fifos.

@item @code{posixlocks}

Maximum number of POSIX locks per user.

@item @code{pseudoterminals}

Maximum number of pseudo-terminals.

@item @code{resident}

Maximum resident set size.

@item @code{rt_priority}

Maximum real-time priority.

@item @code{rt_time}

Maximum CPU time without a blocking system call.

@item @code{sigpending}

Maximum number of pending signals.

@item @code{sockbufsize}

Maximum size of all socket buffers.

@item @code{stacksize}

Maximum stack size for each process.

@item @code{swapsize}

Maximum amount of swap used.

@item @code{umtxp}

Maximum number of POSIX thread library objects.

@item @code{vmemorysize}

Maximum amount of virtual memory.

@item @code{vnodemonitors}

Maximum number of open vnode monitors.
@end table

Which of these resource limits are available depends on the system.
@var{resource} can be abbreviated to any unambiguous prefix.  It
can also be an integer, which corresponds to the integer defined
for the resource by the operating system.

If argument corresponds to a number which is out of the range of the
resources configured into the shell, the shell will try to read or write
the limit anyway, and will report an error if this fails.  As the shell
does not store such resources internally, an attempt to set the limit will
fail unless the @code{-s} option is present.

@var{limit} is a number, with an optional scaling factor, as follows:


@table @asis

@item @var{n}@code{h}

hours

@item @var{n}@code{k}

kilobytes (default)

@item @var{n}@code{m}

megabytes or minutes

@item @var{n}@code{g}

gigabytes

@item [@var{mm}@code{:}]:var:@cite{ss}

minutes and seconds
@end table

The @code{limit} command is not made available by default when the
shell starts in a mode emulating another shell.  It can be made available
with the command @code{zmodload -F zsh/rlimits b:limit}.
@end quotation

@geindex local; Function

@code{local} [ @{@code{+|-@}AHUahlprtux} ] [ @{@code{+|-@}EFLRZi} [ @var{n} ] ] [ @var{name}[@code{=}@var{value}] … ]

@quotation

Same as @code{typeset}, except that the options @code{-g}, and
@code{-f} are not permitted.  In this case the @code{-x} option does not force
the use of @code{-g}, i.e. exported variables will be local to functions.
@end quotation

@geindex logout; Function

@code{logout} [ @var{n} ]

@quotation

Same as @code{exit}, except that it only works in a login shell.
@end quotation

@code{noglob} @var{simple command}

@quotation

See @ref{b7,,Precommand Modifiers}.
@end quotation

@geindex popd; Function

@code{popd} [ @code{-q} ] [ @{@code{+|-}@}:var:@cite{n} ]

@quotation

Remove an entry from the directory stack, and perform a @code{cd} to
the new top directory.  With no argument, the current top entry is
removed.  An argument of the form @code{+}@var{n} identifies a stack
entry by counting from the left of the list shown by the @code{dirs} command,
starting with zero.  An argument of the form @code{-}@var{n} counts from the right.
.. index:: single: PUSHD_MINUS, use of; Program

If the @code{PUSHD_MINUS} option is set, the meanings of @code{+} and
@code{-} in this context are swapped.

If the @code{-q} (quiet) option is specified, the hook function @code{chpwd}
and the functions in the array @code{$chpwd_functions} are not called,
and the new directory stack is not printed.  This is useful for calls to
@code{popd} that do not change the environment seen by an interactive user.
@end quotation

@geindex print; Function

@code{print} [ @code{-abcDilmnNoOpPrsSz} ] [ @code{-u} @var{n} ] [ @code{-f} @var{format} ] [ @code{-C} @var{cols} ]

@quotation

@quotation

[ @code{-v} @var{name} ] [ @code{-xX} @var{tabstop} ] [ @code{-R} [ @code{-en} ]] [ @var{arg} … ]
@end quotation

With the @code{-f} option the arguments are printed as described by @code{printf}.
With no flags or with the flag @code{-}, the arguments are printed on
the standard output as described by @code{echo}, with the following differences:
the escape sequence @code{\M-}@var{x} (or @code{\M}@var{x}) metafies the character
@var{x} (sets the highest bit),
@code{\C-}@var{x} (or @code{\C}@var{x}) produces a control character
(@code{\C-@@} and @code{\C-?} give the characters NULL and delete),
a character code in octal is represented by @code{\}@var{NNN}
(instead of @code{\0}@var{NNN}),
and @code{\E} is a synonym for @code{\e}.
Finally, if not in an escape
sequence, @code{\} escapes the following character and is not printed.

@code{-a}

@quotation

Print arguments with the column incrementing first.  Only useful with the
@code{-c} and @code{-C} options.
@end quotation

@code{-b}

@quotation

Recognize all the escape sequences defined for the @code{bindkey} command,
see @ref{ba,,Zle Builtins}.
@end quotation

@code{-c}

@quotation

Print the arguments in columns.  Unless @code{-a} is also given, arguments are
printed with the row incrementing first.
@end quotation

@code{-C} @var{cols}

@quotation

Print the arguments in @var{cols} columns.  Unless @code{-a} is also given,
arguments are printed with the row incrementing first.
@end quotation

@code{-D}

@quotation

Treat the arguments as paths, replacing directory prefixes with @code{~}
expressions corresponding to directory names, as appropriate.
@end quotation

@code{-i}

@quotation

If given together with @code{-o} or @code{-O}, sorting is performed
case-independently.
@end quotation

@code{-l}

@quotation

Print the arguments separated by newlines instead of spaces.  Note: if
the list of arguments is empty, @code{print -l} will still output one empty
line. To print a possibly-empty list of arguments one per line, use
@code{print -C1}, as in @code{print -rC1 -- "$list[@@]"}.
@end quotation

@code{-m}

@quotation

Take the first argument as a pattern (should be quoted), and remove
it from the argument list together with subsequent arguments that
do not match this pattern.
@end quotation

@code{-n}

@quotation

Do not add a newline to the output.
@end quotation

@code{-N}

@quotation

Print the arguments separated and terminated by nulls. Again,
@code{print -rNC1 -- "$list[@@]"} is a canonical way to print an
arbitrary list as null-delimited records.
@end quotation

@code{-o}

@quotation

Print the arguments sorted in ascending order.
@end quotation

@code{-O}

@quotation

Print the arguments sorted in descending order.
@end quotation

@code{-p}

@quotation

Print the arguments to the input of the coprocess.
@end quotation

@code{-P}

@quotation

Perform prompt expansion (see
@ref{c6,,Expansion of Prompt Sequences}).
In combination with @code{-f},
prompt escape sequences are parsed only within interpolated arguments,
not within the format string.
@end quotation

@code{-r}

@quotation

Ignore the escape conventions of @code{echo}.
@end quotation

@code{-R}

@quotation

Emulate the BSD @code{echo} command, which does not process escape sequences
unless the @code{-e} flag is given.  The @code{-n} flag suppresses the trailing
newline.  Only the @code{-e} and @code{-n} flags are recognized after
@code{-R}; all other arguments and options are printed.
@end quotation

@code{-s}

@quotation

Place the results in the history list instead of on the standard output.
Each argument to the @code{print} command is treated as a single word in the
history, regardless of its content.
@end quotation

@code{-S}

@quotation

Place the results in the history list instead of on the standard output.
In this case only a single argument is allowed; it will be split into
words as if it were a full shell command line.  The effect is
similar to reading the line from a history file with the
@code{HIST_LEX_WORDS} option active.
@end quotation

@code{-u} @var{n}

@quotation

Print the arguments to file descriptor @var{n}.
@end quotation

@code{-v} @var{name}

@quotation

Store the printed arguments as the value of the parameter @var{name}.
@end quotation

@code{-x} @var{tab-stop}

@quotation

Expand leading tabs on each line of output in the printed string
assuming a tab stop every @var{tab-stop} characters.  This is appropriate
for formatting code that may be indented with tabs.  Note that leading
tabs of any argument to print, not just the first, are expanded, even if
@code{print} is using spaces to separate arguments (the column count
is maintained across arguments but may be incorrect on output
owing to previous unexpanded tabs).

The start of the output of each print command is assumed to be aligned
with a tab stop.  Widths of multibyte characters are handled if the
option @code{MULTIBYTE} is in effect.  This option is ignored if other
formatting options are in effect, namely column alignment or
@code{printf} style, or if output is to a special location such as shell
history or the command line editor.
@end quotation

@code{-X} @var{tab-stop}

@quotation

This is similar to @code{-x}, except that all tabs in the printed string
are expanded.  This is appropriate if tabs in the arguments are
being used to produce a table format.
@end quotation

@code{-z}

@quotation

Push the arguments onto the editing buffer stack, separated by spaces.
@end quotation

If any of @code{-m}, @code{-o} or @code{-O} are used in combination with
@code{-f} and there are no arguments (after the removal process in the
case of @code{-m}) then nothing is printed.
@end quotation

@geindex printf; Function

@code{printf} [ @code{-v} @var{name} ] @var{format} [ @var{arg} … ]

@quotation

Print the arguments according to the format specification. Formatting
rules are the same as used in C. The same escape sequences as for @code{echo}
are recognised in the format. All C conversion specifications ending in
one of @code{csdiouxXeEfgGn} are handled. In addition to this, @code{%b} can be
used instead of @code{%s} to cause escape sequences in the argument to be
recognised and @code{%q} can be used to quote the argument in such a way
that allows it to be reused as shell input. With the numeric format
specifiers, if the corresponding argument starts with a quote character,
the numeric value of the following character is used as the number to
print; otherwise the argument is evaluated as an arithmetic expression. See
@ref{c5,,Arithmetic Evaluation} for a description of arithmetic
expressions. With @code{%n}, the corresponding argument is taken as an
identifier which is created as an integer parameter.

Normally, conversion specifications are applied to each argument in order
but they can explicitly specify the @var{n}th argument is to be used by
replacing @code{%} by @code{%}@var{n}@code{$} and @code{*} by @code{*}@var{n}@code{$}.
It is recommended that you do not mix references of this explicit style
with the normal style and the handling of such mixed styles may be subject
to future change.

If arguments remain unused after formatting, the format string is reused
until all arguments have been consumed. With the @code{print} builtin, this
can be suppressed by using the @code{-r} option. If more arguments are
required by the format than have been specified, the behaviour is as if
zero or an empty string had been specified as the argument.

The @code{-v} option causes the output to be stored as the value of the
parameter @var{name}, instead of printed. If @var{name} is an array and
the format string is reused when consuming arguments then one
array element will be used for each use of the format string.
@end quotation

@geindex pushd; Function

@geindex PUSHD_TO_HOME@comma{} use of; Program

@geindex PUSHD_MINUS@comma{} use of; Program

@geindex CDABLE_VARS@comma{} use of; Program

@geindex PUSHD_SILENT@comma{} use of; Program

@code{pushd} [ @code{-qsLP} ] [ @var{arg} ]

@code{pushd} [ @code{-qsLP} ] @var{old} @var{new}

@code{pushd} [ @code{-qsLP} ] @{@code{+|-}@}:var:@cite{n}

@quotation

Change the current directory, and push the old current directory
onto the directory stack.  In the first form, change the
current directory to @var{arg}.
If @var{arg} is not specified, change to the second directory
on the stack (that is, exchange the top two entries), or
change to @code{$HOME} if the @code{PUSHD_TO_HOME}
option is set or if there is only one entry on the stack.
Otherwise, @var{arg} is interpreted as it would be by @code{cd}.
The meaning of @var{old} and @var{new} in the second form is also
the same as for @code{cd}.

The third form of @code{pushd} changes directory by rotating the
directory list.  An argument of the form @code{+}@var{n} identifies a stack
entry by counting from the left of the list shown by the @code{dirs}
command, starting with zero.  An argument of the form @code{-}@var{n} counts
from the right.  If the @code{PUSHD_MINUS} option is set, the meanings
of @code{+} and @code{-} in this context are swapped.

If the @code{-q} (quiet) option is specified, the hook function @code{chpwd}
and the functions in the array @code{$chpwd_functions} are not called,
and the new directory stack is not printed.  This is useful for calls to
@code{pushd} that do not change the environment seen by an interactive user.

If the option @code{-q} is not specified and the shell option @code{PUSHD_SILENT}
is not set, the directory stack will be printed after a @code{pushd} is
performed.

The options @code{-s}, @code{-L} and @code{-P} have the same meanings as for the
@code{cd} builtin.
@end quotation

@geindex pushln; Function

@code{pushln} [ @var{arg} … ]

@quotation

Equivalent to @code{print -nz}.
@end quotation

@geindex pwd; Function

@geindex CHASE_LINKS@comma{} use of; Program

@code{pwd} [ @code{-rLP} ]

@quotation

Print the absolute pathname of the current working directory.
If the @code{-r} or the @code{-P} flag is specified, or the @code{CHASE_LINKS}
option is set and the @code{-L} flag is not given, the printed path will not
contain symbolic links.
@end quotation

@geindex r; Function

@code{r}

@quotation

Same as @code{fc -e -}.
@end quotation

@geindex read; Function

@geindex IFS@comma{} use of; Variable

@code{read} [ @code{-rszpqAclneE} ] [ @code{-t} [ @var{num} ] ] [ @code{-k} [ @var{num} ] ] [ @code{-d} @var{delim} ]

@quotation

@quotation

[ @code{-u} @var{n} ] [ [@var{name}][@code{?}@var{prompt}] ] [ @var{name} …  ]
@end quotation

@geindex REPLY@comma{} use of; Variable

@geindex reply@comma{} use of; Variable

Read one line and break it into fields using the characters
in @code{$IFS} as separators, except as noted below.
The first field is assigned to the first @var{name}, the second field
to the second @var{name}, etc., with leftover
fields assigned to the last @var{name}.
If @var{name} is omitted then
@code{REPLY} is used for scalars and @code{reply} for arrays.

@code{-r}

@quotation

Raw mode: a @code{\} at the end of a line does not signify line
continuation and backslashes in the line don’t quote the following
character and are not removed.
@end quotation

@code{-s}

@quotation

Don’t echo back characters if reading from the terminal.
@end quotation

@code{-q}

@quotation

Read only one character from the terminal and set @var{name} to
@code{y} if this character was @code{y} or @code{Y} and to @code{n} otherwise.
With this flag set the return status is zero only if the character was
@code{y} or @code{Y}.  This option may be used with a timeout (see @code{-t}); if
the read times out, or encounters end of file, status 2 is returned.  Input is
read from the terminal unless one of @code{-u} or @code{-p} is present.  This option
may also be used within zle widgets.
@end quotation

@code{-k} [ @var{num} ]

@quotation

Read only one (or @var{num}) characters.  All are assigned to the first
@var{name}, without word splitting.  This flag is ignored when @code{-q} is
present.  Input is read from the terminal unless one of @code{-u} or @code{-p}
is present.  This option may also be used within zle widgets.

Note that despite the mnemonic `key’ this option does read full
characters, which may consist of multiple bytes if the option
@code{MULTIBYTE} is set.
@end quotation

@code{-z}

@quotation

Read one entry from the editor buffer stack and assign it to the first
@var{name}, without word splitting.  Text is pushed onto the stack with
@code{print -z} or with @code{push-line} from the line editor (see
@code{zshzle}).
This flag is ignored when the @code{-k} or @code{-q} flags are present.
@end quotation

@code{-e}

@code{-E}

@quotation

The input read is printed (echoed) to the standard output.  If the @code{-e}
flag is used, no input is assigned to the parameters.
@end quotation

@code{-A}

@quotation

The first @var{name} is taken as the name of an array and all words are
assigned to it.
@end quotation

@code{-c}

@code{-l}

@quotation

These flags are allowed only if called inside a
function used for completion (specified with the @code{-K} flag to
@code{compctl}).  If the @code{-c} flag is given, the words of the
current command are read. If the @code{-l} flag is given, the whole
line is assigned as a scalar.  If both flags are present, @code{-l}
is used and @code{-c} is ignored.
@end quotation

@code{-n}

@quotation

Together with @code{-c}, the number of the word the cursor is on is
read.  With @code{-l}, the index of the character the cursor is on is
read.  Note that the command name is word number 1, not word 0,
and that when the cursor is at the end of the line, its character
index is the length of the line plus one.
@end quotation

@code{-u} @var{n}

@quotation

Input is read from file descriptor @var{n}.
@end quotation

@code{-p}

@quotation

Input is read from the coprocess.
@end quotation

@code{-d} @var{delim}

@quotation

Input is terminated by the first character of @var{delim} instead of
by newline.  For compatibility with other shells, if @var{delim} is an
empty string, input is terminated at the first NUL.
@end quotation

@code{-t} [ @var{num} ]

@quotation

Test if input is available before attempting to read.  If @var{num}
is present, it must begin with a digit and will be evaluated
to give a number of seconds, which may be a floating point number;
in this case the read times out if input is not available within this
time.  If @var{num} is not present, it is taken to be zero, so that
@code{read} returns immediately if no input is available.
If no input is available, return status 1 and do not set any variables.

This option is not available when reading from the editor buffer with
@code{-z}, when called from within completion with @code{-c} or @code{-l}, with
@code{-q} which clears the input queue before reading, or within zle where
other mechanisms should be used to test for input.

Note that read does not attempt to alter the input processing mode.  The
default mode is canonical input, in which an entire line is read at a time,
so usually @code{read -t} will not read anything until an entire line has
been typed.  However, when reading from the terminal with @code{-k}
input is processed one key at a time; in this case, only availability of
the first character is tested, so that e.g. @code{read -t -k 2} can still
block on the second character.  Use two instances of @code{read -t -k} if
this is not what is wanted.
@end quotation

If the first argument contains a @code{?}, the remainder of this
word is used as a @var{prompt} on standard error when the shell
is interactive.

The value (exit status) of @code{read} is 1 when an end-of-file is
encountered, or when @code{-c} or @code{-l} is present and the command is
not called from a @code{compctl} function, or as described for @code{-q}.
Otherwise the value is 0.

The behavior of some combinations of the @code{-k}, @code{-p}, @code{-q}, @code{-u}
and @code{-z} flags is undefined.  Presently @code{-q} cancels all the others,
@code{-p} cancels @code{-u}, @code{-k} cancels @code{-z}, and otherwise @code{-z}
cancels both @code{-p} and @code{-u}.

The @code{-c} or @code{-l} flags cancel any and all of @code{-kpquz}.
@end quotation

@geindex readonly; Function

@geindex parameters@comma{} marking readonly; Command

@code{readonly}

@quotation

Same as @code{typeset -r}.  With the @code{POSIX_BUILTINS} option set, same
as @code{typeset -gr}.
@end quotation

@geindex rehash; Function

@code{rehash}

@quotation

Same as @code{hash -r}.
@end quotation

@geindex return; Function

@geindex functions@comma{} returning from; Command

@code{return} [ @var{n} ]

@quotation

Causes a shell function or @code{.} script to return to
the invoking script with the return status specified by
an arithmetic expression @var{n}.  Also causes a non-interactive
shell to exit, allowing files containing shell code to be used
both as scripts and as autoloadable shell functions.
For example, the following prints @code{42}:

@example
 () @{ integer foo=40; return "foo + 2" @}
 echo $?
@end example

If @var{n}
is omitted, the return status is that of the last command
executed.

If @code{return} was executed from a trap in a @code{TRAP}@var{NAL} function,
the effect is different for zero and non-zero return status.  With zero
status (or after an implicit return at the end of the trap), the shell
will return to whatever it was previously processing; with a non-zero
status, the shell will behave as interrupted except that the return
status of the trap is retained.  Note that the numeric value of the signal
which caused the trap is passed as the first argument, so the statement
@code{return "128+$1"} will return the same status as if the signal
had not been trapped.
@end quotation

@code{sched}

@quotation

See @ref{96,,The zsh/sched Module}.
@end quotation

@geindex set; Function

@geindex parameters@comma{} listing; Command

@geindex parameters@comma{} positional; Command

@geindex parameters@comma{} setting array; Command

@geindex array parameters@comma{} setting; Command

@geindex KSH_ARRAYS@comma{} use of; Program

@code{set} [ @{@code{+|-}@}:var:@cite{options} | @{@code{+|-@}o} [ @var{option_name} ] ] … [ @{@code{+|-@}A} [ @var{name} ] ]

@quotation

[ @var{arg} … ]

Set the options for the shell and/or set the positional parameters, or
declare and set an array.  If the @code{-s} option is given, it causes the
specified arguments to be sorted before assigning them to the positional
parameters (or to the array @var{name} if @code{-A} is used).  With @code{+s}
sort arguments in descending order.  For the meaning of the other flags, see
@code{zshoptions}.
Flags may be specified by name using the @code{-o} option. If no option
name is supplied with @code{-o}, the current option states are printed:  see
the description of @code{setopt} below for more information on the format.
With @code{+o} they are printed in a form that can be used as input
to the shell.

If the @code{-A} flag is specified, @var{name} is set to an array containing
the given @var{arg}s; if no @var{name} is specified, all arrays are printed
together with their values.

If @code{+A} is used and @var{name} is an array, the
given arguments will replace the initial elements of that array; if no
@var{name} is specified, all arrays are printed without their values.

The behaviour of arguments after @code{-A} @var{name} or @code{+A} @var{name}
depends on whether the option @code{KSH_ARRAYS} is set.  If it is not set, all
arguments following @var{name} are treated as values for the array,
regardless of their form.  If the option is set, normal option processing
continues at that point; only regular arguments are treated as values for
the array.  This means that

@example
 set -A array -x -- foo
@end example

sets @code{array} to @code{-x -- foo} if @code{KSH_ARRAYS} is not set, but sets
the array to @code{foo} and turns on the option @code{-x} if it is set.

If the @code{-A} flag is not present, but there are arguments beyond the
options, the positional parameters are set.  If the option list (if any)
is terminated by @code{--}, and there are no further arguments, the
positional parameters will be unset.

If no arguments and no @code{--} are given, then the names and values of
all parameters are printed on the standard output.  If the only argument is
@code{+}, the names of all parameters are printed.

For historical reasons, @code{set -} is treated as @code{set +xv}
and @code{set -} @var{args} as @code{set +xv --} @var{args} when in
any other emulation mode than zsh’s native mode.
@end quotation

@code{setcap}

@quotation

See @ref{bb,,The zsh/cap Module}.
@end quotation

@geindex setopt; Function

@geindex options@comma{} setting; Command

@code{setopt} [ @{@code{+|-}@}:var:@cite{options} | @{@code{+|-@}o} @var{option_name} ] [ @code{-m} ] [ @var{name} … ]

@quotation

Set the options for the shell.  All options specified either
with flags or by name are set.

If no arguments are supplied, the names of all options currently set are
printed.  The form is chosen so as to minimize the differences from the
default options for the current emulation (the default emulation being
native @code{zsh}, shown as @code{<Z>} in
@ref{9c,,Description of Options}).
Options that are on by default for the emulation are
shown with the prefix @code{no} only if they are off, while other options are
shown without the prefix @code{no} and only if they are on.  In addition to
options changed from the default state by the user, any options activated
automatically by the shell (for example, @code{SHIN_STDIN} or @code{INTERACTIVE})
will be shown in the list.  The format is further modified by the option
@code{KSH_OPTION_PRINT}, however the rationale for choosing options with
or without the @code{no} prefix remains the same in this case.

If the @code{-m} flag is given the arguments are taken as patterns
(which should be quoted to protect them from filename expansion), and all
options with names matching these patterns are set.

Note that a bad option name does not cause execution of subsequent shell
code to be aborted; this behaviour is different from that of @code{set
-o}.  This is because`@w{`} set`@w{`} is regarded as a special builtin by the
POSIX standard, but @code{setopt} is not.
@end quotation

@geindex shift; Function

@geindex parameters@comma{} positional; Command

@code{shift} [ @code{-p} ] [ @var{n} ] [ @var{name} … ]

@quotation

The positional parameters @code{$@{}@var{n}+1`@w{`}@}`@w{`} … are renamed
to @code{$1} …, where @var{n} is an arithmetic expression that
defaults to 1.
If any @var{name}s are given then the arrays with these names are
shifted instead of the positional parameters.

If the option @code{-p} is given arguments are instead removed (popped)
from the end rather than the start of the array.
@end quotation

@geindex source; Function

@code{source} @var{file} [ @var{arg} … ]

@quotation

Same as @code{.}, except that the current directory is always searched and
is always searched first, before directories in @code{$path}.
@end quotation

@code{stat}

@quotation

See @ref{c7,,The zsh/stat Module}.
@end quotation

@geindex suspend; Function

@geindex shell@comma{} suspending; Command

@geindex suspending the shell; Command

@code{suspend} [ @code{-f} ]

@quotation

Suspend the execution of the shell (send it a @code{SIGTSTP})
until it receives a @code{SIGCONT}.
Unless the @code{-f} option is given, this will refuse to suspend a login shell.
@end quotation

@geindex test; Function

@code{test} [ @var{arg} … ]

@code{[} [ @var{arg} … ] @code{]}

@quotation

Like the system version of @code{test}.  Added for compatibility;
use conditional expressions instead (see
@ref{c8,,Conditional Expressions}).
The main differences between the conditional expression syntax and the
@code{test} and @code{[} builtins are:  these commands are not handled
syntactically, so for example an empty variable expansion may cause an
argument to be omitted; syntax errors cause status 2 to be returned instead
of a shell error; and arithmetic operators expect integer arguments rather
than arithmetic expressions.

The command attempts to implement POSIX and its extensions where these
are specified.  Unfortunately there are intrinsic ambiguities in
the syntax; in particular there is no distinction between test operators
and strings that resemble them.  The standard attempts to resolve these
for small numbers of arguments (up to four); for five or more arguments
compatibility cannot be relied on.  Users are urged wherever possible to
use the @code{[[} test syntax which does not have these ambiguities.
@end quotation

@geindex times; Function

@geindex shell@comma{} timing; Command

@geindex timing the shell; Command

@code{times}

@quotation

Print the accumulated user and system times for the shell
and for processes run from the shell.
@end quotation

@geindex trap; Function

@geindex signals@comma{} trapping; Command

@geindex trapping signals; Command

@code{trap} [ @var{arg} ] [ @var{sig} … ]

@quotation

@var{arg} is a series of commands (usually quoted to protect it from
immediate evaluation by the shell) to be read and executed when the shell
receives any of the signals specified by one or more @var{sig} args.
Each @var{sig} can be given as a number,
or as the name of a signal either with or without the string @code{SIG}
in front (e.g. 1, HUP, and SIGHUP are all the same signal).

If @var{arg} is @code{-}, then the specified signals are reset to their
defaults, or, if no @var{sig} args are present, all traps are reset.

If @var{arg} is an empty string, then the specified signals
are ignored by the shell (and by the commands it invokes).

If @var{arg} is omitted but one or more @var{sig} args are provided (i.e.
the first argument is a valid signal number or name), the effect is the
same as if @var{arg} had been specified as @code{-}.

The @code{trap} command with no arguments prints a list of commands
associated with each signal.

If @var{sig} is @code{ZERR} then @var{arg} will be executed
after each command with a nonzero exit status.  @code{ERR} is an alias
for @code{ZERR} on systems that have no @code{SIGERR} signal (this is the
usual case).

If @var{sig} is @code{DEBUG} then @var{arg} will be executed
before each command if the option @code{DEBUG_BEFORE_CMD} is set
(as it is by default), else after each command.  Here, a `command’ is
what is described as a `sublist’ in the shell grammar, see
@ref{c9,,Simple Commands & Pipelines}.
If @code{DEBUG_BEFORE_CMD} is set various additional features are available.
First, it is possible to skip the next command by setting the option
@code{ERR_EXIT}; see the description of the @code{ERR_EXIT} option in
@code{zshoptions}.  Also, the shell parameter
@code{ZSH_DEBUG_CMD} is set to the string corresponding to the command
to be executed following the trap.  Note that this string is reconstructed
from the internal format and may not be formatted the same way as the
original text.  The parameter is unset after the trap is executed.

If @var{sig} is @code{0} or @code{EXIT}
and the @code{trap} statement is executed inside the body of a function,
then the command @var{arg} is executed after the function completes.
The value of @code{$?} at the start of execution is the exit status of the
shell or the return status of the function exiting.
If @var{sig} is @code{0} or @code{EXIT}
and the @code{trap} statement is not executed inside the body of a function,
then the command @var{arg} is executed when the shell terminates; the
trap runs before any @code{zshexit} hook functions.

@code{ZERR}, @code{DEBUG}, and @code{EXIT} traps are not executed inside other
traps.  @code{ZERR} and @code{DEBUG} traps are kept within subshells, while
other traps are reset.

Note that traps defined with the @code{trap} builtin are slightly different
from those defined as @code{TRAP}@var{NAL} () @{ … @}, as the latter have
their own function environment (line numbers, local variables, etc.) while
the former use the environment of the command in which they were called.
For example,

@example
 trap 'print $LINENO' DEBUG
@end example

will print the line number of a command executed after it has run, while

@example
 TRAPDEBUG() @{ print $LINENO; @}
@end example

will always print the number zero.

Alternative signal names are allowed as described under @code{kill} above.
Defining a trap under either name causes any trap under an alternative
name to be removed.  However, it is recommended that for consistency
users stick exclusively to one name or another.
@end quotation

@geindex true; Function

@geindex doing nothing@comma{} successfully; Command

@code{true} [ @var{arg} … ]

@quotation

Do nothing and return an exit status of 0.
@end quotation

@geindex ttyctl; Function

@geindex tty@comma{} freezing; Command

@code{ttyctl} [ @code{-fu} ]

@quotation

The @code{-f} option freezes the tty (i.e. terminal or terminal emulator), and
@code{-u} unfreezes it.
When the tty is frozen, no changes made to the tty settings by
external programs will be honored by the shell, except for changes in the
size of the screen; the shell will
simply reset the settings to their previous values as soon as each
command exits or is suspended.  Thus, @code{stty} and similar programs have
no effect when the tty is frozen.  Freezing the tty does not cause
the current state to be remembered: instead, it causes future changes
to the state to be blocked.

Without options it reports whether the terminal is frozen or not.

Note that, regardless of whether the tty is frozen or not, the
shell needs to change the settings when the line editor starts, so
unfreezing the tty does not guarantee settings made on the
command line are preserved.  Strings of commands run between
editing the command line will see a consistent tty state.
See also the shell variable @code{STTY} for a means of initialising
the tty before running external commands and/or freezing the tty
around a single command.
@end quotation

@geindex type; Function

@code{type} [ @code{-wfpamsS} ] @var{name} …

@quotation

Equivalent to @code{whence -v}.
@end quotation

@geindex typeset; Function

@geindex parameters@comma{} setting; Command

@geindex parameters@comma{} declaring; Command

@code{typeset} [ @{@code{+|-@}AHUaghlmrtux} ] [ @{@code{+|-@}EFLRZip} [ @var{n} ] ]

@quotation

[ @code{+} ] [ @var{name}[@code{=}@var{value}] … ]
@end quotation

@code{typeset @{+|-@}n} [ @code{-g} ] [ @{@code{+|-@}r} ] [ @var{name}[@code{=}@var{value}] … ]

@code{typeset -T} [ @{@code{+|-@}Uglrux} ] [ @{@code{+|-@}LRZp} [ @var{n} ] ]

@quotation

[ @code{+} | @var{SCALAR}[@code{=}@var{value}] @var{array}[@code{=(}@var{value} …`@w{`})`@w{`}] [ @var{sep} ] ]
@end quotation

@code{typeset} @code{-f} [ @{@code{+|-@}TUkmtuz} ] [ @code{+} ] [ @var{name} … ]

@quotation

Set or display attributes and values for shell parameters.

Except as noted below for control flags that change the behavior,
a parameter is created for each @var{name} that does not already refer
to one.  When inside a function, a new parameter is created for every
@var{name} (even those that already exist), and is unset again when the
function completes.  See @ref{40,,Local Parameters}.
The same rules apply to special shell parameters, which
retain their special attributes when made local.

For each @var{name}@code{=}@var{value} assignment, the parameter
@var{name} is set to @var{value}.  If the assignment is omitted and @var{name}
does `not' refer to an existing parameter, a new parameter is initialized
to empty string, zero, or empty array (as appropriate), `unless' the
shell option @code{TYPESET_TO_UNSET} is set.  When that option is set,
the parameter attributes are recorded but the parameter remains unset.

If the shell option @code{TYPESET_SILENT} is not set, for each remaining
@var{name} that refers to a parameter that is already set, the name and
value of the parameter are printed in the form of an assignment.
Nothing is printed for newly-created parameters, or when any attribute
flags listed below are given along with the @var{name}.  Using
@code{+} instead of minus to introduce an attribute turns it off.

If no @var{name} is present, the names and values of all parameters are
printed.  In this case the attribute flags restrict the display to only
those parameters that have the specified attributes, and using @code{+}
rather than @code{-} to introduce the flag suppresses printing of the values
of parameters when there is no parameter name.

All forms of the command handle scalar assignment.  Array assignment is
possible if any of the reserved words @code{declare}, @code{export}, @code{float},
@code{integer}, @code{local}, @code{readonly} or @code{typeset} is matched when the
line is parsed (N.B. not when it is executed).  In this case the arguments
are parsed as assignments, except that the @code{+=} syntax and the
@code{GLOB_ASSIGN} option are not supported, and scalar values after @code{=}
are `not' split further into words, even if expanded (regardless of the
setting of the @code{KSH_TYPESET} option; this option is obsolete).

Examples of the differences between command and reserved word parsing:

@example
 # Reserved word parsing
 typeset svar=$(echo one word) avar=(several words)
@end example

The above creates a scalar parameter @code{svar} and an array
parameter @code{avar} as if the assignments had been

@example
 svar="one word"
 avar=(several words)
@end example

On the other hand:

@example
 # Normal builtin interface
 builtin typeset svar=$(echo two words)
@end example

The @code{builtin} keyword causes the above to use the standard builtin
interface to @code{typeset} in which argument parsing is performed in the same
way as for other commands.  This example creates a scalar @code{svar}
containing the value @code{two} and another scalar parameter @code{words} with
no value.  An array value in this case would either cause an error or be
treated as an obscure set of glob qualifiers.

Arbitrary arguments are allowed if they take the form of assignments
after command line expansion; however, these only perform scalar
assignment:

@example
 var='svar=val'
 typeset $var
@end example

The above sets the scalar parameter @code{svar} to the value @code{val}.
Parentheses around the value within @code{var} would not cause array
assignment as they will be treated as ordinary characters when @code{$var}
is substituted.  Any non-trivial expansion in the name part of the
assignment causes the argument to be treated in this fashion:

@example
 typeset @{var1,var2,var3@}=name
@end example

The above syntax is valid, and has the expected effect of setting the
three parameters to the same value, but the command line is parsed as
a set of three normal command line arguments to @code{typeset} after
expansion.  Hence it is not possible to assign to multiple arrays by
this means.

Note that each interface to any of the commands may be disabled
separately.  For example, @code{disable -r typeset} disables the reserved
word interface to @code{typeset}, exposing the builtin interface, while
@code{disable typeset} disables the builtin.  Note that disabling the
reserved word interface for @code{typeset} may cause problems with the
output of @code{typeset -p}, which assumes the reserved word interface is
available in order to restore array and associative array values.

Unlike parameter assignment statements, @code{typeset}’s exit status on an
assignment that involves a command substitution does not reflect the exit
status of the command substitution.  Therefore, to test for an error in
a command substitution, separate the declaration of the parameter from its
initialization:

@example
 # WRONG
 typeset var1=$(exit 1) || echo "Trouble with var1"

 # RIGHT
 typeset var1 && var1=$(exit 1) || echo "Trouble with var1"
@end example

To initialize a parameter @var{param} to a command output and mark it readonly,
use @code{typeset -r} @var{param} or @code{readonly} @var{param} after the parameter
assignment statement.

@geindex named reference; Command

@geindex reference@comma{} named; Command

The flag @code{-n} creates a `named reference' to another parameter.
The second parameter need not exist at the time the reference is
created.  Only the @code{-H}, @code{-g}, and @code{-r} flags may be used in
conjunction with @code{-n}, having their usual meanings.  The @code{-u}
flag is special and may be applied to alter the scope of the reference.
The @var{name} so created may not be an array element nor use
a subscript, but the @var{value} assigned may be any valid parameter
name syntax, even a subscripted array element (including an associative
array element) or an array slice, which is evaluated when the named
reference is expanded.  It is an error for a named reference to refer
to itself, even indirectly through a chain of references.  When @code{-u}
is applied to a named reference, the parameter identified by @var{value}
is always found in the calling function scope rather than the current
local scope.  In this case, if there is no such parameter in the calling
scope, assignments to the named reference may fail, setting @code{$?} to 1.
See @ref{1a,,Parameter Expansion} and
@ref{71,,Named References} for details of the
behavior of named references.

Local function scoping rules for @code{typeset} do apply with @code{-n},
so a declaration within a function persists only until the end of the
function unless @code{-g -n} is specified, and any local parameter (of
any type) with the same @var{name} supplants a named reference from a
surrounding scope.

A scalar parameter, including an existing named reference, may be
converted to a new named reference by @code{typeset -n} @var{name}, so
the @code{-p} option must be included to display the value of a
specific named reference @var{name}.

If no attribute flags are given, and either no @var{name} arguments are
present or the flag @code{+m} is used, then each parameter name printed is
preceded by a list of the attributes of that parameter (@code{array},
@code{association}, @code{exported}, @code{float}, @code{integer}, @code{readonly},
or @code{undefined} for autoloaded parameters not yet loaded).  If @code{+m} is
used with attribute flags, and all those flags are introduced with
@code{+}, the matching parameter names are printed but their values
are not.

The following control flags change the behavior of @code{typeset}:

@code{+}

@quotation

If @code{+} appears by itself in a separate word as the last option,
then the names of all parameters (functions with @code{-f}) are printed, but
the values (function bodies) are not.  If @var{name} arguments appear,
both those names and their values are printed in the form of assignments.
It is an error for any other options to follow @code{+}, but the
effect of @code{+} is as if all attribute flags which precede it were
given with a @code{+} prefix.  For example, @code{typeset -U +} is
equivalent to @code{typeset +U} and displays the names of all arrays having
the uniqueness attribute, whereas @code{typeset -f -U +} displays the
names of all autoloadable functions.  If @code{+} is the only option,
then type information (array, readonly, etc.) is also printed for each
parameter, in the same manner as @code{typeset +m "*"}.
@end quotation

@code{-g}

@quotation

The @code{-g} (global) means that any resulting parameter will not be
restricted to local scope.  Note that this does not necessarily mean that
the parameter will be global, as the flag will apply to any existing
parameter (even if unset) from an enclosing function.  This flag does not
affect the parameter after creation, hence it has no effect when listing
existing parameters, nor does the flag @code{+g} have any effect except in
combination with @code{-m} (see below).
@end quotation

@code{-m}

@quotation

If the @code{-m} flag is given the @var{name} arguments are taken as patterns
(use quoting to prevent these from being interpreted as file patterns).
With no attribute flags, all parameters (or functions with the @code{-f}
flag) with matching names are printed (the shell option @code{TYPESET_SILENT}
is not used in this case).

If the @code{+g} flag is combined with @code{-m}, a new local parameter is
created for every matching parameter that is not already local.  Otherwise
@code{-m} applies all other flags or assignments to the existing parameters,
except that the @code{-n} option cannot create named references in this way.

Except when assignments are made with @var{name}@code{=}@var{value}, using
@code{+m} forces the matching parameters and their attributes to be printed,
even inside a function.  Note that @code{-m} is ignored if no patterns are
given, so @code{typeset -m} displays attributes but @code{typeset -a +m}
does not.  Ordinary scalar string parameters have no attributes, so for
those @code{+m} prints only the names.
@end quotation

@code{-p} [ @var{n} ]

@quotation

If the @code{-p} option is given, parameters and values are printed in the
form of a typeset command with an assignment, regardless of other flags
and options.  Note that the @code{-H} flag on parameters is respected; no
value will be shown for these parameters.

@code{-p} may be followed by an optional integer argument.  Currently
only the value @code{1} is supported.  In this case arrays and associative
arrays are printed with newlines between indented elements for
readability.

The names and values of readonly special parameters
(most of the parameters marked `<S>’ in
@ref{93,,Parameters Set by the Shell},
except those documented as settable)
are not printed with @code{-p} because to execute those typeset commands
would cause errors.  However, these parameters are printed when they
have been made local to the scope where @code{typeset -p} is run.
@end quotation

@code{-T} [ @var{scalar}[@code{=}@var{value}] @var{array}[@code{=(}@var{value} …`@w{`})`@w{`}] [ @var{sep} ] ]

@quotation

This flag has a different meaning when used with @code{-f}; see below.
Otherwise the @code{-T} option requires zero, two, or three arguments to be
present.  With no arguments, the list of parameters created in this
fashion is shown.  With two or three arguments, the first two are the name
of a scalar and of an array parameter (in that order) that will be tied
together in the manner of @code{$PATH} and @code{$path}.  The optional third
argument is a single-character separator which will be used to join the
elements of the array to form the scalar; if absent, a colon is used, as
with @code{$PATH}.  Only the first character of the separator is significant;
any remaining characters are ignored.  Multibyte characters are not
yet supported.

Only one of the scalar and array parameters may be assigned an initial
value (the restrictions on assignment forms described above also apply).

Both the scalar and the array may be manipulated as normal.  If one is
unset, the other will automatically be unset too.  There is no way of
untying the variables without unsetting them, nor of converting the type
of one of them with another @code{typeset} command; @code{+T} does not work,
assigning an array to @var{scalar} is an error, and assigning a scalar to
@var{array} sets it to be a single-element array.

Note that both @code{typeset -xT ...}  and @code{export -T ...} work, but
only the scalar will be marked for export.  Setting the value using the
scalar version causes a split on all separators (which cannot be quoted).
It is possible to apply @code{-T} to two previously tied variables but with a
different separator character, in which case the variables remain joined
as before but the separator is changed.

When an existing scalar is tied to a new array, the value of the scalar
is preserved but no attribute other than export will be preserved.
@end quotation

Attribute flags that transform the final value (@code{-L}, @code{-R}, @code{-Z},
@code{-l}, @code{-u}) are only applied to the expanded value at the point
of a parameter expansion expression using @code{$}.  They are not applied
when a parameter is retrieved internally by the shell for any purpose.

The following attribute flags may be specified:

@code{-A}

@quotation

The names refer to associative array parameters; see
@ref{1b,,Array Parameters}.
@end quotation

@code{-L} [ @var{n} ]

@quotation

Left justify and remove leading blanks from the value when the parameter
is expanded.
If @var{n} is nonzero, it defines the width of the field.
If @var{n} is zero, the width is determined by the width of the value of
the first assignment.  In the case of numeric parameters, the length of the
complete value assigned to the parameter is used to determine the width,
not the value that would be output.

The width is the count of characters, which may be multibyte characters
if the @code{MULTIBYTE} option is in effect.  Note that the screen
width of the character is not taken into account; if this is required,
use padding with parameter expansion flags
@code{$@{(ml}@var{…}@code{)}@var{…}@code{@}} as described in
@ref{6e,,Parameter Expansion Flags}.

When the parameter is expanded, it is filled on the right with
blanks or truncated if necessary to fit the field.
Note truncation can lead to unexpected results with numeric parameters.
Leading zeros are removed if the @code{-Z} flag is also set.
@end quotation

@code{-R} [ @var{n} ]

@quotation

Similar to @code{-L}, except that right justification is used;
when the parameter is expanded, the field is left filled with
blanks or truncated from the end.  May not be combined with the @code{-Z}
flag.
@end quotation

@code{-U}

@quotation

For arrays (but not for associative arrays), keep only the first
occurrence of each duplicated value.  This may also be set for tied
parameters (see @code{-T}) or colon-separated special parameters like
@code{PATH} or @code{FIGNORE}, etc.  Note the flag takes effect on assignment,
and the type of the variable being assigned to is determinative; for
variables with shared values it is therefore recommended to set the flag
for all interfaces, e.g. @code{typeset -U PATH path}.

This flag has a different meaning when used with @code{-f}; see below.
@end quotation

@code{-Z} [ @var{n} ]

@quotation

Specially handled if set along with the @code{-L} flag.
Otherwise, similar to @code{-R}, except that leading zeros are used for
padding instead of blanks if the first non-blank character is a digit.
Numeric parameters are specially handled: they are always eligible
for padding with zeroes, and the zeroes are inserted at an appropriate
place in the output.
@end quotation

@code{-a}

@quotation

The names refer to array parameters.  An array parameter may be
created this way, but it may be assigned to in the @code{typeset}
statement only if the reserved word form of @code{typeset} is enabled
(as it is by default).  When displaying, both normal and associative
arrays are shown.
@end quotation

@code{-f}

@quotation

The names refer to functions rather than parameters.  No assignments
can be made, and the only other valid flags are @code{-t}, @code{-T}, @code{-k},
@code{-u}, @code{-U} and @code{-z}.  The flag @code{-t} turns on execution tracing
for this function; the flag @code{-T} does the same, but turns off tracing
for any named (not anonymous) function called from the present one,
unless that function also
has the @code{-t} or @code{-T} flag.  The @code{-u} and @code{-U} flags cause the
function to be marked for autoloading; @code{-U} also causes alias
expansion to be suppressed when the function is loaded.  See the
description of the @code{autoload} builtin for details.

Note that the builtin @code{functions} provides the same basic capabilities
as @code{typeset -f} but gives access to a few extra options; @code{autoload}
gives further additional options for the case @code{typeset -fu} and
@code{typeset -fU}.
@end quotation

@code{-h}

@quotation

Hide: only useful for special parameters (those marked `<S>’ in the table in
@ref{93,,Parameters Set by the Shell}),
and for local parameters with the same name as a special parameter,
though harmless for others.  A special parameter with this attribute will
not retain its special effect when made local.  Thus after @code{typeset -h
PATH}, a function containing`@w{`} typeset PATH`@w{`} will create an ordinary
local parameter without the usual behaviour of @code{PATH}.  Alternatively,
the local parameter may itself be given this attribute; hence inside a
function @code{typeset -h PATH} creates an ordinary local parameter and the
special @code{PATH} parameter is not altered in any way.  It is also possible
to create a local parameter using @code{typeset +h} @var{special}, where the
local copy of @var{special} will retain its special properties regardless of
having the @code{-h} attribute.  Global special parameters loaded from shell
modules (for example, those in @code{zsh/mapfile} and @code{zsh/parameter}) are
automatically given the @code{-h} attribute to avoid name clashes.
@end quotation

@code{-H}

@quotation

Hide value: specifies that @code{typeset} will not display the value of the
parameter when listing parameters; the display for such parameters is
always as if the @code{+} flag were given, but use of the parameter is
in other respects normal.  This effect does not apply when the parameter is
specified by name or by pattern with the @code{-m} option.  This is on by
default for the parameters in the @code{zsh/parameter} and @code{zsh/mapfile}
modules.  Note, however, that unlike the @code{-h} flag this is also useful
for non-special parameters.
@end quotation

@code{-i} [ @var{n} ]

@quotation

Use an internal integer representation.  If @var{n} is nonzero it
defines the output arithmetic base, otherwise it is determined by the
first assignment.  Bases from 2 to 36 inclusive are allowed.
@end quotation

@code{-E} [ @var{n} ]

@quotation

Use an internal double-precision floating point representation.  On output
the variable will be converted to scientific notation.  If @var{n} is
nonzero it defines the number of significant figures to display; the
default is ten.
@end quotation

@code{-F} [ @var{n} ]

@quotation

Use an internal double-precision floating point representation.  On output
the variable will be converted to fixed-point decimal notation.  If @var{n}
is nonzero it defines the number of digits to display after the decimal
point; the default is ten.
@end quotation

@code{-l}

@quotation

Convert the result to lower case whenever the parameter is expanded.
The value is `not' converted when assigned.
@end quotation

@code{-r}

@quotation

The given @var{name}s are marked readonly.  Note that if @var{name} is a
special parameter, the readonly attribute can be turned on, but cannot then
be turned off.

If the @code{POSIX_BUILTINS} option is set, the readonly attribute is
more restrictive: unset variables can be marked readonly and cannot then
be set; furthermore, the readonly attribute cannot be removed from any
variable.

It is still possible to change other attributes of the variable though,
some of which like @code{-U} or @code{-Z} would affect the value. More generally,
the readonly attribute should not be relied on as a security mechanism.

Note that in zsh (like in pdksh but unlike most other shells) it is
still possible to create a local variable of the same name as this is
considered a different variable (though this variable, too, can be marked
readonly). Special variables that have been made readonly retain their value
and readonly attribute when made local.
@end quotation

@code{-t}

@quotation

Tags the named parameters.  Tags only exist to flag the parameter for
the user’s own purposes — the list of tagged parameters can be queried
using @code{typeset -t}.  Tags have no other use.  Note that the @code{-t}
flag has a different meaning when used with @code{-f}; see above.
@end quotation

@code{-u}

@quotation

Convert the result to upper case whenever the parameter is expanded.
The value is `not' converted when assigned.
This flag has different meanings when used with @code{-f} or @code{-n}; see above.
@end quotation

@code{-x}

@quotation

Mark for automatic export to the environment of subsequently
executed commands.  If the option @code{GLOBAL_EXPORT} is set, this implies
the option @code{-g}, unless @code{+g} is also explicitly given; in other words
the parameter is not made local to the enclosing function.  This is for
compatibility with previous versions of zsh.
@end quotation
@end quotation

@geindex ulimit; Function

@geindex resource limits; Command

@geindex limits@comma{} resource; Command

@code{ulimit} [ @code{-HSa} ] [ @{ @code{-bcdfiklmnpqrsTtvwx} | @code{-N} @var{resource} @} [ @var{limit} ] … ]

@quotation

Set or display resource limits of the shell and the processes started by
the shell.  The value of @var{limit} can be a number in the unit specified
below or one of the values @code{unlimited}, which removes the limit on the
resource, or @code{hard}, which uses the current value of the hard limit on
the resource.

By default, only soft limits are manipulated. If the @code{-H} flag
is given use hard limits instead of soft limits.  If the @code{-S} flag is given
together with the @code{-H} flag set both hard and soft limits.

If no options are used, the file size limit (@code{-f}) is assumed.

If @var{limit} is omitted the current value of the specified resources are
printed.  When more than one resource value is printed, the limit name and
unit is printed before each value.

When looping over multiple resources, the shell will abort immediately if
it detects a badly formed argument.  However, if it fails to set a limit
for some other reason it will continue trying to set the remaining limits.

Not all the following resources are supported on all systems.  Running
@code{ulimit -a} will show which are supported.


@table @asis

@item @code{-a}

List all of the current resource limits.

@item @code{-b}

Socket buffer size in bytes (N.B. not kilobytes)

@item @code{-c}

512-byte blocks on the size of core dumps.

@item @code{-d}

Kilobytes on the size of the data segment.

@item @code{-e}

Maximum nice value.

@item @code{-f}

512-byte blocks on the size of files written.

@item @code{-i}

The number of pending signals.

@item @code{-k}

The number of kqueues allocated.

@item @code{-l}

Kilobytes on the size of locked-in memory.

@item @code{-m}

Kilobytes on the size of physical memory.

@item @code{-n}

Open file descriptors.

@item @code{-o}

Maximum number of POSIX thread library objects.

@item @code{-p}

The number of pseudo-terminals.

@item @code{-q}

Bytes in POSIX message queues.

@item @code{-r}

Maximum real time priority.  On some systems where this
is not available, such as NetBSD, this has the same effect as @code{-T}
for compatibility with @code{sh}.

@item @code{-s}

Kilobytes on the size of the stack.

@item @code{-T}

The number of simultaneous threads available to the user.

@item @code{-t}

CPU seconds to be used.

@item @code{-u}

The number of processes available to the user.

@item @code{-v}

Kilobytes on the size of virtual memory.  On some systems this
refers to the limit called `address space’.

@item @code{-w}

Kilobytes on the size of swapped out memory.

@item @code{-x}

The number of locks on files.

@item @code{-y}

Maximum size of buffers for pipes/fifos.
@end table

A resource may also be specified by integer in the form @code{-N}
@var{resource}, where @var{resource} corresponds to the integer defined for
the resource by the operating system.  This may be used to set the limits
for resources known to the shell which do not correspond to option letters.
Such limits will be shown by number in the output of @code{ulimit -a}.

The number may alternatively be out of the range of limits compiled into
the shell.  The shell will try to read or write the limit anyway, and
will report an error if this fails.
@end quotation

@geindex umask; Function

@geindex umask; Command

@code{umask} [ @code{-S} ] [ @var{mask} ]

@quotation

The umask is set to @var{mask}.  @var{mask} can be either
an octal number or a symbolic value as described in the @code{chmod(1)} man page.
If @var{mask} is omitted, the current value is printed.  The @code{-S}
option causes the mask to be printed as a symbolic value.  Otherwise,
the mask is printed as an octal number.  Note that in
the symbolic form the permissions you specify are those which are to be
allowed (not denied) to the users specified.
@end quotation

@geindex unalias; Function

@geindex aliases@comma{} removing; Command

@code{unalias} [ @code{-ams} ] @var{name} …

@quotation

Removes aliases.  This command works the same as @code{unhash -a}, except that
the @code{-a} option removes all regular or global aliases, or with @code{-s}
all suffix aliases: in this case no @var{name} arguments may appear.  The
options @code{-m} (remove by pattern) and @code{-s} without @code{-a} (remove
listed suffix aliases) behave as for @code{unhash -a}.  Note that
the meaning of @code{-a} is different between @code{unalias} and @code{unhash}.
@end quotation

@geindex functions@comma{} removing; Command

@geindex unfunction; Function

@code{unfunction}

@quotation

Same as @code{unhash -f}.
@end quotation

@geindex unhash; Function

@code{unhash} [ @code{-adfms} ] @var{name} …

@quotation

Remove the element named @var{name} from an internal hash table.  The
default is remove elements from the command hash table.  The @code{-a}
option causes @code{unhash} to remove regular or global aliases; note
when removing a global aliases that the argument must be quoted to prevent
it from being expanded before being passed to the command.
The @code{-s} option causes @code{unhash} to remove suffix aliases.
The @code{-f} option causes
@code{unhash} to remove shell functions.  The @code{-d} options causes
@code{unhash} to remove named directories.  If the @code{-m} flag is given
the arguments are taken as patterns (should be quoted) and all elements
of the corresponding hash table with matching names will be removed.
@end quotation

@geindex unlimit; Function

@geindex resource limits; Command

@geindex limits@comma{} resource; Command

@code{unlimit} [ @code{-hs} ] @var{resource} …

@quotation

The resource limit for each @var{resource} is set to the hard limit.
If the @code{-h} flag is given and the shell has appropriate privileges,
the hard resource limit for each @var{resource} is removed.
The resources of the shell process are only changed if the @code{-s}
flag is given.

The @code{unlimit} command is not made available by default when the
shell starts in a mode emulating another shell.  It can be made available
with the command @code{zmodload -F zsh/rlimits b:unlimit}.
@end quotation

@geindex unset; Function

@geindex parameters@comma{} unsetting; Command

@code{unset} [ @code{-fmv} ] [ @code{-n} ] @var{name} …

@quotation

Each named parameter is unset.
Local parameters remain local even if unset; they appear unset within scope,
but the previous value will still reappear when the scope ends.

Individual elements of associative array parameters may be unset by using
subscript syntax on @var{name}, which should be quoted (or the entire command
prefixed with @code{noglob}) to protect the subscript from filename generation.

If the @code{-m} flag is specified the arguments are taken as patterns (should
be quoted) and all parameters with matching names are unset.  Note that this
cannot be used when unsetting associative array elements, as the subscript
will be treated as part of the pattern.

The @code{-v} flag specifies that @var{name} refers to parameters. This is
the default behaviour.  If the @code{-n} option is supplied, and
@var{name} is a a named reference, @var{name} will be unset rather than
the variable it references.

@code{unset -f} is equivalent to @code{unfunction}.  The @code{-n} option has
no effect with @code{-f}.
@end quotation

@geindex unsetopt; Function

@geindex options@comma{} unsetting; Command

@code{unsetopt} [ @{@code{+|-}@}:var:@cite{options} | @{@code{+|-@}o} @var{option_name} ] [ @var{name} … ]

@quotation

Unset the options for the shell.  All options specified either
with flags or by name are unset.  If no arguments are supplied,
the names of all options currently unset are printed.
If the @code{-m} flag is given the arguments are taken as patterns
(which should be quoted to preserve them from being interpreted as glob
patterns), and all options with names matching these patterns are unset.
@end quotation

@code{vared}

@quotation

See @ref{ba,,Zle Builtins}.
@end quotation

@geindex wait; Function

@geindex waiting for jobs; Command

@geindex jobs@comma{} waiting for; Command

@code{wait} [ @var{job} … ]

@quotation

Wait for the specified jobs or processes.  If @var{job} is not given
then all currently active child processes are waited for.
Each @var{job} can be either a job specification or the process ID
of a job in the job table.
The exit status from this command is that of the job waited for.
If @var{job} represents an unknown job or process ID, a warning is printed
(unless the @code{POSIX_BUILTINS} option is set) and the exit status is 127.

It is possible to wait for recent processes (specified by process ID,
not by job) that were running in the background even if the process has
exited.  Typically the process ID will be recorded by capturing the
value of the variable @code{$!} immediately after the process has been
started.  There is a limit on the number of process IDs remembered by
the shell; this is given by the value of the system configuration
parameter @code{CHILD_MAX}.  When this limit is reached, older process IDs
are discarded, least recently started processes first.

Note there is no protection against the process ID wrapping, i.e. if the
wait is not executed soon enough there is a chance the process waited
for is the wrong one.  A conflict implies both process IDs have been
generated by the shell, as other processes are not recorded, and that
the user is potentially interested in both, so this problem is intrinsic
to process IDs.
@end quotation

@geindex whence; Function

@code{whence} [ @code{-vcwfpamsS} ] [ @code{-x} @var{num} ] @var{name} …

@quotation

For each @var{name}, indicate how it would be interpreted if used as a
command name.

If @var{name} is not an alias, built-in command, external command, shell
function, hashed command, or a reserved word, the exit status shall be
non-zero, and – if @code{-v}, @code{-c}, or @code{-w} was passed – a message
will be written to standard output.  (This is different from other shells that
write that message to standard error.)

@code{whence} is most useful when @var{name} is only the last path component
of a command, i.e. does not include a @code{/}; in particular, pattern
matching only succeeds if just the non-directory component of the command is
passed.

@code{-v}

@quotation

Produce a more verbose report.
@end quotation

@code{-c}

@quotation

Print the results in a `csh'-like format.
This takes precedence over @code{-v}.
@end quotation

@code{-w}

@quotation

For each @var{name}, print @var{name}@code{:} @var{word} where @var{word}
is one of @code{alias}, @code{builtin}, @code{command}, @code{function},
@code{hashed}, @code{reserved} or @code{none}, according as @var{name}
corresponds to an alias, a built-in command, an external command, a
shell function, a command defined with the @code{hash} builtin, a
reserved word, or is not recognised.  This takes precedence over
@code{-v} and @code{-c}.
@end quotation

@code{-f}

@quotation

Causes the contents of a shell function to be
displayed, which would otherwise not happen unless the @code{-c}
flag were used.
@end quotation

@code{-p}

@quotation

Do a path search for @var{name}
even if it is an alias, reserved word, shell function or builtin.
@end quotation

@code{-a}

@quotation

Do a search for all occurrences of @var{name}
throughout the command path.
Normally only the first occurrence is printed.
When combined with @code{-m}, only names appearing in the command hash
table are searched, but all occurrences of those names are printed.
@end quotation

@code{-m}

@quotation

The arguments are taken as patterns (pattern characters should be
quoted), and the information is displayed for each entry in the command
hash table matching one of these patterns.  The hash table is first
refilled, in case of changes to @code{PATH}.
@end quotation

@code{-s}

@quotation

If a pathname contains symlinks, print the symlink-free pathname as well.
@end quotation

@code{-S}

@quotation

As @code{-s}, but if the pathname had to be resolved by following
multiple symlinks, the intermediate steps are printed, too.  The
symlink resolved at each step might be anywhere in the path.
@end quotation

@code{-x} @var{num}

@quotation

Expand tabs when outputting shell functions using the @code{-c} option.
This has the same effect as the @code{-x} option to the @code{functions}
builtin.
@end quotation
@end quotation

@geindex where; Function

@code{where} [ @code{-wpmsS} ] [ @code{-x} @var{num} ] @var{name} …

@quotation

Equivalent to @code{whence -ca}.
@end quotation

@geindex which; Function

@code{which} [ @code{-wpamsS} ] [ @code{-x} @var{num} ] @var{name} …

@quotation

Equivalent to @code{whence -c}.
@end quotation

@geindex zcompile; Function

@geindex .zwc files@comma{} creation; Command

@geindex compilation; Command

@code{zcompile} [ @code{-U} ] [ @code{-z} | @code{-k} ] [ @code{-R} | @code{-M} ] @var{file} [ @var{name} … ]

@code{zcompile} @code{-ca} [ @code{-m} ] [ @code{-R} | @code{-M} ] @var{file} [ @var{name} … ]

@code{zcompile -t} @var{file} [ @var{name} … ]

@quotation

This builtin command can be used to compile functions or scripts,
storing the compiled form in a file, and to examine files containing
the compiled form.  This allows faster autoloading of functions and
sourcing of scripts by avoiding parsing of the text when the files
are read.

The first form (without the @code{-c}, @code{-a} or @code{-t} options) creates a
compiled file.  If only the @var{file} argument is given, the
output file has the name @var{file}@code{.zwc} and will be placed in
the same directory as the @var{file}.  The shell will load the compiled
file instead of the normal function file when the function
is autoloaded; see @ref{b9,,Autoloading Functions}
for a description of how autoloaded functions are searched.  The
extension @code{.zwc} stands for `zsh word code’.

@geindex fpath@comma{} with zcompile; Variable

If there is at least one @var{name} argument, all the named files
are compiled into the output @var{file} given as the first argument.  If
@var{file} does not end in @code{.zwc}, this extension is automatically
appended.  Files containing multiple compiled functions are called `digest’
files, and are intended to be used as elements of the @code{FPATH/fpath}
special array.

The second form, with the @code{-c} or @code{-a} options, writes the compiled
definitions for all the named functions into @var{file}.  For @code{-c}, the
names must be functions currently defined in the shell, not those marked
for autoloading.  Undefined functions that are marked for autoloading
may be written by using the @code{-a} option, in which case the @code{fpath}
is searched and the contents of the definition files for those
functions, if found, are compiled into @var{file}.  If both @code{-c} and
@code{-a} are given, names of both defined functions and functions marked
for autoloading may be given.  In either case, the functions in files
written with the @code{-c} or @code{-a} option will be autoloaded as if the
@code{KSH_AUTOLOAD} option were unset.

The reason for handling loaded and not-yet-loaded functions with
different options is that some definition files for autoloading define
multiple functions, including the function with the same name as the
file, and, at the end, call that function.  In such cases the output of
@code{zcompile -c} does not include the additional functions defined in
the file, and any other initialization code in the file is lost.  Using
@code{zcompile -a} captures all this extra information.

If the @code{-m} option is combined with @code{-c} or @code{-a},
the @var{name}s are used as patterns and all functions whose names
match one of these patterns will be written. If no @var{name} is given,
the definitions of all functions currently defined or marked as
autoloaded will be written.

Note the second form cannot be used for compiling functions that
include redirections as part of the definition rather than within
the body of the function; for example

@example
 fn1() @{ @{ ... @} >~/logfile @}
@end example

can be compiled but

@example
 fn1() @{ ... @} >~/logfile
@end example

cannot.  It is possible to use the first form of @code{zcompile} to compile
autoloadable functions that include the full function definition instead
of just the body of the function.

The third form, with the @code{-t} option, examines an existing
compiled file.  Without further arguments, the names of the original
files compiled into it are listed.  The first line of output shows
the version of the shell which compiled the file and how the file
will be used (i.e. by reading it directly or by mapping it into memory).
With arguments, nothing is output and the return status is set to zero if
definitions for `all' @var{name}s were found in the compiled
file, and non-zero if the definition for at least one @var{name} was not
found.

Other options:

@code{-U}

@quotation

Aliases are not expanded when compiling the @var{name}d files.
@end quotation

@code{-R}

@quotation

When the compiled file is read, its contents are copied into the
shell’s memory, rather than memory-mapped (see @code{-M}).  This
happens automatically on systems that do not support memory mapping.

When compiling scripts instead of autoloadable functions, it is
often desirable to use this option; otherwise the whole file, including the
code to define functions which have already been defined, will
remain mapped, consequently wasting memory.
@end quotation

@code{-M}

@quotation

The compiled file is mapped into the shell’s memory when read. This
is done in such a way that multiple instances of the shell running
on the same host will share this mapped file.  If neither @code{-R} nor
@code{-M} is given, the @code{zcompile} builtin decides what to do based
on the size of the compiled file.
@end quotation

@code{-k}

@code{-z}

@quotation

These options are used when the compiled file contains functions which
are to be autoloaded. If @code{-z} is given, the
function will be autoloaded as if the @code{KSH_AUTOLOAD} option is
`not' set, even if it is set at the time the compiled file is
read, while if the @code{-k} is given, the function will be loaded as if
@code{KSH_AUTOLOAD} `is' set.  These options also take precedence over
any @code{-k} or @code{-z} options specified to the @code{autoload} builtin. If
neither of these options is given, the function will be loaded as
determined by the setting of the @code{KSH_AUTOLOAD} option at the time
the compiled file is read.

These options may also appear as many times as necessary between the listed
@var{name}s to specify the loading style of all following functions, up to
the next @code{-k} or @code{-z}.
@end quotation

@c DEFINITION-LIST-END

The created file always contains two versions of the compiled
format, one for big-endian machines and one for small-endian
machines.  The upshot of this is that the compiled file is machine
independent and if it is read or mapped, only one half of the file
is actually used (and mapped).


@c ITEM-DEFINITION-END

@c ITEM-BLOCK-END

@code{zformat}

@quotation

See @ref{ca,,The zsh/zutil Module}.
@end quotation

@code{zftp}

@quotation

See @ref{cb,,The zsh/zftp Module}.
@end quotation

@code{zle}

@quotation

See @ref{ba,,Zle Builtins}.
@end quotation

@geindex zmodload; Function

@geindex modules@comma{} loading; Command

@geindex loading modules; Command

@code{zmodload} [ @code{-dL} ] [ @code{-s} ] [ … ]

@code{zmodload -F} [ @code{-alLme} @code{-P} @var{param} ] @var{module} [ [@code{+-}]:var:@cite{feature} … ]

@code{zmodload -e} [ @code{-A} ] [ … ]

@code{zmodload} [ @code{-a} [ @code{-bcpf} [ @code{-I} ] ] ] [ @code{-iL} ] …

@code{zmodload} @code{-u} [ @code{-abcdpf} [ @code{-I} ] ] [ @code{-iL} ] …

@code{zmodload} @code{-A} [ @code{-L} ] [ @var{modalias}[@code{=}@var{module}] … ]

@code{zmodload} @code{-R} @var{modalias} …

@quotation

Performs operations relating to zsh’s loadable modules.
Loading of modules while the shell is running (`dynamical loading’) is not
available on all operating systems, or on all installations on a particular
operating system, although the @code{zmodload} command itself is always
available and can be used to manipulate modules built into versions of the
shell executable without dynamical loading.

Without arguments the names of all currently loaded binary modules are
printed.  The @code{-L} option causes this list to be in the form of a
series of @code{zmodload} commands.  Forms with arguments are:

@code{zmodload} [ @code{-is} ] @var{name} …

@code{zmodload} @code{-u} [ @code{-i} ] @var{name} …

@quotation

In the simplest case, @code{zmodload} loads a binary module.  The module must
be in a file with a name consisting of the specified @var{name} followed by
a standard suffix, usually @code{.so} (@code{.sl} on HPUX).
If the module to be loaded is already loaded the duplicate module is
ignored.  If @code{zmodload} detects an inconsistency, such as an
invalid module name or circular dependency list, the current code block is
aborted.  If it is available, the module is loaded if necessary, while if it
is not available, non-zero status is silently returned.  The option
@code{-i} is accepted for compatibility but has no effect.

The @var{name}d module is searched for in the same way a command is, using
@code{$module_path} instead of @code{$path}.  However, the path search is
performed even when the module name contains a @code{/}, which it usually does.
There is no way to prevent the path search.

If the module supports features (see below), @code{zmodload} tries to
enable all features when loading a module.  If the module was successfully
loaded but not all features could be enabled, @code{zmodload} returns status 2.

If the option @code{-s} is given, no error is printed if the module was not
available (though other errors indicating a problem with the module are
printed).  The return status indicates if the module was loaded.  This
is appropriate if the caller considers the module optional.

With @code{-u}, @code{zmodload} unloads modules.  The same @var{name}
must be given that was given when the module was loaded, but it is not
necessary for the module to exist in the file system.
The @code{-i} option suppresses the error if the module is already
unloaded (or was never loaded).

Each module has a boot and a cleanup function.  The module
will not be loaded if its boot function fails.  Similarly a module
can only be unloaded if its cleanup function runs successfully.
@end quotation

@code{zmodload -F} [ @code{-almLe} @code{-P} @var{param} ] @var{module} [ [@code{+-}]:var:@cite{feature} … ]

@quotation

@code{zmodload -F} allows more selective control over the features provided
by modules.  With no options apart from @code{-F}, the module named
@var{module} is loaded, if it was not already loaded, and the list of
@var{feature}s is set to the required state.  If no
@var{feature}s are specified, the module is loaded, if it was not already
loaded, but the state of features is unchanged.  Each feature
may be preceded by a @code{+} to turn the feature on, or @code{-} to turn it
off; the @code{+} is assumed if neither character is present.
Any feature not explicitly mentioned is left in its current state;
if the module was not previously loaded this means any such features will
remain disabled.  The return status is zero if all features were
set, 1 if the module failed to load, and 2 if some features could
not be set (for example, a parameter couldn’t be added because there
was a different parameter of the same name) but the module was loaded.

The standard features are builtins, conditions, parameters and math
functions; these are indicated by the prefix @code{b:}, @code{c:}
(@code{C:} for an infix condition), @code{p:} and @code{f:}, respectively,
followed by the name that the corresponding feature would have in the
shell.  For example, @code{b:strftime} indicates a builtin named
@code{strftime} and @code{p:EPOCHSECONDS} indicates a parameter named
@code{EPOCHSECONDS}.  The module may provide other (`abstract’) features of
its own as indicated by its documentation; these have no prefix.

With @code{-l} or @code{-L}, features provided by the module are listed.  With
@code{-l} alone, a list of features together with their states is shown, one
feature per line.  With @code{-L} alone, a @code{zmodload -F} command that would
cause enabled features of the module to be turned on is shown.  With
@code{-lL}, a @code{zmodload -F} command that would cause all the features to be
set to their current state is shown.  If one of these combinations is given
with the option @code{-P} @var{param} then the parameter @var{param} is set to an
array of features, either features together with their state or (if
@code{-L} alone is given) enabled features.

With the option @code{-L} the module name may be omitted; then a list
of all enabled features for all modules providing features is printed
in the form of @code{zmodload -F} commands.  If @code{-l} is also given,
the state of both enabled and disabled features is output in that form.

A set of features may be provided together with @code{-l} or @code{-L} and a
module name; in that case only the state of those features is
considered.  Each feature may be preceded by @code{+} or @code{-} but the
character has no effect.  If no set of features is provided, all
features are considered.

With @code{-e}, the command first tests that the module is loaded;
if it is not, status 1 is returned.  If the module is loaded,
the list of features given as an argument is examined.  Any feature
given with no prefix is simply tested to see if the module provides it;
any feature given with a prefix @code{+} or @code{-} is tested to
see if is provided and in the given state.  If the tests on all features
in the list succeed, status 0 is returned, else status 1.

With @code{-m}, each entry in the given list of features is taken
as a pattern to be matched against the list of features provided
by the module.  An initial @code{+} or @code{-} must be given explicitly.
This may not be combined with the @code{-a} option as autoloads must
be specified explicitly.

With @code{-a}, the given list of features is marked for autoload from
the specified module, which may not yet be loaded.  An optional @code{+}
may appear before the feature name.  If the feature is prefixed with
@code{-}, any existing autoload is removed.  The options @code{-l} and @code{-L}
may be used to list autoloads.  Autoloading is specific to individual
features; when the module is loaded only the requested feature is
enabled.  Autoload requests are preserved if the module is
subsequently unloaded until an explicit @code{zmodload -Fa} @var{module}
@code{-}@var{feature} is issued.  It is not an error to request an autoload
for a feature of a module that is already loaded.

When the module is loaded each autoload is checked against the features
actually provided by the module; if the feature is not provided the
autoload request is deleted.  A warning message is output; if the
module is being loaded to provide a different feature, and that autoload
is successful, there is no effect on the status of the current command.
If the module is already loaded at the time when @code{zmodload -Fa} is
run, an error message is printed and status 1 returned.

@code{zmodload -Fa} can be used with the @code{-l}, @code{-L}, @code{-e} and
@code{-P} options for listing and testing the existence of autoloadable
features.  In this case @code{-l} is ignored if @code{-L} is specified.
@code{zmodload -FaL} with no module name lists autoloads for all modules.

Note that only standard features as described above can be autoloaded;
other features require the module to be loaded before enabling.
@end quotation

@code{zmodload} @code{-d} [ @code{-L} ] [ @var{name} ]

@code{zmodload} @code{-d} @var{name} @var{dep} …

@code{zmodload} @code{-ud} @var{name} [ @var{dep} … ]

@quotation

The @code{-d} option can be used to specify module dependencies.  The modules
named in the second and subsequent arguments will be loaded before the
module named in the first argument.

With @code{-d} and one argument, all dependencies for that module are listed.
With @code{-d} and no arguments, all module dependencies are listed.  This
listing is by default in a Makefile-like format.  The @code{-L} option
changes this format to a list of @code{zmodload -d} commands.

If @code{-d} and @code{-u} are both used, dependencies are removed.  If only one
argument is given, all dependencies for that module are removed.
@end quotation

@code{zmodload} @code{-ab} [ @code{-L} ]

@code{zmodload} @code{-ab} [ @code{-i} ] @var{name} [ @var{builtin} … ]

@code{zmodload} @code{-ub} [ @code{-i} ] @var{builtin} …

@quotation

The @code{-ab} option defines autoloaded builtins.  It defines the specified
@var{builtin}s.  When any of those builtins is called, the module specified
in the first argument is loaded and all its features are enabled (for
selective control of features use @code{zmodload -F -a} as described
above).  If only the @var{name} is given, one builtin is defined, with
the same name as the module.  @code{-i} suppresses the error if the builtin
is already defined or autoloaded, but not if another builtin of the
same name is already defined.

With @code{-ab} and no arguments, all autoloaded builtins are listed, with the
module name (if different) shown in parentheses after the builtin name.
The @code{-L} option changes this format to a list of @code{zmodload -a}
commands.

If @code{-b} is used together with the @code{-u} option, it removes builtins
previously defined with @code{-ab}.  This is only possible if the builtin is
not yet loaded.  @code{-i} suppresses the error if the builtin is already
removed (or never existed).

Autoload requests are retained if the module is subsequently unloaded
until an explicit @code{zmodload -ub} @var{builtin} is issued.
@end quotation

@code{zmodload} @code{-ac} [ @code{-IL} ]

@code{zmodload} @code{-ac} [ @code{-iI} ] @var{name} [ @var{cond} … ]

@code{zmodload} @code{-uc} [ @code{-iI} ] @var{cond} …

@quotation

The @code{-ac} option is used to define autoloaded condition codes. The
@var{cond} strings give the names of the conditions defined by the
module. The optional @code{-I} option is used to define infix condition
names. Without this option prefix condition names are defined.

If given no condition names, all defined names are listed (as a series of
@code{zmodload} commands if the @code{-L} option is given).

The @code{-uc} option removes definitions for autoloaded conditions.
@end quotation

@code{zmodload} @code{-ap} [ @code{-L} ]

@code{zmodload} @code{-ap} [ @code{-i} ] @var{name} [ @var{parameter} … ]

@code{zmodload} @code{-up} [ @code{-i} ] @var{parameter} …

@quotation

The @code{-p} option is like the @code{-b} and @code{-c} options, but makes
@code{zmodload} work on autoloaded parameters instead.
@end quotation

@code{zmodload} @code{-af} [ @code{-L} ]

@code{zmodload} @code{-af} [ @code{-i} ] @var{name} [ @var{function} … ]

@code{zmodload} @code{-uf} [ @code{-i} ] @var{function} …

@quotation

The @code{-f} option is like the @code{-b}, @code{-p}, and @code{-c} options, but
makes @code{zmodload} work on autoloaded math functions instead.
@end quotation

@code{zmodload} @code{-a} [ @code{-L} ]

@code{zmodload} @code{-a} [ @code{-i} ] @var{name} [ @var{builtin} … ]

@code{zmodload} @code{-ua} [ @code{-i} ] @var{builtin} …

@quotation

Equivalent to @code{-ab} and @code{-ub}.
@end quotation

@code{zmodload -e} [ @code{-A} ] [ @var{string} … ]

@quotation

The @code{-e} option without arguments lists all loaded modules; if the @code{-A}
option is also given, module aliases corresponding to loaded modules are
also shown.  If arguments are provided, nothing is printed;
the return status is set to zero if all @var{string}s given as arguments
are names of loaded modules and to one if at least on @var{string} is not
the name of a loaded module.  This can be used to test for the
availability of things implemented by modules.  In this case, any
aliases are automatically resolved and the @code{-A} flag is not used.
@end quotation

@code{zmodload} @code{-A} [ @code{-L} ] [ @var{modalias}[@code{=}@var{module}] … ]

@quotation

For each argument, if both @var{modalias} and @var{module} are given,
define @var{modalias} to be an alias for the module @var{module}.
If the module @var{modalias} is ever subsequently requested, either via a
call to @code{zmodload} or implicitly, the shell will attempt to load
@var{module} instead.  If @var{module} is not given, show the definition of
@var{modalias}.  If no arguments are given, list all defined module aliases.
When listing, if the @code{-L} flag was also given, list the definition as a
@code{zmodload} command to recreate the alias.

The existence of aliases for modules is completely independent of whether
the name resolved is actually loaded as a module: while the alias exists,
loading and unloading the module under any alias has exactly the same
effect as using the resolved name, and does not affect the connection
between the alias and the resolved name which can be removed either by
@code{zmodload -R} or by redefining the alias.  Chains of aliases (i.e. where
the first resolved name is itself an alias) are valid so long as these are
not circular.  As the aliases take the same format as module names, they
may include path separators:  in this case, there is no requirement for any
part of the path named to exist as the alias will be resolved first.  For
example, @code{any/old/alias} is always a valid alias.

Dependencies added to aliased modules are actually added to the resolved
module; these remain if the alias is removed.  It is valid to create an
alias whose name is one of the standard shell modules and which resolves to
a different module.  However, if a module has dependencies, it
will not be possible to use the module name as an alias as the module will
already be marked as a loadable module in its own right.

Apart from the above, aliases can be used in the @code{zmodload} command
anywhere module names are required.  However, aliases will not be
shown in lists of loaded modules with a bare @code{zmodload}.
@end quotation

@code{zmodload} @code{-R} @var{modalias} …

@quotation

For each @var{modalias} argument that was previously defined as a module
alias via @code{zmodload -A}, delete the alias.  If any was not defined, an
error is caused and the remainder of the line is ignored.
@end quotation

Note that @code{zsh} makes no distinction between modules that were linked
into the shell and modules that are loaded dynamically. In both cases
this builtin command has to be used to make available the builtins and
other things defined by modules (unless the module is autoloaded on
these definitions). This is true even for systems that don’t support
dynamic loading of modules.
@end quotation

@code{zparseopts}

@quotation

See @ref{ca,,The zsh/zutil Module}.
@end quotation

@code{zprof}

@quotation

See @ref{cc,,The zsh/zprof Module}.
@end quotation

@code{zpty}

@quotation

See @ref{cd,,The zsh/zpty Module}.
@end quotation

@code{zregexparse}

@quotation

See @ref{ca,,The zsh/zutil Module}.
@end quotation

@code{zsocket}

@quotation

See @ref{ce,,The zsh/net/socket Module}.
@end quotation

@code{zstyle}

@quotation

See @ref{ca,,The zsh/zutil Module}.
@end quotation

@code{ztcp}

@quotation

See @ref{cf,,The zsh/net/tcp Module}.
@end quotation
@end quotation

@c historic nodename: Zsh Line Editor

@node Zsh Line Editor,Completion Widgets,Shell Builtin Commands,Top
@anchor{Zsh/zle doc}@anchor{d0}@anchor{Zsh/zle zsh-line-editor}@anchor{d1}
@chapter Zsh Line Editor


@geindex line editor; Command

@geindex editor@comma{} line; Command

@geindex ZLE; Command

@menu
* Description: Description<3>. 
* Keymaps:: 
* Zle Builtins:: 
* Zle Widgets:: 
* User-Defined Widgets:: 
* Standard Widgets:: 
* Terminal Extensions:: 
* Character Highlighting:: 
* Cursor Shape and Color:: 

@end menu

@node Description<3>,Keymaps,,Zsh Line Editor
@anchor{Zsh/zle description}@anchor{d2}
@section Description


@geindex ZLE@comma{} use of; Program

If the @code{ZLE} option is set (which it is by default in interactive shells)
and the shell input is attached to the terminal, the user
is able to edit command lines.

There are two display modes.  The first, multiline mode, is the
default.  It only works if the @code{TERM} parameter is set to a valid
terminal type that can move the cursor up.  The second, single line
mode, is used if @code{TERM} is invalid or incapable of moving the
cursor up, or if the @code{SINGLE_LINE_ZLE} option is set.
.. index:: single: SINGLE_LINE_ZLE, use of; Program

@geindex ksh@comma{} editor mode; Command

@geindex editor ksh style; Command

This mode
is similar to `ksh', and uses no termcap sequences.  If @code{TERM} is
“emacs”, the @code{ZLE} option will be unset by default.

@geindex BAUD@comma{} use of; Variable

@geindex COLUMNS@comma{} use of; Variable

@geindex LINES@comma{} use of; Variable

The parameters @code{BAUD}, @code{COLUMNS}, and @code{LINES} are also used by the
line editor. See @ref{11,,Parameters Used by the Shell}.

@geindex zle_highlight@comma{} use of; Variable

The parameter @code{zle_highlight} is also used by the line editor; see
@ref{60,,Character Highlighting}.  Highlighting
of special characters and the region between the cursor and the
mark (as set with @code{set-mark-command} in Emacs mode, or by @code{visual-mode}
in Vi mode) is enabled
by default; consult this reference for more information.  Irascible
conservatives will wish to know that all highlighting may be disabled by
the following setting:

@example
 zle_highlight=(none)
@end example

In many places, references are made to the @code{numeric argument}.  This can
by default be entered in emacs mode by holding the alt key and typing
a number, or pressing escape before each digit, and in vi command mode
by typing the number before entering a command.  Generally the numeric
argument causes the next command entered to be repeated the specified
number of times, unless otherwise noted below; this is implemented
by the @code{digit-argument} widget. See also @ref{d3,,Arguments}
for some other ways the numeric argument can be modified.

@c historic nodename: Keymaps

@node Keymaps,Zle Builtins,Description<3>,Zsh Line Editor
@anchor{Zsh/zle keymaps}@anchor{d4}
@section Keymaps


@geindex keymaps; Command

@geindex key bindings; Command

@geindex bindings@comma{} key; Command

A keymap in ZLE contains a set of bindings between key sequences
and ZLE commands.  The empty key sequence cannot be bound.

There can be any number of keymaps at any time, and each keymap has one
or more names.  If all of a keymap’s names are deleted, it disappears.
.. index:: single: bindkey, use of; Function

@code{bindkey} can be used to manipulate keymap names.

Initially, there are eight keymaps:


@table @asis

@item @code{emacs}

EMACS emulation

@item @code{viins}

vi emulation - insert mode

@item @code{vicmd}

vi emulation - command mode

@item @code{viopp}

vi emulation - operator pending

@item @code{visual}

vi emulation - selection active

@item @code{isearch}

incremental search mode

@item @code{command}

read a command name

@item @code{.safe}

fallback keymap
@end table

The @code{.safe} keymap is special.  It can never be altered, and the name
can never be removed.  However, it can be linked to other names, which can
be removed.  In the future other special keymaps may be added; users should
avoid using names beginning with @code{.} for their own keymaps.

@geindex VISUAL; Variable

@geindex EDITOR; Variable

In addition to these names, either @code{emacs} or @code{viins} is
also linked to the name @code{main}.  If one of the @code{VISUAL} or
@code{EDITOR} environment variables contain the string @code{vi} when the shell
starts up then it will be @code{viins}, otherwise it will be @code{emacs}.
@code{bindkey}’s @code{-e} and @code{-v}
options provide a convenient way to override this default choice.

When the editor starts up, it will select the @code{main} keymap.
If that keymap doesn’t exist, it will use @code{.safe} instead.

In the @code{.safe} keymap, each single key is bound to @code{self-insert},
except for ^J (line feed) and ^M (return) which are bound to @code{accept-line}.
This is deliberately not pleasant to use; if you are using it, it
means you deleted the main keymap, and you should put it back.

@menu
* Reading Commands:: 
* Local Keymaps:: 

@end menu

@node Reading Commands,Local Keymaps,,Keymaps
@anchor{Zsh/zle reading-commands}@anchor{d5}
@subsection Reading Commands


When ZLE is reading a command from the terminal, it may read a sequence
that is bound to some command and is also a prefix of a longer bound string.
In this case ZLE will wait a certain time to see if more characters
are typed, and if not (or they don’t match any longer string) it will
execute the binding.  This timeout is defined by the @code{KEYTIMEOUT} parameter;
its default is 0.4 sec.  There is no timeout if the prefix string is not
itself bound to a command.

The key timeout is also applied when ZLE is reading the bytes from a
multibyte character string when it is in the appropriate mode.  (This
requires that the shell was compiled with multibyte mode enabled; typically
also the locale has characters with the UTF-8 encoding, although any
multibyte encoding known to the operating system is supported.)  If the
second or a subsequent byte is not read within the timeout period, the
shell acts as if @code{?} were typed and resets the input state.

As well as ZLE commands, key sequences can be bound to other strings, by using
@code{bindkey -s}.
When such a sequence is read, the replacement string is pushed back as input,
and the command reading process starts again using these fake keystrokes.
This input can itself invoke further replacement strings, but in order to
detect loops the process will be stopped if there are twenty such replacements
without a real command being read.

A key sequence typed by the user can be turned into a command name for use
in user-defined widgets with the @code{read-command} widget, described in
@ref{d6,,Miscellaneous}.

@node Local Keymaps,,Reading Commands,Keymaps
@anchor{Zsh/zle local-keymaps}@anchor{d7}
@subsection Local Keymaps


@geindex local keymaps; Command

While for normal editing a single keymap is used exclusively, in many
modes a local keymap allows for some keys to be customised. For example,
in an incremental search mode, a binding in the @code{isearch} keymap will
override a binding in the @code{main} keymap but all keys that are not
overridden can still be used.

If a key sequence is defined in a local keymap, it will hide a key
sequence in the global keymap that is a prefix of that sequence. An
example of this occurs with the binding of @code{iw} in @code{viopp} as this
hides the binding of @code{i} in @code{vicmd}. However, a longer sequence in
the global keymap that shares the same prefix can still apply so for
example the binding of @code{^Xa} in the global keymap will be unaffected
by the binding of @code{^Xb} in the local keymap.

@c historic nodename: Zle Builtins

@node Zle Builtins,Zle Widgets,Keymaps,Zsh Line Editor
@anchor{Zsh/zle zle-builtins}@anchor{ba}
@section Zle Builtins


@geindex zle@comma{} builtin commands; Command

The ZLE module contains three related builtin commands. The @code{bindkey}
command manipulates keymaps and key bindings; the @code{vared} command invokes
ZLE on the value of a shell parameter; and the @code{zle} command manipulates
editing widgets and allows command line access to ZLE commands from within
shell functions.

@geindex bindkey; Function

@geindex keys@comma{} rebinding; Command

@geindex rebinding keys; Command

@geindex keys@comma{} binding; Command

@geindex binding keys; Command

@geindex keymaps; Command

@code{bindkey} [ @var{options} ] @code{-l} [ @code{-L} ] [ @var{keymap} … ]

@code{bindkey} [ @var{options} ] @code{-d}

@code{bindkey} [ @var{options} ] @code{-D} @var{keymap} …

@code{bindkey} [ @var{options} ] @code{-A} @var{old-keymap new-keymap}

@code{bindkey} [ @var{options} ] @code{-N} @var{new-keymap} [ @var{old-keymap} ]

@code{bindkey} [ @var{options} ] @code{-m}

@code{bindkey} [ @var{options} ] @code{-r} @var{in-string} …

@code{bindkey} [ @var{options} ] @code{-s} @var{in-string out-string} …

@code{bindkey} [ @var{options} ] @var{in-string command} …

@code{bindkey} [ @var{options} ] [ @var{in-string} ]

@quotation

@code{bindkey}’s options can be divided into three categories: keymap
selection for the current command, operation selection, and others.  The
keymap selection options are:

@code{-e}

@quotation

Selects keymap @code{emacs} for any operations by the current command,
and also links @code{emacs} to @code{main} so that it is selected by
default the next time the editor starts.
@end quotation

@code{-v}

@quotation

Selects keymap @code{viins} for any operations by the current command,
and also links @code{viins} to @code{main} so that it is selected by default
the next time the editor starts.
@end quotation

@code{-a}

@quotation

Selects keymap @code{vicmd} for any operations by the current command.
@end quotation

@code{-M} @var{keymap}

@quotation

The @var{keymap} specifies a keymap name that is selected for any
operations by the current command.
@end quotation

If a keymap selection is required and none of the options above are used, the
@code{main} keymap is used.  Some operations do not permit a keymap to be
selected, namely:

@code{-l}

@quotation

List all existing keymap names; if any arguments are given, list just
those keymaps.

If the @code{-L} option is also used, list in the form of @code{bindkey}
commands to create or link the keymaps.  @code{bindkey -lL
main `@w{`}shows which keymap is linked to} main`@w{`}, if any, and hence if
the standard emacs or vi emulation is in effect.  This option does
not show the @code{.safe} keymap because it cannot be created in that
fashion; however, neither is @code{bindkey -lL .safe} reported as an
error, it simply outputs nothing.
@end quotation

@code{-d}

@quotation

Delete all existing keymaps and reset to the default state.
@end quotation

@code{-D} @var{keymap} …

@quotation

Delete the named @var{keymap}s.
@end quotation

@code{-A} @var{old-keymap new-keymap}

@quotation

Make the @var{new-keymap} name an alias for @var{old-keymap}, so that
both names refer to the same keymap.  The names have equal standing;
if either is deleted, the other remains.  If there is already a keymap
with the @var{new-keymap} name, it is deleted.
@end quotation

@code{-N} @var{new-keymap} [ @var{old-keymap} ]

@quotation

Create a new keymap, named @var{new-keymap}.  If a keymap already has that
name, it is deleted.  If an @var{old-keymap} name is given, the new keymap
is initialized to be a duplicate of it, otherwise the new keymap will
be empty.
@end quotation

To use a newly created keymap, it should be linked to @code{main}.  Hence
the sequence of commands to create and use a new keymap @code{mymap}
initialized from the @code{emacs} keymap (which remains unchanged) is:

@example
 bindkey -N mymap emacs
 bindkey -A mymap main
@end example

Note that while @code{bindkey -A} @var{newmap} @code{main} will work when
@var{newmap} is @code{emacs} or @code{viins}, it will not work for @code{vicmd}, as
switching from vi insert to command mode becomes impossible.

The following operations act on the @code{main} keymap if no keymap
selection option was given:

@code{-m}

@quotation

Add the built-in set of meta-key bindings to the selected keymap.
Only keys that are unbound or bound to @code{self-insert} are affected.
@end quotation

@code{-r} @var{in-string} …

@quotation

Unbind the specified @var{in-string}s in the selected keymap.
This is exactly equivalent to binding the strings to @code{undefined-key}.

When @code{-R} is also used, interpret the @var{in-string}s as ranges.

When @code{-p} is also used, the @var{in-string}s specify prefixes.  Any
binding that has the given @var{in-string} as a prefix, not including the
binding for the @var{in-string} itself, if any, will be removed.  For
example,

@example
 bindkey -rpM viins '^['
@end example

will remove all bindings in the vi-insert keymap beginning with an escape
character (probably cursor keys), but leave the binding for the escape
character itself (probably @code{vi-cmd-mode}).  This is incompatible with the
option @code{-R}.
@end quotation

@code{-s} @var{in-string out-string} …

@quotation

Bind each @var{in-string} to each @var{out-string}.
When @var{in-string} is typed, @var{out-string} will be
pushed back and treated as input to the line editor.
When @code{-R} is also used, interpret the @var{in-string}s as ranges.

Note that both @var{in-string} and @var{out-string} are subject to the same
form of interpretation, as described below.
@end quotation

@var{in-string command} …

@quotation

Bind each @var{in-string} to each @var{command}.
When @code{-R} is used, interpret the @var{in-string}s as ranges.
@end quotation

[ @var{in-string} ]

@quotation

List key bindings.  If an @var{in-string} is specified, the binding of
that string in the selected keymap is displayed.  Otherwise, all key
bindings in the selected keymap are displayed.  (As a special case,
if the @code{-e} or @code{-v} option is used alone, the keymap is `not'
displayed - the implicit linking of keymaps is the only thing that
happens.)

When the option @code{-p} is used, the @var{in-string} must be present.
The listing shows all bindings which have the given key sequence as a
prefix, not including any bindings for the key sequence itself.

When the @code{-L} option is used, the list is in the form of @code{bindkey}
commands to create the key bindings.
@end quotation

When the @code{-R} option is used as noted above, a valid range consists of
two characters, with an optional @code{-} between them.  All characters
between the two specified, inclusive, are bound as specified.

For either @var{in-string} or @var{out-string}, the following
escape sequences are recognised:


@table @asis

@item @code{\a}

bell character

@item @code{\b}

backspace

@item @code{\e}, @code{\E}

escape

@item @code{\f}

form feed

@item @code{\n}

linefeed (newline)

@item @code{\r}

carriage return

@item @code{\t}

horizontal tab

@item @code{\v}

vertical tab

@item @code{\}@var{NNN}

character code in octal

@item @code{\x}@var{NN}

character code in hexadecimal

@item @code{\u}@var{NNNN}

unicode character code in hexadecimal

@item @code{\U}@var{NNNNNNNN}

unicode character code in hexadecimal

@item @code{\M[-}]:var:@cite{X}

character with meta bit set

@item @code{\C[-}]:var:@cite{X}

control character

@item @code{^}@var{X}

control character
@end table

In all other cases, @code{\} escapes the following character.  Delete is
written as @code{^?}.  Note that @code{\M^?} and @code{^\M?} are not the same,
and that (unlike emacs), the bindings @code{\M-}@var{X} and @code{\e}@var{X}
are entirely distinct, although they are initialized to the same bindings
by @code{bindkey -m}.
@end quotation

@geindex vared; Function

@geindex parameters@comma{} editing; Command

@geindex editing parameters; Command

@code{vared} [ @code{-Aacghe} ] [ @code{-p} @var{prompt} ] [ @code{-r} @var{rprompt} ]

@quotation

@quotation

[ @code{-M} @var{main-keymap} ] [ @code{-m} @var{vicmd-keymap} ]

[ @code{-i} @var{init-widget} ] [ @code{-f} @var{finish-widget} ]

[ @code{-t} @var{tty} ] @var{name}
@end quotation

The value of the parameter @var{name} is loaded into the edit
buffer, and the line editor is invoked.  When the editor exits,
@var{name} is set to the string value returned by the editor.
When the @code{-c} flag is given, the parameter is created if it doesn’t
already exist.  The @code{-a} flag may be given with @code{-c} to create
an array parameter, or the @code{-A} flag to create an associative array.
If the type of an existing parameter does not match the type to be
created, the parameter is unset and recreated.  The @code{-g} flag may
be given to suppress warnings from the @code{WARN_CREATE_GLOBAL}
and @code{WARN_NESTED_VAR} options.

If an array or array slice is being edited, separator characters as defined
in @code{$IFS} will be shown quoted with a backslash, as will backslashes
themselves.  Conversely, when the edited text is split into an array, a
backslash quotes an immediately following separator character or backslash;
no other special handling of backslashes, or any handling of quotes, is
performed.

Individual elements of existing array or associative array parameters
may be edited by using subscript syntax on @var{name}.  New elements are
created automatically, even without @code{-c}.

If the @code{-p} flag is given, the following string will be taken as
the prompt to display at the left.  If the @code{-r} flag is given,
the following string gives the prompt to display at the right.  If the
@code{-h} flag is specified, the history can be accessed from ZLE. If the
@code{-e} flag is given, typing @code{^D} (Control-D) in an empty buffer
causes @code{vared} to exit immediately with a non-zero return value.

The @code{-M} option gives a keymap to link to the @code{main} keymap during
editing, and the @code{-m} option gives a keymap to link to the @code{vicmd}
keymap during editing.  For vi-style editing, this allows a pair of keymaps
to override @code{viins} and @code{vicmd}.  For emacs-style editing, only @code{-M}
is normally needed but the @code{-m} option may still be used.  On exit, the
previous keymaps will be restored.

@code{Vared} calls the usual @code{zle-line-init} and @code{zle-line-finish}
hooks before and after it takes control. Using the @code{-i} and @code{-f}
options, it is possible to replace these with other custom widgets.

If @code{-t} @var{tty} is given, @var{tty} is the name of a terminal device
to be used instead of the default @code{/dev/tty}.  If @var{tty} does not
refer to a terminal an error is reported.
@end quotation

@geindex zle; Function

@geindex widgets@comma{} rebinding; Command

@geindex rebinding widgets; Command

@geindex widgets@comma{} binding; Command

@geindex binding widgets; Command

@geindex widgets@comma{} invoking; Command

@geindex invoking widgets; Command

@geindex widgets@comma{} calling; Command

@geindex calling widgets; Command

@geindex widgets@comma{} defining; Command

@geindex defining widgets; Command

@code{zle}

@code{zle} @code{-l} [ @code{-L} | @code{-a} ] [ @var{string} … ]

@code{zle} @code{-D} @var{widget} …

@code{zle} @code{-A} @var{old-widget} @var{new-widget}

@code{zle} @code{-N} @var{widget} [ @var{function} ]

@code{zle} @code{-f} @var{flag} [ @var{flag}… ]

@code{zle} @code{-C} @var{widget} @var{completion-widget} @var{function}

@code{zle} @code{-R} [ @code{-c} ] [ @var{display-string} ] [ @var{string} … ]

@code{zle} @code{-M} @var{string}

@code{zle} @code{-U} @var{string}

@code{zle} @code{-K} @var{keymap}

@code{zle} @code{-F} [ @code{-L} | @code{-w} ] [ @var{fd} [ @var{handler} ] ]

@code{zle} @code{-I}

@code{zle} @code{-T} [ @code{tc} @var{function} | @code{-r} @code{tc} | @code{-L} ]

@code{zle} @var{widget} [ @code{-n} @var{num} ] [ @code{-f} @var{flag} ] [ @code{-Nw} ] [ @code{-K} @var{keymap} ] @var{args} …

@quotation

The @code{zle} builtin performs a number of different actions concerning
ZLE.

With no options and no arguments, only the return status will be
set.  It is zero if ZLE is currently active and widgets could be
invoked using this builtin command and non-zero otherwise.
Note that even if non-zero status is returned, zle may still be active as
part of the completion system; this does not allow direct calls to ZLE
widgets.

Otherwise, which operation it performs depends on its options:

@code{-l} [ @code{-L} | @code{-a} ] [ @var{string} ]

@quotation

List all existing user-defined widgets.  If the @code{-L}
option is used, list in the form of @code{zle}
commands to create the widgets.

When combined with the @code{-a} option, all widget names are listed,
including the builtin ones. In this case the @code{-L} option is ignored.

If at least one @var{string} is given, and @code{-a} is present or @code{-L} is
not used, nothing will be printed.  The return status will be zero if
all @var{string}s are names of existing widgets and non-zero if at least one
@var{string} is not a name of a defined widget.  If @code{-a} is also
present, all widget names are used for the comparison including builtin
widgets, else only user-defined widgets are used.

If at least one @var{string} is present and the @code{-L} option is used,
user-defined widgets matching any @var{string} are listed in the form of
@code{zle} commands to create the widgets.
@end quotation

@code{-D} @var{widget} …

@quotation

Delete the named @var{widget}s.
@end quotation

@code{-A} @var{old-widget} @var{new-widget}

@quotation

Make the @var{new-widget} name an alias for @var{old-widget}, so that
both names refer to the same widget.  The names have equal standing;
if either is deleted, the other remains.  If there is already a widget
with the @var{new-widget} name, it is deleted.
@end quotation

@code{-N} @var{widget} [ @var{function} ]

@quotation

Create a user-defined widget.  If there is already a widget with the
specified name, it is overwritten.  When the new
widget is invoked from within the editor, the specified shell @var{function}
is called.  If no function name is specified, it defaults to
the same name as the widget.  For further information, see
@ref{d8,,Zle Widgets}.
@end quotation

@code{-f} @var{flag} [ @var{flag}… ]

@quotation

Set various flags on the running widget.  Possible values for @var{flag} are:

@code{yank} for indicating that the widget has yanked text into the buffer.
If the widget is wrapping an existing internal widget, no further
action is necessary, but if it has inserted the text manually, then it
should also take care to set @code{YANK_START} and @code{YANK_END} correctly.
@code{yankbefore} does the same but is used when the yanked text appears
after the cursor.

@code{kill} for indicating that text has been killed into the cutbuffer.
When repeatedly invoking a kill widget, text is appended to the cutbuffer
instead of replacing it, but when wrapping such widgets, it is necessary
to call @code{zle -f kill} to retain this effect.

@code{vichange} for indicating that the widget represents a vi change that
can be repeated as a whole with @code{vi-repeat-change}. The flag should be set
early in the function before inspecting the value of @code{NUMERIC} or invoking
other widgets. This has no effect for a widget invoked from insert mode. If
insert mode is active when the widget finishes, the change extends until next
returning to command mode.
@end quotation

@geindex completion widgets@comma{} creating; Command

@code{-C} @var{widget} @var{completion-widget} @var{function}

@quotation

Create a user-defined completion widget named @var{widget}. The
completion widget will behave like the built-in completion-widget
whose name is given as @var{completion-widget}. To generate the
completions, the shell function @var{function} will be called.
For further information, see @code{zshcompwid}.
@end quotation

@code{-R} [ @code{-c} ] [ @var{display-string} ] [ @var{string} … ]

@quotation

Redisplay the command line.  If a @var{display-string} is
given and not empty, this is shown in the status line (immediately
below the line being edited).

If the optional @var{string}s are given they are listed below the
prompt in the same way as completion lists are printed. If no
@var{string}s are given but the @code{-c} option is used such a list is
cleared.

Note that immediately after returning from running widgets, the command line
will be redisplayed and the strings displayed will be erased.  Therefore, this
option is only useful for widgets that do not exit immediately after using it.

This command can safely be called outside user defined widgets; if zle is
active, the display will be refreshed, while if zle is not active, the
command has no effect.  In this case there will usually be no other
arguments.

The status is zero if zle was active, else one.
@end quotation

@code{-M} @var{string}

@quotation

As with the @code{-R} option, the @var{string} will be displayed below the
command line; unlike the @code{-R} option, the string will not be put into
the status line but will instead be printed normally below the
prompt.  This means that the @var{string} will still be displayed after
the widget returns (until it is overwritten by subsequent commands).
@end quotation

@code{-U} @var{string}

@quotation

This pushes the characters in the @var{string} onto the input stack of
ZLE.  After the widget currently executed finishes ZLE will behave as
if the characters in the @var{string} were typed by the user.

As ZLE uses a stack, if this option is used repeatedly
the last string pushed onto the stack will be processed first.  However,
the characters in each @var{string} will be processed in the order in which
they appear in the string.
@end quotation

@code{-K} @var{keymap}

@quotation

Selects the keymap named @var{keymap}.  An error message will be displayed if
there is no such keymap.

This keymap selection affects the interpretation of following keystrokes
within this invocation of ZLE.  Any following invocation (e.g., the next
command line) will start as usual with the @code{main} keymap selected.
@end quotation

@code{-F} [ @code{-L} | @code{-w} ] [ @var{fd} [ @var{handler} ] ]

@quotation

Only available if your system supports one of the `poll’ or `select’ system
calls; most modern systems do.

Installs @var{handler} (the name of a shell function) to handle input from
file descriptor @var{fd}.  Installing a handler for an @var{fd} which is
already handled causes the existing handler to be replaced.  Any number of
handlers for any number of readable file descriptors may be installed.
Note that zle makes no attempt to check whether this @var{fd} is actually
readable when installing the handler.  The user must make their own
arrangements for handling the file descriptor when zle is not active.

When zle is attempting to read data, it will examine both the terminal and
the list of handled @var{fd}’s.  If data becomes available on a handled
@var{fd}, zle calls @var{handler} with the fd which is ready for reading
as the first argument.  Under normal circumstances this is the only
argument, but if an error was detected, a second argument provides
details: @code{hup} for a disconnect, @code{nval} for a closed or otherwise
invalid descriptor, or @code{err} for any other condition.  Systems that
support only the `select’ system call always use @code{err}.

If the option @code{-w} is also given, the @var{handler} is instead a line
editor widget, typically a shell function made into a widget using
@code{zle -N}.  In that case @var{handler} can use all the facilities of zle
to update the current editing line.  Note, however, that as handling @var{fd}
takes place at a low level changes to the display will not automatically
appear; the widget should call @code{zle -R} to force redisplay.  As of this
writing, widget handlers only support a single argument and thus are never
passed a string for error state, so widgets must be prepared to test the
descriptor themselves.

If either type of handler produces output to the terminal, it should call
@code{zle -I} before doing so (see below).  Handlers should not attempt to
read from the terminal.

If no @var{handler} is given, but an @var{fd} is present, any handler for
that @var{fd} is removed.  If there is none, an error message is printed
and status 1 is returned.

If no arguments are given, or the @code{-L} option is supplied, a list of
handlers is printed in a form which can be stored for later execution.

An @var{fd} (but not a @var{handler}) may optionally be given with the @code{-L}
option; in this case, the function will list the handler if any, else
silently return status 1.

Note that this feature should be used with care.  Activity on one of the
@var{fd}’s which is not properly handled can cause the terminal to become
unusable.  Removing an @var{fd} handler from within a signal trap may cause
unpredictable behavior.

Here is a simple example of using this feature.  A connection to a remote
TCP port is created using the ztcp command; see
@ref{cf,,The zsh/net/tcp Module}.  Then a handler is installed
which simply prints out any data which arrives on this connection.  Note
that `select’ will indicate that the file descriptor needs handling
if the remote side has closed the connection; we handle that by testing
for a failed read.

@example
 if ztcp pwspc 2811; then
   tcpfd=$REPLY
   handler() @{
     zle -I
     local line
     if ! read -r line <&$1; then
       # select marks this fd if we reach EOF,
       # so handle this specially.
       print "[Read on fd $1 failed, removing.]" >&2
       zle -F $1
       return 1
     fi
     print -r - $line
   @}
   zle -F $tcpfd handler
 fi
@end example
@end quotation

@code{-I}

@quotation

Unusually, this option is most useful outside ordinary widget functions,
though it may be used within if normal output to the terminal is required.
It invalidates the current zle display in preparation for output; typically
this will be from a trap function.  It has no effect if zle is not
active.  When a trap exits, the shell checks to see if the display needs
restoring, hence the following will print output in such a way as not to
disturb the line being edited:

@example
 TRAPUSR1() @{
   # Invalidate zle display
   [[ -o zle ]] && zle -I
   # Show output
   print Hello
 @}
@end example

In general, the trap function may need to test whether zle is active before
using this method (as shown in the example), since the @code{zsh/zle} module
may not even be loaded; if it is not, the command can be skipped.

It is possible to call @code{zle -I} several times before control is
returned to the editor; the display will only be invalidated the first time
to minimise disruption.

Note that there are normally better ways of manipulating the display from
within zle widgets; see, for example, @code{zle -R} above.

The returned status is zero if zle was invalidated, even though
this may have been by a previous call to @code{zle -I} or by a system
notification.  To test if a zle widget may be called at this point, execute
@code{zle} with no arguments and examine the return status.
@end quotation

@code{-T}

@quotation

This is used to add, list or remove internal transformations on the
processing performed by the line editor.  It is typically used only for
debugging or testing and is therefore of little interest to the general
user.

@code{zle -T} @var{transformation} @var{func} specifies that the
given @var{transformation} (see below) is effected by shell function
@var{func}.

@code{zle -Tr} @var{transformation} removes the given @var{transformation}
if it was present (it is not an error if none was).

@code{zle -TL} can be used to list all transformations currently in
operation.

Currently the only transformation is @code{tc}.  This is used instead
of outputting termcap codes to the terminal.  When the transformation is
in operation the shell function is passed the termcap code that would be
output as its first argument; if the operation required a numeric
argument, that is passed as a second argument.  The function should set
the shell variable @code{REPLY} to the transformed termcap code.  Typically
this is used to produce some simply formatted version of the code and
optional argument for debugging or testing.  Note that this
transformation is not applied to other non-printing characters such as
carriage returns and newlines.
@end quotation

@var{widget} [ @code{-n} @var{num} ] [ @code{-f} @var{flag} ] [ @code{-Nw} ] [ @code{-K} @var{keymap} ] @var{args} …

@quotation

Invoke the specified @var{widget}.  This can only be done when ZLE is
active; normally this will be within a user-defined widget.

With the options @code{-n} and @code{-N}, the current numeric argument will be
saved and then restored after the call to @var{widget}; @code{-n} @var{num}
sets the numeric argument temporarily to @var{num}, while @code{-N} sets it
to the default, i.e. as if there were none.

With the option @code{-K}, @var{keymap} will be used as the current keymap
during the execution of the widget.  The previous keymap will be
restored when the widget exits.

Normally, calling a widget in this way does not set the special
parameter @code{WIDGET} and related parameters, so that the environment
appears as if the top-level widget called by the user were still
active.  With the option @code{-w}, @code{WIDGET} and related parameters are set
to reflect the widget being executed by the @code{zle} call.

Normally, when @var{widget} returns the special parameter @code{LASTWIDGET} will
point to it.  This can be inhibited by passing the option @code{-f nolast}.

Any further arguments will be passed to the widget; note that as
standard argument handling is performed, any general argument list
should be preceded by @code{--}.  If it is a shell
function, these are passed down as positional parameters; for builtin
widgets it is up to the widget in question what it does with them.
Currently arguments are only handled by the incremental-search commands,
the @code{history-search-forward} and @code{-backward} and the corresponding
functions prefixed by @code{vi-}, and by @code{universal-argument}.  No error is
flagged if the command does not use the arguments, or only uses some of
them.

The return status reflects the success or failure of the operation carried
out by the widget, or if it is a user-defined widget the return status of
the shell function.

A non-zero return status causes the shell to beep when the widget exits,
unless the @code{BEEP} options was unset or the widget was called via the
@code{zle} command.  Thus if a user defined widget requires an immediate beep,
it should call the @code{beep} widget directly.
@end quotation
@end quotation

@c historic nodename: Zle Widgets

@node Zle Widgets,User-Defined Widgets,Zle Builtins,Zsh Line Editor
@anchor{Zsh/zle zle-widgets}@anchor{d8}
@section Zle Widgets


@geindex widgets; Command

All actions in the editor are performed by `widgets’.  A widget’s job is
simply to perform some small action.  The ZLE commands that key sequences
in keymaps are bound to are in fact widgets.  Widgets can be user-defined
or built in.

The standard widgets built into ZLE are listed in
@ref{d9,,Standard Widgets}.
Other built-in widgets can be defined by other modules (see
@code{zshmodules}).
Each built-in widget has two names: its normal canonical name, and the
same name preceded by a @code{.}.  The @code{.} name is special: it can’t be
rebound to a different widget.  This makes the widget available even when
its usual name has been redefined.

User-defined widgets are defined using @code{zle -N}, and implemented
as shell functions.  When the widget is executed, the corresponding
shell function is executed, and can perform editing (or other) actions.
It is recommended that user-defined widgets should not have names
starting with @code{.}.

@c historic nodename: User-Defined Widgets

@node User-Defined Widgets,Standard Widgets,Zle Widgets,Zsh Line Editor
@anchor{Zsh/zle user-defined-widgets}@anchor{da}
@section User-Defined Widgets


@geindex widgets@comma{} user-defined; Command

User-defined widgets, being implemented as shell functions,
can execute any normal shell command.  They can also run other widgets
(whether built-in or user-defined) using the @code{zle} builtin command. The
standard input of the function is redirected from /dev/null to prevent
external commands from unintentionally blocking ZLE by reading from the
terminal, but @code{read -k} or @code{read -q} can be used to read characters.
Finally, they can examine and edit the ZLE buffer being edited by reading
and setting the special parameters described below.

@geindex parameters@comma{} editor; Command

@geindex parameters@comma{} zle; Command

These special parameters are always available in widget functions, but
are not in any way special outside ZLE.  If they have some normal value
outside ZLE, that value is temporarily inaccessible, but will return
when the widget function exits.  These special parameters in fact have
local scope, like parameters created in a function using @code{local}.

Inside completion widgets and traps called while ZLE is active, these
parameters are available read-only.

Note that the parameters appear as local to any ZLE widget in
which they appear.  Hence if it is desired to override them this needs
to be done within a nested function:

@example
 widget-function() @{
   # $WIDGET here refers to the special variable
   # that is local inside widget-function
   () @{
      # This anonymous nested function allows WIDGET
      # to be used as a local variable.  The -h
      # removes the special status of the variable.
      local -h WIDGET
   @}
 @}
@end example

@geindex BUFFER; Variable

@code{BUFFER} (scalar)

@quotation

The entire contents of the edit buffer.  If it is written to, the
cursor remains at the same offset, unless that would put it outside the
buffer.
@end quotation

@geindex BUFFERLINES; Variable

@code{BUFFERLINES} (integer)

@quotation

The number of screen lines needed for the edit buffer currently
displayed on screen (i.e. without any changes to the preceding
parameters done after the last redisplay); read-only.
@end quotation

@geindex CONTEXT; Variable

@code{CONTEXT} (scalar)

@quotation

The context in which zle was called to read a line; read-only.  One of
the values:

@code{start}

@quotation

The start of a command line (at prompt @code{PS1}).
@end quotation

@code{cont}

@quotation

A continuation to a command line (at prompt @code{PS2}).
@end quotation

@code{select}

@quotation

In a @code{select} loop (at prompt @code{PS3}).
@end quotation

@code{vared}

@quotation

Editing a variable in @code{vared}.
@end quotation
@end quotation

@geindex CURSOR; Variable

@code{CURSOR} (integer)

@quotation

The offset of the cursor, within the edit buffer.  This is in the range
0 to @code{$#BUFFER}, and is by definition equal to @code{$#LBUFFER}.
Attempts to move the cursor outside the buffer will result in the
cursor being moved to the appropriate end of the buffer.
@end quotation

@geindex CUTBUFFER; Variable

@code{CUTBUFFER} (scalar)

@quotation

The last item cut using one of the @code{kill-} commands; the string
which the next yank would insert in the line.  Later entries in
the kill ring are in the array @code{killring}.  Note that the
command @code{zle copy-region-as-kill} @var{string} can be used to
set the text of the cut buffer from a shell function and cycle the kill
ring in the same way as interactively killing text.
@end quotation

@geindex HISTNO; Variable

@code{HISTNO} (integer)

@quotation

The current history number.  Setting this has the same effect as
moving up or down in the history to the corresponding history line.
An attempt to set it is ignored if the line is not stored in the
history.  Note this is not the same as the parameter @code{HISTCMD},
which always gives the number of the history line being added to the main
shell’s history.  @code{HISTNO} refers to the line being retrieved within
zle.
@end quotation

@geindex ISEARCHMATCH_ACTIVE; Variable

@geindex ISEARCHMATCH_START; Variable

@geindex ISEARCHMATCH_END; Variable

@code{ISEARCHMATCH_ACTIVE} (integer)

@code{ISEARCHMATCH_START} (integer)

@code{ISEARCHMATCH_END} (integer)

@quotation

@code{ISEARCHMATCH_ACTIVE} indicates whether a part of the @code{BUFFER} is
currently matched by an incremental search pattern. @code{ISEARCHMATCH_START}
and @code{ISEARCHMATCH_END} give the location of the matched part and are
in the same units as @code{CURSOR}. They are only valid for reading
when @code{ISEARCHMATCH_ACTIVE} is non-zero.

All parameters are read-only.
@end quotation

@geindex KEYMAP; Variable

@code{KEYMAP} (scalar)

@quotation

The name of the currently selected keymap; read-only.
@end quotation

@geindex KEYS; Variable

@code{KEYS} (scalar)

@quotation

The keys typed to invoke this widget, as a literal string; read-only.
@end quotation

@geindex KEYS_QUEUED_COUNT; Variable

@code{KEYS_QUEUED_COUNT} (integer)

@quotation

The number of bytes pushed back to the input queue and therefore
available for reading immediately before any I/O is done; read-only.
See also @code{PENDING}; the two values are distinct.
@end quotation

@geindex killring; Variable

@code{killring} (array)

@quotation

The array of previously killed items, with the most recently killed first.
This gives the items that would be retrieved by a @code{yank-pop} in the
same order.  Note, however, that the most recently killed item is in
@code{$CUTBUFFER}; @code{$killring} shows the array of previous entries.

The default size for the kill ring is eight, however the length may be
changed by normal array operations.  Any empty string in the kill ring is
ignored by the @code{yank-pop} command, hence the size of the array
effectively sets the maximum length of the kill ring, while the number of
non-zero strings gives the current length, both as seen by the user at the
command line.
@end quotation

@geindex LASTABORTEDSEARCH; Variable

@code{LASTABORTEDSEARCH} (scalar)

@quotation

The last search string used by an interactive search that was
aborted by the user (status 3 returned by the search widget).
@end quotation

@geindex LASTSEARCH; Variable

@code{LASTSEARCH} (scalar)

@quotation

The last search string used by an interactive search; read-only.
This is set even if the search failed (status 0, 1 or 2 returned
by the search widget), but not if it was aborted by the user.
@end quotation

@geindex LASTWIDGET; Variable

@code{LASTWIDGET} (scalar)

@quotation

The name of the last widget that was executed; read-only.
@end quotation

@geindex LBUFFER; Variable

@code{LBUFFER} (scalar)

@quotation

The part of the buffer that lies to the left of the cursor position.
If it is assigned to, only that part of the buffer is replaced, and the
cursor remains between the new @code{$LBUFFER} and the old @code{$RBUFFER}.
@end quotation

@geindex MARK; Variable

@code{MARK} (integer)

@quotation

Like @code{CURSOR}, but for the mark. With vi-mode operators that wait for
a movement command to select a region of text, setting @code{MARK} allows
the selection to extend in both directions from the initial cursor
position.
@end quotation

@geindex NUMERIC; Variable

@code{NUMERIC} (integer)

@quotation

The numeric argument. If no numeric argument was given, this parameter
is unset. When this is set inside a widget function, builtin widgets
called with the @code{zle} builtin command will use the value
assigned. If it is unset inside a widget function, builtin widgets
called behave as if no numeric argument was given.
@end quotation

@geindex PENDING; Variable

@code{PENDING} (integer)

@quotation

The number of bytes pending for input, i.e. the number of bytes which have
already been typed and can immediately be read. On systems where the shell
is not able to get this information, this parameter will always have a
value of zero.  Read-only.  See also @code{KEYS_QUEUED_COUNT}; the two
values are distinct.
@end quotation

@geindex PREBUFFER; Variable

@code{PREBUFFER} (scalar)

@quotation

In a multi-line input at the secondary prompt, this read-only parameter
contains the contents of the lines before the one the cursor is
currently in.
@end quotation

@geindex PREDISPLAY; Variable

@code{PREDISPLAY} (scalar)

@quotation

Text to be displayed before the start of the editable text buffer.  This
does not have to be a complete line; to display a complete line, a newline
must be appended explicitly.  The text is reset on each new invocation
(but not recursive invocation) of zle.
@end quotation

@geindex POSTDISPLAY; Variable

@code{POSTDISPLAY} (scalar)

@quotation

Text to be displayed after the end of the editable text buffer.  This
does not have to be a complete line; to display a complete line, a newline
must be prepended explicitly.  The text is reset on each new invocation
(but not recursive invocation) of zle.
@end quotation

@geindex RBUFFER; Variable

@code{RBUFFER} (scalar)

@quotation

The part of the buffer that lies to the right of the cursor position.
If it is assigned to, only that part of the buffer is replaced, and the
cursor remains between the old @code{$LBUFFER} and the new @code{$RBUFFER}.
@end quotation

@geindex REGION_ACTIVE; Variable

@code{REGION_ACTIVE} (integer)

@quotation

Indicates if the region is currently active.  It can be assigned 0 or 1
to deactivate and activate the region respectively. A value of 2
activates the region in line-wise mode with the highlighted text
extending for whole lines only; see
@ref{60,,Character Highlighting}.
@end quotation

@geindex region_highlight; Variable

@code{region_highlight} (array)

@quotation

Each element of this array may be set to a string that describes
highlighting for an arbitrary region of the command line that will
take effect the next time the command line is redisplayed.  Highlighting
of the non-editable parts of the command line in @code{PREDISPLAY}
and @code{POSTDISPLAY} are possible, but note that the @code{P} flag
is needed for character indexing to include @code{PREDISPLAY}.

Each string consists of the following whitespace-separated parts:

@quotation


@itemize *

@item 
Optionally, a @code{P} to signify that the start and end offset that
@end itemize

follow include any string set by the @code{PREDISPLAY} special parameter;
this is needed if the predisplay string itself is to be highlighted.
Whitespace between the @code{P} and the start offset is optional.
* A start offset in the same units as @code{CURSOR}.
* An end offset in the same units as @code{CURSOR}.
* A highlight specification in the same format as
used for contexts in the parameter @code{zle_highlight}, see
@ref{60,,Character Highlighting};
for example, @code{standout} or @code{fg=red,bold}.
* Optionally, a string of the form @code{memo=}@var{token}.
The @var{token} consists of everything between the @code{=} and the next
whitespace, comma, NUL, or the end of the string.
The @var{token} is preserved verbatim but not parsed in any way.

Plugins may use this to identify array elements they have added: for example,
a plugin might set @var{token} to its (the plugin’s) name and then use
@code{region_highlight=( $@{region_highlight:#*memo=}@var{token}@code{@} )}
in order to remove array elements it added.

(This example uses the @code{$@{}@var{name}@code{:#}@var{pattern}@code{@}} array-grepping
syntax described in
@ref{1a,,Parameter Expansion}.)
@end quotation

For example,

@example
 region_highlight=("P0 20 bold memo=foobar")
@end example

specifies that the first twenty characters of the text including
any predisplay string should be highlighted in bold.

Note that the effect of @code{region_highlight} is not saved and disappears
as soon as the line is accepted.

Note that zsh 5.8 and older do not support the @code{memo=}@var{token} field
and may misparse the third (highlight specification) field when a memo
is given.

Where a particular region is covered by multiple entries in
@code{region_highlight}, their effects are merged. In the case of conflicts, later
entries take precedence over earlier ones. This precedence ordering can be
overridden by specifying layers.

The final highlighting on the command line depends on both @code{region_highlight}
and @code{zle_highlight}; see
@ref{60,,Character Highlighting} for details.
@end quotation

@geindex registers; Variable

@code{registers} (associative array)

@quotation

The contents of each of the vi register buffers. These are
typically set using @code{vi-set-buffer} followed by a delete, change or
yank command.
@end quotation

@geindex SUFFIX_ACTIVE; Variable

@geindex SUFFIX_START; Variable

@geindex SUFFIX_END; Variable

@code{SUFFIX_ACTIVE} (integer)

@code{SUFFIX_START} (integer)

@code{SUFFIX_END} (integer)

@quotation

@code{SUFFIX_ACTIVE} indicates whether an auto-removable completion suffix
is currently active. @code{SUFFIX_START} and @code{SUFFIX_END} give the
location of the suffix and are in the same units as @code{CURSOR}. They are
only valid for reading when @code{SUFFIX_ACTIVE} is non-zero.

All parameters are read-only.
@end quotation

@geindex UNDO_CHANGE_NO; Variable

@code{UNDO_CHANGE_NO} (integer)

@quotation

A number representing the state of the undo history.  The only use
of this is passing as an argument to the @code{undo} widget in order to
undo back to the recorded point.  Read-only.
@end quotation

@geindex UNDO_LIMIT_NO; Variable

@code{UNDO_LIMIT_NO} (integer)

@quotation

A number corresponding to an existing change in the undo history;
compare @code{UNDO_CHANGE_NO}.  If this is set to a value greater
than zero, the @code{undo} command will not allow the line to
be undone beyond the given change number.  It is still possible
to use @code{zle undo} @var{change} in a widget to undo beyond
that point; in that case, it will not be possible to undo at
all until @code{UNDO_LIMIT_NO} is reduced.  Set to 0 to disable the limit.

A typical use of this variable in a widget function is as follows (note
the additional function scope is required):

@example
 () @{
   local UNDO_LIMIT_NO=$UNDO_CHANGE_NO
   # Perform some form of recursive edit.
 @}
@end example
@end quotation

@geindex WIDGET; Variable

@code{WIDGET} (scalar)

@quotation

The name of the widget currently being executed; read-only.
@end quotation

@geindex WIDGETFUNC; Variable

@code{WIDGETFUNC} (scalar)

@quotation

The name of the shell function that implements a widget defined with
either @code{zle -N} or @code{zle -C}.  In the former case, this is the second
argument to the @code{zle -N} command that defined the widget, or
the first argument if there was no second argument.  In the latter case
this is the third argument to the @code{zle -C} command that defined the
widget.  Read-only.
@end quotation

@geindex WIDGETSTYLE; Variable

@code{WIDGETSTYLE} (scalar)

@quotation

Describes the implementation behind the completion widget currently being
executed; the second argument that followed @code{zle -C} when the widget was
defined.  This is the name of a builtin completion widget.  For widgets
defined with @code{zle -N} this is set to the empty string.  Read-only.
@end quotation

@geindex YANK_ACTIVE; Variable

@geindex YANK_START; Variable

@geindex YANK_END; Variable

@code{YANK_ACTIVE} (integer)

@code{YANK_START} (integer)

@code{YANK_END} (integer)

@quotation

@code{YANK_ACTIVE} indicates whether text has just been yanked (pasted)
into the buffer.  @code{YANK_START} and @code{YANK_END} give the location of
the pasted text and are in the same units as @code{CURSOR}.  They are only
valid for reading when @code{YANK_ACTIVE} is non-zero.  They can also be
assigned by widgets that insert text in a yank-like fashion, for example
wrappers of @code{bracketed-paste}.  See also @code{zle -f}.

@code{YANK_ACTIVE} is read-only.
@end quotation

@geindex ZLE_RECURSIVE; Variable

@code{ZLE_RECURSIVE} (integer)

@quotation

Usually zero, but incremented inside any instance of
@code{recursive-edit}.  Hence indicates the current recursion level.

@code{ZLE_RECURSIVE} is read-only.
@end quotation

@geindex ZLE_STATE; Variable

@code{ZLE_STATE} (scalar)

@quotation

Contains a set of space-separated words that describe the current @code{zle}
state.

Currently, the states shown are the insert mode as set by the
@code{overwrite-mode} or @code{vi-replace} widgets and whether history commands
will visit imported entries as controlled by the set-local-history widget.
The string contains @code{insert} if characters to be inserted on the
command line move existing characters to the right or @code{overwrite}
if characters to be inserted overwrite existing characters. It contains
@code{localhistory} if only local history commands will be visited or
@code{globalhistory} if imported history commands will also be visited.

The substrings are sorted in alphabetical order so that if you want to
test for two specific substrings in a future-proof way, you can do match
by doing:

@example
 if [[ $ZLE_STATE == *globalhistory*insert* ]]; then ...; fi
@end example
@end quotation

@menu
* Special Widgets:: 

@end menu

@node Special Widgets,,,User-Defined Widgets
@anchor{Zsh/zle id1}@anchor{db}@anchor{Zsh/zle special-widgets}@anchor{dc}
@subsection Special Widgets


There are a few user-defined widgets which are special to the shell.
If they do not exist, no special action is taken.  The environment
provided is identical to that for any other editing widget.

@geindex zle-isearch-exit; Type

@code{zle-isearch-exit}

@quotation

Executed at the end of incremental search at the point where the isearch
prompt is removed from the display.  See @code{zle-isearch-update} for
an example.
@end quotation

@geindex zle-isearch-update; Type

@code{zle-isearch-update}

@quotation

Executed within incremental search when the display is about to be
redrawn.  Additional output below the incremental search prompt can be
generated by using @code{zle -M} within the widget.  For example,

@example
 zle-isearch-update() @{ zle -M "Line $HISTNO"; @}
 zle -N zle-isearch-update
@end example

Note the line output by @code{zle -M} is not deleted on exit from
incremental search.  This can be done from a @code{zle-isearch-exit}
widget:

@example
 zle-isearch-exit() @{ zle -M ""; @}
 zle -N zle-isearch-exit
@end example
@end quotation

@geindex zle-line-pre-redraw; Type

@code{zle-line-pre-redraw}

@quotation

Executed whenever the input line is about to be redrawn, providing an
opportunity to update the region_highlight array.
@end quotation

@geindex zle-line-init; Type

@code{zle-line-init}

@quotation

Executed every time the line editor is started to read a new line
of input.  The following example puts the line editor into vi command
mode when it starts up.

@example
 zle-line-init() @{ zle -K vicmd; @}
 zle -N zle-line-init
@end example

(The command inside the function sets the keymap directly; it is
equivalent to @code{zle vi-cmd-mode}.)
@end quotation

@geindex zle-line-finish; Type

@code{zle-line-finish}

@quotation

This is similar to @code{zle-line-init} but is executed every time the
line editor has finished reading a line of input.
@end quotation

@geindex zle-history-line-set; Type

@code{zle-history-line-set}

@quotation

Executed when the history line changes.
@end quotation

@geindex zle-keymap-select; Type

@code{zle-keymap-select}

@quotation

Executed every time the keymap changes, i.e. the special parameter
@code{KEYMAP} is set to a different value, while the line editor is active.
Initialising the keymap when the line editor starts does not cause the
widget to be called.

The value @code{$KEYMAP} within the function reflects the new keymap.  The
old keymap is passed as the sole argument.

This can be used for detecting switches between the vi command
(@code{vicmd}) and insert (usually @code{main}) keymaps.
@end quotation

@c historic nodename: Standard Widgets

@node Standard Widgets,Terminal Extensions,User-Defined Widgets,Zsh Line Editor
@anchor{Zsh/zle standard-widgets}@anchor{d9}
@section Standard Widgets


@geindex widgets@comma{} standard; Command

The following is a list of all the standard widgets,
and their default bindings in emacs mode,
vi command mode and vi insert mode
(the @code{emacs}, @code{vicmd} and @code{viins} keymaps, respectively).

Note that cursor keys are bound to movement keys in all three keymaps;
the shell assumes that the cursor keys send the key sequences reported
by the terminal-handling library (termcap or terminfo).  The key sequences
shown in the list are those based on the VT100, common on many modern
terminals, but in fact these are not necessarily bound.  In the case of the
@code{viins} keymap, the initial escape character of the sequences serves also
to return to the @code{vicmd} keymap: whether this happens is determined by
the @code{KEYTIMEOUT} parameter, see
@ref{11,,Parameters Used by the Shell}.

@c historic nodename: Movement

@menu
* Movement:: 
* History Control:: 
* Modifying Text:: 
* Arguments:: 
* Completion: Completion<3>. 
* Miscellaneous:: 
* Text Objects:: 

@end menu

@node Movement,History Control,,Standard Widgets
@anchor{Zsh/zle movement}@anchor{dd}
@subsection Movement


@geindex vi-backward-blank-word; Type

@code{vi-backward-blank-word} (unbound) (@code{B}) (unbound)

@quotation

Move backward one word, where a word is defined as a series of
non-blank characters.
@end quotation

@geindex vi-backward-blank-word-end; Type

@code{vi-backward-blank-word-end} (unbound) (@code{gE}) (unbound)

@quotation

Move to the end of the previous word, where a word is defined as a
series of non-blank characters.
@end quotation

@geindex backward-char; Type

@code{backward-char} (@code{^B ESC-[D}) (unbound) (unbound)

@quotation

Move backward one character.
@end quotation

@geindex vi-backward-char; Type

@code{vi-backward-char} (unbound) (@code{^H h ^?}) (@code{ESC-[D})

@quotation

Move backward one character, without changing lines.
@end quotation

@geindex backward-word; Type

@code{backward-word} (@code{ESC-B ESC-b}) (unbound) (unbound)

@quotation

Move to the beginning of the previous word.
@end quotation

@geindex emacs-backward-word; Type

@code{emacs-backward-word}

@quotation

Move to the beginning of the previous word.
@end quotation

@geindex vi-backward-word; Type

@code{vi-backward-word} (unbound) (@code{b}) (unbound)

@quotation

Move to the beginning of the previous word, vi-style.
@end quotation

@geindex vi-backward-word-end; Type

@code{vi-backward-word-end} (unbound) (@code{ge}) (unbound)

@quotation

Move to the end of the previous word, vi-style.
@end quotation

@geindex beginning-of-line; Type

@code{beginning-of-line} (@code{^A}) (unbound) (unbound)

@quotation

Move to the beginning of the line.  If already at the beginning
of the line, move to the beginning of the previous line, if any.
@end quotation

@geindex vi-beginning-of-line; Type

@code{vi-beginning-of-line}

@quotation

Move to the beginning of the line, without changing lines.
@end quotation

@geindex down-line; Type

@code{down-line} (unbound) (unbound) (unbound)

@quotation

Move down a line in the buffer.
@end quotation

@geindex end-of-line; Type

@code{end-of-line} (@code{^E}) (unbound) (unbound)

@quotation

Move to the end of the line.  If already at the end
of the line, move to the end of the next line, if any.
@end quotation

@geindex vi-end-of-line; Type

@code{vi-end-of-line} (unbound) (@code{$}) (unbound)

@quotation

Move to the end of the line.
If an argument is given to this command, the cursor will be moved to
the end of the line (argument - 1) lines down.
@end quotation

@geindex vi-forward-blank-word; Type

@code{vi-forward-blank-word} (unbound) (@code{W}) (unbound)

@quotation

Move forward one word, where a word is defined as a series of
non-blank characters.
@end quotation

@geindex vi-forward-blank-word-end; Type

@code{vi-forward-blank-word-end} (unbound) (@code{E}) (unbound)

@quotation

Move to the end of the current word, or, if at the end of the current word,
to the end of the next word,
where a word is defined as a series of non-blank characters.
@end quotation

@geindex forward-char; Type

@code{forward-char} (@code{^F ESC-[C}) (unbound) (unbound)

@quotation

Move forward one character.
@end quotation

@geindex vi-forward-char; Type

@code{vi-forward-char} (unbound) (@code{space l}) (@code{ESC-[C})

@quotation

Move forward one character.
@end quotation

@geindex vi-find-next-char; Type

@code{vi-find-next-char} (@code{^X^F}) (@code{f}) (unbound)

@quotation

Read a character from the keyboard, and move to
the next occurrence of it in the line.
@end quotation

@geindex vi-find-next-char-skip; Type

@code{vi-find-next-char-skip} (unbound) (@code{t}) (unbound)

@quotation

Read a character from the keyboard, and move to
the position just before the next occurrence of it in the line.
@end quotation

@geindex vi-find-prev-char; Type

@code{vi-find-prev-char} (unbound) (@code{F}) (unbound)

@quotation

Read a character from the keyboard, and move to
the previous occurrence of it in the line.
@end quotation

@geindex vi-find-prev-char-skip; Type

@code{vi-find-prev-char-skip} (unbound) (@code{T}) (unbound)

@quotation

Read a character from the keyboard, and move to
the position just after the previous occurrence of it in the line.
@end quotation

@geindex vi-first-non-blank; Type

@code{vi-first-non-blank} (unbound) (@code{_ ^}) (unbound)

@quotation

Move to the first non-blank character in the line.
@end quotation

@geindex vi-forward-word; Type

@code{vi-forward-word} (unbound) (@code{w}) (unbound)

@quotation

Move forward one word, vi-style.
@end quotation

@geindex forward-word; Type

@code{forward-word} (@code{ESC-F ESC-f}) (unbound) (unbound)

@quotation

Move to the beginning of the next word.
The editor’s idea of a word is specified with the @code{WORDCHARS}
parameter.
@end quotation

@geindex emacs-forward-word; Type

@code{emacs-forward-word}

@quotation

Move to the end of the next word.
@end quotation

@geindex vi-forward-word-end; Type

@code{vi-forward-word-end} (unbound) (@code{e}) (unbound)

@quotation

Move to the end of the next word.
@end quotation

@geindex vi-goto-column; Type

@code{vi-goto-column} (@code{ESC-|}) (@code{|}) (unbound)

@quotation

Move to the column specified by the numeric argument.
@end quotation

@geindex vi-goto-mark; Type

@code{vi-goto-mark} (unbound) (>>`@w{`}<<>>`@w{`}<<) (unbound)

@quotation

Move to the specified mark.
@end quotation

@geindex vi-goto-mark-line; Type

@code{vi-goto-mark-line} (unbound) (>>`@w{`}<<>>`@w{`}<<) (unbound)

@quotation

Move to beginning of the line containing the specified mark.
@end quotation

@geindex vi-repeat-find; Type

@code{vi-repeat-find} (unbound) (@code{;}) (unbound)

@quotation

Repeat the last @code{vi-find} command.
@end quotation

@geindex vi-rev-repeat-find; Type

@code{vi-rev-repeat-find} (unbound) (@code{,}) (unbound)

@quotation

Repeat the last @code{vi-find} command in the opposite direction.
@end quotation

@geindex up-line; Type

@code{up-line} (unbound) (unbound) (unbound)

@quotation

Move up a line in the buffer.
@end quotation

@c historic nodename: History Control

@node History Control,Modifying Text,Movement,Standard Widgets
@anchor{Zsh/zle history-control}@anchor{de}
@subsection History Control


@geindex beginning-of-buffer-or-history; Type

@code{beginning-of-buffer-or-history} (@code{ESC-<}) (@code{gg}) (unbound)

@quotation

Move to the beginning of the buffer, or if already there,
move to the first event in the history list.
@end quotation

@geindex beginning-of-line-hist; Type

@code{beginning-of-line-hist}

@quotation

Move to the beginning of the line.  If already at the
beginning of the buffer, move to the previous history line.
@end quotation

@geindex beginning-of-history; Type

@code{beginning-of-history}

@quotation

Move to the first event in the history list.
@end quotation

@geindex down-line-or-history; Type

@code{down-line-or-history} (@code{^N ESC-[B}) (@code{j}) (@code{ESC-[B})

@quotation

Move down a line in the buffer, or if already at the bottom line,
move to the next event in the history list.
@end quotation

@geindex vi-down-line-or-history; Type

@code{vi-down-line-or-history} (unbound) (@code{+}) (unbound)

@quotation

Move down a line in the buffer, or if already at the bottom line,
move to the next event in the history list.
Then move to the first non-blank character on the line.
@end quotation

@geindex down-line-or-search; Type

@code{down-line-or-search}

@quotation

Move down a line in the buffer, or if already at the bottom line,
search forward in the history for a line beginning with the first
word in the buffer.

If called from a function by the @code{zle} command with arguments, the first
argument is taken as the string for which to search, rather than the
first word in the buffer.
@end quotation

@geindex down-history; Type

@code{down-history} (unbound) (@code{^N}) (unbound)

@quotation

Move to the next event in the history list.
@end quotation

@geindex history-beginning-search-backward; Type

@code{history-beginning-search-backward}

@quotation

Search backward in the history for a line beginning with the current
line up to the cursor.
This leaves the cursor in its original position.
@end quotation

@geindex end-of-buffer-or-history; Type

@code{end-of-buffer-or-history} (@code{ESC->}) (unbound) (unbound)

@quotation

Move to the end of the buffer, or if already there,
move to the last event in the history list.
@end quotation

@geindex end-of-line-hist; Type

@code{end-of-line-hist}

@quotation

Move to the end of the line.  If already at the end of
the buffer, move to the next history line.
@end quotation

@geindex end-of-history; Type

@code{end-of-history}

@quotation

Move to the last event in the history list.
@end quotation

@geindex vi-fetch-history; Type

@code{vi-fetch-history} (unbound) (@code{G}) (unbound)

@quotation

Fetch the history line specified by the numeric argument.
This defaults to the current history line
(i.e. the one that isn’t history yet).
@end quotation

@geindex history-incremental-search-backward; Type

@code{history-incremental-search-backward} (@code{^R ^Xr}) (unbound) (unbound)

@quotation

Search backward incrementally for a specified string.  The search is
case-insensitive if the search string does not have uppercase letters and no
numeric argument was given.  The string may begin with @code{^} to anchor the
search to the beginning of the line.  When called from a user-defined
function returns the following statuses: 0, if the search succeeded;
1, if the search failed; 2, if the search term was a bad pattern;
3, if the search was aborted by the @code{send-break} command.

A restricted set of editing functions
is available in the mini-buffer.  Keys are looked up in the special
@code{isearch} keymap, and if not found there in the main keymap (note
that by default the @code{isearch} keymap is empty).
An interrupt signal, as defined by the stty
setting, will stop the search and go back to the original line.  An undefined
key will have the same effect.  Note that the following always
perform the same task within incremental searches and cannot be
replaced by user defined widgets, nor can the set of functions
be extended.  The supported functions are:

@code{accept-and-hold}

@code{accept-and-infer-next-history}

@code{accept-line}

@code{accept-line-and-down-history}

@quotation

Perform the usual function after exiting incremental search.
The command line displayed is executed.
@end quotation

@code{backward-delete-char}

@code{vi-backward-delete-char}

@quotation

Back up one place in the search history.  If the search has been
repeated this does not immediately erase a character in the
minibuffer.
@end quotation

@code{accept-search}

@quotation

Exit incremental search, retaining the command line but performing no
further action.  Note that this function is not bound by default
and has no effect outside incremental search.
@end quotation

@code{backward-delete-word}

@code{backward-kill-word}

@code{vi-backward-kill-word}

@quotation

Back up one character in the minibuffer; if multiple searches
have been performed since the character was inserted the search
history is rewound to the point just before the character was
entered.  Hence this has the effect of repeating
@code{backward-delete-char}.
@end quotation

@code{clear-screen}

@quotation

Clear the screen, remaining in incremental search mode.
@end quotation

@code{history-incremental-search-backward}

@quotation

Find the next occurrence of the contents of the mini-buffer. If the
mini-buffer is empty, the most recent previously used search string is
reinstated.
@end quotation

@code{history-incremental-search-forward}

@quotation

Invert the sense of the search.
@end quotation

@code{magic-space}

@quotation

Inserts a non-magical space.
@end quotation

@code{quoted-insert}

@code{vi-quoted-insert}

@quotation

Quote the character to insert into the minibuffer.
@end quotation

@code{redisplay}

@quotation

Redisplay the command line, remaining in incremental search mode.
@end quotation

@code{vi-cmd-mode}

@quotation

Select the @code{vicmd} keymap;
the @code{main} keymap (insert mode) will be selected initially.

In addition, the modifications that were made while in vi insert mode are
merged to form a single undo event.
@end quotation

@code{vi-repeat-search}

@code{vi-rev-repeat-search}

@quotation

Repeat the search.  The direction of the search is indicated in the
mini-buffer.
@end quotation

Any character that is not bound to one of the above functions, or
@code{self-insert} or @code{self-insert-unmeta}, will cause the mode to be
exited.  The character is then looked up and executed in the keymap in
effect at that point.

When called from a widget function by the @code{zle} command, the incremental
search commands can take a string argument.  This will be treated as a
string of keys, as for arguments to the @code{bindkey} command, and used as
initial input for the command.  Any characters in the string which are
unused by the incremental search will be silently ignored.  For example,

@example
 zle history-incremental-search-backward forceps
@end example

will search backwards for @code{forceps}, leaving the minibuffer containing
the string @code{forceps}.
@end quotation

@geindex history-incremental-search-forward; Type

@code{history-incremental-search-forward} (@code{^S ^Xs}) (unbound) (unbound)

@quotation

Search forward incrementally for a specified string.  The search is
case-insensitive if the search string does not have uppercase letters and no
numeric argument was given.  The string may begin with @code{^} to anchor the
search to the beginning of the line.  The functions available in the
mini-buffer are the same as for @code{history-incremental-search-backward}.
@end quotation

@geindex history-incremental-pattern-search-backward; Type

@geindex history-incremental-pattern-search-forward; Type

@code{history-incremental-pattern-search-backward}

@code{history-incremental-pattern-search-forward}

@quotation

These widgets behave similarly to the corresponding widgets with
no @code{-pattern}, but the search string typed by the user is treated
as a pattern, respecting the current settings of the various options
affecting pattern matching.  See @ref{17,,Filename Generation}
for a description of patterns.
If no numeric argument was given lowercase letters in the search
string may match uppercase letters in the history.  The string may begin
with @code{^} to anchor the search to the beginning of the line.

The prompt changes to indicate an invalid pattern; this may simply
indicate the pattern is not yet complete.

Note that only non-overlapping matches are reported, so an expression
with wildcards may return fewer matches on a line than are visible
by inspection.
@end quotation

@geindex history-search-backward; Type

@code{history-search-backward} (@code{ESC-P ESC-p}) (unbound) (unbound)

@quotation

Search backward in the history for a line beginning with the first
word in the buffer.

If called from a function by the @code{zle} command with arguments, the first
argument is taken as the string for which to search, rather than the
first word in the buffer.
@end quotation

@geindex vi-history-search-backward; Type

@code{vi-history-search-backward} (unbound) (@code{/}) (unbound)

@quotation

Search backward in the history for a specified string.
The string may begin with @code{^} to anchor the search to the
beginning of the line.

A restricted set of editing functions is available in
the mini-buffer.  An interrupt signal, as defined by the stty setting,  will
stop the search.
The functions available in the mini-buffer are:
@code{accept-line},
@code{backward-delete-char},
@code{vi-backward-delete-char},
@code{backward-kill-word},
@code{vi-backward-kill-word},
@code{clear-screen},
@code{redisplay},
@code{quoted-insert}
and
@code{vi-quoted-insert}.

@code{vi-cmd-mode} is treated the same as accept-line, and
@code{magic-space} is treated as a space.
Any other character that is not bound to self-insert or
self-insert-unmeta will beep and be ignored. If the function is called from vi
command mode, the bindings of the current insert mode will be used.

If called from a function by the @code{zle} command with arguments, the first
argument is taken as the string for which to search, rather than the
first word in the buffer.
@end quotation

@geindex history-search-forward; Type

@code{history-search-forward} (@code{ESC-N ESC-n}) (unbound) (unbound)

@quotation

Search forward in the history for a line beginning with the first
word in the buffer.

If called from a function by the @code{zle} command with arguments, the first
argument is taken as the string for which to search, rather than the
first word in the buffer.
@end quotation

@geindex vi-history-search-forward; Type

@code{vi-history-search-forward} (unbound) (@code{?}) (unbound)

@quotation

Search forward in the history for a specified string.
The string may begin with @code{^} to anchor the search to the
beginning of the line. The functions available in the mini-buffer are the same
as for @code{vi-history-search-backward}.  Argument handling is also the same
as for that command.
@end quotation

@geindex infer-next-history; Type

@code{infer-next-history} (@code{^X^N}) (unbound) (unbound)

@quotation

Search in the history list for a line matching the current one and
fetch the event following it.
@end quotation

@geindex insert-last-word; Type

@code{insert-last-word} (@code{ESC-_ ESC-.}) (unbound) (unbound)

@quotation

Insert the last word from the previous history event at the
cursor position.  If a positive numeric argument is given,
insert that word from the end of the previous history event.
If the argument is zero or negative insert that word from the
left (zero inserts the previous command word).  Repeating this command
replaces the word just inserted with the last word from the
history event prior to the one just used; numeric arguments can be used in
the same way to pick a word from that event.

When called from a shell function invoked from a user-defined widget, the
command can take one to three arguments.  The first argument specifies a
history offset which applies to successive calls to this widget: if it is -1,
the default behaviour is used, while if it is 1, successive calls will move
forwards through the history.  The value 0 can be used to indicate that the
history line examined by the previous execution of the command will be
reexamined.  Note that negative numbers should be preceded by a
@code{--} argument to avoid confusing them with options.

If two arguments are given, the second specifies the word on the command
line in normal array index notation (as a more natural alternative to the
numeric argument).  Hence 1 is the first word, and -1 (the default) is the
last word.

If a third argument is given, its value is ignored, but it is used to
signify that the history offset is relative to the current history line,
rather than the one remembered after the previous invocations of
@code{insert-last-word}.

For example, the default behaviour of the command corresponds to

@example
 zle insert-last-word -- -1 -1
@end example

while the command

@example
 zle insert-last-word -- -1 1 -
@end example

always copies the first word of the line in the history immediately before
the line being edited.  This has the side effect that later invocations of
the widget will be relative to that line.
@end quotation

@geindex vi-repeat-search; Type

@code{vi-repeat-search} (unbound) (@code{n}) (unbound)

@quotation

Repeat the last vi history search.
@end quotation

@geindex vi-rev-repeat-search; Type

@code{vi-rev-repeat-search} (unbound) (@code{N}) (unbound)

@quotation

Repeat the last vi history search, but in reverse.
@end quotation

@geindex up-line-or-history; Type

@code{up-line-or-history} (@code{^P ESC-[A}) (@code{k}) (@code{ESC-[A})

@quotation

Move up a line in the buffer, or if already at the top line,
move to the previous event in the history list.
@end quotation

@geindex vi-up-line-or-history; Type

@code{vi-up-line-or-history} (unbound) (@code{-}) (unbound)

@quotation

Move up a line in the buffer, or if already at the top line,
move to the previous event in the history list.
Then move to the first non-blank character on the line.
@end quotation

@geindex up-line-or-search; Type

@code{up-line-or-search}

@quotation

Move up a line in the buffer, or if already at the top line,
search backward in the history for a line beginning with the
first word in the buffer.

If called from a function by the @code{zle} command with arguments, the first
argument is taken as the string for which to search, rather than the
first word in the buffer.
@end quotation

@geindex up-history; Type

@code{up-history} (unbound) (@code{^P}) (unbound)

@quotation

Move to the previous event in the history list.
@end quotation

@geindex history-beginning-search-forward; Type

@code{history-beginning-search-forward}

@quotation

Search forward in the history for a line beginning with the current
line up to the cursor.
This leaves the cursor in its original position.
@end quotation

@geindex set-local-history; Type

@code{set-local-history}

@quotation

By default, history movement commands visit the imported lines as well as
the local lines. This widget lets you toggle this on and off, or set it with
the numeric argument. Zero for both local and imported lines and nonzero for
only local lines.
@end quotation

@c historic nodename: Modifying Text

@node Modifying Text,Arguments,History Control,Standard Widgets
@anchor{Zsh/zle modifying-text}@anchor{df}
@subsection Modifying Text


@geindex vi-add-eol; Type

@code{vi-add-eol} (unbound) (@code{A}) (unbound)

@quotation

Move to the end of the line and enter insert mode.
@end quotation

@geindex vi-add-next; Type

@code{vi-add-next} (unbound) (@code{a}) (unbound)

@quotation

Enter insert mode after the current cursor position, without changing lines.
@end quotation

@geindex backward-delete-char; Type

@code{backward-delete-char} (@code{^H ^?}) (unbound) (unbound)

@quotation

Delete the character behind the cursor.
@end quotation

@geindex vi-backward-delete-char; Type

@code{vi-backward-delete-char} (unbound) (@code{X}) (@code{^H})

@quotation

Delete the character behind the cursor, without changing lines.
If in insert mode, this won’t delete past the point where insert mode was
last entered.
@end quotation

@geindex backward-delete-word; Type

@code{backward-delete-word}

@quotation

Delete the word behind the cursor.
@end quotation

@geindex backward-kill-line; Type

@code{backward-kill-line}

@quotation

Kill from the beginning of the line to the cursor position.
@end quotation

@geindex backward-kill-word; Type

@code{backward-kill-word} (@code{^W ESC-^H ESC-^?}) (unbound) (unbound)

@quotation

Kill the word behind the cursor.
@end quotation

@geindex vi-backward-kill-word; Type

@code{vi-backward-kill-word} (unbound) (unbound) (@code{^W})

@quotation

Kill the word behind the cursor, without going past the point where insert
mode was last entered.
@end quotation

@geindex capitalize-word; Type

@code{capitalize-word} (@code{ESC-C ESC-c}) (unbound) (unbound)

@quotation

Capitalize the current word and move past it.
@end quotation

@geindex vi-change; Type

@code{vi-change} (unbound) (@code{c}) (unbound)

@quotation

Read a movement command from the keyboard, and kill
from the cursor position to the endpoint of the movement.
Then enter insert mode.
If the command is @code{vi-change}, change the current line.

For compatibility with vi, if the command is @code{vi-forward-word}
or @code{vi-forward-blank-word}, the whitespace after the word is not
included. If you prefer the more consistent behaviour with the
whitespace included use the following key binding:

@example
 bindkey -a -s cw dwi
@end example
@end quotation

@geindex vi-change-eol; Type

@code{vi-change-eol} (unbound) (@code{C}) (unbound)

@quotation

Kill to the end of the line and enter insert mode.
@end quotation

@geindex vi-change-whole-line; Type

@code{vi-change-whole-line} (unbound) (@code{S}) (unbound)

@quotation

Kill the current line and enter insert mode.
@end quotation

@geindex copy-region-as-kill; Type

@code{copy-region-as-kill} (@code{ESC-W ESC-w}) (unbound) (unbound)

@quotation

Copy the area from the cursor to the mark to the kill buffer.

If called from a ZLE widget function in the form @code{zle
copy-region-as-kill} @var{string} then @var{string} will be taken as the
text to copy to the kill buffer.  The cursor, the mark and the text on the
command line are not used in this case.
@end quotation

@geindex copy-prev-word; Type

@code{copy-prev-word} (@code{ESC-^_}) (unbound) (unbound)

@quotation

Duplicate the word to the left of the cursor.
@end quotation

@geindex copy-prev-shell-word; Type

@code{copy-prev-shell-word}

@quotation

Like @code{copy-prev-word}, but the word is found by using shell parsing,
whereas @code{copy-prev-word} looks for blanks. This makes a difference
when the word is quoted and contains spaces.
@end quotation

@geindex vi-delete; Type

@code{vi-delete} (unbound) (@code{d}) (unbound)

@quotation

Read a movement command from the keyboard, and kill
from the cursor position to the endpoint of the movement.
If the command is @code{vi-delete}, kill the current line.
@end quotation

@geindex delete-char; Type

@code{delete-char}

@quotation

Delete the character under the cursor.
@end quotation

@geindex vi-delete-char; Type

@code{vi-delete-char} (unbound) (@code{x}) (unbound)

@quotation

Delete the character under the cursor,
without going past the end of the line.
@end quotation

@geindex delete-word; Type

@code{delete-word}

@quotation

Delete the current word.
@end quotation

@geindex down-case-word; Type

@code{down-case-word} (@code{ESC-L ESC-l}) (unbound) (unbound)

@quotation

Convert the current word to all lowercase and move past it.
@end quotation

@geindex vi-down-case; Type

@code{vi-down-case} (unbound) (@code{gu}) (unbound)

@quotation

Read a movement command from the keyboard, and convert all characters
from the cursor position to the endpoint of the movement to lowercase.
If the movement command is @code{vi-down-case}, swap the case of all
characters on the current line.
@end quotation

@geindex kill-word; Type

@code{kill-word} (@code{ESC-D ESC-d}) (unbound) (unbound)

@quotation

Kill the current word.
@end quotation

@geindex gosmacs-transpose-chars; Type

@code{gosmacs-transpose-chars}

@quotation

Exchange the two characters behind the cursor.
@end quotation

@geindex vi-indent; Type

@code{vi-indent} (unbound) (@code{>}) (unbound)

@quotation

Indent a number of lines.
@end quotation

@geindex vi-insert; Type

@code{vi-insert} (unbound) (@code{i}) (unbound)

@quotation

Enter insert mode.
@end quotation

@geindex vi-insert-bol; Type

@code{vi-insert-bol} (unbound) (@code{I}) (unbound)

@quotation

Move to the first non-blank character on the line and enter insert mode.
@end quotation

@geindex vi-join; Type

@code{vi-join} (@code{^X^J}) (@code{J}) (unbound)

@quotation

Join the current line with the next one.
@end quotation

@geindex kill-line; Type

@code{kill-line} (@code{^K}) (unbound) (unbound)

@quotation

Kill from the cursor to the end of the line.
If already on the end of the line, kill the newline character.
@end quotation

@geindex vi-kill-line; Type

@code{vi-kill-line} (unbound) (unbound) (@code{^U})

@quotation

Kill from the cursor back to wherever insert mode was last entered.
@end quotation

@geindex vi-kill-eol; Type

@code{vi-kill-eol} (unbound) (@code{D}) (unbound)

@quotation

Kill from the cursor to the end of the line.
@end quotation

@geindex kill-region; Type

@code{kill-region}

@quotation

Kill from the cursor to the mark.
@end quotation

@geindex kill-buffer; Type

@code{kill-buffer} (@code{^X^K}) (unbound) (unbound)

@quotation

Kill the entire buffer.
@end quotation

@geindex kill-whole-line; Type

@code{kill-whole-line} (@code{^U}) (unbound) (unbound)

@quotation

Kill the current line.
@end quotation

@geindex vi-match-bracket; Type

@code{vi-match-bracket} (@code{^X^B}) (@code{%}) (unbound)

@quotation

Move to the bracket character (one of @code{@{@}}, @code{()} or @code{[]}) that
matches the one under the cursor.
If the cursor is not on a bracket character, move forward without going
past the end of the line to find one, and then go to the matching bracket.
@end quotation

@geindex vi-open-line-above; Type

@code{vi-open-line-above} (unbound) (@code{O}) (unbound)

@quotation

Open a line above the cursor and enter insert mode.
@end quotation

@geindex vi-open-line-below; Type

@code{vi-open-line-below} (unbound) (@code{o}) (unbound)

@quotation

Open a line below the cursor and enter insert mode.
@end quotation

@geindex vi-oper-swap-case; Type

@code{vi-oper-swap-case} (unbound) (@code{g~}) (unbound)

@quotation

Read a movement command from the keyboard, and swap
the case of all characters
from the cursor position to the endpoint of the movement.
If the movement command is @code{vi-oper-swap-case},
swap the case of all characters on the current line.
@end quotation

@geindex overwrite-mode; Type

@code{overwrite-mode} (@code{^X^O}) (unbound) (unbound)

@quotation

Toggle between overwrite mode and insert mode.
@end quotation

@geindex vi-put-before; Type

@code{vi-put-before} (unbound) (@code{P}) (unbound)

@quotation

Insert the contents of the kill buffer before the cursor.
If the kill buffer contains a sequence of lines (as opposed to characters),
paste it above the current line.
@end quotation

@geindex vi-put-after; Type

@code{vi-put-after} (unbound) (@code{p}) (unbound)

@quotation

Insert the contents of the kill buffer after the cursor.
If the kill buffer contains a sequence of lines (as opposed to characters),
paste it below the current line.
@end quotation

@geindex put-replace-selection; Type

@code{put-replace-selection} (unbound) (unbound) (unbound)

@quotation

Replace the contents of the current region or selection with the
contents of the kill buffer. If the kill buffer contains a sequence of
lines (as opposed to characters), the current line will be split by the
pasted lines.
@end quotation

@geindex quoted-insert; Type

@code{quoted-insert} (@code{^V}) (unbound) (unbound)

@quotation

Insert the next character typed into the buffer literally.
An interrupt character will not be inserted.
@end quotation

@geindex vi-quoted-insert; Type

@code{vi-quoted-insert} (unbound) (unbound) (@code{^Q ^V})

@quotation

Display a @code{^} at the cursor position, and
insert the next character typed into the buffer literally.
An interrupt character will not be inserted.
@end quotation

@geindex quote-line; Type

@code{quote-line} (@code{ESC-'}) (unbound) (unbound)

@quotation

Quote the current line; that is, put a >>`@w{`}<<@code{' character at the
beginning and the end, and convert all `@w{`}}’ characters
to @code{\'@w{'}}’.
@end quotation

@geindex quote-region; Type

@code{quote-region} (@code{ESC-"}) (unbound) (unbound)

@quotation

Quote the region from the cursor to the mark.
@end quotation

@geindex vi-replace; Type

@code{vi-replace} (unbound) (@code{R}) (unbound)

@quotation

Enter overwrite mode.
@end quotation

@geindex vi-repeat-change; Type

@code{vi-repeat-change} (unbound) (@code{.}) (unbound)

@quotation

Repeat the last vi mode text modification.
If a count was used with the modification, it is remembered.
If a count is given to this command, it overrides the remembered count,
and is remembered for future uses of this command.
The cut buffer specification is similarly remembered.
@end quotation

@geindex vi-replace-chars; Type

@code{vi-replace-chars} (unbound) (@code{r}) (unbound)

@quotation

Replace the character under the cursor with a character
read from the keyboard.
@end quotation

@geindex self-insert; Type

@code{self-insert} (printable characters) (unbound) (printable characters and some control characters)

@quotation

Insert a character into the buffer at the cursor position.
@end quotation

@geindex self-insert-unmeta; Type

@code{self-insert-unmeta} (@code{ESC-^I ESC-^J ESC-^M}) (unbound) (unbound)

@quotation

Insert a character into the buffer after stripping the meta bit
and converting ^M to ^J.
@end quotation

@geindex vi-substitute; Type

@code{vi-substitute} (unbound) (@code{s}) (unbound)

@quotation

Substitute the next character(s).
@end quotation

@geindex vi-swap-case; Type

@code{vi-swap-case} (unbound) (@code{~}) (unbound)

@quotation

Swap the case of the character under the cursor and move past it.
@end quotation

@geindex transpose-chars; Type

@code{transpose-chars} (@code{^T}) (unbound) (unbound)

@quotation

Exchange the two characters to the left of the
cursor if at end of line, else exchange the
character under the cursor with the character
to the left.
@end quotation

@geindex transpose-words; Type

@code{transpose-words} (@code{ESC-T ESC-t}) (unbound) (unbound)

@quotation

Exchange the current word with the one before it.

With a positive numeric argument `N', the word around the cursor, or
following it if the cursor is between words, is transposed with the
preceding `N' words.  The cursor is put at the end of the resulting
group of words.

With a negative numeric argument `-N', the effect is the same as using
a positive argument `N' except that the original cursor position is
retained, regardless of how the words are rearranged.
@end quotation

@geindex vi-unindent; Type

@code{vi-unindent} (unbound) (@code{<}) (unbound)

@quotation

Unindent a number of lines.
@end quotation

@geindex vi-up-case; Type

@code{vi-up-case} (unbound) (@code{gU}) (unbound)

@quotation

Read a movement command from the keyboard, and convert all characters
from the cursor position to the endpoint of the movement to lowercase.
If the movement command is @code{vi-up-case}, swap the case of all
characters on the current line.
@end quotation

@geindex up-case-word; Type

@code{up-case-word} (@code{ESC-U ESC-u}) (unbound) (unbound)

@quotation

Convert the current word to all caps and move past it.
@end quotation

@geindex yank; Type

@code{yank} (@code{^Y}) (unbound) (unbound)

@quotation

Insert the contents of the kill buffer at the cursor position.
@end quotation

@geindex yank-pop; Type

@code{yank-pop} (@code{ESC-y}) (unbound) (unbound)

@quotation

Remove the text just yanked, rotate the kill-ring (the history of
previously killed text) and yank the new top.  Only works following
@code{yank}, @code{vi-put-before}, @code{vi-put-after} or @code{yank-pop}.
@end quotation

@geindex vi-yank; Type

@code{vi-yank} (unbound) (@code{y}) (unbound)

@quotation

Read a movement command from the keyboard, and copy the region
from the cursor position to the endpoint of the movement
into the kill buffer.
If the command is @code{vi-yank}, copy the current line.
@end quotation

@geindex vi-yank-whole-line; Type

@code{vi-yank-whole-line} (unbound) (@code{Y}) (unbound)

@quotation

Copy the current line into the kill buffer.
@end quotation

@geindex vi-yank-eol; Type

@code{vi-yank-eol}

@quotation

Copy the region from the cursor position to the end of the line
into the kill buffer.
Arguably, this is what Y should do in vi, but it isn’t what it actually does.
@end quotation

@c historic nodename: Arguments

@node Arguments,Completion<3>,Modifying Text,Standard Widgets
@anchor{Zsh/zle arguments}@anchor{d3}
@subsection Arguments


@geindex digit-argument; Type

@code{digit-argument} (@code{ESC-0..ESC-9}) (@code{1-9}) (unbound)

@quotation

Start a new numeric argument, or add to the current one.
See also @code{vi-digit-or-beginning-of-line}.  This only works if bound to a
key sequence ending in a decimal digit.

Inside a widget function, a call to this function treats the last key of
the key sequence which called the widget as the digit.
@end quotation

@geindex neg-argument; Type

@code{neg-argument} (@code{ESC--}) (unbound) (unbound)

@quotation

Changes the sign of the following argument.
@end quotation

@geindex universal-argument; Type

@code{universal-argument}

@quotation

Multiply the argument of the next command by 4.  Alternatively, if
this command is followed by an integer (positive or negative), use
that as the argument for the next command.  Thus digits cannot be
repeated using this command.  For example, if this command occurs
twice, followed immediately by @code{forward-char}, move forward sixteen
spaces; if instead it is followed by @code{-2}, then @code{forward-char},
move backward two spaces.

Inside a widget function, if passed an argument, i.e. @code{zle
universal-argument} @var{num}, the numeric argument will be set to
@var{num}; this is equivalent to @code{NUMERIC=}@var{num}.
@end quotation

@geindex argument-base; Type

@code{argument-base}

@quotation

Use the existing numeric argument as a numeric base, which must be in the
range 2 to 36 inclusive.  Subsequent use of @code{digit-argument} and
@code{universal-argument} will input a new numeric argument in the given base.
The usual hexadecimal convention is used: the letter @code{a} or @code{A}
corresponds to 10, and so on.  Arguments in bases requiring digits from 10
upwards are more conveniently input with @code{universal-argument}, since
@code{ESC-a} etc. are not usually bound to @code{digit-argument}.

The function can be used with a command argument inside a user-defined
widget.  The following code sets the base to 16 and lets the user input a
hexadecimal argument until a key out of the digit range is typed:

@example
 zle argument-base 16
 zle universal-argument
@end example
@end quotation

@c historic nodename: Completion

@node Completion<3>,Miscellaneous,Arguments,Standard Widgets
@anchor{Zsh/zle completion}@anchor{e0}
@subsection Completion


@geindex accept-and-menu-complete; Type

@code{accept-and-menu-complete}

@quotation

In a menu completion, insert the current completion into the buffer,
and advance to the next possible completion.
@end quotation

@geindex complete-word; Type

@code{complete-word}

@quotation

Attempt completion on the current word.
@end quotation

@geindex delete-char-or-list; Type

@code{delete-char-or-list} (@code{^D}) (unbound) (unbound)

@quotation

Delete the character under the cursor.  If the cursor
is at the end of the line, list possible completions for the
current word.
@end quotation

@geindex expand-cmd-path; Type

@code{expand-cmd-path}

@quotation

Expand the current command to its full pathname.
@end quotation

@geindex expand-or-complete; Type

@code{expand-or-complete} (@code{TAB}) (unbound) (@code{TAB})

@quotation

Attempt shell expansion on the current word.
If that fails,
attempt completion.
@end quotation

@geindex expand-or-complete-prefix; Type

@code{expand-or-complete-prefix}

@quotation

Attempt shell expansion on the current word up to cursor.
@end quotation

@geindex expand-history; Type

@code{expand-history} (@code{ESC-space ESC-!}) (unbound) (unbound)

@quotation

Perform history expansion on the edit buffer.
@end quotation

@geindex expand-word; Type

@code{expand-word} (@code{^X*}) (unbound) (unbound)

@quotation

Attempt shell expansion on the current word.
@end quotation

@geindex list-choices; Type

@code{list-choices} (@code{ESC-^D}) (@code{^D =}) (@code{^D})

@quotation

List possible completions for the current word.
@end quotation

@geindex list-expand; Type

@code{list-expand} (@code{^Xg ^XG}) (@code{^G}) (@code{^G})

@quotation

List the expansion of the current word.
@end quotation

@geindex magic-space; Type

@code{magic-space}

@quotation

Perform history expansion and insert a space into the
buffer.  This is intended to be bound to space.
@end quotation

@geindex menu-complete; Type

@geindex MENU_COMPLETE@comma{} use of; Program

@code{menu-complete}

@quotation

Like @code{complete-word}, except that menu completion is used.
See the @code{MENU_COMPLETE} option.
@end quotation

@geindex menu-expand-or-complete; Type

@code{menu-expand-or-complete}

@quotation

Like @code{expand-or-complete}, except that menu completion is used.
@end quotation

@geindex reverse-menu-complete; Type

@code{reverse-menu-complete}

@quotation

Perform menu completion, like @code{menu-complete}, except that if
a menu completion is already in progress, move to the `previous'
completion rather than the next.
@end quotation

@geindex end-of-list; Type

@code{end-of-list}

@quotation

When a previous completion displayed a list below the prompt, this
widget can be used to move the prompt below the list.
@end quotation

@c historic nodename: Miscellaneous

@node Miscellaneous,Text Objects,Completion<3>,Standard Widgets
@anchor{Zsh/zle miscellaneous}@anchor{d6}
@subsection Miscellaneous


@geindex accept-and-hold; Type

@code{accept-and-hold} (@code{ESC-A ESC-a}) (unbound) (unbound)

@quotation

Push the contents of the buffer on the buffer stack
and execute it.
@end quotation

@geindex accept-and-infer-next-history; Type

@code{accept-and-infer-next-history}

@quotation

Execute the contents of the buffer.
Then search the history list for a line matching the current one
and push the event following onto the buffer stack.
@end quotation

@geindex accept-line; Type

@code{accept-line} (@code{^J ^M}) (@code{^J ^M}) (@code{^J ^M})

@quotation

Finish editing the buffer.  Normally this causes the buffer to be
executed as a shell command.
@end quotation

@geindex accept-line-and-down-history; Type

@code{accept-line-and-down-history} (@code{^O}) (unbound) (unbound)

@quotation

Execute the current line, and push the next history
event on the buffer stack.
@end quotation

@geindex auto-suffix-remove; Type

@code{auto-suffix-remove}

@quotation

If the previous action added a suffix (space, slash, etc.) to the word on
the command line, remove it.  Otherwise do nothing.  Removing the suffix
ends any active menu completion or menu selection.

This widget is intended to be called from user-defined widgets to enforce
a desired suffix-removal behavior.
@end quotation

@geindex auto-suffix-retain; Type

@code{auto-suffix-retain}

@quotation

If the previous action added a suffix (space, slash, etc.) to the word on
the command line, force it to be preserved.  Otherwise do nothing.
Retaining the suffix ends any active menu completion or menu selection.

This widget is intended to be called from user-defined widgets to enforce
a desired suffix-preservation behavior.
@end quotation

@geindex beep; Type

@code{beep}

@quotation

Beep, unless the @code{BEEP} option is unset.
@end quotation

@geindex bracketed-paste; Type

@code{bracketed-paste} (@code{^[[200~}) (@code{^[[200~}) (@code{^[[200~})

@quotation

This widget is invoked when text is pasted to the terminal emulator. It
is not intended to be bound to actual keys but instead to the special
sequence generated by the terminal emulator when text is pasted.

When invoked interactively, the pasted text is inserted to the buffer
and placed in the cutbuffer.
If a numeric argument is given, shell quoting will be applied to the
pasted text before it is inserted.

When a named buffer is specified with @code{vi-set-buffer} (@code{"x}),
the pasted text is stored in that named buffer but not inserted.

When called from a widget function as @code{`bracketed-paste} @var{name}`, the
pasted text is assigned to the variable @var{name} and no other processing is
done.

See also the @code{zle_bracketed_paste} parameter.
@end quotation

@geindex vi-cmd-mode; Type

@code{vi-cmd-mode} (@code{^X^V}) (unbound) (^[)

@quotation

Enter command mode; that is, select the @code{vicmd} keymap.
Yes, this is bound by default in emacs mode.
@end quotation

@geindex vi-caps-lock-panic; Type

@code{vi-caps-lock-panic}

@quotation

Hang until any lowercase key is pressed.
This is for vi users without the mental capacity to keep
track of their caps lock key (like the author).
@end quotation

@geindex clear-screen; Type

@code{clear-screen} (@code{^L ESC-^L}) (@code{^L}) (@code{^L})

@quotation

Clear the screen and redraw the prompt.
@end quotation

@geindex deactivate-region; Type

@code{deactivate-region}

@quotation

Make the current region inactive. This disables vim-style visual
selection mode if it is active.
@end quotation

@geindex describe-key-briefly; Type

@code{describe-key-briefly}

@quotation

Reads a key sequence, then prints the function bound to that sequence.
@end quotation

@geindex exchange-point-and-mark; Type

@code{exchange-point-and-mark} (@code{^X^X}) (unbound) (unbound)

@quotation

Exchange the cursor position (point) with the position of the mark.
Unless a negative numeric argument is given, the region between
point and mark is activated so that it can be highlighted.
If a zero numeric argument is given, the region is activated but
point and mark are not swapped.
@end quotation

@geindex execute-named-cmd; Type

@code{execute-named-cmd} (@code{ESC-x}) (:) (unbound)

@quotation

Read the name of an editor command and execute it.  Aliasing this
widget with @code{zle -A} or replacing it with @code{zle -N} has no
effect when interpreting key bindings, but @code{zle execute-named-cmd}
will invoke such an alias or replacement.

A restricted set of editing functions is available in the
mini-buffer.  Keys are looked up in the special
@code{command} keymap, and if not found there in the main keymap.
An interrupt signal, as defined by the stty setting, will
abort the function.  Note that the following always
perform the same task within the @code{executed-named-cmd} environment and
cannot be replaced by user defined widgets, nor can the set of functions
be extended.  The allowed functions are:
@code{backward-delete-char},
@code{vi-backward-delete-char},
@code{clear-screen},
@code{redisplay},
@code{quoted-insert},
@code{vi-quoted-insert},
@code{backward-kill-word},
@code{vi-backward-kill-word},
@code{kill-whole-line},
@code{vi-kill-line},
@code{backward-kill-line},
@code{list-choices},
@code{delete-char-or-list},
@code{complete-word},
@code{accept-line},
@code{expand-or-complete} and
@code{expand-or-complete-prefix}.

@code{kill-region} kills the last word,
and vi-cmd-mode is treated the same as accept-line.
The space and tab characters, if not bound to one of
these functions, will complete the name and then list the
possibilities if the @code{AUTO_LIST} option is set.
Any other character that is not bound to @code{self-insert} or
@code{self-insert-unmeta} will beep and be ignored.
The bindings of the current insert mode will be used.

Currently this command may not be redefined or called by name.
@end quotation

@geindex execute-last-named-cmd; Type

@code{execute-last-named-cmd} (@code{ESC-z}) (unbound) (unbound)

@quotation

Redo the last function executed with @code{execute-named-cmd}.

Like @code{execute-named-cmd}, this command may not be redefined,
but it may be called by name.
@end quotation

@geindex get-line; Type

@code{get-line} (@code{ESC-G ESC-g}) (unbound) (unbound)

@quotation

Pop the top line off the buffer stack and insert it at the
cursor position.
@end quotation

@geindex pound-insert; Type

@code{pound-insert} (unbound) (#) (unbound)

@quotation

If there is no # character at the beginning of the buffer,
add one to the beginning of each line.
If there is one, remove a # from each line that has one.
In either case, accept the current line.
The @code{INTERACTIVE_COMMENTS} option must be set
for this to have any usefulness.
@end quotation

@geindex vi-pound-insert; Type

@code{vi-pound-insert}

@quotation

If there is no # character at the beginning of the current line,
add one.  If there is one, remove it.
The @code{INTERACTIVE_COMMENTS} option must be set
for this to have any usefulness.
@end quotation

@geindex push-input; Type

@code{push-input}

@quotation

Push the entire current multiline construct onto the buffer stack and
return to the top-level (@code{PS1}) prompt.
If the current parser construct is only a single line, this is exactly
like @code{push-line}.
Next time the editor starts up or is popped with @code{get-line}, the
construct will be popped off the top of the buffer stack and loaded
into the editing buffer.
@end quotation

@geindex push-line; Type

@code{push-line} (@code{^Q ESC-Q ESC-q}) (unbound) (unbound)

@quotation

Push the current buffer onto the buffer stack and clear
the buffer.
Next time the editor starts up, the buffer will be popped
off the top of the buffer stack and loaded into the editing
buffer.
@end quotation

@geindex push-line-or-edit; Type

@code{push-line-or-edit}

@quotation

At the top-level (@code{PS1}) prompt, equivalent to @code{push-line}.
At a secondary (@code{PS2}) prompt, move the entire current multiline
construct into the editor buffer.
The latter is equivalent to @code{push-input} followed by @code{get-line}.
@end quotation

@geindex read-command; Type

@code{read-command}

@quotation

Only useful from a user-defined widget.  A keystroke is read just as in
normal operation, but instead of the command being executed the name
of the command that would be executed is stored in the shell parameter
@code{REPLY}.  This can be used as the argument of a future @code{zle}
command.  If the key sequence is not bound, status 1 is returned;
typically, however, @code{REPLY} is set to @code{undefined-key} to indicate
a useless key sequence.
@end quotation

@geindex recursive-edit; Type

@code{recursive-edit}

@quotation

Only useful from a user-defined widget.  At this point in the function,
the editor regains control until one of the standard widgets which would
normally cause zle to exit (typically an @code{accept-line} caused by
hitting the return key) is executed.  Instead, control returns to the
user-defined widget.  The status returned is non-zero if the return was
caused by an error, but the function still continues executing and hence
may tidy up.  This makes it safe for the user-defined widget to alter
the command line or key bindings temporarily.

The following widget, @code{caps-lock}, serves as an example.

@example
 self-insert-ucase() @{
   LBUFFER+=$@{(U)KEYS[-1]@}
 @}

 integer stat

 zle -N self-insert self-insert-ucase
 zle -A caps-lock save-caps-lock
 zle -A accept-line caps-lock

 zle recursive-edit
 stat=$?

 zle -A .self-insert self-insert
 zle -A save-caps-lock caps-lock
 zle -D save-caps-lock

 (( stat )) && zle send-break

 return $stat
@end example

This causes typed letters to be inserted capitalised until either
@code{accept-line} (i.e. typically the return key) is typed or the
@code{caps-lock} widget is invoked again; the later is handled by saving
the old definition of @code{caps-lock} as @code{save-caps-lock} and then
rebinding it to invoke @code{accept-line}.  Note that an error from the
recursive edit is detected as a non-zero return status and propagated by
using the @code{send-break} widget.
@end quotation

@geindex redisplay; Type

@code{redisplay} (unbound) (@code{^R}) (@code{^R})

@quotation

Redisplays the edit buffer.
@end quotation

@geindex reset-prompt; Type

@code{reset-prompt} (unbound) (unbound) (unbound)

@quotation

Force the prompts on both the left and right of the screen to be
re-expanded, then redisplay the edit buffer.  This
reflects changes both to the prompt variables themselves and changes
in the expansion of the values (for example, changes in time or
directory, or changes to the value of variables referred to by the
prompt).

Otherwise, the prompt is only expanded each time zle starts, and
when the display has been interrupted by output from another part of the
shell (such as a job notification) which causes the command line to be
reprinted.

@code{reset-prompt} doesn’t alter the special parameter @code{LASTWIDGET}.
@end quotation

@geindex send-break; Type

@code{send-break} (@code{^G ESC-^G}) (unbound) (unbound)

@quotation

Abort the current editor function, e.g. @code{execute-named-command}, or the
editor itself, e.g. if you are in @code{vared}. Otherwise abort the parsing of
the current line; in this case the aborted line is available in the shell
variable @code{ZLE_LINE_ABORTED}.  If the editor is aborted from within
@code{vared}, the variable @code{ZLE_VARED_ABORTED} is set.
@end quotation

@geindex run-help; Type

@code{run-help} (@code{ESC-H ESC-h}) (unbound) (unbound)

@quotation

Push the buffer onto the buffer stack, and execute the
command @code{run-help} @var{cmd}, where @var{cmd} is the current
command.  @code{run-help} is normally aliased to @code{man}.
@end quotation

@geindex vi-set-buffer; Type

@code{vi-set-buffer} (unbound) (”) (unbound)

@quotation

Specify a buffer to be used in the following command.
There are 39 buffers that can be specified:
the 26 `named’ buffers @code{"a} to @code{"z}, the `yank’ buffer @code{"0},
the nine `queued’ buffers @code{"1} to @code{"9}, the `black hole’ buffer
@code{"_} and the system selection “* and clipboard “+.
The named buffers can also be specified as @code{"A} to @code{"Z}.

When a buffer is specified for a cut, change or yank command, the text
concerned replaces the previous contents of the specified buffer. If
a named buffer is specified using a capital, the newly cut text is
appended to the buffer instead of overwriting it. When using the @code{"_}
buffer, nothing happens. This can be useful for deleting text without
affecting any buffers.

Accessing and updating the system clipboard relies on specific support from
the terminal.

If no buffer is specified for a cut or change command, @code{"1} is used, and
the contents of @code{"1} to @code{"8} are each shifted along one buffer;
the contents of @code{"9} is lost. If no buffer is specified for a yank
command, @code{"0} is used. Finally, a paste command without a specified
buffer will paste the text from the most recent command regardless of any
buffer that might have been used with that command.

When called from a widget function by the @code{zle} command, the buffer
can optionally be specified with an argument. For example,

@example
 zle vi-set-buffer A
@end example
@end quotation

@geindex vi-set-mark; Type

@code{vi-set-mark} (unbound) (@code{m}) (unbound)

@quotation

Set the specified mark at the cursor position.
@end quotation

@geindex set-mark-command; Type

@code{set-mark-command} (^@@) (unbound) (unbound)

@quotation

Set the mark at the cursor position.  If called with a negative
numeric argument, do not set the mark but deactivate the region so that
it is no longer highlighted (it is still usable for other purposes).
Otherwise the region is marked as active.
@end quotation

@geindex spell-word; Type

@code{spell-word} (@code{ESC-$ ESC-S ESC-s}) (unbound) (unbound)

@quotation

Attempt spelling correction on the current word.
@end quotation

@geindex split-undo; Type

@code{split-undo}

@quotation

Breaks the undo sequence at the current change.  This is useful in vi mode as
changes made in insert mode are coalesced on entering command mode.  Similarly,
@code{undo} will normally revert as one all the changes made by a user-defined
widget.
@end quotation

@geindex undefined-key; Type

@code{undefined-key}

@quotation

This command is executed when a key sequence that is not bound to any
command is typed.  By default it beeps.
@end quotation

@geindex undo; Type

@code{undo} (@code{^_ ^Xu ^X^U}) (@code{u}) (unbound)

@quotation

Incrementally undo the last text modification.  When called from a
user-defined widget, takes an optional argument indicating a previous state
of the undo history as returned by the @code{UNDO_CHANGE_NO} variable;
modifications are undone until that state is reached, subject to
any limit imposed by the @code{UNDO_LIMIT_NO} variable.

Note that when invoked from vi command mode, the full prior change made in
insert mode is reverted, the changes having been merged when command mode was
selected.
@end quotation

@geindex redo; Type

@code{redo} (unbound) (@code{^R}) (unbound)

@quotation

Incrementally redo undone text modifications.
@end quotation

@geindex vi-undo-change; Type

@code{vi-undo-change} (unbound) (unbound) (unbound)

@quotation

Undo the last text modification.
If repeated, redo the modification.
@end quotation

@geindex visual-mode; Type

@code{visual-mode} (unbound) (@code{v}) (unbound)

@quotation

Toggle vim-style visual selection mode. If line-wise visual mode is
currently enabled then it is changed to being character-wise. If used
following an operator, it forces the subsequent movement command to be
treated as a character-wise movement.
@end quotation

@geindex visual-line-mode; Type

@code{visual-line-mode} (unbound) (@code{V}) (unbound)

@quotation

Toggle vim-style line-wise visual selection mode. If character-wise
visual mode is currently enabled then it is changed to being line-wise. If used
following an operator, it forces the subsequent movement command to be
treated as a line-wise movement.
@end quotation

@geindex what-cursor-position; Type

@code{what-cursor-position} (@code{^X=}) (@code{ga}) (unbound)

@quotation

Print the character under the cursor, its code as an octal, decimal and
hexadecimal number, the current cursor position within the buffer and the
column of the cursor in the current line.
@end quotation

@geindex where-is; Type

@code{where-is}

@quotation

Read the name of an editor command and print the listing of key
sequences that invoke the specified command.
A restricted set of editing functions is available in the
mini-buffer.  Keys are looked up in the special
@code{command} keymap, and if not found there in the main keymap.
@end quotation

@geindex which-command; Type

@code{which-command} (@code{ESC-?}) (unbound) (unbound)

@quotation

Push the buffer onto the buffer stack, and execute the
command @code{which-command} @var{cmd}, where @var{cmd} is the current
command.  @code{which-command} is normally aliased to @code{whence}.
@end quotation

@geindex vi-digit-or-beginning-of-line; Type

@code{vi-digit-or-beginning-of-line} (unbound) (@code{0}) (unbound)

@quotation

If the last command executed was a digit as part of an argument,
continue the argument.  Otherwise, execute vi-beginning-of-line.
@end quotation

@c historic nodename: Text Objects

@node Text Objects,,Miscellaneous,Standard Widgets
@anchor{Zsh/zle text-objects}@anchor{e1}
@subsection Text Objects


@geindex text objects; Command

Text objects are commands that can be used to select a block of text
according to some criteria. They are a feature of the vim text editor
and so are primarily intended for use with vi operators or from visual
selection mode. However, they can also be used from vi-insert or emacs
mode. Key bindings listed below apply to the @code{viopp} and @code{visual}
keymaps.

@geindex select-a-blank-word; Type

@code{select-a-blank-word} (@code{aW})

@quotation

Select a word including adjacent blanks, where a word is defined as a
series of non-blank characters. With a numeric argument, multiple words
will be selected.
@end quotation

@geindex select-a-shell-word; Type

@code{select-a-shell-word} (@code{aa})

@quotation

Select the current command argument applying the normal rules for
quoting.
@end quotation

@geindex select-a-word; Type

@code{select-a-word} (@code{aw})

@quotation

Select a word including adjacent blanks, using the normal vi-style word
definition. With a numeric argument, multiple words will be selected.
@end quotation

@geindex select-in-blank-word; Type

@code{select-in-blank-word} (@code{iW})

@quotation

Select a word, where a word is defined as a series of non-blank
characters. With a numeric argument, multiple words will be selected.
@end quotation

@geindex select-in-shell-word; Type

@code{select-in-shell-word} (@code{ia})

@quotation

Select the current command argument applying the normal rules for
quoting. If the argument begins and ends with matching quote characters,
these are not included in the selection.
@end quotation

@geindex select-in-word; Type

@code{select-in-word} (@code{iw})

@quotation

Select a word, using the normal vi-style word definition. With a numeric
argument, multiple words will be selected.
@end quotation

@c historic nodename: Terminal Extensions

@node Terminal Extensions,Character Highlighting,Standard Widgets,Zsh Line Editor
@anchor{Zsh/zle terminal-extensions}@anchor{98}
@section Terminal Extensions


@geindex .term.extensions@comma{} setting; Variable

Modern terminals often carry functionality that is not covered by the
`terminfo’ library.  For these cases, the availability of a feature can be
asserted by including it in the array parameter @code{.term.extensions}.
Similarly the absence of a feature can be indicated via it’s inclusion with a
- prefix.  Where a feature isn’t listed, the status of terminal support
is unknown and defaults apply as to whether ZLE will use the feature.  This
is often harmless as terminals ignore extra instructions they don’t recognise.
Even if your terminal does support a particular extension, you may choose to
list it with an initial - as a way to disable the associated feature.
Many extensions are named with common prefixes to group related extensions.
This allows a whole class of extensions to be disabled with a single entry such
as by adding @code{-cursor} to disable cursor shape and color changing.

When ZLE starts, it will add entries for features that were auto-detected.  This
auto-detection uses extensions itself, all named with a @code{query} prefix.  As
this happens when ZLE starts, disabling them needs to be done early in the
startup files.  A value of @code{-query} will disable all terminal queries on
startup, including those that query terminal properties such as colors rather
than detecting features.  Populating the array with the status of auto-detected
features will mean that associated terminal queries are not needed and will be
skipped.

Extensions can be any of the following, where the marks `<D>’ and `<E>’
indicate whether each one is disabled or enabled by default:

@code{bracketed-paste} <E>

@quotation

Many terminal emulators have a feature that allows applications to identify
when text is pasted into the terminal rather than being typed normally.  For
ZLE, this means that special characters such as tabs and newlines can be
inserted instead of invoking editor commands. Furthermore, pasted text forms a
single undo event and if the region is active, pasted text will replace the
region.
@end quotation

@code{cursor-color} <E>

@quotation

Support for changing the color of the cursor.
@end quotation

@code{cursor-shape} <E>

@quotation

Support for changing the shape of the cursor.
@end quotation

@code{integration-output} <E>

@quotation

This provides the terminal with semantic information regarding where the output
from commands start and finish. Some terminals use this information to make it
easy to select just the output from a single command.
@end quotation

@code{integration-prompt} <E>

@quotation

This informs the terminal when the shell displays a prompt. This enables a
variety of terminal features such as displaying markers, allowing you to jump
to previous commands in the scroll-back buffer and ensuring that right prompts
are handled correctly when the window is resized. The end of the prompt also
provides the terminal with a marker for the start of user input.
@end quotation

@code{integration-pwd} <E>

@quotation

This advises the terminal of the shell’s current directory which allows it
to create new windows with the same current working directory.
@end quotation

@code{query-bg} <E>

@quotation

Query the terminal background color which is used for @code{.term.bg} and
@code{.term.mode}.
@end quotation

@code{query-cursorcolor} <E>

@quotation

Query the cursor color. This facilitates restoring the cursor to its original
color if it has been configured via @code{zle_cursorform}. The color is also
assigned to @code{.term.cursor}.
@end quotation

@code{query-fg} <E>

@quotation

Query the terminal foreground color which is used for @code{.term.fg}.
@end quotation

@code{query-id} <E>

@quotation

Query the terminal identification which is used for @code{.term.id} and
@code{.term.version}.
@end quotation

@code{modkeys-kitty} <D>

@code{query-modkeys-kitty} <D>

@quotation

Support for the kitty keyboard handling protocol which enables reporting of a
wider range of key combinations and resolves problems with ambiguous key
sequences.  Currently there is only support for detecting whether the terminal
supports this feature.
@end quotation

@code{modkeys-xterm} <D>

@quotation

Support for the keyboard handling sequences associated with xterm’s
@code{modifyOtherKeys} X resource. This enables reporting of a wider range of key
combinations and resolves some problems with ambiguous key sequences.
@end quotation

@code{truecolor} <D>

@code{query-truecolor} <E>

@quotation

Support for 24-bit truecolor escape sequences.  Auto-detection also tries
termcap and the @code{COLORTERM} environment variable.
@end quotation

@c historic nodename: Character Highlighting

@node Character Highlighting,Cursor Shape and Color,Terminal Extensions,Zsh Line Editor
@anchor{Zsh/zle character-highlighting}@anchor{60}
@section Character Highlighting


@geindex zle_highlight@comma{} setting; Variable

The line editor has the ability to highlight characters or regions
of the line that have a particular significance.  This is controlled
by the array parameter @code{zle_highlight}, if it has been set by the user.

If the parameter contains the single entry @code{none} all highlighting
is turned off.  Note the parameter is still expected to be an array.

Otherwise each entry of the array should consist of a word indicating a
context for highlighting, then a colon, then a comma-separated list of
the types of highlighting to apply in that context.

The contexts available for highlighting are the following:

@geindex region@comma{} highlighting; Command

@geindex highlighting@comma{} region; Command

@code{default}

@quotation

Any text within the command line not affected by any other highlighting.
Text outside the editable area of the command line is not affected.
@end quotation

@code{isearch}

@quotation

When one of the incremental history search widgets is active, the
area of the command line matched by the search string or pattern.
@end quotation

@code{region}

@quotation

The currently selected text. In emacs terminology, this is referred to as
the region and is bounded by the cursor (point) and the mark. The region
is only highlighted if it is active, which is the case after the mark
is modified with @code{set-mark-command} or @code{exchange-point-and-mark}.
Note that whether or not the region is active has no effect on its
use within emacs style widgets, it simply determines whether it is
highlighted. In vi mode, the region corresponds to selected text in
visual mode.
@end quotation

@geindex special characters@comma{} highlighting; Command

@geindex highlighting@comma{} special characters; Command

@code{special}

@quotation

Individual characters that have no direct printable
representation but are shown in a special manner by the line editor.
These characters are described below.
@end quotation

@geindex completion removable suffix@comma{} highlighting; Command

@geindex suffix@comma{} highlighting removable@comma{} in completion; Command

@geindex removable suffix@comma{} highlighting in completion; Command

@code{suffix}

@quotation

This context is used in completion for characters that are
marked as suffixes that will be removed if the completion ends
at that point, the most obvious example being a slash (/) after
a directory name.  Note that suffix removal is configurable; the
circumstances under which the suffix will be removed may differ
for different completions.
@end quotation

@code{paste}

@quotation

Following a command to paste text, the characters that were inserted.
@end quotation

@code{ellipsis}

@quotation

Markers used to indicate where the text doesn’t fit within the terminal.
@end quotation

When @code{region_highlight} is set, the contexts that describe a region –
@code{isearch}, @code{region}, @code{suffix}, and @code{paste} –
are applied first, then @code{region_highlight} is applied, then the remaining
@code{zle_highlight} contexts are applied.  If a particular character is
affected by multiple specifications, the last specification wins.

@code{zle_highlight} may contain additional fields for controlling how
terminal sequences to change colours are output.  Each of the following is
followed by a colon and a string in the same form as for key bindings.
This will not be necessary for the vast majority of terminals as the
defaults shown in parentheses are widely used.

@geindex escape sequences@comma{} terminal@comma{} for highlighting; Command

@geindex terminal escape sequences for highlighting; Command

@code{fg_start_code} (@code{\e[3})

@quotation

The start of the escape sequence for the foreground colour.
This is followed by one to three ASCII digits representing the colour.
Only used for palette colors, i.e. not 24-bit colors specified via a
color triplet.
@end quotation

@code{fg_default_code} (@code{9})

@quotation

The number to use instead of the colour to reset the default foreground
colour.
@end quotation

@code{fg_end_code} (@code{m})

@quotation

The end of the escape sequence for the foreground colour.
@end quotation

@code{bg_start_code} (@code{\e[4})

@quotation

The start of the escape sequence for the background colour.
See @code{fg_start_code} above.
@end quotation

@code{bg_default_code} (@code{9})

@quotation

The number to use instead of the colour to reset the default
background colour.
@end quotation

@code{bg_end_code} (@code{m})

@quotation

The end of the escape sequence for the background colour.
@end quotation

The available types of highlighting are the following.  Note that
not all types of highlighting are available on all terminals:

@code{none}

@quotation

No additional highlighting is applied to the given context.  It is not
useful for this to appear with other types of highlighting; it is used to
override a default.  Any inherited highlighting is retained so for example,
with @code{region:none}, highlighting associated with @code{default} is still used
for the region.
@end quotation

@code{reset}

@quotation

The terminal’s default highlighting is applied to the given context.
This can be useful as a way to clear all inherited highlighting, so
may be used before naming other types of highlighting.
@end quotation

@code{fg=}@var{colour}

@quotation

The foreground colour should be set to @var{colour}, a decimal integer,
the name of one of the eight most widely-supported colours or as a
# followed by an RGB triplet in hexadecimal format.

Not all terminals support this and, of those that do, not all provide
facilities to test the support, hence the user should decide based on the
terminal type.  Most terminals support the colours @code{black}, @code{red},
@code{green}, @code{yellow}, @code{blue}, @code{magenta}, @code{cyan} and @code{white},
which can be set by name.  In addition. @code{default} may be used to
set the terminal’s default foreground colour.  Abbreviations are allowed;
@code{b} or @code{bl} selects black.  Some terminals may generate additional
colours if the @code{bold} attribute is also present.

On recent terminals and on systems with an up-to-date terminal database the
number of colours supported may be tested by the command @code{echotc
Co}; if this succeeds, it indicates a limit on the number of colours which
will be enforced by the line editor.  The number of colours is in any case
limited to 256 (i.e. the range 0 to 255).

Some modern terminal emulators have support for 24-bit true colour (16
million colours). In this case, the hex triplet format can be used. This
consists of a # followed by either a three or six digit hexadecimal
number describing the red, green and blue components of the colour. Hex
triplets can also be used with 88 and 256 colour terminals via the
@code{zsh/nearcolor} module (see @code{zshmodules}).

Colour is also known as color.
@end quotation

@code{bg=}@var{colour}

@quotation

The background colour should be set to @var{colour}.
This works similarly to the foreground colour, except the background is
not usually affected by the bold attribute.
@end quotation

@code{bold}

@quotation

The characters in the given context are shown with a bold font weight.
Not all terminals distinguish bold fonts.
@end quotation

@code{faint}

@quotation

The characters in the given context are shown with a faint font weight.
Not all terminals distinguish faint fonts.
@end quotation

@code{standout}

@quotation

The characters in the given context are shown in the terminal’s standout
mode.  The actual effect is specific to the terminal; on many terminals it
is inverse video.  On some such terminals, where the cursor does not blink
it appears with standout mode negated, making it less than clear where
the cursor actually is.  On such terminals one of the other effects
may be preferable for highlighting the region and matched search string.
@end quotation

@code{underline}

@quotation

The characters in the given context are shown underlined.  Some
terminals show the foreground in a different colour instead; in this
case whitespace will not be highlighted.
@end quotation

@code{italic}

@quotation

The characters in the given context are shown in a italic font.
Not all terminals support italic fonts.
@end quotation

@code{hl=}@var{group}

@quotation

Use the specified highlighting group.  The @var{group} is used as a key into
the associative array @code{.zle.hlgroups} to determine the actual highlighting.
@end quotation

@code{layer=}@var{layer}

@quotation

The layer is used to determine precedence when multiple highlighting regions
overlap. The @var{layer} is a decimal integer, with higher numbers taking
precedence over lower numbers. This cannot be used with the @code{default} and
@code{ellipsis} fields of @code{zle_highlight} because they treated as base layers.
With the other fields 30 applies by default for @code{special}, 20 for @code{region}
and @code{isearch} and 15 for @code{paste}. Highlighting defined in
@code{region_highlight} defaults to layer 10 and would take precedence over
highlighting for any fields of @code{zle_highlight} that are assigned to the same
layer.
@end quotation

@code{opacity=}@var{fg}@code{%}[/@var{bg}@code{%}]

@quotation

Instead of replacing colors in higher layers, the colors can be mixed. The
opacity is specified as a percentage where @code{0%} is fully transparent and
@code{100%} represents the default behavior of replacing the underlying colour.
If a single value is specified, it applies to both foreground and background.
@end quotation

In addition, the simple highlighting types can be prefixed with @code{"no"} to
explicitly disable them. This is useful where highlighting is merged with
inherited highlighting from other definitions. Note that @code{nobold} selects a
normal font weight so also has the effect of disabling @code{faint}.

The characters described above as `special’ are as follows.  The
formatting described here is used irrespective of whether the characters
are highlighted:

ASCII control characters

@quotation

Control characters in the ASCII range are shown as
^ followed by the base character.
@end quotation

Unprintable multibyte characters

@quotation

This item applies to control characters not in the ASCII range,
plus other characters as follows.  If the @code{MULTIBYTE} option is in
effect, multibyte characters not in the ASCII character set that are
reported as having zero width are treated as combining characters when the
option @code{COMBINING_CHARS} is on.  If the option is off, or if a character
appears where a combining character is not valid, the character
is treated as unprintable.

Unprintable multibyte characters are shown as a hexadecimal number between
angle brackets.  The number is the code point of the character in the wide
character set; this may or may not be Unicode, depending on the operating
system.
@end quotation

Invalid multibyte characters

@quotation

If the @code{MULTIBYTE} option is in effect, any sequence of one or more
bytes that does not form a valid character in the current character
set is treated as a series of bytes each shown as a special character.
This case can be distinguished from other unprintable characters
as the bytes are represented as two hexadecimal digits between angle
brackets, as distinct from the four or eight digits that are used for
unprintable characters that are nonetheless valid in the current
character set.

Not all systems support this: for it to work, the system’s representation of
wide characters must be code values from the Universal Character Set,
as defined by IS0 10646 (also known as Unicode).
@end quotation

Wrapped double-width characters

@quotation

When a double-width character appears in the final column of a line, it
is instead shown on the next line. The empty space left in the original
position is highlighted as a special character.
@end quotation

If @code{zle_highlight} is not set or no value applies to a particular
context, the defaults applied are equivalent to

@example
 zle_highlight=(region:standout special:standout
 suffix:bold isearch:underline paste:standout)
@end example

i.e. both the region and special characters are shown in standout mode.

Within widgets, arbitrary regions may be highlighted by setting the
special array parameter @code{region_highlight}; see

Zle Widgets


.

@c historic nodename: Cursor Shape and Color

@node Cursor Shape and Color,,Character Highlighting,Zsh Line Editor
@anchor{Zsh/zle cursor-shape-and-color}@anchor{e2}
@section Cursor Shape and Color


@geindex cursor shape; Command

@geindex cursor color; Command

@geindex zle_cursorform@comma{} setting; Variable

Some terminals support the ability to change the shape and color of the cursor.
On such terminals, the line editor will use cursor styles appropriate to
different contexts. This is controlled via the array parameter
@code{zle_cursorform}. To disable all cursor changes, see the @code{.term.extensions}
parameter.

Each element of the array should consist of a word indicating a context
followed by a colon, then a comma-separated list of properties describing the
shape and color to apply to the cursor.

The available contexts follow with the default value shown in
parentheses. Where no default is given, the terminal’s default is applied:

@code{command}

@quotation

Used for vi normal mode.
@end quotation

@code{edit}

@quotation

The default form used in the line editor and for editing text in emacs
mode.
@end quotation

@code{insert} (@code{bar})

@quotation

Used for vi editing mode.
@end quotation

@code{overwrite}

@quotation

Used when editing text in overwrite mode or with the vi replace command.
@end quotation

@code{pending} (@code{underline})

@quotation

Used where the line editor is waiting for a single key press such as the vi
operator pending mode widget.
@end quotation

@code{region}

@quotation

Applied for both @code{regionstart} and @code{regionend} contexts.
@end quotation

@code{regionstart}

@quotation

Used when the region is active and the cursor is positioned at the start of the
region. The region includes the text under the cursor when it is positioned at
the start so it is best to configure the cursor so that it does not obscure
this fact.
@end quotation

@code{regionend}

@quotation

Used when the region is active and the cursor is positioned at the end of the
region. Note that when this is the case, the region does not include the cursor
position.
@end quotation

@code{visual}

@quotation

Used when vi visual mode is active. The visual selection always includes the
cursor position so the same advice as for @code{regionstart} applies.
@end quotation

The available cursor shapes are @code{none}, @code{bar}, @code{block}, @code{underline} and
@code{hidden}. Additionally, you can specify either @code{blink} or @code{steady} to
indicate whether the cursor should flash and specify a color as an RGB triplet
in hexadecimal format with @code{color=}@var{#xxxxxx}. The value @code{none}
applies the terminal’s defaults. Note that on many terminals, this may
differ from the initial cursor state from when the shell started.

@c historic nodename: Completion Widgets

@node Completion Widgets,Completion System,Zsh Line Editor,Top
@anchor{Zsh/compwid doc}@anchor{e3}@anchor{Zsh/compwid completion-widgets}@anchor{e4}
@chapter Completion Widgets


@geindex completion@comma{} widgets; Command

@geindex completion@comma{} programmable; Command

@geindex completion@comma{} controlling; Command

@menu
* Description: Description<4>. 
* Completion Special Parameters:: 
* Completion Builtin Commands:: 
* Completion Condition Codes:: 
* Completion Matching Control:: 
* Completion Widget Example:: 

@end menu

@node Description<4>,Completion Special Parameters,,Completion Widgets
@anchor{Zsh/compwid description}@anchor{e5}
@section Description


The shell’s programmable completion mechanism can be manipulated in two
ways; here the low-level features supporting the newer, function-based
mechanism are defined.  A complete set of shell functions based on these
features is described in


the next chapter, Completion System

,
and users with no interest in adding to that system (or, potentially,
writing their own – see dictionary entry for `hubris’) should skip
the current section.  The older system based on the @code{compctl} builtin
command is described in @code{zshcompctl}.

Completion widgets are defined by the @code{-C} option to the @code{zle}
builtin command provided by the @code{zsh/zle} module (see
@ref{ba,,Zle Builtins}). For example,

@example
 zle -C complete expand-or-complete completer
@end example

defines a widget named @code{complete}.  The second argument is the name
of any of the builtin widgets that handle completions:
@code{complete-word}, @code{expand-or-complete},
@code{expand-or-complete-prefix}, @code{menu-complete},
@code{menu-expand-or-complete}, @code{reverse-menu-complete},
@code{list-choices}, or @code{delete-char-or-list}.  Note that this will still
work even if the widget in question has been re-bound.

When this newly defined widget is bound to a key
using the @code{bindkey} builtin command defined in the @code{zsh/zle} module
(see @ref{ba,,Zle Builtins}),
typing that key will call the shell function @code{completer}. This
function is responsible for generating completion matches using the
builtins described below.  As with other ZLE widgets, the function is
called with its standard input closed.

Once the function returns, the completion code takes over control again
and treats the matches in the same manner as the specified builtin
widget, in this case @code{expand-or-complete}.

@c historic nodename: Completion Special Parameters

@node Completion Special Parameters,Completion Builtin Commands,Description<4>,Completion Widgets
@anchor{Zsh/compwid completion-special-parameters}@anchor{e6}
@section Completion Special Parameters


The parameters @code{ZLE_REMOVE_SUFFIX_CHARS} and @code{ZLE_SPACE_SUFFIX_CHARS}
are used by the completion mechanism, but are not special. See
@ref{11,,Parameters Used by the Shell}.

Inside completion widgets, and any functions called from them, some
parameters have special meaning; outside these functions they are not
special to the shell in any way.  These parameters are used to pass
information between the completion code and the completion widget. Some of
the builtin commands and the condition codes use or change the current
values of these parameters.  Any existing values will be hidden during
execution of completion widgets; except for @code{compstate}, the parameters
are reset on each function exit (including nested function calls from
within the completion widget) to the values they had when the function was
entered.

@geindex CURRENT; Variable

@code{CURRENT}

@quotation

This is the number of the current word, i.e. the word the cursor is
currently on in the @code{words} array.  Note that this value is only
correct if the @code{ksharrays} option is not set.
@end quotation

@geindex IPREFIX; Variable

@code{IPREFIX}

@quotation

Initially this will be set to the empty string.  This parameter functions
like @code{PREFIX}; it contains a string which precedes the one in @code{PREFIX}
and is not considered part of the list of matches.  Typically, a string is
transferred from the beginning of @code{PREFIX} to the end of @code{IPREFIX}, for
example:

@example
 IPREFIX=$@{PREFIX%%\=*@}=
 PREFIX=$@{PREFIX#*=@}
@end example

causes the part of the prefix up to and including the first equal sign not
to be treated as part of a matched string.  This can be done automatically
by the @code{compset} builtin, see below.
@end quotation

@geindex ISUFFIX; Variable

@code{ISUFFIX}

@quotation

As @code{IPREFIX}, but for a suffix that should not be considered part
of the matches; note that the @code{ISUFFIX} string follows the @code{SUFFIX}
string.
@end quotation

@geindex PREFIX; Variable

@code{PREFIX}

@quotation

Initially this will be set to the part of the current word from the
beginning of the word up to the position of the cursor; it may be altered
to give a common prefix for all matches.
@end quotation

@geindex QIPREFIX; Variable

@code{QIPREFIX}

@quotation

This parameter is read-only and contains the quoted string up to the
word being completed. E.g. when completing @code{"foo}, this parameter
contains the double quote. If the @code{-q} option of @code{compset} is used
(see below), and the original string was @code{"foo bar} with the
cursor on the @code{bar}, this parameter contains @code{"foo} .
@end quotation

@geindex QISUFFIX; Variable

@code{QISUFFIX}

@quotation

Like @code{QIPREFIX}, but containing the suffix.
@end quotation

@geindex SUFFIX; Variable

@code{SUFFIX}

@quotation

Initially this will be set to the part of the current word from the
cursor position to the end; it may be altered to give a common suffix for
all matches.  It is most useful when the option @code{COMPLETE_IN_WORD} is
set, as otherwise the whole word on the command line is treated as a
prefix.
@end quotation

@geindex compstate; Variable

@geindex completion widgets@comma{} examining and setting state in; Command

@code{compstate}

@quotation

This is an associative array with various keys and values that the
completion code uses to exchange information with the completion widget.
The keys are:

@geindex all_quotes@comma{} compstate; Variable

@code{all_quotes}

@quotation

The @code{-q} option of the @code{compset} builtin command (see below)
allows a quoted string to be broken into separate words; if the cursor is
on one of those words, that word will be completed, possibly invoking
@code{compset -q} recursively.  With this key it is possible to test the
types of quoted strings which are currently broken into parts in this
fashion.  Its value contains one character for each quoting level.  The
characters are a single quote or a double quote for strings quoted with
these characters, a dollars sign for strings quoted with
@code{$'}@var{…}@code{'} and a backslash for strings not starting with a
quote character.  The first character in the value always corresponds to the
innermost quoting level.
@end quotation

@geindex context@comma{} compstate; Variable

@code{context}

@quotation

This will be set by the completion code to the overall context
in which completion is attempted. Possible values are:

@code{array_value}

@quotation

when completing inside the value of an array parameter assignment; in
this case the @code{words} array contains the words inside the parentheses.
@end quotation

@code{brace_parameter}

@quotation

when completing the name of a parameter in a parameter expansion beginning
with @code{$@{}.  This context will also be set when completing parameter
flags following @code{$@{(}; the full command line argument is presented
and the handler must test the value to be completed to ascertain that
this is the case.
@end quotation

@code{assign_parameter}

@quotation

when completing the name of a parameter in a parameter assignment.
@end quotation

@code{command}

@quotation

when completing for a normal command (either in command position or for
an argument of the command).
@end quotation

@code{condition}

@quotation

when completing inside a @code{[[...]]} conditional expression; in
this case the @code{words} array contains only the words inside the
conditional expression.
@end quotation

@code{math}

@quotation

when completing in a mathematical environment such as a
@code{((...))} construct.
@end quotation

@code{parameter}

@quotation

when completing the name of a parameter in a parameter expansion beginning
with @code{$} but not @code{$@{}.
@end quotation

@code{redirect}

@quotation

when completing after a redirection operator.
@end quotation

@code{subscript}

@quotation

when completing inside a parameter subscript.
@end quotation

@code{value}

@quotation

when completing the value of a parameter assignment.
@end quotation
@end quotation

@geindex exact@comma{} compstate; Variable

@code{exact}

@quotation

Controls the behaviour when the @code{REC_EXACT} option is set.  It will be
set to @code{accept} if an exact match would be accepted, and will be unset
otherwise.

If it was set when at least one match equal to the string on the line
was generated, the match is accepted.
@end quotation

@geindex exact_string@comma{} compstate; Variable

@code{exact_string}

@quotation

The string of an exact match if one was found, otherwise unset.
@end quotation

@geindex ignored@comma{} compstate; Variable

@code{ignored}

@quotation

The number of completions that were ignored because they matched one of the
patterns given with the @code{-F} option to the @code{compadd} builtin
command.
@end quotation

@geindex insert@comma{} compstate; Variable

@code{insert}

@quotation

This controls the manner in which a match is inserted into the command
line.  On entry to the widget function, if it is unset the command line is
not to be changed; if set to @code{unambiguous}, any prefix common to all
matches is to be inserted; if set to @code{automenu-unambiguous}, the
common prefix is to be inserted and the next invocation of the
completion code may start menu completion (due to the @code{AUTO_MENU}
option being set); if set to @code{menu} or @code{automenu} menu completion
will be started for the matches currently generated (in the
latter case this will happen because the @code{AUTO_MENU} is set). The
value may also contain the string @code{tab} when the completion code
would normally not really do completion, but only insert the TAB
character.

On exit it may be set to any of the values above (where setting it to
the empty string is the same as unsetting it), or to a number, in which
case the match whose number is given will be inserted into the command line.
Negative numbers count backward from the last match (with @code{-1}
selecting the last match) and out-of-range values are wrapped
around, so that a value of zero selects the last match and a value
one more than the maximum selects the first. Unless the value of this
key ends in a space, the match is inserted as in a menu completion,
i.e. without automatically appending a space.

Both @code{menu} and @code{automenu} may also specify the number of the
match to insert, given after a colon.  For example, @code{menu:2} says
to start menu completion, beginning with the second match.

Note that a value containing the substring @code{tab} makes the
matches generated be ignored and only the TAB be inserted.

Finally, it may also be set to @code{all}, which makes all matches
generated be inserted into the line.
@end quotation

@geindex insert_positions@comma{} compstate; Variable

@code{insert_positions}

@quotation

When the completion system inserts an unambiguous string into the
line, there may be multiple places where characters are missing or
where the character inserted differs from at least one match.  The
value of this key contains a colon separated list of all these
positions, as indexes into the command line.
@end quotation

@geindex last_prompt@comma{} compstate; Variable

@code{last_prompt}

@quotation

If this is set to a non-empty string for every match added, the
completion code will move the cursor back to the previous prompt after
the list of completions has been displayed.  Initially this is set or
unset according to the @code{ALWAYS_LAST_PROMPT} option.
@end quotation

@geindex list@comma{} compstate; Variable

@code{list}

@quotation

This controls whether or how the list of matches will be displayed.  If it
is unset or empty they will never be listed; if its value begins with
@code{list}, they will always be listed; if it begins with @code{autolist}
or @code{ambiguous}, they will be listed when the @code{AUTO_LIST} or
@code{LIST_AMBIGUOUS} options respectively would normally cause them to
be.

If the substring @code{force} appears in the value, this makes the
list be shown even if there is only one match. Normally, the list
would be shown only if there are at least two matches.

The value contains the substring @code{packed} if the @code{LIST_PACKED}
option is set. If this substring is given for all matches added to a
group, this group will show the @code{LIST_PACKED} behavior. The same is
done for the @code{LIST_ROWS_FIRST} option with the substring @code{rows}.

Finally, if the value contains the string @code{explanations}, only the
explanation strings, if any, will be listed and if it contains
@code{messages}, only the messages (added with the @code{-x} option of
@code{compadd}) will be listed.  If it contains both @code{explanations} and
@code{messages} both kinds of explanation strings will be listed.  It
will be set appropriately on entry to a completion widget and may be
changed there.
@end quotation

@geindex list_lines@comma{} compstate; Variable

@code{list_lines}

@quotation

This gives the number of lines that are needed to display the full
list of completions.  Note that to calculate the total number of lines
to display you need to add the number of lines needed for the command
line to this value, this is available as the value of the @code{BUFFERLINES}
special parameter.
@end quotation

@geindex list_max@comma{} compstate; Variable

@code{list_max}

@quotation

Initially this is set to the value of the @code{LISTMAX} parameter.
It may be set to any other value; when the widget exits this value
will be used in the same way as the value of @code{LISTMAX}.
@end quotation

@geindex nmatches@comma{} compstate; Variable

@code{nmatches}

@quotation

The number of matches added by the completion code so far.
@end quotation

@geindex old_insert@comma{} compstate; Variable

@code{old_insert}

@quotation

On entry to the widget this will be set to the number of the match of
an old list of completions that is currently inserted into the command
line. If no match has been inserted, this is unset.

As with @code{old_list}, the value of this key will only be used if it is the
string @code{keep}. If it was set to this value by the widget and there was an
old match inserted into the command line, this match will be kept and if
the value of the @code{insert} key specifies that another match should be
inserted, this will be inserted after the old one.
@end quotation

@geindex old_list@comma{} compstate; Variable

@code{old_list}

@quotation

This is set to @code{yes} if there is still a valid list of completions
from a previous completion at the time the widget is invoked.  This will
usually be the case if and only if the previous editing operation was a
completion widget or one of the builtin completion functions.  If there is a
valid list and it is also currently shown on the screen, the value of this
key is @code{shown}.

After the widget has exited the value of this key is only used if it
was set to @code{keep}.  In this case the completion code will continue
to use this old list.  If the widget generated new matches, they will
not be used.
@end quotation

@geindex parameter@comma{} compstate; Variable

@code{parameter}

@quotation

The name of the parameter when completing in a subscript or in the
value of a parameter assignment.
@end quotation

@geindex pattern_insert@comma{} compstate; Variable

@code{pattern_insert}

@quotation

Normally this is set to @code{menu}, which specifies that menu completion will
be used whenever a set of matches was generated using @code{pattern_match}
(see below).  If
it is set to any other non-empty string by the user and menu completion is
not selected by other option settings, the code will instead insert any
common prefix for the generated matches as with normal completion.
@end quotation

@geindex pattern_match@comma{} compstate; Variable

@code{pattern_match}

@quotation

Locally controls the behaviour given by the @code{GLOB_COMPLETE} option.
Initially it is set to @code{*} if and only if the option is set.
The completion widget may set it to this value, to an empty string
(which has the same effect as unsetting it), or to any
other non-empty string.  If it is non-empty, unquoted metacharacters on the
command line will be treated as patterns; if it is @code{*}, then
additionally a wildcard @code{*} is assumed at the cursor position; if
it is empty or unset, metacharacters will be treated literally.

Note that the match specifications given to the @code{compadd} builtin
command are not used if this is set to a non-empty string.
@end quotation

@geindex quote@comma{} compstate; Variable

@code{quote}

@quotation

When completing inside quotes, this contains the quotation character
(i.e. either a single quote, a double quote, or a backtick).  Otherwise it
is unset.
@end quotation

@geindex quoting@comma{} compstate; Variable

@code{quoting}

@quotation

When completing inside single quotes, this is set to the string
@code{single}; inside double quotes, the string
@code{double}; inside backticks, the string @code{backtick}.
Otherwise it is unset.
@end quotation

@geindex redirect@comma{} compstate; Variable

@code{redirect}

@quotation

The redirection operator when completing in a redirection position,
i.e. one of @code{<}, @code{>}, etc.
@end quotation

@geindex restore@comma{} compstate; Variable

@code{restore}

@quotation

This is set to @code{auto} before a function is entered, which forces the
special parameters mentioned above (@code{words}, @code{CURRENT}, @code{PREFIX},
@code{IPREFIX}, @code{SUFFIX}, and @code{ISUFFIX}) to be restored to their
previous values when the function exits.   If a function unsets it or
sets it to any other string, they will not be restored.
@end quotation

@geindex to_end@comma{} compstate; Variable

@code{to_end}

@quotation

Specifies the occasions on which the cursor is moved to the end of a string
when a match is inserted.  On entry to a widget function, it may be
@code{single} if this will happen when a single unambiguous match was inserted
or @code{match} if it will happen any time a match is inserted (for example,
by menu completion; this is likely to be the effect of the @code{ALWAYS_TO_END}
option).

On exit, it may be set to @code{single} as above.  It may also be set to
@code{always}, or to the empty string or unset; in those cases the cursor will
be moved to the end of the string always or never respectively.  Any
other string is treated as @code{match}.
@end quotation

@geindex unambiguous@comma{} compstate; Variable

@code{unambiguous}

@quotation

This key is read-only and will always be set to the common (unambiguous)
prefix the completion code has generated for all matches added so far.
@end quotation

@geindex unambiguous_cursor@comma{} compstate; Variable

@code{unambiguous_cursor}

@quotation

This gives the position the cursor would be placed at if the
common prefix in the @code{unambiguous} key were inserted, relative to
the value of that key. The cursor would be placed before the character
whose index is given by this key.
@end quotation

@geindex unambiguous_positions@comma{} compstate; Variable

@code{unambiguous_positions}

@quotation

This contains all positions where characters in the unambiguous string
are missing or where the character inserted differs from at least one
of the matches.  The positions are given as indexes into the string
given by the value of the @code{unambiguous} key.
@end quotation

@geindex vared@comma{} compstate; Variable

@code{vared}

@quotation

If completion is called while editing a line using the @code{vared}
builtin, the value of this key is set to the name of the parameter
given as an argument to @code{vared}.  This key is only set while a @code{vared}
command is active.
@end quotation
@end quotation

@geindex words; Variable

@code{words}

@quotation

This array contains the words present on the command line currently being
edited.
@end quotation

@c historic nodename: Completion Builtin Commands

@node Completion Builtin Commands,Completion Condition Codes,Completion Special Parameters,Completion Widgets
@anchor{Zsh/compwid completion-builtin-commands}@anchor{e7}
@section Completion Builtin Commands


@geindex compadd; Function

@geindex completion widgets@comma{} adding specified matches; Command

@code{compadd} [ @code{-akqQfenUl12C} ] [ @code{-F} @var{array} ]

@quotation

@quotation

@code{[-P} @var{prefix} ] [ @code{-S} @var{suffix} ]

@code{[-p} @var{hidden-prefix} ] [ @code{-s} @var{hidden-suffix} ]

@code{[-i} @var{ignored-prefix} ] [ @code{-I} @var{ignored-suffix} ]

@code{[-W} @var{file-prefix} ] [ @code{-d} @var{array} ]

@code{[-J} @var{group-name} ] [ @code{-X} @var{explanation} ] [ @code{-x} @var{message} ]

@code{[-V} @var{group-name} ] [ @code{-o} [ @var{order} ] ]

@code{[-r} @var{remove-chars} ] [ @code{-R} @var{remove-func} ]

@code{[-D} @var{array} ] [ @code{-O} @var{array} ] [ @code{-A} @var{array} ]

@code{[-E} @var{number} ]

@code{[-M} @var{match-spec} ] [ @code{--} ] [ @var{completions} … ]
@end quotation

This builtin command can be used to add matches directly and control
all the information the completion code stores with each possible
completion. The return status is zero if at least one match was added and
non-zero if no matches were added.

The completion code breaks each match into seven fields in the order:


@quotation

@var{<ipre><apre><hpre><body><hsuf><asuf><isuf>}
@end quotation

The first field
is an ignored prefix taken from the command line, the contents of the
@code{IPREFIX} parameter plus the string given with the @code{-i}
option. With the @code{-U} option, only the string from the @code{-i}
option is used. The field @var{<apre>} is an optional prefix string
given with the @code{-P} option.  The @var{<hpre>} field is a string
that is considered part of the match but that should not be shown when
listing completions, given with the @code{-p} option; for example,
functions that do filename generation might specify
a common path prefix this way.  @var{<body>} is the part of the match that
should appear in the list of matches shown to the user.
The suffixes @var{<hsuf>},
@var{<asuf>} and @var{<isuf>} correspond to the prefixes @var{<hpre>},
@var{<apre>} and @var{<ipre>} and are given by the options @code{-s}, @code{-S} and
@code{-I}, respectively.

The supported flags are:

@code{-P} @var{prefix}

@quotation

This gives a string to be inserted before each match.  The
string given is not considered as part of the match and any shell
metacharacters in it will not be quoted when the string is inserted.
@end quotation

@code{-S} @var{suffix}

@quotation

Like @code{-P}, but gives a string to be inserted after each match.
@end quotation

@code{-p} @var{hidden-prefix}

@quotation

This gives a string that should be inserted before each
match but that should not appear in the list of matches. Unless the
@code{-U} option is given, this string must be matched as part of the string
on the command line.
@end quotation

@code{-s} @var{hidden-suffix}

@quotation

Like @code{-p}, but gives a string to insert after each match.
@end quotation

@code{-i} @var{ignored-prefix}

@quotation

This gives a string to insert just before any
string given with the @code{-P} option.  Without @code{-P} the string is
inserted before the string given with @code{-p} or directly before each
match.
@end quotation

@code{-I} @var{ignored-suffix}

@quotation

Like @code{-i}, but gives an ignored suffix.
@end quotation

@code{-a}

@quotation

With this flag the @var{completions} are taken as names of arrays and the
actual completions are their values.  If only some elements of the
arrays are needed, the @var{completions} may also contain subscripts, as in
@code{foo[2,-1]}.
@end quotation

@code{-k}

@quotation

With this flag the @var{completions} are taken as names of associative arrays
and the actual completions are their keys.  As for @code{-a}, the
@var{words} may also contain subscripts, as in @code{foo[(R)*bar*]}.
@end quotation

@code{-d} @var{array}

@quotation

This adds per-completion display strings. The @var{array} should contain one
element per @var{completion} given. The completion code will then display the
first element instead of the first @var{completion}, and so on. The
@var{array} may be given as the name of an array parameter, or directly
as a literal array enclosed in parentheses. A literal array is a space or
comma separated list of words; quotes have no special meaning and
backslashes can be used for escaping (for example, @code{(foo\ bar)} produces
one element, @code{foo bar}, while @code{(foo bar)} produces two elements,
@code{foo} and @code{bar}).

If there are fewer display strings than @var{completions}, the leftover
@var{completions} will be displayed unchanged and if there are more display
strings than @var{completions}, the leftover display strings will be silently
ignored.
@end quotation

@code{-l}

@quotation

This option only has an effect if used together with the @code{-d}
option. If it is given, the display strings are listed one per line,
not arrayed in columns.
@end quotation

@code{-o} [ @var{order} ]

@quotation

This controls the order in which matches are sorted. @var{order} is a
comma-separated list comprising the following possible values.  These values
can be abbreviated to their initial two or three characters.  Note that the
order forms part of the group name space so matches with different orderings
will not be in the same group; additionally, since ordering flags are not
respected on the default group, a group name must be given explicitly.  See
@code{-J} and @code{-V} below.

@code{match}

@quotation

If given, the order of the output is determined by the match strings;
otherwise it is determined by the display strings (i.e. the strings given
by the @code{-d} option). This is the default if @code{-o} is specified but
the @var{order} argument is omitted.
@end quotation

@code{nosort}

@quotation

This specifies that the @var{completions}
are pre-sorted and their order should be
preserved.  This value only makes sense alone and cannot be combined with any
others.
@end quotation

@code{numeric}

@quotation

If the matches include numbers, sort them numerically rather than
lexicographically.
@end quotation

@code{reverse}

@quotation

Arrange the matches backwards by reversing the sort ordering.
@end quotation
@end quotation

@code{-J} @var{group-name}

@quotation

Gives the name of the group that the matches should be stored in.
@end quotation

@code{-V} @var{group-name}

@quotation

Like @code{-J} but naming an unsorted group. This option is identical to
the combination of @code{-J} and @code{-o nosort}.
@end quotation

@code{-1}

@quotation

If given together with the @code{-V} option, makes
only consecutive duplicates in the group be removed. If combined with
the @code{-J} option, this has no visible effect. Note that groups
with and without this flag are in different name spaces.
@end quotation

@code{-2}

@quotation

If given together with the @code{-J} or @code{-V} option, makes all
duplicates be kept. Again, groups with and without this flag are in
different name spaces.
@end quotation

@code{-X} @var{explanation}

@quotation

The @var{explanation} string will be printed with the list of matches,
above the group currently selected.

Within the @var{explanation}, the following sequences may be used to
specify output attributes as described in
@ref{e8,,Expansion of Prompt Sequences}:
@code{%B}, @code{%S}, @code{%U}, @code{%F}, @code{%K} and their lower case
counterparts, as well as @code{%H} and @code{%@{...%@}}.  @code{%F},
@code{%K}, @code{%H} and
@code{%@{...%@}} take arguments in the same form as prompt
expansion.  (Note that the sequence @code{%G} is not available; an
argument to @code{%@{} should be used instead.)  The sequence @code{%%}
produces a literal @code{%}.

These sequences are most often employed by users when customising the
@code{format} style (see @ref{e9,,Standard Styles}),
but they must also be taken into account when writing completion
functions, as passing descriptions with unescaped @code{%} characters
to utility functions such as @code{_arguments} and @code{_message} may
produce unexpected results. If arbitrary text is to be passed in a
description, it can be escaped using e.g. @code{$@{my_str//\%/%%@}}.
@end quotation

@code{-x} @var{message}

@quotation

Like @code{-X}, but the @var{message} will be printed even if there are no
matches in the group.
@end quotation

@code{-q}

@quotation

The suffix given with @code{-S} will be automatically removed if
the next character typed is a blank or does not insert anything, or if
the suffix consists of only one character and the next character typed
is the same character.
@end quotation

@code{-r} @var{remove-chars}

@quotation

This is a more versatile form of the @code{-q} option.
The suffix given with @code{-S} or the slash automatically added after
completing directories will be automatically removed if
the next character typed inserts one of the characters given in the
@var{remove-chars}.  This string is parsed as a characters class and
understands the backslash sequences used by the @code{print} command.  For
example, @code{-r "a-z\t"} removes the suffix if the next character typed
inserts a lower case character or a TAB, and @code{-r "^0-9"} removes the
suffix if the next character typed inserts anything but a digit. One extra
backslash sequence is understood in this string: @code{\-} stands for
all characters that insert nothing. Thus @code{-S "=" -q} is the same
as @code{-S "=" -r "= \t\n\-"}.

This option may also be used without the @code{-S} option; then any
automatically added space will be removed when one of the characters in the
list is typed.
@end quotation

@code{-R} @var{remove-func}

@quotation

This is another form of the @code{-r} option. When a match
has been accepted and a suffix has been inserted, the function
@var{remove-func} will be called after the next character typed.  It is
passed the length of the suffix as an argument and can use the special
parameters available in ordinary (non-completion) zle widgets (see
@ref{da,,User-Defined Widgets}
) to analyse and modify the command line.
@end quotation

@code{-f}

@quotation

If this flag is given, all of the matches built from the @var{completions} are
marked as being the names of files.  They are not required to be actual
filenames, but if they are, and the option @code{LIST_TYPES} is set, the
characters describing the types of the files in the completion lists will
be shown. This also forces a slash to be added when the name of a
directory is completed.
@end quotation

@code{-e}

@quotation

This flag can be used to tell the completion code that the matches
added are parameter names for a parameter expansion. This will make
the @code{AUTO_PARAM_SLASH} and @code{AUTO_PARAM_KEYS} options be used for
the matches.
@end quotation

@code{-W} @var{file-prefix}

@quotation

This string is a pathname that will be prepended to each match together
with any prefix specified by the @code{-p} option to form a complete filename
for testing.  Hence it is only useful if combined with the @code{-f} flag, as
the tests will not otherwise be performed.
@end quotation

@code{-F} @var{array}

@quotation

Specifies an array containing patterns.  @var{completions} that match one of
these patterns are ignored, that is, not considered to be matches.

The @var{array} may be the name of an array parameter or a list of
literal patterns enclosed in parentheses and quoted, as in @code{-F "(*?.o
*?.h)"}. If the name of an array is given, the elements of the array are
taken as the patterns.
@end quotation

@code{-Q}

@quotation

This flag instructs the completion
code not to quote any metacharacters in the matches when inserting them
into the command line.
@end quotation

@code{-M} @var{match-spec}

@quotation

This gives local match specifications as described below in
Completion Matching Control. This option may be given more than once.
In this case all @var{match-spec}s given are concatenated with spaces
between them to form the specification string to use.
Note that they will only be used if the @code{-U} option is not given.
@end quotation

@code{-n}

@quotation

Specifies that matching @var{completions} are to be added to the set of
matches, but are not to be listed to the user.
@end quotation

@code{-U}

@quotation

If this flag is given, all @var{completions} are added
to the set of matches and no matching
will be done by the completion code. Normally this is used in
functions that do the matching themselves.
@end quotation

@code{-O} @var{array}

@quotation

If this option is given, the @var{completions} are `not' added to the set of
matches.  Instead, matching is done as usual and all of the
@var{completions} that match
will be stored in the array parameter whose name is given as @var{array}.
@end quotation

@code{-A} @var{array}

@quotation

As the @code{-O} option, except that instead of those of the @var{completions}
which
match being stored in @var{array}, the strings generated internally by the
completion code are stored.  For example,
with a match specification of @code{-M "L:|no="}, a current word of @code{nof}
and @var{completions} of @code{foo}, this
option stores the string @code{nofoo} in the array, whereas the @code{-O}
option stores the @code{foo} originally given.
@end quotation

@code{-D} @var{array}

@quotation

As with @code{-O}, the @var{completions} are not added to the set of matches.
Instead, whenever the @var{n}th @var{completion} does not
match, the @var{n}th element of the @var{array} is removed.  Elements
for which the corresponding @var{completion} matches are retained.
This option can be used more than once to remove elements from multiple
arrays.
@end quotation

@code{-C}

@quotation

This option adds a special match which expands to all other matches
when inserted into the line, even those that are added after this
option is used.  Together with the @code{-d} option it is possible to
specify a string that should be displayed in the list for this special
match.  If no string is given, it will be shown as a string containing
the strings that would be inserted for the other matches, truncated to
the width of the screen.
@end quotation

@code{-E} @var{number}

@quotation

This option adds @var{number} empty matches after matching @var{completions} have
been added.  An empty match takes up space in completion listings but
will never be inserted in the line and can’t be selected with menu
completion or menu selection.  This makes empty matches only useful to
format completion lists and to make explanatory string be shown in
completion lists (since empty matches can be given display strings
with the @code{-d} option).  And because all but one empty string would
otherwise be removed, this option implies the @code{-V} and @code{-2}
options (even if an explicit @code{-J} option is given).  This can be
important to note as it affects the name space into which matches are
added.
@end quotation

@code{-}

@code{--}

@quotation

This flag ends the list of flags and options. All arguments after it
will be taken as the @var{completions} even if they begin with
hyphens.
@end quotation

Except for the @code{-M} flag, if any of these flags is given more than
once, the first one (and its argument) will be used.
@end quotation

@geindex compset; Function

@geindex completion widgets@comma{} modifying special parameters; Command

@code{compset -p} @var{number}

@code{compset -P} [ @var{number} ] @var{pattern}

@code{compset -s} @var{number}

@code{compset -S} [ @var{number} ] @var{pattern}

@code{compset -n} @var{begin} [ @var{end} ]

@code{compset -N} @var{beg-pat} [ @var{end-pat} ]

@code{compset -q}

@quotation

This command simplifies modification of the special parameters,
while its return status allows tests on them to be carried out.

The options are:

@code{-p} @var{number}

@quotation

If the value of the @code{PREFIX} parameter is at least @var{number}
characters long, the first @var{number} characters are removed from it and
appended to the contents of the @code{IPREFIX} parameter.
@end quotation

@code{-P} [ @var{number} ] @var{pattern}

@quotation

If the value of the @code{PREFIX} parameter begins with anything that
matches the @var{pattern}, the matched portion is removed from
@code{PREFIX} and appended to @code{IPREFIX}.

Without the optional @var{number}, the longest match is taken, but
if @var{number} is given, anything up to the @var{number}th match is
moved.  If the @var{number} is negative, the @var{number}th longest
match is moved. For example, if @code{PREFIX} contains the string
@code{a=b=c}, then @code{compset -P '*\='} will move the string @code{a=b=}
into the @code{IPREFIX} parameter, but @code{compset -P 1 '*\='} will move only
the string @code{a=}.
@end quotation

@code{-s} @var{number}

@quotation

As @code{-p}, but transfer the last @var{number} characters from the
value of @code{SUFFIX} to the front of the value of @code{ISUFFIX}.
@end quotation

@code{-S} [ @var{number} ] @var{pattern}

@quotation

As @code{-P}, but match the last portion of @code{SUFFIX} and transfer the
matched portion to the front of the value of @code{ISUFFIX}.
@end quotation

@code{-n} @var{begin} [ @var{end} ]

@quotation

If the current word position as specified by the parameter @code{CURRENT}
is greater than or equal to @var{begin}, anything up to the
@var{begin}th word is removed from the @code{words} array and the value
of the parameter @code{CURRENT} is decremented by @var{begin}.

If the optional @var{end} is given, the modification is done only if
the current word position is also less than or equal to @var{end}. In
this case, the words from position @var{end} onwards are also removed from
the @code{words} array.

Both @var{begin} and @var{end} may be negative to count backwards
from the last element of the @code{words} array.
@end quotation

@code{-N} @var{beg-pat} [ @var{end-pat} ]

@quotation

If one of the elements of the @code{words} array before the one at the
index given by the value of the parameter @code{CURRENT} matches the
pattern @var{beg-pat}, all elements up to and including the matching one are
removed from the @code{words} array and the value of @code{CURRENT} is changed to
point to the same word in the changed array.

If the optional pattern @var{end-pat} is also given, and there is an
element in the @code{words} array matching this pattern, the parameters
are modified only if the index of this word is higher than the one
given by the @code{CURRENT} parameter (so that the matching word has
to be after the cursor). In this case, the words starting with the one
matching @code{end-pat} are also removed from the @code{words}
array. If @code{words} contains no word matching @var{end-pat}, the
testing and modification is performed as if it were not given.
@end quotation

@code{-q}

@quotation

The word
currently being completed is split on spaces into separate words,
respecting the usual shell quoting conventions.  The
resulting words are stored in the @code{words} array, and @code{CURRENT},
@code{PREFIX}, @code{SUFFIX}, @code{QIPREFIX}, and @code{QISUFFIX} are modified to
reflect the word part that is completed.
@end quotation

In all the above cases the return status is zero if the test succeeded
and the parameters were modified and non-zero otherwise. This allows
one to use this builtin in tests such as:

@example
 if compset -P '*\='; then ...
@end example

This forces anything up to and including the last equal sign to be
ignored by the completion code.
@end quotation

@code{compcall} [ @code{-TD} ]

@quotation

This allows the use of completions defined with the @code{compctl} builtin
from within completion widgets.  The list of matches will be generated as
if one of the non-widget completion functions (@code{complete-word}, etc.)
had been called, except that only @code{compctl}s given for specific commands
are used. To force the code to try completions defined with the @code{-T}
option of @code{compctl} and/or the default completion (whether defined by
@code{compctl -D} or the builtin default) in the appropriate places, the
@code{-T} and/or @code{-D} flags can be passed to @code{compcall}.

The return status can be used to test if a matching @code{compctl}
definition was found. It is non-zero if a @code{compctl} was found and
zero otherwise.

Note that this builtin is defined by the @code{zsh/compctl} module.
@end quotation

@c historic nodename: Completion Condition Codes

@node Completion Condition Codes,Completion Matching Control,Completion Builtin Commands,Completion Widgets
@anchor{Zsh/compwid completion-condition-codes}@anchor{ea}
@section Completion Condition Codes


@geindex completion widgets@comma{} condition codes; Command

The following additional condition codes for use within the @code{[[} @var{…} @code{]]}
construct are available in completion widgets.  These work on the special
parameters.  All of these tests can also be performed by the @code{compset}
builtin, but in the case of the condition codes the contents of the special
parameters are not modified.

@geindex -prefix@comma{} within [[; Function

@code{-prefix} [ @var{number} ] @var{pattern}

@quotation

true if the test for the @code{-P} option of @code{compset} would succeed.
@end quotation

@geindex -suffix@comma{} within [[; Function

@code{-suffix} [ @var{number} ] @var{pattern}

@quotation

true if the test for the @code{-S} option of @code{compset} would succeed.
@end quotation

@geindex -after@comma{} within [[; Function

@code{-after} @var{beg-pat}

@quotation

true if the test of the @code{-N} option with only the @var{beg-pat} given
would succeed.
@end quotation

@geindex -between@comma{} within [[; Function

@code{-between} @var{beg-pat end-pat}

@quotation

true if the test for the @code{-N} option with both patterns would succeed.
@end quotation

@c historic nodename: Completion Matching Control

@node Completion Matching Control,Completion Widget Example,Completion Condition Codes,Completion Widgets
@anchor{Zsh/compwid completion-matching-control}@anchor{eb}
@section Completion Matching Control


When the user invokes completion, the current `word' on the command line
(that is, the word the cursor is currently on) is used to generate a `match
pattern'.  Only those `completions' that match the pattern are offered to the
user as `matches'.

The default match pattern is generated from the current word by either

@quotation


@itemize *

@item 
appending a @code{*} (matching any number of characters in a completion)
@end itemize

`or,'
* if the shell option @code{COMPLETE_IN_WORD} is set, inserting a @code{*} at the
cursor position.
@end quotation

This narrow pattern can be broadened selectively by passing a `match
specification' to the @code{compadd} builtin command through its @code{-M} option
(see @ref{e7,,Completion Builtin Commands}).
A match specification consists of one or more @var{matchers} separated by
whitespace.  Matchers in a match specification are applied one at a time, from
left to right.  Once all matchers have been applied, completions are compared
to the final match pattern and non-matching ones are discarded.

@quotation


@itemize *

@item 
Note that the @code{-M} option is ignored if the current word contains a glob
@end itemize

pattern and the shell option @code{GLOB_COMPLETE} is set or if the
@code{pattern_match} key of the special associative array @code{compstate} is set to
a non-empty value (see @ref{e6,,Completion Special Parameters}).


@itemize *

@item 
Users of the
@end itemize


@quotation

Completion System
@end quotation

should generally not use the @code{-M} option directly, but rather use the

@code{matcher-list} and @code{matcher} styles (see
@ref{e9,,Standard Styles}).
@end quotation

Each matcher consists of

@quotation


@itemize *

@item 
a case-sensitive letter

@item 
a @code{:},

@item 
one or more patterns separated by pipes (@code{|}),

@item 
an equals sign (@code{=}), and

@item 
another pattern.
@end itemize
@end quotation

The patterns before the @code{=} are used to match substrings of the current
word.  For each matched substring, the corresponding part of the match pattern
is broadened with the pattern after the @code{=}, by means of a logical @code{OR}.

Each pattern in a matcher consists of either

@quotation


@itemize *

@item 
the empty string or

@item 
a sequence of

@quotation


@itemize *

@item 
literal characters (which may be quoted with a @code{\}),

@item 
question marks (@code{?}),

@item 
bracket expressions (@code{[...]}; see @ref{7c,,Glob Operators}),
@end itemize

and/or
* brace expressions (see below).
@end quotation
@end itemize
@end quotation

Other shell patterns are not allowed.

A brace expression, like a bracket expression, consists of a list of

@quotation


@itemize *

@item 
literal characters,

@item 
ranges (@code{0-9}), and/or

@item 
character classes (@code{[:}@var{name}@code{:]}).
@end itemize
@end quotation

However, they differ from each other as follows:

@quotation


@itemize *

@item 
A brace expression is delimited by a pair of braces (@code{@{...@}}).

@item 
Brace expressions do not support negations.  That is, an initial
@end itemize

@code{!} or @code{^} has no special meaning and will be interpreted as a literal
character.
* When a character in the current word matches the @var{n}th pattern in a brace
expression, the corresponding part of the match pattern is broadened only with
the @var{n}th pattern of the brace expression on the other side of the @code{=},
if there is one; if there is no brace expression on the other side, then this
pattern is the empty string.  However, if either brace expression has more
elements than the other, then the excess entries are simply ignored.  When
comparing indexes, each literal character or character class counts as one
element, but each range is instead expanded to the full list of literal
characters it represents.  Additionally, if on `both' sides of the
@code{=}, the @var{n}th pattern is @code{[:upper:]} or @code{[:lower:]}, then these
are expanded as ranges, too.
@end quotation

Note that, although the matching system does not yet handle multibyte
characters, this is likely to be a future extension.  Hence, using
@code{[:upper:]} and @code{[:lower:]} is recommended over
@code{A-Z} and @code{a-z}.

Below are the different forms of matchers supported.  Each `uppercase' form
behaves exactly like its lowercase counterpart, but adds an additional step
`after' the match pattern has filtered out non-matching completions:  Each of
a match’s substrings that was matched by a subpattern from an uppercase matcher
is replaced with the corresponding substring of the current word.  However,
patterns from `lowercase' matchers have higher weight:  If a substring of the
current word was matched by patterns from both a lowercase and an uppercase
matcher, then the lowercase matcher’s pattern wins and the corresponding part
of the match is not modified.

Unless indicated otherwise, each example listed assumes @code{COMPLETE_IN_WORD} to
be unset (as it is by default).

@code{m:}@var{word-pat}@code{=}@var{match-pat}

@code{M:}@var{word-pat}@code{=}@var{match-pat}

@quotation

For each substring of the current word that matches @var{word-pat}, broaden the
corresponding part of the match pattern to additionally match @var{match-pat}.

Examples:

@quotation

@code{m:@{[:lower:]@}=@{[:upper:]@}} lets any lower case character in the current word
be completed to itself or its uppercase counterpart.  So, the completions
@code{foo}, @code{FOO} and @code{Foo} will are be considered matches for the word
@code{fo}.

@code{M:_=} inserts every underscore from the current word into each match, in the
same relative position, determined by matching the substrings around it.  So,
given a completion @code{foo}, the word @code{f_o} will be completed to the match
@code{f_oo}, even though the latter was not present as a completion.
@end quotation
@end quotation

@code{b:}@var{word-pat}@code{=}@var{match-pat}

@code{B:}@var{word-pat}@code{=}@var{match-pat}

@code{e:}@var{word-pat}@code{=}@var{match-pat}

@code{E:}@var{word-pat}@code{=}@var{match-pat}

@quotation

For each consecutive substring at the @code{b:}eginning or @code{e:}nd of the current
word that matches @var{word-pat}, broaden the corresponding part of the match
pattern to additionally match @var{match-pat}.

Examples:

@quotation

@code{b:-=+} lets any number of minuses at the start of the current word be
completed to a minus or a plus.

@code{B:0=} adds all zeroes at the beginning of the current word to the
beginning of each match.
@end quotation
@end quotation

@code{l:|}@var{word-pat}@code{=}@var{match-pat}

@code{L:|}@var{word-pat}@code{=}@var{match-pat}

@code{r:}@var{word-pat}@code{|=}@var{match-pat}

@code{R:}@var{word-pat}@code{|=}@var{match-pat}

@quotation

If there is a substring at the @code{l:}eft or @code{r:}ight edge of the current word
that matches @var{word-pat}, then broaden the corresponding part of the match
pattern to additionally match @var{match-pat}.

For each @code{l:}, @code{L:}, @code{r:} and @code{R:} matcher (including the ones below),
the pattern @var{match-pat} may also be a @code{*}.  This matches any number of
characters in a completion.

Examples:

@quotation

@code{r:|=*} appends a @code{*} to the match pattern, even when
@code{COMPLETE_IN_WORD} is set and the cursor is not at the end of the current
word.

If the current word starts with a minus, then @code{L:|-=} will prepend it to
each match.
@end quotation
@end quotation

@code{l:}@var{anchor}@code{|}@var{word-pat}@code{=}@var{match-pat}

@code{L:}@var{anchor}@code{|}@var{word-pat}@code{=}@var{match-pat}

@code{r:}@var{word-pat}@code{|}@var{anchor}@code{=}@var{match-pat}

@code{R:}@var{word-pat}@code{|}@var{anchor}@code{=}@var{match-pat}

@quotation

For each substring of the current word that matches @var{word-pat} and has on
its @code{l:}eft or @code{r:}ight another substring matching @var{anchor}, broaden the
corresponding part of the match pattern to additionally match @var{match-pat}.

Note that these matchers (and the ones below) modify only what is matched by
@var{word-pat}; they do not change the matching behavior of what is matched by
@var{anchor} (or @var{coanchor}; see the matchers below).  Thus, unless its
corresponding part of the match pattern has been modified, the anchor in the
current word has to match literally in each completion, just like any other
substring of the current word.

If a matcher includes at least one anchor (which includes the matchers with two
anchors, below), then @var{match-pat} may also be @code{*} or @code{**}.  @code{*}
can match any part of a completion that does not contain any substrings
matching @var{anchor}, whereas a @code{**} can match any part of a completion,
period.  (Note that this is different from the behavior of @code{*} in the
anchorless forms of @code{l:} and @code{r:} and also different from @code{*}
and @code{**} in glob expressions.)

Examples:

@quotation

@code{r:|.=*} makes the completion @code{comp.sources.unix} a match for the word
@code{..u} – but `not' for the word @code{.u}.

Given a completion @code{--foo}, the matcher @code{L:--|no-=} will complete
the word @code{--no-} to the match @code{--no-foo}.
@end quotation
@end quotation

@code{l:}@var{anchor}@code{||}@var{coanchor}@code{=}@var{match-pat}

@code{L:}@var{anchor}@code{||}@var{coanchor}@code{=}@var{match-pat}

@code{r:}@var{coanchor}@code{||}@var{anchor}@code{=}@var{match-pat}

@code{R:}@var{coanchor}@code{||}@var{anchor}@code{=}@var{match-pat}

@quotation

For any two consecutive substrings of the current word that match @var{anchor}
and @var{coanchor}, in the order given, insert the pattern @var{match-pat}
between their corresponding parts in the match pattern.

Note that, unlike @var{anchor}, the pattern @var{coanchor} does not change what
@code{*} can match.

Examples:

@quotation

@code{r:?||[[:upper:]]=*} will complete the current word @code{fB} to
@code{fooBar}, but it will not complete it to @code{fooHooBar} (because @code{*}
here cannot match anything that includes a match for @code{`[[:upper:]]}), nor
will it complete @code{B} to @code{fooBar} (because there is no character in the
current word to match @var{coanchor}).

Given the current word @code{pass.n} and a completion @code{pass.byname}, the
matcher @code{L:.||[[:alpha:]]=by} will produce the match @code{pass.name}.
@end quotation
@end quotation

@code{x:}

@quotation

Ignore this matcher and all matchers to its right.

This matcher is used to mark the end of a match specification.  In a single
standalone list of matchers, this has no use, but where match specifications
are concatenated, as is often the case when using the


Completion System

, it can allow one match specification to override another.
@end quotation

@c historic nodename: Completion Widget Example

@node Completion Widget Example,,Completion Matching Control,Completion Widgets
@anchor{Zsh/compwid completion-widget-example}@anchor{ec}
@section Completion Widget Example


@geindex completion widgets@comma{} example; Command

The first step is to define the widget:

@example
 zle -C complete complete-word complete-files
@end example

Then the widget can be bound to a key using the @code{bindkey} builtin
command:

@example
 bindkey '^X\t' complete
@end example

After that the shell function @code{complete-files} will be invoked
after typing control-X and TAB. The function should then generate the
matches, e.g.:

@example
 complete-files () @{ compadd - * @}
@end example

This function will complete files in the current directory matching the
current word.

@c historic nodename: Completion System

@node Completion System,Completion Using compctl,Completion Widgets,Top
@anchor{Zsh/compsys doc}@anchor{ed}@anchor{Zsh/compsys completion-system}@anchor{ee}
@chapter Completion System


@geindex completion system; Command

@geindex completion@comma{} programmable; Command

@geindex completion@comma{} controlling; Command

@menu
* Description: Description<5>. 
* Initialization:: 
* Completion System Configuration:: 
* Control Functions:: 
* Bindable Commands:: 
* Utility Functions:: 
* Completion System Variables:: 
* Completion Directories:: 

@end menu

@node Description<5>,Initialization,,Completion System
@anchor{Zsh/compsys description}@anchor{ef}
@section Description


This describes the shell code for the `new’ completion system, referred
to as @code{compsys}.  It is written in shell functions based on the
features described in


the previous chapter, Completion Widgets

.

The features are contextual, sensitive to the point at which completion is
started.  Many completions are already provided.
For this reason, a user can perform a great many tasks without
knowing any details beyond how to initialize the system, which is
described @ref{f0,,Initialization}.

The context that decides what completion is to be performed may be

@quotation


@itemize *

@item 
an argument or option position: these describe the position on the
@end itemize

command line at which completion is requested.  For example `first argument
to rmdir, the word being completed names a directory’;


@itemize *

@item 
a special context, denoting an element in the shell’s syntax.  For example
@end itemize

`a word in command position’ or `an array subscript’.
@end quotation

A full context specification contains other elements, as we shall describe.

Besides command names and contexts, the system employs two more
concepts, `styles' and `tags'.  These provide ways for the user
to configure the system’s behaviour.

Tags play a dual role.  They serve as a classification system for
the matches, typically indicating a class of object that the user
may need to distinguish.  For example, when completing arguments of the
@code{ls} command the user may prefer to try @code{files} before @code{directories},
so both of these are tags.  They also appear as the rightmost
element in a context specification.

Styles modify various operations of the completion system, such as
output formatting, but also what kinds of completers are used (and in
what order), or which tags are examined.  Styles may accept arguments
and are manipulated using the @code{zstyle} command described in
@ref{ca,,The zsh/zutil Module}.

In summary, tags describe `what' the completion objects are, and style
@code{how} they are to be completed.  At various points of execution, the
completion system checks what styles and/or tags are defined for the
current context, and uses that to modify its behavior.  The full
description of context handling, which determines how tags and other
elements of the context influence the behaviour of styles, is described
@ref{f1,,Completion System Configuration}.

When a completion is requested, a dispatcher function is called;
see the description of @code{_main_complete} in the list of control functions
below. This dispatcher decides which function should
be called to produce the completions, and calls it. The result is
passed to one or more `completers', functions that implement
individual completion strategies: simple completion, error correction,
completion with error correction, menu selection, etc.

More generally, the shell functions contained in the completion system are
of two types:

@quotation


@itemize *

@item 
those beginning @code{comp} are to be called directly; there are only
@end itemize

a few of these;


@itemize *

@item 
those beginning @code{_} are called by the
@end itemize

completion code.  The shell functions of this set, which implement
completion behaviour and may be bound to keystrokes, are referred to
as `widgets’.  These proliferate as new completions are required.
@end quotation

@c historic nodename: Initialization

@node Initialization,Completion System Configuration,Description<5>,Completion System
@anchor{Zsh/compsys initialization}@anchor{f0}
@section Initialization


@geindex compinstall; Function

@geindex completion system@comma{} installing; Command

If the system was installed completely, it should be enough to
call the shell function @code{compinit} from your initialization file; see the
next section.  However, the function @code{compinstall} can be run by a user
to configure various aspects of the completion system.

Usually, @code{compinstall} will insert code into @code{.zshrc}, although if
that is not writable it will save it in another file and tell you that
file’s location.  Note that it is up to you to make sure that the lines
added to @code{.zshrc} are actually run; you may, for example, need to move
them to an earlier place in the file if @code{.zshrc} usually returns early.
So long as you keep them all together (including the comment lines at the
start and finish), you can rerun @code{compinstall} and it will correctly
locate and modify these lines.  Note, however, that any code you add to
this section by hand is likely to be lost if you rerun @code{compinstall},
although lines using the command @code{zstyle} should be gracefully handled.

The new code will take effect next time you start the shell, or run
@code{.zshrc} by hand; there is also an option to make them take effect
immediately.  However, if @code{compinstall} has removed definitions, you will
need to restart the shell to see the changes.

To run @code{compinstall} you will need to make sure it is in a directory
mentioned in your @code{fpath} parameter, which should already be the case if
zsh was properly configured as long as your startup files do not remove the
appropriate directories from @code{fpath}.  Then it must be autoloaded
(@code{autoload -U compinstall} is recommended).  You can abort the
installation any time you are being prompted for information, and your
@code{.zshrc} will not be altered at all; changes only take place right at the
end, where you are specifically asked for confirmation.

@menu
* Use of compinit:: 
* Autoloaded Files:: 
* Functions: Functions<2>. 

@end menu

@node Use of compinit,Autoloaded Files,,Initialization
@anchor{Zsh/compsys use-of-compinit}@anchor{f2}
@subsection Use of compinit


@geindex compinit; Function

@geindex completion system@comma{} initializing; Command

This section describes the use of @code{compinit} to initialize completion for
the current session when called directly; if you have run
@code{compinstall} it will be called automatically from your @code{.zshrc}.

To initialize the system, the function @code{compinit} should be in a
directory mentioned in the @code{fpath} parameter, and should be autoloaded
(@code{autoload -U compinit} is recommended), and then run simply as
@code{compinit}.  This will define a
few utility functions, arrange for all the necessary shell functions to be
autoloaded, and will then re-define all widgets that do completion to use the
new system.  If you use the @code{menu-select} widget, which is part of the
@code{zsh/complist} module, you should make sure that that module is loaded
before the call to @code{compinit} so that that widget is also
re-defined.  If completion styles (see below) are set up to perform
expansion as well as completion by default, and the TAB key is bound to
@code{expand-or-complete}, @code{compinit} will rebind it to @code{complete-word};
this is necessary to use the correct form of expansion.

Should you need to use the original completion commands, you can still
bind keys to the old widgets by putting a @code{.} in front of the
widget name, e.g. @code{.expand-or-complete}.

To speed up the running of @code{compinit}, it can be made to produce a dumped
configuration that will be read in on future invocations; this is the
default, but can be turned off by calling @code{compinit} with the
option @code{-D}.  The dumped file is @code{.zcompdump} in the same
directory as the startup files (i.e. @code{$ZDOTDIR} or @code{$HOME});
alternatively, an explicit file name can be given by @code{compinit -d}
@var{dumpfile}.  The next invocation of @code{compinit} will read the dumped
file instead of performing a full initialization.

If the number of completion files changes, @code{compinit} will recognise this
and produce a new dump file.  However, if the name of a function or the
arguments in the first line of a @code{#compdef} function (as described below)
change, it is easiest to delete the dump file by hand so that
@code{compinit} will re-create it the next time it is run.  The check
performed to see if there are new functions can be omitted by giving
the option @code{-C}.  In this case the dump file will only be created if
there isn’t one already.  Use option @code{-w} to explain why a dump file
isn’t loaded and/or why it’s regenerated.

The dumping is actually done by another function, @code{compdump}, but you
will only need to run this yourself if you change the configuration
(e.g. using @code{compdef}) and then want to dump the new one.  The name of
the old dumped file will be remembered for this purpose.

If the parameter @code{_compdir} is set, @code{compinit} uses it as a directory
where completion functions can be found; this is only necessary if they are
not already in the function search path.

For security reasons @code{compinit} also checks if the completion system
would use files not owned by root or by the current user, or files in
directories that are world- or group-writable or that are not owned by
root or by the current user.  If such files or directories are found,
@code{compinit} will ask if the completion system should really be used.  To
avoid these tests and make all files found be used without asking, use the
option @code{-u}, and to make @code{compinit} silently ignore all insecure files
and directories use the option @code{-i}.  This security check is skipped
entirely when the @code{-C} option is given, provided the dumpfile exists.

@geindex compaudit; Function

The security check can be retried at any time by running the function
@code{compaudit}.  This is the same check used by @code{compinit}, but when it
is executed directly any changes to @code{fpath} are made local to the
function so they do not persist.  The directories to be checked may be
passed as arguments; if none are given, @code{compaudit} uses @code{fpath} and
@code{_compdir} to find completion system directories, adding missing ones
to @code{fpath} as necessary.  To force a check of exactly the directories
currently named in @code{fpath}, set @code{_compdir} to an empty string before
calling @code{compaudit} or @code{compinit}.

@geindex bashcompinit; Function

The function @code{bashcompinit} provides compatibility with bash’s programmable
completion system.  When run it will define the functions, @code{compgen} and
@code{complete} which correspond to the bash builtins with the same names.
It will then be possible to use completion specifications and functions
written for bash.

@node Autoloaded Files,Functions<2>,Use of compinit,Initialization
@anchor{Zsh/compsys autoloaded-files}@anchor{f3}
@subsection Autoloaded Files


@geindex completion system@comma{} autoloaded functions; Command

The convention for autoloaded functions used in completion is that they
start with an underscore; as already mentioned, the @code{fpath/FPATH}
parameter must contain the directory in which they are stored.  If @code{zsh}
was properly installed on your system, then @code{fpath/FPATH} automatically
contains the required directories for the standard functions.

For incomplete installations, if @code{compinit} does not find enough files
beginning with an underscore (fewer than twenty) in the search path, it
will try to find more by adding the directory @code{_compdir} to the search
path.  If that directory has a subdirectory named @code{Base}, all
subdirectories will be added to the path.  Furthermore, if the subdirectory
@code{Base} has a subdirectory named @code{Core}, @code{compinit} will add all
subdirectories of the subdirectories to the path: this allows
the functions to be in the same format as in the @code{zsh} source
distribution.

@geindex compdef@comma{} use of by compinit; Command

When @code{compinit} is run, it searches all such files accessible via
@code{fpath/FPATH} and reads the first line of each of them.  This line should
contain one of the tags described below.  Files whose first line does not
start with one of these tags are not considered to be part of the
completion system and will not be treated specially.

The tags are:

@code{#compdef} @var{name} … [ @code{-@{p|P}@} @var{pattern} … [ @code{-N} @var{name} … ] ]

@quotation

The file will be made autoloadable and the function defined
in it will be called when completing @var{name}s, each of which is
either the name of a command whose arguments are to be completed or one of
a number of special contexts in the form @code{-}@var{context}@code{-} described
below.

Each @var{name} may also be of the form @var{cmd}@code{=}@var{service}.
When completing the command @var{cmd}, the function typically behaves as
if the command (or special context) @var{service} was being completed
instead.  This provides a way of altering the behaviour of functions
that can perform many different completions.  It is implemented
by setting the parameter @code{$service} when calling the function;
the function may choose to interpret this how it wishes, and simpler
functions will probably ignore it.

If the @code{#compdef} line contains one of the options @code{-p} or @code{-P},
the words following are taken to be patterns.  The function will be
called when completion is attempted for a command or context that matches
one of the patterns.  The options @code{-p} and @code{-P} are used to specify
patterns to be tried before or after other completions respectively.
Hence @code{-P} may be used to specify default actions.

The option @code{-N} is used after a list following @code{-p} or @code{-P}; it
specifies that remaining words no longer define patterns.  It is
possible to toggle between the three options as many times as necessary.
@end quotation

@code{#compdef -k} @var{style key-sequence} …

@quotation

This option creates a widget behaving like the
builtin widget @var{style} and binds it to the given @var{key-sequence}s,
if any.  The @var{style} must be one of the builtin widgets that perform
completion, namely @code{complete-word}, @code{delete-char-or-list},
@code{expand-or-complete}, @code{expand-or-complete-prefix}, @code{list-choices},
@code{menu-complete}, @code{menu-expand-or-complete}, or
@code{reverse-menu-complete}.  If the @code{zsh/complist} module is loaded (see
@ref{f4,,The zsh/complist Module})
the widget @code{menu-select} is also available.

When one of the @var{key-sequence}s is typed, the function in the file will
be invoked to generate the matches.  Note that a key will not be re-bound
if it already was (that is, was bound to something other than
@code{undefined-key}).  The widget created has the same name as the file and
can be bound to any other keys using @code{bindkey} as usual.
@end quotation

@code{#compdef -K} @var{widget-name} @var{style} @var{key-sequence} [ @var{name} @var{style} @var{seq} … ]

@quotation

This is similar to @code{-k} except that only one @var{key-sequence}
argument may be given for each @var{widget-name} @var{style} pair.
However, the entire set of three arguments may be repeated with a
different set of arguments.  Note in particular that the
@var{widget-name} must be distinct in each set.  If it does not begin with
@code{_} this will be added.  The @var{widget-name} should not clash with
the name of any existing widget: names based on the name of the function
are most useful.  For example,

@example
 #compdef -K _foo_complete complete-word "^X^C" \
   _foo_list list-choices "^X^D"
@end example

(all on one line) defines a widget @code{_foo_complete} for completion, bound
to @code{^X^C}, and a widget @code{_foo_list} for listing, bound to @code{^X^D}.
@end quotation

@code{#autoload} [ @var{options} ]

@quotation

Functions with the @code{#autoload} tag are marked for autoloading but
are not otherwise treated specially.  Typically they are to be called
from within one of the completion functions.  Any @var{options} supplied
will be passed to the @code{autoload} builtin; a typical use is @code{+X} to
force the function to be loaded immediately.  Note that the @code{-U} and
@code{-z} flags are always added implicitly.
@end quotation

The @code{#} is part of the tag name and no white space is allowed after it.
The @code{#compdef} tags use the @code{compdef} function described below; the
main difference is that the name of the function is supplied implicitly.

The special contexts for which completion functions can be defined are:

@geindex -array-value-@comma{} completion context; Keystroke

@code{-array-value-}

@quotation

The right hand side of an array-assignment
(@var{name}@code{=(}@var{…}@code{)})
@end quotation

@geindex -assign-parameter-@comma{} completion context; Keystroke

@code{-assign-parameter-}

@quotation

The name of a parameter in an assignment, i.e. on the left hand side of
an @code{=}
@end quotation

@geindex -brace-parameter-@comma{} completion context; Keystroke

@code{-brace-parameter-}

@quotation

The name of a parameter expansion within braces (@code{$@{}@var{…}@code{@}})
@end quotation

@geindex -command-@comma{} completion context; Keystroke

@code{-command-}

@quotation

A word in command position
@end quotation

@geindex -condition-@comma{} completion context; Keystroke

@code{-condition-}

@quotation

A word inside a condition (@code{[[}@var{…}@code{]]})
@end quotation

@geindex -default-@comma{} completion context; Keystroke

@code{-default-}

@quotation

Any word for which no other completion is defined
@end quotation

@geindex -equal-@comma{} completion context; Keystroke

@code{-equal-}

@quotation

A word beginning with an equals sign
@end quotation

@geindex -first-@comma{} completion context; Keystroke

@code{-first-}

@quotation

This is tried before any other completion function.  The function called
may set the @code{_compskip} parameter to one of various values:
@code{all}: no further completion is attempted; a string
containing the substring @code{patterns}: no pattern completion functions
will be called; a string containing @code{default}: the
function for the @code{-default-} context will not be called, but
functions defined for commands will be.
@end quotation

@geindex -math-@comma{} completion context; Keystroke

@code{-math-}

@quotation

Inside mathematical contexts, such as
@code{((}@var{…}@code{))}
@end quotation

@geindex -parameter-@comma{} completion context; Keystroke

@code{-parameter-}

@quotation

The name of a parameter expansion (@code{$}@var{…})
@end quotation

@geindex -redirect-@comma{} completion context; Keystroke

@code{-redirect-}

@quotation

The word after a redirection operator.
@end quotation

@geindex -subscript-@comma{} completion context; Keystroke

@code{-subscript-}

@quotation

The contents of a parameter subscript.
@end quotation

@geindex -tilde-@comma{} completion context; Keystroke

@code{-tilde-}

@quotation

After an initial tilde (@code{~}), but before the first slash
in the word.
@end quotation

@geindex -value-@comma{} completion context; Keystroke

@code{-value-}

@quotation

On the right hand side of an assignment.
@end quotation

Default implementations are supplied for each of these
contexts.  In most cases the context @code{-}@var{context}@code{-} is
implemented by a corresponding function @code{_}@var{context}, for example
the context @code{-tilde-} and the function @code{_tilde}).

The contexts @code{-redirect-} and @code{-value-} allow extra context-specific
information.  (Internally, this is handled by the functions for each
context calling the function @code{_dispatch}.)  The extra
information is added separated by commas.

For the @code{-redirect-} context, the extra information is in the form
@code{-redirect-,}@var{op}@code{,}@var{command}, where @var{op} is the
redirection operator and @var{command} is the name of the command on
the line.  If there is no command on the line yet, the @var{command}
field will be empty.

For the @code{-value-} context, the form is
@code{-value-,}@var{name}@code{,}@var{command}, where @var{name} is the name of
the parameter on the left hand side of the assignment.
In the case of elements of an associative array, for
example @code{assoc=(key <TAB>}, @var{name} is expanded to
@var{name}@code{-}@var{key}.  In certain special contexts, such as
completing after @code{make CFLAGS=}, the @var{command} part gives the
name of the command, here @code{make}; otherwise it is empty.

It is not necessary to define fully specific completions as the
functions provided will try to generate completions by progressively
replacing the elements with @code{-default-}.  For example, when
completing after @code{foo=<TAB>}, @code{_value} will try the names
@code{-value-,foo,} (note the empty @var{command} part),
@code{-value-,foo,-default-} andtt(-value-,-default-,-default-), in
that order, until it finds a function to handle the context.

As an example:

@example
 compdef '_files -g "*.log"' '-redirect-,2>,-default-'
@end example

completes files matching @code{*.log} after @code{2> <TAB>} for any
command with no more specific handler defined.

Also:

@example
 compdef _foo -value-,-default-,-default-
@end example

specifies that @code{_foo} provides completions for the values of
parameters for which no special function has been defined.  This is
usually handled by the function @code{_value} itself.

The same lookup rules are used when looking up styles (as described
below); for example

@example
 zstyle ':completion:*:*:-redirect-,2>,*:*' file-patterns '*.log'
@end example

is another way to make completion after @code{2> <TAB>} complete files
matching @code{*.log}.

@node Functions<2>,,Autoloaded Files,Initialization
@anchor{Zsh/compsys functions}@anchor{f5}
@subsection Functions


The following function is defined by @code{compinit} and may be called
directly.

@geindex compdef; Function

@geindex completion system@comma{} adding definitions; Command

@code{compdef} [ @code{-ane} ] @var{function name} … [ @code{-@{p|P}@} @var{pattern} … [ @code{-N} @var{name} …]]

@code{compdef -d} @var{name} …

@code{compdef -k} [ @code{-an} ] @var{function style key-sequence} [ @var{key-sequence} … ]

@code{compdef -K} [ @code{-an} ] @var{function name style key-seq} [ @var{name style seq} … ]

@quotation

The first form defines the @var{function} to call for completion in the
given contexts as described for the @code{#compdef} tag above.

Alternatively, all the arguments may have the form
@var{cmd}@code{=}@var{service}.  Here @var{service} should already have been
defined by @var{cmd1}@code{=}@var{service} lines in @code{#compdef} files, as
described above.  The argument for @var{cmd} will be completed in the
same way as @var{service}.

The @var{function} argument may alternatively be a string containing
almost any shell code.  If the string contains an equal sign, the above
will take precedence.  The option @code{-e} may be used to specify the first
argument is to be evaluated as shell code even if it contains an equal
sign.  The string will be executed using the @code{eval} builtin command to
generate completions.  This provides a way of avoiding having to define
a new completion function.  For example, to complete files ending in
@code{.h} as arguments to the command @code{foo}:

@example
 compdef '_files -g "*.h"' foo
@end example

The option @code{-n} prevents any completions already defined for the
command or context from being overwritten.

The option @code{-d} deletes any completion defined for the command or
contexts listed.

The @var{name}s may also contain @code{-p}, @code{-P} and @code{-N} options as
described for the @code{#compdef} tag.  The effect on the argument list is
identical, switching between definitions of patterns tried initially,
patterns tried finally, and normal commands and contexts.

The parameter @code{$_compskip} may be set by any function defined for a
pattern context.  If it is set to a value containing the substring
@code{patterns} none of the pattern-functions will be called; if it is
set to a value containing the substring @code{all}, no other function
will be called.  Setting @code{$_compskip} in this manner is of particular
utility when using the @code{-p} option, as otherwise the dispatcher will
move on to additional functions (likely the default one) after calling
the pattern-context one, which can mangle the display of completion
possibilities if not handled properly.

The form with @code{-k} defines a widget with the same name as the @var{function}
that will be called for each of the @var{key-sequence}s; this is like the
@code{#compdef -k} tag.  The function should generate the completions needed
and will otherwise behave like the builtin widget whose name is given as
the @var{style} argument.  The widgets usable for this are:
@code{complete-word}, @code{delete-char-or-list}, @code{expand-or-complete},
@code{expand-or-complete-prefix}, @code{list-choices}, @code{menu-complete},
@code{menu-expand-or-complete}, and @code{reverse-menu-complete}, as well as
@code{menu-select} if the @code{zsh/complist} module is loaded.  The option @code{-n}
prevents the key being bound if it is already to bound to something other
than @code{undefined-key}.

The form with @code{-K} is similar and defines multiple widgets based on the
same @var{function}, each of which requires the set of three arguments
@var{name}, @var{style} and @var{key-seq}uence, where the latter two are as
for @code{-k} and the first must be a unique widget name beginning with an
underscore.

Wherever applicable, the @code{-a} option makes the @var{function}
autoloadable, equivalent to @code{autoload -U} @var{function}.
@end quotation

The function @code{compdef} can be used to associate existing completion
functions with new commands.  For example,

@example
 compdef _pids foo
@end example

uses the function @code{_pids} to complete process IDs for the command @code{foo}.

Note also the @code{_gnu_generic} function described below, which can be
used to complete options for commands that understand the
@code{--help} option.

@c historic nodename: Completion System Configuration

@node Completion System Configuration,Control Functions,Initialization,Completion System
@anchor{Zsh/compsys completion-system-configuration}@anchor{f1}
@section Completion System Configuration


@geindex completion system@comma{} configuration; Command

This section gives a short overview of how the completion system works,
and then more detail on how users can configure how and when matches are
generated.

@menu
* Overview: Overview<2>. 
* Standard Tags:: 
* Standard Styles:: 

@end menu

@node Overview<2>,Standard Tags,,Completion System Configuration
@anchor{Zsh/compsys overview}@anchor{f6}
@subsection Overview


When completion is attempted somewhere on the command line the
completion system begins building the context.  The context represents
everything that the shell knows about the meaning of the command line
and the significance of the cursor position.  This takes account of a
number of things including the command word (such as @code{grep} or
@code{zsh}) and options to which the current word may be an argument
(such as the @code{-o} option to @code{zsh} which takes a shell option as an
argument).

The context starts out very generic (“we are beginning a completion”)
and becomes more specific as more is learned (“the current word is in a
position that is usually a command name” or “the current word might be a
variable name” and so on).  Therefore the context will vary during the
same call to the completion system.

This context information is condensed into a string consisting of multiple
fields separated by colons, referred to simply as `the context’ in the
remainder of the documentation.  Note that a user of the completion system
rarely needs to compose a context string, unless for example a new
function is being written to perform completion for a new command.  What a
user may need to do is compose a `style' pattern, which is matched
against a context when needed to look up context-sensitive options that
configure the completion system.

The next few paragraphs explain how a context is composed within the
completion function suite.  Following that is discussion of how `styles'
are defined.  Styles determine such things as how the matches are
generated, similarly to shell options but with much more control.  They
are defined with the @code{zstyle} builtin command
(see @ref{ca,,The zsh/zutil Module}).

The context string always consists of a fixed set of fields, separated
by colons and with a leading colon before the first.  Fields which are
not yet known are left empty, but the surrounding colons appear anyway.
The fields are always in the order
@code{:completion:}@var{function}@code{:}@var{completer}@code{:}@var{command}@code{:}@var{argument}@code{:}@var{tag}.  These have the following meaning:

@quotation


@itemize *

@item 
The literal string @code{completion}, saying that this style is used by
@end itemize

the completion system.  This distinguishes the context from those used
by, for example, zle widgets and ZFTP functions.


@itemize *

@item 
The @var{function}, if completion is called from a named widget rather
@end itemize

than through the normal completion system.  Typically this is blank, but
it is set by special widgets such as @code{predict-on} and the various
functions in the @code{Widget} directory of the distribution to the name of
that function, often in an abbreviated form.


@itemize *

@item 
The @var{completer} currently active, the name of the function without the
@end itemize

leading underscore and with other underscores converted to hyphens.  A
`completer’ is in overall control of how completion is to be performed;
@code{complete} is the simplest, but other completers exist to perform
related tasks such as correction, or to modify the behaviour of a later
completer.  See @ref{f7,,Control Functions} for more information.


@itemize *

@item 
The @var{command} or a special @code{-}@var{context}@code{-}, just at it appears
@end itemize

following the @code{#compdef} tag or the @code{compdef} function.  Completion
functions for commands that have sub-commands usually modify this field
to contain the name of the command followed by a minus sign and the
sub-command.  For example, the completion function for the @code{cvs}
command sets this field to @code{cvs-add} when completing arguments to
the @code{add} subcommand.


@itemize *

@item 
The @var{argument}; this indicates which command line or option argument
@end itemize

we are completing.  For command arguments this generally takes the form
@code{argument-}@var{n}, where @var{n} is the number of the argument,
and for arguments to options the form @code{option-}@var{opt}@code{-}@var{n}
where @var{n} is the number of the argument to option @var{opt}.  However,
this is only the case if the command line is parsed with standard
UNIX-style options and arguments, so many completions do not set this.


@itemize *

@item 
The @var{tag}.  As described previously, tags are used to discriminate between
@end itemize

the types of matches a completion function can generate in a certain context.
Any completion function may use any tag name it likes, but a list of the
more common ones is given below.
@end quotation

The context is gradually put together as the functions are executed, starting
with the main entry point, which adds @code{:completion:} and the @var{function}
element if necessary.  The completer then adds the @var{completer} element.
The contextual completion adds the @var{command} and @var{argument} options.
Finally, the @var{tag} is added when the types of completion are known.
For example, the context name

@example
 :completion::complete:dvips:option-o-1:files
@end example

says that normal completion was attempted as the first argument to the
option @code{-o} of the command @code{dvips}:

@example
 dvips -o ...
@end example

and the completion function will generate filenames.

Usually completion will be tried for all possible tags in an order given
by the completion function.  However, this can be altered by using the
@code{tag-order} style.  Completion is then restricted to the list of given
tags in the given order.

The @code{_complete_help} bindable command shows all the contexts and tags
available for completion at a particular point.  This provides an easy
way of finding information for @code{tag-order} and other styles.  It is
described in @ref{f8,,Bindable Commands}.

When looking up styles the completion system uses full context names,
including the tag.  Looking up the value of a style therefore consists of
two things: the context, which is matched to the most specific (best
fitting) pattern, and the name of the style itself, which must be
matched exactly.  The following examples demonstrate that patterns
may be loosely defined for styles that apply broadly, or as tightly
defined as desired for styles that apply in narrower circumstances.

For example, many completion functions can generate matches in a
simple and a verbose form and use the @code{verbose} style to decide
which form should be used.  To make all such functions use the verbose form,
put

@example
 zstyle ':completion:*' verbose yes
@end example

in a startup file (probably @code{.zshrc}).
This gives the @code{verbose} style the value @code{yes} in every
context inside the completion system, unless that context has a more
specific definition.  It is best to avoid giving the pattern as @code{*}
in case the style has some meaning outside the completion system.

Many such general purpose styles can be configured simply by using the
@code{compinstall} function.

A more specific example of the use of the @code{verbose} style is by the
completion for the @code{kill} builtin.  If the style is set, the builtin
lists full job texts and process command lines; otherwise it shows the
bare job numbers and PIDs.  To turn the style off for this use only:

@example
 zstyle ':completion:*:*:kill:*:*' verbose no
@end example

For even more control, the style can use one of the tags @code{jobs} or
@code{processes}.  To turn off verbose display only for jobs:

@example
 zstyle ':completion:*:*:kill:*:jobs' verbose no
@end example

The @code{-e} option to @code{zstyle} even allows completion function code to
appear as the argument to a style; this requires some understanding of
the internals of completion functions (see
@code{zshcompwid}).  For example,

@example
 zstyle -e ':completion:*' hosts 'reply=($myhosts)'
@end example

This forces the value of the @code{hosts} style to be read from the
variable @code{myhosts} each time a host name is needed; this is useful
if the value of @code{myhosts} can change dynamically.
For another useful example, see the example in the description of the
@code{file-list} style below.  This form can be
slow and should be avoided for commonly examined styles such
as @code{menu} and @code{list-rows-first}.

Note that the order in which styles are `defined' does not matter; the
style mechanism uses the most specific possible match for a particular
style to determine the set of values.  Strings are
preferred over patterns (for example, @code{:completion::complete:::foo} is
more specific than @code{:completion::complete:::*}), and longer patterns are
preferred over the pattern @code{*}.  See
@ref{ca,,The zsh/zutil Module} for details.

Context patterns that use something other than a wildcard (@code{*}) to match the
middle parts of the context – the @var{completer}, @var{command}, and
@var{argument} in
@code{:completion:}@var{function}@code{:}@var{completer}@code{:}@var{command}@code{:}@var{argument}@code{:}@var{tag}
– should include all six colons (@code{:}) explicitly. Without this,
a pattern such as @code{:completion:*:foo:*} could match @code{foo} against a
component other than the intended one (for example, against @var{completer} when
a match against @var{command} was intended).

Style names like those of tags are arbitrary and depend on the completion
function.  However, the following two sections list some of the most
common tags and styles.

@node Standard Tags,Standard Styles,Overview<2>,Completion System Configuration
@anchor{Zsh/compsys standard-tags}@anchor{f9}
@subsection Standard Tags


@geindex completion system@comma{} tags; Command

Some of the following are only used when looking up particular styles
and do not refer to a type of match.

@geindex accounts@comma{} completion tag; Keystroke

@code{accounts}

@quotation

used to look up the @code{users-hosts} style
@end quotation

@geindex all-expansions@comma{} completion tag; Keystroke

@code{all-expansions}

@quotation

used by the @code{_expand} completer when adding the single string containing
all possible expansions
@end quotation

@geindex all-files@comma{} completion tag; Keystroke

@code{all-files}

@quotation

for the names of all files (as distinct from a particular subset, see the
@code{globbed-files} tag).
@end quotation

@geindex arguments@comma{} completion tag; Keystroke

@code{arguments}

@quotation

for arguments to a command
@end quotation

@geindex arrays@comma{} completion tag; Keystroke

@code{arrays}

@quotation

for names of array parameters
@end quotation

@geindex association-keys@comma{} completion tag; Keystroke

@code{association-keys}

@quotation

for keys of associative arrays; used when completing inside a
subscript to a parameter of this type
@end quotation

@geindex bookmarks@comma{} completion tag; Keystroke

@code{bookmarks}

@quotation

when completing bookmarks (e.g. for URLs and the @code{zftp} function suite)
@end quotation

@geindex builtins@comma{} completion tag; Keystroke

@code{builtins}

@quotation

for names of builtin commands
@end quotation

@geindex characters@comma{} completion tag; Keystroke

@code{characters}

@quotation

for single characters in arguments of commands such as @code{stty}.   Also used
when completing character classes after an opening bracket
@end quotation

@geindex colormapids@comma{} completion tag; Keystroke

@code{colormapids}

@quotation

for X colormap ids
@end quotation

@geindex colors@comma{} completion tag; Keystroke

@code{colors}

@quotation

for color names
@end quotation

@geindex commands@comma{} completion tag; Keystroke

@code{commands}

@quotation

for names of external commands.  Also used by complex commands such as
@code{cvs} when completing names of subcommands.
@end quotation

@geindex contexts@comma{} completion tag; Keystroke

@code{contexts}

@quotation

for contexts in arguments to the @code{zstyle} builtin command
@end quotation

@geindex corrections@comma{} completion tag; Keystroke

@code{corrections}

@quotation

used by the @code{_approximate} and @code{_correct} completers for possible
corrections
@end quotation

@geindex cursors@comma{} completion tag; Keystroke

@code{cursors}

@quotation

for cursor names used by X programs
@end quotation

@geindex default@comma{} completion tag; Keystroke

@code{default}

@quotation

used in some contexts to provide a way of supplying a default when more
specific tags are also valid.  Note that this tag is
used when only the @var{function} field of the context name is set
@end quotation

@geindex descriptions@comma{} completion tag; Keystroke

@code{descriptions}

@quotation

used when looking up the value of the @code{format} style to generate
descriptions for types of matches
@end quotation

@geindex devices@comma{} completion tag; Keystroke

@code{devices}

@quotation

for names of device special files
@end quotation

@geindex directories@comma{} completion tag; Keystroke

@code{directories}

@quotation

for names of directories – @code{local-directories} is used instead
when completing arguments of @code{cd} and related builtin commands when
the @code{cdpath} array is set
@end quotation

@geindex directory-stack@comma{} completion tag; Keystroke

@code{directory-stack}

@quotation

for entries in the directory stack
@end quotation

@geindex displays@comma{} completion tag; Keystroke

@code{displays}

@quotation

for X display names
@end quotation

@geindex domains@comma{} completion tag; Keystroke

@code{domains}

@quotation

for network domains
@end quotation

@geindex email-*@comma{} completion tag; Keystroke

@code{email-}@var{plugin}

@quotation

for email addresses from the @code{_email-}@var{plugin} backend of @code{_email_addresses}
@end quotation

@geindex expansions@comma{} completion tag; Keystroke

@code{expansions}

@quotation

used by the @code{_expand} completer for individual words (as opposed to
the complete set of expansions) resulting from the expansion of a word
on the command line
@end quotation

@geindex extensions@comma{} completion tag; Keystroke

@code{extensions}

@quotation

for X server extensions
@end quotation

@geindex file-descriptors@comma{} completion tag; Keystroke

@code{file-descriptors}

@quotation

for numbers of open file descriptors
@end quotation

@geindex files@comma{} completion tag; Keystroke

@code{files}

@quotation

the generic file-matching tag used by functions completing filenames
@end quotation

@geindex fonts@comma{} completion tag; Keystroke

@code{fonts}

@quotation

for X font names
@end quotation

@geindex fstypes@comma{} completion tag; Keystroke

@code{fstypes}

@quotation

for file system types (e.g. for the @code{mount} command)
@end quotation

@geindex functions@comma{} completion tag; Keystroke

@code{functions}

@quotation

names of functions – normally shell functions, although certain
commands may understand other kinds of function
@end quotation

@geindex globbed-files@comma{} completion tag; Keystroke

@code{globbed-files}

@quotation

for filenames when the name has been generated by pattern matching
@end quotation

@geindex groups@comma{} completion tag; Keystroke

@code{groups}

@quotation

for names of user groups
@end quotation

@geindex history-words@comma{} completion tag; Keystroke

@code{history-words}

@quotation

for words from the history
@end quotation

@geindex hosts@comma{} completion tag; Keystroke

@code{hosts}

@quotation

for hostnames
@end quotation

@geindex indexes@comma{} completion tag; Keystroke

@code{indexes}

@quotation

for array indexes
@end quotation

@geindex interfaces@comma{} completion tag; Keystroke

@code{interfaces}

@quotation

for network interfaces
@end quotation

@geindex jobs@comma{} completion tag; Keystroke

@code{jobs}

@quotation

for jobs (as listed by the @code{jobs} builtin)
@end quotation

@geindex keymaps@comma{} completion tag; Keystroke

@code{keymaps}

@quotation

for names of zsh keymaps
@end quotation

@geindex keysyms@comma{} completion tag; Keystroke

@code{keysyms}

@quotation

for names of X keysyms
@end quotation

@geindex libraries@comma{} completion tag; Keystroke

@code{libraries}

@quotation

for names of system libraries
@end quotation

@geindex limits@comma{} completion tag; Keystroke

@code{limits}

@quotation

for system limits
@end quotation

@geindex local-directories@comma{} completion tag; Keystroke

@code{local-directories}

@quotation

for names of directories that are subdirectories of the current working
directory when completing arguments of @code{cd} and related builtin
commands (compare @code{path-directories}) – when the @code{cdpath}
array is unset, @code{directories} is used instead
@end quotation

@geindex mailboxes@comma{} completion tag; Keystroke

@code{mailboxes}

@quotation

for e-mail folders
@end quotation

@geindex manuals@comma{} completion tag; Keystroke

@code{manuals}

@quotation

for names of manual pages
@end quotation

@geindex maps@comma{} completion tag; Keystroke

@code{maps}

@quotation

for map names (e.g. NIS maps)
@end quotation

@geindex messages@comma{} completion tag; Keystroke

@code{messages}

@quotation

used to look up the @code{format} style for messages
@end quotation

@geindex modifiers@comma{} completion tag; Keystroke

@code{modifiers}

@quotation

for names of X modifiers
@end quotation

@geindex modules@comma{} completion tag; Keystroke

@code{modules}

@quotation

for modules (e.g. @code{zsh} modules)
@end quotation

@geindex my-accounts@comma{} completion tag; Keystroke

@code{my-accounts}

@quotation

used to look up the @code{users-hosts} style
@end quotation

@geindex named-directories@comma{} completion tag; Keystroke

@code{named-directories}

@quotation

for named directories (you wouldn’t have guessed that, would you?)
@end quotation

@geindex names@comma{} completion tag; Keystroke

@code{names}

@quotation

for all kinds of names
@end quotation

@geindex newsgroups@comma{} completion tag; Keystroke

@code{newsgroups}

@quotation

for USENET groups
@end quotation

@geindex nicknames@comma{} completion tag; Keystroke

@code{nicknames}

@quotation

for nicknames of NIS maps
@end quotation

@geindex options@comma{} completion tag; Keystroke

@code{options}

@quotation

for command options
@end quotation

@geindex original@comma{} completion tag; Keystroke

@code{original}

@quotation

used by the @code{_approximate}, @code{_correct} and @code{_expand} completers when
offering the original string as a match
@end quotation

@geindex other-accounts@comma{} completion tag; Keystroke

@code{other-accounts}

@quotation

used to look up the @code{users-hosts} style
@end quotation

@geindex packages@comma{} completion tag; Keystroke

@code{packages}

@quotation

for packages (e.g. @code{rpm} or installed @code{Debian} packages)
@end quotation

@geindex parameters@comma{} completion tag; Keystroke

@code{parameters}

@quotation

for names of parameters
@end quotation

@geindex path-directories@comma{} completion tag; Keystroke

@code{path-directories}

@quotation

for names of directories found by searching the @code{cdpath} array when
completing arguments of @code{cd} and related builtin commands (compare
@code{local-directories})
@end quotation

@geindex paths@comma{} completion tag; Keystroke

@code{paths}

@quotation

used to look up the values of the @code{expand}, @code{ambiguous} and
@code{special-dirs} styles
@end quotation

@geindex pods@comma{} completion tag; Keystroke

@code{pods}

@quotation

for perl pods (documentation files)
@end quotation

@geindex ports@comma{} completion tag; Keystroke

@code{ports}

@quotation

for communication ports
@end quotation

@geindex prefixes@comma{} completion tag; Keystroke

@code{prefixes}

@quotation

for prefixes (like those of a URL)
@end quotation

@geindex printers@comma{} completion tag; Keystroke

@code{printers}

@quotation

for print queue names
@end quotation

@geindex processes@comma{} completion tag; Keystroke

@code{processes}

@quotation

for process identifiers
@end quotation

@geindex processes-names@comma{} completion tag; Keystroke

@code{processes-names}

@quotation

used to look up the @code{command} style when generating the names of
processes for @code{killall}
@end quotation

@geindex sequences@comma{} completion tag; Keystroke

@code{sequences}

@quotation

for sequences (e.g. @code{mh} sequences)
@end quotation

@geindex sessions@comma{} completion tag; Keystroke

@code{sessions}

@quotation

for sessions in the @code{zftp} function suite
@end quotation

@geindex signals@comma{} completion tag; Keystroke

@code{signals}

@quotation

for signal names
@end quotation

@geindex strings@comma{} completion tag; Keystroke

@code{strings}

@quotation

for strings (e.g. the replacement strings for the @code{cd} builtin
command)
@end quotation

@geindex styles@comma{} completion tag; Keystroke

@code{styles}

@quotation

for styles used by the zstyle builtin command
@end quotation

@geindex suffixes@comma{} completion tag; Keystroke

@code{suffixes}

@quotation

for filename extensions
@end quotation

@geindex tags@comma{} completion tag; Keystroke

@code{tags}

@quotation

for tags (e.g. @code{rpm} tags)
@end quotation

@geindex targets@comma{} completion tag; Keystroke

@code{targets}

@quotation

for makefile targets
@end quotation

@geindex time-zones@comma{} completion tag; Keystroke

@code{time-zones}

@quotation

for time zones (e.g. when setting the @code{TZ} parameter)
@end quotation

@geindex types@comma{} completion tag; Keystroke

@code{types}

@quotation

for types of whatever (e.g. address types for the @code{xhost} command)
@end quotation

@geindex urls@comma{} completion tag; Keystroke

@code{urls}

@quotation

used to look up the @code{urls} and @code{local} styles when completing URLs
@end quotation

@geindex users@comma{} completion tag; Keystroke

@code{users}

@quotation

for usernames
@end quotation

@geindex values@comma{} completion tag; Keystroke

@code{values}

@quotation

for one of a set of values in certain lists
@end quotation

@geindex variant@comma{} completion tag; Keystroke

@code{variant}

@quotation

used by @code{_pick_variant} to look up the command to run when determining
what program is installed for a particular command name.
@end quotation

@geindex visuals@comma{} completion tag; Keystroke

@code{visuals}

@quotation

for X visuals
@end quotation

@geindex warnings@comma{} completion tag; Keystroke

@code{warnings}

@quotation

used to look up the @code{format} style for warnings
@end quotation

@geindex widgets@comma{} completion tag; Keystroke

@code{widgets}

@quotation

for zsh widget names
@end quotation

@geindex windows@comma{} completion tag; Keystroke

@code{windows}

@quotation

for IDs of X windows
@end quotation

@geindex zsh-options@comma{} completion tag; Keystroke

@code{zsh-options}

@quotation

for shell options
@end quotation

@node Standard Styles,,Standard Tags,Completion System Configuration
@anchor{Zsh/compsys id1}@anchor{fa}@anchor{Zsh/compsys standard-styles}@anchor{e9}
@subsection Standard Styles


@geindex completion system@comma{} styles; Command

Note that the values of several of these styles represent boolean
values.  Any of the strings @code{true}, @code{on},
@code{yes}, and @code{1} can be used for the value `true’ and
any of the strings @code{false}, @code{off}, @code{no}, and @code{0} for
the value `false’.  The behavior for any other value is undefined
except where explicitly mentioned.  The default value may
be either `true’ or `false’ if the style is not set.

Some of these styles are tested first for every possible tag
corresponding to a type of match, and if no style was found, for the
@code{default} tag.  The most notable styles of this type are @code{menu},
@code{list-colors} and styles controlling completion listing such as
@code{list-packed} and @code{last-prompt}.  When tested for the @code{default}
tag, only the @var{function} field of the context will be set so that
a style using the @code{default} tag will normally be defined along the lines of:

@example
 zstyle ':completion:*:default' menu ...
@end example

@geindex accept-exact@comma{} completion style; Keystroke

@code{accept-exact}

@quotation

This is tested for the @code{default} tag in addition to the tags valid for
the current context.  If it is set to `true’ and any of the trial
matches is the same as the string on the command line, this match will
immediately be accepted (even if it would otherwise be considered
ambiguous).

When completing pathnames (where the tag used is @code{paths})
this style accepts any number of patterns as the value in addition to
the boolean values.  Pathnames matching one of these
patterns will be accepted immediately even if the command line contains
some more partially typed pathname components and these match no file
under the directory accepted.

This style is also used by the @code{_expand} completer to decide if
words beginning with a tilde or parameter expansion should be
expanded.  For example, if there are parameters
@code{foo} and @code{foobar}, the string @code{$foo} will only be expanded if
@code{accept-exact} is set to `true’; otherwise the completion system will
be allowed to complete @code{$foo} to @code{$foobar}. If the style is set to
@code{continue}, @code{_expand} will add the expansion as a match and the completion
system will also be allowed to continue.
@end quotation

@geindex accept-exact-dirs@comma{} completion style; Keystroke

@code{accept-exact-dirs}

@quotation

This is used by filename completion.  Unlike @code{accept-exact} it is
a boolean.  By default, filename completion examines all components
of a path to see if there are completions of that component, even if
the component matches an existing directory.  For example, when
completion after @code{/usr/bin/}, the function examines possible
completions to @code{/usr}.

When this style is `true’, any prefix of a path that matches an existing
directory is accepted without any attempt to complete it further.
Hence, in the given example, the path @code{/usr/bin/} is accepted
immediately and completion tried in that directory.

This style is also useful when completing after directories that
magically appear when referenced, such as ZFS @code{.zfs} directories
or NetApp @code{.snapshot} directories.  When the style is set the
shell does not check for the existence of the directory within the
parent directory.

If you wish to inhibit this behaviour entirely, set the @code{path-completion}
style (see below) to `false’.
@end quotation

@geindex add-space@comma{} completion style; Keystroke

@code{add-space}

@quotation

This style is used by the @code{_expand} completer.  If it is `true’ (the
default), a space will be inserted after all words resulting from the
expansion, or a slash in the case of directory names.  If the value
is @code{file}, the completer will only add a space
to names of existing files.  Either a boolean `true’ or the value
@code{file} may be combined with @code{subst}, in which case the completer
will not add a space to words generated from the expansion of a
substitution of the form @code{$(}@var{…}@code{)} or @code{$@{}@var{…}@code{@}}.

The @code{_prefix} completer uses this style as a simple boolean value
to decide if a space should be inserted before the suffix.
@end quotation

@geindex ambiguous@comma{} completion style; Keystroke

@code{ambiguous}

@quotation

This applies when completing non-final components of filename paths, in
other words those with a trailing slash.  If it is set, the cursor is
left after the first ambiguous component, even if menu completion is in
use.  The style is always tested with the @code{paths} tag.
@end quotation

@geindex assign-list@comma{} completion style; Keystroke

@code{assign-list}

@quotation

When completing after an equals sign that is being treated as an
assignment, the completion system normally completes only one filename.
In some cases the value  may be a list of filenames separated by colons,
as with @code{PATH} and similar parameters.  This style can be set to a
list of patterns matching the names of such parameters.

The default is to complete lists when the word on the line already
contains a colon.
@end quotation

@geindex auto-description@comma{} completion style; Keystroke

@code{auto-description}

@quotation

If set, this style’s value will be used as the description for options that
are not described by the completion functions, but that have exactly
one argument.  The sequence @code{%d} in the value will be replaced by
the description for this argument.  Depending on personal preferences,
it may be useful to set this style to something like @code{specify: %d}.
Note that this may not work for some commands.
@end quotation

@geindex avoid-completer@comma{} completion style; Keystroke

@code{avoid-completer}

@quotation

This is used by the @code{_all_matches} completer to decide if the string
consisting of all matches should be added to the list currently being
generated.  Its value is a list of names of completers.  If any of
these is the name of the completer that generated the matches in this
completion, the string will not be added.

The default value for this style is @code{_expand _oldlist _correct
_approximate}, i.e. it contains the completers for which a string
with all matches will almost never be wanted.
@end quotation

@geindex cache-path@comma{} completion style; Keystroke

@code{cache-path}

@quotation

This style defines the path where any cache files containing dumped
completion data are stored.  It defaults to @code{$ZDOTDIR/.zcompcache}, or
@code{$HOME/.zcompcache} if @code{$ZDOTDIR} is not defined.  The completion
cache will not be used unless the @code{use-cache} style is set.
@end quotation

@geindex cache-policy@comma{} completion style; Keystroke

@code{cache-policy}

@quotation

This style defines the function that will be used to determine whether
a cache needs rebuilding.  See the section on the @code{_cache_invalid}
function below.
@end quotation

@geindex call-command@comma{} completion style; Keystroke

@code{call-command}

@quotation

This style is used in the function for commands such as @code{make} and
@code{ant} where calling the command directly to generate matches suffers
problems such as being slow or, as in the case of @code{make} can
potentially cause actions in the makefile to be executed. If it is set
to `true’ the command is called to generate matches. The default value
of this style is `false’.
@end quotation

@geindex command@comma{} completion style; Keystroke

@code{command}

@quotation

In many places, completion functions need to call external commands to
generate the list of completions.  This style can be used to override the
command that is called in some such cases.  The elements of the value are
joined with spaces to form a command line to execute.  The value can also
start with a hyphen, in which case the usual command will be added to the
end; this is most useful for putting @code{builtin} or @code{command} in
front to make sure the appropriate version of a command is called, for
example to avoid calling a shell function with the same name as an external
command.

As an example, the completion function for process IDs uses this
style with the @code{processes} tag to generate the IDs to complete and
the list of processes to display (if the @code{verbose} style is `true’).
The list produced by the command should look like the output of the
@code{ps} command.  The first line is not displayed, but is searched for
the string @code{PID} (or @code{pid}) to find the position of the
process IDs in the following lines.  If the line does not contain
@code{PID}, the first numbers in each of the other lines are taken as the
process IDs to complete.

Note that the completion function generally has to call the specified
command for each attempt to generate the completion list.  Hence
care should be taken to specify only commands that take a short
time to run, and in particular to avoid any that may never terminate.
@end quotation

@geindex command-path@comma{} completion style; Keystroke

@code{command-path}

@quotation

This is a list of directories to search for commands to complete.  The
default for this style is the value of the special parameter @code{path}.
@end quotation

@geindex commands@comma{} completion style; Keystroke

@code{commands}

@quotation

This is used by the function completing sub-commands for the system
initialisation scripts (residing in @code{/etc/init.d} or somewhere not
too far away from that).  Its values give the default commands to
complete for those commands for which the completion function isn’t
able to find them out automatically.  The default for this style are
the two strings @code{start} and @code{stop}.
@end quotation

@geindex complete@comma{} completion style; Keystroke

@code{complete}

@quotation

This is used by the @code{_expand_alias} function when invoked as a
bindable command.  If set to `true’ and the word on the command
line is not the name of an alias, matching alias names will be
completed.
@end quotation

@geindex complete-options@comma{} completion style; Keystroke

@code{complete-options}

@quotation

This is used by the completer for @code{cd}, @code{chdir} and @code{pushd}.
For these commands a @code{-} is used to introduce a directory stack entry
and completion of these is far more common than completing options.
Hence unless the value of this style is `true’ options will not be
completed, even after an initial @code{-}.  If it is `true’, options will
be completed after an initial @code{-} unless there is a preceding
@code{--} on the command line.
@end quotation

@geindex completer@comma{} completion style; Keystroke

@code{completer}

@quotation

The strings given as the value of this style provide the names of the
completer functions to use. The available completer functions are
described in @ref{f7,,Control Functions}.

Each string may be either the name of a completer function or a string
of the form @var{function}@code{:}@var{name}.  In the first case the
@var{completer} field of the context will contain the name of the
completer without the leading underscore and with all other
underscores replaced by hyphens.  In the second case the
@var{function} is the name of the completer to call, but the context
will contain the user-defined @var{name} in the @var{completer} field of
the context.  If the @var{name} starts with a hyphen, the string for the
context will be build from the name of the completer function as in
the first case with the @var{name} appended to it.  For example:

@example
 zstyle ':completion:*' completer _complete _complete:-foo
@end example

Here, completion will call the @code{_complete} completer twice, once
using @code{complete} and once using @code{complete-foo} in the
@var{completer} field of the context.  Normally, using the same
completer more than once only makes sense when used with the
@var{functions}@code{:}@var{name} form, because otherwise the context
name will be the same in all calls to the completer; possible
exceptions to this rule are the @code{_ignored} and @code{_prefix}
completers.

The default value for this style is @code{_complete _ignored}:
only completion will be done, first using the @code{ignored-patterns} style
and the @code{$fignore} array and then without ignoring matches.
@end quotation

@geindex condition@comma{} completion style; Keystroke

@code{condition}

@quotation

This style is used by the @code{_list} completer function to decide if
insertion of matches should be delayed unconditionally. The default is
`true’.
@end quotation

@geindex delimiters@comma{} completion style; Keystroke

@code{delimiters}

@quotation

This style is used when adding a delimiter for use with history
modifiers or glob qualifiers that have delimited arguments.  It is
an array of preferred delimiters to add.  Non-special characters are
preferred as the completion system may otherwise become confused.
The default list is @code{:}, @code{+}, @code{/}, @code{-}, @code{%}.  The list
may be empty to force a delimiter to be typed.
@end quotation

@geindex disabled@comma{} completion style; Keystroke

@code{disabled}

@quotation

If this is set to `true’, the @code{_expand_alias} completer and bindable
command will try to expand disabled aliases, too.  The default is
`false’.
@end quotation

@geindex domains@comma{} completion style; Keystroke

@code{domains}

@quotation

A list of names of network domains for completion.
If this is not set, domain names will be taken from
the file @code{/etc/resolv.conf}.
@end quotation

@geindex environ@comma{} completion style; Keystroke

@code{environ}

@quotation

The environ style is used when completing for @code{sudo}.  It is set to an
array of @var{VAR}@code{=}@var{value} assignments to be exported into the
local environment before the completion for the target command is invoked.

@example
 zstyle ':completion:*:sudo::' environ \
   PATH="/sbin:/usr/sbin:$PATH" HOME="/root"
@end example
@end quotation

@geindex expand@comma{} completion style; Keystroke

@code{expand}

@quotation

This style is used when completing strings consisting of multiple
parts, such as path names.

If one of its values is the string @code{prefix}, the partially typed
word from the line will be expanded as far as possible even if trailing
parts cannot be completed.

If one of its values is the string @code{suffix}, matching names for
components after the first ambiguous one will also be added.  This means
that the resulting string is the longest unambiguous string possible.
However, menu completion can be used to cycle through all matches.
@end quotation

@geindex extra-verbose@comma{} completion style; Keystroke

@code{extra-verbose}

@quotation

If this style set to `true’, the completion listing is still more verbose.

Currently, it is used for @code{commands} and @code{parameters} tags.
If it is `true’ for the @code{commands} (or @code{parameters}) tag, short
descriptions of the commands (or the values of the parameters) are
displayed along with the command (or parameter) names.
@end quotation

@geindex fake@comma{} completion style; Keystroke

@code{fake}

@quotation

This style may be set for any completion context.  It
specifies additional strings that will always be completed in that
context.  The form of each string is @var{value}@code{:}@var{description};
the colon and description may be omitted, but any literal colons in
@var{value} must be quoted with a backslash.  Any @var{description}
provided is shown alongside the value in completion listings.

It is important to use a sufficiently restrictive context when specifying
fake strings.  Note that the styles @code{fake-files} and @code{fake-parameters}
provide additional features when completing files or parameters.
@end quotation

@geindex fake-always@comma{} completion style; Keystroke

@code{fake-always}

@quotation

This works identically to the @code{fake} style except that
the @code{ignored-patterns} style is not applied to it.  This makes it
possible to override a set of matches completely by setting the
ignored patterns to @code{*}.

The following shows a way of supplementing any tag with arbitrary data, but
having it behave for display purposes like a separate tag.  In this example
we use the features of the @code{tag-order} style to divide the
@code{named-directories} tag into two when performing completion with
the standard completer @code{complete} for arguments of @code{cd}.  The tag
@code{named-directories-normal} behaves as normal, but the tag
@code{named-directories-mine} contains a fixed set of directories.
This has the effect of adding the match group @code{extra directories} with
the given completions.

@example
 zstyle ':completion::complete:cd:*' tag-order \
   'named-directories:-mine:extra\ directories
   named-directories:-normal:named\ directories *'
 zstyle ':completion::complete:cd:*:named-directories-mine' \
   fake-always mydir1 mydir2
 zstyle ':completion::complete:cd:*:named-directories-mine' \
   ignored-patterns '*'
@end example
@end quotation

@geindex fake-files@comma{} completion style; Keystroke

@code{fake-files}

@quotation

This style is used when completing files and looked up
without a tag.  Its values are of the form
@var{dir}@code{:}@var{names…}.  This will add the @var{names} (strings
separated by spaces) as
possible matches when completing in the directory @var{dir}, even if no
such files really exist.  The dir may be a pattern; pattern characters
or colons in @var{dir} should be quoted with a backslash to be treated
literally.

This can be useful on systems that support special file systems whose
top-level pathnames can not be listed or generated with glob patterns
(but see @code{accept-exact-dirs} for a more general way of dealing
with this problem).  It can also be used for directories for which one
does not have read permission.

The pattern form can be used to add a certain `magic’ entry
to all directories on a particular file system.
@end quotation

@geindex fake-parameters@comma{} completion style; Keystroke

@code{fake-parameters}

@quotation

This is used by the completion function for parameter names.
Its values are names of parameters that might not yet be
set but should be completed nonetheless.  Each name may also be
followed by a colon and a string specifying the type of the parameter
(like @code{scalar}, @code{array} or @code{integer}).  If the type is
given, the name will only be completed if parameters of that type are
required in the particular context.  Names for which no type is
specified will always be completed.
@end quotation

@geindex file-list@comma{} completion style; Keystroke

@code{file-list}

@quotation

This style controls whether files completed using the standard builtin
mechanism are to be listed with a long list similar to @code{ls -l}.
Note that this feature uses the shell module
@code{zsh/stat} for file information; this loads the builtin @code{stat}
which will replace any external @code{stat} executable.  To avoid
this the following code can be included in an initialization file:

@example
 zmodload -i zsh/stat
 disable stat
@end example

The style may either be set to a `true’ value (or @code{all}), or
one of the values @code{insert} or @code{list}, indicating that files
are to be listed in long format in all circumstances, or when
attempting to insert a file name, or when listing file names
without attempting to insert one.

More generally, the value may be an array of any of the above values,
optionally followed by @code{=}@var{num}.  If @var{num} is present it
gives the maximum number of matches for which long listing style
will be used.  For example,

@example
 zstyle ':completion:*' file-list list=20 insert=10
@end example

specifies that long format will be used when listing up to 20 files
or inserting a file with up to 10 matches (assuming a listing
is to be shown at all, for example on an ambiguous completion), else short
format will be used.

@example
 zstyle -e ':completion:*' file-list \
        '(( $@{+NUMERIC@} )) && reply=(true)'
@end example

specifies that long format will be used any time a numeric argument is
supplied, else short format.
@end quotation

@geindex file-patterns@comma{} completion style; Keystroke

@code{file-patterns}

@quotation

This is used by the standard function for completing filenames,
@code{_files}.  If the style is unset up to three tags are offered,
@code{globbed-files,directories} and @code{all-files}, depending on
the types of files  expected by the caller of @code{_files}.  The first two
(@code{globbed-files} and @code{directories}) are normally offered
together to make it easier to complete files in sub-directories.

The @code{file-patterns} style provides alternatives to the default tags,
which are not used.  Its value consists of elements of the form
@var{pattern}@code{:}@var{tag}; each string may contain any number of
such specifications separated by spaces.

The @var{pattern} is a pattern that is to be used to generate filenames.
Any occurrence of the sequence @code{%p} is replaced by any
pattern(s)
passed by the function calling @code{_files}.  Colons in the pattern must
be preceded by a backslash to make them distinguishable from the colon
before the @var{tag}.  If more than one pattern is needed, the patterns
can be given inside braces, separated by commas.

The @var{tag}s of all strings in the value will be offered by @code{_files}
and used when looking up other styles.  Any @var{tag}s in the same
word will be offered at the same time and before later words.
If no @code{:}@var{tag} is given the @code{files} tag will be used.

The @var{tag} may also be followed by an optional second colon and a
description, which will be used for the @code{%d} in the value of
the @code{format} style (if that is set) instead of the default
description supplied by the completion function.  The inclusion
of a description also gives precedence to associated options such as
for completion grouping so it can be used where files should be
separated.

For example, to make the @code{rm} command first complete only names of
object files and then the names of all files if there is no matching
object file:

@example
 zstyle ':completion:*:*:rm:*:*' file-patterns \
     '*.o:object-files' '%p:all-files'
@end example

To alter the default behaviour of file completion – offer files
matching a pattern and directories on the first attempt, then all files
– to offer only matching files on the first attempt, then directories,
and finally all files:

@example
 zstyle ':completion:*' file-patterns \
     '%p:globbed-files' '*(-/):directories' '*:all-files'
@end example

This works even where there is no special pattern: @code{_files} matches
all files using the pattern @code{*} at the first step and stops when it
sees this pattern.  Note also it will never try a pattern more than once
for a single completion attempt.

To separate directories into a separate group from the files but still
complete them at the first attempt, a description needs to be given.
Note that directories need to be explicitly excluded from the
globbed-files because @code{*} will match directories. For grouping, it
is also necessary to set the @code{group-name} style.

@example
 zstyle ':completion:*' file-patterns \
     '%p(^-/):globbed-files *(-/):directories:location'
@end example

During the execution of completion functions, the @code{EXTENDED_GLOB}
option is in effect, so the characters @code{#}, @code{~} and @code{^} have
special meanings in the patterns.
@end quotation

@geindex file-sort@comma{} completion style; Keystroke

@code{file-sort}

@quotation

The standard filename completion function uses this style without a tag
to determine in which order the names should be listed; menu completion
will cycle through them in the same order.  The possible
values are: @code{size} to sort by the size of the file;
@code{links} to sort by the number of links to the file;
@code{modification} (or @code{time} or @code{date}) to sort by the last
modification time; @code{access} to sort by the last access time; and
@code{inode} (or @code{change}) to sort by the last inode change
time.  If the style is set to any other value, or is unset, files will be
sorted alphabetically by name.  If the value contains the string
@code{reverse}, sorting is done in the opposite order.  If the value
contains the string @code{follow}, timestamps are associated with the
targets of symbolic links; the default is to use the timestamps
of the links themselves.
@end quotation

@geindex file-split-chars@comma{} completion style; Keystroke

@code{file-split-chars}

@quotation

A set of characters that will cause `all' file completions for
the given context to be split at the point where any of the characters
occurs.  A typical use is to set the style to @code{:}; then everything
up to and including the last @code{:} in the string so far is ignored when
completing files.  As this is quite heavy-handed, it is usually
preferable to update completion functions for contexts where this
behaviour is useful.
@end quotation

@geindex filter@comma{} completion style; Keystroke

@code{filter}

@quotation

The @code{ldap} plugin of email address completion (see @code{_email_addresses}) uses
this style to specify
the attributes to match against when filtering entries.  So for example, if
the style is set to @code{sn}, matching is done against surnames.  Standard
LDAP filtering is used so normal completion matching is bypassed.  If this
style is not set, the LDAP plugin is skipped.  You may also need to set the
@code{command} style to specify how to connect to your LDAP server.
@end quotation

@geindex force-list@comma{} completion style; Keystroke

@code{force-list}

@quotation

This forces a list of completions to be shown at any point where listing is
done, even in cases where the list would usually be suppressed.
For example, normally the list is only shown if
there are at least two different matches.  By setting this style to
@code{always}, the list will always be shown, even if there is only a
single match that will immediately be accepted.  The style may also
be set to a number.  In this case the list will be shown if there are
at least that many matches, even if they would all insert the same
string.

This style is tested for the default tag as well as for each tag valid
for the current completion.  Hence the listing can be forced only for
certain types of match.
@end quotation

@geindex format@comma{} completion style; Keystroke

@code{format}

@quotation

If this is set for the @code{descriptions} tag, its value is used as a
string to display above matches in completion lists.  The sequence
@code{%d} in this string will be replaced with a short description of
what these matches are.  This string may also contain the output
attribute sequences understood by @code{compadd -X}
(see @ref{e7,,Completion Builtin Commands}).

The style is tested with each tag valid for the current completion
before it is tested for the @code{descriptions} tag.  Hence different format
strings can be defined for different types of match.

Note also that some completer functions define additional
@code{%}-sequences.  These are described for the completer functions that
make use of them.

Some completion functions display messages that may be customised by
setting this style for the @code{messages} tag.  Here, the @code{%d} is
replaced with a message given by the completion function.

Finally, the format string is looked up with the @code{warnings} tag,
for use when no matches could be generated at all.  In this case the
@code{%d} is replaced with the descriptions for the matches that were
expected separated by spaces.  The sequence @code{%D} is replaced with
the same descriptions separated by newlines.

It is possible to use printf-style field width specifiers with @code{%d}
and similar escape sequences.  This is handled by the @code{zformat}
builtin command from the @code{zsh/zutil} module, see
@ref{ca,,The zsh/zutil Module}.
@end quotation

@geindex gain-privileges@comma{} completion style; Keystroke

@code{gain-privileges}

@quotation

If set to @code{true}, this style enables the use of commands like @code{sudo}
or @code{doas} to gain extra privileges when retrieving information for
completion. This is only done when a command such as @code{sudo} appears on
the command-line. To force the use of, e.g. @code{sudo} or to override any
prefix that might be added due to @code{gain-privileges}, the @code{command}
style can be used with a value that begins with a hyphen.
@end quotation

@geindex glob@comma{} completion style; Keystroke

@code{glob}

@quotation

This is used by the @code{_expand} completer.  If
it is set to `true’ (the default), globbing will be attempted on the
words resulting from a previous substitution (see the @code{substitute}
style) or else the original string from the line.
@end quotation

@geindex global@comma{} completion style; Keystroke

@code{global}

@quotation

If this is set to `true’ (the default), the @code{_expand_alias}
completer and bindable command will try to expand global aliases.
@end quotation

@geindex group-name@comma{} completion style; Keystroke

@code{group-name}

@quotation

The completion system can group different types of matches, which appear
in separate lists.  This style can be used to give the names of groups
for particular tags.  For example, in command position the completion
system generates names of builtin and external commands, names of
aliases, shell functions and parameters and reserved words as possible
completions.  To have the external commands and shell functions listed
separately:

@example
 zstyle ':completion:*:*:-command-:*:commands' \
        group-name commands
 zstyle ':completion:*:*:-command-:*:functions' \
        group-name functions
@end example

As a consequence, any match with the same tag will be displayed in the
same group.

If the name given is the empty string the name of the tag for
the matches will be used as the name of the group.  So, to have all
different types of matches displayed separately, one can just set:

@example
 zstyle ':completion:*' group-name '@w{'}
@end example

All matches for which no group name is defined will be put in a group
named @code{-default-}.

To display the group name in the output, see the @code{format} style (q.v.)
under the @code{descriptions} tag.
@end quotation

@geindex group-order@comma{} completion style; Keystroke

@code{group-order}

@quotation

This style is additional to the @code{group-name} style to specify the
order for display of the groups defined by that style (compare @code{tag-order},
which determines which completions appear at all).  The groups named
are shown in the given order; any other groups
are shown in the order defined by the completion function.

For example, to have names of builtin commands, shell functions and
external commands appear in that order when completing in command
position:

@example
 zstyle ':completion:*:*:-command-:*:*' group-order \
        builtins functions commands
@end example
@end quotation

@geindex groups@comma{} completion style; Keystroke

@code{groups}

@quotation

A list of names of UNIX groups.  If this is not set,
group names are taken from the YP database or the file @code{/etc/group}.
@end quotation

@geindex hidden@comma{} completion style; Keystroke

@code{hidden}

@quotation

If this is set to `true’, matches for the given context
will not be listed, although
any description for the matches set with the @code{format} style will be
shown.  If it is set to @code{all}, not even the description will be
displayed.

Note that the matches will still be completed; they are just not shown
in the list.  To avoid having matches considered as possible
completions at all, the @code{tag-order} style can be modified as described
below.
@end quotation

@geindex hosts@comma{} completion style; Keystroke

@code{hosts}

@quotation

A list of names of hosts that should be completed.  If this is not set,
hostnames are taken from the file @code{/etc/hosts}.
@end quotation

@geindex hosts-ports@comma{} completion style; Keystroke

@code{hosts-ports}

@quotation

This style is used by commands that need or accept hostnames and
network ports.  The strings in the value should be of the form
@var{host}@code{:}@var{port}.  Valid ports are determined by the presence
of hostnames; multiple ports for the same host may appear.
@end quotation

@geindex ignore-line@comma{} completion style; Keystroke

@code{ignore-line}

@quotation

This is tested for each tag valid for the current completion.  If
it is set to `true’, none of the words that are already on the line
will be considered as possible completions.  If it is set to
@code{current}, the word the cursor is on will not be considered as a
possible completion.  The value @code{current-shown} is similar but only
applies if the list of completions is currently shown on the screen.
Finally, if the style is set to @code{other}, all words on the line except
for the current one will be excluded from the possible completions.

The values @code{current} and @code{current-shown} are a bit like the
opposite of the @code{accept-exact} style:  only strings with
missing characters will be completed.

Note that you almost certainly don’t want to set this to `true’ or
@code{other} for a general
context such as @code{:completion:*}.  This is because it would disallow
completion of, for example, options multiple times even if the command
in question accepts the option more than once.
@end quotation

@geindex ignore-parents@comma{} completion style; Keystroke

@code{ignore-parents}

@quotation

The style is tested without a tag by the function completing pathnames
in order to determine whether to ignore
the names of directories already mentioned in the current word, or the
name of the current working directory.  The value must include one or both
of the following strings:

@code{parent}

@quotation

The name of any directory whose path is already contained in the word on
the line is ignored.  For example, when completing after @code{foo/../}, the
directory @code{foo} will not be considered a valid completion.
@end quotation

@code{pwd}

@quotation

The name of the current working directory will not be completed; hence,
for example, completion after @code{../} will not use the name of the current
directory.
@end quotation

In addition, the value may include one or both of:

@code{..}

@quotation

Ignore the specified directories only when the word on the line contains
the substring @code{../}.
@end quotation

@code{directory}

@quotation

Ignore the specified directories only when names of directories are
completed, not when completing names of files.
@end quotation

Excluded values act in a similar fashion to values of the
@code{ignored-patterns} style, so they can be restored to consideration by
the @code{_ignored} completer.
@end quotation

@geindex ignored-patterns@comma{} completion style; Keystroke

@code{ignored-patterns}

@quotation

A list of patterns; any trial completion matching one of the patterns
will be excluded from consideration.  The
@code{_ignored} completer can appear in the list of completers to
restore the ignored matches.  This is a more configurable
version of the shell parameter @code{$fignore}.

Note that the
@code{EXTENDED_GLOB} option is set during the execution of completion
functions, so the characters @code{#}, @code{~} and @code{^} have special
meanings in the patterns.
@end quotation

@geindex insert@comma{} completion style; Keystroke

@code{insert}

@quotation

This style is used by the @code{_all_matches} completer to decide whether to
insert the list of all matches unconditionally instead of adding the
list as another match.
@end quotation

@geindex insert-ids@comma{} completion style; Keystroke

@code{insert-ids}

@quotation

When completing process IDs, for example as arguments to the @code{kill} and
@code{wait} builtins the name of a
command may be converted to the appropriate process ID.  A problem
arises when the process name typed is not unique.  By default (or if this
style is set explicitly to @code{menu}) the name will be converted
immediately to a set of possible IDs, and menu completion will be started
to cycle through them.

If the value of the style is @code{single},
the shell will wait until the user has typed enough to make the command
unique before converting the name to an ID; attempts at completion will
be unsuccessful until that point.  If the value is any other
string, menu completion will be started when the string typed by the
user is longer than the common prefix to the corresponding IDs.
@end quotation

@geindex insert-sections@comma{} completion style; Keystroke

@code{insert-sections}

@quotation

This style is used with tags of the form @code{manuals.}@var{X} when
completing names of manual pages. If set and the @var{X} in the tag name matches
the section number of the page being completed, the section number is inserted
along with the page name. For example, given

@example
 zstyle ':completion:*:manuals.*' insert-sections true
@end example

@code{man ssh_<TAB>} may be completed to @code{man 5 ssh_config}.

The value may also be set to one of @code{prepend}, or @code{suffix}.
@code{prepend} behaves the same as `true’ as in the above example, while
@code{suffix} would complete @code{man ssh_<TAB>} as @code{man ssh_config.5}.

This is especially useful in conjunction with @code{separate-sections}, as
it ensures that the page requested of @code{man} corresponds to the one
displayed in the completion listing when there are multiple pages with the
same name (e.g., @code{printf(1)} and @code{printf(3)}).

The default for this style is `false’.
@end quotation

@geindex insert-tab@comma{} completion style; Keystroke

@code{insert-tab}

@quotation

If this is set to `true’, the completion system will
insert a TAB character (assuming that was used to start completion) instead
of performing completion when there is no non-blank character to the left
of the cursor.  If it is set to `false’, completion will be done even there.

The value may also contain the substrings @code{pending} or
@code{pending=}@var{val}.  In this case, the typed character will be
inserted instead of starting completion when there is unprocessed input
pending.  If a @var{val} is given, completion will not be done if there
are at least that many characters of unprocessed input.  This is often
useful when pasting characters into a terminal.  Note
however, that it relies on the @code{$PENDING} special parameter from the
@code{zsh/zle} module being set properly which is not guaranteed on all
platforms.

The default value of this style is `true’ except for completion within
@code{vared} builtin command where it is `false’.
@end quotation

@geindex insert-unambiguous@comma{} completion style; Keystroke

@code{insert-unambiguous}

@quotation

This is used by the @code{_match} and @code{_approximate} completers.
These completers are often used with menu completion since the word typed
may bear little resemblance to the final completion.
However, if this style is `true’, the completer will start menu
completion only if it could find no unambiguous initial string at
least as long as the original string typed by the user.

In the case of the @code{_approximate} completer, the completer
field in the context will already have been set to one of
@code{correct-}@var{num} or @code{approximate-}@var{num}, where @var{num} is the
number of errors that were accepted.

In the case of the @code{_match} completer, the style may also be set to
the string @code{pattern}.  Then the pattern on the line is left
unchanged if it does not match unambiguously.
@end quotation

@geindex keep-prefix@comma{} completion style; Keystroke

@code{keep-prefix}

@quotation

This style is used by the @code{_expand} completer.  If it is `true’, the
completer will try to keep a prefix containing a tilde or parameter
expansion.  Hence, for example, the string @code{~/f*} would be expanded to
@code{~/foo} instead of @code{/home/user/foo}.  If the style is set to
@code{changed} (the default), the prefix will only be left unchanged if
there were other changes between the expanded words and the original
word from the command line.  Any other value forces the prefix to be
expanded unconditionally.

The behaviour of @code{_expand} when this style is `true’ is to cause @code{_expand}
to give up when a single expansion with the restored prefix is the same
as the original; hence any remaining completers may be called.
@end quotation

@geindex known-hosts-files; Keystroke

@code{known-hosts-files}

@quotation

This style should contain a list of files to search for host names and
(if the @code{use-ip} style is set) IP addresses in a format compatible with
ssh @code{known_hosts} files.  If it is not set, the files
@code{/etc/ssh/ssh_known_hosts} and @code{~/.ssh/known_hosts} are used.
@end quotation

@geindex last-prompt@comma{} completion style; Keystroke

@code{last-prompt}

@quotation

This is a more flexible form of the @code{ALWAYS_LAST_PROMPT} option.
If it is `true’, the completion system will try to return the cursor to
the previous command line after displaying a completion list.  It is
tested for all tags valid for the current completion, then the
@code{default} tag.  The cursor will be moved back to the
previous line if this style is `true’ for all types of match.  Note
that unlike the @code{ALWAYS_LAST_PROMPT} option this is independent of the
numeric argument.
@end quotation

@geindex list@comma{} completion style; Keystroke

@code{list}

@quotation

This style is used by the @code{_history_complete_word} bindable command.
If it is set to `true’ it has no effect.  If it is set to `false’
matches will not be listed.  This overrides the setting of the options
controlling listing behaviour, in particular @code{AUTO_LIST}.  The context
always starts with @code{:completion:history-words}.
@end quotation

@geindex list-colors@comma{} completion style; Keystroke

@code{list-colors}

@quotation

If the @code{zsh/complist} module is loaded, this style can be used to set
color specifications.  This mechanism replaces the use of the
@code{ZLS_COLORS} and @code{ZLS_COLOURS} parameters described in
@ref{f4,,The zsh/complist Module}, but the syntax is the same.

If this style is set for the @code{default} tag, the strings in the value
are taken as specifications that are to be used everywhere.  If it is
set for other tags, the specifications are used only for matches of
the type described by the tag.  For this to work best, the @code{group-name}
style must be set to an empty string.

In addition to setting styles for specific tags, it is also possible to
use group names specified explicitly by the @code{group-name} tag together
with the @code{(group)} syntax allowed by the @code{ZLS_COLORS} and
@code{ZLS_COLOURS} parameters and simply using the @code{default} tag.

It is possible to use any color specifications already set up for the GNU
version of the @code{ls} command:

@example
 zstyle ':completion:*:default' list-colors \
        $@{(s.:.)LS_COLORS@}
@end example

The default colors are the same as for the GNU @code{ls} command and can be
obtained by setting the style to an empty string (i.e. @code{'@w{'}}).
@end quotation

@geindex list-dirs-first@comma{} completion style; Keystroke

@code{list-dirs-first}

@quotation

This is used by file completion and corresponds to a particular
setting of the @code{file-patterns} style.
If set, the default directories to be completed
are listed separately from and before completion for other files.
@end quotation

@geindex list-grouped@comma{} completion style; Keystroke

@code{list-grouped}

@quotation

If this style is `true’ (the default), the completion system will try to
make certain completion listings more compact by grouping matches.
For example, options for commands that have the same description (shown
when the @code{verbose} style is set to `true’) will appear as a single
entry.  However, menu selection can be used to cycle through all the
matches.
@end quotation

@geindex list-packed@comma{} completion style; Keystroke

@code{list-packed}

@quotation

This is tested for each tag valid in the current context as well as the
@code{default} tag.  If it is set to `true’, the corresponding matches
appear in listings as if the @code{LIST_PACKED} option were set.  If it is
set to `false’, they are listed normally.
@end quotation

@geindex list-prompt@comma{} completion style; Keystroke

@code{list-prompt}

@quotation

If this style is set for the @code{default} tag,
completion lists that don’t fit on the screen can be scrolled (see
@ref{f4,,The zsh/complist Module}).
The value, if not the empty string, will be displayed after every
screenful and the shell will prompt for a key press; if the style is
set to the empty string,
a default prompt will be used.

The value may contain the escape sequences:
@code{%l} or @code{%L}, which will be replaced by the number of the last line
displayed and the total number of lines; @code{%m} or @code{%M},
the number of the  last match shown and the total number of
matches; and @code{%p} and @code{%P}, @code{Top}
when at the beginning of the list, @code{Bottom} when at the end and the
position shown as a percentage of the total length otherwise.  In each
case the form with the uppercase letter will be replaced by a string of fixed
width, padded to the  right with spaces, while the lowercase form will
be replaced by a variable width string.  As in other prompt strings, the
escape sequence @code{`%H}` along with @code{%S}, @code{%s}, @code{%B}, @code{%b},
@code{%U}, @code{%u} for entering and leaving the display modes
standout, bold and underline, and @code{%F}, @code{%f}, @code{%K}, @code{%k} for
changing the foreground background colour, are also available, as is the form
@code{%@{...%@}} for enclosing escape sequences which display with zero
(or, with a numeric argument, some other) width.

After deleting this prompt the variable @code{LISTPROMPT} should be unset for
the removal to take effect.
@end quotation

@geindex list-rows-first@comma{} completion style; Keystroke

@code{list-rows-first}

@quotation

This style is tested in the same way as the @code{list-packed} style and
determines whether matches are to be listed in a rows-first fashion as
if the @code{LIST_ROWS_FIRST} option were set.
@end quotation

@geindex list-separator@comma{} completion style; Keystroke

@code{list-separator}

@quotation

The value of this style is used in completion listing to separate the
string to complete from a description when possible (e.g. when
completing options).  It defaults to @code{--} (two hyphens).
@end quotation

@geindex list-suffixes@comma{} completion style; Keystroke

@code{list-suffixes}

@quotation

This style is used by the function that completes filenames.  If it is
`true’, and completion is attempted on a string containing multiple partially
typed pathname components, all ambiguous components will be shown.
Otherwise, completion stops at the first ambiguous component.
@end quotation

@geindex local@comma{} completion style; Keystroke

@code{local}

@quotation

This is for use with functions that complete URLs for which the
corresponding files are available directly from the file system.
Its value should consist of three strings: a
hostname, the path to the default web pages for the server, and the
directory name used by a user placing web pages within their home
area.

For example:

@example
 zstyle ':completion:*' local toast \
     /var/http/public/toast public_html
@end example

Completion after @code{http://toast/stuff/} will look for files in the
directory @code{/var/http/public/toast/stuff},  while completion after
@code{http://toast/~yousir/} will look for files in the directory
@code{~yousir/public_html}.
@end quotation

@geindex mail-directory@comma{} completion style; Keystroke

@code{mail-directory}

@quotation

If set, zsh will assume that mailbox files can be found in
the directory specified.  It defaults to @code{~/Mail}.
@end quotation

@geindex match-original@comma{} completion style; Keystroke

@code{match-original}

@quotation

This is used by the @code{_match} completer.  If it is set to
@code{only}, @code{_match} will try to generate matches without inserting a
@code{*} at the cursor position.  If set to any other non-empty value,
it will first try to generate matches without inserting the @code{*}
and if that yields no matches, it will try again with the @code{*}
inserted.  If it is unset or set to the empty string, matching will
only be performed with the @code{*} inserted.
@end quotation

@geindex matcher@comma{} completion style; Keystroke

@code{matcher}

@quotation

This style is tested separately for each tag valid in the current
context.  Its value is placed before any match specifications given by the
@code{matcher-list} style so can override them via the use of an @code{x:}
specification.  The value should be in the form described in
@ref{eb,,Completion Matching Control}.
For examples of this, see the description of the @code{tag-order} style.

For notes comparing the use of this and the @code{matcher-list} style, see
under the description of the @code{tag-order} style.
@end quotation

@geindex matcher-list@comma{} completion style; Keystroke

@code{matcher-list}

@quotation

This style can be set to a list of match specifications that are to
be applied everywhere. Match specifications are described in
@ref{eb,,Completion Matching Control}.
The completion system will try them one after another for each completer
selected.  For example, to try first simple completion and, if that
generates no matches, case-insensitive completion:

@example
 zstyle ':completion:*' matcher-list '@w{'} 'm:@{a-zA-Z@}=@{A-Za-z@}'
@end example

By default each specification replaces the previous one; however, if a
specification is prefixed with @code{+}, it is added to the existing list.
Hence it is possible to create increasingly general specifications
without repetition:

@example
 zstyle ':completion:*' matcher-list \
        '@w{'} '+m:@{a-z@}=@{A-Z@}' '+m:@{A-Z@}=@{a-z@}'
@end example

It is possible to create match specifications valid for particular
completers by using the third field of the context.  This applies only
to completers that override the global matcher-list, which as of this
writing includes only @code{_prefix} and @code{_ignored}.  For example, to
use the completers @code{_complete} and @code{_prefix} but allow
case-insensitive completion only with @code{_complete}:

@example
 zstyle ':completion:*' completer _complete _prefix
 zstyle ':completion:*:complete:*:*:*' matcher-list \
        '@w{'} 'm:@{a-zA-Z@}=@{A-Za-z@}'
@end example

User-defined names, as explained for the @code{completer} style, are
available.  This makes it possible to try the same completer more than
once with different match specifications each time.  For example, to try
normal completion without a match specification, then normal completion
with case-insensitive matching, then correction, and finally
partial-word completion:

@example
 zstyle ':completion:*' completer \
     _complete _correct _complete:foo
 zstyle ':completion:*:complete:*:*:*' matcher-list \
     '@w{'} 'm:@{a-zA-Z@}=@{A-Za-z@}'
 zstyle ':completion:*:foo:*:*:*' matcher-list \
     'm:@{a-zA-Z@}=@{A-Za-z@} r:|[-_./]=* r:|=*'
@end example

If the style is unset in any context no match specification is applied.
Note also that some completers such as @code{_correct} and @code{_approximate}
do not use the match specifications at all, though these completers will
only ever be called once even if the @code{matcher-list} contains more than
one element.

Where multiple specifications are useful, note that the `entire'
completion is done for each element of @code{matcher-list}, which can
quickly reduce the shell’s performance.  As a rough rule of thumb,
one to three strings will give acceptable performance.  On the other
hand, putting multiple space-separated values into the same string does
not have an appreciable impact on performance.

If there is no current matcher or it is empty, and the option
@code{NO_CASE_GLOB} is in effect, the matching for files is performed
case-insensitively in any case.  However, any matcher must
explicitly specify case-insensitive matching if that is required.

For notes comparing the use of this and the @code{matcher} style, see
under the description of the @code{tag-order} style.
@end quotation

@geindex max-errors@comma{} completion style; Keystroke

@code{max-errors}

@quotation

This is used by the @code{_approximate} and @code{_correct} completer functions
to determine the maximum number of errors to allow.  The completer will try
to generate completions by first allowing one error, then two errors, and
so on, until either a match or matches were found or the maximum number of
errors given by this style has been reached.

If the value for this style contains the string @code{numeric}, the
completer function will take any numeric argument as the
maximum number of errors allowed. For example, with

@example
 zstyle ':completion:*:approximate:::' max-errors 2 numeric
@end example

two errors are allowed if no numeric argument is given, but with
a numeric argument of six (as in @code{ESC-6 TAB}), up to six
errors are accepted.  Hence with a value of @code{0 numeric}, no correcting
completion will be attempted unless a numeric argument is given.

If the value contains the string @code{not-numeric}, the completer
will `not' try to generate corrected
completions when given a numeric argument, so in this case the number given
should be greater than zero.  For example, @code{2 not-numeric} specifies that
correcting completion with two errors will usually be performed, but if a
numeric argument is given, correcting completion will not be
performed.

The default value for this style is @code{2 numeric}.
@end quotation

@geindex max-matches-width@comma{} completion style; Keystroke

@code{max-matches-width}

@quotation

This style is used to determine the trade off between the width of the
display used for matches and the width used for their descriptions when
the @code{verbose} style is in effect.  The value gives the number of
display columns to reserve for the matches.  The default is half the
width of the screen.

This has the most impact when several matches have the
same description and so will be grouped together.  Increasing the style
will allow more matches to be grouped together; decreasing it will allow
more of the description to be visible.
@end quotation

@geindex menu@comma{} completion style; Keystroke

@code{menu}

@quotation

If this is `true’ in the context of any of the tags defined
for the current completion menu completion will be used.  The value for
a specific tag will take precedence over that for the @code{default} tag.

If none of the values found in this way is `true’ but at least
one is set to @code{auto}, the shell behaves as if the @code{AUTO_MENU}
option is set.

If one of the values is explicitly set to `false’, menu
completion will be explicitly turned off, overriding the
@code{MENU_COMPLETE} option and other settings.

In the form @code{yes=}@var{num}, where @code{yes} may be any of the
`true’ values (@code{yes}, @code{true}, @code{on} and @code{1}),
menu completion will be turned on if there are at least @var{num} matches.
In the form @code{yes=long}, menu completion will be turned on
if the list does not fit on the screen.  This does not activate menu
completion if the widget normally only lists completions, but menu
completion can be activated in that case with the value @code{yes=long-list}
(Typically, the value @code{select=long-list} described later is more
useful as it provides control over scrolling.)

Similarly, with any of the `false’ values (as in @code{no=10}), menu
completion will `not' be used if there are @var{num} or more matches.

The value of this widget also controls menu selection, as implemented by
the @code{zsh/complist} module.  The following values may appear either
alongside or instead of the values above.

If the value contains the string @code{select}, menu selection
will be started unconditionally.

In the form @code{select=}@var{num}, menu selection will only be started if
there are at least @var{num} matches.  If the values for more than one
tag provide a number, the smallest number is taken.

Menu selection can be turned off explicitly by defining a value
containing the stringtt(no-select).

It is also possible to start menu selection only if the list of
matches does not fit on the screen by using the value
@code{select=long}.  To start menu selection even if the current widget
only performs listing, use the value @code{select=long-list}.

To turn on menu completion or menu selection when there are a certain
number of matches `or' the list of matches does not fit on the
screen, both of @code{yes=} and @code{select=} may be given twice, once
with a number and once with @code{long} or @code{long-list}.

Finally, it is possible to activate two special modes of menu selection.
The word @code{interactive} in the value causes interactive mode
to be entered immediately when menu selection is started; see
@ref{f4,,The zsh/complist Module}
for a description of interactive mode.  Including the string
@code{search} does the same for incremental search mode.  To select backward
incremental search, include the string @code{search-backward}.
@end quotation

@geindex muttrc@comma{} completion style; Keystroke

@code{muttrc}

@quotation

If set, gives the location of the mutt configuration file.  It defaults
to @code{~/.muttrc}.
@end quotation

@geindex numbers@comma{} completion style; Keystroke

@code{numbers}

@quotation

This is used with the @code{jobs} tag.  If it is `true’, the shell will
complete job numbers instead of the shortest unambiguous prefix
of the job command text.  If the value is a number, job numbers will
only be used if that many words from the job descriptions are required to
resolve ambiguities.  For example, if the value is @code{1}, strings will
only be used if all jobs differ in the first word on their command lines.
@end quotation

@geindex old-list@comma{} completion style; Keystroke

@code{old-list}

@quotation

This is used by the @code{_oldlist} completer.  If it is set to @code{always},
then standard widgets which perform listing will retain the current list of
matches, however they were generated; this can be turned off explicitly
with the value @code{never}, giving the behaviour without the @code{_oldlist}
completer.  If the style is unset, or any other value, then the existing
list of completions is displayed if it is not already; otherwise, the
standard completion list is generated; this is the default behaviour of
@code{_oldlist}.  However, if there is an old list and this style contains
the name of the completer function that generated the list, then the
old list will be used even if it was generated by a widget which does
not do listing.

For example, suppose you type @code{^Xc} to use the @code{_correct_word}
widget, which generates a list of corrections for the word under the
cursor.  Usually, typing @code{^D} would generate a standard list of
completions for the word on the command line, and show that.  With
@code{_oldlist}, it will instead show the list of corrections already
generated.

As another example consider the @code{_match} completer: with the
@code{insert-unambiguous} style set to `true’ it inserts only a common prefix
string, if there is any.  However, this may remove parts of the original
pattern, so that further completion could produce more matches than on the
first attempt.  By using the @code{_oldlist} completer and setting this style
to @code{_match}, the list of matches generated on the first attempt will be
used again.
@end quotation

@geindex old-matches@comma{} completion style; Keystroke

@code{old-matches}

@quotation

This is used by the @code{_all_matches} completer to decide if an old
list of matches should be used if one exists.  This is selected by one of
the `true’ values or by the string @code{only}.  If
the value is @code{only}, @code{_all_matches} will only use an old list
and won’t have any effect on the list of matches currently being
generated.

If this style is set it is generally unwise to call the @code{_all_matches}
completer unconditionally.  One possible use is for either this style or
the @code{completer} style to be defined with the @code{-e} option to
@code{zstyle} to make the style conditional.
@end quotation

@geindex old-menu@comma{} completion style; Keystroke

@code{old-menu}

@quotation

This is used by the @code{_oldlist} completer.  It controls how menu
completion behaves when a completion has already been inserted and the
user types a standard completion key such as @code{TAB}.  The default
behaviour of @code{_oldlist} is that menu completion always continues
with the existing list of completions.  If this style is set to
`false’, however, a new completion is started if the old list was
generated by a different completion command; this is the behaviour without
the @code{_oldlist} completer.

For example, suppose you type @code{^Xc} to generate a list of corrections,
and menu completion is started in one of the usual ways.  Usually, or with
this style set to `false’, typing @code{TAB} at this point would start
trying to complete the line as it now appears.  With @code{_oldlist}, it
instead continues to cycle through the list of corrections.
@end quotation

@geindex original@comma{} completion style; Keystroke

@code{original}

@quotation

This is used by the @code{_approximate} and @code{_correct}
completers to decide if the original string should be added as
a possible completion.  Normally, this is done only if there are
at least two possible corrections, but if this style is set to `true’, it
is always added.  Note that the style will be examined with the
completer field in the context name set to @code{correct-}@var{num} or
@code{approximate-}@var{num}, where @var{num} is the number of errors that
were accepted.
@end quotation

@geindex packageset@comma{} completion style; Keystroke

@code{packageset}

@quotation

This style is used when completing arguments of the Debian @code{dpkg}
program.  It contains an override for the default package set
for a given context.  For example,

@example
 zstyle ':completion:*:complete:dpkg:option--status-1:*' \
                packageset avail
@end example

causes available packages, rather than only installed packages,
to be completed for @code{dpkg --status}.
@end quotation

@geindex path@comma{} completion style; Keystroke

@code{path}

@quotation

The function that completes color names uses this style with the
@code{colors} tag.  The value should be the pathname of a file
containing color names in the format of an X11 @code{rgb.txt} file.  If
the style is not set but this file is found in one of various standard
locations it will be used as the default.
@end quotation

@geindex path-completion@comma{} completion style; Keystroke

@code{path-completion}

@quotation

This is used by filename completion.  By default, filename completion
examines all components of a path to see if there are completions of
that component.  For example, @code{/u/b/z} can be completed to
@code{/usr/bin/zsh}.  Explicitly setting this style to `false’ inhibits this
behaviour for path components up to the @code{/} before the cursor; this
overrides the setting of @code{accept-exact-dirs}.

Even with the style set to `false’, it is still possible to complete
multiple paths by setting the option @code{COMPLETE_IN_WORD} and moving the
cursor back to the first component in the path to be completed.  For
example, @code{/u/b/z} can be completed to @code{/usr/bin/zsh} if the cursor is
after the @code{/u}.
@end quotation

@geindex pine-directory@comma{} completion style; Keystroke

@code{pine-directory}

@quotation

If set, specifies the directory containing PINE mailbox files.  There
is no default, since recursively searching this directory is inconvenient
for anyone who doesn’t use PINE.
@end quotation

@geindex ports@comma{} completion style; Keystroke

@code{ports}

@quotation

A list of Internet service names (network ports) to complete.  If this is
not set, service names are taken from the file @code{/etc/services}.
@end quotation

@geindex prefix-hidden@comma{} completion style; Keystroke

@code{prefix-hidden}

@quotation

This is used for certain completions which share a common prefix, for
example command options beginning with dashes.  If it is `true’, the
prefix will not be shown in the list of matches.

The default value for this style is `false’.
@end quotation

@geindex prefix-needed@comma{} completion style; Keystroke

@code{prefix-needed}

@quotation

This style is also relevant for matches with a common prefix.  If it is
set to `true’ this common prefix must be typed by the user to generate
the matches.

The style is applicable to the @code{options}, @code{signals}, @code{jobs},
@code{functions}, and @code{parameters} completion tags.

For command options, this means that the initial @code{-}, @code{+}, or
@code{--} must be typed explicitly before option names will be
completed.

For signals, an initial @code{-} is required before signal names will
be completed.

For jobs, an initial @code{%} is required before job names will be
completed.

For function and parameter names, an initial @code{_} or @code{.} is
required before function or parameter names starting with those
characters will be completed.

The default value for this style is `false’ for @code{function} and
@code{parameter} completions, and  `true’ otherwise.
@end quotation

@geindex preserve-prefix@comma{} completion style; Keystroke

@code{preserve-prefix}

@quotation

This style is used when completing path names.  Its value should be a
pattern matching an initial prefix of the word to complete that should
be left unchanged under all circumstances.  For example, on some Unices
an initial @code{//} (double slash) has a special meaning; setting
this style to the string @code{//} will preserve it.  As another example,
setting this style to @code{?:/} under Cygwin would allow completion
after @code{a:/...} and so on.
@end quotation

@geindex range@comma{} completion style; Keystroke

@code{range}

@quotation

This is used by the @code{_history} completer and the
@code{_history_complete_word} bindable command to decide which words
should be completed.

If it is a single number, only the last @var{N} words from the history
will be completed.

If it is a range of the form @var{max}@code{:}@var{slice},
the last @var{slice} words will be completed; then if that
yields no matches, the @var{slice} words before those will be tried and
so on.  This process stops either when at least one match has been
found, or @var{max} words have been tried.

The default is to complete all words from the history at once.
@end quotation

@geindex recursive-files@comma{} completion style; Keystroke

@code{recursive-files}

@quotation

If this style is set, its value is an array of patterns to be
tested against @code{$PWD/}: note the trailing slash, which allows
directories in the pattern to be delimited unambiguously by including
slashes on both sides.  If an ordinary file completion fails
and the word on the command line does not yet have a directory part to its
name, the style is retrieved using the same tag as for the completion
just attempted, then the elements tested against @code{$PWD/} in turn.
If one matches, then the shell reattempts completion by prepending the word
on the command line with each directory in the expansion of @code{**/*(/)}
in turn.  Typically the elements of the style will be set to restrict
the number of directories beneath the current one to a manageable
number, for example @code{*/.git/*}.

For example,

@example
 zstyle ':completion:*' recursive-files '*/zsh/*'
@end example

If the current directory is @code{/home/pws/zsh/Src}, then
@code{zle_tr<TAB>} can be completed to @code{Zle/zle_tricky.c}.
@end quotation

@geindex regular@comma{} completion style; Keystroke

@code{regular}

@quotation

This style is used by the @code{_expand_alias} completer and bindable
command.  If set to `true’ (the default), regular aliases will be
expanded but only in command position.  If it is set to `false’,
regular aliases will never be expanded.   If it is set to @code{always},
regular aliases will be expanded even if not in command position.
@end quotation

@geindex rehash@comma{} completion style; Keystroke

@code{rehash}

@quotation

If this is set when completing external commands, the internal
list (hash) of commands will be updated for each search by issuing
the @code{rehash} command.  There is a speed penalty for this which
is only likely to be noticeable when directories in the path have
slow file access.
@end quotation

@geindex remote-access@comma{} completion style; Keystroke

@code{remote-access}

@quotation

If set to `false’, certain commands will be prevented from making
Internet connections to retrieve remote information.  This includes the
completion for the @code{CVS} command.

It is not always possible to know if connections are in fact to a remote
site, so some may be prevented unnecessarily.
@end quotation

@geindex remove-all-dups@comma{} completion style; Keystroke

@code{remove-all-dups}

@quotation

The @code{_history_complete_word} bindable command and the @code{_history}
completer use this to decide if all duplicate matches should be
removed, rather than just consecutive duplicates.
@end quotation

@geindex select-prompt@comma{} completion style; Keystroke

@code{select-prompt}

@quotation

If this is set for the @code{default} tag, its
value will be displayed during menu selection (see the @code{menu} style
above) when the completion list does not fit on the screen as a
whole.  The same escapes as for the @code{list-prompt} style are
understood, except that the numbers refer to the match or line the mark is
on.  A default prompt is used when the value is the empty string.
@end quotation

@geindex select-scroll@comma{} completion style; Keystroke

@code{select-scroll}

@quotation

This style is tested for the @code{default} tag and determines how a
completion list is scrolled during a menu selection (see the @code{menu}
style above) when the completion list does not fit on the screen as a
whole.  If the value is @code{0} (zero), the list is scrolled by
half-screenfuls; if it is a positive integer, the list is scrolled by the
given number of lines; if it is a negative number, the list is scrolled by a
screenful minus the absolute value of the given number of lines.
The default is to scroll by single lines.
@end quotation

@geindex separate-sections@comma{} completion style; Keystroke

@code{separate-sections}

@quotation

This style is used with the @code{manuals} tag when completing names of
manual pages.  If it is `true’, entries for different sections are
added separately using tag names of the form @code{manuals.}@var{X},
where @var{X} is the section number.  When the @code{group-name} style is
also in effect, pages from different sections will appear separately.
This style is also used similarly with the @code{words} style when
completing words for the dict command. It allows words from different
dictionary databases to be added separately. See also @code{insert-sections}.

The default for this style is `false’.
@end quotation

@geindex show-ambiguity@comma{} completion style; Keystroke

@code{show-ambiguity}

@quotation

If the @code{zsh/complist} module is loaded, this style can be used to
highlight the first ambiguous character in completion lists. The
value is either a color indication such as those supported by the
@code{list-colors} style or, with a value of `true’, a default of
underlining is selected. The highlighting is only applied if the
completion display strings correspond to the actual matches.
@end quotation

@geindex show-completer@comma{} completion style; Keystroke

@code{show-completer}

@quotation

Tested whenever a new completer is tried.  If it is `true’, the completion
system outputs a progress message in the listing area showing what
completer is being tried.  The message will be overwritten by any output
when completions are found and is removed after completion is finished.
@end quotation

@geindex single-ignored@comma{} completion style; Keystroke

@code{single-ignored}

@quotation

This is used by the @code{_ignored} completer when there is only one match.
If its value is @code{show}, the single match will be
displayed but not inserted.  If the value is @code{menu}, then the single
match and the original string are both added as matches and menu completion
is started, making it easy to select either of them.
@end quotation

@geindex sort@comma{} completion style; Keystroke

@code{sort}

@quotation

This allows the standard ordering of matches to be overridden.

If its value is @code{true} or @code{false}, sorting is enabled or disabled.
Additionally the values associated with the @code{-o} option to @code{compadd} can
also be listed: @code{match}, @code{nosort}, @code{numeric}, @code{reverse}.  If it is not
set for the context, the standard behaviour of the calling widget is used.

The style is tested first against the full context including the tag, and
if that fails to produce a value against the context without the tag.

In many cases where a calling widget explicitly selects a particular ordering
in lieu of the default, a value of @code{true} is not honoured.  An example of
where this is not the case is for command history where the default of sorting
matches chronologically may be overridden by setting the style to `true’.

In the @code{_expand} completer, if it is set to
`true’, the expansions generated will always be sorted.  If it is set
to @code{menu}, then the expansions are only sorted when they are offered
as single strings but not in the string containing all possible
expansions.
@end quotation

@geindex special-dirs@comma{} completion style; Keystroke

@code{special-dirs}

@quotation

Normally, the completion code will not produce the directory names
@code{.} and @code{..} as possible completions.  If this style is set to
`true’, it will add both @code{.} and @code{..} as possible completions;
if it is set to @code{..}, only @code{..} will be added.

The following example sets @code{special-dirs} to @code{..} when the
current prefix is empty, is a single @code{.}, or consists only of a path
beginning with @code{../}.  Otherwise the value is `false’.

@example
 zstyle -e ':completion:*' special-dirs \
    '[[ $PREFIX = (../)#(|.|..) ]] && reply=(..)'
@end example
@end quotation

@geindex squeeze-slashes@comma{} completion style; Keystroke

@code{squeeze-slashes}

@quotation

If set to `true’, sequences of slashes in filename paths (for example in
@code{foo//bar}) will be treated as a single slash.  This is the usual
behaviour of UNIX paths.  However, by default the file completion
function behaves as if there were a @code{*} between the slashes.
@end quotation

@geindex stop@comma{} completion style; Keystroke

@code{stop}

@quotation

If set to `true’, the @code{_history_complete_word} bindable
command will stop once when reaching the beginning or end of the
history.  Invoking @code{_history_complete_word} will then wrap around to
the opposite end of the history.  If this style is set to `false’ (the
default), @code{_history_complete_word} will loop immediately as in a
menu completion.
@end quotation

@geindex strip-comments@comma{} completion style; Keystroke

@code{strip-comments}

@quotation

If set to `true’, this style causes non-essential comment text to be
removed from completion matches.  Currently it is only used when
completing e-mail addresses where it removes any display name from the
addresses, cutting them down to plain @var{user@@host} form.
@end quotation

@geindex subst-globs-only@comma{} completion style; Keystroke

@code{subst-globs-only}

@quotation

This is used by the @code{_expand} completer.  If it is set to `true’,
the expansion will only be used if it resulted from globbing; hence,
if expansions resulted from the use of the @code{substitute} style
described below, but these were not further changed by globbing, the
expansions will be rejected.

The default for this style is `false’.
@end quotation

@geindex substitute@comma{} completion style; Keystroke

@code{substitute}

@quotation

This boolean style controls whether the @code{_expand} completer will
first try to expand all substitutions in the string (such as
@code{$(}@var{…}@code{)} and @code{$@{}@var{…}@code{@}}).

The default is `true’.
@end quotation

@geindex suffix@comma{} completion style; Keystroke

@code{suffix}

@quotation

This is used by the @code{_expand} completer if the word starts with a
tilde or contains a parameter expansion.  If it is set to `true’, the
word will only be expanded if it doesn’t have a suffix, i.e. if it is
something like @code{~foo} or @code{$foo} rather than @code{~foo/} or
@code{$foo/bar}, unless that suffix itself contains characters eligible
for expansion.  The default for this style is `true’.
@end quotation

@geindex tag-order@comma{} completion style; Keystroke

@code{tag-order}

@quotation

This provides a mechanism for sorting how the tags available in a
particular context will be used.

The values for the style are sets of space-separated lists of tags.
The tags in each value will be tried at the same time; if no match is
found, the next value is used.  (See the @code{file-patterns} style for
an exception to this behavior.)

For example:

@example
 zstyle ':completion:*:complete:-command-:*:*' tag-order \
     'commands functions'
@end example

specifies that completion in command position first offers
external commands and shell functions.  Remaining tags will be tried if
no completions are found.

In addition to tag names, each string in the value may take one of the
following forms:

@code{-}

@quotation

If any value consists of only a hyphen,
then `only' the tags specified in the other values are
generated.  Normally all tags not explicitly selected are tried last
if the specified tags fail to generate any matches.  This means
that a single value consisting only of a single hyphen
turns off completion.
@end quotation

@code{!} @var{tags}…

@quotation

A string starting with an exclamation mark
specifies names of tags that are `not' to be used.  The effect is
the same as if all other possible tags for the context had been
listed.
@end quotation

@var{tag}@code{:}@var{label} …

@quotation

Here, @var{tag} is one of the standard tags and @var{label} is an
arbitrary name.  Matches are generated as normal but the name @var{label}
is used in contexts instead of @var{tag}.  This is not useful in words
starting with @code{!}.

If the @var{label} starts with a hyphen, the @var{tag} is prepended to the
@var{label} to form the name used for lookup.  This can be
used to make the completion system try a certain tag more than once,
supplying different style settings for each attempt; see below for an
example.
@end quotation

@var{tag}@code{:}@var{label}@code{:}@var{description}

@quotation

As before, but @code{description} will replace the @code{%d} in
the value of the @code{format} style instead of the default description
supplied by the completion function.  Spaces in the description must
be quoted with a backslash.  A @code{%d} appearing
in @var{description} is replaced with the description given by the
completion function.
@end quotation

In any of the forms above the tag may be a pattern or several
patterns in the form @code{@{}@var{pat1}@code{,}@var{pat2…}@code{@}}.  In this
case all matching tags will be used except
for any given explicitly in the same string.

One use of these features is to try
one tag more than once, setting other styles differently on
each attempt, but still to use all the other tags without having to
repeat them all.  For example, to make completion of function names in
command position ignore all the completion functions starting with an
underscore the first time completion is tried:

@example
 zstyle ':completion:*:*:-command-:*:*' tag-order \
     'functions:-non-comp *' functions
 zstyle ':completion:*:functions-non-comp' \
     ignored-patterns '_*'
@end example

On the first attempt, all tags will be offered but the @code{functions} tag
will be replaced by @code{functions-non-comp}.  The @code{ignored-patterns} style
is set for this tag to exclude functions starting with an underscore.
If there are no matches, the second value of the
@code{tag-order} style is used which completes functions using the default
tag, this time presumably including all function names.

The matches for one tag can be split into different groups.  For example:

@example
 zstyle ':completion:*' tag-order \
     'options:-long:long\ options
      options:-short:short\ options
      options:-single-letter:single\ letter\ options'
 zstyle ':completion:*:options-long' \
      ignored-patterns '[-+](|-|[^-]*)'
 zstyle ':completion:*:options-short' \
      ignored-patterns '--*' '[-+]?'
 zstyle ':completion:*:options-single-letter' \
      ignored-patterns '???*'
@end example

With the @code{group-names} style set, options beginning with
@code{--}, options beginning with a single @code{-} or @code{+} but
containing multiple characters, and single-letter options will be
displayed in separate groups with different descriptions.

Another use of patterns is to
try multiple match specifications one after another.  The
@code{matcher-list} style offers something similar, but it is tested very
early in the completion system and hence can’t be set for single
commands nor for more specific contexts.  Here is how to
try normal completion without any match specification and, if that
generates no matches, try again with case-insensitive matching, restricting
the effect to arguments of the command @code{foo}:

@example
 zstyle ':completion:*:*:foo:*:*' tag-order '*' '*:-case'
 zstyle ':completion:*-case' matcher 'm:@{a-z@}=@{A-Z@}'
@end example

First, all the tags offered when completing after @code{foo} are tried using
the normal tag name.  If that generates no matches, the second value of
@code{tag-order} is used, which tries all tags again except that this time
each has @code{-case} appended to its name for lookup of styles.  Hence this
time the value for the @code{matcher} style from the second call to @code{zstyle}
in the example is used to make completion case-insensitive.

It is possible to use the @code{-e} option of the @code{zstyle} builtin
command to specify conditions for the use of particular tags.  For
example:

@example
 zstyle -e '*:-command-:*' tag-order '
     if [[ -n $PREFIX$SUFFIX ]]; then
       reply=( )
     else
       reply=( - )
     fi'
@end example

Completion in command position will be attempted only if the string
typed so far is not empty.  This is tested using the @code{PREFIX}
special parameter; see @ref{e6,,Completion Special Parameters}
for a description of parameters which are special inside completion widgets.
Setting @code{reply} to an empty array provides the default
behaviour of trying all tags at once; setting it to an
array containing only a hyphen disables the use of all tags and hence of
all completions.

If no @code{tag-order} style has been defined for a context, the strings
@code{(|*-)argument-* (|*-)option-* values} and @code{options} plus all
tags offered by the completion function will be used to provide a
sensible default behavior that causes arguments (whether normal command
arguments or arguments of options) to be completed before option names for
most commands.
@end quotation

@geindex urls@comma{} completion style; Keystroke

@code{urls}

@quotation

This is used together with the @code{urls} tag by
functions completing URLs.

If the value consists of more than one string, or if the only string
does not name a file or directory, the strings are used as the URLs to
complete.

If the value contains only one string which is the name of a normal
file the URLs are taken from that file (where the URLs may be
separated by white space or newlines).

Finally, if the only string in the value names a directory, the
directory hierarchy rooted at this directory gives the completions.  The
top level directory should be the file access method, such as
@code{http}, @code{ftp}, @code{bookmark} and so on.  In many cases the next
level of directories will be a filename.  The directory hierarchy can
descend as deep as necessary.

For example,

@example
 zstyle ':completion:*' urls ~/.urls
 mkdir -p ~/.urls/ftp/ftp.zsh.org/pub
@end example

allows completion of all the components of the URL
@code{ftp://ftp.zsh.org/pub} after suitable commands such as
@code{netscape} or @code{lynx}.  Note, however, that access methods and
files are completed separately, so if the @code{hosts} style is set hosts
can be completed without reference to the @code{urls} style.

See the description in the function @code{_urls} itself
for more information (e.g. @code{more $^fpath/_urls(N)}).
@end quotation

@geindex use-cache@comma{} completion style; Keystroke

@code{use-cache}

@quotation

If this is set, the completion caching layer is activated for any completions
which use it (via the @code{_store_cache}, @code{_retrieve_cache}, and
@code{_cache_invalid} functions).  The directory containing the cache
files can be changed with the @code{cache-path} style.
@end quotation

@geindex use-compctl@comma{} completion style; Keystroke

@code{use-compctl}

@quotation

If this style is set to a string `not' equal to @code{false}, @code{0},
@code{no}, and @code{off}, the completion system may use any completion
specifications defined with the @code{compctl} builtin command.  If the
style is unset, this is done only if the @code{zsh/compctl} module
is loaded.  The string may also contain the substring @code{first} to
use completions defined with @code{compctl -T}, and the substring
@code{default} to use the completion defined with @code{compctl -D}.

Note that this is only intended to smooth the transition from
@code{compctl} to the new completion system and may disappear in the
future.

Note also that the definitions from @code{compctl} will only be used if
there is no specific completion function for the command in question.  For
example, if there is a function @code{_foo} to complete arguments to the
command @code{foo}, @code{compctl} will never be invoked for @code{foo}.
However, the @code{compctl} version will be tried if @code{foo} only uses
default completion.
@end quotation

@geindex use-ip@comma{} completion style; Keystroke

@code{use-ip}

@quotation

By default, the function @code{_hosts} that completes host names strips
IP addresses from entries read from host databases such as NIS and
ssh files.  If this style is `true’, the corresponding IP addresses
can be completed as well.  This style is not use in any context
where the @code{hosts} style is set; note also it must be set before
the cache of host names is generated (typically the first completion
attempt).
@end quotation

@geindex users@comma{} completion style; Keystroke

@code{users}

@quotation

This may be set to a list of usernames to be completed.
If it is not set all usernames will be completed.
Note that if it is set only that list of users will be completed;
this is because on some systems querying all users can take
a prohibitive amount of time.
@end quotation

@geindex users-hosts@comma{} completion style; Keystroke

@code{users-hosts}

@quotation

The values of this style should be of the form
@var{user}@code{@@}@var{host} or @var{user}@code{:}@var{host}. It is used for
commands that need pairs of
user- and hostnames.  These commands will complete usernames from this
style (only), and will restrict subsequent hostname completion to hosts
paired with that user in one of the values of the style.

It is possible to group values for sets of commands which allow a remote
login, such as @code{rlogin} and @code{ssh}, by using the @code{my-accounts} tag.
Similarly, values for sets of commands which usually refer to the
accounts of other people, such as @code{talk} and @code{finger}, can be
grouped by using the @code{other-accounts} tag.  More ambivalent commands
may use the @code{accounts} tag.
@end quotation

@geindex users-hosts-ports@comma{} completion style; Keystroke

@code{users-hosts-ports}

@quotation

Like @code{users-hosts} but used for commands like @code{telnet} and
containing strings of the form @var{user}@code{@@}@var{host}@code{:}@var{port}.
@end quotation

@geindex verbose@comma{} completion style; Keystroke

@code{verbose}

@quotation

If set, as it is by default, the completion listing is more verbose.
In particular many commands show descriptions for options if this
style is `true’.
@end quotation

@geindex word@comma{} completion style; Keystroke

@code{word}

@quotation

This is used by the @code{_list} completer, which prevents the insertion of
completions until a second completion attempt when the line has not
changed.  The normal way of finding out if the line has changed is to
compare its entire contents between the two occasions.  If this style is
`true’, the comparison is instead performed only on the current word.
Hence if completion is performed on another word with the same contents,
completion will not be delayed.
@end quotation

@c historic nodename: Control Functions

@node Control Functions,Bindable Commands,Completion System Configuration,Completion System
@anchor{Zsh/compsys control-functions}@anchor{f7}
@section Control Functions


@geindex completion system@comma{} choosing completers; Command

The initialization script @code{compinit} redefines all the widgets
which perform completion to call the supplied widget function
@code{_main_complete}.  This function acts as a wrapper calling the
so-called `completer’ functions that generate matches.  If
@code{_main_complete} is called with arguments, these are taken as the
names of completer functions to be called in the order given.  If no
arguments are given, the set of functions to try is taken from the
@code{completer} style.  For example, to use normal completion and
correction if that doesn’t generate any matches:

@example
 zstyle ':completion:*' completer _complete _correct
@end example

after calling @code{compinit}. The default value for this style is
@code{_complete _ignored}, i.e. normally only ordinary completion is tried,
first with the effect of the @code{ignored-patterns} style and then without
it.  The @code{_main_complete} function uses the return status of the completer
functions to decide if other completers should be called.  If the return
status is zero, no other completers are tried and the @code{_main_complete}
function returns.

If the first argument to @code{_main_complete} is a single hyphen, the
arguments will not be taken as names of completers.  Instead, the
second argument gives a name to use in the @var{completer} field of the
context and the other arguments give a command name and arguments to
call to generate the matches.

The following completer functions are contained in the distribution,
although users may write their own.  Note that in contexts the leading
underscore is stripped, for example basic completion is performed in the
context @code{:completion::complete:}@var{…}.

@geindex completion system@comma{} completers; Command

@geindex _all_matches; Function

@code{_all_matches}

@quotation

This completer can be used to add a string consisting of all other
matches.  As it influences later completers it must appear as the first
completer in the list.  The list of all matches is affected by the
@code{avoid-completer} and @code{old-matches} styles described above.

It may be useful to use the @code{_generic} function described below
to bind @code{_all_matches} to its own keystroke, for example:

@example
 zle -C all-matches complete-word _generic
 bindkey '^Xa' all-matches
 zstyle ':completion:all-matches:*' old-matches only
 zstyle ':completion:all-matches::::' completer _all_matches
@end example

Note that this does not generate completions by itself:  first use
any of the standard ways of generating a list of completions,
then use @code{^Xa} to show all matches.  It is possible instead to
add a standard completer to the list and request that the
list of all matches should be directly inserted:

@example
 zstyle ':completion:all-matches::::' completer \
        _all_matches _complete
 zstyle ':completion:all-matches:*' insert true
@end example

In this case the @code{old-matches} style should not be set.
@end quotation

@geindex _approximate; Function

@code{_approximate}

@quotation

This is similar to the basic @code{_complete} completer but allows the
completions to undergo corrections.  The maximum number of errors can be
specified by the @code{max-errors} style; see
@ref{82,,Approximate Matching}
for how errors are counted.  Normally this completer will only be tried
after the normal @code{_complete} completer:

@example
 zstyle ':completion:*' completer _complete _approximate
@end example

This will give correcting completion if and only if
normal completion yields no possible completions.  When
corrected completions are found, the completer will normally start
menu completion allowing you to cycle through these strings.

This completer uses the tags @code{corrections} and @code{original} when
generating the possible corrections and the original string.  The
@code{format} style for the former may contain the additional sequences
@code{%e} and @code{%o} which will be replaced by the number of errors
accepted to generate the corrections and the original string,
respectively.

The completer progressively increases the number of errors allowed up to
the limit by the @code{max-errors} style, hence if a completion is found
with one error, no completions with two errors will be shown, and so on.
It modifies the completer name in the context to indicate the number of
errors being tried: on the first try the completer field contains
@code{approximate-1}, on the second try @code{approximate-2}, and so on.

When @code{_approximate} is called from another function, the number of
errors to accept may be passed with the @code{-a} option.  The argument
is in the same format as the @code{max-errors} style, all in one string.

Note that this completer (and the @code{_correct} completer mentioned
below) can be quite expensive to call, especially when a large number
of errors are allowed.  One way to avoid this is to set up the
@code{completer} style using the @code{-e} option to zstyle so that some
completers are only used when completion is attempted a second time on
the same string, e.g.:

@example
 zstyle -e ':completion:*' completer '
   if [[ $_last_try != "$HISTNO$BUFFER$CURSOR" ]]; then
     _last_try="$HISTNO$BUFFER$CURSOR"
     reply=(_complete _match _prefix)
   else
     reply=(_ignored _correct _approximate)
   fi'
@end example

This uses the @code{HISTNO} parameter and the @code{BUFFER} and @code{CURSOR}
special parameters that are available inside zle and completion
widgets to find out if the command line hasn’t changed since the last
time completion was tried.  Only then are the @code{_ignored},
@code{_correct} and @code{_approximate} completers called.
@end quotation

@geindex _canonical_paths; Function

@code{_canonical_paths} [ @code{-A} @var{var} ] [ @code{-N} ] [ @code{-MJV12nfX} ] @var{tag} @var{descr} [ @var{paths} … ]

@quotation

This completion function completes all paths given to it, and also tries to
offer completions which point to the same file as one of the paths given
(relative path when an absolute path is given, and vice versa; when @code{..}’s
are present in the word to be completed; and some paths got from symlinks).

@code{-A}, if specified, takes the paths from the array variable specified. Paths can
also be specified on the command line as shown above.  @code{-N}, if specified,
prevents canonicalizing the paths given before using them for completion, in
case they are already so. The options @code{-M}, @code{-J}, @code{-V}, @code{-1}, @code{-2},
@code{-n}, @code{-F}, @code{-X} are passed to @code{compadd}.

See @code{_description} for a description of @var{tag} and @var{descr}.
@end quotation

@geindex _cmdambivalent; Function

@code{_cmdambivalent}

@quotation

Completes the remaining positional arguments as an external command.
The external command and its arguments are completed as separate arguments
(in a manner appropriate for completing @code{/usr/bin/env})
if there are two or more remaining positional arguments on the command line,
and as a quoted command string (in the manner of @code{system(...)}) otherwise.
See also @code{_cmdstring} and @code{_precommand}.

This function takes no arguments.
@end quotation

@geindex _cmdstring; Function

@code{_cmdstring}

@quotation

Completes an external command as a single argument, as for
@code{system(...)}.
@end quotation

@geindex _complete; Function

@code{_complete}

@quotation

This completer generates all possible completions in a context-sensitive
manner, i.e. using the settings defined with the @code{compdef} function
explained above and the current settings of all special parameters.
This gives the normal completion behaviour.

To complete arguments of commands, @code{_complete} uses the utility function
@code{_normal}, which is in turn responsible for finding the particular
function; it is described below.  Various contexts of the form
@code{-}@var{context}@code{-} are handled specifically. These are all
mentioned above as possible arguments to the @code{#compdef} tag.

Before trying to find a function for a specific context, @code{_complete}
checks if the parameter @code{compcontext} is set. Setting
@code{compcontext} allows the usual completion dispatching to be
overridden which is useful in places such as a function that uses
@code{vared} for input. If it is set to an array, the elements are taken
to be the possible matches which will be completed using the tag
@code{values} and the description @code{value}. If it is set to an
associative array, the keys are used as the possible completions and
the values (if non-empty) are used as descriptions for the matches.  If
@code{compcontext} is set to a string containing colons, it should be of
the form @var{tag}@code{:}@var{descr}@code{:}@var{action}.  In this case the
@var{tag} and @var{descr} give the tag and description to use and the
@var{action} indicates what should be completed in one of the forms
accepted by the @code{_arguments} utility function described below.

Finally, if @code{compcontext} is set to a string without colons, the
value is taken as the name of the context to use and the function
defined for that context will be called.  For this purpose, there is a
special context named @code{-command-line-} that completes whole command
lines (commands and their arguments).  This is not used by the completion
system itself but is nonetheless handled when explicitly called.
@end quotation

@geindex _correct; Function

@code{_correct}

@quotation

Generate corrections, but not completions, for the current word; this is
similar to @code{_approximate} but will not allow any number of extra
characters at the cursor as that completer does.  The effect is
similar to spell-checking.  It is based on @code{_approximate}, but the
completer field in the context name is @code{correct}.

For example, with:

@example
 zstyle ':completion:::::' completer \
        _complete _correct _approximate
 zstyle ':completion:*:correct:::' max-errors 2 not-numeric
 zstyle ':completion:*:approximate:::' max-errors 3 numeric
@end example

correction will accept up to two errors.  If a numeric argument is
given, correction will not be performed, but correcting completion
will be, and will accept as many errors as given by the numeric
argument.  Without a numeric argument, first correction and then
correcting completion will be tried, with the first one accepting two
errors and the second one accepting three errors.

When @code{_correct} is called as a function, the number of errors to accept
may be given following the @code{-a} option.  The argument is in the same
form a values to the @code{accept} style, all in one string.

This completer function is intended to be used without the
@code{_approximate} completer or, as in the example, just before
it.  Using it after the @code{_approximate} completer is useless since
@code{_approximate} will at least generate the corrected strings
generated by the @code{_correct} completer – and probably more.
@end quotation

@geindex _expand; Function

@code{_expand}

@quotation

This completer function does not really perform completion, but instead
checks if the word on the command line is eligible for expansion and,
if it is, gives detailed control over how this expansion is done.  For
this to happen, the completion system needs to be invoked with
@code{complete-word}, not @code{expand-or-complete} (the default binding for
@code{TAB}), as otherwise the string will be expanded by the shell’s
internal mechanism before the completion system is started.
Note also this completer should be called before the @code{_complete}
completer function.

The tags used when generating expansions are @code{all-expansions} for the
string containing all possible expansions, @code{expansions} when adding
the possible expansions as single matches and @code{original} when adding
the original string from the line.  The order in which these strings are
generated, if at all, can be controlled by the @code{group-order} and
@code{tag-order} styles, as usual.

The format string for @code{all-expansions} and for @code{expansions} may
contain the sequence @code{%o} which will be replaced by the original
string from the line.

The kind of expansion to be tried is controlled by the @code{substitute},
@code{glob} and @code{subst-globs-only} styles.

It is also possible to call @code{_expand} as a function, in which case the
different modes may be selected with options: @code{-s} for
@code{substitute}, @code{-g} for @code{glob} and @code{-o} for @code{subst-globs-only}.
@end quotation

@geindex _expand_alias; Function

@code{_expand_alias}

@quotation

If the word the cursor is on is an alias, it is expanded and no other
completers are called.  The types of aliases which are to be expanded can
be controlled with the styles @code{regular}, @code{global} and @code{disabled}.

This function is also a bindable command, see
@ref{f8,,Bindable Commands}.
@end quotation

@geindex _extensions; Function

@code{_extensions}

@quotation

If the cursor follows the string @code{*.}, filename extensions are
completed. The extensions are taken from files in current directory or a
directory specified at the beginning of the current word. For exact matches,
completion continues to allow other completers such as @code{_expand} to
expand the pattern. The standard @code{add-space} and @code{prefix-hidden}
styles are observed.
@end quotation

@geindex _external_pwds; Function

@code{_external_pwds}

@quotation

Completes current directories of other zsh processes belonging to the
current user.

This is intended to be used via @code{_generic}, bound to a custom key
combination. Note that pattern matching is enabled so matching is
performed similar to how it works with the @code{_match} completer.
@end quotation

@geindex _history; Function

@code{_history}

@quotation

Complete words from the shell’s command  history.  This completer
can be controlled by the @code{remove-all-dups}, and @code{sort} styles as for the
@code{_history_complete_word} bindable command, see
@ref{f8,,Bindable Commands}
and
@ref{f1,,Completion System Configuration}.
@end quotation

@geindex _ignored; Function

@code{_ignored}

@quotation

The @code{ignored-patterns} style can be set to a list of patterns which are
compared against possible completions; matching ones are removed.
With this completer those matches can be reinstated, as
if no @code{ignored-patterns} style were set.  The completer actually
generates its own list of matches; which completers are invoked
is determined in the same way as for the @code{_prefix} completer.
The @code{single-ignored} style is also available as described above.
@end quotation

@geindex _list; Function

@code{_list}

@quotation

This completer allows the insertion of matches to be delayed until
completion is attempted a second time without the word on the line
being changed.  On the first attempt, only the list of matches will be
shown.  It is affected by the styles @code{condition} and @code{word}, see
@ref{f1,,Completion System Configuration}.
@end quotation

@geindex _match; Function

@code{_match}

@quotation

This completer is intended to be used after the @code{_complete}
completer.  It behaves similarly but the string on the command line may
be a pattern to match against trial completions.  This gives the effect
of the @code{GLOB_COMPLETE} option.

Normally completion will be performed by taking the pattern from the line,
inserting a @code{*} at the cursor position and comparing the resulting
pattern with the possible completions generated.  This can be modified
with the @code{match-original} style described above.

The generated matches will be offered in a menu completion unless the
@code{insert-unambiguous} style is set to `true’; see the description above
for other options for this style.

Note that matcher specifications defined globally or used by the
completion functions (the styles @code{matcher-list} and @code{matcher}) will
not be used.
@end quotation

@geindex _menu; Function

@code{_menu}

@quotation

This completer was written as simple example function to show how menu
completion can be enabled in shell code. However, it has the notable
effect of disabling menu selection which can be useful with
@code{_generic} based widgets. It should be used as the first completer in
the list.  Note that this is independent of the setting of the
@code{MENU_COMPLETE} option and does not work with the other menu
completion widgets such as @code{reverse-menu-complete}, or
@code{accept-and-menu-complete}.
@end quotation

@geindex _oldlist; Function

@code{_oldlist}

@quotation

This completer controls how the standard completion widgets behave
when there is an existing list of completions which may have been
generated by a special completion (i.e. a separately-bound completion
command).  It allows the ordinary completion keys to continue to use the
list of completions thus generated, instead of producing a new list of
ordinary contextual completions.
It should appear in the list of completers before any of
the widgets which generate matches.  It uses two styles: @code{old-list} and
@code{old-menu}, see @ref{f1,,Completion System Configuration}.
@end quotation

@geindex _precommand; Function

@code{_precommand}

@quotation

Complete an external command in word-separated arguments, as for
@code{exec} and @code{/usr/bin/env}.
@end quotation

@geindex _prefix; Function

@code{_prefix}

@quotation

This completer can be used to try completion with the suffix (everything
after the cursor) ignored.  In other words, the suffix will not be
considered to be part of the word to complete.  The effect is similar
to the @code{expand-or-complete-prefix} command.

The @code{completer} style is used to decide which other completers are to
be called to generate matches.  If this style is unset, the list of
completers set for the current context is used – except, of course, the
@code{_prefix} completer itself.  Furthermore, if this completer appears
more than once in the list of completers only those completers not
already tried by the last invocation of @code{_prefix} will be called.

For example, consider this global @code{completer} style:

@example
 zstyle ':completion:*' completer \
     _complete _prefix _correct _prefix:foo
@end example

Here, the @code{_prefix} completer tries normal completion but ignoring the
suffix.  If that doesn’t generate any matches, and neither does
the call to the @code{_correct} completer after it, @code{_prefix} will
be called a second time and, now only trying correction with the
suffix ignored.  On the second invocation the completer part of the
context appears as @code{foo}.

To use @code{_prefix} as the last resort and try only normal completion
when it is invoked:

@example
 zstyle ':completion:*' completer _complete ... _prefix
 zstyle ':completion::prefix:*' completer _complete
@end example

The @code{add-space} style is also respected.  If it is set to `true’ then
@code{_prefix} will insert a space between the matches generated (if any)
and the suffix.

Note that this completer is only useful if the
@code{COMPLETE_IN_WORD} option is set; otherwise, the cursor will
be moved to the end of the current word before the completion code is
called and hence there will be no suffix.
@end quotation

@geindex _user_expand; Function

@code{_user_expand}

@quotation

This completer behaves similarly to the @code{_expand} completer but
instead performs expansions defined by users.  The styles @code{add-space} and
@code{sort} styles specific to the @code{_expand} completer are usable with
@code{_user_expand} in addition to other styles handled more generally by
the completion system.  The tag @code{all-expansions} is also available.

The expansion depends on the array style @code{user-expand} being defined
for the current context; remember that the context for completers is less
specific than that for contextual completion as the full context has not
yet been determined.  Elements of the array may have one of the following
forms:

@code{$}@var{hash}

@quotation

@var{hash} is the name of an associative array.  Note this is not a full
parameter expression, merely a @code{$}, suitably quoted to prevent immediate
expansion, followed by the name of an associative array.  If the trial
expansion word matches a key in @var{hash}, the resulting expansion is the
corresponding value.
@end quotation

@var{_func}

@quotation

@var{_func} is the name of a shell function whose name must begin with
@code{_} but is not otherwise special to the completion system.  The function
is called with the trial word as an argument.  If the word is to be
expanded, the function should set the array @code{reply} to a list of
expansions.  Optionally, it can set @code{REPLY} to a word that will
be used as a description for the set of expansions.
The return status of the function is irrelevant.
@end quotation
@end quotation

@c historic nodename: Bindable Commands

@node Bindable Commands,Utility Functions,Control Functions,Completion System
@anchor{Zsh/compsys bindable-commands}@anchor{f8}
@section Bindable Commands


@geindex completion system@comma{} bindable commands; Command

In addition to the context-dependent completions provided, which are
expected to work in an intuitively obvious way, there are a few widgets
implementing special behaviour which can be bound separately to keys.  The
following is a list of these and their default bindings.

@geindex _bash_completions; Function

@code{_bash_completions}

@quotation

This function is used by two widgets, @code{_bash_complete-word} and
@code{_bash_list-choices}.  It exists to provide compatibility with
completion bindings in bash.  The last character of the binding determines
what is completed: @code{!}, command names; @code{$}, environment variables;
@code{@@}, host names; @code{/}, file names; @code{~} user names.  In bash, the
binding preceded by @code{\e} gives completion, and preceded by @code{^X}
lists options.  As some of these bindings clash with standard zsh
bindings, only @code{\e~} and @code{^X~} are bound by default.  To add the
rest, the following should be added to @code{.zshrc} after @code{compinit} has
been run:

@example
 for key in '!' '$' '@@' '/' '~'; do
   bindkey "\e$key" _bash_complete-word
   bindkey "^X$key" _bash_list-choices
 done
@end example

This includes the bindings for @code{~} in case they were already bound to
something else; the completion code does not override user bindings.
@end quotation

@geindex _correct_filename (^XC); Function

@code{_correct_filename} (@code{^XC})

@quotation

Correct the filename path at the cursor position.  Allows up to six errors
in the name.  Can also be called with an argument to correct
a filename path, independently of zle; the correction is printed on
standard output.
@end quotation

@code{_correct_word} (@code{^Xc})

@quotation

Performs correction of the current argument using the usual contextual
completions as possible choices. This stores the string
@code{correct-word} in the @var{function} field of the context name and
then calls the @code{_correct} completer.
@end quotation

@geindex _expand_alias (^Xa); Function

@code{_expand_alias} (@code{^Xa})

@quotation

This function can be used as a completer and as a bindable command.
It expands the word the cursor is on if it is an alias.  The types of
alias expanded can be controlled with the styles @code{regular}, @code{global}
and @code{disabled}.

When used as a bindable command there is one additional feature that
can be selected by setting the @code{complete} style to `true’.  In this
case, if the word is not the name of an alias, @code{_expand_alias} tries
to complete the word to a full alias name without expanding it.  It
leaves the cursor directly after the completed word so that invoking
@code{_expand_alias} once more will expand the now-complete alias name.
@end quotation

@geindex _expand_word (^Xe); Function

@code{_expand_word} (@code{^Xe})

@quotation

Performs expansion on the current word:  equivalent to the standard
@code{expand-word} command, but using the @code{_expand} completer.  Before
calling it, the @var{function} field of the context is set to
@code{expand-word}.
@end quotation

@geindex _generic; Function

@code{_generic}

@quotation

This function is not defined as a widget and not bound by
default.  However, it can be used to define a widget and will then
store the name of the widget in the @var{function} field of the context
and call the completion system.  This allows custom completion widgets
with their own set of style settings to be defined easily.  For example,
to define a widget that performs normal completion and starts
menu selection:

@example
 zle -C foo complete-word _generic
 bindkey '...' foo
 zstyle ':completion:foo:*' menu yes select=1
@end example

Note in particular that the @code{completer} style may be set for the context
in order to change the set of functions used to generate possible matches.
If @code{_generic} is called with arguments, those are passed through to
@code{_main_complete} as the list of completers in place of those defined by
the @code{completer} style.
@end quotation

@geindex _history_complete_word (\e/); Function

@code{_history_complete_word} (@code{\e/})

@quotation

Complete words from the shell’s command history. This uses the
@code{list}, @code{remove-all-dups}, @code{sort}, and @code{stop} styles.
@end quotation

@geindex _most_recent_file (^Xm); Function

@code{_most_recent_file} (@code{^Xm})

@quotation

Complete the name of the most recently modified file matching the pattern
on the command line (which may be blank).  If given a numeric argument
@var{N}, complete the @var{N}th most recently modified file.  Note the
completion, if any, is always unique.
@end quotation

@geindex _next_tags (^Xn); Function

@code{_next_tags} (@code{^Xn})

@quotation

This command alters the set of matches used to that for the next tag, or
set of tags, either as given by the @code{tag-order} style or as set by
default; these matches would otherwise not be available.
Successive invocations of the command cycle through all possible sets of
tags.
@end quotation

@geindex _read_comp (^X^R); Function

@code{_read_comp} (@code{^X^R})

@quotation

Prompt the user for a string, and use that to perform completion on the
current word.  There are two possibilities for the string.  First, it can
be a set of words beginning @code{_}, for example @code{_files -/}, in which
case the function with any arguments will be called to generate the
completions.  Unambiguous parts of the function name will be completed
automatically (normal completion is not available at this point) until a
space is typed.

Second, any other string will be passed as a set of arguments to
@code{compadd} and should hence be an expression specifying what should
be completed.

A very restricted set of editing commands is available when reading the
string:  @code{DEL} and @code{^H} delete the last character; @code{^U} deletes
the line, and @code{^C} and @code{^G} abort the function, while @code{RET}
accepts the completion.  Note the string is used verbatim as a command
line, so arguments must be quoted in accordance with standard shell rules.

Once a string has been read, the next call to @code{_read_comp} will use the
existing string instead of reading a new one.  To force a new string to be
read, call @code{_read_comp} with a numeric argument.
@end quotation

@geindex _complete_debug (^X?); Function

@code{_complete_debug} (@code{^X?})

@quotation

This widget performs ordinary completion, but captures in a temporary file
a trace of the shell commands executed by the completion system.  Each
completion attempt gets its own file.  A command to view each of these
files is pushed onto the editor buffer stack.
@end quotation

@geindex _complete_help (^Xh); Function

@code{_complete_help} (@code{^Xh})

@quotation

This widget displays information about the context names,
the tags, and the completion functions used
when completing at the current cursor position. If given a numeric
argument other than @code{1} (as in @code{ESC-2 ^Xh}), then the styles
used and the contexts for which they are used will be shown, too.

Note that the information about styles may be incomplete; it depends on the
information available from the completion functions called, which in turn
is determined by the user’s own styles and other settings.
@end quotation

@geindex _complete_help_generic; Function

@code{_complete_help_generic}

@quotation

Unlike other commands listed here, this must be created as a normal ZLE
widget rather than a completion widget (i.e. with @code{zle -N}).  It
is used for generating help with a widget bound to the @code{_generic}
widget that is described above.

If this widget is created using the name of the function, as it is by
default, then when executed it will read a key sequence.  This is expected
to be bound to a call to a completion function that uses the @code{_generic}
widget.  That widget will be executed, and information provided in
the same format that the @code{_complete_help} widget displays for
contextual completion.

If the widget’s name contains @code{debug}, for example if it is created
as @code{zle -N _complete_debug_generic _complete_help_generic}, it
will read and execute the keystring for a generic widget as before,
but then generate debugging information as done by @code{_complete_debug}
for contextual completion.

If the widget’s name contains @code{noread}, it will not read a keystring
but instead arrange that the next use of a generic widget run in
the same shell will have the effect as described above.

The widget works by setting the shell parameter
@code{ZSH_TRACE_GENERIC_WIDGET} which is read by @code{_generic}.  Unsetting
the parameter cancels any pending effect of the @code{noread} form.

For example, after executing the following:

@example
 zle -N _complete_debug_generic _complete_help_generic
 bindkey '^x:' _complete_debug_generic
@end example

typing @code{C-x :} followed by the key sequence for a generic widget
will cause trace output for that widget to be saved to a file.
@end quotation

@geindex _complete_tag (^Xt); Function

@code{_complete_tag} (@code{^Xt})

@quotation

This widget completes symbol tags created by the @code{etags} or @code{ctags}
programmes (note there is no connection with the completion system’s tags)
stored in a file @code{TAGS}, in the format used by @code{etags}, or @code{tags}, in the
format created by @code{ctags}.  It will look back up the path hierarchy for
the first occurrence of either file; if both exist, the file @code{TAGS} is
preferred.  You can specify the full path to a @code{TAGS} or @code{tags} file by
setting the parameter @code{$TAGSFILE} or @code{$tagsfile} respectively.
The corresponding completion tags used are @code{etags} and @code{vtags}, after
emacs and vi respectively.
@end quotation

@c historic nodename: Utility Functions

@node Utility Functions,Completion System Variables,Bindable Commands,Completion System
@anchor{Zsh/compsys utility-functions}@anchor{fb}
@section Utility Functions


@geindex completion system@comma{} utility functions; Command

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

@geindex _absolute_command_paths; Function

@code{_absolute_command_paths}

@quotation

This function completes external commands as absolute paths (unlike
@code{_command_names -e} which completes their basenames).  It takes no
arguments.
@end quotation

@geindex _all_labels; Function

@code{_all_labels} [ @code{-x} ] [ @code{-12VJ} ] @var{tag} @var{name} @var{descr} [ @var{command} @var{arg} … ]

@quotation

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

For example:

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

Will complete the strings from the @code{matches} parameter, using
@code{compadd} with additional options which will take precedence over
those generated by @code{_all_labels}.
@end quotation

@geindex _alternative; Function

@code{_alternative} [ @code{-O} @var{name} ] [ @code{-C} @var{name} ] @var{spec} …

@quotation

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

The tags to use and the action to perform if a tag is requested are
described using the @var{spec}s which are of the form:
@var{tag}@code{:}@var{descr}@code{:}@var{action}.  The @var{tag}s are offered using
@code{_tags} and if the tag is requested, the @var{action} is executed with the
given description @var{descr}.  The @var{action}s are those accepted
by the @code{_arguments} function (described below), with the following
exceptions:

@quotation


@itemize *

@item 
The @code{->}@var{state} and @code{=}@var{…} forms are not supported.

@item 
The @code{((a\:bar b\:baz))} form does not need
@end itemize

the colon to be escaped, since the @var{spec}s have no colon-separated fields
after the @var{action}.
@end quotation

For example, the @var{action} may be a simple function call:

@example
 _alternative \
     'users:user:_users' \
     'hosts:host:_hosts'
@end example

offers usernames and hostnames as possible matches,
generated by the @code{_users} and @code{_hosts} functions respectively.

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

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

Like @code{_tags} this function supports the @code{-C} option to give a
different name for the argument context field.
@end quotation

@geindex _arguments; Function

@code{_arguments} [ @code{-nswWCRS} ] [ @code{-A} @var{pat} ] [ @code{-O} @var{name} ] [ @code{-M} @var{matchspec} ]

@quotation

[ @code{:} ] @var{spec} …
@end quotation

@code{_arguments} [ @var{opt} … ] @code{--} [ @code{-l} ] [ @code{-i} @var{pats} ] [ @code{-s} @var{pair} ]

@quotation

@quotation

[ @var{helpspec} …]
@end quotation

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

`Options Overview'

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

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

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

The options of @code{_arguments} have the following meanings:

@code{-n}

@quotation

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

@code{-s}

@quotation

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

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

Note that @code{-s} after @code{--} has a different meaning, which is documented
in the segment entitled Deriving @var{spec} forms from the help output.
@end quotation

@code{-w}

@quotation

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

@code{-W}

@quotation

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

@code{-C}

@quotation

Modify the @code{curcontext} parameter for an action of the form @code{->}@var{state}.
This is discussed in detail below.
@end quotation

@code{-R}

@quotation

Return status 300 instead of zero when a @code{$state} is to
be handled, in the @code{->}@var{string} syntax.
@end quotation

@code{-S}

@quotation

Do not complete options after a @code{--} appearing on the line,
and ignore the @code{--}.  For example, with @code{-S}, in the line

@example
 foobar -x -- -y
@end example

the @code{-x} is considered an option, the @code{-y} is considered an
argument, and the @code{--} is considered to be neither.

If this option is given twice (as @code{-S -S}), a single @code{-} is also
treated this way.  This is useful for completing zsh’s own builtins as
well as functions that use @code{zparseopts} for option parsing.
@end quotation

@code{-A} @var{pat}

@quotation

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

@code{-O} @var{name}

@quotation

Pass the elements of the array @var{name} as arguments to functions called to
execute @var{action}s.
This is discussed in detail below.
@end quotation

@code{-M} @var{matchspec}

@quotation

Use the match specification @var{matchspec} for completing option names and values.
The default @var{matchspec} allows partial word completion after @code{_} and
@code{-}, such as completing @code{-f-b} to @code{-foo-bar}.  The default
@var{matchspec} is:

@example
 r:|[_-]=* r:|=*
@end example
@end quotation

@code{-0}

@quotation

When populating values of the @code{opt_args} associative array, don’t
backslash-escape colons and backslashes and use NUL rather than colon for
joining multiple values. This option is described in more detail below, under
the heading `:var:'spec`s: actions`.
@end quotation

`:var:'spec`s: overview`

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

@var{n}@code{:}@var{message}@code{:}@var{action}

@var{n}@code{::}@var{message}@code{:}@var{action}

@quotation

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

@code{:}@var{message}@code{:}@var{action}

@code{::}@var{message}@code{:}@var{action}

@quotation

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

@code{*:}@var{message}@code{:}@var{action}

@code{*::}@var{message}@code{:}@var{action}

@code{*:::}@var{message}@code{:}@var{action}

@quotation

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

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

@var{optspec}

@var{optspec}@code{:}@var{…}

@quotation

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

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

@code{*}@var{optspec}

@quotation

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

@code{-}@var{optname}

@code{+}@var{optname}

@quotation

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

Either of @code{-+}@var{optname} and @code{+-}@var{optname} can be used to
specify that @code{-}@var{optname} and @code{+}@var{optname} are both valid.

In all the remaining forms, the leading @code{-} may be replaced by or
paired with @code{+} in this way.
@end quotation

@code{-}@var{optname}@code{-}

@quotation

The first argument of the option must come directly after the option name
`in the same word'.  For example, @code{-foo-:}@var{…} specifies that
the completed option and argument will look like @code{-foo}@var{arg}.
@end quotation

@code{-}@var{optname}@code{+}

@quotation

The first argument may appear immediately after @var{optname} in the same
word, or may appear as a separate word after the option.  For example,
@code{-foo+:}@var{…} specifies that the completed option and argument
will look like either @code{-foo}@var{arg} or @code{-foo} @var{arg}.
@end quotation

@code{-}@var{optname}@code{=}

@quotation

The argument may appear as the next word, or in same word as the option
name provided that it is separated from it by an equals sign, for
example @code{-foo=}@var{arg} or @code{-foo} @var{arg}.
@end quotation

@code{-}@var{optname}@code{=-}

@quotation

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

@var{optspec}@code{[}@var{explanation}@code{]}

@quotation

An explanation string may be appended to any of the preceding forms of
@var{optspec} by enclosing it in brackets, as in @code{-q[query operation]}.

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

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

It is possible for options with a literal @code{+} or @code{=} to
appear, but that character must be quoted, for example @code{-\+}.

Each @var{optarg} following an @var{optspec} must take one of the
following forms:

@code{:}@var{message}@code{:}@var{action}

@code{::}@var{message}@code{:}@var{action}

@quotation

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

This group may be repeated for options which take multiple arguments.
In other words,
@code{:}@var{message1}@code{:}@var{action1}@code{:}@var{message2}@code{:}@var{action2}
specifies that the option takes two arguments.
@end quotation

@code{:*}@var{pattern}@code{:}@var{message}@code{:}@var{action}

@code{:*}@var{pattern}@code{::}@var{message}@code{:}@var{action}

@code{:*}@var{pattern}@code{:::}@var{message}@code{:}@var{action}

@quotation

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

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

Any literal colon in an @var{optname}, @var{message}, or @var{action}
must be preceded by a backslash, @code{\:}.

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

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

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

`:var:'spec`s: actions`

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

The functions called to execute @var{action}s will be called with the
elements of the array named by the @code{-O} @var{name} option as arguments.
This can be used, for example, to pass the same set of options for the
@code{compadd} builtin to all @var{action}s.

The forms for @var{action} are as follows.

@quotation

(single unquoted space)

@quotation

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

@code{(}@var{item1} @var{item2} @var{…}@code{)}

@quotation

One of a list of possible matches, for example:

@example
 :foo:(foo bar baz)
@end example
@end quotation

@code{((:var:`item1`\::var:`desc1` :var:`...`))}

@quotation

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

@example
 :foo:((a\:bar b\:baz))
@end example

The matches will be listed together with their descriptions if the
@code{description} style is set with the @code{values} tag in the context.
@end quotation

@code{->}@var{string}

@quotation

@geindex context@comma{} use of; Variable

@geindex line@comma{} use of; Variable

@geindex opt_args@comma{} use of; Variable

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

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

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

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

A function calling @code{_arguments} with at least
one action containing a @code{->}@var{string} must therefore declare
appropriate local parameters:

@example
 local context state state_descr line
 typeset -A opt_args
@end example

to prevent @code{_arguments} from altering the global environment.
@end quotation

@code{@{}@var{eval-string}@code{@}}

@quotation

A string in braces is evaluated as shell code to generate matches.
This is similar to the  @var{word} @var{…} action described
below, but isn’t limited to a single command.
@end quotation

@code{=} @var{action}

@quotation

@quotation

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

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

@var{word} @var{…}
@end quotation

@var{word} @var{…}

@quotation

@geindex expl@comma{} use of; Variable

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

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

During the performance of the action the array @code{line} will be set to
the normal arguments from the command line, i.e. the words from the
command line after the command name excluding all options and their
arguments.  Also excluded are any words appearing after the current
word, the parsing terminator @code{--} or @code{-} if @code{_arguments}
was called with @code{-S}, and any words ignored by the @code{-A} pattern.

Options are stored in the associative array
@code{opt_args} with option names as keys and their arguments as
the values.  By default, all colons and backslashes in the value are escaped
with backslashes, and if an option has multiple arguments (for example, when
using an @var{optspec} of the form @code{*}@var{optspec}), they are joined with
(unescaped) colons.  However, if the @code{-0} option was passed, no backslash
escaping is performed, and multiple values are joined with NUL bytes.  For
example, after @code{zsh -o foo:foo -o bar:bar -o <TAB>}, the contents of
@code{opt_args} would be

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

by default, and

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

if @code{_arguments} had been called with the @code{-0} option.

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

Furthermore, during the evaluation of the @var{action} the context name in
the @code{curcontext} parameter is altered to append the same string that is
stored in the @code{context} parameter.

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

@example
 local curcontext="$curcontext"
@end example

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

`Grouping Options'

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

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

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

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

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

`Specifying Multiple Sets of Arguments'

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

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

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

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

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

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

`Deriving :var:'spec` forms from the help output`

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

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

For example:

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

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

@example
   -C, --directory=DIR          change to directory DIR
@end example

so that the above specifications will cause directories to be completed
after @code{--directory}, though not after @code{-C}.

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

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

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

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

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

will cause completion to ignore the options
@code{--enable-FEATURE} and @code{--disable-FEATURE} (this example is
useful with GNU @code{configure}).

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

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

@example
 _arguments -- -s "((#s)--enable- --disable-)"
@end example

`Miscellaneous notes'

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

Here is a more general example of the use of @code{_arguments}:

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

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

The @code{-format} option takes one
argument in the next word, described as @var{paper size} for which
only the strings @code{letter} and @code{A4} will be completed.

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

The last two descriptions say what should be completed as
arguments.  The first describes the first argument as a
@var{postscript file} and makes files ending in @code{ps} or @code{eps}
be completed.  The last description gives all other arguments the
description @var{page number} but does not offer completions.
@end quotation

@geindex _as_if; Function

@code{_as_if} @var{command} [@var{arg} … ]

@quotation

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

@example
 compdef '_as_if bar --baz' foo
@end example
@end quotation

@geindex _cache_invalid; Function

@code{_cache_invalid} @var{cache_identifier}

@quotation

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

Example:

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

@geindex _call_function; Function

@code{_call_function} @var{return} @var{name} [ @var{arg} … ]

@quotation

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

The return status of @code{_call_function} itself is zero if the function
@var{name} exists and was called and non-zero otherwise.
@end quotation

@geindex _call_program; Function

@code{_call_program} [ @code{-lpqQ} ] @var{tag} @var{string} …

@quotation

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

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

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

By default, the @var{string}s are passed directly to @code{eval}, which may
require double-quoting in some cases. The options @code{-q} and @code{-Q} can
help with this: with @code{-q}, all @var{string}s are quoted, whereas with
@code{-Q} all @var{string}s except the first one (usually the name of the
command to run) are quoted. @code{-Q} is useful when the first @var{string}
is @code{$words[1]}, which may already be quoted since it is taken directly
from the typed command line. These options do not affect the quoting of
arguments derived from the @code{command} style.
@end quotation

@geindex _combination; Function

@code{_combination} [ @code{-s} @var{pattern} ] @var{tag} @var{style} @var{spec} … @var{field} @var{opts} …

@quotation

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

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

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

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

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

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

All arguments after the required field name are passed to
@code{compadd} when generating matches from the style value, or to
the functions for the fields if they are called.
@end quotation

@geindex _command_names; Function

@code{_command_names} [ @code{-e} | @code{-} ]

@quotation

This function completes words that are valid at command position: names of
aliases, builtins, hashed commands, functions, and so on.  If the @code{-e}
flag is given, or if the list of precommands contains a non-builtin command
(e.g. because @code{_normal -p} has been used previously), only hashed commands
are completed.  The @code{-} flag is ignored.
@end quotation

@geindex _comp_locale; Function

@code{_comp_locale}

@quotation

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

This function should normally be run only in a subshell, because the new
locale is exported to the environment. Typical usage would be
@code{$(_comp_locale;} @var{command} …`@w{`})`@w{`}.
@end quotation

@geindex _completers; Function

@code{_completers} [ @code{-p} ]

@quotation

This function completes names of completers.

@code{-p}

@quotation

Include the leading underscore (@code{_}) in the matches.
@end quotation
@end quotation

@geindex _default; Function

@code{_default}

@quotation

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

@geindex _describe; Function

@code{_describe [-12JVx}] [ @code{-oO} | @code{-t} @var{tag} ] @var{descr} @var{name1} [ @var{name2} ] [ @var{opt} … ]

@quotation

@quotation

[ @code{--} @var{name1} [ @var{name2} ] [ @var{opt} … ] … ]
@end quotation

This function associates completions with descriptions.
Multiple groups separated by @code{--} can be supplied, potentially with
different completion options @var{opt}s.

The @var{descr} is taken as a string to display above the matches if the
@code{format} style for the @code{descriptions} tag is set.

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

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

Finally, a set of options to pass to @code{compadd} can appear.

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

With the @code{-t} option a @var{tag} can be specified.  The default is
@code{values} or, if the @code{-o} option is given, @code{options}.

The options @code{-1}, @code{-2}, @code{-J}, @code{-V}, @code{-x} are passed to
@code{_next_label}.

If selected by the @code{list-grouped} style, strings with the same
description will appear together in the list.

@code{_describe} uses the @code{_all_labels} function to generate the matches, so
it does not need to appear inside a loop over tag labels.
@end quotation

@geindex _description; Function

@code{_description} [ @code{-x} ] [ @code{-12VJ} ] @var{tag} @var{name} @var{descr} [ @var{spec} … ]

@quotation

@geindex expl@comma{} use of; Variable

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

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

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

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

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

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

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

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

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

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

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

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

@geindex _dir_list; Function

@code{_dir_list} [ @code{-s} @var{sep} ] [ @code{-S} ]

@quotation

Complete a list of directory names separated by colons
(the same format as @code{$PATH}).

@code{-s} @var{sep}

@quotation

Use @var{sep} as separator between items.
@var{sep} defaults to a colon (@code{:}).
@end quotation

@code{-S}

@quotation

Add @var{sep} instead of slash (@code{/}) as an autoremoveable suffix.
@end quotation
@end quotation

@geindex _dispatch; Function

@code{_dispatch} @var{context string} …

@quotation

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

The function sets the parameter
@code{$service} to the @var{string} being tried, and sets
the @var{context/command} field (the fourth) of the @code{$curcontext}
parameter to the @var{context} given as the first argument.
@end quotation

@geindex _email_addresses; Function

@code{_email_addresses} [ @code{-c} ] [ @code{-n} @var{plugin} ]

@quotation

Complete email addresses.  Addresses are provided by plugins.

@code{-c}

@quotation

Complete bare @code{localhost@@domain.tld} addresses, without a name part or
a comment.
Without this option, RFC822 @var{Firstname Lastname} @code{<}@var{address}@code{>}
strings are completed.
@end quotation

@code{-n} @var{plugin}

@quotation

Complete aliases from @var{plugin}.
@end quotation

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

Addresses from the @code{_email-}@var{foo} plugin are added under the
tag @code{email-}@var{foo}.

`Writing plugins'

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

@geindex _files; Function

@code{_files}

@quotation

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

This function accepts the full set of options allowed by
@code{_path_files}, described below.
@end quotation

@geindex _gnu_generic; Function

@code{_gnu_generic}

@quotation

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

@example
 compdef _gnu_generic foo bar
@end example

after the call to @code{compinit}.

The completion system as supplied is conservative in its use of this
function, since it is important to be sure the command understands the
option @code{--help}.
@end quotation

@geindex _guard; Function

@code{_guard} [ @var{options} ] @var{pattern descr}

@quotation

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

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

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

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

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

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

@geindex _message; Function

@code{_message} [ @code{-r12} ] [ @code{-VJ} @var{group} ] @var{descr}

@code{_message -e} [ @var{tag} ] @var{descr}

@quotation

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

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

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

The @code{-12VJ} options and the @var{group} are passed to @code{compadd} and
hence determine the group the message string is added to.

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

@geindex _multi_parts; Function

@code{_multi_parts} [ @code{-i} ] @var{sep} @var{array}

@quotation

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

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

Like other utility functions, this function accepts the @code{-V},
@code{-J}, @code{-1}, @code{-2}, @code{-n}, @code{-f}, @code{-X}, @code{-M},
@code{-P}, @code{-S}, @code{-r}, @code{-R}, and @code{-q} options and passes
them to the @code{compadd} builtin.
@end quotation

@geindex _next_label; Function

@code{_next_label} [ @code{-x} ] [ @code{-12VJ} ] @var{tag} @var{name} @var{descr} [ @var{option} … ]

@quotation

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

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

The @var{option}s given after the @var{descr}
are set in the parameter given by @var{name}, and hence are to be passed
to @code{compadd} or whatever function is called to add the matches.

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

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

@geindex _normal; Function

@code{_normal} [ @code{-P} | @code{-p} @var{precommand} ]

@quotation

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

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

@code{-P}

@quotation

Reset the list of precommands. This option should be used if completing
a command line which allows internal commands (e.g. builtins and
functions) regardless of prior precommands (e.g. @code{zsh -c}).
@end quotation

@code{-p} @var{precommand}

@quotation

Append @var{precommand} to the list of precommands. This option should be
used in nearly all cases in which @code{-P} is not applicable. An advantage
of using this option is that it can automatically signal to
@code{_command_names} that subsequent completion should be limited to hashed
commands, which is usually the desired behaviour following commands like
@code{chroot} and @code{nohup}.
@end quotation

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

@geindex _numbers; Function

@code{_numbers} [ @var{option} … ] [ @var{description} ] [ @var{suffix} … ]

@quotation

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

In addition to common @code{compadd} options, @code{_numbers} accepts the following
options:

@code{-t} @var{tag}

@quotation

Specify a tag to use instead of the default of @code{numbers}.
@end quotation

@code{-u} @var{units}

@quotation

Indicate the default units for the number, e.g. @code{bytes}.
@end quotation

@code{-l} @var{min}

@quotation

Specify the lowest possible value for the number.
@end quotation

@code{-m} @var{max}

@quotation

Specify the highest possible value for the number.
@end quotation

@code{-d} @var{default}

@quotation

Specify the default value.
@end quotation

@code{-N}

@quotation

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

@code{-f}

@quotation

Allow decimal numbers.
@end quotation

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

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

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

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

@example
 zstyle ':completion:*:unit-suffixes' format '%x%(r::,)'
@end example
@end quotation

@geindex _options; Function

@code{_options}

@quotation

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

@geindex _options_set; Function

@geindex _options_unset; Function

@code{_options_set} and @code{_options_unset}

@quotation

These functions complete only set or unset options, with the same
matching specification used in the @code{_options} function.

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

@geindex _parameters; Function

@code{_parameters}

@quotation

This is used to complete the names of shell parameters.

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

All other arguments are passed to the @code{compadd} builtin.
@end quotation

@geindex _path_files; Function

@code{_path_files}

@quotation

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

The options accepted by both @code{_path_files} and @code{_files} are:

@code{-f}

@quotation

Complete all filenames.  This is the default.
@end quotation

@code{-/}

@quotation

Specifies that only directories should be completed.
@end quotation

@code{-g} @var{pattern}

@quotation

Specifies that only files matching the @var{pattern} should be completed.
@end quotation

@code{-W} @var{paths}

@quotation

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

@code{-F} @var{ignored-files}

@quotation

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

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

Finally, the @code{_path_files} function  uses the styles @code{expand},
@code{ambiguous}, @code{special-dirs}, @code{list-suffixes} and @code{file-sort}
described above.
@end quotation

@geindex _phony; Function

@code{_phony} … [ @var{word} … ] [ [ @code{--} ] @var{function} [ @code{-} ] … ]

@quotation

This function allows extra matches to be mixed in with the matches
generated by a function.  Sometimes a command accepts special values like
@code{any}, @code{all}, or @code{none} to be specified but the applicable
completion function only generates real values.

@code{_phony} takes all the same arguments as @code{compadd}.  With the exception
of @code{-a}, @code{-d}, @code{-k} and @code{-l}, these are passed on to the
following function.  Unless there is only one word, a @code{--} separator is
needed to indicate where the words finish and the function begins.  You can
also omit the function in which case an empty input won’t match the phony
values, allowing descriptions to be displayed. This is useful where real
values can’t be generated and @code{_message -e} would otherwise be used.

To ensure that real and phony matches are grouped together, any options
defining the match group should be passed to @code{_phony}.
@end quotation

@geindex _pick_variant; Function

@code{_pick_variant} [ @code{-b} @var{builtin-label} ] [ @code{-c} @var{command} ] [ @code{-r} @var{name} ]

@quotation

@quotation

@var{label}@code{=}@var{pattern} … @var{label} [ @var{arg} … ]
@end quotation

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

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

If the @code{-b} @var{builtin-label} is given, the command is tested to
see if it is provided as a shell builtin, possibly autoloaded; if so,
the label @var{builtin-label} is selected as the label for the variant.

If the @code{-r} @var{name} is given, the @var{label} picked is stored in
the parameter named @var{name}.

The results are also cached in the @code{_cmd_variant} associative array
indexed by the name of the command run.
@end quotation

@geindex _regex_arguments; Function

@code{_regex_arguments} @var{name} @var{spec} …

@quotation

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

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

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

Specification arguments take one of following forms, in which
metacharacters such as @code{(}, @code{)}, @code{#} and @code{|}
should be quoted.

@code{/}@var{pattern}@code{/} [@code{%}@var{lookahead}@code{%}] [@code{-}@var{guard}] [@code{:}@var{tag}@code{:}@var{descr}@code{:}@var{action}]

@quotation

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

The argument starting with @code{:} is used in the same manner as an argument to
@code{_alternative}.

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

@code{/}@var{pattern}@code{/+} [@code{%}@var{lookahead}@code{%}] [@code{-}@var{guard}] [@code{:}@var{tag}@code{:}@var{descr}@code{:}@var{action}]

@quotation

This is similar to @code{/}@var{pattern}@code{/} … but the left part of the
command line string (i.e. the part already matched by previous patterns)
is also considered part of the completion target.
@end quotation

@code{/}@var{pattern}@code{/-} [@code{%}@var{lookahead}@code{%}] [@code{-}@var{guard}] [@code{:}@var{tag}@code{:}@var{descr}@code{:}@var{action}]

@quotation

This is similar to @code{/}@var{pattern}@code{/} … but the @var{action}s of the
current and previously matched patterns are ignored even if the
following @var{pattern} matches the empty string.
@end quotation

@code{(} @var{spec} @code{)}

@quotation

Parentheses may be used to groups @var{spec}s; note each parenthesis
is a single argument to @code{_regex_arguments}.
@end quotation

@var{spec} @code{#}

@quotation

This allows any number of repetitions of @var{spec}.
@end quotation

@var{spec} @var{spec}

@quotation

The two @var{spec}s are to be matched one after the other as described
above.
@end quotation

@var{spec} @code{|} @var{spec}

@quotation

Either of the two @var{spec}s can be matched.
@end quotation

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

Examples:

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

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

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

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

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

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

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

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

@geindex _regex_words [ `@w{`}-t`@w{`} ;var;`term` ]; Function

@code{_regex_words} @var{tag} @var{description} @var{spec} …

@quotation

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

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

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

The second part of @var{spec} is a description for the word being
completed.

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

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

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

For example:

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

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

@geindex _requested; Function

@code{_requested} [ @code{-x} ] [ @code{-12VJ} ] @var{tag} [ @var{name} @var{descr} [ @var{command} [ @var{arg} … ] ]

@quotation

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

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

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

If @var{name} and @var{descr} are given, @code{_requested} calls the
@code{_description} function with these arguments together with the options
passed to @code{_requested}.

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

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

If the @var{command} is not @code{compadd}, it must nevertheless be prepared
to handle the same options.
@end quotation

@geindex _retrieve_cache; Function

@code{_retrieve_cache} @var{cache_identifier}

@quotation

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

See @code{_store_cache} below for more details.
@end quotation

@geindex _sep_parts; Function

@code{_sep_parts}

@quotation

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

This function accepts the @code{compadd} options @code{-V}, @code{-J},
@code{-1}, @code{-2}, @code{-n}, @code{-X}, @code{-M}, @code{-P}, @code{-S},
@code{-r}, @code{-R}, and @code{-q} and passes them on to the @code{compadd}
builtin used to add the matches.
@end quotation

@geindex _sequence; Function

@code{_sequence} [ @code{-s} @var{sep} ] [ @code{-n} @var{max} ] [ @code{-d} ] @var{function} [ @code{-} ] …

@quotation

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

Common @code{compadd} options are passed on to the function. It is possible
to use @code{compadd} directly with @code{_sequence}, though @code{_values} may
be more appropriate in this situation.
@end quotation

@geindex _setup; Function

@code{_setup} @var{tag} [ @var{group} ]

@quotation

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

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

This function is called automatically from @code{_description}
and hence is not normally called explicitly.
@end quotation

@geindex _shadow; Function

@geindex _unshadow; Function

@code{_shadow} [ @code{-s} @var{suffix} ] [ – ] @var{command_name} …

@code{_unshadow}

@quotation

The @code{_shadow} function creates a copy of each of the shell functions
in the @var{command_name} arguments.  The original functions can then
be replaced by new implementations.  A later call to @code{_unshadow}
removes the new implementations, if any, and restores the originals.

Recommended usage is to pair @code{_shadow} and @code{_unshadow} calls by
use of an @code{always} block:

@example
 @{
   _shadow fname
   function fname @{
     # Do your new thing
   @}
   # Invoke callers of fname
 @} always @{
   _unshadow
 @}
@end example

The @var{suffix}, if supplied, is prepended by an @code{@@} character and
then appended to each @var{command_name} to create the copy.  Thus

@example
 _shadow -s XX foo
@end example

creates a function named @code{foo@@XX}.  This provides a well-known
name for the original implementation if the new implementation needs
to call it as a wrapper.  If a nested call to  @code{_shadow} uses the
same @var{suffix}, `no new copy is made'.  The presumption thus is
that suffixes and new implementations correspond one to one.

If @var{command_name} is a builtin or external command, and there has been
no preceding @code{_shadow} replacement made, the function so created calls
the shadowed name prefixed by the @code{builtin} or @code{command} keywords as
appropriate.

@example
 @{
   _shadow -s wrap compadd
   compadd () @{
     # compadd@@wrap runs builtin compadd
     compadd@@wrap -O tmparr "$@@" @}
 @} always @{
   _unshadow
 @}
@end example

When no @var{suffix} argument is present, @code{_shadow} creates a unique
suffix to avoid name collisions.

Arguments of @code{_unshadow} are ignored.  Every listed @var{command_name}
for the most recent call to @code{_shadow} is removed.  This differs from
an early implementation that required @code{_unshadow} to receive the
same @var{suffix} and @var{command_name} list as @code{_shadow}.
@end quotation

@geindex _store_cache; Function

@code{_store_cache} @var{cache_identifier} @var{param} …

@quotation

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

The @var{cache_identifier} specifies the file which the data should be
dumped to.  The file is stored in a directory specified by the
@code{cache-path} style which defaults to @code{~/.zcompcache}.  The remaining
@var{param}s arguments are the parameters to dump to the file.

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

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

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

@geindex _tags; Function

@code{_tags} [ [ @code{-C} @var{name} ] @var{tag} … ]

@quotation

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

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

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

@geindex _tilde_files; Function

@code{_tilde_files}

@quotation

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

@geindex _values; Function

@code{_values} [ @code{-O} @var{name} ] [ @code{-s} @var{sep} ] [ @code{-S} @var{sep} ] [ @code{-wC} ] @var{desc} @var{spec} …

@quotation

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

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

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

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

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

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

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

Example:

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

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

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

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

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

@example
 local context state state_descr line
 typeset -A val_args
@end example

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

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

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

@geindex _wanted; Function

@code{_wanted} [ @code{-x} ] [ @code{-C} @var{name} ]  [ @code{-12VJ} ] @var{tag} @var{name} @var{descr} @var{command} [ @var{arg} …]

@quotation

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

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

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

@example
 local expl
 _wanted tag expl 'description'      compadd -- @var{match1} @var{match2}...
@end example

Note that, as for @code{_requested}, the @var{command} must be able to
accept options to be passed down to @code{compadd}.

Like @code{_tags} this function supports the @code{-C} option to give a
different name for the argument context field.  The @code{-x} option has
the same meaning as for @code{_description}.
@end quotation

@geindex _widgets; Function

@code{_widgets} [ @code{-g} @var{pattern} ]

@quotation

This function completes names of zle widgets (see
@ref{d8,,Zle Widgets}).
The @var{pattern}, if present, is matched against values of the @code{$widgets}
special parameter, documented in
@ref{fc,,The zsh/zleparameter Module}.
@end quotation

@c historic nodename: Completion System Variables

@node Completion System Variables,Completion Directories,Utility Functions,Completion System
@anchor{Zsh/compsys completion-system-variables}@anchor{fd}
@section Completion System Variables


@geindex completion system@comma{} variables; Command

There are some standard variables, initialised by the @code{_main_complete}
function and then used from other functions.

The standard variables are:

@code{_comp_caller_options}

@quotation

The completion system uses @code{setopt} to set a number of options. This
allows functions to be written without concern for compatibility with
every possible combination of user options. However, sometimes completion
needs to know what the user’s option preferences are. These are saved
in the @code{_comp_caller_options} associative array. Option names, spelled
in lowercase without underscores, are mapped to one or other of the
strings @code{on} and @code{off}.
@end quotation

@code{_comp_priv_prefix}

@quotation

Completion functions such as @code{_sudo} can set the @code{_comp_priv_prefix}
array to a command prefix that may then be used by @code{_call_program} to
match the privileges when calling programs to generate matches.
@end quotation

@geindex compprefuncs@comma{} use of; Variable

@geindex comppostfuncs@comma{} use of; Variable

Two more features are offered by the @code{_main_complete} function.  The
arrays @code{compprefuncs} and @code{comppostfuncs} may contain
names of functions that are to be called immediately before or after
completion has been tried.  A function will only be called once unless
it explicitly reinserts itself into the array.

@c historic nodename: Completion Directories

@node Completion Directories,,Completion System Variables,Completion System
@anchor{Zsh/compsys completion-directories}@anchor{fe}
@section Completion Directories


@geindex completion system@comma{} directory structure; Command

In the source distribution, the files are contained in various
subdirectories of the @code{Completion} directory.  They may have been
installed in the same structure, or into one single function directory.
The following is a description of the files found in the original directory
structure.  If you wish to alter an installed file, you will need to copy
it to some directory which appears earlier in your @code{fpath} than the
standard directory where it appears.

@code{Base}

@quotation

The core functions and special completion widgets automatically bound
to keys.  You will certainly need most of these, though will
probably not need to alter them.  Many of these are documented above.
@end quotation

@code{Zsh}

@quotation

Functions for completing arguments of shell builtin commands and
utility functions for this.  Some of these are also used by functions from
the @code{Unix} directory.
@end quotation

@code{Unix}

@quotation

Functions for completing arguments of external commands and suites of
commands.  They may need modifying for your system, although in many cases
some attempt is made to decide which version of a command is present.  For
example, completion for the @code{mount} command tries to determine the system
it is running on, while completion for many other utilities try to decide
whether the GNU version of the command is in use, and hence whether the
@code{--help} option is supported.
@end quotation

@code{X}, @code{AIX}, @code{BSD}, …

@quotation

Completion and utility function for commands available only on some systems.
These are not arranged hierarchically, so, for example, both the
@code{Linux} and @code{Debian} directories, as well as the @code{X} directory,
may be useful on your system.
@end quotation

@c historic nodename: Completion Using compctl

@node Completion Using compctl,Zsh Modules,Completion System,Top
@anchor{Zsh/compctl doc}@anchor{ff}@anchor{Zsh/compctl completion-using-compctl}@anchor{100}
@chapter Completion Using compctl


@geindex completion@comma{} programmable; Command

@geindex completion@comma{} controlling; Command


@menu
* Types of completion:: 
* Command Flags:: 
* Option Flags:: 
* Alternative Completion:: 
* Extended Completion:: 
* Example:: 

@end menu

@node Types of completion,Command Flags,,Completion Using compctl
@anchor{Zsh/compctl types-of-completion}@anchor{101}
@section Types of completion


This version of zsh has two ways of performing completion of words on the
command line.  New users of the shell may prefer to use the newer
and more powerful system based on shell functions; this is described
in Completion System, and the basic shell mechanisms which support
it are described in Completion Widgets.  This chapter describes
the older @code{compctl} command.
Description
——————————————————————————–
.. index:: single: compctl; Function


@itemize *

@item 
@code{compctl} [ @code{-CDT} ] @var{options} [ @var{command} … ]

@item 
@code{compctl} [ @code{-CDT} ] @var{options} [ @code{-x} @var{pattern} @var{options} @code{-} … @code{--} ]

@item 
[ @code{+} @var{options} [ @code{-x} … @code{--} ] … [@code{+}] ] [ @var{command} … ]

@item 
@code{compctl} @code{-M} @var{match-specs} …

@item 
@code{compctl} @code{-L} [ @code{-CDTM} ] [ @var{command} … ]

@item 
@code{compctl} @code{+} @var{command} …
@end itemize

Control the editor’s completion behavior according to the supplied set
of @var{options}.  Various editing commands, notably
@code{expand-or-complete-word}, usually bound to tab, will
attempt to complete a word typed by the user, while others, notably
@code{delete-char-or-list}, usually bound to ^D in EMACS editing
mode, list the possibilities; @code{compctl} controls what those
possibilities are.  They may for example be filenames (the most common
case, and hence the default), shell variables, or words from a
user-specified list.

@c historic nodename: Command Flags

@node Command Flags,Option Flags,Types of completion,Completion Using compctl
@anchor{Zsh/compctl command-flags}@anchor{102}
@section Command Flags


Completion of the arguments of a command may be different for each
command or may use the default.  The behavior when completing the
command word itself may also be separately specified.  These
correspond to the following flags and arguments, all of which (except
for @code{-L}) may be combined with any combination of the
@var{options} described subsequently in Option Flags:

@var{command} …

@quotation

controls completion for the named commands, which must be listed last
on the command line.  If completion is attempted for a command with a
pathname containing slashes and no completion definition is found, the
search is retried with the last pathname component. If the command starts
with a @code{=}, completion is tried with the pathname of the command.

Any of the @var{command} strings may be patterns of the form normally
used for filename generation.  These should be quoted to protect them
from immediate expansion; for example the command string @code{'foo*'}
arranges for completion of the words of any command beginning with
@code{foo}.  When completion is attempted, all pattern completions are
tried in the reverse order of their definition until one matches.  By
default, completion then proceeds as normal, i.e. the shell will try to
generate more matches for the specific command on the command line; this
can be overridden by including @code{-tn} in the flags for the pattern
completion.

Note that aliases
are expanded before the command name is determined unless the
@code{COMPLETE_ALIASES} option is set.  Commands may not be combined
with the @code{-C}, @code{-D} or @code{-T} flags.
@end quotation

@code{-C}

@quotation

controls completion when the command word itself is being completed.
If no @code{compctl -C} command has been issued,  the names of any
executable command (whether in the path or specific to the shell, such
as aliases or functions) are completed.
@end quotation

@code{-D}

@quotation

controls default completion behavior for the arguments of commands not
assigned any special behavior.  If no @code{compctl -D} command has
been issued, filenames are completed.
@end quotation

@code{-T}

@quotation

supplies completion flags to be used before any other processing is
done, even before processing for @code{compctl}s defined for specific
commands.  This is especially useful when combined with extended
completion (the @code{-x} flag, see Extended Completion below).
Using this flag you can define default behavior
which will apply to all commands without exception, or you can alter
the standard behavior for all commands.  For example, if your access
to the user database is too slow and/or it contains too many users (so
that completion after @code{~} is too slow to be usable), you can use

@example
 compctl -T -x 's[~] C[0,[^/]#]' -k friends -S/ -tn
@end example

to complete the strings in the array @code{friends} after a @code{~}.
The @code{C[}@var{…}@code{]} argument is necessary so that this form of
@code{~}-completion is
not tried after the directory name is finished.
@end quotation

@code{-L}

@quotation

lists the existing completion behavior in a manner suitable for
putting into a start-up script; the existing behavior is not changed.
Any combination of the above forms, or the @code{-M} flag (which must
follow the @code{-L} flag), may be specified, otherwise all defined
completions are listed.  Any other flags supplied are ignored.
@end quotation

`no argument'

@quotation

If no argument is given, @code{compctl} lists all defined completions
in an abbreviated form;  with a list of @var{options}, all completions
with those flags set (not counting extended completion) are listed.
@end quotation

If the @code{+} flag is alone and followed immediately by the @var{command}
list, the completion behavior for all the commands in the list is reset to
the default.  In other words, completion will subsequently use the
options specified by the @code{-D} flag.

The form with @code{-M} as the first and only option defines global
matching specifications (see @ref{eb,,Completion Matching Control}).
The match specifications given will be used for every completion
attempt (only when using @code{compctl}, not with the new completion
system) and are tried in the order in which they are defined until one
generates at least one match. E.g.:

@example
 compctl -M '@w{'} 'm:@{a-zA-Z@}=@{A-Za-z@}'
@end example

This will first try completion without any global match specifications
(the empty string) and, if that generates no matches, will try case
insensitive completion.

@c historic nodename: Option Flags

@node Option Flags,Alternative Completion,Command Flags,Completion Using compctl
@anchor{Zsh/compctl option-flags}@anchor{103}
@section Option Flags


@quotation


@itemize *

@item 
[ @code{-fcFBdeaRGovNAIOPZEnbjrzu/12} ]

@item 
[ @code{-k} @var{array} ] [ @code{-g} @var{globstring} ] [ @code{-s} @var{subststring} ]

@item 
[ @code{-K} @var{function} ]

@item 
[ @code{-Q} ] [ @code{-P} @var{prefix} ] [ @code{-S} @var{suffix} ]

@item 
[ @code{-W} @var{file-prefix} ] [ @code{-H} @var{num pattern} ]

@item 
[ @code{-q} ] [ @code{-X} @var{explanation} ] [ @code{-Y} @var{explanation} ]

@item 
[ @code{-y} @var{func-or-var} ] [ @code{-l} @var{cmd} ] [ @code{-h} @var{cmd} ] [ @code{-U} ]

@item 
[ @code{-t} @var{continue} ] [ @code{-J} @var{name} ] [ @code{-V} @var{name} ]

@item 
[ @code{-M} @var{match-spec} ]
@end itemize
@end quotation

The remaining @var{options} specify the type of command arguments
to look for during completion.  Any combination of these flags may be
specified; the result is a sorted list of all the possibilities.  The
options are as follows.

@c historic nodename: Simple Flags

@menu
* Simple Flags:: 
* Flags with Arguments:: 
* Control Flags:: 

@end menu

@node Simple Flags,Flags with Arguments,,Option Flags
@anchor{Zsh/compctl simple-flags}@anchor{104}
@subsection Simple Flags


These produce completion lists made up by the shell itself:

@code{-f}

@quotation

Filenames and file system paths.
@end quotation

@code{-/}

@quotation

Just file system paths.
@end quotation

@code{-c}

@quotation

Command names, including aliases, shell functions, builtins
and reserved words.
@end quotation

@code{-F}

@quotation

Function names.
@end quotation

@code{-B}

@quotation

Names of builtin commands.
@end quotation

@code{-m}

@quotation

Names of external commands.
@end quotation

@code{-w}

@quotation

Reserved words.
@end quotation

@code{-a}

@quotation

Alias names.
@end quotation

@code{-R}

@quotation

Names of regular (non-global) aliases.
@end quotation

@code{-G}

@quotation

Names of global aliases.
@end quotation

@code{-d}

@quotation

This can be combined with @code{-F}, @code{-B}, @code{-w},
@code{-a}, @code{-R} and @code{-G} to get names of disabled
functions, builtins, reserved words or aliases.
@end quotation

@code{-e}

@quotation

This option (to show enabled commands) is in effect by default, but
may be combined with @code{-d}; @code{-de} in combination with
@code{-F}, @code{-B}, @code{-w}, @code{-a}, @code{-R} and @code{-G}
will complete names of functions, builtins, reserved words or aliases
whether or not they are disabled.
@end quotation

@code{-o}

@quotation

Names of shell options (see @code{zshoptions}).
@end quotation

@code{-v}

@quotation

Names of any variable defined in the shell.
@end quotation

@code{-N}

@quotation

Names of scalar (non-array) parameters.
@end quotation

@code{-A}

@quotation

Array names.
@end quotation

@code{-I}

@quotation

Names of integer variables.
@end quotation

@code{-O}

@quotation

Names of read-only variables.
@end quotation

@code{-p}

@quotation

Names of parameters used by the shell (including special parameters).
@end quotation

@code{-Z}

@quotation

Names of shell special parameters.
@end quotation

@code{-E}

@quotation

Names of environment variables.
@end quotation

@code{-n}

@quotation

Named directories.
@end quotation

@code{-b}

@quotation

Key binding names.
@end quotation

@code{-j}

@quotation

Job names:  the first word of the job leader’s command line.  This is useful
with the @code{kill} builtin.
@end quotation

@code{-r}

@quotation

Names of running jobs.
@end quotation

@code{-z}

@quotation

Names of suspended jobs.
@end quotation

@code{-u}

@quotation

User names.
@end quotation

@c historic nodename: Flags with Arguments

@node Flags with Arguments,Control Flags,Simple Flags,Option Flags
@anchor{Zsh/compctl flags-with-arguments}@anchor{105}
@subsection Flags with Arguments


These have user supplied arguments to determine how the list of
completions is to be made up:

@code{-k} @var{array}

@quotation

Names taken from the elements of @code{$}@var{array} (note that the @code{$}
does not appear on the command line).
Alternatively, the argument @var{array} itself may be a set
of space- or comma-separated values in parentheses, in which any
delimiter may be escaped with a backslash; in this case the argument
should be quoted.  For example,

@example
 compctl -k "(cputime filesize datasize stacksize
                coredumpsize resident descriptors)" limit
@end example
@end quotation

@code{-g} @var{globstring}

@quotation

The @var{globstring} is expanded using filename globbing; it should be
quoted to protect it from immediate expansion. The resulting
filenames are taken as the possible completions.  Use @code{*(/)} instead of
@code{*/} for directories.  The @code{fignore} special parameter is not
applied to the resulting files.  More than one pattern may be given
separated by blanks. (Note that brace expansion is `not' part of
globbing.  Use the syntax @code{(either|or)} to match alternatives.)
@end quotation

@code{-s} @var{subststring}

@quotation

The @var{subststring} is split into words and these words are than
expanded using all shell expansion mechanisms (see
@code{zshexpn}).
The resulting words are taken as possible
completions.  The @code{fignore} special parameter is not applied to the
resulting files.  Note that @code{-g} is faster for filenames.
@end quotation

@code{-K} @var{function}

@quotation

@geindex reply@comma{} use of; Variable

Call the given function to get the completions.  Unless the name
starts with an underscore, the function is
passed two arguments: the prefix and the suffix of the word on which
completion is to be attempted, in other words those characters before
the cursor position, and those from the cursor position onwards.  The
whole command line can be accessed with the @code{-c} and @code{-l} flags
of the @code{read} builtin. The
function should set the variable @code{reply} to an array containing
the completions (one completion per element); note that @code{reply}
should not be made local to the function.  From such a function the
command line can be accessed with the @code{-c} and @code{-l} flags to
the @code{read} builtin.  For example,

@example
 function whoson @{ reply=(`users`); @}
 compctl -K whoson talk
@end example

completes only logged-on users after @code{talk}.  Note that @code{whoson} must
return an array, so @code{`reply=`users\}`’ would be incorrect.
@end quotation

@code{-H} @var{num pattern}

@quotation

The possible completions are taken from the last @var{num} history
lines.  Only words matching @var{pattern} are taken.  If @var{num} is
zero or negative the whole history is searched and if @var{pattern} is
the empty string all words are taken (as with @code{*}).  A typical
use is

@example
 compctl -D -f + -H 0 '@w{'}
@end example

which forces completion to look back in the history list for a word if
no filename matches.
@end quotation

@c historic nodename: Control Flags

@node Control Flags,,Flags with Arguments,Option Flags
@anchor{Zsh/compctl control-flags}@anchor{106}
@subsection Control Flags


These do not directly specify types of name to be completed, but
manipulate the options that do:

@code{-Q}

@quotation

This instructs the shell not to quote any metacharacters in the possible
completions.  Normally the results of a completion are inserted into
the command line with any metacharacters quoted so that they are
interpreted as normal characters.  This is appropriate for filenames
and ordinary strings.  However, for special effects, such as inserting
a backquoted expression from a completion array (@code{-k}) so that
the expression will not be evaluated until the complete line is
executed, this option must be used.
@end quotation

@code{-P} @var{prefix}

@quotation

The @var{prefix} is inserted just before the completed string; any
initial part already typed will be completed and the whole @var{prefix}
ignored for completion purposes.  For example,

@example
 compctl -j -P "%" kill
@end example

inserts a `%’ after the kill command and then completes job names.
@end quotation

@code{-S} @var{suffix}

@quotation

When a completion is found the @var{suffix} is inserted after
the completed string.  In the case of menu completion the suffix is
inserted immediately, but it is still possible to cycle through the
list of completions by repeatedly hitting the same key.
@end quotation

@code{-W} @var{file-prefix}

@quotation

With directory @var{file-prefix}:  for command, file, directory and
globbing completion (options @code{-c}, @code{-f}, @code{-/}, @code{-g}), the file
prefix is implicitly added in front of the completion.  For example,

@example
 compctl -/ -W ~/Mail maildirs
@end example

completes any subdirectories to any depth beneath the directory
@code{~/Mail}, although that prefix does not appear on the command line.
The @var{file-prefix} may also be of the form accepted by the @code{-k}
flag, i.e. the name of an array or a literal list in parenthesis. In
this case all the directories in the list will be searched for
possible completions.
@end quotation

@code{-q}

@quotation

If used with a suffix as specified by the @code{-S} option, this
causes the suffix to be removed if the next character typed is a blank
or does not insert anything or if the suffix consists of only one character
and the next character typed is the same character; this the same rule used
for the @code{AUTO_REMOVE_SLASH} option.  The option is most useful for list
separators (comma, colon, etc.).
@end quotation

@code{-l} @var{cmd}

@quotation

This option restricts the range
of command line words that are considered to be arguments.  If
combined with one of the extended completion patterns @code{p[...]},
@code{r[...]}, or @code{R[...]}  (see Extended Completion
below) the range is restricted to the range of arguments
specified in the brackets.  Completion is then performed as if these
had been given as arguments to the @var{cmd} supplied with the
option. If the @var{cmd} string is empty the first word in the range
is instead taken as the command name, and command name completion
performed on the first word in the range.  For example,

@example
 compctl -x 'r[-exec,;]' -l '@w{'} -- find
@end example

completes arguments between @code{-exec} and the following @code{;} (or the end
of the command line if there is no such string) as if they were
a separate command line.
@end quotation

@code{-h} @var{cmd}

@quotation

Normally zsh completes quoted strings as a whole. With this option,
completion can be done separately on different parts of such
strings. It works like the @code{-l} option but makes the completion code
work on the parts of the current word that are separated by
spaces. These parts are completed as if they were arguments to the
given @var{cmd}. If @var{cmd} is the empty string, the first part is
completed as a command name, as with @code{-l}.
@end quotation

@code{-U}

@quotation

Use the whole list of possible completions, whether or not they
actually match the word on the command line.  The word typed so far
will be deleted.  This is most useful with a function (given by the
@code{-K} option) which can examine the word components passed to it
(or via the @code{read} builtin’s @code{-c} and @code{-l} flags) and
use its own criteria to decide what matches.  If there is no
completion, the original word is retained.  Since the produced
possible completions seldom have interesting common prefixes
and suffixes, menu completion is started immediately if @code{AUTO_MENU} is
set and this flag is used.
@end quotation

@code{-y} @var{func-or-var}

@quotation

@geindex reply@comma{} use of; Variable

The list provided by @var{func-or-var} is displayed instead of the list
of completions whenever a listing is required; the actual completions
to be inserted are not affected.  It can be provided in two
ways. Firstly, if @var{func-or-var} begins with a @code{$} it defines a
variable, or if it begins with a left parenthesis a literal
array, which contains the list.  A variable may have been set by a
call to a function using the @code{-K} option.  Otherwise it contains the
name of a function which will be executed to create the list.  The
function will be passed as an argument list all matching completions,
including prefixes and suffixes expanded in full, and should set the
array @code{reply} to the result.  In both cases, the display list will
only be retrieved after a complete list of matches has been created.

Note that the returned list does not have to correspond, even in
length, to the original set of matches, and may be passed as a scalar
instead of an array.  No special formatting of characters is
performed on the output in this case; in particular, newlines are
printed literally and if they appear output in columns is suppressed.
@end quotation

@code{-X} @var{explanation}

@quotation

Print @var{explanation} when trying completion on the current set of
options. A @code{%n} in this string is replaced by the number of
matches that were added for this explanation string.
The explanation only appears if completion was tried and there was
no unique match, or when listing completions. Explanation strings
will be listed together with the matches of the group specified
together with the @code{-X} option (using the @code{-J} or @code{-V}
option). If the same explanation string is given to multiple @code{-X}
options, the string appears only once (for each group) and the number
of matches shown for the @code{%n} is the total number of all matches
for each of these uses. In any case, the explanation string will only
be shown if there was at least one match added for the explanation
string.

The sequences @code{%B}, @code{%b}, @code{%S}, @code{%s}, @code{%U}, and @code{%u} specify
output attributes (bold, standout, and underline), @code{%F}, @code{%f}, @code{%K},
@code{%k} specify foreground and background colours, and @code{%@{}@var{…}@code{%@}} can
be used to include literal escape sequences as in prompts.
@end quotation

@code{-Y} @var{explanation}

@quotation

Identical to @code{-X}, except that the @var{explanation} first undergoes
expansion following the usual rules for strings in double quotes.
The expansion will be carried out after any functions are called for
the @code{-K} or @code{-y} options, allowing them to set variables.
@end quotation

@code{-t} @var{continue}

@quotation

The @var{continue}-string contains a character that specifies which set
of completion flags should be used next.  It is useful:

(i) With @code{-T}, or when trying a list of pattern completions, when
@code{compctl} would usually continue with ordinary processing after
finding matches; this can be suppressed with @code{-tn}.

(ii) With a list of alternatives separated by @code{+}, when @code{compctl}
would normally stop when one of the alternatives generates matches.  It
can be forced to consider the next set of completions by adding @code{-t+}
to the flags of the alternative before the @code{+}.

(iii) In an extended completion list (see below), when @code{compctl} would
normally continue until a set of conditions succeeded, then use only
the immediately following flags.  With @code{-t-}, @code{compctl} will
continue trying extended completions after the next @code{-}; with
@code{-tx} it will attempt completion with the default flags, in other
words those before the @code{-x}.
@end quotation

@code{-J} @var{name}

@quotation

This gives the name of the group the matches should be placed in. Groups
are listed and sorted separately; likewise, menu completion will offer
the matches in the groups in the order in which the groups were
defined. If no group name is explicitly given, the matches are stored in
a group named @code{default}. The first time a group name is encountered,
a group with that name is created. After that all matches with the same
group name are stored in that group.

This can be useful with non-exclusive alternative completions.  For
example, in

@example
 compctl -f -J files -t+ + -v -J variables foo
@end example

both files and variables are possible completions, as the @code{-t+} forces
both sets of alternatives before and after the @code{+} to be considered at
once.  Because of the @code{-J} options, however, all files are listed
before all variables.
@end quotation

@code{-V} @var{name}

@quotation

Like @code{-J}, but matches within the group will not be sorted in listings
nor in menu completion. These unsorted groups are in a different name
space from the sorted ones, so groups defined as @code{-J files} and @code{-V
files} are distinct.
@end quotation

@code{-1}

@quotation

If given together with the @code{-V} option, makes
only consecutive duplicates in the group be removed. Note that groups
with and without this flag are in different name spaces.
@end quotation

@code{-2}

@quotation

If given together with the @code{-J} or @code{-V} option, makes all
duplicates be kept. Again, groups with and without this flag are in
different name spaces.
@end quotation

@code{-M} @var{match-spec}

@quotation

This defines additional matching control specifications that should be used
only when testing words for the list of flags this flag appears in. The format
of the @var{match-spec} string is described in
@ref{eb,,Completion Matching Control}.
@end quotation

@c historic nodename: Alternative Completion

@node Alternative Completion,Extended Completion,Option Flags,Completion Using compctl
@anchor{Zsh/compctl alternative-completion}@anchor{107}
@section Alternative Completion


@quotation


@itemize *

@item 
@code{compctl} [ @code{-CDT} ] @var{options} @code{+} @var{options} [ @code{+} … ] [ @code{+} ] @var{command} …
@end itemize
@end quotation

The form with @code{+} specifies alternative options. Completion is
tried with the options before the first @code{+}. If this produces no
matches completion is tried with the flags after the @code{+} and so on. If
there are no flags after the last @code{+} and a match has not been found
up to that point, default completion is tried.
If the list of flags contains a @code{-t} with a @code{+} character, the next
list of flags is used even if the current list produced matches.

@c historic nodename: Extended Completion

Additional options are available that restrict completion to some part
of the command line; this is referred to as `extended completion’.

@node Extended Completion,Example,Alternative Completion,Completion Using compctl
@anchor{Zsh/compctl extended-completion}@anchor{108}
@section Extended Completion


@quotation


@itemize *

@item 
@code{compctl} [ @code{-CDT} ] @var{options} @code{-x} @var{pattern} @var{options} @code{-} … @code{--}

@item 
[ @var{command} … ]

@item 
@code{compctl} [ @code{-CDT} ] @var{options} [ @code{-x} @var{pattern} @var{options} @code{-} … @code{--} ]

@item 
[ @code{+} @var{options} [ @code{-x} … @code{--} ] … [@code{+}] ] [ @var{command} … ]
@end itemize
@end quotation

The form with @code{-x} specifies extended completion for the
commands given; as shown, it may be combined with alternative
completion using @code{+}.  Each @var{pattern} is examined in turn; when a
match is found, the corresponding @var{options}, as described in
Option Flags above, are used to generate possible
completions.  If no @var{pattern} matches, the @var{options} given
before the @code{-x} are used.

Note that each pattern should be supplied as a single argument and
should be quoted to prevent expansion of metacharacters by the
shell.

A @var{pattern} is built of sub-patterns separated by commas; it
matches if at least one of these sub-patterns matches (they are
`or’ed). These sub-patterns are in turn composed of other
sub-patterns separated by white spaces which match if all of the
sub-patterns match (they are `and’ed).  An element of the
sub-patterns is of the form @var{c}@code{[...][...]}, where the pairs of
brackets may be repeated as often as necessary, and matches if any of
the sets of brackets match (an `or’).  The example below makes this
clearer.

The elements may be any of the following:

@code{s[}@var{string}@code{]}…

@quotation

Matches if the current word on the command line starts with
one of the strings given in brackets.  The @var{string} is not removed
and is not part of the completion.
@end quotation

@code{S[}@var{string}@code{]}…

@quotation

Like @code{s[}@var{string}@code{]} except that the @var{string} is part of the
completion.
@end quotation

@code{p[}@var{from}@code{,}@var{to}@code{]}…

@quotation

Matches if the number of the current word is between one of
the @var{from} and @var{to} pairs inclusive. The comma and @var{to}
are optional; @var{to} defaults to the same value as @var{from}.  The
numbers may be negative: @code{-}@var{n} refers to the @var{n}’th last word
on the line.
@end quotation

@code{c[}@var{offset}@code{,}@var{string}@code{]}…

@quotation

Matches if the @var{string} matches the word offset by
@var{offset} from the current word position.  Usually @var{offset}
will be negative.
@end quotation

@code{C[}@var{offset}@code{,}@var{pattern}@code{]}…

@quotation

Like @code{c} but using pattern matching instead.
@end quotation

@code{w[}@var{index}@code{,}@var{string}@code{]}…

@quotation

Matches if the word in position @var{index} is equal
to the corresponding @var{string}.  Note that the word count is made
after any alias expansion.
@end quotation

@code{W[}@var{index}@code{,}@var{pattern}@code{]}…

@quotation

Like @code{w} but using pattern matching instead.
@end quotation

@code{n[}@var{index}@code{,}@var{string}@code{]}…

@quotation

Matches if the current word contains @var{string}.  Anything up to and
including the @var{index}th occurrence of this string will not be
considered part of the completion, but the rest will.  @var{index} may
be negative to count from the end: in most cases, @var{index} will be
1 or -1.  For example,

@example
 compctl -s '`users`' -x 'n[1,@@]' -k hosts -- talk
@end example

will usually complete usernames, but if you insert an @code{@@} after the
name, names from the array @var{hosts} (assumed to contain hostnames,
though you must make the array yourself) will be completed.  Other
commands such as @code{rcp} can be handled similarly.
@end quotation

@code{N[}@var{index}@code{,}@var{string}@code{]}…

@quotation

Like @code{n} except that the string will be
taken as a character class.  Anything up to and including the
@var{index}th occurrence of any of the characters in @var{string}
will not be considered part of the completion.
@end quotation

@code{m[}@var{min}@code{,}@var{max}@code{]}…

@quotation

Matches if the total number of words lies between @var{min} and
@var{max} inclusive.
@end quotation

@code{r[}@var{str1}@code{,}@var{str2}@code{]}…

@quotation

Matches if the cursor is after a word with prefix @var{str1}.  If there
is also a word with prefix @var{str2} on the command line after the one
matched by @var{str1} it matches
only if the cursor is before this word. If the comma and @var{str2} are
omitted, it matches if the cursor is after a word with prefix @var{str1}.
@end quotation

@code{R[}@var{str1}@code{,}@var{str2}@code{]}…

@quotation

Like @code{r} but using pattern matching instead.
@end quotation

@code{q[}@var{str}@code{]}…

@quotation

Matches the word currently being completed is in single quotes and the
@var{str} begins with the letter `s’, or if completion is done in
double quotes and @var{str} starts with the letter `d’, or if
completion is done in backticks and @var{str} starts with a `b’.
@end quotation

@c historic nodename: Example

@node Example,,Extended Completion,Completion Using compctl
@anchor{Zsh/compctl example}@anchor{109}
@section Example


@example
 compctl -u -x 's[+] c[-1,-f],s[-f+]' \
   -g '~/Mail/*(:t)' - 's[-f],c[-1,-f]' -f -- mail
@end example

This is to be interpreted as follows:

If the current command is @code{mail}, then


@quotation

if ((the current word begins with @code{+} and the previous word is @code{-f})
or (the current word begins with @code{-f+})), then complete the
non-directory part (the @code{:t} glob modifier) of files in the directory
@code{~/Mail}; else

if the current word begins with @code{-f} or the previous word was @code{-f}, then
complete any file; else

complete user names.
@end quotation

@node Zsh Modules,Calendar Function System,Completion Using compctl,Top
@anchor{Zsh/modules doc}@anchor{10a}@anchor{Zsh/modules zsh-modules}@anchor{10b}
@chapter Zsh Modules


@geindex modules; Command

@menu
* Description: Description<6>. 
* The zsh/attr Module:: 
* The zsh/cap Module:: 
* The zsh/clone Module:: 
* The zsh/compctl Module:: 
* The zsh/complete Module:: 
* The zsh/complist Module:: 
* The zsh/computil Module:: 
* The zsh/curses Module:: 
* The zsh/datetime Module:: 
* The zsh/db/gdbm Module:: 
* The zsh/deltochar Module:: 
* The zsh/example Module:: 
* The zsh/files Module:: 
* The zsh/hlgroup Module:: 
* The zsh/langinfo Module:: 
* The zsh/ksh93 Module:: 
* The zsh/mapfile Module:: 
* The zsh/mathfunc Module:: 
* The zsh/nearcolor Module:: 
* The zsh/newuser Module:: 
* The zsh/parameter Module:: 
* The zsh/pcre Module:: 
* The zsh/param/private Module:: 
* The zsh/regex Module:: 
* The zsh/random Module:: 
* The zsh/sched Module:: 
* The zsh/net/socket Module:: 
* The zsh/stat Module:: 
* The zsh/system Module:: 
* The zsh/net/tcp Module:: 
* The zsh/termcap Module:: 
* The zsh/terminfo Module:: 
* The zsh/watch Module:: 
* The zsh/zftp Module:: 
* The zsh/zle Module:: 
* The zsh/zleparameter Module:: 
* The zsh/zprof Module:: 
* The zsh/zpty Module:: 
* The zsh/zselect Module:: 
* The zsh/zutil Module:: 

@end menu

@node Description<6>,The zsh/attr Module,,Zsh Modules
@anchor{Zsh/modules description}@anchor{10c}
@section Description


Some optional parts of zsh are in modules, separate from the core
of the shell.  Each of these modules may be linked in to the
shell at build time,
or can be dynamically linked while the shell is running
if the installation supports this feature.
Modules are linked at runtime with the @code{zmodload} command,
see @ref{b6,,Shell Builtin Commands}.

The modules that are bundled with the zsh distribution are:


@table @asis

@item @ref{10d,,The zsh/attr Module}

Builtins for manipulating extended attributes (xattr).

@item @ref{bb,,The zsh/cap Module}

Builtins for manipulating POSIX.1e (POSIX.6) capability (privilege) sets.

@item @ref{bc,,The zsh/clone Module}

A builtin that can clone a running shell onto another terminal.

@item @ref{be,,The zsh/compctl Module}

The @code{compctl} builtin for controlling completion.

@item @ref{10e,,The zsh/complete Module}

The basic completion code.

@item @ref{f4,,The zsh/complist Module}

Completion listing extensions.

@item @ref{bd,,The zsh/computil Module}

A module with utility builtins needed for the shell function based completion system.

@item @ref{10f,,The zsh/curses Module}

curses windowing commands

@item @ref{110,,The zsh/datetime Module}

Some date/time commands and parameters.

@item @ref{111,,The zsh/db/gdbm Module}

Builtins for managing associative array parameters tied to GDBM databases.

@item @ref{112,,The zsh/deltochar Module}

A ZLE function duplicating EMACS’ @code{zap-to-char}.

@item @ref{113,,The zsh/example Module}

An example of how to write a module.

@item @ref{114,,The zsh/files Module}

Some basic file manipulation commands as builtins.

@item @ref{115,,The zsh/hlgroup Module}

Alternative views of highlighting groups

@item @ref{116,,The zsh/langinfo Module}

Interface to locale information.

@item @ref{117,,The zsh/ksh93 Module}

Extended ksh93 compatibility for “emulate ksh”

@item @ref{118,,The zsh/mapfile Module}

Access to external files via a special associative array.

@item @ref{119,,The zsh/mathfunc Module}

Standard scientific functions for use in mathematical evaluations.

@item @ref{11a,,The zsh/nearcolor Module}

Map colours to the nearest colour in the available palette.

@item @ref{11b,,The zsh/newuser Module}

Arrange for files for new users to be installed.

@item @ref{33,,The zsh/parameter Module}

Access to internal hash tables via special associative arrays.

@item @ref{11c,,The zsh/pcre Module}

Interface to the PCRE library.

@item @ref{11d,,The zsh/param/private Module}

Builtins for managing private-scoped parameters in function context.

@item @ref{11e,,The zsh/regex Module}

Interface to the POSIX regex library.

@item @ref{94,,The zsh/random Module}

Some high-quality randomness parameters and functions.

@item @ref{96,,The zsh/sched Module}

A builtin that provides a timed execution facility within the shell.

@item @ref{ce,,The zsh/net/socket Module}

Manipulation of Unix domain sockets

@item @ref{c7,,The zsh/stat Module}

A builtin command interface to the @code{stat} system call.

@item @ref{11f,,The zsh/system Module}

A builtin interface to various low-level system features.

@item @ref{cf,,The zsh/net/tcp Module}

Manipulation of TCP sockets

@item @ref{bf,,The zsh/termcap Module}

Interface to the termcap database.

@item @ref{c0,,The zsh/terminfo Module}

Interface to the terminfo database.

@item @ref{120,,The zsh/watch Module}

Reporting of login and logout events.

@item @ref{cb,,The zsh/zftp Module}

A builtin FTP client.

@item @ref{99,,The zsh/zle Module}

The Zsh Line Editor, including the @code{bindkey} and @code{vared} builtins.

@item @ref{fc,,The zsh/zleparameter Module}

Access to internals of the Zsh Line Editor via parameters.

@item @ref{cc,,The zsh/zprof Module}

A module allowing profiling for shell functions.

@item @ref{cd,,The zsh/zpty Module}

A builtin for starting a command in a pseudo-terminal.

@item @ref{121,,The zsh/zselect Module}

Block and return when file descriptors are ready.

@item @ref{ca,,The zsh/zutil Module}

Some utility builtins, e.g. the one for supporting configuration via styles.
@end table

@node The zsh/attr Module,The zsh/cap Module,Description<6>,Zsh Modules
@anchor{Zsh/modules id1}@anchor{122}@anchor{Zsh/modules the-zsh-attr-module}@anchor{10d}
@section The zsh/attr Module


The @code{zsh/attr} module is used for manipulating extended attributes.
The @code{-h} option causes all commands to operate on symbolic links instead
of their targets.
The builtins in this module are:

@geindex zgetattr; Function

@geindex extended attributes@comma{} xattr@comma{} getting from files; Command

@code{zgetattr} [ @code{-h} ] @var{filename} @var{attribute} [ @var{parameter} ]

@quotation

Get the extended attribute @var{attribute} from the specified
@var{filename}. If the optional argument @var{parameter} is given, the
attribute is set on that parameter instead of being printed to stdout.
@end quotation

@geindex zsetattr; Function

@geindex extended attributes@comma{} xattr@comma{} setting on files; Command

@code{zsetattr} [ @code{-h} ] @var{filename} @var{attribute} @var{value}

@quotation

Set the extended attribute @var{attribute} on the specified
@var{filename} to @var{value}.
@end quotation

@geindex zdelattr; Function

@geindex extended attributes@comma{} xattr@comma{} removing@comma{} deleting; Command

@code{zdelattr} [ @code{-h} ] @var{filename} @var{attribute}

@quotation

Remove the extended attribute @var{attribute} from the specified
@var{filename}.
@end quotation

@geindex zlistattr; Function

@geindex extended attributes@comma{} xattr@comma{} listing; Command

@code{zlistattr} [ @code{-h} ] @var{filename} [ @var{parameter} ]

@quotation

List the extended attributes currently set on the specified
@var{filename}. If the optional argument @var{parameter} is given, the
list of attributes is set on that parameter instead of being printed to stdout.
@end quotation

@code{zgetattr} and @code{zlistattr} allocate memory dynamically.  If the
attribute or list of attributes grows between the allocation and the call
to get them, they return 2.  On all other errors, 1 is returned.  This
allows the calling function to check for this case and retry.

@node The zsh/cap Module,The zsh/clone Module,The zsh/attr Module,Zsh Modules
@anchor{Zsh/modules id2}@anchor{123}@anchor{Zsh/modules the-zsh-cap-module}@anchor{bb}
@section The zsh/cap Module


The @code{zsh/cap} module is used for manipulating POSIX.1e (POSIX.6) capability
sets.  If the operating system does not support this interface, the
builtins defined by this module will do nothing.
The builtins in this module are:

@geindex cap; Function

@geindex capabilities@comma{} setting; Command

@code{cap} [ @var{capabilities} ]

@quotation

Change the shell’s process capability sets to the specified @var{capabilities},
otherwise display the shell’s current capabilities.
@end quotation

@geindex getcap; Function

@geindex capabilities@comma{} getting from files; Command

@code{getcap} @var{filename} …

@quotation

This is a built-in implementation of the POSIX standard utility.  It displays
the capability sets on each specified @var{filename}.
@end quotation

@geindex setcap; Function

@geindex capabilities@comma{} setting on files; Command

@code{setcap} @var{capabilities} @var{filename} …

@quotation

This is a built-in implementation of the POSIX standard utility.  It sets
the capability sets on each specified @var{filename} to the specified
@var{capabilities}.
@end quotation

@node The zsh/clone Module,The zsh/compctl Module,The zsh/cap Module,Zsh Modules
@anchor{Zsh/modules id3}@anchor{124}@anchor{Zsh/modules the-zsh-clone-module}@anchor{bc}
@section The zsh/clone Module


The @code{zsh/clone} module makes available one builtin command:

@geindex clone; Function

@geindex shell@comma{} cloning; Command

@geindex cloning the shell; Command

@geindex terminal; Command

@code{clone} @var{tty}

@quotation

Creates a forked instance of the current shell, attached to the specified
@var{tty}.  In the new shell, the @code{PID}, @code{PPID} and @code{TTY} special
parameters are changed appropriately.  @code{$!} is set to zero in the new
shell, and to the new shell’s PID in the original shell.

The return status of the builtin is zero in both shells if successful,
and non-zero on error.

The target of @code{clone} should be an unused terminal, such as an unused virtual
console or a virtual terminal created by

@example
 xterm -e sh -c 'trap : INT QUIT TSTP; tty;
         while :; do sleep 100000000; done'
@end example

Some words of explanation are warranted about this long xterm command
line: when doing clone on a pseudo-terminal, some other session
(“session” meant as a unix session group, or SID) is already owning
the terminal. Hence the cloned zsh cannot acquire the pseudo-terminal
as a controlling tty. That means two things:

@quotation


@itemize *

@item 
the job control signals will go to the sh-started-by-xterm process
@end itemize

group (that’s why we disable INT QUIT and TSTP with trap; otherwise
the while loop could get suspended or killed)
* the cloned shell will have job control disabled, and the job
control keys (control-C, control-and control-Z) will not work.
@end quotation

This does not apply when cloning to an `unused' vc.

Cloning to a used (and unprepared) terminal will result in two
processes reading simultaneously from the same terminal, with
input bytes going randomly to either process.

@code{clone} is mostly useful as a shell built-in replacement for
openvt.
@end quotation

@node The zsh/compctl Module,The zsh/complete Module,The zsh/clone Module,Zsh Modules
@anchor{Zsh/modules id4}@anchor{125}@anchor{Zsh/modules the-zsh-compctl-module}@anchor{be}
@section The zsh/compctl Module


The @code{zsh/compctl} module makes available two builtin commands. @code{compctl},
is the old, deprecated way to control completions for ZLE.  See
@code{zshcompctl}.
The other builtin command, @code{compcall} can be used in user-defined
completion widgets, see @code{zshcompwid}.

@node The zsh/complete Module,The zsh/complist Module,The zsh/compctl Module,Zsh Modules
@anchor{Zsh/modules id5}@anchor{126}@anchor{Zsh/modules the-zsh-complete-module}@anchor{10e}
@section The zsh/complete Module


The @code{zsh/complete} module makes available several builtin commands which
can be used in user-defined completion widgets, see
@code{zshcompwid}.

@node The zsh/complist Module,The zsh/computil Module,The zsh/complete Module,Zsh Modules
@anchor{Zsh/modules id6}@anchor{127}@anchor{Zsh/modules the-zsh-complist-module}@anchor{f4}
@section The zsh/complist Module


@geindex completion@comma{} listing; Command

@geindex completion@comma{} coloured listings; Command

@geindex completion@comma{} scroll listings; Command

The @code{zsh/complist} module offers three extensions to completion listings:
the ability to highlight matches in such a list, the ability to
scroll through long lists and a different style of menu completion.

@menu
* Colored Completion Listings:: 
* Scrolling in Completion Listings:: 
* Menu Selection:: 

@end menu

@node Colored Completion Listings,Scrolling in Completion Listings,,The zsh/complist Module
@anchor{Zsh/modules colored-completion-listings}@anchor{128}
@subsection Colored Completion Listings


Whenever one of the parameters @code{ZLS_COLORS} or @code{ZLS_COLOURS} is set
and the @code{zsh/complist} module is loaded or linked into the shell,
completion lists will be colored.  Note, however, that @code{complist} will
not automatically be loaded if it is not linked in:  on systems with
dynamic loading, @code{zmodload zsh/complist} is required.

@geindex ZLS_COLORS; Variable

@geindex ZLS_COLOURS; Variable

The parameters @code{ZLS_COLORS} and @code{ZLS_COLOURS} describe how matches
are highlighted.  To turn on highlighting an empty value suffices, in
which case all the default values given below will be used.  The format of
the value of these parameters is the same as used by the GNU version of the
@code{ls} command: a colon-separated list of specifications of the form
@var{name}@code{=}@var{value}.  The @var{name} may be one of the following strings,
most of which specify file types for which the @var{value} will be used.
The strings and their default values are:

@code{no 0}

@quotation

for normal text (i.e. when displaying something other than a matched file)
@end quotation

@code{fi 0}

@quotation

for regular files
@end quotation

@code{di 32}

@quotation

for directories
@end quotation

@code{ln 36}

@quotation

for symbolic links.  If this has the special value @code{target},
symbolic links are dereferenced and the target file used to
determine the display format.
@end quotation

@code{pi 31}

@quotation

for named pipes (FIFOs)
@end quotation

@code{so 33}

@quotation

for sockets
@end quotation

@code{bd 44;37}

@quotation

for block devices
@end quotation

@code{cd 44;37}

@quotation

for character devices
@end quotation

@code{or} @var{none}

@quotation

for a symlink to nonexistent file (default is the value defined for @code{ln})
@end quotation

@code{mi} @var{none}

@quotation

for a non-existent file (default is the value defined for @code{fi}); this code
is currently not used
@end quotation

@code{su 37;41}

@quotation

for files with setuid bit set
@end quotation

@code{sg 30;43}

@quotation

for files with setgid bit set
@end quotation

@code{tw 30;42}

@quotation

for world writable directories with sticky bit set
@end quotation

@code{ow 34;43}

@quotation

for world writable directories without sticky bit set
@end quotation

@code{sa} @var{none}

@quotation

for files with an associated suffix alias; this is only tested
after specific suffixes, as described below
@end quotation

@code{st 37;44}

@quotation

for directories with sticky bit set but not world writable
@end quotation

@code{ex 35}

@quotation

for executable files
@end quotation

@code{lc \e[}

@quotation

for the left code (see below)
@end quotation

@code{rc m}

@quotation

for the right code
@end quotation

@code{tc 0}

@quotation

for the character indicating the file type  printed after filenames if
the @code{LIST_TYPES} option is set
@end quotation

@code{sp 0}

@quotation

for the spaces printed after matches to align the next column
@end quotation

@code{ec} @var{none}

@quotation

for the end code
@end quotation

Apart from these strings, the @var{name} may also be an asterisk
(@code{*}) followed by any string. The @var{value} given for such a
string will be used for all files whose name ends with the string.
The @var{name} may also be an equals sign (@code{=}) followed by a
pattern; the @code{EXTENDED_GLOB} option will be turned on for evaluation
of the pattern.  The @var{value} given for this pattern will be used for all
matches (not just filenames) whose display string are matched by
the pattern.  Definitions for the form with the leading equal sign take
precedence over the values defined for file types, which in turn take
precedence over the form with the leading asterisk (file extensions).

The leading-equals form also allows different parts of the displayed
strings to be colored differently.  For this, the pattern has to use the
@code{(#b)} globbing flag and pairs of parentheses surrounding the
parts of the strings that are to be colored differently.  In this case
the @var{value} may consist of more than one color code separated by
equal signs.  The first code will be used for all parts for which no
explicit code is specified and the following codes will be used for
the parts matched by the sub-patterns in parentheses.  For example,
the specification @code{=(#b)(?)*(?)=0=3=7} will be used for all
matches which are at least two characters long and will use
the code @code{3} for the first character, @code{7} for the last
character and @code{0} for the rest.

All three forms of @var{name} may be preceded by a pattern in
parentheses.  If this is given, the @var{value} will be used
only for matches in groups whose names are matched by the pattern
given in the parentheses.  For example, @code{(g*)m*=43} highlights all
matches beginning with @code{m} in groups whose names  begin with
@code{g} using the color code @code{43}.  In case of the @code{lc},
@code{rc}, and @code{ec} codes, the group pattern is ignored.

Note also that all patterns are tried in the order in which they
appear in the parameter value until the first one matches which is
then used.  Patterns may be matched against completions, descriptions
(possibly with spaces appended for padding), or lines consisting of a
completion followed by a description.  For consistent coloring it may be
necessary to use more than one pattern or a pattern with backreferences.

When printing a match, the code prints the value of @code{lc}, the value
for the file-type or the last matching specification with a @code{*},
the value of @code{rc}, the string to display for the match itself, and
then the value of @code{ec} if that is defined or the values of @code{lc},
@code{no}, and @code{rc} if @code{ec} is not defined.

The default values are ISO 6429 (ANSI) compliant and can be used on
vt100 compatible terminals such as @code{xterm}s.  On monochrome terminals
the default values will have no visible effect.  The @code{colors}
function from the contribution can be used to get associative arrays
containing the codes for ANSI terminals (see
@ref{129,,Other Functions}).
For example, after loading @code{colors}, one could use
@code{$color[red]} to get the code for foreground color red and
@code{$color[bg-green]} for the code for background color green.

If the completion system invoked by compinit is used, these
parameters should not be set directly because the system controls them
itself.  Instead, the @code{list-colors} style should be used (see
@ref{f1,,Completion System Configuration}).

@node Scrolling in Completion Listings,Menu Selection,Colored Completion Listings,The zsh/complist Module
@anchor{Zsh/modules scrolling-in-completion-listings}@anchor{12a}
@subsection Scrolling in Completion Listings


To enable scrolling through a completion list, the @code{LISTPROMPT}
parameter must be set.  Its value will be used as the prompt; if it
is the empty string, a default prompt will be used.  The value may
contain escapes of the form @code{%x}.  It supports the escapes
@code{%B}, @code{%b}, @code{%S}, @code{%s}, @code{%U}, @code{%u}, @code{%F},
@code{%f}, @code{%K}, @code{%k} and
@code{%@{}@var{…}@code{%@}} used also in shell prompts as well as three pairs of
additional sequences: a @code{%l} or @code{%L} is replaced by the number
of the last line shown and the total number of lines in the form
@var{number}@code{/}@var{total}; a @code{%m} or @code{%M} is replaced with
the number of the last match shown and the total number of matches; and
@code{%p} or @code{%P} is replaced with @code{Top}, @code{Bottom} or the
position of the first line shown in percent of the total number of
lines, respectively.  In each of these cases the form with the uppercase
letter will be replaced with a string of fixed width, padded to the
right with spaces, while the lowercase form will not be padded.

If the parameter @code{LISTPROMPT} is set, the completion code will not ask if
the list should be shown.  Instead it immediately starts displaying the
list, stopping after the first screenful, showing the prompt at the bottom,
waiting for a keypress after temporarily switching to the @code{listscroll}
keymap.  Some of the zle functions have a special meaning while scrolling
lists:

@code{send-break}

@quotation

stops listing discarding the key pressed
@end quotation

@code{accept-line}, @code{down-history}, @code{down-line-or-history}

@code{down-line-or-search}, @code{vi-down-line-or-history}

@quotation

scrolls forward one line
@end quotation

@code{complete-word}, @code{menu-complete}, @code{expand-or-complete}

@code{expand-or-complete-prefix}, @code{menu-complete-or-expand}

@quotation

scrolls forward one screenful
@end quotation

@code{accept-search}

@quotation

stop listing but take no other action
@end quotation

Every other character stops listing and immediately processes the key
as usual.  Any key that is not bound in the @code{listscroll} keymap or
that is bound to @code{undefined-key} is looked up in the keymap
currently selected.

As for the @code{ZLS_COLORS} and @code{ZLS_COLOURS} parameters,
@code{LISTPROMPT} should not be set directly when using the shell
function based completion system.  Instead, the @code{list-prompt} style
should be used.

@node Menu Selection,,Scrolling in Completion Listings,The zsh/complist Module
@anchor{Zsh/modules menu-selection}@anchor{12b}
@subsection Menu Selection


@geindex completion@comma{} selecting by cursor; Command

@geindex MENUSELECT; Variable

@geindex menu-select; Type

The @code{zsh/complist} module also offers an alternative style of selecting
matches from a list, called menu selection, which can be used if the
shell is set up to return to the last prompt after showing a
completion list (see the @code{ALWAYS_LAST_PROMPT} option in
@code{zshoptions}).

Menu selection can be invoked directly by
the widget @code{menu-select} defined by this module.  This is a standard
ZLE widget that can be bound to a key in the usual way as described
in @code{zshzle}.

Alternatively,
the parameter @code{MENUSELECT} can be set to an integer, which gives the
minimum number of matches that must be present before menu selection is
automatically turned on.  This second method requires that menu completion
be started, either directly from a widget such as @code{menu-complete}, or due
to one of the options @code{MENU_COMPLETE} or @code{AUTO_MENU} being set.  If
@code{MENUSELECT} is set, but is 0, 1 or empty, menu selection will always be
started during an ambiguous menu completion.

When using the completion system based on shell functions, the
@code{MENUSELECT} parameter should not be used (like the @code{ZLS_COLORS}
and @code{ZLS_COLOURS} parameters described above).  Instead, the @code{menu}
style should be used with the @code{select=}@var{…} keyword.

After menu selection is started, the matches will be listed. If there
are more matches than fit on the screen, only the first screenful is
shown.  The
matches to insert into the command line can be selected from this
list.  In the list one match is highlighted using the value for @code{ma}
from the @code{ZLS_COLORS} or @code{ZLS_COLOURS} parameter.  The default
value for this is @code{7} which forces the selected match to be
highlighted using standout mode on a vt100-compatible terminal.  If
neither @code{ZLS_COLORS} nor @code{ZLS_COLOURS} is set, the same terminal
control sequence as for the @code{%S} escape in prompts is used.

If there are more matches than fit on the screen and the parameter
@code{MENUPROMPT} is set, its value will be shown below the matches.  It
supports the same escape sequences as @code{LISTPROMPT}, but the number
of the match or line shown will be that of the one where the mark is
placed.  If its value is the empty string, a default prompt will be
used.

The @code{MENUSCROLL} parameter can be used to specify how the list is
scrolled.  If the parameter is unset, this is done line by line, if it
is set to @code{0} (zero), the list will scroll half the number of
lines of the screen.  If the value is positive, it gives the number of
lines to scroll and if it is negative, the list will be scrolled
the number of lines of the screen minus the (absolute) value.

As for the @code{ZLS_COLORS}, @code{ZLS_COLOURS} and @code{LISTPROMPT}
parameters, neither @code{MENUPROMPT} nor @code{MENUSCROLL} should be
set directly when using the shell function based completion
system.  Instead, the @code{select-prompt} and @code{select-scroll} styles
should be used.

The completion code sometimes decides not to show all of the matches
in the list.  These hidden matches are either matches for which the
completion function which added them explicitly requested that they
not appear in the list (using the @code{-n} option of the @code{compadd}
builtin command) or they are matches which duplicate a string already
in the list (because they differ only in things like prefixes or
suffixes that are not displayed).  In the list used for menu selection,
however, even these matches are shown so that it is possible to select
them.  To highlight such matches the @code{hi} and @code{du} capabilities in
the @code{ZLS_COLORS} and @code{ZLS_COLOURS} parameters are supported for
hidden matches of the first and second kind, respectively.

Selecting matches is done by moving the mark around using the zle movement
functions.  When not all matches can be shown on the screen at the same
time, the list will scroll up and down when crossing the top or
bottom line.  The following zle functions have special meaning during
menu selection.  Note that the following always
perform the same task within the menu selection map and cannot be
replaced by user defined widgets, nor can the set of functions
be extended:

@code{accept-line}, @code{accept-search}

@quotation

accept the current match and leave menu selection (but do
not cause the command line to be accepted)
@end quotation

@code{send-break}

@quotation

leaves menu selection and restores the previous contents of the
command line
@end quotation

@code{redisplay}, @code{clear-screen}

@quotation

execute their normal function without leaving menu selection
@end quotation

@code{accept-and-hold}, @code{accept-and-menu-complete}

@quotation

accept the currently inserted match and continue selection allowing to
select the next match to insert into the line
@end quotation

@code{accept-and-infer-next-history}

@quotation

accepts the current match and then tries completion with
menu selection again;  in the case of files this allows one to select
a directory and immediately attempt to complete files in it;  if there
are no matches, a message is shown and one can use @code{undo} to go back
to completion on the previous level, every other key leaves menu
selection (including the other zle functions which are otherwise
special during menu selection)
@end quotation

@code{undo}

@quotation

removes matches inserted during the menu selection by one of the three
functions before
@end quotation

@code{down-history}, @code{down-line-or-history}

@code{vi-down-line-or-history},  @code{down-line-or-search}

@quotation

moves the mark one line down
@end quotation

@code{up-history}, @code{up-line-or-history}

@code{vi-up-line-or-history}, @code{up-line-or-search}

@quotation

moves the mark one line up
@end quotation

@code{forward-char}, @code{vi-forward-char}

@quotation

moves the mark one column right
@end quotation

@code{backward-char}, @code{vi-backward-char}

@quotation

moves the mark one column left
@end quotation

@code{forward-word}, @code{vi-forward-word}

@code{vi-forward-word-end}, @code{emacs-forward-word}

@quotation

moves the mark one screenful down
@end quotation

@code{backward-word}, @code{vi-backward-word}, @code{emacs-backward-word}

@quotation

moves the mark one screenful up
@end quotation

@code{vi-forward-blank-word}, @code{vi-forward-blank-word-end}

@quotation

moves the mark to the first line of the next group of matches
@end quotation

@code{vi-backward-blank-word}

@quotation

moves the mark to the last line of the previous group of matches
@end quotation

@code{beginning-of-history}

@quotation

moves the mark to the first line
@end quotation

@code{end-of-history}

@quotation

moves the mark to the last line
@end quotation

@code{beginning-of-buffer-or-history}, @code{beginning-of-line}

@code{beginning-of-line-hist}, @code{vi-beginning-of-line}

@quotation

moves the mark to the leftmost column
@end quotation

@code{end-of-buffer-or-history}, @code{end-of-line}

@code{end-of-line-hist}, @code{vi-end-of-line}

@quotation

moves the mark to the rightmost column
@end quotation

@code{complete-word}, @code{menu-complete}, @code{expand-or-complete}

@code{expand-or-complete-prefix}, @code{menu-expand-or-complete}

@quotation

moves the mark to the next match
@end quotation

@code{reverse-menu-complete}

@quotation

moves the mark to the previous match
@end quotation

@code{vi-insert}

@quotation

this toggles between normal and interactive mode; in interactive mode
the keys bound to @code{self-insert} and @code{self-insert-unmeta} insert
into the command line as in normal editing mode but without leaving
menu selection; after each character completion is tried again and the
list changes to contain only the new matches; the completion widgets
make the longest unambiguous string be inserted in the command line
and @code{undo} and @code{backward-delete-char} go back to the previous set
of matches
@end quotation

@code{history-incremental-search-forward}

@code{history-incremental-search-backward}

@quotation

this starts incremental searches in the list of completions displayed;
in this mode, @code{accept-line} only leaves incremental search, going
back to the normal menu selection mode
@end quotation

All movement functions wrap around at the edges; any other zle function not
listed leaves menu selection and executes that function.  It is possible to
make widgets in the above list do the same by using the form of the widget
with a @code{.} in front.  For example, the widget @code{.accept-line} has
the effect of leaving menu selection and accepting the entire command line.

During this selection the widget uses the keymap @code{menuselect}.  Any
key that is not defined in this keymap or that is bound to
@code{undefined-key} is looked up in the keymap currently selected.  This
is used to ensure that the most important keys used during selection
(namely the cursor keys, return, and TAB) have sensible defaults.  However,
keys in the @code{menuselect} keymap can be modified directly using the
@code{bindkey} builtin command (see @ref{ba,,Zle Builtins}).
For example, to make the return key leave menu selection without
accepting the match currently selected one could call

@example
 bindkey -M menuselect '^M' send-break
@end example

after loading the @code{zsh/complist} module.

@node The zsh/computil Module,The zsh/curses Module,The zsh/complist Module,Zsh Modules
@anchor{Zsh/modules id7}@anchor{12c}@anchor{Zsh/modules the-zsh-computil-module}@anchor{bd}
@section The zsh/computil Module


@geindex completion@comma{} utility; Command

The @code{zsh/computil} module adds several builtin commands that are used by
some of the completion functions in the completion system based on shell
functions (see @code{zshcompsys}).
Except for @code{compquote} these builtin commands are very
specialised and thus not very interesting when writing your own
completion functions.  In summary, these builtin commands are:

@geindex comparguments; Function

@code{comparguments}

@quotation

This is used by the @code{_arguments} function to do the argument and
command line parsing.  Like @code{compdescribe} it has an option @code{-i} to
do the parsing and initialize some internal state and various options
to access the state information to decide what should be completed.
@end quotation

@geindex compdescribe; Function

@code{compdescribe}

@quotation

This is used by the @code{_describe} function to build the displays for
the matches and to get the strings to add as matches with their
options.  On the first call one of the options @code{-i} or @code{-I} should be
supplied as the first argument.  In the first case, display strings without
the descriptions will be generated, in the second case, the string used to
separate the matches from their descriptions must be given as the
second argument and the descriptions (if any) will be shown.  All other
arguments are like the definition arguments to @code{_describe} itself.

Once @code{compdescribe} has been called with either the @code{-i} or the
@code{-I} option, it can be repeatedly called with the @code{-g} option and
the names of four parameters as its arguments.  This will step through
the different sets of matches and store the value of @code{compstate[list]}
in the first scalar, the options for @code{compadd} in the second array,
the matches in the third array, and the strings to be displayed in the
completion listing in the fourth array.  The arrays may then be directly
given to @code{compadd} to register the matches with the completion code.
@end quotation

@geindex compfiles; Function

@code{compfiles}

@quotation

Used by the @code{_path_files} function to optimize complex recursive
filename generation (globbing).  It does three things.  With the
@code{-p} and @code{-P} options it builds the glob patterns to use,
including the paths already handled and trying to optimize the
patterns with respect to the prefix and suffix from the line and the
match specification currently used.  The @code{-i} option does the
directory tests for the @code{ignore-parents} style and the @code{-r} option
tests if a component for some of the matches are equal to the string
on the line and removes all other matches if that is true.
@end quotation

@geindex compgroups; Function

@code{compgroups}

@quotation

Used by the @code{_tags} function to implement the internals of the
@code{group-order} style.  This only takes its arguments as names of
completion groups and creates the groups for it (all six types: sorted
and unsorted, both without removing duplicates, with removing all
duplicates and with removing consecutive duplicates).
@end quotation

@geindex compquote; Function

@code{compquote} [ @code{-p} ] @var{names} …

@quotation

There may be reasons to write completion functions that have to add
the matches using the @code{-Q} option to @code{compadd} and perform quoting
themselves.  Instead of interpreting the first character of the
@code{all_quotes} key of the @code{compstate} special association and using
the @code{q} flag for parameter expansions, one can use this builtin
command.  The arguments are the names of scalar or array parameters
and the values of these parameters are quoted as needed for the
innermost quoting level.  If the @code{-p} option is given, quoting is
done as if there is some prefix before the values of the parameters,
so that a leading equal sign will not be quoted.

The return status is non-zero in case of an error and zero otherwise.
@end quotation

@geindex comptags; Function

@geindex comptry; Function

@code{comptags}

@code{comptry}

@quotation

These implement the internals of the tags mechanism.
@end quotation

@geindex compvalues; Function

@code{compvalues}

@quotation

Like @code{comparguments}, but for the @code{_values} function.
@end quotation

@node The zsh/curses Module,The zsh/datetime Module,The zsh/computil Module,Zsh Modules
@anchor{Zsh/modules id8}@anchor{12d}@anchor{Zsh/modules the-zsh-curses-module}@anchor{10f}
@section The zsh/curses Module


The @code{zsh/curses} module makes available one builtin command and
various parameters.

@menu
* Builtin:: 
* Parameters: Parameters<2>. 

@end menu

@node Builtin,Parameters<2>,,The zsh/curses Module
@anchor{Zsh/modules builtin}@anchor{12e}
@subsection Builtin


@geindex zcurses; Function

@geindex windows@comma{} curses; Command

@code{zcurses} @code{init}

@code{zcurses} @code{end}

@code{zcurses} @code{addwin} @var{targetwin} @var{nlines} @var{ncols} @var{begin_y} @var{begin_x} [ @var{parentwin} ]

@code{zcurses} @code{delwin} @var{targetwin}

@code{zcurses} @code{refresh} [ @var{targetwin} … ]

@code{zcurses} @code{touch} @var{targetwin} …

@code{zcurses} @code{move} @var{targetwin} @var{new_y} @var{new_x}

@code{zcurses} @code{clear} @var{targetwin} [ @code{redraw} | @code{eol} | @code{bot} ]

@code{zcurses} @code{position} @var{targetwin} @var{array}

@code{zcurses} @code{char} @var{targetwin} @var{character}

@code{zcurses} @code{string} @var{targetwin} @var{string}

@code{zcurses} @code{border} @var{targetwin} @var{border}

@code{zcurses} @code{attr} @var{targetwin} [ [@code{+|-}]:var:@cite{attribute} | @var{fg_col}@code{/}@var{bg_col} ] […]

@code{zcurses} @code{bg} @var{targetwin} [ [@code{+|-}]:var:@cite{attribute} | @var{fg_col}@code{/}@var{bg_col} | @code{@@}@var{char} ] […]

@code{zcurses} @code{scroll} @var{targetwin} [ @code{on} | @code{off} | [@code{+|-}]:var:@cite{lines} ]

@code{zcurses} @code{input} @var{targetwin} [ @var{param} [ @var{kparam} [ @var{mparam} ] ] ]

@code{zcurses} @code{mouse} [ @code{delay} @var{num} | [@code{+|-]motion} ]

@code{zcurses} @code{timeout} @var{targetwin} @var{intval}

@code{zcurses} @code{querychar} @var{targetwin} [ @var{param} ]

@code{zcurses} @code{resize} @var{height} @var{width} [ @code{endwin} | @code{nosave} | @code{endwin_nosave} ]

@quotation

Manipulate curses windows.  All uses of this command should be
bracketed by @code{zcurses init} to initialise use of curses, and
@code{zcurses end} to end it; omitting @code{zcurses end} can cause
the terminal to be in an unwanted state.

The subcommand @code{addwin} creates a window with @var{nlines} lines and
@var{ncols} columns.  Its upper left corner will be placed at row
@var{begin_y} and column
@var{begin_x} of the screen.  @var{targetwin} is a string and refers
to the name of a window that is not currently assigned.  Note
in particular the curses convention that vertical values appear
before horizontal values.

If @code{addwin} is given an existing window as the final argument, the new
window is created as a subwindow of @var{parentwin}.  This differs from an
ordinary new window in that the memory of the window contents is shared
with the parent’s memory.  Subwindows must be deleted before their parent.
Note that the coordinates of subwindows are relative to the screen, not
the parent, as with other windows.

Use the subcommand @code{delwin} to delete a window created with
@code{addwin}.  Note that @code{end} does `not' implicitly delete windows,
and that @code{delwin} does not erase the screen image of the window.

The window corresponding to the full visible screen is called
@code{stdscr}; it always exists after @code{zcurses init} and cannot
be delete with @code{delwin}.

The subcommand @code{refresh} will refresh window @var{targetwin}; this is
necessary to make any pending changes (such as characters you have
prepared for output with @code{char}) visible on the screen.  @code{refresh}
without an argument causes the screen to be cleared and redrawn.
If multiple windows are given, the screen is updated once at the end.

The subcommand @code{touch} marks the @var{targetwin}s listed as changed.
This is necessary before @code{refresh}ing windows if a window that
was in front of another window (which may be @code{stdscr}) is deleted.

The subcommand @code{move} moves the cursor position in @var{targetwin} to
new coordinates @var{new_y} and @var{new_x}.  Note that the
subcommand @code{string} (but not the subcommand @code{char}) advances the
cursor position over the characters added.

The subcommand @code{clear} erases the contents of @var{targetwin}.  One
(and no more than one) of three options may be specified.  With the
option @code{redraw}, in addition the next @code{refresh} of @var{targetwin}
will cause the screen to be cleared and repainted.  With the option
@code{eol}, @var{targetwin} is only cleared to the end of the current cursor
line.  With the option
@code{bot}, @var{targetwin} is cleared to the end of the window, i.e
everything to the right and below the cursor is cleared.

The subcommand @code{position} writes various positions associated with
@var{targetwin} into the array named @var{array}.
These are, in order:


@itemize -

@item 
The y and x coordinates of the cursor relative to the top left
of @var{targetwin}

@item 
The y and x coordinates of the top left of @var{targetwin} on the
screen

@item 
The size of @var{targetwin} in y and x dimensions.
@end itemize

Outputting characters and strings are achieved by @code{char} and @code{string}
respectively.

To draw a border around window @var{targetwin}, use @code{border}.  Note
that the border is not subsequently handled specially:  in other words,
the border is simply a set of characters output at the edge of the
window.  Hence it can be overwritten, can scroll off the window, etc.

The subcommand @code{attr} will set @var{targetwin}’s attributes or
foreground/background color pair for any successive character output.
Each @var{attribute} given on the line may be prepended by a @code{+} to set
or a @code{-} to unset that attribute; @code{+} is assumed if absent.  The
attributes supported are @code{blink}, @code{bold}, @code{dim}, @code{reverse},
@code{standout}, and @code{underline}.

Each @var{fg_col}@code{/}@var{bg_col} attribute (to be read as
@var{fg_col} on @var{bg_col}) sets the foreground and background color
for character output.  The color @code{default} is sometimes available
(in particular if the library is ncurses), specifying the foreground
or background color with which the terminal started.  The color pair
@code{default/default} is always available. To use more than the 8 named
colors (red, green, etc.) construct the @var{fg_col}@code{/}@var{bg_col}
pairs where @var{fg_col} and @var{bg_col} are decimal integers, e.g
@code{128/200}.  The maximum color value is 254 if the terminal supports
256 colors.

@code{bg} overrides the color and other attributes of all characters in the
window.  Its usual use is to set the background initially, but it will
overwrite the attributes of any characters at the time when it is called.
In addition to the arguments allowed with @code{attr}, an argument @code{@@}@var{char}
specifies a character to be shown in otherwise blank areas of the window.
Owing to limitations of curses this cannot be a multibyte character
(use of ASCII characters only is recommended).  As the specified set
of attributes override the existing background, turning attributes
off in the arguments is not useful, though this does not cause an error.

The subcommand @code{scroll} can be used with @code{on} or @code{off} to enabled
or disable scrolling of a window when the cursor would otherwise move
below the window due to typing or output.  It can also be used with a
positive or negative integer to scroll the window up or down the given
number of lines without changing the current cursor position (which
therefore appears to move in the opposite direction relative to the
window).  In the second case, if scrolling is @code{off} it is temporarily
turned @code{on} to allow the window to be scrolled.

The subcommand @code{input} reads a single character from the window
without echoing it back.  If @var{param} is supplied the character is
assigned to the parameter @var{param}, else it is assigned to the
parameter @code{REPLY}.

If both @var{param} and @var{kparam} are supplied, the key is read in
`keypad’ mode.  In this mode special keys such as function keys and
arrow keys return the name of the key in the parameter @var{kparam}.  The
key names are the macros defined in the @code{curses.h} or @code{ncurses.h}
with the prefix @code{KEY_} removed; see also the description of the
parameter @code{zcurses_keycodes} below.  Other keys cause a value to be
set in @var{param} as before.  On a successful return only one of
@var{param} or @var{kparam} contains a non-empty string; the other is set
to an empty string.

If @var{mparam} is also supplied, @code{input} attempts to handle mouse
input.  This is only available with the ncurses library; mouse handling
can be detected by checking for the exit status of @code{zcurses mouse} with
no arguments.  If a mouse
button is clicked (or double- or triple-clicked, or pressed or released with
a configurable delay from being clicked) then @var{kparam} is set to the string
@code{MOUSE}, and @var{mparam} is set to an array consisting of the
following elements:


@itemize -

@item 
An identifier to discriminate different input devices; this
is only rarely useful.

@item 
The x, y and z coordinates of the mouse click relative to
the full screen, as three elements in that order (i.e. the y coordinate
is, unusually, after the x coordinate).  The z coordinate is only
available for a few unusual input devices and is otherwise set to zero.

@item 
Any events that occurred as separate items; usually
there will be just one.  An event consists of @code{PRESSED}, @code{RELEASED},
@code{CLICKED}, @code{DOUBLE_CLICKED} or @code{TRIPLE_CLICKED} followed
immediately (in the same element) by the number of the button.

@item 
If the shift key was pressed, the string @code{SHIFT}.

@item 
If the control key was pressed, the string @code{CTRL}.

@item 
If the alt key was pressed, the string @code{ALT}.
@end itemize

Not all mouse events may be passed through to the terminal window;
most terminal emulators handle some mouse events themselves.  Note
that the ncurses manual implies that using input both with and
without mouse handling may cause the mouse cursor to appear and
disappear.

The subcommand @code{mouse} can be used to configure the use of the mouse.
There is no window argument; mouse options are global.
@code{zcurses mouse} with no arguments returns status 0 if mouse handling
is possible, else status 1.  Otherwise, the possible arguments (which
may be combined on the same command line) are as follows.
@code{delay} @var{num} sets the maximum delay in milliseconds between press and
release events to be considered as a click; the value 0 disables click
resolution, and the default is one sixth of a second.  @code{motion} proceeded
by an optional @code{+} (the default) or @code{-} turns on or off
reporting of mouse motion in addition to clicks, presses and releases,
which are always reported.  However, it appears reports for mouse
motion are not currently implemented.

The subcommand @code{timeout} specifies a timeout value for input from
@var{targetwin}.  If @var{intval} is negative, @code{zcurses input} waits
indefinitely for a character to be typed; this is the default.  If
@var{intval} is zero, @code{zcurses input} returns immediately; if there
is typeahead it is returned, else no input is done and status 1 is
returned.  If @var{intval} is positive, @code{zcurses input} waits
@var{intval} milliseconds for input and if there is none at the end of
that period returns status 1.

The subcommand @code{querychar} queries the character at the current cursor
position.  The return values are stored in the array named @var{param} if
supplied, else in the array @code{reply}.  The first value is the character
(which may be a multibyte character if the system supports them); the
second is the color pair in the usual @var{fg_col}@code{/}@var{bg_col}
notation, or @code{0} if color is not supported.  Any attributes other than
color that apply to the character, as set with the subcommand @code{attr},
appear as additional elements.

The subcommand @code{resize} resizes @code{stdscr} and all windows to given
dimensions (windows that stick out from the new dimensions are resized
down). The underlying curses extension (@code{resize_term call}) can be
unavailable. To verify, zeroes can be used for @var{height} and
@var{width}. If the result of the subcommand is @code{0}, resize_term is
available (@code{2} otherwise). Tests show that resizing can be normally
accomplished by calling @code{zcurses end} and @code{zcurses refresh}. The
@code{resize} subcommand is provided for versatility. Multiple system
configurations have been checked and @code{zcurses end} and @code{zcurses
refresh} are still needed for correct terminal state after resize. To
invoke them with @code{resize}, use @var{endwin} argument.  Using
@var{nosave} argument will cause new terminal state to not be saved
internally by @code{zcurses}. This is also provided for versatility and
should normally be not needed.
@end quotation

@node Parameters<2>,,Builtin,The zsh/curses Module
@anchor{Zsh/modules parameters}@anchor{12f}
@subsection Parameters


@geindex ZCURSES_COLORS; Variable

@code{ZCURSES_COLORS}

@quotation

Readonly integer.  The maximum number of colors the terminal
supports.  This value is initialised by the curses library and is not
available until the first time @code{zcurses init} is run.
@end quotation

@geindex ZCURSES_COLOR_PAIRS; Variable

@code{ZCURSES_COLOR_PAIRS}

@quotation

Readonly integer.  The maximum number of color pairs
@var{fg_col}@code{/}@var{bg_col} that may be defined in @code{zcurses attr}
commands; note this limit applies to all color pairs that have been
used whether or not they are currently active.  This value is initialised
by the curses library and is not available until the first time @code{zcurses
init} is run.
@end quotation

@geindex zcurses_attrs; Variable

@code{zcurses_attrs}

@quotation

Readonly array.  The attributes supported by @code{zsh/curses}; available
as soon as the module is loaded.
@end quotation

@geindex zcurses_colors; Variable

@code{zcurses_colors}

@quotation

Readonly array.  The colors supported by @code{zsh/curses}; available
as soon as the module is loaded.
@end quotation

@geindex zcurses_keycodes; Variable

@code{zcurses_keycodes}

@quotation

Readonly array.  The values that may be returned in the second
parameter supplied to @code{zcurses input} in the order in which they
are defined internally by curses.  Not all function keys
are listed, only @code{F0}; curses reserves space for @code{F0} up to @code{F63}.
@end quotation

@geindex zcurses_windows; Variable

@code{zcurses_windows}

@quotation

Readonly array.  The current list of windows, i.e. all windows that
have been created with @code{zcurses addwin} and not removed with
@code{zcurses delwin}.
@end quotation

@node The zsh/datetime Module,The zsh/db/gdbm Module,The zsh/curses Module,Zsh Modules
@anchor{Zsh/modules id9}@anchor{130}@anchor{Zsh/modules the-zsh-datetime-module}@anchor{110}
@section The zsh/datetime Module


The @code{zsh/datetime} module makes available one builtin command:

@geindex strftime; Function

@geindex date string@comma{} printing; Command

@code{strftime} [ @code{-s} @var{scalar} | @code{-n} ] @var{format} [ @var{epochtime} [ @var{nanoseconds} ] ]

@code{strftime} @code{-r} [ @code{-q} ] [ @code{-s} @var{scalar} | @code{-n} ] @var{format} @var{timestring}

@quotation

Output the date in the @var{format} specified.  With no @var{epochtime}, the
current system date/time is used; optionally, @var{epochtime} may be used to
specify the number of seconds since the epoch, and @var{nanoseconds} may
additionally be used to specify the number of nanoseconds past the second
(otherwise that number is assumed to be 0).
See @code{strftime(3)} for details.  The zsh extensions described
under @code{%D@{}@var{string}@code{@}} prompt eqcape in
@ref{131,,Simple Prompt Escapes} are also available.

@code{-n}

@quotation

Suppress printing a newline after the formatted string.
@end quotation

@code{-q}

@quotation

Run quietly; suppress printing of all error messages described below.
Errors for invalid @var{epochtime} values are always printed.
@end quotation

@code{-r}

@quotation

With the option @code{-r} (reverse), use @var{format} to parse the input
string @var{timestring} and output the number of seconds since the epoch at
which the time occurred.  The parsing is implemented by the system
function @code{strptime}; see @code{strptime(3)}.  This means that zsh
format extensions are not available, but for reverse lookup they are not
required.

In most implementations of @code{strptime} any timezone in the
@var{timestring} is ignored and the local timezone declared by the @code{TZ}
environment variable is used; other parameters are set to zero if not
present.

If @var{timestring} does not match @var{format} the command returns status 1
and prints an error message.  If @var{timestring} matches @var{format} but
not all characters in @var{timestring} were used, the conversion succeeds
but also prints an error message.

If either of the system functions @code{strptime} or @code{mktime} is not
available, status 2 is returned and an error message is printed.
@end quotation

@code{-s} @var{scalar}

@quotation

Assign the date string (or epoch time in seconds if @code{-r} is given) to
@var{scalar} instead of printing it.
@end quotation

Note that depending on the system’s declared integral time type,
@code{strftime} may produce incorrect results for epoch times greater than
2147483647 which corresponds to 2038-01-19 03:14:07 +0000.
@end quotation

The @code{zsh/datetime} module makes available several parameters;
all are readonly:

@geindex EPOCHREALTIME; Variable

@code{EPOCHREALTIME}

@quotation

A floating point value representing the number of seconds since
the epoch.  The notional accuracy is to nanoseconds if the
@code{clock_gettime} call is available and to microseconds otherwise,
but in practice the range of double precision floating point and
shell scheduling latencies may be significant effects.
@end quotation

@geindex EPOCHSECONDS; Variable

@code{EPOCHSECONDS}

@quotation

An integer value representing the number of seconds since the
epoch.
@end quotation

@geindex epochtime; Variable

@code{epochtime}

@quotation

An array value containing the number of seconds since the epoch
in the first element and the remainder of the time since the epoch
in nanoseconds in the second element.  To ensure the two elements
are consistent the array should be copied or otherwise referenced
as a single substitution before the values are used.  The following
idiom may be used:

@example
 for secs nsecs in $epochtime; do
   ...
 done
@end example
@end quotation

@node The zsh/db/gdbm Module,The zsh/deltochar Module,The zsh/datetime Module,Zsh Modules
@anchor{Zsh/modules id10}@anchor{132}@anchor{Zsh/modules the-zsh-db-gdbm-module}@anchor{111}
@section The zsh/db/gdbm Module


The @code{zsh/db/gdbm} module is used to create “tied” associative arrays
that interface to database files.  If the GDBM interface is not available,
the builtins defined by this module will report an error.  This module is
also intended as a prototype for creating additional database interfaces,
so the @code{ztie} builtin may move to a more generic module in the future.

The builtins in this module are:

@geindex ztie; Function

@geindex database tied array@comma{} creating; Command

@code{ztie -d db/gdbm -f} @var{filename} [ @code{-r} ] @var{arrayname}

@quotation

Open the GDBM database identified by @var{filename} and, if successful,
create the associative array @var{arrayname} linked to the file.  To create
a local tied array, the parameter must first be declared, so commands
similar to the following would be executed inside a function scope:

@example
 local -A sampledb
 ztie -d db/gdbm -f sample.gdbm sampledb
@end example

The @code{-r} option opens the database file for reading only, creating a
parameter with the readonly attribute.  Without this option, using
@code{ztie} on a file for which the user does not have write permission is
an error.  If writable, the database is opened synchronously so fields
changed in @var{arrayname} are immediately written to @var{filename}.

Changes to the file modes @var{filename} after it has been opened do not
alter the state of @var{arrayname}, but @code{typeset -r} @var{arrayname}
works as expected.
@end quotation

@geindex zuntie; Function

@geindex database tied array@comma{} destroying; Command

@code{zuntie} [ @code{-u} ] @var{arrayname} …

@quotation

Close the GDBM database associated with each @var{arrayname} and then
unset the parameter.  The @code{-u} option forces an unset of parameters
made readonly with @code{ztie -r}.

This happens automatically if the parameter is explicitly unset or its
local scope (function) ends.  Note that a readonly parameter may not be
explicitly unset, so the only way to unset a global parameter created with
@code{ztie -r} is to use @code{zuntie -u}.
@end quotation

@geindex zgdbmpath; Function

@geindex database file path@comma{} reading; Command

@code{zgdbmpath} @var{parametername}

@quotation

Put path to database file assigned to @var{parametername} into @code{REPLY}
scalar.
@end quotation

@geindex zgdbm_tied; Function

@geindex database tied arrays@comma{} enumerating; Command

@code{zgdbm_tied}

@quotation

Array holding names of all tied parameters.
@end quotation

The fields of an associative array tied to GDBM are neither cached nor
otherwise stored in memory, they are read from or written to the database
on each reference.  Thus, for example, the values in a readonly array may
be changed by a second writer of the same database file.

@node The zsh/deltochar Module,The zsh/example Module,The zsh/db/gdbm Module,Zsh Modules
@anchor{Zsh/modules id11}@anchor{133}@anchor{Zsh/modules the-zsh-deltochar-module}@anchor{112}
@section The zsh/deltochar Module


The @code{zsh/deltochar} module makes available two ZLE functions:

@geindex delete-to-char; Type

@code{delete-to-char}

@quotation

Read a character from the keyboard, and
delete from the cursor position up to and including the next
(or, with repeat count @var{n}, the @var{n}th) instance of that character.
Negative repeat counts mean delete backwards.
@end quotation

@geindex zap-to-char; Type

@code{zap-to-char}

@quotation

This behaves like @code{delete-to-char}, except that the final occurrence of
the character itself is not deleted.
@end quotation

@node The zsh/example Module,The zsh/files Module,The zsh/deltochar Module,Zsh Modules
@anchor{Zsh/modules id12}@anchor{134}@anchor{Zsh/modules the-zsh-example-module}@anchor{113}
@section The zsh/example Module


The @code{zsh/example} module makes available one builtin command:

@geindex example; Function

@geindex modules@comma{} example; Command

@geindex modules@comma{} writing; Command

@geindex writing modules; Command

@code{example} [ @code{-flags} ] [ @var{args} … ]

@quotation

Displays the flags and arguments it is invoked with.
@end quotation

The purpose of the module is to serve as an example of how to write a
module.

@node The zsh/files Module,The zsh/hlgroup Module,The zsh/example Module,Zsh Modules
@anchor{Zsh/modules id13}@anchor{135}@anchor{Zsh/modules the-zsh-files-module}@anchor{114}
@section The zsh/files Module


@geindex files@comma{} manipulating; Command

The @code{zsh/files} module makes available some common commands for file
manipulation as builtins; these commands are probably not needed for
many normal situations but can be useful in emergency recovery
situations with constrained resources.  The commands do not implement
all features now required by relevant standards committees.

For all commands, a variant beginning @code{zf_} is also available and loaded
automatically.  Using the features capability of zmodload will let you load
only those names you want.  Note that it’s possible to load only the
builtins with zsh-specific names using the following command:

@example
 zmodload -m -F zsh/files b:zf_\*
@end example

The commands loaded by default are:

@geindex chgrp; Function

@code{chgrp} [ @code{-hRs} ] @var{group} @var{filename} …

@quotation

Changes group of files specified.  This is equivalent to @code{chown} with
a @var{user-spec} argument of @code{:}@var{group}.
@end quotation

@geindex chmod; Function

@code{chmod} [ @code{-Rs} ] @var{mode} @var{filename} …

@quotation

Changes mode of files specified.

The specified @var{mode} must be in octal.

The @code{-R} option causes @code{chmod} to recursively descend into directories,
changing the mode of all files in the directory after
changing the mode of the directory itself.

The @code{-s} option is a zsh extension to @code{chmod} functionality.  It enables
paranoid behaviour, intended to avoid security problems involving
a @code{chmod} being tricked into affecting files other than the ones
intended.  It will refuse to follow symbolic links, so that (for example)
@code{`chmod 600 /tmp/foo/passwd}’ can’t accidentally chmod @code{/etc/passwd}
if @code{/tmp/foo} happens to be a link to @code{/etc}.  It will also check
where it is after leaving directories, so that a recursive chmod of
a deep directory tree can’t end up recursively chmoding @code{/usr} as
a result of directories being moved up the tree.
@end quotation

@geindex chown; Function

@code{chown} [ @code{-hRs} ] @var{user-spec} @var{filename} …

@quotation

Changes ownership and group of files specified.

The @var{user-spec} can be in four forms:


@table @asis

@item @var{user}

change owner to @var{user}; do not change group

@item @var{user}@code{::}

change owner to @var{user}; do not change group

@item @var{user}@code{:}

change owner to @var{user}; change group to @var{user}’s primary group

@item @var{user}@code{:}@var{group}

change owner to @var{user}; change group to @var{group}

@item @code{:}@var{group}

do not change owner; change group to @var{group}
@end table

In each case, the @code{:} may instead be a @code{.}.  The rule is that
if there is a @code{:} then the separator is @code{:}, otherwise
if there is a @code{.} then the separator is @code{.}, otherwise
there is no separator.

Each of @var{user} and @var{group} may be either a username (or group name, as
appropriate) or a decimal user ID (group ID).  Interpretation as a name
takes precedence, if there is an all-numeric username (or group name).

If the target is a symbolic link, the @code{-h} option causes @code{chown} to set
the ownership of the link instead of its target.

The @code{-R} option causes @code{chown} to recursively descend into directories,
changing the ownership of all files in the directory after
changing the ownership of the directory itself.

The @code{-s} option is a zsh extension to @code{chown} functionality.  It enables
paranoid behaviour, intended to avoid security problems involving
a @code{chown} being tricked into affecting files other than the ones
intended.  It will refuse to follow symbolic links, so that (for example)
@code{`chown luser /tmp/foo/passwd}’ can’t accidentally chown @code{/etc/passwd}
if @code{/tmp/foo} happens to be a link to @code{/etc}.  It will also check
where it is after leaving directories, so that a recursive chown of
a deep directory tree can’t end up recursively chowning @code{/usr} as
a result of directories being moved up the tree.
@end quotation

@geindex ln; Function

@code{ln} [ @code{-dfhins} ] @var{filename} @var{dest}

@code{ln} [ @code{-dfhins} ] @var{filename} … @var{dir}

@quotation

Creates hard (or, with @code{-s}, symbolic) links.  In the first form, the
specified @var{dest}ination is created, as a link to the specified
@var{filename}.  In the second form, each of the @var{filename}s is
taken in turn, and linked to a pathname in the specified @var{dir}ectory
that has the same last pathname component.

Normally, @code{ln} will not attempt to create hard links to
directories.  This check can be overridden using the @code{-d} option.
Typically only the super-user can actually succeed in creating
hard links to directories.
This does not apply to symbolic links in any case.

By default, existing files cannot be replaced by links.
The @code{-i} option causes the user to be queried about replacing
existing files.  The @code{-f} option causes existing files to be
silently deleted, without querying.  @code{-f} takes precedence.

The @code{-h} and @code{-n} options are identical and both exist for
compatibility; either one indicates that if the target is a symlink
then it should not be dereferenced.
Typically this is used in combination with @code{-sf} so that if an
existing link points to a directory then it will be removed,
instead of followed.
If this option is used with multiple filenames and the target
is a symbolic link pointing to a directory then the result is
an error.
@end quotation

@geindex mkdir; Function

@code{mkdir} [ @code{-p} ] [ @code{-m} @var{mode} ] @var{dir} …

@quotation

Creates directories.  With the @code{-p} option, non-existing parent
directories are first created if necessary, and there will be
no complaint if the directory already exists.
The @code{-m} option can be used to specify (in octal) a set of file permissions
for the created directories, otherwise mode 777 modified by the current
@code{umask} (see @code{umask(2)}) is used.
@end quotation

@geindex mv; Function

@code{mv} [ @code{-fi} ] @var{filename} @var{dest}

@code{mv} [ @code{-fi} ] @var{filename} … @var{dir}

@quotation

Moves files.  In the first form, the specified @var{filename} is moved
to the specified @var{dest}ination.  In the second form, each of the
@var{filename}s is
taken in turn, and moved to a pathname in the specified @var{dir}ectory
that has the same last pathname component.

By default, the user will be queried before replacing any file
that the user cannot write to, but writable files will be silently
removed.
The @code{-i} option causes the user to be queried about replacing
any existing files.  The @code{-f} option causes any existing files to be
silently deleted, without querying.  @code{-f} takes precedence.

Note that this @code{mv} will not move files across devices.
Historical versions of @code{mv}, when actual renaming is impossible,
fall back on copying and removing files; if this behaviour is desired,
use @code{cp} and @code{rm} manually.  This may change in a future version.
@end quotation

@geindex rm; Function

@code{rm} [ @code{-dfiRrs} ] @var{filename} …

@quotation

Removes files and directories specified.

Normally, @code{rm} will not remove directories (except with the @code{-R} or @code{-r}
options).  The @code{-d} option causes @code{rm} to try removing directories
with @code{unlink} (see @code{unlink(2)}), the same method used for files.
Typically only the super-user can actually succeed in unlinking
directories in this way.
@code{-d} takes precedence over @code{-R} and @code{-r}.

By default, the user will be queried before removing any file
that the user cannot write to, but writable files will be silently
removed.
The @code{-i} option causes the user to be queried about removing
any files.  The @code{-f} option causes files to be
silently deleted, without querying, and suppresses all error indications.
@code{-f} takes precedence.

The @code{-R} and @code{-r} options cause @code{rm} to recursively descend into
directories, deleting all files in the directory before removing the directory
with the @code{rmdir} system call (see @code{rmdir(2)}).

The @code{-s} option is a zsh extension to @code{rm} functionality.  It enables
paranoid behaviour, intended to avoid common security problems involving
a root-run @code{rm} being tricked into removing files other than the ones
intended.  It will refuse to follow symbolic links, so that (for example)
@code{`rm /tmp/foo/passwd}’ can’t accidentally remove @code{/etc/passwd}
if @code{/tmp/foo} happens to be a link to @code{/etc}.  It will also check
where it is after leaving directories, so that a recursive removal of
a deep directory tree can’t end up recursively removing @code{/usr} as
a result of directories being moved up the tree.
@end quotation

@geindex rmdir; Function

@code{rmdir} @var{dir} …

@quotation

Removes empty directories specified.
@end quotation

@geindex sync; Function

@code{sync}

@quotation

Calls the system call of the same name (see @code{sync(2)}), which
flushes dirty buffers to disk.  It might return before the I/O has
actually been completed.
@end quotation

@node The zsh/hlgroup Module,The zsh/langinfo Module,The zsh/files Module,Zsh Modules
@anchor{Zsh/modules id14}@anchor{136}@anchor{Zsh/modules the-zsh-hlgroup-module}@anchor{115}
@section The zsh/hlgroup Module


The @code{zsh/hlgroup} module defines special parameters that represent
highlighting groups in different forms to ease the use of the groups when
configuring other tools.

In each case, these are readonly associative arrays where accessing elements
uses values from the underlying @code{.zle.hlgroups} variable.

@geindex .zle.esc; Variable

@code{.zle.esc}

@quotation

This associative array contains the literal escape sequences used to apply the
highlighting for each group. An example use would be when setting the
@code{LESS_TERMCAP_xx} environment variables for the @code{less} pager.
@end quotation

@geindex .zle.sgr; Variable

@code{.zle.sgr}

@quotation

Where highlighting makes use of CSI escape sequences, this parameter contains
the “Select Graphic Rendition” number sequence. This is useful with, for
example the @code{GREP_COLORS} and  @code{LSCOLORS} environment variables and the
@code{list-colors} style.
@end quotation

@node The zsh/langinfo Module,The zsh/ksh93 Module,The zsh/hlgroup Module,Zsh Modules
@anchor{Zsh/modules id15}@anchor{137}@anchor{Zsh/modules the-zsh-langinfo-module}@anchor{116}
@section The zsh/langinfo Module


The @code{zsh/langinfo} module makes available one parameter:

@geindex langinfo; Variable

@code{langinfo}

@quotation

An associative array that maps langinfo elements to
their values.

Your implementation may support a number of the following keys:

@code{CODESET},
@code{D_T_FMT},
@code{D_FMT},
@code{T_FMT},
@code{RADIXCHAR},
@code{THOUSEP},
@code{YESEXPR},
@code{NOEXPR},
@code{CRNCYSTR},
@code{ABDAY_@{1..7@}},
@code{DAY_@{1..7@}},
@code{ABMON_@{1..12@}},
@code{MON_@{1..12@}},
@code{T_FMT_AMPM},
@code{AM_STR},
@code{PM_STR},
@code{ERA},
@code{ERA_D_FMT},
@code{ERA_D_T_FMT},
@code{ERA_T_FMT},
@code{ALT_DIGITS}
@end quotation

@node The zsh/ksh93 Module,The zsh/mapfile Module,The zsh/langinfo Module,Zsh Modules
@anchor{Zsh/modules id16}@anchor{138}@anchor{Zsh/modules the-zsh-ksh93-module}@anchor{117}
@section The zsh/ksh93 Module


@geindex ksh93; Command

The @code{zsh/ksh93} module provides one builtin and several parameters to
improve compatibility with ksh93.  As of this writing, several ksh93
features are still missing.

@menu
* Ksh Builtins:: 
* Ksh Parameters:: 
* Future Compatibility:: 
* Other Differences:: 

@end menu

@node Ksh Builtins,Ksh Parameters,,The zsh/ksh93 Module
@anchor{Zsh/modules ksh-builtins}@anchor{139}
@subsection Ksh Builtins


The single builtin provided by this module is:

@geindex nameref; Function

@geindex named references@comma{} creating; Command

@code{nameref} [ @code{-gpur} ] @var{pname}[@code{=}@var{rname}]

@quotation

Equivalent to @code{typeset -n} @var{pname}@code{=}@var{rname}

However, @code{nameref} is a builtin command rather than a reserved word,
so handling of assigments in the argument list may differ.
@end quotation

@node Ksh Parameters,Future Compatibility,Ksh Builtins,The zsh/ksh93 Module
@anchor{Zsh/modules ksh-parameters}@anchor{13a}
@subsection Ksh Parameters


@geindex parameters@comma{} ksh; Command

Parameters supplied by this module that are marked with `<K>’ below
are available only when ksh emulation is active before entry to the
shell function, that is, @code{emulate ksh} locally to a function does
not populate these parameters for that function.

@geindex .sh.command; Variable

@code{.sh.command}

@quotation

A named reference to @code{ZSH_DEBUG_CMD}
@end quotation

@geindex .sh.edchar; Variable

@code{.sh.edchar} <K>

@quotation

In a ZLE widget, equivalent to the @code{KEYS} special parameter.  In a
future release, assignments to this parameter will affect the input
stream seen by ZLE.
@end quotation

@geindex .sh.edcol; Variable

@code{.sh.edcol}

@quotation

A named reference to the ZLE special parameter @code{CURSOR}.
@end quotation

@geindex .sh.edmode; Variable

@code{.sh.edmode} <K>

@quotation

In a ZLE widget, this parameter has the value @code{ESC} (@code{$'\e'}) if the
@code{VI} option is set and the @code{main} keymap is selected.  This is
intended for use with vi-mode key bindings (@code{bindkey -v}).  In a
future revision, assigning @code{.sh.edchar=$@{.sh.edmode@}} is expected
to initiate @code{vicmd} mode when @code{viins} is active, and do
nothing when @code{vicmd} is already active.
@end quotation

@geindex .sh.edtext; Variable

@code{.sh.edtext}

@quotation

A named reference to the @code{BUFFER} special ZLE parameter.
@end quotation

@geindex .sh.file; Variable

@code{.sh.file}

@quotation

A named reference to the @code{ZSH_SCRIPT} parameter.
@end quotation

@geindex .sh.fun; Variable

@code{.sh.fun} <K>

@quotation

In a shell function, the function’s name.  Usually the same as @code{$0},
but not affected by @code{POSIX_ARGZERO} or @code{FUNCTION_ARGZERO} options.
@end quotation

@geindex .sh.level; Variable

@code{.sh.level} <K>

@quotation

In a shell function, initially set to the depth of the call stack. This
may be assigned to change the apparent depth.  However, such assignment
does not affect the scope of local parameters.
@end quotation

@geindex .sh.lineno; Variable

@code{.sh.lineno}

@quotation

A named reference to the @code{LINENO} special parameter.
@end quotation

@geindex .sh.match; Variable

@code{.sh.match}

@quotation

An array equivalent to the @code{match} parameter as assigned by the
@code{(#b)} extended globbing flag.  When the
@code{KSH_ARRAYS} option is set, @code{$@{.sh.match[0]@}} gives the value of
the @code{MATCH} parameter as set by the @code{(#m)} extended
globbing flag.  Currently, the @code{EXTENDED_GLOB} option must be enabled
and those flags must be explicitly used in a pattern in order for these
values of @code{.sh.match} to be set.
@end quotation

@geindex .sh.name; Variable

@code{.sh.name} <K>

@quotation

When the @code{vared} command is used, this parameter may be used in
user-defined ZLE widgets to get the name of the variable being edited.
A future release is expected to use this parameter in the implementation
of “discipline functions”.
@end quotation

@geindex .sh.subscript; Variable

@code{.sh.subscript} <K>

@quotation

When @code{vared} has been used on an array element, this parameter holds
the array index (either a number, or an associative array key).
@end quotation

@geindex .sh.subshell; Variable

@code{.sh.subshell}

@quotation

A named reference to the @code{ZSH_SUBSHELL} parameter.
@end quotation

@geindex .sh.value; Variable

@code{.sh.value} <K>

@quotation

In @code{vared} this is a named reference to the ZLE special @code{BUFFER}.
A future release is expected to use this parameter in the implementation
of “discipline functions”.
@end quotation

@geindex .sh.version; Variable

@code{.sh.version}

@quotation

A named reference to @code{ZSH_PATCHLEVEL}.
@end quotation

@node Future Compatibility,Other Differences,Ksh Parameters,The zsh/ksh93 Module
@anchor{Zsh/modules future-compatibility}@anchor{13b}
@subsection Future Compatibility


The following features of ksh93 are not currently supported but may be
available in a future release.

@code{namespace} @var{ident} @code{@{} @var{list} @code{@}}

@quotation

This reserved word executes the current shell compound command
@code{@{} @var{list} @code{@}}, with the special behavior that all functions
and parameters @var{name} declared within @var{list} are implicitly
prefixed to become @code{.}@var{ident}@code{.}@var{name}, and similarly any
reference to a function or parameter @var{name} is searched for as
@code{.}@var{ident}@code{.}@var{name} before falling back to @var{name}.

`THIS FEATURE IS NOT YET IMPLEMENTED.'
@end quotation

@code{.sh.math} <K>

@quotation

This parameter is more accurately considered a namespace.  A function
definition of the form


@quotation

@code{function .sh.math.}@var{name} @var{ident} @code{... @{} @var{list} @code{@}}
@end quotation

is equivalent to the native zsh definition

@example
 @code{function} @var{name} @code{@{}
   @code{local} @var{ident}@code{=$1 ...}
   @var{list}
 @code{@}}
 @code{functions -M} @var{name} @code{1 3}
@end example

Up to 3 @var{ident} arguments, interpreted as floating point numbers,
may be provided for a function defined with @code{.sh.math} in this way.
The names (but not definitions) of all such functions are available
via @code{$@{.sh.math[@@]@}}.

`THIS FEATURE IS NOT YET IMPLEMENTED.'
@end quotation

@code{:var:`name}`.get`@w{`}`@w{`}

@quotation

A shell function having this name, if defined, is invoked whenever the
parameter @code{$@{}@var{name}@code{@}} is referenced, including by commands
such as @code{typeset -p}.  If the special variable @code{.sh.value} is
assigned by the function, that value is substituted instead of the
true value of @var{name}.  This does not change the value of @var{name},
but there is no way to access the actual value without first removing
the function.

Additionally, an explicit reference to @code{$@{}@var{name}@code{.get@}}
calls the function @var{name}@code{.get} even if there is no parameter
@var{name} and substitutes the standard output of the function.

`THIS FEATURE IS NOT YET IMPLEMENTED.'
@end quotation

@code{:var:`name}`.set`@w{`}`@w{`}

@code{:var:`name}`.append`@w{`}`@w{`}

@quotation

Shell functions having these names are invoked when the parameter
@var{name} is assigned or (for array types) has a new field appended.
The function may change the result of the operation by assigning to
the @code{.sh.value} special parameter, or block the change by
unsetting @code{.sh.value}.

Explicit reference to @code{$@{}@var{name}@code{.set@}} or @code{$@{}@var{name}@code{.append@}}
substitutes the standard output of the function.

`THIS FEATURE IS NOT YET IMPLEMENTED.'
@end quotation

@code{:var:`name}`.unset`@w{`}`@w{`}

@quotation

When a function of this name is defined, it is called whenever the
parameter @var{name} would be unset.  The function must explicitly
@code{unset} @var{name}, otherwise the variable remains set.

`THIS FEATURE IS NOT YET IMPLEMENTED.'
@end quotation

@code{typeset -C} @var{name}[@code{=}@var{values} @code{...}]

@quotation

Creates a `compound variable'.

`THIS FEATURE IS NOT YET IMPLEMENTED, and the syntax of :var:'values`
is unlikely to be fully ksh compatible.`
@end quotation

@node Other Differences,,Future Compatibility,The zsh/ksh93 Module
@anchor{Zsh/modules other-differences}@anchor{13c}
@subsection Other Differences


The following features of ksh93 are not currently supported and there are
no plans to implement them.

@var{pathdir}@code{/.paths}

@quotation

Each directory @var{pathdir} in the @code{PATH} parameter may contain a
text file @code{.paths} which may define additional directories to
be searched for function definitions (@code{FPATH}), external executables
(@code{PATH}), and plugin files (similar to @code{MODULE_PATH}).

`THIS FEATURE IS UNLIKELY EVER TO BE IMPLEMENTED.'
@end quotation

@code{builtin -f} @var{file}

@quotation

Installs a new shell builtin command dynamically linked from @var{file},
where @var{file} is found by a path search and the base name of the file
is the name of the builtin to be added.

Similar to @code{zmodload -F zsh/}@var{file} @code{+b:}@var{file}.

`THIS FEATURE IS UNLIKELY EVER TO BE IMPLEMENTED.'
@end quotation

@code{typeset -H} @var{name}[@code{=}@var{value}]

@quotation

Used for `host-name file mapping' on some operating systems.

`THIS FEATURE IS UNLIKELY EVER TO BE IMPLEMENTED.'
@end quotation

@code{typeset @{+|-@}M} @var{mapname} @var{name}[@code{=}@var{value}]

@quotation

Declares a character translation @var{mapname} for values assigned to @var{name}.
@end quotation

@code{typeset -S}

@code{typeset -T}  [@code{-f}] [ @var{tname}@code{=(}@var{values}@code{)} ]

@code{typeset -h} @var{str}

@quotation

Used to define `typed variables' and properties of their `sub-variables'.
The @code{-T} and @code{-h} options conflict with existing zsh usage.
@end quotation

@code{typeset -X} @var{name}[@code{=}@var{value}]

@quotation

Declares a floating-point variable displayed in hexadecimal format.
@end quotation

@code{typeset -b} @var{name}[@code{=}@var{value}]

@quotation

Declares a parameter stored in `base64' format.
@end quotation

@code{typeset -m} @var{newname}@code{=}@var{oldname}

@quotation

`Moves' @var{oldname} to @var{newname}.  Conflicts with native zsh usage.
@end quotation

@node The zsh/mapfile Module,The zsh/mathfunc Module,The zsh/ksh93 Module,Zsh Modules
@anchor{Zsh/modules id17}@anchor{13d}@anchor{Zsh/modules the-zsh-mapfile-module}@anchor{118}
@section The zsh/mapfile Module


@geindex parameter@comma{} file access via; Command

The @code{zsh/mapfile} module provides one special associative array parameter of
the same name.

@geindex mapfile; Variable

@code{mapfile}

@quotation

This associative array takes as keys the names of files; the resulting
value is the content of the file.  The value is treated identically to any
other text coming from a parameter.  The value may also be assigned to, in
which case the file in question is written (whether or not it originally
existed); or an element may be unset, which will delete the file in
question.  For example, @code{vared mapfile[myfile]'}’ works as expected,
editing the file @code{myfile}.

When the array is accessed as a whole, the keys are the names of files in
the current directory, and the values are empty (to save a huge overhead in
memory).  Thus @code{$@{(k)mapfile@}} has the same effect as the glob operator
@code{*(D)}, since files beginning with a dot are not special.  Care must be
taken with expressions such as @code{rm $@{(k)mapfile@}}, which will delete
every file in the current directory without the usual @code{rm *} test.

The parameter @code{mapfile} may be made read-only; in that case, files
referenced may not be written or deleted.

A file may conveniently be read into an array as one line per element
with the form
@var{array}@code{=("$@{(f@@)mapfile[}@var{filename}@code{]@}")}.
The double quotes and the @code{@@} are necessary to prevent empty lines
from being removed.  Note that if the file ends with a newline,
the shell will split on the final newline, generating an additional
empty field; this can be suppressed by using
@var{array}@code{=("$@{(f@@)$@{mapfile[}@var{filename}@code{]%$\n'@}@}")}’.
@end quotation

@menu
* Limitations:: 

@end menu

@node Limitations,,,The zsh/mapfile Module
@anchor{Zsh/modules limitations}@anchor{13e}
@subsection Limitations


Although reading and writing of the file in question is efficiently
handled, zsh’s internal memory management may be arbitrarily baroque;
however, @code{mapfile} is usually very much more efficient than
anything involving a loop.  Note in particular that
the whole contents of the file will always reside physically in memory when
accessed (possibly multiple times, due to standard parameter substitution
operations).  In particular, this means handling of sufficiently long files
(greater than the machine’s swap space, or than the range of the pointer
type) will be incorrect.

No errors are printed or flagged for non-existent, unreadable, or
unwritable files, as the parameter mechanism is too low in the shell
execution hierarchy to make this convenient.

It is unfortunate that the mechanism for loading modules does not yet allow
the user to specify the name of the shell parameter to be given the special
behaviour.

@node The zsh/mathfunc Module,The zsh/nearcolor Module,The zsh/mapfile Module,Zsh Modules
@anchor{Zsh/modules id18}@anchor{13f}@anchor{Zsh/modules the-zsh-mathfunc-module}@anchor{119}
@section The zsh/mathfunc Module


@geindex functions@comma{} mathematical; Command

@geindex mathematical functions; Command

The @code{zsh/mathfunc} module provides standard
mathematical functions for use when
evaluating mathematical formulae.  The syntax agrees with normal C and
FORTRAN conventions, for example,

@example
 (( f = sin(0.3) ))
@end example

assigns the sine of 0.3 to the parameter f.

Most functions take floating point arguments and return a floating point
value.  However, any necessary conversions from or to integer type will be
performed automatically by the shell.  Apart from @code{atan} with a second
argument and the @code{abs}, @code{int} and @code{float} functions, all functions
behave as noted in the manual page for the corresponding C function,
except that any arguments out of range for the function in question will be
detected by the shell and an error reported.

The following functions take a single floating point argument: @code{acos},
@code{acosh}, @code{asin}, @code{asinh}, @code{atan}, @code{atanh}, @code{cbrt}, @code{ceil},
@code{cos}, @code{cosh}, @code{erf}, @code{erfc}, @code{exp}, @code{expm1}, @code{fabs},
@code{floor}, @code{gamma}, @code{j0}, @code{j1}, @code{lgamma}, @code{log}, @code{log10},
@code{log1p}, @code{log2}, @code{logb}, @code{sin}, @code{sinh}, @code{sqrt}, @code{tan},
@code{tanh}, @code{y0}, @code{y1}.  The @code{atan} function can optionally take a
second argument, in which case it behaves like the C function @code{atan2}.
The @code{ilogb}, @code{isinf}, and @code{isnan} functions take a single floating
point argument, but return an integer.

The function @code{signgam} takes no arguments, and returns an integer, which
is the C variable of the same name, as described in @code{gamma(3)}.  Note
that it is therefore only useful immediately after a call to @code{gamma} or
@code{lgamma}.  Note also that @code{signgam()} and @code{signgam} are
distinct expressions.

The functions @code{min}, @code{max}, and @code{sum} are defined not in this module
but in the @code{zmathfunc} autoloadable function, described in
@ref{140,,Mathematical Functions}.

The following functions take two floating point arguments: @code{copysign},
@code{fmod}, @code{hypot}, @code{nextafter}.

The following take an integer first argument and a floating point second
argument: @code{jn}, @code{yn}.

The following take a floating point first argument and an integer second
argument: @code{ldexp}, @code{scalb}.

The function @code{abs} does not convert the type of its single argument; it
returns the absolute value of either a floating point number or an
integer.  The functions @code{float} and @code{int} convert their arguments into
a floating point or integer value (by truncation) respectively.

Note that the C @code{pow} function is available in ordinary math evaluation
as the @code{**} operator and is not provided here.

The function @code{rand48} is available if your system’s mathematical library
has the function @code{erand48(3)}.  It returns a pseudo-random floating point
number between 0 and 1.  It takes a single string optional argument.

If the argument is not present, the random number seed is initialised by
three calls to the @code{rand(3)} function — this produces the
same random
numbers as the next three values of @code{$RANDOM}.

If the argument is present, it gives the name of a scalar parameter where
the current random number seed will be stored.  On the first call, the
value must contain at least twelve hexadecimal digits (the remainder of the
string is ignored), or the seed will be initialised in the same manner as
for a call to @code{rand48} with no argument.  Subsequent calls to
@code{rand48}(@var{param}) will then maintain the seed in the
parameter @var{param} as a string of twelve hexadecimal digits, with no base
signifier.  The random number sequences for different parameters are
completely independent, and are also independent from that used by calls to
@code{rand48} with no argument.

For example, consider

@example
 print $(( rand48(seed) ))
 print $(( rand48() ))
 print $(( rand48(seed) ))
@end example

Assuming @code{$seed} does not exist, it will be initialised by the first
call.  In the second call, the default seed is initialised; note, however,
that because of the properties of @code{rand()} there is a
correlation between
the seeds used for the two initialisations, so for more secure uses, you
should generate your own 12-byte seed.  The third call returns to the same
sequence of random numbers used in the first call, unaffected by the
intervening @code{rand48()}.

@node The zsh/nearcolor Module,The zsh/newuser Module,The zsh/mathfunc Module,Zsh Modules
@anchor{Zsh/modules id19}@anchor{141}@anchor{Zsh/modules the-zsh-nearcolor-module}@anchor{11a}
@section The zsh/nearcolor Module


The @code{zsh/nearcolor} module replaces colours specified as hex triplets
with the nearest colour in the 88 or 256 colour palettes that are widely
used by terminal emulators.  By default, 24-bit true colour escape codes
are generated when colours are specified using hex triplets.  These are
not supported by all terminals.  The purpose of this module is to make
it easier to define colour preferences in a form that can work across a
range of terminal emulators.

Aside from the default colour, the ANSI standard for terminal escape
codes provides for eight colours. The bright attribute brings this to
sixteen. These basic colours are commonly used in terminal applications
due to being widely supported. Expanded 88 and 256 colour palettes are
also common and, while the first sixteen colours vary somewhat between
terminals and configurations, these add a generally consistent and
predictable set of colours.

In order to use the @code{zsh/nearcolor} module, it only needs to be
loaded. Thereafter, whenever a colour is specified using a hex triplet,
it will be compared against each of the available colours and the
closest will be selected. The first sixteen colours are never matched in
this process due to being unpredictable.

The use of a hex triplet will automatically load the @code{zsh/nearcolor}
module if the terminal doesn’t support 24-bit colour. This behaviour can
be modified via the @code{.term.extensions} parameter – see
@ref{98,,Terminal Extensions}.

The module can also be loaded manually. It is recommended to be
selective in doing so. For example, the following checks the
@code{COLORTERM} environment variable:

@example
 [[ $COLORTERM = *(24bit|truecolor)* ]] || zmodload zsh/nearcolor
@end example

Note that some terminals accept the true color escape codes but map
them internally to a more limited palette in a similar manner to the
@code{zsh/nearcolor} module.

@node The zsh/newuser Module,The zsh/parameter Module,The zsh/nearcolor Module,Zsh Modules
@anchor{Zsh/modules id20}@anchor{142}@anchor{Zsh/modules the-zsh-newuser-module}@anchor{11b}
@section The zsh/newuser Module


The @code{zsh/newuser} module is loaded at boot if it is
available, the @code{RCS} option is set, and the @code{PRIVILEGED} option is not
set (all three are true by default).  This takes
place immediately after commands in the global @code{zshenv} file (typically
@code{/etc/zshenv}), if any, have been executed.  If the module is not
available it is silently ignored by the shell; the module may safely be
removed from @code{$MODULE_PATH} by the administrator if it is not required.

On loading, the module tests if any of the start-up files @code{.zshenv},
@code{.zprofile}, @code{.zshrc} or @code{.zlogin} exist in the directory given by
the environment variable @code{ZDOTDIR}, or the user’s home directory if that
is not set.  The test is not performed and the module halts processing if
the shell was in an emulation mode (i.e. had been invoked as some other
shell than zsh).

If none of the start-up files were found, the module then looks for the
file @code{newuser} first in a sitewide directory, usually the parent
directory of the @code{site-functions} directory, and if that is not found the
module searches in a version-specific directory, usually the parent of the
@code{functions} directory containing version-specific functions.  (These
directories can be configured when zsh is built using the
@code{--enable-site-scriptdir=}@var{dir} and @code{--enable-scriptdir=}@var{dir}
flags to @code{configure}, respectively; the defaults are
@var{prefix}@code{/share/zsh} and @var{prefix}@code{/share/zsh/$ZSH_VERSION} where
the default @var{prefix} is @code{/usr/local}.)

If the file @code{newuser} is found, it is then sourced in the same manner as
a start-up file.  The file is expected to contain code to install start-up
files for the user, however any valid shell code will be executed.

The @code{zsh/newuser} module is then unconditionally unloaded.

Note that it is possible to achieve exactly the same effect as the
@code{zsh/newuser} module by adding code to @code{/etc/zshenv}.  The module
exists simply to allow the shell to make arrangements for new users without
the need for intervention by package maintainers and system administrators.

The script supplied with the module invokes the shell function
@code{zsh-newuser-install}.  This may be invoked directly by the user
even if the @code{zsh/newuser} module is disabled.  Note, however, that
if the module is not installed the function will not be installed either.
The function is documented in
@ref{f,,User Configuration Functions}.

@node The zsh/parameter Module,The zsh/pcre Module,The zsh/newuser Module,Zsh Modules
@anchor{Zsh/modules id21}@anchor{143}@anchor{Zsh/modules the-zsh-parameter-module}@anchor{33}
@section The zsh/parameter Module


@geindex parameters@comma{} special; Command

The @code{zsh/parameter} module gives access to some of the internal hash
tables used by the shell by defining some special parameters.

@geindex options; Variable

@code{options}

@quotation

The keys for this associative array are the names of the options that
can be set and unset using the @code{setopt} and @code{unsetopt}
builtins. The value of each key is either the string @code{on} if the
option is currently set, or the string @code{off} if the option is unset.
Setting a key to one of these strings is like setting or unsetting
the option, respectively. Unsetting a key in this array is like
setting it to the value @code{off}.
@end quotation

@geindex commands; Variable

@code{commands}

@quotation

This array gives access to the command hash table. The keys are the
names of external commands, the values are the pathnames of the files
that would be executed when the command would be invoked. Setting a
key in this array defines a new entry in this table in the same way as
with the @code{hash} builtin. Unsetting a key as in @code{unset
"commands[foo]"} removes the entry for the given key from the command
hash table.
@end quotation

@geindex functions; Variable

@code{functions}

@quotation

This associative array maps names of enabled functions to their
definitions. Setting a key in it is like defining a function with the
name given by the key and the body given by the value. Unsetting a key
removes the definition for the function named by the key.
@end quotation

@geindex dis_functions; Variable

@code{dis_functions}

@quotation

Like @code{functions} but for disabled functions.
@end quotation

@geindex functions_source; Variable

@code{functions_source}

@quotation

This readonly associative array maps names of enabled functions to the
name of the file containing the source of the function.

For an autoloaded function that has already been loaded, or marked for
autoload with an absolute path, or that has had its path resolved with
@code{functions -r}, this is the file found for autoloading, resolved
to an absolute path.

For a function defined within the body of a script or sourced file,
this is the name of that file.  In this case, this is the exact path
originally used to that file, which may be a relative path.

For any other function, including any defined at an interactive prompt or
an autoload function whose path has not yet been resolved, this is
the empty string.  However, the hash element is reported as defined
just so long as the function is present:  the keys to this hash are
the same as those to @code{$functions}.
@end quotation

@geindex dis_functions_source; Variable

@code{dis_functions_source}

@quotation

Like @code{functions_source} but for disabled functions.
@end quotation

@geindex builtins; Variable

@code{builtins}

@quotation

This associative array gives information about the builtin commands
currently enabled. The keys are the names of the builtin commands and
the values are either @code{undefined} for builtin commands that will
automatically be loaded from a module if invoked or @code{defined} for
builtin commands that are already loaded.
@end quotation

@geindex dis_builtins; Variable

@code{dis_builtins}

@quotation

Like @code{builtins} but for disabled builtin commands.
@end quotation

@geindex reswords; Variable

@code{reswords}

@quotation

This array contains the enabled reserved words.
@end quotation

@geindex dis_reswords; Variable

@code{dis_reswords}

@quotation

Like @code{reswords} but for disabled reserved words.
@end quotation

@geindex patchars; Variable

@code{patchars}

@quotation

This array contains the enabled pattern characters.
@end quotation

@geindex dis_patchars; Variable

@code{dis_patchars}

@quotation

Like @code{patchars} but for disabled pattern characters.
@end quotation

@geindex aliases; Variable

@code{aliases}

@quotation

This maps the names of the regular aliases currently enabled to their
expansions.
@end quotation

@geindex dis_aliases; Variable

@code{dis_aliases}

@quotation

Like @code{aliases} but for disabled regular aliases.
@end quotation

@geindex galiases; Variable

@code{galiases}

@quotation

Like @code{aliases}, but for global aliases.
@end quotation

@geindex dis_galiases; Variable

@code{dis_galiases}

@quotation

Like @code{galiases} but for disabled global aliases.
@end quotation

@geindex saliases; Variable

@code{saliases}

@quotation

Like @code{raliases}, but for suffix aliases.
@end quotation

@geindex dis_saliases; Variable

@code{dis_saliases}

@quotation

Like @code{saliases} but for disabled suffix aliases.
@end quotation

@geindex parameters; Variable

@code{parameters}

@quotation

The keys in this associative array are the names of the parameters
currently defined. The values are strings describing the type of the
parameter, in the same format used by the @code{t} parameter flag, see
@ref{6e,,Parameter Expansion Flags}.
The value may also be @code{undefined} indicating a parameter that
may be autoloaded from a module but has not yet been referenced.
When the key is the name of a named reference, the value is
@code{nameref-} prepended to the type of the referenced parameter,
for example

@example
 % typeset -n parms=parameters
 % print -r $@{parameters[parms]@}
 nameref-association-readonly-hide-hideval-special
@end example

Setting or unsetting keys in this array is not possible.
@end quotation

@geindex modules; Variable

@code{modules}

@quotation

An associative array giving information about modules. The keys are the names
of the modules loaded, registered to be autoloaded, or aliased. The
value says which state the named module is in and is one of the
strings @code{loaded}, @code{autoloaded}, or @code{alias:}@var{name},
where @var{name} is the name the module is aliased to.

Setting or unsetting keys in this array is not possible.
@end quotation

@geindex dirstack; Variable

@code{dirstack}

@quotation

A normal array holding the elements of the directory stack. Note that
the output of the @code{dirs} builtin command includes one more
directory, the current working directory.
@end quotation

@geindex history; Variable

@code{history}

@quotation

This associative array maps history event numbers to the full history lines.
Although it is presented as an associative array, the array of all values
(@code{$@{history[@@]@}}) is guaranteed to be returned in order from most recent
to oldest history event, that is, by decreasing history event number.
@end quotation

@geindex historywords; Variable

@code{historywords}

@quotation

A special array containing the words stored in the history.  These also
appear in most to least recent order.
@end quotation

@geindex jobdirs; Variable

@code{jobdirs}

@quotation

This associative array maps job numbers to the directories from which the
job was started (which may not be the current directory of the job).

The keys of the associative arrays are usually valid job numbers,
and these are the values output with, for example, @code{$@{(k)jobdirs@}}.
Non-numeric job references may be used when looking up a value;
for example, @code{$@{jobdirs[%+]@}} refers to the current job.

See the @code{jobs} builtin for how job information is provided in a subshell.
@end quotation

@geindex jobtexts; Variable

@code{jobtexts}

@quotation

This associative array maps job numbers to the texts of the command lines
that were used to start the jobs.

Handling of the keys of the associative array is as described for
@code{jobdirs} above.

See the @code{jobs} builtin for how job information is provided in a subshell.
@end quotation

@geindex jobstates; Variable

@code{jobstates}

@quotation

This associative array gives information about the states of the jobs
currently known. The keys are the job numbers and the values are
strings of the form
@var{job-state}@code{:}@var{mark}@code{:}@var{pid}@code{=}@var{state}…. The
@var{job-state} gives the state the whole job is currently in, one of
@code{running}, @code{suspended}, or @code{done}. The @var{mark} is
@code{+} for the current job, @code{-} for the previous job and empty
otherwise. This is followed by one @code{:}@var{pid}@code{=}@var{state} for every
process in the job. The @var{pid}s are, of course, the process IDs and
the @var{state} describes the state of that process.

Handling of the keys of the associative array is as described for
@code{jobdirs} above.

See the @code{jobs} builtin for how job information is provided in a subshell.
@end quotation

@geindex nameddirs; Variable

@code{nameddirs}

@quotation

This associative array maps the names of named directories to the pathnames
they stand for.
@end quotation

@geindex userdirs; Variable

@code{userdirs}

@quotation

This associative array maps user names to the pathnames of their home
directories.
@end quotation

@geindex usergroups; Variable

@code{usergroups}

@quotation

This associative array maps names of system groups of which the current
user is a member to the corresponding group identifiers.  The contents
are the same as the groups output by the @code{id} command.
@end quotation

@geindex funcfiletrace; Variable

@code{funcfiletrace}

@quotation

This array contains the absolute line numbers and corresponding file
names for the point where the current function, sourced file, or (if
@code{EVAL_LINENO} is set) @code{eval} command was
called.  The array is of the same length as @code{funcsourcetrace} and
@code{functrace}, but differs from @code{funcsourcetrace} in that the line and
file are the point of call, not the point of definition, and differs
from @code{functrace} in that all values are absolute line numbers in
files, rather than relative to the start of a function, if any.
@end quotation

@geindex funcsourcetrace; Variable

@code{funcsourcetrace}

@quotation

This array contains the file names and line numbers of the
points where the functions, sourced files, and (if @code{EVAL_LINENO} is set)
@code{eval} commands currently being executed were
defined.  The line number is the line where the @code{function} @var{name}
or @var{name} @code{()} started.  In the case of an autoloaded
function  the line number is reported as zero.
The format of each element is @var{filename}@code{:}@var{lineno}.

For functions autoloaded from a file in native zsh format, where only the
body of the function occurs in the file, or for files that have been
executed by the @code{source} or @code{.} builtins, the trace information is
shown as @var{filename}@code{:}@var{0}, since the entire file is the
definition.  The source file name is resolved to an absolute path when
the function is loaded or the path to it otherwise resolved.

Most users will be interested in the information in the
@code{funcfiletrace} array instead.
@end quotation

@geindex funcstack; Variable

@code{funcstack}

@quotation

This array contains the names of the functions, sourced files,
and (if @code{EVAL_LINENO} is set) @code{eval} commands. currently being
executed. The first element is the name of the function using the
parameter.

The standard shell array @code{zsh_eval_context} can be used to
determine the type of shell construct being executed at each depth:
note, however, that is in the opposite order, with the most recent
item last, and it is more detailed, for example including an
entry for @code{toplevel}, the main shell code being executed
either interactively or from a script, which is not present
in @code{$funcstack}.
@end quotation

@geindex functrace; Variable

@code{functrace}

@quotation

This array contains the names and line numbers of the callers
corresponding to the functions currently being executed.
The format of each element is @var{name}@code{:}@var{lineno}.
Callers are also shown for sourced files; the caller is the point
where the @code{source} or @code{.} command was executed.
@end quotation

@node The zsh/pcre Module,The zsh/param/private Module,The zsh/parameter Module,Zsh Modules
@anchor{Zsh/modules id22}@anchor{144}@anchor{Zsh/modules the-zsh-pcre-module}@anchor{11c}
@section The zsh/pcre Module


@geindex regular expressions@comma{} perl-compatible; Command

The @code{zsh/pcre} module makes some commands available as builtins:

@geindex pcre_compile; Function

@code{pcre_compile} [ @code{-aimxs} ] @var{PCRE}

@quotation

Compiles a perl-compatible regular expression.

Option @code{-a} will force the pattern to be anchored.
Option @code{-i} will compile a case-insensitive pattern.
Option @code{-m} will compile a multi-line pattern; that is,
@code{^} and @code{$} will match newlines within the pattern.
Option @code{-x} will compile an extended pattern, wherein
whitespace and @code{#} comments are ignored.
Option @code{-s} makes the dot metacharacter match all characters,
including those that indicate newline.
@end quotation

@geindex pcre_study; Function

@code{pcre_study}

@quotation

Requests JIT compilation for the previously-compiled PCRE which
may result in faster matching.
@end quotation

@geindex pcre_match; Function

@code{pcre_match} [ @code{-v} @var{var} ] [ @code{-a} @var{arr} ] [ @code{-A} @var{assoc} ] [ @code{-n} @var{offset} ] [ @code{-bd} ] @var{string}

@quotation

Returns successfully if @code{string} matches the previously-compiled
PCRE.

Upon successful match,
if the expression captures substrings within parentheses,
@code{pcre_match} will set the array @code{match} to those
substrings, unless the @code{-a} option is given, in which
case it will set the array @var{arr}.  Similarly, the variable
@code{MATCH} will be set to the entire matched portion of the
string, unless the @code{-v} option is given, in which case the variable
@var{var} will be set. Furthermore, any named captures will
be stored in the associative array @code{.pcre.match} unless an
alternative is given with @code{-A}.
No variables are altered if there is no successful match.
A @code{-n} option starts searching for a match from the
byte @var{offset} position in @var{string}.  If the @code{-b} option is given,
the variable @code{ZPCRE_OP} will be set to an offset pair string,
representing the byte offset positions of the entire matched portion
within the @var{string}.  For example, a @code{ZPCRE_OP} set to “32 45” indicates
that the matched portion began on byte offset 32 and ended on byte offset 44.
Here, byte offset position 45 is the position directly after the matched
portion.  Keep in mind that the byte position isn’t necessarily the same
as the character position when UTF-8 characters are involved.
Consequently, the byte offset positions are only to be relied on in the
context of using them for subsequent searches on @var{string}, using an offset
position as an argument to the @code{-n} option.  This is mostly
used to implement the “find all non-overlapping matches” functionality.

A simple example of “find all non-overlapping matches”:

@example
 string="The following zip codes: 78884 90210 99513"
 pcre_compile -m "\d@{5@}"
 accum=()
 pcre_match -b -- $string
 while [[ $? -eq 0 ]] do
     b=($=ZPCRE_OP)
     accum+=$MATCH
     pcre_match -b -n $b[2] -- $string
 done
 print -l $accum
@end example

The option @code{-d} uses the alternative breadth-first DFA search algorithm of
pcre. This sets @code{match}, or the array given with @code{-a}, to all the matches
found from the same start point in the subject.

If the regular expression contains string callouts, these are executed as
shell code, while numerical callouts are ignored. During the execution of the
callout, the string the regular expression is matching against is available
in the parameter @code{.pcre.subject}. The parameter @code{.pcre.pos} contains the
position in that string that is currently being matched against. If there is
a non-zero return status from the shell code, the callout does not match. Note
that callouts are not available in the below -pcre-match test condition. It is
also likely not a good idea to call any pcre related builtins from a callout. As
an example, the following will print out @code{bar}:

@example
 pcre_compile 'foo(?C"echo $@{.pcre.subject[$@{.pcre.pos@},-1]@}")'
 pcre_match foobar
@end example
@end quotation

The @code{zsh/pcre} module makes available the following test condition:

@geindex pcre-match; Function

@var{expr} @code{-pcre-match} @var{pcre}

@quotation

Matches a string against a perl-compatible regular expression.

For example,

@example
 [[ "$text" -pcre-match ^d+$ ]] &&
 print text variable contains only "d's".
@end example

@geindex REMATCH_PCRE; Program

@geindex NO_CASE_MATCH; Program

If the @code{REMATCH_PCRE} option is set, the @code{=~} operator is equivalent to
@code{-pcre-match}, and the @code{NO_CASE_MATCH} option may be used.  Note that
@code{NO_CASE_MATCH} never applies to the @code{pcre_match} builtin, instead use
the @code{-i} switch of @code{pcre_compile}.
@end quotation

@node The zsh/param/private Module,The zsh/regex Module,The zsh/pcre Module,Zsh Modules
@anchor{Zsh/modules id23}@anchor{145}@anchor{Zsh/modules the-zsh-param-private-module}@anchor{11d}
@section The zsh/param/private Module


The @code{zsh/param/private} module is used to create parameters whose scope
is limited to the current function body, and `not' to other functions
called by the current function.

This module provides a single autoloaded builtin:

@geindex private; Function

@geindex private parameter@comma{} creating; Command

@code{private} [ @{@code{+|-@}AHUahlmrtux} ] [ @{@code{+|-@}EFLRZi} [ @var{n} ] ] [ @var{name}[@code{=}@var{value}] … ]

@quotation

The @code{private} builtin accepts all the same options and arguments as @code{local}
(@code{zshbuiltins}) except
for the @code{-T} option.  Tied parameters may not be made private.

The @code{-p} option is presently disabled because the state of
private parameters cannot reliably be reloaded.  When @code{typeset -p}
outputs a private parameter, it is treated as a local with the
@code{-h} (hide) option enabled.

If used at the top level (outside a function scope), @code{private} creates a
normal parameter in the same manner as @code{declare} or @code{typeset}.  A
warning about this is printed if @code{WARN_CREATE_GLOBAL} is set
(@code{zshoptions}). Used inside a
function scope, @code{private} creates a local parameter similar to one
declared with @code{local}, except having special properties noted below.

Special parameters which expose or manipulate internal shell state, such
as @code{ARGC}, @code{argv}, @code{COLUMNS}, @code{LINES}, @code{UID}, @code{EUID}, @code{IFS},
@code{PROMPT}, @code{RANDOM}, @code{SECONDS}, etc., cannot be made private unless
the @code{-h} option is used to hide the special meaning of the
parameter.  This may change in the future.
@end quotation

As with other @code{typeset} equivalents, @code{private} is both a builtin and a
reserved word, so arrays may be assigned with parenthesized word list
@var{name}@code{=(}@var{value}…`@w{`})`@w{`} syntax.  However, the reserved
word @code{private} is not available until @code{zsh/param/private} is loaded,
so care must be taken with order of execution and parsing for function
definitions which use @code{private}.  To compensate for this, the module
also adds the option @code{-P} to the @code{local} builtin to declare private
parameters.

For example, this construction fails if @code{zsh/param/private} has not yet
been loaded when @code{bad_declaration} is defined:

@example
 bad_declaration() @{
   zmodload zsh/param/private
   private array=( one two three )
 @}
@end example

This construction works because @code{local} is already a keyword, and the
module is loaded before the statement is executed:

@example
 good_declaration() @{
   zmodload zsh/param/private
   local -P array=( one two three )
 @}
@end example

The following is usable in scripts but may have trouble with @code{autoload}:

@example
 zmodload zsh/param/private
 iffy_declaration() @{
   private array=( one two three )
 @}
@end example

The @code{private} builtin may always be used with scalar assignments and
for declarations without assignments.

Parameters declared with @code{private} have the following properties:

@quotation


@itemize *

@item 
Within the function body where it is declared, the parameter
@end itemize

behaves as a local, except as noted above for tied or special parameters.
* The type of a parameter declared private cannot be changed in the
scope where it was declared, even if the parameter is unset.  Thus an
array cannot be assigned to a private scalar, etc.
* Within any other function called by the declaring function, the
private parameter does `NOT' hide other parameters of the same name, so
for example a global parameter of the same name is visible and may be
assigned or unset.  This includes calls to anonymous functions, although
that may also change in the future.  However, the private name may not be
created outside the local scope when it was not previously declared.
* An exported private remains in the environment of inner scopes but
appears unset for the current shell in those scopes.  Generally, exporting
private parameters should be avoided.
* Current shell command substitutions such as @code{$@{|...@}},
@code{$@{|}@var{var}@code{|...@}} and @code{$@{ ... @}} may read and assign
private parameters from the enclosing function.
* Declaring a private parameter in a current shell command substitution
limits that parameter to the scope of the command substitution, just as if
the parameter were declared in a function.  This also prevents access by
any enclosed current shell command substitutions, but other substitutions
may use the private parameter because those have the same calling scope.
@end quotation

Note that this differs from the static scope defined by compiled languages
derived from C, in that a new call to the same function creates a new
scope, i.e., the parameter is still associated with the call stack rather
than with the function definition.  It differs from ksh @code{typeset -S}
because the syntax used to define the function has no bearing on whether
the parameter scope is respected.

@node The zsh/regex Module,The zsh/random Module,The zsh/param/private Module,Zsh Modules
@anchor{Zsh/modules id24}@anchor{146}@anchor{Zsh/modules the-zsh-regex-module}@anchor{11e}
@section The zsh/regex Module


@geindex regular expressions; Command

@geindex regex; Command

The @code{zsh/regex} module makes available the following test condition:

@geindex regex-match; Function

@var{expr} @code{-regex-match} @var{regex}

@quotation

Matches a string against a POSIX extended regular expression.
On successful match,
matched portion of the string will normally be placed in the @code{MATCH}
variable.  If there are any capturing parentheses within the regex, then
the @code{match} array variable will contain those.
If the match is not successful, then the variables will not be altered.

For example,

@example
 [[ alphabetical -regex-match ^a([^a]+)a([^a]+)a ]] &&
 print -l $MATCH X $match
@end example

If the option @code{REMATCH_PCRE} is not set, then the @code{=~} operator will
automatically load this module as needed and will invoke the
@code{-regex-match} operator.

If @code{BASH_REMATCH} is set, then the array @code{BASH_REMATCH} will be set
instead of @code{MATCH} and @code{match}.

Note that the @code{zsh/regex} module logic relies on the host system. The
same @var{expr} and @var{regex} pair could produce different results on different
platforms if a @var{regex} with non-standard syntax is given.

For example, no syntax for matching a word boundary is defined in the POSIX
extended regular expression standard. GNU @code{libc} and BSD @code{libc} both provide
such syntaxes as extensions (@code{\b} and @code{[[:<:]]/[[:>:]]} respectively),
but neither of these syntaxes is supported by both of these implementations.

Refer to the @code{regcomp(3)} and @code{re_format(7)} manual pages on your
system for locally-supported syntax.
@end quotation

@node The zsh/random Module,The zsh/sched Module,The zsh/regex Module,Zsh Modules
@anchor{Zsh/modules id25}@anchor{147}@anchor{Zsh/modules the-zsh-random-module}@anchor{94}
@section The zsh/random Module


The @code{zsh/random} module gets random data from the kernel random pool. If no
kernel random pool can be found, the module will not load.

@menu
* Parameters: Parameters<3>. 
* Math Functions:: 

@end menu

@node Parameters<3>,Math Functions,,The zsh/random Module
@anchor{Zsh/modules id26}@anchor{148}
@subsection Parameters


@geindex SRANDOM; Variable

@code{SRANDOM}

@quotation

A random positive 32-bit integer between 0 and 4,294,967,295.  This parameter
is read-only. The name was chosen for compatibility with Bash and to
distinguish it from @code{RANDOM} which has a documented repeatable behavior.
@end quotation

@node Math Functions,,Parameters<3>,The zsh/random Module
@anchor{Zsh/modules math-functions}@anchor{149}
@subsection Math Functions


@code{zrand_float()}

@quotation

Returns a random floating point number between 0 and 1 inclusive.
@end quotation

@code{zrand_int}(@var{upper}, @var{lower}, @var{inclusive})

@quotation

Returns a random integer between @var{lower} and @var{upper}. All parameters
are optional.  If none are specified it is equivalent to @code{SRANDOM}. Note
that this is equivalent to passing the default values except that it
is inclusive.

@var{upper} is the upper bound on the resultant number and defaults to
4,294,967,295. It is exclusive by default, unless @var{inclusive} is passed.

@var{lower} is the lower bound and defaults to 0.

The defaults of these two arguments are also the maximum and minimum to which
either can be set.

@var{inclusive} is a flag that controls whether the @var{upper} bound is
exclusive or inclusive. Passing any non-zero value makes it inclusive,
otherwise it is exclusive when the @var{upper} bound is specified. The
@var{lower} bound is always inclusive.

This is to facilitate a construct like @code{$a[zrand_int($#a)+1]} rather
than @code{$a[zrand_int($#a-1)+1]}.
For example, if $#a is 16, you would use @code{zrand_int(16)} which has
16 possible return values 0-15.  Because the function can return zero, in order
to use it as an array index from 1-16 you need to add one.  It would
be an array index range error for it to also potentially return 16 ($#a). You
could, however, use the construct @code{zrand_int(16,1,1)} instead of
adding 1 to achieve the same result, but it is more verbose.

Most statistics algorithms seem to also expect 0 to @var{upper}-1, so this was
deemed the most commonly desired case and chosen as the default.
@end quotation

@node The zsh/sched Module,The zsh/net/socket Module,The zsh/random Module,Zsh Modules
@anchor{Zsh/modules id27}@anchor{14a}@anchor{Zsh/modules the-zsh-sched-module}@anchor{96}
@section The zsh/sched Module


The @code{zsh/sched} module makes available one builtin command and one
parameter.

@geindex sched; Function

@geindex timed execution; Command

@geindex execution@comma{} timed; Command

@code{sched} [@code{-o}] [@code{+}]:var:@cite{hh}@code{:}@var{mm}[@code{:}@var{ss}] @var{command} …

@code{sched} [@code{-o}] [@code{+}]:var:@cite{seconds} @var{command} …

@code{sched} [ @code{-}@var{item} ]

@quotation

Make an entry in the scheduled list of commands to execute.
The time may be specified in either absolute or relative time,
and either as hours, minutes and (optionally) seconds separated by a
colon, or seconds alone.
An absolute number of seconds indicates the time since the epoch
(1970/01/01 00:00); this is useful in combination with the features in
the @code{zsh/datetime} module, see
@ref{110,,The zsh/datetime Module}.

With no arguments, prints the list of scheduled commands.  If the
scheduled command has the @code{-o} flag set, this is shown at the
start of the command.

With the argument @code{-}@var{item}, removes the given item
from the list.  The numbering of the list is continuous and entries are
in time order, so the numbering can change when entries are added or
deleted.

Commands are executed either immediately before a prompt, or while
the shell’s line editor is waiting for input.  In the latter case
it is useful to be able to produce output that does not interfere
with the line being edited.  Providing the option @code{-o} causes
the shell to clear the command line before the event and redraw it
afterwards.  This should be used with any scheduled event that produces
visible output to the terminal; it is not needed, for example, with
output that updates a terminal emulator’s title bar.

To effect changes to the editor buffer when an event executes, use the
@code{zle} command with no arguments to test whether the editor is active,
and if it is, then use @code{zle} @var{widget} to access the editor via
the named @var{widget}.

The @code{sched} builtin is not made available by default when the shell
starts in a mode emulating another shell.  It can be made available
with the command @code{zmodload -F zsh/sched b:sched}.
@end quotation

@geindex zsh_scheduled_events; Variable

@code{zsh_scheduled_events}

@quotation

A readonly array corresponding to the events scheduled by the
@code{sched} builtin.  The indices of the array correspond to the numbers
shown when @code{sched} is run with no arguments (provided that the
@code{KSH_ARRAYS} option is not set).  The value of the array
consists of the scheduled time in seconds since the epoch
(see @ref{110,,The zsh/datetime Module} for facilities for
using this number), followed by a colon, followed by any options
(which may be empty but will be preceded by a @code{-} otherwise),
followed by a colon, followed by the command to be executed.

The @code{sched} builtin should be used for manipulating the events.  Note
that this will have an immediate effect on the contents of the array,
so that indices may become invalid.
@end quotation

@node The zsh/net/socket Module,The zsh/stat Module,The zsh/sched Module,Zsh Modules
@anchor{Zsh/modules id28}@anchor{14b}@anchor{Zsh/modules the-zsh-net-socket-module}@anchor{ce}
@section The zsh/net/socket Module


The @code{zsh/net/socket} module makes available one builtin command:

@geindex zsocket; Function

@geindex sockets; Command

@geindex sockets@comma{} Unix domain; Command

@code{zsocket} [ @code{-alstv} ] [ @code{-d} @var{fd} ] [ @var{args} ]

@quotation

@code{zsocket} is implemented as a builtin to allow full use of shell
command line editing, file I/O, and job control mechanisms.
@end quotation

@menu
* Outbound Connections:: 
* Inbound Connections:: 

@end menu

@node Outbound Connections,Inbound Connections,,The zsh/net/socket Module
@anchor{Zsh/modules outbound-connections}@anchor{14c}
@subsection Outbound Connections


@geindex sockets@comma{} outbound Unix domain; Command

@code{zsocket} [ @code{-v} ] [ @code{-d} @var{fd} ] @var{filename}

@quotation

Open a new Unix domain connection to @var{filename}.
The shell parameter @code{REPLY} will be set to the file descriptor
associated with that connection.  Currently, only stream connections
are supported.

If @code{-d} is specified, its argument
will be taken as the target file descriptor for the
connection.

In order to elicit more verbose output, use @code{-v}.

File descriptors can be closed with normal shell syntax when no longer
needed, for example:

@example
 exec @{REPLY@}>&-
@end example

The @code{zsocket -s :var:`fd}` command may also be used to shut down a
socket fd before closing it. This will send an EOF to the other side,
while this side can still read their subsequent response before closing
the connection fully, for example.
@end quotation

@node Inbound Connections,,Outbound Connections,The zsh/net/socket Module
@anchor{Zsh/modules inbound-connections}@anchor{14d}
@subsection Inbound Connections


@geindex sockets@comma{} inbound Unix domain; Command

@code{zsocket} @code{-l} [ @code{-v} ] [ @code{-d} @var{fd} ] @var{filename}

@quotation

@code{zsocket -l} will open a socket listening on @var{filename}.
The shell parameter @code{REPLY} will be set to the file descriptor
associated with that listener.  The file descriptor remains open in subshells
and forked external executables.

If @code{-d} is specified, its argument
will be taken as the target file descriptor for
the connection.

In order to elicit more verbose output, use @code{-v}.
@end quotation

@code{zsocket} @code{-a} [ @code{-tv} ] [ @code{-d} @var{targetfd} ] @var{listenfd}

@quotation

@code{zsocket -a} will accept an incoming connection
to the socket associated with @var{listenfd}.
The shell parameter @code{REPLY} will
be set to the file descriptor associated with
the inbound connection.  The file descriptor remains open in subshells
and forked external executables.

If @code{-d} is specified, its argument
will be taken as the target file descriptor for the
connection.

If @code{-t} is specified, @code{zsocket} will return
if no incoming connection is pending.  Otherwise
it will wait for one.

In order to elicit more verbose output, use @code{-v}.
@end quotation

@node The zsh/stat Module,The zsh/system Module,The zsh/net/socket Module,Zsh Modules
@anchor{Zsh/modules id29}@anchor{14e}@anchor{Zsh/modules the-zsh-stat-module}@anchor{c7}
@section The zsh/stat Module


The @code{zsh/stat} module makes available one builtin command under
two possible names:

@geindex zstat; Function

@geindex stat; Function

@geindex files@comma{} listing; Command

@geindex files@comma{} examining; Command

@code{zstat} [ @code{-gnNolLtTrs} ] [ @code{-f} @var{fd} ] [ @code{-H} @var{hash} ] [ @code{-A} @var{array} ] [ @code{-F} @var{fmt} ]

@quotation

[ @code{+}@var{element} ] [ @var{file} … ]
@end quotation

@code{stat} @var{…}

@quotation

The command acts as a front end to the @code{stat} system call (see
@code{stat(2)}).  The same command is provided with two names; as
the name @code{stat} is often used by an external command it is recommended
that only the @code{zstat} form of the command is used.  This can be
arranged by loading the module with the command @code{zmodload -F zsh/stat
b:zstat}.

If the @code{stat} call fails, the appropriate system error message
printed and status 1 is returned.
The fields of @code{struct stat} give information about
the files provided as arguments to the command.  In addition to those
available from the @code{stat} call, an extra element @code{link} is provided.
These elements are:

@code{device}

@quotation

The number of the device on which the file resides.
@end quotation

@code{inode}

@quotation

The unique number of the file on this device (`inode' number).
@end quotation

@code{mode}

@quotation

The mode of the file; that is, the file’s type and access permissions.
With the @code{-s} option, this will
be returned as a string corresponding to the first column in the
display of the @code{ls -l} command.
@end quotation

@code{nlink}

@quotation

The number of hard links to the file.
@end quotation

@code{uid}

@quotation

The user ID of the owner of the file.  With the @code{-s}
option, this is displayed as a user name.
@end quotation

@code{gid}

@quotation

The group ID of the file.  With the @code{-s} option, this
is displayed as a group name.
@end quotation

@code{rdev}

@quotation

The raw device number.  This is only useful for special devices.
@end quotation

@code{size}

@quotation

The size of the file in bytes.
@end quotation

@code{atime}

@code{mtime}

@code{ctime}

@quotation

The last access, modification and inode change times
of the file, respectively, as the number of seconds since
midnight GMT on 1st January, 1970.  With the @code{-s} option,
these are printed as strings for the local time zone; the format
can be altered with the @code{-F} option, and with the @code{-g}
option the times are in GMT.
@end quotation

@code{blksize}

@quotation

The number of bytes in one allocation block on the
device on which the file resides.
@end quotation

@code{block}

@quotation

The number of disk blocks used by the file.
@end quotation

@code{link}

@quotation

If the file is a link and the @code{-L} option is in
effect, this contains the name of the file linked to, otherwise
it is empty.  Note that if this element is selected (@code{`zstat +link}’)
then the @code{-L} option is automatically used.
@end quotation

A particular element may be selected by including its name
preceded by a @code{+} in the option list; only one element is allowed.
The element may be shortened to any unique set of leading
characters.  Otherwise, all elements will be shown for all files.

Options:

@code{-A} @var{array}

@quotation

Instead of displaying the results on standard
output, assign them to an @var{array}, one @code{struct stat} element per array
element for each file in order.  In this case neither the name
of the element nor the name of the files appears in @var{array} unless the
@code{-t} or @code{-n} options were given, respectively.  If @code{-t} is given,
the element name appears as a prefix to the
appropriate array element; if @code{-n} is given, the file name
appears as a separate array element preceding all the others.
Other formatting options are respected.
@end quotation

@code{-H} @var{hash}

@quotation

Similar to @code{-A}, but instead assign the values to @var{hash}.  The keys
are the elements listed above.  If the @code{-n} option is provided then the
name of the file is included in the hash with key @code{name}.
@end quotation

@code{-f} @var{fd}

@quotation

Use the file on file descriptor @var{fd} instead of
named files; no list of file names is allowed in this case.
@end quotation

@code{-F} @var{fmt}

@quotation

Supplies a @code{strftime} (see @code{strftime(3)}) string for the
formatting of the time elements.  The format string supports all of the
zsh extensions (see the description of @code{%D@{}@var{string}@code{@}}
prompt escape in @ref{131,,Simple Prompt Escapes}).
In particular, @code{-F %s.%N} can be used to show timestamps with nanosecond
precision if supported by the system.
The @code{-s} option is implied.
@end quotation

@code{-g}

@quotation

Show the time elements in the GMT time zone.  The
@code{-s} option is implied.
@end quotation

@code{-l}

@quotation

List the names of the type elements (to standard
output or an array as appropriate) and return immediately;
arguments, and options other than @code{-A}, are ignored.
@end quotation

@code{-L}

@quotation

Perform an @code{lstat} (see @code{lstat(2)}) rather than a @code{stat}
system call.  In this case, if the file is a link, information
about the link itself rather than the target file is returned.
This option is required to make the @code{link} element useful.
It’s important to note that this is the exact opposite from @code{ls(1)},
etc.
@end quotation

@code{-n}

@quotation

Always show the names of files.  Usually these are
only shown when output is to standard output and there is more
than one file in the list.
@end quotation

@code{-N}

@quotation

Never show the names of files.
@end quotation

@code{-o}

@quotation

If a raw file mode is printed, show it in octal, which is more useful for
human consumption than the default of decimal.  A leading zero will be
printed in this case.  Note that this does not affect whether a raw or
formatted file mode is shown, which is controlled by the @code{-r} and @code{-s}
options, nor whether a mode is shown at all.
@end quotation

@code{-r}

@quotation

Print raw data (the default format) alongside string
data (the @code{-s} format); the string data appears in parentheses
after the raw data.
@end quotation

@code{-s}

@quotation

Print @code{mode}, @code{uid}, @code{gid} and the three time
elements as strings instead of numbers.  In each case the format
is like that of @code{ls -l}.
@end quotation

@code{-t}

@quotation

Always show the type names for the elements of
@code{struct stat}.  Usually these are only shown when output is to
standard output and no individual element has been selected.
@end quotation

@code{-T}

@quotation

Never show the type names of the @code{struct stat} elements.
@end quotation
@end quotation

@node The zsh/system Module,The zsh/net/tcp Module,The zsh/stat Module,Zsh Modules
@anchor{Zsh/modules id30}@anchor{14f}@anchor{Zsh/modules the-zsh-system-module}@anchor{11f}
@section The zsh/system Module


The @code{zsh/system} module makes available various builtin commands and
parameters.

@menu
* Builtins:: 
* Math Functions: Math Functions<2>. 
* Parameters: Parameters<4>. 

@end menu

@node Builtins,Math Functions<2>,,The zsh/system Module
@anchor{Zsh/modules builtins}@anchor{150}
@subsection Builtins


@geindex syserror; Function

@code{syserror} [ @code{-e} @var{errvar} ] [ @code{-p} @var{prefix} ] [ @var{errno} | @var{errname} ]

@quotation

This command prints out the error message associated with @var{errno}, a
system error number, followed by a newline to standard error.

Instead of the error number, a name @var{errname}, for example
@code{ENOENT}, may be used.  The set of names is the same as the contents
of the array @code{errnos}, see below.

If the string @var{prefix} is given, it is printed in front of the error
message, with no intervening space.

If @var{errvar} is supplied, the entire message, without a newline, is
assigned to the parameter names @var{errvar} and nothing is output.

A return status of 0 indicates the message was successfully printed
(although it may not be useful if the error number was out of the
system’s range), a return status of 1 indicates an error in the
parameters, and a return status of 2 indicates the error name was
not recognised (no message is printed for this).
@end quotation

@geindex sysopen; Function

@code{sysopen} [ @code{-arw} ] [ @code{-m} @var{permissions} ] [ @code{-o} @var{options} ]

@quotation

@quotation

@code{-u} @var{fd} @var{file}
@end quotation

This command opens a file. The @code{-r}, @code{-w} and @code{-a} flags indicate
whether the file should be opened for reading, writing and appending,
respectively. The @code{-m} option allows the initial permissions to use when
creating a file to be specified in octal form.  The file descriptor is
specified with @code{-u}. Either an explicit file descriptor in the range 0 to 9 can
be specified or a variable name can be given to which the file descriptor
number will be assigned.

The @code{-o} option allows various system specific options to be
specified as a comma-separated list. The following is a list of possible
options. Note that, depending on the system, some may not be available.

@code{cloexec}

@quotation

mark file to be closed when other programs are executed (else
the file descriptor remains open in subshells and forked external
executables)
@end quotation

@code{create}

@code{creat}

@quotation

create file if it does not exist
@end quotation

@code{excl}

@quotation

create file, error if it already exists
@end quotation

@code{noatime}

@quotation

suppress updating of the file atime
@end quotation

@code{nofollow}

@quotation

fail if @var{file} is a symbolic link
@end quotation

@code{nonblock}

@quotation

the file is opened in nonblocking mode
@end quotation

@code{sync}

@quotation

request that writes wait until data has been physically written
@end quotation

@code{truncate}

@code{trunc}

@quotation

truncate file to size 0
@end quotation

A return status of 0 indicates the descriptor was successfully opened,
otherwise an error message is printed, and 1 is returned for an error
in the parameters to the command, or 2 is returned for a system error.
The parameter @code{ERRNO} is nonzero for system errors.

To close the file, use one of the following:

@example
 @code{exec @{}@var{fd}@code{@}<&-}
 @code{exec @{}@var{fd}@code{@}>&-}
@end example
@end quotation

@geindex sysread; Function

@code{sysread} [ @code{-c} @var{countvar} ] [ @code{-i} @var{infd} ] [ @code{-o} @var{outfd} ]

@quotation

@quotation

[ @code{-s} @var{bufsize} ] [ @code{-t} @var{timeout} ] [ @var{param} ]
@end quotation

Perform a single system read from file descriptor @var{infd}, or zero if
that is not given.  The result of the read is stored in @var{param} or
@code{REPLY} if that is not given.  If @var{countvar} is given, the number
of bytes read is assigned to the parameter named by @var{countvar}.

The maximum number of bytes read is @var{bufsize} or 8192 if that is not
given, however the command returns as soon as any number of bytes was
successfully read.

If @var{timeout} is given, it specifies a timeout in seconds, which may
be zero to poll the file descriptor.  This is handled by the @code{poll}
system call if available, otherwise the @code{select} system call if
available.

If @var{outfd} is given, an attempt is made to write all the bytes just
read to the file descriptor @var{outfd}.  If this fails, because of a
system error other than @code{EINTR} or because of an internal zsh error
during an interrupt, the bytes read but not written are stored in the
parameter named by @var{param} if supplied (no default is used in this
case), and the number of bytes read but not written is stored in the
parameter named by @var{countvar} if that is supplied.  If it was
successful, @var{countvar} contains the full number of bytes transferred,
as usual, and @var{param} is not set.

The error @code{EINTR} (interrupted system call) is handled internally so
that shell interrupts are transparent to the caller.  Any other error
causes a return.

The possible return statuses are

0

@quotation

At least one byte of data was successfully read and, if appropriate,
written.
@end quotation

1

@quotation

There was an error in the parameters to the command.  This is the only
error for which a message is printed to standard error.
@end quotation

2

@quotation

There was an error on the read, or on polling the input file descriptor
for a timeout.  The parameter @code{ERRNO} identifies the error.
@end quotation

3

@quotation

Data were successfully read, but there was an error writing them
to @var{outfd}.  The parameter @code{ERRNO} identifies the error.
@end quotation

4

@quotation

The attempt to read timed out.  Note this does not set @code{ERRNO} as this
is not a system error.
@end quotation

5

@quotation

No system error occurred, but zero bytes were read.  This usually
indicates end of file.  The parameters are set according to the
usual rules; no write to @var{outfd} is attempted.
@end quotation
@end quotation

@code{sysseek} [ @code{-u} @var{fd} ] [ @code{-w} @code{start|end|current} ] @var{offset}

@quotation

The current file position at which future reads and writes will take place is
adjusted to the specified byte offset. The @var{offset} is evaluated as a math
expression. The @code{-u} option allows the file descriptor to be specified. By
default the offset is specified relative to the start or the file but, with the
@code{-w} option, it is possible to specify that the offset should be relative to
the current position or the end of the file.

The return status may be 0 for success, 1 for an error in the parameters
to the command, or 2 for an error on the seek; no error message is
printed in the last case, but the parameter @code{ERRNO} reflects
the error that occurred.
@end quotation

@code{syswrite} [ @code{-c} @var{countvar} ] [ @code{-o} @var{outfd} ] @var{data}

@quotation

The data (a single string of bytes) are written to the file descriptor
@var{outfd}, or 1 if that is not given, using the @code{write} system call.
Multiple write operations may be used if the first does not write all
the data.

If @var{countvar} is given, the number of byte written is stored in the
parameter named by @var{countvar}; this may not be the full length of
@var{data} if an error occurred.

The error @code{EINTR} (interrupted system call) is handled internally by
retrying; otherwise an error causes the command to return.  For example,
if the file descriptor is set to non-blocking output, an error
@code{EAGAIN} (on some systems, @code{EWOULDBLOCK}) may result in the command
returning early.

The return status may be 0 for success, 1 for an error in the parameters
to the command, or 2 for an error on the write; no error message is
printed in the last case, but the parameter @code{ERRNO} reflects
the error that occurred.
@end quotation

@code{zsystem flock} [ @code{-t} @var{timeout} ] [ @code{-i} @var{interval} ] [ @code{-f} @var{var} ] [@code{-er}] @var{file}

@code{zsystem flock -u} @var{fd_expr}

@quotation

The builtin @code{zsystem}’s subcommand @code{flock} performs advisory file
locking (via the @code{fcntl(2)} system call) over the entire contents
of the given file.  This form of locking requires the processes
accessing the file to cooperate; its most obvious use is between two
instances of the shell itself.

In the first form the named @var{file}, which must already exist, is
locked by opening a file descriptor to the file and applying a lock to
the file descriptor.  The lock terminates when the shell process that
created the lock exits; it is therefore often convenient to create file
locks within subshells, since the lock is automatically released when
the subshell exits.  Note that use of the @code{print} builtin with the
@code{-u} option will, as a side effect, release the lock, as will redirection
to the file in the shell holding the lock.  To work around this use a
subshell, e.g. @code{(print message) >>} @var{file}.  Status 0 is
returned if the lock succeeds, else status 1.

In the second form the file descriptor given by the arithmetic
expression @var{fd_expr} is closed, releasing a lock.  The file descriptor
can be queried by using the @code{-f} @var{var} form during the lock;
on a successful lock, the shell variable @var{var} is set to the file
descriptor used for locking.  The lock will be released if the
file descriptor is closed by any other means, for example using
@code{exec @{}@var{var}@code{@}>&-}; however, the form described here performs
a safety check that the file descriptor is in use for file locking.

By default the shell waits indefinitely for the lock to succeed.
The option @code{-t} @var{timeout} specifies a timeout for the lock in
seconds; fractional seconds are allowed.  During this period, the
shell will attempt to lock the file every @var{interval} seconds
if the @code{-i} @var{interval} option is given, otherwise once a second.
(This @var{interval} is shortened before the last attempt if needed,
so that the shell waits only until the @var{timeout} and not longer.)
If the attempt times out, status 2 is returned.

(Note: @var{timeout} is limited to 2^30-1 seconds (about 34 years), and
@var{interval} to 0.999 * LONG_MAX microseconds (only about 35 minutes
on 32-bit systems).)

If the option @code{-e} is given, the file descriptor for the lock is
preserved when the shell uses @code{exec} to start a new process;
otherwise it is closed at that point and the lock released.

If the option @code{-r} is given, the lock is only for reading, otherwise
it is for reading and writing.  The file descriptor is opened
accordingly.
@end quotation

@code{zsystem supports} @var{subcommand}

@quotation

The builtin @code{zsystem}’s subcommand @code{supports} tests whether a
given subcommand is supported.  It returns status 0 if so, else
status 1.  It operates silently unless there was a syntax error
(i.e. the wrong number of arguments), in which case status 255
is returned.  Status 1 can indicate one of two things:  @var{subcommand}
is known but not supported by the current operating system, or
@var{subcommand} is not known (possibly because this is an older
version of the shell before it was implemented).
@end quotation

@node Math Functions<2>,Parameters<4>,Builtins,The zsh/system Module
@anchor{Zsh/modules id31}@anchor{151}
@subsection Math Functions


@code{systell(:var:`fd`)}

@quotation

The systell math function returns the current file position for the file
descriptor passed as an argument.
@end quotation

@node Parameters<4>,,Math Functions<2>,The zsh/system Module
@anchor{Zsh/modules id32}@anchor{152}
@subsection Parameters


@geindex errnos; Variable

@code{errnos}

@quotation

A readonly array of the names of errors defined on the system.  These
are typically macros defined in C by including the system header file
@code{errno.h}.  The index of each name (assuming the option @code{KSH_ARRAYS}
is unset) corresponds to the error number.  Error numbers @var{num}
before the last known error which have no name are given the name
@code{E}@var{num} in the array.

Note that aliases for errors are not handled; only the canonical name is
used.
@end quotation

@geindex sysparams; Variable

@code{sysparams}

@quotation

A readonly associative array.  The keys are:

@code{pid}

@quotation

@geindex pid@comma{} sysparams; Variable

Returns the process ID of the current process, even in subshells.  Compare
@code{$$}, which returns the process ID of the main shell process.
@end quotation

@code{ppid}

@quotation

@geindex ppid@comma{} sysparams; Variable

Returns the current process ID of the parent of the current process, even
in subshells.  Compare @code{$PPID}, which returns the process ID of the
initial parent of the main shell process.
@end quotation

@code{procsubstpid}

@quotation

Returns the process ID of the last process started for process
substitution, i.e. the @code{<(}@var{…}@code{)} and
@code{>(}@var{…}@code{)} expansions.
@end quotation
@end quotation

@node The zsh/net/tcp Module,The zsh/termcap Module,The zsh/system Module,Zsh Modules
@anchor{Zsh/modules id33}@anchor{153}@anchor{Zsh/modules the-zsh-net-tcp-module}@anchor{cf}
@section The zsh/net/tcp Module


The @code{zsh/net/tcp} module makes available one builtin command:

@geindex ztcp; Function

@geindex TCP; Command

@geindex sockets@comma{} TCP; Command

@code{ztcp} [ @code{-acflLstv} ] [ @code{-d} @var{fd} ] [ @var{args} ]

@quotation

@code{ztcp} is implemented as a builtin to allow full use of shell
command line editing, file I/O, and job control mechanisms.

If @code{ztcp} is run with no options, it will output
the contents of its session table.

If it is run with only the option @code{-L}, it will output the contents of
the session table in a format suitable for automatic parsing.  The option
is ignored if given with a command to open or close a session.  The output
consists of a set of lines, one per session, each containing the following
elements separated by spaces:

File descriptor

@quotation

The file descriptor in use for the connection.  For normal inbound (@code{I})
and outbound (@code{O}) connections this may be read and written by the usual
shell mechanisms.  However, it should only be closed with @code{ztcp -c}.
@end quotation

Connection type

@quotation

A letter indicating how the session was created:

@code{Z}

@quotation

A session created with the @code{zftp} command.
@end quotation

@code{L}

@quotation

A connection opened for listening with @code{ztcp -l}.
@end quotation

@code{I}

@quotation

An inbound connection accepted with @code{ztcp -a}.
@end quotation

@code{O}

@quotation

An outbound connection created with @code{ztcp} @var{host} @var{…}.
@end quotation

@code{S}

@quotation

A connection that has been shut down with @code{ztcp -s}.
@end quotation
@end quotation

The local host

@quotation

This is usually set to an all-zero IP address as the address of the
localhost is irrelevant.
@end quotation

The local port

@quotation

This is likely to be zero unless the connection is for listening.
@end quotation

The remote host

@quotation

This is the fully qualified domain name of the peer, if available, else an
IP address.  It is an all-zero IP address for a session opened for
listening.
@end quotation

The remote port

@quotation

This is zero for a connection opened for listening.
@end quotation
@end quotation

@menu
* Outbound Connections: Outbound Connections<2>. 
* Inbound Connections: Inbound Connections<2>. 
* Closing Connections:: 
* Example: Example<2>. 

@end menu

@node Outbound Connections<2>,Inbound Connections<2>,,The zsh/net/tcp Module
@anchor{Zsh/modules id34}@anchor{154}
@subsection Outbound Connections


@geindex sockets@comma{} outbound TCP; Command

@code{ztcp} [ @code{-v} ] [ @code{-d} @var{fd} ] @var{host} [ @var{port} ]

@quotation

Open a new TCP connection to @var{host}.  If the @var{port} is
omitted, it will default to port 23.  The connection will
be added to the session table and the shell parameter
@code{REPLY} will be set to the file descriptor associated
with that connection.

If @code{-d} is specified, its argument will be taken as the target file
descriptor for the connection.

In order to elicit more verbose output, use @code{-v}.
@end quotation

@node Inbound Connections<2>,Closing Connections,Outbound Connections<2>,The zsh/net/tcp Module
@anchor{Zsh/modules id35}@anchor{155}
@subsection Inbound Connections


@geindex sockets@comma{} inbound TCP; Command

@code{ztcp} @code{-l} [ @code{-v} ] [ @code{-d} @var{fd} ] @var{port}

@quotation

@code{ztcp -l} will open a socket listening on TCP
@var{port}.  The socket will be added to the
session table and the shell parameter @code{REPLY}
will be set to the file descriptor associated
with that listener.

If @code{-d} is specified, its argument will be taken as the target file
descriptor for the connection.

In order to elicit more verbose output, use @code{-v}.
@end quotation

@code{ztcp} @code{-a} [ @code{-tv} ] [ @code{-d} @var{targetfd} ] @var{listenfd}

@quotation

@code{ztcp -a} will accept an incoming connection
to the port associated with @var{listenfd}.
The connection will be added to the session
table and the shell parameter @code{REPLY} will
be set to the file descriptor associated with
the inbound connection.

If @code{-d} is specified, its argument
will be taken as the target file descriptor for the
connection.

If @code{-t} is specified, @code{ztcp} will return
if no incoming connection is pending.  Otherwise
it will wait for one.

In order to elicit more verbose output, use @code{-v}.
@end quotation

@node Closing Connections,Example<2>,Inbound Connections<2>,The zsh/net/tcp Module
@anchor{Zsh/modules closing-connections}@anchor{156}
@subsection Closing Connections


@geindex sockets@comma{} closing TCP; Command

@code{ztcp} @code{-s} @var{fd}

@quotation

@code{ztcp -s} will shut down the socket associated
with @var{fd}. This means a graceful termination
of the connection is initiated, flushing unsent
data (due to Nagle’s algorithm, for example). To
complete it, you should also drain any remaining
data on the fd by reading it. Afterwards you should
use @code{ztcp -c} to close the fd. If you close it
without first using @code{ztcp -s} and draining the
data, the kernel may reset the connection, causing
data you sent to not be received by the other end.

Note that this is only useful for inbound and
outbound connections, not for listening sockets.
@end quotation

@code{ztcp} @code{-cf} [ @code{-v} ] [ @var{fd} ]

@code{ztcp} @code{-c} [ @code{-v} ] [ @var{fd} ]

@quotation

@code{ztcp -c} will close the socket associated
with @var{fd}.  The socket will be removed from the
session table.  If @var{fd} is not specified,
@code{ztcp} will close everything in the session table.

See also the previous @code{ztcp -s} entry.

Normally, sockets registered by zftp (see
@ref{cb,,The zsh/zftp Module})
cannot be closed this way.  In order
to force such a socket closed, use @code{-f}.

In order to elicit more verbose output, use @code{-v}.
@end quotation

@node Example<2>,,Closing Connections,The zsh/net/tcp Module
@anchor{Zsh/modules example}@anchor{157}
@subsection Example


@geindex TCP@comma{} example; Command

Here is how to create a TCP connection between two instances of zsh.  We
need to pick an unassigned port; here we use the randomly chosen 5123.

On @code{host1},

@example
 zmodload zsh/net/tcp
 ztcp -l 5123
 listenfd=$REPLY
 ztcp -a $listenfd
 fd=$REPLY
@end example

The second from last command blocks until there is an incoming connection.

Now create a connection from @code{host2} (which may, of course, be the same
machine):

@example
 zmodload zsh/net/tcp
 ztcp host1 5123
 fd=$REPLY
@end example

Now on each host, @code{$fd} contains a file descriptor for talking to the
other.  For example, on @code{host1}:

@example
 print This is a message >&$fd
@end example

and on @code{host2}:

@example
 read -r line <&$fd; print -r - $line
@end example

prints @code{This is a message}.

To tidy up, on @code{host1}:

@example
 ztcp -c $listenfd
 ztcp -s $fd
 ztcp -c $fd
@end example

and on @code{host2}

@example
 ztcp -s $fd
 ztcp -c $fd
@end example

@node The zsh/termcap Module,The zsh/terminfo Module,The zsh/net/tcp Module,Zsh Modules
@anchor{Zsh/modules id36}@anchor{158}@anchor{Zsh/modules the-zsh-termcap-module}@anchor{bf}
@section The zsh/termcap Module


The @code{zsh/termcap} module makes available one builtin command:

@geindex echotc; Function

@geindex termcap value@comma{} printing; Command

@code{echotc} @var{cap} [ @var{arg} … ]

@quotation

Output the termcap value corresponding to the capability
@var{cap}, with optional arguments.
@end quotation

The @code{zsh/termcap} module makes available one parameter:

@geindex termcap; Variable

@code{termcap}

@quotation

An associative array that maps termcap capability codes to
their values.
@end quotation

@node The zsh/terminfo Module,The zsh/watch Module,The zsh/termcap Module,Zsh Modules
@anchor{Zsh/modules id37}@anchor{159}@anchor{Zsh/modules the-zsh-terminfo-module}@anchor{c0}
@section The zsh/terminfo Module


The @code{zsh/terminfo} module makes available one builtin command:

@geindex echoti; Function

@geindex terminfo value@comma{} printing; Command

@code{echoti} @var{cap} [ @var{arg} ]

@quotation

Output the terminfo value corresponding to the capability
@var{cap}, instantiated with @var{arg} if applicable.
@end quotation

The @code{zsh/terminfo} module makes available one parameter:

@geindex terminfo; Variable

@code{terminfo}

@quotation

An associative array that maps terminfo capability names to
their values.
@end quotation

@node The zsh/watch Module,The zsh/zftp Module,The zsh/terminfo Module,Zsh Modules
@anchor{Zsh/modules id38}@anchor{15a}@anchor{Zsh/modules the-zsh-watch-module}@anchor{120}
@section The zsh/watch Module


The @code{zsh/watch} module can be used to report when specific users log in or
out. This is controlled via the following parameters.

@geindex LOGCHECK; Variable

@code{LOGCHECK}

@quotation

The interval in seconds between checks for login/logout activity
using the @code{watch} parameter.
@end quotation

@geindex watch; Variable

@geindex WATCH; Variable

@code{watch} <S> <Z> (@code{WATCH} <S>)

@quotation

An array (colon-separated list) of login/logout events to report.

If it contains the single word @code{all}, then all login/logout events
are reported.  If it contains the single word @code{notme}, then all
events are reported as with @code{all} except @code{$USERNAME}.

An entry in this list may consist of a username,
an @code{@@} followed by a remote hostname,
and a @code{%} followed by a line (tty).  Any of these may
be a pattern (be sure to quote this during the assignment to
@code{watch} so that it does not immediately perform file generation);
the setting of the @code{EXTENDED_GLOB} option is respected.
Any or all of these components may be present in an entry;
if a login/logout event matches all of them,
it is reported.

For example, with the @code{EXTENDED_GLOB} option set, the following:

@example
 watch=('^(pws|barts)')
@end example

causes reports for activity associated with any user other than @code{pws}
or @code{barts}.
@end quotation

@geindex WATCHFMT; Variable

@code{WATCHFMT}

@quotation

The format of login/logout reports if the @code{watch} parameter is set.
Default is @code{%n has %a %l from %m}.
Recognizes the following escape sequences, many of which are described
further in @ref{131,,Simple Prompt Escapes}:

@code{%n}

@quotation

The name of the user that logged in/out.
@end quotation

@code{%a}

@quotation

The observed action, i.e. “logged on” or “logged off”.
@end quotation

@code{%l}

@quotation

The line (tty) the user is logged in on.
@end quotation

@code{%M}

@quotation

The full hostname of the remote host.
@end quotation

@code{%m}

@quotation

The hostname up to the first @code{.}.  If only the
IP address is available or the utmp field contains
the name of an X-windows display, the whole name is printed.

`NOTE:'
The @code{%m} and @code{%M} escapes will work only if there is a host name
field in the utmp on your machine.  Otherwise they are
treated as ordinary strings.
@end quotation

@code{%F@{}@var{color}@code{@}} (@code{%f})

@quotation

Start (stop) using a different foreground color.
@end quotation

@code{%K@{}@var{color}@code{@}} (@code{%k})

@quotation

Start (stop) using a different background color.
@end quotation

@code{%H@{}@var{group}@code{@}}

@quotation

Change all character visual attributes using a highlighting
specification from the @code{.zle.hlgroups} associative array.
@end quotation

@code{%S} (@code{%s})

@quotation

Start (stop) standout mode.
@end quotation

@code{%U} (@code{%u})

@quotation

Start (stop) underline mode.
@end quotation

@code{%B} (@code{%b})

@quotation

Start (stop) boldface mode.
@end quotation

@code{%t}

@code{%@@}

@quotation

The time, in 12-hour, am/pm format.
@end quotation

@code{%T}

@quotation

The time, in 24-hour format.
@end quotation

@code{%w}

@quotation

The date in @var{day}@code{-}@var{dd} format.
@end quotation

@code{%W}

@quotation

The date in @var{mm}@code{/}@var{dd}@code{/}@var{yy} format.
@end quotation

@code{%D}

@quotation

The date in @var{yy}@code{-}@var{mm}@code{-}@var{dd} format.
@end quotation

@code{%D@{}@var{string}@code{@}}

@quotation

The date formatted as @var{string} using the @code{strftime} function, with
zsh extensions as described for @code{%D@{}@var{string}@code{@}} escape sequence in
@ref{131,,Simple Prompt Escapes}.
@end quotation

@code{%(}@var{x}@code{:}@var{true-text}@code{:}@var{false-text}@code{)}

@quotation

Specifies a ternary expression.
The character following the @var{x} is
arbitrary; the same character is used to separate the text
for the “true” result from that for the “false” result.
Both the separator and the right parenthesis may be escaped
with a backslash.
Ternary expressions may be nested.

The test character @var{x} may be any one of @code{l}, @code{n}, @code{m}
or @code{M}, which indicate a `true’ result if the corresponding
escape sequence would return a non-empty value; or it may be @code{a},
which indicates a `true’ result if the watched user has logged in,
or `false’ if he has logged out.
Other characters evaluate to neither true nor false; the entire
expression is omitted in this case.

If the result is `true’, then the @var{true-text}
is formatted according to the rules above and printed,
and the @var{false-text} is skipped.
If `false’, the @var{true-text} is skipped and the @var{false-text}
is formatted and printed.
Either or both of the branches may be empty, but
both separators must be present in any case.
@end quotation
@end quotation

Furthermore, the @code{zsh/watch} module makes available one builtin
command:

@geindex log; Function

@geindex watch@comma{} use of; Variable

@geindex watching users; Command

@geindex users@comma{} watching; Command

@code{log}

@quotation

List all users currently logged in who are affected by
the current setting of the @code{watch} parameter.
@end quotation

@node The zsh/zftp Module,The zsh/zle Module,The zsh/watch Module,Zsh Modules
@anchor{Zsh/modules id39}@anchor{15b}@anchor{Zsh/modules the-zsh-zftp-module}@anchor{cb}
@section The zsh/zftp Module


The @code{zsh/zftp} module makes available one builtin command:

@geindex zftp; Function

@geindex FTP; Command

@geindex files@comma{} transferring; Command

@code{zftp} @var{subcommand} [ @var{args} ]

@quotation

The @code{zsh/zftp} module is a client for FTP (file transfer protocol).  It
is implemented as a builtin to allow full use of shell command line
editing, file I/O, and job control mechanisms.  Often, users will
access it via shell functions providing a more powerful interface; a set is
provided with the @code{zsh} distribution and is described in
@code{zshzftpsys}.
However, the @code{zftp} command is entirely usable in its
own right.

All commands consist of the command name @code{zftp} followed by the name
of a subcommand.  These are listed below.  The return status of each
subcommand is supposed to reflect the success or failure of the remote
operation.  See a description of the variable @code{ZFTP_VERBOSE} for
more information on how responses from the server may be printed.
@end quotation

@menu
* Subcommands:: 
* Parameters: Parameters<5>. 
* Functions: Functions<3>. 
* Problems:: 

@end menu

@node Subcommands,Parameters<5>,,The zsh/zftp Module
@anchor{Zsh/modules subcommands}@anchor{15c}
@subsection Subcommands


@geindex zftp@comma{} subcommands; Command

@geindex FTP@comma{} starting a session; Command

@code{open} @var{host}[@code{:}@var{port}] [ @var{user} [ @var{password} [ @var{account} ] ] ]

@quotation

Open a new FTP session to @var{host}, which may be the name of a TCP/IP
connected host or an IP number in the standard dot notation.  If the
argument is in the form @var{host}@code{:}@var{port}, open a connection to
TCP port @var{port} instead of the standard FTP port 21.  This may be
the name of a TCP service or a number:  see the description of
@code{ZFTP_PORT} below for more information.

If IPv6 addresses in colon format are used, the @var{host} should be
surrounded by quoted square brackets to distinguish it from the @var{port},
for example @code{'[fe80::203:baff:fe02:8b56]'}.  For consistency this is
allowed with all forms of @var{host}.

Remaining arguments are passed to the @code{login} subcommand.  Note that
if no arguments beyond @var{host} are supplied, @code{open} will `not'
automatically call @code{login}.  If no arguments at all are supplied,
@code{open} will use the parameters set by the @code{params} subcommand.

After a successful open, the shell variables @code{ZFTP_HOST}, @code{ZFTP_PORT},
@code{ZFTP_IP} and @code{ZFTP_SYSTEM} are available; see `Variables’
below.
@end quotation

@code{login} [ @var{name} [ @var{password} [ @var{account} ] ] ]

@code{user} [ @var{name} [ @var{password} [ @var{account} ] ] ]

@quotation

Login the user @var{name} with parameters @var{password} and @var{account}.
Any of the parameters can be omitted, and will be read from standard
input if needed (@var{name} is always needed).  If
standard input is a terminal, a prompt for each one will be printed on
standard error and @var{password} will not be echoed.  If any of the
parameters are not used, a warning message is printed.

After a successful login, the shell variables @code{ZFTP_USER},
@code{ZFTP_ACCOUNT} and @code{ZFTP_PWD} are available; see `Variables’
below.

This command may be re-issued when a user is already logged in, and
the server will first be reinitialized for a new user.
@end quotation

@code{params} [ @var{host} [ @var{user} [ @var{password} [ @var{account} ] ] ] ]

@code{params} @code{-}

@quotation

Store the given parameters for a later @code{open} command with no
arguments.  Only those given on the command line will be remembered.
If no arguments are given, the parameters currently set are printed,
although the password will appear as a line of stars; the return status is
one if no parameters were set, zero otherwise.

Any of the parameters may be specified as a @code{?}, which
may need to be quoted to protect it from shell expansion.  In this case,
the appropriate parameter will be read from stdin as with the
@code{login} subcommand, including special handling of @var{password}.  If the
@code{?} is followed by a string, that is used as the prompt for reading the
parameter instead of the default message (any necessary punctuation and
whitespace should be included at the end of the prompt).  The first letter
of the parameter (only) may be quoted with a @code{\}; hence an argument
@code{"\\$word"} guarantees that the string from the shell parameter @code{$word}
will be treated literally, whether or not it begins with a @code{?}.

If instead a single @code{-} is given, the existing parameters, if any,
are deleted.  In that case, calling @code{open} with no arguments will
cause an error.

The list of parameters is not deleted after a @code{close}, however it
will be deleted if the @code{zsh/zftp} module is unloaded.

For example,

@example
 zftp params ftp.elsewhere.xx juser '?Password for juser: '
@end example

will store the host @code{ftp.elsewhere.xx} and the user @code{juser} and
then prompt the user for the corresponding password with the given prompt.
@end quotation

@code{test}

@quotation

Test the connection; if the server has reported
that it has closed the connection (maybe due to a timeout), return
status 2; if no connection was open anyway, return status 1; else
return status 0.  The @code{test} subcommand is
silent, apart from messages printed by the @code{$ZFTP_VERBOSE}
mechanism, or error messages if the connection closes.  There is no
network overhead for this test.

The test is only supported on systems with either the
@code{select(2)} or
@code{poll(2)} system calls; otherwise the message @code{not
supported on this system} is printed instead.

The @code{test} subcommand will automatically be called at the start of any
other subcommand for the current session when a connection is open.
@end quotation

@code{cd} @var{directory}

@quotation

Change the remote directory to @var{directory}.  Also alters the shell
variable @code{ZFTP_PWD}.
@end quotation

@code{cdup}

@quotation

Change the remote directory to the one higher in the directory tree.
Note that @code{cd ..} will also work correctly on non-UNIX systems.
@end quotation

@code{dir} [ @var{arg} … ]

@quotation

Give a (verbose) listing of the remote directory.  The @var{arg}s are
passed directly to the server. The command’s behaviour is implementation
dependent, but a UNIX server will typically interpret @var{arg}s as
arguments to the @code{ls} command and with no arguments return the
result of @code{ls -l}. The directory is listed to standard output.
@end quotation

@code{ls} [ @var{arg} … ]

@quotation

Give a (short) listing of the remote directory.  With no @var{arg},
produces a raw list of the files in the directory, one per line.
Otherwise, up to vagaries of the server implementation, behaves
similar to @code{dir}.
@end quotation

@code{type} [ @var{type} ]

@quotation

Change the type for the transfer to @var{type}, or print the current type
if @var{type} is absent.  The allowed values are @code{A} (ASCII),
@code{I} (Image, i.e. binary), or @code{B} (a synonym for @code{I}).

The FTP default for a transfer is ASCII.  However, if @code{zftp} finds
that the remote host is a UNIX machine with 8-bit byes, it will
automatically switch to using binary for file transfers upon
@code{open}.  This can subsequently be overridden.

The transfer type is only passed to the remote host when a data
connection is established; this command involves no network overhead.
@end quotation

@code{ascii}

@quotation

The same as @code{type A}.
@end quotation

@code{binary}

@quotation

The same as @code{type I}.
@end quotation

@code{mode} [ @code{S} | @code{B} ]

@quotation

Set the mode type to stream (@code{S}) or block (@code{B}).  Stream mode is
the default; block mode is not widely supported.
@end quotation

@code{remote} @var{file} …

@code{local} [ @var{file} … ]

@quotation

Print the size and last modification time of the remote or local
files.  If there is more than one item on the list, the name of the
file is printed first.  The first number is the file size, the second
is the last modification time of the file in the format
@code{CCYYMMDDhhmmSS} consisting of year, month, date, hour, minutes and
seconds in GMT.  Note that this format, including the length, is
guaranteed, so that time strings can be directly compared via the
@code{[[} builtin’s @code{<} and @code{>} operators, even if they are too long
to be represented as integers.

Not all servers support the commands for retrieving this information.
In that case, the @code{remote} command will print nothing and return
status 2, compared with status 1 for a file not found.

The @code{local} command (but not @code{remote}) may be used with no
arguments, in which case the information comes from examining file
descriptor zero.  This is the same file as seen by a @code{put} command
with no further redirection.
@end quotation

@code{get} @var{file} …

@quotation

Retrieve all @var{file}s from the server, concatenating them
and sending them to standard output.
@end quotation

@code{put} @var{file} …

@quotation

For each @var{file}, read a file from standard input and send that to
the remote host with the given name.
@end quotation

@code{append} @var{file} …

@quotation

As @code{put}, but if the remote @var{file} already exists, data is
appended to it instead of overwriting it.
@end quotation

@code{getat} @var{file} @var{point}

@code{putat} @var{file} @var{point}

@code{appendat} @var{file} @var{point}

@quotation

Versions of @code{get}, @code{put} and @code{append} which will start the
transfer at the given @var{point} in the remote @var{file}.  This is
useful for appending to an incomplete local file.  However, note that
this ability is not universally supported by servers (and is not quite
the behaviour specified by the standard).
@end quotation

@code{delete} @var{file} …

@quotation

Delete the list of files on the server.
@end quotation

@code{mkdir} @var{directory}

@quotation

Create a new directory @var{directory} on the server.
@end quotation

@code{rmdir} @var{directory}

@quotation

Delete the directory @var{directory}  on the server.
@end quotation

@code{rename} @var{old-name} @var{new-name}

@quotation

Rename file @var{old-name} to @var{new-name} on the server.
@end quotation

@code{site} @var{arg} …

@quotation

Send a host-specific command to the server.  You will probably
only need this if instructed by the server to use it.
@end quotation

@code{quote} @var{arg} …

@quotation

Send the raw FTP command sequence to the server.  You should be
familiar with the FTP command set as defined in RFC959 before doing
this.  Useful commands may include @code{STAT} and @code{HELP}.  Note also
the mechanism for returning messages as described for the variable
@code{ZFTP_VERBOSE} below, in particular that all messages from the
control connection are sent to standard error.
@end quotation

@code{close}

@code{quit}

@quotation

Close the current data connection.  This unsets the shell parameters
@code{ZFTP_HOST}, @code{ZFTP_PORT}, @code{ZFTP_IP}, @code{ZFTP_SYSTEM}, @code{ZFTP_USER},
@code{ZFTP_ACCOUNT}, @code{ZFTP_PWD}, @code{ZFTP_TYPE} and @code{ZFTP_MODE}.
@end quotation

@code{session} [ @var{sessname} ]

@quotation

Allows multiple FTP sessions to be used at once.  The name of the session
is an arbitrary string of characters; the default session is called
@code{default}.  If this command is called without an argument, it will list
all the current sessions; with an argument, it will either switch to the
existing session called @var{sessname}, or create a new session of that name.

Each session remembers the status of the connection, the set of
connection-specific shell parameters (the same set as are unset when a
connection closes, as given in the description of @code{close}), and any user
parameters specified with the @code{params} subcommand.  Changing to a
previous session restores those values; changing to a new session
initialises them in the same way as if @code{zftp} had just been loaded.  The
name of the current session is given by the parameter @code{ZFTP_SESSION}.
@end quotation

@code{rmsession} [ @var{sessname} ]

@quotation

Delete a session; if a name is not given, the current session is deleted.
If the current session is deleted, the earliest existing session becomes
the new current session, otherwise the current session is not changed.
If the session being deleted is the only one, a new session called
@code{default} is created and becomes the current session; note that this is
a new session even if the session being deleted is also called
@code{default}. It is recommended that sessions not be deleted while
background commands which use @code{zftp} are still active.
@end quotation

@node Parameters<5>,Functions<3>,Subcommands,The zsh/zftp Module
@anchor{Zsh/modules id40}@anchor{15d}
@subsection Parameters


@geindex zftp@comma{} parameters; Command

The following shell parameters are used by @code{zftp}.  Currently none
of them are special.

@geindex ZFTP_TMOUT; Variable

@code{ZFTP_TMOUT}

@quotation

Integer.  The time in seconds to wait for a network operation to
complete before returning an error.  If this is not set when the
module is loaded, it will be given the default value 60.  A value of
zero turns off timeouts.  If a timeout occurs on the control
connection it will be closed.  Use a larger value if this occurs too
frequently.
@end quotation

@geindex ZFTP_IP; Variable

@code{ZFTP_IP}

@quotation

Readonly.  The IP address of the current connection in dot notation.
@end quotation

@geindex ZFTP_HOST; Variable

@code{ZFTP_HOST}

@quotation

Readonly.  The hostname of the current remote server.  If the host was
opened as an IP number, @code{ZFTP_HOST} contains that instead; this
saves the overhead for a name lookup, as IP numbers are most commonly
used when a nameserver is unavailable.
@end quotation

@geindex ZFTP_PORT; Variable

@code{ZFTP_PORT}

@quotation

Readonly.  The number of the remote TCP port to which the connection is
open (even if the port was originally specified as a named service).
Usually this is the standard FTP port, 21.

In the unlikely event that your system does not have the appropriate
conversion functions, this appears in network byte order.  If your
system is little-endian, the port then consists of two swapped bytes and the
standard port will be reported as 5376.  In that case, numeric ports passed
to @code{zftp open} will also need to be in this format.
@end quotation

@geindex ZFTP_SYSTEM; Variable

@code{ZFTP_SYSTEM}

@quotation

Readonly.  The system type string returned by the server in response
to an FTP @code{SYST} request.  The most interesting case is a string
beginning @code{"UNIX Type: L8"}, which ensures maximum compatibility
with a local UNIX host.
@end quotation

@geindex ZFTP_TYPE; Variable

@code{ZFTP_TYPE}

@quotation

Readonly.  The type to be used for data transfers , either @code{A} or
@code{I}.   Use the @code{type} subcommand to change this.
@end quotation

@geindex ZFTP_USER; Variable

@code{ZFTP_USER}

@quotation

Readonly.  The username currently logged in, if any.
@end quotation

@geindex ZFTP_ACCOUNT; Variable

@code{ZFTP_ACCOUNT}

@quotation

Readonly.  The account name of the current user, if any.  Most servers
do not require an account name.
@end quotation

@geindex ZFTP_PWD; Variable

@code{ZFTP_PWD}

@quotation

Readonly.  The current directory on the server.
@end quotation

@geindex ZFTP_CODE; Variable

@code{ZFTP_CODE}

@quotation

Readonly.  The three digit code of the last FTP reply from the server
as a string.  This can still be read after the connection is closed, and
is not changed when the current session changes.
@end quotation

@geindex ZFTP_REPLY; Variable

@code{ZFTP_REPLY}

@quotation

Readonly.  The last line of the last reply sent by the server.  This
can still be read after the connection is closed, and is not changed when
the current session changes.
@end quotation

@geindex ZFTP_SESSION; Variable

@code{ZFTP_SESSION}

@quotation

Readonly.  The name of the current FTP session; see the description of the
@code{session} subcommand.
@end quotation

@geindex ZFTP_PREFS; Variable

@code{ZFTP_PREFS}

@quotation

A string of preferences for altering aspects of @code{zftp}’s behaviour.
Each preference is a single character.  The following are defined:

@code{P}

@quotation

Passive:  attempt to make the remote server initiate data transfers.
This is slightly more efficient than sendport mode.  If the letter
@code{S} occurs later in the string, @code{zftp} will use sendport mode if
passive mode is not available.
@end quotation

@code{S}

@quotation

Sendport:  initiate transfers by the FTP @code{PORT} command.  If this
occurs before any @code{P} in the string, passive mode will never be
attempted.
@end quotation

@code{D}

@quotation

Dumb:  use only the bare minimum of FTP commands.  This prevents
the variables @code{ZFTP_SYSTEM} and @code{ZFTP_PWD} from being set, and
will mean all connections default to ASCII type.  It may prevent
@code{ZFTP_SIZE} from being set during a transfer if the server
does not send it anyway (many servers do).
@end quotation

If @code{ZFTP_PREFS} is not set when @code{zftp} is loaded, it will be set to a
default of @code{PS}, i.e. use passive mode if available, otherwise
fall back to sendport mode.
@end quotation

@geindex ZFTP_VERBOSE; Variable

@code{ZFTP_VERBOSE}

@quotation

A string of digits between 0 and 5 inclusive, specifying which
responses from the server should be printed.  All responses go to
standard error.  If any of the numbers 1 to 5 appear in the string,
raw responses from the server with reply codes beginning with that
digit will be printed to standard error.  The first digit of the three
digit reply code is defined by RFC959 to correspond to:


@enumerate 

@item 
A positive preliminary reply.

@item 
A positive completion reply.

@item 
A positive intermediate reply.

@item 
A transient negative completion reply.

@item 
A permanent negative completion reply.
@end enumerate

It should be noted that, for unknown reasons, the reply `Service not
available’, which forces termination of a connection, is classified as
421, i.e. `transient negative’, an interesting interpretation of the word
`transient’.

The code 0 is special:  it indicates that all but the last line of
multiline replies read from the server will be printed to standard
error in a processed format.  By convention, servers use this
mechanism for sending information for the user to read.  The
appropriate reply code, if it matches the same response, takes
priority.

If @code{ZFTP_VERBOSE} is not set when @code{zftp} is loaded, it will be
set to the default value @code{450}, i.e., messages destined for the user
and all errors will be printed.  A null string is valid and
specifies that no messages should be printed.
@end quotation

@node Functions<3>,Problems,Parameters<5>,The zsh/zftp Module
@anchor{Zsh/modules functions}@anchor{15e}
@subsection Functions


@geindex zftp@comma{} functions; Command

@geindex zftp_chpwd@comma{} specification; Function

@code{zftp_chpwd}

@quotation

If this function is set by the user, it is called every time the
directory changes on the server, including when a user is logged
in, or when a connection is closed.  In the last case, @code{$ZFTP_PWD}
will be unset; otherwise it will reflect the new directory.
@end quotation

@geindex zftp_progress@comma{} specification; Function

@code{zftp_progress}

@quotation

If this function is set by the user, it will be called during
a @code{get}, @code{put} or @code{append} operation each time sufficient data
has been received from the host.  During a @code{get}, the data is sent
to standard output, so it is vital that this function should write
to standard error or directly to the terminal, `not' to standard
output.

When it is called with a transfer in progress, the following
additional shell parameters are set:

@geindex ZFTP_FILE; Variable

@code{ZFTP_FILE}

@quotation

The name of the remote file being transferred from or to.
@end quotation

@geindex ZFTP_TRANSFER; Variable

@code{ZFTP_TRANSFER}

@quotation

A @code{G} for a @code{get} operation and a @code{P} for a @code{put} operation.
@end quotation

@geindex ZFTP_SIZE; Variable

@code{ZFTP_SIZE}

@quotation

The total size of the complete file being transferred:
the same as the first value provided by the
@code{remote} and @code{local} subcommands for a particular file.
If the server cannot supply this value for a remote file being
retrieved, it will not be set.  If input is from a pipe the value may
be incorrect and correspond simply to a full pipe buffer.
@end quotation

@geindex ZFTP_COUNT; Variable

@code{ZFTP_COUNT}

@quotation

The amount of data so far transferred; a number between zero and
@code{$ZFTP_SIZE}, if that is set.  This number is always available.
@end quotation

The function is initially called with @code{ZFTP_TRANSFER} set
appropriately and @code{ZFTP_COUNT} set to zero.  After the transfer is
finished, the function will be called one more time with
@code{ZFTP_TRANSFER} set to @code{GF} or @code{PF}, in case it wishes to tidy
up.  It is otherwise never called twice with the same value of
@code{ZFTP_COUNT}.

Sometimes the progress meter may cause disruption.  It is up to the
user to decide whether the function should be defined and to use
@code{unfunction} when necessary.
@end quotation

@node Problems,,Functions<3>,The zsh/zftp Module
@anchor{Zsh/modules problems}@anchor{15f}
@subsection Problems


@geindex zftp@comma{} problems; Command

A connection may not be opened in the left hand side of a pipe as this
occurs in a subshell and the file information is not updated in the main
shell.  In the case of type or mode changes or closing the connection in a
subshell, the information is returned but variables are not updated until
the next call to @code{zftp}.  Other status changes in subshells will not be
reflected by changes to the variables (but should be otherwise harmless).

Deleting sessions while a @code{zftp} command is active in the background can
have unexpected effects, even if it does not use the session being deleted.
This is because all shell subprocesses share information on the state of
all connections, and deleting a session changes the ordering of that
information.

On some operating systems, the control connection is not valid after a
fork(), so that operations in subshells, on the left hand side
of a pipeline, or in the background are not possible, as they should be.
This is presumably a bug in the operating system.

@node The zsh/zle Module,The zsh/zleparameter Module,The zsh/zftp Module,Zsh Modules
@anchor{Zsh/modules id41}@anchor{160}@anchor{Zsh/modules the-zsh-zle-module}@anchor{99}
@section The zsh/zle Module


The @code{zsh/zle} module contains the Zsh Line Editor.  See
@code{zshzle}.

@node The zsh/zleparameter Module,The zsh/zprof Module,The zsh/zle Module,Zsh Modules
@anchor{Zsh/modules id42}@anchor{161}@anchor{Zsh/modules the-zsh-zleparameter-module}@anchor{fc}
@section The zsh/zleparameter Module


@geindex parameters@comma{} special; Command

The @code{zsh/zleparameter} module defines two special parameters that can be
used to access internal information of the Zsh Line Editor (see
@code{zshzle}).

@geindex keymaps; Variable

@code{keymaps}

@quotation

This array contains the names of the keymaps currently defined.
@end quotation

@geindex widgets; Variable

@code{widgets}

@quotation

This associative array contains one entry per widget. The name
of the widget is the key and the value gives information about the
widget. It is either

@quotation

the string @code{builtin} for builtin widgets,
a string of the form @code{user:}@var{name} for user-defined widgets,

@quotation

where @var{name} is the name of the shell function implementing the widget,
@end quotation


@table @asis

@item a string of the form @code{completion:}@var{type}@code{:}@var{name}

for completion widgets,
@end table

or a null value if the widget is not yet fully defined.
@end quotation

In the penultimate case, @var{type} is the name of the builtin widget the
completion widget imitates in its behavior and @var{name} is the name
of the shell function implementing the completion widget.
@end quotation

@node The zsh/zprof Module,The zsh/zpty Module,The zsh/zleparameter Module,Zsh Modules
@anchor{Zsh/modules id43}@anchor{162}@anchor{Zsh/modules the-zsh-zprof-module}@anchor{cc}
@section The zsh/zprof Module


@geindex functions@comma{} profiling; Command

When loaded, the @code{zsh/zprof} causes shell functions to be profiled.
The profiling results can be obtained with the @code{zprof}
builtin command made available by this module.  There is no way to turn
profiling off other than unloading the module.

@geindex zprof; Function

@code{zprof} [ @code{-c} ]

@quotation

Without the @code{-c} option, @code{zprof} lists profiling results to
standard output.  The format is comparable to that of commands like
@code{gprof}.

At the top there is a summary listing all functions that were called
at least once.  This summary is sorted in decreasing order of the
amount of time spent in each.  The lines contain
the number of the function in order, which is used in
other parts of the list in suffixes of the form
@code{[}@var{num}@code{]}, then the number of calls made to the function.
The next three columns list the time in
milliseconds spent in the function and its descendants, the average
time in milliseconds spent in the function and its descendants per
call and the percentage of time spent in all shell functions used in
this function and its descendants.  The following three columns give
the same information, but counting only the time spent in the function
itself.  The final column shows the name of the function.

After the summary, detailed information about every function that was
invoked is listed, sorted in decreasing order of the amount of time spent
in each function and its descendants.  Each of these entries consists of
descriptions for the functions that called the function described, the
function itself, and the functions that were called from it.  The
description for the function itself has the same format as in the summary
(and shows the same information).  The other lines don’t show the number of
the function at the beginning and have their function named indented to
make it easier to distinguish the line showing the function described in
the section from the surrounding lines.

The information shown in this case is almost the same as in the summary,
but only refers to the call hierarchy being displayed.  For example, for a
calling function the column showing the total running time lists the time
spent in the described function and its descendants only for the times when
it was called from that particular calling function.  Likewise, for a
called function, this columns lists the total time spent in the called
function and its descendants only for the times when it was called from the
function described.

Also in this case, the column showing the number of calls to a function
also shows a slash and then the total number of invocations made to the
called function.

As long as the @code{zsh/zprof} module is loaded, profiling will be done and
multiple invocations of the @code{zprof} builtin command will show the
times and numbers of calls since the module was loaded.  With the
@code{-c} option, the @code{zprof} builtin command will reset its internal
counters and will not show the listing.
@end quotation

@node The zsh/zpty Module,The zsh/zselect Module,The zsh/zprof Module,Zsh Modules
@anchor{Zsh/modules id44}@anchor{163}@anchor{Zsh/modules the-zsh-zpty-module}@anchor{cd}
@section The zsh/zpty Module


The @code{zsh/zpty} module offers one builtin:

@geindex zpty; Function

@code{zpty} [ @code{-e} ] [ @code{-b} ] @var{name} [ @var{arg} … ]

@quotation

The arguments following @var{name} are concatenated with spaces between,
then executed as a command, as if passed to the @code{eval} builtin.  The
command runs under a newly assigned pseudo-terminal; this is useful for
running commands non-interactively which expect an interactive
environment.  The @var{name} is not part of the command, but is used to
refer to this command in later calls to @code{zpty}.

With the @code{-e} option, the pseudo-terminal is set up so that input
characters are echoed.

With the @code{-b} option, input to and output from the pseudo-terminal are
made non-blocking.

The shell parameter @code{REPLY} is set to the file descriptor assigned to
the master side of the pseudo-terminal.  This allows the terminal to be
monitored with ZLE descriptor handlers (see the description of option
@code{-F} for @code{zle} builtin in @ref{ba,,Zle Builtins})
or manipulated with @code{sysread} and @code{syswrite} builtins
(see @ref{11f,,The zsh/system Module}).
`Warning': Use of @code{sysread}
and @code{syswrite} is `not' recommended; use @code{zpty -r} and @code{zpty -w}
unless you know exactly what you are doing.
@end quotation

@code{zpty} @code{-d} [ @var{name} … ]

@quotation

The @code{-d} option is used to delete commands previously started, by
supplying a list of their @var{name}s.  If no @var{name} is given, all
commands are deleted.  Deleting a command causes the HUP signal to be sent
to the corresponding process.  It is not a good idea to use this form in a
subshell, as it will kill the command but leave the parent shell confused
about the state, and it may try to kill another process that re-used the
process ID.
@end quotation

@code{zpty} @code{-w} [ @code{-n} ] @var{name} [ @var{string} … ]

@quotation

The @code{-w} option can be used to send the to command @var{name} the given
@var{string}s as input (separated by spaces).  If the @code{-n} option is
`not' given, a newline is added at the end.

If no @var{string} is provided, the standard input is copied to the
pseudo-terminal; this may stop before copying the full input if the
pseudo-terminal is non-blocking.  The exact input is always copied:
the @code{-n} option is not applied.

Note that the command under the pseudo-terminal sees this input as if it
were typed, so beware when sending special tty driver characters such as
word-erase, line-kill, and end-of-file.
@end quotation

@code{zpty} @code{-r} [ @code{-mt} ] @var{name} [ @var{param} [ @var{pattern} ] ]

@quotation

The @code{-r} option can be used to read the output of the command @var{name}.
With only a @var{name} argument, the output read is copied to the standard
output.  Unless the pseudo-terminal is non-blocking, copying continues
until the command under the pseudo-terminal exits; when non-blocking, only
as much output as is immediately available is copied.  The return status is
zero if any output is copied.

When also given a @var{param} argument, at most one line is read and stored
in the parameter named @var{param}.  Less than a full line may be read if
the pseudo-terminal is non-blocking.  The return status is zero if at least
one character is stored in @var{param}.

If a @var{pattern} is given as well, output is read until the whole string
read matches the @var{pattern}, even in the non-blocking case.  The return
status is zero if the string read matches the pattern, or if the command
has exited but at least one character could still be read.  If the option
@code{-m} is present, the return status is zero only if the pattern matches.
As of this writing, a maximum of one megabyte of output can be consumed
this way; if a full megabyte is read without matching the pattern, the
return status is non-zero.

In all cases, the return status is non-zero if nothing could be read, and
is @code{2} if this is because the command has finished.

If the @code{-r} option is combined with the @code{-t} option, @code{zpty} tests
whether output is available before trying to read.  If no output is
available, @code{zpty} immediately returns the status @code{1}.  When used
with a @var{pattern}, the behaviour on a failed poll is similar to
when the command has exited:  the return value is zero if at least
one character could still be read even if the pattern failed to match.
@end quotation

@code{zpty} @code{-t} @var{name}

@quotation

The @code{-t} option without the @code{-r} option can be used to test whether the
command @var{name} is still running.  It returns a zero status if the command
is running and a non-zero value otherwise.  Note that this does not indicate
whether or not any output is available to read.
@end quotation

@code{zpty} [ @code{-L} ]

@quotation

The last form, without any arguments, is used to list the commands
currently defined.  If the @code{-L} option is given, this is done in the
form of calls to the @code{zpty} builtin.
@end quotation

@node The zsh/zselect Module,The zsh/zutil Module,The zsh/zpty Module,Zsh Modules
@anchor{Zsh/modules id45}@anchor{164}@anchor{Zsh/modules the-zsh-zselect-module}@anchor{121}
@section The zsh/zselect Module


The @code{zsh/zselect} module makes available one builtin command:

@geindex zselect; Function

@geindex select@comma{} system call; Command

@geindex file descriptors@comma{} waiting for; Command

@code{zselect} [ @code{-rwe} ] [ @code{-t} @var{timeout} ] [ @code{-a} @var{array} ] [ @code{-A} @var{assoc} ] [ @var{fd} … ]

@quotation

The @code{zselect} builtin is a front-end to the `select’ system call, which
blocks until a file descriptor is ready for reading or writing, or has an
error condition, with an optional timeout.  If this is not available on
your system, the command prints an error message and returns status 2
(normal errors return status 1).  For more information, see your system’s
documentation for @code{select(2)}.  Note there is no connection with the
shell builtin of the same name.

Arguments and options may be intermingled in any order.  Non-option
arguments are file descriptors, which must be decimal integers.  By
default, file descriptors are to be tested for reading, i.e. @code{zselect}
will return when data is available to be read from the file descriptor, or
more precisely, when a read operation from the file descriptor will not
block.  After a @code{-r}, @code{-w} and @code{-e}, the given file descriptors are
to be tested for reading, writing, or error conditions.  These options and
an arbitrary list of file descriptors may be given in any order.

(The presence of an `error condition’ is not well defined in the
documentation for many implementations of the select system call.
According to recent versions of the POSIX specification, it is really an
`exception' condition, of which the only standard example is out-of-band
data received on a socket.  So zsh users are unlikely to find the @code{-e}
option useful.)

The option @code{-t} @var{timeout} specifies a timeout in hundredths of a
second.  This may be zero, in which case the file descriptors will simply
be polled and @code{zselect} will return immediately.  It is possible to call
zselect with no file descriptors and a non-zero timeout for use as a
finer-grained replacement for `sleep’; note, however, the return status is
always 1 for a timeout.

The option @code{-a} @var{array} indicates that @var{array} should be set to
indicate the file descriptor(s) which are ready.  If the option
is not
given, the array @code{reply} will be used for this purpose.  The array will
contain a string similar to the arguments for @code{zselect}.  For example,

@example
 zselect -t 0 -r 0 -w 1
@end example

might return immediately with status 0 and @code{$reply} containing @code{-r 0 -w
1} to show that both file descriptors are ready for the requested
operations.

The option @code{-A} @var{assoc} indicates that the associative array
@var{assoc} should be set to indicate the file descriptor(s)
which are ready.  This option overrides the option @code{-a}, nor will
@code{reply} be modified.  The keys of @code{assoc} are the file descriptors, and
the corresponding values are any of the characters @code{rwe} to indicate
the condition.

The command returns status 0 if some file descriptors are ready for
reading.  If the operation timed out, or a timeout of 0 was given and no
file descriptors were ready, or there was an error, it returns status 1 and
the array will not be set (nor modified in any way).  If there was an error
in the select operation the appropriate error message is printed.
@end quotation

@node The zsh/zutil Module,,The zsh/zselect Module,Zsh Modules
@anchor{Zsh/modules id46}@anchor{165}@anchor{Zsh/modules the-zsh-zutil-module}@anchor{ca}
@section The zsh/zutil Module


@geindex builtins@comma{} utility; Command

The @code{zsh/zutil} module only adds some builtins:

@geindex zstyle; Function

@code{zstyle} [ @code{-L} [ @var{metapattern} [ @var{style} ] ] ]

@code{zstyle} [ @code{-e} | @code{-} | @code{--} ] @var{pattern} @var{style} @var{string} …

@code{zstyle -d} [ @var{pattern} [ @var{style} … ] ]

@code{zstyle -g} @var{name} [ @var{pattern} [ @var{style} ] ]

@code{zstyle -q} @var{context} @var{style}

@code{zstyle -@{a|b|s}@} @var{context} @var{style} @var{name} [ @var{sep} ]

@code{zstyle -@{T|t}@} @var{context} @var{style} [ @var{string} … ]

@code{zstyle -m} @var{context} @var{style} @var{pattern}

@quotation

This builtin command is used to define and lookup styles.  Styles are
pairs of names and values, where the values consist of any number of
strings.  They are stored together with patterns and lookup is done by
giving a string, called the `context', which is matched against the
patterns.  The definition stored for the most specific pattern that matches
will be returned.

A pattern is considered to be more specific
than another if it contains more components (substrings separated by
colons) or if the patterns for the components are more specific, where
simple strings are considered to be more specific than patterns and
complex patterns are considered to be more specific than the pattern
@code{*}.  A @code{*} in the pattern will match zero or more characters
in the context; colons are not treated specially in this regard.
If two patterns are equally specific, the tie is broken in favour of
the pattern that was defined first.

`Example'
.. index:: single: preferred-precipitation, example style; Keystroke

@geindex weather@comma{} example function; Function

For example, a fictional @code{weather} plugin might state in its documentation
that it looks up the @code{preferred-precipitation} style under the
@code{:weather:}@var{continent}@code{:}@var{day-of-the-week}@code{:}@var{phase-of-the-moon} context.
According to this, you might set the following in your @code{zshrc}:

@example
 zstyle ':weather:europe:*' preferred-precipitation rain
 zstyle ':weather:*:Sunday:*' preferred-precipitation snow
@end example

Then the plugin would run under the hood a command such as

@example
 zstyle -s \
   ":weather:$@{continent@}:$@{day_of_week@}:$@{moon_phase@}" \
   preferred-precipitation REPLY
@end example

in order to retrieve your preference into the scalar variable @code{$REPLY}.
On Sundays @code{$REPLY} would be set to @code{snow}; in Europe it would be set
to @code{rain}; and on Sundays in Europe it would be set to @code{snow} again,
because the patterns @code{:weather:europe:*} and @code{:weather:*:Sunday:*} both
match the @var{context} argument to @code{zstyle -s}, are equally specific, and the
latter is more specific (because it has more colon-separated components).

`Usage'

The forms that operate on patterns are the following.

@code{zstyle} [ @code{-L} [ @var{metapattern} [ @var{style} ] ] ]

@quotation

Without arguments, lists style definitions.  Styles
are shown in alphabetic order and patterns are shown in the order
@code{zstyle} will test them.

If the @code{-L} option is given, listing is done in the form of calls to
@code{zstyle}.  The optional first argument, @var{metapattern}, is a pattern which
will be matched against the string supplied as @var{pattern} when the style was
defined.  Note:
this means, for example, @code{zstyle -L ":completion:*"} will
match any supplied pattern beginning @code{:completion:}, not
just @code{":completion:*"}:  use @code{':completion:\*'} to match that.
The optional second argument limits the output to a specific @var{style} (not a
pattern).  @code{-L} is not compatible with any other options.
@end quotation

@code{zstyle} [ @code{-} | @code{--} | @code{-e} ] @var{pattern} @var{style} @var{string} …

@quotation

@geindex reply@comma{} use of; Variable

Defines the given @var{style} for the @var{pattern} with the @var{string}s as
the value.  If the @code{-e} option is given, the @var{string}s will be
concatenated (separated by spaces) and the resulting string will be
evaluated (in the same way as it is done by the @code{eval} builtin
command) when the style is looked up.  In this case the parameter
@code{reply} must be assigned to set the strings returned after the
evaluation.  Before evaluating the value, @code{reply} is unset, and
if it is still unset after the evaluation, the style is treated as if
it were not set.
@end quotation

@code{zstyle -d} [ @var{pattern} [ @var{style} … ] ]

@quotation

Delete style definitions. Without arguments all definitions are deleted,
with a @var{pattern} all definitions for that pattern are deleted and if
any @var{style}s are given, then only those styles are deleted for the
@var{pattern}.
@end quotation

@code{zstyle -g} @var{name} [ @var{pattern} [ @var{style} ] ]

@quotation

Retrieve a style definition. The @var{name} is
used as the name of an array in which the results are stored. Without
any further arguments, all patterns defined are returned. With a
@var{pattern} the styles defined for that pattern are returned and with
both a @var{pattern} and a @var{style}, the value strings of that
combination is returned.
@end quotation

The other forms can be used to look up or test styles for a given context.

@code{zstyle -q} @var{context} @var{style}

@quotation

Return @code{0} if @var{style} is defined in @var{context}.  This does not
evaluate expressions defined by @code{zstyle -e} and does not examine any
values set by @var{style}.  The expected use is to test whether a style
has been defined for @var{context} before asserting a new style.
@end quotation

@code{zstyle -s} @var{context} @var{style} @var{name} [ @var{sep} ]

@quotation

The parameter @var{name} is set to the value of the style interpreted as a
string.  If the value contains several strings they are concatenated with
spaces (or with the @var{sep} string if that is given) between them.

Return @code{0} if the style is set, @code{1} otherwise.
@end quotation

@code{zstyle -b} @var{context} @var{style} @var{name}

@quotation

The value is stored in @var{name} as a boolean, i.e. as the string
@code{yes} if the value has only one string and that string is equal to one
of @code{yes}, @code{true}, @code{on}, or @code{1}. If the value is any other
string or has more than one string, the parameter is set to @code{no}.

Return @code{0} if @var{name} is set to @code{yes}, @code{1} otherwise.
@end quotation

@code{zstyle -a} @var{context} @var{style} @var{name}

@quotation

The value is stored in @var{name} as an array. If @var{name} is declared
as an associative array,  the first, third, etc. strings are used as the
keys and the other strings are used as the values.

Return @code{0} if the style is set, @code{1} otherwise.
@end quotation

@code{zstyle -t} @var{context} @var{style} [ @var{string} … ]

@code{zstyle -T} @var{context} @var{style} [ @var{string} … ]

@quotation

Test the value of a style, i.e. the @code{-t} option only returns a status
(sets @code{$?}).  Without any @var{string} the return status is zero if the
style is defined for at least one matching pattern, has only one string in
its value, and that is equal to one of @code{true}, @code{yes}, @code{on} or
@code{1}. If any @var{string}s are given the status is zero if and only if
at least one of the @var{string}s is equal to at least one of the strings
in the value. If the style is defined but doesn’t match, the return status
is @code{1}. If the style is not defined, the status is @code{2}.

The @code{-T} option tests the values of the style like @code{-t}, but it
returns status zero (rather than @code{2}) if the style is not defined for any
matching pattern.
@end quotation

@code{zstyle -m} @var{context} @var{style} @var{pattern}

@quotation

Match a value. Returns status zero if the
@var{pattern} matches at least one of the strings in the value.
@end quotation
@end quotation

@geindex zformat; Function

@code{zformat -f} [ @code{-qQ} ] ] @var{param} @var{format} @var{spec} …

@code{zformat -F} [ @code{-qQ} ] ] @var{param} @var{format} @var{spec} …

@code{zformat -a} @var{array} @var{sep} @var{spec} …

@quotation

This builtin provides different forms of formatting.

The first form is selected with the @code{-f} option.
In this case the @var{format}
string will be modified by replacing sequences starting with a percent
sign in it with strings from the @var{spec}s.  Each @var{spec} should be
of the form @var{char}@code{:}@var{string} which will cause every
appearance of the sequence @code{%}@var{char} in @var{format} to be replaced
by the @var{string}.  The @code{%} sequence may also contain optional
minimum and maximum field width specifications between the @code{%} and
the @var{char} in the form @code{%}@var{min}@code{.}@var{max}@code{c},
i.e. the minimum field width is given first and if the maximum field
width is used, it has to be preceded by a dot.  Specifying a minimum field
width makes the result be padded with spaces to the right if the
@var{string} is shorter than the requested width.  Padding to the left
can be achieved by giving a negative minimum field width.  If a maximum
field width is specified, the @var{string} will be truncated after that
many characters.

The @var{char} in each @var{spec} may optionally be preceded by an
escaping indicator, either @code{%} to explicitly enable the
@var{spec}-escaping behaviour of @code{-q} described below, or @code{%%} to
explicitly disable it.  The default behaviour is to `not' escape specs.

Any @code{%} sequence in @code{format} that does not match a given @var{spec}
(or one of the special sequences described below) is output as-is.  If
desired, these sequences may be processed by a second round of
formatting, by prompt expansion, etc. – see also @code{-q}.

The sequence @code{%%} can be used to produce a literal @code{%}.
After all @code{%} sequences have been processed, the resulting string is
stored in the parameter @var{param}.

The @code{%}-escapes also understand ternary expressions in the form used by
prompts.  The @code{%} is followed by a @code{(} and then an ordinary
format specifier character as described above.  There may be a set of
digits either before or after the @code{(}; these specify a test
number, which defaults to zero.  Negative numbers are also allowed.  An
arbitrary delimiter character follows the format specifier, which is
followed by a piece of `true’ text, the delimiter character again, a piece
of `false’ text, and a closing parenthesis.  The complete expression
(without the digits) thus looks like
@code{%(}@var{X}@code{.}@var{text1}@code{.}@var{text2}@code{)}, except that
the @code{.} character is arbitrary.  The value given for the format
specifier in the @var{char}@code{:}@var{string} expressions is evaluated as a
mathematical expression, and compared with the test number.  If they are
the same, @var{text1} is output, else @var{text2} is output.  A parenthesis
may be escaped in @var{text2} as @code{%)}.  Either of @var{text1} or
@var{text2} may contain nested @code{%}-escapes.

For example:

@example
 zformat -f REPLY "The answer is '%3(c.yes.no)'." c:3
@end example

outputs “The answer is ‘yes’.” to @code{REPLY} since the value for the format
specifier @code{c} is 3, agreeing with the digit argument to the ternary
expression.

With @code{-F} instead of @code{-f}, ternary expressions choose between the
`true’ or `false’ text on the basis of whether the format specifier is
present and non-empty.  If a test number is provided, it tests the width
of the value given in the format specifier – with a positive
number the condition is true when the width is `greater than' that
number, and with a negative number the condition is true when the width
is `less than or equal to' the absolute value of that number.

With @code{-q}, @code{%} characters in the @var{spec}s are escaped by default
as they are inserted into the formatted string, and pre-escaped @code{%} and
@code{`)}` characters in the format string are left as they are.  For
example:

@example
 zformat -qF REPLY '%%foo%% %B%d%b' d:%bar%
@end example

outputs @code{%%foo%% %B%%bar%%%b} to @code{REPLY}.  This is useful when the
formatted string will undergo further expansion – in this example
the @code{%B...%b} sequences could be used with prompt expansion to
produce bold text.  One notable use case is formatting a description to
be passed to @code{compadd -x} in a completion function.

Since the output with @code{-q} is expected to be subject to further
processing, width specifiers don’t count the extra escape characters,
ensuring that the widths are correct `after' that processing.
Additionally, with @code{-F}, ternary-expression test numbers are compared
against the `pre-escaped' spec lengths.

@code{-Q} is like @code{-q} except that it interprets pre-escaped @code{%} and
@code{`)} characters in the format string as normal.

The optional escaping indicator can be used to exempt individual
@var{spec}s from escaping as described above.  For example:

@example
 zformat -qF REPLY %d %D' d:%foo% %%D:%bar%
@end example

outputs @code{%%foo%% %bar%} to @code{REPLY}.

The form using the @code{-a} option can be used for aligning
strings.  Here, the @var{spec}s are of the form
@var{left}@code{:}@var{right} where @var{left} and @var{right} are
arbitrary strings.  These strings are modified by replacing the colons
by the @var{sep} string and padding the @var{left} strings with spaces
to the right so that the @var{sep} strings in the result (and hence the
@var{right} strings after them) are all aligned if the strings are
printed below each other.  All strings without a colon are left
unchanged and all strings with an empty @var{right} string have the
trailing colon removed.  In both cases the lengths of the strings
are not used to determine how the other strings are to be aligned.
A colon in the @var{left} string can be escaped with a backslash.
The resulting strings are stored in the @var{array}.
@end quotation

@geindex zregexparse; Function

@code{zregexparse}

@quotation

This implements some internals of the @code{_regex_arguments} function.
@end quotation

@geindex zparseopts; Function

@code{zparseopts} [ @code{-DEFGKM} ] [ @code{-a} @var{array} ] [ @code{-A} @var{assoc} ] [ @code{-n} @var{name} ] [ @code{-v} @var{argv} ] [ @code{-} ] @var{spec} …

@quotation

This builtin simplifies the parsing of options in positional parameters,
i.e. the set of arguments given by @code{$*}.  Each @var{spec} describes one
option and must be of the form @var{opt}[@code{=}@var{array}].  If an option
described by @var{opt} is found in the positional parameters it is copied
into the @var{array} specified with the @code{-a} option; if the optional
@code{=}@var{array} is given, it is instead copied into that array, which
should be declared as a normal array and never as an associative array.

At least one @var{spec} must be given.  If a single spec is given which
is either an empty string or a single hyphen (as in
@code{zparseopts -DF '@w{'}}), it signifies that no options are recognised.
(This is useful for future-proofing functions that might gain options
later.)  Otherwise, it is an error to give any @var{spec} without an
@code{=}@var{array} unless one of the @code{-a} or @code{-A} options is used.

Unless the @code{-E} option is given, parsing stops at the first string
that isn’t described by one of the @var{spec}s.  Even with @code{-E},
parsing always stops at a positional parameter equal to @code{--} or
(without @code{-G}) @code{-}. See also @code{-F}.

The @var{opt} description must be one of the following.  Any of the special
characters can appear in the option name provided it is preceded by a
backslash.

@var{name}

@var{name}@code{+}

@quotation

The @var{name} is the name of the option without the leading @code{-}.  To
specify a GNU-style long option, one of the usual two leading @code{-} must
be included in @var{name}; for example, a @code{--file} option is
represented by a @var{name} of @code{-file}.

If a @code{+} appears after @var{name}, the option is appended to @var{array}
each time it is found in the positional parameters; without the @code{+}
only the `last' occurrence of the option is preserved.

If one of these forms is used, the option takes no argument, so parsing
stops if the next positional parameter does not also begin with @code{-}
(unless the @code{-E} option is used).
@end quotation

@var{name}@code{:}

@var{name}@code{:-}

@var{name}@code{::}

@quotation

If one or two colons are given, the option takes an argument; with one
colon, the argument is mandatory and with two colons it is optional.  The
argument is appended to the @var{array} after the option itself.

An optional argument is put into the same array element as the option name
(note that this makes empty strings as arguments indistinguishable).  A
mandatory argument is added as a separate element unless the @code{:-} form
is used, in which case the argument is put into the same element.

A @code{+} as described above may appear between the @var{name} and the
first colon.
@end quotation

By default, option-arguments may appear either immediately following the
option in the same positional parameter or in the next one. Even an optional
argument may appear in the next parameter, unless it begins with a @code{-}.
Additionally, there is no special consideration given to an @code{=}
between an option and its argument. To make parsing use the more common
GNU-style conventions, use the @code{-G} option.

When the names of two options that take no arguments overlap, the longest one
wins, so that parsing for the @var{spec}s @code{-foo -foobar} (for example) is
unambiguous. However, due to the aforementioned handling of option-arguments,
ambiguities may arise when at least one overlapping @var{spec} takes an
argument, as in @code{-foo: -foobar}. In that case, the last matching
@var{spec} wins. (This is not an issue with GNU-style parsing.)

In order to distinguish GNU-style long option @var{spec}s from
@code{zparseopts}’s own options, they `must' be preceded by a @code{-},
@code{--}, or short option @code{spec}, as in @code{zparseopts -Ga opts - -foo}.

The options of @code{zparseopts} itself are:

@code{-a} @var{array}

@quotation

As described above, this names the default array in which to store the
recognised options.
@end quotation

@code{-A} @var{assoc}

@quotation

If this is given, the options and their values are also put into an
associative array with the option names as keys and the arguments (if any)
as the values.
@end quotation

@code{-D}

@quotation

If this option is given, all options found are removed from the positional
parameters of the calling shell or shell function, up to but not including
any not described by the @var{spec}s.  If the first such parameter is
@code{--} or (without @code{-G}) @code{-}, it is removed as well.  This is
similar to using the @code{shift} builtin.
@end quotation

@code{-E}

@quotation

This changes the parsing rules to `not' stop at the first string
that isn’t described by one of the @var{spec}s.  It can be used to test
for or (if used together with @code{-D}) extract options and their
arguments, ignoring all other options and arguments that may be in the
positional parameters.  As indicated above, parsing still stops at the
first @code{-} or @code{--} not described by a @var{spec}, but it is not
removed when used with @code{-D}.
@end quotation

@code{-F}

@quotation

If this option is given, @code{zparseopts} immediately stops at the first
option-like parameter not described by one of the @var{spec}s, prints an
error message, and returns status 1.  Removal (@code{-D}) and extraction
(@code{-E}) are not performed, and option arrays are not updated.  This
provides basic validation for the given options.

Note that the appearance in the positional parameters of an option without
its required argument always aborts parsing and returns an error as described
above regardless of whether this option is used.
@end quotation

@code{-G}

@quotation

This option specifies that options are parsed in the GNU style,
similar to @code{getopt_long(3)}. In particular:

Given the @var{spec} @code{-foo:}, the positional parameter
@code{--foo=bar} is interpreted as option @code{--foo} with
argument @code{bar}, rather than argument @code{=bar} as is the default,
whilst the positional parameter @code{--foobar} is considered an
unknown option (unless another @var{spec} describes it). This applies
to both singly and doubly hyphenated long options.

An empty option-argument can be given to its long option in the same
parameter using a trailing @code{=}.

An optional argument to a long option must be given with the
equals syntax, and an optional argument to a short option must
follow it immediately in the same parameter; in both cases the
following parameter is considered unrelated.

Whenever a long option and its argument are stored in the same array
element, an @code{=} is used to separate them.

A mandatory option-argument given in a separate parameter from its
option (as in @code{--foo} @code{bar}), or any option-argument given to
a short option in the same parameter, is always treated the same
regardless of whether this option is in effect.

Lastly, when this option is active, only @code{--} is treated as an
explicit option-parsing terminator in the parsed arguments; a single
@code{-} is considered a normal operand.

Note: Unlike most @code{getopt_long(3)} implementations,
@code{zparseopts} does not support abbreviating long options.
@end quotation

@code{-K}

@quotation

With this option, the arrays specified with the @code{-a} option and with the
@code{=}@var{array} forms are kept unchanged when none of the @var{spec}s for
them is used.  Otherwise the entire array is replaced when any of the
@var{spec}s is used.  Individual elements of associative arrays specified
with the @code{-A} option are preserved by @code{-K}.  This allows assignment of
default values to arrays before calling @code{zparseopts}.
@end quotation

@code{-M}

@quotation

This changes the assignment rules to implement a map among equivalent
option names.  If any @var{spec} uses the @code{=}@var{array} form, the
string @var{array} is interpreted as the name of another @var{spec},
which is used to choose where to store the values.
Values stored in an associative array (@code{-A}) use the name of the
mapped-to option, whereas values stored in an array use the last
as-given option name.  If no other @var{spec}
is found, the values are stored as usual.  This changes only the way the
values are stored, not the way @code{$*} is parsed, so results may be
unpredictable if the @var{name}@code{+} specifier is used inconsistently.
@end quotation

@code{-n} @var{name}

@quotation

If this option is given, @var{name} is used when printing usage errors
intended for the end user.  Otherwise, the name of the calling function
or script is used.  Error messages arising from misusage of @code{zparseopts}
itself are not affected by this option.
@end quotation

@code{-v} @var{argv}

@quotation

With this option, the elements of the named array @var{argv} are used as the
positional parameters to parse, rather than those given by @code{$*}.  The
array may be modified according to the @code{-D} option.
@end quotation

For example,

@example
 set -- -a -bx -c y -cz baz -cend
 zparseopts a=foo b:=bar c+:=bar
@end example

will have the effect of

@example
 foo=(-a)
 bar=(-b x -c y -c z)
@end example

The arguments from @code{baz} on will not be used.

As an example for the @code{-E} option, consider:

@example
 set -- -a x -b y -c z arg1 arg2
 zparseopts -E -D b:=bar
@end example

will have the effect of

@example
 bar=(-b y)
 set -- -a x -c z arg1 arg2
@end example

I.e., the option @code{-b} and its arguments are taken from the
positional parameters and put into the array @code{bar}.

The @code{-M} option can be used like this:

@example
 set -- -a -bx -c y -cz baz -cend
 zparseopts -A bar -M a=foo b+: c:=b
@end example

to have the effect of

@example
 foo=(-a)
 bar=(-a '@w{'} -b xyz)
@end example
@end quotation

The following is a useful general-purpose pattern:

@example
 local -A opts
 zparseopts -DFGA opts - x -long: || return
 (( $+opts[-x] )) && ... # handle -x
 (( $+opts[--long] )) && ... # handle --long, optarg in $opts[--long]
@end example

@c historic nodename: Calendar Function System

@node Calendar Function System,TCP Function System,Zsh Modules,Top
@anchor{Zsh/calsys doc}@anchor{166}@anchor{Zsh/calsys calendar-function-system}@anchor{167}
@chapter Calendar Function System


@geindex calendar function system; Command

@geindex zsh/datetime@comma{} function system based on; Command

@menu
* Description: Description<7>. 
* File and Date Formats:: 
* User Functions:: 
* Styles:: 
* Utility functions:: 
* Bugs:: 

@end menu

@node Description<7>,File and Date Formats,,Calendar Function System
@anchor{Zsh/calsys description}@anchor{168}
@section Description


The shell is supplied with a series of functions to replace and enhance the
traditional Unix @code{calendar} programme, which warns the user of imminent
or future events, details of which are stored in a text file (typically
@code{calendar} in the user’s home directory).  The version provided here
includes a mechanism for alerting the user when an event is due.

In addition functions @code{age}, @code{before} and @code{after} are provided
that can be used in a glob qualifier; they allow files to be selected
based on their modification times.

The format of the @code{calendar} file and the dates used there in and in
the @code{age} function are described first, then the functions that can
be called to examine and modify the @code{calendar} file.

The functions here depend on the availability of the @code{zsh/datetime}
module which is usually installed with the shell.  The library function
@code{strptime()} must be available; it is present on most recent
operating systems.

@c historic nodename: Calendar File and Date Formats

@node File and Date Formats,User Functions,Description<7>,Calendar Function System
@anchor{Zsh/calsys file-and-date-formats}@anchor{169}@anchor{Zsh/calsys id1}@anchor{16a}
@section File and Date Formats


@menu
* Calendar File Format:: 
* Date Format:: 
* Relative Time Format:: 
* Example: Example<3>. 

@end menu

@node Calendar File Format,Date Format,,File and Date Formats
@anchor{Zsh/calsys calendar-file-format}@anchor{16b}
@subsection Calendar File Format


The calendar file is by default @code{~/calendar}.  This can be configured
by the @code{calendar-file} style, see @ref{16c,,Styles}.
The basic format consists
of a series of separate lines, with no indentation, each including
a date and time specification followed by a description of the event.

Various enhancements to this format are supported, based on the syntax
of Emacs calendar mode.  An indented line indicates a continuation line
that continues the description of the event from the preceding line
(note the date may not be continued in this way).  An initial ampersand
(@code{&}) is ignored for compatibility.

An indented line on which the first non-whitespace character is @code{#}
is not displayed with the calendar entry, but is still scanned for
information.  This can be used to hide information useful to the
calendar system but not to the user, such as the unique identifier
used by @code{calendar_add}.

The Emacs extension that a date with no description may refer to a number
of succeeding events at different times is not supported.

Unless the @code{done-file} style has been altered, any events which
have been processed are appended to the file with the same name as the
calendar file with the suffix @code{.done}, hence @code{~/calendar.done} by
default.

An example is shown below.

@node Date Format,Relative Time Format,Calendar File Format,File and Date Formats
@anchor{Zsh/calsys date-format}@anchor{16d}
@subsection Date Format


The format of the date and time is designed to allow flexibility without
admitting ambiguity.  (The words `date’ and `time’ are both used in the
documentation below; except where specifically noted this implies a string
that may include both a date and a time specification.)  Note that there is
no localization support; month and day names must be in English and
separator characters are fixed.  Matching is case insensitive, and only the
first three letters of the names are significant, although as a special
case a form beginning “month” does not match “Monday”.  Furthermore, time
zones are not handled; all times are assumed to be local.

It is recommended that, rather than exploring the intricacies of the
system, users find a date format that is natural to them and stick to it.
This will avoid unexpected effects.  Various key facts should be noted.

@quotation


@itemize *

@item 
In particular, note the confusion between
@end itemize

@var{month}@code{/}@var{day}@code{/}@var{year} and
@var{day}@code{/}@var{month}@code{/}@var{year} when the month is numeric; these
formats should be avoided if at all possible.  Many alternatives are
available.
* The year must be given in full to avoid confusion, and only years
from 1900 to 2099 inclusive are matched.
@end quotation

The following give some obvious examples; users finding here
a format they like and not subject to vagaries of style may skip
the full description.  As dates and times are matched separately
(even though the time may be embedded in the date), any date format
may be mixed with any format for the time of day provide the
separators are clear (whitespace, colons, commas).

@example
 2007/04/03 13:13
 2007/04/03:13:13
 2007/04/03 1:13 pm
 3rd April 2007, 13:13
 April 3rd 2007 1:13 p.m.
 Apr 3, 2007 13:13
 Tue Apr 03 13:13:00 2007
 13:13 2007/apr/3
@end example

More detailed rules follow.

Times are parsed and extracted before dates.  They must use colons
to separate hours and minutes, though a dot is allowed before seconds
if they are present.  This limits time formats to the following:

@quotation


@itemize *

@item 
@var{HH}@code{:}@var{MM}[@code{:}@var{SS}[@code{.}@var{FFFFF}]] [@code{am|pm|a.m.|p.m.}]

@item 
@var{HH}@code{:}@var{MM}@code{.}@var{SS}[@code{.}@var{FFFFF}] [@code{am|pm|a.m.|p.m.}]
@end itemize
@end quotation

Here, square brackets indicate optional elements, possibly with
alternatives.  Fractions of a second are recognised but ignored.  For
absolute times (the normal format require by the @code{calendar} file and the
@code{age}, @code{before} and @code{after} functions) a date is mandatory but a
time of day is not; the time returned is at the start of the date.  One
variation is allowed: if @code{a.m.} or @code{p.m.} or one of their variants
is present, an hour without a minute is allowed, e.g. @code{3 p.m.}.

Time zones are not handled, though if one is matched following a time
specification it will be removed to allow a surrounding date to be
parsed.  This only happens if the format of the timezone is not too
unusual.  The following are examples of forms that are understood:

@example
 +0100
 GMT
 GMT-7
 CET+1CDT
@end example

Any part of the timezone that is not numeric must have exactly three
capital letters in the name.

Dates suffer from the ambiguity between @var{DD}@code{/}@var{MM}@code{/}@var{YYYY}
and @var{MM}@code{/}@var{DD}@code{/}@var{YYYY}.  It is recommended this form is
avoided with purely numeric dates, but use of ordinals,
eg. @code{3rd/04/2007}, will resolve the ambiguity as the ordinal is always
parsed as the day of the month.  Years must be four digits (and the first
two must be @code{19} or @code{20}); @code{03/04/08} is not recognised.  Other
numbers may have leading zeroes, but they are not required.  The following
are handled:

@quotation


@itemize *

@item 
@var{YYYY}@code{/}@var{MM}@code{/}@var{DD}

@item 
@var{YYYY}@code{-}@var{MM}@code{-}@var{DD}

@item 
@var{YYYY}@code{/}@var{MNM}@code{/}@var{DD}

@item 
@var{YYYY}@code{-}@var{MNM}@code{-}@var{DD}

@item 
@var{DD}[@code{th|st|rd}] @var{MNM}[@code{,}] [ @var{YYYY} ]

@item 
@var{MNM} @var{DD}[@code{th|st|rd][,}] [ @var{YYYY} ]

@item 
@var{DD}[@code{th|st|rd]/}@var{MM}[@code{,}] @var{YYYY}

@item 
@var{DD}[@code{th|st|rd]/}@var{MM}@code{/}@var{YYYY}

@item 
@var{MM}@code{/}@var{DD}[@code{th|st|rd][,}] @var{YYYY}

@item 
@var{MM}@code{/}@var{DD}[@code{th|st|rd]/}@var{YYYY}
@end itemize
@end quotation

Here, @var{MNM} is at least the first three letters of a month name,
matched case-insensitively.  The remainder of the month name may appear but
its contents are irrelevant, so janissary, febrile, martial, apricot,
maybe, junta, etc. are happily handled.

Where the year is shown as optional, the current year is assumed.  There
are only two such cases, the form @code{Jun 20} or @code{14 September} (the only
two commonly occurring forms, apart from a “the” in some forms of English,
which isn’t currently supported).  Such dates will of course become
ambiguous in the future, so should ideally be avoided.

Times may follow dates with a colon, e.g. @code{1965/07/12:09:45}; this is in
order to provide a format with no whitespace.  A comma and whitespace are
allowed, e.g. @code{1965/07/12, 09:45}.  Currently the order of these
separators is not checked, so illogical formats such as @code{1965/07/12, :
,09:45} will also be matched.  For simplicity such variations are not shown
in the list above.  Otherwise, a time is only recognised as being
associated with a date if there is only whitespace in between, or if the
time was embedded in the date.

Days of the week are not normally scanned, but will be ignored if they
occur at the start of the date pattern only.  However, in contexts where it
is useful to specify dates relative to today, days of the week with no
other date specification may be given.  The day is assumed to be either
today or within the past week.  Likewise, the words @code{yesterday},
@code{today} and @code{tomorrow} are handled.  All matches are case-insensitive.
Hence if today is Monday, then @code{Sunday} is equivalent to @code{yesterday},
@code{Monday} is equivalent to @code{today}, but @code{Tuesday} gives a date six
days ago.  This is not generally useful within the calendar file.
Dates in this format may be combined with a time specification; for
example @code{Tomorrow, 8 p.m.}.

For example, the standard date format:

@example
 Fri Aug 18 17:00:48 BST 2006
@end example

is handled by matching @var{HH}@code{:}@var{MM}@code{:}@var{SS} and removing it
together with the matched (but unused) time zone.  This leaves the following:

@example
 Fri Aug 18 2006
@end example

@code{Fri} is ignored and the rest is matched according to the standard rules.

@node Relative Time Format,Example<3>,Date Format,File and Date Formats
@anchor{Zsh/calsys relative-time-format}@anchor{16e}
@subsection Relative Time Format


In certain places relative times are handled.  Here, a date is not allowed;
instead a combination of various supported periods are allowed, together
with an optional time.  The periods must be in order from most to
least significant.

In some cases, a more accurate calculation is possible when there is an
anchor date:  offsets of months or years pick the correct day, rather than
being rounded, and it is possible to pick a particular day in a month as
`(1st Friday)’, etc., as described in more detail below.

Anchors are available in the following cases.  If one or two times are
passed to the function @code{calendar}, the start time acts an anchor for the
end time when the end time is relative (even if the start time is
implicit).  When examining calendar files, the scheduled event being
examined anchors the warning time when it is given explicitly by means of
the @code{WARN} keyword; likewise, the scheduled event anchors a repetition
period when given by the @code{RPT} keyword, so that specifications such as
@code{RPT 2 months, 3rd Thursday} are handled properly.  Finally, the @code{-R}
argument to @code{calendar_scandate} directly provides an anchor for relative
calculations.

The periods handled, with possible abbreviations are:

Years

@quotation

@code{years}, @code{yrs}, @code{ys}, @code{year}, @code{yr}, @code{y}, @code{yearly}.
A year is 365.25 days unless there is an anchor.
@end quotation

Months

@quotation

@code{months}, @code{mons}, @code{mnths}, @code{mths}, @code{month}, @code{mon},
@code{mnth}, @code{mth}, @code{monthly}.  Note that @code{m}, @code{ms}, @code{mn}, @code{mns}
are ambiguous and are `not' handled.  A month is a period
of 30 days rather than a calendar month unless there is an anchor.
@end quotation

Weeks

@quotation

@code{weeks}, @code{wks}, @code{ws}, @code{week}, @code{wk}, @code{w}, @code{weekly}
@end quotation

Days

@quotation

@code{days}, @code{dys}, @code{ds}, @code{day}, @code{dy}, @code{d}, @code{daily}
@end quotation

Hours

@quotation

@code{hours}, @code{hrs}, @code{hs}, @code{hour}, @code{hr}, @code{h}, @code{hourly}
@end quotation

Minutes

@quotation

@code{minutes}, @code{mins}, @code{minute}, @code{min}, but `not' @code{m},
@code{ms}, @code{mn} or @code{mns}
@end quotation

Seconds

@quotation

@code{seconds}, @code{secs}, @code{ss}, @code{second}, @code{sec}, @code{s}
@end quotation

Spaces between the numbers are optional, but are required between items,
although a comma may be used (with or without spaces).

The forms @code{yearly} to @code{hourly} allow the number to be omitted; it is
assumed to be 1.  For example, @code{1 d} and @code{daily} are equivalent.  Note
that using those forms with plurals is confusing; @code{2 yearly} is the same
as @code{2 years}, `not' twice yearly, so it is recommended they only
be used without numbers.

When an anchor time is present, there is an extension to handle regular
events in the form of the @var{n}th @var{some}day of the month.  Such a
specification must occur immediately after any year and month
specification, but before any time of day, and must be in the form
@var{n}(@code{th|st|rd}) @var{day}, for example @code{1st Tuesday} or
@code{3rd Monday}.  As in other places, days are matched case insensitively,
must be in English, and only the first three letters are significant except
that a form beginning `month’ does not match `Monday’.  No attempt is made
to sanitize the resulting date; attempts to squeeze too many occurrences
into a month will push the day into the next month (but in the obvious
fashion, retaining the correct day of the week).

Here are some examples:

@example
 30 years 3 months 4 days 3:42:41
 14 days 5 hours
 Monthly, 3rd Thursday
 4d,10hr
@end example

@node Example<3>,,Relative Time Format,File and Date Formats
@anchor{Zsh/calsys example}@anchor{16f}
@subsection Example


Here is an example calendar file.  It uses a consistent date format,
as recommended above.

@example
 Feb 1, 2006 14:30 Pointless bureaucratic meeting
 Mar 27, 2006 11:00 Mutual recrimination and finger pointing
   Bring water pistol and waterproofs
 Mar 31, 2006 14:00 Very serious managerial pontification
   # UID 12C7878A9A50
 Apr 10, 2006 13:30 Even more pointless blame assignment exercise WARN 30 mins
 May 18, 2006 16:00 Regular moaning session RPT monthly, 3rd Thursday
@end example

The second entry has a continuation line.  The third entry has a
continuation line that will not be shown when the entry is displayed, but
the unique identifier will be used by the @code{calendar_add} function when
updating the event.  The fourth entry will produce a warning 30 minutes
before the event (to allow you to equip yourself appropriately).  The fifth
entry repeats after a month on the 3rd Thursday, i.e. June 15, 2006, at the
same time.

@c historic nodename: Calendar System User Functions

@node User Functions,Styles,File and Date Formats,Calendar Function System
@anchor{Zsh/calsys user-functions}@anchor{170}
@section User Functions


This section describes functions that are designed to be called
directly by the user.  The first part describes those functions
associated with the user’s calendar; the second part describes
the use in glob qualifiers.

@menu
* Calendar System Functions:: 
* Glob Qualifiers: Glob Qualifiers<2>. 

@end menu

@node Calendar System Functions,Glob Qualifiers<2>,,User Functions
@anchor{Zsh/calsys calendar-system-functions}@anchor{171}
@subsection Calendar System Functions


@geindex calendar; Function

@code{calendar} [ @code{-abdDsv} ] [ @code{-C} @var{calfile} ] [ @code{-n} @var{num} ] [ @code{-S} @var{showprog} ]

@quotation

[ [ @var{start} ] @var{end} ]
@end quotation

@code{calendar -r} [ @code{-abdDrsv} ] [ @code{-C} @var{calfile} ] [ @code{-n} @var{num} ] [ @code{-S} @var{showprog} ]

@quotation

@quotation

[ @var{start} ]
@end quotation

Show events in the calendar.

With no arguments, show events from the start of today until the end of
the next working day after today.  In other words, if today is Friday,
Saturday, or Sunday, show up to the end of the following Monday, otherwise
show today and tomorrow.

If @var{end} is given, show events from the start of today up to the time
and date given, which is in the format described in the previous section.
Note that if this is a date the time is assumed to be midnight at the
start of the date, so that effectively this shows all events before
the given date.

@var{end} may start with a @code{+}, in which case the remainder of the
specification is a relative time format as described in the previous
section indicating the range of time from the start time that is to
be included.

If @var{start} is also given, show events starting from that time and date.
The word @code{now} can be used to indicate the current time.

To implement an alert when events are due, include @code{calendar -s} in your
@code{~/.zshrc} file.

Options:

@code{-a}

@quotation

Show all items in the calendar, regardless of the @code{start} and
@code{end}.
@end quotation

@code{-b}

@quotation

Brief:  don’t display continuation lines (i.e. indented lines following
the line with the date/time), just the first line.
@end quotation

@code{-B} @var{lines}

@quotation

Brief: display at most the first @var{lines} lines of the calendar
entry.  @code{-B 1} is equivalent to @code{-b}.
@end quotation

@code{-C} @var{calfile}

@quotation

Explicitly specify a calendar file instead of the value of
the @code{calendar-file} style or the default @code{~/calendar}.
@end quotation

@code{-d}

@quotation

Move any events that have passed from the calendar file to the
“done” file, as given by the @code{done-file} style or the default
which is the calendar file with @code{.done} appended.  This option
is implied by the @code{-s} option.
@end quotation

@code{-D}

@quotation

Turns off the option @code{-d}, even if the @code{-s} option is also present.
@end quotation

@code{-n} @var{num}, @code{-}@var{num}

@quotation

Show at least @var{num} events, if present in the calendar file, regardless
of the @code{start} and @code{end}.
@end quotation

@code{-r}

@quotation

Show all the remaining options in the calendar, ignoring the given @var{end}
time.  The @var{start} time is respected; any argument given is treated
as a @var{start} time.
@end quotation

@code{-s}

@quotation

Use the shell’s @code{sched} command to schedule a timed event that
will warn the user when an event is due.  Note that the @code{sched} command
only runs if the shell is at an interactive prompt; a foreground task
blocks the scheduled task from running until it is finished.

The timed event usually runs the programme @code{calendar_show} to show
the event, as described in @ref{172,,Utility Functions}.

By default, a warning of the event is shown five minutes before it is due.
The warning period can be configured by the style @code{warn-time} or
for a single calendar entry by including @code{WARN} @var{reltime} in the first
line of the entry, where @var{reltime} is one of the usual relative time
formats.

A repeated event may be indicated by including @code{RPT} @var{reldate} in the
first line of the entry.  After the scheduled event has been displayed
it will be re-entered into the calendar file at a time @var{reldate}
after the existing event.  Note that this is currently the only use
made of the repeat count, so that it is not possible to query the schedule
for a recurrence of an event in the calendar until the previous event
has passed.

If @code{RPT} is used, it is also possible to specify that certain
recurrences of an event are rescheduled or cancelled.  This is
done with the @code{OCCURRENCE} keyword, followed by whitespace and the
date and time of the occurrence in the regular sequence, followed by
whitespace and either the date and time of the rescheduled event or
the exact string @code{CANCELLED}.  In this case the date and time must
be in exactly the “date with local time” format used by the
@code{text/calendar} MIME type (RFC 2445),
@var{<YYYY><MM><DD>}@code{T}@var{<hh><mm><ss>} (note the presence of the literal
character @code{T}).  The first word (the regular recurrence) may be
something other than a proper date/time to indicate that the event
is additional to the normal sequence; a convention that retains
the formatting appearance is @code{XXXXXXXXTXXXXXX}.

Furthermore, it is useful to record the next regular recurrence
(as then the displayed date may be for a rescheduled event so cannot
be used for calculating the regular sequence).  This is specified by
@code{RECURRENCE} and a time or date in the same format.  @code{calendar_add}
adds such an indication when it encounters a recurring event that does not
include one, based on the headline date/time.

If @code{calendar_add} is used to update occurrences the @code{UID} keyword
described there should be present in both the existing entry and the added
occurrence in order to identify recurring event sequences.

For example,

@example
 Thu May 6, 2010 11:00 Informal chat RPT 1 week
   # RECURRENCE 20100506T110000
   # OCCURRENCE 20100513T110000 20100513T120000
   # OCCURRENCE 20100520T110000 CANCELLED
@end example

The event that occurs at 11:00 on 13th May 2010 is rescheduled an hour
later.  The event that occurs a week later is cancelled.  The occurrences
are given on a continuation line starting with a @code{#} character so will
not usually be displayed as part of the event.  As elsewhere, no account of
time zones is taken with the times. After the next event occurs the headline
date/time will be @code{Thu May 13, 2010 12:00} while the @code{RECURRENCE}
date/time will be @code{20100513T110000} (note that cancelled and
moved events are not taken account of in the @code{RECURRENCE}, which
records what the next regular recurrence is, but they are accounted for in
the headline date/time).

It is safe to run @code{calendar -s} to reschedule an existing event
(if the calendar file has changed, for example), and also to have it
running in multiples instances of the shell since the calendar file
is locked when in use.

By default, expired events are moved to the “done” file; see the @code{-d}
option.  Use @code{-D} to prevent this.
@end quotation

@code{-S} @var{showprog}

@quotation

Explicitly specify a programme to be used for showing events instead
of the value of the @code{show-prog} style or the default @code{calendar_show}.
@end quotation

@code{-v}

@quotation

Verbose:  show more information about stages of processing.  This
is useful for confirming that the function has successfully parsed
the dates in the calendar file.
@end quotation
@end quotation

@geindex calendar_add; Function

@code{calendar_add} [ @code{-BL} ] @var{event} …

@quotation

Adds a single event to the calendar in the appropriate location.
The event can contain multiple lines, as described in
@ref{169,,File and Date Formats}.
Using this function ensures that the calendar file is sorted in date
and time order.  It also makes special arrangements for locking
the file while it is altered.  The old calendar is left in a file
with the suffix @code{.old}.

The option @code{-B} indicates that backing up the calendar file will be
handled by the caller and should not be performed by @code{calendar_add}.  The
option @code{-L} indicates that @code{calendar_add} does not need to lock the
calendar file as it is already locked.  These options will not usually be
needed by users.

If the style @code{reformat-date} is true, the date and time of the
new entry will be rewritten into the standard date format:  see
the descriptions of this style and the style @code{date-format}.

The function can use a unique identifier stored with each event to ensure
that updates to existing events are treated correctly.  The entry
should contain the word @code{UID}, followed by whitespace, followed by
a word consisting entirely of hexadecimal digits of arbitrary length
(all digits are significant, including leading zeroes).  As the UID
is not directly useful to the user, it is convenient to hide it on
an indented continuation line starting with a @code{#}, for example:

@example
 Aug 31, 2007 09:30  Celebrate the end of the holidays
   # UID 045B78A0
@end example

The second line will not be shown by the @code{calendar} function.

It is possible to specify the @code{RPT} keyword followed by @code{CANCELLED}
instead of a relative time.  This causes any matched event or series
of events to be cancelled (the original event does not have to be marked
as recurring in order to be cancelled by this method).  A @code{UID} is
required in order to match an existing event in the calendar.

@code{calendar_add} will attempt to manage recurrences and occurrences of
repeating events as described for event scheduling by @code{calendar -s}
above.  To reschedule or cancel a single event @code{calendar_add} should be
called with an entry that includes the correct @code{UID} but does `not'
include the @code{RPT} keyword as this is taken to mean the entry applies to a
series of repeating events and hence replaces all existing information.
Each rescheduled or cancelled occurrence must have an @code{OCCURRENCE}
keyword in the entry passed to @code{calendar_add} which will be merged into
the calendar file.  Any existing reference to the occurrence is replaced.
An occurrence that does not refer to a valid existing event is added as a
one-off occurrence to the same calendar entry.
@end quotation

@geindex calendar_edit; Function

@code{calendar_edit}

@quotation

This calls the user’s editor to edit the calendar file.  If
there are arguments, they are taken as the editor to use (the file name
is appended to the commands); otherwise, the editor is given by the
variable @code{VISUAL}, if set, else the variable @code{EDITOR}.

If the calendar scheduler was running, then after editing the file
@code{calendar -s} is called to update it.

This function locks out the calendar system during the edit.
Hence it should be used to edit the calendar file if there is any
possibility of a calendar event occurring meanwhile.  Note this
can lead to another shell with calendar functions enabled hanging waiting
for a lock, so it is necessary to quit the editor as soon as possible.
@end quotation

@geindex calendar_parse; Function

@code{calendar_parse} @var{calendar-entry}

@quotation

This is the internal function that analyses the parts of a calendar
entry, which is passed as the only argument.  The function returns
status 1 if the argument could not be parsed as a calendar entry
and status 2 if the wrong number of arguments were passed; it also sets the
parameter @code{reply} to an empty associative array.  Otherwise,
it returns status 0 and sets elements of the associative
array @code{reply} as follows:


@table @asis

@item @code{time}

The time as a string of digits in the same units as
@code{$EPOCHSECONDS}

@item @code{schedtime}

The regularly scheduled time.  This may differ from
the actual event time @code{time} if this is a recurring event and the next
occurrence has been rescheduled.  Then @code{time} gives the actual time
and @code{schedtime} the time of the regular recurrence before modification.

@item @code{text1}

The text from the line not including the date and time of the
event, but including any @code{WARN} or @code{RPT} keywords and values.

@item @code{warntime}

Any warning time given by the @code{WARN} keyword as a string
of digits containing the time at which to warn in the same units as
@code{$EPOCHSECONDS}.  (Note this is an absolute time, not the relative time
passed down.)  Not set no @code{WARN} keyword and value were
matched.

@item @code{warnstr}

The raw string matched after the @code{WARN} keyword, else unset.

@item @code{rpttime}

Any recurrence time given by the @code{RPT} keyword as a string
of digits containing the time of the recurrence in the same units
as @code{$EPOCHSECONDS}.  (Note this is an absolute time.)  Not set if
no @code{RPT} keyword and value were matched.

@item @code{schedrpttime}

The next regularly scheduled occurrence of a recurring
event before modification.  This may differ from @code{rpttime}, which is the
actual time of the event that may have been rescheduled from the regular
time.

@item @code{rptstr}

The raw string matched after the @code{RPT} keyword, else unset.

@item @code{text2}

The text from the line after removal of the date and any
keywords and values.
@end table
@end quotation

@geindex calendar_showdate; Function

@code{calendar_showdate} [ @code{-r} ] [ @code{-f} @var{fmt} ] @var{date-spec} …

@quotation

The given @var{date-spec} is interpreted and the corresponding date and
time printed.  If the initial @var{date-spec} begins with a @code{+} or
@code{-} it is treated as relative to the current time; @var{date-spec}s after
the first are treated as relative to the date calculated so far and
a leading @code{+} is optional in that case.  This allows one to
use the system as a date calculator.  For example, @code{calendar_showdate '+1
month, 1st Friday'} shows the date of the first Friday of next month.

With the option @code{-r} nothing is printed but the value of the date and
time in seconds since the epoch is stored in the parameter @code{REPLY}.

With the option @code{-f} @var{fmt} the given date/time conversion format
is passed to @code{strftime}; see notes on the @code{date-format} style below.

In order to avoid ambiguity with negative relative date specifications,
options must occur in separate words; in other words, @code{-r} and @code{-f}
should not be combined in the same word.
@end quotation

@geindex calendar_sort; Function

@code{calendar_sort}

@quotation

Sorts the calendar file into date and time order.    The old calendar is
left in a file with the suffix @code{.old}.
@end quotation

@node Glob Qualifiers<2>,,Calendar System Functions,User Functions
@anchor{Zsh/calsys glob-qualifiers}@anchor{173}
@subsection Glob Qualifiers


@code{age}

@quotation

@geindex age; Function

The function @code{age} can be autoloaded and use separately from
the calendar system, although it uses the function @code{calendar_scandate}
for date formatting.  It requires the @code{zsh/stat} builtin, but uses
only the builtin @code{zstat}.

@code{age} selects files having a given modification time for use
as a glob qualifier.  The format of the date is the same as that
understood by the calendar system, described in
@ref{169,,File and Date Formats}.

The function can take one or two arguments, which can be supplied either
directly as command or arguments, or separately as shell parameters.

@example
 print *(e:age 2006/10/04 2006/10/09:)
@end example

The example above matches all files modified between the start of those
dates.  The second argument may alternatively be a relative time
introduced by a @code{+}:

@example
 print *(e:age 2006/10/04 +5d:)
@end example

The example above is equivalent to the previous example.

In addition to the special use of days of the week, @code{today} and
@code{yesterday}, times with no date may be specified; these apply to today.
Obviously such uses become problematic around midnight.

@example
 print *(e-age 12:00 13:30-)
@end example

The example above shows files modified between 12:00 and 13:00 today.

@example
 print *(e:age 2006/10/04:)
@end example

The example above matches all files modified on that date.  If the second
argument is omitted it is taken to be exactly 24 hours after the first
argument (even if the first argument contains a time).

@example
 print *(e-age 2006/10/04:10:15 2006/10/04:10:45-)
@end example

The example above supplies times.  Note that whitespace within the time and
date specification must be quoted to ensure @code{age} receives the correct
arguments, hence the use of the additional colon to separate the date and
time.

@example
 AGEREF=2006/10/04:10:15
 AGEREF2=2006/10/04:10:45
 print *(+age)
@end example

This shows the same example before using another form of argument
passing.  The dates and times in the parameters @code{AGEREF} and @code{AGEREF2}
stay in effect until unset, but will be overridden if any argument is
passed as an explicit argument to age.  Any explicit argument
causes both parameters to be ignored.

Instead of an explicit date and time, it’s possible to use the
modification time of a file as the date and time for either argument
by introducing the file name with a colon:

@example
 print *(e-age :file1-)
@end example

matches all files created on the same day (24 hours starting from
midnight) as @code{file1}.

@example
 print *(e-age :file1 :file2-)
@end example

matches all files modified no earlier than @code{file1} and
no later than @code{file2}; precision here is to the nearest second.
@end quotation

@code{after}

@code{before}

@quotation

@geindex after; Function

@geindex before; Function

The functions @code{after} and @code{before} are simpler versions of @code{age}
that take just one argument.  The argument is parsed similarly to an
argument of @code{age}; if it is not given the variable @code{AGEREF} is
consulted.  As the names of the functions suggest, a file matches if its
modification time is after or before the time and date specified.  If
a time only is given the date is today.

The two following examples are therefore equivalent:

@example
 print *(e-after 12:00-)
 print *(e-after today:12:00-)
@end example
@end quotation

@c historic nodename: Calendar Styles

@node Styles,Utility functions,User Functions,Calendar Function System
@anchor{Zsh/calsys id2}@anchor{174}@anchor{Zsh/calsys styles}@anchor{16c}
@section Styles


The zsh style mechanism using the @code{zstyle} command is describe in
@ref{ca,,The zsh/zutil Module}. This is the same mechanism
used in the completion system.

The styles below are all examined in the context
@code{:datetime:}@var{function}@code{:}, for example @code{:datetime:calendar:}.

@geindex calendar-file; Keystroke

@code{calendar-file}

@quotation

The location of the main calendar.  The default is @code{~/calendar}.
@end quotation

@geindex date-format; Keystroke

@code{date-format}

@quotation

A @code{strftime} format string (see @code{strftime(3)}) with the zsh
extensions providing various numbers with no leading zero or space
if the number is a single digit as described for the
@code{%D@{}@var{string}@code{@}} prompt format in
@ref{175,,Simple Prompt Escapes}.

This is used for outputting dates in @code{calendar}, both to support
the @code{-v} option and when adding recurring events back to the calendar
file, and in @code{calendar_showdate} as the final output format.

If the style is not set, the default used is similar the standard system
format as output by the @code{date} command (also known as `ctime format’):
@code{%a %b %d %H:%M:%S %Z %Y}.
@end quotation

@geindex done-file; Keystroke

@code{done-file}

@quotation

The location of the file to which events which have passed are appended.
The default is the calendar file location with the suffix @code{.done}.
The style may be set to an empty string in which case a “done” file
will not be maintained.
@end quotation

@geindex reformat-date; Keystroke

@code{reformat-date}

@quotation

Boolean, used by @code{calendar_add}.  If it is true, the date and time
of new entries added to the calendar will be reformatted to the format
given by the style @code{date-format} or its default.  Only the date and
time of the event itself is reformatted; any subsidiary dates and times
such as those associated with repeat and warning times are left alone.
@end quotation

@geindex show-prog; Keystroke

@code{show-prog}

@quotation

The programme run by @code{calendar} for showing events.  It will
be passed the start time and stop time of the events requested in seconds
since the epoch followed by the event text.  Note that @code{calendar -s} uses
a start time and stop time equal to one another to indicate alerts
for specific events.

The default is the function @code{calendar_show}.
@end quotation

@geindex warn-time; Keystroke

@code{warn-time}

@quotation

The time before an event at which a warning will be displayed, if the
first line of the event does not include the text @code{EVENT} @var{reltime}.
The default is 5 minutes.
@end quotation

@c historic nodename: Calendar Utility Functions

@node Utility functions,Bugs,Styles,Calendar Function System
@anchor{Zsh/calsys id3}@anchor{176}@anchor{Zsh/calsys utility-functions}@anchor{172}
@section Utility functions


@geindex calendar_lockfiles; Function

@code{calendar_lockfiles}

@quotation

Attempt to lock the files given in the argument.  To prevent
problems with network file locking this is done in an ad hoc fashion
by attempting to create a symbolic link to the file with the name
@var{file}@code{.lockfile}.  No other system level functions are used
for locking, i.e. the file can be accessed and modified by any
utility that does not use this mechanism.  In particular, the user is not
prevented from editing the calendar file at the same time unless
@code{calendar_edit} is used.

Three attempts are made to lock the file before giving up.  If the module
@code{zsh/zselect} is available, the times of the attempts are jittered so that
multiple instances of the calling function are unlikely to retry at the
same time.

The files locked are appended to the array @code{lockfiles}, which should
be local to the caller.

If all files were successfully locked, status zero is returned, else status one.

This function may be used as a general file locking function, although
this will only work if only this mechanism is used to lock files.
@end quotation

@geindex calendar_read; Function

@code{calendar_read}

@quotation

This is a backend used by various other functions to parse the
calendar file, which is passed as the only argument.  The array
@code{calendar_entries} is set to the list of events in the file; no
pruning is done except that ampersands are removed from the start of
the line.  Each entry may contain multiple lines.
@end quotation

@geindex calendar_scandate; Function

@code{calendar_scandate}

@quotation

This is a generic function to parse dates and times that may be
used separately from the calendar system.  The argument is a date
or time specification as described in @ref{169,,File and Date Formats}.
The parameter @code{REPLY}
is set to the number of seconds since the epoch corresponding to that date
or time.  By default, the date and time may occur anywhere within the given
argument.

Returns status zero if the date and time were successfully parsed,
else one.

Options:

@code{-a}

@quotation

The date and time are anchored to the start of the argument; they
will not be matched if there is preceding text.
@end quotation

@code{-A}

@quotation

The date and time are anchored to both the start and end of the argument;
they will not be matched if the is any other text in the argument.
@end quotation

@code{-d}

@quotation

Enable additional debugging output.
@end quotation

@code{-m}

@quotation

Minus.  When @code{-R} @var{anchor_time} is also given the relative time is
calculated backwards from @var{anchor_time}.
@end quotation

@code{-r}

@quotation

The argument passed is to be parsed as a relative time.
@end quotation

@code{-R} @var{anchor_time}

@quotation

The argument passed is to be parsed as a relative time.  The time is
relative to @var{anchor_time}, a time in seconds since the epoch,
and the returned value is the absolute time corresponding to advancing
@var{anchor_time} by the relative time given.
This allows lengths of months to be correctly taken into account.  If
the final day does not exist in the given month, the last day of the
final month is given.  For example, if the anchor time is during 31st
January 2007 and the relative time is 1 month, the final time is the
same time of day during 28th February 2007.
@end quotation

@code{-s}

@quotation

In addition to setting @code{REPLY}, set @code{REPLY2} to the remainder of
the argument after the date and time have been stripped.  This is
empty if the option @code{-A} was given.
@end quotation

@code{-t}

@quotation

Allow a time with no date specification.  The date is assumed to be
today.  The behaviour is unspecified if the iron tongue of midnight
is tolling twelve.
@end quotation
@end quotation

@geindex calendar_show; Function

@code{calendar_show}

@quotation

The function used by default to display events.  It accepts a start time
and end time for events, both in epoch seconds, and an event description.

The event is always printed to standard output.  If the command line editor
is active (which will usually be the case) the command line will be
redisplayed after the output.

If the parameter @code{DISPLAY} is set and the start and end times are
the same (indicating a scheduled event), the function uses the
command @code{xmessage} to display a window with the event details.
@end quotation

@c historic nodename: Calendar Bugs

@node Bugs,,Utility functions,Calendar Function System
@anchor{Zsh/calsys bugs}@anchor{177}
@section Bugs


As the system is based entirely on shell functions (with a little support
from the @code{zsh/datetime} module) the mechanisms used are not as robust as
those provided by a dedicated calendar utility.  Consequently the user
should not rely on the shell for vital alerts.

There is no @code{calendar_delete} function.

There is no localization support for dates and times, nor any support
for the use of time zones.

Relative periods of months and years do not take into account the variable
number of days.

The @code{calendar_show} function is currently hardwired to use @code{xmessage}
for displaying alerts on X Window System displays.  This should be
configurable and ideally integrate better with the desktop.

@code{calendar_lockfiles} hangs the shell while waiting for a lock on a file.
If called from a scheduled task, it should instead reschedule the event
that caused it.

@c historic nodename: TCP Function System

@node TCP Function System,Zftp Function System,Calendar Function System,Top
@anchor{Zsh/tcpsys doc}@anchor{178}@anchor{Zsh/tcpsys tcp-function-system}@anchor{179}
@chapter TCP Function System


@geindex TCP function system; Command

@geindex ztcp@comma{} function system based on; Command

@menu
* Description: Description<8>. 
* TCP User Functions:: 
* TCP User-defined Functions:: 
* TCP Utility Functions:: 
* TCP User Parameters:: 
* TCP User-defined Parameters:: 
* TCP Utility Parameters:: 
* TCP Examples:: 
* TCP Bugs:: 

@end menu

@node Description<8>,TCP User Functions,,TCP Function System
@anchor{Zsh/tcpsys description}@anchor{17a}
@section Description


A module @code{zsh/net/tcp} is provided to provide network I/O over
TCP/IP from within the shell; see its description in
@ref{cf,,The zsh/net/tcp Module}.
This manual page describes a function suite based on the module.
If the module is installed, the functions are usually installed at the
same time, in which case they will be available for
autoloading in the default function search path.  In addition to the
@code{zsh/net/tcp} module, the @code{zsh/zselect} module is used to implement
timeouts on read operations.  For troubleshooting tips, consult the
corresponding advice for the @code{zftp} functions described in
@code{zshzftpsys}.

There are functions corresponding to the basic I/O operations open, close,
read and send, named @code{tcp_open} etc., as well as a function
@code{tcp_expect} for pattern match analysis of data read as input.  The
system makes it easy to receive data from and send data to multiple named
sessions at once.  In addition, it can be linked with the shell’s line
editor in such a way that input data is automatically shown at the
terminal.  Other facilities available including logging, filtering and
configurable output prompts.

To use the system where it is available, it should be enough to
@code{autoload -U tcp_open} and run @code{tcp_open} as documented below to
start a session.  The @code{tcp_open} function will autoload the remaining
functions.

@c historic nodename: TCP Functions

@node TCP User Functions,TCP User-defined Functions,Description<8>,TCP Function System
@anchor{Zsh/tcpsys tcp-user-functions}@anchor{17b}
@section TCP User Functions


@menu
* Basic I/O:: 
* Session Management:: 
* Advanced I/O:: 
* `One-shot’ File Transfer:: 

@end menu

@node Basic I/O,Session Management,,TCP User Functions
@anchor{Zsh/tcpsys basic-i-o}@anchor{17c}
@subsection Basic I/O


@geindex tcp_open; Function

@code{tcp_open} [ @code{-qz} ] @var{host port} [ @var{sess} ]

@code{tcp_open} [ @code{-qz} ] [ @code{-s} @var{sess} | @code{-l} @var{sess}[@code{,}…] ] …

@code{tcp_open} [ @code{-qz} ] [ @code{-a} @var{fd} | @code{-f} @var{fd} ] [ @var{sess} ]

@quotation

Open a new session.  In the first and simplest form, open a TCP connection
to host @var{host} at port @var{port}; numeric and symbolic forms are
understood for both.

If @var{sess} is given, this becomes the name of the session which can be
used to refer to multiple different TCP connections.  If @var{sess} is
not given, the function will invent a numeric name value (note this is
`not' the same as the file descriptor to which the session is attached).
It is recommended that session names not include `funny’ characters, where
funny characters are not well-defined but certainly do not include
alphanumerics or underscores, and certainly do include whitespace.

In the second case, one or more sessions to be opened are given by name.
A single session name is given after @code{-s} and a comma-separated list
after @code{-l}; both options may be repeated as many times as necessary.
A failure to open any session causes @code{tcp_open} to abort.
The host and port are read from the file @code{.ztcp_sessions} in the same
directory as the user’s zsh initialisation files, i.e. usually the home
directory, but @code{$ZDOTDIR} if that is set.  The file consists of lines
each giving a session name and the corresponding host and port, in that
order (note the session name comes first, not last), separated by
whitespace.

The third form allows passive and fake TCP connections.  If the option
@code{-a} is used, its argument is a file descriptor open for listening for
connections.  No function front-end is provided to open such a file
descriptor, but a call to @code{ztcp -l} @var{port} will create one with the
file descriptor stored in the parameter @code{$REPLY}.  The listening port can
be closed with @code{ztcp -c} @var{fd}.  A call to @code{tcp_open -a} @var{fd}
will block until a remote TCP connection is made to @var{port} on the local
machine.  At this point, a session is created in the usual way and is
largely indistinguishable from an active connection created with one of the
first two forms.

If the option @code{-f} is used, its argument is a file descriptor which is
used directly as if it were a TCP session.  How well the remainder of the
TCP function system copes with this depends on what actually underlies this
file descriptor.  A regular file is likely to be unusable; a FIFO (pipe) of
some sort will work better, but note that it is not a good idea for two
different sessions to attempt to read from the same FIFO at once.

If the option @code{-q} is given with any of the three forms, @code{tcp_open}
will not print informational messages, although it will in any case exit
with an appropriate status.

If the line editor (zle) is in use, which is typically the case if the
shell is interactive, @code{tcp_open} installs a handler inside zle which
will check for new data at the same time as it checks for keyboard input.
This is convenient as the shell consumes no CPU time while waiting; the
test is performed by the operating system.  Giving the option @code{-z} to
any of the forms of @code{tcp_open} prevents the handler from being
installed, so data must be read explicitly.  Note, however, this is not
necessary for executing complete sets of send and read commands from a
function, as zle is not active at this point.  Generally speaking, the
handler is only active when the shell is waiting for input at a command
prompt or in the @code{vared} builtin.  The option has no effect if zle is not
active; @code{[[ -o zle]]} will test for this.

The first session to be opened becomes the current session and subsequent
calls to @code{tcp_open} do not change it.  The current session is stored
in the parameter @code{$TCP_SESS}; see below for more detail about the
parameters used by the system.

The function @code{tcp_on_open}, if defined, is called when a session
is opened.  See the description below.
@end quotation

@geindex tcp_close; Function

@code{tcp_close} [ @code{-qn} ] [ @code{-a} | @code{-l} @var{sess}[@code{,}…] | @var{sess} … ]

@quotation

Close the named sessions, or the current session if none is given,
or all open sessions if @code{-a} is given.  The options @code{-l} and @code{-s} are
both handled for consistency with @code{tcp_open}, although the latter is
redundant.

If the session being closed is the current one, @code{$TCP_SESS} is unset,
leaving no current session, even if there are other sessions still open.

If the session was opened with @code{tcp_open -f}, the file descriptor is
closed so long as it is in the range 0 to 9 accessible directly from the
command line.  If the option @code{-n} is given, no attempt will be made to
close file descriptors in this case.  The @code{-n} option is not used for
genuine @code{ztcp} session; the file descriptors are always closed with the
session.

If the option @code{-q} is given, no informational messages will be printed.
@end quotation

@geindex tcp_read; Function

@code{tcp_read} [ @code{-bdq} ] [ @code{-t} @var{TO} ] [ @code{-T} @var{TO} ]

@quotation

@quotation

[ @code{-a} | @code{-u} @var{fd}[@code{,}…] | @code{-l} @var{sess}[@code{,}…] | @code{-s} @var{sess} … ]
@end quotation

Perform a read operation on the current session, or on a list of
sessions if any are given with @code{-u}, @code{-l} or @code{-s}, or all open
sessions if the option @code{-a} is given.  Any of the @code{-u}, @code{-l} or
@code{-s} options may be repeated or mixed together.  The @code{-u} option
specifies a file descriptor directly (only those managed by this system
are useful), the other two specify sessions as described for
@code{tcp_open} above.

The function checks for new data available on all the sessions listed.
Unless the @code{-b} option is given, it will not block waiting for new data.
Any one line of data from any of the available sessions will be read,
stored in the parameter @code{$TCP_LINE}, and displayed to standard output
unless @code{$TCP_SILENT} contains a non-empty string.  When printed to
standard output the string @code{$TCP_PROMPT} will be shown at the start of
the line; the default form for this includes the name of the session being
read.  See below for more information on these parameters.  In this mode,
@code{tcp_read} can be called repeatedly until it returns status 2 which
indicates all pending input from all specified sessions has been handled.

With the option @code{-b}, equivalent to an infinite timeout, the function
will block until a line is available to read from one of the specified
sessions.  However, only a single line is returned.

The option @code{-d} indicates that all pending input should be drained.  In
this case @code{tcp_read} may process multiple lines in the manner given
above; only the last is stored in @code{$TCP_LINE}, but the complete set is
stored in the array @code{$tcp_lines}.  This is cleared at the start of each
call to @code{tcp_read}.

The options @code{-t} and @code{-T} specify a timeout in seconds, which may be a
floating point number for increased accuracy.  With @code{-t} the timeout is
applied before each line read.  With @code{-T}, the timeout applies to the
overall operation, possibly including multiple read operations if the
option @code{-d} is present; without this option, there is no distinction
between @code{-t} and @code{-T}.

The function does not print informational messages, but if the option
@code{-q} is given, no error message is printed for a non-existent session.

A return status of 2 indicates a timeout or no data to read.  Any other
non-zero return status indicates some error condition.

See @code{tcp_log} for how to control where data is sent by @code{tcp_read}.
@end quotation

@geindex tcp_send; Function

@code{tcp_send} [ @code{-cnq} ] [ @code{-s} @var{sess} | @code{-l} @var{sess}[@code{,}…] ] @var{data} …

@code{tcp_send} [ @code{-cnq} ] @code{-a} @var{data} …

@quotation

Send the supplied data strings to all the specified sessions in turn.  The
underlying operation differs little from a @code{print -r} to the session’s
file descriptor, although it attempts to prevent the shell from dying owing
to a @code{SIGPIPE} caused by an attempt to write to a defunct session.

The option @code{-c} causes @code{tcp_send} to behave like @code{cat}.  It reads
lines from standard input until end of input and sends them in turn to the
specified session(s) exactly as if they were given as @var{data}
arguments to individual @code{tcp_send} commands.

The option @code{-n} prevents @code{tcp_send} from putting a newline at the end
of the data strings.

The remaining options all behave as for @code{tcp_read}.

The data arguments are not further processed once they have been passed to
@code{tcp_send}; they are simply passed down to @code{print -r}.

If the parameter @code{$TCP_OUTPUT} is a non-empty string and logging is
enabled then the data sent to each session will be echoed to the log
file(s) with @code{$TCP_OUTPUT} in front where appropriate, much
in the manner of @code{$TCP_PROMPT}.
@end quotation

@node Session Management,Advanced I/O,Basic I/O,TCP User Functions
@anchor{Zsh/tcpsys session-management}@anchor{17d}
@subsection Session Management


@geindex tcp_alias; Function

@code{tcp_alias} [ @code{-q} ] @var{alias}@code{=}@var{sess} …

@code{tcp_alias} [ @code{-q} ] [ @var{alias} … ]

@code{tcp_alias} @code{-d} [ @code{-q} ] @var{alias} …

@quotation

This function is not particularly well tested.

The first form creates an alias for a session name; @var{alias} can then be
used to refer to the existing session @var{sess}.  As many aliases may be
listed as required.

The second form lists any aliases specified, or all aliases if none.

The third form deletes all the aliases listed.  The underlying sessions are
not affected.

The option @code{-q} suppresses an inconsistently chosen subset of error
messages.
@end quotation

@geindex tcp_log; Function

@code{tcp_log} [ @code{-asc} ] [ @code{-n} | @code{-N} ] [ @var{logfile} ]

@quotation

With an argument @var{logfile}, all future input from @code{tcp_read} will be
logged to the named file.  Unless @code{-a} (append) is given, this file will
first be truncated or created empty.  With no arguments, show the current
status of logging.

With the option @code{-s}, per-session logging is enabled.  Input from
@code{tcp_read} is output to the file @var{logfile}@code{.}@var{sess}.  As the
session is automatically discriminated by the filename, the contents are
raw (no @code{$TCP_PROMPT}).  The option  @code{-a} applies as above.
Per-session logging and logging of all data in one file are not mutually
exclusive.

The option @code{-c} closes all logging, both complete and per-session logs.

The options @code{-n} and @code{-N} respectively turn off or restore output of
data read by @code{tcp_read} to standard output; hence @code{tcp_log -cn} turns
off all output by @code{tcp_read}.

The function is purely a convenient front end to setting the parameters
@code{$TCP_LOG}, @code{$TCP_LOG_SESS}, @code{$TCP_SILENT}, which are described below.
@end quotation

@geindex tcp_rename; Function

@code{tcp_rename} @var{old} @var{new}

@quotation

Rename session @var{old} to session @var{new}.  The old name becomes invalid.
@end quotation

@geindex tcp_sess; Function

@code{tcp_sess} [ @var{sess} [ @var{command} [ @var{arg} … ] ] ]

@quotation

With no arguments, list all the open sessions and associated file
descriptors.  The current session is marked with a star.  For use in
functions, direct access to the parameters @code{$tcp_by_name}, @code{$tcp_by_fd}
and @code{$TCP_SESS} is probably more convenient; see below.

With a @var{sess} argument, set the current session to @var{sess}.
This is equivalent to changing @code{$TCP_SESS} directly.

With additional arguments, temporarily set the current session while
executing @var{command} @var{arg} ….  @var{command} is re-evaluated
so as to expand aliases etc., but the remaining @var{arg}s are passed
through as that appear to @code{tcp_sess}.  The original session is restored
when @code{tcp_sess} exits.
@end quotation

@node Advanced I/O,`One-shot’ File Transfer,Session Management,TCP User Functions
@anchor{Zsh/tcpsys advanced-i-o}@anchor{17e}
@subsection Advanced I/O


@geindex tcp_command; Function

@code{tcp_command} @var{send-option} … @var{send-argument} …

@quotation

This is a convenient front-end to @code{tcp_send}.  All arguments are passed
to @code{tcp_send}, then the function pauses waiting for data.  While data is
arriving at least every @code{$TCP_TIMEOUT} (default 0.3) seconds, data is
handled and printed out according to the current settings.  Status 0 is
always returned.

This is generally only useful for interactive use, to prevent the display
becoming fragmented by output returned from the connection.  Within a
programme or function it is generally better to handle reading data by a
more explicit method.
@end quotation

@geindex tcp_expect; Function

@code{tcp_expect} [ @code{-q} ] [ @code{-p} @var{var} | @code{-P} @var{var} ] [ @code{-t} @var{TO} | @code{-T} @var{TO} ]

@quotation

@quotation

[ @code{-a} | @code{-s} @var{sess} | @code{-l} @var{sess}[@code{,}…] ] @var{pattern} …
@end quotation

Wait for input matching any of the given @var{pattern}s from any of the
specified sessions.  Input is ignored until an input line matches one of
the given patterns; at this point status zero is returned, the matching
line is stored in @code{$TCP_LINE}, and the full set of lines read during the
call to @code{tcp_expect} is stored in the array @code{$tcp_expect_lines}.

Sessions are specified in the same way as @code{tcp_read}: the default is to
use the current session, otherwise the sessions specified by @code{-a},
@code{-s}, or @code{-l} are used.

Each @var{pattern} is a standard zsh extended-globbing pattern; note that it
needs to be quoted to avoid it being expanded immediately by filename
generation.  It must match the full line, so to match a substring there
must be a @code{*} at the start and end.  The line matched against includes
the @code{$TCP_PROMPT} added by @code{tcp_read}.  It is possible to include the
globbing flags @code{#b} or @code{#m} in the patterns to make backreferences
available in the parameters @code{$MATCH}, @code{$match}, etc., as described in
the base zsh documentation on pattern matching.

Unlike @code{tcp_read}, the default behaviour of @code{tcp_expect} is to block
indefinitely until the required input is found.  This can be modified by
specifying a timeout with @code{-t} or @code{-T}; these function as in
@code{tcp_read}, specifying a per-read or overall timeout, respectively, in
seconds, as an integer or floating-point number.  As @code{tcp_read}, the
function returns status 2 if a timeout occurs.

The function returns as soon as any one of the patterns given match.  If
the caller needs to know which of the patterns matched, the option @code{-p}
@var{var} can be used; on return, @code{$var} is set to the number of the
pattern using ordinary zsh indexing, i.e. the first is 1, and so on.  Note
the absence of a @code{$} in front of @var{var}.  To avoid clashes, the
parameter cannot begin with @code{_expect}.  The index -1 is used if
there is a timeout and 0 if there is no match.

The option @code{-P} @var{var} works similarly to @code{-p}, but instead of
numerical indexes the regular arguments must begin with a prefix
followed by a colon: that prefix is then used as a tag to which @var{var}
is set when the argument matches.  The tag @code{timeout} is used if there
is a timeout and the empty string if there is no match.  Note it is
acceptable for different arguments to start with the same prefix if the
matches do not need to be distinguished.

The option @code{-q} is passed directly down to @code{tcp_read}.

As all input is done via @code{tcp_read}, all the usual rules about output of
lines read apply.  One exception is that the parameter @code{$tcp_lines} will
only reflect the line actually matched by @code{tcp_expect}; use
@code{$tcp_expect_lines} for the full set of lines read during the function
call.
@end quotation

@geindex tcp_proxy; Function

@code{tcp_proxy}

@quotation

This is a simple-minded function to accept a TCP connection and execute a
command with I/O redirected to the connection.  Extreme caution should be
taken as there is no security whatsoever and this can leave your computer
open to the world.  Ideally, it should only be used behind a firewall.

The first argument is a TCP port on which the function will listen.

The remaining arguments give a command and its arguments to execute with
standard input, standard output and standard error redirected to the
file descriptor on which the TCP session has been accepted.
If no command is given, a new zsh is started.  This gives everyone on
your network direct access to your account, which in many cases will be a
bad thing.

The command is run in the background, so @code{tcp_proxy} can then accept new
connections.  It continues to accept new connections until interrupted.
@end quotation

@geindex tcp_spam; Function

@code{tcp_spam} [ @code{-ertv} ] [ @code{-a} | @code{-s} @var{sess} | @code{-l} @var{sess}[@code{,}…] ] @var{cmd} [ @var{arg} … ]

@quotation

Execute @var{cmd} [ @var{arg} … ] for each session in turn.  Note this executes
the command and arguments; it does not send the command line as data
unless the @code{-t} (transmit) option is given.

The sessions may be selected explicitly with the standard @code{-a}, @code{-s} or
@code{-l} options, or may be chosen implicitly.  If none of the three options
is given the rules are: first, if the array @code{$tcp_spam_list} is set, this
is taken as the list of sessions, otherwise all sessions are taken.
Second, any sessions given in the array @code{$tcp_no_spam_list} are removed
from the list of sessions.

Normally, any sessions added by the @code{-a} flag or when all sessions are
chosen implicitly are spammed in alphabetic order; sessions given by the
@code{$tcp_spam_list} array or on the command line are spammed in the order
given.  The @code{-r} flag reverses the order however it was arrived it.

The @code{-v} flag specifies that a @code{$TCP_PROMPT} will be output before each
session.  This is output after any modification to @code{TCP_SESS} by the
user-defined @code{tcp_on_spam} function described below.  (Obviously that
function is able to generate its own output.)

If the option @code{-e} is present, the line given as @var{cmd} [ @var{arg} … ] is executed
using @code{eval}, otherwise it is executed without any further processing.
@end quotation

@geindex tcp_talk; Function

@code{tcp_talk}

@quotation

This is a fairly simple-minded attempt to force input to the line editor to
go straight to the default @code{TCP_SESS}.

An escape string, @code{$TCP_TALK_ESCAPE}, default @code{:}, is used to allow
access to normal shell operation.  If it is on its own at the start of the
line, or followed only by whitespace, the line editor returns to normal
operation.  Otherwise, the string and any following whitespace are skipped
and the remainder of the line executed as shell input without any change of
the line editor’s operating mode.

The current implementation is somewhat deficient in terms of use of the
command history.  For this reason, many users will prefer to use some form
of alternative approach for sending data easily to the current session.
One simple approach is to alias some special character (such as @code{%}) to
@code{tcp_command --}.
@end quotation

@geindex tcp_wait; Function

@code{tcp_wait}

@quotation

The sole argument is an integer or floating point number which gives the
seconds to delay.  The shell will do nothing for that period except wait
for input on all TCP sessions by calling @code{tcp_read -a}.  This is similar
to the interactive behaviour at the command prompt when zle handlers are
installed.
@end quotation

@node `One-shot’ File Transfer,,Advanced I/O,TCP User Functions
@anchor{Zsh/tcpsys one-shot-file-transfer}@anchor{17f}
@subsection `One-shot’ File Transfer


@code{tcp_point} @var{port}

@code{tcp_shoot} @var{host} @var{port}

@quotation

This pair of functions provide a simple way to transfer a file between
two hosts within the shell.  Note, however, that bulk data transfer is
currently done using @code{cat}.  @code{tcp_point} reads any data arriving at
@var{port} and sends it to standard output; @code{tcp_shoot} connects to
@var{port} on @var{host} and sends its standard input.  Any unused @var{port}
may be used; the standard mechanism for picking a port is to think of a
random four-digit number above 1024 until one works.

To transfer a file from host @code{woodcock} to host @code{springes}, on
@code{springes}:

@example
 tcp_point 8091 >output_file
@end example

and on @code{woodcock}:

@example
 tcp_shoot springes 8091 <input_file
@end example

As these two functions do not require @code{tcp_open} to set up a TCP
connection first, they may need to be autoloaded separately.
@end quotation

@node TCP User-defined Functions,TCP Utility Functions,TCP User Functions,TCP Function System
@anchor{Zsh/tcpsys tcp-user-defined-functions}@anchor{180}
@section TCP User-defined Functions


Certain functions, if defined by the user, will be called by the function
system in certain contexts.  This facility depends on the module
@code{zsh/parameter}, which is usually available in interactive shells as the
completion system depends on it.  None of the functions need be defined;
they simply provide convenient hooks when necessary.

Typically, these are called after the requested action has been taken, so
that the various parameters will reflect the new state.

@geindex tcp_on_alias; Function

@code{tcp_on_alias} @var{alias} @var{fd}

@quotation

When an alias is defined, this function will be called with two arguments:
the name of the alias, and the file descriptor of the corresponding session.
@end quotation

@geindex tcp_on_awol; Function

@code{tcp_on_awol} @var{sess} @var{fd}

@quotation

If the function @code{tcp_fd_handler} is handling input from the line
editor and detects that the file descriptor is no longer reusable,
by default it removes it from the list of file descriptors handled
by this method and prints a message.  If the function @code{tcp_on_awol}
is defined it is called immediately before this point.  It may
return status 100, which indicates that the normal handling should
still be performed; any other return status indicates that no further
action should be taken and the @code{tcp_fd_handler} should return
immediately with the given status.  Typically the action of @code{tcp_on_awol}
will be to close the session.

The variable @code{TCP_INVALIDATE_ZLE} will be a non-empty string if it is
necessary to invalidate the line editor display using @code{zle -I} before
printing output from the function.

(`AWOL’ is military jargon for `absent without leave’ or some
variation.  It has no pre-existing technical meaning known to the author.)
@end quotation

@geindex tcp_on_close; Function

@code{tcp_on_close} @var{sess} @var{fd}

@quotation

This is called with the name of a session being closed and the file
descriptor which corresponded to that session.  Both will be invalid by
the time the function is called.
@end quotation

@geindex tcp_on_open; Function

@code{tcp_on_open} @var{sess} @var{fd}

@quotation

This is called after a new session has been defined with the session name
and file descriptor as arguments.  If it returns a non-zero status,
opening the session is assumed to fail and the session is closed
again; however, @code{tcp_open} will continue to attempt to open any
remaining sessions given on the command line.
@end quotation

@geindex tcp_on_rename; Function

@code{tcp_on_rename} @var{oldsess} @var{fd} @var{newsess}

@quotation

This is called after a session has been renamed with the three arguments
old session name, file descriptor, new session name.
@end quotation

@geindex tcp_on_spam; Function

@code{tcp_on_spam} @var{sess} @var{command …}

@quotation

This is called once for each session spammed, just `before' a command is
executed for a session by @code{tcp_spam}.  The arguments are the session name
followed by the command list to be executed.  If @code{tcp_spam} was called
with the option @code{-t}, the first command will be @code{tcp_send}.

This function is called after @code{$TCP_SESS} is set to reflect the session
to be spammed, but before any use of it is made.  Hence it is possible to
alter the value of @code{$TCP_SESS} within this function.  For example, the
session arguments to @code{tcp_spam} could include extra information to be
stripped off and processed in @code{tcp_on_spam}.

If the function sets the parameter @code{$REPLY} to @code{done}, the command
line is not executed; in addition, no prompt is printed for the @code{-v}
option to @code{tcp_spam}.
@end quotation

@geindex tcp_on_unalias; Function

@code{tcp_on_unalias} @var{alias} @var{fd}

@quotation

This is called with the name of an alias and the corresponding session’s
file descriptor after an alias has been deleted.
@end quotation

@node TCP Utility Functions,TCP User Parameters,TCP User-defined Functions,TCP Function System
@anchor{Zsh/tcpsys tcp-utility-functions}@anchor{181}
@section TCP Utility Functions


The following functions are used by the TCP function system but will rarely
if ever need to be called directly.

@geindex tcp_fd_handler; Function

@code{tcp_fd_handler}

@quotation

This is the function installed by @code{tcp_open} for handling input from
within the line editor, if that is required.  It is in the format
documented for the builtin @code{zle -F} in @ref{ba,,Zle Builtins}.

While active, the function sets the parameter @code{TCP_HANDLER_ACTIVE} to 1.
This allows shell code called internally (for example, by setting
@code{tcp_on_read}) to tell if is being called when the shell is otherwise
idle at the editor prompt.
@end quotation

@geindex tcp_output; Function

@code{tcp_output} [ @code{-q} ] @code{-P} @var{prompt} @code{-F} @var{fd} @code{-S} @var{sess}

@quotation

This function is used for both logging and handling output to standard
output, from within @code{tcp_read} and (if @code{$TCP_OUTPUT} is set)
@code{tcp_send}.

The @var{prompt} to use is specified by @code{-P}; the default is the empty
string.  It can contain:

@code{%c}

@quotation

Expands to 1 if the session is the current session, otherwise 0.  Used
with ternary expressions such as @code{%(c.-.+)} to
output @code{+} for the current session and @code{-} otherwise.
@end quotation

@code{%f}

@quotation

Replaced by the session’s file descriptor.
@end quotation

@code{%s}

@quotation

Replaced by the session name.
@end quotation

@code{%%}

@quotation

Replaced by a single @code{%}.
@end quotation

The option @code{-q} suppresses output to standard output, but not to any log
files which are configured.

The @code{-S} and @code{-F} options are used to pass in the session name and file
descriptor for possible replacement in the prompt.
@end quotation

@c historic nodename: TCP Parameters

@node TCP User Parameters,TCP User-defined Parameters,TCP Utility Functions,TCP Function System
@anchor{Zsh/tcpsys tcp-user-parameters}@anchor{182}
@section TCP User Parameters


Parameters follow the usual convention that uppercase is used for scalars
and integers, while lowercase is used for normal and associative array.
It is always safe for user code to read these parameters.  Some parameters
may also be set; these are noted explicitly.  Others are included in this
group as they are set by the function system for the user’s benefit,
i.e. setting them is typically not useful but is benign.

It is often also useful to make settable parameters local to a function.
For example, @code{local TCP_SILENT=1} specifies that data read during the
function call will not be printed to standard output, regardless of the
setting outside the function.  Likewise, @code{local TCP_SESS=}@var{sess}
sets a session for the duration of a function, and @code{local
TCP_PROMPT=} specifies that no prompt is used for input during the
function.

@geindex tcp_expect_lines; Variable

@code{tcp_expect_lines}

@quotation

Array.  The set of lines read during the last call to @code{tcp_expect},
including the last (@code{$TCP_LINE}).
@end quotation

@geindex tcp_filter; Variable

@code{tcp_filter}

@quotation

Array. May be set directly.  A set of extended globbing patterns which,
if matched in @code{tcp_output}, will cause the line not to be printed to
standard output.  The patterns should be defined as described for the
arguments to @code{tcp_expect}.  Output of line to log files is not affected.
@end quotation

@geindex TCP_HANDLER_ACTIVE; Variable

@code{TCP_HANDLER_ACTIVE}

@quotation

Scalar.  Set to 1 within @code{tcp_fd_handler} to indicate to functions
called recursively that they have been called during an editor session.
Otherwise unset.
@end quotation

@geindex TCP_LINE; Variable

@code{TCP_LINE}

@quotation

The last line read by @code{tcp_read}, and hence also @code{tcp_expect}.
@end quotation

@geindex TCP_LINE_FD; Variable

@code{TCP_LINE_FD}

@quotation

The file descriptor from which @code{$TCP_LINE} was read.
@code{$@{tcp_by_fd[$TCP_LINE_FD]@}} will give the corresponding session name.
@end quotation

@geindex tcp_lines; Variable

@code{tcp_lines}

@quotation

Array. The set of lines read during the last call to @code{tcp_read},
including the last (@code{$TCP_LINE}).
@end quotation

@geindex TCP_LOG; Variable

@code{TCP_LOG}

@quotation

May be set directly, although it is also controlled by @code{tcp_log}.
The name of a file to which output from all sessions will be sent.
The output is proceeded by the usual @code{$TCP_PROMPT}.  If it is not an
absolute path name, it will follow the user’s current directory.
@end quotation

@geindex TCP_LOG_SESS; Function

@code{TCP_LOG_SESS}

@quotation

May be set directly, although it is also controlled by @code{tcp_log}.
The prefix for a set of files to which output from each session separately
will be sent; the full filename is @code{$@{TCP_LOG_SESS@}.}@var{sess}.
Output to each file is raw; no prompt is added.  If it is not an absolute
path name, it will follow the user’s current directory.
@end quotation

@geindex tcp_no_spam_list; Variable

@code{tcp_no_spam_list}

@quotation

Array.  May be set directly.  See @code{tcp_spam} for how this is used.
@end quotation

@geindex TCP_OUTPUT; Variable

@code{TCP_OUTPUT}

@quotation

May be set directly.  If a non-empty string, any data sent to a session by
@code{tcp_send} will be logged.  This parameter gives the prompt to be used
in a file specified by @code{$TCP_LOG} but not in a file generated from
@code{$TCP_LOG_SESS}.  The prompt string has the same format as
@code{TCP_PROMPT} and the same rules for its use apply.
@end quotation

@geindex TCP_PROMPT; Variable

@code{TCP_PROMPT}

@quotation

May be set directly.  Used as the prefix for data read by @code{tcp_read}
which is printed to standard output or to the log file given by
@code{$TCP_LOG}, if any.  Any @code{%s}, @code{%f} or @code{%%} occurring in the
string will be replaced by the name of the session, the session’s
underlying file descriptor, or a single @code{%}, respectively.  The
expression @code{%c} expands to 1 if the session being read is the current
session, else 0; this is most useful in ternary expressions such as
@code{%(c.-.+)} which outputs @code{+} if the session is
the current one, else @code{-}.

If the prompt starts with @code{%P}, this is stripped and the complete
result of the previous stage is passed through standard prompt @code{%}-style
formatting before being output.
@end quotation

@geindex TCP_READ_DEBUG; Variable

@code{TCP_READ_DEBUG}

@quotation

May be set directly.  If this has non-zero length, @code{tcp_read} will give
some limited diagnostics about data being read.
@end quotation

@geindex TCP_SECONDS_START; Variable

@code{TCP_SECONDS_START}

@quotation

This value is created and initialised to zero by tcp_open.

The functions @code{tcp_read} and @code{tcp_expect} use the shell’s
@code{SECONDS} parameter for their own timing purposes.  If that parameter
is not of floating point type on entry to one of the functions, it will
create a local parameter @code{SECONDS} which is floating point and set the
parameter @code{TCP_SECONDS_START} to the previous value of @code{$SECONDS}.
If the parameter is already floating point, it is used without a local
copy being created and @code{TCP_SECONDS_START} is not set.  As the global
value is zero, the shell elapsed time is guaranteed to be the sum of
@code{$SECONDS} and @code{$TCP_SECONDS_START}.

This can be avoided by setting @code{SECONDS} globally to a floating point
value using @code{typeset -F SECONDS}; then the TCP functions will never
make a local copy and never set @code{TCP_SECONDS_START} to a non-zero value.
@end quotation

@geindex TCP_SESS; Variable

@code{TCP_SESS}

@quotation

May be set directly.  The current session; must refer to one of the
sessions established by @code{tcp_open}.
@end quotation

@geindex TCP_SILENT; Variable

@code{TCP_SILENT}

@quotation

May be set directly, although it is also controlled by @code{tcp_log}.
If of non-zero length, data read by @code{tcp_read} will not be written to
standard output, though may still be written to a log file.
@end quotation

@geindex tcp_spam_list; Variable

@code{tcp_spam_list}

@quotation

Array.  May be set directly.  See the description of the function
@code{tcp_spam} for how this is used.
@end quotation

@geindex TCP_TALK_ESCAPE; Variable

@code{TCP_TALK_ESCAPE}

@quotation

May be set directly.  See the description of the function @code{tcp_talk} for
how this is used.
@end quotation

@geindex TCP_TIMEOUT; Variable

@code{TCP_TIMEOUT}

@quotation

May be set directly.  Currently this is only used by the function
@code{tcp_command}, see above.
@end quotation

@node TCP User-defined Parameters,TCP Utility Parameters,TCP User Parameters,TCP Function System
@anchor{Zsh/tcpsys tcp-user-defined-parameters}@anchor{183}
@section TCP User-defined Parameters


The following parameters are not set by the function system, but have
a special effect if set by the user.

@geindex tcp_on_read; Variable

@code{tcp_on_read}

@quotation

This should be an associative array; if it is not, the behaviour is
undefined.  Each key is the name of a shell function or other command,
and the corresponding value is a shell pattern (using @code{EXTENDED_GLOB}).
Every line read from a TCP session directly or indirectly using
@code{tcp_read} (which includes lines read by @code{tcp_expect}) is compared
against the pattern.  If the line matches, the command given in the key is
called with two arguments: the name of the session from which the line was
read, and the line itself.

If any function called to handle a line returns a non-zero status, the
line is not output.  Thus a @code{tcp_on_read} handler containing only
the instruction @code{return 1} can be used to suppress output of
particular lines (see, however, @code{tcp_filter} above).  However, the line
is still stored in @code{TCP_LINE} and @code{tcp_lines}; this occurs after all
@code{tcp_on_read} processing.
@end quotation

@node TCP Utility Parameters,TCP Examples,TCP User-defined Parameters,TCP Function System
@anchor{Zsh/tcpsys tcp-utility-parameters}@anchor{184}
@section TCP Utility Parameters


These parameters are controlled by the function system; they may be read
directly, but should not usually be set by user code.

@geindex tcp_aliases; Function

@code{tcp_aliases}

@quotation

Associative array.  The keys are the names of sessions established with
@code{tcp_open}; each value is a space-separated list of aliases which refer
to that session.
@end quotation

@geindex tcp_by_fd; Function

@code{tcp_by_fd}

@quotation

Associative array.  The keys are session file descriptors; each
value is the name of that session.
@end quotation

@geindex tcp_by_name; Function

@code{tcp_by_name}

@quotation

Associative array.  The keys are the names of sessions; each value is the
file descriptor associated with that session.
@end quotation

@c historic nodename: TCP Examples

@node TCP Examples,TCP Bugs,TCP Utility Parameters,TCP Function System
@anchor{Zsh/tcpsys tcp-examples}@anchor{185}
@section TCP Examples


Here is a trivial example using a remote calculator.

To create a calculator server on port 7337 (see the @code{dc} manual page for
quite how infuriating the underlying command is):

@example
 tcp_proxy 7337 dc
@end example

To connect to this from the same host with a session also named @code{dc}:

@example
 tcp_open localhost 7337 dc
@end example

To send a command to the remote session and wait a short while for output
(assuming @code{dc} is the current session):

@example
 tcp_command 2 4 + p
@end example

To close the session:

@example
 tcp_close
@end example

The @code{tcp_proxy} needs to be killed to be stopped.  Note this will not
usually kill any connections which have already been accepted, and also
that the port is not immediately available for reuse.

The following chunk of code puts a list of sessions into an xterm header,
with the current session followed by a star.

@example
 print -n "\033]2;TCP:" $@{(k)tcp_by_name:/$TCP_SESS/$TCP_SESS\*@} "\a"
@end example

@c historic nodename: TCP Bugs

@node TCP Bugs,,TCP Examples,TCP Function System
@anchor{Zsh/tcpsys tcp-bugs}@anchor{186}
@section TCP Bugs


The function @code{tcp_read} uses the shell’s normal @code{read} builtin.  As
this reads a complete line at once, data arriving without a terminating
newline can cause the function to block indefinitely.

Though the function suite works well for interactive use and for data
arriving in small amounts, the performance when large amounts of data are
being exchanged is likely to be extremely poor.

@c historic nodename: Zftp Function System

@node Zftp Function System,User Contributions,TCP Function System,Top
@anchor{Zsh/zftpsys doc}@anchor{187}@anchor{Zsh/zftpsys zftp-function-system}@anchor{188}
@chapter Zftp Function System


@geindex zftp function system; Command

@geindex FTP@comma{} functions for using shell as client; Command

@menu
* Description: Description<9>. 
* Installation:: 
* Functions: Functions<4>. 
* Miscellaneous Features:: 

@end menu

@node Description<9>,Installation,,Zftp Function System
@anchor{Zsh/zftpsys description}@anchor{189}
@section Description


This describes the set of shell functions supplied with the source
distribution as an interface to the @code{zftp} builtin command, allowing you
to perform FTP operations from the shell command line or within functions
or scripts.  The interface is similar to a traditional FTP client (e.g. the
@code{ftp} command itself, see @code{ftp(1)}), but as it is entirely done
within the shell all the familiar completion, editing and globbing features,
and so on, are present, and macros are particularly simple to write as they
are just ordinary shell functions.

The prerequisite is that the @code{zftp} command, as described in
@ref{cb,,The zsh/zftp Module}, must be available in the
version of @code{zsh} installed at your site.  If the shell is configured to
load new commands at run time, it probably is: typing @code{zmodload zsh/zftp}
will make sure (if that runs silently, it has worked).  If this is not the
case, it is possible @code{zftp} was linked into the shell anyway: to test
this, type @code{which zftp} and if @code{zftp} is available you will get the
message @code{zftp: shell built-in command}.

Commands given directly with @code{zftp} builtin may be interspersed between
the functions in this suite; in a few cases, using @code{zftp} directly may
cause some of the status information stored in shell parameters to become
invalid.  Note in particular the description of the variables
@code{$ZFTP_TMOUT}, @code{$ZFTP_PREFS} and @code{$ZFTP_VERBOSE} for @code{zftp}.

@c historic nodename: Installation

@node Installation,Functions<4>,Description<9>,Zftp Function System
@anchor{Zsh/zftpsys installation}@anchor{18a}
@section Installation


You should make sure all the functions from the @code{Functions/Zftp}
directory of the source distribution are available; they all begin with the
two letters @code{zf}.  They may already have been installed on your system;
otherwise, you will need to find them and copy them.  The directory should
appear as one of the elements of the @code{$fpath} array (this should already
be the case if they were installed), and at least the function @code{zfinit}
should be autoloaded; it will autoload the rest.  Finally, to initialize
the use of the system you need to call the @code{zfinit} function.  The
following code in your @code{.zshrc} will arrange for this; assume the
functions are stored in the directory @code{~/myfns}:

@example
 fpath=(~/myfns $fpath)
 autoload -U zfinit
 zfinit
@end example

Note that @code{zfinit} assumes you are using the @code{zmodload} method to
load the @code{zftp} command.  If it is already built into the shell, change
@code{zfinit} to @code{zfinit -n}.  It is helpful (though not essential) if the
call to @code{zfinit} appears after any code to initialize the new completion
system, else unnecessary @code{compctl} commands will be given.

@c historic nodename: Zftp Functions

@node Functions<4>,Miscellaneous Features,Installation,Zftp Function System
@anchor{Zsh/zftpsys functions}@anchor{18b}
@section Functions


The sequence of operations in performing a file transfer is essentially the
same as that in a standard FTP client.  Note that, due to a quirk of the
shell’s @code{getopts} builtin, for those functions that handle options you
must use @code{--} rather than @code{-} to ensure the remaining arguments
are treated literally (a single @code{-} is treated as an argument).

@menu
* Opening a Connection:: 
* Directory Management:: 
* Status Commands:: 
* Retrieving Files:: 
* Sending Files:: 
* Closing the Connection:: 
* Session Management: Session Management<2>. 
* Bookmarks:: 
* Other Functions:: 

@end menu

@node Opening a Connection,Directory Management,,Functions<4>
@anchor{Zsh/zftpsys opening-a-connection}@anchor{18c}
@subsection Opening a Connection


@geindex zfparams; Function

@code{zfparams} [ @var{host} [ @var{user} [ @var{password} … ] ] ]

@quotation

Set or show the parameters for a future @code{zfopen} with no arguments.  If
no arguments are given, the current parameters are displayed (the password
will be shown as a line of asterisks).  If a @var{host} is given, and either the
@var{user} or @var{password} is not, they will be prompted for; also, any
parameter given as @code{?} will be prompted for, and if the @code{?} is
followed by a string, that will be used as the prompt.  As @code{zfopen} calls
@code{zfparams} to store the parameters, this usually need not be called
directly.

A single argument @code{-} will delete the stored parameters.  This will
also cause the memory of the last directory (and so on) on the other host
to be deleted.
@end quotation

@geindex zfopen; Function

@code{zfopen} [ @code{-1} ] [ @var{host} [ @var{user} [ @var{password} [ @var{account} ] ] ] ]

@quotation

If @var{host} is present, open a connection to that host under username
@var{user} with password @var{password} (and, on the rare occasions when it
is necessary, account @var{account}).  If a necessary parameter is missing or
given as @code{?} it will be prompted for.  If @var{host} is not present, use
a previously stored set of parameters.

If the command was successful, and the terminal is compatible with
@code{xterm} or is @code{sun-cmd}, a summary will appear in the title bar,
giving the local @code{host:directory} and the remote @code{host:directory};
this is handled by the function @code{zftp_chpwd}, described below.

Normally, the @var{host}, @var{user} and @var{password} are internally
recorded for later re-opening, either by a @code{zfopen} with no arguments, or
automatically (see below).  With the option @code{-1}, no information is
stored.  Also, if an open command with arguments failed, the parameters
will not be retained (and any previous parameters will also be deleted).
A @code{zfopen} on its own, or a @code{zfopen -1}, never alters the stored
parameters.

Both @code{zfopen} and @code{zfanon} (but not @code{zfparams}) understand URLs of
the form @code{ftp://}@var{host}/@var{path…} as meaning to connect to the
@var{host}, then change directory to @var{path} (which must be a directory,
not a file).  The @code{ftp://} can be omitted; the trailing @code{/} is enough
to trigger recognition of the @var{path}.  Note prefixes other than
@code{ftp:} are not recognized, and that all characters after the first
slash beyond @var{host} are significant in @var{path}.
@end quotation

@geindex zfanon; Function

@code{zfanon} [ @code{-1} ] @var{host}

@quotation

Open a connection @var{host} for anonymous FTP.  The username used is
@code{anonymous}.  The password (which will be reported the first time) is
generated as @var{user}@code{@@}@var{host}; this is then stored in the shell
parameter @code{$EMAIL_ADDR} which can alternatively be set manually to a
suitable string.
@end quotation

@node Directory Management,Status Commands,Opening a Connection,Functions<4>
@anchor{Zsh/zftpsys directory-management}@anchor{18d}
@subsection Directory Management


@geindex zfcd; Function

@code{zfcd} [ @var{dir} ]

@code{zfcd -}

@code{zfcd} @var{old} @var{new}

@quotation

Change the current directory on the remote server:  this is implemented to
have many of the features of the shell builtin @code{cd}.

In the first form with @var{dir} present, change to the directory @var{dir}.
The command @code{zfcd ..} is treated specially, so is guaranteed to work on
non-UNIX servers (note this is handled internally by @code{zftp}).  If @var{dir}
is omitted, has the effect of @code{zfcd ~}.

The second form changes to the directory previously current.

The third form attempts to change the current directory by replacing the
first occurrence of the string @var{old} with the string @var{new} in the
current directory.

Note that in this command, and indeed anywhere a remote filename is
expected, the string which on the local host corresponds to @code{~} is
converted back to a @code{~} before being passed to the remote machine.
This is convenient because of the way expansion is performed on the command
line before @code{zfcd} receives a string.  For example, suppose the command
is @code{zfcd ~/foo}.  The shell will expand this to a full path such as
@code{zfcd /home/user2/pws/foo}.  At this stage, @code{zfcd} recognises the
initial path as corresponding to @code{~} and will send the directory to
the remote host as @code{~/foo}, so that the @code{~} will be expanded by the
server to the correct remote host directory.  Other named directories of
the form @code{~name} are not treated in this fashion.
@end quotation

@geindex zfhere; Function

@code{zfhere}

@quotation

Change directory on the remote server to the one corresponding to the
current local directory, with special handling of @code{~} as in @code{zfcd}.
For example, if the current local directory is @code{~/foo/bar}, then
@code{zfhere} performs the effect of @code{zfcd ~/foo/bar}.
@end quotation

@geindex zfdir; Function

@code{zfdir} [ @code{-rfd} ] [ @code{-} ] [ @var{dir-options} ] [ @var{dir} ]

@quotation

Produce a long directory listing.  The arguments @var{dir-options} and
@var{dir} are passed directly to the server and their effect is
implementation dependent, but specifying a particular remote directory
@var{dir} is usually possible.  The output is passed through a pager
given by the environment variable @code{$PAGER}, or @code{more} if that is not
set.

The directory is usually cached for re-use.  In fact, two caches are
maintained.  One is for use when there is no @var{dir-options} or @var{dir},
i.e. a full listing of the current remote directory; it is flushed
when the current remote directory changes.  The other is
kept for repeated use of @code{zfdir} with the same arguments; for example,
repeated use of @code{zfdir /pub/gnu} will only require the directory to be
retrieved on the first call.  Alternatively, this cache can be re-viewed with
the @code{-r} option.  As relative directories will confuse
@code{zfdir}, the @code{-f} option can be used to force the cache to be flushed
before the directory is listed.  The option @code{-d} will delete both
caches without showing a directory listing; it will also delete the cache
of file names in the current remote directory, if any.
@end quotation

@geindex zfls; Function

@code{zfls} [ @var{ls-options} ] [ @var{dir} ]

@quotation

List files on the remote server.  With no arguments, this will produce a
simple list of file names for the current remote directory.  Any arguments
are passed directly to the server.  No pager and no caching is used.
@end quotation

@node Status Commands,Retrieving Files,Directory Management,Functions<4>
@anchor{Zsh/zftpsys status-commands}@anchor{18e}
@subsection Status Commands


@geindex zftype; Function

@code{zftype} [ @var{type} ]

@quotation

With no arguments, show the type of data to be transferred, usually ASCII
or binary.  With an argument, change the type: the types @code{A} or
@code{ASCII} for ASCII data and @code{B} or @code{BINARY}, @code{I} or
@code{IMAGE} for binary data are understood case-insensitively.
@end quotation

@geindex zfstat; Function

@code{zfstat} [ @code{-v} ]

@quotation

Show the status of the current or last connection, as well as the status of
some of @code{zftp}’s status variables.  With the @code{-v} option, a more
verbose listing is produced by querying the server for its version of
events, too.
@end quotation

@node Retrieving Files,Sending Files,Status Commands,Functions<4>
@anchor{Zsh/zftpsys retrieving-files}@anchor{18f}
@subsection Retrieving Files


The commands for retrieving files all take at least two options. @code{-G}
suppresses remote filename expansion which would otherwise be performed
(see below for a more detailed description of that).  @code{-t} attempts
to set the modification time of the local file to that of the remote file:
see the description of the function @code{zfrtime} below for more information.

@geindex zfget; Function

@code{zfget} [ @code{-Gtc} ] @var{file1} …

@quotation

Retrieve all the listed files @var{file1} … one at a time from the remote
server.  If a file contains a @code{/}, the full name is passed to the
remote server, but the file is stored locally under the name given by the
part after the final @code{/}.  The option @code{-c} (cat) forces all files to
be sent as a single stream to standard output; in this case the @code{-t}
option has no effect.
@end quotation

@geindex zfuget; Function

@code{zfuget} [ @code{-Gvst} ] @var{file1} …

@quotation

As @code{zfget}, but only retrieve files where the version on the remote
server is newer (has a later modification time), or where the local file
does not exist.  If the remote file is older but the files have different
sizes, or if the sizes are the same but the remote file is newer, the user
will usually be queried.  With the option @code{-s}, the command runs silently
and will always retrieve the file in either of those two cases.  With the
option @code{-v}, the command prints more information about the files while it
is working out whether or not to transfer them.
@end quotation

@geindex zfcget; Function

@code{zfcget} [ @code{-Gt} ] @var{file1} …

@quotation

As @code{zfget}, but if any of the local files exists, and is shorter than
the corresponding remote file, the command assumes that it is the result of
a partially completed transfer and attempts to transfer the rest of the
file.  This is useful on a poor connection which keeps failing.

Note that this requires a commonly implemented, but non-standard, version
of the FTP protocol, so is not guaranteed to work on all servers.
@end quotation

@geindex zfgcp; Function

@code{zfgcp} [ @code{-Gt} ] @var{remote-file} @var{local-file}

@code{zfgcp} [ @code{-Gt} ] @var{rfile1} … @var{ldir}

@quotation

This retrieves files from the remote server with arguments behaving
similarly to the @code{cp} command.

In the first form, copy @var{remote-file} from the server to the local file
@var{local-file}.

In the second form, copy all the remote files @var{rfile1} … into the
local directory @var{ldir} retaining the same basenames.  This assumes UNIX
directory semantics.
@end quotation

@node Sending Files,Closing the Connection,Retrieving Files,Functions<4>
@anchor{Zsh/zftpsys sending-files}@anchor{190}
@subsection Sending Files


@geindex zfput; Function

@code{zfput} [ @code{-r} ] @var{file1} …

@quotation

Send all the @var{file1} … given separately to the remote server.  If a
filename contains a @code{/}, the full filename is used locally to find the
file, but only the basename is used for the remote file name.

With the option @code{-r}, if any of the @var{files} are directories they are
sent recursively with all their subdirectories, including files beginning
with @code{.}.  This requires that the remote machine understand UNIX file
semantics, since @code{/} is used as a directory separator.
@end quotation

@geindex zfuput; Function

@code{zfuput} [ @code{-vs} ] @var{file1} …

@quotation

As @code{zfput}, but only send files which are newer than their remote
equivalents, or if the remote file does not exist.  The logic is the same
as for @code{zfuget}, but reversed between local and remote files.
@end quotation

@geindex zfcput; Function

@code{zfcput} @var{file1} …

@quotation

As @code{zfput}, but if any remote file already exists and is shorter than the
local equivalent, assume it is the result of an incomplete transfer and
send the rest of the file to append to the existing part.  As the FTP
append command is part of the standard set, this is in principle more
likely to work than @code{zfcget}.
@end quotation

@geindex zfpcp; Function

@code{zfpcp} @var{local-file} @var{remote-file}

@code{zfpcp} @var{lfile1} … @var{rdir}

@quotation

This sends files to the remote server with arguments behaving similarly to
the @code{cp} command.

With two arguments, copy @var{local-file} to the server as
@var{remote-file}.

With more than two arguments, copy all the local files @var{lfile1} … into
the existing remote directory @var{rdir} retaining the same basenames.  This
assumes UNIX directory semantics.

A problem arises if you attempt to use @code{zfpcp} @var{lfile1} @var{rdir},
i.e. the second form of copying but with two arguments, as the command has
no simple way of knowing if @var{rdir} corresponds to a directory or a
filename.  It attempts to resolve this in various ways.  First, if the
@var{rdir} argument is @code{.} or @code{..} or ends in a slash, it is assumed
to be a directory.  Secondly, if the operation of copying to a remote file
in the first form failed, and the remote server sends back the expected
failure code 553 and a reply including the string @code{Is a directory},
then @code{zfpcp} will retry using the second form.
@end quotation

@node Closing the Connection,Session Management<2>,Sending Files,Functions<4>
@anchor{Zsh/zftpsys closing-the-connection}@anchor{191}
@subsection Closing the Connection


@geindex zfclose; Function

@code{zfclose}

@quotation

Close the connection.
@end quotation

@node Session Management<2>,Bookmarks,Closing the Connection,Functions<4>
@anchor{Zsh/zftpsys session-management}@anchor{192}
@subsection Session Management


@geindex zfsession; Function

@code{zfsession} [ @code{-lvod} ] [ @var{sessname} ]

@quotation

Allows you to manage multiple FTP sessions at once.  By default,
connections take place in a session called @code{default}; by giving the
command @code{zfsession} @var{sessname} you can change to a new or existing
session with a name of your choice.  The new session remembers its own
connection, as well as associated shell parameters, and also the host/user
parameters set by @code{zfparams}.  Hence you can have different sessions set
up to connect to different hosts, each remembering the appropriate host,
user and password.

With no arguments, @code{zfsession} prints the name of the current session;
with the option @code{-l} it lists all sessions which currently exist, and
with the option @code{-v} it gives a verbose list showing the host and
directory for each session, where the current session is marked with an
asterisk.  With @code{-o}, it will switch to the most recent previous session.

With @code{-d}, the given session (or else the current one) is removed;
everything to do with it is completely forgotten.  If it was the only
session, a new session called @code{default} is created and made current.
It is safest not to delete sessions while background commands using
@code{zftp} are active.
@end quotation

@geindex zftransfer; Function

@code{zftransfer} @var{sess1}@code{:}@var{file1} @var{sess2}@code{:}@var{file2}

@quotation

Transfer files between two sessions; no local copy is made.  The file
is read from the session @var{sess1} as @var{file1} and written to session
@var{sess2} as file @var{file2}; @var{file1} and @var{file2} may be relative to
the current directories of the session.  Either @var{sess1} or @var{sess2}
may be omitted (though the colon should be retained if there is a
possibility of a colon appearing in the file name) and defaults to the
current session; @var{file2} may be omitted or may end with a slash, in
which case the basename of @var{file1} will be added.  The sessions
@var{sess1} and @var{sess2} must be distinct.

The operation is performed using pipes, so it is required that the
connections still be valid in a subshell, which is not the case under
versions of some operating systems, presumably due to a system bug.
@end quotation

@node Bookmarks,Other Functions,Session Management<2>,Functions<4>
@anchor{Zsh/zftpsys bookmarks}@anchor{193}
@subsection Bookmarks


The two functions @code{zfmark} and @code{zfgoto} allow you to `bookmark’ the
present location (host, user and directory) of the current FTP connection
for later use.  The file to be used for storing and retrieving bookmarks is
given by the parameter @code{$ZFTP_BMFILE}; if not set when one of the two
functions is called, it will be set to the file @code{.zfbkmarks} in the
directory where your zsh startup files live (usually @code{~}).

@geindex zfmark; Function

@code{zfmark} [ @var{bookmark} ]

@quotation

If given an argument, mark the current host, user and directory under the
name @var{bookmark} for later use by @code{zfgoto}.  If there is no connection
open, use the values for the last connection immediately before it was
closed; it is an error if there was none.  Any existing bookmark
under the same name will be silently replaced.

If not given an argument, list the existing bookmarks and the points to
which they refer in the form @var{user}@code{@@}@var{host}@code{:}@var{directory};
this is the format in which they are stored, and the file may be edited
directly.
@end quotation

@geindex zfgoto; Function

@code{zfgoto} [ @code{-n} ] @var{bookmark}

@quotation

Return to the location given by @var{bookmark}, as previously set by
@code{zfmark}.  If the location has user @code{ftp} or @code{anonymous}, open
the connection with @code{zfanon}, so that no password is required.  If the
user and host parameters match those stored for the current session, if
any, those will be used, and again no password is required.  Otherwise a
password will be prompted for.

With the option @code{-n}, the bookmark is taken to be a nickname stored by
the @code{ncftp} program in its bookmark file, which is assumed to be
@code{~/.ncftp/bookmarks}.  The function works identically in other ways.
Note that there is no mechanism for adding or modifying @code{ncftp} bookmarks
from the zftp functions.
@end quotation

@node Other Functions,,Bookmarks,Functions<4>
@anchor{Zsh/zftpsys other-functions}@anchor{194}
@subsection Other Functions


Mostly, these functions will not be called directly (apart from
@code{zfinit}), but are described here for completeness.  You may wish to
alter @code{zftp_chpwd} and @code{zftp_progress}, in particular.

@geindex zfinit; Function

@code{zfinit} [ @code{-n} ]

@quotation

As described above, this is used to initialize the zftp function system.
The @code{-n} option should be used if the zftp command is already built into
the shell.
@end quotation

@geindex zfautocheck; Function

@code{zfautocheck} [ @code{-dn} ]

@quotation

This function is called to implement automatic reopening behaviour, as
described in more detail below.  The options must appear in the first
argument; @code{-n} prevents the command from changing to the old directory,
while @code{-d} prevents it from setting the variable @code{do_close}, which it
otherwise does as a flag for automatically closing the connection after a
transfer.  The host and directory for the last session are stored in the
variable @code{$zflastsession}, but the internal host/user/password parameters
must also be correctly set.
@end quotation

@geindex zfcd_match; Function

@code{zfcd_match :var:`prefix` :var:`suffix}`

@quotation

This performs matching for completion of remote directory names.  If the
remote server is UNIX, it will attempt to persuade the server to list the
remote directory with subdirectories marked, which usually works but is not
guaranteed.  On other hosts it simply calls @code{zfget_match} and hence
completes all files, not just directories.  On some systems, directories
may not even look like filenames.
@end quotation

@geindex zfget_match; Function

@code{zfget_match :var:`prefix` :var:`suffix}`

@quotation

This performs matching for completion of remote filenames.  It caches files
for the current directory (only) in the shell parameter @code{$zftp_fcache}.
It is in the form to be called by the @code{-K} option of @code{compctl}, but
also works when called from a widget-style completion function with
@var{prefix} and @var{suffix} set appropriately.
@end quotation

@geindex zfrglob; Function

@code{zfrglob :var:`varname}`

@quotation

Perform remote globbing, as describes in more detail below.  @var{varname}
is the name of a variable containing the pattern to be expanded; if there
were any matches, the same variable will be set to the expanded set of
filenames on return.
@end quotation

@geindex zfrtime; Function

@code{zfrtime} @var{lfile} @var{rfile} [ @var{time} ]

@quotation

Set the local file @var{lfile} to have the same modification time as the
remote file @var{rfile}, or the explicit time @var{time} in FTP format
@code{CCYYMMDDhhmmSS} for the GMT timezone.  This uses the shell’s
@code{zsh/datetime} module to perform the conversion from
GMT to local time.
@end quotation

@geindex zftp_chpwd@comma{} supplied version; Function

@code{zftp_chpwd}

@quotation

This function is called every time a connection is opened, or closed, or
the remote directory changes.  This version alters the title bar of an
@code{xterm}-compatible or @code{sun-cmd} terminal emulator to reflect the
local and remote hostnames and current directories.  It works best when
combined with the function @code{chpwd}.  In particular, a function of
the form

@example
 chpwd() @{
   if [[ -n $ZFTP_USER ]]; then
     zftp_chpwd
   else
     # usual chpwd e.g put host:directory in title bar
   fi
 @}
@end example

fits in well.
@end quotation

@geindex zftp_progress@comma{} supplied version; Function

@code{zftp_progress}

@quotation

This function shows the status of the transfer.  It will not write anything
unless the output is going to a terminal; however, if you transfer files in
the background, you should turn off progress reports by hand using
@code{zstyle :zftp:*' progress none}’.  Note also that if you alter it, any
output `must' be to standard error, as standard output may be a file
being received.  The form of the progress meter, or whether it is used at
all, can be configured without altering the function, as described in the
next section.
@end quotation

@geindex zffcache; Function

@code{zffcache}

@quotation

This is used to implement caching of files in the current directory for
each session separately.  It is used by @code{zfget_match} and @code{zfrglob}.
@end quotation

@c historic nodename: Miscellaneous Features

@node Miscellaneous Features,,Functions<4>,Zftp Function System
@anchor{Zsh/zftpsys miscellaneous-features}@anchor{195}
@section Miscellaneous Features


@menu
* Configuration:: 
* Remote Globbing:: 
* Automatic and Temporary Reopening:: 
* Completion: Completion<4>. 

@end menu

@node Configuration,Remote Globbing,,Miscellaneous Features
@anchor{Zsh/zftpsys configuration}@anchor{196}
@subsection Configuration


@geindex zftp function system@comma{} configuration; Command

@geindex zftp function system@comma{} styles; Command

@geindex styles in zftp functions; Command

Various styles are available using the standard shell style mechanism,
described in @ref{ca,,The zsh/zutil Module}. Briefly, the
command @code{zstyle :zftp:*'} @var{style} @var{value} …’.
defines the @var{style} to have value @var{value}; more than one value may be
given, although that is not useful in the cases described here.  These
values will then be used throughout the zftp function system.  For more
precise control, the first argument, which gives a pattern that matches `contexts' in which the
style applies, can be modified to include a particular function, as for
example @code{:zftp:zfget}: the style will then have the given value only
in the @code{zfget} function, and will override styles set under @code{:zftp:*}.
Note that only the top level function name, as called by
the user, is used; calling of lower level functions is transparent to the
user.  Hence modifications to the title bar in @code{zftp_chpwd} use the
contexts @code{:zftp:zfopen}, @code{:zftp:zfcd}, etc., depending where it was
called from.  The following styles are understood:

@geindex progress@comma{} zftp style; Keystroke

@code{progress}

@quotation

Controls the way that @code{zftp_progress} reports on the progress of a
transfer.  If empty, unset, or @code{none}, no progress report is made; if
@code{bar} a growing bar of inverse video is shown; if @code{percent} (or any
other string, though this may change in future), the percentage of the file
transferred is shown.  The bar meter requires that the width of the
terminal be available via the @code{$COLUMNS} parameter (normally this is set
automatically).  If the size of the file being transferred is not
available, @code{bar} and @code{percent} meters will simply show the number of
bytes transferred so far.

When @code{zfinit} is run, if this style is not defined for the context
@code{:zftp:*}, it will be set to `bar’.
@end quotation

@geindex update@comma{} zftp style; Keystroke

@code{update}

@quotation

Specifies the minimum time interval between updates of the progress meter
in seconds.  No update is made unless new data has been received, so the
actual time interval is limited only by @code{$ZFTP_TIMEOUT}.

As described for @code{progress}, @code{zfinit} will force this to default to 1.
@end quotation

@geindex remote-glob@comma{} zftp style; Keystroke

@code{remote-glob}

@quotation

If set to @code{1}, @code{yes} or @code{true}, filename generation (globbing) is
performed on the remote machine instead of by zsh itself; see below.
@end quotation

@geindex titlebar@comma{} zftp style; Keystroke

@code{titlebar}

@quotation

If set to @code{1}, @code{yes} or @code{true}, @code{zftp_chpwd} will put the remote host and
remote directory into the titlebar of terminal emulators such as xterm or
sun-cmd that allow this.

As described for @code{progress}, @code{zfinit} will force this to default to 1.
@end quotation

@geindex chpwd@comma{} zftp style; Keystroke

@code{chpwd}

@quotation

If set to @code{1} @code{yes} or @code{true}, @code{zftp_chpwd} will call the function
@code{chpwd} when a connection is closed.  This is useful if the remote host
details were put into the terminal title bar by @code{zftp_chpwd} and your
usual @code{chpwd} also modifies the title bar.

When @code{zfinit} is run, it will determine whether @code{chpwd} exists and if
so it will set the default value for the style to 1 if none exists
already.
@end quotation

Note that there is also an associative array @code{zfconfig} which contains
values used by the function system.  This should not be modified or
overwritten.

@node Remote Globbing,Automatic and Temporary Reopening,Configuration,Miscellaneous Features
@anchor{Zsh/zftpsys remote-globbing}@anchor{197}
@subsection Remote Globbing


@geindex zftp function system@comma{} remote globbing; Command

The commands for retrieving files usually perform filename generation
(globbing) on their arguments; this can be turned off by passing the option
@code{-G} to each of the commands.  Normally this operates by retrieving a
complete list of files for the directory in question, then matching these
locally against the pattern supplied.  This has the advantage that the full
range of zsh patterns (respecting the setting of the option
@code{EXTENDED_GLOB}) can be used.  However, it means that the directory part
of a filename will not be expanded and must be given exactly.  If the
remote server does not support the UNIX directory semantics, directory
handling is problematic and it is recommended that globbing only be used
within the current directory.  The list of files in the current directory,
if retrieved, will be cached, so that subsequent globs in the same
directory without an intervening @code{zfcd} are much faster.

If the @code{remote-glob} style (see above) is set, globbing is instead
performed on the remote host: the server is asked for a list of matching
files.  This is highly dependent on how the server is implemented, though
typically UNIX servers will provide support for basic glob patterns.  This
may in some cases be faster, as it avoids retrieving the entire list of
directory contents.

@node Automatic and Temporary Reopening,Completion<4>,Remote Globbing,Miscellaneous Features
@anchor{Zsh/zftpsys automatic-and-temporary-reopening}@anchor{198}
@subsection Automatic and Temporary Reopening


@geindex zftp function system@comma{} automatic reopening; Command

As described for the @code{zfopen} command, a subsequent @code{zfopen} with no
parameters will reopen the connection to the last host (this includes
connections made with the @code{zfanon} command).  Opened in this fashion, the
connection starts in the default remote directory and will remain open
until explicitly closed.

Automatic re-opening is also available.  If a connection is not currently
open and a command requiring a connection is given, the last connection is
implicitly reopened.  In this case the directory which was current when the
connection was closed again becomes the current directory (unless, of
course, the command given changes it).  Automatic reopening will also take
place if the connection was close by the remote server for whatever reason
(e.g. a timeout).  It is not available if the @code{-1} option to @code{zfopen}
or @code{zfanon} was used.

Furthermore, if the command issued is a file transfer, the connection will
be closed after the transfer is finished, hence providing a one-shot mode
for transfers.  This does not apply to directory changing or listing
commands; for example a @code{zfdir} may reopen a connection but will leave it
open.  Also, automatic closure will only ever happen in the same command as
automatic opening, i.e a @code{zfdir} directly followed by a @code{zfget} will
never close the connection automatically.

Information about the previous connection is given by the @code{zfstat}
function.  So, for example, if that reports:

@example
 Session:        default
 Not connected.
 Last session:   ftp.bar.com:/pub/textfiles
@end example

then the command @code{zfget file.txt} will attempt to reopen a connection to
@code{ftp.bar.com}, retrieve the file @code{/pub/textfiles/file.txt}, and
immediately close the connection again.  On the other hand, @code{zfcd ..}
will open the connection in the directory @code{/pub} and leave it open.

Note that all the above is local to each session; if you return to a
previous session, the connection for that session is the one which will be
reopened.

@node Completion<4>,,Automatic and Temporary Reopening,Miscellaneous Features
@anchor{Zsh/zftpsys completion}@anchor{199}
@subsection Completion


Completion of local and remote files, directories, sessions and bookmarks
is supported.  The older, @code{compctl}-style completion is defined when
@code{zfinit} is called; support for the new widget-based completion system is
provided in the function @code{Completion/Zsh/Command/_zftp}, which should be
installed with the other functions of the completion system and hence
should automatically be available.

@c historic nodename: User Contributions

@node User Contributions,Index,Zftp Function System,Top
@anchor{Zsh/contrib doc}@anchor{19a}@anchor{Zsh/contrib user-contributions}@anchor{19b}
@chapter User Contributions


@geindex user contributions; Command

@menu
* Description: Description<10>. 
* Utilities:: 
* Remembering Recent Directories:: 
* Abbreviated dynamic references to directories:: 
* Gathering information from version control systems:: 
* Prompt Themes:: 
* ZLE Functions:: 
* Exception Handling:: 
* MIME Functions:: 
* Mathematical Functions:: 
* User Configuration Functions:: 
* Other Functions: Other Functions<2>. 

@end menu

@node Description<10>,Utilities,,User Contributions
@anchor{Zsh/contrib description}@anchor{19c}
@section Description


The Zsh source distribution includes a number of items contributed by the
user community.  These are not inherently a part of the shell, and some
may not be available in every zsh installation.  The most significant of
these are documented here.  For documentation on other contributed items
such as shell functions, look for comments in the function source files.

@c historic nodename: Utilities

@node Utilities,Remembering Recent Directories,Description<10>,User Contributions
@anchor{Zsh/contrib utilities}@anchor{19d}
@section Utilities


@menu
* Accessing On-Line Help:: 
* Recompiling Functions:: 
* Keyboard Definition:: 
* Dumping Shell State:: 
* Manipulating Hook Functions:: 

@end menu

@node Accessing On-Line Help,Recompiling Functions,,Utilities
@anchor{Zsh/contrib accessing-on-line-help}@anchor{19e}@anchor{Zsh/contrib id1}@anchor{19f}
@subsection Accessing On-Line Help


@geindex helpfiles utility; Command

The key sequence @code{ESC h} is normally bound by ZLE to execute the
@code{run-help} widget (see @code{zshzle}).
This invokes the @code{run-help} command with the command word from the
current input line as its argument.  By default, @code{run-help} is an alias
for the @code{man} command, so this often fails when the command word is a
shell builtin or a user-defined function.  By redefining the @code{run-help}
alias, one can improve the on-line help provided by the shell.

The @code{helpfiles} utility, found in the @code{Util} directory of the
distribution, is a Perl program that can be used to process the zsh manual
to produce a separate help file for each shell builtin and for many other
shell features as well.  The autoloadable @code{run-help} function, found in
@code{Functions/Misc}, searches for these helpfiles and performs several
other tests to produce the most complete help possible for the command.

Help files are installed by default to a subdirectory of @code{/usr/share/zsh}
or @code{/usr/local/share/zsh}.

To create your own help files with @code{helpfiles}, choose or create a
directory where the individual command help files will reside.  For
example, you might choose @code{~/zsh_help}.  If you unpacked the zsh
distribution in your home directory, you would use the commands:

@example
 mkdir ~/zsh_help
 perl ~/zsh- |release| /Util/helpfiles ~/zsh_help
@end example

@geindex HELPDIR; Variable

The @code{HELPDIR} parameter tells @code{run-help} where to look for the help
files. When unset, it uses the default installation path.
To use your own set of help files, set this to the appropriate path
in one of your startup files:

@example
 HELPDIR=~/zsh_help
@end example

@geindex run-help@comma{} use of; Function

To use the @code{run-help} function, you need to add lines something
like the following to your @code{.zshrc} or equivalent startup file:

@example
 unalias run-help
 autoload run-help
@end example

Note that in order for @code{autoload run-help} to work, the @code{run-help}
file must be in one of the directories named in your @code{fpath} array (see
@ref{11,,Parameters Used by the Shell}).
This should already be the case if you have a standard zsh
installation; if it is not, copy @code{Functions/Misc/run-help} to an
appropriate directory.

@node Recompiling Functions,Keyboard Definition,Accessing On-Line Help,Utilities
@anchor{Zsh/contrib id2}@anchor{1a0}@anchor{Zsh/contrib recompiling-functions}@anchor{1a1}
@subsection Recompiling Functions


@geindex functions@comma{} recompiling; Command

@geindex zrecompile utility; Command

If you frequently edit your zsh functions, or periodically update your zsh
installation to track the latest developments, you may find that function
digests compiled with the @code{zcompile} builtin are frequently out of date
with respect to the function source files.  This is not usually a problem,
because zsh always looks for the newest file when loading a function, but
it may cause slower shell startup and function loading.  Also, if a digest
file is explicitly used as an element of @code{fpath}, zsh won’t check whether
any of its source files has changed.

The @code{zrecompile} autoloadable function, found in @code{Functions/Misc}, can
be used to keep function digests up to date.

@geindex zrecompile; Function

@code{zrecompile} [ @code{-qt} ] [ @var{name} … ]

@code{zrecompile} [ @code{-qt} ] @code{-p} @var{arg} … [ @code{--} @var{arg} … ]

@quotation

This tries to find @code{*.zwc} files and automatically re-compile them if at
least one of the original files is newer than the compiled file.  This
works only if the names stored in the compiled files are full paths or are
relative to the directory that contains the @code{.zwc} file.

In the first form, each @var{name} is the name of a compiled file or a
directory containing @code{*.zwc} files that should be checked.  If no
arguments are given, the directories and @code{*.zwc} files in @code{fpath} are
used.

When @code{-t} is given, no compilation is performed, but a return status of
zero (true) is set if there are files that need to be re-compiled and
non-zero (false) otherwise.  The @code{-q} option quiets the chatty output
that describes what @code{zrecompile} is doing.

Without the @code{-t} option, the return status is zero if all files that
needed re-compilation could be compiled and non-zero if compilation for at
least one of the files failed.

If the @code{-p} option is given, the @var{arg}s are interpreted as one
or more sets of arguments for @code{zcompile}, separated by @code{--}.
For example:

@example
 zrecompile -p \
            -R ~/.zshrc -- \
            -M ~/.zcompdump -- \
            ~/zsh/comp.zwc ~/zsh/Completion/*/_*
@end example

This compiles @code{~/.zshrc} into @code{~/.zshrc.zwc} if that doesn’t exist or
if it is older than @code{~/.zshrc}. The compiled file will be marked for
reading instead of mapping. The same is done for @code{~/.zcompdump} and
@code{~/.zcompdump.zwc}, but this compiled file is marked for mapping. The
last line re-creates the file @code{~/zsh/comp.zwc} if any of the files
matching the given pattern is newer than it.

Without the @code{-p} option, @code{zrecompile} does not create function digests
that do not already exist, nor does it add new functions to the digest.
@end quotation

The following shell loop is an example of a method for creating function
digests for all functions in your @code{fpath}, assuming that you have write
permission to the directories:

@example
 for ((i=1; i <= $#fpath; ++i)); do
   dir=$fpath[i]
   zwc=$@{dir:t@}.zwc
   if [[ $dir == (.|..) || $dir == (.|..)/* ]]; then
     continue
   fi
   files=($dir/*(N-.))
   if [[ -w $dir:h && -n $files ]]; then
     files=($@{$@{(M)files%/*/*@}#/@})
     if ( cd $dir:h &&
          zrecompile -p -U -z $zwc $files ); then
       fpath[i]=$fpath[i].zwc
     fi
   fi
 done
@end example

The @code{-U} and @code{-z} options are appropriate for functions in the default
zsh installation @code{fpath}; you may need to use different options for your
personal function directories.

Once the digests have been created and your @code{fpath} modified to refer to
them, you can keep them up to date by running @code{zrecompile} with no
arguments.

@node Keyboard Definition,Dumping Shell State,Recompiling Functions,Utilities
@anchor{Zsh/contrib id3}@anchor{1a2}@anchor{Zsh/contrib keyboard-definition}@anchor{1a3}
@subsection Keyboard Definition


@geindex keyboard definition; Command

@geindex zkbd; Function

The large number of possible combinations of keyboards, workstations,
terminals, emulators, and window systems makes it impossible for zsh to
have built-in key bindings for every situation.  The @code{zkbd} utility,
found in @code{Functions/Misc}, can help you quickly create key bindings for your
configuration.

Run @code{zkbd} either as an autoloaded function, or as a shell script:

@example
 zsh -f ~/zsh- |release| /Functions/Misc/zkbd
@end example

When you run @code{zkbd}, it first asks you to enter your terminal type; if
the default it offers is correct, just press return.  It then asks you to
press a number of different keys to determine characteristics of your
keyboard and terminal; @code{zkbd} warns you if it finds anything out of the
ordinary, such as a Delete key that sends neither @code{^H} nor @code{^?}.

The keystrokes read by @code{zkbd} are recorded as a definition for an
associative array named @code{key}, written to a file in the subdirectory
@code{.zkbd} within either your @code{HOME} or, if specified, @code{ZDOTDIR} directory.
Alternatively, you can tell @code{zkbd} the directory to write new files into
with the @code{-d} option, e.g. @code{zkbd -d $ZCACHEDIR/zkbd}. In either case, the
directory is created if it did not exist. The name of the file is composed from
the @code{TERM}, @code{VENDOR} and @code{OSTYPE} parameters, joined by hyphens.

You may read this file into your @code{.zshrc} or another startup file with
the @code{source} or @code{.} commands, then reference the @code{key} parameter
in bindkey commands, like this:

@example
 source $@{ZDOTDIR:-$HOME@}/.zkbd/$TERM-$VENDOR-$OSTYPE
 [[ -n $@{key[Left]@} ]] && bindkey "$@{key[Left]@}" backward-char
 [[ -n $@{key[Right]@} ]] && bindkey "$@{key[Right]@}" forward-char
 # etc.
@end example

Note that in order for @code{autoload zkbd} to work, the @code{zkdb} file must
be in one of the directories named in your @code{fpath} array (see
@ref{11,,Parameters Used by the Shell}).
This should already be the case if you have a standard zsh
installation; if it is not, copy @code{Functions/Misc/zkbd} to an
appropriate directory.

@node Dumping Shell State,Manipulating Hook Functions,Keyboard Definition,Utilities
@anchor{Zsh/contrib dumping-shell-state}@anchor{1a4}
@subsection Dumping Shell State


@geindex reporter utility; Command

Occasionally you may encounter what appears to be a bug in the shell,
particularly if you are using a beta version of zsh or a development
release.  Usually it is sufficient to send a description of the
problem to one of the zsh mailing lists (see @ref{1a5,,Mailing Lists}),
but sometimes one of the zsh developers will need to recreate your
environment in order to track the problem down.

The script named @code{reporter}, found in the @code{Util} directory of the
distribution, is provided for this purpose.  (It is also possible to
@code{autoload reporter}, but @code{reporter} is not installed in @code{fpath}
by default.)  This script outputs a detailed dump of the shell state,
in the form of another script that can be read with @code{zsh -f} to
recreate that state.

To use @code{reporter}, read the script into your shell with the @code{.}
command and redirect the output into a file:

@example
 . ~/zsh- |release| /Util/reporter > zsh.report
@end example

You should check the @code{zsh.report} file for any sensitive information
such as passwords and delete them by hand before sending the script to the
developers.  Also, as the output can be voluminous, it’s best to wait for
the developers to ask for this information before sending it.

You can also use @code{reporter} to dump only a subset of the shell state.
This is sometimes useful for creating startup files for the first time.
Most of the output from reporter is far more detailed than usually is
necessary for a startup file, but the @code{aliases}, @code{options}, and
@code{zstyles} states may be useful because they include only changes from
the defaults.  The @code{bindings} state may be useful if you have created
any of your own keymaps, because @code{reporter} arranges to dump the keymap
creation commands as well as the bindings for every keymap.

As is usual with automated tools, if you create a startup file with
@code{reporter}, you should edit the results to remove unnecessary commands.
Note that if you’re using the new completion system, you should `not'
dump the @code{functions} state to your startup files with @code{reporter}; use
the @code{compdump} function instead (see
@code{zshcompsys}).

@code{reporter} [ @var{state} … ]

@quotation

@geindex reporter; Function

Print to standard output the indicated subset of the current shell state.
The @var{state} arguments may be one or more of:


@table @asis

@item @code{all}

Output everything listed below.

@item @code{aliases}

Output alias definitions.

@item @code{bindings}

Output ZLE key maps and bindings.

@item @code{completion}

Output old-style @code{compctl} commands.
New completion is covered by @code{functions} and @code{zstyles}.

@item @code{functions}

Output autoloads and function definitions.

@item @code{limits}

Output @code{limit} commands.

@item @code{options}

Output @code{setopt} commands.

@item @code{styles}

Same as @code{zstyles}.

@item @code{variables}

Output shell parameter assignments, plus @code{export}
commands for any environment variables.

@item @code{zstyles}

Output @code{zstyle} commands.
@end table

If the @var{state} is omitted, @code{all} is assumed.
@end quotation

With the exception of @code{all}, every @var{state} can be abbreviated by
any prefix, even a single letter; thus @code{a} is the same as @code{aliases},
@code{z} is the same as @code{zstyles}, etc.

@node Manipulating Hook Functions,,Dumping Shell State,Utilities
@anchor{Zsh/contrib id4}@anchor{1a6}@anchor{Zsh/contrib manipulating-hook-functions}@anchor{1a7}
@subsection Manipulating Hook Functions


@geindex hook function utility; Command

@geindex add-zsh-hook; Function

@code{add-zsh-hook} [ @code{-L} | @code{-dD} ] [ @code{-Uzk} ] @var{hook} @var{function}

@quotation

Several functions are special to the shell, as described in
@ref{1a8,,Special Functions},
in that they are automatically called at specific points during shell execution.
Each has an associated array consisting of names of functions to be
called at the same point; these are so-called `hook functions’.
The shell function @code{add-zsh-hook} provides a simple way of adding or
removing functions from the array.

@var{hook} is one of @code{chpwd}, @code{periodic}, @code{precmd}, @code{preexec},
@code{zshaddhistory}, @code{zshexit}, or @code{zsh_directory_name},
the special functions in question.  Note that @code{zsh_directory_name}
is called in a different way from the other functions, but may
still be manipulated as a hook.

@var{function} is name of an ordinary shell function.  If no options
are given this will be added to the array of functions to be executed
in the given context.
Functions are invoked in the order they were added.

If the option @code{-L} is given, the current values for the hook arrays
are listed with @code{typeset}.

If the option @code{-d} is given, the @var{function} is removed from
the array of functions to be executed.

If the option @code{-D} is given, the @var{function} is treated as a pattern
and any matching names of functions are removed from the array of
functions to be executed.

The options @code{-U}, @code{-z} and @code{-k} are passed as arguments to
@code{autoload} for @var{function}.  For functions contributed with zsh, the
options @code{-Uz} are appropriate.
@end quotation

@geindex add-zle-hook-widget; Function

@code{add-zle-hook-widget} [ @code{-L} | @code{-dD} ] [ @code{-Uzk} ] @var{hook} @var{widgetname}

@quotation

Several widget names are special to the line editor, as described in
@ref{dc,,Special Widgets},
in that they are automatically called at specific points during editing.
Unlike function hooks, these do not use a predefined array of other names
to call at the same point; the shell function @code{add-zle-hook-widget}
maintains a similar array and arranges for the special widget to invoke
those additional widgets.

@var{hook} is one of @code{isearch-exit}, @code{isearch-update},
@code{line-pre-redraw}, @code{line-init}, @code{line-finish}, @code{history-line-set},
or @code{keymap-select}, corresponding to each of the special widgets
@code{zle-isearch-exit}, etc.  The special widget names are also accepted
as the @var{hook} argument.

@var{widgetname} is the name of a ZLE widget.  If no options are given this
is added to the array of widgets to be invoked in the given hook context.
Widgets are invoked in the order they were added, with

@example
 @code{zle} @var{widgetname} @code{-Nw -f "nolast" -- "$@@"}
@end example

@geindex WIDGET@comma{} in hooks; Variable

Note that this means that the @code{WIDGET} special parameter tracks the
@var{widgetname} when the widget function is called, rather than tracking
the name of the corresponding special hook widget.

If the option @code{-d} is given, the @var{widgetname} is removed from
the array of widgets to be executed.

If the option @code{-D} is given, the @var{widgetname} is treated as a pattern
and any matching names of widgets are removed from the array.

If @var{widgetname} does not name an existing widget when added to the
array, it is assumed that a shell function also named @var{widgetname} is
meant to provide the implementation of the widget.  This name is therefore
marked for autoloading, and the options @code{-U}, @code{-z} and @code{-k} are
passed as arguments to @code{autoload} as with @code{add-zsh-hook}.  The
widget is also created with @code{zle -N} @var{widgetname} to cause the
corresponding function to be loaded the first time the hook is called.

The arrays of @var{widgetname} are currently maintained in @code{zstyle}
contexts, one for each @var{hook} context, with a style of @code{widgets}.
If the @code{-L} option is given, this set of styles is listed with
@code{zstyle -L}.  This implementation may change, and the special widgets
that refer to the styles are created only if @code{add-zle-hook-widget} is
called to add at least one widget, so if this function is used for any
hooks, then all hooks should be managed only via this function.
@end quotation

@c historic nodename: Recent Directories

@geindex recent directories@comma{} maintaining list of; Command

@geindex directories@comma{} maintaining list of recent; Command

@geindex cdr; Function

@geindex _cdr; Function

@geindex chpwd_recent_add; Function

@geindex chpwd_recent_dirs; Function

@geindex chpwd_recent_filehandler; Function

@node Remembering Recent Directories,Abbreviated dynamic references to directories,Utilities,User Contributions
@anchor{Zsh/contrib remembering-recent-directories}@anchor{1a9}
@section Remembering Recent Directories


The function @code{cdr} allows you to change the working directory to a
previous working directory from a list maintained automatically.  It is
similar in concept to the directory stack controlled by the @code{pushd},
@code{popd} and @code{dirs} builtins, but is more configurable, and as it stores
all entries in files it is maintained across sessions and (by default)
between terminal emulators in the current session.  Duplicates are
automatically removed, so that the list reflects the single most recent
use of each directory.

Note that the @code{pushd} directory stack is not actually modified or used
by @code{cdr} unless you configure it to do so as described in the
configuration section below.

@menu
* Installation: Installation<2>. 
* Use:: 
* Options: Options<3>. 
* Configuration: Configuration<2>. 
* Use with Dynamic Directory Naming:: 
* Details of Directory Handling:: 

@end menu

@node Installation<2>,Use,,Remembering Recent Directories
@anchor{Zsh/contrib installation}@anchor{1aa}
@subsection Installation


The system works by means of a hook function that is called every time the
directory changes.  To install the system, autoload the required functions
and use the @code{add-zsh-hook} function described above:

@example
 autoload -Uz chpwd_recent_dirs cdr add-zsh-hook
 add-zsh-hook chpwd chpwd_recent_dirs
@end example

Now every time you change directly interactively, no matter which
command you use, the directory to which you change will be remembered
in most-recent-first order.

@node Use,Options<3>,Installation<2>,Remembering Recent Directories
@anchor{Zsh/contrib use}@anchor{1ab}
@subsection Use


All direct user interaction is via the @code{cdr} function.

The argument to cdr is a number @var{N} corresponding to the @var{N}th most
recently changed-to directory.  1 is the immediately preceding directory;
the current directory is remembered but is not offered as a destination.
Note that if you have multiple windows open 1 may refer to a directory
changed to in another window; you can avoid this by having per-terminal
files for storing directory as described for the
@code{recent-dirs-file} style below.

If you set the @code{recent-dirs-default} style described below @code{cdr}
will behave the same as @code{cd} if given a non-numeric argument, or more
than one argument.  The recent directory list is updated just the same
however you change directory.

If the argument is omitted, 1 is assumed.  This is similar to @code{pushd}’s
behaviour of swapping the two most recent directories on the stack.

Completion for the argument to @code{cdr} is available if compinit has been
run; menu selection is recommended, using:

@example
 zstyle ':completion:*:*:cdr:*:*' menu selection
@end example

to allow you to cycle through recent directories; the order is preserved,
so the first choice is the most recent directory before the current one.
The verbose style is also recommended to ensure the directory is shown; this
style is on by default so no action is required unless you have changed it.

@node Options<3>,Configuration<2>,Use,Remembering Recent Directories
@anchor{Zsh/contrib options}@anchor{1ac}
@subsection Options


The behaviour of @code{cdr} may be modified by the following options.

@code{-l}

@quotation

lists the numbers and the corresponding directories in
abbreviated form (i.e. with @code{~} substitution reapplied), one per line.
The directories here are not quoted (this would only be an issue if a
directory name contained a newline).  This is used by the completion
system.
@end quotation

@code{-r}

@quotation

sets the variable @code{reply} to the current set of directories.  Nothing
is printed and the directory is not changed.
@end quotation

@code{-e}

@quotation

allows you to edit the list of directories, one per line.  The
list can be edited to any extent you like; no sanity checking is
performed.  Completion is available.  No quoting is necessary (except for
newlines, where I have in any case no sympathy); directories are in
unabbreviated form and contain an absolute path, i.e. they start with @code{/}.
Usually the first entry should be left as the current directory.
@end quotation

@code{-p '}@var{pattern}@code{'}

@quotation

Prunes any items in the directory list that match the given extended glob
pattern; the pattern needs to be quoted from immediate expansion on the
command line.  The pattern is matched against each completely expanded
file name in the list; the full string must match, so wildcards at the
end (e.g. @code{'*removeme*'}) are needed to remove entries with a given
substring.

If output is to a terminal, then the function will print the new list
after pruning and prompt for confirmation by the user.  This output and
confirmation step can be skipped by using @code{-P} instead of @code{-p}.
@end quotation

@node Configuration<2>,Use with Dynamic Directory Naming,Options<3>,Remembering Recent Directories
@anchor{Zsh/contrib configuration}@anchor{1ad}
@subsection Configuration


Configuration is by means of the styles mechanism that should be familiar
from completion; if not, see the description of the @code{zstyle} command in
@ref{ca,,The zsh/zutil Module}.  The context for setting styles
should be @code{':chpwd:*'} in case the meaning of the context is extended in
future, for example:

@example
 zstyle ':chpwd:*' recent-dirs-max 0
@end example

sets the value of the @code{recent-dirs-max} style to 0.  In practice the
style name is specific enough that a context of ‘*’ should be fine.

An exception is @code{recent-dirs-insert}, which is used exclusively by the
completion system and so has the usual completion system context
(@code{':completion:*'} if nothing more specific is needed), though again
@code{'*'} should be fine in practice.

@code{recent-dirs-default}

@quotation

If true, and the command is expecting a recent directory index, and
either there is more than one argument or the argument is not an
integer, then fall through to “cd”.  This allows the lazy to use only
one command for directory changing.  Completion recognises this, too;
see recent-dirs-insert for how to control completion when this option
is in use.
@end quotation

@code{recent-dirs-file}

@quotation

The file where the list of directories is saved.  The default
is @code{$@{ZDOTDIR:-$HOME@}/.chpwd-recent-dirs}, i.e. this is in your
home directory unless you have set the variable @code{ZDOTDIR} to point
somewhere else.  Directory names are saved in @code{$'}@var{…}@code{'} quoted
form, so each line in the file can be supplied directly to the shell as an
argument.

The value of this style may be an array.  In this case, the first
file in the list will always be used for saving directories while any
other files are left untouched.  When reading the recent directory
list, if there are fewer than the maximum number of entries in the
first file, the contents of later files in the array will be appended
with duplicates removed from the list shown.  The contents of the two
files are not sorted together, i.e. all the entries in the first file
are shown first.  The special value @code{+} can appear in the list to
indicate the default file should be read at that point.  This allows
effects like the following:

@example
 zstyle ':chpwd:*' recent-dirs-file \
 ~/.chpwd-recent-dirs-$@{TTY##*/@} +
@end example

Recent directories are read from a file numbered according to
the terminal.  If there are insufficient entries the list
is supplemented from the default file.

It is possible to use @code{zstyle -e} to make the directory configurable
at run time:

@example
 zstyle -e ':chpwd:*' recent-dirs-file pick-recent-dirs-file
 pick-recent-dirs-file() @{
   if [[ $PWD = ~/text/writing(|/*) ]]; then
     reply=(~/.chpwd-recent-dirs-writing)
   else
     reply=(+)
   fi
 @}
@end example

In this example, if the current directory is @code{~/text/writing} or a
directory under it, then use a special file for saving recent
directories, else use the default.
@end quotation

@code{recent-dirs-insert}

@quotation

Used by completion.  If @code{recent-dirs-default} is true, then setting
this to @code{true} causes the actual directory, rather than its index, to
be inserted on the command line; this has the same effect as using
the corresponding index, but makes the history clearer and the line
easier to edit.  With this setting, if part of an argument was
already typed, normal directory completion rather than recent
directory completion is done; this is because recent directory
completion is expected to be done by cycling through entries menu
fashion.

If the value of the style is @code{always}, then only recent directories will
be completed; in that case, use the @code{cd} command when you want to
complete other directories.

If the value is @code{fallback}, recent directories will be tried first, then
normal directory completion is performed if recent directory completion
failed to find a match.

Finally, if the value is @code{both} then both sets of completions are
presented; the usual tag mechanism can be used to distinguish results, with
recent directories tagged as @code{recent-dirs}.  Note that the recent
directories inserted are abbreviated with directory names where appropriate.
@end quotation

@code{recent-dirs-max}

@quotation

The maximum number of directories to save to the file.  If
this is zero or negative there is no maximum.  The default is 20.
Note this includes the current directory, which isn’t offered,
so the highest number of directories you will be offered
is one less than the maximum.
@end quotation

@code{recent-dirs-prune}

@quotation

This style is an array determining what directories should (or should
not) be added to the recent list.  Elements of the array can include:

@code{parent}

@quotation

Prune parents (more accurately, ancestors) from the recent list.
If present, changing directly down by any number of directories
causes the current directory to be overwritten.  For example,
changing from ~pws to ~pws/some/other/dir causes ~pws not to be
left on the recent directory stack.  This only applies to direct
changes to descendant directories; earlier directories on the
list are not pruned.  For example, changing from ~pws/yet/another
to ~pws/some/other/dir does not cause ~pws to be pruned.
@end quotation

@code{pattern:}@var{pattern}

@quotation

Gives a zsh pattern for directories that should not be
added to the recent list (if not already there).  This element
can be repeated to add different patterns.  For example,
@code{'pattern:/tmp(|/*)'} stops @code{/tmp} or its descendants
from being added.  The @code{EXTENDED_GLOB} option is always turned on
for these patterns.
@end quotation
@end quotation

@code{recent-dirs-pushd}

@quotation

If set to true, @code{cdr} will use @code{pushd} instead of @code{cd} to change the
directory, so the directory is saved on the directory stack.  As the
directory stack is completely separate from the list of files saved
by the mechanism used in this file there is no obvious reason to do
this.
@end quotation

@node Use with Dynamic Directory Naming,Details of Directory Handling,Configuration<2>,Remembering Recent Directories
@anchor{Zsh/contrib use-with-dynamic-directory-naming}@anchor{1ae}
@subsection Use with Dynamic Directory Naming


It is possible to refer to recent directories using the dynamic directory
name syntax by using the supplied function @code{zsh_directory_name_cdr}
a hook:

@example
 autoload -Uz add-zsh-hook
 add-zsh-hook -Uz zsh_directory_name zsh_directory_name_cdr
@end example

When this is done, @code{~[1]} will refer to the most recent
directory other than $PWD, and so on.  Completion after @code{~[}@var{…}
also works.

@node Details of Directory Handling,,Use with Dynamic Directory Naming,Remembering Recent Directories
@anchor{Zsh/contrib details-of-directory-handling}@anchor{1af}
@subsection Details of Directory Handling


This section is for the curious or confused; most users will not
need to know this information.

Recent directories are saved to a file immediately and hence are
preserved across sessions.  Note currently no file locking is applied:
the list is updated immediately on interactive commands and nowhere else
(unlike history), and it is assumed you are only going to change
directory in one window at once.  This is not safe on shared accounts,
but in any case the system has limited utility when someone else is
changing to a different set of directories behind your back.

To make this a little safer, only directory changes instituted from the
command line, either directly or indirectly through shell function calls
(but not through subshells, evals, traps, completion functions and the
like) are saved.  Shell functions should use @code{cd -q} or @code{pushd -q} to
avoid side effects if the change to the directory is to be invisible at the
command line.  See the contents of the function @code{chpwd_recent_dirs} for
more details.

@c historic nodename: Other Directory Functions

@geindex directories@comma{} named@comma{} dynamic@comma{} helper function; Command

@geindex dynamic directory naming@comma{} helper function; Command

@geindex named directories@comma{} dynamic@comma{} helper function; Command

@geindex zsh_directory_name_generic; Function

@node Abbreviated dynamic references to directories,Gathering information from version control systems,Remembering Recent Directories,User Contributions
@anchor{Zsh/contrib abbreviated-dynamic-references-to-directories}@anchor{1b0}
@section Abbreviated dynamic references to directories


The dynamic directory naming system is described in
@ref{78,,Dynamic Named Directories}.  In this, a reference to
@code{~[}@var{…}@code{]} is expanded by a function found by the hooks
mechanism.

The contributed function @code{zsh_directory_name_generic} provides a
system allowing the user to refer to directories with only a limited
amount of new code.  It supports all three of the standard interfaces
for directory naming: converting from a name to a directory, converting
in the reverse direction to find a short name, and completion of names.

The main feature of this function is a path-like syntax,
combining abbreviations at multiple levels separated by “:”.
As an example, ~[g:p:s] might specify:

@code{g}

@quotation

The top level directory for your git area.  This first component
has to match, or the function will return indicating another
directory name hook function should be tried.
@end quotation

@code{p}

@quotation

The name of a project within your git area.
@end quotation

@code{s}

@quotation

The source area within that project.
@end quotation

This allows you to collapse references to long hierarchies to a very
compact form, particularly if the hierarchies are similar across different
areas of the disk.

Name components may be completed: if a description is shown at the top
of the list of completions, it includes the path to which previous
components expand, while the description for an individual completion
shows the path segment it would add.  No additional configuration is
needed for this as the completion system is aware of the dynamic
directory name mechanism.

@menu
* Usage:: 
* Configuration: Configuration<3>. 
* Complete Example:: 

@end menu

@node Usage,Configuration<3>,,Abbreviated dynamic references to directories
@anchor{Zsh/contrib usage}@anchor{1b1}
@subsection Usage


To use the function, first define a wrapper function for your specific
case.  We’ll assume it’s to be autoloaded.  This can have any name but
we’ll refer to it as zdn_mywrapper.  This wrapper function will define
various variables and then call this function with the same arguments
that the wrapper function gets.  This configuration is described below.

Then arrange for the wrapper to be run as a zsh_directory_name hook:

@example
 autoload -Uz add-zsh-hook zsh_directory_name_generic zdn_mywrapper
 add-zsh-hook -U zsh_directory_name zdn_mywrapper
@end example

@node Configuration<3>,Complete Example,Usage,Abbreviated dynamic references to directories
@anchor{Zsh/contrib id5}@anchor{1b2}
@subsection Configuration


The wrapper function should define a local associative array zdn_top.
Alternatively, this can be set with a style called @code{mapping}.  The
context for the style is @code{:zdn:}@var{wrapper-name} where
@var{wrapper-name} is the function calling zsh_directory_name_generic;
for example:

@example
 zstyle :zdn:zdn_mywrapper: mapping zdn_mywrapper_top
@end example

The keys in this associative array correspond to the first component of
the name.  The values are matching directories.  They may have an
optional suffix with a slash followed by a colon and the name of a
variable in the same format to give the next component.  (The slash
before the colon is to disambiguate the case where a colon is needed in
the path for a drive.  There is otherwise no syntax for escaping this,
so path components whose names start with a colon are not supported.)  A
special component @code{:default:} specifies a variable in the form
@code{/:}@var{var} (the path section is ignored and so is usually empty)
that will be used for the next component if no variable is given for the
path.  Variables referred to within @code{zdn_top} have the same format as
@code{zdn_top} itself, but contain relative paths.

For example,

@example
 local -A zdn_top=(
   g   ~/git
   ga  ~/alternate/git
   gs  /scratch/$USER/git/:second2
   :default: /:second1
 )
@end example

This specifies the behaviour of a directory referred to as @code{~[g:...]}
or @code{~[ga:...]} or @code{~[gs:...]}.  Later path components are optional;
in that case @code{~[g]} expands to @code{~/git}, and so on.  @code{gs} expands
to @code{/scratch/$USER/git} and uses the associative array @code{second2} to
match the second component; @code{g} and @code{ga} use the associative array
@code{second1} to match the second component.

When expanding a name to a directory, if the first component is not @code{g} or
@code{ga} or @code{gs}, it is not an error; the function simply returns 1 so that a
later hook function can be tried.  However, matching the first component
commits the function, so if a later component does not match, an error
is printed (though this still does not stop later hooks from being
executed).

For components after the first, a relative path is expected, but note that
multiple levels may still appear.  Here is an example of @code{second1}:

@example
 local -A second1=(
   p   myproject
   s   somproject
   os  otherproject/subproject/:third
 )
@end example

The path as found from @code{zdn_top} is extended with the matching
directory, so @code{~[g:p]} becomes @code{~/git/myproject}.  The slash between
is added automatically (it’s not possible to have a later component
modify the name of a directory already matched).  Only @code{os} specifies
a variable for a third component, and there’s no @code{:default:}, so it’s
an error to use a name like @code{~[g:p:x]} or @code{~[ga:s:y]} because
there’s nowhere to look up the @code{x} or @code{y}.

The associative arrays need to be visible within this function; the
generic function therefore uses internal variable names beginning
@code{_zdn_} in order to avoid clashes.  Note that the variable @code{reply}
needs to be passed back to the shell, so should not be local in the
calling function.

The function does not test whether directories assembled by component
actually exist; this allows the system to work across automounted
file systems.  The error from the command trying to use a non-existent
directory should be sufficient to indicate the problem.

@node Complete Example,,Configuration<3>,Abbreviated dynamic references to directories
@anchor{Zsh/contrib complete-example}@anchor{1b3}
@subsection Complete Example


Here is a full fictitious but usable autoloadable definition of the
example function defined by the code above.  So @code{~[gs:p:s]} expands
to @code{/scratch/$USER/git/myscratchproject/top/srcdir} (with @code{$USER}
also expanded).

@example
 local -A zdn_top=(
   g   ~/git
   ga  ~/alternate/git
   gs  /scratch/$USER/git/:second2
   :default: /:second1
 )

 local -A second1=(
   p   myproject
   s   somproject
   os  otherproject/subproject/:third
 )

 local -A second2=(
   p   myscratchproject
   s   somescratchproject
 )

 local -A third=(
   s   top/srcdir
   d   top/documentation
 )

 # autoload not needed if you did this at initialisation...
 autoload -Uz zsh_directory_name_generic
 zsh_directory_name_generic "$@@
@end example

It is also possible to use global associative arrays, suitably named,
and set the style for the context of your wrapper function to
refer to this.  Then your set up code would contain the following:

@example
 typeset -A zdn_mywrapper_top=(...)
 # ... and so on for other associative arrays ...
 zstyle ':zdn:zdn_mywrapper:' mapping zdn_mywrapper_top
 autoload -Uz add-zsh-hook zsh_directory_name_generic zdn_mywrapper
 add-zsh-hook -U zsh_directory_name zdn_mywrapper
@end example

and the function @code{zdn_mywrapper} would contain only the following:

@example
 zsh_directory_name_generic "$@@"
@end example

@c historic nodename: Version Control Information

@node Gathering information from version control systems,Prompt Themes,Abbreviated dynamic references to directories,User Contributions
@anchor{Zsh/contrib gathering-information-from-version-control-systems}@anchor{1b4}
@section Gathering information from version control systems


@geindex version control utility; Command

In a lot of cases, it is nice to automatically retrieve information from
version control systems (VCSs), such as subversion, CVS or git, to be able
to provide it to the user; possibly in the user’s prompt. So that you can
instantly tell which branch you are currently on, for example.

In order to do that, you may use the @code{vcs_info} function.

The following VCSs are supported, showing the abbreviated name by which
they are referred to within the system:


@table @asis

@item Bazaar (@code{bzr})

@indicateurl{https://bazaar.canonical.com/}

@item Codeville (@code{cdv})

@indicateurl{http://freecode.com/projects/codeville/}

@item Concurrent Versioning System (@code{cvs})

@indicateurl{https://www.nongnu.org/cvs/}

@item Darcs (@code{darcs})

@indicateurl{http://darcs.net/}

@item Fossil (@code{fossil})

@indicateurl{https://fossil-scm.org/}

@item Git (@code{git})

@indicateurl{https://git-scm.com/}

@item GNU arch (@code{tla})

@indicateurl{https://www.gnu.org/software/gnu-arch/}

@item Mercurial (@code{hg})

@indicateurl{https://www.mercurial-scm.org/}

@item Monotone (@code{mtn})

@indicateurl{https://monotone.ca/}

@item Perforce (@code{p4})

@indicateurl{https://www.perforce.com/}

@item Subversion (@code{svn})

@indicateurl{https://subversion.apache.org/}

@item SVK (@code{svk})

@indicateurl{https://svk.bestpractical.com/}
@end table

There is also support for the patch management system @code{quilt}
(@indicateurl{https://savannah.nongnu.org/projects/quilt}). See


vcs_info Quilt Support

below for details.

To load @code{vcs_info}:

@example
 autoload -Uz vcs_info
@end example

It can be used in any existing prompt, because it does not require any
specific @code{$psvar} entries to be available.

@c historic nodename: vcs_info Quickstart

@menu
* Quickstart:: 
* Configuration: Configuration<4>. 
* Oddities:: 
* Quilt Support:: 
* Function Descriptions (Public API): Function Descriptions Public API. 
* Variable Description:: 
* Hooks in vcs_info:: 
* Examples: Examples<2>. 

@end menu

@node Quickstart,Configuration<4>,,Gathering information from version control systems
@anchor{Zsh/contrib quickstart}@anchor{1b5}
@subsection Quickstart


To get this feature working quickly (including colors), you can do the
following (assuming, you loaded @code{vcs_info} properly - see above):

@example
 zstyle ':vcs_info:*' actionformats \
     '%F@{5@}(%f%s%F@{5@})%F@{3@}-%F@{5@}[%F@{2@}%b%F@{3@}|%F@{1@}%a%F@{5@}]%f '
 zstyle ':vcs_info:*' formats       \
     '%F@{5@}(%f%s%F@{5@})%F@{3@}-%F@{5@}[%F@{2@}%b%F@{5@}]%f '
 zstyle ':vcs_info:(sv[nk]|bzr):*' branchformat '%b%F@{1@}:%F@{3@}%r'
 precmd () @{ vcs_info @}
 PS1='%F@{5@}[%F@{2@}%n%F@{5@}] %F@{3@}%3~ $@{vcs_info_msg_0_@}%f%# '
@end example

Obviously, the last two lines are there for demonstration. You need to
call @code{vcs_info} from your @code{precmd} function. Once that is done you need
a `single quoted' @code{'$@{vcs_info_msg_0_@}'} in your prompt.

To be able to use @code{'$@{vcs_info_msg_0_@}'} directly in your prompt like
this, you will need to have the @code{PROMPT_SUBST} option enabled.

Now call the @code{vcs_info_printsys} utility from the command line:

@example
 % vcs_info_printsys
 ## list of supported version control backends:
 ## disabled systems are prefixed by a hash sign (#)
 bzr
 cdv
 cvs
 darcs
 fossil
 git
 hg
 mtn
 p4
 svk
 svn
 tla
 ## flavours (cannot be used in the enable or disable styles; they
 ## are enabled and disabled with their master [git-svn -> git])
 ## they *can* be used in contexts: ':vcs_info:git-svn:*'.
 git-p4
 git-svn
 hg-git
 hg-hgsubversion
 hg-hgsvn
@end example

You may not want all of these because there is no point in running the
code to detect systems you do not use.  So there is a way to disable
some backends altogether:

@example
 zstyle ':vcs_info:*' disable bzr cdv darcs mtn svk tla
@end example

You may also pick a few from that list and enable only those:

@example
 zstyle ':vcs_info:*' enable git cvs svn
@end example

If you rerun @code{vcs_info_printsys} after one of these commands, you will
see the backends listed in the @code{disable} style (or backends not in the
@code{enable} style - if you used that) marked as disabled by a hash sign.
That means the detection of these systems is skipped `completely'. No
wasted time there.

@c historic nodename: vcs_info Configuration

@node Configuration<4>,Oddities,Quickstart,Gathering information from version control systems
@anchor{Zsh/contrib id6}@anchor{1b6}
@subsection Configuration


The @code{vcs_info} feature can be configured via @code{zstyle}.

First, the context in which we are working:

@example
 :vcs_info:@var{vcs-string}:@var{user-context}:@var{repo-root-name}
@end example

@var{vcs-string}

@quotation

is one of: @code{git}, @code{git-svn}, @code{git-p4}, @code{hg}, @code{hg-git},
@code{hg-hgsubversion}, @code{hg-hgsvn}, @code{darcs}, @code{bzr}, @code{cdv}, @code{mtn},
@code{svn}, @code{cvs}, @code{svk}, @code{tla}, @code{p4} or @code{fossil}.
This is followed by @code{.quilt-}@var{quilt-mode} in Quilt mode
(see
.. only:: man

@quotation

`Quilt Support'
@end quotation

@quotation

vcs_info Quilt Support
@end quotation

for details)

and by @code{+}@var{hook-name} while hooks are active
(see
.. only:: man

@quotation

`Hooks in vcs_info'
@end quotation

@quotation

vcs_info Hooks
@end quotation

for details).

Currently, hooks in quilt mode don’t add the @code{.quilt-}@var{quilt-mode} information.
This may change in the future.
@end quotation

@var{user-context}

@quotation

is a freely configurable string, assignable by
the user as the first argument to @code{vcs_info} (see its description
below).
@end quotation

@var{repo-root-name}

@quotation

is the name of a repository in which you want a
style to match. So, if you want a setting specific to @code{/usr/src/zsh},
with that being a CVS checkout, you can set @var{repo-root-name} to
@code{zsh} to make it so.
@end quotation

There are three special values for @var{vcs-string}: The first is named
@code{-init-}, that is in effect as long as there was no decision what VCS
backend to use. The second is @code{-preinit-}; it is used `before'
@code{vcs_info} is run, when initializing the data exporting variables. The
third special value is @code{formats} and is used by the @code{vcs_info_lastmsg}
for looking up its styles.

The initial value of @var{repo-root-name} is @code{-all-} and it is replaced
with the actual name, as soon as it is known. Only use this part of the
context for defining the @code{formats}, @code{actionformats} or
@code{branchformat} styles, as it is guaranteed that @var{repo-root-name} is
set up correctly for these only. For all other styles, just use @code{'*'}
instead.

There are two pre-defined values for @var{user-context}:


@table @asis

@item @code{default}

the one used if none is specified

@item @code{command}

used by vcs_info_lastmsg to lookup its styles
@end table

You can of course use @code{':vcs_info:*'} to match all VCSs in all
user-contexts at once.

This is a description of all styles that are looked up.

@geindex formats; Keystroke

@code{formats}

@quotation

A list of formats, used when actionformats is not used
(which is most of the time).
@end quotation

@geindex actionformats; Keystroke

@code{actionformats}

@quotation

A list of formats, used if there is a special
action going on in your current repository; like an interactive rebase or
a merge conflict.
@end quotation

@geindex branchformat; Keystroke

@code{branchformat}

@quotation

Some backends replace @code{%b} in the formats and
actionformats styles above, not only by a branch name but also by a
revision number. This style lets you modify how that string should look.
@end quotation

@geindex nvcsformats; Keystroke

@code{nvcsformats}

@quotation

These “formats” are set when we didn’t detect a version control system
for the current directory or @code{vcs_info} was disabled. This is useful if
you want @code{vcs_info} to completely take over the generation of your
prompt. You would do something like @code{PS1='$@{vcs_info_msg_0_@}'} to
accomplish that.
@end quotation

@geindex hgrevformat; Keystroke

@code{hgrevformat}

@quotation

@code{hg} uses both a hash and a revision number to reference a specific
changeset in a repository. With this style you can format the revision
string (see @code{branchformat}) to include either or both. It’s only
useful when @code{get-revision} is true. Note, the full 40-character revision id
is not available (except when using the @code{use-simple} option) because
executing hg more than once per prompt is too slow; you may customize this
behavior using hooks.
@end quotation

@geindex max-exports; Keystroke

@code{max-exports}

@quotation

Defines the maximum number of
@code{vcs_info_msg_*_} variables @code{vcs_info} will set.
@end quotation

@geindex enable; Keystroke

@code{enable}

@quotation

A list of backends you want to use. Checked in the @code{-init-} context. If
this list contains an item called @code{NONE} no backend is used at all and
@code{vcs_info} will do nothing. If this list contains @code{ALL}, @code{vcs_info}
will use all known backends. Only with @code{ALL} in @code{enable} will the
@code{disable} style have any effect. @code{ALL} and @code{NONE} are case insensitive.
@end quotation

@geindex disable; Keystroke

@code{disable}

@quotation

A list of VCSs you don’t want @code{vcs_info} to test for
repositories (checked in the @code{-init-} context, too). Only used if
@code{enable} contains @code{ALL}.
@end quotation

@geindex disable-patterns; Keystroke

@code{disable-patterns}

@quotation

A list of patterns that are checked against @code{$PWD}. If a pattern
matches, @code{vcs_info} will be disabled. This style is checked in the
@code{:vcs_info:-init-:*:-all-} context.

Say, @code{~/.zsh} is a directory under version control, in which you do
not want @code{vcs_info} to be active, do:

@example
 zstyle ':vcs_info:*' disable-patterns "$@{(b)HOME@}/.zsh(|/*)"
@end example
@end quotation

@geindex use-quilt; Keystroke

@code{use-quilt}

@quotation

If enabled, the @code{quilt} support code is active in `addon’ mode.
See
.. only:: man

@quotation

`Quilt Support'
@end quotation

@quotation

vcs_info Quilt Support
@end quotation

for details.
@end quotation

@geindex quilt-standalone; Keystroke

@code{quilt-standalone}

@quotation

If enabled, `standalone’ mode detection is attempted if no VCS is active
in a given directory. See
.. only:: man

@quotation

`Quilt Support'
@end quotation

@quotation

vcs_info Quilt Support
@end quotation

for details.
@end quotation

@geindex quilt-patch-dir; Keystroke

@code{quilt-patch-dir}

@quotation

Overwrite the value of the @code{$QUILT_PATCHES} environment variable. See


@quotation

vcs_info Quilt Support
@end quotation

for details.
@end quotation

@geindex quiltcommand; Keystroke

@code{quiltcommand}

@quotation

When @code{quilt} itself is called in quilt support, the value of this style
is used as the command name.
@end quotation

@geindex check-for-changes; Keystroke

@code{check-for-changes}

@quotation

If enabled, this style causes the @code{%c} and @code{%u} format escapes to show
when the working directory has uncommitted changes. The strings displayed by
these escapes can be controlled via the @code{stagedstr} and @code{unstagedstr}
styles. The only backends that currently support this option are @code{git},
@code{hg}, and @code{bzr} (the latter two only support unstaged).

For this style to be evaluated with the @code{hg} backend, the @code{get-revision}
style needs to be set and the @code{use-simple} style needs to be unset. The
latter is the default; the former is not.

With the @code{bzr} backend, `lightweight checkouts' only honor this style if
the @code{use-server} style is set.

Note, the actions taken if this style is enabled are potentially expensive
(read: they may be slow, depending on how big the current repository is).
Therefore, it is disabled by default.
@end quotation

@geindex check-for-staged-changes; Keystroke

@code{check-for-staged-changes}

@quotation

This style is like @code{check-for-changes}, but it never checks the worktree
files, only the metadata in the @code{.$@{vcs@}} dir.  Therefore,
this style initializes only the @code{%c} escape (with @code{stagedstr}) but
not the @code{%u} escape.  This style is faster than @code{check-for-changes}.

In the @code{git} backend, this style checks for changes in the index.
Other backends do not currently implement this style.

This style is disabled by default.
@end quotation

@geindex stagedstr; Keystroke

@code{stagedstr}

@quotation

This string will be used in the @code{%c} escape if there are staged changes in
the repository.
@end quotation

@geindex unstagedstr; Keystroke

@code{unstagedstr}

@quotation

This string will be used in the @code{%u} escape if there are unstaged changes
in the repository.
@end quotation

@geindex command; Keystroke

@code{command}

@quotation

This style causes @code{vcs_info} to use the supplied string as the command
to use as the VCS’s binary. Note, that setting this in ‘@code{:vcs_info:*}’ is
not a good idea.

If the value of this style is empty (which is the default), the used binary
name is the name of the backend in use (e.g. @code{svn} is used in an @code{svn}
repository).

The @code{repo-root-name} part in the context is always the default @code{-all-}
when this style is looked up.

For example, this style can be used to use binaries from non-default
installation directories. Assume, @code{git} is installed in /usr/bin but
your sysadmin installed a newer version in /usr/local/bin. Instead of
changing the order of your @code{$PATH} parameter, you can do this:

@example
 zstyle ':vcs_info:git:*:-all-' command /usr/local/bin/git
@end example
@end quotation

@geindex use-server; Keystroke

@code{use-server}

@quotation

This is used by the Perforce backend (@code{p4}) to decide if it should
contact the Perforce server to find out if a directory is managed
by Perforce.  This is the only reliable way of doing this, but runs
the risk of a delay if the server name cannot be found.  If the
server (more specifically, the @var{host}@code{:}@var{port} pair describing the
server) cannot be contacted, its name is put into the associative array
@code{vcs_info_p4_dead_servers} and is not contacted again during the session
until it is removed by hand.  If you do not set this style, the @code{p4}
backend is only usable if you have set the environment variable
@code{P4CONFIG} to a file name and have corresponding files in the root
directories of each Perforce client.  See comments in the function
@code{VCS_INFO_detect_p4} for more detail.

The Bazaar backend (@code{bzr}) uses this to permit contacting the server
about lightweight checkouts, see the @code{check-for-changes} style.
@end quotation

@geindex use-simple; Keystroke

@code{use-simple}

@quotation

If there are two different ways of gathering
information, you can select the simpler one by setting this style to true;
the default is to use the not-that-simple code, which is potentially a lot
slower but might be more accurate in all possible cases. This style is
used by the @code{bzr}, @code{hg}, and @code{git} backends. In the case of @code{hg} it will invoke
the external hexdump program to parse the binary dirstate cache file; this
method will not return the local revision number.
@end quotation

@geindex get-revision; Keystroke

@code{get-revision}

@quotation

If set to true, vcs_info goes the extra mile to figure out the revision of
a repository’s work tree (currently for the @code{git} and @code{hg} backends,
where this kind of information is not always vital). For @code{git}, the
hash value of the currently checked out commit is available via the @code{%i}
expansion. With @code{hg}, the local revision number and the corresponding
global hash are available via @code{%i}.
@end quotation

@geindex get-mq; Keystroke

@code{get-mq}

@quotation

If set to true, the @code{hg} backend will look for a Mercurial Queue (@code{mq})
patch directory. Information will be available via the @code{%m} replacement.
@end quotation

@geindex get-bookmarks; Keystroke

@code{get-bookmarks}

@quotation

If set to true, the @code{hg} backend will try to get a list of current
bookmarks. They will be available via the @code{%m} replacement.

The default is to generate a comma-separated list of all bookmark names
that refer to the currently checked out revision.  If a bookmark is active,
its name is suffixed an asterisk and placed first in the list.
@end quotation

@geindex use-prompt-escapes; Keystroke

@code{use-prompt-escapes}

@quotation

Determines if we assume that the assembled
string from @code{vcs_info} includes prompt escapes. (Used by
@code{vcs_info_lastmsg}.)
@end quotation

@geindex debug; Keystroke

@code{debug}

@quotation

Enable debugging output to track possible problems. Currently this style
is only used by @code{vcs_info}’s hooks system.
@end quotation

@geindex hooks; Keystroke

@code{hooks}

@quotation

A list style that defines hook-function names. See
.. only:: man

@quotation

`Hooks in vcs_info'
@end quotation

vcs_info Hooks

below for details.
@end quotation

@geindex patch-format; Keystroke

@geindex nopatch-format; Keystroke

@code{patch-format}

@code{nopatch-format}

@quotation

This pair of styles format the patch information used by the @code{%m} expando in
formats and actionformats for the @code{git} and @code{hg} backends.  The value is
subject to certain @code{%}-expansions described below.
The expanded value is made available in the global @code{backend_misc} array as
@code{$@{backend_misc[patches]@}} (also if a @code{set-patch-format} hook is used).
@end quotation

@geindex get-unapplied; Keystroke

@code{get-unapplied}

@quotation

This boolean style controls whether a backend should attempt to gather a list
of unapplied patches (for example with Mercurial Queue patches).

Used by the @code{quilt}, @code{hg}, and @code{git} backends.
@end quotation

The default values for these styles in all contexts are:


@table @asis

@item @code{formats}

“ (%s)-[%b]%u%c-”

@item @code{actionformats}

“ (%s)-[%b|%a]%u%c-”

@item @code{branchformat}

“%b:%r” (for bzr, svn, svk and hg)

@item @code{nvcsformats}

“”

@item @code{hgrevformat}

“%r:%h”

@item @code{max-exports}

2

@item @code{enable}

ALL

@item @code{disable}

(empty list)

@item @code{disable-patterns}

(empty list)

@item @code{check-for-changes}

false

@item @code{check-for-staged-changes}

false

@item @code{stagedstr}

(string: “S”)

@item @code{unstagedstr}

(string: “U”)

@item @code{command}

(empty string)

@item @code{use-server}

false

@item @code{use-simple}

false

@item @code{get-revision}

false

@item @code{get-mq}

true

@item @code{get-bookmarks}

false

@item @code{use-prompt-escapes}

true

@item @code{debug}

false

@item @code{hooks}

(empty list)

@item @code{use-quilt}

false

@item @code{quilt-standalone}

false

@item @code{quilt-patch-dir}

empty - use @code{$QUILT_PATCHES}

@item @code{quiltcommand}

quilt

@item @code{patch-format}

@var{backend dependent}

@item @code{nopatch-format}

@var{backend dependent}

@item @code{get-unapplied}

false
@end table

In normal @code{formats} and @code{actionformats} the following replacements are
done:


@table @asis

@item @code{%s}

The VCS in use (git, hg, svn, etc.).

@item @code{%b}

Information about the current branch.

@item @code{%a}

An identifier that describes the action. Only makes sense in
@code{actionformats}.

@item @code{%i}

The current revision number or identifier. For @code{hg}
the @code{hgrevformat} style may be used to customize the output.

@item @code{%c}

The string from the @code{stagedstr} style if there are staged
changes in the repository.

@item @code{%u}

The string from the @code{unstagedstr} style if there are
unstaged changes in the repository.

@item @code{%R}

The base directory of the repository.

@item @code{%r}

The repository name. If @code{%R} is @code{/foo/bar/repoXY}, @code{%r}
is @code{repoXY}.

@item @code{%S}

A subdirectory within a repository. If @code{$PWD} is
@code{/foo/bar/repoXY/beer/tasty}, @code{%S} is @code{beer/tasty}.
@end table

@code{%m}

@quotation

A “misc” replacement. It is at the discretion of the backend to
decide what this replacement expands to.

The @code{hg} and @code{git} backends use this expando to display patch information.
@code{hg} sources patch information from the @code{mq} extensions; @code{git} from in-progress
@code{rebase} and @code{cherry-pick} operations and from the @code{stgit} extension.  The @code{patch-format}
and @code{nopatch-format} styles control the generated string.  The former is used
when at least one patch from the patch queue has been applied, and the latter
otherwise.

The @code{hg} backend displays bookmark information in this expando (in addition
to @code{mq} information).  See the @code{get-mq} and @code{get-bookmarks} styles.  Both
of these styles may be enabled at the same time.  If both are enabled, both
resulting strings will be shown separated by a semicolon (that cannot currently
be customized).

The @code{quilt} `standalone’ backend sets this expando to the same value as the
@code{%Q} expando.
@end quotation

@code{%Q}

@quotation

Quilt series information.
When quilt is used (either in `addon’ mode or as a `standalone’ backend),
this expando is set to the quilt series’ @code{patch-format} string.
The @code{set-patch-format} hook and @code{nopatch-format} style are honoured.

See
.. only:: man

@quotation

`Quilt Support'
@end quotation

@quotation

vcs_info Quilt Support
@end quotation

below for details.
@end quotation

In @code{branchformat} these replacements are done:


@table @asis

@item @code{%b}

The branch name. For @code{hg}, the branch name can include a
topic name.

@item @code{%r}

The current revision number or the @code{hgrevformat} style for
@code{hg}.
@end table

In @code{hgrevformat} these replacements are done:


@table @asis

@item @code{%r}

The current local revision number.

@item @code{%h}

The current global revision identifier.
@end table

In @code{patch-format} and @code{nopatch-format} these replacements are done:


@table @asis

@item @code{%p}

The name of the top-most applied patch; may be overridden by the @code{applied-string} hook.

@item @code{%u}

The number of unapplied patches; may be overridden by the @code{unapplied-string} hook.

@item @code{%n}

The number of applied patches.

@item @code{%c}

The number of unapplied patches.

@item @code{%a}

The number of all patches (@code{%a = %n + %c}).

@item @code{%g}

The names of active @code{mq} guards (@code{hg} backend).

@item @code{%G}

The number of active @code{mq} guards (@code{hg} backend).
@end table

Not all VCS backends have to support all replacements. For @code{nvcsformats}
no replacements are performed at all, it is just a string.

@c historic nodename: vcs_info Oddities

@node Oddities,Quilt Support,Configuration<4>,Gathering information from version control systems
@anchor{Zsh/contrib oddities}@anchor{1b7}
@subsection Oddities


If you want to use the @code{%b} (bold off) prompt expansion in @code{formats},
which expands @code{%b} itself, use @code{%%b}. That will cause the @code{vcs_info}
expansion to replace @code{%%b} with @code{%b}, so that zsh’s prompt expansion
mechanism can handle it. Similarly, to hand down @code{%b} from
@code{branchformat}, use @code{%%%%b}. Sorry for this inconvenience, but it
cannot be easily avoided. Luckily we do not clash with a lot of prompt
expansions and this only needs to be done for those.

When one of the @code{gen-applied-string}, @code{gen-unapplied-string}, and
@code{set-patch-format} hooks is defined,
applying @code{%}-escaping (@code{foo=$@{foo//%'/%%@}}’) to the interpolated values
for use in the prompt is the responsibility of those hooks (jointly);
when neither of those hooks is defined, @code{vcs_info} handles escaping by itself.
We regret this coupling, but it was required for backwards compatibility.

@c historic nodename: vcs_info Quilt Support

@node Quilt Support,Function Descriptions Public API,Oddities,Gathering information from version control systems
@anchor{Zsh/contrib quilt-support}@anchor{1b8}
@subsection Quilt Support


`Quilt' is not a version control system, therefore this is not implemented
as a backend. It can help keeping track of a series of patches. People use it
to keep a set of changes they want to use on top of software packages (which
is tightly integrated into the package build process - the Debian project
does this for a large number of packages). Quilt can also help individual
developers keep track of their own patches on top of real version control
systems.

The @code{vcs_info} integration tries to support both ways of using quilt by
having two slightly different modes of operation: `addon’ mode and
`standalone’ mode).

Quilt integration is off by default; to enable it, set the @code{use-quilt} style,
and add @code{%Q} to your @code{formats} or @code{actionformats} style:

@example
 zstyle ':vcs_info:*' use-quilt true
@end example

Styles looked up from the Quilt support code include @code{.quilt-}@var{quilt-mode}
in the @var{vcs-string} part of the context, where @var{quilt-mode} is either
@code{addon} or @code{standalone}.
Example: @code{:vcs_info:git.quilt-addon:default:}@var{repo-root-name}.

For `addon’ mode to become active @code{vcs_info} must have already detected a
real version control system controlling the directory. If that is the case,
a directory that holds quilt’s patches needs to be found. That directory is
configurable via the @code{QUILT_PATCHES} environment variable. If that
variable exists its value is used, otherwise the value @code{patches} is
assumed. The value from @code{$QUILT_PATCHES} can be overwritten using the
@code{quilt-patch-dir} style. (Note: you can use @code{vcs_info} to keep the value
of @code{$QUILT_PATCHES} correct all the time via the @code{post-quilt} hook).

When the directory in question is found, quilt is assumed to be active. To
gather more information, @code{vcs_info} looks for a directory called `.pc’;
Quilt uses that directory to track its current state. If this directory does
not exist we know that quilt has not done anything to the working directory
(read: no patches have been applied yet).

If patches are applied, @code{vcs_info} will try to find out which. If you want
to know which patches of a series are not yet applied, you need to activate
the @code{get-unapplied} style in the appropriate context.

@code{vcs_info} allows for very detailed control over how the gathered
information is presented (see


vcs_info Configuration and vcs_info Hooks

),
all of which are documented below. Note there are a number of
other patch tracking systems that work on top of a certain version control
system (like @code{stgit} for `git', or @code{mq} for `hg'); the configuration
for systems like that are generally configured the same way as the `quilt'
support.

If the `quilt' support is working in `addon’ mode, the produced string is
available as a simple format replacement (@code{%Q} to be precise), which can
be used in @code{formats} and @code{actionformats}; see below for details).

If, on the other hand, the support code is working in `standalone’ mode,
@code{vcs_info} will pretend as if @code{quilt} were an actual version control
system. That means that the version control system identifier (which
otherwise would be something like `svn’ or `cvs’) will be set to
@code{-quilt-}. This has implications on the used style context where this
identifier is the second element. @code{vcs_info} will have filled in a proper
value for the “repository’s” root directory and the string containing the
information about quilt’s state will be available as the `misc’ replacement
(and @code{%Q} for compatibility with `addon’ mode).

What is left to discuss is how `standalone’ mode is detected. The detection
itself is a series of searches for directories. You can have this detection
enabled all the time in every directory that is not otherwise under version
control. If you know there is only a limited set of trees where you would
like @code{vcs_info} to try and look for Quilt in `standalone’ mode to minimise
the amount of searching on every call to @code{vcs_info}, there are a number of
ways to do that:

Essentially, `standalone’ mode detection is controlled by a style called
@code{quilt-standalone}. It is a string style and its value can have different
effects. The simplest values are: @code{always} to run detection every time
@code{vcs_info} is run, and @code{never} to turn the detection off entirely.

If the value of @code{quilt-standalone} is something else, it is interpreted
differently. If the value is the name of a scalar variable the value of that
variable is checked and that value is used in the same `always’/`never’ way
as described above.

If the value of @code{quilt-standalone} is an array, the elements of that array
are used as directory names under which you want the detection to be active.

If @code{quilt-standalone} is an associative array, the keys are taken as
directory names under which you want the detection to be active, but only if
the corresponding value is the string @code{true}.

Last, but not least, if the value of @code{quilt-standalone} is the name of a
function, the function is called without arguments and the return value
decides whether detection should be active. A `0’ return value is true; a
non-zero return value is interpreted as false.

Note, if there is both a function and a variable by the name of
@code{quilt-standalone}, the function will take precedence.

@c historic nodename: vcs_info API

@node Function Descriptions Public API,Variable Description,Quilt Support,Gathering information from version control systems
@anchor{Zsh/contrib function-descriptions-public-api}@anchor{1b9}
@subsection Function Descriptions (Public API)


@geindex vcs_info; Function

@code{vcs_info} [@var{user-context}]

@quotation

The main function, that runs all backends and assembles all data into
@code{$@{vcs_info_msg_*_@}}. This is the function you want to call from
@code{precmd} if you want to include up-to-date information in your prompt (see


vcs_info Variables

below).  If an argument is given, that string will be
used instead of @code{default} in the @var{user-context} field of the style
context.
@end quotation

@geindex vcs_info_hookadd; Function

@code{vcs_info_hookadd}

@quotation

Statically registers a number of functions to a given hook. The hook needs
to be given as the first argument; what follows is a list of hook-function
names to register to the hook. The @code{+vi-} prefix needs to be left out
here. See
.. only:: man

@quotation

`Hooks in vcs_info'
@end quotation

vcs_info Hooks

below for details.
@end quotation

@geindex vcs_info_hookdel; Function

@code{vcs_info_hookdel}

@quotation

Remove hook-functions from a given hook. The hook needs to be given as the
first non-option argument; what follows is a list of hook-function
names to un-register from the hook. If @code{-a} is used as the first
argument, @code{all} occurrences of the functions are unregistered. Otherwise
only the last occurrence is removed (if a function was registered to a hook
more than once). The @code{+vi-} prefix needs to be left out here.
See
.. only:: man

@quotation

`Hooks in vcs_info'
@end quotation

vcs_info Hooks

below for details.
@end quotation

@geindex vcs_info_lastmsg; Function

@code{vcs_info_lastmsg}

@quotation

Outputs the current values of @code{$@{vcs_info_msg_*_@}}.
Takes into account the value of the @code{use-prompt-escapes} style in
@code{':vcs_info:formats:command:-all-'}. It also only prints @code{max-exports}
values.
@end quotation

@geindex vcs_info_printsys; Function

@code{vcs_info_printsys} [@var{user-context}]

@quotation

Prints a list of all
supported version control systems. Useful to find out possible contexts
(and which of them are enabled) or values for the @code{disable} style.
@end quotation

@geindex vcs_info_setsys; Function

@code{vcs_info_setsys}

@quotation

Initializes @code{vcs_info}’s internal list of
available backends. With this function, you can add support for new VCSs
without restarting the shell.
@end quotation

All functions named @code{VCS_INFO_*} are for internal use only.

@c historic nodename: vcs_info Variables

@node Variable Description,Hooks in vcs_info,Function Descriptions Public API,Gathering information from version control systems
@anchor{Zsh/contrib variable-description}@anchor{1ba}
@subsection Variable Description


@code{$@{vcs_info_msg_}@var{N}@code{_@}} (Note the trailing underscore)

@quotation

Where @var{N} is an integer, e.g., @code{vcs_info_msg_0_}. These variables
are the storage for the informational message the last @code{vcs_info} call
has assembled. These are strongly connected to the @code{formats},
@code{actionformats} and @code{nvcsformats} styles described above. Those styles
are lists. The first member of that list gets expanded into
@code{$@{vcs_info_msg_0_@}}, the second into @code{$@{vcs_info_msg_1_@}}
and the Nth into @code{$@{vcs_info_msg_N-1_@}}. (See the @code{max-exports}
style above.)
@end quotation

All variables named @code{VCS_INFO_*} are for internal use only.

@c historic nodename: vcs_info Hooks

@node Hooks in vcs_info,Examples<2>,Variable Description,Gathering information from version control systems
@anchor{Zsh/contrib hooks-in-vcs-info}@anchor{1bb}
@subsection Hooks in vcs_info


Hooks are places in @code{vcs_info} where you can run your own code. That
code can communicate with the code that called it and through that,
change the system’s behaviour.

For configuration, hooks change the style context:

@example
 :vcs_info:@var{vcs-string}+:var:@cite{hook-name}:@var{user-context}:@var{repo-root-name}
@end example

To register functions to a hook, you need to list them in the @code{hooks}
style in the appropriate context.

Example:

@example
 zstyle ':vcs_info:*+foo:*' hooks bar baz
@end example

This registers functions to the hook `foo’ for all backends. In order to
avoid namespace problems, all registered function names are prepended by
a @code{+vi-}, so the actual functions called for the `foo’ hook are
@code{+vi-bar} and @code{+vi-baz}.

If you would like to register a function to a hook regardless of the
current context, you may use the @code{vcs_info_hookadd} function. To remove
a function that was added like that, the @code{vcs_info_hookdel} function
can be used.

If something seems weird, you can enable the `debug’ boolean style in
the proper context and the hook-calling code will print what it tried
to execute and whether the function in question existed.

When you register more than one function to a hook, all functions are
executed one after another until one function returns non-zero or until
all functions have been called. Context-sensitive hook functions are
executed @code{before} statically registered ones (the ones added by
@code{vcs_info_hookadd}).

You may pass data between functions via an associative array, @code{user_data}.
For example:

@example
 +vi-git-myfirsthook()@{
     user_data[myval]=$myval
 @}
 +vi-git-mysecondhook()@{
     # do something with $@{user_data[myval]@}
 @}
@end example

There are a number of variables that are special in hook contexts:

@code{ret}

@quotation

The return value that the hooks system will return to the caller. The
default is an integer `zero’. If and how a changed @code{ret} value changes
the execution of the caller depends on the specific hook. See the hook
documentation below for details.
@end quotation

@code{hook_com}

@quotation

An associated array which is used for bidirectional communication from
the caller to hook functions. The used keys depend on the specific hook.
@end quotation

@code{context}

@quotation

The active context of the hook. Functions that wish to change this
variable should make it local scope first.
@end quotation

@code{vcs}

@quotation

The current VCS after it was detected. The same values as in the
enable/disable style are used. Available in all hooks except @code{start-up}.
@end quotation

Finally, the full list of currently available hooks:

@code{start-up}

@quotation

Called after starting @code{vcs_info} but before the VCS in this directory is
determined. It can be used to deactivate @code{vcs_info} temporarily if
necessary. When @code{ret} is set to @code{1}, @code{vcs_info} aborts and does
nothing; when set to @code{2}, @code{vcs_info} sets up everything as if no
version control were active and exits.
@end quotation

@code{pre-get-data}

@quotation

Same as @code{start-up} but after the VCS was detected.
@end quotation

@code{gen-hg-bookmark-string}

@quotation

Called in the Mercurial backend when a bookmark string is generated; the
@code{get-revision} and @code{get-bookmarks} styles must be true.

This hook gets the names of the Mercurial bookmarks that
@code{vcs_info} collected from `hg’.

If a bookmark is active, the key @code{$@{hook_com[hg-active-bookmark]@}} is
set to its name.  The key is otherwise unset.

When setting @code{ret} to non-zero, the string in
@code{$@{hook_com[hg-bookmark-string]@}} will be used in the @code{%m} escape in
@code{formats} and @code{actionformats} and will be available in the global
@code{backend_misc} array as @code{$@{backend_misc[bookmarks]@}}.
@end quotation

@code{gen-applied-string}

@quotation

Called in the @code{git} (with @code{stgit} or during rebase or merge), and @code{hg}
(with @code{mq}) backends and in @code{quilt} support when the @code{applied-string}
is generated; the @code{use-quilt} zstyle must be true for @code{quilt} (the @code{mq}
and @code{stgit} backends are active by default).

The arguments to this hook describe applied patches
in the opposite order, which means that the first argument is the
top-most patch and so forth.

When the patches’ log messages can be extracted, those are embedded
within each argument after a space, so each argument is of the form
@var{patch-name} @var{first line of the log message}, where @var{patch-name}
contains no whitespace. The @code{mq} backend passes arguments of
the form @var{patch name}, with possible embedded spaces, but without
extracting the patch’s log message.

When setting @code{ret} to non-zero, the string in
@code{$@{hook_com[applied-string]@}} will be
available as @code{%p} in the @code{patch-format} and @code{nopatch-format} styles.
This hook is, in concert with @code{set-patch-format}, responsible for
@code{%}-escaping that value for use in the prompt.
(See
.. only:: man

@quotation

the `Oddities' subsection above
@end quotation

vcs_info Oddities

.)

The @code{quilt} backend passes to this hook the inputs
@code{$@{hook_com[quilt-patches-dir]@}} and, if it has been
determined, @code{$@{hook_com[quilt-pc-dir]@}}.
@end quotation

@code{gen-unapplied-string}

@quotation

Called in the @code{git} (with @code{stgit} or during rebase), and @code{hg} (with
@code{mq}) backend and in @code{quilt} support when the @code{unapplied-string} is
generated; the @code{get-unapplied} style must be true.

This hook gets the names of all unapplied patches which @code{vcs_info}
in order, which means that the first argument is
the patch next-in-line to be applied and so forth.

The format of each argument is as for @code{gen-applied-string}, above.

When setting @code{ret} to non-zero, the string in
@code{$@{hook_com[unapplied-string]@}} will be available as @code{%u} in the
@code{patch-format} and @code{nopatch-format} styles.
This hook is, in concert with @code{set-patch-format}, responsible for
@code{%}-escaping that value for use in the prompt.
(See
.. only:: man

@quotation

the `Oddities' subsection above
@end quotation

vcs_info Oddities

.)

The @code{quilt} backend passes to this hook the inputs
@code{$@{hook_com[quilt-patches-dir]@}} and, if it has been
determined, @code{$@{hook_com[quilt-pc-dir]@}}.
@end quotation

@code{gen-mqguards-string}

@quotation

Called in the @code{hg} backend when @code{guards-string} is generated; the
@code{get-mq} style must be true (default).

This hook gets the names of any active @code{mq} guards.

When setting @code{ret} to non-zero, the string in
@code{$@{hook_com[guards-string]@}} will be used in the @code{%g} escape in the
@code{patch-format} and @code{nopatch-format} styles.
@end quotation

@code{no-vcs}

@quotation

This hooks is called when no version control system was detected.

The @code{hook_com} parameter is not used.
@end quotation

@code{post-backend}

@quotation

Called as soon as the backend has finished collecting information.

The @code{hook_com} keys available are as for the @code{set-message} hook.
@end quotation

@code{post-quilt}

@quotation

Called after the @code{quilt} support is done. The following information
is passed as arguments to the hook: 1. the quilt-support mode (`addon’ or
`standalone’); 2. the directory that contains the patch series; 3. the
directory that holds quilt’s status information (the `.pc’ directory) or
the string @code{"-nopc-"} if that directory wasn’t found.

The `hook_com’ parameter is not used.
@end quotation

@code{set-branch-format}

@quotation

Called before @code{branchformat} is set. The only argument to the
hook is the format that is configured at this point.

The @code{hook_com} keys considered are @code{branch} and @code{revision}.
They are set to the values figured out so far by @code{vcs_info} and any
change will be used directly when the actual replacement is done.

If @code{ret} is set to non-zero, the string in
@code{$@{hook_com[branch-replace]@}} will be used unchanged as the
@code{%b} replacement in the variables set by @code{vcs_info}.
@end quotation

@code{set-hgrev-format}

@quotation

Called before a @code{hgrevformat} is set. The only argument to the
hook is the format that is configured at this point.

The @code{hook_com} keys considered are @code{hash} and @code{localrev}.
They are set to the values figured out so far by @code{vcs_info} and any
change will be used directly when the actual replacement is done.

If @code{ret} is set to non-zero, the string in
@code{$@{hook_com[rev-replace]@}} will be used unchanged as the
@code{%i} replacement in the variables set by @code{vcs_info}.
@end quotation

@code{pre-addon-quilt}

@quotation

This hook is used when @code{vcs_info}’s quilt functionality is active in “addon”
mode (quilt used on top of a real version control system). It is activated
right before any quilt specific action is taken.

Setting the @code{ret} variable in this hook to a non-zero value avoids any
quilt specific actions from being run at all.
@end quotation

@code{set-patch-format}

@quotation

This hook is used to control some of the possible expansions in
@code{patch-format} and @code{nopatch-format} styles with patch queue systems such as
quilt, mqueue and the like.

This hook is used in the @code{git}, @code{hg} and @code{quilt} backends.

The hook allows the control of the @code{%p} (@code{$@{hook_com[applied]@}}) and @code{%u}
(@code{$@{hook_com[unapplied]@}}) expansion in all backends that use the hook. With
the mercurial backend, the @code{%g} (@code{$@{hook_com[guards]@}}) expansion is
controllable in addition to that.

If @code{ret} is set to non-zero, the string in @code{$@{hook_com[patch-replace]@}}
will be used unchanged instead of an expanded format from @code{patch-format} or
@code{nopatch-format}.

This hook is, in concert with the @code{gen-applied-string} or
@code{gen-unapplied-string} hooks if they are defined, responsible for
@code{%}-escaping the final @code{patch-format} value for use in the prompt.
(See
.. only:: man

@quotation

the `Oddities' subsection above
@end quotation

vcs_info Oddities

.)

The @code{quilt} backend passes to this hook the inputs
@code{$@{hook_com[quilt-patches-dir]@}} and, if it has been
determined, @code{$@{hook_com[quilt-pc-dir]@}}.
@end quotation

@code{set-message}

@quotation

Called each time before a @code{vcs_info_msg_}@var{N}@code{_} message is set.
It takes two arguments; the first being the @var{N} in the message
variable name, the second is the currently configured @code{formats} or
@code{actionformats}.

There are a number of @code{hook_com} keys, that are used here:
@code{action}, @code{branch}, @code{base}, @code{base-name}, @code{subdir},
@code{staged}, @code{unstaged}, @code{revision}, @code{misc}, @code{vcs}
and one @code{miscN} entry for each backend-specific data field (@code{N}
starting at zero). They are set to the values figured out so far by
@code{vcs_info} and any change will be used directly when the actual
replacement is done.

Since this hook is triggered multiple times (once for each configured
@code{formats} or @code{actionformats}), each of the @code{hook_com} keys mentioned
above (except for the @code{miscN} entries) has an @code{_orig} counterpart,
so even if you changed a value to your liking you can still get the
original value in the next run. Changing the @code{_orig} values is
probably not a good idea.

If @code{ret} is set to non-zero, the string in
@code{$@{hook_com[message]@}} will be used unchanged as the message by
@code{vcs_info}.
@end quotation

If all of this sounds rather confusing, take a look at


vcs_info Examples

and also in the @code{Misc/vcs_info-examples} file in the Zsh source.
They contain some explanatory code.

@c historic nodename: vcs_info Examples

@node Examples<2>,,Hooks in vcs_info,Gathering information from version control systems
@anchor{Zsh/contrib examples}@anchor{1bc}
@subsection Examples


Don’t use @code{vcs_info} at all (even though it’s in your prompt):

@example
 zstyle ':vcs_info:*' enable NONE
@end example

Disable the backends for @code{bzr} and @code{svk}:

@example
 zstyle ':vcs_info:*' disable bzr svk
@end example

Disable everything `but' @code{bzr} and @code{svk}:

@example
 zstyle ':vcs_info:*' enable bzr svk
@end example

Provide a special formats for @code{git}:

@example
 zstyle ':vcs_info:git:*' formats       ' GIT, BABY! [%b]'
 zstyle ':vcs_info:git:*' actionformats ' GIT ACTION! [%b|%a]'
@end example

All @code{%x} expansion in all sorts of formats (@code{formats}, @code{actionformats},
@code{branchformat}, you name it) are done using the @code{zformat} builtin from
the @code{zsh/zutil} module. That means you can do everything with these
@code{%x} items what zformat supports. In particular, if you want something
that is really long to have a fixed width, like a hash in a mercurial
branchformat, you can do this: @code{%12.12i}. That’ll shrink the 40 character
hash to its 12 leading characters. The form is actually
@code{%}@var{min}@code{.}@var{max}@code{x}. More is possible.
See @ref{ca,,The zsh/zutil Module} for details.

Use the quicker @code{bzr} backend

@example
 zstyle ':vcs_info:bzr:*' use-simple true
@end example

If you do use @code{use-simple}, please report if it does `the-right-thing[tm]’.

Display the revision number in yellow for @code{bzr} and @code{svn}:

@example
 zstyle ':vcs_info:(svn|bzr):*' \
        branchformat '%b%%F@{yellow@}:%r'
@end example

The doubled percent sign is explained in


vcs_info Oddities

.

Alternatively, one can use the raw colour codes directly:

@example
 zstyle ':vcs_info:(svn|bzr):*' \
        branchformat '%b%@{'$@{fg[yellow]@}'%@}:%r'
@end example

Normally when a variable is interpolated into a format string, the variable
needs to be @code{%}-escaped. In this example we skipped that because we assume
the value of @code{$@{fg[yellow]@}} doesn’t contain any @code{%} signs.

Make sure you enclose the color codes in @code{%@{}@var{…}@code{%@}}
if you want to use the string provided by @code{vcs_info} in prompts.

Here is how to print the VCS information as a command (not in a prompt):

@example
 vcsi() @{ vcs_info interactive; vcs_info_lastmsg @}
@end example

This way, you can even define different formats for output via
@code{vcs_info_lastmsg} in the ‘@code{:vcs_info:*:interactive:*}’ namespace.

Now as promised, some code that uses hooks:
say, you’d like to replace the string `svn’ by `subversion’ in
@code{vcs_info}’s @code{%s} @code{formats} replacement.

First, we will tell @code{vcs_info} to call a function when populating
the message variables with the gathered information:

@example
 zstyle ':vcs_info:*+set-message:*' hooks svn2subversion
@end example

Nothing happens. Which is reasonable, since we didn’t define the actual
function yet. To see what the hooks subsystem is trying to do, enable the
@code{debug} style:

@example
 zstyle ':vcs_info:*+*:*' debug true
@end example

That should give you an idea what is going on. Specifically, the function
that we are looking for is @code{+vi-svn2subversion}. Note, the @code{+vi-}
prefix. So, everything is in order, just as documented. When you are done
checking out the debugging output, disable it again:

@example
 zstyle ':vcs_info:*+*:*' debug false
@end example

Now, let’s define the function:

@example
 function +vi-svn2subversion() @{
     [[ $@{hook_com[vcs_orig]@} == svn ]] && hook_com[vcs]=subversion
 @}
@end example

Simple enough. And it could have even been simpler, if only we had
registered our function in a less generic context. If we do it only in
the @code{svn} backend’s context, we don’t need to test which the active
backend is:

@example
 zstyle ':vcs_info:svn+set-message:*' hooks svn2subversion
@end example

@example
 function +vi-svn2subversion() @{
     hook_com[vcs]=subversion
 @}
@end example

And finally a little more elaborate example, that uses a hook to create
a customised bookmark string for the @code{hg} backend.

Again, we start off by registering a function:

@example
 zstyle ':vcs_info:hg+gen-hg-bookmark-string:*' hooks hgbookmarks
@end example

And then we define the @code{+vi-hgbookmarks} function:

@example
 function +vi-hgbookmarks() @{
     # The default is to connect all bookmark names by
     # commas. This mixes things up a little.
     # Imagine, there's one type of bookmarks that is
     # special to you. Say, because it's *your* work.
     # Those bookmarks look always like this: "sh/*"
     # (because your initials are sh, for example).
     # This makes the bookmarks string use only those
     # bookmarks. If there's more than one, it
     # concatenates them using commas.
     # The bookmarks returned by \`hg' are available in
     # the function's positional parameters.
     local s="$@{(Mj:,:)@@:#sh/*@}"
     # Now, the communication with the code that calls
     # the hook functions is done via the hook_com[]
     # hash. The key at which the \`gen-hg-bookmark-string'
     # hook looks is \`hg-bookmark-string'. So:
     hook_com[hg-bookmark-string]=$s
     # And to signal that we want to use the string we
     # just generated, set the special variable \`ret' to
     # something other than the default zero:
     ret=1
     return 0
 @}
@end example

Some longer examples and code snippets which might be useful are available in
the examples file located at Misc/vcs_info-examples in the Zsh source
directory.

This concludes our guided tour through zsh’s @code{vcs_info}.

@c historic nodename: Prompt Themes

@node Prompt Themes,ZLE Functions,Gathering information from version control systems,User Contributions
@anchor{Zsh/contrib prompt-themes}@anchor{1e}
@section Prompt Themes


@menu
* Installation: Installation<3>. 
* Theme Selection:: 
* Utility Themes:: 
* Writing Themes:: 

@end menu

@node Installation<3>,Theme Selection,,Prompt Themes
@anchor{Zsh/contrib id7}@anchor{1bd}
@subsection Installation


You should make sure all the functions from the @code{Functions/Prompts}
directory of the source distribution are available; they all begin with
the string @code{prompt_} except for the special function @code{promptinit}.
You also need the @code{colors} and @code{add-zsh-hook} functions from
@code{Functions/Misc}.
All these functions may already be installed on your system; if not,
you will need to find them and copy them.  The directory should appear as
one of the elements of the @code{fpath} array (this should already be the
case if they were installed), and at least the function @code{promptinit}
should be autoloaded; it will autoload the rest.  Finally, to initialize
the use of the system you need to call the @code{promptinit} function.  The
following code in your @code{.zshrc} will arrange for this; assume the
functions are stored in the directory @code{~/myfns}:

@example
 fpath=(~/myfns $fpath)
 autoload -U promptinit
 promptinit
@end example

@node Theme Selection,Utility Themes,Installation<3>,Prompt Themes
@anchor{Zsh/contrib theme-selection}@anchor{1be}
@subsection Theme Selection


Use the @code{prompt} command to select your preferred theme.  This command
may be added to your @code{.zshrc} following the call to @code{promptinit} in
order to start zsh with a theme already selected.

@code{prompt} [ @code{-c} | @code{-l} ]

@code{prompt} [ @code{-p} | @code{-h} ] [ @var{theme} … ]

@code{prompt} [ @code{-s} ] @var{theme} [ @var{arg} … ]

@quotation

Set or examine the prompt theme.  With no options and a @var{theme}
argument, the theme with that name is set as the current theme.  The
available themes are determined at run time; use the @code{-l} option to see
a list.  The special @var{theme} @code{random} selects at random one of the
available themes and sets your prompt to that.

In some cases the @var{theme} may be modified by one or more arguments,
which should be given after the theme name.  See the help for each theme
for descriptions of these arguments.

Options are:


@table @asis

@item @code{-c}

Show the currently selected theme and its parameters, if any.

@item @code{-l}

List all available prompt themes.

@item @code{-p}

Preview the theme named by @var{theme}, or all themes if no
@var{theme} is given.

@item @code{-h}

Show help for the theme named by @var{theme}, or for the
@code{prompt} function if no @var{theme} is given.

@item @code{-s}

Set @var{theme} as the current theme and save state.
@end table
@end quotation

@code{prompt_}@var{theme}@code{_setup}

@quotation

Each available @var{theme} has a setup function which is called by the
@code{prompt} function to install that theme.  This function may define
other functions as necessary to maintain the prompt, including functions
used to preview the prompt or provide help for its use.  You should not
normally call a theme’s setup function directly.
@end quotation

@node Utility Themes,Writing Themes,Theme Selection,Prompt Themes
@anchor{Zsh/contrib utility-themes}@anchor{1bf}
@subsection Utility Themes


@code{prompt off}

@quotation

The theme @code{off} sets all the prompt variables to minimal values with
no special effects.
@end quotation

@code{prompt default}

@quotation

The theme @code{default} sets all prompt variables to the same state as
if an interactive zsh was started with no initialization files.
@end quotation

@code{prompt restore}

@quotation

The special theme @code{restore} erases all theme settings and sets prompt
variables to their state before the first time the @code{prompt} function
was run, provided each theme has properly defined its cleanup (see below).

Note that you can undo @code{prompt off} and @code{prompt default} with
@code{prompt restore}, but a second restore does not undo the first.
@end quotation

@node Writing Themes,,Utility Themes,Prompt Themes
@anchor{Zsh/contrib writing-themes}@anchor{1c0}
@subsection Writing Themes


The first step for adding your own theme is to choose a name for it,
and create a file @code{prompt_:var:`name`_setup} in a directory in your
@code{fpath}, such as @code{~/myfns} in the example above.  The file should
at minimum contain assignments for the prompt variables that your
theme wishes to modify.  By convention, themes use @code{PS1}, @code{PS2},
@code{RPS1}, etc., rather than the longer @code{PROMPT} and @code{RPROMPT}.

The file is autoloaded as a function in the current shell context, so
it may contain any necessary commands to customize your theme, including
defining additional functions.  To make some complex tasks easier, your
setup function may also do any of the following:

Assign @code{prompt_opts}

@quotation

The array @code{prompt_opts} may be assigned any of @code{"bang"}, @code{"cr"},
@code{"percent"}, @code{"sp"}, and/or @code{"subst"} as values.  The corresponding
setopts (@code{promptbang}, etc.) are turned on, all other prompt-related
options are turned off.  The @code{prompt_opts} array preserves setopts even
beyond the scope of @code{localoptions}, should your function need that.
@end quotation

Modify hooks

@quotation

Use of @code{add-zsh-hook} and @code{add-zle-hook-widget} is recommended (see
@ref{1a7,,Manipulating Hook Functions}).
All hooks that follow the naming pattern @code{prompt_}@var{theme}@code{_}@var{hook}
are automatically removed when the prompt theme changes or is disabled.
@end quotation

Declare cleanup

@quotation

If your function makes any other changes that should be undone when the
theme is disabled, your setup function may call

@example
 prompt_cleanup @var{command}
@end example

where @var{command} should be suitably quoted.  If your theme is ever
disabled or replaced by another, @var{command} is executed with @code{eval}.
You may declare more than one such cleanup hook.
@end quotation

Define preview

@quotation

Define or autoload a function @code{prompt_}@var{name}@code{_preview} to display
a simulated version of your prompt.  A simple default previewer is
defined by @code{promptinit} for themes that do not define their own.
This preview function is called by @code{prompt -p}.
@end quotation

Provide help

@quotation

Define or autoload a function @code{prompt_}@var{name}@code{_help} to display
documentation or help text for your theme.
This help function is called by @code{prompt -h}.
@end quotation

@c historic nodename: ZLE Functions

@node ZLE Functions,Exception Handling,Prompt Themes,User Contributions
@anchor{Zsh/contrib zle-functions}@anchor{14}
@section ZLE Functions


@menu
* Widgets:: 
* Utility Functions: Utility Functions<2>. 
* Styles: Styles<2>. 

@end menu

@node Widgets,Utility Functions<2>,,ZLE Functions
@anchor{Zsh/contrib widgets}@anchor{1c1}
@subsection Widgets


These functions all implement user-defined ZLE widgets (see
@ref{da,,User-Defined Widgets})
which can be bound to keystrokes in interactive shells.  To use them,
your @code{.zshrc} should contain lines of the form

@example
 autoload @var{function}
 zle -N @var{function}
@end example

followed by an appropriate @code{bindkey} command to associate the function
with a key sequence.  Suggested bindings are described below.

bash-style word functions

@quotation

If you are looking for functions to implement moving over and editing
words in the manner of bash, where only alphanumeric characters are
considered word characters, you can use the functions described in
the next section.  The following is sufficient:

@example
 autoload -U select-word-style
 select-word-style bash
@end example
@end quotation

@geindex forward-word-match; Type

@geindex backward-word-match; Type

@geindex kill-word-match; Type

@geindex backward-kill-word-match; Type

@geindex transpose-words-match; Type

@geindex capitalize-word-match; Type

@geindex up-case-word-match; Type

@geindex down-case-word-match; Type

@geindex delete-whole-word-match; Type

@geindex select-word-match; Type

@geindex select-word-style; Type

@geindex match-word-context; Type

@geindex match-words-by-style; Type

@code{forward-word-match}, @code{backward-word-match}

@code{kill-word-match}, @code{backward-kill-word-match}

@code{transpose-words-match}, @code{capitalize-word-match}

@code{up-case-word-match}, @code{down-case-word-match}

@code{delete-whole-word-match}, @code{select-word-match}

@code{select-word-style}, @code{match-word-context}, @code{match-words-by-style}

@quotation

The first eight @code{-match} functions are drop-in replacements for the
builtin widgets without the suffix.  By default they behave in a similar
way.  However, by the use of styles and the function @code{select-word-style},
the way words are matched can be altered. @code{select-word-match} is intended
to be used as a text object in vi mode but with custom word styles. For
comparison, the widgets described in @ref{e1,,Text Objects}
use fixed definitions of words, compatible
with the @code{vim} editor.

The simplest way of configuring the functions is to use
@code{select-word-style}, which can either be called as a normal function with
the appropriate argument, or invoked as a user-defined widget that will
prompt for the first character of the word style to be used.  The first
time it is invoked, the first eight @code{-match} functions will automatically
replace the builtin versions, so they do not need to be loaded explicitly.

The word styles available are as follows.  Only the first character
is examined.

@code{bash}

@quotation

Word characters are alphanumeric characters only.
@end quotation

@code{normal}

@quotation

As in normal shell operation:  word characters are alphanumeric characters
plus any characters present in the string given by the parameter
@code{$WORDCHARS}.
@end quotation

@code{shell}

@quotation

Words are complete shell command arguments, possibly including complete
quoted strings, or any tokens special to the shell.
@end quotation

@code{whitespace}

@quotation

Words are any set of characters delimited by whitespace.
@end quotation

@code{default}

@quotation

Restore the default settings; this is usually the same as @code{normal}.
@end quotation

All but @code{default} can be input as an upper case character, which has
the same effect but with subword matching turned on.  In this case, words
with upper case characters are treated specially: each separate run of
upper case characters, or an upper case character followed by any number of
other characters, is considered a word.  The style @code{subword-range}
can supply an alternative character range to the default @code{[:upper:]};
the value of the style is treated as the contents of a @code{[}@var{…}@code{]}
pattern (note that the outer brackets should not be supplied, only
those surrounding named ranges).

More control can be obtained using the @code{zstyle} command, as described in
@ref{ca,,The zsh/zutil Module}.  Each style is looked up in the
context @code{:zle:}@var{widget} where @var{widget} is the name of the
user-defined widget, not the name of the function implementing it, so in
the case of the definitions supplied by @code{select-word-style} the
appropriate contexts are @code{:zle:forward-word}, and so on.  The function
@code{select-word-style} itself always defines styles for the context
@code{:zle:*} which can be overridden by more specific (longer) patterns as
well as explicit contexts.

The style @code{word-style} specifies the rules to use.  This may have the
following values.

@code{normal}

@quotation

Use the standard shell rules, i.e. alphanumerics and @code{$WORDCHARS}, unless
overridden by the styles @code{word-chars} or @code{word-class}.
@end quotation

@code{specified}

@quotation

Similar to @code{normal}, but `only' the specified characters, and not also
alphanumerics, are considered word characters.
@end quotation

@code{unspecified}

@quotation

The negation of specified.  The given characters are those which will
`not' be considered part of a word.
@end quotation

@code{shell}

@quotation

Words are obtained by using the syntactic rules for generating shell
command arguments.  In addition, special tokens which are never command
arguments such as @code{()} are also treated as words.
@end quotation

@code{whitespace}

@quotation

Words are whitespace-delimited strings of characters.
@end quotation

The first three of those rules usually use @code{$WORDCHARS}, but the value
in the parameter can be overridden by the style @code{word-chars}, which works
in exactly the same way as @code{$WORDCHARS}.  In addition, the style
@code{word-class} uses character class syntax to group characters and takes
precedence over @code{word-chars} if both are set.  The @code{word-class} style
does not include the surrounding brackets of the character class; for
example, @code{-:[:alnum:]} is a valid @code{word-class} to include all
alphanumerics plus the characters @code{-} and @code{:}.  Be careful
including @code{]}, @code{^} and @code{-} as these are special inside
character classes.

@code{word-style} may also have @code{-subword} appended to its value to
turn on subword matching, as described above.

The style @code{skip-chars} is mostly useful for
@code{transpose-words} and similar functions.  If set, it gives a count of
characters starting at the cursor position which will not be considered
part of the word and are treated as space, regardless of what they actually
are.  For example, if

@example
 zstyle ':zle:transpose-words' skip-chars 1
@end example

has been set, and @code{transpose-words-match} is called with the cursor on
the @var{X} of @code{foo}@var{X}@code{bar}, where @var{X} can be any character, then
the resulting expression is @code{bar}@var{X}@code{foo}.

Finer grained control can be obtained by setting the style @code{word-context}
to an array of pairs of entries.  Each pair of entries consists of a
@var{pattern} and a @var{subcontext}.  The shell argument the cursor is on is
matched against each @var{pattern} in turn until one matches; if it does,
the context is extended by a colon and the corresponding @var{subcontext}.
Note that the test is made against the original word on the line, with no
stripping of quotes.  Special handling is done between words: the current
context is examined and if it contains the string @code{between} the word
is set to a single space; else if it is contains the string @code{back},
the word before the cursor is considered, else the word after cursor is
considered. Some examples are given below.

The style @code{skip-whitespace-first} is only used with the
@code{forward-word} widget.  If it is set to true, then @code{forward-word}
skips any non-word-characters, followed by any non-word-characters:
this is similar to the behaviour of other word-orientated widgets,
and also that used by other editors, however it differs from the
standard zsh behaviour.  When using @code{select-word-style} the widget
is set in the context @code{:zle:*} to @code{true} if the word style is
@code{bash} and @code{false} otherwise.  It may be overridden by setting it in
the more specific context @code{:zle:forward-word*}.

It is possible to create widgets with specific behaviour by defining
a new widget implemented by the appropriate generic function, then
setting a style for the context of the specific widget.  For example,
the following defines a widget @code{backward-kill-space-word} using
@code{backward-kill-word-match}, the generic widget implementing
@code{backward-kill-word} behaviour, and ensures that the new widget
always implements space-delimited behaviour.

@example
 zle -N backward-kill-space-word backward-kill-word-match
 zstyle :zle:backward-kill-space-word word-style space
@end example

The widget @code{backward-kill-space-word} can now be bound to a key.

Here are some further examples of use of the styles, actually taken from the
simplified interface in @code{select-word-style}:

@example
 zstyle ':zle:*' word-style standard
 zstyle ':zle:*' word-chars '@w{'}
@end example

Implements bash-style word handling for all widgets, i.e. only
alphanumerics are word characters; equivalent to setting
the parameter @code{WORDCHARS} empty for the given context.

@example
 style ':zle:*kill*' word-style space
@end example

Uses space-delimited words for widgets with the word `kill’ in the name.
Neither of the styles @code{word-chars} nor @code{word-class} is used in this case.

Here are some examples of use of the @code{word-context} style to extend
the context.

@example
 zstyle ':zle:*' word-context \
        "*/*" filename "[[:space:]]" whitespace
 zstyle ':zle:transpose-words:whitespace' word-style shell
 zstyle ':zle:transpose-words:filename' word-style normal
 zstyle ':zle:transpose-words:filename' word-chars '@w{'}
@end example

This provides two different ways of using @code{transpose-words} depending on
whether the cursor is on whitespace between words or on a filename, here
any word containing a @code{/}.  On whitespace, complete arguments as defined
by standard shell rules will be transposed.  In a filename, only
alphanumerics will be transposed.  Elsewhere, words will be transposed
using the default style for @code{:zle:transpose-words}.

The word matching and all the handling of @code{zstyle} settings is actually
implemented by the function @code{match-words-by-style}.  This can be used to
create new user-defined widgets.  The calling function should set the local
parameter @code{curcontext} to @code{:zle:}@var{widget}, create the local
parameter @code{matched_words} and call @code{match-words-by-style} with no
arguments.  On return, @code{matched_words} will be set to an array with the
elements: (1) the start of the line (2) the word before the cursor (3) any
non-word characters between that word and the cursor (4) any non-word
character at the cursor position plus any remaining non-word characters
before the next word, including all characters specified by the
@code{skip-chars} style, (5) the word at or following the cursor (6) any
non-word characters following that word (7) the remainder of the line.  Any
of the elements may be an empty string; the calling function should test
for this to decide whether it can perform its function.

If the variable @code{matched_words} is defined by the caller to
@code{match-words-by-style} as an associative array (@code{local -A
matched_words}), then the seven values given above should be retrieved
from it as elements named @code{start}, @code{word-before-cursor},
@code{ws-before-cursor}, @code{ws-after-cursor}, @code{word-after-cursor},
@code{ws-after-word}, and @code{end}.  In addition the element
@code{is-word-start} is 1 if the cursor is on the start of a word or
subword, or on white space before it (the cases can be distinguished by
testing the @code{ws-after-cursor} element) and 0 otherwise.  This form is
recommended for future compatibility.

It is possible to pass options with arguments to @code{match-words-by-style}
to override the use of styles.  The options are:


@table @asis

@item @code{-w}

@var{word-style}

@item @code{-s}

@var{skip-chars}

@item @code{-c}

@var{word-class}

@item @code{-C}

@var{word-chars}

@item @code{-r}

@var{subword-range}
@end table

For example, @code{match-words-by-style -w shell -c 0} may be used to
extract the command argument around the cursor.

The @code{word-context} style is implemented by the function
@code{match-word-context}.  This should not usually need to be called
directly.
@end quotation

@geindex bracketed-paste-magic; Type

@code{bracketed-paste-magic}

@quotation

The @code{bracketed-paste} widget (see @ref{d6,,Miscellaneous})
inserts pasted text literally into the editor buffer rather than interpret
it as keystrokes.  This disables some common usages where the self-insert
widget is replaced in order to accomplish some extra processing.  An
example is the contributed @code{url-quote-magic} widget described below.

The @code{bracketed-paste-magic} widget is meant to replace @code{bracketed-paste}
with a wrapper that re-enables these self-insert actions, and other
actions as selected by zstyles.  Therefore this widget is installed with

@example
 autoload -Uz bracketed-paste-magic
 zle -N bracketed-paste bracketed-paste-magic
@end example

Other than enabling some widget processing, @code{bracketed-paste-magic}
attempts to replicate @code{bracketed-paste} as faithfully as possible.

The following zstyles may be set to control processing of pasted text.
All are looked up in the context @code{:bracketed-paste-magic}.

@code{active-widgets}

@quotation

A list of patterns matching widget names that should be activated during
the paste.  All other key sequences are processed as self-insert-unmeta.
The default is @code{self-*} so any user-defined widgets named with that
prefix are active along with the builtin self-insert.

If this style is not set (explicitly deleted) or set to an empty value,
no widgets are active and the pasted text is inserted literally.  If the
value includes @code{undefined-key}, any unknown sequences are discarded
from the pasted text.
@end quotation

@code{inactive-keys}

@quotation

The inverse of @code{active-widgets}, a list of key sequences that always use
@code{self-insert-unmeta} even when bound to an active widget.  Note that
this is a list of literal key sequences, not patterns.
@end quotation

@code{paste-init}

@quotation

A list of function names, called in widget context (but not as widgets).
The functions are called in order until one of them returns a non-zero
status.  The parameter @code{PASTED} contains the initial state of the
pasted text.  All other ZLE parameters such as @code{BUFFER} have their
normal values and side-effects, and full history is available, so for
example @code{paste-init} functions may move words from @code{BUFFER} into
@code{PASTED} to make those words visible to the @code{active-widgets}.

A non-zero return from a @code{paste-init} function does `not' prevent the
paste itself from proceeding.

Loading @code{bracketed-paste-magic} defines @code{backward-extend-paste}, a
helper function for use in @code{paste-init}.

@example
 zstyle :bracketed-paste-magic paste-init \
        backward-extend-paste
@end example

When a paste would insert into the middle of a word or append text to a
word already on the line, @code{backward-extend-paste} moves the prefix
from @code{LBUFFER} into @code{PASTED} so that the @code{active-widgets} see the
full word so far.  This may be useful with @code{url-quote-magic}.
@end quotation

@code{paste-finish}

@quotation

Another list of function names called in order until one returns non-zero.
These functions are called `after' the pasted text has been processed
by the @code{active-widgets}, but `before' it is inserted into @code{BUFFER}.
ZLE parameters have their normal values and side-effects.

A non-zero return from a @code{paste-finish} function does `not' prevent
the paste itself from proceeding.

Loading @code{bracketed-paste-magic} also defines @code{quote-paste}, a helper
function for use in @code{paste-finish}.

@example
 zstyle :bracketed-paste-magic paste-finish \
        quote-paste
 zstyle :bracketed-paste-magic:finish quote-style \
        qqq
@end example

When the pasted text is inserted into @code{BUFFER}, it is quoted per the
@code{quote-style} value.  To forcibly turn off the built-in numeric prefix
quoting of @code{bracketed-paste}, use:

@example
 zstyle :bracketed-paste-magic:finish quote-style \
        none
@end example
@end quotation

`Important:' During @code{active-widgets} processing of the paste (after
@code{paste-init} and before @code{paste-finish}), @code{BUFFER} starts empty and
history is restricted, so cursor motions, etc., may not pass outside of
the pasted content.  Text assigned to @code{BUFFER} by the active widgets
is copied back into @code{PASTED} before @code{paste-finish}.
@end quotation

@geindex bracketed-paste-url-magic; Type

@code{bracketed-paste-url-magic}

@quotation

This widget is a simpler version of using @code{bracketed-paste-magic}
to enable @code{quote-url-magic}. Rather than re-interpreting everything as
keystrokes, it simply handles quoting of pasted urls itself, and all other
text is handled like the default bracketed-paste widget.

It limits the quoting to pastes that consist of a single url, but you
can also enable or disable quoting explicitly for a paste by setting
NUMERIC to 1 or 2 respectively (ie, by pressing alt-1 or alt-2 before
pasting).

It is also possible to customize the list of schemas used to
decide if something is a url by setting the @code{schema} style in the
@code{:bracketed-paste-url-magic} context, for example:

@example
 zstyle :bracketed-paste-url-magic schema http:// myspecialschema:
@end example

The default list of schemas is @code{http:// https:// ftp:// ftps:// file:// ssh:// sftp:// magnet:}.

The widget itself is installed in a similar way as
@code{bracketed-paste-magic} above, by

@example
 autoload -Uz bracketed-paste-url-magic
 zle -N bracketed-paste bracketed-paste-url-magic
@end example
@end quotation

@geindex copy-earlier-word; Type

@code{copy-earlier-word}

@quotation

This widget works like a combination of @code{insert-last-word} and
@code{copy-prev-shell-word}.  Repeated invocations of the widget retrieve
earlier words on the relevant history line.  With a numeric argument
@var{N}, insert the @var{N}th word from the history line; @var{N} may be
negative to count from the end of the line.

If @code{insert-last-word} has been used to retrieve the last word on a
previous history line, repeated invocations will replace that word with
earlier words from the same line.

Otherwise, the widget applies to words on the line currently being edited.
The @code{widget} style can be set to the name of another widget that should
be called to retrieve words.  This widget must accept the same three
arguments as @code{insert-last-word}.
@end quotation

@geindex cycle-completion-positions; Type

@code{cycle-completion-positions}

@quotation

After inserting an unambiguous string into the command line, the new
function based completion system may know about multiple places in
this string where characters are missing or differ from at least one
of the possible matches.  It will then place the cursor on the
position it considers to be the most interesting one, i.e. the one
where one can disambiguate between as many matches as possible with as
little typing as possible.

This widget allows the cursor to be easily moved to the other interesting
spots.  It can be invoked repeatedly to cycle between all positions
reported by the completion system.
@end quotation

@geindex delete-whole-word-match; Type

@code{delete-whole-word-match}

@quotation

This is another function which works like the @code{-match} functions
described immediately above, i.e. using styles to decide the word
boundaries.  However, it is not a replacement for any existing function.

The basic behaviour is to delete the word around the cursor.  There is no
numeric argument handling; only the single word around the cursor is
considered.  If the widget contains the string @code{kill}, the removed text
will be placed in the cutbuffer for future yanking.  This can be obtained
by defining @code{kill-whole-word-match} as follows:

@example
 zle -N kill-whole-word-match delete-whole-word-match
@end example

and then binding the widget @code{kill-whole-word-match}.
@end quotation

@geindex down-line-or-beginning-search; Type

@geindex up-line-or-beginning-search; Type

@code{up-line-or-beginning-search}, @code{down-line-or-beginning-search}

@quotation

These widgets are similar to the builtin functions @code{up-line-or-search}
and @code{down-line-or-search}:  if in a multiline buffer they move up or
down within the buffer, otherwise they search for a history line matching
the start of the current line.  In this case, however, they search for
a line which matches the current line up to the current cursor position, in
the manner of @code{history-beginning-search-backward} and @code{-forward}, rather
than the first word on the line.
@end quotation

@geindex edit-command-line; Type

@code{edit-command-line}

@quotation

Edit the command line using your visual editor, as in @code{ksh}.

@example
 bindkey -M vicmd v edit-command-line
@end example

The editor to be used can also be specified using the @code{editor} style in
the context of the widget. It is specified as an array of command and
arguments:

@example
 zstyle :zle:edit-command-line editor gvim -f
@end example
@end quotation

@geindex expand-absolute-path; Type

@code{expand-absolute-path}

@quotation

Expand the file name under the cursor to an absolute path, resolving
symbolic links.  Where possible, the initial path segment is turned
into a named directory or reference to a user’s home directory.
@end quotation

@geindex history-beginning-search-backward-end; Type

@geindex history-beginning-search-forward-end; Type

@code{history-search-end}

@quotation

This function implements the widgets
@code{history-beginning-search-backward-end} and
@code{history-beginning-search-forward-end}.  These commands work by first
calling the corresponding builtin widget (see
@ref{de,,History Control})
and then moving the cursor to the end of the line.  The original cursor
position is remembered and restored before calling the builtin widget a
second time, so that the same search is repeated to look farther through
the history.

Although you @code{autoload} only one function, the commands to use it are
slightly different because it implements two widgets.

@example
 zle -N history-beginning-search-backward-end \
        history-search-end
 zle -N history-beginning-search-forward-end \
        history-search-end
 bindkey '\e^P' history-beginning-search-backward-end
 bindkey '\e^N' history-beginning-search-forward-end
@end example
@end quotation

@geindex history-beginning-search-menu; Type

@code{history-beginning-search-menu}

@quotation

This function implements yet another form of history searching.  The
text before the cursor is used to select lines from the history,
as for @code{history-beginning-search-backward} except that all matches are
shown in a numbered menu.  Typing the appropriate digits inserts the
full history line.  Note that leading zeroes must be typed (they are only
shown when necessary for removing ambiguity).  The entire history is
searched; there is no distinction between forwards and backwards.

With a numeric argument, the search is not anchored to the start of
the line; the string typed by the use may appear anywhere in the line
in the history.

If the widget name contains @code{-end} the cursor is moved to the end of
the line inserted.  If the widget name contains @code{-space} any space
in the text typed is treated as a wildcard and can match anything (hence
a leading space is equivalent to giving a numeric argument).  Both
forms can be combined, for example:

@example
 zle -N history-beginning-search-menu-space-end \
        history-beginning-search-menu
@end example
@end quotation

@geindex history-pattern-search; Type

@geindex history-pattern-search-backward; Type

@geindex history-pattern-search-forward; Type

@code{history-pattern-search}

@quotation

The function @code{history-pattern-search} implements widgets which prompt
for a pattern with which to search the history backwards or forwards.  The
pattern is in the usual zsh format, however the first character may be
@code{^} to anchor the search to the start of the line, and the last character
may be @code{$} to anchor the search to the end of the line.  If the
search was not anchored to the end of the line the cursor is positioned
just after the pattern found.

The commands to create bindable widgets are similar to those in the
example immediately above:

@example
 autoload -U history-pattern-search
 zle -N history-pattern-search-backward history-pattern-search
 zle -N history-pattern-search-forward history-pattern-search
@end example
@end quotation

@geindex incarg; Type

@geindex incarg@comma{} use of; Variable

@code{incarg}

@quotation

This widget allows you to increment integers on the current line. In addition
to decimals, it can handle hexadecimals prefixed with @code{0x}, binaries with
@code{0b}, and octals with @code{0o}.

By default, the target integer will be incremented by one. With a numeric
argument, the integer is incremented by the amount of the argument. The shell
parameter @code{incarg} may be set to change the default increment to something
other than one.

The behavior of this widget changes depending on the widget name.

When the widget is named @code{incarg}, the widget will increment an integer
placed under the cursor placed or just to the left of it. @code{decarg}, on the
other hand, decrements the integer. When the name is prefixed with @code{vi},
the cursor will jump to the nearest integer after the cursor before incrementing
it. The @code{vi} prefix can also be combined with a @code{backward-} prefix to make
the widget search backwards for numbers.

There’s also a @code{sync-} prefix that can be added to the widget name. This
variant is used for creating a sequence of numbers on split terminals with
synchronized key input. The first pane won’t increment the integer at all, but
each pane after that will have the integer incremented once more than the
previous pane. It currently supports tmux and iTerm2.

The prefixes @code{vi}, @code{backward-}, and @code{sync-} can be combined, for example,
into @code{vim-sync-} or @code{vim-backward-sync-}. The @code{vi} prefix needs to be
at the very beginning.

@example
 bindkey '^X+' incarg
@end example
@end quotation

@geindex incremental-complete-word; Type

@code{incremental-complete-word}

@quotation

This allows incremental completion of a word.  After starting this
command, a list of completion choices can be shown after every character
you type, which you can delete with @code{^H} or @code{DEL}.  Pressing return
accepts the completion so far and returns you to normal editing (that is,
the command line is `not' immediately executed).  You can hit @code{TAB} to
do normal completion, @code{^G} to abort back to the state when you started,
and @code{^D} to list the matches.

This works only with the new function based completion system.

@example
 bindkey '^Xi' incremental-complete-word
@end example
@end quotation

@geindex insert-composed-char; Type

@code{insert-composed-char}

@quotation

This function allows you to compose characters that don’t appear on the
keyboard to be inserted into the command line.  The command is followed by
two keys corresponding to ASCII characters (there is no prompt).  For
accented characters, the two keys are a base character followed by a code
for the accent, while for other special characters the two characters
together form a mnemonic for the character to be inserted.  The
two-character codes are a subset of those given by RFC 1345 (see for
example @indicateurl{http://www.faqs.org/rfcs/rfc1345.html}).

The function may optionally be followed by up to two characters which
replace one or both of the characters read from the keyboard; if both
characters are supplied, no input is read.  For example,
@code{insert-composed-char a:} can be used within a widget to insert an a with
umlaut into the command line.  This has the advantages over use of a
literal character that it is more portable.

For best results zsh should have been built with support for multibyte
characters (configured with @code{--enable-multibyte}); however, the function
works for the limited range of characters available in single-byte
character sets such as ISO-8859-1.

The character is converted into the local representation and
inserted into the command line at the cursor position.
(The conversion is done within the shell, using whatever facilities
the C library provides.)  With a numeric argument, the character and its
code are previewed in the status line

The function may be run outside zle in which case it prints the character
(together with a newline) to standard output.  Input is still read from
keystrokes.

See @code{insert-unicode-char} for an alternative way of inserting Unicode
characters using their hexadecimal character number.

The set of accented characters is reasonably complete up to Unicode
character U+0180, the set of special characters less so.  However, it
is very sporadic from that point.  Adding new characters is easy,
however; see the function @code{define-composed-chars}.  Please send any
additions to @code{zsh-workers@@zsh.org}.

The codes for the second character when used to accent the first are as
follows.  Note that not every character can take every accent.


@table @asis

@item @code{!}

Grave.

@item @code{'}

Acute.

@item @code{>}

Circumflex.

@item @code{?}

Tilde.  (This is not @code{~} as RFC 1345 does not assume that
character is present on the keyboard.)

@item @code{-}

Macron.  (A horizontal bar over the base character.)

@item @code{(}

Breve.  (A shallow dish shape over the base character.)

@item @code{.}

Dot above the base character, or in the case of @code{i} no dot,
or in the case of @code{L} and @code{l} a centered dot.

@item @code{:}

Diaeresis (Umlaut).

@item @code{c}

Cedilla.

@item @code{_}

Underline, however there are currently no underlined characters.

@item @code{/}

Stroke through the base character.

@item @code{"}

Double acute (only supported on a few letters).

@item @code{;}

Ogonek.  (A little forward facing hook at the bottom right
of the character.)

@item @code{<}

Caron.  (A little v over the letter.)

@item @code{0}

Circle over the base character.

@item @code{2}

Hook over the base character.

@item @code{9}

Horn over the base character.
@end table

The most common characters from the Arabic, Cyrillic, Greek and Hebrew
alphabets are available; consult RFC 1345 for the appropriate sequences.
In addition, a set of two letter codes not in RFC 1345 are available for
the double-width characters corresponding to ASCII characters from @code{!}
to @code{~} (0x21 to 0x7e) by preceding the character with @code{^}, for
example @code{^A} for a double-width @code{A}.

The following other two-character sequences are understood.

ASCII characters

@quotation

These are already present on most keyboards:


@table @asis

@item @code{<(}

Left square bracket

@item @code{//}

Backslash (solidus)

@item @code{)>}

Right square bracket

@item @code{(!}

Left brace (curly bracket)

@item @code{!!}

Vertical bar (pipe symbol)

@item @code{!)}

Right brace (curly bracket)

@item @code{'?}

Tilde
@end table
@end quotation

Special letters

@quotation

Characters found in various variants of the Latin alphabet:


@table @asis

@item @code{ss}

Eszett (scharfes S)

@item @code{D-}, @code{d-}

Eth

@item @code{TH}, @code{th}

Thorn

@item @code{kk}

Kra

@item @code{'n}

‘n

@item @code{NG}, @code{ng}

Ng

@item @code{OI}, @code{oi}

Oi

@item @code{yr}

yr

@item @code{ED}

ezh
@end table
@end quotation

Currency symbols

@quotation


@table @asis

@item @code{Ct}

Cent

@item @code{Pd}

Pound sterling (also lira and others)

@item @code{Cu}

Currency

@item @code{Ye}

Yen

@item @code{Eu}

Euro (N.B. not in RFC 1345)
@end table
@end quotation

Punctuation characters

@quotation

References to “right” quotes indicate the shape (like a 9 rather than 6)
rather than their grammatical use.  (For example, a “right” low double
quote is used to open quotations in German.)


@table @asis

@item @code{!I}

Inverted exclamation mark

@item @code{BB}

Broken vertical bar

@item @code{SE}

Section

@item @code{Co}

Copyright

@item @code{-a}

Spanish feminine ordinal indicator

@item @code{<<}

Left guillemet

@item @code{--}

Soft hyphen

@item @code{Rg}

Registered trade mark

@item @code{PI}

Pilcrow (paragraph)

@item @code{-o}

Spanish masculine ordinal indicator

@item @code{>>}

Right guillemet

@item @code{?I}

Inverted question mark

@item @code{-1}

Hyphen

@item @code{-N}

En dash

@item @code{-M}

Em dash

@item @code{-3}

Horizontal bar

@item @code{:3}

Vertical ellipsis

@item @code{.3}

Horizontal midline ellipsis

@item @code{!2}

Double vertical line

@item @code{=2}

Double low line

@item @code{'6}

Left single quote

@item @code{'9}

Right single quote

@item @code{.9}

“Right” low quote

@item @code{9'}

Reversed “right” quote

@item @code{"6}

Left double quote

@item @code{"9}

Right double quote

@item @code{:9}

“Right” low double quote

@item @code{9"}

Reversed “right” double quote

@item @code{/-}

Dagger

@item @code{/=}

Double dagger
@end table
@end quotation

Mathematical symbols

@quotation


@table @asis

@item @code{DG}

Degree

@item @code{-2}, @code{+-}, @code{-+}


@itemize -

@item 
sign, +/- sign, -/+ sign
@end itemize

@item @code{2S}

Superscript 2

@item @code{3S}

Superscript 3

@item @code{1S}

Superscript 1

@item @code{My}

Micro

@item @code{.M}

Middle dot

@item @code{14}

Quarter

@item @code{12}

Half

@item @code{34}

Three quarters

@item @code{*X}

Multiplication

@item @code{-:}

Division

@item @code{%0}

Per mille

@item @code{FA}, @code{TE}, @code{/0}

For all, there exists, empty set

@item @code{dP}, @code{DE}, @code{NB}

Partial derivative, delta (increment), del
(nabla)

@item @code{(-}, @code{-)}

Element of, contains

@item @code{*P}, @code{+Z}

Product, sum

@item @code{*-}, @code{Ob}, @code{Sb}

Asterisk, ring, bullet

@item @code{RT}, @code{0(}, @code{00}

Root sign, proportional to, infinity
@end table
@end quotation

Other symbols

@quotation


@table @asis

@item @code{cS}, @code{cH}, @code{cD}, @code{cC}

Card suits: spades, hearts, diamonds,
clubs

@item @code{Md}, @code{M8}, @code{M2}, @code{Mb}, @code{Mx}, @code{MX}

Musical notation:
crotchet (quarter note), quaver (eighth note), semiquavers (sixteenth
notes), flag sign, natural sign, sharp sign

@item @code{Fm}, @code{Ml}

Female, male
@end table
@end quotation

Accents on their own

@quotation


@table @asis

@item @code{'>}

Circumflex (same as caret, @code{^})

@item @code{'!}

Grave (same as backtick, >>`@w{`}<<>>`@w{`}<<)

@item @code{',}

Cedilla

@item @code{':}

Diaeresis (Umlaut)

@item @code{'m}

Macron

@item @code{'@w{'}}

Acute
@end table
@end quotation
@end quotation

@geindex insert-files; Type

@code{insert-files}

@quotation

This function allows you type a file pattern, and see the results of the
expansion at each step.  When you hit return, all expansions are inserted
into the command line.

@example
 bindkey ^Xf' insert-files
@end example
@end quotation

@geindex insert-unicode-char; Type

@code{insert-unicode-char}

@quotation

When first executed, the user inputs a set of hexadecimal digits.
This is terminated with another call to @code{insert-unicode-char}.
The digits are then turned into the corresponding Unicode character.
For example, if the widget is bound to @code{^XU}, the character sequence
@code{^XU 4 c ^XU} inserts @code{L} (Unicode U+004c).

See @code{insert-composed-char} for a way of inserting characters
using a two-character mnemonic.
@end quotation

@geindex narrow-to-region; Type

@geindex narrow-to-region-invisible; Type

@code{narrow-to-region} [ @code{-p} @var{pre} ] [ @code{-P} @var{post} ]

@quotation

[ @code{-S} @var{statepm} | @code{-R} @var{statepm} | [ @code{-l} @var{lbufvar} ] [ @code{-r} @var{rbufvar} ] ]

[ @code{-n} ] [ @var{start} @var{end} ]
@end quotation

@code{narrow-to-region-invisible}

@quotation

Narrow the editable portion of the buffer to the region between the cursor
and the mark, which may be in either order.  The region may not be empty.

@code{narrow-to-region} may be used as a widget or called as a function from a
user-defined widget; by default, the text outside the editable area remains
visible.  A @code{recursive-edit} is performed and the original widening
status is then restored.  Various options and arguments are available when
it is called as a function.

The options @code{-p} @var{pretext} and @code{-P} @var{posttext} may be
used to replace the text before and after the display for the duration of
the function; either or both may be an empty string.

If the option @code{-n} is also given, @var{pretext} or @var{posttext} will only
be inserted if there is text before or after the region respectively which
will be made invisible.

Two numeric arguments may be given which will be used instead of the cursor
and mark positions.

The option @code{-S} @var{statepm} is used to narrow according to the other
options while saving the original state in the parameter with name
@var{statepm}, while the option @code{-R} @var{statepm} is used to restore the
state from the parameter; note in both cases the `name' of the parameter
is required.  In the second case, other options and arguments are
irrelevant.  When this method is used, no @code{recursive-edit} is performed;
the calling widget should call this function with the option @code{-S},
perform its own editing on the command line or pass control to the user
via @code{zle recursive-edit}, then call this function with the option
@code{-R}.  The argument @var{statepm} must be a suitable name for an ordinary
parameter, except that parameters beginning with the prefix @code{_ntr_} are
reserved for use within @code{narrow-to-region}.  Typically the parameter will
be local to the calling function.

The options @code{-l} @var{lbufvar} and @code{-r} @var{rbufvar} may be used to
specify parameters where the widget will store the resulting text from
the operation.  The parameter @var{lbufvar} will contain @code{LBUFFER}
and @var{rbufvar} will contain @code{RBUFFER}.  Neither of these two options
may be used with @code{-S} or @code{-R}.

@code{narrow-to-region-invisible} is a simple widget which calls
@code{narrow-to-region} with arguments which replace any text outside the
region with @code{...}.  It does not take any arguments.

The display is restored (and the widget returns) upon any zle command
which would usually cause the line to be accepted or aborted.  Hence an
additional such command is required to accept or abort the current line.

The return status of both widgets is zero if the line was accepted, else
non-zero.

Here is a trivial example of a widget using this feature.

@example
 local state
 narrow-to-region -p $'Editing restricted region\n' \
   -P '@w{'} -S state
 zle recursive-edit
 narrow-to-region -R state
@end example
@end quotation

@geindex predict-on; Type

@geindex predict-off; Type

@code{predict-on}

@quotation

This set of functions implements predictive typing using history search.
After @code{predict-on}, typing characters causes the editor to look backward
in the history for the first line beginning with what you have typed so
far.  After @code{predict-off}, editing returns to normal for the line found.
In fact, you often don’t even need to use @code{predict-off}, because if the
line doesn’t match something in the history, adding a key performs
standard completion, and then inserts itself if no completions were found.
However, editing in the middle of a line is liable to confuse prediction;
see the @code{toggle} style below.

With the function based completion system (which is needed for this), you
should be able to type @code{TAB} at almost any point to advance the cursor
to the next >>`<<`interesting’’ character position (usually the end of the
current word, but sometimes somewhere in the middle of the word).  And of
course as soon as the entire line is what you want, you can accept with
return, without needing to move the cursor to the end first.

The first time @code{predict-on} is used, it creates several additional
widget functions:


@table @asis

@item @code{delete-backward-and-predict}

Replaces the @code{backward-delete-char}
widget.  You do not need to bind this yourself.

@item @code{insert-and-predict}

Implements predictive typing by replacing the
@code{self-insert} widget.  You do not need to bind this yourself.

@item @code{predict-off}

Turns off predictive typing.
@end table

Although you @code{autoload} only the @code{predict-on} function, it is
necessary to create a keybinding for @code{predict-off} as well.

@example
 zle -N predict-on
 zle -N predict-off
 bindkey '^X^Z' predict-on
 bindkey '^Z' predict-off
@end example
@end quotation

@geindex read-from-minibuffer; Type

@code{read-from-minibuffer}

@quotation

This is most useful when called as a function from inside a widget, but will
work correctly as a widget in its own right.  It prompts for a value
below the current command line; a value may be input using all of the
standard zle operations (and not merely the restricted set available
when executing, for example, @code{execute-named-cmd}).  The value is then
returned to the calling function in the parameter @code{$REPLY} and the
editing buffer restored to its previous state.  If the read was aborted
by a keyboard break (typically @code{^G}), the function returns status 1
and @code{$REPLY} is not set.

If one argument is supplied to the function it is taken as a prompt,
otherwise @code{?}  is used.  If two arguments are supplied, they are the
prompt and the initial value of @code{$LBUFFER}, and if a third argument is
given it is the initial value of @code{$RBUFFER}.  This provides a default
value and starting cursor placement.  Upon return the entire buffer is the
value of @code{$REPLY}.

One option is available: @code{-k} @var{num} specifies that @var{num}
characters are to be read instead of a whole line.  The line editor is not
invoked recursively in this case, so depending on the terminal settings
the input may not be visible, and only the input keys are placed in
@code{$REPLY}, not the entire buffer.  Note that unlike the @code{read} builtin
@var{num} must be given; there is no default.

The name is a slight misnomer, as in fact the shell’s own minibuffer is
not used.  Hence it is still possible to call @code{executed-named-cmd} and
similar functions while reading a value.
@end quotation

@geindex replace-argument; Type

@geindex replace-argument-edit; Type

@code{replace-argument}, @code{replace-argument-edit}

@quotation

The function @code{replace-argument} can be used to replace a command
line argument in the current command line or, if the current command
line is empty, in the last command line executed (the new command line
is not executed).  Arguments are as delimited by standard shell syntax,

If a numeric argument is given, that specifies the argument to be
replaced.  0 means the command name, as in history expansion.
A negative numeric argument counts backward from the last word.

If no numeric argument is given, the current argument is replaced;
this is the last argument if the previous history line is being used.

The function prompts for a replacement argument.

If the widget contains the string @code{edit}, for example is defined as

@example
 zle -N replace-argument-edit replace-argument
@end example

then the function presents the current value of the argument for
editing, otherwise the editing buffer for the replacement is
initially empty.
@end quotation

@geindex replace-string; Type

@geindex replace-string-again; Type

@geindex replace-pattern; Type

@code{replace-string}, @code{replace-pattern}

@code{replace-string-again}, @code{replace-pattern-again}

@quotation

The function @code{replace-string} implements three widgets.
If defined under the same name as the function, it prompts for two
strings; the first (source) string will be replaced by the second
everywhere it occurs in the line editing buffer.

If the widget name contains the word @code{pattern}, for example by
defining the widget using the command @code{zle -N replace-pattern
replace-string}, then the matching is performed using zsh patterns.  All
zsh extended globbing patterns can be used in the source string; note
that unlike filename generation the pattern does not need to match an
entire word, nor do glob qualifiers have any effect.  In addition, the
replacement string can contain parameter or command substitutions.
Furthermore, a @code{&} in the replacement string will be replaced with
the matched source string, and a backquoted digit @code{\}@var{N} will be
replaced by the @var{N}th parenthesised expression matched.  The form
@code{\@{}@var{N}@code{@}} may be used to protect the digit from following
digits.

If the widget instead contains the word @code{regex} (or @code{regexp}),
then the matching is performed using regular expressions, respecting
the setting of the option @code{RE_MATCH_PCRE} (see the description of the
function @code{regexp-replace} below).  The special replacement facilities
described above for pattern matching are available.

By default the previous source or replacement string will not be offered
for editing.  However, this feature can be activated by setting the style
@code{edit-previous} in the context @code{:zle:}@var{widget} (for example,
@code{:zle:replace-string}) to @code{true}.  In addition, a positive
numeric argument forces the previous values to be offered, a negative or
zero argument forces them not to be.

The function @code{replace-string-again} can be used to repeat the previous
replacement; no prompting is done.  As with @code{replace-string}, if the name
of the widget contains the word @code{pattern} or @code{regex}, pattern or
regular expression matching is performed, else a literal string
replacement.  Note that the previous source and replacement text are the
same whether pattern, regular expression or string matching is used.

In addition, @code{replace-string} shows the previous replacement above
the prompt, so long as there was one during the current session; if the
source string is empty, that replacement will be repeated without
the widget prompting for a replacement string.

For example, starting from the line:

@example
 print This line contains fan and fond
@end example

and invoking @code{replace-pattern} with the source string
@code{f(?)n} and
the replacement string @code{c\1r} produces the not very useful line:

@example
 print This line contains car and cord
@end example

The range of the replacement string can be limited by using the
@code{narrow-to-region-invisible} widget.  One limitation of the current
version is that @code{undo} will cycle through changes to the replacement
and source strings before undoing the replacement itself.
@end quotation

@geindex send-invisible; Type

@code{send-invisible}

@quotation

This is similar to read-from-minibuffer in that it may be called as a
function from a widget or as a widget of its own, and interactively reads
input from the keyboard.  However, the input being typed is concealed and
a string of asterisks (@code{*}) is shown instead.  The value is saved in
the parameter @code{$INVISIBLE} to which a reference is inserted into the
editing buffer at the restored cursor position.  If the read was aborted
by a keyboard break (typically @code{^G}) or another escape from editing such
as @code{push-line}, @code{$INVISIBLE} is set to empty and the original buffer
is restored unchanged.

If one argument is supplied to the function it is taken as a prompt,
otherwise @code{Non-echoed text:}  is used (as in emacs).  If a second and
third argument are supplied they are used to begin and end the reference
to @code{$INVISIBLE} that is inserted into the buffer.  The default is to
open with @code{$@{}, then @code{INVISIBLE}, and close with @code{@}}, but many
other effects are possible.
@end quotation

@geindex smart-insert-last-word; Type

@code{smart-insert-last-word}

@quotation

This function may replace the @code{insert-last-word} widget, like so:

@example
 zle -N insert-last-word smart-insert-last-word
@end example

With a numeric argument, or when passed command line arguments in a call
from another widget, it behaves like @code{insert-last-word}, except that
words in comments are ignored when @code{INTERACTIVE_COMMENTS} is set.

Otherwise, the rightmost @cite{`interesting’’ word from the previous command is found and inserted. The default definition of `@w{`}interesting’’ is that the word contains at least one alphabetic character@comma{} slash@comma{} or backslash. This definition may be overridden by use of the `@w{`}match`} style.  The
context used to look up the style is the widget name, so usually the
context is @code{:insert-last-word}.  However, you can bind this function to
different widgets to use different patterns:

@example
 zle -N insert-last-assignment smart-insert-last-word
 zstyle :insert-last-assignment match '[[:alpha:]][][[:alnum:]]#=*'
 bindkey '\e=' insert-last-assignment
@end example

If no interesting word is found and the @code{auto-previous} style is set to
a true value, the search continues upward through the history.  When
@code{auto-previous} is unset or false (the default), the widget must be
invoked repeatedly in order to search earlier history lines.
@end quotation

@geindex transpose-lines; Type

@code{transpose-lines}

@quotation

Only useful with a multi-line editing buffer; the lines here are
lines within the current on-screen buffer, not history lines.
The effect is similar to the function of the same name in Emacs.

Transpose the current line with the previous line and move the cursor
to the start of the next line.  Repeating this (which can be done by
providing a positive numeric argument) has the effect of moving
the line above the cursor down by a number of lines.

With a negative numeric argument, requires two lines above the
cursor.  These two lines are transposed and the cursor moved to the
start of the previous line.  Using a numeric argument less than -1
has the effect of moving the line above the cursor up by minus that
number of lines.
@end quotation

@geindex url-quote-magic; Type

@code{url-quote-magic}

@quotation

This widget replaces the built-in @code{self-insert} to make it easier to
type URLs as command line arguments.  As you type, the input character is
analyzed and, if it may need quoting, the current word is checked for a
URI scheme.  If one is found and the current word is not already in
quotes, a backslash is inserted before the input character.

Styles to control quoting behavior:

@code{url-metas}

@quotation

This style is looked up in the context @code{:url-quote-magic:}@var{scheme}
(where @var{scheme} is that of the current URL, e.g. “@code{ftp}”).  The value
is a string listing the characters to be treated as globbing
metacharacters when appearing in a URL using that scheme.  The default is
to quote all zsh extended globbing characters, excluding ‘@code{<}’ and
‘@code{>}’ but including braces (as in brace expansion).  See also
@code{url-seps}.
@end quotation

@code{url-seps}

@quotation

Like @code{url-metas}, but lists characters that should be considered command
separators, redirections, history references, etc.  The default is to
quote the standard set of shell separators, excluding those that overlap
with the extended globbing characters, but including ‘@code{<}’ and
‘@code{>}’ and the first character of @code{$histchars}.
@end quotation

@code{url-globbers}

@quotation

This style is looked up in the context @code{:url-quote-magic}.  The values
form a list of command names that are expected to do their own globbing
on the URL string.  This implies that they are aliased to use the
@code{noglob} modifier.  When the first word on the line matches one of the
values `and' the URL refers to a local file (see @code{url-local-schema}),
only the @code{url-seps} characters are quoted; the @code{url-metas} are left
alone, allowing them to affect command-line parsing, completion, etc.  The
default values are a literal @code{noglob} plus (when the @code{zsh/parameter}
module is available) any commands aliased to the helper function
@code{urlglobber} or its alias @code{globurl}.
@end quotation

@code{url-local-schema}

@quotation

This style is always looked up in the context @code{:urlglobber}, even
though it is used by both url-quote-magic and urlglobber.  The values form
a list of URI schema that should be treated as referring to local files by
their real local path names, as opposed to files which are specified
relative to a web-server-defined document root.  The defaults are
“@code{ftp}” and “@code{file}”.
@end quotation

@code{url-other-schema}

@quotation

Like @code{url-local-schema}, but lists all other URI schema upon which
@code{urlglobber} and @code{url-quote-magic} should act.  If the URI on the
command line does not have a scheme appearing either in this list or in
@code{url-local-schema}, it is not magically quoted.  The default values are
“@code{http}”, “@code{https}”, and “@code{ftp}”.  When a scheme appears both here
and in @code{url-local-schema}, it is quoted differently depending on whether
the command name appears in @code{url-globbers}.
@end quotation

Loading @code{url-quote-magic} also defines a helper function @code{urlglobber}
and aliases @code{globurl} to @code{noglob urlglobber}.  This function takes
a local URL apart, attempts to pattern-match the local file portion of the
URL path, and then puts the results back into URL format again.
@end quotation

@geindex vi-pipe; Type

@code{vi-pipe}

@quotation

This function reads a movement command from the keyboard and then
prompts for an external command. The part of the buffer covered by
the movement is piped to the external command and then replaced by
the command’s output. If the movement command is bound to vi-pipe,
the current line is used.

The function serves as an example for reading a vi movement command
from within a user-defined widget.
@end quotation

@geindex which-command; Type

@code{which-command}

@quotation

This function is a drop-in replacement for the builtin widget
@code{which-command}.  It has enhanced behaviour, in that it correctly
detects whether or not the command word needs to be expanded as an
alias; if so, it continues tracing the command word from the expanded
alias until it reaches the command that will be executed.

The style @code{whence} is available in the context @code{:zle:$WIDGET}; this
may be set to an array to give the command and options that will be used to
investigate the command word found.  The default is @code{whence -c}.
@end quotation

@geindex zcalc-auto-insert; Type

@code{zcalc-auto-insert}

@quotation

This function is useful together with the @code{zcalc} function described in
@ref{140,,Mathematical Functions}.
It should be bound to a key representing a binary operator such
as @code{+}, @code{-}, @code{*} or @code{/}.  When running in zcalc,
if the key occurs at the start of the line or immediately following
an open parenthesis, the text @code{"ans "} is inserted before the
representation of the key itself.  This allows easy use of the
answer from the previous calculation in the current line.  The
text to be inserted before the symbol typed can be modified by setting
the variable @code{ZCALC_AUTO_INSERT_PREFIX}.

Hence, for example, typing @code{+12} followed by return adds 12
to the previous result.

If zcalc is in RPN mode (@code{-r} option) the effect of this binding is
automatically suppressed as operators alone on a line are meaningful.

When not in zcalc, the key simply inserts the symbol itself.
@end quotation

@node Utility Functions<2>,Styles<2>,Widgets,ZLE Functions
@anchor{Zsh/contrib utility-functions}@anchor{1c2}
@subsection Utility Functions


These functions are useful in constructing widgets.  They
should be loaded with @code{autoload -U} @var{function} and called
as indicated from user-defined widgets.

@geindex split-shell-arguments; Type

@code{split-shell-arguments}

@quotation

This function splits the line currently being edited into shell arguments
and whitespace.  The result is stored in the array @code{reply}.  The array
contains all the parts of the line in order, starting with any whitespace
before the first argument, and finishing with any whitespace after the last
argument.  Hence (so long as the option @code{KSH_ARRAYS} is not set)
whitespace is given by odd indices in the array and arguments by
even indices.  Note that no stripping of quotes is done; joining together
all the elements of @code{reply} in order is guaranteed to produce the
original line.

The parameter @code{REPLY} is set to the index of the word in @code{reply} which
contains the character after the cursor, where the first element has index
1.  The parameter @code{REPLY2} is set to the index of the character under the
cursor in that word, where the first character has index 1.

Hence @code{reply}, @code{REPLY} and @code{REPLY2} should all be made local to
the enclosing function.

See the function @code{modify-current-argument}, described below, for
an example of how to call this function.
@end quotation

@geindex modify-current-argument; Type

@code{modify-current-argument} [ @var{expr-using-}@code{$ARG} | @var{func} ]

@quotation

This function provides a simple method of allowing user-defined widgets
to modify the command line argument under the cursor (or immediately to the
left of the cursor if the cursor is between arguments).

The argument can be an expression which when evaluated operates on the shell
parameter @code{ARG}, which will have been set to the command line argument
under the cursor.  The expression should be suitably quoted to prevent
it being evaluated too early.

Alternatively, if the argument does not contain the string @code{ARG}, it
is assumed to be a shell function, to which the current command line
argument is passed as the only argument.  The function should set the
variable @code{REPLY} to the new value for the command line argument.
If the function returns non-zero status, so does the calling function.

For example, a user-defined widget containing the following code
converts the characters in the argument under the cursor into all upper
case:

@example
 modify-current-argument '$@{(U)ARG@}'
@end example

The following strips any quoting from the current word (whether backslashes
or one of the styles of quotes), and replaces it with single quoting
throughout:

@example
 modify-current-argument '$@{(qq)$@{(Q)ARG@}@}'
@end example

The following performs directory expansion on the command line
argument and replaces it by the absolute path:

@example
 expand-dir() @{
   REPLY=$@{~1@}
   REPLY=$@{REPLY:a@}
 @}
 modify-current-argument expand-dir
@end example

In practice the function @code{expand-dir} would probably not be defined
within the widget where @code{modify-current-argument} is called.
@end quotation

@node Styles<2>,,Utility Functions<2>,ZLE Functions
@anchor{Zsh/contrib styles}@anchor{1c3}
@subsection Styles


The behavior of several of the above widgets can be controlled by the use
of the @code{zstyle} mechanism.  In particular, widgets that interact with
the completion system pass along their context to any completions that
they invoke.

@geindex break-keys@comma{} widget style; Keystroke

@code{break-keys}

@quotation

This style is used by the @code{incremental-complete-word} widget. Its value
should be a pattern, and all keys matching this pattern will cause the
widget to stop incremental completion without the key having any further
effect. Like all styles used directly by
@code{incremental-complete-word}, this style is looked up using the
context @code{:incremental}.
@end quotation

@geindex completer@comma{} completion style; Keystroke

@code{completer}

@quotation

The @code{incremental-complete-word} and @code{insert-and-predict} widgets set
up their top-level context name before calling completion.  This allows
one to define different sets of completer functions for normal completion
and for these widgets.  For example, to use completion, approximation and
correction for normal completion, completion and correction for
incremental completion and only completion for prediction one could use:

@example
 zstyle ':completion:*' completer \
         _complete _correct _approximate
 zstyle ':completion:incremental:*' completer \
         _complete _correct
 zstyle ':completion:predict:*' completer \
         _complete
@end example

It is a good idea to restrict the completers used in prediction, because
they may be automatically invoked as you type.  The @code{_list} and
@code{_menu} completers should never be used with prediction.  The
@code{_approximate}, @code{_correct}, @code{_expand}, and @code{_match} completers may
be used, but be aware that they may change characters anywhere in the word
behind the cursor, so you need to watch carefully that the result is what
you intended.
@end quotation

@geindex cursor@comma{} completion style; Keystroke

@code{cursor}

@quotation

The @code{insert-and-predict} widget uses this style, in the context
@code{:predict}, to decide where to place the cursor after completion has
been tried.  Values are:

@code{complete}

@quotation

The cursor is left where it was when completion finished, but only if
it is after a character equal to the one just inserted by the user.  If
it is after another character, this value is the same as @code{key}.
@end quotation

@code{key}

@quotation

The cursor is left
after the @var{n}th occurrence of the character just inserted, where
@var{n} is the number of times that character appeared in the word
before completion was attempted.  In short, this has the effect of
leaving the cursor after the character just typed even if the
completion code found out that no other characters need to be inserted
at that position.
@end quotation

Any other value for this style unconditionally leaves the cursor at the
position where the completion code left it.
@end quotation

@geindex list@comma{} widget style; Keystroke

@code{list}

@quotation

When using the @code{incremental-complete-word} widget, this style says
if the matches should be listed on every key press (if they fit on the
screen).  Use the context prefix @code{:completion:incremental}.

The @code{insert-and-predict} widget uses this style to decide if the
completion should be shown even if there is only one possible completion.
This is done if the value of this style is the string @code{always}.  In this
case the context is @code{:predict} (`not' @code{:completion:predict}).
@end quotation

@geindex match@comma{} widget style; Keystroke

@code{match}

@quotation

This style is used by @code{smart-insert-last-word} to provide a pattern
(using full @code{EXTENDED_GLOB} syntax) that matches an interesting word.
The context is the name of the widget to which @code{smart-insert-last-word}
is bound (see above).  The default behavior of @code{smart-insert-last-word}
is equivalent to:

@example
 zstyle :insert-last-word match '*[[:alpha:]/\\]*'
@end example

However, you might want to include words that contain spaces:

@example
 zstyle :insert-last-word match '*[[:alpha:][:space:]/\\]*'
@end example

Or include numbers as long as the word is at least two characters long:

@example
 zstyle :insert-last-word match '*([[:digit:]]?|[[:alpha:]/\\])*'
@end example

The above example causes redirections like “2>” to be included.
@end quotation

@geindex prompt@comma{} widget style; Keystroke

@code{prompt}

@quotation

The @code{incremental-complete-word} widget shows the value of this
style in the status line during incremental completion.  The string
value may contain any of the following substrings in the manner of
the @code{PS1} and other prompt parameters:

@code{%c}

@quotation

Replaced by the name of the completer function that generated the
matches (without the leading underscore).
@end quotation

@code{%l}

@quotation

When the @code{list} style is set,
replaced by @code{...} if the list of matches is too long to fit on the
screen and with an empty string otherwise.  If the @code{list} style is
`false’ or not set, @code{%l} is always removed.
@end quotation

@code{%n}

@quotation

Replaced by the number of matches generated.
@end quotation

@code{%s}

@quotation

Replaced by @code{-no match-}, @code{-no prefix-}, or an empty string
if there is no completion matching the word on the line, if the
matches have no common prefix different from the word on the line, or
if there is such a common prefix, respectively.
@end quotation

@code{%u}

@quotation

Replaced by the unambiguous part of all matches, if there
is any, and if it is different from the word on the line.
@end quotation

Like @code{break-keys}, this uses the @code{:incremental} context.
@end quotation

@geindex stop-keys@comma{} widget style; Keystroke

@code{stop-keys}

@quotation

This style is used by the @code{incremental-complete-word} widget.  Its value
is treated similarly to the one for the @code{break-keys} style (and uses
the same context: @code{:incremental}).  However, in
this case all keys matching the pattern given as its value will stop
incremental completion and will then execute their usual function.
@end quotation

@geindex toggle@comma{} widget style; Keystroke

@code{toggle}

@quotation

This boolean style is used by @code{predict-on} and its related widgets in
the context @code{:predict}.  If set to one of the standard `true’ values,
predictive typing is automatically toggled off in situations where it is
unlikely to be useful, such as when editing a multi-line buffer or after
moving into the middle of a line and then deleting a character.  The
default is to leave prediction turned on until an explicit call to
@code{predict-off}.
@end quotation

@geindex verbose@comma{} widget style; Keystroke

@code{verbose}

@quotation

This boolean style is used by @code{predict-on} and its related widgets in
the context @code{:predict}.  If set to one of the standard `true’ values,
these widgets display a message below the prompt when the predictive state
is toggled.  This is most useful in combination with the @code{toggle} style.
The default does not display these messages.
@end quotation

@geindex widget@comma{} widget style; Keystroke

@code{widget}

@quotation

This style is similar to the @code{command} style: For widget functions that
use @code{zle} to call other widgets, this style can sometimes be used to
override the widget which is called.  The context for this style is the
name of the calling widget (`not' the name of the calling function,
because one function may be bound to multiple widget names).

@example
 zstyle :copy-earlier-word widget smart-insert-last-word
@end example

Check the documentation for the calling widget or function to determine
whether the @code{widget} style is used.
@end quotation

@c historic nodename: Exception Handling

@node Exception Handling,MIME Functions,ZLE Functions,User Contributions
@anchor{Zsh/contrib exception-handling}@anchor{1c4}
@section Exception Handling


Two functions are provided to enable zsh to provide exception handling in a
form that should be familiar from other languages.

@geindex throw; Function

@code{throw} @var{exception}

@quotation

The function @code{throw} throws the named @var{exception}.  The name is
an arbitrary string and is only used by the @code{throw} and @code{catch}
functions.  An exception is for the most part treated the same as a
shell error, i.e. an unhandled exception will cause the shell to abort all
processing in a function or script and to return to the top level in an
interactive shell.
@end quotation

@code{catch} @var{exception-pattern}

@quotation

The function @code{catch} returns status zero if an exception was thrown and
the pattern @var{exception-pattern} matches its name.  Otherwise it
returns status 1.  @var{exception-pattern} is a standard
shell pattern, respecting the current setting of the @code{EXTENDED_GLOB}
option.  An alias @code{catch} is also defined to prevent the argument to the
function from matching filenames, so patterns may be used unquoted.  Note
that as exceptions are not fundamentally different from other shell errors
it is possible to catch shell errors by using an empty string as the
exception name.  The shell variable @code{CAUGHT} is set by @code{catch} to the
name of the exception caught.  It is possible to rethrow an exception by
calling the @code{throw} function again once an exception has been caught.
.. index:: single: catch; Function
@end quotation

The functions are designed to be used together with the @code{always} construct
described in @ref{1c5,,Complex Commands}.
This is important as only this
construct provides the required support for exceptions.  A typical example
is as follows.

@example
 @{
   # "try" block
   # ... nested code here calls "throw MyExcept"
 @} always @{
   # "always" block
   if catch MyExcept; then
     print "Caught exception MyExcept"
   elif catch '@w{'}; then
     print "Caught a shell error.  Propagating..."
     throw '@w{'}
   fi
   # Other exceptions are not handled but may be caught further
   # up the call stack.
 @}
@end example

If all exceptions should be caught, the following idiom might be
preferable.

@example
 @{
   # ... nested code here throws an exception
 @} always @{
   if catch *; then
     case $CAUGHT in
       (MyExcept)
       print "Caught my own exception"
       ;;
       (*)
       print "Caught some other exception"
       ;;
     esac
   fi
 @}
@end example

In common with exception handling in other languages, the exception may be
thrown by code deeply nested inside the `try’ block.  However, note that it
must be thrown inside the current shell, not in a subshell forked for a
pipeline, parenthesised current-shell construct, or some form of
command or process substitution.

The system internally uses the shell variable @code{EXCEPTION} to record the
name of the exception between throwing and catching.  One drawback of this
scheme is that if the exception is not handled the variable @code{EXCEPTION}
remains set and may be incorrectly recognised as the name of an exception
if a shell error subsequently occurs.  Adding @code{unset EXCEPTION} at the
start of the outermost layer of any code that uses exception handling will
eliminate this problem.

@c historic nodename: MIME Functions

@node MIME Functions,Mathematical Functions,Exception Handling,User Contributions
@anchor{Zsh/contrib mime-functions}@anchor{1c6}
@section MIME Functions


Three functions are available to provide handling of files recognised by
extension, for example to dispatch a file @code{text.ps} when executed as a
command to an appropriate viewer.

@geindex zsh-mime-setup; Function

@geindex zsh-mime-handler; Function

@code{zsh-mime-setup} [ @code{-fv} ] [ @code{-l} [ @var{suffix} … ] ]

@code{zsh-mime-handler} [ @code{-l} ] @var{command argument} …

@quotation

These two functions use the files @code{~/.mime.types} and @code{/etc/mime.types},
which associate types and extensions, as well as @code{~/.mailcap} and
@code{/etc/mailcap} files, which associate types and the programs that
handle them.  These are provided on many systems with the Multimedia
Internet Mail Extensions.

To enable the system, the function @code{zsh-mime-setup} should be
autoloaded and run.  This allows files with extensions to be treated
as executable; such files be completed by the function completion system.
The function @code{zsh-mime-handler} should not need to be called by the
user.

The system works by setting up suffix aliases with @code{alias -s}.
Suffix aliases already installed by the user will not be overwritten.

For suffixes defined in lower case, upper case variants will also
automatically be handled (e.g. @code{PDF} is automatically handled if
handling for the suffix @code{pdf} is defined), but not vice versa.

Repeated calls to @code{zsh-mime-setup} do not override the existing
mapping between suffixes and executable files unless the option @code{-f}
is given.  Note, however, that this does not override existing suffix
aliases assigned to handlers other than @code{zsh-mime-handler}.

Calling @code{zsh-mime-setup} with the option @code{-l} lists the existing
mappings without altering them.  Suffixes to list (which may contain
pattern characters that should be quoted from immediate interpretation
on the command line) may be given as additional arguments, otherwise
all suffixes are listed.

Calling @code{zsh-mime-setup} with the option
@code{-v} causes verbose output to be shown during the setup operation.

The system respects the @code{mailcap} flags @code{needsterminal} and
@code{copiousoutput}; see @code{mailcap(4)} or @code{mailcap(5)}
(the man page’s name varies across platforms).

The functions use the following styles, which are defined with the
@code{zstyle} builtin command (@ref{ca,,The zsh/zutil Module}).
They should be defined
before @code{zsh-mime-setup} is run.  The contexts used all
start with @code{:mime:}, with additional components in some cases.
It is recommended that a trailing @code{*} (suitably quoted) be appended
to style patterns in case the system is extended in future.  Some
examples are given below.

For files that have multiple suffixes, e.g. @code{.pdf.gz}, where the
context includes the suffix it will be looked up starting with the
longest possible suffix until a match for the style is found.
For example, if @code{.pdf.gz} produces a match for the handler, that
will be used; otherwise the handler for @code{.gz} will be used.  Note
that, owing to the way suffix aliases work, it is always required that
there be a handler for the shortest possible suffix, so in this example
@code{.pdf.gz} can only be handled if @code{.gz} is also handled (though
not necessarily in the same way).  Alternatively, if no handling
for @code{.gz} on its own is needed, simply adding the command

@example
 alias -s gz=zsh-mime-handler
@end example

to the initialisation code is sufficient; @code{.gz} will not be handled
on its own, but may be in combination with other suffixes.

@geindex current-shell@comma{} MIME style; Keystroke

@code{current-shell}

@quotation

If this boolean style is true, the mailcap handler for the context in
question is run using the @code{eval} builtin instead of by starting a new
@code{sh} process.  This is more efficient, but may not work in the occasional
cases where the mailcap handler uses strict POSIX syntax.
@end quotation

@geindex disown@comma{} MIME style; Keystroke

@code{disown}

@quotation

If this boolean style is true, mailcap handlers started in the
background will be disowned, i.e. not subject to job control within
the parent shell.  Such handlers nearly always produce their own
windows, so the only likely harmful side effect of setting the style is
that it becomes harder to kill jobs from within the shell.
@end quotation

@geindex execute-as-is@comma{} MIME style; Keystroke

@code{execute-as-is}

@quotation

This style gives a list of patterns to be matched against files
passed for execution with a handler program.  If the file matches
the pattern, the entire command line is executed in its current form,
with no handler.  This is useful for files which might have suffixes
but nonetheless be executable in their own right.  If the style
is not set, the pattern @code{*(*) *(/)} is used;
hence executable files are executed directly and not passed to a
handler, and the option @code{AUTO_CD} may be used to change to directories
that happen to have MIME suffixes.
@end quotation

@geindex execute-never@comma{} MIME style; Keystroke

@code{execute-never}

@quotation

This style is useful in combination with @code{execute-as-is}.  It is
set to an array of patterns corresponding to full paths to files that
should never be treated as executable, even if the file passed to
the MIME handler matches @code{execute-as-is}.  This is useful for file
systems that don’t handle execute permission or that contain executables
from another operating system.  For example, if @code{/mnt/windows} is a
Windows mount, then

@example
 zstyle ':mime:*' execute-never '/mnt/windows/*'
@end example

will ensure that any files found in that area will be executed as MIME
types even if they are executable.  As this example shows, the complete
file name is matched against the pattern, regardless of how the file
was passed to the handler.  The file is resolved to a full path using
the @code{:P} modifier described in @ref{6b,,Modifiers};
this means that symbolic links are resolved where possible, so that
links into other file systems behave in the correct fashion.
@end quotation

@geindex file-path@comma{} MIME style; Keystroke

@code{file-path}

@quotation

Used if the style @code{find-file-in-path} is true for the same context.
Set to an array of directories that are used for searching for the
file to be handled; the default is the command path given by the
special parameter @code{path}.  The shell option @code{PATH_DIRS} is respected;
if that is set, the appropriate path will be searched even if the
name of the file to be handled as it appears on the command line contains
a @code{/}.
The full context is @code{:mime:.}@var{suffix}@code{:}, as described for the style
@code{handler}.
@end quotation

@geindex find-file-in-path@comma{} MIME style; Keystroke

@code{find-file-in-path}

@quotation

If set, allows files whose names do not contain absolute paths
to be searched for in the command path or the path specified by the
@code{file-path} style.  If the file is not found in the path, it is looked
for locally (whether or not the current directory is in the path); if it is
not found locally, the handler will abort unless the @code{handle-nonexistent}
style is set.  Files found in the path are tested as described for
the style @code{execute-as-is}.
The full context is @code{:mime:.}@var{suffix}@code{:}, as described for the style
@code{handler}.
@end quotation

@geindex flags@comma{} MIME style; Keystroke

@code{flags}

@quotation

Defines flags to go with a handler; the context is as for the
@code{handler} style, and the format is as for the flags in @code{mailcap}.
@end quotation

@geindex handle-nonexistent@comma{} MIME style; Keystroke

@code{handle-nonexistent}

@quotation

By default, arguments that don’t correspond to files are not passed
to the MIME handler in order to prevent it from intercepting commands found
in the path that happen to have suffixes.  This style may be set to
an array of extended glob patterns for arguments that will be passed to the
handler even if they don’t exist.  If it is not explicitly set it
defaults to @code{[[:alpha:]]#:/*} which allows URLs to be passed to the MIME
handler even though they don’t exist in that format in the file system.
The full context is @code{:mime:.}@var{suffix}@code{:}, as described for the style
@code{handler}.
@end quotation

@geindex handler@comma{} MIME style; Keystroke

@code{handler}

@quotation

Specifies a handler for a suffix; the suffix is given by the context as
@code{:mime:.}@var{suffix}@code{:}, and the format of the handler is exactly
that in @code{mailcap}.  Note in particular the @code{.} and trailing colon
to distinguish this use of the context.  This overrides any handler
specified by the @code{mailcap} files.  If the handler requires a terminal,
the @code{flags} style should be set to include the word @code{needsterminal},
or if the output is to be displayed through a pager (but not if the
handler is itself a pager), it should include @code{copiousoutput}.
@end quotation

@geindex mailcap@comma{} MIME style; Keystroke

@code{mailcap}

@quotation

A list of files in the format of @code{~/.mailcap} and
@code{/etc/mailcap} to be read during setup, replacing the default list
which consists of those two files.  The context is @code{:mime:}.
A @code{+} in the list will be replaced by the default files.
@end quotation

@geindex mailcap-priorities@comma{} MIME style; Keystroke

@code{mailcap-priorities}

@quotation

This style is used to resolve multiple mailcap entries for the same MIME
type.  It consists of an array of the following elements, in descending
order of priority; later entries will be used if earlier entries are
unable to resolve the entries being compared.  If none of the tests
resolve the entries, the first entry encountered is retained.

@code{files}

@quotation

The order of files (entries in the @code{mailcap} style) read.  Earlier
files are preferred.  (Note this does not resolve entries in the same file.)
@end quotation

@code{priority}

@quotation

The priority flag from the mailcap entry.  The priority is an integer
from 0 to 9 with the default value being 5.
@end quotation

@code{flags}

@quotation

The test given by the @code{mailcap-prio-flags} option is used to resolve
entries.
@end quotation

@code{place}

@quotation

Later entries are preferred; as the entries are strictly ordered, this
test always succeeds.
@end quotation

Note that as this style is handled during initialisation, the context
is always @code{:mime:}, with no discrimination by suffix.
@end quotation

@geindex mailcap-prio-flags@comma{} MIME style; Keystroke

@code{mailcap-prio-flags}

@quotation

This style is used when the keyword @code{flags} is encountered in the
list of tests specified by the @code{mailcap-priorities} style.
It should be set to a list of patterns, each of which is tested against
the flags specified in the mailcap entry (in other words, the sets of
assignments found with some entries in the mailcap file).  Earlier
patterns in the list are preferred to later ones, and matched patterns
are preferred to unmatched ones.
@end quotation

@geindex mime-types@comma{} MIME style; Keystroke

@code{mime-types}

@quotation

A list of files in the format of @code{~/.mime.types} and
@code{/etc/mime.types} to be read during setup, replacing the default list
which consists of those two files.  The context is @code{:mime:}.
A @code{+} in the list will be replaced by the default files.
@end quotation

@geindex never-background@comma{} MIME style; Keystroke

@code{never-background}

@quotation

If this boolean style is set, the handler for the given context is
always run in the foreground, even if the flags provided in the mailcap
entry suggest it need not be (for example, it doesn’t require a
terminal).
@end quotation

@geindex pager@comma{} MIME style; Keystroke

@code{pager}

@quotation

If set, will be used instead of @code{$PAGER} or @code{more} to handle
suffixes where the @code{copiousoutput} flag is set.  The context is
as for @code{handler}, i.e. @code{:mime:.}@var{suffix}@code{:} for handling
a file with the given @var{suffix}.
@end quotation

Examples:

@example
 zstyle ':mime:*' mailcap ~/.mailcap /usr/local/etc/mailcap
 zstyle ':mime:.txt:' handler less %s
 zstyle ':mime:.txt:' flags needsterminal
@end example

When @code{zsh-mime-setup} is subsequently run, it will look for
@code{mailcap} entries in the two files given.  Files of suffix @code{.txt}
will be handled by running @code{less} @var{file.txt}.  The flag
@code{needsterminal} is set to show that this program must run attached to a
terminal.

As there are several steps to dispatching a command, the following
should be checked if attempting to execute a file by extension
@code{.}@var{ext} does not have the expected effect.

The command @code{alias -s} @var{ext} should show
@code{ps=zsh-mime-handler}.  If it shows something else, another suffix
alias was already installed and was not overwritten.  If it shows
nothing, no handler was installed:  this is most likely because no
handler was found in the @code{.mime.types} and @code{mailcap} combination for
@code{.ext} files.  In that case, appropriate handling should be added to
@code{~/.mime.types} and @code{mailcap}.

If the extension is handled by @code{zsh-mime-handler} but the file is
not opened correctly, either the handler defined for the type is
incorrect, or the flags associated with it are in appropriate.  Running
@code{zsh-mime-setup -l} will show the handler and, if there are any, the
flags.  A @code{%s} in the handler is replaced by the file (suitably quoted
if necessary).  Check that the handler program listed lists and can
be run in the way shown.  Also check that the flags @code{needsterminal} or
@code{copiousoutput} are set if the handler needs to be run under a
terminal; the second flag is used if the output should be sent to a pager.
An example of a suitable @code{mailcap} entry for such a program is:

@example
 text/html; /usr/bin/lynx '%s'; needsterminal
@end example

Running @code{zsh-mime-handler -l} @var{command line} prints the command
line that would be executed, simplified to remove the effect of any
flags, and quoted so that the output can be run as a complete zsh
command line.  This is used by the completion system to decide how to
complete after a file handled by @code{zsh-mime-setup}.
@end quotation

@geindex pick-web-browser; Function

@code{pick-web-browser}

@quotation

This function is separate from the two MIME functions described above
and can be assigned directly to a suffix:

@example
 autoload -U pick-web-browser
 alias -s html=pick-web-browser
@end example

It is provided as an intelligent front end to dispatch a web browser.
It may be run as either a function or a shell script.  The status
255 is returned if no browser could be started.

Various styles are available to customize the choice of browsers:

@code{browser-style}

@quotation

The value of the style is an array giving preferences in decreasing order
for the type of browser to use.  The values of elements may be

@code{running}

@quotation

Use a GUI browser that is already running when an X Window display is
available.  The browsers listed in the @code{x-browsers} style are tried
in order until one is found; if it is, the file will be displayed in
that browser, so the user may need to check whether it has appeared.
If no running browser is found, one is not started.  Browsers other than
Firefox, Opera and Konqueror are assumed to understand the Mozilla
syntax for opening a URL remotely.
@end quotation

@code{x}

@quotation

Start a new GUI browser when an X Window display is available.  Search for
the availability of one of the browsers listed in the @code{x-browsers} style
and start the first one that is found.  No check is made for an already
running browser.
@end quotation

@code{tty}

@quotation

Start a terminal-based browser.  Search for the availability of one
of the browsers listed in the @code{tty-browsers} style and start the
first one that is found.
@end quotation

If the style is not set the default @code{running x tty} is used.
@end quotation

@code{x-browsers}

@quotation

An array in decreasing order
of preference of browsers to use when running under the X Window System.
The array consists of the command name under which to start the
browser.  They are looked up in the context @code{:mime:} (which may
be extended in future, so appending @code{*} is recommended).  For
example,

@example
 zstyle ':mime:*' x-browsers opera konqueror firefox
@end example

specifies that @code{pick-web-browser} should first look for a running
instance of Opera, Konqueror or Firefox, in that order, and if it
fails to find any should attempt to start Opera.  The default is
@code{firefox mozilla netscape opera konqueror}.
@end quotation

@code{tty-browsers}

@quotation

An array similar to @code{x-browsers}, except that it gives browsers to
use when no X Window display is available.  The default is
@code{elinks links lynx}.
@end quotation

@code{command}

@quotation

If it is set this style is used to pick the command
used to open a page for a browser.  The context is
@code{:mime:browser:new:$browser:} to start a new browser or
@code{:mime:browser:running:$browser:} to open a URL in a browser already
running on the current X display, where @code{$browser} is the value matched
in the @code{x-browsers} or @code{tty-browsers} style.  The escape sequence
@code{%b} in the style’s value will be replaced by the browser, while @code{%u}
will be replaced by the URL.  If the style is not set, the default for all
new instances is equivalent to @code{%b %u} and the defaults for using running
browsers are equivalent to the values @code{kfmclient openURL %u} for
Konqueror, @code{firefox -new-tab %u} for Firefox, @code{opera -newpage %u}
for Opera, and @code{%b -remote "openUrl(%u)"} for all others.
@end quotation
@end quotation

@c historic nodename: Mathematical Functions

@node Mathematical Functions,User Configuration Functions,MIME Functions,User Contributions
@anchor{Zsh/contrib mathematical-functions}@anchor{140}
@section Mathematical Functions


@geindex zcalc; Function

@code{zcalc} [ @code{-erf} ] [ @var{expression} … ]

@quotation

A reasonably powerful calculator based on zsh’s arithmetic evaluation
facility.  The syntax is similar to that of formulae in most programming
languages; see
@ref{1c7,,Arithmetic Evaluation} for details.

Non-programmers should note that, as in many other programming
languages, expressions involving only integers (whether constants
without a @code{.}, variables containing such constants as strings, or
variables declared to be integers) are by default evaluated using
integer arithmetic, which is not how an ordinary desk calculator
operates.  To force floating point operation, pass the option @code{-f};
see further notes below.

If the file @code{~/.zcalcrc} exists it will be sourced inside the function
once it is set up and about to process the command line.  This
can be used, for example, to set shell options; @code{emulate -L zsh}
and @code{setopt extendedglob} are in effect at this point.  Any
failure to source the file if it exists is treated as fatal.
As with other initialisation files, the directory @code{$ZDOTDIR} is used
instead of @code{$HOME} if it is set.

The mathematical library @code{zsh/mathfunc} will be loaded if it is
available; see
@ref{119,,The zsh/mathfunc Module}.  The mathematical functions
correspond to the raw system libraries, so trigonometric functions are
evaluated using radians, and so on.

Each line typed is evaluated as an expression.  The prompt shows a number,
which corresponds to a positional parameter where the result of that
calculation is stored.  For example, the result of the calculation on the
line preceded by @code{4>}  is available as @code{$4}.  The last value
calculated is available as @code{ans}.  Full command line editing, including
the history of previous calculations, is available; the history is saved in
the file @code{$ZCALC_HISTFILE}.  If @code{$ZCALC_HISTFILE} is unset,
@code{$ZDOTDIR/.zcalc_history} is used instead, which in turn falls backs to
@code{$HOME/.zcalc_history} if @code{$ZDOTDIR} is unset.  To exit, enter a blank
line or type @code{:q} on its own (@code{q} is allowed for historical
compatibility).

A line ending with a single backslash is treated in the same fashion
as it is in command line editing:  the backslash is removed, the
function prompts for more input (the prompt is preceded by @code{...}
to indicate this), and the lines are combined into one to get the final
result.  In addition, if the input so far contains more open than
close parentheses @code{zcalc} will prompt for more input.

If arguments are given to @code{zcalc} on start up, they are used to prime the
first few positional parameters.  A visual indication of this is given when
the calculator starts.

The constants @code{PI} (3.14159…) and @code{E} (2.71828…) are provided.
Parameter assignment is possible, but note that all parameters will be
put into the global namespace unless the @code{:local} special command is
used.  The function creates local variables whose names start with
@code{_}, so users should avoid doing so.  The variables @code{ans} (the last
answer) and @code{stack} (the stack in RPN mode) may be referred to
directly; @code{stack} is an array but elements of it are numeric.  Various
other special variables are used locally with their standard meaning,
for example @code{compcontext}, @code{match}, @code{mbegin}, @code{mend}, @code{psvar}.

The output base can be initialised by passing the option @code{-#}@var{base},
for example @code{zcalc -#16} (the @code{#} may have to be quoted, depending
on the globbing options set).

If the option @code{-e} is set, the function runs non-interactively:
the arguments are treated as expressions to be evaluated as if entered
interactively line by line.

If the option @code{-f} is set, all numbers are treated as floating
point, hence for example the expression @code{3/4} evaluates to 0.75
rather than 0.  Options must appear in separate words.

If the option @code{-r} is set, RPN (Reverse Polish Notation) mode is
entered.  This has various additional properties:

Stack

@quotation

Evaluated values are maintained in a stack; this is contained in
an array named @code{stack} with the most recent value in @code{$@{stack[1]@}}.
@end quotation

Operators and functions

@quotation

If the line entered matches an operator (@code{+}, @code{-}, @code{*},
@code{/}, @code{**}, @code{^}, @code{|} or @code{&}) or a function supplied by the
@code{zsh/mathfunc} library, the bottom element or elements of the stack
are popped to use as the argument or arguments.  The higher elements
of stack (least recent) are used as earlier arguments.  The result is
then pushed into @code{$@{stack[1]@}}.
@end quotation

Expressions

@quotation

Other expressions are evaluated normally, printed, and added to the
stack as numeric values.  The syntax within expressions on a single line
is normal shell arithmetic (not RPN).
@end quotation

Stack listing

@quotation

If an integer follows the option @code{-r} with no space, then
on every evaluation that many elements of the stack, where available,
are printed instead of just the most recent result.  Hence, for example,
@code{zcalc -r4} shows @code{$stack[4]} to @code{$stack[1]} each time results
are printed.
@end quotation

Duplication: @code{=}

@quotation

The pseudo-operator @code{=} causes the most recent element of
the stack to be duplicated onto the stack.
@end quotation

@code{pop}

@quotation

The pseudo-function @code{pop} causes the most recent element of
the stack to be popped.  A @code{>} on its own has the same effect.
@end quotation

@code{>}@var{ident}

@quotation

The expression @code{>} followed (with no space) by a shell identifier
causes the most recent element of the stack to be popped and
assigned to the variable with that name.  The variable is
local to the @code{zcalc} function.
@end quotation

@code{<}@var{ident}

@quotation

The expression @code{<} followed (with no space) by a shell identifier
causes the value of the variable with that name to be pushed
onto the stack.  @var{ident} may be an integer, in which
case the previous result with that number (as shown before
the @code{>} in the standard @code{zcalc} prompt) is put on the stack.
@end quotation

Exchange: @code{xy}

@quotation

The pseudo-function @code{xy} causes the most recent two elements of
the stack to be exchanged.  @code{<>} has the same effect.
@end quotation

The prompt is configurable via the parameter @code{ZCALCPROMPT}, which
undergoes standard prompt expansion.  The index of the current entry is
stored locally in the first element of the array @code{psvar}, which can be
referred to in @code{ZCALCPROMPT} as @code{%1v}.  The default prompt is
@code{%1v>} .

The variable @code{ZCALC_ACTIVE} is set within the function and can
be tested by nested functions; it has the value @code{rpn} if RPN mode is
active, else 1.

A few special commands are available; these are introduced by a colon.
For backward compatibility, the colon may be omitted for certain
commands.  Completion is available if @code{compinit} has been run.

The output precision may be specified within zcalc by special commands
familiar from many calculators.

@code{:norm}

@quotation

The default output format.  It corresponds to the printf @code{%g}
specification.  Typically this shows six decimal digits.
@end quotation

@code{:sci} @var{digits}

@quotation

Scientific notation, corresponding to the printf @code{%g} output format with
the precision given by @var{digits}.  This produces either fixed point or
exponential notation depending on the value output.
@end quotation

@code{:fix} @var{digits}

@quotation

Fixed point notation, corresponding to the printf @code{%f} output format with
the precision given by @var{digits}.
@end quotation

@code{:eng} @var{digits}

@quotation

Exponential notation, corresponding to the printf @code{%E} output format with
the precision given by @var{digits}.
@end quotation

@code{:raw}

@quotation

Raw output:  this is the default form of the output from a math
evaluation.  This may show more precision than the number actually
possesses.
@end quotation

Other special commands:

@code{:!}@var{line…}

@quotation

Execute @var{line…} as a normal shell command line.  Note that it
is executed in the context of the function, i.e. with local variables.
Space is optional after @code{:!}.
@end quotation

@code{:local} @var{arg} …

@quotation

Declare variables local to the function.  Other variables
may be used, too, but they will be taken from or put into the global
scope.
@end quotation

@code{:function} @var{name} [ @var{body} ]

@quotation

Define a mathematical function or (with no @var{body}) delete it.
@code{:function} may be abbreviated to @code{:func} or simply @code{:f}.
The @var{name} may contain the same characters as a shell function name.
The function is defined using @code{zmathfuncdef}, see below.

Note that @code{zcalc} takes care of all quoting.  Hence for example:

@example
 :f cube $1 * $1 * $1
@end example

defines a function to cube the sole argument.  Functions so defined, or
indeed any functions defined directly or indirectly using @code{functions
-M}, are available to execute by typing only the name on the line in RPN
mode; this pops the appropriate number of arguments off the stack
to pass to the function, i.e. 1 in the case of the example @code{cube}
function.  If there are optional arguments only the mandatory
arguments are supplied by this means.
@end quotation

@code{[#}@var{base}@code{]}

@quotation

This is not a special command, rather part of normal arithmetic
syntax; however, when this form appears on a line by itself the default
output radix is set to @var{base}.  Use, for example, @code{[#16]} to display
hexadecimal output preceded by an indication of the base, or @code{[##16]}
just to display the raw number in the given base.  Bases themselves are
always specified in decimal. @code{[#]} restores the normal output format.
Note that setting an output base suppresses floating point output; use
@code{[#]} to return to normal operation.
@end quotation

@code{$}@var{var}

@quotation

Print out the value of var literally; does not affect the calculation.
To use the value of var, omit the leading @code{$}.
@end quotation

See the comments in the function for a few extra tips.
@end quotation

@geindex max; Function

@geindex min; Function

@geindex sum; Function

@geindex zmathfunc; Function

@code{min(}@var{arg}@code{, ...)}

@code{max(}@var{arg}@code{, ...)}

@code{sum(}@var{arg}@code{, ...)}

@code{zmathfunc}

@quotation

The function @code{zmathfunc} defines the three mathematical functions
@code{min}, @code{max}, and @code{sum}.  The functions @code{min} and @code{max} take
one or more arguments.  The function @code{sum} takes zero or more arguments.
Arguments can be of different types (ints and floats).

Not to be confused with the @code{zsh/mathfunc} module, described in
@ref{119,,The zsh/mathfunc Module}.
@end quotation

@geindex zmathfuncdef; Function

@code{zmathfuncdef} [ @var{mathfunc} [ @var{body} ] ]

@quotation

A convenient front end to @code{functions -M}.

With two arguments, define a mathematical function named @var{mathfunc}
which can be used in any form of arithmetic evaluation.  @var{body}
is a mathematical expression to implement the function.  It may
contain references to position parameters @code{$1}, @code{$2}, …
to refer to mandatory parameters and @code{$@{1:-}@var{defvalue}@code{@}} …
to refer to optional parameters.  Note that the forms must be
strictly adhered to for the function to calculate the correct number
of arguments.  The implementation is held in a shell function named
@code{zsh_math_func_}@var{mathfunc}; usually the user will not need
to refer to the shell function directly.  Any existing function
of the same name is silently replaced.

With one argument, remove the mathematical function @var{mathfunc}
as well as the shell function implementation.

With no arguments, list all @var{mathfunc} functions in a form
suitable for restoring the definition.
The functions have not necessarily been defined by @code{zmathfuncdef}.
@end quotation

@c historic nodename: User Configuration Functions

@node User Configuration Functions,Other Functions<2>,Mathematical Functions,User Contributions
@anchor{Zsh/contrib user-configuration-functions}@anchor{f}
@section User Configuration Functions


The @code{zsh/newuser} module comes with a function to aid in configuring
shell options for new users.  If the module is installed, this function can
also be run by hand.  It is available even if the module’s default
behaviour, namely running the function for a new user logging in without
startup files, is inhibited.

@code{zsh-newuser-install} [ @code{-f} ]

@quotation

The function presents the user with various options for customizing
their initialization scripts.  Currently only @code{~/.zshrc} is handled.
@code{$ZDOTDIR/.zshrc} is used instead if the parameter @code{ZDOTDIR} is
set; this provides a way for the user to configure a file without
altering an existing @code{.zshrc}.

By default the function exits immediately if it finds any of the files
@code{.zshenv}, @code{.zprofile}, @code{.zshrc}, or @code{.zlogin} in the appropriate
directory.  The option @code{-f} is required in order to force the function
to continue.  Note this may happen even if @code{.zshrc} itself does not
exist.

As currently configured, the function will exit immediately if the
user has root privileges; this behaviour cannot be overridden.

Once activated, the function’s behaviour is supposed to be
self-explanatory.  Menus are present allowing the user to alter
the value of options and parameters.  Suggestions for improvements are
always welcome.

When the script exits, the user is given the opportunity to save the new
file or not; changes are not irreversible until this point.  However,
the script is careful to restrict changes to the file only to a group
marked by the lines @code{# Lines configured by zsh-newuser-install} and
@code{# End of lines configured by zsh-newuser-install}.  In addition,
the old version of @code{.zshrc} is saved to a file with the suffix
@code{.zni} appended.

If the function edits an existing @code{.zshrc}, it is up to the user
to ensure that the changes made will take effect.  For example, if
control usually returns early from the existing @code{.zshrc} the lines
will not be executed; or a later initialization file may override
options or parameters, and so on.  The function itself does not attempt to
detect any such conflicts.
@end quotation

@c historic nodename: Other Functions

@node Other Functions<2>,,User Configuration Functions,User Contributions
@anchor{Zsh/contrib other-functions}@anchor{129}
@section Other Functions


There are a large number of helpful functions in the @code{Functions/Misc}
directory of the zsh distribution.  Most are very simple and do not
require documentation here, but a few are worthy of special mention.

@menu
* Descriptions:: 
* Styles: Styles<3>. 

@end menu

@node Descriptions,Styles<3>,,Other Functions<2>
@anchor{Zsh/contrib descriptions}@anchor{1c8}
@subsection Descriptions


@geindex colors; Function

@code{colors}

@quotation

This function initializes several associative arrays to map color names to
(and from) the ANSI standard eight-color terminal codes.  These are used
by the prompt theme system (see @ref{1e,,Prompt Themes}).
You seldom should need to run
@code{colors} more than once.

The eight base colors are: @code{black}, @code{red}, @code{green}, @code{yellow},
@code{blue}, @code{magenta}, @code{cyan}, and @code{white}.  Each of these has codes for
foreground and background.  In addition there are seven intensity attributes:
@code{bold}, @code{faint}, @code{italic}, @code{underline}, @code{blink}, @code{reverse},
and @code{conceal}.  Finally, there are seven codes used to negate attributes:
@code{none} (reset all attributes to the defaults), @code{normal}
(neither bold nor faint), @code{no-italic}, @code{no-underline}, @code{no-blink},
@code{no-reverse}, and @code{no-conceal}.

Some terminals do not support all combinations of colors and intensities.
Prior to zsh @code{5.8.1} the intensity @code{standout} was provided.  It has
been replaced by the more specific @code{italic} and @code{reverse} to match
the specification, but some terminals may swap these or make one of them
produce blinking text even if the @code{blink} code is not usable.

The associative arrays are:

@code{color}

@code{colour}

@quotation

Map all the color names to their integer codes, and integer codes to the
color names.  The eight base names map to the foreground color codes, as
do names prefixed with @code{fg-}, such as @code{fg-red}.  Names prefixed
with @code{bg-}, such as @code{bg-blue}, refer to the background codes.  The
reverse mapping from code to color yields base name for foreground codes
and the @code{bg-} form for backgrounds.

Although it is a misnomer to call them `colors’, these arrays also map the
other fourteen attributes from names to codes and codes to names.
@end quotation

@code{fg}

@code{fg_bold}

@code{fg_no_bold}

@quotation

Map the eight basic color names to ANSI terminal escape sequences that set
the corresponding foreground text properties.  The @code{fg} sequences change
the color without changing the eight intensity attributes.
@end quotation

@code{bg}

@code{bg_bold}

@code{bg_no_bold}

@quotation

Map the eight basic color names to ANSI terminal escape sequences that set
the corresponding background properties.  The @code{bg} sequences change the
color without changing the eight intensity attributes.
@end quotation

In addition, the scalar parameters @code{reset_color} and @code{bold_color} are
set to the ANSI terminal escapes that turn off all attributes and turn on
bold intensity, respectively.
@end quotation

@geindex fned; Function

@code{fned} [ @code{-x} @var{num} ] @var{name}

@quotation

Same as @code{zed -f}.  This function does not appear in the zsh
distribution, but can be created by linking @code{zed} to the name @code{fned}
in some directory in your @code{fpath}.
@end quotation

@geindex histed; Function

@code{histed} [ [ @var{name} ] @var{size} ]

@quotation

Same as @code{zed -h}.  This function does not appear in the zsh
distribution, but can be created by linking @code{zed} to the name @code{histed}
in some directory in your @code{fpath}.
@end quotation

@geindex is-at-least; Function

@code{is-at-least} @var{needed} [ @var{present} ]

@quotation

Perform a greater-than-or-equal-to comparison of two strings having the
format of a zsh version number; that is, a string of numbers and text with
segments separated by dots or dashes.  If the @var{present} string is not
provided, @code{$ZSH_VERSION} is used.  Segments are paired left-to-right in
the two strings with leading non-number parts ignored.  If one string has
fewer segments than the other, the missing segments are considered zero.

This is useful in startup files to set options and other state that are
not available in all versions of zsh.

@example
 is-at-least 3.1.6-15 && setopt NO_GLOBAL_RCS
 is-at-least 3.1.0 && setopt HIST_REDUCE_BLANKS
 is-at-least 2.6-17 || print "You can't use is-at-least here."
@end example
@end quotation

@geindex mkshadow; Function

@geindex rmshadow; Function

@code{mkshadow} [ @code{-s} @var{suffix} ] [ – ] @var{command_name} …

@code{rmshadow}

@quotation

These functions are an interface to the @code{_shadow} and @code{_unshadow}
completion utilities to make them more easily accessible in other
contexts.  Usage is exactly as for the completion utility:

@example
 @{
   mkshadow fname
   function fname @{
     # Do your new thing
   @}
   # Invoke callers of fname
 @} always @{
   rmshadow
 @}
@end example

Upon return, the value of @code{$REPLY} is the suffix used to create a
copy of the original @var{command_name}, so @var{command_name}@code{@@$REPLY}
invokes that original.
@end quotation

@geindex nslookup; Function

@code{nslookup} [ @var{arg} … ]

@quotation

This wrapper function for the @code{nslookup} command requires the
@code{zsh/zpty} module (see @ref{cd,,The zsh/zpty Module}).
It behaves exactly like the standard @code{nslookup}
except that it provides customizable prompts (including a right-side
prompt) and completion of nslookup commands, host names, etc. (if you use
the function-based completion system).  Completion styles may be set with
the context prefix @code{:completion:nslookup}.

See also the @code{pager}, @code{prompt} and @code{rprompt} styles below.
@end quotation

@geindex regexp-replace; Function

@code{regexp-replace} @var{var} @var{regexp} [ @var{replace} ]

@quotation

Use regular expressions to perform a global search and replace operation
on a variable.  POSIX extended regular expressions (ERE) are used,
unless the option @code{RE_MATCH_PCRE} has been set, in which case
Perl-compatible regular expressions are used
(this requires the shell to be linked against the @code{pcre}
library).

@var{var} is the name of the variable containing the string to be matched.
The variable will be modified directly by the function.  The
variables @code{MATCH}, @code{MBEGIN}, @code{MEND}, @code{match}, @code{mbegin}, @code{mend},
as well as any variables starting with @code{_regexp_replace}
should be avoided as these are used by the regular expression code.

@var{regexp} is the regular expression to match against the string.

@var{replace} is the replacement text.  This can contain parameter, command
and arithmetic expressions which will be replaced:  in particular, a
reference to @code{$MATCH} will be replaced by the text matched by the pattern.
If not given, matches are replaced with nothing.

The return status is 0 if at least one match was performed, else 1.

Note that if using POSIX EREs, the @code{^} or word boundary operators
(where available) may not work properly.
@end quotation

@geindex run-help; Function

@code{run-help} @var{cmd}

@quotation

This function is designed to be invoked by the @code{run-help} ZLE widget,
in place of the default alias.  See @ref{19e,,Accessing On-Line Help}
for setup instructions.

In the discussion which follows, if @var{cmd} is a file system path, it is
first reduced to its rightmost component (the file name).

Help is first sought by looking for a file named @var{cmd} in the directory
named by the @code{HELPDIR} parameter.  If no file is found, an assistant
function, alias, or command named @code{run-help-:var:`cmd}` is sought.  If
found, the assistant is executed with the rest of the current command line
(everything after the command name @var{cmd}) as its arguments.  When
neither file nor assistant is found, the external command
@code{man} @var{cmd} is run.

An example assistant for the “ssh” command:

@example
 run-help-ssh() @{
     emulate -LR zsh
     local -a args
     # Delete the "-l username" option
     zparseopts -D -E -a args l:
     # Delete other options, leaving: host command
     args=($@{@@:#-*@})
     if [[ $@{#args@} -lt 2 ]]; then
         man ssh
     else
         run-help $args[2]
     fi
 @}
@end example

Several of these assistants are provided in the @code{Functions/Misc}
directory.  These must be autoloaded, or placed as executable scripts in
your search path, in order to be found and used by @code{run-help}.

@geindex run-help-btrfs; Function

@geindex run-help-git; Function

@geindex run-help-ip; Function

@geindex run-help-openssl; Function

@geindex run-help-p4; Function

@geindex run-help-sudo; Function

@geindex run-help-svk; Function

@geindex run-help-svn; Function

@code{run-help-btrfs}

@code{run-help-git}

@code{run-help-ip}

@code{run-help-openssl}

@code{run-help-p4}

@code{run-help-sudo}

@code{run-help-svk}

@code{run-help-svn}

@quotation

Assistant functions for the
@code{btrfs},
@code{git},
@code{ip},
@code{openssl},
@code{p4},
@code{sudo},
@code{svk},
and
@code{svn},
commands.
@end quotation
@end quotation

@code{tetris}

@quotation

Zsh was once accused of not being as complete as Emacs,
because it lacked a Tetris game.  This function was written to
refute this vicious slander.

This function must be used as a ZLE widget:

@example
 autoload -U tetris
 zle -N tetris
 bindkey @var{keys} tetris
@end example

To start a game, execute the widget by typing the @var{keys}.  Whatever command
line you were editing disappears temporarily, and your keymap is also
temporarily replaced by the Tetris control keys.  The previous editor state
is restored when you quit the game (by pressing @code{q}) or when you lose.

If you quit in the middle of a game, the next invocation of the @code{tetris}
widget will continue where you left off.  If you lost, it will start a new
game.
@end quotation

@code{tetriscurses}

@quotation

This is a port of the above to zcurses.  The input handling is improved
a bit so that moving a block sideways doesn’t automatically advance a
timestep, and the graphics use unicode block graphics.

This version does not save the game state between invocations, and is not
invoked as a widget, but rather as:

@example
 autoload -U tetriscurses
 tetriscurses
@end example
@end quotation

@geindex zargs; Function

@code{zargs} [ @var{option} … @code{--} ] [ @var{input} … ] [ @code{--} @var{command} [ @var{arg} … ] ]

@quotation

This function has a similar purpose to GNU xargs.  Instead of
reading lines of arguments from the standard input, it takes them from
the command line.  This is useful because zsh, especially with recursive
glob operators, often can construct a command line for a shell function
that is longer than can be accepted by an external command.

The @var{option} list represents options of the @code{zargs} command itself,
which are the same as those of @code{xargs}.  The @var{input} list is the
collection of strings (often file names) that become the arguments of the
@code{command}, analogous to the standard input of @code{xargs}.  Finally, the
@var{arg} list consists of those arguments (usually options) that are
passed to the @var{command} each time it runs.  The @var{arg} list precedes
the elements from the @code{input} list in each run.  If no @var{command} is
provided, then no @var{arg} list may be provided, and in that event the
default command is @code{print} with arguments @code{-r --}.

For example, to get a long @code{ls} listing of all non-hidden plain files
in the current directory or its subdirectories:

@example
 autoload -U zargs
 zargs -- **/*(.) -- ls -ld --
@end example

The first and third occurrences of @code{--} are used to mark the end
of options for @code{zargs} and @code{ls} respectively to guard against
filenames starting with @code{-}, while the second is used to separate the
list of files from the command to run (@code{ls -ld --}).

The first @code{--} would also be needed if there was a chance the
list might be empty as in:

@example
 zargs -r -- ./*.back(#qN) -- rm -f
@end example

In the event that the string @code{--} is or may be an @var{input}, the
@code{-e} option may be used to change the end-of-inputs marker.  Note that
this does `not' change the end-of-options marker.  For example, to use
@code{..} as the marker:

@example
 zargs -e.. -- **/*(.) .. ls -ld --
@end example

This is a good choice in that example because no plain file can be named
@code{..}, but the best end-marker depends on the circumstances.

The options @code{-i}, @code{-I}, @code{-l}, @code{-L}, and @code{-n} differ slightly
from their usage in @code{xargs}.  There are no input lines for @code{zargs} to
count, so @code{-l} and @code{-L} count through the @var{input} list, and @code{-n}
counts the number of arguments passed to each execution of @var{command},
`including' any @var{arg} list.  Also, any time @code{-i} or @code{-I} is used,
each @var{input} is processed separately as if by @code{-L} @code{1}.

For details of the other @code{zargs} options, see the @code{xargs(1)} man page (but note
the difference in function between @code{zargs} and @code{xargs}) or run
@code{zargs} with the @code{--help} option.
@end quotation

@geindex zed; Function

@code{zed} [ @code{-f} [ @code{-x} @var{num} ] ] @var{name}

@code{zed} [ @code{-h} [ @var{name} ] @var{size} ]

@code{zed -b}

@quotation

This function uses the ZLE editor to edit a file or function.

Only one @var{name} argument is allowed.
If the @code{-f} option is given, the name is taken to be that of
a function; if the function is marked for autoloading, @code{zed} searches
for it in the @code{fpath} and loads it.  Note that functions edited this way
are installed into the current shell, but `not' written back to the
autoload file.  In this case the @code{-x} option specifies that leading
tabs indenting the function according to syntax should be converted into
the given number of spaces; @code{-x 2} is consistent with the layout
of functions distributed with the shell.

Without @code{-f}, @var{name} is the path name of the file to edit, which need
not exist; it is created on write, if necessary.  With @code{-h}, the file is
presumed to contain history events.

When no file name is provided for @code{-h} the current shell history is edited
in place.  The history is renumbered when zed exits successfully.

When editing history, multi-line events must have a trailing backslash on
every line before the last.

While editing, the function sets the main keymap to @code{zed} and the
vi command keymap to @code{zed-vicmd}.  These will be copied from the existing
@code{main} and @code{vicmd} keymaps if they do not exist the first time @code{zed}
is run.  They can be used to provide special key bindings used only in zed.

If it creates the keymap, @code{zed} rebinds the return key to insert a line
break and @code{^X^W} to accept the edit in the @code{zed} keymap, and binds
@code{ZZ} to accept the edit in the @code{zed-vicmd} keymap.

The bindings alone can be installed by running @code{zed -b}.  This is
suitable for putting into a startup file.  Note that, if rerun,
this will overwrite the existing @code{zed} and @code{zed-vicmd} keymaps.

Completion is available, and styles may be set with the context prefix
@code{:completion:zed:}.

@geindex zed-set-file-name; Function

A zle widget @code{zed-set-file-name} is available.  This can be called
by name from within zed using @code{\ex zed-set-file-name} or can be
bound to a key in either of the @code{zed} or @code{zed-vicmd} keymaps after
@code{zed -b} has been run.  When the widget is called, it prompts for
a new name for the file being edited.  When zed exits the file will be
written under that name and the original file will be left alone.  The
widget has no effect when invoked from @code{zed -f}.  The completion
context is changed to @code{:completion:zed-set-file-name:}.  When editing
the current history with @code{zed -h}, the history is first updated and
then the file is written, but the global setting of @code{HISTFILE} is not
altered.

While @code{zed-set-file-name} is running, zed uses the keymap
@code{zed-normal-keymap}, which is linked from the main keymap in effect
at the time zed initialised its bindings.  (This is to make the return key
operate normally.)  The result is that if the main keymap has been changed,
the widget won’t notice.  This is not a concern for most users.
@end quotation

@geindex zcp; Function

@geindex zln; Function

@code{zcp} [ @code{-finqQvwW} ] @var{srcpat} @var{dest}

@code{zln} [ @code{-finqQsvwW} ] @var{srcpat} @var{dest}

@quotation

Same as @code{zmv -C} and @code{zmv -L}, respectively.  These functions do not
appear in the zsh distribution, but can be created by linking @code{zmv} to
the names @code{zcp} and @code{zln} in some directory in your @code{fpath}.
@end quotation

@geindex zgetopt; Function

@code{zgetopt} [ @code{-A} @var{array} ] [ @code{-l} @var{spec} ] [ @code{-n} @var{name} ] [ @code{-o} @var{spec} ] @code{--} [ @var{arg} … ]

@quotation

This is a wrapper around @code{zparseopts} (from @code{zsh/zutil}) which
provides an interface similar to the util-linux implementation of
@code{getopt(1)} (sometimes called GNU @code{getopt}). It
simplifies GNU-style argument parsing (including permutation) and
can make it easier to write functions and scripts with complex APIs,
particularly ones where the order of options is significant.

The typical usage pattern is as follows:

@example
 zgetopt -o abc: -l aaa,bbb,ccc: -- "$@@" || return
 while (( $# )); do
   case $1 in
     -a|--aaa) ...; shift ;;        # handle -a
     -b|--bbb) ...; shift ;;        # handle -b
     -c|--ccc) ...; shift 2 ;;      # handle -c and arg
     --)       ...; shift; break ;; # end of options
   esac
 done
 # handle operands
@end example

It can also be called as a stand-alone script from other shells
using the more traditional print-and-eval pattern:

@example
 args=$( zgetopt -n myscript -o abc: -l aaa,bbb,ccc: -- "$@@" ) || return
 eval set -- "$args"
 while [ $# -ne 0 ]; do ...; done
@end example

Options:


@table @asis

@item @code{-A :var:`array}`

When called as a function, assign the parsed
arguments to the named array @var{array}. Defaults to @code{argv}, which
overwrites the caller’s positional parameters. Has no meaning when
called as a script, in which case the parsed and quoted arguments are
always printed to standard output. An empty string forces the
printing behaviour in either mode.

@item @code{-l :var:`spec}`

Specify long options to recognise when
parsing. These should be given using just the option name (no
dashes), suffixed by @code{:} or @code{::} if it takes a mandatory or
optional argument respectively. Multiple options can be defined
either by separating them by commas or by supplying -l again.
Example: @code{-l foo,bar: -l baz}

@item @code{-n :var:`name}`

Specify the name to use in the error message
if argument parsing fails. Defaults to the name of the nearest
calling function or the base name of @code{$ZSH_ARGZERO}. Note that
errors related to the usage of @code{zgetopt} itself are always reported
as coming from @code{zgetopt}.

@item @code{-o :var:`spec}`

Specify short options to recognise when
parsing. These should be given as a single string, in the same format
used by the @code{getopts} built-in or the @code{getopt(3)}
library function, again using @code{:} or @code{::} to indicate a
mandatory or optional argument. The spec may be prefixed with @code{+}
to indicate that option parsing should stop at the first non-option
argument (equivalent to setting the environment variable
@code{POSIXLY_CORRECT}). Example: @code{-o ab:cd::}
@end table

At least one of @code{-o} or @code{-l} must be given. The function’s own
options should be followed by zero or more arguments to parse. It is
critical that these be separated explicitly by @code{--}, as in the
above examples, to ensure that the function can accurately
distinguish the arguments it’s meant to parse from its own.

Refer to the manual for util-linux’s @code{getopt(1)} for
more information about the way arguments are parsed and results are
returned. Note however that this function is not intended to be a
complete re-implementation. In particular: it omits all
portability/compatibility features, it doesn’t support the
@code{--alternative} option, and it doesn’t support abbreviating long
options.
@end quotation

@code{zkbd}

@quotation

See @ref{1a3,,Keyboard Definition}.
@end quotation

@geindex zmv; Function

@code{zmv} [ @code{-finqQsvwW} ] [ @code{-C} | @code{-L} | @code{-M} | -@{@code{p|P}@} @var{program} ] [ @code{-o} @var{optstring} ]

@quotation

@var{srcpat} @var{dest}

Move (usually, rename) files matching the pattern @var{srcpat} to
corresponding files having names of the form given by @var{dest}, where
@var{srcpat} contains parentheses surrounding patterns which will be
replaced in turn by @code{$1}, @code{$2}, … in @var{dest}.  For example,

@example
 zmv '(*).lis' '$1.txt'
@end example

renames @code{foo.lis} to @code{foo.txt}, @code{my.old.stuff.lis} to
@code{my.old.stuff.txt}, and so on.

The pattern is always treated as an @code{EXTENDED_GLOB} pattern.  Any file
whose name is not changed by the substitution is simply ignored.  Any
error (no files matched the @var{srcpat}, substitution resulted in an empty
string, two substitutions gave the same result, the destination was an
existing regular file and @code{-f} was not given) causes the entire function
to abort without doing anything.

In addition to pattern replacement, the variable @code{$f} can be referred
to in the second (replacement) argument.  This makes it possible to
use variable substitution to alter the argument; see examples below.

Options:


@table @asis

@item @code{-f}

Force overwriting of destination files.  Not currently
passed down to the @code{mv/cp/ln} command due to vagaries of
implementations (but you can use @code{-o-f} to do that).

@item @code{-i}

Interactive: show each line to be executed and ask the user
whether to execute it.  @code{Y} or @code{y} will execute it, anything else will
skip it.  Note that you just need to type one character.

@item @code{-n}

No execution: print what would happen, but don’t do it.

@item @code{-q}

Turn bare glob qualifiers off: now assumed by default, so
this has no effect.

@item @code{-Q}

Force bare glob qualifiers on.  Don’t turn this on unless
you are actually using glob qualifiers in a pattern.

@item @code{-s}

Symbolic, passed down to @code{ln}; only works with @code{-L}.

@item @code{-v}

Verbose: print each command as it’s being executed.

@item @code{-w}

Pick out wildcard parts of the pattern, as described above,
and implicitly add parentheses for referring to them.

@item @code{-W}

Just like @code{-w}, with the addition of turning wildcards in
the replacement pattern into sequential @code{$@{1@}} .. @code{$@{N@}} references.
@end table

@code{-C}

@code{-L}


@table @asis

@item @code{-M}

Force @code{cp}, @code{ln} or @code{mv}, respectively, regardless of
the name of the function.

@item @code{-p} @var{program}

Call @var{program} instead of @code{cp}, @code{ln} or
@code{mv}.  Whatever it does, it should at least understand the form


@example
 @var{program} @code{--} @var{oldname} @var{newname}
@end example

where @var{oldname} and @var{newname} are filenames generated by @code{zmv}.
@var{program} will be split into words, so might be e.g. the name
of an archive tool plus a copy or rename subcommand.

@item @code{-P} @var{program}

As @code{-p} @var{program}, except that
@var{program} does not accept a following @code{--} to indicate the
end of options.  In this case filenames must already be in a sane
form for the program in question.

@item @code{-o} @var{optstring}

The @var{optstring} is split into words and
passed down verbatim to the @code{cp}, @code{ln} or @code{mv} command called to
perform the work.  It should probably begin with a @code{-}.
@end table

Further examples:

@example
 zmv -v '(* *)' '$@{1// /_@}'
@end example

For any file in the current directory with at least one space in the name,
replace every space by an underscore and display the commands executed.

@example
 zmv -v '* *' '$@{f// /_@}'
@end example

This does exactly the same by referring to the file name stored in @code{$f}.

For more complete examples and other implementation details, see the
@code{zmv} source file, usually located in one of the directories named in
your @code{fpath}, or in @code{Functions/Misc/zmv} in the zsh distribution.
@end quotation

@code{zrecompile}

@quotation

See @ref{1a1,,Recompiling Functions}.
@end quotation

@geindex zstyle+; Function

@code{zstyle+} @var{context} @var{style} @var{value} [ @code{+} @var{subcontext} @var{style} @var{value} … ]

@quotation

This makes defining styles a bit simpler by using a single @code{+} as a
special token that allows you to append a context name to the previously
used context name.  Like this:

@example
 zstyle+ ':foo:bar' @var{style1} @var{value1}         +':baz'     @var{style2} @var{value2}         +':frob'    @var{style3} @var{value3}
@end example

This defines @var{style1} with @var{value1} for the context @code{:foo:bar} as usual,
but it also defines @var{style2} with @var{value2} for the context
@code{:foo:bar:baz} and @var{style3} with @var{value3} for @code{:foo:bar:frob}.  Any
@var{subcontext} may be the empty string to re-use the first context
unchanged.
@end quotation

@node Styles<3>,,Descriptions,Other Functions<2>
@anchor{Zsh/contrib id14}@anchor{1c9}
@subsection Styles


@geindex insert-tab@comma{} completion style; Keystroke

@code{insert-tab}

@quotation

The @code{zed} function `sets' this style in context @code{:completion:zed:*}
to turn off completion when @code{TAB} is typed at the beginning of a line.
You may override this by setting your own value for this context and style.
@end quotation

@geindex pager@comma{} nslookup style; Keystroke

@code{pager}

@quotation

The @code{nslookup} function looks up this style in the context
@code{:nslookup} to determine the program used to display output that does
not fit on a single screen.
@end quotation

@geindex prompt@comma{} nslookup style; Keystroke

@geindex rprompt@comma{} nslookup style; Keystroke

@code{prompt}

@code{rprompt}

@quotation

The @code{nslookup} function looks up this style in the context
@code{:nslookup} to set the prompt and the right-side prompt, respectively.
The usual expansions for the @code{PS1} and @code{RPS1} parameters may be used
(see @ref{1ca,,Expansion of Prompt Sequences}).
@end quotation

@node Index,,User Contributions,Top
@unnumbered Index


@printindex ge

@anchor{76}@w{                              }
@anchor{6f}@w{                              }
@anchor{Zsh/options signals}@w{                              }
@anchor{Zsh/redirect simple-commands-pipelines}@w{                              }
@anchor{Zsh/options invocation}@w{                              }
@anchor{Zsh/builtins id9}@w{                              }
@anchor{b8}@w{                              }
@anchor{e8}@w{                              }
@anchor{Zsh/params functions}@w{                              }
@anchor{Zsh/params arithmetic-evaluation}@w{                              }
@anchor{37}@w{                              }
@anchor{Zsh/builtins compatibility}@w{                              }
@anchor{Zsh/builtins invocation}@w{                              }
@anchor{Zsh/options errors}@w{                              }
@anchor{1c7}@w{                              }
@anchor{Zsh/options redirection}@w{                              }
@anchor{c3}@w{                              }
@anchor{97}@w{                              }
@anchor{Zsh/params complex-commands}@w{                              }
@anchor{Zsh/expn expansion-of-prompt-sequences}@w{                              }
@anchor{a9}@w{                              }
@anchor{ab}@w{                              }
@anchor{95}@w{                              }
@anchor{67}@w{                              }
@anchor{c1}@w{                              }
@anchor{ae}@w{                              }
@anchor{Zsh/builtins expansion-of-prompt-sequences}@w{                              }
@anchor{1c5}@w{                              }
@anchor{Zsh/contrib mailing-lists}@w{                              }
@anchor{c4}@w{                              }
@anchor{Zsh/params invocation}@w{                              }
@anchor{Zsh/contrib expansion-of-prompt-sequences}@w{                              }
@anchor{6c}@w{                              }
@anchor{91}@w{                              }
@anchor{Zsh/compwid expansion-of-prompt-sequences}@w{                              }
@anchor{a5}@w{                              }
@anchor{c2}@w{                              }
@anchor{1ca}@w{                              }
@anchor{Zsh/expn arithmetic-evaluation}@w{                              }
@anchor{1a8}@w{                              }
@anchor{Zsh/jobs id6}@w{                              }
@anchor{Zsh/calsys simple-prompt-escapes}@w{                              }
@anchor{Zsh/builtins simple-commands-pipelines}@w{                              }
@anchor{Zsh/builtins precommand-modifiers}@w{                              }
@anchor{Zsh/contrib complex-commands}@w{                              }
@anchor{Zsh/contrib special-functions}@w{                              }
@anchor{c6}@w{                              }
@anchor{a3}@w{                              }
@anchor{c5}@w{                              }
@anchor{b9}@w{                              }
@anchor{b7}@w{                              }
@anchor{Zsh/contrib arithmetic-evaluation}@w{                              }
@anchor{Zsh/builtins signals}@w{                              }
@anchor{aa}@w{                              }
@anchor{Zsh/params expansion-of-prompt-sequences}@w{                              }
@anchor{1a5}@w{                              }
@anchor{Zsh/options arithmetic-evaluation}@w{                              }
@anchor{c9}@w{                              }
@anchor{a7}@w{                              }
@anchor{Zsh/roadmap functions}@w{                              }
@anchor{Zsh/builtins simple-prompt-escapes}@w{                              }
@anchor{4d}@w{                              }
@anchor{8f}@w{                              }
@anchor{19}@w{                              }
@anchor{65}@w{                              }
@anchor{89}@w{                              }
@anchor{Zsh/builtins aliasing}@w{                              }
@anchor{Zsh/options reserved-words}@w{                              }
@anchor{Zsh/expn simple-prompt-escapes}@w{                              }
@anchor{Zsh/params quoting}@w{                              }
@anchor{1d}@w{                              }
@anchor{Zsh/modules simple-prompt-escapes}@w{                              }
@anchor{131}@w{                              }
@anchor{175}@w{                              }
@anchor{Zsh/roadmap shell-grammar}@w{                              }
@anchor{Zsh/builtins arithmetic-evaluation}@w{                              }
@anchor{c8}@w{                              }
@anchor{Zsh/expn id6}@w{                              }
@anchor{Zsh/options expansion-of-prompt-sequences}@w{                              }
@anchor{ad}@w{                              }
@anchor{Zsh/expn aliasing}@w{                              }
@anchor{92}@w{                              }
@anchor{Zsh/options special-functions}@w{                              }
@anchor{Zsh/builtins conditional-expressions}@w{                              }

@c %**end of body
@bye
