3/3/13
Vi Cheat Sheet
AdvancedViCheatSheet
Starting/Ending Status Modes InsertingText Motion DeletingText Yanking ChangingText PuttingText Buffers Markers
Searching ReplacingText RegularExpressions Counts Ranges ShellFunctions Files VISettings KeyMapping Other
ClickherefortheBasicVICheatsheet GeneralNotes: [Link],typethefollowingcommandfollowedbyacarriage return::setshowmode [Link]!!!SomakesureCapsLockisOFF.
StartingandEndingVI
StartingVI vifilename virfilename vi+nfilename vi+filename Editsfilename Editslastsaveversionoffilename afteracrash Editsfilename andplacescurseratlinen Editsfilename andplacescurseronlastline
vi+/stringfilename Editsfilename andplacescurseronfirstoccuranceofstring vifilename file2... EndingVI ZZor:wqor:x :w :w! :wfile :w!file :n,mwfile :n,mw>>file :q :q! :e! :we! SavesandexitsVI Savescurrentfilebutdoesn'texit Savescurrentfileoverridingnormalchecksbutdoesn'texit Savescurrentasfile butdoesn'texit Savestofile overridingnormalchecksbutdoesn'texit Saveslinesnthroughmtofile Saveslinesnthroughmtotheendoffile QuitsVIandmaypromptifyouneedtosave QuitsVIandwithoutsaving Editsfilediscardinganyunsavedchanges(startsover) Savesandcontinuestoeditcurrentfile Editsfilename ,theneditsfile2...Afterthesave,use:n
Status
[Link]/docs/[Link]
1/10
3/3/13
Vi Cheat Sheet
:.= := l
Showscurrentlinenumber Showsnumberoflinesinfile Displaystab(^l)backslash(\)backspace(^H)newline($)bell(^G)formfeed(^L^)ofcurrentline
ControlG Showsfilename,currentlinenumber,totallinesinfile,and%offilelocation
Modes
[Link],wherethecursor [Link] command.[ESC]returnstheeditortocommandmode(whereyoucanquit,forexamplebytyping:q!).Most commandsexecuteassoonasyoutypethemexceptfor"colon"commandswhichexecutewhenyoupressthe ruturnkey.
InsertingText
i I a A o O r R CTRLv char :rfile :nrfile CTRLior TAB Insertbeforecursor Insertbeforeline Appendaftercursor Appendafterline Openanewlineaftercurrentline Openanewlinebeforecurrentline Replaceonecharacter Replacemanycharacters Whileinserting,ignoresspecialmeaningofchar(e.g.,forinsertingcharacterslikeESCandCTRL) untilESCisused Readsfile andinsertsitaftercurrentline Readsfile andinsertsitafterlinen Whileinserting,insertsoneshiftwidth
ThingstodowhileinInsertMode:
CTRLhorBackspace Whileinserting,deletespreviouscharacter CTRLw CTRLx CTRLv Whileinserting,deletespreviousword Whileinserting,deletestostartofinsertedtext Takethenextcharacterliterally.([Link],typeControlvControlh)
Motion
h j k l Arrow Keys w W Moveleft Movedown Moveup Moveright Thesedowork,[Link] keysarenotmappedcorrectlyinclient. Movetonextword Movetonextblankdelimitedword
[Link]/docs/[Link]
2/10
3/3/13
Vi Cheat Sheet
b B ^ +or e E ( ) { } [[ ]] 0or| n| $ 1G G nG :n fc Fc H nH M L nL
Movetothebeginningoftheword Movetothebeginningofblankdelimtedword Movestothefirstnonblankcharacterinthecurrentline Movestothefirstcharacterinthenextline Movestothefirstnonblankcharacterinthepreviousline Movetotheendoftheword MovetotheendofBlankdelimitedword Moveasentenceback Moveasentenceforward Moveaparagraphback Moveaparagraphforward Moveasectionback Moveasectionforward Movetothebeginingoftheline Movestothecolumnninthecurrentline Movetotheendoftheline Movetothefirstlineofthefile Movetothelastlineofthefile Movetonthlineofthefile Movetonthlineofthefile Moveforwardtoc Movebacktoc Movetotopofscreen Movestonthlinefromthetopofthescreen Movetomiddleofscreen Movetobottonofscreen Movestonthlinefromthebottomofthescreen
Control Moveforwardscreen d Control Moveforwardonefullscreen f Control Movebackwardscreen u Control Movebackwardonefullscreen b CTRLe CTRLy CTRLu CTRLd CTRLb CTRLf CTRLI z nz z. nz. z nz % Movesscreenuponeline Movesscreendownoneline Movesscreenuppage Movesscreendownpage Movesscreenuponepage Movesscreendownonepage Redrawsscreen zcarriagereturnmakesthecurrentlinethetoplineonthepage Makesthelinenthetoplineonthepage Makesthecurrentlinethemiddlelineonthepage Makesthelinenthemiddlelineonthepage Makesthecurrentlinethebottomlineonthepage Makesthelinenthebottomlineonthepage Movetoassociated(),{},[]
[Link]/docs/[Link]
3/10
3/3/13
Vi Cheat Sheet
DeletingText
[Link],dwdeletesaword. Afewotherdeletesare: x nx X nX D d$ ddor:d ndw ndb ndd :n,md dMotion_cmd "np "1pu.u. Deletecharactertotherightofcursor Deletesncharactersstartingwithcurrentomittingndeletescurrentcharacteronly Deletecharactertotheleftofcursor Deletespreviousncharactersomittingndeletespreviouscharacteronly Deletetotheendoftheline Deletesfromthecursortotheendoftheline Deletecurrentline Deletesthenextnwordsstartingwithcurrent Deletesthepreviousnwordsstartingwithcurrent Deletesnlinesbeginningwiththecurrentline Deleteslinesnthroughm DeleteseverythingincludedintheMotionCommand(e.g.,dGwoulddeletefromcurrentposition totheendofthefile,andd4woulddeletetotheendofthefourthsentence). Retrievesthelastnthdelete(last9deletesarekeptinabuffer) Scrollsthroughthedeletebufferuntilthedesireddeleteisretrieved(repeatu.)
YankingText
Likedeletion,[Link],y$yanks [Link]: yy :y nyyornY y Motion_cmd "(az)nyyor "(az)ndd Yankthecurrentline Yankthecurrentline Placesnlinesinthebuffercopies CopieseverythingfromthecursertotheMotionCommand(e.g.,yGwouldcopyfromcurrent positiontotheendofthefile,andy4wouldcopytotheendofthefourthsentence) Copiesorcuts(deletes)nlinesintoanamedbufferathroughzomittingnworksoncurrentline
Changingtext
[Link] [Link]: C ccorS xp stext cwtext Ctext cMotion_cmd <<or>> n<<orn>> Changetotheendoftheline ChangethewholelineuntilESCispressed Switchescharacteratcursorwithfollowingcharacter SubstitutestextforthecurrentcharacteruntilESCisused ChangescurrentwordtotextuntilESCisused ChangesrestofthecurrentlinetotextuntilESCisused ChangestotextfromcurrentpositiontoMotionCommanduntilESCisused Shiftsthelineleftorright(respectively)byoneshiftwidth(atab) Shiftsnlinesleftorright(respectively)byoneshiftwidth(atab)
[Link]/docs/[Link]
4/10
3/3/13
Vi Cheat Sheet
<Motion_cmdor>Motion_cmd UsewithMotionCommandtoshiftmultiplelinesleftorright
Puttingtext
p P Putafterthepositionoraftertheline Putbeforethepoitionorbeforetheline
"(az)por"(az)P Pastestextfromanamedbufferathroughzafterorbeforethecurrentline
Buffers
Namedbuffersmaybespecifiedbeforeanydeletion,change,[Link] form"[Link],"[Link] putbackintotextwithanappropriate"ap.
Markers
[Link] alsobeusedaslimitsforranges. mc Setmarkerconthisline `c Gotobeginningofmarkercline. 'c Gotofirstnonblankcharacterofmarkercline.
Searchforstrings
/string ?string n N % fc Fc tc Tchar ?str :setic :setnoic :n,ms/str1/str2/opt & :g/str/cmd :v/str/cmd , Searchforwardforstring Searchbackforstring Searchfornextinstanceofstring Searchforpreviousinstanceofstring Searchestobeginningofbalancing()[]or{} Searchesforwardincurrentlinetochar Searchesbackwardincurrentlinetochar Searchesforwardincurrentlinetocharacterbeforechar Searchesbackwardincurrentlinetocharacterbeforechar Findsinreverseforstr Ignorescasewhensearching Paysattentiontocasewhensearching Searchesfromntomforstr1replacesstr1tostr2usingoptoptcanbegforglobal change,ctoconfirmchange(ytoacknowledge,tosuppress),andptoprintchangedlines Repeatslast:scommand Runscmdonalllinesthatcontainstr Executescmdonalllinesthatdonotmatchstr Repeats,inreversedirection,last/or?searchcommand
:g/str1/s/str2/str3/ Findsthelinecontainingstr1,replacesstr2withstr3
[Link]/docs/[Link]
5/10
3/3/13
Vi Cheat Sheet
Replace
Thesearchandreplacefunctionisaccomplishedwiththe:[Link] rangesorthe:gcommand(below). :s/pattern/string/flags Replacepatternwithstringaccordingtoflags. g c & FlagReplacealloccurencesofpattern FlagConfirmreplaces. Repeatlast:scommand
RegularExpressions
.(dot) Anysinglecharacterexceptnewline * [...] [^...] \< \> ^ $ \< \> \n \ \\ zeroormoreoccurancesofanycharacter Anysinglecharacterspecifiedintheset Anysinglecharacternotspecifiedintheset Matchesbeginningofword Matchesendofword Anchorbeginningoftheline Anchorendofline Anchorbeginingofword Anchorendofword Contentsofnthgrouping Escapesthemeaningofthenextcharacter(e.g.,\$allowsyoutosearchfor$) Escapesthe\character
\(...\) Groupingusuallyusedtogroupconditions
[...]SetExamples
[AZ] [az] [09] [./=+] [AF] [09AZ] [AZ][azA Z] [az]{m} [az]{m,n} TheSETfromCapitalAtoCapitalZ TheSETfromlowercaseatolowercasez TheSETfrom0to9(Allnumerals) TheSETcontaining.(dot),/(slash),=,and+ TheSETfromCapitalAtoCapitalFandthedash(dashesmustbespecifiedfirst) TheSETcontainingallcapitallettersanddigitsandaspace Inthefirstposition,theSETfromCapitalAtoCapitalZ Inthesecondcharacterposition,theSETcontainingallletters LookformoccurancesoftheSETfromlowercaseatolowercasez Lookforatleastmoccurances,butnomorethannoccurancesoftheSETfromlowercaseato lowercasez
RegularExpressionExamples
/Hello/ /^TEST$/ /^[azA Z]/ /^[az].*/ MatchesifthelinecontainsthevalueHello MatchesifthelinecontainsTESTbyitself Matchesifthelinestartswithanyletter Matchesifthefirstcharacterofthelineisazandthereisatleastonemoreofanycharacter followingit
[Link]/docs/[Link]
6/10
3/3/13
Vi Cheat Sheet
/2134$/ /\(21|35\)/ /[09]*/ /^[^#]/
Matchesiflineendswith2134 Matchesisthelinecontains21or35 Notetheuseof()withthepipesymboltospecifythe'or'condition Matchesiftherearezeroormorenumbersintheline Matchesifthefirstcharacterisnota#intheline
Notes: [Link] [Link]
Counts
[Link] example,[Link] insertionsmayberepeatedconvenientlywiththismethod,saytoinsertthesameline100times.
Ranges
Rangesmayprecedemost"colon"[Link] :3,[Link]:scommandtoperformareplacementon severallines,aswith:.,$s/pattern/string/gtomakeareplacementfromthecurrentlinetotheendofthefile. :n,m :. :$ :'c :% RangeLinesnm RangeCurrentline RangeLastline RangeMarkerc RangeAlllinesinfile
:g/pattern/ RangeAlllinesthatcontainpattern
ShellFunctions
:!cmd !!cmd :!! :r!cmd :ffile :w!cmd :cddir :sh :sofile !}sort Executesshellcommandcmdyoucanaddthesespecialcharacterstoindicate:%nameofcurrent file#nameoflastfileedited Executesshellcommandcmd,placesoutputinfilestartingatcurrentline Executeslastshellcommand Readsandinsertsoutputfromcmd Renamescurrentfiletofile Sendscurrentlyeditedfiletocmdasstandardinputandexecutecmd Changescurrentworkingdirectorytodir Startsasubshell(CTRLdreturnstoeditor) Readsandexecutescommandsinfile(fileisashellscript) Sortsfromcurrentpositiontoendofparagraphandreplacestextwithsortedtext
!Motion_cmd SendstextfromcurrentpositiontoMotionCommandtoshellcommandcmd
Files
:wfile Writetofile
[Link]/docs/[Link]
7/10
3/3/13
Vi Cheat Sheet
:rfile :n :p :efile
Readfile inafterline Gotonextfile Gotopreviousfile Editfile
!!program Replacelinewithoutputfromprogram
VISettings noto
Note:[Link],entertype:setoptiontoturn themonor:[Link] youopenVI,[Link] optionswithoutthecolon(:)precedingtheoption Set Default Description
:setai :setall :setap :setaw :setbf :setdir=tmp :seteb :seted :setht= :setic :setlisp :setlist :setmagic :setmesg :setnooption :setnu :setopt :setpara= :setprompt :setre :setremap :setreport :setro :setscroll=n nonu opt para= LIlPLPPPQPbpP prompt nore remap noreport noro scroll=11 noai aw noaw nobf dir=/tmp noed noed ht=8 noic nolisp nolist magic mesg Turnsonautoindentation Printsalloptionstothescreen PrintslineafterdcJm:stucommands Automaticwriteon:n!e#^^:rew^}:tag Discardscontrolcharactersfrominput Setstmptodirectoryorbufferfile Precedeserrormessageswithabell Precedeserrormessageswithabell Setsterminalhardwaretabs Ignorescasewhensearching ModifiesbracketsforLispcompatibility. Showstabs(^l)andendofline($) Allowspatternmatchingwithspecialcharacters Allowsotherstosendmessages Turnsoffoption Showslinenumbers SpeedsoutputeliminatesautomaticRETURN macronamesthatstartparagraphsfor{and} operators Promptsforcommandinputwith: Simulatessmartterminalondumbterminal Acceptmacroswithinmacros Indicateslargestsizeofchangesreportedonstatus line Changesfiletypeto"readonly" setnlinesforCTRLdandz setshellescape(defaultis/bin/sh)toshell_path Indicatesinputorreplacemodeatbottom Posponedisplayupdatesduringinserts Showmatching{or(as)or}istyped Setsshiftwidthtoncharacters Pathforfilescheckedfortags(currentdirectory includedindefault)
:set sh=/bin/sh sh=shell_path :set showmode :setslow :setsm :setsw=n :settags=x nosm slow nosm sw=8 tags= /usr/lib/tags
[Link]/docs/[Link]
8/10
3/3/13
Vi Cheat Sheet
/usr/lib/tags :setterm :setterse :settimeout :settl=n :setts=n :setwa :setwarn :set window=n :setwm=n :setws tl=0 ts=8 nowa warn window=n wm=0 ws $TERM noterse
includedindefault) Printsterminaltype Shortenmessageswithterse Eliminatesonesecondtimelimitformacros Setssignificanceoftagsbeyondncharacters(0 meansall) Setstabstopstonfortextinput Inhibitsnormalchecksbeforewritecommands Warns"nowritesincelast change" Setsnumberoflinesinatextwindowton Setsautomaticwraparoundnspacesfromright margin. Setsautomaticwraparoundnspacesfromright margin.
KeyMapping
NOTE:MapallowsyoutodefinestringsofVI [Link]".exrc" inyourhomedirectory,anymaporset commandyouplaceinsidethisfilewillbe [Link] controlcharacterslikeESCinthemacro, [Link] youneedtoincludequotes("),precede themwitha\(backslash).Unusedkeysinvi are:KVgqv*=andthefunctionkeys. Example(TheactualVIcommandsarein blue)::mapv/ICTRLvESCdwiYouCTRLv ESCESC Description:Whenvispressed,searchfor "I"(/IESC),deleteword(dw),andinsert "You"(iYouESC).CTRLvallowsESCtobe inserted
:mapkeycmd_seq Defineskeytoruncmd_seqwhenpressed :map :unmapkey :abstrstring :ab :unastr Displaysallcreatedmacrosonstatusline Removesmacrodefinitionforkey Whenstrisinput,replacesitwithstring Displaysallabbreviations Unabbreviatesstr
Other
~ J Toggleupperandlowercase Joinlines
[Link]/docs/[Link]
9/10
3/3/13
Vi Cheat Sheet
nJ
Joinsthenextnlinestogetheromittingnjoinsthebeginningofthenextlinetotheendofthecurrent line Repeatlasttextchangingcommand Undolastchange(Note:[Link]) Undoallchangestoline RepeatslastfFtorTsearchcommand Youcanopenupanewsplitscreenwindowin(n)viandthenuse^wtoswitchbetweenthetwo.
. u U :Nor :E
Returntothetop
PageproducedbyLagmonsterFeb2009
[Link]/docs/[Link]
10/10