Vi Cheat Sheet
Vi Cheat Sheet
Vi Cheat Sheet
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
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
www.lagmonster.org/docs/vi2.html
1/10
3/3/13
Vi Cheat Sheet
:.= := l
ControlG Showsfilename,currentlinenumber,totallinesinfile,and%offilelocation
Modes
Vihastwomodesinsertionmodeandcommandmode.Theeditorbeginsincommandmode,wherethecursor movementandtextdeletionandpastingoccur.Insertionmodebeginsuponenteringaninsertionorchange 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.(i.e.ToinsertaControlH,typeControlvControlh)
Motion
h j k l Arrow Keys w W Moveleft Movedown Moveup Moveright Thesedowork,buttheymaybetooslowonbigfiles.Alsomayhaveunpredictableresultswhenarrow keysarenotmappedcorrectlyinclient. Movetonextword Movetonextblankdelimitedword
www.lagmonster.org/docs/vi2.html
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(),{},[]
www.lagmonster.org/docs/vi2.html
3/10
3/3/13
Vi Cheat Sheet
DeletingText
Almostalldeletioncommandsareperformedbytypingdfollowedbyamotion.Forexample,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,almostallyankcommandsareperformedbytypingyfollowedbyamotion.Forexample,y$yanks totheendoftheline.Twootheryankcommandsare: yy :y nyyornY y Motion_cmd "(az)nyyor "(az)ndd Yankthecurrentline Yankthecurrentline Placesnlinesinthebuffercopies CopieseverythingfromthecursertotheMotionCommand(e.g.,yGwouldcopyfromcurrent positiontotheendofthefile,andy4wouldcopytotheendofthefourthsentence) Copiesorcuts(deletes)nlinesintoanamedbufferathroughzomittingnworksoncurrentline
Changingtext
Thechangecommandisadeletioncommandthatleavestheeditorininsertmode.Itisperformedbytypingc followedbyamotion.Forexamplecwchangesaword.Afewotherchangecommandsare: 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)
www.lagmonster.org/docs/vi2.html
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,yankorputcommand.Thegeneralprefixhasthe form"cwherecisanylowercasecharacter.forexample,"adwdeletesawordintobuffera.Itmaythereafterbe putbackintotextwithanappropriate"ap.
Markers
Namedmarkersmaybesetonanylineinafile.Anylowercaselettermaybeamarkername.Markersmay 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
www.lagmonster.org/docs/vi2.html
5/10
3/3/13
Vi Cheat Sheet
Replace
Thesearchandreplacefunctionisaccomplishedwiththe:scommand.Itiscommonlyusedincombinationwith 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
www.lagmonster.org/docs/vi2.html
6/10
3/3/13
Vi Cheat Sheet
Counts
Nearlyeverycommandmaybeprecededbyanumberthatspecifieshowmanytimesitistobeperformed.For example,5dwwilldelete5wordsand3fewillmovethecursorforwardtothe3rdoccurenceofthelettere.Even insertionsmayberepeatedconvenientlywiththismethod,saytoinsertthesameline100times.
Ranges
Rangesmayprecedemost"colon"commandsandcausethemtobeexecutedonalineorlines.Forexample :3,7dwoulddeletelines37.Rangesarecommonlycombinedwiththe: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
www.lagmonster.org/docs/vi2.html
7/10
3/3/13
Vi Cheat Sheet
:rfile :n :p :efile
!!program Replacelinewithoutputfromprogram
VISettings noto
:set sh=/bin/sh sh=shell_path :set showmode :setslow :setsm :setsw=n :settags=x nosm slow nosm sw=8 tags= /usr/lib/tags
www.lagmonster.org/docs/vi2.html
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 commands.Ifyoucreateafilecalled".exrc" inyourhomedirectory,anymaporset commandyouplaceinsidethisfilewillbe executedeverytimeyourunVI.Toimbed controlcharacterslikeESCinthemacro, youneedtoprecedethemwithCTRLv.If 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
www.lagmonster.org/docs/vi2.html
9/10
3/3/13
Vi Cheat Sheet
nJ
. u U :Nor :E
Returntothetop
PageproducedbyLagmonsterFeb2009
www.lagmonster.org/docs/vi2.html
10/10