You are on page 1of 14

Page1

1 2 3 4 5 6 7 8 9 10 11 12 13 Contents Generalinformation,references Grammar(shellsyntax) Patterns:globbingandqualifiers Options Optionscont.;optionaliases,singleletteroptions Expansion:basicforms,history,prompts Expansion:variables:formsandflags Shellvariables:setbyshell,usedbyshell Testoperators;numericexpressions Completion:contexts,completers,tags Completioncont.:tagscont,styles Completioncont.:stylescont,utilityfunctions Zshlineeditor(zle)

ZshReferenceCard
generalinpart1,concentratingonbashandzshinparts2and3. Thecontentsofthebookareasfollows;wherenotedwithpage referencestothiscardtheyexpandonthebriefhintshere. Part1(IntroducingtheShell)containsthefollowingchapters: 1 IntroductiontoShells 2 UsingShellFeaturesTogether 3 MoreShellFeatures (c.f.page2) Part2(Usingbashandzsh)containsthefollowingchapters: 4 EnteringandEditingtheCommandLine (c.f.pages6and13) 5 StartingtheShell (c.f.pages4and5) 6 MoreAboutShellHistory (c.f.pages6and8) 7 Prompts (c.f.page6) 8 FilesandDirectories (c.f.page9) 9 PatternMatching (c.f.page3) 10 Completion (c.fpages10through12) 11 JobsandProcesses (c.f.page6)

Version4.2
programs,linkstoexternalresources,andaglossary. Zshmanualpages Toaccessdocumentationfromwithintheshell,usetheman commandwithoneofthefollowingarguments: Introduction,startupandshutdown zsh Syntax,redirection,functions,jobs,tests zshmisc Expansionandsubstitution zshexpn Parameters(variables) zshparam Optionstotheshell zshoptions Shellbuiltincommands zshbuiltins Thelineeditor,excludingcompletion zshzle Thelowlevelcompletionfacitilities zshcompwid Thenewcompletionsystem(morereadable) zshcompsys Theoldcompletionsystem(deprecated) zshcompctl zshmodules Modulesloadablewithzmodload FunctionsforusingrawTCPviabuiltins zshtcpsys FunctionsforusingFTPviabuiltins zshzftpsys Contributedfunctionsforzleetc. zshcontrib Everythinginonelargemanualpage zshall Mailinglists zsh-users@zsh.org:users'mailinglistforgeneralquestions andtips;tojoin,mail zsh-users-subscribe@zsh.org. zsh-workers@zsh.org:mailinglistforbugreports,patches anddevelopers'discussions;tojoin,mail zsh-workers-subscribe@zsh.org.Newdeveloperswith someUnix/Linuxexperiencearewelcome.

Notes Thedescriptionshereareverybrief.Youwillnotbeabletolearn shellsyntaxfromthem;seethevariousreferencesbelow.In particularthecompletionsystemisextremelyrichandthe descriptionsofitsutilityfunctionsarethebarestmemoryjoggers. Thestartandendofeachsectionisalignedwithpageboundaries, soyoucanprintoutonlythepartsyouwanttoreferto. References Zshmanual:Suppliedwiththeshell:shouldbeinstalledinUnix manualpageandinfoformats.TexinfogeneratesPSorPDF; availableasseparatedocbundlefromsameplaceastheshell.

Part3(ExtendingtheShell)containsthefollowingchapters: http://zsh.sourceforge.net/:Sitewithmuch 12 Variables informationaboutzsh,includingHTMLmanualandamoreuser (c.f.pages7and8) friendlyguidetotheshell,aswellastheFAQ. 13 ScriptingandFunctions (c.f.page2) Zshwiki:http://www.zshwiki.org/:Extensiblezshweb 14 WritingEditorCommands pageswrittenbyusers. (c.fpage13) 15 WritingCompletionFunctions FromBashtoZShell:ConqueringtheCommandLine,by (c.f.pages10through12) OliverKiddle,JerryPeekandPeterStephenson,Apress,ISBN1 590593766.IntroductiontointeractiveuseofUnixshellsin ThethreeappendicescontainshortdescriptionsofstandardUnix

Page2
Grammar Listisanysequenceofsublists(includingjustone) separatedby;ornewline.;andnewlinearealways interchangeableexceptin;;. Sublistisanysequenceofpipelines(includingjustone) connectedby&&or||. Pipelineisanysequenceofsimplecommandsconnectedby|.

ZshReferenceCard
if listi1; then[;] listt1; [ elif listi2; then listt2; ] [ else listt3; ] fi Iflisti1istrue,executelistt1;elseiflisti2istrue executelistt2;elseexecutelistt3. } Nonportablealternative.

Version4.2

select name [ in word ]; do list; done Printmenuofwords,readanumber,setnametoselectedword, executelistuntilendofinput.Portablebutrare.

for name [ in word ] (list[;]) do list; Executelistinasubshell(anewprocesswherenothingthat Commandiseitherasimplecommand(acommandword) done followedoptionallybyword oroneofthespecialcommands Executelistwithvariablenamesettoeachofword inturn happensaffectsthecurrentshell). below. Ifin isomittedthepositionalparametersareused. {list[;]} Executelist(nonewprocess:simplyseparateslistfromwhats Wordisanytextthatproducesasinglewordwhenexpanded; for name in word ; { list } aroundandcantakeredirections). word isanynumberoftheseseparatedbywhitespace. foreach name ( word ) [;] list; function nameword {[;] list[;] } Nameisashellidentifier:analphabeticcharacteror_followed end nameword () {[;] list[;] } byanysequenceofalphanumericcharactersor_. Nonportablealternativeforms. Definefunctionnamednameword;executeslistwhenrun; [] indicatesoptional;dotsontheirownlinemeanany numberofrepetitionsofthelinejustabove. Boldtextistobetypedliterally. Statustrueorfalseisdeterminedby:forcommands,the returnstatus;forpipelinesthelastcommand;forsubliststhelast pipeline;forliststhelastsublistthatwasexecuted. sublist1 && sublist2 [ && sublist3 ] Executesublistsuntiloneisfalse. while listw; do listd; done Whilelistwistrueexecutelistd. until listu; do listd; done Nonportable:whilelistuisnottrueexecutelistd. repeat numexp; do list; done repeat numexp sublist Nonportable:repeatlistorsublist numexp times. runningnamewordword1makesword1availableas$1 etc.infunctionbody.listmustendwith[;]ornewlinefor portability.nameword canberepeatedtodefinemultiple functions(rare,nonportable). time [ pipeline ] Reporttimeforpipelineifgivenelsetotalsforcurrentshell. [[ condition ]] Evaluatecondition(seebelow),givesstatustrueorfalse.

case word in [(] pattern1[|pattern2...]) [;] list ;; sublist1 || sublist2 [ || sublist2 ] esac Executesublists untiloneistrue.Notestringsof Trymatchingwordagainsteverypatterninturnuntilsuccess. &&sublistscancontain||sublistsandviceversa;theyareparsed Executethecorrespondinglist.;& insteadof&& meansfall lefttoright. throughtonextlist. command1 | command2 [ | command3 ] Executecommand1,sendingitsoutputtotheinputof command2,andsoon(apipeline). case word { [(] pattern1[|pattern2...]) [;] list ;;

Page3
Basicpatterns: * ? [class] [^class] <num1-num2> Patternmatching(globbing)

ZshReferenceCard
KSH_GLOBoperators(patternsmaycontain|foralternatives): Grouppatterns @(pat) *(pat) Zeroormoreoccurrencesofpat Oneormoreoccurrencesofpat +(pat) ?(pat) Zerooroneoccurrencesofpat Anythingbutthepatternpat !(pat)

Version4.2

Setgid S Stickybit t fspec Haschmodstylepermissionsspec Anystring Evaluationstringreturnstruestatus estring Anycharacter +cmd Samebutcmdmustbealphanumericor_ Anysinglecharacterfromclass Devicenumberdev(major*256+minor) ddev Anysinglecharacternotfromclass l[-+]num Linkcountis(lessthan,greaterthan)num Anynumberbetweennum1andnum2 OwnedbycurrenteffectiveUID GlobbingflagswithEXTENDED_GLOB: U <-num2>from0;<num1->toinfinity. OwnedbycurrenteffectiveGID Matchcaseinsensitively G (#i) Directoriestoanylevel **/ Lowercasematchesuppercase uuid Ownedbygivenuid(maybe<name>) (#l) Grouppatterns (pat1) Matchcasesensitively (#I) ggid Ownedbygivengid(maybe<name>) (pat1|pat2) pat1orpat2 (anynumberof|s) (#b) Parenthesessetmatch,mbegin,mend a[Mwhms][-+]n Accesstimeingivenunits(seebelow) Parenthesesnolongersetarrays (#B) m[Mwhms][-+]n Modificationtimeingivenunits Characterclassesmaycontainanycharacterorthefollowing MatchinMATCH,MBEGIN,MEND c[Mwhms][-+]n Inodechangetimeingivenunits specialpatternsinanymix;literalmustbefirst;literal^must (#m) Sizeingivenunits(seebelow) L[kmp][-+]n (#M) DontuseMATCHetc. notbefirst: Negatefollowingqualifiers ^ Matchwithnumapproximations (#anum) a-b Acharacterintherangeatob Togglefollowinglinks(firstoneturnson) Matchonlyatstartofteststring (#s) Analphanumericcharacter [:alnum:] Markdirectories M Matchonlyatendofteststring (#e) Analphabeticcharacter [:alpha:] Markdirectories,links,specialfiles T (#qexpr) exprisaasetofglobqualifiers(below) AcharacterintheASCIIcharacterset [:ascii:] Wholepatternexpandstoemptyifnomatch N Aspaceortab [:blank:] Leadingdotsmaybematched D Globqualifiers(inparenthesesafterfilenamepattern): Acontrolcharacter [:cntrl:] Sortnumbersnumerically n Directory / Adecimaldigit [:digit:] Orderbygivencode(asbelow;mayrepeat) F Nonemptydirectory;foremptyuse(/^F) o[nLlamcd] Aprintablecharacterotherthanwhitespace [:graph:] Orderbyreverseofgivencode O[nLlamcd] Plainfile . Alowercaseletter [:lower:] [num] Selectnumthfileincurrentorder Symboliclink @ Aprintablecharacter [:print:] Selectnum1thtonum2thfile(asarrays) [num1,num2] Socket = Apunctuationcharacter [:punct:] :X HistorymodifierX;mayhavemore Namepipe(FIFO) p Anywhitespacecharacter [:space:] Executableplainfile * TimeunitsareMonth,week,hour,minute,second;defaultisday. Anuppercaseletter [:upper:] Specialfile % Sizeunitsarekilobytes,megabytesor512byteblocks(p);default Ahexadecimaldigit [:xdigit:] Blockspecialfile %b isbytes;uppercasemeansthesameaslowercase. Characterspecialfile %c Ordercodesarename(default),size,linkcount,accesstime, Extendedpatterns(optionEXTENDED_GLOBmustbeset): Readablebyowner(N.B.notcurrentuser) modificationtime,inodechangetime,directorydepth. r Anythingthatdoesntmatchpat ^pat Writeablebyowner pat1^pat2 Matchpat1thenanythingotherthanpat2 w Executablebyowner x Anythingmatchingpat1butnotpat2 pat1~pat2 Readablebymembersoffilesgroup A X# ZeroormoreoccurrencesofelementX Writeablebymembersoffilesgroup I OneormoreoccurrencesofelementX X## Executablebymembersoffilesgroup E Worldreadable R Worldwriteable W Worldexecutable X Setuid s

Page4
Options Setoptionswithsetopt,unsetwithunsetopt.Asterisk indicatesonbydefaultfornativezsh. Expandaliases *ALIASES Exportallvariablestoenvironment ALL_EXPORT *ALWAYS_LAST_PROMPT Completionlistsafterprompt Oncompletiongotoendofword ALWAYS_TO_END Historyappendstoexistingfile *APPEND_HISTORY AUTO_CD Directoryascommanddoescd AUTO_CONTINUE Jobsarecontinuedwhendisowned Listambiguouscompletions *AUTO_LIST Menucompleteaftertwotabs *AUTO_MENU Variablesalwayscanbe%~abbrevs AUTO_NAME_DIRS Magiccompletionforparameters *AUTO_PARAM_KEYS *AUTO_PARAM_SLASH $dirname completeswith/ AUTO_PUSHD cdusesdirectorystacktoo *AUTO_REMOVE_SLASH Trailing/incompletionremoved AUTO_RESUME cmdcanresumejob%cmd Errorsonpatternsyntax;elseliteral *BAD_PATTERN *BANG_HIST !stylehistoryallowed Globqualifierswithbareparens *BARE_GLOB_QUAL Listcompletionsonsecondtab BASH_AUTO_LIST Beeponallerrors *BEEP Backgroundjobsatlowerpriority *BG_NICE BRACE_CCL X{ab}expandstoXa Xb BSD_ECHO Noechoescapesunles-egiven Globcasesensitively *CASE_GLOB C_BASES Outputhexadecimalwith0x CDABLE_VARS cd varworksif$varisdirectory CHASE_DOTS Resolve..incd CHASE_LINKS Resolvesymboliclinksincd Checkjobsbeforeexitingshell *CHECK_JOBS Allowredirectionstooverwrite *CLOBBER Completionusesunexpandedaliases COMPLETE_ALIASES Completionworksinsidewords COMPLETE_IN_WORD Correctspellingofcommands CORRECT Correctspellingofallarguments CORRECT_ALL CSH_JUNKIE_HISTORY Single!forpreviouscommand CSH_JUNKIE_LOOPS list; endfordo...done Nonewlinesinquotes CSH_JUNKIE_QUOTES Redirectionswithnocommandsfail CSH_NULLCMD

ZshReferenceCard
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 Oneglobmustsucceed,failuresgo Dvorakkeyboardforcorrection Sameasbindkey -e Expand=cmdto/path/to/cmd Exitshellonnonzerostatus Returnfromfunctioninstead $LINENOcountsinsideevalcode Executecommands Seeglobbingsectionabove Timestampssavedtohistoryfile Use^S/^Qstyleflowcontrol $0infunctionisitsname Useglobbingasdescribedabove Exportedvariablesnotmadelocal Execute/etc/z*files var=*expands,assignsarray Patternsareactiveincompletion Patternsmaymatchleadingdots Substitutedcharactersmayglob Storecommandlocationforspeed Storeforallcommandsindir Storeallonfirstcompletion Onclobbererror,uparrowtoretry Beepwhengoingbeyondhistory Duplicatehistoryentrieslostfirst 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 *NOTIFY NULL_GLOB NUMERIC_GLOB_SORT OCTAL_ZEROES Historysearchfindsonceonly OVERSTRIKE Removeallearlierduplicatelines PATH_DIRS Removeduplicateofpreviousline POSIX_BUILTINS Dontstorelinesstartingwithspace PRINT_EIGHT_BIT Dontstoreshellfunctions PRINT_EXIT_VALUE Dontstorehistoryandfc PRIVILEGED Trimmultipleinsgnificantblanks PROMPT_BANG Removeduplicateswhensaving *PROMPT_CR Show!historylineforediting *PROMPT_PERCENT SendSIGHUPtoprocesesonexit PROMPT_SUBST Dontuse{a,b}expansions PUSHD_IGNORE_DUPS PUSHD_MINUS Ignore^D(stty eofchar) Savehistorylinebyline PUSHD_SILENT Shellisinteractive PUSHD_TO_HOME

Version4.2
#oninteractivelineforcomment Indexingetc.forarrayslikeksh Functionfileincludesfunctionname Seeglobbingabove Showalloptionsplusonoroff Nowordsplittingintypesetetc. Listcompletionswhenambiguous Beeponambiguouscompletion Morecompactcompletionlists Listcompletionsacross Filetypeslistedincompletion Optionsresetonfunctionreturn Trapsresetonfunctionreturn Shellisloginshell Moreverboselistingofjobs Specialexpansionafterall= Warnifmailfiletimestampchanged Append/toglobbeddirectories Cyclethroughambiguousmatches Shellhasjobcontrolenabled Multipleredirectionsarespecial Errorifglobfailstomatch Asynchronousjobcontrolmessages Failedglobsareremovedfromline Numbersinglobssortednumerically Leadingzerosinintegersforceoctal Startlineeditorinoverstrikemode dir/cmdcanbefoundin$PATH Illogicalcommandbehaviour Printall8bitcharactersdirectly Returnstatusprintedunlesszero Specialbehaviouronsetuid/setgid Specialtreatmentof!inprompt Promptalwaysatstartofline %escapesexpandedinprompts $expansionetc.inprompts Dontpushdirmultiplyonstack Reversesenseofand+inpushd Nononerrmessagesfrompushd pushdwithnoargumentgoesto~

Page5
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 VERBOSE VI XTRACE ZLE X$arraygivesXelt1Xelt2etc. ''insidesinglequotesgives' Runstartupfiles Exactcompletionmatchesaregood Shellhasrestrictedcapabilities Dontwarnonrm * Waitbeforeaskingifrm *isOK Saveandrestorehistoryperline ~etc.expansiondoneearly Disablesnonextendedzshglobs Shellinputcomesfromstdin Commandlessredirectionslikesh Singleletteroptionsarelikesh for words; listworks Splitnonarrayvariablesyuckily Executeonecommandthenexit Lineeditingonsingleline(badtty) Unmatched`atendoflineignored Rightpromptgoesawayafteredit Trapsmayrunwhenwaiting Silentontypeset foo UnsetvariablesOK,treatasempty Outputcommandstobeexecuted Sameasbindkey -v Showtraceofexecutionwith$PS4 Lineeditorusedtoinputlines

ZshReferenceCard
Singleletteroptions(usedwithsetaswellassetopt): -0 CORRECT -1 PRINT_EXIT_VALUE -2 NO_BAD_PATTERN -3 NO_NO_MATCH -4 GLOB_DOTS -5 NOTIFY -6 BG_NICE -7 IGNORE_EOF -8 MARK_DIRS -9 AUTO_LIST -B NO_BEEP -C NO_CLOBBER -D PUSHD_TO_HOME -E PUSHD_SILENT -F NO_GLOB -G NULL_GLOB -H RM_STAR_SILENT -I IGNORE_BRACES -J AUTO_CD -K NO_BANG_HIST -L SUN_KEYBOARD_HACK -M SINGLE_LINE_ZLE -N AUTO_PUSHD -O CORRECT_ALL -P RC_EXPAND_PARAM -Q PATH_DIRS -R LONG_LIST_JOBS -S REC_EXACT -T CDABLE_VARS -U MAIL_WARNING -V NO_PROMPT_CR -W AUTO_RESUME -X LIST_TYPES -Y MENU_COMPLETE -Z ZLE -a ALL_EXPORT -e ERR_EXIT -f NO_RCS -g HIST_IGNORE_SPACE -h HIST_IGNORE_DUPS -i INTERACTIVE -k INTERACTIVE_COMMENTS

Version4.2
-l LOGIN -m MONITOR -n NO_EXEC -p PRIVILEGED -r RESTRICTED -s SHIN_STDIN -t SINGLE_COMMAND -u NO_UNSET -v VERBOSE -w CHASE_LINKS -x XTRACE -y SH_WORD_SPLIT Notealso-Atosetarrays,-btoendoptionprocessing,-cto passasinglecommand,-mtosetpatternargument,-otospecify longname(mayrepeat),stosortpositionalparameters.

Optionaliases(nativezshonright): BRACE_EXPAND NO_IGNORE_BRACES DOT_GLOB GLOB_DOTS HASH_ALL HASH_CMDS HIST_APPEND APPEND_HISTORY HIST_EXPAND BANG_HIST LOG NO_HIST_NO_FUNCTIONS MAIL_WARN MAIL_WARNING ONE_CMD SINGLE_COMMAND PHYSICAL CHASE_LINKS PROMPT_VARS PROMPT_SUBST STDIN SHIN_STDIN TRACK_ALL HASH_CMDS

Page6
Expansion Basicformsofexpansionintheordertheyorder: Historyexpansion !expr Aliasexpansion alias Replacedbyfilewithoutputfromcmds <(cmds) =(cmds) Samebutcanbereread(usefordiff) >(cmds) Replacedbyfilewithinputtocmds Variablesubstitution $var Samebutprotected,allowsmoreoptions ${var} Replacedbyoutputofcmds $(cmds) Olderformofsame,hardertonest `cmds` Arithmeticresultofevaluatingexpr $((expr)) X{a,b}Y XaY Xby (N.B.doesnopatternmatching) X{1..3}Y X1Y X2y X3y X{08..10}Y X08Y X09y X10y Userhome,nameddir(dirisvarname) ~user, ~dir /full/path/to/cmd =cmd Globfilenames,asabove pattern Historyexpansion: !! !{!} ! !13 !-2 !cmd !?str !# Wordselectors: !!:0 !!:1 !!:^ !!:$ !:% !!:2-4 !!:-4 !!:* !!:2* !!:2-

ZshReferenceCard
Modifiersonarguments(canomitwordselector): Trailingpathcomponentremoved !!:1:h Onlytrailingpathcomponentleft !!:1:t Fileextension.extremoved !!:1:r Onlyextensionextleft !!:1:e Printresultbutdontexecute !!:1:p Quotefromfurthersubstitution !!:1:q Striponelevelofquotes !!:1:Q Quoteandalsobreakatwhitespace !!:1:x Converttoalllowercase !!:1:l Converttoalluppercase !!:1:u !!:1:s/s1/s2/ Replacestrings1bys2 !!:1:gs/s2/s2/ Samebutglobal !!:1:& Usesames1ands2onnewtarget Mostmodifiersworkonvariables(e.g${var:h})oringlob qualifiers(e.g.*(:h)),thefollowingonlyworkthere: ${var:fm} Repeatmodifiermtillstopschanging SamebutnomorethanNtimes ${var:F:N:m} ${var:wm} Applymodifermtowordsofstring ${var:W:sep:m} Samebutwordsareseparatedbysep %M %m %N %n %S %s %T %U %u %v %W %w %y %_ %~ %{esc%} %X(.tstr.fstr) %<str< %>str>

Version4.2
Fullhostname Hostnametofirstdotorndots Nameofscript,function,sourcedfile Nameofuser(sameas$USERNAME) Start(stop)standoutmode Timeofday,24hourformat Start(stop)underlinemode(patchysupport) nthcomponentof$psvararray DateasmiddleendianMM/DD/YY DateasDAY DD Loginterminalwithout/dev Parserstate(continuationlines,debug) Like%/,%dbutwithtildesubstitution Escapesequenceescdoesntmovecursor tstriftestXgivesn,elsefstr Truncatetononleft,stronleftifso Truncatetononright,stronrightifso

Immediatelyprecedingline(allofit) Samebutprotected,mayhaveargsin{} Linejustreferredto,default!! Linenumbered13(historyshowsnos.) Commandtwobeforecurrent Lastcommandbeginningcmd Lastcommandcontainingstr Currentcommandlinesofar

Testcharactersin%X(.tstr.fstr):!Privileged; #uidn;? laststatusn;_atleastnnestedconstructs;/atleastn$PWD elements;~samewith~subst;Dmonthisn;ddayofmonthisn; Promptexpansion(withPROMPT_PERCENT,onbydefault);may geffectivegidisn;jatleastnjobs;L$SHLVLatleastn;lat leastncharsonlinesofar;S $SECONDSatleastn;Thoursisn; takeadecimalnumbern(default0)immediatelyafterthe%: tminutesisn;vatleastncomponentsin$psvar;wdayof Currenthistoryeventnumber %! %h weekisn(Sunday=0). %# #ifsuperuser,else% Asingle% A)(usewith%X(.tstr.fstr)) Timein24hourformatwithseconds $PWD;ngivestrailingparts,-nleading Deprecatedalternatives,differbydefaultn Returnstatusoflastcommand Timeofdayinam/pmformat Start(stop)boldfacemode DateasYY-MM-DD,optionalstrftimespec Cleartoendofline Script/functionlinenumber($LINENO) Numberofjobsaslistedbyjobs Shelldepth($SHLVL) Loginterminalwithout/devor /dev/tty

%% %) %* %/ %c Extractargument0(commandword) Argumentnumbered1(firstcmdarg) %? Alsoargument1 %@ Lastcommandargument %B Wordfoundby!?str(needscorrectline) %D Word2to4inclusive %E Words0to4inclusive %i Words1to$inclusive %j Words2to$inclusive %L Words2to$1inclusive %l

%d %. %C %t (%b) %D{str}

Page7
Parameter(Variable)Expansion Basicforms:strwillalsobeexpanded;mostformsworkon wordsofarrayseparately: ${var} Substitutecontentsofvar,nosplitting 1ifvarisset,else0 ${+var} ${var:-str} $varifnonnull,elsestr ${var-str} $varifset(evenifnull)elsestr ${var:=str} $varifnonnull,elsestrandsetvartoit ${var::=str} Samebutalwaysusestr ${var:?str} $varifnonnullelseerror,abort ${var:+str} strif$varisnonnull minmatchofpatremovedfromhead ${var#pat} ${var##pat} maxmatchofpatremovedfromhead minmatchofpatremovedfromtail ${var%pat} ${var%%pat} maxmatchofpatremovedfromtail ${var:#pat} $varunlesspatmatches,thenempty Oneoccurrenceofpreplacedbyr ${var/p/r} ${var//p/r} Alloccurrencesofpreplacedbyr Lengthofvarinwords(array)orbytes ${#var} Expandelementslikebraceexpansion ${^var} Splitwordsofresultlikelessershells ${=var} Allowglobbing,fileexpansiononresult ${~var} ${${var%p}#q} Apply%pthen#qto$var

ZshReferenceCard

Version4.2

Quoteresultwithbackslashes Orderofrules: q Quoteresultwithsinglequotes 1. Nestedsubstitution:frominsideout qq Quoteresultwithdoublequotes qqq 2. Subscripts:${arr[3]}extractword;${str[2]} qqqq Quoteresultwith$'...' extractcharacter;${arr[2,4]},${str[4,8]} Stripquotesfromresult Q extractrange;-1islastword/char,-2previousetc. Outputtypeofvariable(seebelow) t 3. ${(P)var}replacesnamewithvalue Unique:removeduplicatesafterfirst u 4. $arrayjoinsarray,mayuse(j:str:) Uppercaseresult U 5. Nestedsubscripte.g.${${var[2,4]}[1]} v Includevalueinresult;mayhave(kv) 6. #,%,/etc.modifications Visiblerepresentationofspecialchars V 7. Joinifnotjoinedand(j:str:),(F) w Countwordswith${#var} 8. Splitif(s),(z),(z),= Samebutemptywordscount W 9. SplitifSH_WORD_SPLIT Reportparsingerrors(normallyignored) X 10. Apply(u) Splittowordsusingshellgrammar z 11. Apply(o),(O) p Followingformsrecognizeprint\escapes 12. Apply(e) j:str: Joinwordswithstrbetween 13. Apply(l.str.),(r.str.) Padwithspacesonlefttowidthx l:x: 14. Ifsinglewordneededforcontext,joinwith$IFS[1]. l:x::s1: Samebutpadwithrepeateds1 Samebuts2usedoncebeforeanys1s l:x::s1::s2: Typesshownwith(t)havebasictypescalar,array, r:x::s1::s2: Padonright,otherwisesameaslforms integer,float,assocation,thenhyphenseparatedwords s:str: Splittoarrayonoccurrencesofstr fromfollowinglist: Withpatterns,searchsubstrings S Parameterislocaltofunction local I:exp: Withpatterns,matchexpthoccurrence left Leftjustifiedwithtypeset -L Withpatterns,includematchbeginning B right_blanks Rightjustifiedwithtypeset -R Withpatterns,includematchend E Parameterflagsinparentheses,immediatelyafterleftbrace: right_zeros Rightjustifiedwithtypeset -Z Withpatterns,includematchedportion M % Expand%sinresultasinprompts lower Lowercaseforcedwithtypeset -l Withpatterns,includelengthofmatch N Arrayexpandevenindoublequotes @ upper Uppercaseforcedwithtypeset -u Withpatterns,includeunmatchedpart(rest) readonly A Createarrayparameterwith${...=...} R Readonly,typeset -rorreadonly Delimetersshownas:str:maybeanypairofcharsormatched tag a Arrayindexorder,soOaisreversed Taggedastypeset -t(nospecialeffect) parenthses(str),{str},[str],<str>. c Countcharactersfor${#var} export Exportedwithexport,typeset -x Capitalizeresult C unique Elementsuniquewithtypeset -U Doparameter,comand,arithexpansion e hide Variablenotspecialinfunc(typeset -h) Splitresulttoarrayonnewlines f hideval typesethidesvalue(typeset -H) Joinarrayswithnewlinesbetweenelements F Variablespecialtoshell special i oiorOisortcaseindependently Forassociativearray,resultiskeys k Lowercaseresult L n onorOnsortnumerically Sortintoascendingorder o Sortintodescendingorder O Interpretresultasparametername,getvalue P

Page8
Parameters(Variables) Parameterssetbyshell,denotesspecialtoshell(maynotbe reusedexceptbyhidingwithtypesethinfunctions) ProcessIDoflastbackgroundprocess ! Numberofargumentstoscriptorfunction # Same ARGC ProcessIDofmainshellprocess $ Stringofsingleletteroptionsset Positionalparameters * Same argv Same,butdoessplittingindoublequotes @ Statusoflastcommand ? Nameofshell,usuallyreflectsfunctions 0 Lastargumentofpreviouscommand _ Machinetype(runtime) CPUTYPE EffectiveGID(viasystemcall),setifroot EGID EffectiveUID(viasystemcall),setifroot EUID Lastsystemerrornumber ERRNO RealgroupID(viasystemcall),setifroot GID Thecurrenthistorylinenumber HISTCMD Thehostname HOST Linenumberinshell,function LINENO Loginname(exportedbydefault) LOGNAME Machinetype(compiletime) MACHTYPE Previousdirectory OLDPWD Argumentforoptionhandledbygetopts OPTARG Indexofpositionalparameteringetopts OPTIND Operatingsystemtype(compiletime) OSTYPE Arraygivingstatusesoflastpipeline pipestatus ProcessIDofparentofmainshell PPID Currentdirectory PWD Apseudorandomnumber,repeating RANDOM Secondssinceshellstarted SECONDS Depthofcurrentshell SHLVL Arraygivingnamesofsignals signals Statusoflastcommand status Inalwaysblock,1iferrorintryblock TRY_BLOCK_ ERROR Terminalassociatedwithshellifany TTY Timeforwhichterminalhasbeenidle TTYIDLE RealuserID(viasystemcall),setifroot UID USERNAME VENDOR ZSH_NAME ZSH_VERSION

ZshReferenceCard
PS1, PROMPT, prompt PS2, PROMPT2 PS3, PROMPT3 PS4, PROMPT4 psvar : Parametersusedbytheshellifset::indicatesarrayswith correspondingcolonseparatedpathse.g.cdpathandCDPATH: READNULLCMD REPORTTIME Exporttosetnameofexternalcommand ARGV0 Baudrate:compensationforslowterminals REPLY BAUD reply cdpath : Directoriessearchedforcdtarget RPS1, RPROMPT Widthofscreen COLUMNS RPS2, DIRSTACKSIZE Maximumsizeofstackforpushd RPROMPT2 ENV Filetosourcewhenstartedasshorksh SAVEHIST FCEDIT Defaulteditorusedbyfc SPROMPT Listofsuffixesignoredinfilecompletion fignore : STTY Directoriestosearchforautoloading fpath : TERM History,quickreplace,commentchars histchars TIMEFMT Same,deprecated HISTCHARS TMOUT Fileforreadingandwritingshellhistory HISTFILE Numberofhistorylineskeptinternally TMPPREFIX HISTSIZE HOME Homedirectoryfor~anddefaultcdtarget watch : Charactersthatseparatefieldsinwords WATCHFMT IFS Timetowaitforrestofkeyseq(1/100s) KEYTIMEOUT WORDCHARS LANG Locale(usualvariable,LC_*override) ZBEEP ZDOTDIR LC_ALL Locale(overridesLANG,LC_*) Localeforsortingetc. LC_COLLATE Localeforcharacterhandling LC_CTYPE Localeformessages LC_MESSAGES Localefordecimalpoint,thousands LC_NUMERIC Localefordateandtime LC_TIME Heightofscreen LINES Numberofcompletionsshownw/oasking LISTMAX LOGCHECK Intervalforchecking$watch MAIL Mailfiletocheck($mailpathoverrides) Mailcheckinterval,secs(beforeprompt) MAILCHECK Listoffilestocheckfornewmail mailpath : manpath : Directoriestofindmanual,usedbyman module_path : Directoriesforzmodloadtofindmodules Commandusedifonlyredirectiongiven NULLCMD Commandsearchpath path : Termcapstringssenttoterminalafteredit POSTEDIT Namefor$UID,setifroot Operatingsystemvendor(compiletime) Basenameofcommandusedtostartshell Versionnumberofshell

Version4.2
Printedatstartoffirstlineofoutput;see aboveforescapesequencesforallPSs Printedforcontinuationlines Printwithinselectloop Fortracingexecution(xtraceoption) Usedwith%nvinprompts Commandusedwhenonlyinputredirgiven Showreportifcommandtakesthislong(s) Usedtoreturnavaluee.g.byread Usedtoreturnarrayvalue Printedonrightofscreenforfirstline Printedonrightofscreeenforcontinuation line Maxnumberofhistorylinessaved Promptwhencorrectingspelling Exportwithsttyargumentstocommand Typeofterminalinuse(xtermetc.) Formatforreportingusagewithtime SendSIGALRMaftersecondsofinactivity Pathprefixforshellstemporaryfiles Listofusersorall, notmetowatchfor Formatofreportsfor$watch Charsconsideredpartsofwordbyzle Stringtoreplacebeepsinlineeditor Usedforstartupfilesinsteadof~ifset

Page9

ZshReferenceCard

Version4.2

Trueifstringadoesnotmatchpatternb != Testsandnumericexpressions :(true/falseseparatorforternaryoperator) Trueifstringasortsbeforestringb Usuallyusedafterif,while,untilorwith&&or||,butthestatus < =,+=,-=,*=,/=,%=,**=,&=,^=,|=,<<=,>>=, Trueifstringasortsafterstringb maybeusefulanywheree.g.asimplicitreturnstatusforfunction. > &&=,^^=,||= -eq Trueifnumericalexpressionsaandbareequal , (asinC,evaluatebothsidesandreturnrighthand Trueifnumericalexpressionsaandbarenotequal -ne Filetests,e.g.[[ -e file ]]: side). -lt Trueifa<bnumerically -a Trueiffileexists Trueifa>bnumerically -gt Trueiffileisblockspecial -b Forfunctionsusezmodload -izsh/mathfunc;functions -le Trueifabnumerically -c Trueiffileischaracterspecial availableareasdescribedinCmathlibrarymanual: Trueifabnumerically -ge Trueiffileisdirectory -d Singlefloatingpointargument,returnfloatingpoint: -e Trueiffileexists acos,acosh,asin,asinh,atan(optionalsecond Trueiffileisaregularfile(notspecialordirectory Combiningexpressions:exprisanyoftheabove,ortheresultof -f argumentlikeCatan2),atanh,cbrt,ceil,cos, -g Trueiffilehassetgidbitset(modeincludes02000) anycombinationofthefollowing: cosh,erf,erfc,exp,expm1,fabs,floor, Grouptests ( expr ) Trueiffileissymboliclink -h gamma,j0,j1,lgamma,log,log10,log1p, Trueifexprisfalseandviceversa -k Trueiffilehasstickybitset(modeincludes02000) ! expr logb,sin,sinh,sqrt,tan,tanh,y0,y1 exprA && exprB Trueifbothexpressionstrue Trueiffileisnamedpipe(FIFO) -p Singlefloatingpointargument,returninteger:ilogb exprA || exprB Trueifeitherexpressiontrue -r Trueiffileisreadablebycurrentprocess Noarguments,returninteger:signgam(remember Trueiffilehasnonzerosize -s parentheses) -u Trueiffilehassetuidbitset(modeincludes04000) Forcomplicatednumerictestsuse(( expr ))whereexpris Twofloatingpointarguments,returnfloatingpoint: Trueiffileiswriteablebycurrentprocess anumericexpression:statusis1ifexprisnonzeroelse0.Same -w copysign,fmod,hypot,nextafter -x Trueiffileexecutablebycurrentprocess syntaxusedin$(( expr ))substitution.Precedencesof Oneinteger,onefloatingpointargument,returnfloating Trueiffileissymboliclink -L operatorsfromhighesttolowestare: point:jn,yn -O TrueiffileownedbyeffectiveUIDofcurrent func(arg...),numericconstant(e.g.3,-4,3.24, Onefloatingpoint,oneintegerargument,returnfloating process -14.6e-10),var(doesnotrequire$infrontunless point:ldexp,scalb -G TrueiffilehaseffectiveGIDofcurrentprocess somesubstitutione.g.${#var}isneeded,$iserrorif Eitherintegerorfloatingpoint,returnsametype:abs Trueiffileisasocket(specialcommunicationfile) -S varistobemodified) Coercetofloatingpoint:float -N Trueiffilehasaccesstimenonewerthanmodtime ( expr ) Coercetointeger:int !,~,++(postorpreincrement),--(postor Optionalstringargument(read/writevariablename), Othersingleargumenttests,e.g.[[ -n str ]]: predecrement),unary+,unaryreturnfloatingpoint:rand48 Trueifstrhasnonzerolength -n & Exampleuse: -o Trueifoptionstrisset ^ zmodload -i zsh/mathfunc Trueifstr(number)isopenfiledescriptor -t | float x -z Trueifstrhaszerolength **(exponentiation) (( x = 26.4 * sqrt(2) )) *,/,% print $(( log(x)/2 )) Multipleargumenttestse.g.[[ a -eq b ]]:numerical binary+,binaryexpressionsmaybequotedformulaee.g.1*2: <<,>> -nt Trueiffileaisnewerthanfileb <,<=,>,>= Trueiffileaisolderthanfileb -ot ==,!= -ef Trueifaandbrefertosamefile(i.e.arelinked) && Trueifstringamatchespatternb = ||,^^ Samebutmoremodern(andstillnotoftenused) == ?(ternaryoperator)

Page10
Completion Loadnewcompletionsystemwith: autoload -Uz compinit compinit Configuration:usesstyles zstyle context style value wherecontextmaybeapatternmatchingthefollowingform: :completion:func:completer:cmd:arg:tag inwhich: completion Literalstringalwaysusedbycompletionfunctions func Nameofdirectlycalledwidget,blankforcontextualcompletion completer Methodofcompletione.g.complete;seebelow cmd Nameofcommandbeingcompleted,orspecialcommandcontext arg Onlyvalidwithstandardparsing:arg-nfornthargument option-opt-nfornthargumentofoptionopt tag Indicationoftypeofthingtobecompletedatthispoint. -braceparameter-assignparameter-command-condition-default-equal-first-math-parameter-redirect-subscript-tilde-value-

ZshReferenceCard
Parameterwithin${} Lefthandsideofassignment Wordincommandposition Wordin[[ ... ]]condition Wordwithnospecificcompletion Wordbeginningwithequalssign Triedfirst,mayset_compskip Insidearithmeticsuchas(( ... )) Parameterwithbare$infront Wordafterredirectionoperator Insideparametersubscript Between~andfirst/ofargument Righthandsideofassignment files fonts fstypes functions globbed-files groups history-words hosts indexes jobs interfaces keymaps keysyms libraries limits local-directories manuals mailboxes maps messages modifiers modules my-accounts named-directories names newsgroups nicknames options original other-accounts Tagscontinued: packages parameters path-directories paths pods ports prefixes printers processes processes-names

Version4.2
Genericfilematchingtag Xfontnames Filessystemtypesformountetc. Shellfunctions,possiblyothertypes Namesoffilesmatchedbypattern UNIXgroups Wordsfromshellhistory Namesofnetworkhosts Indexesofarrays Shelljobs Networkinterfaces(asfromifconfig) ZLEkeymaps NamesofXkeysyms Namesofsystemlibraries Systemresourcelimits Subdirectoriesofcurrentdirectories Namesofmanualpages Emailfolders NISmapsetc. Usedinformatstyleformessages Xmodifiers Shellmodulesetc. Ownaccounts,withusershostsstyle Directoriesnamedbyaparameter Namesofallsorts USENETnewgroups NicknamesofNISmaps Optionstocommands Originalwhencorrecting,expanding Otheraccountswithusershostsstyle RPM,Debianetc.packages Namesofshellparameters Directoriesunder$cdpath Usedwithassorteddirectorypaths Perldocumentation TCP,UDPprots URLetc.prefixes Namesofprintqueues PIDs Namesofprocessesinkillall

Tags: accounts all-expansions all-files arguments arrays association-keys bookmarks Completers(indicatesmodifiersexistingorlatercompletions): builtins characters _all_matches Latercompletersaddallmatches colormapids Completewitherrorsinpartsofar _approximate colors Basiccompletion _complete commands Correctwordalreadytyped _correct contexts Performshellexpansions _expand corrections _expand_alias Expandaliasesonly cursors Completewordsfromshellhistory _history default Reinstatematchesomitted _ignored descriptions Listonfirstcompletion,insertonsecond _list devices Completeusingpatternsfromline _match directories Menucompletion,nomenuselection _menu Useexistinglistbeforegeneratingnewone directory-stack _oldlist displays Completeignoringwhatsaftercursor _prefix domains Commandcontexts:anycommandnameplusthespecialcontexts: expansions file-descriptors -array-value- Elementinarray

Forusershostsstyle Whenexpanding,everythingatonce Allfilesratherthanasubset Commandarguments Namesofarrayparameters Keysofassociativearrays BookmarksforURLs,ZFTP,etc. Namesofbuiltincommands Characterclasses,sttycharacters XcolormapIDs Namesofcolors,usuallyX Externalcommands,subcommands Contextsinzstyle Possibleapproximations,corrections Xcursornames Nothingspecificincertaincontexts Usedinformatstyleformatches Devicespecialfiles Directories Entriesinpushddirectorystack Xdisplays Networkdomain(DNS)names Individualexpansionsinsteadofall Numbersofopenfiledescriptors

Page11
sequences sessions signals strings styles suffixes tags targets time-zones types urls users values variant visuals warnings widgets windows zsh-options MHsequencesetc. ZFTPsessionsetc. Systemsignalnames,HUPetc. Assortedstrings,e.g.secondargofcd Stylesinzstyle Filenameextensions Tagsusedwithrpmetc. TargetsinsideMakefiles TimezoneswithTZparameteretc. Assortedtypesofanything Usedwithwebaddresses Namesofusers Valuesinlists Usedwhenpickingvariantofcommand Xvisuals Usedintheformatstyleforwarnings Namesofzshwidgets IDsofXwindows Shelloptions

ZshReferenceCard
fake-files dir:namesaddnamesindir fake-parameters Paramstocompleteevenifnotyetset file-patterns pattern:taggeneratesfileswithtag size,links,time,access,inode,reverse file-sort InLDAP,attributesforfiltering filter force-list Justlistmatches:alwaysornumber format Descstring,%dshowsspecificdesc glob Attemptglobexpansion(_expand) global Globalaliases(_expand_alias) Namegroupsshowntogetherbytag group-name Ordergroupsshowntogetherbytag group-order groups Unixgroups,asper/etc/group Completebutdontlistmatches hidden hosts Listofhostnames,as/etc/hosts hosts-ports Listofhosts:portsforTCP/UDP Dontcompletewordsalreadypresent ignore-line ignore-parents parentorpwd:ignoreparentdirs ignored-patterns Ifpatternmatched,dontcomplete insert Allmatchesatonce(_all_matches) insert-ids Convert%cmdtounambiguousPID InsertTABifnononwhitespaceyet insert-tab Onlymenucompletewhennoprefixto insertunambiguous insert Trytokeepexpandableprefix keep-prefix Returntolasteditinglineifpossible last-prompt Controllistingwhenhistorycompleting list list-colors ColorspecslikeLS_COLORS Groupedlistingshownmorecompactly list-grouped Allmatchesshownmorecompactly list-packed Promptwhenscrollingcompletions list-prompt list-rows-first Incrementrowsfirstinlists Showambiguousbitsofmultiplepaths list-suffixes Separatesdescriptioninverboselist list-separator local host:path:dirforURLsasfiles mail-directory Directoryformailboxfiles(~/Mail) match-original Add*whenmatching(_match) Applymatchcontrolsyntaxpertag matcher Applymatchcontrolsyntaxglobally matcher-list Maxerrorsallowedinapprox/correct max-errors max-matches-width Colstoreserveformatches(notdesc) Usemenucompletion menu muttrc numbers old-list old-matches old-menu original packageset path pine-directory ports prefix-hidden prefix-needed preserve-prefix range regular Stylescontinued: remote-access remove-all-dups select-prompt select-scroll separate-sections show-completer single-ignored sort special-dirs squeeze-slashes stop strip-comments subst-globs-only substitute suffix tag-order urls use-cache use-compctl use-perl users users-hosts users-hosts-ports verbose word

Version4.2
Alternativefor~/.muttrc Preferjobnumbersinsteadofname Retainlistofmatches(_oldlist) Useoldmatchlist(_all_matches) Keeplistformeus(_oldlist) Addoriginalmatchforapprox/correct ForargumentsofDebiandpkg ForXcolors,pathtorgb.txt DirectoryforPINEmailboxes TCP/IPservices(/etc/services) Hidecommonprefixe.g.inoptions Commonprefixmustbytypedbyuser Initialfilepatternstoleavealone Rangeofwordsinhistorytoconsider Completeregularaliases Controlremoteaccessfore.g._cvs Nevercompleteduplicatesinhistory Promptshowninmenuselection Linestoscrollinmenuselection Manualsectionsusedaspartoftag Showprogressofcompletersasmsg Control_ignorewhensinglematch Overridesortingofmatches Add.and..tofilelist fo//baisfo/banotfo/*/ba Pausebeforeloopingshellhistory Removedisplaynamefromemailaddr Onlytakeexpansionsfromglobbing Whenexpanding,firsttrysubst Onlyexpandpathwithno/suffix Preferenceorderfortagsincontext DeterminewhereURLsaretakenfrom Controlcachingforvariouscommands Usecomptlstylecompletions UsesimplerPerlcodefor_make Listofusernames Listofuser@hostpossibilities Listofuser@host:port Verboseoutpute.g.optiondescriptions Linechangesbasedoncurrentword

Styles(indicatesonbydefault): Acceptexactmatchevenifambiguous accept-exact Addaspaceafterexpansions add-space Cursorafterambiguouspathcomponent ambiguous assign-list PATHstylelistonassignment auto-description Stringforoptiondescswithoutspecific avoid-completer Avoidcompleterwith_all_matches Pathtotopofvariouscaches cache-path Functiontodecideoncacherebuilding cache-policy Iftrue,useexternal(slow)command call-command Externalcommandtocall(+args) command command-path OverridePATHforcommandstomatch Defaultsysinitcommands(startetc.) commands complete Completealiases(_expand_alias) Thelistofcompleterstotry(seeabove) completer Delayinsertionofmatches(_list) condition disabled Disabledaliases(_expand_alias) Ifset,_cvsuseslsinsteadofzsh/stat disable-stat domains Netdomains(/etc/resolv.conf) expand Forprefix,suffixinmultipleparts fake Addvalue:descfakecompletions

Page12
Using_arguments forparsingstandardcommandarguments: Threeargumentsgiveargument/optionselector,messageto output,actiontotake.Examples: 1:msg:_comp Firstarg;showmsg,exec_comp Sameforoptionalargument 1::msg:_comp Argnumberinferredfromposition :msg:_comp Anyoftheremainingargs(restargs) *:msg:_comp *::msg:_comp wordsetc.settonormalargs settoargsforthischunk *:::msg:_comp -foo Completeoption-foo +foo Completeoption+foo -+foo Complete-fooor+foo Optionmayoccurmultipletimes *-foo -foo-:esg:_comp Optionhasarginsameword -foo+:msg:_comp Optionhasarginsameornextword -foo=:msg:_comp Optionarg-foo=baror-foo bar -foo=-:msg:_comp Optionargis-foo=baronly -foo[desc] Optionhasdescriptiondesc *:*pat:msg:_comp Completewordsuptopat *:*pat::msg:_comp Modifywordsetc.forargs (-goo -boo)-foo -fooexcludes-goo,-boo (*)-foo -fooexcludesrestargsasmatches (:)-foo -fooexcludesnormalargs (-)-foo -fooexcludesalloptions !-foo -fooshouldnotbecompleted Showmessagebutdontcomplete *:msg:<space> Matchesarelisteditems *:msg:(a b) *:msg:((a\:dsc)) Matcheswithdescriptions *:msg:->string Arraystatehasstringifmatched Shellcodegeneratesmatches *:msg:{code} Insertdummyargumentfirst *:msg:= action *:msg:_comp arg Call_compwithadditionalargs *:msg: _comp arg Call_compwithonlygivenarg -a set1 -c - Commonandspecificcompletionsets - "(set1)" -c - Mutuallyexclusivesets Allowcombinedsingleletters -s Same,evenifoptionhasargs -sw -Guessoptionsbyusing--help Same,ignoringoptionsmatchingpat -- -i pat

ZshReferenceCard
Examplesofotherutilityfunctions: _alternative \ users:user:_users \ hosts:host:_hosts Eitherusersorhosts(tag,description,action) _describe setdesc arr1 -Associatedescriptionswithcompletions;arr1 contains completion:descriptionentries _message text-msg Dontcomplete,justoutputtext-msg _multi_parts sep array Completebypartswithseparatorsep,$arraycontainsfull matches. _path_files Completefilesincludingpartialpaths;_filesissmartfrontend; options-fallfiles(default),-g patmatchingpat(with _filesmaybedirectoriestoo),-/directoriesonly,-W dirs pathsinwhichfilesarefound,-F filesfilestoignore, overridesignored-patterns _sep_parts arr1 sep1 arr2 sep2 Elementsfromarr1,thenseparator,thenelementsfromarr2, etc. _values -s sep desc spec1 spec2 Completemultiplevaluesseparatedbysep;valuesaregivenby specs,eachofwhichissimilarto_argumentsoptionspec withoutleading_wanted thing expl my things \ compadd mything1 mything2 Typicalwayofaddingcompletionsmything1etc.withtag things anddescriptionmy things;explshouldbelocal variable.Usesingletag,c.f._tagsand_requested _tags tag1 tag2 _requested tag Implementloopsoverdifferenttags

Version4.2

_all_labels tag expl descr compcommand _next_label tag expl descr Implementloopsoverdifferentlabelsforeach_requestedtag

Page13
Zshlineeditor(zle) Builtinwidgets,emacsbinding,vicmdbinding,viinsbinding; denotesescapekey: accept-and-hold a accept-and-infer-next-history accept-and-menu-complete accept-line ^M ^M ^M accept-line-and-down-history ^O argument-base backward-char ^B backward-delete-char ^H backward-delete-word backward-kill-line backward-kill-word ^W backward-word b beep beginning-of-buffer-or-history < beginning-of-history beginning-of-line ^A beginning-of-line-hist capitalize-word c clear-screen ^L ^L ^L complete-word copy-prev-word ^_ copy-prev-shell-word copy-region-as-kill w delete-char delete-char-or-list ^D delete-word describe-key-briefly digit-argument 0.. 1..9 down-case-word l down-history ^n down-line-or-history ^n j down down-line-or-search emacs-backward-word emacs-forward-word end-of-buffer-or-history > end-of-history end-of-line ^E end-of-line-hist end-of-list exchange-point-and-mark ^X^X

ZshReferenceCard
execute-last-named-cmd execute-name-cmd expand-cmd-path expand-history expand-or-complete expand-or-complete-prefix expand-word forward-char forward-word get-line gosmacs-transpose-chars history-beginning-searchbackward history-beginning-searchforward history-incremental-searchbackward history-incremental-searchforward history-search-backward history-search-forward infer-next-history insert-last-word kill-buffer kill-line kill-region kill-whole-line kill-word list-choices list-expand magic-space menu-complete menu-expand-or-complete neg-argument overwrite-mode pound-insert push-input push-line push-line-or-edit quoted-insert quote-line quote-region recursive-edit z x ! ^I ^X* f g ^F ^I 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-digit-or-beginning-of-line vi-down-line-or-history Builtinwidgetscont.: vi-end-of-line vi-fetch-history vi-find-next-char vi-find-next-char-skip vi-find-prev-char

Version4.2
^R ^R

h ... ^M ^G ^@ s ^T t ^_ u ^p ^p k

...

^R ^Xr ^S ^Xs p n ^x^n _ ^X^K ^K ^U d ^d ^d ^Xg ^G

up

A a B h ^H left X ^H ^W b c C S ^XV d x 0 +

^d ^G

^X^O q ^V '

$ G ^X^F f t F

Page14
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-history-search-backward 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 vi-substitute vi-swap-case vi-undo-change vi-unindent vi-up-line-or-history vi-yank vi-yank-eol vi-yank-whole-line T ^ W E l w e | | ` / ? > i I ^X^J J D ^X^B % O o P p . ; N R r , m s ~ u < y Y

ZshReferenceCard
what-cursor-position where-is which-command yank rght yank-pop ^X= ? ^y y \Mx,\M-x \Cx,\C-x ^x ^? \\ Keymaps: emacs viins vicmd .safe

Version4.2
Set8thbitincharacter Controlcharactere.g. \C-a Controlcharactere.g.^a(sameas^A) Delete Singlebackslash LikeEmacseditor LikeVieditorininsertmode LikeVieditorincommandmode Emergencykeymap,notmodifiable

^U

^V

Specialparametersinsideuserdefinedwidgets;indicates readonly: Entireeditingbuffer BUFFER Numberofscreenlinesforfullbuffer BUFFERLINES CONTEXT start,cont,select,vared CURSOR Indexofcursorpositioninto$BUFFER Lastitemtobekilled CUTBUFFER Currentlyhistorylinebeingretrieved HISTNO Currentlyselectedkeymap KEYMAP Keystypedtoinvokecurrentwidget KEYS Arrayofpreviouslykilleditems,canresize killring Lastsearchstringininteractivesearch LASTSEARCH Lastwidgettobeexecuted LASTWIDGET Partofbufferleftofcursor LBUFFER MARK Indexofmarkpositioninto$BUFFER Numericargumentpassedwithwidget NUMERIC Numberofbytesstilltoberead PENDING Inputalreadyread(nolongerbeingedited) PREBUFFER Texttodisplaybeforeeditablebuffer PREDISPLAY Texttodisplayaftereditablebuffer POSTDISPLAY Partofbufferstartingfromcursor RBUFFER Nameofwidgetbeingexecuted WIDGET WIDGETFUNC Nameoffunctionimplementing$WIDGET Implementationstyleofcompletionwidget WIDGETSTYLE Specialcharactersinbindkeystrings: Bell(alarm) \a Backspace \b Escape \e,\E Formfeed \f Newline \n Carriagereturn \r Tab(horizontal) \t Tab(vertical) \v \nnn Octalcharactere.g\081 \xnn Hexadecimalcharactereg.\x41

Examplesofkeybinding: bindkey '^xt' gosmacs-transpose-chars bindkey '\e[2~' overwrite-mode bindkey -M viins '^u' backward-kill-line bindkey -s '^x^z' '\eqsuspend\n' autoload -Uz replace-string zle -N replace-string bindkey '\er' replace-string zle -N replace-string replace-pattern bindkey '\e%' replace-pattern Seeman zshcontribforsuppliededitingfunctionssuchas replace-string.

You might also like