Page 1 1 2 3 4 5 6 7 8 9 10 11 12 13
Zsh Reference Card Contents Genera Generall inform informati ation, on, refere reference ncess Gram Gramma marr (she (shell ll synt syntax ax)) Patter Patterns: ns: globbi globbing ng and qualif qualifier ierss Options Options Options cont.; cont.; option option aliases, aliases, single single letter letter options options Expans Expansion ion:: basic basic forms, forms, histor history, y, prompt promptss Expans Expansion ion:: variab variables les:: forms forms and flags flags Shell Shell varia variable bles: s: set by shell shell,, used used by shell shell Test Test operat operators ors;; numeri numericc expres expressio sions ns Comple Completio tion: n: contex contexts, ts, comple completer ters, s, tags tags Comple Completio tion n cont.: cont.: tags tags cont, cont, style styless Completion Completion cont.: cont.: styles styles cont, utility utility functions functions Zsh Zsh line line edit editor or (zle (zle))
general in part 1, concentrating on bash and ash in parts 2 and 3. The contents of the book are as follows; where noted with page references to this card they expand on the brief hints here. Part 1 (Introducing the Shell) contains the following chapters: 1 Intr Introd oduc ucti tion on to Shel Shells ls 2 Usin Using g Shel Shelll Feat Featur ures es Toge Togeth ther er 3 More More Shel Shelll Feat Featur ures es (c.f. page 2)
Part 2 (Using bash and zsh) contains the following chapters: 4 Enteri Entering ng and Editin Editing g the Comman Command d Line Line (c.f. pages 6 and 13) 5 St ar ar titi ng ng th e S he hel l (c.f. pages 4 and 5) 6 More More About About Shel Shelll Hist Histor ory y Notes The descriptions here are very brief. You will not be able to learn learn (c.f. pages 6 and 8) shell syntax from them; see the various references references below. In 7 Prompts particular the completion system is extremely rich and the (c.f. page 6) descriptions of its utility functions are the barest memory joggers. 8 File Filess and and Dire Direct ctor orie iess (c.f. page 9) The start and end of each section is aligned with page boundaries, 9 Pa tttt er er n Ma tc tc hi hin g so you can print out only the parts you want to refer to. (c.f. page 3) 10 Comp le letion References (c.f pages 10 through 12) Jobs Jobs and and Proc Proces esse sess Zsh manual: Supplied with the shell: should be installed in Unix 11 manual page and info formats. formats. Texinfo generates PS or PDF; (c.f. page 6) available as separate doc bundle from same place as the shell. Part3 (Extending the Shell) contains the following chapters: http://zsh.sunsite.dk/ http://zsh.sunsite.dk /: Site with much much information 12 Variables about zsh, including HTML manual and a more userfriendly (c.f. pages 7 and 8) guide to the shell, as well as the FAQ. 13 Scri Script ptin ing g and and Func Functi tion onss (c.f. page 2) Writ Writin ing g Edit Editor or Comma Command ndss Zsh wiki: http://www.zshwiki.org/: Extensible zsh web 14 pages written by users. (c.f page 13) 15 Writin Writing g Comple Completio tion n Functi Functions ons (c.f. pages 10 through 12) From Bash to Z Shell: Conquering the Command Line , by Oliver Kiddle, Jerry Peek and Peter Stephenson, Apress, ISBN 1 59059 376 6. Introduction to interactive interactive use of Unix shells in
Version 4.2
Page 2
Zsh Reference Card Grammar
, and so on (a pipeline ). ). command2 pipeline
List is any sequence of sublists (including just one) separated by ; or newline. ; and newline are always interchangeable except in ;;.
if listi1; then[;] listt1; ; then listt2 ; ] [ elif listi2 … [ else listt3 ; ] pipelines (including just one) Sublist is any sequence of pipelines fi connected by && or ||. listi1 is true, execute listt1; else if listi2 is true If listi1 ; else execute listt3 . Pipeline is any sequence of simple commands connected by |. execute listt2 Command is either a simple command (a command word) followed optionally by word … or one of the special commands below. Word is any text that produces a single word when expanded; word … is any number of these separated by whitespace. Name is a shell identifier: an alphabetic character or _ followed by any sequence of alphanumeric characters or _. [ … ] indicates optional; dots on their own line mean any number of repetitions of the line just above. Bold text is to be typed literally. Status “true” or “false” is determined determined by: for commands, the return status; for pipelines the last command; for sublists the last pipeline; for lists the last sublist that was executed.
sublist1 && sublist2 [ sublist2 [ && sublist3 … ] Execute sublists until one is false . sublist1 || sublist2 [ sublist2 [ || sublist2 … ] Execute sublists until one is true . Note strings of && sublists can contain || sublists and vice versa; they are parsed left to right. command1 | command2 [ | comm comman and3 d3 … ] Execute command1, sending its output to the input of
Version 4.2 case word { [(] pattern1[ ... ...]) [;] list ;; | pattern1[ pattern2 pattern2 … } Nonportable alternative.
name [ in word …]; select name [ do list; done Print menu of words, read a number, set name to selected word, execute list until end of input. Portable but rare.
for name [ name [ in word … ] do list; done list[;]) (list[ Execute list with variable name set to each of word … in turn Execute list in a subshell (a new process where nothing that If in … is omitted the positional parameters are used. happens affects the current shell). for name in word …; { list } foreach name ( word … ) [;] list; end
{list[ list[;]} Execute list (no new process: simply separates list from what’s around and can take redirections).
Nonportable alternative forms.
function nameword {[;] list[ list[;] } nameword () {[;] list[ list[;] } Define function named nameword ; executes list when run; running nameword word1 … makes word1 … available as $1 etc. in function body. list must end with [;] or newline for portability. nameword can be repeated to define multiple
while listw ; do listd ; done While listw is true execute listd . until listu ; do listd ; done Nonportable: while listu is not true execute listd . repeat numexp ; do list; done numexp sublist repeat numexp sublist Nonportable: repeat list or sublist numexp times. case word in | [(] pattern1[ pattern1[ pattern2 pattern2 ... ...]) [;] list ;; … esac Try matching word against every pattern in turn until success. Execute the corresponding list. ;& instead of && means fall through to next list.
functions (rare, nonportable).
pipeline ] time [ pipeline ] pipeline if given else totals for current shell. Report time for pipeline
[[ condition ]] Evaluate condition (see below), gives status true or false.
Page 3
Zsh Reference Card
Version 4.2
E Executable by members of file’s group R World readable * Any string W World writeable ? Any character X World executable [class] Any single character from class s Setuid [^class] Any single character not from class S Setgid Any number between num1 and num2 t Sticky bit <-num2 > from 0; to infinity. fspec Globbing flags with EXTENDED_GLOB: Has chmodstyle permissions spec **/ Directories to any level (#i) estring Match case insensitively Evaluation string returns true status pat1 pat1) ( Group patterns (#l) +cmd _ Lower case matches upper case Same but cmd must be alphanumeric or _ ( | ) pat1 pat1 pat2 pat2 pat1 or pat2 pat2 (any number of |’s) (#I) ddev Match case sensitively Device number dev (major*256 + minor) (#b) l[-+]num Parentheses set match, mbegin, mend Link count is (less than, greater than) num Character classes may contain any character or the following (#B) U Parentheses no longer set arrays Owned by current effective UID special patterns in any mix; literal – must be first; literal ^ must (#m) G Match in MATCH, MBEGIN, MEND Owned by current effective GID not be first: (#M) uuid >) Don’t use MATCH etc. Owned by given uid (may be ) [:alnum:] An alphanumeric character (#s) a[Mwhms][-+]n Access time in given units Match only at start of test string [:alpha:] An alphabetic character (#e) m[Mwhms][-+]n Modification time in given units Match only at end of test string [:ascii:] A character in the ASCII character set (#qexpr ) c[Mwhms][-+]n Inode change time in given units expr is a a set of glob qualifiers (below) [:blank:] A space or tab ^ Negate following qualifiers [:cntrl:] A control character Glob qualifiers (in parentheses after file name pattern): Toggle following links (first one turns on) [:digit:] A decimal digit / M Directory Mark directories [:graph:] A printable character other than whitespace F Nonempty directory; for empty use (/^F) T Mark directories, links, special files [:lower:] A lower case letter . N Plain file Whole pattern expands to empty if no match [:print:] A printable character @ D Symbolic link Leading dots may be matched [:punct:] A punctuation character = n Socket Sort numbers numerically [:space:] Any whitespace character p o[nLlamcd] Name pipe (FIFO) Order by given code (may repeat) [:upper:] An upper case letter * O[nLlamcd] Executable plain file Order by reverse of given code [:xdigit:] A hexadecimal digit % [num ] Special file Select num th th file in current order %b [num1,num2 ] Block special file Select num1th to num2 th th file (as arrays) Extended patterns (option EXTENDED_GLOB must be set): %c :X Character special file History modifier X ; may have more ^ pat pat Anything that doesn’t match pat r Readable by owner (N.B. not current user) Time units are Month, week, hour, minute, second. pat1 pat2 pat2 ^ Match pat1 then anything other than pat2 Order codes are name (default), size, link count, access time, w Writeable by owner ~ pat1 pat2 pat2 pat2 Anything matching pat1 but not pat2 modification time, inode change time, directory depth. 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 Pattern matching (globbing)
Basic patterns:
KSH_GLOB operators (patterns may contain | for alternatives): @( pat pat) Group patterns pat pat) *( pat Zero or more occurrences of +( pat pat) pat One or more occurrences of pat pat) ?( Zero or one occurrences of pat !( pat pat) Anything but the pattern pat
Page 4 Options Set options with setopt, unset with unsetopt. Asterisk indicates on by default for native zsh. *ALIASES Expand aliases ALL_EXPORT Export all variables to environment *ALWAYS_LAST_PROMPT Completion lists after prompt ALWAYS_TO_END On completion go to end of word *APPEND_HISTORY History appends to existing file AUTO_CD Directory as command does cd AUTO_CONTINUE Jobs are continued when disowned *AUTO_LIST List ambiguous completions *AUTO_MENU Menu complete after two tabs AUTO_NAME_DIRS Variables always can be %~ abbrevs *AUTO_PARAM_KEYS Magic completion for parameters *AUTO_PARAM_SLASH $dirname completes with / AUTO_PUSHD cd uses directory stack too *AUTO_REMOVE_SLASH Trailing / in completion removed AUTO_RESUME cmd can resume job %cmd *BAD_PATTERN Errors on pattern syntax; else literal *BANG_HIST ! style history allowed *BARE_GLOB_QUAL Glob qualifiers with bare parens BASH_AUTO_LIST List completions on second tab *BEEP Beep on all errors *BG_NICE Background jobs at lower priority BRACE_CCL X{ab} expands to Xa Xb BSD_ECHO No echo escapes unles -e given *CASE_GLOB Glob case sensitively C_BASES Output hexadecimal with 0x CDABLE_VARS cd var works if $var is directory CHASE_DOTS Resolve .. in cd CHASE_LINKS Resolve symbolic links in cd *CHECK_JOBS Check jobs before exiting shell *CLOBBER Allow redirections to overwrite COMPLETE_ALIASES Completion uses unexpanded aliases COMPLETE_IN_WORD Completion works inside words CORRECT Correct spelling of commands
Zsh Reference Card CORRECT_ALL CSH_JUNKIE_HISTORY CSH_JUNKIE_LOOPS CSH_JUNKIE_QUOTES CSH_NULLCMD CSH_NULL_GLOB DVORAK EMACS *EQUALS ERR_EXIT ERR_RETURN *EVAL_LINE_NO *EXEC EXTENDED_GLOB EXTENDED_HISTORY *FLOW_CONTROL *FUNCTION_ARGZER0 *GLOB *GLOBAL_EXPORT *GLOBAL_RCS GLOB_ASSIGN GLOB_COMPLETE GLOB_DOTS GLOB_SUBST *HASH_CMDS *HASH_DIRS *HASH_LIST_ALL HIST_ALLOW_CLOBBER *HIST_BEEP HIST_EXPIRE_DUPS_ FIRST HIST_FIND_NO_DUPS HIST_IGNORE_ALL_ DUPS HIST_IGNORE_DUPS HIST_IGNORE_SPACE HIST_NO_FUNCTIONS
HIST_NO_STORE HIST_REDUCE_BLANKS HIST_SAVE_NO_DUPS HIST_VERIFY *HUP IGNORE_BRACES IGNORE_EOF INC_APPEND_HISTORY INTERACTIVE INTERACTIVE_ COMMENTS KSH_ARRAYS KSH_AUTOLOAD KSH_GLOB KSH_OPTION_PRINT KSH_TYPESET *LIST_AMBIGUOUS *LIST_BEEP LIST_PACKED LIST_ROWS_FIRST *LIST_TYPES LOCAL_OPTIONS LOCAL_TRAPS LOGIN LONG_LIST_JOBS MAGIC_EQUAL_SUBST MAIL_WARNING MARK_DIRS MENU_COMPLETE MONITOR *MULTIOS *NOMATCH History search finds once only *NOTIFY Remove all earlier duplicate lines NULL_GLOB Remove duplicate of previous line NUMERIC_GLOB_SORT Don’t store lines starting with space OCTAL_ZEROES
Correct spelling of all arguments Single ! for previous command list; end for do...done No newlines in quotes Redirections with no commands fail One glob must succeed, failures go Dvorak keyboard for correction Same as bindkey -e path/to Expand =cmd to path / /cmd Exit shell on nonzero status Return from function instead $LINENO counts inside eval code Execute commands See globbing section above Timestamps saved to history file Use ^S / ^Q ^Q style flow control $0 in function is its name Use globbing as described above Exported variables not made local Execute /etc/z* files var =* =* expands, assigns array Patterns are active in completion Patterns may match leading dots Substituted characters may glob Store command location for speed Store for all commands in dir Store all on first completion On clobber error, up arrow to retry Beep when going beyond history Duplicate history entries lost first
Don’t store shell functions
Version 4.2 Don’t store history and fc Trim multiple insgnificant blanks Remove duplicates when saving Show ! history line for editing Send SIGHUP to proceses on exit } expansions Don’t use {a,b Ignore ^D (stty eof char) Save history line by line Shell is interactive # on interactive line for comment Indexing etc. for arrays like ksh Function file includes function name See globbing above Show all options plus on or off No word splitting in typeset etc. List completions when ambiguous Beep on ambiguous completion More compact completion lists List completions across File types listed in completion Options reset on function return Traps reset on function return Shell is login shell More verbose listing of jobs Special expansion after all = Warn if mail file timestamp changed Append / to globbed directories Cycle through ambiguous matches Shell has job control enabled Multiple redirections are special Error if glob fails to match Asynchronous job control messages Failed globs are removed from line Numbers in globs sorted numerically Leading zeros in integers force octal
Page 5 OVERSTRIKE PATH_DIRS POSIX_BUILTINS PRINT_EIGHT_BIT PRINT_EXIT_VALUE PRIVILEGED PROMPT_BANG *PROMPT_CR *PROMPT_PERCENT PROMPT_SUBST PUSHD_IGNORE_DUPS PUSHD_MINUS PUSHD_SILENT PUSHD_TO_HOME RC_EXPAND_PARAM RC_QUOTES *RCS REC_EXACT RESTRICTED RM_STAR_SILENT RM_STAR_WAIT SHARE_HISTORY SH_FILE_EXPANSION SH_GLOB SHIN_STDIN SH_NULL_CMD SH_OPTION_LETTERS *SHORT_LOOPS SH_WORD_SPLIT SINGLE_COMMAND SINGLE_LINE_ZLE SUN_KEYBOARD_HACK TRANSIENT_RPROMPT TRAPS_ASYNC TYPESET_SILENT *UNSET
Zsh Reference Card Start line editor in overstrike mode dir /cmd can be found in $PATH Illogical command behaviour Print all 8bit characters directly Return status printed unless zero Special behaviour on setuid/setgid Special treatment of ! in prompt Prompt always at start of line % escapes expanded in prompts $ expansion etc. in prompts Don’t push dir multiply on stack Reverse sense of – and + in pushd No nonerr messages from pushd pushd with no argument goes to ~ X$array gives Xelt1 Xelt2 etc. '' inside single quotes gives ' Run startup files Exact completion matches are good Shell has restricted capabilities Don’t warn on rm * Wait before asking if rm * is OK Save and restore history per line ~ etc. expansion done early Disables nonextended zsh globs Shell input comes from stdin Commandless redirections like sh Single letter options are like sh for words; list works Split nonarray variables yuckily Execute one command then exit Line editing on single line (bad tty) Unmatched ` at end of line ignored Right prompt goes away after edit Traps may run when waiting Silent on typeset foo Unset variables OK, treat as empty
VERBOSE VI XTRACE ZLE
Output commands to be executed Same as bindkey -v Show trace of execution with $PS4 Line editor used to input lines
Option aliases (native zsh on right):
BRAC BRACE_ E_EX EXPA PAND ND DOT_GLOB HASH_ALL HIST HIST_A _APP PPEN END D HIST_EXPAND LOG MAIL_WARN ONE_CMD PHYSICAL PROM PROMPT PT_V _VAR ARS S STDIN TRACK_ALL
NO_I NO_IGN GNOR ORE_ E_BR BRAC ACES ES GLOB_DOTS HASH_CMDS APP APPEND_ END_HI HIST STOR ORY Y BANG_HIST NO_HIST_NO_FUNCTIONS MAIL_WARNING SINGLE_COMMAND CHASE_LINKS PRO PROMPT_ MPT_SU SUBS BST T SHIN_STDIN HASH_CMDS
Single letter options (used with set as well as setopt):
-0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -B -C -D -E -F -G -H -I -J -K
CORRECT PRINT_EXIT_VALUE NO_BAD_PATTERN NO_NO_MATCH GLOB_DOTS NOTIFY BG_NICE IGNORE_EOF MARK_DIRS AUTO_LIST NO_BEEP NO_CLOBBER PUSHD_TO_HOME PUSHD_SILENT NO_GLOB NULL_GLOB RM_STAR_SILENT IGNORE_BRACES AUTO_CD NO_BANG_HIST
Version 4.2 -L -M -N -O -P -Q -R -S -T -U -V -W -X -Y -Z -a -e -f -g -h -i -k -l -m -n -p -r -s -t -u -v -w -x -y
SUN_KEYBOARD_HACK SINGLE_LINE_ZLE AUTO_PUSHD CORRECT_ALL RC_EXPAND_PARAM PATH_DIRS LONG_LIST_JOBS REC_EXACT CDABLE_VARS MAIL_WARNING NO_PROMPT_CR AUTO_RESUME LIST_TYPES MENU_COMPLETE ZLE ALL_EXPORT ERR_EXIT NO_RCS HIST_IGNORE_SPACE HIST_IGNORE_DUPS INTERACTIVE INTERACTIVE_COMMENTS LOGIN MONITOR NO_EXEC PRIVILEGED RESTRICTED SHIN_STDIN SINGLE_COMMAND NO_UNSET VERBOSE CHASE_LINKS XTRACE SH_WORD_SPLIT Note also -A to set arrays, -b to end option processing, -c to pass a single command, -m to set pattern argument, -o to specify long name (may repeat), s to sort positional parameters.
Page 6
Zsh Reference Card
Expansion Basic forms of expansion in the order they order: !expr History expansion alias Alias expansion <(cmds) Replaced by file with output from cmds =(cmds) Same but can be reread (use for diff) >(cmds) Replaced by file with input to cmds $var Variable substitution ${var } Same but protected, allows more options $(cmds) Replaced by output of cmds `cmds` Older form of same, harder to nest $((expr )) )) Arithmetic result of evaluating expr X {a,b }Y XaY Xby (N.B. does no pattern matching) {1..3} {1..3}Y 1Y X 2y X 3y X X {08..10} {08..10}Y 08 08Y X 09 09y X 10 10y X X ~user , ~dir User home, named dir (dir is var name) /full/path/to/cmd =cmd pattern Glob file names, as above
History expansion:
!! !{!} ! !13 !-2 !cmd !?str !#
Immediately preceding line (all of it) Same but protected, may have args in {} Line just referred to, default !! Line numbered 13 (history shows nos.) Command two before current Last command beginning cmd Last command containing str Current command line so far
Word selectors:
!!:0 !!:1 !!:^ !!:$ !:% !!:2-4 !!:-4
Extract argument 0 (command word) Argument numbered 1 (first cmd arg) Also argument 1 Last command argument Word found by !?str (needs correct line) Word 2 to 4 inclusive Words 0 to 4 inclusive
!!:* !!:2* !!:2-
Words 1 to $ inclusive Words 2 to $ inclusive Words 2 to $1 inclusive
Modifiers on arguments (can omit word selector): Trailing path component removed Only trailing path component left File extension .ext removed Only extension ext left Print result but don’t execute Quote from further substitution Strip one level of quotes Quote and also break at whitespace Convert to all lower case Convert to all upper case Replace string s1 by s2 Same but global Use same s1 and s2 on new target
!!:1:h !!:1:t !!:1:r !!:1:e !!:1:p !!:1:q !!:1:Q !!:1:x !!:1:l !!:1:u !!:1:s/s1/s2 / !!:1:gs/s2 /s2 / !!:1:&
Most modifiers work on variables (e.g ${var:h}) or in glob qualifiers (e.g. *(:h)), the following only work there: ${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 ${var:W:sep :m } Same but words are separated by sep
Version 4.2 %@ %t %B (%b) %D %D{str } %E %i %j %L %l
Time of day in am/pm format St ar ar t ( st sto p) p) b ol old f ac ace mo de de -MM -DD Date as YY , optional strftime spec Clear to end of line Script/function line number ( $LINENO) Number of jobs as listed by jobs Shell depth ( $SHLVL) Login terminal without /dev or
/dev/tty %M %m %N %n %S %s %T %U %u %v %W %w %y %_ %~ %{esc%} %X (. (.tstr .fstr ) %str >
Full host name Host name to first dot or n dots Name of script, function, sourced file Name of user (same as $USERNAME) Start (stop) standout mode Time of day, 24hour format Start (stop) underline mode (patchy support) nth component of $psvar array Date as middleendian MM /DD /YY Date as DAY DD Login terminal without /dev Parser state (continuation lines, debug) Like %/, %d but with tilde substitution Escape sequence esc doesn’t move cursor tstr if test X gives n, else fstr Truncate to n on left, str on left if so Truncate to n on right, str on right if so
Prompt expansion (with PROMPT_PERCENT, on by default); may take a decimal number n (default 0) immediately after the %: (. (.tstr .fstr ): ! Privileged; # uid n; ? Test characters in %X %! %h Current history event number last status n; _ at least n nested constructs; / at least n $PWD %# # if superuser, else % elements; ~ same with ~ subst; D month is n; d day of month is n; %% A single % g effective gid is n; j at least n jobs; L $SHLVL at least n; l at %) A ) (use with %X (. (.tstr .fstr )) least n chars on line so far; S $SECONDS at least n; T hours is n; %* Time in 24hour format with seconds t minutes is n; v at least n components in $psvar; w day of %/ %d $PWD; n gives trailing parts, -n leading week is n (Sunday = 0). %c %. %C Deprecated alternatives, differ by default n %? Return status of last command
Page 7
Zsh Reference Card
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 q Quote result with backslashes qq Quote result with single quotes qqq Quote result with double quotes qqqq Quote result with $'...' Q Strip quotes from result t Output type of variable (see below) u Unique: remove duplicates after first U Upper case result v Include value in result; may have (kv) V Visible representation of special chars w Count words with ${#var } W Same but empty words count X Report parsing errors (normally ignored) z Split to words using shell grammar p Following forms recognize print \escapes j:str: Join words with str between l:x: Pad with spaces on left to width x l:x::s1: Same but pad with repeated s1 l:x::s1::s2: Same but s2 used once before any s1s Parameter flags in parentheses, immediately after left brace: r:x::s1::s2: Pad on right, otherwise same as l forms % Expand %s in result as in prompts s:str: Split to array on occurrences of str @ Array expand even in double quotes S With patterns, search substrings A Create array parameter with ${...=...} I:exp: With patterns, match exp th th occurrence a Array index order, so Oa is reversed B With patterns, include match beginning c } Count characters for ${#var E With patterns, include match end C Capitalize result M With patterns, include matched portion e Do parameter, comand, arith expansion N With patterns, include length of match f Split result to array on newlines R With patterns, include unmatched part (rest) F Join arrays with newlines between elements Delimeters shown as :str : may be any pair of chars or matched i oi or Oi sort case independently parenthses (str ), {str }, [str ], . k For associative array, result is keys
Parameter (Variable) Expansion Basic forms: str will also be expanded; most forms work on words of array separately: ${var } Substitute contents of var , no splitting ${+var } 1 if var is set, else 0 ${var ::-str } $var if nonnull, else str ${var -str } $var if set (even if null) else str ${var := :=str } $var if nonnull, else str and set var to it ${var ::= ::=str } Same but always use str ${var :? :?str } $var if nonnull else error, abort ${var :+ :+str } str if $var is nonnull ${var # pat pat} pat removed from head min match of ${var ## # pat #pat} max match of pat removed from head ${var % pat pat} pat removed from tail min match of ${var %% % pat %pat} pat removed from tail max match of ${var :# : pat #pat} $var unless pat pat matches, then empty ${var / /r } p p p replaced by r One occurrence of ${var // / p /p /r } p replaced by r All occurrences of ${#var } Length of var in words (array) or bytes ${^var } Expand elements like brace expansion ${=var } Split words of result like lesser shells ${~var } Allow globbing, file expansion on result p p ${${var % }# }#q } Apply p % p then #q to $var
Version 4.2 Order of rules: 1. Nested Nested substitu substitution: tion: from inside inside out [3]} [3]} extract word; ${str [2]} [2]} 2. Subscr Subscript ipts: s: ${arr extract character; ${arr [2,4]} [2,4]}, ${str [4,8]} [4,8]} extract range; -1 is last word/char, -2 previous etc. } replaces name with value 3. ${(P)var 4. ¨$array ¨ joins array, may use (j:str :) :) [2,4]}[1]} [2,4]}[1]} 5. Nested Nested subscript subscript e.g. ${${var 6. #, %, / etc. modifications :) :), (F) 7. Join if not joined joined and (j:str 8. Spli Splitt if (s), (z), (z), = 9. Spli Splitt if SH_WORD_SPLIT 10. Apply Apply (u) 11. Apply Apply (o), (O) 12. Apply Apply (e) 13. Apply Apply (l.str .) .), (r.str .) .) 14. If single word word needed for context, join with $IFS[1]. Types shown with (t) have basic type scalar, array, integer, float, assocation, then hyphenseparated words from following list:
local left right_blanks right_zeros lower upper readonly tag export unique hide hideval special
Parameter is local to function Left justified with typeset -L Right justified with typeset -R Right justified with typeset -Z Lower case forced with typeset -l Upper case forced with typeset -u Readonly, typeset -r or readonly Tagged as typeset -t (no special effect) Exported with export, typeset -x Elements unique with typeset -U Variable not special in func ( typeset -h) typeset hides value ( typeset -H) Variable special to shell
Page 8 Parameters (Variables) Parameters set by shell, denotes special to shell (may not be reused except by hiding with typeset h in functions) ! Process ID of last background process # Number of arguments to script or function ARGC Same $ Process ID of main shell process String of single letter options set * Positional parameters argv Same @ Same, but does splitting in double quotes ? Status of last command 0 Name of shell, usually reflects functions _ Last argument of previous command CPUTYPE Machine type (run time) EGID Effective GID (via system call), set if root EUID Effective UID (via system call), set if root ERRNO Last system error number GID Real group ID (via system call), set if root HISTCMD The current history line number HOST The host name LINENO Line number in shell, function LOGNAME Login name (exported by default) MACHTYPE Machine type (compile time) OLDPWD Previous directory OPTARG Argument for option handled by getopts OPTIND Index of positional parameter in getopts OSTYPE Operating system type (compile time) pipestatus Array giving statuses of last pipeline PPID Process ID of parent of main shell PWD Current directory RANDOM A pseudorandom number, repeating SECONDS Seconds since shell started SHLVL Depth of current shell signals Array giving names of signals status Status of last command
Zsh Reference Card TRY_BLOCK_ ERROR TTY TTYIDLE UID USERNAME VENDOR ZSH_NAME ZSH_VERSION
LOGCHECK MAIL Terminal associated with shell if any MAILCHECK Time for which terminal has been idle mailpath : Real user ID (via system call), set if root manpath : Name for $UID, set if root module_path : Operating system vendor (compile time) NULLCMD Base name of command used to start shell path : Version number of shell POSTEDIT PS1, PROMPT, Parameters used by the shell if set: : indicates arrays with prompt corresponding colonseparated paths e.g. cdpath and CDPATH: PS2, PROMPT2 ARGV0 Export to set name of external command PS3, PROMPT3 BAUD Baud rate: compensation for slow terminals PS4, PROMPT4 cdpath : Directories searched for cd target psvar : COLUMNS Width of screen READNULLCMD DIRSTACKSIZE Maximum size of stack for pushd REPORTTIME ENV File to source when started as sh or ksh REPLY FCEDIT Default editor used by fc reply fignore : List of suffixes ignored in file completion RPS1, RPROMPT fpath : Directories to search for autoloading RPS2, histchars History, quick replace, comment chars RPROMPT2 HISTCHARS Same, deprecated SAVEHIST HISTFILE File for reading and writing shell history SPROMPT HISTSIZE Number of history lines kept internally STTY HOME Home directory for ~ and default cd target TERM IFS Characters that separate fields in words TIMEFMT KEYTIMEOUT Time to wait for rest of key seq (1/100 s) TMOUT LANG Locale (usual variable, LC_* override) TMPPREFIX LC_ALL Locale (overrides LANG, LC_*) watch : LC_COLLATE Locale for sorting etc. WATCHFMT LC_CTYPE Locale for character handling WORDCHARS LC_MESSAGES Locale for messages ZBEEP LC_NUMERIC Locale for decimal point, thousands ZDOTDIR LC_TIME Locale for date and time LINES Height of screen LISTMAX Number of completions shown w/o asking In always block, 1 if error in try block
Version 4.2 Interval for checking $watch Mail file to check ( $mailpath overrides) Mail check interval, secs (before prompt) List of files to check for new mail Directories to find manual, used by man Directories for zmodload to find modules Command used if only redirection given Command search path Termcap strings sent to terminal after edit Printed at start of first line of output; see above for escape sequences for all PSs Printed for continuation lines Print within select loop For tracing execution ( xtrace option) Used with %nv in prompts Command used when only input redir given Show report if command takes this long (s) Used to return a value e.g. by read Used to return array value Printed on right of screen for first line Printed on right of screeen for continuation line Max number of history lines saved Prompt when correcting spelling Export with stty arguments to command Type of terminal in use ( xterm etc.) Format for reporting usage with time Send SIGALRM after seconds of inactivity Path prefix for shell’s temporary files List of users or all, notme to watch for Format of reports for $watch Chars considered parts of word by zle String to replace beeps in line editor Used for startup files instead of ~ if set
Page 9 Tests and numeric expressions Usually used after if, while, until or with && or ||, but the status may be useful anywhere e.g. as implicit return status for function.
File tests, e.g. [[ -e file ]]: -a True if file exists -b True if file is block special -c True if file is character special -d True if file is directory -e True if file exists -f True if file is a regular file (not special or directory -g True if file has setgid bit set (mode includes 02000) -h True if file is symbolic link -k True if file has sticky bit set (mode includes 02000) -p True if file is named pipe (FIFO) -r True if file is readable by current process -s True if file has nonzero size -u True if file has setuid bit set (mode includes 04000) -w True if file is writeable by current process -x True if file executable by current process -L True if file is symbolic link -O True if file owned by effective UID of current process -G True if file has effective GID of current process -S True if file is a socket (special communication file) -N True if file has access time no newer than mod time Other single argument tests, e.g. [[ -n str ]]: -n True if str has nonzero length -o True if option str is set -t True if str (number) is open file descriptor -z True if str has zero length
Zsh Reference Card -ef = == != < > -eq -ne -lt -gt -le -ge
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) True if string a does not match pattern b True if string a sorts before string b True if string a sorts after string b True if numerical expressions a and b are equal True if numerical expressions a and b are not equal True if a < b numerically True if a > b numerically True if a ≤ b numerically True if a ≥ b numerically
• • • • • • •
•
<, <=, >, >= ==, != && ||, ^^ ? (ternary operator) : (true/false separator for ternary operator) =, +=, -=, *=, /=, %=, **=, &=, ^=, |=, <<=, >>=, &&=, ^^=, ||= , (as in C, evaluate both sides and return right hand side).
For functions use zmodload -i zsh/mathfunc; functions available are as described in C math library manual: Single floating point argument, return floating point: acos, acosh, asin, asinh, atan (optional second argument like C atan2), atanh, cbrt, ceil, cos, cosh, erf, erfc, exp, expm1, fabs, floor, gamma, j0, j1, lgamma, log, log10, log1p, logb, sin, sinh, sqrt, tan, tanh, y0, y1 Single floating point argument, return integer: ilogb No arguments, return integer: signgam (remember parentheses) Two floating point arguments, return floating point: copysign, fmod, hypot, nextafter One integer, one floating point argument, return floating point: jn, yn One floating point, one integer argument, return floating point: ldexp, scalb Either integer or floating point, return same type: abs Coerce to floating point: float Coerce to integer: int Optional string argument (read/write variable name), return floating point: rand48 Example use: •
Combining expressions: expr is any of the above, or the result of any combination of the following: ( expr ) Group tests ! expr True if expr is false and vice versa exprA && exprB True if both expressions true exprA || exprB True if either expression true For complicated numeric tests use (( expr )) where expr is a numeric expression: status is 1 if expr is nonzero else else 0. Same syntax used in $(( expr )) substitution. Precedences of operators from highest to lowest are: func(arg...), numeric constant (e.g. 3, -4, 3.24, -14.6e-10), var (does not require $ in front unless some substitution e.g. ${#var } is needed, $ is error if var is to be modified) ( expr ) !, ~, ++ (post or preincrement), -- (post or predecrement), unary +, unary •
• •
• • •
Multiple argument tests e.g. [[ a -eq b ]]: numerical ‘ 1*2’ : 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
Version 4.2
• • • •
& ^ | ** (exponentiation) *, /, % binary +, binary <<, >>
• •
•
•
•
• • • •
zmodload -i zsh/mathfunc float x (( x = 26.4 * sqrt(2) )) print $(( log(x)/2 ))
Page 10 Completion Load new completion system with:
Zsh Reference Card
Version 4.2
Command contexts: any command name plus the special contexts: directories
-array-value- Element in array autoload -Uz compinit -braceParameter within ${…} compinit parameter-assignLeft hand side of assignment Configuration: uses styles parameterzstyle context style value … style value -commandWord in command position where context may be a pattern matching the following form: -conditionWord in [[ ... ]] condition :completion:func:completer :cmd :arg :tag -defaultWord with no specific completion in which: -equalWord beginning with equals sign completion -firstTried first, may set _compskip Literal string always used by completion functions -mathInside arithmetic such as (( ... )) func -parameterParameter with bare $ in front Name of directly called widget, blank for contextual completion -redirectWord after redirection operator completer -subscriptMethod of completion e.g. complete; see below Inside parameter subscript cmd -tildeBetween ~ and first / of argument Name of command being completed, or special command context -valueRight hand side of assignment arg Only valid with standard parsing: arg-n for nth argument Tags: option-opt-n for nth argument of option opt accounts For usershosts style tag all-expansions When expanding, everything at once Indication of type of thing to be completed at this point. all-files All files rather than a subset arguments Command arguments Completers (indicates modifiers existing or later completions): arrays Names of array parameters _all_matches Later completers add all matches association-keys Keys of associative arrays _approximate Complete with errors in part so far bookmarks Bookmarks for URLs, ZFTP, etc. _complete Basic completion builtins Names of builtin commands _correct Correct word already typed characters Character classes, stty characters _expand Perform shell expansions colormapids X colormap IDs _expand_alias Expand aliases only colors Names of colors, usually X _history Complete words from shell history commands External commands, subcommands _ignored Reinstate matches omitted contexts Contexts in zstyle _list List on first completion, insert on second corrections Possible approximations, corrections _match Complete using patterns from line cursors X cursor names _menu Menu completion, no menu selection Nothing specific in certain contexts _oldlist Use existing list before generating new one default descriptions Used in format style for matches _prefix Complete ignoring what’s after cursor devices Device special files
Directories
directory-stack Entries in pushd directory stack displays X displays domains Network domain (DNS) names expansions Individual expansions instead of all file-descriptors Numbers of open file descriptors files Generic file matching tag fonts X font names fstypes Files system types for mount etc. functions Shell functions, possibly other types globbed-files Names of files matched by pattern groups UNIX groups history-words Words from shell history hosts Names of network hosts indexes Indexes of arrays jobs Shell jobs interfaces Network interfaces (as from ifconfig) keymaps ZLE keymaps keysyms Names of X keysyms libraries Names of system libraries limits System resource limits local-directories Subdirectories of current directories manuals Names of manual pages mailboxes Email folders maps NIS maps etc. messages Used in format style for messages modifiers X modifiers modules Shell modules etc. my-accounts Own accounts, with usershosts style named-directories Directories named by a parameter names Names of all sorts newsgroups USENET newgroups nicknames Nicknames of NIS maps options Options to commands original Original when correcting, expanding other-accounts Other accounts with usershosts style
Page 11
Zsh Reference Card
auto-description avoid-completer cache-path cache-policy call-command command command-path commands complete completer condition disabled disable-stat domains expand fake fake-files fake-parameters file-patterns file-sort filter force-list format glob global group-name group-order groups hidden hosts hosts-ports Styles (indicates on by default): ignore-line accept-exact Accept exact match even if ambiguous ignore-parents add-space Add a space after expansions ignored-patterns ambiguous Cursor after ambiguous path component insert assign-list PATHstyle list on assignment insert-ids Tags continued:
packages parameters path-directories paths pods ports prefixes printers processes processes-names sequences sessions signals strings styles suffixes tags targets time-zones types urls users values variant visuals warnings widgets windows zsh-options
RPM, Debian etc. packages Names of shell parameters Directories under $cdpath Used with assorted directory paths Perl documentation TCP, UDP prots URL etc. prefixes Names of print queues PIDs Names of processes in killall MH sequences etc. ZFTP sessions etc. System signal names, HUP etc. Assorted strings, e.g. second arg of cd Styles in zstyle Filename extensions Tags used with rpm etc. Targets inside Makefiles Time zones with TZ parameter etc. Assorted types of anything Used with web addresses Names of users Values in lists Used when picking variant of command X visuals Used in the format style for warnings Names of zsh widgets IDs of X windows Shell options
Version 4.2
String for option descs without specific insert-tab Insert TAB if no nonwhitespace yet Avoid completer with _all_matches insertOnly menu complete when no prefix to unambiguous Path to top of various caches insert Function to decide on cache rebuilding keep-prefix Try to keep expandable prefix last-prompt If true, use external (slow) command Return to last editing line if possible list External command to call (+args) Control listing when history completing Override PATH for commands to match list-colors Color specs like LS_COLORS list-grouped Default sys init commands (start etc.) Grouped listing shown more compactly Complete aliases ( _expand_alias) list-packed All matches shown more compactly The list of completers to try (see above) list-prompt Prompt when scrolling completions list-rows-first Increment rows first in lists Delay insertion of matches (_list) Disabled aliases ( _expand_alias) list-suffixes Show ambiguous bits of multiple paths If set, _cvs uses ls instead of zsh/stat list-separator Separates description in verbose list host path path:dir for URLs as files Net domains (/etc/resolv.conf) local : For prefix, suffix in multiple parts mail-directory Directory for mailbox files ( ~/Mail) Add value :desc fake completions match-original Add * when matching ( _match) matcher :names add names in dir Apply match control syntax per tag dir matcher-list Params to complete even if not yet set Apply match control syntax globally pattern:tag generates files with tag max-errors Max errors allowed in approx/correct size, links, time, access, inode, reverse max-matches-width Cols to reserve for matches (not desc) menu In LDAP, attributes for filtering Use menu completion muttrc Just list matches: always or number Alternative for ~/.muttrc numbers Desc string, %d shows specific desc Prefer job numbers instead of name old-list Attempt glob expansion ( _expand) Retain list of matches ( _oldlist) old-matches Global aliases ( _expand_alias) Use old match list ( _all_matches) old-menu Name groups shown together by tag Keep list for meus ( _oldlist) original Order groups shown together by tag Add original match for approx/correct packageset Unix groups, as per /etc/group For arguments of Debian dpkg path Complete but don’t list matches For X colors, path to rgb.txt pine-directory List of host names, as /etc/hosts Directory for PINE mailboxes ports for TCP/UDP ports List of hosts ports : TCP/IP services ( /etc/services) Don’t complete words already present prefix-hidden Hide common prefix e.g. in options prefix-needed parent or pwd: ignore parent dirs Common prefix must by typed by user preserve-prefix Initial file patterns to leave alone If pattern matched, don’t complete All matches at once ( _all_matches) range Range of words in history to consider regular Convert %cmd to unambiguous PID Complete regular aliases
Page 12
Zsh Reference Card
-foo Complete option -foo +foo Complete option +foo -+foo Complete -foo or +foo *-foo Option may occur multiple times -foo-:esg:_comp Option has arg in same word -foo+:msg:_comp Option has arg in same or next word -foo=:msg:_comp Option arg -foo=bar or -foo bar -foo=-:msg:_comp Option arg is -foo=bar only -foo[desc] Option has description desc *:*pat:msg:_comp Complete words up to pat *:*pat::msg:_comp Modify words etc. for args (-goo -boo)-foo -foo excludes -goo, -boo (*)-foo -foo excludes rest args as matches (:)-foo -foo excludes normal args (-)-foo -foo excludes all options !-foo -foo should not be completed *:msg: Show message but don’t complete *:msg:(a b) Matches are listed items *:msg:((a\:dsc)) Matches with descriptions *:msg:->string Array state has string if matched *:msg:{code } Shell code generates matches *:msg:= action Insert dummy argument first *:msg:_comp arg Call _comp with additional args *:msg: _comp arg Call _comp with only given arg -a –set1 -c - … Common and specific completion sets - "(set1)" -c - … Mutually exclusive sets -s Allow combined single letters Using _arguments for parsing standard command arguments: -sw Same, even if option has args Three arguments give argument/option selector, message to -Guess options by using --help output, action to take. Examples: -- -i pat Same, ignoring options matching pat 1:msg:_comp First arg; show msg, exec _comp 1::msg:_comp Same for optional argument Examples of other utility functions: :msg:_comp Arg number inferred from position _alternative \ *:msg:_comp Any of the remaining args (“rest args”) ‘ users:user:_users’\ users:user:_users’\ *::msg:_comp words etc. set to normal args hosts:host:_hosts ‘ hosts:host:_hosts *:::msg:_comp Either users or hosts (tag, description, action) … set to args for this chunk
Version 4.2
Styles continued:
_describe setdesc arr1 --
remote-access
Associate descriptions with completions; arr1 contains completion:description entries
Control remote access for e.g. _cvs remove-all-dups Never complete duplicates in history select-prompt Prompt shown in menu selection select-scroll Lines to scroll in menu selection separate-sections Manual sections used as part of tag show-completer Show progress of completers as msg single-ignored Control _ignore when single match sort Override sorting of matches special-dirs Add . and .. to file list squeeze-slashes fo//ba is fo/ba not fo/*/ba stop Pause before looping shell history strip-comments Remove display name from email addr subst-globs-only Only take expansions from globbing substitute When expanding, first try subst suffix Only expand path with no /suffix tag-order Preference order for tags in context urls Determine where URLs are taken from use-cache Control caching for various commands use-compctl Use comptlstyle completions use-perl Use simpler Perl code for _make users List of user names users-hosts @host possibilities List of user users-hosts-ports List of user port @host port : verbose Verbose output e.g. option descriptions word Line changes based on current word
_message text-msg Don’t complete, just output text-msg
_multi_parts sep array sep array Complete by parts with separator sep , $array contains full matches.
_path_files Complete files including partial paths; _files is smart front end; options -f all files (default), -g pat matching pat (with _files maybe directories too), -/ directories only, -W dirs paths in which files are found, -F files files to ignore, overrides ignored-patterns
_sep_parts arr1 sep1 arr2 sep2 … Elements from arr1, then separator, then elements from arr2 , etc.
_values -s sep desc sep desc spec1 spec2 spec2 … … Complete multiple values separated by sep ; values are given by specs, each of which is similar to _arguments option spec without leading _wanted thing expl my m ‘y things’\ compadd mything1 mything2 … Typical way of adding completions mything1 etc. with tag things and description my things; expl should be local variable. Use single tag, tag, c.f. _tags and _requested _tags tag1 tag2 _requested tag Implement loops over different tags
_all_labels tag expl descr compcommand _next_label tag expl descr Implement loops over different labels for each _requested tag
Page 13
Zsh Reference Card
end-of-list exch exchan ange ge-p -poi oint nt-a -and nd-m -mar ark k execute-last-named-cmd execute-name-cmd accept-and-hold a € expand-cmd-path accept-and-infer-next-history expand-history accept-and-menu-complete expand-or-complete accept-line ^M ^M ^M expand-or-complete-prefix accept-line accept-line-and-d -and-down-hi own-history story ^O expand-word argument-base forward-char backward-char ^B forward-word backward-delete-char ^H get-line backward-delete-word gosmacs-transpose-chars backward-kill-line history-beginning-searchbackward-kill-word ^W backward backward-word b € history-beginning-searchbeep forward beginning-of-buffer-or-history €< history-incremental-searchbeginning-of-history backward beginning-of-line ^A history-incremental-searchbeginning-of-line-hist forward capitalize-word €c hist histor oryy-se sear arch ch-b -bac ackw kwa ard clear-screen ^L ^L ^L hist histor oryy-se sear arch ch-f -for orwa war rd complete-word infer-next-history copy-prev-word €^_ insert-last-word copy-prev-shell-word kill-buffer copy-region-as-kill €w kill-line delete-char kill-region delete-char-or-list ^D kill-whole-line delete-word kill-word describe-key-briefly list-choices digit-argument 0 € .. 1..9 list-expand down-case-word €l magic-space down-history ^n down menu-complete down-line-or-history ^n j menu-expand-or-complete down-line-or-search neg-argument emacs-backward-word overwrite-mode emacs-forward-word pound-insert end-of-buffer-or-history €> push-input end-of-history push-line end-of-line ^E push-line-or-edit end-of-line-hist Zsh line editor (zle) Builtin widgets, emacs binding, vicmd binding, viins binding; € denotes escape key:
Version 4.2 ^X^X ^X^X z€ x € ! € ^I
^I
^X* ^F €f g €
^R ^Xr ^S ^Xs €p €n ^x^n €_ ^X^K ^K ^U €d ^ €d ^d ^Xg ^G
€ ^X^O # q €
^d ^G
quoted-insert quote-line quote-region recursive-edit redisplay redo reset-prompt reverse-menu-complete run-help self-insert self-insert-unmeta send-break set-mark-command spell-word set-local-history transpose-chars transpose-words undefined-key undo universal-argument up-case-word up-history up-line-or-history up-line-or-search vi-add-eol vi-add-next vi-backward-blank-word vi-backward-char vi-backward-delete-char vi-backward-kill-word vi-backward-word vi-beginning-of-line vi-caps-lock-panic vi-change vi-change-eol vi-change-whole-line vi-cmd-mode vi-delete vi-delete-char vi-d vi-dig igit it-o -orr-be begi ginn nnin ingg-of of-l -lin ine e vi-down-line-or-history
^V ' € €” ^R
h € ... €^M ^G ^@ s €
^R
...
^T €t ^_ u € ^p
^p k
up
A a B h ^H left X ^H ^W b c C S ^XV
€ d x 0 +
Page 14
Zsh Reference Card
Builtin widgets cont.:
vi-end-of-line vi-fetch-history vi-find-next-char vi-find-next-char-skip vi-find-prev-char vi-find-prev-char-skip vi-first-non-blank vi-forward-blank-word vi-forward-blank-word-end vi-forward-char vi-forward-word vi-forward-word-end vi-goto-column vi-goto-mark vi-goto-mark-line vi-h vi-his isto tory ry-s -sea earc rchh-ba back ckw ward ard vi-history-search-forward vi-indent vi-insert vi-insert-bol vi-join vi-kill-eol vi-kill-line vi-match-bracket vi-open-line-above vi-open-line-below vi-oper-swap-case vi-pound-insert vi-put-after vi-put-before vi-quoted-insert vi-repeat-change vi-repeat-find vi-repeat-search vi-replace vi-replace-chars vi-rev-repeat-find vi-rev-repeat-search vi-set-buffer vi-set-mark
$ G ^X^F f t F T ^ W E l w e €| | `
vi-substitute vi-swap-case vi-undo-change vi-unindent vi-up-line-or-history vi-yank vi-yank-eol vi-yank-whole-line what-cursor-position where-is rght which-command yank yank-pop
˙
/ ? > i I ^X^J J D ^U ^X^B % O o
P p ^V . ; N R r , “ m
Version 4.2 s ~ u < y Y ^X= ? € ^y y €
Special parameters inside userdefined widgets; indicates readonly: BUFFER Entire editing buffer BUFFERLINES Number of screen lines for full buffer CONTEXT start, cont, select, vared CURSOR Index of cursor position into $BUFFER CUTBUFFER Last item to be killed HISTNO Currently history line being retrieved KEYMAP Currently selected keymap KEYS Keys typed to invoke current widget killring Array of previously killed items, can resize LASTSEARCH Last search string in interactive search LASTWIDGET Last widget to be executed LBUFFER Part of buffer left of cursor MARK Index of mark position into $BUFFER NUMERIC Numeric argument passed with widget PENDING Number of bytes still to be read PREBUFFER Input already read (no longer being edited) PREDISPLAY Text to display before editable buffer POSTDISPLAY Text to display after editable buffer RBUFFER Part of buffer starting from cursor WIDGET Name of widget being executed WIDGETFUNC Name of function implementing $WIDGET WIDGETSTYLE Implementation style of completion widget
Special characters in bindkey strings: \a Bell (alarm) \b Backspace \e, \E Escape \f Form feed \n Newline \r Carriage return \t Tab (horizontal) \v Tab (vertical) \nnn Octal character e.g \081 \xnn Hexadecimal character eg. \x41 \Mx , \M-x Set 8th bit in character \Cx , \C-x Control character e.g. \C-a ^x Control character e.g. ^a (same as ^A) ^? Delete \\ Single backslash Keymaps:
emacs viins vicmd .safe
Like Emacs editor Like Vi editor in insert mode Like Vi editor in command mode Emergency keymap, not modifiable