AnIntroductiontoDisplayEditingwithVi WilliamJoy Revisedforversions3.5/2.13by MarkHorton ComputerScienceDivision DepartmentofElectricalEngineeringandComputerScience UniversityofCalifornia,Berkeley Berkeley,Ca.94720 ABSTRACT Vi(visual)isadisplayorientedinteractivetexteditor.Whenusingvithe screenofyourterminalactsasawindowintothefilewhichyouareediting. Changeswhichyoumaketothefilearereflectedinwhatyousee. Usingviyoucaninsertnewtextanyplaceinthefilequiteeasily.Mostof thecommandstovimovethecursoraroundinthefile.Therearecommandsto movethecursorforwardandbackwardinunitsofcharacters,words,sentences andparagraphs.Asmallsetofoperators,likedfordeleteandcforchange,are combinedwiththemotioncommandstoformoperationssuchasdeletewordor changeparagraph,inasimpleandnaturalway.Thisregularityandthe mnemonicassignmentofcommandstokeysmakestheeditorcommandseteasy torememberandtouse. Viwillworkonalargenumberofdisplayterminals,andnewterminalsare easilydrivenaftereditingaterminaldescriptionfile.Whileitisadvantageousto haveanintelligentterminalwhichcanlocallyinsertanddeletelinesandcharactersfromthedisplay,theeditorwillfunctionquitewellondumbterminalsover slowphonelines.Theeditormakesallowanceforthelowbandwidthinthesesituationsandusessmallerwindowsizesanddifferentdisplayupdatingalgorithms tomakebestuseofthelimitedspeedavailable. Itisalsopossibletousethecommandsetofvionhardcopyterminals,storagetubesand‘‘glasstty’s’’usingaonelineeditingwindow;thusvi’scommand setisavailableonallterminals.Thefullcommandsetofthemoretraditional, lineorientededitorexisavailablewithinvi;itisquitesimpletoswitchbetween thetwomodesofediting. 6April1993 AnIntroductiontoDisplayEditingwithVi WilliamJoy Revisedforversions3.5/2.13by MarkHorton ComputerScienceDivision DepartmentofElectricalEngineeringandComputerScience UniversityofCalifornia,Berkeley Berkeley,Ca.94720 1.Gettingstarted Thisdocumentprovidesaquickintroductiontovi.(Pronouncedvee-eye.)Youshouldbe runningvionafileyouarefamiliarwithwhileyouarereadingthis.Thefirstpartofthisdocument(sections1through5)describesthebasicsofusingvi.Sometopicsofspecialinterestare presentedinsection6,andsomenitty-grittydetailsofhowtheeditorfunctionsaresavedforsec-tion7toavoidclutteringthepresentationhere. Thereisalsoashortappendixhere,whichgivesforeachcharacterthespecialmeanings whichthischaracterhasinvi.Attachedtothisdocumentshouldbeaquickreferencecard.This cardsummarizesthecommandsofviinaverycompactformat.Youshouldhavethecardhandy whileyouarelearningvi. 1.1.Specifyingterminaltype Beforeyoucanstartviyoumusttellthesystemwhatkindofterminalyouareusing.Here isa(necessarilyincomplete)listofterminaltypecodes.Ifyourterminaldoesnotappearhere, youshouldconsultwithoneofthestaffmembersonyoursystemtofindoutthecodeforyourterminal.Ifyourterminaldoesnothaveacode,onecanbeassignedandadescriptionfortheterminalcanbecreated. CodeFullnameType 2621Hewlett-Packard2621A/PIntelligent 2645Hewlett-Packard264xIntelligent act4MicrotermACT-IVDumb act5MicrotermACT-VDumb adm3aLearSieglerADM-3aDumb adm31LearSieglerADM-31Intelligent c100HumanDesignConcept100Intelligent dm1520Datamedia1520Dumb dm2500Datamedia2500Intelligent dm3025Datamedia3025Intelligent foxPerkin-ElmerFoxDumb h1500Hazeltine1500Intelligent h19Heathkith19Intelligent i100Infoton100Intelligent mimeImitatingasmartact4Intelligent ThefinancialsupportofanIBMGraduateFellowshipandtheNationalScienceFoundationunder grantsMCS74-07644-A03andMCS78-07291isgratefullyacknowledged.

-2-t1061Teleray1061Intelligent vt52DecVT-52Dumb SupposeforexamplethatyouhaveaHewlett-PackardHP2621Aterminal.Thecodeused bythesystemforthisterminalis‘2621’.Inthiscaseyoucanuseoneofthefollowingcommands totellthesystemthetypeofyourterminal: %setenvTERM2621 Thiscommandworkswiththeshellcshonbothversion6and7systems.Ifyouareusingthe standardversion7shellthenyoushouldgivethecommands $TERM=2621 $exportTERM Ifyouwanttoarrangetohaveyourterminaltypesetupautomaticallywhenyoulogin,you canusethetsetprogram.Ifyoudialinonamime,butoftenusehardwiredports,atypicalline foryour.loginfile(ifyouusecsh)wouldbe setenvTERM` tset−−dmime` orforyour.profilefile(ifyouusesh) TERM=` tset−−dmime` Tsetknowswhichterminalsarehardwiredtoeachportandneedsonlytobetoldthatwhenyou dialinyouareprobablyonamime.Tsetisusuallyusedtochangetheeraseandkillcharacters, too. 1.2.Editingafile Aftertellingthesystemwhichkindofterminalyouhave,youshouldmakeacopyofafile youarefamiliarwith,andrunvionthisfile,givingthecommand %viname replacingnamewiththenameofthecopyfileyoujustcreated.Thescreenshouldclearandthe textofyourfileshouldappearonthescreen.Ifsomethingelsehappensrefertothefootnote.‡ 1.3.Theeditor’scopy:thebuffer Theeditordoesnotdirectlymodifythefilewhichyouareediting.Rather,theeditormakes acopyofthisfile,inaplacecalledthebuffer,andremembersthefile’sname.Youdonotaffect thecontentsofthefileunlessanduntilyouwritethechangesyoumakebackintotheoriginalfile. 1.4.Notationalconventions Inourexamples,inputwhichmustbetypedasiswillbepresentedinboldface.Text whichshouldbereplacedwithappropriateinputwillbegiveninitalics.Wewillrepresentspecial charactersinSMALLCAPITALS. ‡Ifyougavethesystemanincorrectterminaltypecodethentheeditormayhavejustmadeamess outofyourscreen.Thishappenswhenitsendscontrolcodesforonekindofterminaltosomeother kindofterminal.Inthiscasehitthekeys:q(colonandtheqkey)andthenhittheRETURNkey. Thisshouldgetyoubacktothecommandlevelinterpreter.Figureoutwhatyoudidwrong(ask someoneelseifnecessary)andtryagain. Anotherthingwhichcangowrongisthatyoutypedthewrongfilenameandtheeditorjust printedanerrordiagnostic.Inthiscaseyoushouldfollowtheaboveprocedureforgettingoutofthe editor,andtryagainthistimespellingthefilenamecorrectly. Iftheeditordoesn’tseemtorespondtothecommandswhichyoutypehere,trysendinganinterrupttoitbyhittingtheDELorRUBkeyonyourterminal,andthenhittingthe:qcommandagainfollowedbyacarriagereturn.

-3-1.5.Arrowkeys Theeditorcommandsetisindependentoftheterminalyouareusing.Onmostterminals withcursorpositioningkeys,thesekeyswillalsoworkwithintheeditor.Ifyoudon’thavecursor positioningkeys,orevenifyoudo,youcanusethehjkandlkeysascursorpositioningkeys (thesearelabelledwitharrowsonanadm3a).* (ParticularnotefortheHP2621:onthisterminalthefunctionkeysmustbeshifted(ick)to sendtothemachine,otherwisetheyonlyactlocally.Unshiftedusewillleavethecursorpositionedincorrectly.) 1.6.Specialcharacters:ESC,CRandDEL Severalofthesespecialcharactersareveryimportant,sobesuretofindthemrightnow. LookonyourkeyboardforakeylabelledESCorALT.Itshouldbeneartheupperleftcornerof yourterminal.Tryhittingthiskeyafewtimes.Theeditorwillringthebelltoindicatethatitis inaquiescentstate.‡PartiallyformedcommandsarecancelledbyESC,andwhenyouinserttext inthefileyouendthetextinsertionwithESC.Thiskeyisafairlyharmlessonetohit,soyoucan justhititifyoudon’tknowwhatisgoingonuntiltheeditorringsthebell. TheCRorRETURNkeyisimportantbecauseitisusedtoterminatecertaincommands.Itis usuallyattherightsideofthekeyboard,andisthesamecommandusedattheendofeachshell command. AnotherveryusefulkeyistheDELorRUBkey,whichgeneratesaninterrupt,tellingtheeditortostopwhatitisdoing.Itisaforcefulwayofmakingtheeditorlistentoyou,ortoreturnit tothequiescentstateifyoudon’tknowordon’tlikewhatisgoingon.Tryhittingthe‘/’keyon yourterminal.Thiskeyisusedwhenyouwanttospecifyastringtobesearchedfor.Thecursor shouldnowbepositionedatthebottomlineoftheterminalaftera‘/’printedasaprompt.You cangetthecursorbacktothecurrentpositionbyhittingtheDELorRUBkey;trythisnow.* FromnowonwewillsimplyrefertohittingtheDELorRUBkeyas‘‘sendinganinterrupt.’’** Theeditoroftenechoesyourcommandsonthelastlineoftheterminal.Ifthecursorison thefirstpositionofthislastline,thentheeditorisperformingacomputation,suchascomputing anewpositioninthefileafterasearchorrunningacommandtoreformatpartofthebuffer. Whenthisishappeningyoucanstoptheeditorbysendinganinterrupt. 1.7.Gettingoutoftheeditor Afteryouhaveworkedwiththisintroductionforawhile,andyouwishtodosomethingelse, youcangivethecommandZZtotheeditor.Thiswillwritethecontentsoftheeditor’sbuffer backintothefileyouareediting,ifyoumadeanychanges,andthenquitfromtheeditor.You canalsoendaneditorsessionbygivingthecommand:q!CR;†thisisadangerousbutoccasionally essentialcommandwhichendstheeditorsessionanddiscardsallyourchanges.Youneedtoknow aboutthiscommandincaseyouchangetheeditor’scopyofafileyouwishonlytolookat.Be verycarefulnottogivethiscommandwhenyoureallywanttosavethechangesyouhavemade. 2.Movingaroundinthefile *Aswewillseelater,hmovesbacktotheleft(likecontrol-hwhichisabackspace),jmovesdown(in thesamecolumn),kmovesup(inthesamecolumn),andlmovestotheright. ‡Onsmartterminalswhereitispossible,theeditorwillquietlyflashthescreenratherthanringing thebell. *Backspacingoverthe‘/’willalsocancelthesearch. **Onsomesystems,thisinterruptibilitycomesataprice:youcannottypeaheadwhentheeditoris computingwiththecursoronthebottomline. †AllcommandswhichreadfromthelastdisplaylinecanalsobeterminatedwithaESCaswellasan CR.

-4-2.1.Scrollingandpaging Theeditorhasanumberofcommandsformovingaroundinthefile.Themostusefulof theseisgeneratedbyhittingthecontrolandDkeysatthesametime,acontrol-Dor‘ˆ D’.We willusethistwocharacternotationforreferringtothesecontrolkeysfromnowon.Youmay haveakeylabelled‘ˆ ’onyourterminal.Thiskeywillberepresentedas‘↑’inthisdocument;‘ˆ ’ isexclusivelyusedaspartofthe‘ˆ x’notationforcontrolcharacters.‡ Asyouknownowifyoutriedhittingˆ D,thiscommandscrollsdowninthefile.TheD thusstandsfordown.Manyeditorcommandsaremnemonicandthismakesthemmucheasierto remember.Forinstancethecommandtoscrollupisˆ U.Manydumbterminalscan’tscrollup atall,inwhichcasehittingˆ Uclearsthescreenandrefreshesitwithalinewhichisfartherback inthefileatthetop. Ifyouwanttoseemoreofthefilebelowwhereyouare,youcanhitˆ Etoexposeonemore lineatthebottomofthescreen,leavingthecursorwhereitis.‡‡Thecommandˆ Y(whichis hopelesslynon-mnemonic,butnexttoˆ Uonthekeyboard)exposesonemorelineatthetopof thescreen. Thereareotherwaystomovearoundinthefile;thekeysˆ Fandˆ B‡moveforwardand backwardapage,keepingacoupleoflinesofcontinuitybetweenscreenssothatitispossibleto readthroughafileusingtheseratherthanˆ Dandˆ Uifyouwish. Noticethedifferencebetweenscrollingandpaging.Ifyouaretryingtoreadthetextina file,hittingˆ Ftomoveforwardapagewillleaveyouonlyalittlecontexttolookbackat. Scrollingontheotherhandleavesmorecontext,andhappensmoresmoothly.Youcancontinue toreadthetextasscrollingistakingplace. 2.2.Searching,goto,andpreviouscontext Anotherwaytopositionyourselfinthefileisbygivingtheeditorastringtosearchfor. Typethecharacter/followedbyastringofcharactersterminatedbyCR.Theeditorwillposition thecursoratthenextoccurrenceofthisstring.Tryhittingntothengotothenextoccurrence ofthisstring.Thecharacter?willsearchbackwardsfromwhereyouare,andisotherwiselike/.† Ifthesearchstringyougivetheeditorisnotpresentinthefiletheeditorwillprintadiagnosticonthelastlineofthescreen,andthecursorwillbereturnedtoitsinitialposition. Ifyouwishthesearchtomatchonlyatthebeginningofaline,beginthesearchstringwith an↑.Tomatchonlyattheendofaline,endthesearchstringwitha$.Thus/↑searchCRwill searchfortheword‘search’atthebeginningofaline,and/last$CRsearchesfortheword‘last’at theendofaline.* ThecommandG,whenprecededbyanumberwillpositionthecursoratthatlineinthe file.Thus1Gwillmovethecursortothefirstlineofthefile.IfyougiveGnocount,thenit movestotheendofthefile. Ifyouareneartheendofthefile,andthelastlineisnotatthebottomofthescreen,the editorwillplaceonlythecharacter‘˜ ’oneachremainingline.Thisindicatesthatthelastlinein thefileisonthescreen;thatis,the‘˜ ’linesarepasttheendofthefile. ‡Ifyoudon’thavea‘ˆ ’keyonyourterminalthenthereisprobablyakeylabelled‘↑’;inanycase thesecharactersareoneandthesame. ‡‡Version3only. ‡Notavailableinallv2editorsduetomemoryconstraints. †Thesesearcheswillnormallywraparoundtheendofthefile,andthusfindthestringevenifitis notonalineinthedirectionyousearchprovideditisanywhereelseinthefile.Youcandisablethis wraparoundinscansbygivingthecommand:senowrapscanCR,ormorebriefly:senowsCR. *Actually,thestringyougivetosearchforherecanbearegularexpressioninthesenseoftheeditors ex(1)anded(1).Ifyoudon’twishtolearnaboutthisyet,youcandisablethismoregeneralfacility bydoing:senomagicCR;byputtingthiscommandinEXINITinyourenvironment,youcanhave thisalwaysbeineffect(moreaboutEXINITlater.)

-5-Youcanfindoutthestateofthefileyouareeditingbytypingaˆ G.Theeditorwillshow youthenameofthefileyouareediting,thenumberofthecurrentline,thenumberoflinesinthe buffer,andthepercentageofthewaythroughthebufferwhichyouare.Trydoingthisnow,and rememberthenumberofthelineyouareon.GiveaGcommandtogettotheendandthen anotherGcommandtogetbackwhereyouwere. Youcanalsogetbacktoapreviouspositionbyusingthecommand` ` (twobackquotes). ThisisoftenmoreconvenientthanGbecauseitrequiresnoadvancepreparation.TrygivingaG orasearchwith/or?andthena` ` togetbacktowhereyouwere.Ifyouaccidentallyhitnor anycommandwhichmovesyoufarawayfromacontextofinterest,youcanquicklygetbackby hitting` ` . 2.3.Movingaroundonthescreen Nowtryjustmovingthecursoraroundonthescreen.Ifyourterminalhasarrowkeys(4or 5keyswitharrowsgoingineachdirection)trythemandconvinceyourselfthattheywork.(On certainterminalsusingv2editors,theywon’t.)Ifyoudon’thaveworkingarrowkeys,youcan alwaysuseh,j,k,andl.Experiencedusersofvipreferthesekeystoarrowkeys,becausethey areusuallyrightunderneaththeirfingers. Hitthe+key.Eachtimeyoudo,noticethatthecursoradvancestothenextlineinthe file,atthefirstnon-whitepositionontheline.The−keyislike+butgoestheotherway. Theseareverycommonkeysformovingupanddownlinesinthefile.Noticethatifyougo offthebottomortopwiththesekeysthenthescreenwillscrolldown(andupifpossible)tobring alineatatimeintoview.TheRETURNkeyhasthesameeffectasthe+key. Vialsohascommandstotakeyoutothetop,middleandbottomofthescreen.Hwilltake youtothetop(home)lineonthescreen.Tryprecedingitwithanumberasin3H.Thiswill takeyoutothethirdlineonthescreen.Manyvicommandstakeprecedingnumbersanddo interestingthingswiththem.TryM,whichtakesyoutothemiddlelineonthescreen,andL, whichtakesyoutothelastlineonthescreen.Lalsotakescounts,thus5Lwilltakeyoutothe fifthlinefromthebottom. 2.4.Movingwithinaline Nowtrypickingawordonsomelineonthescreen,notthefirstwordontheline.movethe cursorusingRETURNand−tobeonthelinewherethewordis.Tryhittingthewkey.Thiswill advancethecursortothenextwordontheline.Tryhittingthebkeytobackupwordsinthe line.Alsotrytheekeywhichadvancesyoutotheendofthecurrentwordratherthantothe beginningofthenextword.AlsotrySPACE(thespacebar)whichmovesrightonecharacterand theBS(backspaceorˆ H)keywhichmovesleftonecharacter.Thekeyhworksasˆ Hdoesandis usefulifyoudon’thaveaBSkey.(Also,asnotedjustabove,lwillmovetotheright.) Ifthelinehadpunctuationinityoumayhavenoticedthatthatthewandbkeysstopped ateachgroupofpunctuation.Youcanalsogobackandforwardswordswithoutstoppingat punctuationbyusingWandBratherthanthelowercaseequivalents.Thinkoftheseasbigger words.Trytheseonafewlineswithpunctuationtoseehowtheydifferfromthelowercasew andb. Thewordkeyswraparoundtheendofline,ratherthanstoppingattheend.Trymovingto awordonalinebelowwhereyouarebyrepeatedlyhittingw. 2.5.Summary SPACEadvancethecursoroneposition ˆ Bbackwardstopreviouspage ˆ Dscrollsdowninthefile ˆ Eexposesanotherlineatthebottom(v3)

-6-ˆ Fforwardtonextpage ˆ Gtellwhatisgoingon ˆ Hbackspacethecursor ˆ Nnextline,samecolumn ˆ Ppreviousline,samecolumn ˆ Uscrollsupinthefile ˆ Yexposesanotherlineatthetop(v3) +nextline,atthebeginning −previousline,atthebeginning /scanforafollowingstringforwards ?scanbackwards Bbackaword,ignoringpunctuation Ggotospecifiedline,lastdefault Hhomescreenline Mmiddlescreenline Llastscreenline Wforwardaword,ignoringpunctuation bbackaword eendofcurrentword nscanfornextinstanceof/or?pattern wwordafterthisword 2.6.View‡ Ifyouwanttousetheeditortolookatafile,ratherthantomakechanges,invokeitasview insteadofvi.Thiswillsetthereadonlyoptionwhichwillpreventyoufromaccidentlyoverwriting thefile. 3.Makingsimplechanges 3.1.Inserting Oneofthemostusefulcommandsisthei(insert)command.Afteryoutypei,everything youtypeuntilyouhitESCisinsertedintothefile.Trythisnow;positionyourselftosomewordin thefileandtryinsertingtextbeforethisword.Ifyouareonandumbterminalitwillseem,fora minute,thatsomeofthecharactersinyourlinehavebeenoverwritten,buttheywillreappear whenyouhitESC. Nowtryfindingawordwhichcan,butdoesnot,endinan‘s’.Positionyourselfatthis wordandtypee(movetoendofword),thenaforappendandthen‘sESC’toterminatethetextualinsert.Thissequenceofcommandscanbeusedtoeasilypluralizeaword. Tryinsertingandappendingafewtimestomakesureyouunderstandhowthisworks;i placingtexttotheleftofthecursor,atotheright. Itisoftenthecasethatyouwanttoaddnewlinestothefileyouareediting,beforeorafter somespecificlineinthefile.Findalinewherethismakessenseandthengivethecommandoto createanewlineafterthelineyouareon,orthecommandOtocreateanewlinebeforetheline youareon.Afteryoucreateanewlineinthisway,textyoutypeuptoanESCisinsertedonthe newline. Manyrelatededitorcommandsareinvokedbythesameletterkeyanddifferonlyinthat oneisgivenbyalowercasekeyandtheotherisgivenbyanuppercasekey.Inthesecases,the uppercasekeyoftendiffersfromthelowercasekeyinitssenseofdirection,withtheuppercase keyworkingbackwardand/orup,whilethelowercasekeymovesforwardand/ordown. ‡Notavailableinallv2editorsduetomemoryconstraints.

-7-Wheneveryouaretypingintext,youcangivemanylinesofinputorjustafewcharacters. Totypeinmorethanonelineoftext,hitaRETURNatthemiddleofyourinput.Anewlinewill becreatedfortext,andyoucancontinuetotype.Ifyouareonaslowanddumbterminalthe editormaychoosetowaittoredrawthetailofthescreen,andwillletyoutypeovertheexisting screenlines.Thisavoidsthelengthydelaywhichwouldoccuriftheeditorattemptedtokeepthe tailofthescreenalwaysuptodate.Thetailofthescreenwillbefixedup,andthemissinglines willreappear,whenyouhitESC. Whileyouareinsertingnewtext,youcanusethecharactersyounormallyuseatthesystem commandlevel(usuallyˆ Hor#)tobackspaceoverthelastcharacterwhichyoutyped,andthe characterwhichyouusetokillinputlines(usually@,ˆ X,orˆ U)toerasetheinputyouhave typedonthecurrentline.†Thecharacterˆ Wwilleraseawholewordandleaveyouafterthe spaceafterthepreviousword;itisusefulforquicklybackingupinaninsert. Noticethatwhenyoubackspaceduringaninsertionthecharactersyoubackspaceoverare noterased;thecursormovesbackwards,andthecharactersremainonthedisplay.Thisisoften usefulifyouareplanningtotypeinsomethingsimilar.Inanycasethecharactersdisappearwhen whenyouhitESC;ifyouwanttogetridofthemimmediately,hitanESCandthenaagain. Noticealsothatyoucan’terasecharacterswhichyoudidn’tinsert,andthatyoucan’t backspacearoundtheendofaline.Ifyouneedtobackuptothepreviouslinetomakeacorrection,justhitESCandmovethecursorbacktothepreviousline.Aftermakingthecorrectionyou canreturntowhereyouwereandusetheinsertorappendcommandagain. 3.2.Makingsmallcorrections Youcanmakesmallcorrectionsinexistingtextquiteeasily.Findasinglecharacterwhichis wrongorjustpickanycharacter.Usethearrowkeystofindthecharacter,orgetnearthecharacterwiththewordmotionkeysandtheneitherbackspace(hittheBSkeyorˆ Horevenjusth) orSPACE(usingthespacebar)untilthecursorisonthecharacterwhichiswrong.Ifthecharacterisnotneededthenhitthexkey;thisdeletesthecharacterfromthefile.Itisanalogoustothe wayyouxoutcharacterswhenyoumakemistakesonatypewriter(exceptit’snotasmessy). Ifthecharacterisincorrect,youcanreplaceitwiththecorrectcharacterbygivingthecommandrc,wherecisreplacedbythecorrectcharacter.Finallyifthecharacterwhichisincorrect shouldbereplacedbymorethanonecharacter,givethecommandswhichsubstitutesastringof characters,endingwithESC,forit.Ifthereareasmallnumberofcharacterswhicharewrongyou canprecedeswithacountofthenumberofcharacterstobereplaced.Countsarealsouseful withxtospecifythenumberofcharacterstobedeleted. 3.3.Morecorrections:operators Youalreadyknowalmostenoughtomakechangesatahigherlevel.Allyouneedtoknow nowisthatthedkeyactsasadeleteoperator.Trythecommanddwtodeleteaword.Tryhitting.afewtimes.Noticethatthisrepeatstheeffectofthedw.Thecommand.repeatsthelast commandwhichmadeachange.Youcanrememberitbyanalogywithanellipsis‘...’. Nowtrydb.Thisdeletesawordbackwards,namelytheprecedingword.TrydSPACE. Thisdeletesasinglecharacter,andisequivalenttothexcommand. Anotherveryusefuloperatoriscorchange.Thecommandcwthuschangesthetextofa singleword.YoufollowitbythereplacementtextendingwithanESC.Findawordwhichyou canchangetoanother,andtrythisnow.Noticethattheendofthetexttobechangedwas markedwiththecharacter‘$’sothatyoucanseethisasyouaretypinginthenewmaterial. †Infact,thecharacterˆ H(backspace)alwaysworkstoerasethelastinputcharacterhere,regardless ofwhatyourerasecharacteris.

-8-3.4.Operatingonlines Itisoftenthecasethatyouwanttooperateonlines.Findalinewhichyouwanttodelete, andtypedd,thedoperatortwice.Thiswilldeletetheline.Ifyouareonadumbterminal,the editormayjusterasethelineonthescreen,replacingitwithalinewithonlyan@onit.This linedoesnotcorrespondtoanylineinyourfile,butonlyactsasaplaceholder.Ithelpstoavoid alengthyredrawoftherestofthescreenwhichwouldbenecessarytocloseuptheholecreated bythedeletiononaterminalwithoutadeletelinecapability. Tryrepeatingthecoperatortwice;thiswillchangeawholeline,erasingitspreviouscontentsandreplacingthemwithtextyoutypeuptoanESC.† Youcandeleteorchangemorethanonelinebyprecedingtheddorccwithacount,i.e. 5dddeletes5lines.YoucanalsogiveacommandlikedLtodeleteallthelinesuptoandincludingthelastlineonthescreen,ord3Ltodeletethroughthethirdfromthebottomline.Trysome commandslikethisnow.*Noticethattheeditorletsyouknowwhenyouchangealargenumber oflinessothatyoucanseetheextentofthechange.Theeditorwillalsoalwaystellyouwhena changeyoumakeaffectstextwhichyoucannotsee. 3.5.Undoing Nowsupposethatthelastchangewhichyoumadewasincorrect;youcouldusetheinsert, deleteandappendcommandstoputthecorrectmaterialback.However,sinceitisoftenthecase thatweregretachangeormakeachangeincorrectly,theeditorprovidesau(undo)commandto reversethelastchangewhichyoumade.Trythisafewtimes,andgiveittwiceinarowtonotice thatanualsoundoesau. Theundocommandletsyoureverseonlyasinglechange.Afteryoumakeanumberof changestoaline,youmaydecidethatyouwouldratherhavetheoriginalstateofthelineback. TheUcommandrestoresthecurrentlinetothestatebeforeyoustartedchangingit. Youcanrecovertextwhichyoudelete,evenifundowillnotbringitback;seethesectionon recoveringlosttextbelow. 3.6.Summary SPACEadvancethecursoroneposition ˆ Hbackspacethecursor ˆ Weraseawordduringaninsert eraseyourerase(usuallyˆ Hor#),erasesacharacterduringaninsert killyourkill(usually@,ˆ X,orˆ U),killstheinsertonthisline .repeatsthechangingcommand Oopensandinputsnewlines,abovethecurrent Uundoesthechangesyoumadetothecurrentline aappendstextafterthecursor cchangestheobjectyouspecifytothefollowingtext ddeletestheobjectyouspecify iinsertstextbeforethecursor oopensandinputsnewlines,belowthecurrent uundoesthelastchange †ThecommandSisaconvenientsynonymforforcc,byanalogywiths.ThinkofSasasubstitute onlines,whilesisasubstituteoncharacters. *Onesubtlepointhereinvolvesusingthe/searchafterad.Thiswillnormallydeletecharacters fromthecurrentpositiontothepointofthematch.Ifwhatisdesiredistodeletewholelinesincludingthetwopoints,givethepatternas/pat/+0,alineaddress.

-9-4.Movingabout;rearrangingandduplicatingtext 4.1.Lowlevelcharactermotions Nowmovethecursortoalinewherethereisapunctuationorabracketingcharactersuch asaparenthesisoracommaorperiod.Trythecommandfxwherexisthischaracter.Thiscommandfindsthenextxcharactertotherightofthecursorinthecurrentline.Trythenhittinga;, whichfindsthenextinstanceofthesamecharacter.Byusingthefcommandandthena sequenceof;’syoucanoftengettoaparticularplaceinalinemuchfasterthanwithasequence ofwordmotionsorSPACEs.ThereisalsoaFcommand,whichislikef,butsearchesbackward. The;commandrepeatsFalso. Whenyouareoperatingonthetextinalineitisoftendesirabletodealwiththecharacters upto,butnotincluding,thefirstinstanceofacharacter.Trydfxforsomexnowandnoticethat thexcharacterisdeleted.Undothiswithuandthentrydtx;thetherestandsforto,i.e. deleteuptothenextx,butnotthex.ThecommandTisthereverseoft. Whenworkingwiththetextofasingleline,an↑movesthecursortothefirstnon-white positionontheline,anda$movesittotheendoftheline.Thus$awillappendnewtextatthe endofthecurrentline. Yourfilemayhavetab(ˆ I)charactersinit.Thesecharactersarerepresentedasanumber ofspacesexpandingtoatabstop,wheretabstopsareevery8positions.*Whenthecursorisat atab,itsitsonthelastoftheseveralspaceswhichrepresentthattab.Trymovingthecursor backandforthovertabssoyouunderstandhowthisworks. Onrareoccasions,yourfilemayhavenonprintingcharactersinit.Thesecharactersaredisplayedinthesamewaytheyarerepresentedinthisdocument,thatiswithatwocharactercode, thefirstcharacterofwhichis‘ˆ ’.Onthescreennon-printingcharactersresemblea‘ˆ ’character adjacenttoanother,butspacingorbackspacingoverthecharacterwillrevealthatthetwocharactersare,likethespacesrepresentingatabcharacter,asinglecharacter. Theeditorsometimesdiscardscontrolcharacters,dependingonthecharacterandthesettingofthebeautifyoption,ifyouattempttoinserttheminyourfile.Youcangetacontrolcharacterinthefilebybeginninganinsertandthentypingaˆ Vbeforethecontrolcharacter.The ˆ Vquotesthefollowingcharacter,causingittobeinserteddirectlyintothefile. 4.2.Higherleveltextobjects Inworkingwithadocumentitisoftenadvantageoustoworkintermsofsentences,paragraphs,andsections.Theoperations(and)movetothebeginningofthepreviousandnextsentencesrespectively.Thusthecommandd)willdeletetherestofthecurrentsentence;likewised( willdeletetheprevioussentenceifyouareatthebeginningofthecurrentsentence,orthecurrent sentenceuptowhereyouareifyouarenotatthebeginningofthecurrentsentence. Asentenceisdefinedtoendata‘.’,‘!’or‘?’whichisfollowedbyeithertheendofaline,or bytwospaces.Anynumberofclosing‘)’,‘]’,‘"’and‘´ ’charactersmayappearafterthe‘.’,‘!’or ‘?’beforethespacesorendofline. Theoperations{and}moveoverparagraphsandtheoperations[[and]]moveoversections.† Aparagraphbeginsaftereachemptyline,andalsoateachofasetofparagraphmacros, specifiedbythepairsofcharactersinthedefinitionofthestringvaluedoptionparagraphs.The defaultsettingforthisoptiondefinestheparagraphmacrosofthe−msand−mmmacropack- *Thisissettablebyacommandoftheform:sets=xCR,wherexis4tosettabstopseveryfour columns.Thishaseffectonthescreenrepresentationwithintheeditor. †The[[and]]operationsrequiretheoperationcharactertobedoubledbecausetheycanmovethe cursorfarfromwhereitcurrentlyis.Whileitiseasytogetbackwiththecommand` ` ,thesecommandswouldstillbefrustratingiftheywereeasytohitaccidentally.

-10-ages,i.e.the‘.IP’,‘.LP’,‘.PP’and‘.QP’,‘.P’and‘.LI’macros.‡Eachparagraphboundaryisalso asentenceboundary.Thesentenceandparagraphcommandscanbegivencountstooperateover groupsofsentencesandparagraphs. Sectionsintheeditorbeginaftereachmacrointhesectionsoption,normally‘.NH’,‘.SH’, ‘.H’and‘.HU’,andeachlinewithaformfeedˆ Linthefirstcolumn.Sectionboundariesare alwayslineandparagraphboundariesalso. Tryexperimentingwiththesentenceandparagraphcommandsuntilyouaresurehowthey work.Ifyouhavealargedocument,trylookingthroughitusingthesectioncommands.Thesectioncommandsinterpretaprecedingcountasadifferentwindowsizeinwhichtoredrawthe screenatthenewlocation,andthiswindowsizeisthebasesizefornewlydrawnwindowsuntil anothersizeisspecified.Thisisveryusefulifyouareonaslowterminalandarelookingfora particularsection.Youcangivethefirstsectioncommandasmallcounttothenseeeachsuccessivesectionheadinginasmallwindow. 4.3.Rearrangingandduplicatingtext Theeditorhasasingleunnamedbufferwherethelastdeletedorchangedawaytextissaved, andasetofnamedbuffersa−zwhichyoucanusetosavecopiesoftextandtomovetextaround inyourfileandbetweenfiles. Theoperatoryyanksacopyoftheobjectwhichfollowsintotheunnamedbuffer.Ifprecededbyabuffername,"xy,wherexhereisreplacedbyalettera−z,itplacesthetextinthe namedbuffer.ThetextcanthenbeputbackinthefilewiththecommandspandP;pputsthe textafterorbelowthecursor,whilePputsthetextbeforeorabovethecursor. Ifthetextwhichyouyankformsapartofaline,orisanobjectsuchasasentencewhich partiallyspansmorethanoneline,thenwhenyouputthetextback,itwillbeplacedafterthe cursor(orbeforeifyouuseP).Iftheyankedtextformswholelines,theywillbeputbackas wholelines,withoutchangingthecurrentline.Inthiscase,theputactsmuchlikeaoorOcommand. TrythecommandYP.Thismakesacopyofthecurrentlineandleavesyouonthiscopy, whichisplacedbeforethecurrentline.ThecommandYisaconvenientabbreviationforyy. ThecommandYpwillalsomakeacopyofthecurrentline,andplaceitafterthecurrentline. YoucangiveYacountoflinestoyank,andthusduplicateseverallines;try3YP. Tomovetextwithinthebuffer,youneedtodeleteitinoneplace,andputitbackin another.Youcanprecedeadeleteoperationbythenameofabufferinwhichthetextistobe storedasin"a5dddeleting5linesintothenamedbuffera.Youcanthenmovethecursortothe eventualrestingplaceofthetheselinesanddoa"apor"aPtoputthemback.Infact,youcan switchandeditanotherfilebeforeyouputthelinesback,bygivingacommandoftheform:e nameCRwherenameisthenameoftheotherfileyouwanttoedit.Youwillhavetowriteback thecontentsofthecurrenteditorbuffer(ordiscardthem)ifyouhavemadechangesbeforethe editorwillletyouswitchtotheotherfile.Anordinarydeletecommandsavesthetextinthe unnamedbuffer,sothatanordinaryputcanmoveitelsewhere.However,theunnamedbufferis lostwhenyouchangefiles,sotomovetextfromonefiletoanotheryoushoulduseanunnamed buffer. 4.4.Summary. ↑firstnon-whiteonline $endofline )forwardsentence ‡Youcaneasilychangeorextendthissetofmacrosbyassigningadifferentstringtotheparagraphs optioninyourEXINIT.Seesection6.2fordetails.The‘.bp’directiveisalsoconsideredtostarta paragraph.

-11- }forwardparagraph ]]forwardsection (backwardsentence {backwardparagraph [[backwardsection fxfindxforwardinline pputtextback,aftercursororbelowcurrentline yyankoperator,forcopiesandmoves txuptoxforward,foroperators Fxfbackwardinline Pputtextback,beforecursororabovecurrentline Txtbackwardinline 5.Highlevelcommands 5.1.Writing,quitting,editingnewfiles SofarwehaveseenhowtoenterviandtowriteoutourfileusingeitherZZor:wCR.The firstexitsfromtheeditor,(writingifchangesweremade),thesecondwritesandstaysintheeditor. Ifyouhavechangedtheeditor’scopyofthefilebutdonotwishtosaveyourchanges,either becauseyoumessedupthefileordecidedthatthechangesarenotanimprovementtothefile, thenyoucangivethecommand:q!CRtoquitfromtheeditorwithoutwritingthechanges.You canalsoreeditthesamefile(startingover)bygivingthecommand:e!CR.Thesecommands shouldbeusedonlyrarely,andwithcaution,asitisnotpossibletorecoverthechangesyouhave madeafteryoudiscardtheminthismanner. Youcaneditadifferentfilewithoutleavingtheeditorbygivingthecommand:enameCR. Ifyouhavenotwrittenoutyourfilebeforeyoutrytodothis,thentheeditorwilltellyouthis, anddelayeditingtheotherfile.Youcanthengivethecommand:wCRtosaveyourworkand thenthe:enameCRcommandagain,orcarefullygivethecommand:e!nameCR,whicheditsthe otherfilediscardingthechangesyouhavemadetothecurrentfile.Tohavetheeditorautomaticallysavechanges,includesetautowriteinyourEXINIT,anduse:ninsteadof:e. 5.2.Escapingtoashell Youcangettoashelltoexecuteasinglecommandbygivingavicommandoftheform :!cmdCR.Thesystemwillrunthesinglecommandcmdandwhenthecommandfinishes,theeditorwillaskyoutohitaRETURNtocontinue.Whenyouhavefinishedlookingattheoutputon thescreen,youshouldhitRETURNandtheeditorwillclearthescreenandredrawit.Youcan thencontinueediting.Youcanalsogiveanother:commandwhenitasksyouforaRETURN;in thiscasethescreenwillnotberedrawn. Ifyouwishtoexecutemorethanonecommandintheshell,thenyoucangivethecommand :shCR.Thiswillgiveyouanewshell,andwhenyoufinishwiththeshell,endingitbytypinga ˆ D,theeditorwillclearthescreenandcontinue. Onsystemswhichsupportit,ˆ Zwillsuspendtheeditorandreturntothe(toplevel)shell. Whentheeditorisresumed,thescreenwillberedrawn. 5.3.Markingandreturning Thecommand` ` returnedtothepreviousplaceafteramotionofthecursorbyacommand suchas/,?orG.Youcanalsomarklinesinthefilewithsinglelettertagsandreturntothese markslaterbynamingthetags.Trymarkingthecurrentlinewiththecommandmx,whereyou shouldpicksomeletterforx,say‘a’.Thenmovethecursortoadifferentline(anywayyoulike) andhit` a.Thecursorwillreturntotheplacewhichyoumarked.Markslastonlyuntilyouedit anotherfile.

-12-Whenusingoperatorssuchasdandreferringtomarkedlines,itisoftendesirabletodelete wholelinesratherthandeletingtotheexactpositioninthelinemarkedbym.Inthiscaseyou canusetheform´ xratherthan` x.Usedwithoutanoperator,´ xwillmovetothefirstnonwhitecharacterofthemarkedline;similarly´ ´ movestothefirstnon-whitecharacteroftheline containingthepreviouscontextmark` ` . 5.4.Adjustingthescreen Ifthescreenimageismessedupbecauseofatransmissionerrortoyourterminal,orbecause someprogramotherthantheeditorwroteoutputtoyourterminal,youcanhitaˆ L,theASCII form-feedcharacter,tocausethescreentoberefreshed. Onadumbterminal,ifthereare@linesinthemiddleofthescreenasaresultoflinedeletion,youmaygetridoftheselinesbytypingˆ Rtocausetheeditortoretypethescreen,closing uptheseholes. Finally,ifyouwishtoplaceacertainlineonthescreenatthetopmiddleorbottomofthe screen,youcanpositionthecursortothatline,andthengiveazcommand.Youshouldfollow thezcommandwithaRETURNifyouwantthelinetoappearatthetopofthewindow,a.ifyou wantitatthecenter,ora−ifyouwantitatthebottom.(z.,z-,andz+arenotavailableonall v2editors.) 6.Specialtopics 6.1.Editingonslowterminals Whenyouareonaslowterminal,itisimportanttolimittheamountofoutputwhichis generatedtoyourscreensothatyouwillnotsufferlongdelays,waitingforthescreentobe refreshed.Wehavealreadypointedouthowtheeditoroptimizestheupdatingofthescreenduringinsertionsondumbterminalstolimitthedelays,andhowtheeditoreraseslinesto@when theyaredeletedondumbterminals. Theuseoftheslowterminalinsertionmodeiscontrolledbytheslowopenoption.Youcan forcetheeditortousethismodeevenonfasterterminalsbygivingthecommand:seslowCR.If yoursystemissluggishthishelpslessentheamountofoutputcomingtoyourterminal.Youcan disablethisoptionby:senoslowCR. Theeditorcansimulateanintelligentterminalonadumbone.Trygivingthecommand:se redrawCR.Thissimulationgeneratesagreatdealofoutputandisgenerallytolerableonlyon lightlyloadedsystemsandfastterminals.Youcandisablethisbygivingthecommand :senoredrawCR. Theeditoralsomakeseditingmorepleasantatlowspeedbystartingeditinginasmallwindow,andlettingthewindowexpandasyouedit.Thisworksparticularlywellonintelligentterminals.Theeditorcanexpandthewindoweasilywhenyouinsertinthemiddleofthescreenon theseterminals.Ifpossible,trytheeditoronanintelligentterminaltoseehowthisworks. Youcancontrolthesizeofthewindowwhichisredrawneachtimethescreenisclearedby givingwindowsizesasargumenttothecommandswhichcauselargescreenmotions: :/?[[]]` ´ Thusifyouaresearchingforaparticularinstanceofacommonstringinafileyoucanprecede thefirstsearchcommandbyasmallnumber,say3,andtheeditorwilldrawthreelinewindows aroundeachinstanceofthestringwhichitlocates. Youcaneasilyexpandorcontractthewindow,placingthecurrentlineasyouchoose,by givinganumberonazcommand,afterthezandbeforethefollowingRETURN,.or−.Thusthe commandz5.redrawsthescreenwiththecurrentlineinthecenterofafivelinewindow.† †Notethatthecommand5z.hasanentirelydifferenteffect,placingline5inthecenterofanewwindow.

-13-Iftheeditorisredrawingorotherwiseupdatinglargeportionsofthedisplay,youcaninter-ruptthisupdatingbyhittingaDELorRUBasusual.Ifyoudothisyoumaypartiallyconfusethe editoraboutwhatisdisplayedonthescreen.Youcanstilleditthetextonthescreenifyouwish; clearuptheconfusionbyhittingaˆ L;ormoveorsearchagain,ignoringthecurrentstateofthe display. Seesection7.8onopenmodeforanotherwaytousethevicommandsetonslowterminals. 6.2.Options,set,andeditorstartupfiles Theeditorhasasetofoptions,someofwhichhavebeenmentionedabove.Themostuseful optionsaregiveninthefollowingtable. NameDefaultDescription autoindentnoai Supplyindentationautomatically autowritenoawAutomaticwritebefore:n,:ta,ˆ ↑,! ignorecasenoic Ignorecaseinsearching lispnolisp({)}commandsdealwithS-expressions listnolistTabsprintasˆ I;endoflinesmarkedwith$ magicnomagicThecharacters.[and*arespecialinscans numbernonuLinesaredisplayedprefixedwithlinenumbers paragraphspara=IPLPPPQPbpPLIMacronameswhichstartparagraphs redrawnoreSimulateasmartterminalonadumbone sectionssect=NHSHHHUMacronameswhichstartnewsections shiftwidthsw=8Shiftdistancefor<,>andinputˆ Dandˆ T showmatchnosmShowmatching(or{as)or}istyped slowopenslowPostponedisplayupdatesduringinserts termdumbThekindofterminalyouareusing. Theoptionsareofthreekinds:numericoptions,stringoptions,andtoggleoptions.You cansetnumericandstringoptionsbyastatementoftheform setopt=val andtoggleoptionscanbesetorunsetbystatementsofoneoftheforms setopt setnoopt ThesestatementscanbeplacedinyourEXINITinyourenvironment,orgivenwhileyouarerunningvibyprecedingthemwitha:andfollowingthemwithaCR. Youcangetalistofalloptionswhichyouhavechangedbythecommand:setCR,orthe valueofasingleoptionbythecommand:setopt?CR.Alistofallpossibleoptionsandtheirvaluesisgeneratedby:setallCR.Setcanbeabbreviatedse.Multipleoptionscanbeplacedonone line,e.g.:seaiawnuCR. Optionssetbythesetcommandonlylastwhileyoustayintheeditor.Itiscommonto wanttohavecertainoptionssetwheneveryouusetheeditor.Thiscanbeaccomplishedbycreatingalistofexcommands†whicharetoberuneverytimeyoustartupex,edit,orvi.Atypical listincludesasetcommand,andpossiblyafewmapcommands(onv3editors).Sinceitis advisabletogetthesecommandsononeline,theycanbeseparatedwiththe|character,for example: setaiawterse|map@dd|map#x whichsetstheoptionsautoindent,autowrite,terse,(thesetcommand),makes@deletealine, (thefirstmap),andmakes#deleteacharacter,(thesecondmap).(Seesection6.9fora descriptionofthemapcommand,whichonlyworksinversion3.)Thisstringshouldbeplacedin †Allcommandswhichstartwith:areexcommands.

-14-thevariableEXINITinyourenvironment.Ifyouusecsh,putthislineinthefile.logininyour homedirectory: setenvEXINIT´ setaiawterse|map@dd|map#x´ Ifyouusethestandardv7shell,puttheselinesinthefile.profileinyourhomedirectory: EXINIT=´ setaiawterse|map@dd|map#x´ exportEXINIT Onaversion6system,theconceptofenvironmentsisnotpresent.Inthiscase,putthelinein thefile.exrcinyourhomedirectory. setaiawterse|map@dd|map#x Ofcourse,theparticularsofthelinewoulddependonwhichoptionsyouwantedtoset. 6.3.Recoveringlostlines Youmighthaveaseriousproblemifyoudeleteanumberoflinesandthenregretthatthey weredeleted.Despairnot,theeditorsavesthelast9deletedblocksoftextinasetofnumbered registers1−9.Youcangetthen’thpreviousdeletedtextbackinyourfilebythecommand"np. The"heresaysthatabuffernameistofollow,nisthenumberofthebufferyouwishtotry(use thenumber1fornow),andpistheputcommand,whichputstextinthebufferafterthecursor. Ifthisdoesn’tbringbackthetextyouwanted,hitutoundothisandthen.(period)torepeat theputcommand.Ingeneralthe.commandwillrepeatthelastchangeyoumade.Asaspecial case,whenthelastcommandreferstoanumberedtextbuffer,the.commandincrementsthe numberofthebufferbeforerepeatingthecommand.Thusasequenceoftheform "1pu.u.u. will,ifrepeatedlongenough,showyouallthedeletedtextwhichhasbeensavedforyou.Youcan omittheucommandsheretogatherupallthistextinthebuffer,orstopafterany.commandto keepjustthethenrecoveredtext.ThecommandPcanalsobeusedratherthanptoputthe recoveredtextbeforeratherthanafterthecursor. 6.4.Recoveringlostfiles Ifthesystemcrashes,youcanrecovertheworkyouweredoingtowithinafewchanges. Youwillnormallyreceivemailwhenyounextlogingivingyouthenameofthefilewhichhasbeen savedforyou.Youshouldthenchangetothedirectorywhereyouwerewhenthesystemcrashed andgiveacommandoftheform: %vi−rname replacingnamewiththenameofthefilewhichyouwereediting.Thiswillrecoveryourworktoa pointnearwhereyouleftoff.† Youcangetalistingofthefileswhicharesavedforyoubygivingthecommand: %vi−r Ifthereismorethanoneinstanceofaparticularfilesaved,theeditorgivesyouthenewest instanceeachtimeyourecoverit.Youcanthusgetanoldersavedcopybackbyfirstrecovering thenewercopies. Forthisfeaturetowork,vimustbecorrectlyinstalledbyasuperuseronyoursystem,and themailprogrammustexisttoreceivemail.Theinvocation‘‘vi-r’’willnotalwayslistallsaved files,buttheycanberecoveredeveniftheyarenotlisted. †Inrarecases,someofthelinesofthefilemaybelost.Theeditorwillgiveyouthenumbersofthese linesandthetextofthelineswillbereplacedbythestring‘LOST’.Theselineswillalmostalwaysbe amongthelastfewwhichyouchanged.Youcaneitherchoosetodiscardthechangeswhichyoumade (iftheyareeasytoremake)ortoreplacethefewlostlinesbyhand.

-15-6.5.Continuoustextinput Whenyouaretypinginlargeamountsoftextitisconvenienttohavelinesbrokennearthe rightmarginautomatically.Youcancausethistohappenbygivingthecommand:se wm=10CR.Thiscausesalllinestobebrokenataspaceatleast10columnsfromtherighthand edgeofthescreen.* Iftheeditorbreaksaninputlineandyouwishtoputitbacktogetheryoucantellittojoin thelineswithJ.YoucangiveJacountofthenumberoflinestobejoinedasin3Jtojoin3 lines.Theeditorsupplieswhitespace,ifappropriate,atthejunctureofthejoinedlines,and leavesthecursoratthiswhitespace.Youcankillthewhitespacewithxifyoudon’twantit. 6.6.Featuresforeditingprograms Theeditorhasanumberofcommandsforeditingprograms.Thethingthatmostdistinguisheseditingofprogramsfromeditingoftextisthedesirabilityofmaintaininganindented structuretothebodyoftheprogram.Theeditorhasaautoindentfacilityforhelpingyougeneratecorrectlyindentedprograms. Toenablethisfacilityyoucangivethecommand:seaiCR.Nowtryopeninganewline withoandtypesomecharactersonthelineafterafewtabs.Ifyounowstartanotherline,notice thattheeditorsupplieswhitespaceatthebeginningofthelinetolineitupwiththeprevious line.Youcannotbackspaceoverthisindentation,butyoucanuseˆ Dkeytobacktaboverthe suppliedindentation. Eachtimeyoutypeˆ Dyoubackuponeposition,normallytoan8columnboundary.This amountissettable;theeditorhasanoptioncalledshiftwidthwhichyoucansettochangethis value.Trygivingthecommand:sesw=4CRandthenexperimentingwithautoindentagain. Forshiftinglinesintheprogramleftandright,thereareoperators<and>.Theseshift thelinesyouspecifyrightorleftbyoneshiftwidth.Try<<and>>whichshiftonelineleftor right,and<Land>Lshiftingtherestofthedisplayleftandright. Ifyouhaveacomplicatedexpressionandwishtoseehowtheparenthesesmatch,putthe cursorataleftorrightparenthesisandhit%.Thiswillshowyouthematchingparenthesis. Thisworksalsoforbraces{and},andbrackets[and]. IfyouareeditingCprograms,youcanusethe[[and]]keystoadvanceorretreattoaline startingwitha{,i.e.afunctiondeclarationatatime.When]]isusedwithanoperatoritstops afteralinewhichstartswith};thisissometimesusefulwithy]]. 6.7.Filteringportionsofthebuffer Youcanrunsystemcommandsoverportionsofthebufferusingtheoperator!.Youcanuse thistosortlinesinthebuffer,ortoreformatportionsofthebufferwithapretty-printer.Try typinginalistofrandomwords,oneperlineandendingthemwithablankline.Backuptothe beginningofthelist,andthengivethecommand!}sortCR.Thissaystosortthenextparagraph ofmaterial,andtheblanklineendsaparagraph. 6.8.CommandsforeditingLISP† IfyouareeditingaLISPprogramyoushouldsettheoptionlispbydoing:selispCR.This changesthe(and)commandstomovebackwardandforwardovers-expressions.The{and} commandsarelike(and)butdon’tstopatatoms.Thesecanbeusedtoskiptothenextlist,or throughacommentquickly. TheautoindentoptionworksdifferentlyforLISP,supplyingindenttoalignatthefirstargumenttothelastopenlist.Ifthereisnosuchargumentthentheindentistwospacesmorethan thelastlevel. *Thisfeatureisnotavailableonsomev2editors.Inv2editorswhereitisavailable,thebreakcan onlyoccurtotherightofthespecifiedboundaryinsteadoftotheleft. †TheLISPfeaturesarenotavailableonsomev2editorsduetomemoryconstraints.

-16-ThereisanotheroptionwhichisusefulfortypinginLISP,theshowmatchoption.Tryset-tingitwith:sesmCRandthentrytypinga‘(’somewordsandthena‘)’.Noticethatthecursor showsthepositionofthe‘(’whichmatchesthe‘)’briefly.Thishappensonlyifthematching‘(’is onthescreen,andthecursorstaysthereforatmostonesecond. Theeditoralsohasanoperatortorealignexistinglinesasthoughtheyhadbeentypedin withlispandautoindentset.Thisisthe=operator.Trythecommand=%atthebeginningof afunction.Thiswillrealignallthelinesofthefunctiondeclaration. WhenyouareeditingLISP,,the[[and]]advanceandretreattolinesbeginningwitha(, andareusefulfordealingwithentirefunctiondefinitions. 6.9.Macros‡ Vihasaparameterlessmacrofacility,whichletsyousetitupsothatwhenyouhitasingle keystroke,theeditorwillactasthoughyouhadhitsomelongersequenceofkeys.Youcanset thisupifyoufindyourselftypingthesamesequenceofcommandsrepeatedly. Briefly,therearetwoflavorsofmacros: a)Oneswhereyouputthemacrobodyinabufferregister,sayx.Youcanthentype@xto invokethemacro.The@maybefollowedbyanother@torepeatthelastmacro. b)Youcanusethemapcommandfromvi(typicallyinyourEXINIT)withacommandofthe form: :maplhsrhsCR mappinglhsintorhs.Therearerestrictions:lhsshouldbeonekeystroke(either1character oronefunctionkey)sinceitmustbeenteredwithinonesecond(unlessnotimeoutisset,in whichcaseyoucantypeitasslowlyasyouwish,andviwillwaitforyoutofinishitbefore itechoesanything).Thelhscanbenolongerthan10characters,therhsnolongerthan 100.Togetaspace,tabornewlineintolhsorrhsyoushouldescapethemwithaˆ V.(It maybenecessarytodoubletheˆ Vifthemapcommandisgiveninsidevi,ratherthanin ex.)Spacesandtabsinsidetherhsneednotbeescaped. Thustomaketheqkeywriteandexittheeditor,youcangivethecommand :mapq:wqˆ Vˆ VCRCR whichmeansthatwheneveryoutypeq,itwillbeasthoughyouhadtypedthefourcharacters :wqCR.Aˆ V’sisneededbecausewithoutittheCRwouldendthe:command,ratherthan becomingpartofthemapdefinition.Therearetwoˆ V’sbecausefromwithinvi,twoˆ V’smust betypedtogetone.ThefirstCRispartoftherhs,thesecondterminatesthe:command. Macroscanbedeletedwith unmaplhs Ifthelhsofamacrois‘‘#0’’through‘‘#9’’,thismapstheparticularfunctionkeyinsteadof the2character‘‘#’’sequence.Sothatterminalswithoutfunctionkeyscanaccesssuchdefinitions,theform‘‘#x’’willmeanfunctionkeyxonallterminals(andneednotbetypedwithinone second.)Thecharacter‘‘#’’canbechangedbyusingamacrointheusualway: :mapˆ Vˆ Vˆ I# tousetab,forexample.(Thiswon’taffectthemapcommand,whichstilluses#,butjustthe invocationfromvisualmode. Theundocommandreversesanentiremacrocallasaunit,ifitmadeanychanges. Placinga‘!’afterthewordmapcausesthemappingtoapplytoinputmode,ratherthan commandmode.Thus,toarrangeforˆ Ttobethesameas4spacesininputmode,youcan type: ‡Themacrofeatureisavailableonlyinversion3editors.

-17- :mapˆ Tˆ Vb/b/b/b/ whereb/isablank.Theˆ Visnecessarytopreventtheblanksfrombeingtakenaswhitespace betweenthelhsandrhs. 7.WordAbbreviations‡‡ Afeaturesimilartomacrosininputmodeiswordabbreviation.Thisallowsyoutotypea shortwordandhaveitexpandedintoalongerwordorwords.Thecommandsare:abbreviate and:unabbreviate(:aband:una)andhavethesamesyntaxas:map.Forexample: :abeecsElectricalEngineeringandComputerSciences causestheword‘eecs’toalwaysbechangedintothephrase‘ElectricalEngineeringandComputer Sciences’.Wordabbreviationisdifferentfrommacrosinthatonlywholewordsareaffected.If ‘eecs’weretypedaspartofalargerword,itwouldbeleftalone.Also,thepartialwordisechoed asitistyped.Thereisnoneedforanabbreviationtobeasinglekeystroke,asitshouldbewith amacro. 7.1.Abbreviations Theeditorhasanumberofshortcommandswhichabbreviatelongercommandswhichwe haveintroducedhere.Youcanfindthesecommandseasilyonthequickreferencecard.They oftensaveabitoftypingandyoucanlearnthemasconvenient. 8.Nitty-grittydetails 8.1.Linerepresentationinthedisplay Theeditorfoldslonglogicallinesontomanyphysicallinesinthedisplay.Commandswhich advancelinesadvancelogicallinesandwillskipoverallthesegmentsofalineinonemotion. Thecommand|movesthecursortoaspecificcolumn,andmaybeusefulforgettingnearthe middleofalonglinetosplititinhalf.Try80|onalinewhichismorethan80columnslong.† Theeditoronlyputsfulllinesonthedisplay;ifthereisnotenoughroomonthedisplayto fitalogicalline,theeditorleavesthephysicallineempty,placingonlyan@onthelineasaplace holder.Whenyoudeletelinesonadumbterminal,theeditorwilloftenjustclearthelinesto@ tosavetime(ratherthanrewritingtherestofthescreen.)Youcanalwaysmaximizetheinformationonthescreenbygivingtheˆ Rcommand. Ifyouwish,youcanhavetheeditorplacelinenumbersbeforeeachlineonthedisplay.Give thecommand:senuCRtoenablethis,andthecommand:senonuCRtoturnitoff.Youcan havetabsrepresentedasˆ Iandtheendsoflinesindicatedwith‘$’bygivingthecommand:se listCR;:senolistCRturnsthisoff. Finally,linesconsistingofonlythecharacter‘˜ ’aredisplayedwhenthelastlineinthefileis inthemiddleofthescreen.Theserepresentphysicallineswhicharepastthelogicalendoffile. 8.2.Counts Mostvicommandswilluseaprecedingcounttoaffecttheirbehaviorinsomeway.Thefollowingtablegivesthecommonwaysinwhichthecountsareused: newwindowsize:/?[[]]` ´ scrollamountˆ Dˆ U line/columnnumberzG| repeateffectmostoftherest ‡‡Version3only. †YoucanmakelonglinesveryeasilybyusingJtojointogethershortlines.

-18-Theeditormaintainsanotionofthecurrentdefaultwindowsize.Onterminalswhichrun atspeedsgreaterthan1200baudtheeditorusesthefullterminalscreen.Onterminalswhichare slowerthan1200baud(mostdialuplinesareinthisgroup)theeditoruses8linesasthedefault windowsize.At1200baudthedefaultis16lines. Thissizeisthesizeusedwhentheeditorclearsandrefillsthescreenafterasearchorother motionmovesfarfromtheedgeofthecurrentwindow.Thecommandswhichtakeanewwindow sizeascountalloftencausethescreentoberedrawn.Ifyouanticipatethis,butdonotneedas largeawindowasyouarecurrentlyusing,youmaywishtochangethescreensizebyspecifying thenewsizebeforethesecommands.Inanycase,thenumberoflinesusedonthescreenwill expandifyoumoveoffthetopwitha−orsimilarcommandoroffthebottomwithacommand suchasRETURNorˆ D.Thewindowwillreverttothelastspecifiedsizethenexttimeitis clearedandrefilled.† Thescrollcommandsˆ Dandˆ Ulikewiseremembertheamountofscrolllastspecified, usinghalfthebasicwindowsizeinitially.Thesimpleinsertcommandsuseacounttospecifya repetitionoftheinsertedtext.Thus10a+−−−−ESCwillinsertagrid-likestringoftext.Afew commandsalsouseaprecedingcountasalineorcolumnnumber. Exceptforafewcommandswhichignoreanycounts(suchasˆ R),therestoftheeditor commandsuseacounttoindicateasimplerepetitionoftheireffect.Thus5wadvancesfive wordsonthecurrentline,while5RETURNadvancesfivelines.Averyusefulinstanceofacountas arepetitionisacountgiventothe.command,whichrepeatsthelastchangingcommand.Ifyou dodwandthen3.,youwilldeletefirstoneandthenthreewords.Youcanthendeletetwomore wordswith2.. 8.3.Morefilemanipulationcommands Thefollowingtableliststhefilemanipulationcommandswhichyoucanusewhenyouarein vi. :wwritebackchanges :wqwriteandquit :xwrite(ifnecessary)andquit(sameasZZ). :enameeditfilename :e!reedit,discardingchanges :e+nameedit,startingatend :e+nedit,startingatlinen :e#editalternatefile :wnamewritefilename :w!nameoverwritefilename :x,ywnamewritelinesxthroughytoname :rnamereadfilenameintobuffer :r!cmdreadoutputofcmdintobuffer :neditnextfileinargumentlist :n!editnextfile,discardingchangestocurrent :nargsspecifynewargumentlist :tatageditfilecontainingtagtag,attag AllofthesecommandsarefollowedbyaCRorESC.Themostbasiccommandsare:wand:e.A normaleditingsessiononasinglefilewillendwithaZZcommand.Ifyouareeditingforalong periodoftimeyoucangive:wcommandsoccasionallyaftermajoramountsofediting,andthen finishwithaZZ.Whenyoueditmorethanonefile,youcanfinishwithonewitha:wandstart editinganewfilebygivinga:ecommand,orsetautowriteanduse:n<file>. †Butnotbyaˆ Lwhichjustredrawsthescreenasitis.

-19-Ifyoumakechangestotheeditor’scopyofafile,butdonotwishtowritethemback,then youmustgivean!afterthecommandyouwouldotherwiseuse;thisforcestheeditortodiscard anychangesyouhavemade.Usethiscarefully. The:ecommandcanbegivena+argumenttostartattheendofthefile,ora+nargumenttostartatlinen.Inactuality,nmaybeanyeditorcommandnotcontainingaspace,usefullyascanlike+/pator+?pat.Informingnewnamestotheecommand,youcanusethecharacter%whichisreplacedbythecurrentfilename,orthecharacter#whichisreplacedbythe alternatefilename.Thealternatefilenameisgenerallythelastnameyoutypedotherthanthe currentfile.Thusifyoutrytodoa:eandgetadiagnosticthatyouhaven’twrittenthefile,you cangivea:wcommandandthena:e#commandtoredotheprevious:e. Youcanwritepartofthebuffertoafilebyfindingoutthelinesthatboundtherangetobe writtenusingˆ G,andgivingthesenumbersafterthe:andbeforethew,separatedby,’s.You canalsomarktheselineswithmandthenuseanaddressoftheform´ x,´ yonthewcommand here. Youcanreadanotherfileintothebufferafterthecurrentlinebyusingthe:rcommand. Youcansimilarlyreadintheoutputfromacommand,justuse!cmdinsteadofafilename. Ifyouwishtoeditasetoffilesinsuccession,youcangiveallthenamesonthecommand line,andthenediteachoneinturnusingthecommand:n.Itisalsopossibletorespecifythelist offilestobeeditedbygivingthe:ncommandalistoffilenames,orapatterntobeexpandedas youwouldhavegivenitontheinitialvicommand. Ifyouareeditinglargeprograms,youwillfindthe:tacommandveryuseful.Itutilizesa databaseoffunctionnamesandtheirlocations,whichcanbecreatedbyprogramssuchasctags, toquicklyfindafunctionwhosenameyougive.Ifthe:tacommandwillrequiretheeditorto switchfiles,thenyoumust:worabandonanychangesbeforeswitching.Youcanrepeatthe:ta commandwithoutanyargumentstolookforthesametagagain.(Thetagfeatureisnotavailable insomev2editors.) 8.4.Moreaboutsearchingforstrings Whenyouaresearchingforstringsinthefilewith/and?,theeditornormallyplacesyou atthenextorpreviousoccurrenceofthestring.Ifyouareusinganoperatorsuchasd,cory, thenyoumaywellwishtoaffectlinesuptothelinebeforethelinecontainingthepattern.You cangiveasearchoftheform/pat/−ntorefertothen’thlinebeforethenextlinecontainingpat, oryoucanuse+insteadof−torefertothelinesaftertheonecontainingpat.Ifyoudon’tgive alineoffset,thentheeditorwillaffectcharactersuptothematchplace,ratherthanwholelines; thususe‘‘+0’’toaffecttothelinewhichmatches. Youcanhavetheeditorignorethecaseofwordsinthesearchesitdoesbygivingthecommand:seicCR.Thecommand:senoicCRturnsthisoff. Stringsgiventosearchesmayactuallyberegularexpressions.Ifyoudonotwantorneed thisfacility,youshould setnomagic inyourEXINIT.Inthiscase,onlythecharacters↑and$arespecialinpatterns.Thecharacter \isalsothenspecial(asitismosteverywhereinthesystem),andmaybeusedtogetatthean extendedpatternmatchingfacility.Itisalsonecessarytousea\beforea/inaforwardscanor a?inabackwardscan,inanycase.Thefollowingtablegivestheextendedformswhenmagicis set. Ifyouusenomagicmode,thenthe.[and*primitivesaregivenwithapreceding\.

-20-8.5.Moreaboutinputmode Thereareanumberofcharacterswhichyoucanusetomakecorrectionsduringinputmode. Thesearesummarizedinthefollowingtable. ˆ Hdeletesthelastinputcharacter ˆ Wdeletesthelastinputword,definedasbyb eraseyourerasecharacter,sameasˆ H killyourkillcharacter,deletestheinputonthisline \escapesafollowingˆ Handyoureraseandkill ESCendsaninsertion DELinterruptsaninsertion,terminatingitabnormally CRstartsanewline ˆ Dbacktabsoverautoindent 0ˆ Dkillsalltheautoindent ↑ˆ Dsameas0ˆ D,butrestoresindentnextline ˆ Vquotesthenextnon-printingcharacterintothefile Themostusualwayofmakingcorrectionstoinputisbytypingˆ Htocorrectasinglecharacter,orbytypingoneormoreˆ W’stobackoverincorrectwords.Ifyouuse#asyourerase characterinthenormalsystem,itwillworklikeˆ H. Yoursystemkillcharacter,normally@,ˆ Xorˆ U,willerasealltheinputyouhavegiven onthecurrentline.Ingeneral,youcanneithereraseinputbackaroundalineboundarynorcan youerasecharacterswhichyoudidnotinsertwiththisinsertioncommand.Tomakecorrections onthepreviouslineafteranewlinehasbeenstartedyoucanhitESCtoendtheinsertion,move overandmakethecorrection,andthenreturntowhereyouweretocontinue.ThecommandA whichappendsattheendofthecurrentlineisoftenusefulforcontinuing. Ifyouwishtotypeinyoureraseorkillcharacter(say#or@)thenyoumustprecedeit witha\,justasyouwoulddoatthenormalsystemcommandlevel.Amoregeneralwayoftypingnon-printingcharactersintothefileistoprecedethemwithaˆ V.Theˆ Vechoesasa↑ characteronwhichthecursorrests.Thisindicatesthattheeditorexpectsyoutotypeacontrol character.Infactyoumaytypeanycharacteranditwillbeinsertedintothefileatthatpoint.* Ifyouareusingautoindentyoucanbacktabovertheindentwhichitsuppliesbytypinga ˆ D.Thisbacksuptoashiftwidthboundary.Thisonlyworksimmediatelyafterthesupplied autoindent. Whenyouareusingautoindentyoumaywishtoplacealabelattheleftmarginofaline. Thewaytodothiseasilyistotype↑andthenˆ D.Theeditorwillmovethecursortotheleft marginforoneline,andrestorethepreviousindentonthenext.Youcanalsotypea0followed immediatelybyaˆ Difyouwishtokillalltheindentandnothaveitcomebackonthenextline. 8.6.Uppercaseonlyterminals Ifyourterminalhasonlyuppercase,youcanstillusevibyusingthenormalsystemconventionfortypingonsuchaterminal.Characterswhichyounormallytypeareconvertedtolower case,andyoucantypeuppercaselettersbyprecedingthemwitha\.Thecharacters{˜ }|` arenotavailableonsuchterminals,butyoucanescapethemas\(\↑\)\!\´ .Thesecharacters *Thisisnotquitetrue.TheimplementationoftheeditordoesnotallowtheNULL(ˆ @)characterto appearinfiles.AlsotheLF(linefeedorˆ J)characterisusedbytheeditortoseparatelinesinthefile, soitcannotappearinthemiddleofaline.Youcaninsertanyothercharacter,however,ifyouwait fortheeditortoechothe↑beforeyoutypethecharacter.Infact,theeditorwilltreatafollowingletterasarequestforthecorrespondingcontrolcharacter.Thisistheonlywaytotypeˆ Sorˆ Q,since thesystemnormallyusesthemtosuspendandresumeoutputandnevergivesthemtotheeditorto process. ‡The\characteryougivewillnotechountilyoutypeanotherkey.

-21-arerepresentedonthedisplayinthesamewaytheyaretyped.‡‡ 8.7.Viandex Viisactuallyonemodeofeditingwithintheeditorex.Whenyouarerunningviyoucan escapetothelineorientededitorofexbygivingthecommandQ.Allofthe:commandswhich wereintroducedaboveareavailableinex.Likewise,mostexcommandscanbeinvokedfromvi using:.Justgivethemwithoutthe:andfollowthemwithaCR. Inrareinstances,aninternalerrormayoccurinvi.Inthiscaseyouwillgetadiagnostic andbeleftinthecommandmodeofex.Youcanthensaveyourworkandquitifyouwishby givingacommandxafterthe:whichexpromptsyouwith,oryoucanreentervibygivingexavi command. Thereareanumberofthingswhichyoucandomoreeasilyinexthaninvi.Systematic changesinlineorientedmaterialareparticularlyeasy.Youcanreadtheadvancededitingdocumentsfortheeditoredtofindoutalotmoreaboutthisstyleofediting.Experiencedusersoften mixtheiruseofexcommandmodeandvicommandmodetospeedtheworktheyaredoing. 8.8.Openmode:vionhardcopyterminalsand‘‘glasstty’s’’‡ Ifyouareonahardcopyterminaloraterminalwhichdoesnothaveacursorwhichcan moveoffthebottomline,youcanstillusethecommandsetofvi,butinadifferentmode.When yougiveavicommand,theeditorwilltellyouthatitisusingopenmode.Thisnamecomesfrom theopencommandinex,whichisusedtogetintothesamemode. Theonlydifferencebetweenvisualmodeandopenmodeisthewayinwhichthetextisdisplayed. Inopenmodetheeditorusesasinglelinewindowintothefile,andmovingbackwardand forwardinthefilecausesnewlinestobedisplayed,alwaysbelowthecurrentline.Twocommandsofviworkdifferentlyinopen:zandˆ R.Thezcommanddoesnottakeparameters,but ratherdrawsawindowofcontextaroundthecurrentlineandthenreturnsyoutothecurrentline. Ifyouareonahardcopyterminal,theˆ Rcommandwillretypethecurrentline.Onsuch terminals,theeditornormallyusestwolinestorepresentthecurrentline.Thefirstlineisacopy ofthelineasyoustartedtoeditit,andyouworkonthelinebelowthisline.Whenyoudelete characters,theeditortypesanumberof\’stoshowyouthecharacterswhicharedeleted.The editoralsoreprintsthecurrentlinesoonaftersuchchangessothatyoucanseewhattheline lookslikeagain. Itissometimesusefultousethismodeonveryslowterminalswhichcansupportviinthe fullscreenmode.Youcandothisbyenteringexandusinganopencommand. Acknowledgements BruceEnglarencouragedtheearlydevelopmentofthisdisplayeditor.PeterKesslerhelped bringsanitytoversion2’scommandlayout.BillJoywroteversions1and2.0through2.7,and createdtheframeworkthatusersseeinthepresenteditor.MarkHortonaddedmacrosandother featuresandmadetheeditorworkonalargenumberofterminalsandUnixsystems. ‡Notavailableinallv2editorsduetomemoryconstraints.