ZSHCONTRIB(1)
โจ ZSHCONTRIB โจ
okay bestie so this is the ZSHCONTRIB(1) page โ zshcontrib, the whole "user contributions to zsh" situation. General Commands Manual energy. buckle up ๐
๐ NAME ๐
zshcontrib โ user contributions to zsh
๐ธ DESCRIPTION ๐ธ
So the zsh source distribution ships with a bunch of stuff that the user community made. not the shell itself, bestie โ these things are not inherently part of the shell, and some of them might not even be in your zsh install. The biggest ones are documented right here. For the other contributed items (shell functions and whatnot), you gotta go look for comments in the actual function source files. iykyk ๐ซถ
๐ UTILITIES ๐
๐ฆ Accessing On-Line Help ๐ฆ
The key sequence ESC h is normally bound by ZLE to run the run-help widget (peep zshzle(1)). It calls the run-help command and hands it the command word from whatever you're currently typing as its argument. By default, run-help is just an alias for the man command, which is why it lowkey flops when your command word is a shell builtin or a user-defined function. But!! if you redefine the run-help alias you can make the shell's on-line help way better. slay โจ
The helpfiles utility (it lives in the Util directory of the distribution) is a Perl program that processes the zsh manual and spits out a separate help file for each shell builtin โ plus for lots of other shell features too. The autoloadable run-help function (found in Functions/Misc) goes looking for those helpfiles and does several other checks so it can give you the most complete help possible for the command. obsessed.
Help files get installed by default into a subdirectory of /usr/share/zsh or /usr/local/share/zsh.
Wanna make your own help files with helpfiles? Pick or create a directory where the individual command help files will live. For example, maybe you want ~/zsh_help. If you unpacked the zsh distribution in your home directory, you'd run:
mkdir ~/zsh_help
perl ~/zsh-5.9.2/Util/helpfiles ~/zsh_help
The HELPDIR parameter tells run-help where to look for the help files. When it's unset, it uses the default installation path. So to use your own set of help files, set it to the right path in one of your startup files:
HELPDIR=~/zsh_help
And to actually use the run-help function you need to add lines something like this to your .zshrc (or equivalent startup file):
unalias run-help
autoload run-help
โ ๏ธ heads up: forautoload run-helpto work, therun-helpfile has to be in one of the directories named in yourfpatharray (seezshparam(1)). This should already be true if you've got a standard zsh installation โ if it's not, copyFunctions/Misc/run-helpinto an appropriate directory. no cap.
๐ง Recompiling Functions ๐ง
If you're the type who edits your zsh functions constantly, or you periodically update your zsh install to track the latest developments, you might find that function digests compiled with the zcompile builtin go out of date with the function source files a lot. Usually that's fine โ zsh always looks for the newest file when loading a function โ but it can make shell startup and function loading slower. Also, if a digest file is explicitly used as an element of fpath, zsh won't check whether any of its source files has changed. ๐
Enter the zrecompile autoloadable function, found in Functions/Misc. It keeps your function digests up to date.
zrecompile [ -qt ] [ name ... ]
zrecompile [ -qt ] -p arg ... [ -- arg ... ]
This tries to find *.zwc files and automatically re-compile them if at least one of the original files is newer than the compiled file. This only works if the names stored in the compiled files are full paths, or are relative to the directory that contains the .zwc file.
In the first form, each name is the name of a compiled file or a directory containing *.zwc files that should be checked. If you give no arguments, the directories and *.zwc files in fpath are used.
When -t is given, no compilation happens โ but the return status is zero (true) if there are files that need re-compiling, and non-zero (false) otherwise. The -q option quiets the chatty output that describes what zrecompile is doing.
Without the -t option, the return status is zero if all the files that needed re-compilation could be compiled, and non-zero if compilation failed for at least one of them.
If the -p option is given, the args are interpreted as one or more sets of arguments for zcompile, separated by --. For example:
zrecompile -p \
-R ~/.zshrc -- \
-M ~/.zcompdump -- \
~/zsh/comp.zwc ~/zsh/Completion/*/_*
This compiles ~/.zshrc into ~/.zshrc.zwc if that doesn't exist or if it's older than ~/.zshrc. The compiled file gets marked for reading instead of mapping. Same deal for ~/.zcompdump and ~/.zcompdump.zwc, except that compiled file is marked for mapping. The last line re-creates the file ~/zsh/comp.zwc if any of the files matching the given pattern is newer than it. ๐ฅ
Without the -p option, zrecompile does not create function digests that don't already exist, and it doesn't add new functions to the digest.
Okay so this shell loop is an example of a method for creating function digests for all functions in your fpath, assuming you have write permission to the directories:
for ((i=1; i <= $#fpath; ++i)); do
dir=$fpath[i]
zwc=${dir:t}.zwc
if [[ $dir == (.|..) || $dir == (.|..)/* ]]; then
continue
fi
files=($dir/*(N-.))
if [[ -w $dir:h && -n $files ]]; then
files=(${${(M)files%/*/*}#/})
if ( cd $dir:h &&
zrecompile -p -U -z $zwc $files ); then
fpath[i]=$fpath[i].zwc
fi
fi
done
The -U and -z options are appropriate for functions in the default zsh installation fpath; you may need different options for your personal function directories. fr fr.
Once the digests have been created and your fpath modified to refer to them, you can keep them up to date by running zrecompile with no arguments. iconic.
๐ Keyboard Definition ๐
The sheer number of possible combos of keyboards, workstations, terminals, emulators, and window systems makes it literally impossible for zsh to have built-in key bindings for every situation. The zkbd utility, found in Functions/Misc, helps you quickly create key bindings for your configuration. ๐ซถ
Run zkbd either as an autoloaded function, or as a shell script:
zsh -f ~/zsh-5.9.2/Functions/Misc/zkbd
When you run zkbd, the first thing it does is ask you to enter your terminal type โ if the default it offers is right, just press return. Then it asks you to press a number of different keys so it can figure out the characteristics of your keyboard and terminal. zkbd warns you if it finds anything out of the ordinary, like a Delete key that sends neither ^H nor ^?. ๐
The keystrokes read by zkbd get recorded as a definition for an associative array named key, written to a file in the .zkbd subdirectory inside either your HOME or ZDOTDIR directory. The name of the file is composed from the TERM, VENDOR and OSTYPE parameters, joined by hyphens.
You can read this file into your .zshrc or another startup file with the 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 forautoload zkbdto work, thezkdbfile must be in one of the directories named in yourfpatharray (seezshparam(1)). This should already be the case if you have a standard zsh installation; if it's not, copyFunctions/Misc/zkbdto an appropriate directory.
๐ Dumping Shell State ๐
Every now and then you'll hit what looks like a bug in the shell โ especially if you're on a beta version of zsh or a development release. Usually it's enough to send a description of the problem to one of the zsh mailing lists (see zsh(1)), but sometimes one of the zsh developers will need to recreate your environment to track the problem down. ๐ญ
That's what the script named reporter is for โ it's in the Util directory of the distribution. (You can also autoload reporter, but reporter is not installed in fpath by default.) This script outputs a detailed dump of the shell state, in the form of another script that can be read with zsh -f to recreate that state. so useful.
To use reporter, read the script into your shell with the . command and redirect the output into a file:
. ~/zsh-5.9.2/Util/reporter > zsh.report
๐จ bestie please: check the zsh.report file for any sensitive information like passwords and delete them by hand before sending the script to the developers. Also, since the output can be voluminous, it's best to wait for the developers to actually ask for this information before sending it. don't just dump it on them.
You can also use reporter to dump only a subset of the shell state. This is sometimes useful for creating startup files for the first time. Most of the output from reporter is way more detailed than you'd usually need for a startup file โ but the aliases, options, and zstyles states may be useful because they include only changes from the defaults. The bindings state may be useful if you've created any of your own keymaps, because reporter arranges to dump the keymap creation commands as well as the bindings for every keymap. ๐
As is usual with automated tools, if you create a startup file with reporter, you should edit the results to remove unnecessary commands. And note: if you're using the new completion system, you should not dump the functions state to your startup files with reporter โ use the compdump function instead (see 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 below, the whole entire buffet ๐aliasesโ output alias definitionsbindingsโ output ZLE key maps and bindingscompletionโ output old-stylecompctlcommands (new completion is covered byfunctionsandzstyles, iykyk)functionsโ output autoloads and function definitionslimitsโ output limit commandsoptionsโ outputsetoptcommandsstylesโ same aszstylesvariablesโ output shell parameter assignments, plusexportcommands for any environment variableszstylesโ outputzstylecommands
If you straight up omit the state, all is assumed โ no cap, that's the default ๐ซถ
And here's the cute part: with the exception of all, every state can be abbreviated by any prefix, even a single letter ๐ so a is the same as aliases, z is the same as zstyles, etc. Lazy girlie behavior fully supported.
โจ Manipulating Hook Functions โจ
add-zsh-hook [ -L | -dD ] [ -Uzk ] hook function
Okay so bestie, some functions are special to the shell โ they're described in the section SPECIAL FUNCTIONS in zshmisc(1) โ because the shell calls them automatically at specific points during execution ๐ฅ Each one has an associated array, and that array holds the names of functions to be called at that same point. Those are the so-called hook functions. The shell function add-zsh-hook gives you a simple little way to add or remove functions from the array. Iconic.
hook is one of chpwd, periodic, precmd, preexec, zshaddhistory, zshexit, or zsh_directory_name โ those are the special functions in question ๐ธ Just a heads up: zsh_directory_name is called in a different way from the other functions, but it can still be manipulated as a hook anyway.
function is the name of an ordinary shell function. If you give no options, it gets added to the array of functions to be executed in the given context. Functions are invoked in the order they were added โญ
-Lโ lists the current values for the hook arrays withtypeset-dโ the function is removed from the array of functions to be executed-Dโ the function is treated as a pattern, and any matching names of functions get removed from the array of functions to be executed-U,-z,-kโ these get passed as arguments toautoloadforfunction. For functions contributed with zsh, the options-Uzare the appropriate vibe ๐
add-zle-hook-widget [ -L | -dD ] [ -Uzk ] hook widgetname
Same energy, but for the line editor ๐ฆ Several widget names are special to ZLE โ see the section Special Widgets in zshzle(1) โ in that they're automatically called at specific points during editing. Unlike function hooks, these don't use a predefined array of other names to call at the same point; instead the shell function add-zle-hook-widget maintains a similar array and arranges for the special widget to invoke those additional widgets. Clever, honestly.
hook is one of isearch-exit, isearch-update, line-pre-redraw, line-init, line-finish, history-line-set, or keymap-select, corresponding to each of the special widgets zle-isearch-exit, etc. The special widget names are also accepted as the hook argument, so you've got options, queen ๐
widgetname is the name of a ZLE widget. If no options are given, this is added to the array of widgets to be invoked in the given hook context. Widgets are invoked in the order they were added, with:
zle widgetname -Nw -f "nolast" -- "$@"
Note that this means theWIDGETspecial parameter trackswidgetnamewhen the widget function is called, rather than tracking the name of the corresponding special hook widget. Important detail, don't forget it ๐
-dโwidgetnameis removed from the array of widgets to be executed-Dโwidgetnameis treated as a pattern, and any matching names of widgets are removed from the array
If widgetname doesn't name an existing widget when it's added to the array, it's assumed that a shell function also named widgetname is meant to provide the implementation of the widget ๐ So that name gets marked for autoloading, and the options -U, -z and -k are passed as arguments to autoload, just like with add-zsh-hook. The widget is also created with zle -N widgetname so that the corresponding function gets loaded the first time the hook is called.
The arrays of widgetname are currently maintained in zstyle contexts, one for each hook context, with a style of widgets. If the -L option is given, this set of styles is listed with zstyle -L ๐
Okay so real talk โ this implementation may change, and the special widgets that refer to the styles are created only if add-zle-hook-widget is called to add at least one widget. So if this function is used for any hooks, then all hooks should be managed only via this function. Don't mix and match, bestie, it's giving chaos ๐
๐ REMEMBERING RECENT DIRECTORIES ๐
The function cdr lets you change the working directory to a previous working directory from a list that's maintained automatically ๐ญ It's similar in concept to the directory stack controlled by the pushd, popd and dirs builtins, but it's more configurable โ and because it stores all entries in files, it's maintained across sessions and (by default) between terminal emulators in the current session ๐ฅ Duplicates are automatically removed, so the list reflects the single most recent use of each directory. Clean.
Note that thepushddirectory stack is not actually modified or used bycdrunless you configure it to do so as described in the configuration section below ๐
๐ธ Installation ๐ธ
The system works by means of a hook function that's 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 directory interactively, no matter which command you use, the directory you change to will be remembered in most-recent-first order ๐
โจ Use โจ
All direct user interaction is via the cdr function.
The argument to cdr is a number N corresponding to the *N*th most recently changed-to directory. 1 is the immediately preceding directory; the current directory is remembered but is not offered as a destination ๐
โโ๏ธ Note that if you have multiple windows open, 1 may refer to a directory changed to in another window โ you can avoid this by having per-terminal files for storing directories, as described for the recent-dirs-file style below.
If you set the recent-dirs-default style described below, cdr will behave the same as cd if given a non-numeric argument, or more than one argument. The recent directory list is updated just the same however you change directory ๐ซถ
If the argument is omitted, 1 is assumed. This is similar to pushd's behaviour of swapping the two most recent directories on the stack ๐
Completion for the argument to cdr is available if compinit has been run; menu selection is recommended, using:
zstyle ':completion:*:*:cdr:*:*' menu selection
to allow you to cycle through recent directories ๐ The order is preserved, so the first choice is the most recent directory before the current one. The verbose style is also recommended to ensure the directory is shown; this style is on by default so no action is required unless you've changed it.
๐ 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 variablereplyto the current set of directories. Nothing is printed and the directory is not changed.-eโ allows you to edit the list of directories, one per line. The list can be edited to any extent you like; no sanity checking is performed ๐ Completion is available. No quoting is necessary (except for newlines, where the original author has in any case no sympathy ๐ญ); directories are in unabbreviated form and contain an absolute path, i.e. they start with/. Usually the first entry should be left as the current directory.-p'pattern' โ prunes any items in the directory list that match the given extended glob pattern; the pattern needs to be quoted from immediate expansion on the command line. The pattern is matched against each completely expanded file name in the list; the full string must match, so wildcards at the end (e.g.'*removeme*') are needed to remove entries with a given substring ๐ฆ
If output is to a terminal, then the function will print the new list after pruning and prompt for confirmation by the user. This output and confirmation step can be skipped by using -P instead of -p ๐
๐ Configuration ๐
Configuration is by means of the styles mechanism that should be familiar from completion; if not, see the description of the zstyle command in 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
sets the value of the recent-dirs-max style to 0. In practice the style name is specific enough that a context of '*' should be fine ๐ธ
An exception is recent-dirs-insert, which is used exclusively by the completion system and so has the usual completion system context (':completion:*' if nothing more specific is needed), though again '*' should be fine in practice.
recent-dirs-default : If true, and the command is expecting a recent directory index, and either there is more than one argument or the argument is not an integer, then fall through to "cd" ๐ซถ This allows the lazy to use only one command for directory changing. Completion recognises this, too; see recent-dirs-insert for how to control completion when this option is in use.
๐
recent-dirs-file
okay so this one is literally just where do we keep the receipts โ aka the file where the list of directories gets saved. the default is ${ZDOTDIR:-$HOME}/.chpwd-recent-dirs, which lowkey means it lives in your home directory unless you've set the variable ZDOTDIR to point somewhere else. directory names are saved in $'...' quoted form, so like โ every single line in the file can be handed straight to the shell as an argument. slay, no parsing drama.
the value of this style can also be an array, and that's where it gets fun. the first file in the list is always the one used for saving directories, while any other files are left untouched. when reading the recent directory list, if there are fewer than the maximum number of entries in that first file, the contents of later files in the array get appended, with duplicates removed from the list shown. important: the contents of the two files are not sorted together, so all the entries in the first file are shown first. ๐ซถ
the special value + can show up in the list to indicate the default file should be read at that point. this allows effects like:
zstyle ':chpwd:*' recent-dirs-file \
~/.chpwd-recent-dirs-${TTY##*/} +
so recent directories get read from a file numbered according to the terminal, and if there are insufficient entries the list is supplemented from the default file. iconic behaviour honestly.
and yes, you can flex with 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. main character config fr.
๐ recent-dirs-insert
this one's used by completion. if recent-dirs-default is true, then setting this to true causes the actual directory, rather than its index, to be inserted on the command line. same effect as using the corresponding index, but it makes the history clearer and the line easier to edit. with this setting, if part of an argument was already typed, normal directory completion rather than recent directory completion is done โ because recent directory completion is expected to be done by cycling through entries menu fashion. iykyk.
if the value of the style is always, then only recent directories will be completed; in that case, use the cd command when you want to complete other directories.
if the value is fallback, recent directories will be tried first, then normal directory completion is performed if recent directory completion failed to find a match.
finally, if the value is both then both sets of completions are presented; the usual tag mechanism can be used to distinguish results, with recent directories tagged as recent-dirs. note that the recent directories inserted are abbreviated with directory names where appropriate. cute and functional ๐
โจ recent-dirs-max
the maximum number of directories to save to the file. if this is zero or negative there is no maximum. the default is 20.
heads up bestie: this includes the current directory, which isn't offered, so the highest number of directories you'll actually be offered is one less than the maximum. ๐
๐ธ 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โ prune parents (more accurately, ancestors) from the recent list. if present, changing directly down by any number of directories causes the current directory to be overwritten. for example, changing from~pwsto~pws/some/other/dircauses~pwsnot to be left on the recent directory stack. this only applies to direct changes to descendant directories; earlier directories on the list are not pruned. for example, changing from~pws/yet/anotherto~pws/some/other/dirdoes not cause~pwsto be pruned. so specific, love that for us.pattern:patternโ gives a zsh pattern for directories that should not be added to the recent list (if not already there). this element can be repeated to add different patterns. for example,'pattern:/tmp(|/*)'stops/tmpor its descendants from being added. theEXTENDED_GLOBoption is always turned on for these patterns. ๐ฆ
๐ง recent-dirs-pushd
if set to true, cdr will use pushd instead of cd to change the directory, so the directory is saved on the directory stack. and here's the thing โ since the directory stack is completely separate from the list of files saved by the mechanism used in this file, there's no obvious reason to do this. like, do with that information what you will ๐
๐ 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 as 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. yes bestie, it's giving magic and honestly? obsessed. ๐ฅ
๐ Details of directory handling
this section is for the curious or the confused; most users will not need to know this information. but you're here, so let's go ๐
recent directories are saved to a file immediately and hence are preserved across sessions. note that currently no file locking is applied: the list is updated immediately on interactive commands and nowhere else (unlike history), and it is assumed you're only going to change directory in one window at once. this is not safe on shared accounts, but in any case the system has limited utility when someone else is changing to a different set of directories behind your back. ๐ญ
to make this a little safer, only directory changes instituted from the command line โ either directly or indirectly through shell function calls (but not through subshells, evals, traps, completion functions and the like) โ are saved. shell functions should use cd -q or pushd -q to avoid side effects if the change to the directory is to be invisible at the command line. see the contents of the function chpwd_recent_dirs for more details. periodt. โญ
โจ ABBREVIATED DYNAMIC REFERENCES TO DIRECTORIES โจ
Okay so bestie, the dynamic directory naming system? The whole thing is described over in the subsection Dynamic named directories of the section Filename Expansion in zshexpn(1). Basically, a reference to ~[...] gets expanded by a function that's found by the hooks mechanism. That's the vibe. ๐ธ
The contributed function zsh_directory_name_generic gives you a whole system where you can refer to directories with only a limited amount of new code. Ngl it's giving genius. It supports all three of the standard interfaces for directory naming:
- converting from a name to a directory
- converting in the reverse direction to find a short name
- completion of names
The main character feature of this function is a path-like syntax โ it combines abbreviations at multiple levels separated by :. So for example, ~[g:p:s] might specify:
gโ the top level directory for your git area. This first component has to match, or the function will return indicating that another directory name hook function should be tried.pโ the name of a project within your git area.sโ the source area within that project. This lets you collapse references to long hierarchies into a very compact form, particularly if the hierarchies are similar across different areas of the disk. Obsessed.
Name components may be completed: if a description is shown at the top of the list of completions, it includes the path to which previous components expand, while the description for an individual completion shows the path segment it would add. No additional configuration needed for this, because the completion system is already aware of the dynamic directory name mechanism. ๐
Usage ๐ซถ
To use the function, first define a wrapper function for your specific case. We'll assume it's to be autoloaded. It can have any name but we'll refer to it as zdn_mywrapper. This wrapper function will define various variables and then call this function with the same arguments that the wrapper function gets. This configuration is described below. ๐
Then arrange for the wrapper to be run as a zsh_directory_name hook:
autoload -Uz add-zsh-hook zsh_directory_name_generic zdn_mywrapper
add-zsh-hook -U zsh_directory_name zdn_mywrapper
Configuration ๐
The wrapper function should define a local associative array zdn_top. Alternatively, this can be set with a style called mapping. The context for the style is :zdn:wrapper-name where wrapper-name is the function calling zsh_directory_name_generic; for example:
zstyle :zdn:zdn_mywrapper: mapping zdn_mywrapper_top
The keys in this associative array correspond to the first component of the name. The values are matching directories. They may have an optional suffix with a slash followed by a colon and the name of a variable in the same format to give the next component. (The slash before the colon is there to disambiguate the case where a colon is needed in the path for a drive. There is otherwise no syntax for escaping this, so path components whose names start with a colon are not supported.) A special component :default: specifies a variable in the form /:var (the path section is ignored and so is usually empty) that will be used for the next component if no variable is given for the path. Variables referred to within zdn_top have the same format as zdn_top itself, but contain relative paths.
For example,
local -A zdn_top=(
g ~/git
ga ~/alternate/git
gs /scratch/$USER/git/:second2
:default: /:second1
)
This specifies the behaviour of a directory referred to as ~[g:...] or ~[ga:...] or ~[gs:...]. Later path components are optional; in that case ~[g] expands to ~/git, and so on. gs expands to /scratch/$USER/git and uses the associative array second2 to match the second component; g and ga use the associative array second1 to match the second component.
When expanding a name to a directory, if the first component is not g or ga or gs, it is not an error; the function simply returns 1 so that a later hook function can be tried. However, matching the first component commits the function, so if a later component does not match, an error is printed (though this still does not stop later hooks from being executed). ๐
For components after the first, a relative path is expected, but note that multiple levels may still appear. Here's an example of second1:
local -A second1=(
p myproject
s somproject
os otherproject/subproject/:third
)
The path as found from zdn_top is extended with the matching directory, so ~[g:p] becomes ~/git/myproject. The slash between is added automatically (it's not possible to have a later component modify the name of a directory already matched). Only os specifies a variable for a third component, and there's no :default:, so it's an error to use a name like ~[g:p:x] or ~[ga:s:y] because there's nowhere to look up the x or y. ๐
The associative arrays need to be visible within this function; the generic function therefore uses internal variable names beginning _zdn_ in order to avoid clashes. Note that the variable reply needs to be passed back to the shell, so should not be local in the calling function.
Heads up bestie: the function does not test whether directories assembled by component actually exist. That's on purpose โ it lets the system work across automounted file systems. The error from the command trying to use a non-existent directory should be sufficient to indicate the problem. ๐ฅ
Complete example ๐
Here's a full fictitious but usable autoloadable definition of the example function defined by the code above. So ~[gs:p:s] expands to /scratch/$USER/git/myscratchproject/top/srcdir (with $USER also expanded).
local -A zdn_top=(
g ~/git
ga ~/alternate/git
gs /scratch/$USER/git/:second2
:default: /:second1
)
local -A second1=(
p myproject
s somproject
os otherproject/subproject/:third
)
local -A second2=(
p myscratchproject
s somescratchproject
)
local -A third=(
s top/srcdir
d top/documentation
)
# autoload not needed if you did this at initialisation...
autoload -Uz zsh_directory_name_generic
zsh_directory_name_generic "$@"
It is also possible to use global associative arrays, suitably named, and set the style for the context of your wrapper function to refer to this. Then your set up code would contain the following:
typeset -A zdn_mywrapper_top=(...)
# ... and so on for other associative arrays ...
zstyle ':zdn:zdn_mywrapper:' mapping zdn_mywrapper_top
autoload -Uz add-zsh-hook zsh_directory_name_generic zdn_mywrapper
add-zsh-hook -U zsh_directory_name zdn_mywrapper
and the function zdn_mywrapper would contain only the following:
zsh_directory_name_generic "$@"
๐ GATHERING INFORMATION FROM VERSION CONTROL SYSTEMS ๐
In a lot of cases, it is nice to automatically retrieve information from version control systems (VCSs), such as subversion, CVS or git, to be able to provide it to the user; possibly in the user's prompt. So that you can instantly tell which branch you are currently on, for example. Literally a game changer for your prompt's main character energy. โจ
In order to do that, you may use the vcs_info function.
The following VCSs are supported, showing the abbreviated name by which they are referred to within the system:
- Bazaar (
bzr) โ https://bazaar.canonical.com/ - Codeville (
cdv) โ http://freecode.com/projects/codeville/ - Concurrent Versioning System (
cvs) โ https://www.nongnu.org/cvs/ - Darcs (
darcs) โ http://darcs.net/ - Fossil (
fossil) โ https://fossil-scm.org/ - Git (
git) โ https://git-scm.com/ - GNU arch (
tla) โ https://www.gnu.org/software/gnu-arch/ - Mercurial (
hg) โ https://www.mercurial-scm.org/ - Monotone (
mtn) โ https://monotone.ca/ - Perforce (
p4) โ https://www.perforce.com/ - Subversion (
svn) โ https://subversion.apache.org/ - SVK (
svk) โ https://svk.bestpractical.com/
There is also support for the patch management system quilt (https://savannah.nongnu.org/projects/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 specific $psvar entries to be available. Slay. ๐
Quickstart โญ
To get this feature working quickly (including colors), you can do the following (assuming you loaded vcs_info properly โ see above):
zstyle ':vcs_info:*' actionformats \
'%F{5}(%f%s%F{5})%F{3}-%F{5}[%F{2}%b%F{3}|%F{1}%a%F{5}]%f '
zstyle ':vcs_info:*' formats \
'%F{5}(%f%s%F{5})%F{3}-%F{5}[%F{2}%b%F{5}]%f '
zstyle ':vcs_info:(sv[nk]|bzr):*' branchformat '%b%F{1}:%F{3}%r'
precmd () { vcs_info }
PS1='%F{5}[%F{2}%n%F{5}] %F{3}%3~ ${vcs_info_msg_0_}%f%# '
Obviously, the last two lines are there for demonstration. You need to call vcs_info from your precmd function. Once that's done you need a single quoted '${vcs_info_msg_0_}' in your prompt.
To be able to use '${vcs_info_msg_0_}' directly in your prompt like this, you will need to have the PROMPT_SUBST option enabled.
Now call the vcs_info_printsys utility from the command line:
% vcs_info_printsys
## list of supported version control backends:
## disabled systems are prefixed by a hash sign (#)
bzr
cdv
cvs
darcs
fossil
git
hg
mtn
p4
svk
svn
tla
## flavours (cannot be used in the enable or disable styles; they
## are enabled and disabled with their master [git-svn -> git])
## they *can* be used in contexts: ':vcs_info:git-svn:*'.
git-p4
git-svn
hg-git
hg-hgsubversion
hg-hgsvn
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's 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
If you rerun vcs_info_printsys after one of these commands, you will see the backends listed in the disable style (or backends not in the enable style โ if you used that) marked as disabled by a hash sign. That means the detection of these systems is skipped completely. No wasted time there. ๐ฆ
๐ 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โ is one of:git,git-svn,git-p4,hg,hg-git,hg-hgsubversion,hg-hgsvn,darcs,bzr,cdv,mtn,svn,cvs,svk,tla,p4orfossil. This is followed by.quilt-quilt-modein Quilt mode (see Quilt Support for details) and by+hook-namewhile hooks are active (see Hooks invcs_infofor details).
Currently, hooks in quilt mode don't add the .quilt-quilt-mode information. This may change in the future.
user-contextโ is a freely configurable string, assignable by the user as the first argument tovcs_info(see its description below).repo-root-nameโ is the name of a repository in which you want a style to match. So, if you want a setting specific to/usr/src/zsh, with that being a CVS checkout, you can setrepo-root-nametozshto make it so.
There are three special values for vcs-string:
- The first is named
-init-, that is in effect as long as there was no decision what VCS backend to use. - The second is
-preinit-; it is used beforevcs_infois run, when initializing the data exporting variables. - The third special value is
formatsand is used by thevcs_info_lastmsgfor looking up its styles.
The initial value of repo-root-name is -all- and it is replaced with the actual name, as soon as it is known. Only use this part of the context for defining the formats, actionformats or branchformat styles, as it is guaranteed that repo-root-name is set up correctly for these only. For all other styles, just use * instead.
There are two pre-defined values for user-context:
defaultโ the one used if none is specifiedcommandโ used byvcs_info_lastmsgto 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 whenactionformatsis 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%bin theformatsandactionformatsstyles above, not only by a branch name but also by a revision number. This style lets you modify how that string should look.nvcsformatsโ These "formats" are set when we didn't detect a version control system for the current directory orvcs_infowas disabled. This is useful if you wantvcs_infoto completely take over the generation of your prompt. You would do something likePS1='${vcs_info_msg_0_}'to accomplish that.hgrevformatโhguses both a hash and a revision number to reference a specific changeset in a repository. With this style you can format the revision string (seebranchformat) to include either or both. It's only useful whenget-revisionis true. Note, the full 40-character revision id is not available (except when using theuse-simpleoption) because executinghgmore than once per prompt is too slow; you may customize this behavior using hooks.max-exportsโ Defines the maximum number ofvcs_info_msg_*_variablesvcs_infowill set.enableโ A list of backends you want to use. Checked in the-init-context. If this list contains an item calledNONEno backend is used at all andvcs_infowill do nothing. If this list containsALL,vcs_infowill use all known backends. Only withALLinenablewill thedisablestyle have any effect.ALLandNONEare case insensitive.disableโ A list of VCSs you don't wantvcs_infoto test for repositories (checked in the-init-context, too). Only used ifenablecontainsALL.disable-patternsโ A list of patterns that are checked against$PWD. If a pattern matches,vcs_infowill be disabled. This style is checked in the:vcs_info:-init-:*:-all-context.
Say, ~/.zsh is a directory under version control, in which you do not want vcs_info to be active, do:
zstyle ':vcs_info:*' disable-patterns "${(b)HOME}/.zsh(|/*)"
use-quiltโ If enabled, the quilt support code is active inaddonmode. See Quilt Support for details.quilt-standaloneโ If enabled,standalonemode 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_PATCHESenvironment 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โ If enabled, this style causes the%cand%uformat escapes to show when the working directory has uncommitted changes. The strings displayed by these escapes can be controlled via thestagedstrandunstagedstrstyles. The only backends that currently support this option aregit,hg, andbzr(the latter two only support unstaged). For this style to be evaluated with thehgbackend, theget-revisionstyle needs to be set and theuse-simplestyle needs to be unset. The latter is the default; the former is not. With thebzrbackend, lightweight checkouts only honor this style if theuse-serverstyle is set. Note, the actions taken if this style is enabled are potentially expensive (read: they may be slow, depending on how big the current repository is). Therefore, it is disabled by default.check-for-staged-changesโ This style is likecheck-for-changes, but it never checks the worktree files, only the metadata in the.${vcs}dir. Therefore, this style initializes only the%cescape (withstagedstr) but not the%uescape. This style is faster thancheck-for-changes. In thegitbackend, this style checks for changes in the index. Other backends do not currently implement this style. This style is disabled by default.stagedstrโ This string will be used in the%cescape if there are staged changes in the repository.unstagedstrโ This string will be used in the%uescape if there are unstaged changes in the repository.commandโ This style causesvcs_infoto use the supplied string as the command to use as the VCS's binary. Note, that setting this in':vcs_info:*'is not a good idea. If the value of this style is empty (which is the default), the used binary name is the name of the backend in use (e.g.svnis used in ansvnrepository). Therepo-root-namepart in the context is always the default-all-when this style is looked up. For example, this style can be used to use binaries from non-default installation directories. Assume,gitis installed in/usr/binbut your sysadmin installed a newer version in/usr/local/bin. Instead of changing the order of your$PATHparameter, you can do this:
zstyle ':vcs_info:git:*:-all-' command /usr/local/bin/git
use-serverโ This is used by the Perforce backend (p4) to decide if it should contact the Perforce server to find out if a directory is managed by Perforce. This is the only reliable way of doing this, but runs the risk of a delay if the server name cannot be found. If the server (more specifically, thehost:portpair describing the server) cannot be contacted, its name is put into the associative arrayvcs_info_p4_dead_serversand is not contacted again during the session until it is removed by hand. If you do not set this style, thep4backend is only usable if you have set the environment variableP4CONFIGto a file name and have corresponding files in the root directories of each Perforce client. See comments in the functionVCS_INFO_detect_p4for more detail. The Bazaar backend (bzr) uses this to permit contacting the server about lightweight checkouts, see thecheck-for-changesstyle.use-simpleโ If there are two different ways of gathering information, you can select the simpler one by setting this style to true; the default is to use the not-that-simple code, which is potentially a lot slower but might be more accurate in all possible cases. This style is used by thebzr,hg, andgitbackends. In the case ofhgit will invoke the externalhexdumpprogram to parse the binary dirstate cache file; this method will not return the local revision number.get-revisionโ If set to true,vcs_infogoes the extra mile to figure out the revision of a repository's work tree (currently for thegitandhgbackends, where this kind of information is not always vital). Forgit, the hash value of the currently checked out commit is available via the%iexpansion. Withhg, the local revision number and the corresponding global hash are available via%i.get-mqโ If set to true, thehgbackend will look for a Mercurial Queue (mq) patch directory. Information will be available via the%mreplacement.get-bookmarksโ If set to true, thehgbackend will try to get a list of current bookmarks. They will be available via the%mreplacement. The default is to generate a comma-separated list of all bookmark names that refer to the currently checked out revision. If a bookmark is active, its name is suffixed an asterisk and placed first in the list.use-prompt-escapesโ Determines if we assume that the assembled string fromvcs_infoincludes prompt escapes. (Used byvcs_info_lastmsg.)debugโ Enable debugging output to track possible problems. Currently this style is only used byvcs_info's hooks system.hooksโ A list style that defines hook-function names. See Hooks invcs_infobelow for details.patch-format,nopatch-formatโ bestie, this pair is the glow-up crew for the patch info that the%mexpando shows informatsandactionformats, for thegitandhgbackends. The value gets hit with certain%-expansions (listed below, keep scrolling ๐ ). The expanded value then chills in the globalbackend_miscarray as${backend_misc[patches]}โ yes, even if you're using aset-patch-formathook. โจget-unappliedโ a boolean style that decides whether a backend even bothers trying to round up a list of unapplied patches (think Mercurial Queue patches, for example). ๐ซถ
Used by the quilt, hg, and git backends.
The default values for these styles in all contexts are, no cap:
formatsโ" (%s)-[%b]%u%c-"actionformatsโ" (%s)-[%b|%a]%u%c-"branchformatโ"%b:%r"(forbzr,svn,svkandhg)nvcsformatsโ""hgrevformatโ"%r:%h"max-exportsโ2enableโALLdisableโ (empty list)disable-patternsโ (empty list)check-for-changesโfalsecheck-for-staged-changesโfalsestagedstrโ (string:"S")unstagedstrโ (string:"U")commandโ (empty string)use-serverโfalseuse-simpleโfalseget-revisionโfalseget-mqโtrueget-bookmarksโfalseuse-prompt-escapesโtruedebugโfalsehooksโ (empty list)use-quiltโfalsequilt-standaloneโfalsequilt-patch-dirโ empty โ use$QUILT_PATCHESquiltcommandโquiltpatch-formatโ backend dependentnopatch-formatโ backend dependentget-unappliedโfalse
๐ธ the replacements, aka what actually gets swapped in
In normal formats and actionformats, these swaps happen, periodt:
%sโ the VCS in use (git,hg,svn, etc.).%bโ info about the current branch.%aโ an identifier describing the action. Only makes sense inactionformats, bestie.%iโ the current revision number or identifier. Forhg, thehgrevformatstyle can be used to customize the output.%cโ the string from thestagedstrstyle if there are staged changes in the repository.%uโ the string from theunstagedstrstyle if there are unstaged changes in the repository.%Rโ the base directory of the repository.%rโ the repository name. If%Ris/foo/bar/repoXY, then%risrepoXY. iykyk ๐ง%Sโ a subdirectory within a repository. If$PWDis/foo/bar/repoXY/beer/tasty, then%Sisbeer/tasty.%mโ a "misc" replacement. It's fully at the discretion of the backend to decide what this one expands to. ๐
The hg and git backends use this expando to show patch information. hg sources patch info from the mq extensions; git gets it from in-progress rebase and cherry-pick operations and from the stgit extension. The patch-format and nopatch-format styles control the generated string. The former is used when at least one patch from the patch queue has been applied, and the latter otherwise. ๐
The hg backend also displays bookmark information in this expando (on top of mq info, not instead of). See the get-mq and get-bookmarks styles. Both of these styles may be enabled at the same time. If both are on, both resulting strings get shown separated by a semicolon โ and no, that separator cannot currently be customized. ๐ญ
The quilt standalone backend sets this expando to the same value as the %Q expando.
%Qโ Quilt series information. When quilt is in use (either inaddonmode or as astandalonebackend), this expando is set to the quilt series'patch-formatstring. Theset-patch-formathook and thenopatch-formatstyle are honoured. ๐
See Quilt Support below for the details.
In branchformat, these replacements are done:
%bโ the branch name. Forhg, the branch name can include a topic name.%rโ the current revision number, or thehgrevformatstyle forhg.
In hgrevformat, these replacements are done:
%rโ the current local revision number.%hโ the current global revision identifier.
In patch-format and nopatch-format, these replacements are done:
%pโ the name of the top-most applied patch; may be overridden by theapplied-stringhook.%uโ the number of unapplied patches; may be overridden by theunapplied-stringhook.%nโ the number of applied patches.%cโ the number of unapplied patches.%aโ the number of all patches (%a = %n + %c).%gโ the names of active mq guards (hgbackend).%Gโ the number of active mq guards (hgbackend).
Not every VCS backend has to support every replacement โ it's giving โจoptionalโจ. For nvcsformats, no replacements are performed at all, it's literally just a string. ๐
๐ Oddities
Okay so this part is weird but stay with me, bestie.
If you want to use the %b (bold off) prompt expansion inside formats โ the one that expands %b itself, yes, chaotic โ use %%b. That makes the vcs_info expansion replace %%b with %b, so zsh's prompt expansion mechanism can handle it. Similarly, to hand down %b from branchformat, use %%%%b. ๐ญ Sorry for this inconvenience, but it cannot be easily avoided. Luckily we don't clash with a whole lot of prompt expansions, and this only needs to be done for those.
When one of the gen-applied-string, gen-unapplied-string, and set-patch-format hooks is defined, applying %-escaping (foo=${foo//'%'/%%}) to the interpolated values for use in the prompt becomes the responsibility of those hooks (jointly). When none of those hooks is defined, vcs_info handles the escaping by itself. We regret this coupling, but it was required for backwards compatibility. ๐
๐งต Quilt Support
Quilt is not a version control system, so this is not implemented as a backend. What it does do is help keep track of a series of patches. People use it to keep a set of changes they want on top of software packages โ which is tightly integrated into the package build process (the Debian project does this for a large number of packages, iconic behaviour tbh). Quilt can also help individual developers keep track of their own patches on top of real version control systems. ๐
The vcs_info integration tries to support both ways of using quilt by having two slightly different modes of operation: addon mode and standalone mode. ๐ซถ
Quilt integration is off by default. To enable it, set the use-quilt style, and add %Q to your formats or actionformats style:
zstyle ':vcs_info:*' use-quilt true
Styles looked up from the Quilt support code include .quilt-quilt-mode in the vcs-string part of the context, where quilt-mode is either addon or standalone. Example:
:vcs_info:git.quilt-addon:default:repo-root-name.
For addon mode to become active, vcs_info must have already detected a real version control system controlling the directory. If that's 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 quilt-patch-dir style. (Note: you can use vcs_info to keep the value of $QUILT_PATCHES correct all the time via the post-quilt hook. โจ)
Once the directory in question is found, quilt is assumed to be active. To gather more info, vcs_info looks for a directory called .pc โ Quilt uses that directory to track its current state. If this directory does not exist, we know quilt hasn't done anything to the working directory (read: no patches have been applied yet). ๐
If patches are applied, vcs_info will try to find out which. If you want to know which patches of a series are not yet applied, you need to activate the get-unapplied style in the appropriate context.
vcs_info allows for very detailed control over how the gathered information is presented (see the Configuration and Hooks in vcs_info sections), all of which are documented below. Note there are a number of other patch tracking systems that work on top of a certain version control system (like stgit for git, or mq for hg); the configuration for systems like that is generally set up the same way as the quilt support. ๐
If the quilt support is working in addon mode, the produced string is available as a simple format replacement (%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 the version control system identifier (which otherwise would be something like svn or cvs) gets 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 info about quilt's state will be available as the misc replacement (and %Q for compatibility with addon mode). ๐
What's left to discuss is how standalone mode gets detected. The detection itself is a series of searches for directories. You can have this detection enabled all the time in every directory that isn't otherwise under version control. If you know there's only a limited set of trees where you'd like vcs_info to try and look for Quilt in standalone mode โ y'know, to minimise the amount of searching on every single 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's 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's interpreted differently. If the value is the name of a scalar variable, the value of that variable gets checked and that value is used in the same always/never way as described above.
If the value of quilt-standalone is an array, the elements of that array are used as directory names under which you want the detection to be active. ๐ธ
If quilt-standalone is an associative array, the keys are taken as directory names under which you want the detection to be active โ but only if the corresponding value is the string true.
Last, but definitely not least, if the value of quilt-standalone is the name of a function, that function is called without arguments and its return value decides whether detection should be active. A 0 return value is true; a non-zero return value is interpreted as false. ๐ฆ
โจ Function Descriptions (Public API) โจ
okay so quick heads up bestie: if there's both a function AND a variable named quilt-standalone, the function wins. no cap. ๐
vcs_info[user-context] โ the main character fr. this one runs all the backends and assembles literally all the data into${vcs_info_msg_*_}. this is THE function you call fromprecmdwhen you want your prompt to have up-to-date info (peep the Variable Description below ๐). if you give it an argument, that string gets used instead ofdefaultin theuser-contextfield of the style context. slay.vcs_info_hookaddโ statically registers a bunch of functions to a given hook. the hook goes first, then the list of hook-function names to register. leave the+vi-prefix off here, okay? see Hooks in vcs_info below for the deets.vcs_info_hookdelโ yeets hook-functions off a given hook. the hook is the first non-option argument; what follows is the list of hook-function names to un-register. if-ais your first argument, all occurrences of those functions get unregistered. otherwise only the last occurrence gets removed (that's if a function was registered to a hook more than once, fyi). also leave the+vi-prefix off. see Hooks in vcs_info below ๐vcs_info_lastmsgโ outputs the current values of${vcs_info_msg_*_}. it takes theuse-prompt-escapesstyle in':vcs_info:formats:command:-all-'into account, and it only printsmax-exportsvalues.vcs_info_printsys[user-context] โ prints a list of every supported version control system. super useful for finding possible contexts (and which ones are enabled ๐) or values for thedisablestyle.vcs_info_setsysโ initializes vcs_info's internal list of available backends. with this one you can add support for new VCSs without restarting the shell. iconic.
โ ๏ธ all functions named VCS_INFO_* are for internal use only. hands off bestie ๐
๐ธ Variable Description ๐ธ
${vcs_info_msg_N_}(note the trailing underscore!!) โ whereNis an integer, e.g.vcs_info_msg_0_. these variables are the storage for the informational message that the lastvcs_infocall assembled. they're strongly connected to theformats,actionformatsandnvcsformatsstyles described above. those styles are lists: the first member gets expanded into${vcs_info_msg_0_}, the second into${vcs_info_msg_1_}, and the Nth into${vcs_info_msg_N-1_}. (see themax-exportsstyle above ๐ซถ)
โ ๏ธ all variables named VCS_INFO_* are for internal use only. same deal, don't touch ๐ซถ
๐ช Hooks in vcs_info ๐ช
Hooks are little spots inside vcs_info where you can run your own code. that code can talk to the code that called it, and through that, actually change how the system behaves. it's giving main character energy tbh โจ
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 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. and to dodge namespace problems, every registered function name gets a +vi- shoved on the front, so the actual functions called for the foo hook are +vi-bar and +vi-baz. cute, right? ๐
If you wanna register a function to a hook regardless of the current context, use the vcs_info_hookadd function. to remove a function that was added that way, vcs_info_hookdel is your girl.
If something seems weird (and it will ๐ญ), you can enable the debug boolean style in the proper context and the hook-calling code will print what it tried to execute and whether the function in question even existed. little detective moment ๐
When you register more than one function to a hook, all the functions are executed one after another until one returns non-zero or until all of them have been called. context-sensitive hook functions run before the statically registered ones (the ones added by vcs_info_hookadd). order matters, bestie ๐
You may pass data between functions via an associative array, user_data. for example:
+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 integerzero. if and how a changedretvalue changes the execution of the caller depends on the specific hook. see the hook documentation below for details.hook_comโ an associated array used for bidirectional communication from the caller to hook functions. the keys used 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. (local scope first, okay?? ๐)vcsโ the current VCS after it was detected. same values as in theenable/disablestyle. available in all hooks exceptstart-up.
Finally, the full list of currently available hooks:
start-upโ called after starting vcs_info but before the VCS in this directory is determined. it can be used to deactivate vcs_info temporarily if you need to. whenretis set to1, vcs_info aborts and does nothing; when set to2, vcs_info sets everything up as if no version control were active and exits. dramatic exit, love that for us ๐pre-get-dataโ same asstart-upbut after the VCS was detected.gen-hg-bookmark-stringโ called in the Mercurial backend when a bookmark string is generated; theget-revisionandget-bookmarksstyles must be true. this hook gets the names of the Mercurial bookmarks that vcs_info collected fromhg. if a bookmark is active, the key${hook_com[hg-active-bookmark]}is set to its name. the key is otherwise unset. when settingretto non-zero, the string in${hook_com[hg-bookmark-string]}will be used in the%mescape informatsandactionformatsand will be available in the globalbackend_miscarray as${backend_misc[bookmarks]}. ๐gen-applied-stringโ called in the git (with stgit or during rebase or merge), and hg (with mq) backends and in quilt support when the applied-string is generated; theuse-quiltzstyle must be true for quilt (themqandstgitbackends are active by default). the arguments to this hook describe applied patches in the opposite order, which means the first argument is the top-most patch and so forth. when the patches' log messages can be extracted, those are embedded within each argument after a space, so each argument is of the formpatch-name first line of the log message, wherepatch-namecontains no whitespace. the mq backend passes arguments of the formpatch name, with possible embedded spaces, but without extracting the patch's log message. when settingretto non-zero, the string in${hook_com[applied-string]}will be available as%pin thepatch-formatandnopatch-formatstyles. this hook is, in concert withset-patch-format, responsible for%-escaping that value for use in the prompt. (see the Oddities section.) the quilt backend passes to this hook the inputs${hook_com[quilt-patches-dir]}and, if it has been determined,${hook_com[quilt-pc-dir]}.gen-unapplied-stringโ called in the git (with stgit or during rebase), and hg (with mq) backend and in quilt support when the unapplied-string is generated; theget-unappliedstyle must be true. this hook gets the names of all unapplied patches which vcs_info collected, in order, which means the first argument is the patch next-in-line to be applied and so forth. the format of each argument is as forgen-applied-string, above. when settingretto non-zero, the string in${hook_com[unapplied-string]}will be available as%uin thepatch-formatandnopatch-formatstyles. this hook is, in concert withset-patch-format, responsible for%-escaping that value for use in the prompt. (see the Oddities section.) the quilt backend passes to this hook the inputs${hook_com[quilt-patches-dir]}and, if it has been determined,${hook_com[quilt-pc-dir]}.gen-mqguards-stringโ called in the hg backend whenguards-stringis generated; theget-mqstyle must be true (default). this hook gets the names of any active mq guards. when settingretto non-zero, the string in${hook_com[guards-string]}will be used in the%gescape in thepatch-formatandnopatch-formatstyles.no-vcsโ this hook is called when no version control system was detected. thehook_comparameter is not used.post-backendโ called as soon as the backend has finished collecting information. thehook_comkeys available are as for theset-messagehook.post-quiltโ called after the quilt support is done. the following info is passed as arguments to the hook: 1. the quilt-support mode (addonorstandalone); 2. the directory that contains the patch series; 3. the directory that holds quilt's status information (the.pcdirectory) or the string-nopc-if that directory wasn't found. thehook_comparameter is not used.set-branch-formatโ called beforebranchformatis set. the only argument to the hook is the format that is configured at this point. thehook_comkeys considered arebranchandrevision. they're set to the values figured out so far by vcs_info and any change will be used directly when the actual replacement is done. ifretis set to non-zero, the string in${hook_com[branch-replace]}will be used unchanged as the%breplacement in the variables set by vcs_info. ๐set-hgrev-formatโ called before ahgrevformatis set. the only argument to the hook is the format that is configured at this point. thehook_comkeys considered arehashandlocalrev. they're 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.
pre-addon-quiltโ this one kicks in whenevervcs_info's quilt functionality is active in "addon" mode (aka quilt running on top of a real version control system). It fires right before any quilt-specific action gets taken.
Set the ret variable to a non-zero value in this hook and literally no quilt-specific action runs at all. none. zero. ๐
set-patch-formatโ this hook is how you control some of the possible expansions inpatch-formatandnopatch-formatstyles, for patch queue systems like quilt, mqueue and the like. ๐งต
It's used in the git, hg and quilt backends.
The hook lets you control the %p (${hook_com[applied]}) and %u (${hook_com[unapplied]}) expansion in all backends that use the hook. With the mercurial backend, the %g (${hook_com[guards]}) expansion is controllable in addition to that.
If ret is set to non-zero, the string in ${hook_com[patch-replace]} will be used unchanged instead of an expanded format from patch-format or nopatch-format.
This hook is, together with the gen-applied-string or gen-unapplied-string hooks if they're defined, responsible for %-escaping the final patch-format value so it's safe to use in the prompt. (Peep the Oddities section for that one.)
The quilt backend passes to this hook the inputs ${hook_com[quilt-patches-dir]} and, if it has been determined, ${hook_com[quilt-pc-dir]}.
set-messageโ called each time before avcs_info_msg_N_message gets set. It takes two arguments: the first one is theNin the message variable name, and the second is the currently configuredformatsoractionformats.
There are a bunch of hook_com keys used here: action, branch, base, base-name, subdir, staged, unstaged, revision, misc, vcs, plus one miscN entry for each backend-specific data field (N starting at zero). They're set to the values figured out so far by vcs_info, and any change you make gets used directly when the actual replacement happens. โจ
Since this hook is triggered multiple times (once for each configured formats or actionformats), each of the 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 grab the original value on the next run.
Changing the _orig values is probably not a good idea. ๐
If ret is set to non-zero, the string in ${hook_com[message]} will be used unchanged as the message by vcs_info.
If all of this sounds rather confusing, take a look at the Examples section below and also in the Misc/vcs_info-examples file in the Zsh source. They contain some explanatory code. ๐ซถ
๐ธ 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) is done using the zformat builtin from the zsh/zutil module. That means you can do everything with these %x items that zformat supports. In particular, if you want something that's really long to have a fixed width โ like a hash in a mercurial branchformat โ you can do this: %12.12i. That'll shrink the 40 character hash to its 12 leading characters. The form is actually %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%%F{yellow}:%r'
The doubled percent sign is explained in the Oddities section. ๐
Alternatively, one can use the raw colour codes directly:
zstyle ':vcs_info:(svn|bzr):*' \
branchformat '%b%{'${fg[yellow]}'%}:%r'
Normally when a variable is interpolated into a format string, the variable needs to be %-escaped. In this example we skipped that because we assume the value of ${fg[yellow]} doesn't contain any % signs.
Make sure you enclose the color codes in%{...%}if you want to use the string provided byvcs_infoin prompts. ๐จ
Here's how to print the VCS information as a command (not in a prompt):
vcsi() { vcs_info interactive; vcs_info_lastmsg }
This way, you can even define different formats for output via vcs_info_lastmsg in the ':vcs_info:*:interactive:*' 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 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're 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:
function +vi-hgbookmarks() {
# The default is to connect all bookmark names by
# commas. This mixes things up a little.
# Imagine, there's one type of bookmarks that is
# special to you. Say, because it's *your* work.
# Those bookmarks look always like this: "sh/*"
# (because your initials are sh, for example).
# This makes the bookmarks string use only those
# bookmarks. If there's more than one, it
# concatenates them using commas.
# The bookmarks returned by `hg' are available in
# the function's positional parameters.
local s="${(Mj:,:)@:#sh/*}"
# Now, the communication with the code that calls
# the hook functions is done via the hook_com[]
# hash. The key at which the `gen-hg-bookmark-string'
# hook looks is `hg-bookmark-string'. So:
hook_com[hg-bookmark-string]=$s
# And to signal that we want to use the string we
# just generated, set the special variable `ret' to
# something other than the default zero:
ret=1
return 0
}
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 ๐ธ
Okay bestie, this is the part where your terminal starts looking expensive. It's giving main character energy for your prompt, and honestly? Obsessed.
โจ Installation
First things first: 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. Iconic exception, we stan.
You also need the colors and add-zsh-hook functions from Functions/Misc.
These functions may already be installed on your system (slay), but if not, you'll need to find them and copy them. The directory should appear as one of the elements of the fpath array (which should already be the case if they were installed), and at least the function promptinit should be autoloaded โ it will autoload the rest, like the little manager it is.
Finally, to initialize the use of the system you need to call the promptinit function. The following code in your .zshrc will arrange for this; assume the functions are stored in the directory ~/myfns:
fpath=(~/myfns $fpath)
autoload -U promptinit
promptinit
That's it, you're so back. ๐
๐ 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. No more boring default prompt, periodt.
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. Chaos, but make itโจaestheticโจ.
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. Like a lil' "who am I" moment for your prompt.-lโ List all available prompt themes. Window shopping, bestie.-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 thepromptfunction if no theme is given.-sโ Set theme as the current theme and save state.
prompt_theme_setup
Each available theme has a setup function which is called by the prompt function to install that theme. This function may define other functions as necessary to maintain the prompt, including functions used to preview the prompt or provide help for its use. You should not normally call a theme's setup function directly โ that's the prompt function's job, don't steal its moment. ๐
๐ฆ Utility Themes
prompt offโ The themeoffsets all the prompt variables to minimal values with no special effects. Bare bones, zero drama.prompt defaultโ The themedefaultsets all prompt variables to the same state as if an interactive zsh was started with no initialization files. A lil' reset to factory settings, if you will.prompt restoreโ The special themerestoreerases all theme settings and sets prompt variables to their state before the first time thepromptfunction was run, provided each theme has properly defined its cleanup (see below). Cleanup queen behavior.
Heads up bestie: you can undoprompt offandprompt defaultwithprompt restore, but a second restore does not undo the first. One undo per undo, them's the rules. ๐ญ
๐ Writing Themes
The first step for adding your own theme is to choose a name for it, and create a file prompt_name_setup in a directory in your fpath, such as ~/myfns in the example above. Yes, name is a placeholder โ that's your theme's name, go wild.
The file should at minimum contain assignments for the prompt variables that your theme wishes to modify. By convention, themes use PS1, PS2, RPS1, etc., rather than the longer PROMPT and RPROMPT. Shorter is cuter, iykyk.
The file is autoloaded as a function in the current shell context, so it may contain any necessary commands to customize your theme, including defining additional functions. To make some complex tasks easier, your setup function may also do any of the following:
Assign prompt_opts
The array prompt_opts may be assigned any of "bang", "cr", "percent", "sp", and/or "subst" as values. The corresponding setopts (promptbang, etc.) are turned on, and all other prompt-related options are turned off. The prompt_opts array preserves setopts even beyond the scope of localoptions, should your function need that. Sneaky but valid. ๐ง
Modify hooks
Use of add-zsh-hook and add-zle-hook-widget is recommended (see the Manipulating Hook Functions section above). All hooks that follow the naming pattern prompt_theme_hook are automatically removed when the prompt theme changes or is disabled. Self-cleaning, we love a low-maintenance icon.
Declare cleanup
If your function makes any other changes that should be undone when the theme is disabled, your setup function may call
prompt_cleanup command
where command should be suitably quoted. If your theme is ever disabled or replaced by another, command is executed with eval. You may declare more than one such cleanup hook. No cap, stack 'em up.
Define preview
Define or autoload a function prompt_name_preview to display a simulated version of your prompt. A simple default previewer is defined by promptinit for themes that do not define their own. This preview function is called by prompt -p. Try before you buy, bestie.
Provide help
Define or autoload a function prompt_name_help to display documentation or help text for your theme. This help function is called by prompt -h. Be the theme that explains itself. ๐ซถ
๐ 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. Keybindings are literally your terminal's love language. ๐ฅ
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
The -match girlies ๐
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 delete-whole-word-match, select-word-match select-word-style, match-word-context, match-words-by-style
The first eight -match functions are drop-in replacements for the builtin widgets without the suffix. By default they behave in a similar way. However, by the use of styles and the function select-word-style, the way words are matched can be altered.
select-word-match is intended to be used as a text object in vi mode but with custom word styles. For comparison, the widgets described in zshzle(1) under Text Objects use fixed definitions of words, compatible with the vim editor.
The simplest way of configuring the functions is to use select-word-style, which can either be called as a normal function with the appropriate argument, or invoked as a user-defined widget that will prompt for the first character of the word style to be used. The first time it is invoked, the first eight -match functions will automatically replace the builtin versions, so they do not need to be loaded explicitly. Glow-up, automatic.
The word styles available are as follows. Only the first character is examined โ so efficient.
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 asnormal.
All but default can be input as an upper case character, which has the same effect but with subword matching turned on. In this case, words with upper case characters are treated specially: each separate run of upper case characters, or an upper case character followed by any number of other characters, is considered a word. The style subword-range can supply an alternative character range to the 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). Careful with the brackets, bestie, they're literally load-bearing. ๐ญ
More control can be obtained using the zstyle command, as described in zshmodules(1). Each style is looked up in the context :zle:widget where widget is the name of the user-defined widget, not the name of the function implementing it, so in the case of the definitions supplied by select-word-style the appropriate contexts are :zle:forward-word, and so on. The function select-word-style itself always defines styles for the context :zle:* which can be overridden by more specific (longer) patterns as well as explicit contexts. Specificity is a flex.
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 stylesword-charsorword-class.specifiedโ Similar tonormal, but only the specified characters, and not also alphanumerics, are considered word characters.unspecifiedโ The negation ofspecified. 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โ Words are whitespace-delimited strings of characters.
Okay so the first three of those rules usually use $WORDCHARS, but bestie you can override that value with the style word-chars, which works in exactly the same way as $WORDCHARS. โจ And on top of that, the style word-class uses character class syntax to group characters and it takes precedence over word-chars if both are set. The word-class style does not include the surrounding brackets of the character class โ for example, -:[:alnum:] is a valid word-class to include all alphanumerics plus the characters - and :. Be careful including ], ^ and - though, because those are special inside character classes. ๐
word-style may also have -subword appended to its value to turn on subword matching, as described above. ๐
The style skip-chars is mostly useful for transpose-words and similar functions. If set, it gives a count of characters starting at the cursor position which will not be considered part of the word and are treated as space, regardless of what they actually are. For example, if
zstyle ':zle:transpose-words' skip-chars 1
has been set, and transpose-words-match is called with the cursor on the X of fooXbar, where X can be any character, then the resulting expression is barXfoo. ๐
Finer grained control can be obtained by setting the style word-context to an array of pairs of entries. Each pair of entries consists of a pattern and a subcontext. The shell argument the cursor is on is matched against each pattern in turn until one matches; if it does, the context is extended by a colon and the corresponding subcontext. Note that the test is made against the original word on the line, with no stripping of quotes. Special handling is done between words: the current context is examined and if it contains the string between the word is set to a single space; else if it contains the string back, the word before the cursor is considered, else the word after cursor is considered. Some examples are given below. ๐
The style skip-whitespace-first is only used with the forward-word widget. If it is set to true, then forward-word skips any non-word-characters, followed by any non-word-characters: this is similar to the behaviour of other word-orientated widgets, and also that used by other editors, however it differs from the standard zsh behaviour. When using select-word-style the widget is set in the context :zle:* to true if the word style is bash and false otherwise. It may be overridden by setting it in the more specific context :zle:forward-word*. ๐
It is possible to create widgets with specific behaviour by defining a new widget implemented by the appropriate generic function, then setting a style for the context of the specific widget. For example, the following defines a widget backward-kill-space-word using backward-kill-word-match, the generic widget implementing backward-kill-word behaviour, and ensures that the new widget always implements space-delimited behaviour. ๐ฅ
zle -N backward-kill-space-word backward-kill-word-match
zstyle :zle:backward-kill-space-word word-style space
The widget backward-kill-space-word can now be bound to a key. slay ๐
Here are some further 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 \
"*/*" filename "[[:space:]]" whitespace
zstyle ':zle:transpose-words:whitespace' word-style shell
zstyle ':zle:transpose-words:filename' word-style normal
zstyle ':zle:transpose-words:filename' word-chars ''
This provides two different ways of using transpose-words depending on whether the cursor is on whitespace between words or on a filename, here any word containing a /. On whitespace, complete arguments as defined by standard shell rules will be transposed. In a filename, only alphanumerics will be transposed. Elsewhere, words will be transposed using the default style for :zle:transpose-words. ๐ธ
The word matching and all the handling of zstyle settings is actually implemented by the function match-words-by-style. This can be used to create new user-defined widgets. The calling function should set the local parameter curcontext to :zle:widget, create the local parameter matched_words and call match-words-by-style with no arguments. On return, matched_words will be set to an array with the elements: (1) the start of the line (2) the word before the cursor (3) any non-word characters between that word and the cursor (4) any non-word character at the cursor position plus any remaining non-word characters before the next word, including all characters specified by the skip-chars style, (5) the word at or following the cursor (6) any non-word characters following that word (7) the remainder of the line. Any of the elements may be an empty string; the calling function should test for this to decide whether it can perform its function. ๐ง
If the variable matched_words is defined by the caller to match-words-by-style as an associative array (local -A matched_words), then the seven values given above should be retrieved from it as elements named start, word-before-cursor, ws-before-cursor, ws-after-cursor, word-after-cursor, ws-after-word, and end. In addition the element is-word-start is 1 if the cursor is on the start of a word or subword, or on white space before it (the cases can be distinguished by testing the ws-after-cursor element) and 0 otherwise. This form is recommended for future compatibility. ๐
It is possible to pass options with arguments to match-words-by-style to override the use of styles. The options are:
-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. ๐ซถ
๐ bracketed-paste-magic ๐
The bracketed-paste widget (see the subsection Miscellaneous' in zshzle(1)) inserts pasted text literally into the editor buffer rather than interpret it as keystrokes. This disables some common usages where the self-insertwidget is replaced in order to accomplish some extra processing. An example is the contributedurl-quote-magic` widget described below. ๐ญ
The bracketed-paste-magic widget is meant to replace bracketed-paste with a wrapper that re-enables these self-insert actions, and other actions as selected by zstyles. Therefore this widget is installed with ๐
autoload -Uz bracketed-paste-magic
zle -N bracketed-paste bracketed-paste-magic
Other than enabling some widget processing, bracketed-paste-magic attempts to replicate bracketed-paste as faithfully as possible.
The following zstyles may be set to control processing of pasted text. All are looked up in the context `:bracketed-paste-magic'.
๐ active-widgets
A list of patterns matching widget names that should be activated during the paste. All other key sequences are processed as self-insert-unmeta. The default is `self-*' so any user-defined widgets named with that prefix are active along with the builtin self-insert.
If this style is not set (explicitly deleted) or set to an empty value, no widgets are active and the pasted text is inserted literally. If the value includes `undefined-key', any unknown sequences are discarded from the pasted text. ๐
๐ inactive-keys
The inverse of active-widgets, a list of key sequences that always use self-insert-unmeta even when bound to an active widget. Note that this is a list of literal key sequences, not patterns. ๐
๐ paste-init
A list of function names, called in widget context (but not as widgets). The functions are called in order until one of them returns a non-zero status. The parameter `PASTED' contains the initial state of the pasted text. All other ZLE parameters such as `BUFFER' have their normal values and side-effects, and full history is available, so for example paste-init functions may move words from BUFFER into PASTED to make those words visible to the active-widgets.
A non-zero return from a paste-init function does not prevent the paste itself from proceeding.
Loading bracketed-paste-magic defines backward-extend-paste, a helper function for use in paste-init. ๐
zstyle :bracketed-paste-magic paste-init \
backward-extend-paste
When a paste would insert into the middle of a word or append text to a word already on the line, backward-extend-paste moves the prefix from LBUFFER into PASTED so that the active-widgets see the full word so far. This may be useful with url-quote-magic. โจ
paste-finish (still living inside bracketed-paste-magic, we're not done yet ๐
)
Okay so this is another list of function names, and they get called in order until one of them returns non-zero. Cute, right?
These ones run after the pasted text has been processed by the active-widgets, but before it's inserted into BUFFER. ZLE parameters have their normal values and side-effects while this happens. โจ
Heads up bestie: a non-zero return from a paste-finish function does not prevent the paste itself from proceeding.
Loading bracketed-paste-magic also defines quote-paste, which is a helper function for use in paste-finish. ๐ซถ
zstyle :bracketed-paste-magic paste-finish \
quote-paste
zstyle :bracketed-paste-magic:finish quote-style \
qqq
When the pasted text is inserted into BUFFER, it is quoted per the quote-style value. And if you wanna forcibly turn off the built-in numeric prefix quoting of bracketed-paste, do this:
zstyle :bracketed-paste-magic:finish quote-style \
none
Important, like actually important: During active-widgets processing of the paste (afterpaste-initand beforepaste-finish),BUFFERstarts empty and history is restricted, so cursor motions, etc., may not pass outside of the pasted content. Text assigned toBUFFERby the active widgets is copied back intoPASTEDbeforepaste-finish. ๐ธ
copy-earlier-word
This widget is giving "combination of insert-last-word and copy-prev-shell-word" energy. ๐ฅ Repeated invocations of the widget retrieve earlier words on the relevant history line. With a numeric argument N, insert the Nth word from the history line; N may be negative to count from the end of the line.
If insert-last-word has been used to retrieve the last word on a previous history line, repeated invocations will replace that word with earlier words from the same line. ๐
Otherwise, the widget applies to words on the line currently being edited. The widget style can be set to the name of another widget that should be called to retrieve words. That widget must accept the same three arguments as insert-last-word. No cap. ๐
cycle-completion-positions
So after inserting an unambiguous string into the command line, the new function based completion system may know about multiple places in this string where characters are missing or differ from at least one of the possible matches. It'll then place the cursor on the position it considers the most interesting one โ i.e. the one where you can disambiguate between as many matches as possible with as little typing as possible. Lowkey genius. โญ
This widget lets the cursor hop around to the other interesting spots. Invoke it repeatedly and it cycles between all the positions reported by the completion system. It's giving little cursor road trip. ๐ฆ
delete-whole-word-match
Another function that works like the -match functions described immediately above, i.e. using styles to decide the word boundaries. But โ and this is the plot twist โ it is not a replacement for any existing function. ๐
The basic behaviour is to delete the word around the cursor. There is no numeric argument handling; only the single word around the cursor is considered. If the widget contains the string kill, the removed text will be placed in the cutbuffer for future yanking. You get that by defining kill-whole-word-match like this:
zle -N kill-whole-word-match delete-whole-word-match
โฆand then binding the widget kill-whole-word-match. Periodt. ๐
up-line-or-beginning-search, down-line-or-beginning-search
These widgets are similar to the builtin functions up-line-or-search and down-line-or-search: if in a multiline buffer they move up or down within the buffer, otherwise they search for a history line matching the start of the current line. Same vibe, right? But here's the difference, bestie: they search for a line which matches the current line up to the current cursor position, in the manner of history-beginning-search-backward and -forward, rather than the first word on the line. ๐ง
edit-command-line
Edit the command line using your visual editor, as in ksh. That's it, that's the widget. ๐
bindkey -M vicmd v edit-command-line
The editor to be used can also be specified using the editor style in the context of the widget. It's specified as an array of command and arguments:
zstyle :zle:edit-command-line editor gvim -f
expand-absolute-path
Expand the file name under the cursor to an absolute path, resolving symbolic links. Where possible, the initial path segment is turned into a named directory or reference to a user's home directory. So like, ~-ify it where it can. Absolutel-ify it where it can't. ๐
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)) and then moving the cursor to the end of the line. The original cursor position is remembered and restored before calling the builtin widget a second time, so that the same search is repeated to look farther through the history. ๐
Although you autoload only one function, the commands to use it are slightly different because it implements two widgets:
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
And here's yet another form of history searching, because zsh will never stop giving us options. ๐ญ The text before the cursor is used to select lines from the history, as for history-beginning-search-backward โ except that all matches are shown in a numbered menu. Typing the appropriate digits inserts the full history line. Note that leading zeroes must be typed (they are only shown when necessary for removing ambiguity). The entire history is searched; there is no distinction between forwards and backwards. ๐
With a numeric argument, the search is not anchored to the start of the line; the string typed by the use may appear anywhere in the line in the history.
If the widget name contains -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 numeric argument). Both forms can be combined, for example:
zle -N history-beginning-search-menu-space-end \
history-beginning-search-menu
history-pattern-search
The function history-pattern-search implements widgets which prompt for a pattern with which to search the history backwards or forwards. The pattern is in the usual zsh format, however the first character may be ^ to anchor the search to the start of the line, and the last character may be $ to anchor the search to the end of the line. If the search was not anchored to the end of the line the cursor is positioned just after the pattern found. ๐ฆ
The commands to create bindable widgets are similar to those in the example immediately above:
autoload -U history-pattern-search
zle -N history-pattern-search-backward history-pattern-search
zle -N history-pattern-search-forward history-pattern-search
incarg
Typing the keystrokes for this widget with the cursor placed on or to the left of an integer causes that integer to be incremented by one. With a numeric argument, the number is incremented by the amount of the argument (decremented if the numeric argument is negative). The shell parameter incarg may be set to change the default increment to something other than one. ๐ข
bindkey '^X+' incarg
incremental-complete-word
This allows incremental completion of a word. After starting this command, a list of completion choices can be shown after every character you type, which you can delete with ^H or DEL. Pressing return accepts the completion so far and returns you to normal editing (that is, the command line is not immediately executed โ no accidental sends, thank you ๐). You can hit TAB to do normal completion, ^G to abort back to the state when you started, and ^D to list the matches. ๐ซถ
This works only with the new function based completion system.
bindkey '^Xi' incremental-complete-word
insert-composed-char
This function allows you to compose characters that don't appear on the keyboard and get them inserted into the command line. The command is followed by two keys corresponding to ASCII characters (there is no prompt, so don't go looking for one ๐
). For accented characters, the two keys are a base character followed by a code for the accent, while for other special characters the two characters together form a mnemonic for the character to be inserted. The two-character codes are a subset of those given by RFC 1345 (see for example http://www.faqs.org/rfcs/rfc1345.html). โจ
The function may optionally be followed by up to two characters which replace one or both of the characters read from the keyboard; if both characters are supplied, no input is read. For example, insert-composed-char a: can be used within a widget to insert an a with umlaut into the command line. This has the advantages over use of a literal character that it is more portable. ๐ง
For best results zsh should have been built with support for multibyte characters (configured with --enable-multibyte); however, the function works for the limited range of characters available in single-byte character sets such as ISO-8859-1.
The character is converted into the local representation and inserted into the command line at the cursor position. (The conversion is done within the shell, using whatever facilities the C library provides.) With a numeric argument, the character and its code are previewed in the status line. โญ
The function can totally be run outside zle too โ in that case it prints the character (plus a newline) to standard output. Input is still read from keystrokes though, no cap.
See insert-unicode-char if you'd rather insert Unicode characters by their hexadecimal number โ different vibe, same goal.
The accented-characters set is reasonably complete up to Unicode character U+0180, but the special characters? Less so, ngl. And past that point it's honestly very sporadic ๐. Adding new characters is easy though โ check out the function define-composed-chars. And please send any additions to zsh-workers@zsh.org ๐ซถ.
The codes for the second character when it's used to accent the first are these. Just know that not every character can take every accent, bestie:
!โ Grave.'โ Acute.>โ Circumflex.?โ Tilde. (This is not~, because RFC 1345 doesn't assume that character is present on the keyboard.)-โ Macron. (A horizontal bar over the base character.)(โ Breve. (A shallow dish shape over the base character.).โ Dot above the base character, or in the case ofino dot, or in the case ofLandla centered dot.:โ Diaeresis (Umlaut).cโ 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โ Horn over the base character.
The most common characters from the Arabic, Cyrillic, Greek and Hebrew alphabets are available โ consult RFC 1345 for the appropriate sequences โจ. Plus, there's a set of two-letter codes not in RFC 1345 for the double-width characters corresponding to ASCII characters from ! to ~ (0x21 to 0x7e), made by putting ^ in front of the character โ for example ^A gives you a double-width A ๐
The following other two-character sequences are understood, too:
ASCII characters
These are already present on most keyboards, so, like, free real estate:
<(โ 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-โ EthTH,thโ Thornkkโ Kra'nโ 'nNG,ngโ NgOI,oiโ Oiyrโ yrEDโ ezh
Currency symbols
Ctโ CentPdโ Pound sterling (also lira and others)Cuโ CurrencyYeโ YenEuโ Euro (N.B. not in RFC 1345)
Punctuation characters
Heads up: 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. Iconic, honestly.)
!Iโ Inverted exclamation markBBโ Broken vertical barSEโ SectionCoโ Copyright-aโ Spanish feminine ordinal indicator<<โ Left guillemet--โ Soft hyphenRgโ Registered trade markPIโ 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 quote9'โ Reversed "right" quote"6โ Left double quote"9โ Right double quote:9โ "Right" low double quote9"โ Reversed "right" double quote/-โ Dagger/=โ Double dagger
Mathematical symbols
Math girlies rise up ๐ฅ:
DGโ Degree-2,+-,-+โ-sign,+/-sign,-/+sign2Sโ Superscript 23Sโ Superscript 31Sโ Superscript 1Myโ Micro.Mโ Middle dot14โ Quarter12โ Half34โ Three quarters*Xโ Multiplication-:โ Division%0โ Per milleFA,TE,/0โ For all, there exists, empty setdP,DE,NBโ Partial derivative, delta (increment), del (nabla)(-,-)โ Element of, contains*P,+Zโ Product, sum*-,Ob,Sbโ Asterisk, ring, bulletRT,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 signFm,Mlโ Female, male
Accents on their own
'>โ Circumflex (same as caret,^)'!โ Grave (same as backtick,`)',โ Cedilla':โ Diaeresis (Umlaut)'mโ Macron''โ Acute
insert-files
This one lets you type a file pattern and see the results of the expansion at every single step ๐. When you hit return, all the expansions get inserted into the command line. Chef's kiss.
bindkey '^Xf' insert-files
insert-unicode-char
The first time you execute it, you type in a set of hexadecimal digits. That's terminated with another call to insert-unicode-char. The digits then get turned into the corresponding Unicode character โจ. So 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
narrow-to-region [ -p pre ] [ -P post ]
[ -S statepm | -R statepm | [ -l lbufvar ] [ -r rbufvar
] ]
[ -n ] [ start end ]
narrow-to-region-invisible
Okay so this narrows the editable portion of the buffer to the region between the cursor and the mark โ and those can be in either order, no stress. The region may not be empty, though.
narrow-to-region can be used as a widget or called as a function from a user-defined widget; by default, the text outside the editable area stays visible. A recursive-edit is performed, and then the original widening status gets restored ๐ซถ. Various options and arguments are available when it's called as a function.
The options -p pretext and -P posttext replace the text before and after the display for the duration of the function; either or both may be an empty string.
If the option -n is also given, pretext or posttext will only be inserted if there is text before or after the region respectively which will be made invisible.
Two numeric arguments may be given, and they'll be used instead of the cursor and mark positions.
The option -S statepm narrows according to the other options while saving the original state in the parameter with name statepm, while the option -R statepm restores the state from the parameter โ and in both cases the name of the parameter is required, bestie, don't skip it. In the second case, other options and arguments are irrelevant. When this method is used, no recursive-edit is performed; the calling widget should call this function with the option -S, do its own editing on the command line or pass control to the user via `zle recursive-edit', then call this function with the option -R. The argument statepm must be a suitable name for an ordinary parameter, except that parameters beginning with the prefix _ntr_ are reserved for use within narrow-to-region. Typically the parameter will be local to the calling function.
The options -l lbufvar and -r rbufvar may be used to specify parameters where the widget will store the resulting text from the operation. The parameter lbufvar will contain LBUFFER and rbufvar will contain RBUFFER. Neither of these two options may be used with -S or -R โ ๏ธ.
narrow-to-region-invisible is a simple widget which calls narrow-to-region with arguments that replace any text outside the region with .... It does not take any arguments.
The display is restored (and the widget returns) upon any zle command which would usually cause the line to be accepted or aborted. Hence an additional such command is required to accept or abort the current line.
The return status of both widgets is zero if the line was accepted, else non-zero.
Here's a trivial example of a widget using this feature:
local state
narrow-to-region -p $'Editing restricted region\n' \
-P '' -S state
zle recursive-edit
narrow-to-region -R state
predict-on
This set of functions implements predictive typing using history search ๐ฎ. After predict-on, typing characters causes the editor to look backward in the history for the first line beginning with what you've typed so far. After predict-off, editing returns to normal for the line found. Honestly, you often don't even need to use predict-off, because if the line doesn't match something in the history, adding a key performs standard completion, and then inserts itself if no completions were found. However โ editing in the middle of a line is liable to confuse prediction; see the toggle style below ๐.
With the function based completion system (which is needed for this), you should be able to hit Tab at basically any point and have the cursor yeet itself forward to the next "interesting" character position โ usually the end of the current word, but lowkey sometimes somewhere in the middle of the word. And obviously the second the whole line is what you want, you just accept with return, no need to drag the cursor to the end first. Main character cursor behaviour, honestly. โจ
The first time predict-on is used, it creates several additional widget functions for you:
delete-backward-and-predictโ Replaces thebackward-delete-charwidget. You do not need to bind this yourself. ๐ซถinsert-and-predictโ Implements predictive typing by replacing theself-insertwidget. You do not need to bind this yourself either, bestie.predict-offโ Turns off predictive typing. The off switch, the vibe check, the "ok I'm done" button.
So even though you only autoload the predict-on function, it is necessary to create a keybinding for predict-off as well. Both of them. Non-negotiable. ๐
zle -N predict-on
zle -N predict-off
bindkey '^X^Z' predict-on
bindkey '^Z' predict-off
๐ธ read-from-minibuffer
This one is most useful when called as a function from inside a widget, but it will work correctly as a widget in its own right too. Iconic flexibility. It prompts for a value below the current command line, and you can input that value using all of the standard zle operations โ not merely the restricted set available when executing, for example, execute-named-cmd. Then the value is returned to the calling function in the parameter $REPLY, and the editing buffer is restored to its previous state. Chef's kiss. ๐
If the read was aborted by a keyboard break (typically Ctrl+G), the function returns status 1 and $REPLY is not set. Rude but fair.
Argument situation, since ikykyk:
- One argument โ it's taken as a prompt. Otherwise
'? 'is used. - Two arguments โ they're the prompt and the initial value of
$LBUFFER. - Three arguments โ the third one is the initial value of
$RBUFFER.
That gives you a default value and a starting cursor placement, which is honestly so thoughtful. Upon return, the entire buffer is the value of $REPLY.
One option is available:
-k numโ specifies that num characters are to be read instead of a whole line. Heads up though: the line editor is not invoked recursively in this case, so depending on the terminal settings the input may not be visible, and only the input keys are placed in$REPLY, not the entire buffer. Also note that unlike thereadbuiltin, num must be given โ there is no default. No vibes-based guessing allowed.
Okay so the name is a slight misnomer, because in fact the shell's own minibuffer is not used. Which is actually a slay โ it means it's still possible to call executed-named-cmd and similar functions while reading a value. ๐
๐ฆ replace-argument, replace-argument-edit
The function replace-argument can be used to replace a command line argument in the current command line or, if the current command line is empty, in the last command line executed (and psst โ the new command line is not executed). Arguments are as delimited by standard shell syntax,
If a numeric argument is given, that specifies the argument to be replaced. 0 means the command name, as in history expansion. A negative numeric argument counts backward from the last word. Tracking, bestie. ๐
If no numeric argument is given, the current argument is replaced; this is the last argument if the previous history line is being used.
The function prompts for a replacement argument. Easy.
If the widget contains the string edit, for example is defined as
zle -N replace-argument-edit replace-argument
then the function presents the current value of the argument for editing โ otherwise the editing buffer for the replacement is initially empty. Blank slate energy. ๐
โจ 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. Find and replace but make it zle.
If the widget name contains the word pattern, for example by defining the widget using the command zle -N replace-pattern replace-string, then the matching is performed using zsh patterns. All zsh extended globbing patterns can be used in the source string โ but note that unlike filename generation, the pattern does not need to match an entire word, nor do glob qualifiers have any effect. In addition, the replacement string can contain parameter or command substitutions. Furthermore:
- a
&in the replacement string will be replaced with the matched source string, and - a backquoted digit
\Nwill be replaced by the *N*th 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 regexp), then the matching is performed using regular expressions, respecting the setting of the option RE_MATCH_PCRE (see the description of the function regexp-replace below). The special replacement facilities described above for pattern matching are available. Same energy, regex edition.
By default the previous source or replacement string will not be offered for editing. However, this feature can be activated by setting the style edit-previous in the context :zle:widget (for example, :zle:replace-string) to true. In addition, a positive numeric argument forces the previous values to be offered, a negative or zero argument forces them not to be. Zero chill about zeros.
The function replace-string-again can be used to repeat the previous replacement; no prompting is done. As with replace-string, if the name of the widget contains the word pattern or regex, pattern or regular expression matching is performed, else a literal string replacement. Note that the previous source and replacement text are the same whether pattern, regular expression or string matching is used. One source of truth, periodt.
In addition, replace-string shows the previous replacement above the prompt, so long as there was one during the current session; if the source string is empty, that replacement will be repeated without the widget prompting for a replacement string. Convenient? Yes. Dangerous? Also kind of yes, watch it. ๐
For example, starting from the line:
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. So likeโฆ undo has layers now. ๐ญ
๐ซ 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 โ and this is the whole point โ the input being typed is concealed and a string of asterisks (*) is shown instead. Secretive. Mysterious. Main character with secrets. ๐
The value is saved in the parameter $INVISIBLE, to which a reference is inserted into the editing buffer at the restored cursor position. If the read was aborted by a keyboard break (typically Ctrl+G) or another escape from editing such as push-line, $INVISIBLE is set to empty and the original buffer is restored unchanged.
If one argument is supplied to the function it is taken as a prompt, otherwise 'Non-echoed text: ' is used (as in emacs). If a second and third argument are supplied they are used to begin and end the reference to $INVISIBLE that is inserted into the buffer. The default is to open with ${, then INVISIBLE, and close with }, but many other effects are possible. Customise away, bestie. ๐
โญ 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 argument, 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. Tiny but important detail, ngl.
Otherwise, the rightmost "interesting" word from the previous command is found and inserted. The default definition of "interesting" is that the word contains at least one alphabetic character, slash, or backslash. This definition may be overridden by use of the match style. The context used to look up the style is the widget name, so usually the context is :insert-last-word. However, you can bind this function to different widgets to use different patterns โ the way that this is fully customisable is honestly so good:
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. So yes, you're spamming the key. That's the intended workflow. ๐ฅ
๐ transpose-lines
Only useful with a multi-line editing buffer โ and the lines here are lines within the current on-screen buffer, not history lines. Important distinction, don't get it twisted. The effect is similar to the function of the same name in Emacs.
Transpose the current line with the previous line and move the cursor to the start of the next line. Repeating this (which can be done by providing a positive numeric argument) has the effect of moving the line above the cursor down by a number of lines. Line shuffle, basically. ๐
With a negative numeric argument, requires two lines above the cursor. These two lines are transposed and the cursor moved to the start of the previous line. Using a numeric argument less than -1 has the effect of moving the line above the cursor up by minus that number of lines. Math girlie behaviour and I respect it. ๐
๐ url-quote-magic
okay so this widget literally replaces the built-in self-insert to make typing URLs as command line arguments way easier โจ. As you type, the input character gets analyzed and, if it might need quoting, the current word is checked for a URI scheme. If one is found and the current word isn't already in quotes, a backslash gets inserted before the input character. slay.
Styles that control the quoting behavior, bestie:
url-metasโ this style is looked up in the context:url-quote-magic:scheme(where scheme is that of the current URL, like "ftp"). The value is a string listing the characters to be treated as globbing metacharacters when appearing in a URL using that scheme. The default is to quote all zsh extended globbing characters, excluding<and>but including braces (as in brace expansion). See alsourl-seps.url-sepsโ likeurl-metas, but lists characters that should be considered command separators, redirections, history references, etc. The default is to quote the standard set of shell separators, excluding those that overlap with the extended globbing characters, but including<and>and the first character of$histchars.url-globbersโ this style is looked up in the context:url-quote-magic. The values form a list of command names that are expected to do their own globbing on the URL string. This implies that they're aliased to use thenoglobmodifier. When the first word on the line matches one of the values and the URL refers to a local file (seeurl-local-schema), only theurl-sepscharacters are quoted; theurl-metasare left alone, allowing them to affect command-line parsing, completion, etc. The default values are a literalnoglobplus (when thezsh/parametermodule is available) any commands aliased to the helper functionurlglobberor its aliasgloburl.url-local-schemaโ this style is always looked up in the context:urlglobber, even though it's used by bothurl-quote-magicandurlglobber. The values form a list of URI schema that should be treated as referring to local files by their real local path names, as opposed to files which are specified relative to a web-server-defined document root. The defaults are"ftp"and"file".url-other-schemaโ likeurl-local-schema, but lists all other URI schema upon whichurlglobberandurl-quote-magicshould act. If the URI on the command line doesn't have a scheme appearing either in this list or inurl-local-schema, it's not magically quoted ๐ช. The default values are"http","https", and"ftp". When a scheme appears both here and inurl-local-schema, it gets quoted differently depending on whether the command name appears inurl-globbers.
Loading url-quote-magic also defines a helper function urlglobber and aliases globurl to noglob urlglobber ๐. This function takes a local URL apart, attempts to pattern-match the local file portion of the URL path, and then puts the results back into URL format again. iconic.
๐ฐ vi-pipe
This function reads a movement command from the keyboard and then prompts for an external command. The part of the buffer covered by the movement gets piped to the external command and then replaced by the command's output. If the movement command is bound to vi-pipe, the current line is used.
It serves as an example for reading a vi movement command from within a user-defined widget, iykyk โจ.
๐ต๏ธ which-command
This function is a drop-in replacement for the builtin widget which-command. It has enhanced behaviour, in that it correctly detects whether or not the command word needs to be expanded as an alias; if so, it continues tracing the command word from the expanded alias until it reaches the command that will actually be executed. no cap, it goes all the way down.
The style whence is available in the context :zle:$WIDGET; this may be set to an array to give the command and options that will be used to investigate the command word found. The default is whence -c.
๐งฎ zcalc-auto-insert
This function is useful together with the zcalc function described in the section Mathematical Functions. It should be bound to a key representing a binary operator such as +, -, * or /. When running in zcalc, if the key occurs at the start of the line or immediately following an open parenthesis, the text "ans " is inserted before the representation of the key itself. This allows easy use of the answer from the previous calculation in the current line ๐ฅ. The text to be inserted before the symbol typed can be modified by setting the variable ZCALC_AUTO_INSERT_PREFIX.
Hence, for example, typing +12 followed by return adds 12 to the previous result. math queen behavior honestly.
If zcalc is in RPN mode (-r option) the effect of this binding is automatically suppressed, as operators alone on a line are meaningful.
When not in zcalc, the key simply inserts the symbol itself. ๐ซถ
๐ ๏ธ 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
This function splits the line currently being edited into shell arguments and whitespace. The result is stored in the array reply. The array contains all the parts of the line in order, starting with any whitespace before the first argument, and finishing with any whitespace after the last argument. Hence (so long as the option KSH_ARRAYS is not set) whitespace is given by odd indices in the array and arguments by even indices ๐. Note that no stripping of quotes is done; joining together all the elements of reply in order is guaranteed to produce the original line. fr fr.
The parameter REPLY is set to the index of the word in reply which contains the character after the cursor, where the first element has index 1. The parameter REPLY2 is set to the index of the character under the cursor in that word, where the first character has index 1.
Hencereply,REPLYandREPLY2should all be made local to the enclosing function. ๐
See the function modify-current-argument, described below, for an example of how to call this function.
๐ช modify-current-argument [ expr-using-$ARG | func ]
This function provides a simple method of allowing user-defined widgets to modify the command line argument under the cursor (or immediately to the left of the cursor if the cursor is between arguments).
The argument can be an expression which when evaluated operates on the shell parameter ARG, which will have been set to the command line argument under the cursor. The expression should be suitably quoted to prevent it being evaluated too early.
Alternatively, if the argument does not contain the string ARG, it is assumed to be a shell function, to which the current command line argument is passed as the only argument. The function should set the variable REPLY to the new value for the command line argument. If the function returns non-zero status, so does the calling function.
For example, a user-defined widget containing the following code converts the characters in the argument under the cursor into all upper case:
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}}'
The following performs directory expansion on the command line argument and replaces it by the absolute path:
expand-dir() {
REPLY=${~1}
REPLY=${REPLY:a}
}
modify-current-argument expand-dir
In practice the function expand-dir would probably not be defined within the widget where modify-current-argument is called. ๐ธ
๐จ 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
This style is used by the incremental-complete-word widget. Its value should be a pattern, and all keys matching this pattern will cause the widget to stop incremental completion without the key having any further effect. Like all styles used directly by incremental-complete-word, this style is looked up using the context :incremental.
๐งฉ completer
The incremental-complete-word and insert-and-predict widgets set up their top-level context name before calling completion. This allows one to define different sets of completer functions for normal completion and for these widgets ๐. For example, to use completion, approximation and correction for normal completion, completion and correction for incremental completion and only completion for prediction, one could use:
zstyle ':completion:*' completer \
_complete _correct _approximate
zstyle ':completion:incremental:*' completer \
_complete _correct
zstyle ':completion:predict:*' completer \
_complete
periodt. ๐
cursorโ bestie, this is the<pink>insert-and-predict</pink>widget's little "where do I leave the cursor tho" style, used in the context:predict. It decides where the cursor lands after completion has been tried. The values are:completeโ the cursor just stays put where it was when completion finished, but only if it's after a character equal to the one the user just inserted. If it's after some other character, this value behaves the same askey.keyโ the cursor gets left after the nth occurrence of the character just inserted, where n is how many times that character appeared in the word before completion was attempted. TL;DR: it leaves the cursor after the character you just typed, even if the completion code figured out that no other characters even need inserting at that position.
Any other value for this style just unconditionally leaves the cursor wherever the completion code left it. no thoughts, head empty ๐
listโ with the<hotpink>incremental-complete-wordwidget, this style says whether the matches should be listed on every single key press (that is, if they actually fit on the screen, whichโฆ sometimes they do not ๐ญ). Use the context prefix:completion:incremental`.
The <pink>insert-and-predictwidget also uses this style to decide if the completion should be shown even when there's only <italic>one</italic> possible completion. That happens when the value of this style is the stringalways. In that case the context is :predict(and like, <italic>not</italic>:completion:predict`, okay? noted โจ).
matchโ this one's for<hotpink>smart-insert-last-word, giving it a pattern (using fullEXTENDED_GLOBsyntax, fancy) that matches an "interesting" word. The context is the name of the widget thatsmart-insert-last-wordis bound to (see above ๐). The default behavior ofsmart-insert-last-word` is literally equivalent to:
zstyle :insert-last-word match '*[[:alpha:]/\\]*'
But maybe you want words with spaces in them? valid, iconic, do this:
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:]/\\])*'
That last example above causes redirections like "2>" to be included. ate. ๐ฅ
promptโ the<hotpink>incremental-complete-wordwidget shows the value of this style in the status line during incremental completion. The string value can contain any of these substrings, in the same manner as thePS1` and other prompt parameters:%cโ replaced by the name of the completer function that generated the matches (without the leading underscore).%lโ when theliststyle is set, replaced by...if the list of matches is too long to fit on the screen, and with an empty string otherwise. If theliststyle isfalseor just not set,%lis 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's different from the word on the line.
Like break-keys, this uses the :incremental context.
stop-keysโ used by the<hotpink>incremental-complete-wordwidget. Its value is treated similarly to the one for thebreak-keysstyle (and uses that 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. so it's a little keyboard interrupt moment ๐toggleโ this boolean style is used bypredict-onand its related widgets in the context:predict. If it's set to one of the standardtruevalues, predictive typing gets automatically toggled off in situations where it's unlikely to be useful โ think editing a multi-line buffer, or after moving into the middle of a line and then deleting a character. The default is to leave prediction turned on until an explicit call topredict-off. she's persistent like that ๐verboseโ this boolean style is used bypredict-onand its related widgets in the context:predict. If it's set to one of the standardtruevalues, these widgets display a message below the prompt when the predictive state is toggled. This is most useful in combination with thetogglestyle. The default does not display these messages. (quiet main character energy โจ)widgetโ similar to thecommandstyle, bestie: for widget functions that usezleto call other widgets, this style can sometimes be used to override which widget actually gets called. The context for this style is the name of the calling widget (not the name of the calling function, because one function may be bound to multiple widget names โ sneaky, right?)
zstyle :copy-earlier-word widget smart-insert-last-word
Check the documentation for the calling widget or function to figure out whether the widget style is used. ๐
๐จ EXCEPTION HANDLING ๐จ
Two functions are provided so zsh can give you exception handling in a form that should feel familiar if you've ever touched another language. yes bestie, we have try/catch vibes at home ๐
throwexception โ this function throws the named exception. The name is an arbitrary string and is only used by thethrowandcatchfunctions. An exception is for the most part treated the same as a shell error, i.e. an unhandled exception will cause the shell to abort all processing in a function or script and to return to the top level in an interactive shell. so like, do handle it, fr fr ๐ญcatchexception-pattern โ returns status zero if an exception was thrown and theexception-patternmatches its name. Otherwise it returns status1.exception-patternis a standard shell pattern, respecting the current setting of theEXTENDED_GLOBoption. An aliascatchis also defined to prevent the argument to the function from matching filenames, so patterns may be used unquoted. Note that since exceptions are not fundamentally different from other shell errors, it's possible to catch shell errors by using an empty string as the exception name. The shell variableCAUGHTis set bycatchto the name of the exception caught. And it's possible to rethrow an exception by calling thethrowfunction again once an exception has been caught. ๐ฆ
These functions are designed to be used together with the always construct described in zshmisc(1). This is important because 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. and by might be, we mean it's lowkey iconic:
{
# ... 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
}
In common with exception handling in other languages, the exception may be thrown by code deeply nested inside the try block. However, note that it must be thrown inside the current shell โ not in a subshell forked for a pipeline, parenthesised current-shell construct, or some form of command or process substitution. keep it in the family, bestie ๐ซถ
๐จ The system internally uses the shell variableEXCEPTIONto record the name of the exception between throwing and catching. One drawback of this scheme: if the exception is not handled, the variableEXCEPTIONremains set and may be incorrectly recognised as the name of an exception if a shell error subsequently occurs. Addingunset EXCEPTIONat the start of the outermost layer of any code that uses exception handling will eliminate this problem. little cleanup era, we love to see it ๐ง
๐ 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. fancy file princess treatment ๐
zsh-mime-setup [ -fv ] [ -l [ suffix ... ] ]
zsh-mime-handler [ -l ] command argument ...
These two functions use the files ~/.mime.types and /etc/mime.types, which associate types and extensions, as well as ~/.mailcap and /etc/mailcap files, which associate types and the programs that handle them. These are provided on many systems with the Multimedia Internet Mail Extensions. (iykyk ๐)
To enable the system, the function zsh-mime-setup should be autoloaded and run. This allows files with extensions to be treated as executable; such files be completed by the function completion system. The function zsh-mime-handler should not need to be called by the user. she's backend-only, that's her whole brand โจ
The system works by setting up suffix aliases with alias -s. Suffix aliases already installed by the user will not be overwritten โ respect the user's setup, periodt ๐
For suffixes defined in lower case, upper case variants will also automatically be handled (e.g. PDF is automatically handled if handling for the suffix pdf is defined), but not vice versa. one-way street, bestie ๐ธ
Repeated calls to zsh-mime-setup do not override the existing mapping between suffixes and executable files unless you pass the option -f. But heads up ๐ซถ โ that still doesn't override existing suffix aliases assigned to handlers other than zsh-mime-handler. Okurrr? ๐
Calling zsh-mime-setup with the option -l lists the existing mappings without altering them. Suffixes to list (which may contain pattern characters that should be quoted from immediate interpretation on the command line) may be given as additional arguments, otherwise all suffixes are listed. window shopping for your file handlers โจ
Calling zsh-mime-setup with the option -v causes verbose output to be shown during the setup operation. Very "tell me everything" of it ๐
The system respects the mailcap flags needsterminal and copiousoutput; see mailcap(4) or mailcap(5) (the man page's name varies across platforms). iykyk ๐ธ
The functions use the following styles, which are defined with the zstyle builtin command (see zshmodules(1)). They should be defined before zsh-mime-setup is run. The contexts used all start with :mime:, with additional components in some cases. It is recommended that a trailing * (suitably quoted) be appended to style patterns in case the system is extended in future. Some examples are given below. future-proofing is self-care fr ๐
For files that have multiple suffixes, e.g. .pdf.gz, where the context includes the suffix it will be looked up starting with the longest possible suffix until a match for the style is found. For example, if .pdf.gz produces a match for the handler, that will be used; otherwise the handler for .gz will be used. Note that, owing to the way suffix aliases work, it is always required that there be a handler for the shortest possible suffix, so in this example .pdf.gz can only be handled if .gz is also handled (though not necessarily in the same way). the way that's a whole dependency chain ๐ญ Alternatively, if no handling for .gz on its own is needed, simply adding the command
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. iconic little workaround ๐ฆ
current-shellโ If this boolean style is true, the mailcap handler for the context in question is run using theevalbuiltin instead of by starting a newshprocess. This is more efficient, but may not work in the occasional cases where the mailcap handler uses strict POSIX syntax. faster but kinda risky, ngldisownโ If this boolean style is true, mailcap handlers started in the background will be disowned, i.e. not subject to job control within the parent shell. Such handlers nearly always produce their own windows, so the only likely harmful side effect of setting the style is that it becomes harder to kill jobs from within the shell. lowkey a tradeoff ๐execute-as-isโ This style gives a list of patterns to be matched against files passed for execution with a handler program. If the file matches the pattern, the entire command line is executed in its current form, with no handler. This is useful for files which might have suffixes but nonetheless be executable in their own right. If the style is not set, the pattern*(*) *(/)is used; hence executable files are executed directly and not passed to a handler, and the optionAUTO_CDmay be used to change to directories that happen to have MIME suffixes. the defaults really said respect the executable ๐execute-neverโ This style is useful in combination withexecute-as-is. It is set to an array of patterns corresponding to full paths to files that should never be treated as executable, even if the file passed to the MIME handler matchesexecute-as-is. This is useful for file systems that don't handle execute permission or that contain executables from another operating system. For example, if/mnt/windowsis a Windows mount, then
zstyle ':mime:*' execute-never '/mnt/windows/*'
will ensure that any files found in that area will be executed as MIME types even if they are executable. As this example shows, the complete file name is matched against the pattern, regardless of how the file was passed to the handler. The file is resolved to a full path using the :P modifier described in the subsection Modifiers in zshexpn(1); this means that symbolic links are resolved where possible, so that links into other file systems behave in the correct fashion. symlink-aware and thriving โจ
file-pathโ Used if the stylefind-file-in-pathis true for the same context. Set to an array of directories that are used for searching for the file to be handled; the default is the command path given by the special parameterpath. The shell optionPATH_DIRSis respected; if that is set, the appropriate path will be searched even if the name of the file to be handled as it appears on the command line contains a/. The full context is:mime:.suffix:, as described for the stylehandler. remember the trailing colon bestie ๐find-file-in-pathโ If set, allows files whose names do not contain absolute paths to be searched for in the command path or the path specified by thefile-pathstyle. If the file is not found in the path, it is looked for locally (whether or not the current directory is in the path); if it is not found locally, the handler will abort unless thehandle-nonexistentstyle is set. Files found in the path are tested as described for the styleexecute-as-is. The full context is:mime:.suffix:, as described for the stylehandler. look in path, then look at home, then give up ๐ซถflagsโ Defines flags to go with a handler; the context is as for thehandlerstyle, and the format is as for the flags in mailcap. ๐handle-nonexistentโ By default, arguments that don't correspond to files are not passed to the MIME handler in order to prevent it from intercepting commands found in the path that happen to have suffixes. This style may be set to an array of extended glob patterns for arguments that will be passed to the handler even if they don't exist. If it is not explicitly set it defaults to[[:alpha:]]#:/*which allows URLs to be passed to the MIME handler even though they don't exist in that format in the file system. The full context is:mime:.suffix:, as described for the stylehandler. so your URLs get to vibeslide right through ๐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.and trailing colon to distinguish this use of the context. This overrides any handler specified by the mailcap files. If the handler requires a terminal, theflagsstyle should be set to include the wordneedsterminal, or if the output is to be displayed through a pager (but not if the handler is itself a pager), it should includecopiousoutput. details matter, periodt ๐ฅmailcapโ A list of files in the format of~/.mailcapand/etc/mailcapto 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. the+is doing a lil magic trick โจmailcap-prioritiesโ This style is used to resolve multiple mailcap entries for the same MIME type. It consists of an array of the following elements, in descending order of priority; later entries will be used if earlier entries are unable to resolve the entries being compared. If none of the tests resolve the entries, the first entry encountered is retained.filesโ The order of files (entries in themailcapstyle) 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 from0to9with the default value being5.flagsโ The test given by themailcap-prio-flagsoption 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. no suffix silliness here, she's global ๐
mailcap-prio-flagsโ This style is used when the keywordflagsis encountered in the list of tests specified by themailcap-prioritiesstyle. It should be set to a list of patterns, each of which is tested against the flags specified in the mailcap entry (in other words, the sets of assignments found with some entries in the mailcap file). Earlier patterns in the list are preferred to later ones, and matched patterns are preferred to unmatched ones. first match wins, bestie ๐ฆmime-typesโ A list of files in the format of~/.mime.typesand/etc/mime.typesto 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. same deal, different file ๐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). main character handlers stay in the foreground, no cap ๐pagerโ if you set this, it gets used instead of$PAGERormoreto handle suffixes that have thecopiousoutputflag set ๐ the context works exactly likehandler, aka:mime:.suffix:for handling a file with that suffix.
Examples, bestie, straight up:
zstyle ':mime:*' mailcap ~/.mailcap /usr/local/etc/mailcap
zstyle ':mime:.txt:' handler less %s
zstyle ':mime:.txt:' flags needsterminal
So when zsh-mime-setup runs next, it's gonna go looking for mailcap entries in those two files you just named ๐ files with a .txt suffix get handled by running less file.txt, and the needsterminal flag is set to say "hey, this program has to run attached to a terminal, no cap".
Now โ because dispatching a command is a whole multi-step situation, here's the checklist if executing a file by extension .ext is not giving what you expected ๐ญ
- The command
alias -s extshould showps=zsh-mime-handler. If it shows something else, another suffix alias was already installed and didn't get overwritten. If it shows nothing, no handler was installed โ most likely because no handler was found in the.mime.typesand mailcap combo for.extfiles. In that case, add the appropriate handling to~/.mime.typesand mailcap. - If the extension is handled by
zsh-mime-handlerbut the file doesn't open correctly, then either the handler defined for the type is wrong, or the flags associated with it are inappropriate. Runningzsh-mime-setup -lwill show the handler and, if there are any, the flags. A%sin the handler gets replaced by the file (suitably quoted if necessary). Check that the handler program listed actually lists and can be run the way it's shown ๐. Also check that theneedsterminalorcopiousoutputflags are set if the handler needs to run under a terminal; that second flag is used when the output should go to a pager. An example of a suitable mailcap entry for such a program is:
text/html; /usr/bin/lynx '%s'; needsterminal
Running zsh-mime-handler -l command line prints the command line that would be executed, simplified to remove the effect of any flags, and quoted so the output can be run as a complete zsh command line โจ the completion system uses this to figure out how to complete after a file handled by zsh-mime-setup.
๐ฆ pick-web-browser
This function is separate from the two MIME functions above and can be assigned directly to a suffix, like so:
autoload -U pick-web-browser
alias -s html=pick-web-browser
It's basically an intelligent front end for dispatching a web browser ๐ it can be run as either a function or a shell script. Status 255 is returned if no browser could be started ๐
Various styles are available to customize which browsers get chosen:
โจ browser-style
The value of this style is an array giving preferences in decreasing order for the type of browser to use. The values of elements may be:
runningโ use a GUI browser that's already running when an X Window display is available. The browsers listed in thex-browsersstyle get tried in order until one is found; if one is, the file gets displayed in that browser, so you might need to check whether it actually appeared ๐ if no running browser is found, one is not started. Browsers other than Firefox, Opera and Konqueror are assumed to understand the Mozilla syntax for opening a URL remotely.xโ start a new GUI browser when an X Window display is available. Search for the availability of one of the browsers listed in thex-browsersstyle and start the first one 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 thetty-browsersstyle and start the first one found.
If the style isn't 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 is made of the command name under which to start the browser. They get looked up in the context :mime: (which may be extended in future, so appending * is recommended, iykyk). For example:
zstyle ':mime:*' x-browsers opera konqueror firefox
says pick-web-browser should first look for a running instance of Opera, Konqueror or Firefox, in that order, and if it fails to find any, should attempt to start Opera ๐ฅ the default is firefox mozilla netscape opera konqueror.
โจ tty-browsers
An array similar to x-browsers, except it gives the browsers to use when no X Window display is available. The default is elinks links lynx ๐ธ
โจ command
If set, this style picks the command used to open a page for a browser. The context is :mime:browser:new:$browser: to start a new browser, or :mime:browser:running:$browser: to open a URL in a browser already running on the current X display, where $browser is the value matched in the x-browsers or tty-browsers style. The escape sequence %b in the style's value gets replaced by the browser, while %u gets replaced by the URL ๐ซ if the style isn't set, the default for all new instances is equivalent to %b %u, and the defaults for using running browsers are equivalent to the values kfmclient openURL %u for Konqueror, firefox -new-tab %u for Firefox, opera -newpage %u for Opera, and %b -remote "openUrl(%u)" for all others.
๐งฎ MATHEMATICAL FUNCTIONS
โจ zcalc
zcalc [ -erf ] [ expression ... ]
A reasonably powerful calculator based on zsh's arithmetic evaluation facility ๐ the syntax is similar to formulae in most programming languages; peep the section Arithmetic Evaluation in zshmisc(1) for the details.
Non-programmers, listen up bestie ๐ข as in many other programming languages, expressions involving only integers (whether constants without a ., variables containing such constants as strings, or variables declared to be integers) are by default evaluated using integer arithmetic, which is not how an ordinary desk calculator operates ๐ญ to force floating point operation, pass the option -f; more notes below.
If the file ~/.zcalcrc exists it will be sourced inside the function once it's set up and about to process the command line โจ you can use this, for example, to set shell options; emulate -L zsh and setopt extendedglob are in effect at this point. Any failure to source the file if it exists is treated as fatal ๐ and like with other initialisation files, the directory $ZDOTDIR is used instead of $HOME if it's set.
The mathematical library zsh/mathfunc will be loaded if it's available; see the section The zsh/mathfunc Module in zshmodules(1). The mathematical functions correspond to the raw system libraries, so trigonometric functions are evaluated using radians, and so on ๐
Each line typed is evaluated as an expression. The prompt shows a number, which corresponds to a positional parameter where that calculation's result is stored ๐ for example, the result of the calculation on the line preceded by 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 gets saved in the file ~/.zcalc_history ๐พ to exit, enter a blank line or type :q on its own (q is allowed for historical compatibility).
A line ending with a single backslash is treated the same way as it is in command line editing: the backslash is removed, the function prompts for more input (the prompt is preceded by ... to indicate this), and the lines get combined into one to get the final result ๐ซถ in addition, if the input so far contains more open than close parentheses, zcalc will prompt for more input.
If arguments are given to zcalc on start up, they're used to prime the first few positional parameters. A visual indication of this is given when the calculator starts ๐
The constants PI (3.14159...) and E (2.71828...) are provided โจ parameter assignment is possible, but note that all parameters will be put into the global namespace unless the :local special command is used. The function creates local variables whose names start with _, so users should avoid doing that ๐ the variables ans (the last answer) and stack (the stack in RPN mode) may be referred to directly; stack is an array but elements of it are numeric. Various other special variables are used locally with their standard meaning, for example compcontext, match, mbegin, mend, psvar.
The output base can be initialised by passing the option -#base, for example zcalc -#16 (the # may have to be quoted, depending on the globbing options set) ๐
If the option -e is set, the function runs non-interactively: the arguments are treated as expressions to be evaluated as if entered interactively line by line.
If the option -f is set, all numbers are treated as floating point, hence for example the expression 3/4 evaluates to 0.75 rather than 0 ๐ options must appear in separate words.
Stack
Evaluated values live in a stack, bestie โ it's literally just an array called stack with the freshest value sitting pretty in ${stack[1]}. โจ
Operators and functions
If what you typed matches an operator (+, -, *, /, **, ^, | or &) or one of the functions the zsh/mathfunc library brings to the party, then the bottom element (or elements ๐) of the stack get popped off to serve as the argument(s). The higher elements of stack (aka the least recent ones) get used as the earlier arguments. The result then gets pushed right back into ${stack[1]}. Iconic behavior only.
Expressions
Anything else gets evaluated totally normally, printed, and added to the stack as numeric values. Heads up though: the syntax within expressions on a single line is regular shell arithmetic โ not RPN. Don't get it twisted ๐ซถ
Stack listing
If an integer follows -r with no space in between, then on every evaluation that many elements of the stack (where available, no drama) get printed instead of just the most recent result. So for example zcalc -r4 shows $stack[4] to $stack[1] every time results print. Slay.
Duplication: =
The pseudo-operator = makes the most recent element of the stack get duplicated onto the stack. Copy-paste energy ๐
pop
The pseudo-function pop pops the most recent element of the stack. A lone > does the exact same thing, no cap.
>ident
The expression > followed (with no space!) by a shell identifier pops the most recent element of the stack and assigns it to the variable with that name. That variable is local to the zcalc function, fyi.
<ident
The expression < followed (again, no space) by a shell identifier pushes the value of that variable onto the stack. ident can be an integer, in which case the previous result with that number (as shown before the > in the standard zcalc prompt) gets put on the stack. Cute, right?
Exchange: xy
The pseudo-function xy swaps out the most recent two elements of the stack. <> does the same vibe. ๐
The prompt is configurable via the parameter ZCALCPROMPT, and it goes through standard prompt expansion. The index of the current entry is stored locally in the first element of the array psvar, which you can refer to in ZCALCPROMPT as %1v. The default prompt is %1v> .
The variable ZCALC_ACTIVE is set inside the function and can be tested by nested functions; it holds the value rpn if RPN mode is active, otherwise 1.
A few special commands are available too โ these get introduced by a colon :. For backward compatibility, the colon can be omitted for certain commands. Completion is available if compinit has been run. ๐
The output precision can be specified within zcalc by special commands that'll feel super familiar if you've ever touched a calculator.
:normโ the default output format. It corresponds to theprintf %gspecification. Typically this shows six decimal digits.:sci digitsโ scientific notation, corresponding to theprintf %goutput 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 theprintf %foutput format with the precision given by digits.:eng digitsโ exponential notation, corresponding to theprintf %Eoutput format with the precision given by digits.:rawโ raw output: this is the default form of the output from a math evaluation. It may show more precision than the number actually possesses. ๐
Other special commands
:!line...โ execute line... as a normal shell command line. Note that it runs in the context of the function, i.e. with local variables. Space is optional after:!.:local arg ...โ declare variables local to the function. Other variables may be used too, but they'll be taken from or put into the global scope.:function name [ body ]โ define a mathematical function, or (with no body) delete it.:functionmay be abbreviated to:funcor simply:f. The name may contain the same characters as a shell function name. The function is defined usingzmathfuncdef, see below.
Note that zcalc takes care of all quoting for you. Hence, for example:
:f cube $1 * $1 * $1
defines a function that cubes the sole argument. Functions defined this way โ or indeed any functions defined directly or indirectly using functions -M โ are available to execute by typing only the name on the line in RPN mode. That pops the appropriate number of arguments off the stack to pass to the function, i.e. 1 in the case of the example cube function. If there are optional arguments, only the mandatory arguments get supplied this way.
[#base]โ okay so this isn't actually a special command, it's part of normal arithmetic syntax. But when this form appears on a line by itself, the default output radix gets 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 get back to normal operation. โ ๏ธ$varโ print out the value of var literally; does not affect the calculation. To use the value of var, omit the leading$.
See the comments in the function for a few extra tips. ๐
min(arg, ...)
max(arg, ...)
sum(arg, ...)
zmathfunc
The function zmathfunc defines the three mathematical functions min, max, and sum. The functions min and max take one or more arguments. The function sum takes zero or more arguments. Arguments can be of different types (ints and floats). ๐
Not to be confused with the zsh/mathfunc module, described in the section The zsh/mathfunc Module in zshmodules(1).
zmathfuncdef [ mathfunc [ body ] ]
A convenient front end to functions -M. ๐ซถ
With two arguments, define a mathematical function named mathfunc which can be used in any form of arithmetic evaluation. body is a mathematical expression to implement the function. It may contain references to position parameters $1, $2, ... to refer to mandatory parameters and ${1:-defvalue} ... to refer to optional parameters. Note that the forms must be strictly adhered to for the function to calculate the correct number of arguments. The implementation is held in a shell function named zsh_math_func_mathfunc; usually the user won't need to refer to the shell function directly. Any existing function of the same name gets silently replaced. ๐
With one argument, remove the mathematical function mathfunc as well as the shell function implementation.
With no arguments, list all mathfunc functions in a form suitable for restoring the definition. The functions have not necessarily been defined by zmathfuncdef.
๐ USER CONFIGURATION FUNCTIONS ๐
The zsh/newuser module comes with a function to help configure shell options for new users. If the module is installed, this function can also be run by hand. It's available even if the module's default behaviour โ namely running the function for a new user logging in without startup files โ is inhibited. โจ
zsh-newuser-install [ -f ]
The function presents the user with various options for customizing their initialization scripts. Currently only ~/.zshrc is handled. $ZDOTDIR/.zshrc is used instead if the parameter ZDOTDIR is set; this provides a way for the user to configure a file without altering an existing .zshrc. ๐
By default the function exits immediately if it finds any of the files .zshenv, .zprofile, .zshrc, or .zlogin in the appropriate directory. The option -f is required in order to force the function to continue. Note this may happen even if .zshrc itself does not exist.
As currently configured, the function will exit immediately if the user has root privileges; this behaviour cannot be overridden. ๐ฅ
Once activated, the function's behaviour is supposed to be self-explanatory. Menus are present allowing the user to alter the value of options and parameters. Suggestions for improvements are always welcome. ๐ฅบ
When the script exits, the user is given the opportunity to save the new file or not; changes are not irreversible until this point. However, the script is careful to restrict changes to the file only to a group marked by the lines # Lines configured by zsh-newuser-install and # End of lines configured by zsh-newuser-install. In addition, the old version of .zshrc is saved to a file with the suffix .zni appended.
If the function edits an existing .zshrc, it is up to the user to ensure that the changes made will actually take effect. For example, if control usually returns early from the existing .zshrc the lines won't be executed; or a later initialization file may override options or parameters, and so on. The function itself does not attempt to detect any such conflicts. ๐
๐ธ 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 โ the vibe palette
Okay so colors initializes a whole bunch of associative arrays that map color names to (and from) the ANSI standard eight-color terminal codes. These are literally the ones used by the prompt theme system (iykyk โ see above ๐). You will seldom need to run colors more than once, bestie.
The eight base colors are: black, red, green, yellow, blue, magenta, cyan, and white. Each of these has codes for foreground and background. On top of that, there are seven intensity attributes: bold, faint, standout, underline, blink, reverse, and conceal. And finally, there are seven codes used to negate attributes: none (reset all attributes to the defaults), normal (neither bold nor faint), no-standout, no-underline, no-blink, no-reverse, and no-conceal.
Heads up bestie ๐ โ some terminals do not support all combinations of colors and intensities. Not all hardware ate. ๐
The associative arrays are:
colorcolourโ these 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 withfg-, such asfg-red. Names prefixed withbg-, such asbg-blue, refer to the background codes. The reverse mapping from code to color yields the base name for foreground codes and thebg-form for backgrounds.
Ngl, even though it's a misnomer to call them colors, these arrays also map the other fourteen attributes from names to codes and codes to names. It's giving "we contain multitudes" โจ.
fgfg_boldfg_no_boldโ these map the eight basic color names to ANSI terminal escape sequences that set the corresponding foreground text properties. Thefgsequences change the color without changing the eight intensity attributes.bgbg_boldbg_no_boldโ these map the eight basic color names to ANSI terminal escape sequences that set the corresponding background properties. Thebgsequences change the color without changing the eight intensity attributes. Same energy, just the background edition ๐ซถ.
Oh and also โ the scalar parameters reset_color and bold_color get set to the ANSI terminal escapes that turn off all attributes and turn on bold intensity, respectively. Iconic behavior, truly. ๐
๐งธ fned [ -x num ] name
Literally the same as zed -f. This function does not appear in the zsh distribution, but you can create it by linking zed to the name fned in some directory in your fpath. DIY queen behavior fr fr ๐
.
๐ histed [ [ name ] size ]
Same as zed -h. Also not in the zsh distribution โ same deal, make it yourself by linking zed to the name histed in some directory in your fpath. Slay, build your own tools ๐.
โ๏ธ is-at-least needed [ present ]
Okay this one is lowkey a lifesaver. It performs a greater-than-or-equal-to comparison of two strings that have the format of a zsh version number โ that is, a string of numbers and text with segments separated by dots or dashes. If the present string is not provided, $ZSH_VERSION is used. No cap.
Segments are paired left-to-right in the two strings, with leading non-number parts ignored. If one string has fewer segments than the other, the missing segments are considered zero. Periodt.
This is useful in startup files to set options and other state that are not available in all versions of zsh:
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."
Look at that graceful handling. We love a compatibility queen ๐ธ.
๐ nslookup [ arg ... ]
This is a wrapper function for the nslookup command, and it 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
Use regular expressions to perform a global search and replace operation on a variable. The tea โ: POSIX extended regular expressions (ERE) are used, unless the option RE_MATCH_PCRE has been set, in which case Perl-compatible regular expressions are used (this requires the shell to be linked against the pcre library).
varis the name of the variable containing the string to be matched. The variable will be modified directly by the function. The variablesMATCH,MBEGIN,MEND,match,mbegin,mendshould be avoided as these are used by the regular expression code. Don't touch them bestie, they're busy ๐.regexpis the regular expression to match against the string.replaceis the replacement text. This can contain parameter, command and arithmetic expressions which will be replaced: in particular, a reference to$MATCHwill be replaced by the text matched by the pattern.
The return status is 0 if at least one match was performed, else 1.
Note that if using POSIX EREs, the ^ or word boundary operators (where available) may not work properly. Just so you know ๐ญ.
๐ 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 for setup instructions.
In the discussion which follows, if cmd is a file system path, it is first reduced to its rightmost component (the file name). Clean and simple โจ.
Help is first sought by looking for a file named cmd in the directory named by the HELPDIR parameter. If no file is found, an assistant function, alias, or command named run-help-cmd is sought. If found, the assistant is executed with the rest of the current command line (everything after the command name cmd) as its arguments. When neither file nor assistant is found, the external command man cmd is run.
An example assistant for the "ssh" command โ because we stan a custom helper:
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-btrfsrun-help-gitrun-help-iprun-help-opensslrun-help-p4run-help-sudorun-help-svkrun-help-svn
These are assistant functions for the btrfs, git, ip, openssl, p4, sudo, svk, and svn commands. The whole squad is here ๐ซถ.
๐ฎ tetris
Okay so 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. And honestly? It ate. ๐ ๐ฅ
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. Main character energy ๐ญ.
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. (F in the chat for your losses ๐.)
๐น๏ธ tetriscurses
This is a port of the above to zcurses. The input handling is improved a bit so that moving a block sideways doesn't automatically advance a timestep, and the graphics use unicode block graphics. Upgraded and glowing โจ.
This version does not save the game state between invocations, and is not invoked as a widget, but rather as:
autoload -U tetriscurses
tetriscurses
No save files, no widget shenanigans โ just vibes ๐.
๐ฆ zargs [ option ... -- ] [ input ... ] [ -- command [ arg ... ] ]
This function has a similar purpose to GNU xargs. Instead of reading lines of arguments from standard input, it takes them from the command line. This is useful because zsh, especially with recursive glob operators, often can construct a command line for a shell function that is longer than can be accepted by an external command. Genuinely so helpful ngl ๐ซถ.
- The
optionlist represents options of thezargscommand itself, which are the same as those ofxargs. - The
inputlist is the collection of strings (often file names) that become the arguments of the command, analogous to the standard input ofxargs. - Finally, the
arglist consists of those arguments (usually options) that are passed to the command each time it runs. Thearglist precedes the elements from theinputlist in each run.
If no command is provided, then no arg list may be provided, and in that event the default command is print with arguments -r --. Defaults coming throughhh ๐
For example, to get a long ls listing of all non-hidden plain files in the current directory or its subdirectories:
autoload -U zargs
zargs -- **/*(.) -- ls -ld --
The first and third occurrences of -- are used to mark the end of options for zargs and ls respectively to guard against filenames starting with -, while the second is used to separate the list of files from the command to run (ls -ld --). It's giving careful queen behavior.
The first -- would also be needed if there was a chance the list might be empty, as in:
zargs -r -- ./*.back(#qN) -- rm -f
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 -ld --
This is a good choice in that example because no plain file can be named .., but the best end-marker depends on the circumstances. Choose wisely bestie ๐งโจ.
Okay so real talk about the zargs flag tea โ โ the options -i, -I, -l, -L, and -n are slightly different from how they act in xargs, and that's on purpose, bestie. There are no input lines for zargs to count, so -l and -L count through the input list instead, and -n counts the number of arguments passed to each execution of command, including any arg list. Also, the moment you use -i or -I, each input gets processed separately, as if by -L 1. No cap.
For the deets on all the other zargs options, go check the xargs(1) man page (but bestie, pls note the difference in function between zargs and xargs, they are not the same girl) โ or just run zargs with the --help option and let it spill. ๐
๐ zed โจ
zed [ -f [ -x num ] ] name
zed [ -h [ name ] size ]
zed -b
This function uses the ZLE editor to edit a file or function. Iconic behaviour, honestly.
Only one name argument is allowed, periodt. If the -f option is given, name is taken to be that of a function; and if that function is marked for autoloading, zed searches for it in the fpath and loads it. Heads up though ๐ โ functions edited this way are installed into the current shell, but not written back to the autoload file. In this case the -x option specifies that leading tabs indenting the function according to syntax should be converted into the given number of spaces; -x 2 is consistent with the layout of functions distributed with the shell. Slay.
Without -f, name is the path name of the file to edit, which doesn't even need to exist โ it gets created on write, if necessary. Very "we'll figure it out" energy. With -h, the file is presumed to contain history events.
When no file name is provided for -h, the current shell history is edited in place. The history is renumbered when zed exits successfully. โจ
When editing history, multi-line events must have a trailing backslash on every line before the last. Yes, every single one. Don't @ me.
While editing, the function sets the main keymap to zed and the vi command keymap to zed-vicmd. These will be copied from the existing main and vicmd keymaps if they don't exist the first time zed is run. They can be used to provide special key bindings used only in zed.
If it creates the keymap, zed rebinds the return key to insert a line break and ^X^W to accept the edit in the zed keymap, and binds ZZ to accept the edit in the zed-vicmd keymap. Muscle memory unlocked ๐ฅ
The bindings alone can be installed by running zed -b. This is suitable for putting into a startup file โ like, put it in your .zshrc and vibe. But note that, if rerun, this will overwrite the existing zed and zed-vicmd keymaps. โ ๏ธ Rerun at your own risk, bestie.
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 \ex zed-set-file-name or can be bound to a key in either of the zed or zed-vicmd keymaps after zed -b has been run. When the widget is called, it prompts for a new name for the file being edited. When zed exits the file will be written under that name and the original file will be left alone. The widget has no effect when invoked from zed -f. The completion context is changed to :completion:zed-set-file-name:. When editing the current history with zed -h, the history is first updated and then the file is written, but the global setting of HISTFILE is not altered. ๐ซถ
While zed-set-file-name is running, zed uses the keymap zed-normal-keymap, which is linked from the main keymap in effect at the time zed initialised its bindings. (This is to make the return key operate normally.) The result is that if the main keymap has been changed, the widget won't notice. Fr fr, this is not a concern for most users. ๐
๐ zcp & zln
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. DIY queen behaviour ๐
โญ zkbd
See Keyboard Definition above. That's it, that's the whole entry. Go look up there ๐
๐ zmv
zmv [ -finqQsvwW ] [ -C | -L | -M | -{p|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. Like mad libs but for your filenames, and honestly? Obsessed.
For example,
zmv '(*).lis' '$1.txt'
renames foo.lis to foo.txt, my.old.stuff.lis to my.old.stuff.txt, and so on. Chef's kiss ๐งโ๐ณ
The pattern is always treated as an EXTENDED_GLOB pattern. Any file whose name is not changed by the substitution is simply ignored. Any error (a substitution resulted in an empty string, two substitutions gave the same result, the destination was an existing regular file and -f was not given) causes the entire function to abort without doing anything. It's giving all-or-nothing, and tbh that's a valid boundary ๐
In addition to pattern replacement, the variable $f can be referred to in the second (replacement) argument. This makes it possible to use variable substitution to alter the argument; see examples below.
โจ Options โจ
-fโ Force overwriting of destination files. Not currently passed down to themv/cp/lncommand due to vagaries of implementations (but you can use-o-fto do that).-iโ Interactive: show each line to be executed and ask the user whether to execute it.Yorywill execute it, anything else will skip it. Note that you just need to type one character. One! That's it! โจ-nโ No execution: print what would happen, but don't do it. Manifesting without the commitment, honestly.-qโ Turn bare glob qualifiers off: now assumed by default, so this has no effect. Retro icon ๐-Qโ Force bare glob qualifiers on. Don't turn this on unless you are actually using glob qualifiers in a pattern. Like, actually actually.-sโ Symbolic, passed down toln; 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โ Forcecp,lnormv, respectively, regardless of the name of the function.-pprogram โ Call program instead ofcp,lnormv. Whatever it does, it should at least understand the formprogram -- oldname newnamewhere oldname and newname are filenames generated byzmv. program will be split into words, so might be e.g. the name of an archive tool plus a copy or rename subcommand.-Pprogram โ As-pprogram, except that program does not accept a following--to indicate the end of options. In this case filenames must already be in a sane form for the program in question.-ooptstring โ The optstring is split into words and passed down verbatim to thecp,lnormvcommand called to perform the work. It should probably begin with a-.
๐ธ Further examples ๐ธ
zmv -v '(* *)' '${1// /_}'
For any file in the current directory with at least one space in the name, replace every space by an underscore and display the commands executed.
zmv -v '* *' '${f// /_}'
This does exactly the same by referring to the file name stored in $f. Twin flames, these two ๐
For more complete examples and other implementation details, see the zmv source file, usually located in one of the directories named in your fpath, or in Functions/Misc/zmv in the zsh distribution.
๐ฆ zrecompile
See Recompiling Functions above. Short entry, main character energy anyway โญ
๐ zstyle+
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. So much less typing, I'm obsessed ๐ญ
๐ 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. Your shell, your rules ๐ซถ
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)). Cute prompt, cute right prompt, cute everything ๐ธ
And that's a wrap on ZSHCONTRIB(1), bestie ๐ This page is from zsh 5.9.2, dated July 12, 2026, and it's the ZSHCONTRIB(1) manual page โ go forth and configure your heart out, you've earned it ๐โจ๐
๐ฆ where this page comes from
- arch rolling: zsh 5.9.2-1 ยท custom
- nixpkgs unstable: zsh 5.9.2
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms