eval.txt 135 KB

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