eval.txt 166 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758
  1. *eval.txt* For Vim version 9.0. Last change: 2022 Dec 11
  2. VIM REFERENCE MANUAL by Bram Moolenaar
  3. Expression evaluation *expression* *expr* *E15* *eval*
  4. *E1002*
  5. Using expressions is introduced in chapter 41 of the user manual |usr_41.txt|.
  6. Note: Expression evaluation can be disabled at compile time. If this has been
  7. done, the features in this document are not available. See |+eval| and
  8. |no-eval-feature|.
  9. This file is mainly about the backwards compatible (legacy) Vim script. For
  10. specifics of Vim9 script, which can execute much faster, supports type
  11. checking and much more, see |vim9.txt|. Where the syntax or semantics differ
  12. a remark is given.
  13. 1. Variables |variables|
  14. 1.1 Variable types
  15. 1.2 Function references |Funcref|
  16. 1.3 Lists |Lists|
  17. 1.4 Dictionaries |Dictionaries|
  18. 1.5 Blobs |Blobs|
  19. 1.6 More about variables |more-variables|
  20. 2. Expression syntax |expression-syntax|
  21. 3. Internal variable |internal-variables|
  22. 4. Builtin Functions |functions|
  23. 5. Defining functions |user-functions|
  24. 6. Curly braces names |curly-braces-names|
  25. 7. Commands |expression-commands|
  26. 8. Exception handling |exception-handling|
  27. 9. Examples |eval-examples|
  28. 10. Vim script version |vimscript-version|
  29. 11. No +eval feature |no-eval-feature|
  30. 12. The sandbox |eval-sandbox|
  31. 13. Textlock |textlock|
  32. Testing support is documented in |testing.txt|.
  33. Profiling is documented at |profiling|.
  34. ==============================================================================
  35. 1. Variables *variables*
  36. 1.1 Variable types ~
  37. *E712* *E896* *E897* *E899* *E1098*
  38. *E1107* *E1135* *E1138*
  39. There are ten types of variables:
  40. *Number* *Integer*
  41. Number A 32 or 64 bit signed number. |expr-number|
  42. The number of bits is available in |v:numbersize|.
  43. Examples: -123 0x10 0177 0o177 0b1011
  44. Float A floating point number. |floating-point-format| *Float*
  45. Examples: 123.456 1.15e-6 -1.1e3
  46. String A NUL terminated string of 8-bit unsigned characters (bytes).
  47. |expr-string| Examples: "ab\txx\"--" 'x-z''a,c'
  48. List An ordered sequence of items, see |List| for details.
  49. Example: [1, 2, ['a', 'b']]
  50. Dictionary An associative, unordered array: Each entry has a key and a
  51. value. |Dictionary|
  52. Examples:
  53. {'blue': "#0000ff", 'red': "#ff0000"}
  54. #{blue: "#0000ff", red: "#ff0000"}
  55. Funcref A reference to a function |Funcref|.
  56. Example: function("strlen")
  57. It can be bound to a dictionary and arguments, it then works
  58. like a Partial.
  59. Example: function("Callback", [arg], myDict)
  60. Special |v:false|, |v:true|, |v:none| and |v:null|. *Special*
  61. Job Used for a job, see |job_start()|. *Job* *Jobs*
  62. Channel Used for a channel, see |ch_open()|. *Channel* *Channels*
  63. Blob Binary Large Object. Stores any sequence of bytes. See |Blob|
  64. for details
  65. Example: 0zFF00ED015DAF
  66. 0z is an empty Blob.
  67. The Number and String types are converted automatically, depending on how they
  68. are used.
  69. Conversion from a Number to a String is by making the ASCII representation of
  70. the Number. Examples:
  71. Number 123 --> String "123" ~
  72. Number 0 --> String "0" ~
  73. Number -1 --> String "-1" ~
  74. *octal*
  75. Conversion from a String to a Number only happens in legacy Vim script, not in
  76. Vim9 script. It is done by converting the first digits to a number.
  77. Hexadecimal "0xf9", Octal "017" or "0o17", and Binary "0b10"
  78. numbers are recognized
  79. NOTE: when using |Vim9| script or |scriptversion-4| octal with a leading "0"
  80. is not recognized. The 0o notation requires patch 8.2.0886.
  81. If the String doesn't start with digits, the result is zero.
  82. Examples:
  83. String "456" --> Number 456 ~
  84. String "6bar" --> Number 6 ~
  85. String "foo" --> Number 0 ~
  86. String "0xf1" --> Number 241 ~
  87. String "0100" --> Number 64 ~
  88. String "0o100" --> Number 64 ~
  89. String "0b101" --> Number 5 ~
  90. String "-8" --> Number -8 ~
  91. String "+8" --> Number 0 ~
  92. To force conversion from String to Number, add zero to it: >
  93. :echo "0100" + 0
  94. < 64 ~
  95. To avoid a leading zero to cause octal conversion, or for using a different
  96. base, use |str2nr()|.
  97. *TRUE* *FALSE* *Boolean*
  98. For boolean operators Numbers are used. Zero is FALSE, non-zero is TRUE.
  99. You can also use |v:false| and |v:true|, in Vim9 script |false| and |true|.
  100. When TRUE is returned from a function it is the Number one, FALSE is the
  101. number zero.
  102. Note that in the command: >
  103. :if "foo"
  104. :" NOT executed
  105. "foo" is converted to 0, which means FALSE. If the string starts with a
  106. non-zero number it means TRUE: >
  107. :if "8foo"
  108. :" executed
  109. To test for a non-empty string, use empty(): >
  110. :if !empty("foo")
  111. < *falsy* *truthy*
  112. An expression can be used as a condition, ignoring the type and only using
  113. whether the value is "sort of true" or "sort of false". Falsy is:
  114. the number zero
  115. empty string, blob, list or dictionary
  116. Other values are truthy. Examples:
  117. 0 falsy
  118. 1 truthy
  119. -1 truthy
  120. 0.0 falsy
  121. 0.1 truthy
  122. '' falsy
  123. 'x' truthy
  124. [] falsy
  125. [0] truthy
  126. {} falsy
  127. #{x: 1} truthy
  128. 0z falsy
  129. 0z00 truthy
  130. *non-zero-arg*
  131. Function arguments often behave slightly different from |TRUE|: If the
  132. argument is present and it evaluates to a non-zero Number, |v:true| or a
  133. non-empty String, then the value is considered to be TRUE.
  134. Note that " " and "0" are also non-empty strings, thus considered to be TRUE.
  135. A List, Dictionary or Float is not a Number or String, thus evaluate to FALSE.
  136. *E611* *E745* *E728* *E703* *E729* *E730* *E731* *E908* *E910*
  137. *E913* *E974* *E975* *E976* *E1319* *E1320* *E1321* *E1322*
  138. *E1323* *E1324*
  139. |List|, |Dictionary|, |Funcref|, |Job|, |Channel|, |Blob|, |Class| and
  140. |object| types are not automatically converted.
  141. *E805* *E806* *E808*
  142. When mixing Number and Float the Number is converted to Float. Otherwise
  143. there is no automatic conversion of Float. You can use str2float() for String
  144. to Float, printf() for Float to String and float2nr() for Float to Number.
  145. *E362* *E891* *E892* *E893* *E894* *E907* *E911* *E914*
  146. When expecting a Float a Number can also be used, but nothing else.
  147. *no-type-checking*
  148. You will not get an error if you try to change the type of a variable.
  149. 1.2 Function references ~
  150. *Funcref* *E695* *E718* *E1192*
  151. A Funcref variable is obtained with the |function()| function, the |funcref()|
  152. function, (in |Vim9| script) the name of a function, or created with the
  153. lambda expression |expr-lambda|. It can be used in an expression in the place
  154. of a function name, before the parenthesis around the arguments, to invoke the
  155. function it refers to. Example in |Vim9| script: >
  156. :var Fn = MyFunc
  157. :echo Fn()
  158. Legacy script: >
  159. :let Fn = function("MyFunc")
  160. :echo Fn()
  161. < *E704* *E705* *E707*
  162. A Funcref variable must start with a capital, "s:", "w:", "t:" or "b:". You
  163. can use "g:" but the following name must still start with a capital. You
  164. cannot have both a Funcref variable and a function with the same name.
  165. A special case is defining a function and directly assigning its Funcref to a
  166. Dictionary entry. Example: >
  167. :function dict.init() dict
  168. : let self.val = 0
  169. :endfunction
  170. The key of the Dictionary can start with a lower case letter. The actual
  171. function name is not used here. Also see |numbered-function|.
  172. A Funcref can also be used with the |:call| command: >
  173. :call Fn()
  174. :call dict.init()
  175. The name of the referenced function can be obtained with |string()|. >
  176. :let func = string(Fn)
  177. You can use |call()| to invoke a Funcref and use a list variable for the
  178. arguments: >
  179. :let r = call(Fn, mylist)
  180. <
  181. *Partial*
  182. A Funcref optionally binds a Dictionary and/or arguments. This is also called
  183. a Partial. This is created by passing the Dictionary and/or arguments to
  184. function() or funcref(). When calling the function the Dictionary and/or
  185. arguments will be passed to the function. Example: >
  186. let Cb = function('Callback', ['foo'], myDict)
  187. call Cb('bar')
  188. This will invoke the function as if using: >
  189. call myDict.Callback('foo', 'bar')
  190. This is very useful when passing a function around, e.g. in the arguments of
  191. |ch_open()|.
  192. Note that binding a function to a Dictionary also happens when the function is
  193. a member of the Dictionary: >
  194. let myDict.myFunction = MyFunction
  195. call myDict.myFunction()
  196. Here MyFunction() will get myDict passed as "self". This happens when the
  197. "myFunction" member is accessed. When making assigning "myFunction" to
  198. otherDict and calling it, it will be bound to otherDict: >
  199. let otherDict.myFunction = myDict.myFunction
  200. call otherDict.myFunction()
  201. Now "self" will be "otherDict". But when the dictionary was bound explicitly
  202. this won't happen: >
  203. let myDict.myFunction = function(MyFunction, myDict)
  204. let otherDict.myFunction = myDict.myFunction
  205. call otherDict.myFunction()
  206. Here "self" will be "myDict", because it was bound explicitly.
  207. 1.3 Lists ~
  208. *list* *List* *Lists* *E686*
  209. A List is an ordered sequence of items. An item can be of any type. Items
  210. can be accessed by their index number. Items can be added and removed at any
  211. position in the sequence.
  212. List creation ~
  213. *E696* *E697*
  214. A List is created with a comma-separated list of items in square brackets.
  215. Examples: >
  216. :let mylist = [1, two, 3, "four"]
  217. :let emptylist = []
  218. An item can be any expression. Using a List for an item creates a
  219. List of Lists: >
  220. :let nestlist = [[11, 12], [21, 22], [31, 32]]
  221. An extra comma after the last item is ignored.
  222. List index ~
  223. *list-index* *E684*
  224. An item in the List can be accessed by putting the index in square brackets
  225. after the List. Indexes are zero-based, thus the first item has index zero. >
  226. :let item = mylist[0] " get the first item: 1
  227. :let item = mylist[2] " get the third item: 3
  228. When the resulting item is a list this can be repeated: >
  229. :let item = nestlist[0][1] " get the first list, second item: 12
  230. <
  231. A negative index is counted from the end. Index -1 refers to the last item in
  232. the List, -2 to the last but one item, etc. >
  233. :let last = mylist[-1] " get the last item: "four"
  234. To avoid an error for an invalid index use the |get()| function. When an item
  235. is not available it returns zero or the default value you specify: >
  236. :echo get(mylist, idx)
  237. :echo get(mylist, idx, "NONE")
  238. List concatenation ~
  239. *list-concatenation*
  240. Two lists can be concatenated with the "+" operator: >
  241. :let longlist = mylist + [5, 6]
  242. :let mylist += [7, 8]
  243. To prepend or append an item, turn the item into a list by putting [] around
  244. it. To change a list in-place, refer to |list-modification| below.
  245. Sublist ~
  246. *sublist*
  247. A part of the List can be obtained by specifying the first and last index,
  248. separated by a colon in square brackets: >
  249. :let shortlist = mylist[2:-1] " get List [3, "four"]
  250. Omitting the first index is similar to zero. Omitting the last index is
  251. similar to -1. >
  252. :let endlist = mylist[2:] " from item 2 to the end: [3, "four"]
  253. :let shortlist = mylist[2:2] " List with one item: [3]
  254. :let otherlist = mylist[:] " make a copy of the List
  255. Notice that the last index is inclusive. If you prefer using an exclusive
  256. index use the |slice()| method.
  257. If the first index is beyond the last item of the List or the second item is
  258. before the first item, the result is an empty list. There is no error
  259. message.
  260. If the second index is equal to or greater than the length of the list the
  261. length minus one is used: >
  262. :let mylist = [0, 1, 2, 3]
  263. :echo mylist[2:8] " result: [2, 3]
  264. NOTE: mylist[s:e] means using the variable "s:e" as index. Watch out for
  265. using a single letter variable before the ":". Insert a space when needed:
  266. mylist[s : e].
  267. List identity ~
  268. *list-identity*
  269. When variable "aa" is a list and you assign it to another variable "bb", both
  270. variables refer to the same list. Thus changing the list "aa" will also
  271. change "bb": >
  272. :let aa = [1, 2, 3]
  273. :let bb = aa
  274. :call add(aa, 4)
  275. :echo bb
  276. < [1, 2, 3, 4]
  277. Making a copy of a list is done with the |copy()| function. Using [:] also
  278. works, as explained above. This creates a shallow copy of the list: Changing
  279. a list item in the list will also change the item in the copied list: >
  280. :let aa = [[1, 'a'], 2, 3]
  281. :let bb = copy(aa)
  282. :call add(aa, 4)
  283. :let aa[0][1] = 'aaa'
  284. :echo aa
  285. < [[1, aaa], 2, 3, 4] >
  286. :echo bb
  287. < [[1, aaa], 2, 3]
  288. To make a completely independent list use |deepcopy()|. This also makes a
  289. copy of the values in the list, recursively. Up to a hundred levels deep.
  290. The operator "is" can be used to check if two variables refer to the same
  291. List. "isnot" does the opposite. In contrast "==" compares if two lists have
  292. the same value. >
  293. :let alist = [1, 2, 3]
  294. :let blist = [1, 2, 3]
  295. :echo alist is blist
  296. < 0 >
  297. :echo alist == blist
  298. < 1
  299. Note about comparing lists: Two lists are considered equal if they have the
  300. same length and all items compare equal, as with using "==". There is one
  301. exception: When comparing a number with a string they are considered
  302. different. There is no automatic type conversion, as with using "==" on
  303. variables. Example: >
  304. echo 4 == "4"
  305. < 1 >
  306. echo [4] == ["4"]
  307. < 0
  308. Thus comparing Lists is more strict than comparing numbers and strings. You
  309. can compare simple values this way too by putting them in a list: >
  310. :let a = 5
  311. :let b = "5"
  312. :echo a == b
  313. < 1 >
  314. :echo [a] == [b]
  315. < 0
  316. List unpack ~
  317. To unpack the items in a list to individual variables, put the variables in
  318. square brackets, like list items: >
  319. :let [var1, var2] = mylist
  320. When the number of variables does not match the number of items in the list
  321. this produces an error. To handle any extra items from the list append ";"
  322. and a variable name: >
  323. :let [var1, var2; rest] = mylist
  324. This works like: >
  325. :let var1 = mylist[0]
  326. :let var2 = mylist[1]
  327. :let rest = mylist[2:]
  328. Except that there is no error if there are only two items. "rest" will be an
  329. empty list then.
  330. List modification ~
  331. *list-modification*
  332. To change a specific item of a list use |:let| this way: >
  333. :let list[4] = "four"
  334. :let listlist[0][3] = item
  335. To change part of a list you can specify the first and last item to be
  336. modified. The value must at least have the number of items in the range: >
  337. :let list[3:5] = [3, 4, 5]
  338. Adding and removing items from a list is done with functions. Here are a few
  339. examples: >
  340. :call insert(list, 'a') " prepend item 'a'
  341. :call insert(list, 'a', 3) " insert item 'a' before list[3]
  342. :call add(list, "new") " append String item
  343. :call add(list, [1, 2]) " append a List as one new item
  344. :call extend(list, [1, 2]) " extend the list with two more items
  345. :let i = remove(list, 3) " remove item 3
  346. :unlet list[3] " idem
  347. :let l = remove(list, 3, -1) " remove items 3 to last item
  348. :unlet list[3 : ] " idem
  349. :call filter(list, 'v:val !~ "x"') " remove items with an 'x'
  350. Changing the order of items in a list: >
  351. :call sort(list) " sort a list alphabetically
  352. :call reverse(list) " reverse the order of items
  353. :call uniq(sort(list)) " sort and remove duplicates
  354. For loop ~
  355. The |:for| loop executes commands for each item in a List, String or Blob.
  356. A variable is set to each item in sequence. Example with a List: >
  357. :for item in mylist
  358. : call Doit(item)
  359. :endfor
  360. This works like: >
  361. :let index = 0
  362. :while index < len(mylist)
  363. : let item = mylist[index]
  364. : :call Doit(item)
  365. : let index = index + 1
  366. :endwhile
  367. If all you want to do is modify each item in the list then the |map()|
  368. function will be a simpler method than a for loop.
  369. Just like the |:let| command, |:for| also accepts a list of variables. This
  370. requires the argument to be a List of Lists. >
  371. :for [lnum, col] in [[1, 3], [2, 8], [3, 0]]
  372. : call Doit(lnum, col)
  373. :endfor
  374. This works like a |:let| command is done for each list item. Again, the types
  375. must remain the same to avoid an error.
  376. It is also possible to put remaining items in a List variable: >
  377. :for [i, j; rest] in listlist
  378. : call Doit(i, j)
  379. : if !empty(rest)
  380. : echo "remainder: " .. string(rest)
  381. : endif
  382. :endfor
  383. For a Blob one byte at a time is used.
  384. For a String one character, including any composing characters, is used as a
  385. String. Example: >
  386. for c in text
  387. echo 'This character is ' .. c
  388. endfor
  389. List functions ~
  390. *E714*
  391. Functions that are useful with a List: >
  392. :let r = call(funcname, list) " call a function with an argument list
  393. :if empty(list) " check if list is empty
  394. :let l = len(list) " number of items in list
  395. :let big = max(list) " maximum value in list
  396. :let small = min(list) " minimum value in list
  397. :let xs = count(list, 'x') " count nr of times 'x' appears in list
  398. :let i = index(list, 'x') " index of first 'x' in list
  399. :let lines = getline(1, 10) " get ten text lines from buffer
  400. :call append('$', lines) " append text lines in buffer
  401. :let list = split("a b c") " create list from items in a string
  402. :let string = join(list, ', ') " create string from list items
  403. :let s = string(list) " String representation of list
  404. :call map(list, '">> " .. v:val') " prepend ">> " to each item
  405. Don't forget that a combination of features can make things simple. For
  406. example, to add up all the numbers in a list: >
  407. :exe 'let sum = ' .. join(nrlist, '+')
  408. 1.4 Dictionaries ~
  409. *dict* *Dict* *Dictionaries* *Dictionary*
  410. A Dictionary is an associative array: Each entry has a key and a value. The
  411. entry can be located with the key. The entries are stored without a specific
  412. ordering.
  413. Dictionary creation ~
  414. *E720* *E721* *E722* *E723*
  415. A Dictionary is created with a comma-separated list of entries in curly
  416. braces. Each entry has a key and a value, separated by a colon. Each key can
  417. only appear once. Examples: >
  418. :let mydict = {1: 'one', 2: 'two', 3: 'three'}
  419. :let emptydict = {}
  420. < *E713* *E716* *E717*
  421. A key is always a String. You can use a Number, it will be converted to a
  422. String automatically. Thus the String '4' and the number 4 will find the same
  423. entry. Note that the String '04' and the Number 04 are different, since the
  424. Number will be converted to the String '4', leading zeros are dropped. The
  425. empty string can also be used as a key.
  426. In |Vim9| script a literal key can be used if it consists only of alphanumeric
  427. characters, underscore and dash, see |vim9-literal-dict|.
  428. *literal-Dict* *#{}*
  429. To avoid having to put quotes around every key the #{} form can be used in
  430. legacy script. This does require the key to consist only of ASCII letters,
  431. digits, '-' and '_'. Example: >
  432. :let mydict = #{zero: 0, one_key: 1, two-key: 2, 333: 3}
  433. Note that 333 here is the string "333". Empty keys are not possible with #{}.
  434. In |Vim9| script the #{} form cannot be used because it can be confused with
  435. the start of a comment.
  436. A value can be any expression. Using a Dictionary for a value creates a
  437. nested Dictionary: >
  438. :let nestdict = {1: {11: 'a', 12: 'b'}, 2: {21: 'c'}}
  439. An extra comma after the last entry is ignored.
  440. Accessing entries ~
  441. The normal way to access an entry is by putting the key in square brackets: >
  442. :let val = mydict["one"]
  443. :let mydict["four"] = 4
  444. You can add new entries to an existing Dictionary this way, unlike Lists.
  445. For keys that consist entirely of letters, digits and underscore the following
  446. form can be used |expr-entry|: >
  447. :let val = mydict.one
  448. :let mydict.four = 4
  449. Since an entry can be any type, also a List and a Dictionary, the indexing and
  450. key lookup can be repeated: >
  451. :echo dict.key[idx].key
  452. Dictionary to List conversion ~
  453. You may want to loop over the entries in a dictionary. For this you need to
  454. turn the Dictionary into a List and pass it to |:for|.
  455. Most often you want to loop over the keys, using the |keys()| function: >
  456. :for key in keys(mydict)
  457. : echo key .. ': ' .. mydict[key]
  458. :endfor
  459. The List of keys is unsorted. You may want to sort them first: >
  460. :for key in sort(keys(mydict))
  461. To loop over the values use the |values()| function: >
  462. :for v in values(mydict)
  463. : echo "value: " .. v
  464. :endfor
  465. If you want both the key and the value use the |items()| function. It returns
  466. a List in which each item is a List with two items, the key and the value: >
  467. :for [key, value] in items(mydict)
  468. : echo key .. ': ' .. value
  469. :endfor
  470. Dictionary identity ~
  471. *dict-identity*
  472. Just like Lists you need to use |copy()| and |deepcopy()| to make a copy of a
  473. Dictionary. Otherwise, assignment results in referring to the same
  474. Dictionary: >
  475. :let onedict = {'a': 1, 'b': 2}
  476. :let adict = onedict
  477. :let adict['a'] = 11
  478. :echo onedict['a']
  479. 11
  480. Two Dictionaries compare equal if all the key-value pairs compare equal. For
  481. more info see |list-identity|.
  482. Dictionary modification ~
  483. *dict-modification*
  484. To change an already existing entry of a Dictionary, or to add a new entry,
  485. use |:let| this way: >
  486. :let dict[4] = "four"
  487. :let dict['one'] = item
  488. Removing an entry from a Dictionary is done with |remove()| or |:unlet|.
  489. Three ways to remove the entry with key "aaa" from dict: >
  490. :let i = remove(dict, 'aaa')
  491. :unlet dict.aaa
  492. :unlet dict['aaa']
  493. Merging a Dictionary with another is done with |extend()|: >
  494. :call extend(adict, bdict)
  495. This extends adict with all entries from bdict. Duplicate keys cause entries
  496. in adict to be overwritten. An optional third argument can change this.
  497. Note that the order of entries in a Dictionary is irrelevant, thus don't
  498. expect ":echo adict" to show the items from bdict after the older entries in
  499. adict.
  500. Weeding out entries from a Dictionary can be done with |filter()|: >
  501. :call filter(dict, 'v:val =~ "x"')
  502. This removes all entries from "dict" with a value not matching 'x'.
  503. This can also be used to remove all entries: >
  504. call filter(dict, 0)
  505. In some situations it is not allowed to remove or add entries to a Dictionary.
  506. Especially when iterating over all the entries. You will get *E1313* or
  507. another error in that case.
  508. Dictionary function ~
  509. *Dictionary-function* *self* *E725* *E862*
  510. When a function is defined with the "dict" attribute it can be used in a
  511. special way with a dictionary. Example: >
  512. :function Mylen() dict
  513. : return len(self.data)
  514. :endfunction
  515. :let mydict = {'data': [0, 1, 2, 3], 'len': function("Mylen")}
  516. :echo mydict.len()
  517. This is like a method in object oriented programming. The entry in the
  518. Dictionary is a |Funcref|. The local variable "self" refers to the dictionary
  519. the function was invoked from. When using |Vim9| script you can use classes
  520. and objects, see `:class`.
  521. It is also possible to add a function without the "dict" attribute as a
  522. Funcref to a Dictionary, but the "self" variable is not available then.
  523. *numbered-function* *anonymous-function*
  524. To avoid the extra name for the function it can be defined and directly
  525. assigned to a Dictionary in this way: >
  526. :let mydict = {'data': [0, 1, 2, 3]}
  527. :function mydict.len()
  528. : return len(self.data)
  529. :endfunction
  530. :echo mydict.len()
  531. The function will then get a number and the value of dict.len is a |Funcref|
  532. that references this function. The function can only be used through a
  533. |Funcref|. It will automatically be deleted when there is no |Funcref|
  534. remaining that refers to it.
  535. It is not necessary to use the "dict" attribute for a numbered function.
  536. If you get an error for a numbered function, you can find out what it is with
  537. a trick. Assuming the function is 42, the command is: >
  538. :function g:42
  539. Functions for Dictionaries ~
  540. *E715*
  541. Functions that can be used with a Dictionary: >
  542. :if has_key(dict, 'foo') " TRUE if dict has entry with key "foo"
  543. :if empty(dict) " TRUE if dict is empty
  544. :let l = len(dict) " number of items in dict
  545. :let big = max(dict) " maximum value in dict
  546. :let small = min(dict) " minimum value in dict
  547. :let xs = count(dict, 'x') " count nr of times 'x' appears in dict
  548. :let s = string(dict) " String representation of dict
  549. :call map(dict, '">> " .. v:val') " prepend ">> " to each item
  550. 1.5 Blobs ~
  551. *blob* *Blob* *Blobs* *E978*
  552. A Blob is a binary object. It can be used to read an image from a file and
  553. send it over a channel, for example.
  554. A Blob mostly behaves like a |List| of numbers, where each number has the
  555. value of an 8-bit byte, from 0 to 255.
  556. Blob creation ~
  557. A Blob can be created with a |blob-literal|: >
  558. :let b = 0zFF00ED015DAF
  559. Dots can be inserted between bytes (pair of hex characters) for readability,
  560. they don't change the value: >
  561. :let b = 0zFF00.ED01.5DAF
  562. A blob can be read from a file with |readfile()| passing the {type} argument
  563. set to "B", for example: >
  564. :let b = readfile('image.png', 'B')
  565. A blob can be read from a channel with the |ch_readblob()| function.
  566. Blob index ~
  567. *blob-index* *E979*
  568. A byte in the Blob can be accessed by putting the index in square brackets
  569. after the Blob. Indexes are zero-based, thus the first byte has index zero. >
  570. :let myblob = 0z00112233
  571. :let byte = myblob[0] " get the first byte: 0x00
  572. :let byte = myblob[2] " get the third byte: 0x22
  573. A negative index is counted from the end. Index -1 refers to the last byte in
  574. the Blob, -2 to the last but one byte, etc. >
  575. :let last = myblob[-1] " get the last byte: 0x33
  576. To avoid an error for an invalid index use the |get()| function. When an item
  577. is not available it returns -1 or the default value you specify: >
  578. :echo get(myblob, idx)
  579. :echo get(myblob, idx, 999)
  580. Blob iteration ~
  581. The |:for| loop executes commands for each byte of a Blob. The loop variable is
  582. set to each byte in the Blob. Example: >
  583. :for byte in 0z112233
  584. : call Doit(byte)
  585. :endfor
  586. This calls Doit() with 0x11, 0x22 and 0x33.
  587. Blob concatenation ~
  588. Two blobs can be concatenated with the "+" operator: >
  589. :let longblob = myblob + 0z4455
  590. :let myblob += 0z6677
  591. To change a blob in-place see |blob-modification| below.
  592. Part of a blob ~
  593. A part of the Blob can be obtained by specifying the first and last index,
  594. separated by a colon in square brackets: >
  595. :let myblob = 0z00112233
  596. :let shortblob = myblob[1:2] " get 0z1122
  597. :let shortblob = myblob[2:-1] " get 0z2233
  598. Omitting the first index is similar to zero. Omitting the last index is
  599. similar to -1. >
  600. :let endblob = myblob[2:] " from item 2 to the end: 0z2233
  601. :let shortblob = myblob[2:2] " Blob with one byte: 0z22
  602. :let otherblob = myblob[:] " make a copy of the Blob
  603. If the first index is beyond the last byte of the Blob or the second index is
  604. before the first index, the result is an empty Blob. There is no error
  605. message.
  606. If the second index is equal to or greater than the length of the list the
  607. length minus one is used: >
  608. :echo myblob[2:8] " result: 0z2233
  609. Blob modification ~
  610. *blob-modification* *E1182* *E1184*
  611. To change a specific byte of a blob use |:let| this way: >
  612. :let blob[4] = 0x44
  613. When the index is just one beyond the end of the Blob, it is appended. Any
  614. higher index is an error.
  615. To change a sequence of bytes the [:] notation can be used: >
  616. let blob[1:3] = 0z445566
  617. The length of the replaced bytes must be exactly the same as the value
  618. provided. *E972*
  619. To change part of a blob you can specify the first and last byte to be
  620. modified. The value must have the same number of bytes in the range: >
  621. :let blob[3:5] = 0z334455
  622. You can also use the functions |add()|, |remove()| and |insert()|.
  623. Blob identity ~
  624. Blobs can be compared for equality: >
  625. if blob == 0z001122
  626. And for equal identity: >
  627. if blob is otherblob
  628. < *blob-identity* *E977*
  629. When variable "aa" is a Blob and you assign it to another variable "bb", both
  630. variables refer to the same Blob. Then the "is" operator returns true.
  631. When making a copy using [:] or |copy()| the values are the same, but the
  632. identity is different: >
  633. :let blob = 0z112233
  634. :let blob2 = blob
  635. :echo blob == blob2
  636. < 1 >
  637. :echo blob is blob2
  638. < 1 >
  639. :let blob3 = blob[:]
  640. :echo blob == blob3
  641. < 1 >
  642. :echo blob is blob3
  643. < 0
  644. Making a copy of a Blob is done with the |copy()| function. Using [:] also
  645. works, as explained above.
  646. 1.6 More about variables ~
  647. *more-variables*
  648. If you need to know the type of a variable or expression, use the |type()|
  649. function.
  650. When the '!' flag is included in the 'viminfo' option, global variables that
  651. start with an uppercase letter, and don't contain a lowercase letter, are
  652. stored in the viminfo file |viminfo-file|.
  653. When the 'sessionoptions' option contains "global", global variables that
  654. start with an uppercase letter and contain at least one lowercase letter are
  655. stored in the session file |session-file|.
  656. variable name can be stored where ~
  657. my_var_6 not
  658. My_Var_6 session file
  659. MY_VAR_6 viminfo file
  660. In legacy script it is possible to form a variable name with curly braces, see
  661. |curly-braces-names|.
  662. ==============================================================================
  663. 2. Expression syntax *expression-syntax*
  664. *E1143*
  665. Expression syntax summary, from least to most significant:
  666. |expr1| expr2
  667. expr2 ? expr1 : expr1 if-then-else
  668. |expr2| expr3
  669. expr3 || expr3 ... logical OR
  670. |expr3| expr4
  671. expr4 && expr4 ... logical AND
  672. |expr4| expr5
  673. expr5 == expr5 equal
  674. expr5 != expr5 not equal
  675. expr5 > expr5 greater than
  676. expr5 >= expr5 greater than or equal
  677. expr5 < expr5 smaller than
  678. expr5 <= expr5 smaller than or equal
  679. expr5 =~ expr5 regexp matches
  680. expr5 !~ expr5 regexp doesn't match
  681. expr5 ==? expr5 equal, ignoring case
  682. expr5 ==# expr5 equal, match case
  683. etc. As above, append ? for ignoring case, # for
  684. matching case
  685. expr5 is expr5 same |List|, |Dictionary| or |Blob| instance
  686. expr5 isnot expr5 different |List|, |Dictionary| or |Blob|
  687. instance
  688. |expr5| expr6 << expr6 bitwise left shift
  689. expr6 >> expr6 bitwise right shift
  690. |expr6| expr7
  691. expr7 + expr7 ... number addition, list or blob concatenation
  692. expr7 - expr7 ... number subtraction
  693. expr7 . expr7 ... string concatenation
  694. expr7 .. expr7 ... string concatenation
  695. |expr7| expr8
  696. expr8 * expr8 ... number multiplication
  697. expr8 / expr8 ... number division
  698. expr8 % expr8 ... number modulo
  699. |expr8| expr9
  700. <type>expr9 type check and conversion (|Vim9| only)
  701. |expr9| expr10
  702. ! expr9 logical NOT
  703. - expr9 unary minus
  704. + expr9 unary plus
  705. |expr10| expr11
  706. expr10[expr1] byte of a String or item of a |List|
  707. expr10[expr1 : expr1] substring of a String or sublist of a |List|
  708. expr10.name entry in a |Dictionary|
  709. expr10(expr1, ...) function call with |Funcref| variable
  710. expr10->name(expr1, ...) |method| call
  711. |expr11| number number constant
  712. "string" string constant, backslash is special
  713. 'string' string constant, ' is doubled
  714. [expr1, ...] |List|
  715. {expr1: expr1, ...} |Dictionary|
  716. #{key: expr1, ...} legacy |Dictionary|
  717. &option option value
  718. (expr1) nested expression
  719. variable internal variable
  720. va{ria}ble internal variable with curly braces
  721. $VAR environment variable
  722. @r contents of register 'r'
  723. function(expr1, ...) function call
  724. func{ti}on(expr1, ...) function call with curly braces
  725. {args -> expr1} legacy lambda expression
  726. (args) => expr1 Vim9 lambda expression
  727. "..." indicates that the operations in this level can be concatenated.
  728. Example: >
  729. &nu || &list && &shell == "csh"
  730. All expressions within one level are parsed from left to right.
  731. Expression nesting is limited to 1000 levels deep (300 when build with MSVC)
  732. to avoid running out of stack and crashing. *E1169*
  733. expr1 *expr1* *ternary* *falsy-operator* *??* *E109*
  734. -----
  735. The ternary operator: expr2 ? expr1 : expr1
  736. The falsy operator: expr2 ?? expr1
  737. Ternary operator ~
  738. In legacy script the expression before the '?' is evaluated to a number. If
  739. it evaluates to |TRUE|, the result is the value of the expression between the
  740. '?' and ':', otherwise the result is the value of the expression after the
  741. ':'.
  742. In |Vim9| script the first expression must evaluate to a boolean, see
  743. |vim9-boolean|.
  744. Example: >
  745. :echo lnum == 1 ? "top" : lnum
  746. Since the first expression is an "expr2", it cannot contain another ?:. The
  747. other two expressions can, thus allow for recursive use of ?:.
  748. Example: >
  749. :echo lnum == 1 ? "top" : lnum == 1000 ? "last" : lnum
  750. To keep this readable, using |line-continuation| is suggested: >
  751. :echo lnum == 1
  752. :\ ? "top"
  753. :\ : lnum == 1000
  754. :\ ? "last"
  755. :\ : lnum
  756. You should always put a space before the ':', otherwise it can be mistaken for
  757. use in a variable such as "a:1".
  758. Falsy operator ~
  759. This is also known as the "null coalescing operator", but that's too
  760. complicated, thus we just call it the falsy operator.
  761. The expression before the '??' is evaluated. If it evaluates to
  762. |truthy|, this is used as the result. Otherwise the expression after the '??'
  763. is evaluated and used as the result. This is most useful to have a default
  764. value for an expression that may result in zero or empty: >
  765. echo theList ?? 'list is empty'
  766. echo GetName() ?? 'unknown'
  767. These are similar, but not equal: >
  768. expr2 ?? expr1
  769. expr2 ? expr2 : expr1
  770. In the second line "expr2" is evaluated twice. And in |Vim9| script the type
  771. of expr2 before "?" must be a boolean.
  772. expr2 and expr3 *expr2* *expr3*
  773. ---------------
  774. expr3 || expr3 .. logical OR *expr-barbar*
  775. expr4 && expr4 .. logical AND *expr-&&*
  776. The "||" and "&&" operators take one argument on each side.
  777. In legacy script the arguments are (converted to) Numbers.
  778. In |Vim9| script the values must be boolean, see |vim9-boolean|. Use "!!" to
  779. convert any type to a boolean.
  780. The result is:
  781. input output ~
  782. n1 n2 n1 || n2 n1 && n2 ~
  783. |FALSE| |FALSE| |FALSE| |FALSE|
  784. |FALSE| |TRUE| |TRUE| |FALSE|
  785. |TRUE| |FALSE| |TRUE| |FALSE|
  786. |TRUE| |TRUE| |TRUE| |TRUE|
  787. The operators can be concatenated, for example: >
  788. &nu || &list && &shell == "csh"
  789. Note that "&&" takes precedence over "||", so this has the meaning of: >
  790. &nu || (&list && &shell == "csh")
  791. Once the result is known, the expression "short-circuits", that is, further
  792. arguments are not evaluated. This is like what happens in C. For example: >
  793. let a = 1
  794. echo a || b
  795. This is valid even if there is no variable called "b" because "a" is |TRUE|,
  796. so the result must be |TRUE|. Similarly below: >
  797. echo exists("b") && b == "yes"
  798. This is valid whether "b" has been defined or not. The second clause will
  799. only be evaluated if "b" has been defined.
  800. expr4 *expr4* *E1153*
  801. -----
  802. expr5 {cmp} expr5
  803. Compare two expr5 expressions. In legacy script the result is a 0 if it
  804. evaluates to false, or 1 if it evaluates to true. In |Vim9| script the result
  805. is |true| or |false|.
  806. *expr-==* *expr-!=* *expr->* *expr->=*
  807. *expr-<* *expr-<=* *expr-=~* *expr-!~*
  808. *expr-==#* *expr-!=#* *expr->#* *expr->=#*
  809. *expr-<#* *expr-<=#* *expr-=~#* *expr-!~#*
  810. *expr-==?* *expr-!=?* *expr->?* *expr->=?*
  811. *expr-<?* *expr-<=?* *expr-=~?* *expr-!~?*
  812. *expr-is* *expr-isnot* *expr-is#* *expr-isnot#*
  813. *expr-is?* *expr-isnot?* *E1072*
  814. use 'ignorecase' match case ignore case ~
  815. equal == ==# ==?
  816. not equal != !=# !=?
  817. greater than > ># >?
  818. greater than or equal >= >=# >=?
  819. smaller than < <# <?
  820. smaller than or equal <= <=# <=?
  821. regexp matches =~ =~# =~?
  822. regexp doesn't match !~ !~# !~?
  823. same instance is is# is?
  824. different instance isnot isnot# isnot?
  825. Examples:
  826. "abc" ==# "Abc" evaluates to 0
  827. "abc" ==? "Abc" evaluates to 1
  828. "abc" == "Abc" evaluates to 1 if 'ignorecase' is set, 0 otherwise
  829. NOTE: In |Vim9| script 'ignorecase' is not used.
  830. *E691* *E692*
  831. A |List| can only be compared with a |List| and only "equal", "not equal",
  832. "is" and "isnot" can be used. This compares the values of the list,
  833. recursively. Ignoring case means case is ignored when comparing item values.
  834. *E735* *E736*
  835. A |Dictionary| can only be compared with a |Dictionary| and only "equal", "not
  836. equal", "is" and "isnot" can be used. This compares the key/values of the
  837. |Dictionary| recursively. Ignoring case means case is ignored when comparing
  838. item values.
  839. *E694*
  840. A |Funcref| can only be compared with a |Funcref| and only "equal", "not
  841. equal", "is" and "isnot" can be used. Case is never ignored. Whether
  842. arguments or a Dictionary are bound (with a partial) matters. The
  843. Dictionaries must also be equal (or the same, in case of "is") and the
  844. arguments must be equal (or the same).
  845. To compare Funcrefs to see if they refer to the same function, ignoring bound
  846. Dictionary and arguments, use |get()| to get the function name: >
  847. if get(Part1, 'name') == get(Part2, 'name')
  848. " Part1 and Part2 refer to the same function
  849. < *E1037*
  850. Using "is" or "isnot" with a |List|, |Dictionary| or |Blob| checks whether
  851. the expressions are referring to the same |List|, |Dictionary| or |Blob|
  852. instance. A copy of a |List| is different from the original |List|. When
  853. using "is" without a |List|, |Dictionary| or |Blob|, it is equivalent to
  854. using "equal", using "isnot" equivalent to using "not equal". Except that
  855. a different type means the values are different: >
  856. echo 4 == '4'
  857. 1
  858. echo 4 is '4'
  859. 0
  860. echo 0 is []
  861. 0
  862. "is#"/"isnot#" and "is?"/"isnot?" can be used to match and ignore case.
  863. In |Vim9| script this doesn't work, two strings are never identical.
  864. In legacy script, when comparing a String with a Number, the String is
  865. converted to a Number, and the comparison is done on Numbers. This means
  866. that: >
  867. echo 0 == 'x'
  868. 1
  869. because 'x' converted to a Number is zero. However: >
  870. echo [0] == ['x']
  871. 0
  872. Inside a List or Dictionary this conversion is not used.
  873. In |Vim9| script the types must match.
  874. When comparing two Strings, this is done with strcmp() or stricmp(). This
  875. results in the mathematical difference (comparing byte values), not
  876. necessarily the alphabetical difference in the local language.
  877. When using the operators with a trailing '#', or the short version and
  878. 'ignorecase' is off, the comparing is done with strcmp(): case matters.
  879. When using the operators with a trailing '?', or the short version and
  880. 'ignorecase' is set, the comparing is done with stricmp(): case is ignored.
  881. 'smartcase' is not used.
  882. The "=~" and "!~" operators match the lefthand argument with the righthand
  883. argument, which is used as a pattern. See |pattern| for what a pattern is.
  884. This matching is always done like 'magic' was set and 'cpoptions' is empty, no
  885. matter what the actual value of 'magic' or 'cpoptions' is. This makes scripts
  886. portable. To avoid backslashes in the regexp pattern to be doubled, use a
  887. single-quote string, see |literal-string|.
  888. Since a string is considered to be a single line, a multi-line pattern
  889. (containing \n, backslash-n) will not match. However, a literal NL character
  890. can be matched like an ordinary character. Examples:
  891. "foo\nbar" =~ "\n" evaluates to 1
  892. "foo\nbar" =~ "\\n" evaluates to 0
  893. expr5 *expr5* *bitwise-shift*
  894. -----
  895. expr6 << expr6 bitwise left shift *expr-<<*
  896. expr6 >> expr6 bitwise right shift *expr->>*
  897. *E1282* *E1283*
  898. The "<<" and ">>" operators can be used to perform bitwise left or right shift
  899. of the left operand by the number of bits specified by the right operand. The
  900. operands are used as positive numbers. When shifting right with ">>" the
  901. topmost bit (sometimes called the sign bit) is cleared. If the right operand
  902. (shift amount) is more than the maximum number of bits in a number
  903. (|v:numbersize|) the result is zero.
  904. expr6 and expr7 *expr6* *expr7* *E1036* *E1051*
  905. ---------------
  906. expr7 + expr7 Number addition, |List| or |Blob| concatenation *expr-+*
  907. expr7 - expr7 Number subtraction *expr--*
  908. expr7 . expr7 String concatenation *expr-.*
  909. expr7 .. expr7 String concatenation *expr-..*
  910. For |Lists| only "+" is possible and then both expr7 must be a list. The
  911. result is a new list with the two lists Concatenated.
  912. For String concatenation ".." is preferred, since "." is ambiguous, it is also
  913. used for |Dict| member access and floating point numbers.
  914. In |Vim9| script and when |vimscript-version| is 2 or higher, using "." is not
  915. allowed.
  916. In |Vim9| script the arguments of ".." are converted to String for simple
  917. types: Number, Float, Special and Bool. For other types |string()| should be
  918. used.
  919. expr8 * expr8 Number multiplication *expr-star*
  920. expr8 / expr8 Number division *expr-/*
  921. expr8 % expr8 Number modulo *expr-%*
  922. In legacy script, for all operators except "." and "..", Strings are converted
  923. to Numbers.
  924. For bitwise operators see |and()|, |or()| and |xor()|.
  925. Note the difference between "+" and ".." in legacy script:
  926. "123" + "456" = 579
  927. "123" .. "456" = "123456"
  928. Since '..' has the same precedence as '+' and '-', you need to read: >
  929. 1 .. 90 + 90.0
  930. As: >
  931. (1 .. 90) + 90.0
  932. That works in legacy script, since the String "190" is automatically converted
  933. to the Number 190, which can be added to the Float 90.0. However: >
  934. 1 .. 90 * 90.0
  935. Should be read as: >
  936. 1 .. (90 * 90.0)
  937. Since '..' has lower precedence than '*'. This does NOT work, since this
  938. attempts to concatenate a Float and a String.
  939. When dividing a Number by zero the result depends on the value:
  940. 0 / 0 = -0x80000000 (like NaN for Float)
  941. >0 / 0 = 0x7fffffff (like positive infinity)
  942. <0 / 0 = -0x7fffffff (like negative infinity)
  943. (before Vim 7.2 it was always 0x7fffffff)
  944. In |Vim9| script dividing a number by zero is an error. *E1154*
  945. When 64-bit Number support is enabled:
  946. 0 / 0 = -0x8000000000000000 (like NaN for Float)
  947. >0 / 0 = 0x7fffffffffffffff (like positive infinity)
  948. <0 / 0 = -0x7fffffffffffffff (like negative infinity)
  949. When the righthand side of '%' is zero, the result is 0.
  950. None of these work for |Funcref|s.
  951. ".", ".." and "%" do not work for Float. *E804* *E1035*
  952. expr8 *expr8*
  953. -----
  954. <type>expr9
  955. This is only available in |Vim9| script, see |type-casting|.
  956. expr9 *expr9*
  957. -----
  958. ! expr9 logical NOT *expr-!*
  959. - expr9 unary minus *expr-unary--*
  960. + expr9 unary plus *expr-unary-+*
  961. For '!' |TRUE| becomes |FALSE|, |FALSE| becomes |TRUE| (one).
  962. For '-' the sign of the number is changed.
  963. For '+' the number is unchanged. Note: "++" has no effect.
  964. In legacy script a String will be converted to a Number first. Note that if
  965. the string does not start with a digit you likely don't get what you expect.
  966. In |Vim9| script an error is given when "-" or "+" is used and the type is not
  967. a number.
  968. In |Vim9| script "!" can be used for any type and the result is always a
  969. boolean. Use "!!" to convert any type to a boolean, according to whether the
  970. value is |falsy|.
  971. These three can be repeated and mixed. Examples:
  972. !-1 == 0
  973. !!8 == 1
  974. --9 == 9
  975. expr10 *expr10*
  976. ------
  977. This expression is either |expr11| or a sequence of the alternatives below,
  978. in any order. E.g., these are all possible:
  979. expr10[expr1].name
  980. expr10.name[expr1]
  981. expr10(expr1, ...)[expr1].name
  982. expr10->(expr1, ...)[expr1]
  983. Evaluation is always from left to right.
  984. expr10[expr1] item of String or |List| *expr-[]* *E111*
  985. *E909* *subscript* *E1062*
  986. In legacy Vim script:
  987. If expr10 is a Number or String this results in a String that contains the
  988. expr1'th single byte from expr10. expr10 is used as a String (a number is
  989. automatically converted to a String), expr1 as a Number. This doesn't
  990. recognize multibyte encodings, see `byteidx()` for an alternative, or use
  991. `split()` to turn the string into a list of characters. Example, to get the
  992. byte under the cursor: >
  993. :let c = getline(".")[col(".") - 1]
  994. In |Vim9| script: *E1147* *E1148*
  995. If expr10 is a String this results in a String that contains the expr1'th
  996. single character (including any composing characters) from expr10. To use byte
  997. indexes use |strpart()|.
  998. Index zero gives the first byte or character. Careful: text column numbers
  999. start with one!
  1000. If the length of the String is less than the index, the result is an empty
  1001. String. A negative index always results in an empty string (reason: backward
  1002. compatibility). Use [-1:] to get the last byte or character.
  1003. In Vim9 script a negative index is used like with a list: count from the end.
  1004. If expr10 is a |List| then it results the item at index expr1. See |list-index|
  1005. for possible index values. If the index is out of range this results in an
  1006. error. Example: >
  1007. :let item = mylist[-1] " get last item
  1008. Generally, if a |List| index is equal to or higher than the length of the
  1009. |List|, or more negative than the length of the |List|, this results in an
  1010. error.
  1011. expr10[expr1a : expr1b] substring or |sublist| *expr-[:]* *substring*
  1012. If expr10 is a String this results in the substring with the bytes or
  1013. characters from expr1a to and including expr1b. expr10 is used as a String,
  1014. expr1a and expr1b are used as a Number.
  1015. In legacy Vim script the indexes are byte indexes. This doesn't recognize
  1016. multibyte encodings, see |byteidx()| for computing the indexes. If expr10 is
  1017. a Number it is first converted to a String.
  1018. In Vim9 script the indexes are character indexes and include composing
  1019. characters. To use byte indexes use |strpart()|. To use character indexes
  1020. without including composing characters use |strcharpart()|.
  1021. The item at index expr1b is included, it is inclusive. For an exclusive index
  1022. use the |slice()| function.
  1023. If expr1a is omitted zero is used. If expr1b is omitted the length of the
  1024. string minus one is used.
  1025. A negative number can be used to measure from the end of the string. -1 is
  1026. the last character, -2 the last but one, etc.
  1027. If an index goes out of range for the string characters are omitted. If
  1028. expr1b is smaller than expr1a the result is an empty string.
  1029. Examples: >
  1030. :let c = name[-1:] " last byte of a string
  1031. :let c = name[0:-1] " the whole string
  1032. :let c = name[-2:-2] " last but one byte of a string
  1033. :let s = line(".")[4:] " from the fifth byte to the end
  1034. :let s = s[:-3] " remove last two bytes
  1035. <
  1036. *slice*
  1037. If expr10 is a |List| this results in a new |List| with the items indicated by
  1038. the indexes expr1a and expr1b. This works like with a String, as explained
  1039. just above. Also see |sublist| below. Examples: >
  1040. :let l = mylist[:3] " first four items
  1041. :let l = mylist[4:4] " List with one item
  1042. :let l = mylist[:] " shallow copy of a List
  1043. If expr10 is a |Blob| this results in a new |Blob| with the bytes in the
  1044. indexes expr1a and expr1b, inclusive. Examples: >
  1045. :let b = 0zDEADBEEF
  1046. :let bs = b[1:2] " 0zADBE
  1047. :let bs = b[:] " copy of 0zDEADBEEF
  1048. Using expr10[expr1] or expr10[expr1a : expr1b] on a |Funcref| results in an
  1049. error.
  1050. Watch out for confusion between a namespace and a variable followed by a colon
  1051. for a sublist: >
  1052. mylist[n:] " uses variable n
  1053. mylist[s:] " uses namespace s:, error!
  1054. expr10.name entry in a |Dictionary| *expr-entry*
  1055. *E1203* *E1229*
  1056. If expr10 is a |Dictionary| and it is followed by a dot, then the following
  1057. name will be used as a key in the |Dictionary|. This is just like:
  1058. expr10[name].
  1059. The name must consist of alphanumeric characters, just like a variable name,
  1060. but it may start with a number. Curly braces cannot be used.
  1061. There must not be white space before or after the dot.
  1062. Examples: >
  1063. :let dict = {"one": 1, 2: "two"}
  1064. :echo dict.one " shows "1"
  1065. :echo dict.2 " shows "two"
  1066. :echo dict .2 " error because of space before the dot
  1067. Note that the dot is also used for String concatenation. To avoid confusion
  1068. always put spaces around the dot for String concatenation.
  1069. expr10(expr1, ...) |Funcref| function call *E1085*
  1070. When expr10 is a |Funcref| type variable, invoke the function it refers to.
  1071. expr10->name([args]) method call *method* *->*
  1072. expr10->{lambda}([args])
  1073. *E260* *E276* *E1265*
  1074. For methods that are also available as global functions this is the same as: >
  1075. name(expr10 [, args])
  1076. There can also be methods specifically for the type of "expr10".
  1077. This allows for chaining, passing the value that one method returns to the
  1078. next method: >
  1079. mylist->filter(filterexpr)->map(mapexpr)->sort()->join()
  1080. <
  1081. Example of using a lambda: >
  1082. GetPercentage()->{x -> x * 100}()->printf('%d%%')
  1083. <
  1084. When using -> the |expr9| operators will be applied first, thus: >
  1085. -1.234->string()
  1086. Is equivalent to: >
  1087. (-1.234)->string()
  1088. And NOT: >
  1089. -(1.234->string())
  1090. What comes after "->" can be a name, a simple expression (not containing any
  1091. parenthesis), or any expression in parentheses: >
  1092. base->name(args)
  1093. base->some.name(args)
  1094. base->alist[idx](args)
  1095. base->(getFuncRef())(args)
  1096. Note that in the last call the base is passed to the function resulting from
  1097. "(getFuncRef())", inserted before "args". *E1275*
  1098. *E274*
  1099. "->name(" must not contain white space. There can be white space before the
  1100. "->" and after the "(", thus you can split the lines like this: >
  1101. mylist
  1102. \ ->filter(filterexpr)
  1103. \ ->map(mapexpr)
  1104. \ ->sort()
  1105. \ ->join()
  1106. When using the lambda form there must be no white space between the } and the
  1107. (.
  1108. *expr11*
  1109. number
  1110. ------
  1111. number number constant *expr-number*
  1112. *0x* *hex-number* *0o* *octal-number* *binary-number*
  1113. Decimal, Hexadecimal (starting with 0x or 0X), Binary (starting with 0b or 0B)
  1114. and Octal (starting with 0, 0o or 0O).
  1115. Assuming 64 bit numbers are used (see |v:numbersize|) an unsigned number is
  1116. truncated to 0x7fffffffffffffff or 9223372036854775807. You can use -1 to get
  1117. 0xffffffffffffffff.
  1118. *floating-point-format*
  1119. Floating point numbers can be written in two forms:
  1120. [-+]{N}.{M}
  1121. [-+]{N}.{M}[eE][-+]{exp}
  1122. {N} and {M} are numbers. Both {N} and {M} must be present and can only
  1123. contain digits, except that in |Vim9| script in {N} single quotes between
  1124. digits are ignored.
  1125. [-+] means there is an optional plus or minus sign.
  1126. {exp} is the exponent, power of 10.
  1127. Only a decimal point is accepted, not a comma. No matter what the current
  1128. locale is.
  1129. Examples:
  1130. 123.456
  1131. +0.0001
  1132. 55.0
  1133. -0.123
  1134. 1.234e03
  1135. 1.0E-6
  1136. -3.1416e+88
  1137. These are INVALID:
  1138. 3. empty {M}
  1139. 1e40 missing .{M}
  1140. Rationale:
  1141. Before floating point was introduced, the text "123.456" was interpreted as
  1142. the two numbers "123" and "456", both converted to a string and concatenated,
  1143. resulting in the string "123456". Since this was considered pointless, and we
  1144. could not find it intentionally being used in Vim scripts, this backwards
  1145. incompatibility was accepted in favor of being able to use the normal notation
  1146. for floating point numbers.
  1147. *float-pi* *float-e*
  1148. A few useful values to copy&paste: >
  1149. :let pi = 3.14159265359
  1150. :let e = 2.71828182846
  1151. Or, if you don't want to write them in as floating-point literals, you can
  1152. also use functions, like the following: >
  1153. :let pi = acos(-1.0)
  1154. :let e = exp(1.0)
  1155. <
  1156. *floating-point-precision*
  1157. The precision and range of floating points numbers depends on what "double"
  1158. means in the library Vim was compiled with. There is no way to change this at
  1159. runtime.
  1160. The default for displaying a |Float| is to use 6 decimal places, like using
  1161. printf("%g", f). You can select something else when using the |printf()|
  1162. function. Example: >
  1163. :echo printf('%.15e', atan(1))
  1164. < 7.853981633974483e-01
  1165. string *string* *String* *expr-string* *E114*
  1166. ------
  1167. "string" string constant *expr-quote*
  1168. Note that double quotes are used.
  1169. A string constant accepts these special characters:
  1170. \... three-digit octal number (e.g., "\316")
  1171. \.. two-digit octal number (must be followed by non-digit)
  1172. \. one-digit octal number (must be followed by non-digit)
  1173. \x.. byte specified with two hex numbers (e.g., "\x1f")
  1174. \x. byte specified with one hex number (must be followed by non-hex char)
  1175. \X.. same as \x..
  1176. \X. same as \x.
  1177. \u.... character specified with up to 4 hex numbers, stored according to the
  1178. current value of 'encoding' (e.g., "\u02a4")
  1179. \U.... same as \u but allows up to 8 hex numbers.
  1180. \b backspace <BS>
  1181. \e escape <Esc>
  1182. \f formfeed 0x0C
  1183. \n newline <NL>
  1184. \r return <CR>
  1185. \t tab <Tab>
  1186. \\ backslash
  1187. \" double quote
  1188. \<xxx> Special key named "xxx". e.g. "\<C-W>" for CTRL-W. This is for use
  1189. in mappings, the 0x80 byte is escaped.
  1190. To use the double quote character it must be escaped: "<M-\">".
  1191. Don't use <Char-xxxx> to get a UTF-8 character, use \uxxxx as
  1192. mentioned above.
  1193. \<*xxx> Like \<xxx> but prepends a modifier instead of including it in the
  1194. character. E.g. "\<C-w>" is one character 0x17 while "\<*C-w>" is four
  1195. bytes: 3 for the CTRL modifier and then character "W".
  1196. Note that "\xff" is stored as the byte 255, which may be invalid in some
  1197. encodings. Use "\u00ff" to store character 255 according to the current value
  1198. of 'encoding'.
  1199. Note that "\000" and "\x00" force the end of the string.
  1200. blob-literal *blob-literal* *E973*
  1201. ------------
  1202. Hexadecimal starting with 0z or 0Z, with an arbitrary number of bytes.
  1203. The sequence must be an even number of hex characters. Example: >
  1204. :let b = 0zFF00ED015DAF
  1205. literal-string *literal-string* *E115*
  1206. ---------------
  1207. 'string' string constant *expr-'*
  1208. Note that single quotes are used.
  1209. This string is taken as it is. No backslashes are removed or have a special
  1210. meaning. The only exception is that two quotes stand for one quote.
  1211. Single quoted strings are useful for patterns, so that backslashes do not need
  1212. to be doubled. These two commands are equivalent: >
  1213. if a =~ "\\s*"
  1214. if a =~ '\s*'
  1215. interpolated-string *$quote* *interpolated-string*
  1216. --------------------
  1217. $"string" interpolated string constant *expr-$quote*
  1218. $'string' interpolated literal string constant *expr-$'*
  1219. Interpolated strings are an extension of the |string| and |literal-string|,
  1220. allowing the inclusion of Vim script expressions (see |expr1|). Any
  1221. expression returning a value can be enclosed between curly braces. The value
  1222. is converted to a string. All the text and results of the expressions
  1223. are concatenated to make a new string.
  1224. *E1278* *E1279*
  1225. To include an opening brace '{' or closing brace '}' in the string content
  1226. double it. For double quoted strings using a backslash also works. A single
  1227. closing brace '}' will result in an error.
  1228. Examples: >
  1229. let your_name = input("What's your name? ")
  1230. < What's your name? Peter ~
  1231. >
  1232. echo
  1233. echo $"Hello, {your_name}!"
  1234. < Hello, Peter! ~
  1235. >
  1236. echo $"The square root of {{9}} is {sqrt(9)}"
  1237. < The square root of {9} is 3.0 ~
  1238. option *expr-option* *E112* *E113*
  1239. ------
  1240. &option option value, local value if possible
  1241. &g:option global option value
  1242. &l:option local option value
  1243. Examples: >
  1244. echo "tabstop is " .. &tabstop
  1245. if &insertmode
  1246. Any option name can be used here. See |options|. When using the local value
  1247. and there is no buffer-local or window-local value, the global value is used
  1248. anyway.
  1249. register *expr-register* *@r*
  1250. --------
  1251. @r contents of register 'r'
  1252. The result is the contents of the named register, as a single string.
  1253. Newlines are inserted where required. To get the contents of the unnamed
  1254. register use @" or @@. See |registers| for an explanation of the available
  1255. registers.
  1256. When using the '=' register you get the expression itself, not what it
  1257. evaluates to. Use |eval()| to evaluate it.
  1258. nesting *expr-nesting* *E110*
  1259. -------
  1260. (expr1) nested expression
  1261. environment variable *expr-env*
  1262. --------------------
  1263. $VAR environment variable
  1264. The String value of any environment variable. When it is not defined, the
  1265. result is an empty string.
  1266. The functions `getenv()` and `setenv()` can also be used and work for
  1267. environment variables with non-alphanumeric names.
  1268. The function `environ()` can be used to get a Dict with all environment
  1269. variables.
  1270. *expr-env-expand*
  1271. Note that there is a difference between using $VAR directly and using
  1272. expand("$VAR"). Using it directly will only expand environment variables that
  1273. are known inside the current Vim session. Using expand() will first try using
  1274. the environment variables known inside the current Vim session. If that
  1275. fails, a shell will be used to expand the variable. This can be slow, but it
  1276. does expand all variables that the shell knows about. Example: >
  1277. :echo $shell
  1278. :echo expand("$shell")
  1279. The first one probably doesn't echo anything, the second echoes the $shell
  1280. variable (if your shell supports it).
  1281. internal variable *expr-variable* *E1015* *E1089*
  1282. -----------------
  1283. variable internal variable
  1284. See below |internal-variables|.
  1285. function call *expr-function* *E116* *E118* *E119* *E120*
  1286. -------------
  1287. function(expr1, ...) function call
  1288. See below |functions|.
  1289. lambda expression *expr-lambda* *lambda*
  1290. -----------------
  1291. {args -> expr1} legacy lambda expression *E451*
  1292. (args) => expr1 |Vim9| lambda expression
  1293. A lambda expression creates a new unnamed function which returns the result of
  1294. evaluating |expr1|. Lambda expressions differ from |user-functions| in
  1295. the following ways:
  1296. 1. The body of the lambda expression is an |expr1| and not a sequence of |Ex|
  1297. commands.
  1298. 2. The prefix "a:" should not be used for arguments. E.g.: >
  1299. :let F = {arg1, arg2 -> arg1 - arg2}
  1300. :echo F(5, 2)
  1301. < 3
  1302. The arguments are optional. Example: >
  1303. :let F = {-> 'error function'}
  1304. :echo F('ignored')
  1305. < error function
  1306. The |Vim9| lambda does not only use a different syntax, it also adds type
  1307. checking and can be split over multiple lines, see |vim9-lambda|.
  1308. *closure*
  1309. Lambda expressions can access outer scope variables and arguments. This is
  1310. often called a closure. Example where "i" and "a:arg" are used in a lambda
  1311. while they already exist in the function scope. They remain valid even after
  1312. the function returns: >
  1313. :function Foo(arg)
  1314. : let i = 3
  1315. : return {x -> x + i - a:arg}
  1316. :endfunction
  1317. :let Bar = Foo(4)
  1318. :echo Bar(6)
  1319. < 5
  1320. Note that the variables must exist in the outer scope before the lambda is
  1321. defined for this to work. See also |:func-closure|.
  1322. Lambda and closure support can be checked with: >
  1323. if has('lambda')
  1324. Examples for using a lambda expression with |sort()|, |map()| and |filter()|: >
  1325. :echo map([1, 2, 3], {idx, val -> val + 1})
  1326. < [2, 3, 4] >
  1327. :echo sort([3,7,2,1,4], {a, b -> a - b})
  1328. < [1, 2, 3, 4, 7]
  1329. The lambda expression is also useful for Channel, Job and timer: >
  1330. :let timer = timer_start(500,
  1331. \ {-> execute("echo 'Handler called'", "")},
  1332. \ {'repeat': 3})
  1333. < Handler called
  1334. Handler called
  1335. Handler called
  1336. Note that it is possible to cause memory to be used and not freed if the
  1337. closure is referenced by the context it depends on: >
  1338. function Function()
  1339. let x = 0
  1340. let F = {-> x}
  1341. endfunction
  1342. The closure uses "x" from the function scope, and "F" in that same scope
  1343. refers to the closure. This cycle results in the memory not being freed.
  1344. Recommendation: don't do this.
  1345. Notice how execute() is used to execute an Ex command. That's ugly though.
  1346. In Vim9 script you can use a command block, see |inline-function|.
  1347. Although you can use the loop variable of a `for` command, it must still exist
  1348. when the closure is called, otherwise you get an error. *E1302*
  1349. Lambda expressions have internal names like '<lambda>42'. If you get an error
  1350. for a lambda expression, you can find what it is with the following command: >
  1351. :function <lambda>42
  1352. See also: |numbered-function|
  1353. ==============================================================================
  1354. 3. Internal variable *internal-variables* *E461* *E1001*
  1355. An internal variable name can be made up of letters, digits and '_'. But it
  1356. cannot start with a digit. In legacy script it is also possible to use curly
  1357. braces, see |curly-braces-names|.
  1358. In legacy script an internal variable is created with the ":let" command
  1359. |:let|. An internal variable is explicitly destroyed with the ":unlet"
  1360. command |:unlet|.
  1361. Using a name that is not an internal variable or refers to a variable that has
  1362. been destroyed results in an error.
  1363. In |Vim9| script `:let` is not used and variables work differently, see |:var|.
  1364. *variable-scope*
  1365. There are several name spaces for variables. Which one is to be used is
  1366. specified by what is prepended:
  1367. (nothing) In a function: local to the function;
  1368. in a legacy script: global;
  1369. in a |Vim9| script: local to the script
  1370. |buffer-variable| b: Local to the current buffer.
  1371. |window-variable| w: Local to the current window.
  1372. |tabpage-variable| t: Local to the current tab page.
  1373. |global-variable| g: Global.
  1374. |local-variable| l: Local to a function (only in a legacy function)
  1375. |script-variable| s: Local to a |:source|'ed Vim script.
  1376. |function-argument| a: Function argument (only in a legacy function).
  1377. |vim-variable| v: Global, predefined by Vim.
  1378. The scope name by itself can be used as a |Dictionary|. For example, to
  1379. delete all script-local variables: >
  1380. :for k in keys(s:)
  1381. : unlet s:[k]
  1382. :endfor
  1383. Note: in Vim9 script variables can also be local to a block of commands, see
  1384. |vim9-scopes|.
  1385. *buffer-variable* *b:var* *b:*
  1386. A variable name that is preceded with "b:" is local to the current buffer.
  1387. Thus you can have several "b:foo" variables, one for each buffer.
  1388. This kind of variable is deleted when the buffer is wiped out or deleted with
  1389. |:bdelete|.
  1390. One local buffer variable is predefined:
  1391. *b:changedtick* *changetick*
  1392. b:changedtick The total number of changes to the current buffer. It is
  1393. incremented for each change. An undo command is also a change
  1394. in this case. Resetting 'modified' when writing the buffer is
  1395. also counted.
  1396. This can be used to perform an action only when the buffer has
  1397. changed. Example: >
  1398. :if my_changedtick != b:changedtick
  1399. : let my_changedtick = b:changedtick
  1400. : call My_Update()
  1401. :endif
  1402. < You cannot change or delete the b:changedtick variable.
  1403. *window-variable* *w:var* *w:*
  1404. A variable name that is preceded with "w:" is local to the current window. It
  1405. is deleted when the window is closed.
  1406. *tabpage-variable* *t:var* *t:*
  1407. A variable name that is preceded with "t:" is local to the current tab page,
  1408. It is deleted when the tab page is closed. {not available when compiled
  1409. without the |+windows| feature}
  1410. *global-variable* *g:var* *g:*
  1411. Inside functions and in |Vim9| script global variables are accessed with "g:".
  1412. Omitting this will access a variable local to a function or script. "g:"
  1413. can also be used in any other place if you like.
  1414. *local-variable* *l:var* *l:*
  1415. Inside functions local variables are accessed without prepending anything.
  1416. But you can also prepend "l:" if you like. However, without prepending "l:"
  1417. you may run into reserved variable names. For example "count". By itself it
  1418. refers to "v:count". Using "l:count" you can have a local variable with the
  1419. same name.
  1420. *script-variable* *s:var*
  1421. In a legacy Vim script variables starting with "s:" can be used. They cannot
  1422. be accessed from outside of the scripts, thus are local to the script.
  1423. In |Vim9| script the "s:" prefix can be omitted, variables are script-local by
  1424. default.
  1425. They can be used in:
  1426. - commands executed while the script is sourced
  1427. - functions defined in the script
  1428. - autocommands defined in the script
  1429. - functions and autocommands defined in functions and autocommands which were
  1430. defined in the script (recursively)
  1431. - user defined commands defined in the script
  1432. Thus not in:
  1433. - other scripts sourced from this one
  1434. - mappings
  1435. - menus
  1436. - etc.
  1437. Script variables can be used to avoid conflicts with global variable names.
  1438. Take this example: >
  1439. let s:counter = 0
  1440. function MyCounter()
  1441. let s:counter = s:counter + 1
  1442. echo s:counter
  1443. endfunction
  1444. command Tick call MyCounter()
  1445. You can now invoke "Tick" from any script, and the "s:counter" variable in
  1446. that script will not be changed, only the "s:counter" in the script where
  1447. "Tick" was defined is used.
  1448. Another example that does the same: >
  1449. let s:counter = 0
  1450. command Tick let s:counter = s:counter + 1 | echo s:counter
  1451. When calling a function and invoking a user-defined command, the context for
  1452. script variables is set to the script where the function or command was
  1453. defined.
  1454. The script variables are also available when a function is defined inside a
  1455. function that is defined in a script. Example: >
  1456. let s:counter = 0
  1457. function StartCounting(incr)
  1458. if a:incr
  1459. function MyCounter()
  1460. let s:counter = s:counter + 1
  1461. endfunction
  1462. else
  1463. function MyCounter()
  1464. let s:counter = s:counter - 1
  1465. endfunction
  1466. endif
  1467. endfunction
  1468. This defines the MyCounter() function either for counting up or counting down
  1469. when calling StartCounting(). It doesn't matter from where StartCounting() is
  1470. called, the s:counter variable will be accessible in MyCounter().
  1471. When the same script is sourced again it will use the same script variables.
  1472. They will remain valid as long as Vim is running. This can be used to
  1473. maintain a counter: >
  1474. if !exists("s:counter")
  1475. let s:counter = 1
  1476. echo "script executed for the first time"
  1477. else
  1478. let s:counter = s:counter + 1
  1479. echo "script executed " .. s:counter .. " times now"
  1480. endif
  1481. Note that this means that filetype plugins don't get a different set of script
  1482. variables for each buffer. Use local buffer variables instead |b:var|.
  1483. PREDEFINED VIM VARIABLES *vim-variable* *v:var* *v:*
  1484. *E963* *E1063*
  1485. Some variables can be set by the user, but the type cannot be changed.
  1486. *v:argv* *argv-variable*
  1487. v:argv The command line arguments Vim was invoked with. This is a
  1488. list of strings. The first item is the Vim command.
  1489. See |v:progpath| for the command with full path.
  1490. *v:beval_col* *beval_col-variable*
  1491. v:beval_col The number of the column, over which the mouse pointer is.
  1492. This is the byte index in the |v:beval_lnum| line.
  1493. Only valid while evaluating the 'balloonexpr' option.
  1494. *v:beval_bufnr* *beval_bufnr-variable*
  1495. v:beval_bufnr The number of the buffer, over which the mouse pointer is. Only
  1496. valid while evaluating the 'balloonexpr' option.
  1497. *v:beval_lnum* *beval_lnum-variable*
  1498. v:beval_lnum The number of the line, over which the mouse pointer is. Only
  1499. valid while evaluating the 'balloonexpr' option.
  1500. *v:beval_text* *beval_text-variable*
  1501. v:beval_text The text under or after the mouse pointer. Usually a word as
  1502. it is useful for debugging a C program. 'iskeyword' applies,
  1503. but a dot and "->" before the position is included. When on a
  1504. ']' the text before it is used, including the matching '[' and
  1505. word before it. When on a Visual area within one line the
  1506. highlighted text is used. Also see |<cexpr>|.
  1507. Only valid while evaluating the 'balloonexpr' option.
  1508. *v:beval_winnr* *beval_winnr-variable*
  1509. v:beval_winnr The number of the window, over which the mouse pointer is. Only
  1510. valid while evaluating the 'balloonexpr' option. The first
  1511. window has number zero (unlike most other places where a
  1512. window gets a number).
  1513. *v:beval_winid* *beval_winid-variable*
  1514. v:beval_winid The |window-ID| of the window, over which the mouse pointer
  1515. is. Otherwise like v:beval_winnr.
  1516. *v:char* *char-variable*
  1517. v:char Argument for evaluating 'formatexpr' and used for the typed
  1518. character when using <expr> in an abbreviation |:map-<expr>|.
  1519. It is also used by the |InsertCharPre| and |InsertEnter| events.
  1520. *v:charconvert_from* *charconvert_from-variable*
  1521. v:charconvert_from
  1522. The name of the character encoding of a file to be converted.
  1523. Only valid while evaluating the 'charconvert' option.
  1524. *v:charconvert_to* *charconvert_to-variable*
  1525. v:charconvert_to
  1526. The name of the character encoding of a file after conversion.
  1527. Only valid while evaluating the 'charconvert' option.
  1528. *v:cmdarg* *cmdarg-variable*
  1529. v:cmdarg This variable is used for two purposes:
  1530. 1. The extra arguments given to a file read/write command.
  1531. Currently these are "++enc=" and "++ff=". This variable is
  1532. set before an autocommand event for a file read/write
  1533. command is triggered. There is a leading space to make it
  1534. possible to append this variable directly after the
  1535. read/write command. Note: The "+cmd" argument isn't
  1536. included here, because it will be executed anyway.
  1537. 2. When printing a PostScript file with ":hardcopy" this is
  1538. the argument for the ":hardcopy" command. This can be used
  1539. in 'printexpr'.
  1540. *v:cmdbang* *cmdbang-variable*
  1541. v:cmdbang Set like v:cmdarg for a file read/write command. When a "!"
  1542. was used the value is 1, otherwise it is 0. Note that this
  1543. can only be used in autocommands. For user commands |<bang>|
  1544. can be used.
  1545. *v:collate* *collate-variable*
  1546. v:collate The current locale setting for collation order of the runtime
  1547. environment. This allows Vim scripts to be aware of the
  1548. current locale encoding. Technical: it's the value of
  1549. LC_COLLATE. When not using a locale the value is "C".
  1550. This variable can not be set directly, use the |:language|
  1551. command.
  1552. See |multi-lang|.
  1553. *v:colornames*
  1554. v:colornames A dictionary that maps color names to hex color strings. These
  1555. color names can be used with the |highlight-guifg|,
  1556. |highlight-guibg|, and |highlight-guisp| parameters. Updating
  1557. an entry in v:colornames has no immediate effect on the syntax
  1558. highlighting. The highlight commands (probably in a
  1559. colorscheme script) need to be re-evaluated in order to use
  1560. the updated color values. For example: >
  1561. :let v:colornames['fuscia'] = '#cf3ab4'
  1562. :let v:colornames['mauve'] = '#915f6d'
  1563. :highlight Normal guifg=fuscia guibg=mauve
  1564. <
  1565. This cannot be used to override the |cterm-colors| but it can
  1566. be used to override other colors. For example, the X11 colors
  1567. defined in the `colors/lists/default.vim` (previously defined
  1568. in |rgb.txt|). When defining new color names in a plugin, the
  1569. recommended practice is to set a color entry only when it does
  1570. not already exist. For example: >
  1571. :call extend(v:colornames, {
  1572. \ 'fuscia': '#cf3ab4',
  1573. \ 'mauve': '#915f6d,
  1574. \ }, 'keep')
  1575. <
  1576. Using |extend()| with the 'keep' option updates each color only
  1577. if it did not exist in |v:colornames|. Doing so allows the
  1578. user to choose the precise color value for a common name
  1579. by setting it in their |.vimrc|.
  1580. It is possible to remove entries from this dictionary but
  1581. doing so is NOT recommended, because it is disruptive to
  1582. other scripts. It is also unlikely to achieve the desired
  1583. result because the |:colorscheme| and |:highlight| commands will
  1584. both automatically load all `colors/lists/default.vim` color
  1585. scripts.
  1586. *v:completed_item* *completed_item-variable*
  1587. v:completed_item
  1588. |Dictionary| containing the |complete-items| for the most
  1589. recently completed word after |CompleteDone|. The
  1590. |Dictionary| is empty if the completion failed.
  1591. Note: Plugins can modify the value to emulate the builtin
  1592. |CompleteDone| event behavior.
  1593. *v:count* *count-variable*
  1594. v:count The count given for the last Normal mode command. Can be used
  1595. to get the count before a mapping. Read-only. Example: >
  1596. :map _x :<C-U>echo "the count is " .. v:count<CR>
  1597. < Note: The <C-U> is required to remove the line range that you
  1598. get when typing ':' after a count.
  1599. When there are two counts, as in "3d2w", they are multiplied,
  1600. just like what happens in the command, "d6w" for the example.
  1601. Also used for evaluating the 'formatexpr' option.
  1602. "count" also works, for backwards compatibility, unless
  1603. |scriptversion| is 3 or higher.
  1604. *v:count1* *count1-variable*
  1605. v:count1 Just like "v:count", but defaults to one when no count is
  1606. used.
  1607. *v:ctype* *ctype-variable*
  1608. v:ctype The current locale setting for characters of the runtime
  1609. environment. This allows Vim scripts to be aware of the
  1610. current locale encoding. Technical: it's the value of
  1611. LC_CTYPE. When not using a locale the value is "C".
  1612. This variable can not be set directly, use the |:language|
  1613. command.
  1614. See |multi-lang|.
  1615. *v:dying* *dying-variable*
  1616. v:dying Normally zero. When a deadly signal is caught it's set to
  1617. one. When multiple signals are caught the number increases.
  1618. Can be used in an autocommand to check if Vim didn't
  1619. terminate normally. {only works on Unix}
  1620. Example: >
  1621. :au VimLeave * if v:dying | echo "\nAAAAaaaarrrggghhhh!!!\n" | endif
  1622. < Note: if another deadly signal is caught when v:dying is one,
  1623. VimLeave autocommands will not be executed.
  1624. *v:exiting* *exiting-variable*
  1625. v:exiting Vim exit code. Normally zero, non-zero when something went
  1626. wrong. The value is v:null before invoking the |VimLeavePre|
  1627. and |VimLeave| autocmds. See |:q|, |:x| and |:cquit|.
  1628. Example: >
  1629. :au VimLeave * echo "Exit value is " .. v:exiting
  1630. <
  1631. *v:echospace* *echospace-variable*
  1632. v:echospace Number of screen cells that can be used for an `:echo` message
  1633. in the last screen line before causing the |hit-enter-prompt|.
  1634. Depends on 'showcmd', 'ruler' and 'columns'. You need to
  1635. check 'cmdheight' for whether there are full-width lines
  1636. available above the last line.
  1637. *v:errmsg* *errmsg-variable*
  1638. v:errmsg Last given error message. It's allowed to set this variable.
  1639. Example: >
  1640. :let v:errmsg = ""
  1641. :silent! next
  1642. :if v:errmsg != ""
  1643. : ... handle error
  1644. < "errmsg" also works, for backwards compatibility, unless
  1645. |scriptversion| is 3 or higher.
  1646. *v:errors* *errors-variable* *assert-return*
  1647. v:errors Errors found by assert functions, such as |assert_true()|.
  1648. This is a list of strings.
  1649. The assert functions append an item when an assert fails.
  1650. The return value indicates this: a one is returned if an item
  1651. was added to v:errors, otherwise zero is returned.
  1652. To remove old results make it empty: >
  1653. :let v:errors = []
  1654. < If v:errors is set to anything but a list it is made an empty
  1655. list by the assert function.
  1656. *v:event* *event-variable*
  1657. v:event Dictionary containing information about the current
  1658. |autocommand|. See the specific event for what it puts in
  1659. this dictionary.
  1660. The dictionary is emptied when the |autocommand| finishes,
  1661. please refer to |dict-identity| for how to get an independent
  1662. copy of it. Use |deepcopy()| if you want to keep the
  1663. information after the event triggers. Example: >
  1664. au TextYankPost * let g:foo = deepcopy(v:event)
  1665. <
  1666. *v:exception* *exception-variable*
  1667. v:exception The value of the exception most recently caught and not
  1668. finished. See also |v:throwpoint| and |throw-variables|.
  1669. Example: >
  1670. :try
  1671. : throw "oops"
  1672. :catch /.*/
  1673. : echo "caught " .. v:exception
  1674. :endtry
  1675. < Output: "caught oops".
  1676. *v:false* *false-variable*
  1677. v:false A Number with value zero. Used to put "false" in JSON. See
  1678. |json_encode()|.
  1679. When used as a string this evaluates to "v:false". >
  1680. echo v:false
  1681. < v:false ~
  1682. That is so that eval() can parse the string back to the same
  1683. value. Read-only.
  1684. In |Vim9| script "false" can be used which has a boolean type.
  1685. *v:fcs_reason* *fcs_reason-variable*
  1686. v:fcs_reason The reason why the |FileChangedShell| event was triggered.
  1687. Can be used in an autocommand to decide what to do and/or what
  1688. to set v:fcs_choice to. Possible values:
  1689. deleted file no longer exists
  1690. conflict file contents, mode or timestamp was
  1691. changed and buffer is modified
  1692. changed file contents has changed
  1693. mode mode of file changed
  1694. time only file timestamp changed
  1695. *v:fcs_choice* *fcs_choice-variable*
  1696. v:fcs_choice What should happen after a |FileChangedShell| event was
  1697. triggered. Can be used in an autocommand to tell Vim what to
  1698. do with the affected buffer:
  1699. reload Reload the buffer (does not work if
  1700. the file was deleted).
  1701. edit Reload the buffer and detect the
  1702. values for options such as
  1703. 'fileformat', 'fileencoding', 'binary'
  1704. (does not work if the file was
  1705. deleted).
  1706. ask Ask the user what to do, as if there
  1707. was no autocommand. Except that when
  1708. only the timestamp changed nothing
  1709. will happen.
  1710. <empty> Nothing, the autocommand should do
  1711. everything that needs to be done.
  1712. The default is empty. If another (invalid) value is used then
  1713. Vim behaves like it is empty, there is no warning message.
  1714. *v:fname* *fname-variable*
  1715. v:fname When evaluating 'includeexpr': the file name that was
  1716. detected. Empty otherwise.
  1717. *v:fname_in* *fname_in-variable*
  1718. v:fname_in The name of the input file. Valid while evaluating:
  1719. option used for ~
  1720. 'charconvert' file to be converted
  1721. 'diffexpr' original file
  1722. 'patchexpr' original file
  1723. 'printexpr' file to be printed
  1724. And set to the swap file name for |SwapExists|.
  1725. *v:fname_out* *fname_out-variable*
  1726. v:fname_out The name of the output file. Only valid while
  1727. evaluating:
  1728. option used for ~
  1729. 'charconvert' resulting converted file (*)
  1730. 'diffexpr' output of diff
  1731. 'patchexpr' resulting patched file
  1732. (*) When doing conversion for a write command (e.g., ":w
  1733. file") it will be equal to v:fname_in. When doing conversion
  1734. for a read command (e.g., ":e file") it will be a temporary
  1735. file and different from v:fname_in.
  1736. *v:fname_new* *fname_new-variable*
  1737. v:fname_new The name of the new version of the file. Only valid while
  1738. evaluating 'diffexpr'.
  1739. *v:fname_diff* *fname_diff-variable*
  1740. v:fname_diff The name of the diff (patch) file. Only valid while
  1741. evaluating 'patchexpr'.
  1742. *v:folddashes* *folddashes-variable*
  1743. v:folddashes Used for 'foldtext': dashes representing foldlevel of a closed
  1744. fold.
  1745. Read-only in the |sandbox|. |fold-foldtext|
  1746. *v:foldlevel* *foldlevel-variable*
  1747. v:foldlevel Used for 'foldtext': foldlevel of closed fold.
  1748. Read-only in the |sandbox|. |fold-foldtext|
  1749. *v:foldend* *foldend-variable*
  1750. v:foldend Used for 'foldtext': last line of closed fold.
  1751. Read-only in the |sandbox|. |fold-foldtext|
  1752. *v:foldstart* *foldstart-variable*
  1753. v:foldstart Used for 'foldtext': first line of closed fold.
  1754. Read-only in the |sandbox|. |fold-foldtext|
  1755. *v:hlsearch* *hlsearch-variable*
  1756. v:hlsearch Variable that indicates whether search highlighting is on.
  1757. Setting it makes sense only if 'hlsearch' is enabled which
  1758. requires |+extra_search|. Setting this variable to zero acts
  1759. like the |:nohlsearch| command, setting it to one acts like >
  1760. let &hlsearch = &hlsearch
  1761. < Note that the value is restored when returning from a
  1762. function. |function-search-undo|.
  1763. *v:insertmode* *insertmode-variable*
  1764. v:insertmode Used for the |InsertEnter| and |InsertChange| autocommand
  1765. events. Values:
  1766. i Insert mode
  1767. r Replace mode
  1768. v Virtual Replace mode
  1769. *v:key* *key-variable*
  1770. v:key Key of the current item of a |Dictionary|. Only valid while
  1771. evaluating the expression used with |map()| and |filter()|.
  1772. Read-only.
  1773. *v:lang* *lang-variable*
  1774. v:lang The current locale setting for messages of the runtime
  1775. environment. This allows Vim scripts to be aware of the
  1776. current language. Technical: it's the value of LC_MESSAGES.
  1777. The value is system dependent.
  1778. This variable can not be set directly, use the |:language|
  1779. command.
  1780. It can be different from |v:ctype| when messages are desired
  1781. in a different language than what is used for character
  1782. encoding. See |multi-lang|.
  1783. *v:lc_time* *lc_time-variable*
  1784. v:lc_time The current locale setting for time messages of the runtime
  1785. environment. This allows Vim scripts to be aware of the
  1786. current language. Technical: it's the value of LC_TIME.
  1787. This variable can not be set directly, use the |:language|
  1788. command. See |multi-lang|.
  1789. *v:lnum* *lnum-variable*
  1790. v:lnum Line number for the 'foldexpr' |fold-expr|, 'formatexpr' and
  1791. 'indentexpr' expressions, tab page number for 'guitablabel'
  1792. and 'guitabtooltip'. Only valid while one of these
  1793. expressions is being evaluated. Read-only when in the
  1794. |sandbox|.
  1795. *v:maxcol* *maxcol-variable*
  1796. v:maxcol Maximum line length. Depending on where it is used it can be
  1797. screen columns, characters or bytes. The value currently is
  1798. 2147483647 on all systems.
  1799. *v:mouse_win* *mouse_win-variable*
  1800. v:mouse_win Window number for a mouse click obtained with |getchar()|.
  1801. First window has number 1, like with |winnr()|. The value is
  1802. zero when there was no mouse button click.
  1803. *v:mouse_winid* *mouse_winid-variable*
  1804. v:mouse_winid Window ID for a mouse click obtained with |getchar()|.
  1805. The value is zero when there was no mouse button click.
  1806. *v:mouse_lnum* *mouse_lnum-variable*
  1807. v:mouse_lnum Line number for a mouse click obtained with |getchar()|.
  1808. This is the text line number, not the screen line number. The
  1809. value is zero when there was no mouse button click.
  1810. *v:mouse_col* *mouse_col-variable*
  1811. v:mouse_col Column number for a mouse click obtained with |getchar()|.
  1812. This is the screen column number, like with |virtcol()|. The
  1813. value is zero when there was no mouse button click.
  1814. *v:none* *none-variable* *None*
  1815. v:none An empty String. Used to put an empty item in JSON. See
  1816. |json_encode()|.
  1817. This can also be used as a function argument to use the
  1818. default value, see |none-function_argument|.
  1819. When used as a number this evaluates to zero.
  1820. When used as a string this evaluates to "v:none". >
  1821. echo v:none
  1822. < v:none ~
  1823. That is so that eval() can parse the string back to the same
  1824. value. Read-only.
  1825. Note that using `== v:none` and `!= v:none` will often give
  1826. an error. Instead, use `is v:none` and `isnot v:none` .
  1827. *v:null* *null-variable*
  1828. v:null An empty String. Used to put "null" in JSON. See
  1829. |json_encode()|.
  1830. When used as a number this evaluates to zero.
  1831. When used as a string this evaluates to "v:null". >
  1832. echo v:null
  1833. < v:null ~
  1834. That is so that eval() can parse the string back to the same
  1835. value. Read-only.
  1836. In |Vim9| script `null` can be used without "v:".
  1837. In some places `v:null` and `null` can be used for a List,
  1838. Dict, Job, etc. that is not set. That is slightly different
  1839. than an empty List, Dict, etc.
  1840. *v:numbermax* *numbermax-variable*
  1841. v:numbermax Maximum value of a number.
  1842. *v:numbermin* *numbermin-variable*
  1843. v:numbermin Minimum value of a number (negative).
  1844. *v:numbersize* *numbersize-variable*
  1845. v:numbersize Number of bits in a Number. This is normally 64, but on some
  1846. systems it may be 32.
  1847. *v:oldfiles* *oldfiles-variable*
  1848. v:oldfiles List of file names that is loaded from the |viminfo| file on
  1849. startup. These are the files that Vim remembers marks for.
  1850. The length of the List is limited by the ' argument of the
  1851. 'viminfo' option (default is 100).
  1852. When the |viminfo| file is not used the List is empty.
  1853. Also see |:oldfiles| and |c_#<|.
  1854. The List can be modified, but this has no effect on what is
  1855. stored in the |viminfo| file later. If you use values other
  1856. than String this will cause trouble.
  1857. {only when compiled with the |+viminfo| feature}
  1858. *v:option_new*
  1859. v:option_new New value of the option. Valid while executing an |OptionSet|
  1860. autocommand.
  1861. *v:option_old*
  1862. v:option_old Old value of the option. Valid while executing an |OptionSet|
  1863. autocommand. Depending on the command used for setting and the
  1864. kind of option this is either the local old value or the
  1865. global old value.
  1866. *v:option_oldlocal*
  1867. v:option_oldlocal
  1868. Old local value of the option. Valid while executing an
  1869. |OptionSet| autocommand.
  1870. *v:option_oldglobal*
  1871. v:option_oldglobal
  1872. Old global value of the option. Valid while executing an
  1873. |OptionSet| autocommand.
  1874. *v:option_type*
  1875. v:option_type Scope of the set command. Valid while executing an
  1876. |OptionSet| autocommand. Can be either "global" or "local"
  1877. *v:option_command*
  1878. v:option_command
  1879. Command used to set the option. Valid while executing an
  1880. |OptionSet| autocommand.
  1881. value option was set via ~
  1882. "setlocal" |:setlocal| or ":let l:xxx"
  1883. "setglobal" |:setglobal| or ":let g:xxx"
  1884. "set" |:set| or |:let|
  1885. "modeline" |modeline|
  1886. *v:operator* *operator-variable*
  1887. v:operator The last operator given in Normal mode. This is a single
  1888. character except for commands starting with <g> or <z>,
  1889. in which case it is two characters. Best used alongside
  1890. |v:prevcount| and |v:register|. Useful if you want to cancel
  1891. Operator-pending mode and then use the operator, e.g.: >
  1892. :omap O <Esc>:call MyMotion(v:operator)<CR>
  1893. < The value remains set until another operator is entered, thus
  1894. don't expect it to be empty.
  1895. v:operator is not set for |:delete|, |:yank| or other Ex
  1896. commands.
  1897. Read-only.
  1898. *v:prevcount* *prevcount-variable*
  1899. v:prevcount The count given for the last but one Normal mode command.
  1900. This is the v:count value of the previous command. Useful if
  1901. you want to cancel Visual or Operator-pending mode and then
  1902. use the count, e.g.: >
  1903. :vmap % <Esc>:call MyFilter(v:prevcount)<CR>
  1904. < Read-only.
  1905. *v:profiling* *profiling-variable*
  1906. v:profiling Normally zero. Set to one after using ":profile start".
  1907. See |profiling|.
  1908. *v:progname* *progname-variable*
  1909. v:progname Contains the name (with path removed) with which Vim was
  1910. invoked. Allows you to do special initialisations for |view|,
  1911. |evim| etc., or any other name you might symlink to Vim.
  1912. Read-only.
  1913. *v:progpath* *progpath-variable*
  1914. v:progpath Contains the command with which Vim was invoked, in a form
  1915. that when passed to the shell will run the same Vim executable
  1916. as the current one (if $PATH remains unchanged).
  1917. Useful if you want to message a Vim server using a
  1918. |--remote-expr|.
  1919. To get the full path use: >
  1920. echo exepath(v:progpath)
  1921. < If the command has a relative path it will be expanded to the
  1922. full path, so that it still works after `:cd`. Thus starting
  1923. "./vim" results in "/home/user/path/to/vim/src/vim".
  1924. On Linux and other systems it will always be the full path.
  1925. On Mac it may just be "vim" and using exepath() as mentioned
  1926. above should be used to get the full path.
  1927. On MS-Windows the executable may be called "vim.exe", but the
  1928. ".exe" is not added to v:progpath.
  1929. Read-only.
  1930. *v:register* *register-variable*
  1931. v:register The name of the register in effect for the current normal mode
  1932. command (regardless of whether that command actually used a
  1933. register). Or for the currently executing normal mode mapping
  1934. (use this in custom commands that take a register).
  1935. If none is supplied it is the default register '"', unless
  1936. 'clipboard' contains "unnamed" or "unnamedplus", then it is
  1937. '*' or '+'.
  1938. Also see |getreg()| and |setreg()|
  1939. *v:scrollstart* *scrollstart-variable*
  1940. v:scrollstart String describing the script or function that caused the
  1941. screen to scroll up. It's only set when it is empty, thus the
  1942. first reason is remembered. It is set to "Unknown" for a
  1943. typed command.
  1944. This can be used to find out why your script causes the
  1945. hit-enter prompt.
  1946. *v:servername* *servername-variable*
  1947. v:servername The resulting registered |client-server-name| if any.
  1948. Read-only.
  1949. v:searchforward *v:searchforward* *searchforward-variable*
  1950. Search direction: 1 after a forward search, 0 after a
  1951. backward search. It is reset to forward when directly setting
  1952. the last search pattern, see |quote/|.
  1953. Note that the value is restored when returning from a
  1954. function. |function-search-undo|.
  1955. Read-write.
  1956. *v:shell_error* *shell_error-variable*
  1957. v:shell_error Result of the last shell command. When non-zero, the last
  1958. shell command had an error. When zero, there was no problem.
  1959. This only works when the shell returns the error code to Vim.
  1960. The value -1 is often used when the command could not be
  1961. executed. Read-only.
  1962. Example: >
  1963. :!mv foo bar
  1964. :if v:shell_error
  1965. : echo 'could not rename "foo" to "bar"!'
  1966. :endif
  1967. < "shell_error" also works, for backwards compatibility, unless
  1968. |scriptversion| is 3 or higher.
  1969. *v:sizeofint* *sizeofint-variable*
  1970. v:sizeofint Number of bytes in an int. Depends on how Vim was compiled.
  1971. This is only useful for deciding whether a test will give the
  1972. expected result.
  1973. *v:sizeoflong* *sizeoflong-variable*
  1974. v:sizeoflong Number of bytes in a long. Depends on how Vim was compiled.
  1975. This is only useful for deciding whether a test will give the
  1976. expected result.
  1977. *v:sizeofpointer* *sizeofpointer-variable*
  1978. v:sizeofpointer Number of bytes in a pointer. Depends on how Vim was compiled.
  1979. This is only useful for deciding whether a test will give the
  1980. expected result.
  1981. *v:statusmsg* *statusmsg-variable*
  1982. v:statusmsg Last given status message. It's allowed to set this variable.
  1983. *v:swapname* *swapname-variable*
  1984. v:swapname Only valid when executing |SwapExists| autocommands: Name of
  1985. the swap file found. Read-only.
  1986. *v:swapchoice* *swapchoice-variable*
  1987. v:swapchoice |SwapExists| autocommands can set this to the selected choice
  1988. for handling an existing swap file:
  1989. 'o' Open read-only
  1990. 'e' Edit anyway
  1991. 'r' Recover
  1992. 'd' Delete swapfile
  1993. 'q' Quit
  1994. 'a' Abort
  1995. The value should be a single-character string. An empty value
  1996. results in the user being asked, as would happen when there is
  1997. no SwapExists autocommand. The default is empty.
  1998. *v:swapcommand* *swapcommand-variable*
  1999. v:swapcommand Normal mode command to be executed after a file has been
  2000. opened. Can be used for a |SwapExists| autocommand to have
  2001. another Vim open the file and jump to the right place. For
  2002. example, when jumping to a tag the value is ":tag tagname\r".
  2003. For ":edit +cmd file" the value is ":cmd\r".
  2004. *v:t_TYPE* *v:t_bool* *t_bool-variable*
  2005. v:t_bool Value of |Boolean| type. Read-only. See: |type()|
  2006. *v:t_channel* *t_channel-variable*
  2007. v:t_channel Value of |Channel| type. Read-only. See: |type()|
  2008. *v:t_dict* *t_dict-variable*
  2009. v:t_dict Value of |Dictionary| type. Read-only. See: |type()|
  2010. *v:t_float* *t_float-variable*
  2011. v:t_float Value of |Float| type. Read-only. See: |type()|
  2012. *v:t_func* *t_func-variable*
  2013. v:t_func Value of |Funcref| type. Read-only. See: |type()|
  2014. *v:t_job* *t_job-variable*
  2015. v:t_job Value of |Job| type. Read-only. See: |type()|
  2016. *v:t_list* *t_list-variable*
  2017. v:t_list Value of |List| type. Read-only. See: |type()|
  2018. *v:t_none* *t_none-variable*
  2019. v:t_none Value of |None| type. Read-only. See: |type()|
  2020. *v:t_number* *t_number-variable*
  2021. v:t_number Value of |Number| type. Read-only. See: |type()|
  2022. *v:t_string* *t_string-variable*
  2023. v:t_string Value of |String| type. Read-only. See: |type()|
  2024. *v:t_blob* *t_blob-variable*
  2025. v:t_blob Value of |Blob| type. Read-only. See: |type()|
  2026. *v:termresponse* *termresponse-variable*
  2027. v:termresponse The escape sequence returned by the terminal for the |t_RV|
  2028. termcap entry. It is set when Vim receives an escape sequence
  2029. that starts with ESC [ or CSI, then '>' or '?' and ends in a
  2030. 'c', with only digits and ';' in between.
  2031. When this option is set, the TermResponse autocommand event is
  2032. fired, so that you can react to the response from the
  2033. terminal. You can use |terminalprops()| to see what Vim
  2034. figured out about the terminal.
  2035. The response from a new xterm is: "<Esc>[> Pp ; Pv ; Pc c". Pp
  2036. is the terminal type: 0 for vt100 and 1 for vt220. Pv is the
  2037. patch level (since this was introduced in patch 95, it's
  2038. always 95 or higher). Pc is always zero.
  2039. If Pv is 141 or higher then Vim will try to request terminal
  2040. codes. This only works with xterm |xterm-codes|.
  2041. {only when compiled with |+termresponse| feature}
  2042. *v:termblinkresp*
  2043. v:termblinkresp The escape sequence returned by the terminal for the |t_RC|
  2044. termcap entry. This is used to find out whether the terminal
  2045. cursor is blinking. This is used by |term_getcursor()|.
  2046. *v:termstyleresp*
  2047. v:termstyleresp The escape sequence returned by the terminal for the |t_RS|
  2048. termcap entry. This is used to find out what the shape of the
  2049. cursor is. This is used by |term_getcursor()|.
  2050. *v:termrbgresp*
  2051. v:termrbgresp The escape sequence returned by the terminal for the |t_RB|
  2052. termcap entry. This is used to find out what the terminal
  2053. background color is, see 'background'.
  2054. *v:termrfgresp*
  2055. v:termrfgresp The escape sequence returned by the terminal for the |t_RF|
  2056. termcap entry. This is used to find out what the terminal
  2057. foreground color is.
  2058. *v:termu7resp*
  2059. v:termu7resp The escape sequence returned by the terminal for the |t_u7|
  2060. termcap entry. This is used to find out what the terminal
  2061. does with ambiguous width characters, see 'ambiwidth'.
  2062. *v:testing* *testing-variable*
  2063. v:testing Must be set before using `test_garbagecollect_now()`.
  2064. Also, when set certain error messages won't be shown for 2
  2065. seconds. (e.g. "'dictionary' option is empty")
  2066. *v:this_session* *this_session-variable*
  2067. v:this_session Full filename of the last loaded or saved session file. See
  2068. |:mksession|. It is allowed to set this variable. When no
  2069. session file has been saved, this variable is empty.
  2070. "this_session" also works, for backwards compatibility, unless
  2071. |scriptversion| is 3 or higher
  2072. *v:throwpoint* *throwpoint-variable*
  2073. v:throwpoint The point where the exception most recently caught and not
  2074. finished was thrown. Not set when commands are typed. See
  2075. also |v:exception| and |throw-variables|.
  2076. Example: >
  2077. :try
  2078. : throw "oops"
  2079. :catch /.*/
  2080. : echo "Exception from" v:throwpoint
  2081. :endtry
  2082. < Output: "Exception from test.vim, line 2"
  2083. *v:true* *true-variable*
  2084. v:true A Number with value one. Used to put "true" in JSON. See
  2085. |json_encode()|.
  2086. When used as a string this evaluates to "v:true". >
  2087. echo v:true
  2088. < v:true ~
  2089. That is so that eval() can parse the string back to the same
  2090. value. Read-only.
  2091. In |Vim9| script "true" can be used which has a boolean type.
  2092. *v:val* *val-variable*
  2093. v:val Value of the current item of a |List| or |Dictionary|. Only
  2094. valid while evaluating the expression used with |map()| and
  2095. |filter()|. Read-only.
  2096. *v:version* *version-variable*
  2097. v:version Version number of Vim: Major version number times 100 plus
  2098. minor version number. Version 5.0 is 500. Version 5.1
  2099. is 501. Read-only. "version" also works, for backwards
  2100. compatibility, unless |scriptversion| is 3 or higher.
  2101. Use |has()| to check if a certain patch was included, e.g.: >
  2102. if has("patch-7.4.123")
  2103. < Note that patch numbers are specific to the version, thus both
  2104. version 5.0 and 5.1 may have a patch 123, but these are
  2105. completely different.
  2106. *v:versionlong* *versionlong-variable*
  2107. v:versionlong Like v:version, but also including the patchlevel in the last
  2108. four digits. Version 8.1 with patch 123 has value 8010123.
  2109. This can be used like this: >
  2110. if v:versionlong >= 8010123
  2111. < However, if there are gaps in the list of patches included
  2112. this will not work well. This can happen if a recent patch
  2113. was included into an older version, e.g. for a security fix.
  2114. Use the has() function to make sure the patch is actually
  2115. included.
  2116. *v:vim_did_enter* *vim_did_enter-variable*
  2117. v:vim_did_enter Zero until most of startup is done. It is set to one just
  2118. before |VimEnter| autocommands are triggered.
  2119. *v:warningmsg* *warningmsg-variable*
  2120. v:warningmsg Last given warning message. It's allowed to set this variable.
  2121. *v:windowid* *windowid-variable*
  2122. v:windowid When any X11 based GUI is running or when running in a
  2123. terminal and Vim connects to the X server (|-X|) this will be
  2124. set to the window ID.
  2125. When an MS-Windows GUI is running this will be set to the
  2126. window handle.
  2127. Otherwise the value is zero.
  2128. Note: for windows inside Vim use |winnr()| or |win_getid()|,
  2129. see |window-ID|.
  2130. ==============================================================================
  2131. 4. Builtin Functions *functions*
  2132. See |function-list| for a list grouped by what the function is used for.
  2133. The alphabetic list of all builtin functions and details are in a separate
  2134. help file: |builtin-functions|.
  2135. ==============================================================================
  2136. 5. Defining functions *user-functions*
  2137. New functions can be defined. These can be called just like builtin
  2138. functions. The function takes arguments, executes a sequence of Ex commands
  2139. and can return a value.
  2140. You can find most information about defining functions in |userfunc.txt|.
  2141. For Vim9 functions, which execute much faster, support type checking and more,
  2142. see |vim9.txt|.
  2143. ==============================================================================
  2144. 6. Curly braces names *curly-braces-names*
  2145. In most places where you can use a variable, you can use a "curly braces name"
  2146. variable. This is a regular variable name with one or more expressions
  2147. wrapped in braces {} like this: >
  2148. my_{adjective}_variable
  2149. This only works in legacy Vim script, not in |Vim9| script.
  2150. When Vim encounters this, it evaluates the expression inside the braces, puts
  2151. that in place of the expression, and re-interprets the whole as a variable
  2152. name. So in the above example, if the variable "adjective" was set to
  2153. "noisy", then the reference would be to "my_noisy_variable", whereas if
  2154. "adjective" was set to "quiet", then it would be to "my_quiet_variable".
  2155. One application for this is to create a set of variables governed by an option
  2156. value. For example, the statement >
  2157. echo my_{&background}_message
  2158. would output the contents of "my_dark_message" or "my_light_message" depending
  2159. on the current value of 'background'.
  2160. You can use multiple brace pairs: >
  2161. echo my_{adverb}_{adjective}_message
  2162. ..or even nest them: >
  2163. echo my_{ad{end_of_word}}_message
  2164. where "end_of_word" is either "verb" or "jective".
  2165. However, the expression inside the braces must evaluate to a valid single
  2166. variable name, e.g. this is invalid: >
  2167. :let foo='a + b'
  2168. :echo c{foo}d
  2169. .. since the result of expansion is "ca + bd", which is not a variable name.
  2170. *curly-braces-function-names*
  2171. You can call and define functions by an evaluated name in a similar way.
  2172. Example: >
  2173. :let func_end='whizz'
  2174. :call my_func_{func_end}(parameter)
  2175. This would call the function "my_func_whizz(parameter)".
  2176. This does NOT work: >
  2177. :let i = 3
  2178. :let @{i} = '' " error
  2179. :echo @{i} " error
  2180. ==============================================================================
  2181. 7. Commands *expression-commands*
  2182. Note: in |Vim9| script `:let` is not used. `:var` is used for variable
  2183. declarations and assignments do not use a command. |vim9-declaration|
  2184. :let {var-name} = {expr1} *:let* *E18*
  2185. Set internal variable {var-name} to the result of the
  2186. expression {expr1}. The variable will get the type
  2187. from the {expr}. If {var-name} didn't exist yet, it
  2188. is created.
  2189. :let {var-name}[{idx}] = {expr1} *E689* *E1141*
  2190. Set a list item to the result of the expression
  2191. {expr1}. {var-name} must refer to a list and {idx}
  2192. must be a valid index in that list. For nested list
  2193. the index can be repeated.
  2194. This cannot be used to add an item to a |List|.
  2195. This cannot be used to set a byte in a String. You
  2196. can do that like this: >
  2197. :let var = var[0:2] .. 'X' .. var[4:]
  2198. < When {var-name} is a |Blob| then {idx} can be the
  2199. length of the blob, in which case one byte is
  2200. appended.
  2201. *E711* *E719* *E1165* *E1166* *E1183*
  2202. :let {var-name}[{idx1}:{idx2}] = {expr1} *E708* *E709* *E710*
  2203. Set a sequence of items in a |List| to the result of
  2204. the expression {expr1}, which must be a list with the
  2205. correct number of items.
  2206. {idx1} can be omitted, zero is used instead.
  2207. {idx2} can be omitted, meaning the end of the list.
  2208. When the selected range of items is partly past the
  2209. end of the list, items will be added.
  2210. *:let+=* *:let-=* *:letstar=* *:let/=* *:let%=*
  2211. *:let.=* *:let..=* *E734* *E985* *E1019*
  2212. :let {var} += {expr1} Like ":let {var} = {var} + {expr1}".
  2213. :let {var} -= {expr1} Like ":let {var} = {var} - {expr1}".
  2214. :let {var} *= {expr1} Like ":let {var} = {var} * {expr1}".
  2215. :let {var} /= {expr1} Like ":let {var} = {var} / {expr1}".
  2216. :let {var} %= {expr1} Like ":let {var} = {var} % {expr1}".
  2217. :let {var} .= {expr1} Like ":let {var} = {var} . {expr1}".
  2218. :let {var} ..= {expr1} Like ":let {var} = {var} .. {expr1}".
  2219. These fail if {var} was not set yet and when the type
  2220. of {var} and {expr1} don't fit the operator.
  2221. `.=` is not supported with Vim script version 2 and
  2222. later, see |vimscript-version|.
  2223. :let ${env-name} = {expr1} *:let-environment* *:let-$*
  2224. Set environment variable {env-name} to the result of
  2225. the expression {expr1}. The type is always String.
  2226. On some systems making an environment variable empty
  2227. causes it to be deleted. Many systems do not make a
  2228. difference between an environment variable that is not
  2229. set and an environment variable that is empty.
  2230. :let ${env-name} .= {expr1}
  2231. Append {expr1} to the environment variable {env-name}.
  2232. If the environment variable didn't exist yet this
  2233. works like "=".
  2234. :let @{reg-name} = {expr1} *:let-register* *:let-@*
  2235. Write the result of the expression {expr1} in register
  2236. {reg-name}. {reg-name} must be a single letter, and
  2237. must be the name of a writable register (see
  2238. |registers|). "@@" can be used for the unnamed
  2239. register, "@/" for the search pattern.
  2240. If the result of {expr1} ends in a <CR> or <NL>, the
  2241. register will be linewise, otherwise it will be set to
  2242. characterwise.
  2243. This can be used to clear the last search pattern: >
  2244. :let @/ = ""
  2245. < This is different from searching for an empty string,
  2246. that would match everywhere.
  2247. :let @{reg-name} .= {expr1}
  2248. Append {expr1} to register {reg-name}. If the
  2249. register was empty it's like setting it to {expr1}.
  2250. :let &{option-name} = {expr1} *:let-option* *:let-&*
  2251. Set option {option-name} to the result of the
  2252. expression {expr1}. A String or Number value is
  2253. always converted to the type of the option.
  2254. For an option local to a window or buffer the effect
  2255. is just like using the |:set| command: both the local
  2256. value and the global value are changed.
  2257. Example: >
  2258. :let &path = &path .. ',/usr/local/include'
  2259. < This also works for terminal codes in the form t_xx.
  2260. But only for alphanumerical names. Example: >
  2261. :let &t_k1 = "\<Esc>[234;"
  2262. < When the code does not exist yet it will be created as
  2263. a terminal key code, there is no error.
  2264. :let &{option-name} .= {expr1}
  2265. For a string option: Append {expr1} to the value.
  2266. Does not insert a comma like |:set+=|.
  2267. :let &{option-name} += {expr1}
  2268. :let &{option-name} -= {expr1}
  2269. For a number or boolean option: Add or subtract
  2270. {expr1}.
  2271. :let &l:{option-name} = {expr1}
  2272. :let &l:{option-name} .= {expr1}
  2273. :let &l:{option-name} += {expr1}
  2274. :let &l:{option-name} -= {expr1}
  2275. Like above, but only set the local value of an option
  2276. (if there is one). Works like |:setlocal|.
  2277. :let &g:{option-name} = {expr1}
  2278. :let &g:{option-name} .= {expr1}
  2279. :let &g:{option-name} += {expr1}
  2280. :let &g:{option-name} -= {expr1}
  2281. Like above, but only set the global value of an option
  2282. (if there is one). Works like |:setglobal|.
  2283. *E1093*
  2284. :let [{name1}, {name2}, ...] = {expr1} *:let-unpack* *E687* *E688*
  2285. {expr1} must evaluate to a |List|. The first item in
  2286. the list is assigned to {name1}, the second item to
  2287. {name2}, etc.
  2288. The number of names must match the number of items in
  2289. the |List|.
  2290. Each name can be one of the items of the ":let"
  2291. command as mentioned above.
  2292. Example: >
  2293. :let [s, item] = GetItem(s)
  2294. < Detail: {expr1} is evaluated first, then the
  2295. assignments are done in sequence. This matters if
  2296. {name2} depends on {name1}. Example: >
  2297. :let x = [0, 1]
  2298. :let i = 0
  2299. :let [i, x[i]] = [1, 2]
  2300. :echo x
  2301. < The result is [0, 2].
  2302. :let [{name1}, {name2}, ...] .= {expr1}
  2303. :let [{name1}, {name2}, ...] += {expr1}
  2304. :let [{name1}, {name2}, ...] -= {expr1}
  2305. Like above, but append/add/subtract the value for each
  2306. |List| item.
  2307. :let [{name}, ..., ; {lastname}] = {expr1} *E452*
  2308. Like |:let-unpack| above, but the |List| may have more
  2309. items than there are names. A list of the remaining
  2310. items is assigned to {lastname}. If there are no
  2311. remaining items {lastname} is set to an empty list.
  2312. Example: >
  2313. :let [a, b; rest] = ["aval", "bval", 3, 4]
  2314. <
  2315. :let [{name}, ..., ; {lastname}] .= {expr1}
  2316. :let [{name}, ..., ; {lastname}] += {expr1}
  2317. :let [{name}, ..., ; {lastname}] -= {expr1}
  2318. Like above, but append/add/subtract the value for each
  2319. |List| item.
  2320. *:let=<<* *:let-heredoc*
  2321. *E990* *E991* *E172* *E221* *E1145*
  2322. :let {var-name} =<< [trim] [eval] {endmarker}
  2323. text...
  2324. text...
  2325. {endmarker}
  2326. Set internal variable {var-name} to a |List|
  2327. containing the lines of text bounded by the string
  2328. {endmarker}.
  2329. If "eval" is not specified, then each line of text is
  2330. used as a |literal-string|, except that single quotes
  2331. does not need to be doubled.
  2332. If "eval" is specified, then any Vim expression in the
  2333. form {expr} is evaluated and the result replaces the
  2334. expression, like with |interpolated-string|.
  2335. Example where $HOME is expanded: >
  2336. let lines =<< trim eval END
  2337. some text
  2338. See the file {$HOME}/.vimrc
  2339. more text
  2340. END
  2341. < There can be multiple Vim expressions in a single line
  2342. but an expression cannot span multiple lines. If any
  2343. expression evaluation fails, then the assignment fails.
  2344. {endmarker} must not contain white space.
  2345. {endmarker} cannot start with a lower case character.
  2346. The last line should end only with the {endmarker}
  2347. string without any other character. Watch out for
  2348. white space after {endmarker}!
  2349. Without "trim" any white space characters in the lines
  2350. of text are preserved. If "trim" is specified before
  2351. {endmarker}, then indentation is stripped so you can
  2352. do: >
  2353. let text =<< trim END
  2354. if ok
  2355. echo 'done'
  2356. endif
  2357. END
  2358. < Results in: ["if ok", " echo 'done'", "endif"]
  2359. The marker must line up with "let" and the indentation
  2360. of the first line is removed from all the text lines.
  2361. Specifically: all the leading indentation exactly
  2362. matching the leading indentation of the first
  2363. non-empty text line is stripped from the input lines.
  2364. All leading indentation exactly matching the leading
  2365. indentation before `let` is stripped from the line
  2366. containing {endmarker}. Note that the difference
  2367. between space and tab matters here.
  2368. If {var-name} didn't exist yet, it is created.
  2369. Cannot be followed by another command, but can be
  2370. followed by a comment.
  2371. To avoid line continuation to be applied, consider
  2372. adding 'C' to 'cpoptions': >
  2373. set cpo+=C
  2374. let var =<< END
  2375. \ leading backslash
  2376. END
  2377. set cpo-=C
  2378. <
  2379. Examples: >
  2380. let var1 =<< END
  2381. Sample text 1
  2382. Sample text 2
  2383. Sample text 3
  2384. END
  2385. let data =<< trim DATA
  2386. 1 2 3 4
  2387. 5 6 7 8
  2388. DATA
  2389. let code =<< trim eval CODE
  2390. let v = {10 + 20}
  2391. let h = "{$HOME}"
  2392. let s = "{Str1()} abc {Str2()}"
  2393. let n = {MyFunc(3, 4)}
  2394. CODE
  2395. <
  2396. *E121*
  2397. :let {var-name} .. List the value of variable {var-name}. Multiple
  2398. variable names may be given. Special names recognized
  2399. here: *E738*
  2400. g: global variables
  2401. b: local buffer variables
  2402. w: local window variables
  2403. t: local tab page variables
  2404. s: script-local variables
  2405. l: local function variables
  2406. v: Vim variables.
  2407. This does not work in Vim9 script. |vim9-declaration|
  2408. :let List the values of all variables. The type of the
  2409. variable is indicated before the value:
  2410. <nothing> String
  2411. # Number
  2412. * Funcref
  2413. This does not work in Vim9 script. |vim9-declaration|
  2414. :unl[et][!] {name} ... *:unlet* *:unl* *E108* *E795* *E1081*
  2415. Remove the internal variable {name}. Several variable
  2416. names can be given, they are all removed. The name
  2417. may also be a |List| or |Dictionary| item.
  2418. With [!] no error message is given for non-existing
  2419. variables.
  2420. One or more items from a |List| can be removed: >
  2421. :unlet list[3] " remove fourth item
  2422. :unlet list[3:] " remove fourth item to last
  2423. < One item from a |Dictionary| can be removed at a time: >
  2424. :unlet dict['two']
  2425. :unlet dict.two
  2426. < This is especially useful to clean up used global
  2427. variables and script-local variables (these are not
  2428. deleted when the script ends). Function-local
  2429. variables are automatically deleted when the function
  2430. ends.
  2431. :unl[et] ${env-name} ... *:unlet-environment* *:unlet-$*
  2432. Remove environment variable {env-name}.
  2433. Can mix {name} and ${env-name} in one :unlet command.
  2434. No error message is given for a non-existing
  2435. variable, also without !.
  2436. If the system does not support deleting an environment
  2437. variable, it is made empty.
  2438. *:cons* *:const* *E1018*
  2439. :cons[t] {var-name} = {expr1}
  2440. :cons[t] [{name1}, {name2}, ...] = {expr1}
  2441. :cons[t] [{name}, ..., ; {lastname}] = {expr1}
  2442. :cons[t] {var-name} =<< [trim] {marker}
  2443. text...
  2444. text...
  2445. {marker}
  2446. Similar to |:let|, but additionally lock the variable
  2447. after setting the value. This is the same as locking
  2448. the variable with |:lockvar| just after |:let|, thus: >
  2449. :const x = 1
  2450. < is equivalent to: >
  2451. :let x = 1
  2452. :lockvar! x
  2453. < NOTE: in Vim9 script `:const` works differently, see
  2454. |vim9-const|
  2455. This is useful if you want to make sure the variable
  2456. is not modified. If the value is a List or Dictionary
  2457. literal then the items also cannot be changed: >
  2458. const ll = [1, 2, 3]
  2459. let ll[1] = 5 " Error!
  2460. < Nested references are not locked: >
  2461. let lvar = ['a']
  2462. const lconst = [0, lvar]
  2463. let lconst[0] = 2 " Error!
  2464. let lconst[1][0] = 'b' " OK
  2465. < *E995*
  2466. |:const| does not allow to for changing a variable: >
  2467. :let x = 1
  2468. :const x = 2 " Error!
  2469. < *E996*
  2470. Note that environment variables, option values and
  2471. register values cannot be used here, since they cannot
  2472. be locked.
  2473. :cons[t]
  2474. :cons[t] {var-name}
  2475. If no argument is given or only {var-name} is given,
  2476. the behavior is the same as |:let|.
  2477. :lockv[ar][!] [depth] {name} ... *:lockvar* *:lockv*
  2478. Lock the internal variable {name}. Locking means that
  2479. it can no longer be changed (until it is unlocked).
  2480. A locked variable can be deleted: >
  2481. :lockvar v
  2482. :let v = 'asdf' " fails!
  2483. :unlet v " works
  2484. < *E741* *E940* *E1118* *E1119* *E1120* *E1121* *E1122*
  2485. If you try to change a locked variable you get an
  2486. error message: "E741: Value is locked: {name}".
  2487. If you try to lock or unlock a built-in variable you
  2488. get an error message: "E940: Cannot lock or unlock
  2489. variable {name}".
  2490. [depth] is relevant when locking a |List| or
  2491. |Dictionary|. It specifies how deep the locking goes:
  2492. 0 Lock the variable {name} but not its
  2493. value.
  2494. 1 Lock the |List| or |Dictionary| itself,
  2495. cannot add or remove items, but can
  2496. still change their values.
  2497. 2 Also lock the values, cannot change
  2498. the items. If an item is a |List| or
  2499. |Dictionary|, cannot add or remove
  2500. items, but can still change the
  2501. values.
  2502. 3 Like 2 but for the |List| /
  2503. |Dictionary| in the |List| /
  2504. |Dictionary|, one level deeper.
  2505. The default [depth] is 2, thus when {name} is a |List|
  2506. or |Dictionary| the values cannot be changed.
  2507. Example with [depth] 0: >
  2508. let mylist = [1, 2, 3]
  2509. lockvar 0 mylist
  2510. let mylist[0] = 77 " OK
  2511. call add(mylist, 4] " OK
  2512. let mylist = [7, 8, 9] " Error!
  2513. < *E743*
  2514. For unlimited depth use [!] and omit [depth].
  2515. However, there is a maximum depth of 100 to catch
  2516. loops.
  2517. Note that when two variables refer to the same |List|
  2518. and you lock one of them, the |List| will also be
  2519. locked when used through the other variable.
  2520. Example: >
  2521. :let l = [0, 1, 2, 3]
  2522. :let cl = l
  2523. :lockvar l
  2524. :let cl[1] = 99 " won't work!
  2525. < You may want to make a copy of a list to avoid this.
  2526. See |deepcopy()|.
  2527. :unlo[ckvar][!] [depth] {name} ... *:unlockvar* *:unlo* *E1246*
  2528. Unlock the internal variable {name}. Does the
  2529. opposite of |:lockvar|.
  2530. If {name} does not exist:
  2531. - In |Vim9| script an error is given.
  2532. - In legacy script this is silently ignored.
  2533. :if {expr1} *:if* *:end* *:endif* *:en* *E171* *E579* *E580*
  2534. :en[dif] Execute the commands until the next matching `:else`
  2535. or `:endif` if {expr1} evaluates to non-zero.
  2536. Although the short forms work, it is recommended to
  2537. always use `:endif` to avoid confusion and to make
  2538. auto-indenting work properly.
  2539. From Vim version 4.5 until 5.0, every Ex command in
  2540. between the `:if` and `:endif` is ignored. These two
  2541. commands were just to allow for future expansions in a
  2542. backward compatible way. Nesting was allowed. Note
  2543. that any `:else` or `:elseif` was ignored, the `else`
  2544. part was not executed either.
  2545. You can use this to remain compatible with older
  2546. versions: >
  2547. :if version >= 500
  2548. : version-5-specific-commands
  2549. :endif
  2550. < The commands still need to be parsed to find the
  2551. `endif`. Sometimes an older Vim has a problem with a
  2552. new command. For example, `:silent` is recognized as
  2553. a `:substitute` command. In that case `:execute` can
  2554. avoid problems: >
  2555. :if version >= 600
  2556. : execute "silent 1,$delete"
  2557. :endif
  2558. <
  2559. In |Vim9| script `:endif` cannot be shortened, to
  2560. improve script readability.
  2561. NOTE: The `:append` and `:insert` commands don't work
  2562. properly in between `:if` and `:endif`.
  2563. *:else* *:el* *E581* *E583*
  2564. :el[se] Execute the commands until the next matching `:else`
  2565. or `:endif` if they previously were not being
  2566. executed.
  2567. In |Vim9| script `:else` cannot be shortened, to
  2568. improve script readability.
  2569. *:elseif* *:elsei* *E582* *E584*
  2570. :elsei[f] {expr1} Short for `:else` `:if`, with the addition that there
  2571. is no extra `:endif`.
  2572. In |Vim9| script `:elseif` cannot be shortened, to
  2573. improve script readability.
  2574. :wh[ile] {expr1} *:while* *:endwhile* *:wh* *:endw*
  2575. *E170* *E585* *E588* *E733*
  2576. :endw[hile] Repeat the commands between `:while` and `:endwhile`,
  2577. as long as {expr1} evaluates to non-zero.
  2578. When an error is detected from a command inside the
  2579. loop, execution continues after the `endwhile`.
  2580. Example: >
  2581. :let lnum = 1
  2582. :while lnum <= line("$")
  2583. :call FixLine(lnum)
  2584. :let lnum = lnum + 1
  2585. :endwhile
  2586. <
  2587. In |Vim9| script `:while` and `:endwhile` cannot be
  2588. shortened, to improve script readability.
  2589. NOTE: The `:append` and `:insert` commands don't work
  2590. properly inside a `:while` and `:for` loop.
  2591. :for {var} in {object} *:for* *E690* *E732*
  2592. :endfo[r] *:endfo* *:endfor*
  2593. Repeat the commands between `:for` and `:endfor` for
  2594. each item in {object}. {object} can be a |List|,
  2595. a |Blob| or a |String|. *E1177*
  2596. Variable {var} is set to the value of each item.
  2597. In |Vim9| script the loop variable must not have been
  2598. declared yet, unless when it is a
  2599. global/window/tab/buffer variable.
  2600. When an error is detected for a command inside the
  2601. loop, execution continues after the `endfor`.
  2602. Changing {object} inside the loop affects what items
  2603. are used. Make a copy if this is unwanted: >
  2604. :for item in copy(mylist)
  2605. <
  2606. When {object} is a |List| and not making a copy, in
  2607. legacy script Vim stores a reference to the next item
  2608. in the |List| before executing the commands with the
  2609. current item. Thus the current item can be removed
  2610. without effect. Removing any later item means it will
  2611. not be found. Thus the following example works (an
  2612. inefficient way to make a |List| empty): >
  2613. for item in mylist
  2614. call remove(mylist, 0)
  2615. endfor
  2616. < Note that reordering the |List| (e.g., with sort() or
  2617. reverse()) may have unexpected effects.
  2618. In |Vim9| script the index is used. If an item before
  2619. the current one is deleted the next item will be
  2620. skipped.
  2621. When {object} is a |Blob|, Vim always makes a copy to
  2622. iterate over. Unlike with |List|, modifying the
  2623. |Blob| does not affect the iteration.
  2624. When {object} is a |String| each item is a string with
  2625. one character, plus any combining characters.
  2626. In |Vim9| script `:endfor` cannot be shortened, to
  2627. improve script readability.
  2628. :for [{var1}, {var2}, ...] in {listlist}
  2629. :endfo[r] *E1140*
  2630. Like `:for` above, but each item in {listlist} must be
  2631. a list, of which each item is assigned to {var1},
  2632. {var2}, etc. Example: >
  2633. :for [lnum, col] in [[1, 3], [2, 5], [3, 8]]
  2634. :echo getline(lnum)[col]
  2635. :endfor
  2636. <
  2637. *:continue* *:con* *E586*
  2638. :con[tinue] When used inside a `:while` or `:for` loop, jumps back
  2639. to the start of the loop.
  2640. If it is used after a `:try` inside the loop but
  2641. before the matching `:finally` (if present), the
  2642. commands following the `:finally` up to the matching
  2643. `:endtry` are executed first. This process applies to
  2644. all nested `:try`s inside the loop. The outermost
  2645. `:endtry` then jumps back to the start of the loop.
  2646. In |Vim9| script `:cont` is the shortest form, to
  2647. improve script readability.
  2648. *:break* *:brea* *E587*
  2649. :brea[k] When used inside a `:while` or `:for` loop, skips to
  2650. the command after the matching `:endwhile` or
  2651. `:endfor`.
  2652. If it is used after a `:try` inside the loop but
  2653. before the matching `:finally` (if present), the
  2654. commands following the `:finally` up to the matching
  2655. `:endtry` are executed first. This process applies to
  2656. all nested `:try`s inside the loop. The outermost
  2657. `:endtry` then jumps to the command after the loop.
  2658. In |Vim9| script `:break` cannot be shortened, to
  2659. improve script readability.
  2660. :try *:try* *:endt* *:endtry*
  2661. *E600* *E601* *E602* *E1032*
  2662. :endt[ry] Change the error handling for the commands between
  2663. `:try` and `:endtry` including everything being
  2664. executed across `:source` commands, function calls,
  2665. or autocommand invocations.
  2666. When an error or interrupt is detected and there is
  2667. a `:finally` command following, execution continues
  2668. after the `:finally`. Otherwise, or when the
  2669. `:endtry` is reached thereafter, the next
  2670. (dynamically) surrounding `:try` is checked for
  2671. a corresponding `:finally` etc. Then the script
  2672. processing is terminated. Whether a function
  2673. definition has an "abort" argument does not matter.
  2674. Example: >
  2675. try | call Unknown() | finally | echomsg "cleanup" | endtry
  2676. echomsg "not reached"
  2677. <
  2678. Moreover, an error or interrupt (dynamically) inside
  2679. `:try` and `:endtry` is converted to an exception. It
  2680. can be caught as if it were thrown by a `:throw`
  2681. command (see `:catch`). In this case, the script
  2682. processing is not terminated.
  2683. The value "Vim:Interrupt" is used for an interrupt
  2684. exception. An error in a Vim command is converted
  2685. to a value of the form "Vim({command}):{errmsg}",
  2686. other errors are converted to a value of the form
  2687. "Vim:{errmsg}". {command} is the full command name,
  2688. and {errmsg} is the message that is displayed if the
  2689. error exception is not caught, always beginning with
  2690. the error number.
  2691. Examples: >
  2692. try | sleep 100 | catch /^Vim:Interrupt$/ | endtry
  2693. try | edit | catch /^Vim(edit):E\d\+/ | echo "error" | endtry
  2694. <
  2695. In |Vim9| script `:endtry` cannot be shortened, to
  2696. improve script readability.
  2697. *:cat* *:catch*
  2698. *E603* *E604* *E605* *E654* *E1033*
  2699. :cat[ch] /{pattern}/ The following commands until the next `:catch`,
  2700. `:finally`, or `:endtry` that belongs to the same
  2701. `:try` as the `:catch` are executed when an exception
  2702. matching {pattern} is being thrown and has not yet
  2703. been caught by a previous `:catch`. Otherwise, these
  2704. commands are skipped.
  2705. When {pattern} is omitted all errors are caught.
  2706. Examples: >
  2707. :catch /^Vim:Interrupt$/ " catch interrupts (CTRL-C)
  2708. :catch /^Vim\%((\a\+)\)\=:E/ " catch all Vim errors
  2709. :catch /^Vim\%((\a\+)\)\=:/ " catch errors and interrupts
  2710. :catch /^Vim(write):/ " catch all errors in :write
  2711. :catch /^Vim\%((\a\+)\)\=:E123:/ " catch error E123
  2712. :catch /my-exception/ " catch user exception
  2713. :catch /.*/ " catch everything
  2714. :catch " same as /.*/
  2715. <
  2716. Another character can be used instead of / around the
  2717. {pattern}, so long as it does not have a special
  2718. meaning (e.g., '|' or '"') and doesn't occur inside
  2719. {pattern}. *E1067*
  2720. Information about the exception is available in
  2721. |v:exception|. Also see |throw-variables|.
  2722. NOTE: It is not reliable to ":catch" the TEXT of
  2723. an error message because it may vary in different
  2724. locales.
  2725. In |Vim9| script `:catch` cannot be shortened, to
  2726. improve script readability.
  2727. *:fina* *:finally* *E606* *E607*
  2728. :fina[lly] The following commands until the matching `:endtry`
  2729. are executed whenever the part between the matching
  2730. `:try` and the `:finally` is left: either by falling
  2731. through to the `:finally` or by a `:continue`,
  2732. `:break`, `:finish`, or `:return`, or by an error or
  2733. interrupt or exception (see `:throw`).
  2734. In |Vim9| script `:finally` cannot be shortened, to
  2735. improve script readability and avoid confusion with
  2736. `:final`.
  2737. *:th* *:throw* *E608* *E1129*
  2738. :th[row] {expr1} The {expr1} is evaluated and thrown as an exception.
  2739. If the ":throw" is used after a `:try` but before the
  2740. first corresponding `:catch`, commands are skipped
  2741. until the first `:catch` matching {expr1} is reached.
  2742. If there is no such `:catch` or if the ":throw" is
  2743. used after a `:catch` but before the `:finally`, the
  2744. commands following the `:finally` (if present) up to
  2745. the matching `:endtry` are executed. If the `:throw`
  2746. is after the `:finally`, commands up to the `:endtry`
  2747. are skipped. At the ":endtry", this process applies
  2748. again for the next dynamically surrounding `:try`
  2749. (which may be found in a calling function or sourcing
  2750. script), until a matching `:catch` has been found.
  2751. If the exception is not caught, the command processing
  2752. is terminated.
  2753. Example: >
  2754. :try | throw "oops" | catch /^oo/ | echo "caught" | endtry
  2755. < Note that "catch" may need to be on a separate line
  2756. for when an error causes the parsing to skip the whole
  2757. line and not see the "|" that separates the commands.
  2758. In |Vim9| script `:throw` cannot be shortened, to
  2759. improve script readability.
  2760. *:ec* *:echo*
  2761. :ec[ho] {expr1} .. Echoes each {expr1}, with a space in between. The
  2762. first {expr1} starts on a new line.
  2763. Also see |:comment|.
  2764. Use "\n" to start a new line. Use "\r" to move the
  2765. cursor to the first column.
  2766. Uses the highlighting set by the `:echohl` command.
  2767. Cannot be followed by a comment.
  2768. Example: >
  2769. :echo "the value of 'shell' is" &shell
  2770. < *:echo-redraw*
  2771. A later redraw may make the message disappear again.
  2772. And since Vim mostly postpones redrawing until it's
  2773. finished with a sequence of commands this happens
  2774. quite often. To avoid that a command from before the
  2775. `:echo` causes a redraw afterwards (redraws are often
  2776. postponed until you type something), force a redraw
  2777. with the `:redraw` command. Example: >
  2778. :new | redraw | echo "there is a new window"
  2779. <
  2780. *:echon*
  2781. :echon {expr1} .. Echoes each {expr1}, without anything added. Also see
  2782. |:comment|.
  2783. Uses the highlighting set by the `:echohl` command.
  2784. Cannot be followed by a comment.
  2785. Example: >
  2786. :echon "the value of 'shell' is " &shell
  2787. <
  2788. Note the difference between using `:echo`, which is a
  2789. Vim command, and `:!echo`, which is an external shell
  2790. command: >
  2791. :!echo % --> filename
  2792. < The arguments of ":!" are expanded, see |:_%|. >
  2793. :!echo "%" --> filename or "filename"
  2794. < Like the previous example. Whether you see the double
  2795. quotes or not depends on your 'shell'. >
  2796. :echo % --> nothing
  2797. < The '%' is an illegal character in an expression. >
  2798. :echo "%" --> %
  2799. < This just echoes the '%' character. >
  2800. :echo expand("%") --> filename
  2801. < This calls the expand() function to expand the '%'.
  2802. *:echoh* *:echohl*
  2803. :echoh[l] {name} Use the highlight group {name} for the following
  2804. `:echo`, `:echon` and `:echomsg` commands. Also used
  2805. for the `input()` prompt. Example: >
  2806. :echohl WarningMsg | echo "Don't panic!" | echohl None
  2807. < Don't forget to set the group back to "None",
  2808. otherwise all following echo's will be highlighted.
  2809. *:echom* *:echomsg*
  2810. :echom[sg] {expr1} .. Echo the expression(s) as a true message, saving the
  2811. message in the |message-history|.
  2812. Spaces are placed between the arguments as with the
  2813. `:echo` command. But unprintable characters are
  2814. displayed, not interpreted.
  2815. The parsing works slightly different from `:echo`,
  2816. more like `:execute`. All the expressions are first
  2817. evaluated and concatenated before echoing anything.
  2818. If expressions does not evaluate to a Number or
  2819. String, string() is used to turn it into a string.
  2820. Uses the highlighting set by the `:echohl` command.
  2821. Example: >
  2822. :echomsg "It's a Zizzer Zazzer Zuzz, as you can plainly see."
  2823. < See |:echo-redraw| to avoid the message disappearing
  2824. when the screen is redrawn.
  2825. *:echow* *:echowin* *:echowindow*
  2826. :[N]echow[indow] {expr1} ..
  2827. Like |:echomsg| but when the messages popup window is
  2828. available the message is displayed there. This means
  2829. it will show for three seconds and avoid a
  2830. |hit-enter| prompt. If you want to hide it before
  2831. that, press Esc in Normal mode (when it would
  2832. otherwise beep). If it disappears too soon you can
  2833. use `:messages` to see the text.
  2834. When [N] is given then the window will show up for
  2835. this number of seconds. The last `:echowindow` with a
  2836. count matters, it is used once only.
  2837. The message window is available when Vim was compiled
  2838. with the +timer and the +popupwin features.
  2839. *:echoe* *:echoerr*
  2840. :echoe[rr] {expr1} .. Echo the expression(s) as an error message, saving the
  2841. message in the |message-history|. When used in a
  2842. script or function the line number will be added.
  2843. Spaces are placed between the arguments as with the
  2844. `:echomsg` command. When used inside a try conditional,
  2845. the message is raised as an error exception instead
  2846. (see |try-echoerr|).
  2847. Example: >
  2848. :echoerr "This script just failed!"
  2849. < If you just want a highlighted message use `:echohl`.
  2850. And to get a beep: >
  2851. :exe "normal \<Esc>"
  2852. :echoc[onsole] {expr1} .. *:echoc* *:echoconsole*
  2853. Intended for testing: works like `:echomsg` but when
  2854. running in the GUI and started from a terminal write
  2855. the text to stdout.
  2856. *:eval*
  2857. :eval {expr} Evaluate {expr} and discard the result. Example: >
  2858. :eval Getlist()->Filter()->append('$')
  2859. < The expression is supposed to have a side effect,
  2860. since the resulting value is not used. In the example
  2861. the `append()` call appends the List with text to the
  2862. buffer. This is similar to `:call` but works with any
  2863. expression.
  2864. In |Vim9| script an expression without an effect will
  2865. result in error *E1207* . This should help noticing
  2866. mistakes.
  2867. The command can be shortened to `:ev` or `:eva`, but
  2868. these are hard to recognize and therefore not to be
  2869. used.
  2870. The command cannot be followed by "|" and another
  2871. command, since "|" is seen as part of the expression.
  2872. *:exe* *:execute*
  2873. :exe[cute] {expr1} .. Executes the string that results from the evaluation
  2874. of {expr1} as an Ex command.
  2875. Multiple arguments are concatenated, with a space in
  2876. between. To avoid the extra space use the ".."
  2877. operator to concatenate strings into one argument.
  2878. {expr1} is used as the processed command, command line
  2879. editing keys are not recognized.
  2880. Cannot be followed by a comment.
  2881. Examples: >
  2882. :execute "buffer" nextbuf
  2883. :execute "normal" count .. "w"
  2884. <
  2885. ":execute" can be used to append a command to commands
  2886. that don't accept a '|'. Example: >
  2887. :execute '!ls' | echo "theend"
  2888. < ":execute" is also a nice way to avoid having to type
  2889. control characters in a Vim script for a ":normal"
  2890. command: >
  2891. :execute "normal ixxx\<Esc>"
  2892. < This has an <Esc> character, see |expr-string|.
  2893. Be careful to correctly escape special characters in
  2894. file names. The |fnameescape()| function can be used
  2895. for Vim commands, |shellescape()| for |:!| commands.
  2896. Examples: >
  2897. :execute "e " .. fnameescape(filename)
  2898. :execute "!ls " .. shellescape(filename, 1)
  2899. <
  2900. Note: The executed string may be any command-line, but
  2901. starting or ending "if", "while" and "for" does not
  2902. always work, because when commands are skipped the
  2903. ":execute" is not evaluated and Vim loses track of
  2904. where blocks start and end. Also "break" and
  2905. "continue" should not be inside ":execute".
  2906. This example does not work, because the ":execute" is
  2907. not evaluated and Vim does not see the "while", and
  2908. gives an error for finding an ":endwhile": >
  2909. :if 0
  2910. : execute 'while i > 5'
  2911. : echo "test"
  2912. : endwhile
  2913. :endif
  2914. <
  2915. It is allowed to have a "while" or "if" command
  2916. completely in the executed string: >
  2917. :execute 'while i < 5 | echo i | let i = i + 1 | endwhile'
  2918. <
  2919. *:exe-comment*
  2920. ":execute", ":echo" and ":echon" cannot be followed by
  2921. a comment directly, because they see the '"' as the
  2922. start of a string. But, you can use '|' followed by a
  2923. comment. Example: >
  2924. :echo "foo" | "this is a comment
  2925. ==============================================================================
  2926. 8. Exception handling *exception-handling*
  2927. The Vim script language comprises an exception handling feature. This section
  2928. explains how it can be used in a Vim script.
  2929. Exceptions may be raised by Vim on an error or on interrupt, see
  2930. |catch-errors| and |catch-interrupt|. You can also explicitly throw an
  2931. exception by using the ":throw" command, see |throw-catch|.
  2932. TRY CONDITIONALS *try-conditionals*
  2933. Exceptions can be caught or can cause cleanup code to be executed. You can
  2934. use a try conditional to specify catch clauses (that catch exceptions) and/or
  2935. a finally clause (to be executed for cleanup).
  2936. A try conditional begins with a |:try| command and ends at the matching
  2937. |:endtry| command. In between, you can use a |:catch| command to start
  2938. a catch clause, or a |:finally| command to start a finally clause. There may
  2939. be none or multiple catch clauses, but there is at most one finally clause,
  2940. which must not be followed by any catch clauses. The lines before the catch
  2941. clauses and the finally clause is called a try block. >
  2942. :try
  2943. : ...
  2944. : ... TRY BLOCK
  2945. : ...
  2946. :catch /{pattern}/
  2947. : ...
  2948. : ... CATCH CLAUSE
  2949. : ...
  2950. :catch /{pattern}/
  2951. : ...
  2952. : ... CATCH CLAUSE
  2953. : ...
  2954. :finally
  2955. : ...
  2956. : ... FINALLY CLAUSE
  2957. : ...
  2958. :endtry
  2959. The try conditional allows to watch code for exceptions and to take the
  2960. appropriate actions. Exceptions from the try block may be caught. Exceptions
  2961. from the try block and also the catch clauses may cause cleanup actions.
  2962. When no exception is thrown during execution of the try block, the control
  2963. is transferred to the finally clause, if present. After its execution, the
  2964. script continues with the line following the ":endtry".
  2965. When an exception occurs during execution of the try block, the remaining
  2966. lines in the try block are skipped. The exception is matched against the
  2967. patterns specified as arguments to the ":catch" commands. The catch clause
  2968. after the first matching ":catch" is taken, other catch clauses are not
  2969. executed. The catch clause ends when the next ":catch", ":finally", or
  2970. ":endtry" command is reached - whatever is first. Then, the finally clause
  2971. (if present) is executed. When the ":endtry" is reached, the script execution
  2972. continues in the following line as usual.
  2973. When an exception that does not match any of the patterns specified by the
  2974. ":catch" commands is thrown in the try block, the exception is not caught by
  2975. that try conditional and none of the catch clauses is executed. Only the
  2976. finally clause, if present, is taken. The exception pends during execution of
  2977. the finally clause. It is resumed at the ":endtry", so that commands after
  2978. the ":endtry" are not executed and the exception might be caught elsewhere,
  2979. see |try-nesting|.
  2980. When during execution of a catch clause another exception is thrown, the
  2981. remaining lines in that catch clause are not executed. The new exception is
  2982. not matched against the patterns in any of the ":catch" commands of the same
  2983. try conditional and none of its catch clauses is taken. If there is, however,
  2984. a finally clause, it is executed, and the exception pends during its
  2985. execution. The commands following the ":endtry" are not executed. The new
  2986. exception might, however, be caught elsewhere, see |try-nesting|.
  2987. When during execution of the finally clause (if present) an exception is
  2988. thrown, the remaining lines in the finally clause are skipped. If the finally
  2989. clause has been taken because of an exception from the try block or one of the
  2990. catch clauses, the original (pending) exception is discarded. The commands
  2991. following the ":endtry" are not executed, and the exception from the finally
  2992. clause is propagated and can be caught elsewhere, see |try-nesting|.
  2993. The finally clause is also executed, when a ":break" or ":continue" for
  2994. a ":while" loop enclosing the complete try conditional is executed from the
  2995. try block or a catch clause. Or when a ":return" or ":finish" is executed
  2996. from the try block or a catch clause of a try conditional in a function or
  2997. sourced script, respectively. The ":break", ":continue", ":return", or
  2998. ":finish" pends during execution of the finally clause and is resumed when the
  2999. ":endtry" is reached. It is, however, discarded when an exception is thrown
  3000. from the finally clause.
  3001. When a ":break" or ":continue" for a ":while" loop enclosing the complete
  3002. try conditional or when a ":return" or ":finish" is encountered in the finally
  3003. clause, the rest of the finally clause is skipped, and the ":break",
  3004. ":continue", ":return" or ":finish" is executed as usual. If the finally
  3005. clause has been taken because of an exception or an earlier ":break",
  3006. ":continue", ":return", or ":finish" from the try block or a catch clause,
  3007. this pending exception or command is discarded.
  3008. For examples see |throw-catch| and |try-finally|.
  3009. NESTING OF TRY CONDITIONALS *try-nesting*
  3010. Try conditionals can be nested arbitrarily. That is, a complete try
  3011. conditional can be put into the try block, a catch clause, or the finally
  3012. clause of another try conditional. If the inner try conditional does not
  3013. catch an exception thrown in its try block or throws a new exception from one
  3014. of its catch clauses or its finally clause, the outer try conditional is
  3015. checked according to the rules above. If the inner try conditional is in the
  3016. try block of the outer try conditional, its catch clauses are checked, but
  3017. otherwise only the finally clause is executed. It does not matter for
  3018. nesting, whether the inner try conditional is directly contained in the outer
  3019. one, or whether the outer one sources a script or calls a function containing
  3020. the inner try conditional.
  3021. When none of the active try conditionals catches an exception, just their
  3022. finally clauses are executed. Thereafter, the script processing terminates.
  3023. An error message is displayed in case of an uncaught exception explicitly
  3024. thrown by a ":throw" command. For uncaught error and interrupt exceptions
  3025. implicitly raised by Vim, the error message(s) or interrupt message are shown
  3026. as usual.
  3027. For examples see |throw-catch|.
  3028. EXAMINING EXCEPTION HANDLING CODE *except-examine*
  3029. Exception handling code can get tricky. If you are in doubt what happens, set
  3030. 'verbose' to 13 or use the ":13verbose" command modifier when sourcing your
  3031. script file. Then you see when an exception is thrown, discarded, caught, or
  3032. finished. When using a verbosity level of at least 14, things pending in
  3033. a finally clause are also shown. This information is also given in debug mode
  3034. (see |debug-scripts|).
  3035. THROWING AND CATCHING EXCEPTIONS *throw-catch*
  3036. You can throw any number or string as an exception. Use the |:throw| command
  3037. and pass the value to be thrown as argument: >
  3038. :throw 4711
  3039. :throw "string"
  3040. < *throw-expression*
  3041. You can also specify an expression argument. The expression is then evaluated
  3042. first, and the result is thrown: >
  3043. :throw 4705 + strlen("string")
  3044. :throw strpart("strings", 0, 6)
  3045. An exception might be thrown during evaluation of the argument of the ":throw"
  3046. command. Unless it is caught there, the expression evaluation is abandoned.
  3047. The ":throw" command then does not throw a new exception.
  3048. Example: >
  3049. :function! Foo(arg)
  3050. : try
  3051. : throw a:arg
  3052. : catch /foo/
  3053. : endtry
  3054. : return 1
  3055. :endfunction
  3056. :
  3057. :function! Bar()
  3058. : echo "in Bar"
  3059. : return 4710
  3060. :endfunction
  3061. :
  3062. :throw Foo("arrgh") + Bar()
  3063. This throws "arrgh", and "in Bar" is not displayed since Bar() is not
  3064. executed. >
  3065. :throw Foo("foo") + Bar()
  3066. however displays "in Bar" and throws 4711.
  3067. Any other command that takes an expression as argument might also be
  3068. abandoned by an (uncaught) exception during the expression evaluation. The
  3069. exception is then propagated to the caller of the command.
  3070. Example: >
  3071. :if Foo("arrgh")
  3072. : echo "then"
  3073. :else
  3074. : echo "else"
  3075. :endif
  3076. Here neither of "then" or "else" is displayed.
  3077. *catch-order*
  3078. Exceptions can be caught by a try conditional with one or more |:catch|
  3079. commands, see |try-conditionals|. The values to be caught by each ":catch"
  3080. command can be specified as a pattern argument. The subsequent catch clause
  3081. gets executed when a matching exception is caught.
  3082. Example: >
  3083. :function! Foo(value)
  3084. : try
  3085. : throw a:value
  3086. : catch /^\d\+$/
  3087. : echo "Number thrown"
  3088. : catch /.*/
  3089. : echo "String thrown"
  3090. : endtry
  3091. :endfunction
  3092. :
  3093. :call Foo(0x1267)
  3094. :call Foo('string')
  3095. The first call to Foo() displays "Number thrown", the second "String thrown".
  3096. An exception is matched against the ":catch" commands in the order they are
  3097. specified. Only the first match counts. So you should place the more
  3098. specific ":catch" first. The following order does not make sense: >
  3099. : catch /.*/
  3100. : echo "String thrown"
  3101. : catch /^\d\+$/
  3102. : echo "Number thrown"
  3103. The first ":catch" here matches always, so that the second catch clause is
  3104. never taken.
  3105. *throw-variables*
  3106. If you catch an exception by a general pattern, you may access the exact value
  3107. in the variable |v:exception|: >
  3108. : catch /^\d\+$/
  3109. : echo "Number thrown. Value is" v:exception
  3110. You may also be interested where an exception was thrown. This is stored in
  3111. |v:throwpoint|. Note that "v:exception" and "v:throwpoint" are valid for the
  3112. exception most recently caught as long it is not finished.
  3113. Example: >
  3114. :function! Caught()
  3115. : if v:exception != ""
  3116. : echo 'Caught "' . v:exception .. '" in ' .. v:throwpoint
  3117. : else
  3118. : echo 'Nothing caught'
  3119. : endif
  3120. :endfunction
  3121. :
  3122. :function! Foo()
  3123. : try
  3124. : try
  3125. : try
  3126. : throw 4711
  3127. : finally
  3128. : call Caught()
  3129. : endtry
  3130. : catch /.*/
  3131. : call Caught()
  3132. : throw "oops"
  3133. : endtry
  3134. : catch /.*/
  3135. : call Caught()
  3136. : finally
  3137. : call Caught()
  3138. : endtry
  3139. :endfunction
  3140. :
  3141. :call Foo()
  3142. This displays >
  3143. Nothing caught
  3144. Caught "4711" in function Foo, line 4
  3145. Caught "oops" in function Foo, line 10
  3146. Nothing caught
  3147. A practical example: The following command ":LineNumber" displays the line
  3148. number in the script or function where it has been used: >
  3149. :function! LineNumber()
  3150. : return substitute(v:throwpoint, '.*\D\(\d\+\).*', '\1', "")
  3151. :endfunction
  3152. :command! LineNumber try | throw "" | catch | echo LineNumber() | endtry
  3153. <
  3154. *try-nested*
  3155. An exception that is not caught by a try conditional can be caught by
  3156. a surrounding try conditional: >
  3157. :try
  3158. : try
  3159. : throw "foo"
  3160. : catch /foobar/
  3161. : echo "foobar"
  3162. : finally
  3163. : echo "inner finally"
  3164. : endtry
  3165. :catch /foo/
  3166. : echo "foo"
  3167. :endtry
  3168. The inner try conditional does not catch the exception, just its finally
  3169. clause is executed. The exception is then caught by the outer try
  3170. conditional. The example displays "inner finally" and then "foo".
  3171. *throw-from-catch*
  3172. You can catch an exception and throw a new one to be caught elsewhere from the
  3173. catch clause: >
  3174. :function! Foo()
  3175. : throw "foo"
  3176. :endfunction
  3177. :
  3178. :function! Bar()
  3179. : try
  3180. : call Foo()
  3181. : catch /foo/
  3182. : echo "Caught foo, throw bar"
  3183. : throw "bar"
  3184. : endtry
  3185. :endfunction
  3186. :
  3187. :try
  3188. : call Bar()
  3189. :catch /.*/
  3190. : echo "Caught" v:exception
  3191. :endtry
  3192. This displays "Caught foo, throw bar" and then "Caught bar".
  3193. *rethrow*
  3194. There is no real rethrow in the Vim script language, but you may throw
  3195. "v:exception" instead: >
  3196. :function! Bar()
  3197. : try
  3198. : call Foo()
  3199. : catch /.*/
  3200. : echo "Rethrow" v:exception
  3201. : throw v:exception
  3202. : endtry
  3203. :endfunction
  3204. < *try-echoerr*
  3205. Note that this method cannot be used to "rethrow" Vim error or interrupt
  3206. exceptions, because it is not possible to fake Vim internal exceptions.
  3207. Trying so causes an error exception. You should throw your own exception
  3208. denoting the situation. If you want to cause a Vim error exception containing
  3209. the original error exception value, you can use the |:echoerr| command: >
  3210. :try
  3211. : try
  3212. : asdf
  3213. : catch /.*/
  3214. : echoerr v:exception
  3215. : endtry
  3216. :catch /.*/
  3217. : echo v:exception
  3218. :endtry
  3219. This code displays
  3220. Vim(echoerr):Vim:E492: Not an editor command: asdf ~
  3221. CLEANUP CODE *try-finally*
  3222. Scripts often change global settings and restore them at their end. If the
  3223. user however interrupts the script by pressing CTRL-C, the settings remain in
  3224. an inconsistent state. The same may happen to you in the development phase of
  3225. a script when an error occurs or you explicitly throw an exception without
  3226. catching it. You can solve these problems by using a try conditional with
  3227. a finally clause for restoring the settings. Its execution is guaranteed on
  3228. normal control flow, on error, on an explicit ":throw", and on interrupt.
  3229. (Note that errors and interrupts from inside the try conditional are converted
  3230. to exceptions. When not caught, they terminate the script after the finally
  3231. clause has been executed.)
  3232. Example: >
  3233. :try
  3234. : let s:saved_ts = &ts
  3235. : set ts=17
  3236. :
  3237. : " Do the hard work here.
  3238. :
  3239. :finally
  3240. : let &ts = s:saved_ts
  3241. : unlet s:saved_ts
  3242. :endtry
  3243. This method should be used locally whenever a function or part of a script
  3244. changes global settings which need to be restored on failure or normal exit of
  3245. that function or script part.
  3246. *break-finally*
  3247. Cleanup code works also when the try block or a catch clause is left by
  3248. a ":continue", ":break", ":return", or ":finish".
  3249. Example: >
  3250. :let first = 1
  3251. :while 1
  3252. : try
  3253. : if first
  3254. : echo "first"
  3255. : let first = 0
  3256. : continue
  3257. : else
  3258. : throw "second"
  3259. : endif
  3260. : catch /.*/
  3261. : echo v:exception
  3262. : break
  3263. : finally
  3264. : echo "cleanup"
  3265. : endtry
  3266. : echo "still in while"
  3267. :endwhile
  3268. :echo "end"
  3269. This displays "first", "cleanup", "second", "cleanup", and "end". >
  3270. :function! Foo()
  3271. : try
  3272. : return 4711
  3273. : finally
  3274. : echo "cleanup\n"
  3275. : endtry
  3276. : echo "Foo still active"
  3277. :endfunction
  3278. :
  3279. :echo Foo() "returned by Foo"
  3280. This displays "cleanup" and "4711 returned by Foo". You don't need to add an
  3281. extra ":return" in the finally clause. (Above all, this would override the
  3282. return value.)
  3283. *except-from-finally*
  3284. Using either of ":continue", ":break", ":return", ":finish", or ":throw" in
  3285. a finally clause is possible, but not recommended since it abandons the
  3286. cleanup actions for the try conditional. But, of course, interrupt and error
  3287. exceptions might get raised from a finally clause.
  3288. Example where an error in the finally clause stops an interrupt from
  3289. working correctly: >
  3290. :try
  3291. : try
  3292. : echo "Press CTRL-C for interrupt"
  3293. : while 1
  3294. : endwhile
  3295. : finally
  3296. : unlet novar
  3297. : endtry
  3298. :catch /novar/
  3299. :endtry
  3300. :echo "Script still running"
  3301. :sleep 1
  3302. If you need to put commands that could fail into a finally clause, you should
  3303. think about catching or ignoring the errors in these commands, see
  3304. |catch-errors| and |ignore-errors|.
  3305. CATCHING ERRORS *catch-errors*
  3306. If you want to catch specific errors, you just have to put the code to be
  3307. watched in a try block and add a catch clause for the error message. The
  3308. presence of the try conditional causes all errors to be converted to an
  3309. exception. No message is displayed and |v:errmsg| is not set then. To find
  3310. the right pattern for the ":catch" command, you have to know how the format of
  3311. the error exception is.
  3312. Error exceptions have the following format: >
  3313. Vim({cmdname}):{errmsg}
  3314. or >
  3315. Vim:{errmsg}
  3316. {cmdname} is the name of the command that failed; the second form is used when
  3317. the command name is not known. {errmsg} is the error message usually produced
  3318. when the error occurs outside try conditionals. It always begins with
  3319. a capital "E", followed by a two or three-digit error number, a colon, and
  3320. a space.
  3321. Examples:
  3322. The command >
  3323. :unlet novar
  3324. normally produces the error message >
  3325. E108: No such variable: "novar"
  3326. which is converted inside try conditionals to an exception >
  3327. Vim(unlet):E108: No such variable: "novar"
  3328. The command >
  3329. :dwim
  3330. normally produces the error message >
  3331. E492: Not an editor command: dwim
  3332. which is converted inside try conditionals to an exception >
  3333. Vim:E492: Not an editor command: dwim
  3334. You can catch all ":unlet" errors by a >
  3335. :catch /^Vim(unlet):/
  3336. or all errors for misspelled command names by a >
  3337. :catch /^Vim:E492:/
  3338. Some error messages may be produced by different commands: >
  3339. :function nofunc
  3340. and >
  3341. :delfunction nofunc
  3342. both produce the error message >
  3343. E128: Function name must start with a capital: nofunc
  3344. which is converted inside try conditionals to an exception >
  3345. Vim(function):E128: Function name must start with a capital: nofunc
  3346. or >
  3347. Vim(delfunction):E128: Function name must start with a capital: nofunc
  3348. respectively. You can catch the error by its number independently on the
  3349. command that caused it if you use the following pattern: >
  3350. :catch /^Vim(\a\+):E128:/
  3351. Some commands like >
  3352. :let x = novar
  3353. produce multiple error messages, here: >
  3354. E121: Undefined variable: novar
  3355. E15: Invalid expression: novar
  3356. Only the first is used for the exception value, since it is the most specific
  3357. one (see |except-several-errors|). So you can catch it by >
  3358. :catch /^Vim(\a\+):E121:/
  3359. You can catch all errors related to the name "nofunc" by >
  3360. :catch /\<nofunc\>/
  3361. You can catch all Vim errors in the ":write" and ":read" commands by >
  3362. :catch /^Vim(\(write\|read\)):E\d\+:/
  3363. You can catch all Vim errors by the pattern >
  3364. :catch /^Vim\((\a\+)\)\=:E\d\+:/
  3365. <
  3366. *catch-text*
  3367. NOTE: You should never catch the error message text itself: >
  3368. :catch /No such variable/
  3369. only works in the English locale, but not when the user has selected
  3370. a different language by the |:language| command. It is however helpful to
  3371. cite the message text in a comment: >
  3372. :catch /^Vim(\a\+):E108:/ " No such variable
  3373. IGNORING ERRORS *ignore-errors*
  3374. You can ignore errors in a specific Vim command by catching them locally: >
  3375. :try
  3376. : write
  3377. :catch
  3378. :endtry
  3379. But you are strongly recommended NOT to use this simple form, since it could
  3380. catch more than you want. With the ":write" command, some autocommands could
  3381. be executed and cause errors not related to writing, for instance: >
  3382. :au BufWritePre * unlet novar
  3383. There could even be such errors you are not responsible for as a script
  3384. writer: a user of your script might have defined such autocommands. You would
  3385. then hide the error from the user.
  3386. It is much better to use >
  3387. :try
  3388. : write
  3389. :catch /^Vim(write):/
  3390. :endtry
  3391. which only catches real write errors. So catch only what you'd like to ignore
  3392. intentionally.
  3393. For a single command that does not cause execution of autocommands, you could
  3394. even suppress the conversion of errors to exceptions by the ":silent!"
  3395. command: >
  3396. :silent! nunmap k
  3397. This works also when a try conditional is active.
  3398. CATCHING INTERRUPTS *catch-interrupt*
  3399. When there are active try conditionals, an interrupt (CTRL-C) is converted to
  3400. the exception "Vim:Interrupt". You can catch it like every exception. The
  3401. script is not terminated, then.
  3402. Example: >
  3403. :function! TASK1()
  3404. : sleep 10
  3405. :endfunction
  3406. :function! TASK2()
  3407. : sleep 20
  3408. :endfunction
  3409. :while 1
  3410. : let command = input("Type a command: ")
  3411. : try
  3412. : if command == ""
  3413. : continue
  3414. : elseif command == "END"
  3415. : break
  3416. : elseif command == "TASK1"
  3417. : call TASK1()
  3418. : elseif command == "TASK2"
  3419. : call TASK2()
  3420. : else
  3421. : echo "\nIllegal command:" command
  3422. : continue
  3423. : endif
  3424. : catch /^Vim:Interrupt$/
  3425. : echo "\nCommand interrupted"
  3426. : " Caught the interrupt. Continue with next prompt.
  3427. : endtry
  3428. :endwhile
  3429. You can interrupt a task here by pressing CTRL-C; the script then asks for
  3430. a new command. If you press CTRL-C at the prompt, the script is terminated.
  3431. For testing what happens when CTRL-C would be pressed on a specific line in
  3432. your script, use the debug mode and execute the |>quit| or |>interrupt|
  3433. command on that line. See |debug-scripts|.
  3434. CATCHING ALL *catch-all*
  3435. The commands >
  3436. :catch /.*/
  3437. :catch //
  3438. :catch
  3439. catch everything, error exceptions, interrupt exceptions and exceptions
  3440. explicitly thrown by the |:throw| command. This is useful at the top level of
  3441. a script in order to catch unexpected things.
  3442. Example: >
  3443. :try
  3444. :
  3445. : " do the hard work here
  3446. :
  3447. :catch /MyException/
  3448. :
  3449. : " handle known problem
  3450. :
  3451. :catch /^Vim:Interrupt$/
  3452. : echo "Script interrupted"
  3453. :catch /.*/
  3454. : echo "Internal error (" .. v:exception .. ")"
  3455. : echo " - occurred at " .. v:throwpoint
  3456. :endtry
  3457. :" end of script
  3458. Note: Catching all might catch more things than you want. Thus, you are
  3459. strongly encouraged to catch only for problems that you can really handle by
  3460. specifying a pattern argument to the ":catch".
  3461. Example: Catching all could make it nearly impossible to interrupt a script
  3462. by pressing CTRL-C: >
  3463. :while 1
  3464. : try
  3465. : sleep 1
  3466. : catch
  3467. : endtry
  3468. :endwhile
  3469. EXCEPTIONS AND AUTOCOMMANDS *except-autocmd*
  3470. Exceptions may be used during execution of autocommands. Example: >
  3471. :autocmd User x try
  3472. :autocmd User x throw "Oops!"
  3473. :autocmd User x catch
  3474. :autocmd User x echo v:exception
  3475. :autocmd User x endtry
  3476. :autocmd User x throw "Arrgh!"
  3477. :autocmd User x echo "Should not be displayed"
  3478. :
  3479. :try
  3480. : doautocmd User x
  3481. :catch
  3482. : echo v:exception
  3483. :endtry
  3484. This displays "Oops!" and "Arrgh!".
  3485. *except-autocmd-Pre*
  3486. For some commands, autocommands get executed before the main action of the
  3487. command takes place. If an exception is thrown and not caught in the sequence
  3488. of autocommands, the sequence and the command that caused its execution are
  3489. abandoned and the exception is propagated to the caller of the command.
  3490. Example: >
  3491. :autocmd BufWritePre * throw "FAIL"
  3492. :autocmd BufWritePre * echo "Should not be displayed"
  3493. :
  3494. :try
  3495. : write
  3496. :catch
  3497. : echo "Caught:" v:exception "from" v:throwpoint
  3498. :endtry
  3499. Here, the ":write" command does not write the file currently being edited (as
  3500. you can see by checking 'modified'), since the exception from the BufWritePre
  3501. autocommand abandons the ":write". The exception is then caught and the
  3502. script displays: >
  3503. Caught: FAIL from BufWrite Auto commands for "*"
  3504. <
  3505. *except-autocmd-Post*
  3506. For some commands, autocommands get executed after the main action of the
  3507. command has taken place. If this main action fails and the command is inside
  3508. an active try conditional, the autocommands are skipped and an error exception
  3509. is thrown that can be caught by the caller of the command.
  3510. Example: >
  3511. :autocmd BufWritePost * echo "File successfully written!"
  3512. :
  3513. :try
  3514. : write /i/m/p/o/s/s/i/b/l/e
  3515. :catch
  3516. : echo v:exception
  3517. :endtry
  3518. This just displays: >
  3519. Vim(write):E212: Can't open file for writing (/i/m/p/o/s/s/i/b/l/e)
  3520. If you really need to execute the autocommands even when the main action
  3521. fails, trigger the event from the catch clause.
  3522. Example: >
  3523. :autocmd BufWritePre * set noreadonly
  3524. :autocmd BufWritePost * set readonly
  3525. :
  3526. :try
  3527. : write /i/m/p/o/s/s/i/b/l/e
  3528. :catch
  3529. : doautocmd BufWritePost /i/m/p/o/s/s/i/b/l/e
  3530. :endtry
  3531. <
  3532. You can also use ":silent!": >
  3533. :let x = "ok"
  3534. :let v:errmsg = ""
  3535. :autocmd BufWritePost * if v:errmsg != ""
  3536. :autocmd BufWritePost * let x = "after fail"
  3537. :autocmd BufWritePost * endif
  3538. :try
  3539. : silent! write /i/m/p/o/s/s/i/b/l/e
  3540. :catch
  3541. :endtry
  3542. :echo x
  3543. This displays "after fail".
  3544. If the main action of the command does not fail, exceptions from the
  3545. autocommands will be catchable by the caller of the command: >
  3546. :autocmd BufWritePost * throw ":-("
  3547. :autocmd BufWritePost * echo "Should not be displayed"
  3548. :
  3549. :try
  3550. : write
  3551. :catch
  3552. : echo v:exception
  3553. :endtry
  3554. <
  3555. *except-autocmd-Cmd*
  3556. For some commands, the normal action can be replaced by a sequence of
  3557. autocommands. Exceptions from that sequence will be catchable by the caller
  3558. of the command.
  3559. Example: For the ":write" command, the caller cannot know whether the file
  3560. had actually been written when the exception occurred. You need to tell it in
  3561. some way. >
  3562. :if !exists("cnt")
  3563. : let cnt = 0
  3564. :
  3565. : autocmd BufWriteCmd * if &modified
  3566. : autocmd BufWriteCmd * let cnt = cnt + 1
  3567. : autocmd BufWriteCmd * if cnt % 3 == 2
  3568. : autocmd BufWriteCmd * throw "BufWriteCmdError"
  3569. : autocmd BufWriteCmd * endif
  3570. : autocmd BufWriteCmd * write | set nomodified
  3571. : autocmd BufWriteCmd * if cnt % 3 == 0
  3572. : autocmd BufWriteCmd * throw "BufWriteCmdError"
  3573. : autocmd BufWriteCmd * endif
  3574. : autocmd BufWriteCmd * echo "File successfully written!"
  3575. : autocmd BufWriteCmd * endif
  3576. :endif
  3577. :
  3578. :try
  3579. : write
  3580. :catch /^BufWriteCmdError$/
  3581. : if &modified
  3582. : echo "Error on writing (file contents not changed)"
  3583. : else
  3584. : echo "Error after writing"
  3585. : endif
  3586. :catch /^Vim(write):/
  3587. : echo "Error on writing"
  3588. :endtry
  3589. When this script is sourced several times after making changes, it displays
  3590. first >
  3591. File successfully written!
  3592. then >
  3593. Error on writing (file contents not changed)
  3594. then >
  3595. Error after writing
  3596. etc.
  3597. *except-autocmd-ill*
  3598. You cannot spread a try conditional over autocommands for different events.
  3599. The following code is ill-formed: >
  3600. :autocmd BufWritePre * try
  3601. :
  3602. :autocmd BufWritePost * catch
  3603. :autocmd BufWritePost * echo v:exception
  3604. :autocmd BufWritePost * endtry
  3605. :
  3606. :write
  3607. EXCEPTION HIERARCHIES AND PARAMETERIZED EXCEPTIONS *except-hier-param*
  3608. Some programming languages allow to use hierarchies of exception classes or to
  3609. pass additional information with the object of an exception class. You can do
  3610. similar things in Vim.
  3611. In order to throw an exception from a hierarchy, just throw the complete
  3612. class name with the components separated by a colon, for instance throw the
  3613. string "EXCEPT:MATHERR:OVERFLOW" for an overflow in a mathematical library.
  3614. When you want to pass additional information with your exception class, add
  3615. it in parentheses, for instance throw the string "EXCEPT:IO:WRITEERR(myfile)"
  3616. for an error when writing "myfile".
  3617. With the appropriate patterns in the ":catch" command, you can catch for
  3618. base classes or derived classes of your hierarchy. Additional information in
  3619. parentheses can be cut out from |v:exception| with the ":substitute" command.
  3620. Example: >
  3621. :function! CheckRange(a, func)
  3622. : if a:a < 0
  3623. : throw "EXCEPT:MATHERR:RANGE(" .. a:func .. ")"
  3624. : endif
  3625. :endfunction
  3626. :
  3627. :function! Add(a, b)
  3628. : call CheckRange(a:a, "Add")
  3629. : call CheckRange(a:b, "Add")
  3630. : let c = a:a + a:b
  3631. : if c < 0
  3632. : throw "EXCEPT:MATHERR:OVERFLOW"
  3633. : endif
  3634. : return c
  3635. :endfunction
  3636. :
  3637. :function! Div(a, b)
  3638. : call CheckRange(a:a, "Div")
  3639. : call CheckRange(a:b, "Div")
  3640. : if (a:b == 0)
  3641. : throw "EXCEPT:MATHERR:ZERODIV"
  3642. : endif
  3643. : return a:a / a:b
  3644. :endfunction
  3645. :
  3646. :function! Write(file)
  3647. : try
  3648. : execute "write" fnameescape(a:file)
  3649. : catch /^Vim(write):/
  3650. : throw "EXCEPT:IO(" .. getcwd() .. ", " .. a:file .. "):WRITEERR"
  3651. : endtry
  3652. :endfunction
  3653. :
  3654. :try
  3655. :
  3656. : " something with arithmetic and I/O
  3657. :
  3658. :catch /^EXCEPT:MATHERR:RANGE/
  3659. : let function = substitute(v:exception, '.*(\(\a\+\)).*', '\1', "")
  3660. : echo "Range error in" function
  3661. :
  3662. :catch /^EXCEPT:MATHERR/ " catches OVERFLOW and ZERODIV
  3663. : echo "Math error"
  3664. :
  3665. :catch /^EXCEPT:IO/
  3666. : let dir = substitute(v:exception, '.*(\(.\+\),\s*.\+).*', '\1', "")
  3667. : let file = substitute(v:exception, '.*(.\+,\s*\(.\+\)).*', '\1', "")
  3668. : if file !~ '^/'
  3669. : let file = dir .. "/" .. file
  3670. : endif
  3671. : echo 'I/O error for "' .. file .. '"'
  3672. :
  3673. :catch /^EXCEPT/
  3674. : echo "Unspecified error"
  3675. :
  3676. :endtry
  3677. The exceptions raised by Vim itself (on error or when pressing CTRL-C) use
  3678. a flat hierarchy: they are all in the "Vim" class. You cannot throw yourself
  3679. exceptions with the "Vim" prefix; they are reserved for Vim.
  3680. Vim error exceptions are parameterized with the name of the command that
  3681. failed, if known. See |catch-errors|.
  3682. PECULIARITIES
  3683. *except-compat*
  3684. The exception handling concept requires that the command sequence causing the
  3685. exception is aborted immediately and control is transferred to finally clauses
  3686. and/or a catch clause.
  3687. In the Vim script language there are cases where scripts and functions
  3688. continue after an error: in functions without the "abort" flag or in a command
  3689. after ":silent!", control flow goes to the following line, and outside
  3690. functions, control flow goes to the line following the outermost ":endwhile"
  3691. or ":endif". On the other hand, errors should be catchable as exceptions
  3692. (thus, requiring the immediate abortion).
  3693. This problem has been solved by converting errors to exceptions and using
  3694. immediate abortion (if not suppressed by ":silent!") only when a try
  3695. conditional is active. This is no restriction since an (error) exception can
  3696. be caught only from an active try conditional. If you want an immediate
  3697. termination without catching the error, just use a try conditional without
  3698. catch clause. (You can cause cleanup code being executed before termination
  3699. by specifying a finally clause.)
  3700. When no try conditional is active, the usual abortion and continuation
  3701. behavior is used instead of immediate abortion. This ensures compatibility of
  3702. scripts written for Vim 6.1 and earlier.
  3703. However, when sourcing an existing script that does not use exception handling
  3704. commands (or when calling one of its functions) from inside an active try
  3705. conditional of a new script, you might change the control flow of the existing
  3706. script on error. You get the immediate abortion on error and can catch the
  3707. error in the new script. If however the sourced script suppresses error
  3708. messages by using the ":silent!" command (checking for errors by testing
  3709. |v:errmsg| if appropriate), its execution path is not changed. The error is
  3710. not converted to an exception. (See |:silent|.) So the only remaining cause
  3711. where this happens is for scripts that don't care about errors and produce
  3712. error messages. You probably won't want to use such code from your new
  3713. scripts.
  3714. *except-syntax-err*
  3715. Syntax errors in the exception handling commands are never caught by any of
  3716. the ":catch" commands of the try conditional they belong to. Its finally
  3717. clauses, however, is executed.
  3718. Example: >
  3719. :try
  3720. : try
  3721. : throw 4711
  3722. : catch /\(/
  3723. : echo "in catch with syntax error"
  3724. : catch
  3725. : echo "inner catch-all"
  3726. : finally
  3727. : echo "inner finally"
  3728. : endtry
  3729. :catch
  3730. : echo 'outer catch-all caught "' .. v:exception .. '"'
  3731. : finally
  3732. : echo "outer finally"
  3733. :endtry
  3734. This displays: >
  3735. inner finally
  3736. outer catch-all caught "Vim(catch):E54: Unmatched \("
  3737. outer finally
  3738. The original exception is discarded and an error exception is raised, instead.
  3739. *except-single-line*
  3740. The ":try", ":catch", ":finally", and ":endtry" commands can be put on
  3741. a single line, but then syntax errors may make it difficult to recognize the
  3742. "catch" line, thus you better avoid this.
  3743. Example: >
  3744. :try | unlet! foo # | catch | endtry
  3745. raises an error exception for the trailing characters after the ":unlet!"
  3746. argument, but does not see the ":catch" and ":endtry" commands, so that the
  3747. error exception is discarded and the "E488: Trailing characters" message gets
  3748. displayed.
  3749. *except-several-errors*
  3750. When several errors appear in a single command, the first error message is
  3751. usually the most specific one and therefore converted to the error exception.
  3752. Example: >
  3753. echo novar
  3754. causes >
  3755. E121: Undefined variable: novar
  3756. E15: Invalid expression: novar
  3757. The value of the error exception inside try conditionals is: >
  3758. Vim(echo):E121: Undefined variable: novar
  3759. < *except-syntax-error*
  3760. But when a syntax error is detected after a normal error in the same command,
  3761. the syntax error is used for the exception being thrown.
  3762. Example: >
  3763. unlet novar #
  3764. causes >
  3765. E108: No such variable: "novar"
  3766. E488: Trailing characters
  3767. The value of the error exception inside try conditionals is: >
  3768. Vim(unlet):E488: Trailing characters
  3769. This is done because the syntax error might change the execution path in a way
  3770. not intended by the user. Example: >
  3771. try
  3772. try | unlet novar # | catch | echo v:exception | endtry
  3773. catch /.*/
  3774. echo "outer catch:" v:exception
  3775. endtry
  3776. This displays "outer catch: Vim(unlet):E488: Trailing characters", and then
  3777. a "E600: Missing :endtry" error message is given, see |except-single-line|.
  3778. ==============================================================================
  3779. 9. Examples *eval-examples*
  3780. Printing in Binary ~
  3781. >
  3782. :" The function Nr2Bin() returns the binary string representation of a number.
  3783. :func Nr2Bin(nr)
  3784. : let n = a:nr
  3785. : let r = ""
  3786. : while n
  3787. : let r = '01'[n % 2] .. r
  3788. : let n = n / 2
  3789. : endwhile
  3790. : return r
  3791. :endfunc
  3792. :" The function String2Bin() converts each character in a string to a
  3793. :" binary string, separated with dashes.
  3794. :func String2Bin(str)
  3795. : let out = ''
  3796. : for ix in range(strlen(a:str))
  3797. : let out = out .. '-' .. Nr2Bin(char2nr(a:str[ix]))
  3798. : endfor
  3799. : return out[1:]
  3800. :endfunc
  3801. Example of its use: >
  3802. :echo Nr2Bin(32)
  3803. result: "100000" >
  3804. :echo String2Bin("32")
  3805. result: "110011-110010"
  3806. Sorting lines ~
  3807. This example sorts lines with a specific compare function. >
  3808. :func SortBuffer()
  3809. : let lines = getline(1, '$')
  3810. : call sort(lines, function("Strcmp"))
  3811. : call setline(1, lines)
  3812. :endfunction
  3813. As a one-liner: >
  3814. :call setline(1, sort(getline(1, '$'), function("Strcmp")))
  3815. scanf() replacement ~
  3816. *sscanf*
  3817. There is no sscanf() function in Vim. If you need to extract parts from a
  3818. line, you can use matchstr() and substitute() to do it. This example shows
  3819. how to get the file name, line number and column number out of a line like
  3820. "foobar.txt, 123, 45". >
  3821. :" Set up the match bit
  3822. :let mx='\(\f\+\),\s*\(\d\+\),\s*\(\d\+\)'
  3823. :"get the part matching the whole expression
  3824. :let l = matchstr(line, mx)
  3825. :"get each item out of the match
  3826. :let file = substitute(l, mx, '\1', '')
  3827. :let lnum = substitute(l, mx, '\2', '')
  3828. :let col = substitute(l, mx, '\3', '')
  3829. The input is in the variable "line", the results in the variables "file",
  3830. "lnum" and "col". (idea from Michael Geddes)
  3831. getting the scriptnames in a Dictionary ~
  3832. *scriptnames-dictionary*
  3833. The |:scriptnames| command can be used to get a list of all script files that
  3834. have been sourced. There is no equivalent function or variable for this
  3835. (because it's rarely needed). In case you need to manipulate the list this
  3836. code can be used: >
  3837. " Get the output of ":scriptnames" in the scriptnames_output variable.
  3838. let scriptnames_output = ''
  3839. redir => scriptnames_output
  3840. silent scriptnames
  3841. redir END
  3842. " Split the output into lines and parse each line. Add an entry to the
  3843. " "scripts" dictionary.
  3844. let scripts = {}
  3845. for line in split(scriptnames_output, "\n")
  3846. " Only do non-blank lines.
  3847. if line =~ '\S'
  3848. " Get the first number in the line.
  3849. let nr = matchstr(line, '\d\+')
  3850. " Get the file name, remove the script number " 123: ".
  3851. let name = substitute(line, '.\+:\s*', '', '')
  3852. " Add an item to the Dictionary
  3853. let scripts[nr] = name
  3854. endif
  3855. endfor
  3856. unlet scriptnames_output
  3857. ==============================================================================
  3858. 10. Vim script versions *vimscript-version* *vimscript-versions*
  3859. *scriptversion*
  3860. Over time many features have been added to Vim script. This includes Ex
  3861. commands, functions, variable types, etc. Each individual feature can be
  3862. checked with the |has()| and |exists()| functions.
  3863. Sometimes old syntax of functionality gets in the way of making Vim better.
  3864. When support is taken away this will break older Vim scripts. To make this
  3865. explicit the |:scriptversion| command can be used. When a Vim script is not
  3866. compatible with older versions of Vim this will give an explicit error,
  3867. instead of failing in mysterious ways.
  3868. When using a legacy function, defined with `:function`, in |Vim9| script then
  3869. scriptversion 4 is used.
  3870. *scriptversion-1* >
  3871. :scriptversion 1
  3872. < This is the original Vim script, same as not using a |:scriptversion|
  3873. command. Can be used to go back to old syntax for a range of lines.
  3874. Test for support with: >
  3875. has('vimscript-1')
  3876. < *scriptversion-2* >
  3877. :scriptversion 2
  3878. < String concatenation with "." is not supported, use ".." instead.
  3879. This avoids the ambiguity using "." for Dict member access and
  3880. floating point numbers. Now ".5" means the number 0.5.
  3881. *scriptversion-3* >
  3882. :scriptversion 3
  3883. < All |vim-variable|s must be prefixed by "v:". E.g. "version" doesn't
  3884. work as |v:version| anymore, it can be used as a normal variable.
  3885. Same for some obvious names as "count" and others.
  3886. Test for support with: >
  3887. has('vimscript-3')
  3888. <
  3889. *scriptversion-4* >
  3890. :scriptversion 4
  3891. < Numbers with a leading zero are not recognized as octal. "0o" or "0O"
  3892. is still recognized as octal. With the
  3893. previous version you get: >
  3894. echo 017 " displays 15 (octal)
  3895. echo 0o17 " displays 15 (octal)
  3896. echo 018 " displays 18 (decimal)
  3897. < with script version 4: >
  3898. echo 017 " displays 17 (decimal)
  3899. echo 0o17 " displays 15 (octal)
  3900. echo 018 " displays 18 (decimal)
  3901. < Also, it is possible to use single quotes inside numbers to make them
  3902. easier to read: >
  3903. echo 1'000'000
  3904. < The quotes must be surrounded by digits.
  3905. Test for support with: >
  3906. has('vimscript-4')
  3907. ==============================================================================
  3908. 11. No +eval feature *no-eval-feature*
  3909. When the |+eval| feature was disabled at compile time, none of the expression
  3910. evaluation commands are available. To prevent this from causing Vim scripts
  3911. to generate all kinds of errors, the ":if" and ":endif" commands are still
  3912. recognized, though the argument of the ":if" and everything between the ":if"
  3913. and the matching ":endif" is ignored. Nesting of ":if" blocks is allowed, but
  3914. only if the commands are at the start of the line. The ":else" command is not
  3915. recognized.
  3916. Example of how to avoid executing commands when the |+eval| feature is
  3917. missing: >
  3918. :if 1
  3919. : echo "Expression evaluation is compiled in"
  3920. :else
  3921. : echo "You will _never_ see this message"
  3922. :endif
  3923. To execute a command only when the |+eval| feature is disabled can be done in
  3924. two ways. The simplest is to exit the script (or Vim) prematurely: >
  3925. if 1
  3926. echo "commands executed with +eval"
  3927. finish
  3928. endif
  3929. args " command executed without +eval
  3930. If you do not want to abort loading the script you can use a trick, as this
  3931. example shows: >
  3932. silent! while 0
  3933. set history=111
  3934. silent! endwhile
  3935. When the |+eval| feature is available the command is skipped because of the
  3936. "while 0". Without the |+eval| feature the "while 0" is an error, which is
  3937. silently ignored, and the command is executed.
  3938. ==============================================================================
  3939. 12. The sandbox *eval-sandbox* *sandbox*
  3940. The 'foldexpr', 'formatexpr', 'includeexpr', 'indentexpr', 'statusline' and
  3941. 'foldtext' options may be evaluated in a sandbox. This means that you are
  3942. protected from these expressions having nasty side effects. This gives some
  3943. safety for when these options are set from a modeline. It is also used when
  3944. the command from a tags file is executed and for CTRL-R = in the command line.
  3945. The sandbox is also used for the |:sandbox| command.
  3946. *E48*
  3947. These items are not allowed in the sandbox:
  3948. - changing the buffer text
  3949. - defining or changing mapping, autocommands, user commands
  3950. - setting certain options (see |option-summary|)
  3951. - setting certain v: variables (see |v:var|) *E794*
  3952. - executing a shell command
  3953. - reading or writing a file
  3954. - jumping to another buffer or editing a file
  3955. - executing Python, Perl, etc. commands
  3956. This is not guaranteed 100% secure, but it should block most attacks.
  3957. *:san* *:sandbox*
  3958. :san[dbox] {cmd} Execute {cmd} in the sandbox. Useful to evaluate an
  3959. option that may have been set from a modeline, e.g.
  3960. 'foldexpr'.
  3961. *sandbox-option*
  3962. A few options contain an expression. When this expression is evaluated it may
  3963. have to be done in the sandbox to avoid a security risk. But the sandbox is
  3964. restrictive, thus this only happens when the option was set from an insecure
  3965. location. Insecure in this context are:
  3966. - sourcing a .vimrc or .exrc in the current directory
  3967. - while executing in the sandbox
  3968. - value coming from a modeline
  3969. - executing a function that was defined in the sandbox
  3970. Note that when in the sandbox and saving an option value and restoring it, the
  3971. option will still be marked as it was set in the sandbox.
  3972. ==============================================================================
  3973. 13. Textlock *textlock*
  3974. In a few situations it is not allowed to change the text in the buffer, jump
  3975. to another window and some other things that might confuse or break what Vim
  3976. is currently doing. This mostly applies to things that happen when Vim is
  3977. actually doing something else. For example, evaluating the 'balloonexpr' may
  3978. happen any moment the mouse cursor is resting at some position.
  3979. This is not allowed when the textlock is active:
  3980. - changing the buffer text
  3981. - jumping to another buffer or window
  3982. - editing another file
  3983. - closing a window or quitting Vim
  3984. - etc.
  3985. vim:tw=78:ts=8:noet:ft=help:norl: