You are on page 1of 14

 Page 1 Zsh Reference Card Version 4.

Contents general in part 1, concentrating on bash and zsh in parts 2 and 3.  programs, links to external resources, and a glossary.


1 General information, references The contents of the book are as follows; where noted with page 
2 Grammar (shell syntax) references to this card they expand on the brief hints here. Zsh manual pages
3 Patterns: globbing and qualifiers To access documentation from within the shell, use the man
4 Options Part 1 (Introducing the Shell) contains the following chapters: command with one of the following arguments:
5 Options cont.; option aliases, single letter options 1 Introduction to Shells zsh Introduction, startup and shutdown
6 Expansion: basic forms, history, prompts 2 Using Shell Features Together zshmisc Syntax, redirection, functions, jobs, tests
7 Expansion: variables: forms and flags 3 More Shell Features zshexpn Expansion and substitution
8 Shell variables: set by shell, used by shell (c.f. page 2) zshparam Parameters (variables)
9 Test operators; numeric expressions zshoptions Options to the shell
10 Completion: contexts, completers, tags Part 2 (Using bash and zsh) contains the following chapters: zshbuiltins Shell builtin commands
11 Completion cont.: tags cont, styles 4 Entering and Editing the Command Line zshzle The line editor, excluding completion
12 Completion cont.: styles cont, utility functions (c.f. pages 6 and 13) zshcompwid The low­level completion facitilities
zshcompsys The new completion system (more readable)
13 Zsh line editor (zle) 5 Starting the Shell
zshcompctl The old completion system (deprecated)
(c.f. pages 4 and 5)
zshmodules Modules loadable with zmodload
Notes 6 More About Shell History
zshtcpsys Functions for using raw TCP via builtins
The descriptions here are very brief.  You will not be able to learn  (c.f. pages 6 and 8)
zshzftpsys Functions for using FTP via builtins
shell syntax from them; see the various references below.  In  7 Prompts
zshcontrib Contributed functions for zle etc.
particular the completion system is extremely rich and the  (c.f. page 6) zshall Everything in one large manual page
descriptions of its utility functions are the barest memory joggers. 8 Files and Directories
(c.f. page 9) Mailing lists
The start and end of each section is aligned with page boundaries,  9 Pattern Matching zsh-users@zsh.org: users' mailing list for general questions 
so you can print out only the parts you want to refer to. (c.f. page 3) and tips; to join, mail
10 Completion zsh-users-subscribe@zsh.org.
References (c.f pages 10 through 12)
Zsh manual:  Supplied with the shell: should be installed in Unix  11 Jobs and Processes zsh-workers@zsh.org: mailing list for bug reports, patches 
manual page and info formats.  Texinfo generates PS or PDF;  (c.f. page 6) and developers' discussions; to join, mail
available as separate doc bundle from same place as the shell. zsh-workers-subscribe@zsh.org.  New developers with 
Part3 (Extending the Shell) contains the following chapters: some Unix/Linux experience are welcome.
http://zsh.sourceforge.net/:  Site with much  12 Variables
information about zsh, including HTML manual and a more user­ (c.f. pages 7 and 8)
friendly guide to the shell, as well as the FAQ. 13 Scripting and Functions
(c.f. page 2)
Zsh wiki: http://www.zshwiki.org/: Extensible zsh web  14 Writing Editor Commands
pages written by users. (c.f page 13)
15 Writing Completion Functions
From Bash to Z Shell: Conquering the Command Line, by  (c.f. pages 10 through 12)
Oliver Kiddle, Jerry Peek and Peter Stephenson, Apress, ISBN 1 
59059 376 6.  Introduction to interactive use of Unix shells in  The three appendices contain short descriptions of standard Unix 
 Page 2 Zsh Reference Card Version 4.2 

Grammar }
List is any sequence of sublists (including just one)  if listi1; then[;] listt1; Non­portable alternative.
separated by ; or newline. ; and newline are always  [ elif listi2; then listt2; ]
interchangeable except in ;;. … select name [ in word …];
[ else listt3; ] do list;
Sublist is any sequence of pipelines (including just one)  fi done
If listi1 is true, execute listt1; else if listi2 is true  Print menu of words, read a number, set name to selected word, 
connected by && or ||. 
execute listt2; else execute listt3. execute list until end of input. Portable but rare.
Pipeline is any sequence of simple commands connected by |.
for name [ in word … ] (list[;])
do list; Execute list in a subshell (a new process where nothing that 
Command is either a simple command (a command word) done
followed optionally by word … or one of the special commands  Execute list with variable name set to each of word … in turn happens affects the current shell).
below. If in … is omitted the positional parameters are used. {list[;]}
Execute list (no new process: simply separates list from what’s 
Word is any text that produces a single word when expanded;  for name in word …; { list } around and can take redirections).
word … is any number of these separated by whitespace. foreach name ( word … ) [;]
list; function nameword {[;] list[;] }
Name is a shell identifier: an alphabetic character or _ followed  end
nameword () {[;] list[;] }
by any sequence of alphanumeric characters or _.  Non­portable alternative forms. Define function named nameword; executes list when run; 
running nameword word1 … makes word1 … available as $1
[ … ] indicates optional; dots on their own line mean any  while listw; do listd; done
etc. in function body.  list must end with [;] or newline for 
number of repetitions of the line just above. While listw is true execute listd.
portability. nameword can be repeated to define multiple 
until listu; do listd; done functions (rare, non­portable).
 Bold text is to be typed literally.
Non­portable: while listu is not true execute listd.
time [ pipeline ]
Status  “true” or “false” is determined by: for commands, the  Report time for pipeline if given else totals for current shell.
repeat numexp; do list; done
return status; for pipelines the last command; for sublists the last 
repeat numexp sublist
pipeline; for lists the last sublist that was executed. [[ condition ]]
Non­portable:  repeat  list or sublist numexp times.
Evaluate condition (see below), gives status true or false.
sublist1 && sublist2 [ && sublist3 … ]
case word in
Execute sublists until one is false. [(] pattern1[|pattern2...]) [;] list ;;

sublist1 || sublist2 [ || sublist2 … ] esac
Execute sublists until one is true.  Note strings of  Try matching word against every pattern in turn until success. 
&& sublists can contain || sublists and vice versa; they are parsed  Execute the corresponding list.  ;& instead of &&  means fall 
left to right. through to next list.

command1 | command2 [ | command3 … ] case word {


Execute command1, sending its output to the input of  [(] pattern1[|pattern2...]) [;] list ;;
command2, and so on (a pipeline). …
 Page 3 Zsh Reference Card Version 4.2 

Pattern matching (globbing) KSH_GLOB operators (patterns may contain | for alternatives): S Setgid


Basic patterns: @(pat) Group patterns t Sticky bit
* Any string *(pat) Zero or more occurrences of pat fspec Has chmod­style permissions spec
? Any character +(pat) One or more occurrences of pat estring Evaluation string returns true status
[class] Any single character from class ?(pat) Zero or one occurrences of pat +cmd Same but cmd must be alphanumeric or _
[^class] Any single character not from class !(pat) Anything but the pattern pat ddev Device number dev (major*256 + minor)
<num1-num2> Any number between num1 and num2 l[-+]num Link count is (less than, greater than) num
<-num2> from 0; <num1-> to infinity. Globbing flags with EXTENDED_GLOB: U Owned by current effective UID
**/ Directories to any level (#i) Match case insensitively G Owned by current effective GID
(pat1) Group patterns (#l) Lower case matches upper case uuid Owned by given uid (may be <name>)
(pat1|pat2) pat1 or pat2 (any number of |’s) (#I) Match case sensitively ggid Owned by given gid (may be <name>)
(#b) Parentheses set match, mbegin, mend a[Mwhms][-+]n Access time in given units (see below)
Character classes may contain any character or the following  (#B) Parentheses no longer set arrays m[Mwhms][-+]n Modification time in given units
special patterns in any mix; literal – must be first; literal ^ must  (#m) Match in MATCH,  MBEGIN, MEND c[Mwhms][-+]n Inode change time in given units
not be first: (#M) Don’t use MATCH etc. L[kmp][-+]n Size in given units (see below)
a-b A character in the range a to b (#anum) Match with num approximations ^ Negate following qualifiers
[:alnum:] An alphanumeric character (#s) Match only at start of test string - Toggle following links (first one turns on)
[:alpha:] An alphabetic character (#e) Match only at end of test string M Mark directories
[:ascii:] A character in the ASCII character set (#qexpr) expr is a a set of glob qualifiers (below) T Mark directories, links, special files
[:blank:] A space or tab N Whole pattern expands to empty if no match
[:cntrl:] A control character Glob qualifiers (in parentheses after file name pattern): D Leading dots may be matched
[:digit:] A decimal digit / Directory n Sort numbers numerically
[:graph:] A printable character other than whitespace F Non­empty directory; for empty use (/^F) o[nLlamcd] Order by given code (as below; may repeat)
[:lower:] A lower case letter . Plain file O[nLlamcd] Order by reverse of given code
[:print:] A printable character @ Symbolic link [num] Select numth file in current order
[:punct:] A punctuation character = Socket [num1,num2] Select num1th to num2th file (as arrays)
[:space:] Any whitespace character p Name pipe (FIFO) :X History modifier X; may have more
[:upper:] An upper case letter * Executable plain file Time units are Month, week, hour, minute, second; default is day.
[:xdigit:] A hexadecimal digit % Special file Size units are kilobytes, megabytes or 512­byte blocks (p); default 
%b Block special file is bytes; upper case means the same as lower case.
Extended patterns (option EXTENDED_GLOB must be set): %c Character special file Order codes are name (default), size, link count, access time, 
^pat Anything that doesn’t match pat r Readable by owner (N.B. not current user) modification time, inode change time, directory depth.
pat1^pat2 Match pat1 then anything other than pat2 w Writeable by owner
pat1~pat2 Anything matching pat1 but not pat2 x Executable by owner
X# Zero or more occurrences of element X A Readable by members of file’s group
X## One or more occurrences of element X I Writeable by members of file’s group
E Executable by members of file’s group
R World readable
W World writeable
X World executable
s Setuid
 Page 4 Zsh Reference Card Version 4.2 

Options CSH_NULL_GLOB One glob must succeed, failures go INTERACTIVE_ # on interactive line for comment


Set options with setopt, unset with  unsetopt.  Asterisk  DVORAK Dvorak keyboard for correction COMMENTS
indicates on by default for native zsh. EMACS Same as bindkey -e KSH_ARRAYS Indexing etc. for arrays like ksh
*ALIASES Expand aliases *EQUALS Expand =cmd to /path/to/cmd KSH_AUTOLOAD Function file includes function name
ALL_EXPORT Export all variables to environment ERR_EXIT Exit shell on non­zero status KSH_GLOB See globbing above
*ALWAYS_LAST_PROMPT Completion lists after prompt ERR_RETURN Return from function instead KSH_OPTION_PRINT Show all options plus on or off
ALWAYS_TO_END On completion go to end of word *EVAL_LINE_NO $LINENO counts inside eval code KSH_TYPESET No word splitting in typeset etc.
*APPEND_HISTORY History appends to existing file *EXEC Execute commands *LIST_AMBIGUOUS List completions when ambiguous
AUTO_CD Directory as command does cd EXTENDED_GLOB See globbing section above *LIST_BEEP Beep on ambiguous completion
AUTO_CONTINUE Jobs are continued when disowned EXTENDED_HISTORY Timestamps saved to history file LIST_PACKED More compact completion lists
*AUTO_LIST List ambiguous completions *FLOW_CONTROL Use ^S/^Q style flow control LIST_ROWS_FIRST List completions across
*AUTO_MENU Menu complete after two tabs *FUNCTION_ARGZER0 $0 in function is its name *LIST_TYPES File types listed in completion
AUTO_NAME_DIRS Variables always can be %~ abbrevs *GLOB Use globbing as described above LOCAL_OPTIONS Options reset on function return
*AUTO_PARAM_KEYS Magic completion for parameters *GLOBAL_EXPORT Exported variables not made local LOCAL_TRAPS Traps reset on function return
*AUTO_PARAM_SLASH $dirname completes with / *GLOBAL_RCS Execute /etc/z* files LOGIN Shell is login shell
AUTO_PUSHD cd uses directory stack too GLOB_ASSIGN var=* expands, assigns array LONG_LIST_JOBS More verbose listing of jobs
*AUTO_REMOVE_SLASH Trailing / in completion removed GLOB_COMPLETE Patterns are active in completion MAGIC_EQUAL_SUBST Special expansion after all =
AUTO_RESUME cmd can resume job %cmd GLOB_DOTS Patterns may match leading dots MAIL_WARNING Warn if mail file timestamp changed
*BAD_PATTERN Errors on pattern syntax; else literal GLOB_SUBST Substituted characters may glob MARK_DIRS Append / to globbed directories
*BANG_HIST ! style history allowed *HASH_CMDS Store command location for speed MENU_COMPLETE Cycle through ambiguous matches
*BARE_GLOB_QUAL Glob qualifiers with bare parens *HASH_DIRS Store for all commands in dir MONITOR Shell has job control enabled
BASH_AUTO_LIST List completions on second tab *HASH_LIST_ALL Store all on first completion *MULTIOS Multiple redirections are special
*BEEP Beep on all errors HIST_ALLOW_CLOBBER On clobber error, up arrow to retry *NOMATCH Error if glob fails to match
*BG_NICE Background jobs at lower priority *HIST_BEEP Beep when going beyond history *NOTIFY Asynchronous job control messages
BRACE_CCL X{ab} expands to Xa Xb HIST_EXPIRE_DUPS_ Duplicate history entries lost first NULL_GLOB Failed globs are removed from line
BSD_ECHO No echo escapes unles -e given FIRST NUMERIC_GLOB_SORT Numbers in globs sorted numerically
*CASE_GLOB Glob case sensitively HIST_FIND_NO_DUPS History search finds once only OCTAL_ZEROES Leading zeros in integers force octal
C_BASES Output hexadecimal with 0x HIST_IGNORE_ALL_ Remove all earlier duplicate lines OVERSTRIKE Start line editor in overstrike mode
CDABLE_VARS cd var  works if $var is directory DUPS PATH_DIRS dir/cmd can be found in $PATH
CHASE_DOTS Resolve .. in cd HIST_IGNORE_DUPS Remove duplicate of previous line POSIX_BUILTINS Illogical command behaviour
CHASE_LINKS Resolve symbolic links in cd HIST_IGNORE_SPACE Don’t store lines starting with space PRINT_EIGHT_BIT Print all 8­bit characters directly
HIST_NO_FUNCTIONS Don’t store shell functions PRINT_EXIT_VALUE Return status printed unless zero
*CHECK_JOBS Check jobs before exiting shell
Allow redirections to overwrite HIST_NO_STORE Don’t store history and fc PRIVILEGED Special behaviour on setuid/setgid
*CLOBBER
Completion uses unexpanded aliases HIST_REDUCE_BLANKS Trim multiple insgnificant blanks PROMPT_BANG Special treatment of ! in prompt
COMPLETE_ALIASES
HIST_SAVE_NO_DUPS Remove duplicates when saving *PROMPT_CR Prompt always at start of line
COMPLETE_IN_WORD Completion works inside words
CORRECT Correct spelling of commands HIST_VERIFY Show ! history line for editing *PROMPT_PERCENT % escapes expanded in prompts
CORRECT_ALL Correct spelling of all arguments *HUP Send SIGHUP to proceses on exit PROMPT_SUBST $ expansion etc. in prompts
CSH_JUNKIE_HISTORY Single ! for previous command IGNORE_BRACES Don’t use {a,b} expansions PUSHD_IGNORE_DUPS Don’t push dir multiply on stack
CSH_JUNKIE_LOOPS list; end for do...done IGNORE_EOF Ignore ^D (stty eof char) PUSHD_MINUS Reverse sense of – and + in pushd
CSH_JUNKIE_QUOTES No newlines in quotes INC_APPEND_HISTORY Save history line by line PUSHD_SILENT No non­err messages from pushd
CSH_NULLCMD Redirections with no commands fail INTERACTIVE Shell is interactive PUSHD_TO_HOME pushd with no argument goes to ~
 Page 5 Zsh Reference Card Version 4.2 

RC_EXPAND_PARAM X$array gives Xelt1 Xelt2 etc. Single letter options (used with set as well as setopt): -l LOGIN


RC_QUOTES '' inside single quotes gives ' -0 CORRECT -m MONITOR
*RCS Run startup files -1 PRINT_EXIT_VALUE -n NO_EXEC
REC_EXACT Exact completion matches are good -2 NO_BAD_PATTERN -p PRIVILEGED
RESTRICTED Shell has restricted capabilities -3 NO_NO_MATCH -r RESTRICTED
RM_STAR_SILENT Don’t warn on rm * -4 GLOB_DOTS -s SHIN_STDIN
RM_STAR_WAIT Wait before asking if rm * is OK -5 NOTIFY -t SINGLE_COMMAND
SHARE_HISTORY Save and restore history per line -6 BG_NICE -u NO_UNSET
-7 IGNORE_EOF -v VERBOSE
SH_FILE_EXPANSION ~ etc. expansion done early
-8 MARK_DIRS -w CHASE_LINKS
SH_GLOB Disables non­extended zsh globs
-9 AUTO_LIST -x XTRACE
SHIN_STDIN Shell input comes from stdin
-B NO_BEEP -y SH_WORD_SPLIT
SH_NULL_CMD Commandless redirections like sh Note also -A to set arrays, -b to end option processing, -c to 
-C NO_CLOBBER
SH_OPTION_LETTERS Single letter options are like sh -D PUSHD_TO_HOME pass a single command,  -m to set pattern argument, -o to specify 
*SHORT_LOOPS for words; list works -E PUSHD_SILENT long name (may repeat), ­s to sort positional parameters.
SH_WORD_SPLIT Split non­array variables yuckily -F NO_GLOB
SINGLE_COMMAND Execute one command then exit -G NULL_GLOB
SINGLE_LINE_ZLE Line editing on single line (bad tty) -H RM_STAR_SILENT
SUN_KEYBOARD_HACK Unmatched ` at end of line ignored -I IGNORE_BRACES
TRANSIENT_RPROMPT Right prompt goes away after edit -J AUTO_CD
TRAPS_ASYNC Traps may run when waiting -K NO_BANG_HIST
TYPESET_SILENT Silent on typeset foo -L SUN_KEYBOARD_HACK
*UNSET Unset variables OK, treat as empty -M SINGLE_LINE_ZLE
VERBOSE Output commands to be executed -N AUTO_PUSHD
VI Same as bindkey -v -O CORRECT_ALL
XTRACE Show trace of execution with $PS4 -P RC_EXPAND_PARAM
ZLE Line editor used to input lines -Q PATH_DIRS
-R LONG_LIST_JOBS
-S REC_EXACT
Option aliases (native zsh on right):
-T CDABLE_VARS
BRACE_EXPAND NO_IGNORE_BRACES
-U MAIL_WARNING
DOT_GLOB GLOB_DOTS
-V NO_PROMPT_CR
HASH_ALL HASH_CMDS
-W AUTO_RESUME
HIST_APPEND APPEND_HISTORY
-X LIST_TYPES
HIST_EXPAND BANG_HIST
-Y MENU_COMPLETE
LOG NO_HIST_NO_FUNCTIONS
-Z ZLE
MAIL_WARN MAIL_WARNING
-a ALL_EXPORT
ONE_CMD SINGLE_COMMAND
-e ERR_EXIT
PHYSICAL CHASE_LINKS
-f NO_RCS
PROMPT_VARS PROMPT_SUBST
-g HIST_IGNORE_SPACE
STDIN SHIN_STDIN
-h HIST_IGNORE_DUPS
TRACK_ALL HASH_CMDS
-i INTERACTIVE
-k INTERACTIVE_COMMENTS
 Page 6 Zsh Reference Card Version 4.2 

Expansion Modifiers on arguments (can omit word selector): %M Full host name


Basic forms of expansion in the order they order: !!:1:h Trailing path component removed %m Host name to first dot or n dots
!expr History expansion !!:1:t Only trailing path component left %N Name of script, function, sourced file
alias Alias expansion !!:1:r File extension .ext removed %n Name of user (same as $USERNAME)
<(cmds) Replaced by file with output from cmds !!:1:e Only extension ext left %S %s Start (stop) standout mode
=(cmds) Same but can be reread (use for diff) !!:1:p Print result but don’t execute %T Time of day, 24­hour format
>(cmds) Replaced by file with input to cmds !!:1:q Quote from further substitution %U %u Start (stop) underline mode (patchy support)
$var Variable substitution !!:1:Q Strip one level of quotes %v nth component of $psvar array
${var} Same but protected, allows more options !!:1:x Quote and also break at whitespace %W Date as middle­endian MM/DD/YY
$(cmds) Replaced by output of cmds !!:1:l Convert to all lower case %w Date as DAY DD
`cmds` Older form of same, harder to nest !!:1:u Convert to all upper case %y Login terminal without /dev
$((expr)) Arithmetic result of evaluating expr !!:1:s/s1/s2/ Replace string s1 by s2 %_ Parser state (continuation lines, debug)
X{a,b}Y XaY Xby (N.B. does no pattern matching) !!:1:gs/s2/s2/ Same but global %~ Like %/, %d but with tilde substitution
X{1..3}Y X1Y X2y X3y !!:1:& Use same s1 and s2 on new target %{esc%} Escape sequence esc doesn’t move cursor
X{08..10}Y X08Y X09y X10y %X(.tstr.fstr) tstr if test X gives n, else fstr
~user, ~dir User home, named dir (dir is var name) Most modifiers work on variables (e.g ${var:h}) or in glob  %<str< Truncate to n on left, str on left if so
=cmd /full/path/to/cmd qualifiers (e.g. *(:h)), the following only work there: %>str> Truncate to n on right, str on right if so
pattern Glob file names, as above ${var:fm} Repeat modifier m till stops changing
${var:F:N:m} Same but no more than N times
${var:wm} Apply modifer m to words of string Test characters in %X(.tstr.fstr): ! Privileged; # uid n; ?
History expansion:
Immediately preceding line (all of it) ${var:W:sep:m} Same but words are separated by sep last status n; _ at least n nested constructs; / at least n $PWD
!!
!{!} Same but protected, may have args in {} elements; ~ same with ~ subst; D month is n; d day of month is n; 
! Line just referred to, default !! Prompt expansion (with PROMPT_PERCENT, on by default); may  g effective gid is n; j at least n jobs; L $SHLVL at least n; l at 
!13 Line numbered 13 (history shows nos.) take a decimal number n (default 0) immediately after the %: least n chars on line so far; S $SECONDS at least n; T hours is n; 
!-2 Command two before current %! %h Current history event number t minutes is n; v at least n components in $psvar; w day of 
!cmd Last command beginning cmd %# # if superuser, else % week is n (Sunday = 0).
!?str Last command containing str %% A single %
!# Current command line so far %) A ) (use with %X(.tstr.fstr))
%* Time in 24­hour format with seconds
Word selectors: %/ %d $PWD; n gives trailing parts, -n leading
!!:0 Extract argument 0 (command word) %c %. %C Deprecated alternatives, differ by default n
!!:1 Argument numbered 1 (first cmd arg) %? Return status of last command
!!:^ Also argument 1 %@ %t Time of day in am/pm format
!!:$ Last command argument %B (%b) Start (stop) bold face mode
!:% Word found by !?str (needs correct line) %D %D{str} Date as YY-MM-DD, optional strftime spec
!!:2-4 Word 2 to 4 inclusive %E Clear to end of line
!!:-4 Words 0 to 4 inclusive %i Script/function line number ($LINENO)
!!:* Words 1 to $ inclusive %j Number of jobs as listed by jobs
!!:2* Words 2 to $ inclusive %L Shell depth ($SHLVL)
!!:2- Words 2 to $­1 inclusive %l Login terminal without /dev or 
/dev/tty
 Page 7 Zsh Reference Card Version 4.2 

Parameter (Variable) Expansion q Quote result with backslashes Order of rules:


Basic forms: str will also be expanded; most forms work on  qq Quote result with single quotes 1. Nested substitution: from inside out
words of array separately: qqq Quote result with double quotes 2. Subscripts: ${arr[3]} extract word; ${str[2]}
${var} Substitute contents of var, no splitting qqqq Quote result with $'...' extract character; ${arr[2,4]}, ${str[4,8]}
${+var} 1 if var is set, else 0 Q Strip quotes from result extract range; -1 is last word/char, -2 previous etc.
${var:-str} $var if non­null, else str t Output type of variable (see below) 3. ${(P)var} replaces name with value
${var-str} $var if set (even if null) else str u Unique: remove duplicates after first 4. ¨$array¨ joins array, may use (j:str:)
${var:=str} $var if non­null, else str and set var to it U Upper case result 5. Nested subscript e.g. ${${var[2,4]}[1]}
${var::=str} Same but always use str v Include value in result; may have (kv) 6. #, %, / etc. modifications
${var:?str} $var if non­null else error, abort V Visible representation of special chars 7. Join if not joined and (j:str:), (F)
${var:+str} str if $var is non­null w Count words with ${#var} 8. Split if (s), (z), (z), =
${var#pat} min match of pat removed from head W Same but empty words count 9. Split if SH_WORD_SPLIT
${var##pat} max match of pat removed from head X Report parsing errors (normally ignored) 10. Apply (u)
${var%pat} min match of pat removed from tail z Split to words using shell grammar 11. Apply (o), (O)
${var%%pat} max match of pat removed from tail p Following forms recognize print \­escapes 12. Apply (e)
${var:#pat} $var unless pat matches, then empty j:str: Join words with str between 13. Apply (l.str.), (r.str.)
${var/p/r} One occurrence of p replaced by r l:x: Pad with spaces on left to width x 14. If single word needed for context, join with $IFS[1].
${var//p/r} All occurrences of p replaced by r l:x::s1: Same but pad with repeated s1
${#var} Length of var in words (array) or bytes l:x::s1::s2: Same but s2 used once before any s1s Types shown with (t) have basic type scalar, array, 
${^var} Expand elements like brace expansion r:x::s1::s2: Pad on right, otherwise same as l forms integer, float, assocation, then hyphen­separated words 
${=var} Split words of result like lesser shells s:str: Split to array on occurrences of str from following list:
${~var} Allow globbing, file expansion on result S With patterns, search substrings local Parameter is local to function
${${var%p}#q} Apply %p then #q to $var I:exp: With patterns, match expth occurrence left Left justified with typeset -L
B With patterns, include match beginning right_blanks Right justified with typeset -R
Parameter flags in parentheses, immediately after left brace: E With patterns, include match end right_zeros Right justified with typeset -Z
% Expand %s in result as in prompts M With patterns, include matched portion lower Lower case forced with typeset -l
@ Array expand even in double quotes N With patterns, include length of match upper Upper case forced with typeset -u
A Create array parameter with ${...=...} R With patterns, include unmatched part (rest) readonly Read­only, typeset -r or readonly
a Array index order, so Oa is reversed Delimeters  shown as :str: may be any pair of chars or matched  tag Tagged as typeset -t (no special effect)
c Count characters for ${#var} parenthses (str), {str}, [str], <str>. export Exported with export, typeset -x
C Capitalize result unique Elements unique with typeset -U
e Do parameter, comand, arith expansion hide Variable not special in func (typeset -h)
f Split result to array on newlines hideval typeset hides value (typeset -H)
F Join arrays with newlines between elements special Variable special to shell
i oi or Oi sort case independently
k For associative array, result is keys
L Lower case result
n on or On sort numerically
o Sort into ascending order
O Sort into descending order
P Interpret result as parameter name, get value
 Page 8 Zsh Reference Card Version 4.2 

Parameters (Variables) USERNAME Name for $UID, set if root PS1, PROMPT, Printed at start of first line of output; see 


Parameters set by shell, denotes special to shell (may not be  VENDOR Operating system vendor (compile time) prompt above for escape sequences for all PSs
reused except by hiding with typeset ­h in functions) ZSH_NAME Base name of command used to start shell PS2, PROMPT2 Printed for continuation lines
! Process ID of last background process ZSH_VERSION Version number of shell PS3, PROMPT3 Print within select loop
# Number of arguments to script or function PS4, PROMPT4 For tracing execution (xtrace option)
ARGC Same Parameters used by the shell if set: : indicates arrays with  psvar : Used with %nv in prompts
$ Process ID of main shell process corresponding colon­separated paths e.g. cdpath and CDPATH: READNULLCMD Command used when only input redir given
- String of single letter options set ARGV0 Export to set name of external command REPORTTIME Show report if command takes this long (s)
* Positional parameters BAUD Baud rate: compensation for slow terminals REPLY Used to return a value e.g. by read
argv Same cdpath : Directories searched for cd target reply Used to return array value
@ Same, but does splitting in double quotes COLUMNS Width of screen RPS1, RPROMPT Printed on right of screen for first line
? Status of last command DIRSTACKSIZE Maximum size of stack for pushd RPS2, Printed on right of screeen for continuation 
0 Name of shell, usually reflects functions ENV File to source when started as sh or ksh RPROMPT2 line 
_ Last argument of previous command FCEDIT Default editor used by fc SAVEHIST Max number of history lines saved
CPUTYPE Machine type (run time) fignore : List of suffixes ignored in file completion SPROMPT Prompt when correcting spelling
EGID Effective GID (via system call), set if root fpath : Directories to search for autoloading STTY Export with stty arguments to command
EUID Effective UID (via system call), set if root histchars History, quick replace, comment chars TERM Type of terminal in use (xterm etc.)
ERRNO Last system error number HISTCHARS Same, deprecated TIMEFMT Format for reporting usage with time
GID Real group ID (via system call), set if root HISTFILE File for reading and writing shell history TMOUT Send SIGALRM after seconds of inactivity
HISTCMD The current history line number HISTSIZE Number of history lines kept internally TMPPREFIX Path prefix for shell’s temporary files
HOST The host name HOME Home directory for ~ and default cd target watch : List of users or all, notme to watch for
LINENO Line number in shell, function IFS Characters that separate fields in words WATCHFMT Format of reports for $watch
LOGNAME Login name (exported by default) KEYTIMEOUT Time to wait for  rest of key seq (1/100 s) WORDCHARS Chars considered parts of word by zle
MACHTYPE Machine type (compile time) LANG Locale (usual variable, LC_* override) ZBEEP String to replace beeps in line editor
OLDPWD Previous directory LC_ALL Locale (overrides LANG, LC_*) ZDOTDIR Used for startup files instead of ~ if set
OPTARG Argument for option handled by getopts LC_COLLATE Locale for sorting etc.
OPTIND Index of positional parameter in getopts LC_CTYPE Locale for character handling
OSTYPE Operating system type (compile time) LC_MESSAGES Locale for messages
pipestatus Array giving statuses of last pipeline LC_NUMERIC Locale for decimal point, thousands
PPID Process ID of parent of main shell LC_TIME Locale for date and time
PWD Current directory LINES Height of screen
RANDOM A pseudo­random number, repeating LISTMAX Number of completions shown w/o asking
SECONDS Seconds since shell started LOGCHECK Interval for checking $watch
SHLVL Depth of current shell MAIL Mail file to check ($mailpath overrides)
signals Array giving names of signals MAILCHECK Mail check interval, secs (before prompt)
status Status of last command mailpath : List of files to check for new mail
TRY_BLOCK_ In always block, 1 if error in try block manpath : Directories to find manual, used by man
ERROR module_path : Directories for zmodload to find modules
TTY Terminal associated with shell if any NULLCMD Command used if only redirection given
TTYIDLE Time for which terminal has been idle path : Command search path
UID Real user ID (via system call), set if root POSTEDIT Termcap strings sent to terminal after edit
 Page 9 Zsh Reference Card Version 4.2 

Tests and numeric expressions != True if string a does not match pattern b • : (true/false separator for ternary operator)


Usually used after if, while, until or with && or ||, but the status  < True if string a sorts before string b • =, +=, -=, *=, /=, %=, **=, &=, ^=, |=, <<=, >>=, 
may be useful anywhere e.g. as implicit return status for function. > True if string a sorts after string b &&=, ^^=, ||=
-eq True if numerical expressions a and b are equal • , (as in C, evaluate both sides and return right hand 
File tests, e.g. [[ -e file ]]: -ne True if numerical expressions a and b are not equal side).
-a True if file exists -lt True if a < b numerically
-b True if file is block special -gt True if a > b numerically For functions use zmodload -i zsh/mathfunc; functions 
-c True if file is character special -le True if a ≤ b numerically available are as described in C math library manual:
-d True if file is directory -ge True if a ≥ b numerically • Single floating point argument, return floating point: 
-e True if file exists acos, acosh, asin, asinh, atan (optional second 
-f True if file is a regular file (not special or directory Combining expressions: expr is any of the above, or the result of  argument like C atan2), atanh, cbrt, ceil, cos, 
-g True if file has setgid bit set (mode includes 02000) any combination of the following: cosh, erf, erfc, exp, expm1, fabs, floor, 
-h True if file is symbolic link ( expr ) Group tests gamma, j0, j1, lgamma, log, log10, log1p, 
-k True if file has sticky bit set (mode includes 02000) ! expr True if expr is false and vice versa logb, sin, sinh, sqrt, tan, tanh, y0, y1
-p True if file is named pipe (FIFO) exprA && exprB True if both expressions true • Single floating point argument, return integer: ilogb
-r True if file is readable by current process exprA || exprB True if either expression true • No arguments, return integer: signgam (remember 
-s True if file has non­zero size parentheses)
-u True if file has setuid bit set (mode includes 04000) For complicated numeric tests use (( expr )) where expr is  • Two floating point arguments, return floating point: 
-w True if file is writeable by current process a numeric expression: status is 1 if expr is non­zero else 0.  Same  copysign, fmod, hypot, nextafter
-x True if file executable by current process syntax used in $(( expr )) substitution. Precedences of  • One integer, one floating point argument, return floating 
-L True if file is symbolic link operators from highest to lowest are: point: jn, yn
-O True if file owned by effective UID of current  • func(arg...), numeric constant (e.g. 3, -4, 3.24,  • One floating point, one integer argument, return floating 
process -14.6e-10), var (does not require $ in front unless  point: ldexp, scalb
-G True if file has effective GID of current process some substitution e.g. ${#var} is needed, $ is error if  • Either integer or floating point, return same type: abs
-S True if file is a socket (special communication file) var is to be modified) • Coerce to floating point: float
-N True if file has access time no newer than mod time • ( expr ) • Coerce to integer: int
• !, ~, ++ (post­ or preincrement), -- (post­ or  • Optional string argument (read/write variable name), 
Other single argument tests, e.g. [[ -n str ]]: predecrement), unary +, unary -
-n True if str has non­zero length return floating point: rand48
• &
-o True if option str is set Example use:
• ^ zmodload -i zsh/mathfunc
-t True if str (number) is open file descriptor • | float x
-z True if str has zero length • ** (exponentiation) (( x = 26.4 * sqrt(2) ))
• *, /, % print $(( log(x)/2 ))
Multiple argument tests e.g. [[ a -eq b ]]:  numerical  • binary +, binary -
expressions may be quoted formulae e.g. ‘1*2’: • <<, >>
-nt True if file a is newer than file b • <, <=, >, >=
-ot True if file a is older than file b • ==, !=
-ef True if a and b refer to same file (i.e. are linked) • &&
= True if string a matches pattern b
• ||, ^^
== Same but more modern (and still not often used)
• ? (ternary operator)
 Page 10 Zsh Reference Card Version 4.2 

Completion -brace- Parameter within ${…} files Generic file matching tag


Load new completion system with: parameter- fonts X font names
autoload -Uz compinit -assign- Left hand side of assignment fstypes Files system types for mount etc.
compinit parameter- functions Shell functions, possibly other types
-command- Word in command position globbed-files Names of files matched by pattern
Configuration: uses styles -condition- Word in [[ ... ]] condition groups UNIX groups
zstyle context style value… -default- Word with no specific completion history-words Words from shell history
where context  may be a pattern matching the following form: -equal- Word beginning with equals sign hosts Names of network hosts
:completion:func:completer:cmd:arg:tag -first- Tried first, may set _compskip indexes Indexes of arrays
in which: -math- Inside arithmetic such as (( ... )) jobs Shell jobs
completion -parameter- Parameter with bare $ in front interfaces Network interfaces (as from ifconfig)
Literal string always used by completion functions -redirect- Word after redirection operator keymaps ZLE keymaps
func -subscript- Inside parameter subscript keysyms Names of X keysyms
Name of directly called widget, blank for contextual completion -tilde- Between ~ and first / of argument libraries Names of system libraries
completer -value- Right hand side of assignment limits System resource limits
Method of completion e.g. complete; see below local-directories Subdirectories of current directories
cmd Tags: manuals Names of manual pages
Name of command being completed, or special command context accounts For users­hosts style mailboxes E­mail folders
arg all-expansions When expanding, everything at once maps NIS maps etc.
Only valid with standard parsing: arg-n for nth argument all-files All files rather than a subset messages Used in format style for messages
option-opt-n for nth argument of option opt arguments Command arguments modifiers X modifiers
tag arrays Names of array parameters modules Shell modules etc.
Indication of type of thing to be completed at this point. association-keys Keys of associative arrays my-accounts Own accounts, with users­hosts style
bookmarks Bookmarks for URLs, ZFTP, etc. named-directories Directories named by a parameter
Completers (indicates modifiers existing or later completions): builtins Names of builtin commands names Names of all sorts
_all_matches Later completers add all matches characters Character classes, stty characters newsgroups USENET newgroups
_approximate Complete with errors in part so far colormapids X colormap IDs nicknames Nicknames of NIS maps
_complete Basic completion colors Names of colors, usually X options Options to commands
_correct Correct word already typed commands External commands, subcommands original Original when correcting, expanding
_expand Perform shell expansions contexts Contexts in zstyle other-accounts Other accounts with users­hosts style
_expand_alias Expand aliases only corrections Possible approximations, corrections Tags continued:
_history Complete words from shell history cursors X cursor names packages RPM, Debian etc. packages
_ignored Reinstate matches omitted default Nothing specific in certain contexts parameters Names of shell parameters
_list List on first completion, insert on second descriptions Used in format style for matches path-directories Directories under $cdpath
_match Complete using patterns from line devices Device special files paths Used with assorted directory paths
_menu Menu completion, no menu selection directories Directories pods Perl documentation
_oldlist Use existing list before generating new one directory-stack Entries in pushd directory stack ports TCP, UDP prots
_prefix Complete ignoring what’s after cursor displays X displays prefixes URL etc. prefixes
domains Network domain (DNS) names printers Names of print queues
Command contexts: any command name plus the special contexts: expansions Individual expansions instead of all processes PIDs
file-descriptors Numbers of open file descriptors processes-names Names of processes in killall
-array-value- Element in array
 Page 11 Zsh Reference Card Version 4.2 

sequences MH sequences etc. fake-files dir:names add names in dir muttrc Alternative for ~/.muttrc


sessions ZFTP sessions etc. fake-parameters Params to complete even if not yet set numbers Prefer job numbers instead of name
signals System signal names, HUP etc. file-patterns pattern:tag generates files with tag old-list Retain list of matches (_oldlist)
strings Assorted strings, e.g. second arg of cd file-sort size, links, time, access, inode, reverse old-matches Use old match list (_all_matches)
styles Styles in zstyle filter In LDAP, attributes for filtering old-menu Keep list for meus (_oldlist)
suffixes Filename extensions force-list Just list matches: always or number original Add original match for approx/correct
tags Tags used with rpm etc. format Desc string, %d shows specific desc packageset For arguments of Debian dpkg
targets Targets inside Makefiles glob Attempt glob expansion (_expand) path For X colors, path to rgb.txt
time-zones Time zones with TZ parameter etc. global Global aliases (_expand_alias) pine-directory Directory for PINE mailboxes
types Assorted types of anything group-name Name groups shown together by tag ports TCP/IP services (/etc/services)
urls Used with web addresses group-order Order groups shown together by tag prefix-hidden Hide common prefix e.g. in options
users Names of users groups Unix groups, as per /etc/group prefix-needed Common prefix must by typed by user
values Values in lists hidden Complete but don’t list matches preserve-prefix Initial file patterns to leave alone
variant Used when picking variant of command hosts List of host names, as /etc/hosts range Range of words in history to consider
visuals X visuals hosts-ports List of hosts:ports for TCP/UDP regular Complete regular aliases
warnings Used in the format style for warnings ignore-line Don’t complete words already present Styles continued:
widgets Names of zsh widgets ignore-parents parent or pwd: ignore parent dirs remote-access Control remote access for e.g. _cvs
windows IDs of X windows ignored-patterns If pattern matched, don’t complete remove-all-dups Never complete duplicates in history
zsh-options Shell options insert All matches at once (_all_matches) select-prompt Prompt shown in menu selection
insert-ids Convert %cmd to unambiguous PID select-scroll Lines to scroll in menu selection
Styles (indicates on by default): insert-tab Insert TAB if no non­whitespace yet separate-sections Manual sections used as part of tag
accept-exact Accept exact match even if ambiguous insert- Only menu complete when no prefix to  show-completer Show progress of completers as msg
add-space Add a space after expansions unambiguous insert single-ignored Control _ignore when single match
ambiguous Cursor after ambiguous path component keep-prefix Try to keep expandable prefix sort Override sorting of matches
assign-list PATH­style list on assignment last-prompt Return to last editing line if possible special-dirs Add . and .. to file list
auto-description String for option descs without specific list Control listing when history completing squeeze-slashes fo//ba is fo/ba not fo/*/ba
avoid-completer Avoid completer with _all_matches list-colors Color specs like LS_COLORS stop Pause before looping shell history
cache-path Path to top of various caches list-grouped Grouped listing shown more compactly strip-comments Remove display name from email addr
cache-policy Function to decide on cache rebuilding list-packed All matches shown more compactly subst-globs-only Only take expansions from globbing
call-command If true, use external (slow) command list-prompt Prompt when scrolling completions substitute When expanding, first try subst
command External command to call (+args) list-rows-first Increment rows first in lists suffix Only expand path with no /suffix
command-path Override PATH for commands to match list-suffixes Show ambiguous bits of multiple paths tag-order Preference order for tags in context
commands Default sys init commands (start etc.) list-separator Separates description in verbose list urls Determine where URLs are taken from
complete Complete aliases (_expand_alias) local host:path:dir for URLs as files use-cache Control caching for various commands
completer The list of completers to try (see above) mail-directory Directory for mailbox files (~/Mail) use-compctl Use comptl­style completions
condition Delay insertion of matches (_list) match-original Add * when matching (_match) use-perl Use simpler Perl code for _make
disabled Disabled aliases (_expand_alias) matcher Apply match control syntax per tag users List of user names
disable-stat If set, _cvs uses ls instead of zsh/stat matcher-list Apply match control syntax globally users-hosts List of user@host possibilities
domains Net domains (/etc/resolv.conf) max-errors Max errors allowed in approx/correct users-hosts-ports List of user@host:port
expand For prefix, suffix in multiple parts max-matches-width Cols to reserve for matches (not desc) verbose Verbose output e.g. option descriptions
fake Add value:desc fake completions menu Use menu completion word Line changes based on current word
 Page 12 Zsh Reference Card Version 4.2 

_requested tag
Using _arguments for parsing standard command arguments: Examples of other utility functions: Implement loops over different tags
Three arguments give argument/option selector, message to  _alternative \
output, action to take.  Examples: ‘users:user:_users’ \ _all_labels tag expl descr compcommand
1:msg:_comp First arg; show msg, exec _comp ‘hosts:host:_hosts _next_label tag expl descr
1::msg:_comp Same for optional argument Either users or hosts (tag, description, action) Implement loops over different labels for each _requested tag
:msg:_comp Arg number inferred from position _describe setdesc arr1 --
*:msg:_comp Any of the remaining args (“rest args”) Associate descriptions with completions; arr1 contains 
*::msg:_comp words etc. set to normal args completion:description entries
*:::msg:_comp … set to args for this chunk
-foo Complete option -foo _message text-msg
+foo Complete option +foo Don’t complete, just output text-msg
-+foo Complete -foo or +foo
*-foo Option may occur multiple times _multi_parts sep array
-foo-:esg:_comp Option has arg in same word Complete by parts with separator sep, $array contains full 
-foo+:msg:_comp Option has arg in same or next word matches.
-foo=:msg:_comp Option arg -foo=bar or -foo bar
-foo=-:msg:_comp Option arg is -foo=bar only _path_files
-foo[desc] Option has description desc Complete files including partial paths; _files is smart front end; 
*:*pat:msg:_comp Complete words up to pat options -f all files (default), -g pat matching pat (with 
*:*pat::msg:_comp Modify words etc. for args
_files maybe directories too), -/ directories only, -W dirs
(-goo -boo)-foo -foo excludes -goo,  -boo
paths in which files are found, -F files files to ignore, 
(*)-foo -foo excludes rest args as matches
overrides ignored-patterns
(:)-foo -foo excludes normal args
(-)-foo -foo excludes all options
_sep_parts arr1 sep1 arr2 sep2 ……
!-foo -foo should not be completed
Elements from arr1, then separator, then elements from arr2, 
*:msg:<space> Show message but don’t complete
etc.
*:msg:(a b) Matches are listed items
*:msg:((a\:dsc)) Matches with descriptions
_values -s sep desc spec1 spec2 …
*:msg:->string Array state has string if matched
Complete multiple values separated by sep; values are given by 
*:msg:{code} Shell code generates matches
specs, each of which is similar to _arguments option spec
*:msg:= action Insert dummy argument first
*:msg:_comp arg Call _comp with additional args without leading -
*:msg: _comp arg Call _comp with only given arg
-a – set1 -c - … Common and specific completion sets _wanted thing expl ‘my things’ \
compadd mything1 mything2 …
- "(set1)" -c - … Mutually exclusive sets
Allow combined single letters Typical way of adding completions mything1 etc. with tag 
-s
-sw Same, even if option has args things and description my things; expl should be local 
-- Guess options by using --help variable.  Use single tag, c.f. _tags and _requested
-- -i pat Same, ignoring options matching pat
_tags tag1 tag2
 Page 13 Zsh Reference Card Version 4.2 

Zsh line editor (zle) execute-last-named-cmd €z redisplay ^R ^R


Builtin widgets, emacs binding, vicmd binding, viins binding; execute-name-cmd €x redo
€ denotes escape key: expand-cmd-path reset-prompt
accept-and-hold €a expand-history €! reverse-menu-complete
accept-and-infer-next-history expand-or-complete ^I ^I run-help €h
accept-and-menu-complete expand-or-complete-prefix self-insert ... ...
accept-line ^M ^M ^M expand-word ^X* self-insert-unmeta €^M
accept-line-and-down-history ^O forward-char ^F send-break ^G
argument-base forward-word €f set-mark-command ^@
backward-char ^B get-line €g spell-word €s
backward-delete-char ^H gosmacs-transpose-chars set-local-history
backward-delete-word history-beginning-search- transpose-chars ^T
backward-kill-line backward transpose-words €t
backward-kill-word ^W history-beginning-search- undefined-key
backward-word €b forward undo ^_
beep history-incremental-search- ^R universal-argument
beginning-of-buffer-or-history €< backward ^Xr up-case-word €u
beginning-of-history history-incremental-search- ^S up-history ^p
beginning-of-line ^A forward ^Xs up-line-or-history ^p k up
beginning-of-line-hist history-search-backward €p up-line-or-search
capitalize-word €c history-search-forward €n vi-add-eol A
clear-screen ^L ^L ^L infer-next-history ^x^n vi-add-next a
complete-word insert-last-word €_ vi-backward-blank-word B
copy-prev-word €^_ kill-buffer ^X^K vi-backward-char h ^H left
copy-prev-shell-word kill-line ^K vi-backward-delete-char X ^H
copy-region-as-kill €w kill-region vi-backward-kill-word ^W
delete-char kill-whole-line ^U vi-backward-word b
delete-char-or-list ^D kill-word €d vi-beginning-of-line
delete-word list-choices €^d ^d ^d vi-caps-lock-panic
describe-key-briefly list-expand ^Xg ^G ^G vi-change c
digit-argument €0.. 1..9 magic-space vi-change-eol C
down-case-word €l menu-complete vi-change-whole-line S
down-history ^n menu-expand-or-complete vi-cmd-mode ^XV €
down-line-or-history ^n j down neg-argument €- vi-delete d
down-line-or-search overwrite-mode ^X^O vi-delete-char x
emacs-backward-word pound-insert # vi-digit-or-beginning-of-line 0
emacs-forward-word push-input vi-down-line-or-history +
end-of-buffer-or-history €> push-line €q Builtin widgets cont.:
end-of-history push-line-or-edit vi-end-of-line $
end-of-line ^E quoted-insert ^V vi-fetch-history G
end-of-line-hist quote-line €' vi-find-next-char ^X^F f
end-of-list quote-region €” vi-find-next-char-skip t
exchange-point-and-mark ^X^X recursive-edit vi-find-prev-char F
 Page 14 Zsh Reference Card Version 4.2 

vi-find-prev-char-skip T what-cursor-position ^X= \Mx, \M-x Set 8th bit in character


vi-first-non-blank ^ where-is \Cx, \C-x Control character e.g. \C-a
vi-forward-blank-word W which-command €? ^x Control character e.g. ^a (same as ^A)
vi-forward-blank-word-end E yank ^y ^? Delete
vi-forward-char l rght yank-pop €y \\ Single backslash
vi-forward-word w
vi-forward-word-end e Special parameters inside user­defined widgets; indicates  Keymaps:
vi-goto-column €| | readonly: emacs Like Emacs editor
vi-goto-mark ` BUFFER Entire editing buffer viins Like Vi editor in insert mode
vi-goto-mark-line ˙ BUFFERLINES Number of screen lines for full buffer vicmd Like Vi editor in command mode
vi-history-search-backward / CONTEXT start, cont, select, vared .safe Emergency keymap, not modifiable
vi-history-search-forward ?
CURSOR Index of cursor position into $BUFFER
vi-indent >
CUTBUFFER Last item to be killed Examples of key binding:
vi-insert i
HISTNO Currently history line being retrieved bindkey '^xt' gosmacs-transpose-chars
vi-insert-bol I
KEYMAP Currently selected keymap bindkey '\e[2~' overwrite-mode
vi-join ^X^J J
vi-kill-eol D KEYS Keys typed to invoke current widget bindkey -M viins '^u' backward-kill-line
vi-kill-line ^U killring Array of previously killed items, can resize bindkey -s '^x^z' '\eqsuspend\n'
vi-match-bracket ^X^B % LASTSEARCH Last search string in interactive search
vi-open-line-above O LASTWIDGET Last widget to be executed autoload -Uz replace-string
vi-open-line-below o LBUFFER Part of buffer left of cursor zle -N replace-string
vi-oper-swap-case MARK Index of mark position into $BUFFER bindkey '\er' replace-string
vi-pound-insert NUMERIC Numeric argument passed with widget zle -N replace-string replace-pattern
vi-put-after P PENDING Number of bytes still to be read bindkey '\e%' replace-pattern
vi-put-before p PREBUFFER Input already read (no longer being edited) See man zshcontrib for supplied editing functions such as 
vi-quoted-insert ^V PREDISPLAY Text to display before editable buffer replace-string.
vi-repeat-change . POSTDISPLAY Text to display after editable buffer
vi-repeat-find ; RBUFFER Part of buffer starting from cursor
vi-repeat-search N WIDGET Name of widget being executed
vi-replace R WIDGETFUNC Name of function implementing $WIDGET
vi-replace-chars r WIDGETSTYLE Implementation style of completion widget
vi-rev-repeat-find , Special characters in bindkey strings:
vi-rev-repeat-search \a Bell (alarm)
vi-set-buffer “ \b Backspace
vi-set-mark m
\e, \E Escape
vi-substitute s
\f Form feed
vi-swap-case ~
\n Newline
vi-undo-change u
vi-unindent < \r Carriage return
vi-up-line-or-history - \t Tab (horizontal)
vi-yank y \v Tab (vertical)
vi-yank-eol Y \nnn Octal character e.g \081
vi-yank-whole-line \xnn Hexadecimal character eg. \x41

You might also like