text: NAME
  zshcontrib - user contributions to zsh
  DESCRIPTION.
  UTILITIES
  Accessing On-Line Help The key sequence ESC h is normally bound by ZLE to execute the run-help widget (see zshzle(1)).: mkdir ~/zsh_help cd ~/zsh_help man zshall | colcrt - | \ perl ~/zsh-4.3.17/Util/helpfiles Next, to use the run-help function, you need to add lines something like the following to your .zshrc or equivalent startup file: unalias run-help autoload run-help HELPDIR=~/zsh_help The HELPDIR parameter tells run-help where to look for the help files. If your system already has a help file directory installed, set HELPDIR to the path of that directory instead. Note that in order for `autoload run-help' to work, the run-help file must be in one of the directories named in your fpath array (see zshparam(1)). This should already be the case if you have a standard zsh installation; if it is not, copy Functions/Misc/run-help to an appropriate directory. Recompiling Functions. zrecompile [ -qt ] [ name ... ] zrecompile [ -qt ] -p args [ -- args ... ] `--'. For example: zrecompile -p \ -R ~/.zshrc -- \ -M ~/.zcompdump -- \ ~/zsh/comp.zwc ~/zsh/Completion/*/_*: for (. Keyboard Definition: zsh -f ~/zsh-4.3.17/Functions/Misc/zkbd `source' or `.' commands, then reference the key parameter in bindkey commands, like this: source ${ZDOTDIR:-$HOME}/.zkbd/$TERM-$VENDOR-$OSTYPE [[ -n ${key[Left]} ]] && bindkey "${key[Left]}" backward-char [[ -n ${key[Right]} ]] && bindkey "${key[Right]}" forward-char # etc. Note that in order for `autoload zkbd' to work, the zkdb file must be in one of the directories named in your fpath array (see zshparam(1)). This should already be the case if you have a standard zsh installation; if it is not, copy Functions/Misc/zkbd to an appropriate directory. Dumping Shell State 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 zsh(1)), `zsh -f' to recreate that state. To use reporter, read the script into your shell with the `.' command and redirect the output into a file: . ~/zsh-4.3.17/Util/reporter > zsh.report zshcompsys(1)). reporter [ state ... ] Print to standard output the indicated subset of the current shell state. The state arguments may be one or more of: all Output everything listed below. aliases Output alias definitions. bindings Output ZLE key maps and bindings. completion Output old-style compctl commands. New completion is covered by functions and zstyles. functions Output autoloads and function definitions. limits Output limit commands. options Output setopt commands. styles Same as zstyles. variables Output shell parameter assignments, plus export commands for any environment variables. zstyles Output zstyle commands. If the state is omitted, all is assumed. With the exception of `all', every state can be abbreviated by any prefix, even a single letter; thus a is the same as aliases, z is the same as zstyles, etc. Manipulating Hook Functions add-zsh-hook [-dD] hook function Several functions are special to the shell, as described in the section SPECIAL FUNCTIONS, see zshmisc(1), in that they are automatic called at a specific point 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.
  REMEMBERING RECENT DIRECTORIES.) 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 add-zsh-hook function described above: autoload -Uz chpwd_recent_dirs cdr add-zsh-hook add-zsh-hook chpwd chpwd_recent_dirs 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. Use: zstyle ':completion:*:*:cdr:*:*' menu selection. Options The behaviour of cdr may be modified by the following options. -l lists the numbers and the corresponding directories in abbreviated form (i.e. with ~ 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. -r sets the variable reply to the current set of directories. Nothing is printed and the directory is not changed. -e Configuration is by means of the styles mechanism that should be familiar from completion; if not, see the description of the zstyle command in see zshmodules(1). The context for setting styles should be ':chpwd:*' in case the meaning of the context is extended in future, for example: zstyle ':chpwd:*' recent-dirs-max 0. recent-dirs-default. recent-dirs-file: zstyle ':chpwd:*' recent-dirs-file \ ~/.chpwd-recent-dirs-${TTY##*/} + 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 zstyle -e to make the directory configurable at run time: 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 } In this example, if the current directory is ~/text/writing or a directory under it, then use a special file for saving recent directories, else use the default. recent-dirs-insert. recent-dirs-max. recent-dirs-prune This style is an array determining what directories should (or should not) be added to the recent list. Elements of the array can include: parent. pattern:pattern. recent-dirs-pushd. Use with dynamic directory naming It is possible to refer to recent directories using the dynamic directory name syntax by using the supplied function zsh_directory_name_cdr a hook: autoload -Uz add-zsh-hook add-zsh-hook -Uz zsh_directory_name zsh_directory_name_cdr When this is done, ~[1] will refer to the most recent directory other than $PWD, and so on. Completion after ~[... also works. Details of directory handling.
  GATHERING INFORMATION FROM VERSION CONTROL SYSTEMS: Bazaar (bzr) Codeville (cdv) Concurrent Versioning System (cvs) Darcs (darcs) Fossil (fossil) Git (git) GNU arch (tla) Mercurial (hg) Monotone (mtn) Perforce (p4) Subversion (svn) SVK (svk) There is also support for the patch management system quilt (). See Quilt Support below for details. To load vcs_info: autoload -Uz vcs_info It can be used in any existing prompt, because it does not require any $psvar entries to be left available. Quickstart To get this feature working quickly (including colors), you can do the following (assuming, you loaded vcs_info properly - see above):: % vcs_info_printsys ## list of supported version control backends: ## disabled systems are prefixed by a hash sign (#) bzr cdv cvs darcs fossil 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: zstyle ':vcs_info:*' disable bzr cdv darcs mtn svk tla You may also pick a few from that list and enable only those: zstyle ':vcs_info:*' enable git cvs svn. Configuration The vcs_info feature can be configured via zstyle. First, the context in which we are working: :vcs_info:vcs-string:user-context:repo-root-name vcs-string `+'. (See Hooks in vcs_info below.) user-context is a freely configurable string, assignable by the user as the first argument to vcs_info (see its description below). repo-root-name: default the one used if none is specified command used by vcs_info_lastmsg to lookup its styles You can of course use ':vcs_info:*' to match all VCSs in all user-contexts at once. This is a description of all styles that are looked up. formats A list of formats, used when actionformats is not used (which is most of the time). actionformats 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. branchformat Some backends replace %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. nvcsformatsgrevformat 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 branchformat) to include either or both. It's only useful when get-revision is true. max-exports Defines the maximum number of vcs_info_msg_*_ variables vcs_info will export. enable. disable A list of VCSs you don't want vcs_info to test for repositories (checked in the -init- context, too). Only used if enable contains ALL. disable-patterns: zstyle ':vcs_info:*' disable-patterns "$HOME/.zsh(|/*)" use-quilt If enabled, the quilt support code is active in `addon' mode. See Quilt Support for details. quilt-standalone If enabled, `standalone' mode detection is attempted if no VCS is active in a given directory. See Quilt Support for details. quilt-patch-dir Overwrite the value of the $QUILT_PATCHES environment variable. See Quilt Support for details. quiltcommand When quilt itself is called in quilt support the value of this style is used as the command name. check-for-changes. stagedstr This string will be used in the %c escape if there are staged changes in the repository. unstagedstr This string will be used in the %u escape if there are unstaged changes in the repository. command: zstyle ':vcs_info:git:*:-all-' command /usr/local/bin/git use-server. use-simple. get-revision. get-mq If set to true, the hg backend will look for a Mercurial Queue (mq) patch directory. Information will be available via the `%m' replacement. get-bookmarks If set to true, the hg backend will try to get a list of current bookmarks. They will be available via the `%m' replacement. use-prompt-escapes Determines if we assume that the assembled string from vcs_info includes prompt escapes. (Used by vcs_info_lastmsg.) debug Enable debugging output to track possible problems. Currently this style is only used by vcs_info's hooks system. hooks A list style that defines hook-function names. See Hooks in vcs_info below for details. The default values for these styles in all contexts are: formats " (%s)-[%b]%u%c-" actionformats " (%s)-[%b|%a]%u%c-" branchformat "%b:%r" (for bzr, svn, svk and hg) nvcsformats "" hgrevformat "%r:%h" max-exports 2 enable ALL disable (empty list) disable-patterns (empty list) check-for-changes false stagedstr (string: "S") unstagedstr (string: "U") command (empty string) use-server false use-simple false get-revision false get-mq true get-bookmarks false use-prompt-escapes true debug false hooks (empty list) use-quilt false quilt-standalone false quilt-patch-dir empty - use $QUILT_PATCHES quiltcommand quilt In normal formats and actionformats the following replacements are done: %s The VCS in use (git, hg, svn, etc.). %b Information about the current branch. %a An identifier that describes the action. Only makes sense in actionformats. %i The current revision number or identifier. For hg the hgrevformat style may be used to customize the output. %c The string from the stagedstr style if there are staged changes in the repository. %u The string from the unstagedstr style if there are unstaged changes in the repository. %R The base directory of the repository. %r The repository name. If %R is /foo/bar/repoXY, %r is repoXY. %S A subdirectory within a repository. If $PWD is /foo/bar/repoXY/beer/tasty, %S is beer/tasty. %m A "misc" replacement. It is at the discretion of the backend to decide what this replacement expands to. It is currently used by the hg and git backends to display patch information from the mq and stgit extensions. In branchformat these replacements are done: %b The branch name. %r The current revision number or the hgrevformat style for hg. In hgrevformat these replacements are done: %r The current local revision number. %h The current 40-character changeset ID hash identifier. In patch-format and nopatch-format these replacements are done: %p The name of the top-most applied patch. %u The number of unapplied patches. %n The number of applied patches. %c The number of unapplied patches. %g The names of active mq guards (hg backend). %G The number of active mq guards (hg backend). Not all VCS backends have to support all replacements. For nvcsformats no replacements are performed at all, it is just a string. Oddities Support: `addon' mode and `standalone' mode). For `addon' mode to become active 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 `QUILT_PATCHES' environment variable. If that variable exists its value is used, otherwise the value `patches' is assumed. The value from $QUILT_PATCHES can be overwritten using the `qu `addon' mode, the produced string is available as a simple format replacement (%Q to be precise), which can be used in formats and actionformats; see below for details). If, on the other hand, the support code is working in `standalone' mode, vcs_info will pretend as if 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 `-quilt-'. This has implications on the used style context where this identifier is the second element. 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 %Q for compatibility with `addon' mode. `standalone' mode to minimise the amount of searching on every call to vcs_info, there are a number of ways to do that: Essentially, `standalone' mode detection is controlled by a style called `quilt-standalone'. It is a string style and its value can have different effects. The simplest values are: `always' to run detection every time vcs_info is run, and `never' to turn the detection off entirely. If the value of 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' `true'. Last, but not least, if the value of 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 quilt-standalone, the function will take precedence. Function Descriptions (Public API) vcs_info [user-context]. vcs_info_hookadd 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 `+vi-' prefix needs to be left out here. See Hooks in vcs_info below for details. vcs_info_hookdel 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 `-a' is used as the first argument, all occurances of the functions are unregistered. Otherwise only the last occurance is removed (if a function was registered to a hook more than once) . The `+vi-' prefix needs to be left out here. See Hooks in vcs_info below for details. vcs_info_lastmsg Outputs the last ${vcs_info_msg_*_} value. Takes into account the value of the use-prompt-escapes style in ':vcs_info:formats:command:-all-'. It also only prints max-exports values. vcs_info_printsys [user-context] 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 disable style. vcs_info_setsys Initializes vcs_info's internal list of available backends. With this function, you can add support for new VCSs without restarting the shell. All functions named VCS_INFO_* are for internal use only. Variable Description ${vcs_info_msg_N_} (Note the trailing underscore) in vcs_info Hooks are places in 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: :vcs_info:vcs-string+hook-name:user-context:repo-root-name To register functions to a hook, you need to list them in the hooks style in the appropriate context. Example: zstyle ':vcs_info:*+foo:*' hooks bar baz This registers functions to the hook `foo' for all backends. In order to avoid namespace problems, all registered function names are prepended by a `+vi-', so the actual functions called for the `foo' hook are `+vi-bar' and ` `debug': +vi-git-myfirsthook(){ user_data[myval]=$myval } +vi-git-mysecondhook(){ # do something with ${user_data[myval]} } There are a number of variables that are special in hook contexts: ret The return value that the hooks system will return to the caller. The default is an integer `zero'. If and how a changed ret value changes the execution of the caller depends on the specific hook. See the hook documentation below for details. hook_com An associated array which is used for bidirectional communication from the caller to hook functions. The used keys depend on the specific hook. context The active context of the hook. Functions that wish to change this variable should make it local scope first. vcs The current VCS after it was detected. The same values as in the enable/disable style are used. Available in all hooks except start-up. Finally, the full list of currently available hooks: start-up. pre-get-data Same as start-up but after the VCS was detected. gen-hg-bookmark-string Called in the Mercurial backend when a bookmark string is generated; the get-revision and get-bookmarks styles must be true. This hook gets the names of the Mercurial bookmarks that vcs_info collected from `hg'. When setting ret to non-zero, the string in ${hook_com[hg-bookmark-string]} will be used in the %m escape in formats and actionformats and will be availabe in the global backend_misc array as ${backend_misc[bookmarks]}. gen-applied-string. gen-unapplied-string. gen-mqguards-string. no-vcs This hooks is called when no version control system was detected. The `hook_com' parameter is not used. post-quilt Called after the 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 "-nopc-" if that directory wasn't found. The `hook_com' parameter is not used. set-branch-format Called before `branchformat' is set. The only argument to the hook is the format that is configured at this point. The `hook_com' keys considered are `branch' and `revision'. They are set to the values figured out so far by vcs_info and any change will be used directly when the actual replacement is done. If ret is set to non-zero, the string in ${hook_com[branch-replace]} will be used unchanged as the `%b' replacement in the variables set by vcs_info. set-hgrev-format Called before a `hgrevformat' is set. The only argument to the hook is the format that is configured at this point. The `hook_com' keys considered are `hash' and `localrev'. They are set to the values figured out so far by vcs_info and any change will be used directly when the actual replacement is done. If ret is set to non-zero, the string in ${hook_com[rev-replace]} will be used unchanged as the `%i' replacement in the variables set by vcs_info. set-message Called each time before a `vcs_info_msg_N_' message is set. It takes two arguments; the first being the `N' in the message variable name, the second is the currently configured formats or actionformats. There are a number of `hook_com' keys, that are used here: `action', `branch', `base', `base-name', `subdir', `staged', `unstaged', `revision', `misc', `vcs' and one `misc `hook_com' keys mentioned above (except for the miscN entries) has an `_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 `. Examples Don't use vcs_info at all (even though it's in your prompt): zstyle ':vcs_info:*' enable NONE Disable the backends for bzr and svk: zstyle ':vcs_info:*' disable bzr svk Disable everything but bzr and svk: zstyle ':vcs_info:*' enable bzr svk Provide a special formats for git: zstyle ':vcs_info:git:*' formats ' GIT, BABY! [%b]' zstyle ':vcs_info:git:*' actionformats ' GIT ACTION! [%b|%a]' All %x expansion in all sorts of formats ("formats", "actionformats", branchformat, you name it) are done using the `zformat' builtin from the `z `%min.maxx'. More is possible. See the section `The zsh/zutil Module' in zshmodules(1) for details. Use the quicker bzr backend zstyle ':vcs_info:bzr:*' use-simple true If you do use use-simple, please report if it does `the-right-thing[tm]'. Display the revision number in yellow for bzr and svn: zstyle ':vcs_info:(svn|bzr):*' branchformat '%b%{'${fg[yellow]}'%}:%r' If you want colors, make sure you enclose the color codes in %{...%} if you want to use the string provided by vcs_info in prompts. Here is how to print the VCS information as a command (not in a prompt): alias vcsi='vcs_info command; vcs_info_lastmsg' This way, you can even define different formats for output via vcs_info_lastmsg in the ':vcs_info:*:command:*' namespace. Now as promised, some code that uses hooks: say, you'd like to replace the string `svn' by `subversion' in vcs_info's %s formats replacement. First, we will tell vcs_info to call a function when populating the message variables with the gathered information: zstyle ':vcs_info:*+set-message:*' hooks svn2subversion 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 `debug' style: zstyle ':vcs_info:*+*:*' debug true That should give you an idea what is going on. Specifically, the function that we are looking for is `+vi-svn2subversion'. Note, the `+vi-' prefix. So, everything is in order, just as documented. When you are done checking out the debugging output, disable it again: zstyle ':vcs_info:*+*:*' debug false Now, let's define the function: function +vi-svn2subversion() { [[ ${hook_com[vcs_orig]} == svn ]] && hook_com[vcs]=subversion } 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 `svn' backend's context, we don't need to test which the active backend is: zstyle ':vcs_info:svn+set-message:*' hooks svn2subversion function +vi-svn2subversion() { hook_com[vcs]=subversion } And finally a little more elaborate example, that uses a hook to create a customised bookmark string for the hg backend. Again, we start off by registering a function: zstyle ':vcs_info:hg+gen-hg-bookmark-string:*' hooks hgbookmarks And then we define the `+vi-hgbookmarks function: } 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 vcs_info.
  PROMPT THEMES
  Installation You should make sure all the functions from the Functions/Prompts directory of the source distribution are available; they all begin with the string `prompt_' except for the special function`promptinit'. You also need the `colors': fpath=(~/myfns $fpath) autoload -U promptinit promptinit Theme Selection Use the prompt command to select your preferred theme. This command may be added to your .zshrc following the call to promptinit in order to start zsh with a theme already selected. prompt [ -c | -l ] prompt [ -p | -h ] [ theme ... ] prompt [ -s ] theme [ arg ... ] Set or examine the prompt theme. With no options and a theme argument, the theme with that name is set as the current theme. The available themes are determined at run time; use the -l option to see a list. The special theme `random' selects at random one of the available themes and sets your prompt to that. In some cases the 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: -c Show the currently selected theme and its parameters, if any. -l List all available prompt themes. -p Preview the theme named by theme, or all themes if no theme is given. -h Show help for the theme named by theme, or for the prompt function if no theme is given. -s Set theme as the current theme and save state. prompt_theme_setup.
  ZLE FUNCTIONS
  Widgets These functions all implement user-defined ZLE widgets (see zshzle(1)) which can be bound to keystrokes in interactive shells. To use them, your .zshrc should contain lines of the form autoload function zle -N function followed by an appropriate bindkey command to associate the function with a key sequence. Suggested bindings are described below. bash-style word functions 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: autoload -U select-word-style select-word-style bash forward-word-match, backward-word-match kill-word-match, backward-kill-word-match transpose-words-match, capitalize-word-match up-case-word-match, down-case-word-match select-word-style, match-word-context, match-words-by-style The eight `. bash Word characters are alphanumeric characters only. normal As in normal shell operation: word characters are alphanumeric characters plus any characters present in the string given by the parameter $WORDCHARS. shell Words are complete shell command arguments, possibly including complete quoted strings, or any tokens special to the shell. whitespace Words are any set of characters delimited by whitespace. default Restore the default settings; this is usually the same as `normal'. All but `default' `[:upper:]'; the value of the style is treated as the contents of a `[...]' pattern (note that the outer brackets should not be supplied, only those surrounding named ranges). More control can be obtained using the zstyle command, as described in zshmodules(1). `:zle:*' which can be overridden by more specific (longer) patterns as well as explicit contexts. The style word-style specifies the rules to use. This may have the following values. normal Use the standard shell rules, i.e. alphanumerics and $WORDCHARS, unless overridden by the styles word-chars or word-class. specified Similar to normal, but only the specified characters, and not also alphanumerics, are considered word characters. unspecified The negation of specified. The given characters are those which will not be considered part of a word. shell Words are obtained by using the syntactic rules for generating shell command arguments. In addition, special tokens which are never command arguments such as `()' are also treated as words. whitespace, `-:[:alnum:]' is a valid word-class to include all alphanumerics plus the characters `-' and `:'. Be careful including `]', `^' and `-' as these are special inside character classes. word-style may also have ` zstyle ':zle:transpose-words' skip-chars 1. Here are some examples of use of the styles, actually taken from the simplified interface in select-word-style: zstyle ':zle:*' word-style standard zstyle ':zle:*' word-chars '' Implements bash-style word handling for all widgets, i.e. only alphanumerics are word characters; equivalent to setting the parameter WORDCHARS empty for the given context. style ':zle:*kill*' word-style space Uses space-delimited words for widgets with the word `kill' in the name. Neither of the styles word-chars nor word-class is used in this case. Here are some examples of use of the word-context style to extend the context. zstyle ':zle:*' word-context "*/*" file "[[: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 word-style -s skip-chars -c word-class -C word-chars -r subword-range For example, match-words-by-style -w shell -c 0 may be used to extract the command argument around the cursor. The word-context style is implemented by the function match-word-context. This should not usually need to be called directly. copy-earlier-word. cycle-completion-positions. delete-whole-word-match: zle -N kill-whole-word-match delete-whole-word-match and then binding the widget kill-whole-word-match. up-line-or-beginning-search, down-line-or-beginning-command-line Edit the command line using your visual editor, as in ksh. bindkey -M vicmd v edit-command-line history-search-end This function implements the widgets history-beginning-search-backward-end and history-beginning-search-forward-end. These commands work by first calling the corresponding builtin widget (see `History Control' in zshzle(1)). 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 history-beginning-search-menu `-end' the cursor is moved to the end of the line inserted. If the widget name contains `-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 prefix argument). Both forms can be combined, for example: zle -N history-beginning-search-menu-space-end \ history-beginning-search-menu history-pattern-search: autoload -U history-pattern-search zle -N history-pattern-search-backward history-pattern-search zle -N history-pattern-search-forward history-pattern-search incarg. bindkey '^X+' incarg incremental-complete-word. bindkey '^Xi' incremental-complete-word insert-composed Cedilla. _ Underline, however there are currently no underlined characters. / Stroke through the base character. " Double acute (only supported on a few letters). ; Ogonek. (A little forward facing hook at the bottom right of the character.) < Caron. (A little v over the letter.) 0 Circle over the base character. 2 Hook over the base character. 9. ASCII characters These are already present on most keyboards: <( Left square bracket // Backslash (solidus) )> Right square bracket (! Left brace (curly bracket) !! Vertical bar (pipe symbol) !) Right brace (curly bracket) '? Tilde Special letters Characters found in various variants of the Latin alphabet: ss Eszett (scharfes S) D-, d- Eth TH, th Thorn kk Kra 'n 'n NG, ng Ng OI, oi Oi yr yr ED ezh Currency symbols Ct Cent Pd Pound sterling (also lira and others) Cu Currency Ye Yen Eu Euro (N.B. not in RFC 1345) Punctuation characters 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.) !I Inverted exclamation mark BB Broken vertical bar SE Section Co Copyright -a Spanish feminine ordinal indicator << Left guillemet -- Soft hyphen Rg Registered trade mark PI Pilcrow (paragraph) -o Spanish masculine ordinal indicator >> Right guillemet ?I Inverted question mark -1 Hyphen -N En dash -M Em dash -3 Horizontal bar :3 Vertical ellipsis .3 Horizontal midline ellipsis !2 Double vertical line =2 Double low line '6 Left single quote '9 Right single quote .9 "Right" low quote 9' Reversed "right" quote "6 Left double quote "9 Right double quote :9 "Right" low double quote 9" Reversed "right" double quote /- Dagger /= Double dagger Mathematical symbols DG Degree -2, +-, -+ - sign, +/- sign, -/+ sign 2S Superscript 2 3S Superscript 3 1S Superscript 1 My Micro .M Middle dot 14 Quarter 12 Half 34 Three quarters *X Multiplication -: Division %0 Per mille FA, TE, /0 For all, there exists, empty set dP, DE, NB Partial derivative, delta (increment), del (nabla) (-, -) Element of, contains *P, +Z Product, sum *-, Ob, Sb Asterisk, ring, bullet RT, 0(, 00 Root sign, proportional to, infinity Other symbols cS, cH, cD, cC Card suits: spades, hearts, diamonds, clubs Md, M8, M2, Mb, Mx, MX Musical notation: crotchet (quarter note), quaver (eighth note), semiquavers (sixteenth notes), flag sign, natural sign, sharp sign Fm, Ml Female, male Accents on their own '> Circumflex (same as caret, ^) '! Grave (same as backtick, `) ', Cedilla ': Diaeresis (Umlaut) 'm Macron '' Acute insert-files 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. bindkey '^Xf' insert-files insert-unicode-char When first executed, the user inputs a set of hexadecimal digits. This is terminated with another call to insert-unicode-char. The digits are then turned into the corresponding Unicode character. For example, if the widget is bound to ^XU, the character sequence `^XU 4 c ^XU' inserts L (Unicode U+004c). See insert-composed-char for a way of inserting characters using a two-character mnemonic. narrow-to-region [ -p pre ] [ -P post ] [ -S statepm | -R statepm ] [ -n ] [ start end ]) narrow-to-region-invisible `z. local state narrow-to-region -p $'Editing restricted region\n' \ -P '' -S state zle recursive-edit narrow-to-region -R state predict-on: delete-backward-and-predict Replaces the backward-delete-char widget. You do not need to bind this yourself. insert-and-predict Implements predictive typing by replacing the self-insert widget. You do not need to bind this yourself. predict-off Turns off predictive typing. Although you autoload only the predict-on function, it is necessary to create a keybinding for predict-off as well. zle -N predict-on zle -N predict-off bindkey '^X^Z' predict-on bindkey '^Z' predict-off read-from-minibuffer. replace-string, replace-pattern replace-string-again, replace-pattern-again The function 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 `pattern', for example by defining the widget using the command `z `&' in the replacement string will be replaced with the matched source string, and a backquoted digit `\N' will be replaced by the Nth parenthesised expression matched. The form `\{N}' may be used to protect the digit from following digits. If the widget instead contains the word `regex' (or `regex `pattern' or `regex',: print This line contains fan and fond and invoking replace-pattern with the source string `f(?)n' and the replacement string `c\1r' produces the not very useful line: print This line contains car and cord The range of the replacement string can be limited by using the narrow-to-region-invisible widget. One limitation of the current version is that undo will cycle through changes to the replacement and source strings before undoing the replacement itself. send-invisible 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 (`*') `Non. smart-insert-last-word This function may replace the insert-last-word widget, like so: zle -N insert-last-word smart-insert-last-word With a numeric prefix, or when passed command line arguments in a call from another widget, it behaves like insert-last-word, except that words in comments are ignored when INTERACTIVE_COMMENTS is set. Otherwise, the rightmost ``interesting'' word from the previous command is found and inserted. The default definition of ``interesting'': zle -N insert-last-assignment smart-insert-last-word zstyle :insert-last-assignment match '[[:alpha:]][][[:alnum:]]#=*' bindkey '\e=' insert-last-assignment If no interesting word is found and the auto-previous style is set to a true value, the search continues upward through the history. When auto-previous is unset or false (the default), the widget must be invoked repeatedly in order to search earlier history lines. transpose. which-command. Utility Functions These functions are useful in constructing widgets. They should be loaded with `autoload -U function' and called as indicated from user-defined widgets. split-shell-arguments. modify-current-argument expr-using-$ARG 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 should be an expression which when evaluated operates on the shell parameter 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. For example, a user-defined widget containing the following code converts the characters in the argument under the cursor into all upper case: modify-current-argument '${(U)ARG}' 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: modify-current-argument '${(qq)${(Q)ARG}}' Styles The behavior of several of the above widgets can be controlled by the use of the zstyle mechanism. In particular, widgets that interact with the completion system pass along their context to any completions that they invoke. break-keys `:incremental'. completer: zstyle ':completion:*' completer \ _complete _correct _approximate zstyle ':completion:incremental:*' completer \ _complete _correct zstyle ':completion:predict:*' completer \ _complete. cursor The insert-and-predict widget uses this style, in the context `:predict', to decide where to place the cursor after completion has been tried. Values are: complete 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 `key'. key. list When using the 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 `:completion:incremental'. The 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 always. In this case the context is `:predict' (not `:completion:predict'). match: zstyle :insert-last-word match '*[[:alpha:]/\\]*' However, you might want to include words that contain spaces: zstyle :insert-last-word match '*[[:alpha:][:space:]/\\]*' Or include numbers as long as the word is at least two characters long: zstyle :insert-last-word match '*([[:digit:]]?|[[:alpha:]/\\])*' The above example causes redirections like "2>" to be included. prompt The 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 PS1 and other prompt parameters: %c Replaced by the name of the completer function that generated the matches (without the leading underscore). %l When the list style is set, replaced by `...' if the list of matches is too long to fit on the screen and with an empty string otherwise. If the list style is `false' or not set, `%l' is always removed. %n Replaced by the number of matches generated. %s Replaced by `-no match-', `-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. %u Replaced by the unambiguous part of all matches, if there is any, and if it is different from the word on the line. Like `break-keys', this uses the `:incremental' context. stop-keys This style is used by the incremental-complete-word widget. Its value is treated similarly to the one for the break-keys style (and uses the same context: `: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. toggle This boolean style is used by predict-on and its related widgets in the context `:predict'.. verbose This boolean style is used by predict-on and its related widgets in the context `: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 toggle style. The default does not display these messages. widget). zstyle :copy-earlier-word widget smart-insert-last-word Check the documentation for the calling widget or function to determine whether the widget style is used.
  EXCEPTION HANDLING
  Two functions are provided to enable zsh to provide exception handling in a form that should be familiar from other languages. throw exception. catch exception-pattern zshmisc(1). This is important as only this construct provides the required support for exceptions. A typical example is as follows. { # "try" block # ... nested code here calls "throw MyExcept" } always { # "always" block if catch MyExcept; then print "Caught exception MyExcept" elif catch ''; then print "Caught a shell error. Propagating..." throw '' fi # Other exceptions are not handled but may be caught further # up the call stack. } If all exceptions should be caught, the following idiom might be preferable. { # ... 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 }.
  MIME FUNCTIONS
  Three functions are available to provide handling of files recognised by extension, for example to dispatch a file text.ps when executed as a command to an appropriate viewer. zsh-mime-setup [ -fv ] [ -l [ suffix ... ] ] zsh-mime-handler [-l] command arguments ... `alias  mailcap(4). The functions use the following styles, which are defined with the zstyle builtin command (see zshmodules(1)). alias -s gz=zsh-mime-handler to the initialisation code is sufficient; .gz will not be handled on its own, but may be in combination with other suffixes. current-shell. execute-as-is. file-path `/'. The full context is :mime:.suffix:, as described for the style handler. find-file-in-path. flags Defines flags to go with a handler; the context is as for the handler style, and the format is as for the flags in mailcap. handle-nonexistent. handler Specifies a handler for a suffix; the suffix is given by the context as :mime:.suffix:, and the format of the handler is exactly that in mailcap. Note in particular the `.'. mailcap A list of files in the format of ~/.mailcap and /etc/mailcap to be read during setup, replacing the default list which consists of those two files. The context is :mime:. A + in the list will be replaced by the default files. mailcap-priorities. files The order of files (entries in the mailcap style) read. Earlier files are preferred. (Note this does not resolve entries in the same file.) priority The priority flag from the mailcap entry. The priority is an integer from 0 to 9 with the default value being 5. flags The test given by the mailcap-prio-flags option is used to resolve entries. place Later entries are preferred; as the entries are strictly ordered, this test always succeeds. Note that as this style is handled during initialisation, the context is always :mime:, with no discrimination by suffix. mailcap-prio-flags. mime-types A list of files in the format of ~/.mime.types and /etc/mime.types to be read during setup, replacing the default list which consists of those two files. The context is :mime:. A + in the list will be replaced by the default files. never-background 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). pager If set, will be used instead of $PAGER or more to handle suffixes where the copiousoutput flag is set. The context is as for handler, i.e. :mime:.suffix: for handling a file with the given suffix. Examples: zstyle ':mime:*' mailcap ~/.mailcap /usr/local/etc/mailcap zstyle ':mime:.txt:' handler less %s zstyle ':mime:.txt:' flags needsterminal When zsh-mime-setup is subsequently run, it will look for mailcap entries in the two files given. Files of suffix .txt will be handled by running `less `alias -s ext' should show `ps: text/html; /usr/bin/lynx '%s'; needsterminal Running `z. pick-web-browser This function is separate from the two MIME functions described above and can be assigned directly to a suffix: autoload -U pick-web-browser alias -s html=pick-web-browser 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: browser-style 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 running. x Start a new GUI browser when an X Window display is available. Search for the availability of one of the browsers listed in the x-browsers style and start the first one that is found. No check is made for an already running browser. tty Start a terminal-based browser. Search for the availability of one of the browsers listed in the tty-browsers style and start the first one that is found. If the style is not set the default running x tty is used. x-browsers 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 :mime: (which may be extended in future, so appending `*' is recommended). For example, zstyle ':mime:*' x-browsers opera konqueror firefox. tty-browsers An array similar to x-browsers, except that it gives browsers to use when no X Window display is available. The default is elinks links lynx. command.
  MATHEMATICAL FUNCTIONS
  zcalc [ expression ... ] A reasonably powerful calculator based on zsh's arithmetic evaluation facility. The syntax is similar to that of formulae in most programming languages; see the section `Arithmetic Evaluation' in zshmisc(1) for details. The mathematical library zsh/mathfunc will be loaded if it is available; see the section `The zsh/mathfunc Module' in zshmodules(1). `4> ' is available as $4. The last value calculated is available as ans. Full command line editing, including the history of previous calculations, is available; the history is saved in the file ~/.zcalc_history. To exit, enter a blank line or type `:q' on its own (`q' `-#base', for example `zcalc -#16' (the `#' may have to be quoted, depending on the globbing options set). The prompt is configurable via the parameter ZCALCPROMPT, which undergoes standard prompt expansion. The index of the current entry is stored locally in the first element of the array psvar, which can be referred to in ZCALCPROMPT as `%1v'. The default prompt is `. :norm The default output format. It corresponds to the printf %g specification. Typically this shows six decimal digits. :sci digits Scientific notation, corresponding to the printf %g output format with the precision given by digits. This produces either fixed point or exponential notation depending on the value output. :fix digits Fixed point notation, corresponding to the printf %f output format with the precision given by digits. :eng digits Exponential notation, corresponding to the printf %E output format with the precision given by digits. :raw Raw output: this is the default form of the output from a math evaluation. This may show more precision than the number actually possesses. Other special commands: :!line... Execute 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 :!. :local arg ... Declare variables local to the function. Note that certain variables are used by the function for its own purposes. Other variables may be used, too, but they will be taken from or put into the global scope. :function name [ body ] Define a mathematical function or (with no body) delete it. The function is defined using zmathfuncdef, see below. Note that zcalc takes care of all quoting. Hence for example: function cube $1 * $1 * $1 defines a function to cube the sole argument. [#base] 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 base. Use, for example, `[#16]' to display hexadecimal output preceded by an indication of the base, or `[##16]' just to display the raw number in the given base. Bases themselves are always specified in decimal. `[#]' restores the normal output format. Note that setting an output base suppresses floating point output; use `[#]' to return to normal operation. See the comments in the function for a few extra tips. zmathfuncdef [ mathfunc [ body ] ].
  USER CONFIGURATION FUNCTIONS. zsh-newuser-install [ -f ] `# Lines configured by zsh-newuser-install' and `#.
  OTHER FUNCTIONS
  There are a large number of helpful functions in the 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. Descriptions colors 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 above).: color colour 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 `fg-', such as `fg-red'. Names prefixed with `bg-', such as `bg-blue', refer to the background codes. The reverse mapping from code to color yields base name for foreground codes and the 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. fg fg_bold fg_no_bold Map the eight basic color names to ANSI terminal escape sequences that set the corresponding foreground text properties. The fg sequences change the color without changing the eight intensity attributes. bg bg_bold bg_no_bold. fned name Same as zed -f. This function does not appear in the zsh distribution, but can be created by linking zed to the name fned in some directory in your fpath. is-at-least needed [ present ]. 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." nslookup [ arg ... ] This wrapper function for the nslookup command requires the zsh/zpty module (see zshmodules(1)). It behaves exactly like the standard 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 `:completion:nslookup'. See also the pager, prompt and rprompt styles below. regexp-replace var regexp replace. run-help cmd This function is designed to be invoked by the run-help ZLE widget, in place of the default alias. See `Accessing On-Line Help' above `man cmd' is run. An example assistant for the "ssh" command: 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 } Several of these assistants are provided in the Functions/Misc directory. These must be autoloaded, or placed as executable scripts in your search path, in order to be found and used by run-help. run-help-git run-help-svk run-help-svn Assistant functions for the git, svk, and svn commands. tetris 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: autoload -U tetris zle -N tetris bindkey keys tetris To start a game, execute the widget by typing the 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 `q') or when you lose. If you quit in the middle of a game, the next invocation of the tetris widget will continue where you left off. If you lost, it will start a new game. zargs [ option ... -- ] [ input ... ] [ -- command [ arg ... ] ] `print' with arguments `-r --'. For example, to get a long ls listing of all plain files in the current directory or its subdirectories: autoload -U zargs zargs -- **/*(.) -- ls -l Note that `--' `-', then the first `--' may be omitted. In the event that the string `--' is or may be an input, the -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 `..' as the marker: zargs -e.. -- **/*(.) .. ls -l This is a good choice in that example because no plain file can be named `..', but the best end-marker depends on the circumstances. For details of the other zargs options, see xargs(1) or run zargs with the --help option. zed [ -f ] name zed -b `^X^W' to accept the edit in the zed keymap, and binds `ZZ' to accept the edit in the zed-vicmd keymap. The bindings alone can be installed by running `zed -b'. This is suitable for putting into a startup file. Note that, if rerun, this will overwrite the existing zed and zed-vicmd keymaps. Completion is available, and styles may be set with the context prefix `:completion:zed'. A zle widget zed-set-file-name is available. This can be called by name from within zed using ` `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 with `zed . zcp [ -finqQvwW ] srcpat dest zln [ -finqQsvwW ] srcpat dest Same as zmv -C and zmv -L, respectively. These functions do not appear in the zsh distribution, but can be created by linking zmv to the names zcp and zln in some directory in your fpath. zkbd See `Keyboard Definition' above. zmv [ -finqQsvwW ] [ -C | -L | -M | -p program ] [ -o optstring ] srcpat dest Move (usually, rename) files matching the pattern srcpat to corresponding files having names of the form given by dest, where srcpat contains parentheses surrounding patterns which will be replaced in turn by $1, $2, ... in dest. For example, zmv '(*).lis' '$1.txt' renames `foo.lis' to `foo.txt', `my.old.stuff.lis' to `my: -f Force overwriting of destination files. Not currently passed down to the mv/cp/ln command due to vagaries of implementations (but you can use -o-f to do that). -i Interactive: show each line to be executed and ask the user whether to execute it. `Y' or `y' will execute it, anything else will skip it. Note that you just need to type one character. -n No execution: print what would happen, but don't do it. -q Turn bare glob qualifiers off: now assumed by default, so this has no effect. -Q Force bare glob qualifiers on. Don't turn this on unless you are actually using glob qualifiers in a pattern. -s Symbolic, passed down to ln; only works with -L. -v Verbose: print each command as it's being executed. -w Pick out wildcard parts of the pattern, as described above, and implicitly add parentheses for referring to them. -W Just like -w, with the addition of turning wildcards in the replacement pattern into sequential ${1} .. ${N} references. -C -L -M Force cp, ln or mv, respectively, regardless of the name of the function. -p program Call program instead of cp, ln or mv. Whatever it does, it should at least understand the form `program -- oldname newname' where oldname and newname are filenames generated by zmv. -o optstring The optstring is split into words and passed down verbatim to the cp, ln or mv command called to perform the work. It should probably begin with a `-'. Further examples: zmv -v '(* *)' '${1// /_}'. zrecompile See `Recompiling Functions' above. zstyle+ context style value [ + subcontext style value ... ] This makes defining styles a bit simpler by using a single `+' as a special token that allows you to append a context name to the previously used context name. Like this: zstyle+ ':foo:bar' style1 value1 \ + ':baz' style2 value2 \ + ':frob' style3 value3 This defines `style1' with `value1' for the context :foo:bar as usual, but it also defines `style2' with `value2' for the context :foo:bar:baz and `style3' with `value3' for :foo:bar:frob. Any subcontext may be the empty string to re-use the first context unchanged. Styles insert-tab The zed function sets this style in context `:completion:zed:*' to turn off completion when TAB is typed at the beginning of a line. You may override this by setting your own value for this context and style. pager The nslookup function looks up this style in the context `:nslookup' to determine the program used to display output that does not fit on a single screen. prompt rprompt The nslookup function looks up this style in the context `:nslookup' to set the prompt and the right-side prompt, respectively. The usual expansions for the PS1 and RPS1 parameters may be used (see EXPANSION OF PROMPT SEQUENCES in zshmisc(1)).