eval.txt 152 KB

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