Start of change

zsh modules

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 zmodload command.

The modules that are bundled with the zsh distribution are:
zsh/attr
Built-ins for manipulating extended attributes (xattr).
zsh/datetime
Some date/time commands and parameters.
zsh/example
An example of how to write a module.
zsh/langinfo
Interface to locale information.
zsh/mathfunc
Standard scientific functions for use in mathematical evaluations.
zsh/nearcolor
Map colors to the nearest color in the available palette.
zsh/parameter
Access to internal hash tables via special associative arrays.
zsh/param/private
Builtins for managing private-scoped parameters in function context.
zsh/regex
Interface to the POSIX regex library.
zsh/sched
A built-in that provides a timed execution facility within the shell.
zsh/stat
A built-in command interface to the stat system call.
zsh/system
A built-in interface to various low-level system features.
zsh/termcap
Interface to the termcap database.
zsh/terminfo
Interface to the terminfo database.
zsh/zselect
Block and return when file descriptors are ready.
zsh/zutil
Some utility built-ins, such as the one for supporting configuration via styles.

The zsh/attr module

The zsh/attr module is used for manipulating extended attributes. The -h option causes all commands to operate on symbolic links instead of their targets. The built-ins in this module are:
zgetattr [ -h ] FILENAME ATTRIBUTE [PARAMETER ]
Get the extended attribute ATTRIBUTE from the specified FILENAME. If the optional argument PARAMETER is given, the attribute is set on that parameter instead of being printed to stdout.
zsetattr [ -h ] FILENAME ATTRIBUTE VALUE
Set the extended attribute ATTRIBUTE on the specified FILENAME to VALUE.
zdelattr [ -h ] FILENAME ATTRIBUTE
Remove the extended attribute ATTRIBUTE from the specified FILENAME.
zlistattr [ -h ] FILENAME [PARAMETER ]
List the extended attributes currently set on the specified FILENAME. If the optional argument PARAMETER is given, the list of attributes is set on that parameter instead of being printed to stdout.

zgetattr and 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.

The zsh/datetime module

The zsh/datetime module makes available one built-in command:
strftime [ -s SCALAR ] FORMAT [ EPOCHTIME [ NANOSECONDS ] ]
strftime -r [ -q ] [ -s SCALAR ] FORMAT TIMESTRING
Output the date in the FORMAT specified. With no EPOCHTIME, the current system date/time is used; optionally, EPOCHTIME may be used to specify the number of seconds since the epoch, and NANOSECONDS may additionally be used to specify the number of nanoseconds past the second (otherwise that number is assumed to be 0). See man page strftime(3) for details. The zsh extensions described in Prompt expansion are also available.
-q
Run quietly; suppress printing of all error messages described below. Errors for invalid EPOCHTIME values are always printed.
-r
With the option -r (reverse), use FORMAT to parse the input string TIMESTRING and output the number of seconds since the epoch at which the time occurred. The parsing is implemented by the system function strptime; see man page strptime(3). This means that zsh format extensions are not available, but for reverse lookup they are not required.

In most implementations of strftime any timezone in the TIMESTRING is ignored and the local timezone declared by the TZ environment variable is used; other parameters are set to zero if not present.

If TIMESTRING does not match FORMAT the command returns status 1 and prints an error message. If TIMESTRING matches FORMAT but not all characters in TIMESTRING were used, the conversion succeeds but also prints an error message.

If either of the system functions strptime or mktime is not available, status 2 is returned and an error message is printed.

-s SCALAR
Assign the date string (or epoch time in seconds if -r is given) to SCALAR instead of printing it.

Note that depending on the system's declared integral time type, strftime may produce incorrect results for epoch times greater than 2147483647 which corresponds to 2038-01-19 03:14:07 +0000.

The zsh/datetime module makes available several parameters; all are readonly:
EPOCHREALTIME
A floating point value representing the number of seconds since the epoch. The notional accuracy is to nanoseconds if the 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.
EPOCHSECONDS
An integer value representing the number of seconds since the epoch.
epochtime
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:
          for secs nsecs in $epochtime; do
            ...
          done

The zsh/example module

The zsh/example module makes available one built-in command:
example [ -flags ] [ ARGS ... ]
Displays the flags and arguments it is invoked with.

The purpose of the module is to serve as an example of how to write a module.

The zsh/langinfo module

The zsh/langinfo module makes available one parameter:
langinfo
An associative array that maps langinfo elements to their values.
Your implementation may support a number of the following keys:
     CODESET, D_T_FMT, D_FMT, T_FMT, RADIXCHAR, THOUSEP, YESEXPR,
     NOEXPR, CRNCYSTR, ABDAY_{1..7}, DAY_{1..7}, ABMON_{1..12},
     MON_{1..12}, T_FMT_AMPM, AM_STR, PM_STR, ERA, ERA_D_FMT,
     ERA_D_T_FMT, ERA_T_FMT, ALT_DIGITS

The zsh/mathfunc module

The zsh/mathfunc module provides standard mathematical functions for use when evaluating mathematical formulae. The syntax agrees with normal C and FORTRAN conventions, for example,
 (( f = sin(0.3) ))
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 atan with a second argument and the abs, int and 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: acos, acosh, asin, asinh, atan, atanh, cbrt, ceil, cos, cosh, erf, erfc, exp, expm1, fabs, floor, gamma, j0, j1, lgamma, log, log10, log1p, log2, logb, sin, sinh, sqrt, tan, tanh, y0, y1. The atan function can optionally take a second argument, in which case it behaves like the C function atan2. The ilogb function takes a single floating point argument, but returns an integer.

The function signgam takes no arguments, and returns an integer, which is the C variable of the same name, as described in man page gamma(3). Note that it is therefore only useful immediately after a call to gamma or lgamma. Note also that 'signgam()' and 'signgam' are distinct expressions.

The functions min, max, and sum are defined not in this module but in the zmathfunc autoloadable function, described in Mathematical Functions::.

The following functions take two floating point arguments: copysign, fmod, hypot, nextafter.

The following take an integer first argument and a floating point second argument: jn, yn.

The function 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 float and int convert their arguments into a floating point or integer value (by truncation) respectively.

The C pow function is available in ordinary math evaluation as the '**' operator and is not provided as part of zshell.

The function rand48 is available if your system's mathematical library has the function 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 initialized by three calls to the rand(3) function -- this produces the same random numbers as the next three values of $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 initialized in the same manner as for a call to rand48 with no argument. Subsequent calls to rand48(PARAM) will then maintain the seed in the parameter 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 rand48 with no argument.

For example, consider
     print $(( rand48(seed) ))
     print $(( rand48() ))
     print $(( rand48(seed) ))

Assuming $seed does not exist, it will be initialized by the first call. In the second call, the default seed is initialized; note, however, that because of the properties of rand() there is a correlation between the seeds used for the two initializations, 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 rand48().

The zsh/nearcolor module

The zsh/nearcolor module replaces colors specified as hex triplets with the nearest color in the 88 or 256 color palettes that are widely used by terminal emulators. By default, 24-bit true color escape codes are generated when colors are specified using hex triplets. These are not supported by all terminals. The purpose of this module is to make it easier to define color preferences in a form that can work across a range of terminal emulators.

Aside from the default color, the ANSI standard for terminal escape codes provides for eight colors. The bright attribute brings this to sixteen. These basic colors are commonly used in terminal applications due to being widely supported. Expanded 88 and 256 color palettes are also common and, while the first sixteen colors vary somewhat between terminals and configurations, these add a generally consistent and predictable set of colors.

In order to use the zsh/nearcolor module, it only needs to be loaded. Thereafter, whenever a color is specified using a hex triplet, it will be compared against each of the available colors and the closest will be selected. The first sixteen colors are never matched in this process due to being unpredictable.

It is not possible to reliably detect support for true color in the terminal emulator. It is therefore recommended to be selective in loading the zsh/nearcolor module. For example, the following checks the COLORTERM environment variable:
[[ $COLORTERM = *(24bit|truecolor)* ]] || zmodload zsh/nearcolor

Some terminals accept the true color escape codes but map them internally to a more limited palette in a similar manner to the zsh/nearcolor module.

The zsh/parameter module

The zsh/parameter module gives access to some of the internal hash tables used by the shell by defining some special parameters.
options
The keys for this associative array are the names of the options that can be set and unset using the setopt and unsetopt built-ins. The value of each key is either the string on if the option is currently set, or the string 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 off.
commands
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 hash built-in. Unsetting a key as in 'unset "commands[foo]"' removes the entry for the given key from the command hash table.
functions
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.
dis_functions
Like functions but for disabled functions.
functions_source
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 '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 $functions.

dis_functions_source
Like functions_source but for disabled functions.
builtins
This associative array gives information about the built-in commands currently enabled. The keys are the names of the built-in commands and the values are either 'undefined' for built-in commands that will automatically be loaded from a module if invoked or 'defined' for built-in commands that are already loaded.
dis_builtins
Like built-ins but for disabled built-in commands.
reswords
This array contains the enabled reserved words.
dis_reswords
Like reswords but for disabled reserved words.
patchars
This array contains the enabled pattern characters.
dis_patchars
Like patchars but for disabled pattern characters.
aliases
This maps the names of the regular aliases currently enabled to their expansions.
dis_aliases
Like aliases but for disabled regular aliases.
galiases
Like aliases, but for global aliases.
dis_galiases
Like galiases but for disabled global aliases.
saliases
Like raliases, but for suffix aliases.
dis_saliases
Like saliases but for disabled suffix aliases.
parameters
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 t parameter flag, see Parameter expansion. Setting or unsetting keys in this array is not possible.
modules
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 'loaded', 'autoloaded', or 'alias:NAME', where NAME is the name the module is aliased to.

Setting or unsetting keys in this array is not possible.

dirstack
A normal array holding the elements of the directory stack. Note that the output of the dirs built-in command includes one more directory, the current working directory.
history
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 (${history[@]}) is guaranteed to be returned in order from most recent to oldest history event, that is, by decreasing history event number.
historywords
A special array containing the words stored in the history. These also appear in most to least recent order.
jobdirs
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, ${(k)jobdirs}. Non-numeric job references may be used when looking up a value; for example, ${jobdirs[%+]} refers to the current job.

jobtexts
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 jobdirs.

jobstates
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 'JOB-STATE:MARK:PID=STATE...'. The JOB-STATE gives the state the whole job is currently in, one of 'running', 'suspended', or 'done'. The MARK is '+' for the current job, '-' for the previous job and empty otherwise. This is followed by one ':PID=STATE' for every process in the job. The PIDs are, of course, the process IDs and the STATE describes the state of that process.

Handling of the keys of the associative array is as described for jobdirs.

nameddirs
This associative array maps the names of named directories to the path names they stand for.
userdirs
This associative array maps user names to the path names of their home directories.
usergroups
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 id command.
funcfiletrace
This array contains the absolute line numbers and corresponding file names for the point where the current function, sourced file, or (if EVAL_LINENO is set) eval command was called. The array is of the same length as funcsourcetrace and functrace, but differs from funcsourcetrace in that the line and file are the point of call, not the point of definition, and differs from functrace in that all values are absolute line numbers in files, rather than relative to the start of a function, if any.
funcsourcetrace
This array contains the file names and line numbers of the points where the functions, sourced files, and (if EVAL_LINENO is set) eval commands currently being executed were defined. The line number is the line where the 'function NAME' or 'NAME ()' started. In the case of an autoloaded function the line number is reported as zero. The format of each element is FILENAME: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 source or '.' built-ins, the trace information is shown as FILENAME: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 funcfiletrace array instead.

funcstack
This array contains the names of the functions, sourced files, and (if EVAL_LINENO is set) eval commands. currently being executed. The first element is the name of the function using the parameter.

The standard shell array 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 toplevel, the main shell code being executed either interactively or from a script, which is not present in $funcstack.

functrace
This array contains the names and line numbers of the callers corresponding to the functions currently being executed. The format of each element is NAME:LINENO. Callers are also shown for sourced files; the caller is the point where the source or '.' command was executed.

The zsh/param/private module

The 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 built-in:
private [ {+|-}AHUahlprtux ] [ {+|-}EFLRZi [ N ] ] [ NAME[=VALUE] ... ]
The private built-in command accepts all the same options and arguments as local (see Shell built-in commands) except for the '-T' option. Tied parameters may not be made private.

If used at the top level (outside a function scope), private creates a normal parameter in the same manner as declare or typeset. A warning about this is printed if WARN_CREATE_GLOBAL is set (*Note Options::). Used inside a function scope, private creates a local parameter similar to one declared with local, except having special properties noted below.

Special parameters which expose or manipulate internal shell state, such as ARGC, argv, COLUMNS, LINES, UID, EUID, IFS, PROMPT, RANDOM, and SECONDS, cannot be made private unless the '-h' option is used to hide the special meaning of the parameter. This may change in the future.

As with other typeset equivalents, private is both a built-in and a reserved word, so arrays may be assigned with parenthesized word list NAME=(VALUE...) syntax. However, the reserved word 'private' is not available until zsh/param/private is loaded, so care must be taken with order of execution and parsing for function definitions which use private. To compensate for this, the module also adds the option '-P' to the 'local' built-in to declare private parameters.

For example, this construction fails if zsh/param/private has not yet been loaded when 'bad_declaration' is defined:
     bad_declaration() {
       zmodload zsh/param/private
       private array=( one two three )
     }
This construction works because local is already a keyword, and the module is loaded before the statement is executed:
     good_declaration() {
       zmodload zsh/param/private
       local -P array=( one two three )
     }
The following is usable in scripts but may have trouble with autoload:
     zmodload zsh/param/private
     iffy_declaration() {
       private array=( one two three )
     }

The private built-in may always be used with scalar assignments and for declarations without assignments.

Parameters declared with private have the following properties:
  • Within the function body where it is declared, the parameter 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, for example.
  • 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.
  • 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.

Note that this differs from the static scope defined by compiled languages derived from C, in that the a new call to the same function creates a new scope. That is, the parameter is still associated with the call stack rather than with the function definition. It differs from ksh 'typeset -S' because the syntax used to define the function has no bearing on whether the parameter scope is respected.

The zsh/regex module

The zsh/regex module makes available the following test condition:
EXPR -regex-match REGEX
Matches a string against a POSIX extended regular expression. On successful match, matched portion of the string will normally be placed in the MATCH variable. If there are any capturing parentheses within the regex, then the match array variable will contain those. If the match is not successful, then the variables will not be altered.
For example,
          [[ alphabetical -regex-match ^a([^a]+)a([^a]+)a ]] &&
          print -l $MATCH X $match

If the option REMATCH_PCRE is not set, then the =~ operator will automatically load this module as needed and will invoke the -regex-match operator.

If BASH_REMATCH is set, then the array BASH_REMATCH will be set instead of MATCH and match.

The zsh/sched module

The zsh/sched module makes available one builtin command and one parameter.
sched [-o] [+]HH:MM[:SS] COMMAND ...
sched [-o] [+]SECONDS COMMAND ...
sched [ -ITEM ]
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 zsh/datetime module, see The zsh/datetime Module::.

With no arguments, prints the list of scheduled commands. If the scheduled command has the -o flag set, this is shown at the start of the command.

With the argument '-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 -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 'zle' command with no arguments to test whether the editor is active, and if it is, then use 'zle WIDGET' to access the editor via the named WIDGET.

The sched built-in is not made available by default when the shell starts in a mode emulating another shell. It can be made available with the command 'zmodload -F zsh/sched b:sched'.

zsh_scheduled_events
A readonly array corresponding to the events scheduled by the sched built-in. The indices of the array correspond to the numbers shown when sched is run with no arguments (provided that the KSH_ARRAYS option is not set). The value of the array consists of the scheduled time in seconds since the epoch, followed by a colon, followed by any options (which may be empty but will be preceded by a '-' otherwise), followed by a colon, followed by the command to be executed.

The sched built-in 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.

The zsh/stat module

The zsh/stat module makes available one built-in command under two possible names:
zstat [ -gnNolLtTrs ] [ -f FD ] [ -H HASH ] [ -A ARRAY ] [ -F FMT ] [ +ELEMENT ] [ FILE ... ]
stat ...
The command acts as a front end to the stat system call (see man page stat(2)). The same command is provided with two names; as the name stat is often used by an external command it is recommended that only the zstat form of the command is used. This can be arranged by loading the module with the command 'zmodload -F zsh/stat b:zstat'.
If the stat call fails, the appropriate system error message printed and status 1 is returned. The fields of struct stat give information about the files provided as arguments to the command. In addition to those available from the stat call, an extra element 'link' is provided. These elements are:
device
The number of the device on which the file resides.
inode
The unique number of the file on this device ('_inode_' number).
mode
The mode of the file; that is, the file's type and access permissions. With the -s option, this will be returned as a string corresponding to the first column in the display of the ls -l command.
nlink
The number of hard links to the file.
uid
The user ID of the owner of the file. With the -s option, this is displayed as a user name.
gid
The group ID of the file. With the -s option, this is displayed as a group name.
rdev
The raw device number. This is only useful for special devices.
size
The size of the file in bytes.
atime
mtime
ctime
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 -s option, these are printed as strings for the local time zone; the format can be altered with the -F option, and with the -g option the times are in GMT.
blksize
The number of bytes in one allocation block on the device on which the file resides.
block
The number of disk blocks used by the file.
link
If the file is a link and the -L option is in effect, this contains the name of the file linked to, otherwise it is empty. If this element is selected (''zstat +link'') then the -L option is automatically used.

A particular element may be selected by including its name preceded by a '+' in the option list; only one element is allowed. The element can be shortened to any unique set of leading characters. Otherwise, all elements will be shown for all files.

Options:
-A ARRAY
Instead of displaying the results on standard output, assign them to an ARRAY, one 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 ARRAY unless the -t or -n options were given, respectively. If -t is given, the element name appears as a prefix to the appropriate array element; if -n is given, the file name appears as a separate array element preceding all the others. Other formatting options are respected.
-H HASH
Similar to -A, but instead assign the values to HASH. The keys are the elements previously listed. If the -n option is provided then the name of the file is included in the hash with key name.
-f FD
Use the file on file descriptor FD instead of named files; no list of file names is allowed in this case.
-F FMT
Supplies a strftime (see man page strftime(3)) string for the formatting of the time elements. The format string supports all of the zsh extensions described in Prompt expansion. The -s option is implied.
-g
Show the time elements in the GMT time zone. The -s option is implied.
-l
List the names of the type elements (to standard output or an array as appropriate) and return immediately; arguments, and options other than -A, are ignored.
-L
Perform an lstat (see man page lstat(2)) rather than a 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 link element useful. It's important to note that this is the exact opposite from man page ls(1).
-n
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.
-N
Never show the names of files.
-o
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 -r and -s options, nor whether a mode is shown at all.
-r
Print raw data (the default format) alongside string data (the -s format); the string data appears in parentheses after the raw data.
-s
Print mode, uid, gid and the three time elements as strings instead of numbers. In each case the format is like that of ls -l.
-t
Always show the type names for the elements of struct stat. Usually these are only shown when output is to standard output and no individual element has been selected.
-T
Never show the type names of the struct stat elements.

The zsh/system module

The zsh/system module makes available various built-in commands and parameters.
Built-ins
syserror [ -e ERRVAR ] [ -p PREFIX ] [ ERRNO | ERRNAME ]
This command prints out the error message associated with ERRNO, a system error number, followed by a newline to standard error.

Instead of the error number, a name ERRNAME, for example ENOENT, may be used. The set of names is the same as the contents of the array errnos, see below.

If the string PREFIX is given, it is printed in front of the error message, with no intervening space.

If ERRVAR is supplied, the entire message, without a newline, is assigned to the parameter names 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 recognized (no message is printed for this).

sysopen [ -arw ] [ -m PERMISSIONS ] [ -o OPTIONS ] -u FD FILE
This command opens a file. The -r, -w and -a flags indicate whether the file should be opened for reading, writing and appending, respectively. The -m option allows the initial permissions to use when creating a file to be specified in octal form. The file descriptor is specified with -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 -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.
cloexec
Mark file to be closed when other programs are executed (else the file descriptor remains open in subshells and forked external executables)
create
creat
Create file if it does not exist.
excl
Create file, error if it already exists.
noatime
Suppress updating of the file atime.
nofollow
Fail if FILE is a symbolic link.
sync
Request that writes wait until data has been physically written.
truncate
trunc
Truncate file to size 0.
To close the file, use one of the following:
          exec {FD}<&-
          exec {FD}>&-
sysread [ -c COUNTVAR ] [ -i INFD ] [ -o OUTFD ] [ -s BUFSIZE ] [ -t TIMEOUT ] [ PARAM ]
Perform a single system read from file descriptor INFD, or zero if that is not given. The result of the read is stored in PARAM or REPLY if that is not given. If COUNTVAR is given, the number of bytes read is assigned to the parameter named by COUNTVAR.

The maximum number of bytes read is BUFSIZE or 8192 if that is not given, however the command returns as soon as any number of bytes was successfully read.

If TIMEOUT is given, it specifies a timeout in seconds, which may be zero to poll the file descriptor. This is handled by the poll system call if available, otherwise the select system call if available.

If OUTFD is given, an attempt is made to write all the bytes just read to the file descriptor OUTFD. If this fails, because of a system error other than EINTR or because of an internal zsh error during an interrupt, the bytes read but not written are stored in the parameter named by 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 COUNTVAR if that is supplied. If it was successful, COUNTVAR contains the full number of bytes transferred, as usual, and PARAM is not set.

The error 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
At least one byte of data was successfully read and, if appropriate, written.
1
There was an error in the parameters to the command. This is the only error for which a message is printed to standard error.
2
There was an error on the read, or on polling the input file descriptor for a timeout. The parameter ERRNO gives the error.
3
Data were successfully read, but there was an error writing them to OUTFD. The parameter ERRNO gives the error.
4
The attempt to read timed out. Note this does not set ERRNO as this is not a system error.
5
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 OUTFD is attempted.
sysseek [ -u FD ] [ -w start|end|current ] OFFSET
The current file position at which future reads and writes will take place is adjusted to the specified byte offset. The OFFSET is evaluated as a math expression. The -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 -w option, it is possible to specify that the offset should be relative to the current position or the end of the file.
syswrite [ -c COUNTVAR ] [ -o OUTFD ] DATA
The data (a single string of bytes) are written to the file descriptor OUTFD, or 1 if that is not given, using the write system call. Multiple write operations may be used if the first does not write all the data.

If COUNTVAR is given, the number of byte written is stored in the parameter named by COUNTVAR; this may not be the full length of DATA if an error occurred.

The error 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 EAGAIN (on some systems, 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 ERRNO will reflect the error that occurred.

zsystem flock [ -t TIMEOUT ] [ -f VAR ] [-er] FILE
zsystem flock -u FD_EXPR
The built-in zsystem's subcommand flock performs advisory file locking (via the man page 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 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 print built-in with the -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, for example, '(print message) >> FILE'. Status 0 is returned if the lock succeeds, else status 1.

In the second form the file descriptor given by the arithmetic expression FD_EXPR is closed, releasing a lock. The file descriptor can be queried by using the '-f VAR' form during the lock; on a successful lock, the shell variable 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 'exec {VAR}>&-'; 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 -t TIMEOUT specifies a timeout for the lock in seconds; currently this must be an integer. The shell will attempt to lock the file once a second during this period. If the attempt times out, status 2 is returned.

If the option -e is given, the file descriptor for the lock is preserved when the shell uses exec to start a new process; otherwise it is closed at that point and the lock released.

If the option -r is given, the lock is only for reading, otherwise it is for reading and writing. The file descriptor is opened accordingly.

zsystem supports SUBCOMMAND
The built-in zsystem's subcommand 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 (such as the wrong number of arguments), in which case status 255 is returned. Status 1 can indicate one of two things: SUBCOMMAND is known but not supported by the current operating system, or SUBCOMMAND is not known (possibly because this is an older version of the shell before it was implemented).
Math functions
systell(FD)
The systell math function returns the current file position for the file descriptor passed as an argument.
Parameters
errnos
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 errno.h. The index of each name (assuming the option KSH_ARRAYS is unset) corresponds to the error number. Error numbers NUM before the last known error which have no name are given the name ENUM in the array.

Aliases for errors are not handled; only the canonical name is used.

sysparams
A readonly associative array. The keys are:
pid
Returns the process ID of the current process, even in subshells. Compare $$, which returns the process ID of the main shell process.
ppid
Returns the process ID of the parent of the current process, even in subshells. Compare $PPID, which returns the process ID of the parent of the main shell process.
procsubstpid
Returns the process ID of the last process started for process substitution, that is, the <(...) and >(...) expansions.

The zsh/termcap module

The zsh/termcap module makes available one built-in command:
echotc CAP [ ARG ... ]
Output the termcap value corresponding to the capability CAP, with optional arguments.
The zsh/termcap module makes available one parameter:
termcap
An associative array that maps termcap capability codes to their values.

The zsh/terminfo module

The zsh/terminfo module makes available one built-in command:
echoti CAP [ ARG ]
Output the terminfo value corresponding to the capability CAP, instantiated with ARG if applicable.
The zsh/terminfo module makes available one parameter:
terminfo
An associative array that maps terminfo capability names to their values.

The zsh/zselect module

The zsh/zselect module makes available one built-in command:
zselect [ -rwe ] [ -t TIMEOUT ] [ -a ARRAY ] [ -A ASSOC ] [ FD ... ]
The zselect built-in 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 systems documentation for man page select(3). Note there is no connection with the shell built-in 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, that is, 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 -r, -w and -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 -e option useful.)

The option '-t TIMEOUT' specifies a timeout in hundredths of a second. This may be zero, in which case the file descriptors will simply be polled and zselect will return immediately. It is possible to call zselect with no file descriptors and a nonzero timeout for use as a finer-grained replacement for 'sleep'; note, however, the return status is always 1 for a timeout.

The option '-a ARRAY' indicates that ARRAY should be set to indicate the file descriptor(s) which are ready. If the option is not given, the array reply will be used for this purpose. The array will contain a string similar to the arguments for zselect. For example,
zselect -t 0 -r 0 -w 1
might return immediately with status 0 and $reply containing '-r 0 -w 1' to show that both file descriptors are ready for the requested operations.

The option '-A ASSOC' indicates that the associative array ASSOC should be set to indicate the file descriptor(s) which are ready. This option overrides the option -a, nor will reply be modified. The keys of assoc are the file descriptors, and the corresponding values are any of the characters '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.

The zsh/zutil module

The zsh/zutil module only adds some built-ins:
zstyle [ -L [ METAPATTERN [ STYLE ] ] ]
zstyle [ -e | - | -- ] PATTERN STYLE STRING ...
zstyle -d [ PATTERN [ STYLE ... ] ]
zstyle -g NAME [ PATTERN [ STYLE ] ]
zstyle -{a|b|s} CONTEXT STYLE NAME [ SEP ]
zstyle -{T|t} CONTEXT STYLE [ STRING ... ]
zstyle -m CONTEXT STYLE PATTERN
This built-in 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 '*'. A '*' 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 favor of the pattern that was defined first.

For example, to define your preferred form of precipitation depending on which city you're in, you might set the following in your zshrc:
          zstyle ':weather:europe:*' preferred-precipitation rain
          zstyle ':weather:europe:germany:* preferred-precipitation none
          zstyle ':weather:europe:germany:*:munich' preferred-precipitation snow
Then, the fictional 'weather' plugin might run under the hood a command such as
zstyle -s ":weather:${continent}:${country}:${county}:${city}" preferred-precipitation REPLY
in order to retrieve your preference into the scalar variable $REPLY.
The forms that operate on patterns are the following.
zstyle [ -L [ METAPATTERN [ STYLE ] ] ]
Without arguments, lists style definitions. Styles are shown in alphabetic order and patterns are shown in the order zstyle will test them.

If the -L option is given, listing is done in the form of calls to zstyle. The optional first argument, METAPATTERN, is a pattern which will be matched against the string supplied as PATTERN when the style was defined. The optional second argument limits the output to a specific STYLE (not a pattern). -L is not compatible with any other options.

zstyle [ - | -- | -e ] PATTERN STYLE STRING ...
Defines the given STYLE for the PATTERN with the STRINGs as the value. If the -e option is given, the STRINGs will be concatenated (separated by spaces) and the resulting string will be evaluated (in the same way as it is done by the eval built-in command) when the style is looked up. In this case the parameter 'reply' must be assigned to set the strings returned after the evaluation. Before evaluating the value, reply is unset, and if it is still unset after the evaluation, the style is treated as if it were not set.
zstyle -d [ PATTERN [ STYLE ... ] ]
Delete style definitions. Without arguments all definitions are deleted, with a PATTERN all definitions for that pattern are deleted and if any STYLEs are given, then only those styles are deleted for the PATTERN.
zstyle -g NAME [ PATTERN [ STYLE ] ]
Retrieve a style definition. The 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 PATTERN the styles defined for that pattern are returned and with both a PATTERN and a STYLE, the value strings of that combination is returned.
The other forms can be used to look up or test styles for a given context.
zstyle -s CONTEXT STYLE NAME [ SEP ]
The parameter 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 SEP string if that is given) between them.

Return 0 if the style is set, 1 otherwise.

zstyle -b CONTEXT STYLE NAME
The value is stored in NAME as a boolean, that is, as the string 'yes' if the value has only one string and that string is equal to one of 'yes', 'true', 'on', or '1'. If the value is any other string or has more than one string, the parameter is set to 'no'.

Return 0 if NAME is set to 'yes', 1 otherwise.

zstyle -a CONTEXT STYLE NAME
The value is stored in NAME as an array. If NAME is declared as an associative array, the first, third, and so on, strings are used as the keys and the other strings are used as the values.

Return 0 if the style is set, 1 otherwise.

zstyle -t CONTEXT STYLE [ STRING ... ]
zstyle -T CONTEXT STYLE [ STRING ... ]
Test the value of a style, that is, the -t option only returns a status (sets $?). Without any 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 'true', 'yes', 'on' or '1'. If any STRINGs are given the status is zero if and only if at least one of the STRINGs 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 1. If the style is not defined, the status is 2.

The -T option tests the values of the style like -t, but it returns status zero (rather than 2) if the style is not defined for any matching pattern.

zstyle -m CONTEXT STYLE PATTERN
Match a value. Returns status zero if the PATTERN matches at least one of the strings in the value.
zformat -f PARAM FORMAT SPEC ...
zformat -a ARRAY SEP SPEC ...
This built-in provides two different forms of formatting. The first form is selected with the -f option. In this case the FORMAT string will be modified by replacing sequences starting with a percent sign in it with strings from the SPECs. Each SPEC should be of the form 'CHAR:STRING' which will cause every appearance of the sequence '%CHAR' in FORMAT to be replaced by the STRING. The '%' sequence may also contain optional minimum and maximum field width specifications between the '%' and the 'CHAR' in the form '%MIN.MAXc', that is, 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 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 STRING will be truncated after that many characters. After all '%' sequences for the given SPECs have been processed, the resulting string is stored in the parameter PARAM.

The %-escapes also understand ternary expressions in the form used by prompts. The % is followed by a '(' and then an ordinary format specifier character. There may be a set of digits either before or after the '('; 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 '%(X.TEXT1.TEXT2)', except that the '.' character is arbitrary. The value given for the format specifier in the CHAR:STRING expressions is evaluated as a mathematical expression, and compared with the test number. If they are the same, TEXT1 is output, else TEXT2 is output. A parenthesis can be escaped in TEXT2 as %). Either of TEXT1 or TEXT2 may contain nested %-escapes.

For example:
 zformat -f REPLY "The answer is '%3(c.yes.no)'." c:3
outputs "The answer is 'yes'." to REPLY since the value for the format specifier c is 3, agreeing with the digit argument to the ternary expression.

The second form, using the -a option, can be used for aligning strings. Here, the SPECs are of the form 'LEFT:RIGHT' where 'LEFT' and 'RIGHT' are arbitrary strings. These strings are modified by replacing the colons by the SEP string and padding the LEFT strings with spaces to the right so that the SEP strings in the result (and hence the RIGHT strings after them) are all aligned if the strings are printed under each other. All strings without a colon are left unchanged and all strings with an empty 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 LEFT string can be escaped with a backslash. The resulting strings are stored in the ARRAY.

zregexparse
This implements some internals of the regex_arguments function.
zparseopts [ -D -E -F -K -M ] [ -a ARRAY ] [ -A ASSOC ] [ - ] SPEC ...
This built-in simplifies the parsing of options in positional parameters, that is, the set of arguments given by $*. Each SPEC describes one option and must be of the form 'OPT[=ARRAY]'. If an option described by OPT is found in the positional parameters it is copied into the ARRAY specified with the -a option. If the optional '=ARRAY' is given, it is instead copied into that array, which should be declared as a normal array and never as an associative array.

It is an error to give any SPEC without an '=ARRAY' unless one of the -a or -A options is used.

Unless the -E option is given, parsing stops at the first string that isn't described by one of the SPECs. Even with -E, parsing always stops at a positional parameter equal to '-' or '--'. See also -F.

The 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.
NAME
NAME+
The NAME is the name of the option without the leading '-'. To specify a GNU-style long option, one of the usual two leading '-' must be included in NAME; for example, a '--file' option is represented by a NAME of '-file'.

If a '+' appears after NAME, the option is appended to ARRAY each time it is found in the positional parameters; without the '+' 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 '-' (unless the -E option is used).

NAME:
NAME:-
NAME::
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 ARRAY after the option itself.

An optional argument is put into the same array element as the option name, which makes empty strings as arguments indistinguishable. A mandatory argument is added as a separate element unless the ':-' form is used, in which case the argument is put into the same element.

A '+' can appear between the NAME and the first colon.

In all cases, option-arguments must 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 '-'. There is no special handling of '=' as with GNU-style argument parsers; given the SPEC '-foo:', the positional parameter '--foo=bar' is parsed as '--foo' with an argument of '=bar'.

When the names of two options that take no arguments overlap, the longest option wins, so that parsing for the SPECs '-foo -foobar' (for example) is unambiguous. However, due to the handling of option-arguments, ambiguities might arise when at least one overlapping SPEC takes an argument, as in '-foo: -foobar'. In that case, the last matching SPEC wins.

The options of zparseopts itself cannot be stacked because, for example, the stack '-DEK' is indistinguishable from a SPEC for the GNU-style long option '--DEK'. The options of zparseopts itself are as follows:
-a ARRAY
Names the default array in which to store the recognized options.
-A ASSOC
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.
-D
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 that is not described by the SPECs. If the first such parameter is '-' or '--', it is removed as well. This is similar to using the shift built-in.
-E
This changes the parsing rules to not stop at the first string that is not described by one of the SPECs. It can be used to test for or (if used together with -D) extract options and their arguments, ignoring all other options and arguments that may be in the positional parameters. Parsing still stops at the first '-' or '--' not described by a SPEC, but it is not removed when used with -D.
-F
If this option is given, zparseopts immediately stops at the first option-like parameter that is not described by one of the SPECs, prints an error message, and returns status 1. Removal (-D) and extraction (-E) are not performed, and option arrays are not updated. This provides basic validation for the given options.

The appearance in the positional parameters of an option without its required argument always aborts parsing and returns an error regardless of whether this option is used.

-K
With this option, the arrays that are specified with the -a option and with the '=ARRAY' forms are kept unchanged when none of the SPECs for them is used. Otherwise, the entire array is replaced when any of the SPECs is used. Individual elements of associative arrays that are specified with the -A option are preserved by -K. This allows assignment of default values to arrays before calling zparseopts.
-M
This changes the assignment rules to implement a map among equivalent option names. If any SPEC uses the '=ARRAY' form, the string ARRAY is interpreted as the name of another SPEC, which is used to choose where to store the values. If no other SPEC is found, the values are stored as usual. This changes only the way that the values are stored, not the way $* is parsed. Results might be unpredictable if the 'NAME+' specifier is used inconsistently.
For example,
          set -- -a -bx -c y -cz baz -cend
          zparseopts a=foo b:=bar c+:=bar
has the effect of
          foo=(-a)
          bar=(-b x -c y -c z)
The arguments from 'baz' on is not used.
As an example for the -E option, consider:
          bar=(-b y)
          set -- -a x -c z arg1 arg2
that is, the option -b and its arguments are taken from the positional parameters and put into the array bar.
The -M option can be used like this:
          set -- -a -bx -c y -cz baz -cend
          zparseopts -A bar -M a=foo b+: c:=b
to have the effect of
          foo=(-a)
          bar=(-a '' -b xyz)
End of change