18.3 Zle Builtins

The ZLE module contains three related builtin commands. The bindkey command manipulates keymaps and key bindings; the vared command invokes ZLE on the value of a shell parameter; and the zle command manipulates editing widgets and allows command line access to ZLE commands from within shell functions.

bindkey [ options ] -l [ -L ] [ keymap ... ]
bindkey [ options ] -d
bindkey [ options ] -D keymap ...
bindkey [ options ] -A old-keymap new-keymap
bindkey [ options ] -N new-keymap [ old-keymap ]
bindkey [ options ] -m
bindkey [ options ] -r in-string ...
bindkey [ options ] -s in-string out-string ...
bindkey [ options ] in-string command ...
bindkey [ options ] [ in-string ]

bindkey’s options can be divided into three categories: keymap selection for the current command, operation selection, and others. The keymap selection options are:

-e

Selects keymap ‘emacs’ for any operations by the current command, and also links ‘emacs’ to ‘main’ so that it is selected by default the next time the editor starts.

-v

Selects keymap ‘viins’ for any operations by the current command, and also links ‘viins’ to ‘main’ so that it is selected by default the next time the editor starts.

-a

Selects keymap ‘vicmd’ for any operations by the current command.

-M keymap

The keymap specifies a keymap name that is selected for any operations by the current command.

If a keymap selection is required and none of the options above are used, the ‘main’ keymap is used. Some operations do not permit a keymap to be selected, namely:

-l

List all existing keymap names; if any arguments are given, list just those keymaps.

If the -L option is also used, list in the form of bindkey commands to create or link the keymaps. ‘bindkey -lL main’ shows which keymap is linked to ‘main’, if any, and hence if the standard emacs or vi emulation is in effect. This option does not show the .safe keymap because it cannot be created in that fashion; however, neither is ‘bindkey -lL .safe’ reported as an error, it simply outputs nothing.

-d

Delete all existing keymaps and reset to the default state.

-D keymap ...

Delete the named keymaps.

-A old-keymap new-keymap

Make the new-keymap name an alias for 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 new-keymap name, it is deleted.

-N new-keymap [ old-keymap ]

Create a new keymap, named new-keymap. If a keymap already has that name, it is deleted. If an old-keymap name is given, the new keymap is initialized to be a duplicate of it, otherwise the new keymap will be empty.

To use a newly created keymap, it should be linked to main. Hence the sequence of commands to create and use a new keymap ‘mymap’ initialized from the emacs keymap (which remains unchanged) is:

bindkey -N mymap emacs
bindkey -A mymap main

Note that while ‘bindkey -A newmap main’ will work when newmap is emacs or viins, it will not work for vicmd, as switching from vi insert to command mode becomes impossible.

The following operations act on the ‘main’ keymap if no keymap selection option was given:

-m

Add the built-in set of meta-key bindings to the selected keymap. Only keys that are unbound or bound to self-insert are affected.

-r in-string ...

Unbind the specified in-strings in the selected keymap. This is exactly equivalent to binding the strings to undefined-key.

When -R is also used, interpret the in-strings as ranges.

When -p is also used, the in-strings specify prefixes. Any binding that has the given in-string as a prefix, not including the binding for the in-string itself, if any, will be removed. For example,

bindkey -rpM viins '^['

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 vi-cmd-mode). This is incompatible with the option -R.

-s in-string out-string ...

Bind each in-string to each out-string. When in-string is typed, out-string will be pushed back and treated as input to the line editor. When -R is also used, interpret the in-strings as ranges.

Note that both in-string and out-string are subject to the same form of interpretation, as described below.

in-string command ...

Bind each in-string to each command. When -R is used, interpret the in-strings as ranges.

[ in-string ]

List key bindings. If an 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 -e or -v option is used alone, the keymap is not displayed - the implicit linking of keymaps is the only thing that happens.)

When the option -p is used, the 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 -L option is used, the list is in the form of bindkey commands to create the key bindings.

When the -R option is used as noted above, a valid range consists of two characters, with an optional ‘-’ between them. All characters between the two specified, inclusive, are bound as specified.

For either in-string or out-string, the following escape sequences are recognised:

\a

bell character

\b

backspace

\e, \E

escape

\f

form feed

\n

linefeed (newline)

\r

carriage return

\t

horizontal tab

\v

vertical tab

\NNN

character code in octal

\xNN

character code in hexadecimal

\uNNNN

unicode character code in hexadecimal

\UNNNNNNNN

unicode character code in hexadecimal

\M[-]X

character with meta bit set

\C[-]X

control character

^X

control character

In all other cases, ‘\’ escapes the following character. Delete is written as ‘^?’. Note that ‘\M^?’ and ‘^\M?’ are not the same, and that (unlike emacs), the bindings ‘\M-X’ and ‘\eX’ are entirely distinct, although they are initialized to the same bindings by ‘bindkey -m’.

vared [ -Aacghe ] [ -p prompt ] [ -r rprompt ]
      [ -M main-keymap ] [ -m vicmd-keymap ]
      [ -i init-widget ] [ -f finish-widget ]
      [ -t tty ] name

The value of the parameter name is loaded into the edit buffer, and the line editor is invoked. When the editor exits, name is set to the string value returned by the editor. When the -c flag is given, the parameter is created if it doesn’t already exist. The -a flag may be given with -c to create an array parameter, or the -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 -g flag may be given to suppress warnings from the WARN_CREATE_GLOBAL and WARN_NESTED_VAR options.

If an array or array slice is being edited, separator characters as defined in $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 name. New elements are created automatically, even without -c.

If the -p flag is given, the following string will be taken as the prompt to display at the left. If the -r flag is given, the following string gives the prompt to display at the right. If the -h flag is specified, the history can be accessed from ZLE. If the -e flag is given, typing ^D (Control-D) on an empty line causes vared to exit immediately with a non-zero return value.

The -M option gives a keymap to link to the main keymap during editing, and the -m option gives a keymap to link to the vicmd keymap during editing. For vi-style editing, this allows a pair of keymaps to override viins and vicmd. For emacs-style editing, only -M is normally needed but the -m option may still be used. On exit, the previous keymaps will be restored.

Vared calls the usual ‘zle-line-init’ and ‘zle-line-finish’ hooks before and after it takes control. Using the -i and -f options, it is possible to replace these with other custom widgets.

If ‘-t tty’ is given, tty is the name of a terminal device to be used instead of the default /dev/tty. If tty does not refer to a terminal an error is reported.

zle
zle -l [ -L | -a ] [ string ... ]
zle -D widget ...
zle -A old-widget new-widget
zle -N widget [ function ]
zle -f flag [ flag... ]
zle -C widget completion-widget function
zle -R [ -c ] [ display-string ] [ string ... ]
zle -M string
zle -U string
zle -K keymap
zle -F [ -L | -w ] [ fd [ handler ] ]
zle -I
zle -T [ tc function | -r tc | -L ]
zle widget [ -n num ] [ -f flag ] [ -Nw ] [ -K keymap ] args ...

The 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:

-l [ -L | -a ] [ string ]

List all existing user-defined widgets. If the -L option is used, list in the form of zle commands to create the widgets.

When combined with the -a option, all widget names are listed, including the builtin ones. In this case the -L option is ignored.

If at least one string is given, and -a is present or -L is not used, nothing will be printed. The return status will be zero if all strings are names of existing widgets and non-zero if at least one string is not a name of a defined widget. If -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 string is present and the -L option is used, user-defined widgets matching any string are listed in the form of zle commands to create the widgets.

-D widget ...

Delete the named widgets.

-A old-widget new-widget

Make the new-widget name an alias for 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 new-widget name, it is deleted.

-N widget [ function ]

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 function is called. If no function name is specified, it defaults to the same name as the widget. For further information, see Zle Widgets.

-f flag [ flag... ]

Set various flags on the running widget. Possible values for flag are:

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 YANK_START and YANK_END correctly. yankbefore does the same but is used when the yanked text appears after the cursor.

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 ‘zle -f kill’ to retain this effect.

vichange for indicating that the widget represents a vi change that can be repeated as a whole with ‘vi-repeat-change’. The flag should be set early in the function before inspecting the value of 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.

-C widget completion-widget function

Create a user-defined completion widget named widget. The completion widget will behave like the built-in completion-widget whose name is given as completion-widget. To generate the completions, the shell function function will be called. For further information, see Completion Widgets.

-R [ -c ] [ display-string ] [ string ... ]

Redisplay the command line. If a display-string is given and not empty, this is shown in the status line (immediately below the line being edited).

If the optional strings are given they are listed below the prompt in the same way as completion lists are printed. If no strings are given but the -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.

-M string

As with the -R option, the string will be displayed below the command line; unlike the -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 string will still be displayed after the widget returns (until it is overwritten by subsequent commands).

-U string

This pushes the characters in the string onto the input stack of ZLE. After the widget currently executed finishes ZLE will behave as if the characters in the 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 string will be processed in the order in which they appear in the string.

-K keymap

Selects the keymap named 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 ‘main’ keymap selected.

-F [ -L | -w ] [ fd [ handler ] ]

Only available if your system supports one of the ‘poll’ or ‘select’ system calls; most modern systems do.

Installs handler (the name of a shell function) to handle input from file descriptor fd. Installing a handler for an 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 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 fd’s. If data becomes available on a handled fd, zle calls 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: ‘hup’ for a disconnect, ‘nval’ for a closed or otherwise invalid descriptor, or ‘err’ for any other condition. Systems that support only the ‘select’ system call always use ‘err’.

If the option -w is also given, the handler is instead a line editor widget, typically a shell function made into a widget using ‘zle -N’. In that case handler can use all the facilities of zle to update the current editing line. Note, however, that as handling fd takes place at a low level changes to the display will not automatically appear; the widget should call ‘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 ‘zle -I’ before doing so (see below). Handlers should not attempt to read from the terminal.

If no handler is given, but an fd is present, any handler for that fd is removed. If there is none, an error message is printed and status 1 is returned.

If no arguments are given, or the -L option is supplied, a list of handlers is printed in a form which can be stored for later execution.

An fd (but not a handler) may optionally be given with the -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 fd’s which is not properly handled can cause the terminal to become unusable. Removing an 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 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.

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
-I

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:

TRAPUSR1() {
  # Invalidate zle display
  [[ -o zle ]] && zle -I
  # Show output
  print Hello
}

In general, the trap function may need to test whether zle is active before using this method (as shown in the example), since the zsh/zle module may not even be loaded; if it is not, the command can be skipped.

It is possible to call ‘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, ‘zle -R’ above.

The returned status is zero if zle was invalidated, even though this may have been by a previous call to ‘zle -I’ or by a system notification. To test if a zle widget may be called at this point, execute zle with no arguments and examine the return status.

-T

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.

zle -T transformation func’ specifies that the given transformation (see below) is effected by shell function func.

zle -Tr transformation’ removes the given transformation if it was present (it is not an error if none was).

zle -TL’ can be used to list all transformations currently in operation.

Currently the only transformation is 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 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.

widget [ -n num ] [ -f flag ] [ -Nw ] [ -K keymap ] args ...

Invoke the specified widget. This can only be done when ZLE is active; normally this will be within a user-defined widget.

With the options -n and -N, the current numeric argument will be saved and then restored after the call to widget; ‘-n num’ sets the numeric argument temporarily to num, while ‘-N’ sets it to the default, i.e. as if there were none.

With the option -K, 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 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 -w, WIDGET and related parameters are set to reflect the widget being executed by the zle call.

Normally, when widget returns the special parameter LASTWIDGET will point to it. This can be inhibited by passing the option -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 --. 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 history-search-forward and -backward and the corresponding functions prefixed by vi-, and by 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 BEEP options was unset or the widget was called via the zle command. Thus if a user defined widget requires an immediate beep, it should call the beep widget directly.