usr_41.txt 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568
  1. *usr_41.txt* Nvim
  2. VIM USER MANUAL - by Bram Moolenaar
  3. Write a Vim script
  4. The Vim script language is used for the startup vimrc file, syntax files, and
  5. many other things. This chapter explains the items that can be used in a Vim
  6. script. There are a lot of them, thus this is a long chapter.
  7. |41.1| Introduction
  8. |41.2| Variables
  9. |41.3| Expressions
  10. |41.4| Conditionals
  11. |41.5| Executing an expression
  12. |41.6| Using functions
  13. |41.7| Defining a function
  14. |41.8| Lists and Dictionaries
  15. |41.9| Exceptions
  16. |41.10| Various remarks
  17. |41.11| Writing a plugin
  18. |41.12| Writing a filetype plugin
  19. |41.13| Writing a compiler plugin
  20. |41.14| Writing a plugin that loads quickly
  21. |41.15| Writing library scripts
  22. |41.16| Distributing Vim scripts
  23. Next chapter: |usr_42.txt| Add new menus
  24. Previous chapter: |usr_40.txt| Make new commands
  25. Table of contents: |usr_toc.txt|
  26. ==============================================================================
  27. *41.1* Introduction *vim-script-intro* *script*
  28. Your first experience with Vim scripts is the vimrc file. Vim reads it when
  29. it starts up and executes the commands. You can set options to values you
  30. prefer. And you can use any colon command in it (commands that start with a
  31. ":"; these are sometimes referred to as Ex commands or command-line commands).
  32. Syntax files are also Vim scripts. As are files that set options for a
  33. specific file type. A complicated macro can be defined by a separate Vim
  34. script file. You can think of other uses yourself.
  35. Let's start with a simple example: >
  36. :let i = 1
  37. :while i < 5
  38. : echo "count is" i
  39. : let i += 1
  40. :endwhile
  41. <
  42. Note:
  43. The ":" characters are not really needed here. You only need to use
  44. them when you type a command. In a Vim script file they can be left
  45. out. We will use them here anyway to make clear these are colon
  46. commands and make them stand out from Normal mode commands.
  47. Note:
  48. You can try out the examples by yanking the lines from the text here
  49. and executing them with :@"
  50. The output of the example code is:
  51. count is 1 ~
  52. count is 2 ~
  53. count is 3 ~
  54. count is 4 ~
  55. In the first line the ":let" command assigns a value to a variable. The
  56. generic form is: >
  57. :let {variable} = {expression}
  58. In this case the variable name is "i" and the expression is a simple value,
  59. the number one.
  60. The ":while" command starts a loop. The generic form is: >
  61. :while {condition}
  62. : {statements}
  63. :endwhile
  64. The statements until the matching ":endwhile" are executed for as long as the
  65. condition is true. The condition used here is the expression "i < 5". This
  66. is true when the variable i is smaller than five.
  67. Note:
  68. If you happen to write a while loop that keeps on running, you can
  69. interrupt it by pressing CTRL-C (CTRL-Break on MS-Windows).
  70. The ":echo" command prints its arguments. In this case the string "count is"
  71. and the value of the variable i. Since i is one, this will print:
  72. count is 1 ~
  73. Then there is the ":let i += 1" command. This does the same thing as
  74. ":let i = i + 1". This adds one to the variable i and assigns the new value
  75. to the same variable.
  76. The example was given to explain the commands, but would you really want to
  77. make such a loop, it can be written much more compact: >
  78. :for i in range(1, 4)
  79. : echo "count is" i
  80. :endfor
  81. We won't explain how |:for| and |range()| work until later. Follow the links
  82. if you are impatient.
  83. FOUR KINDS OF NUMBERS
  84. Numbers can be decimal, hexadecimal, octal or binary. A hexadecimal number
  85. starts with "0x" or "0X". For example "0x1f" is decimal 31. An octal number
  86. starts with a zero. "017" is decimal 15. A binary number starts with "0b" or
  87. "0B". For example "0b101" is decimal 5. Careful: don't put a zero before a
  88. decimal number, it will be interpreted as an octal number!
  89. The ":echo" command always prints decimal numbers. Example: >
  90. :echo 0x7f 036
  91. < 127 30 ~
  92. A number is made negative with a minus sign. This also works for hexadecimal,
  93. octal and binary numbers. A minus sign is also used for subtraction. Compare
  94. this with the previous example: >
  95. :echo 0x7f -036
  96. < 97 ~
  97. White space in an expression is ignored. However, it's recommended to use it
  98. for separating items, to make the expression easier to read. For example, to
  99. avoid the confusion with a negative number above, put a space between the
  100. minus sign and the following number: >
  101. :echo 0x7f - 036
  102. ==============================================================================
  103. *41.2* Variables
  104. A variable name consists of ASCII letters, digits and the underscore. It
  105. cannot start with a digit. Valid variable names are:
  106. counter
  107. _aap3
  108. very_long_variable_name_with_underscores
  109. FuncLength
  110. LENGTH
  111. Invalid names are "foo+bar" and "6var".
  112. These variables are global. To see a list of currently defined variables
  113. use this command: >
  114. :let
  115. You can use global variables everywhere. This also means that when the
  116. variable "count" is used in one script file, it might also be used in another
  117. file. This leads to confusion at least, and real problems at worst. To avoid
  118. this, you can use a variable local to a script file by prepending "s:". For
  119. example, one script contains this code: >
  120. :let s:count = 1
  121. :while s:count < 5
  122. : source other.vim
  123. : let s:count += 1
  124. :endwhile
  125. Since "s:count" is local to this script, you can be sure that sourcing the
  126. "other.vim" script will not change this variable. If "other.vim" also uses an
  127. "s:count" variable, it will be a different copy, local to that script. More
  128. about script-local variables here: |script-variable|.
  129. There are more kinds of variables, see |internal-variables|. The most often
  130. used ones are:
  131. b:name variable local to a buffer
  132. w:name variable local to a window
  133. g:name global variable (also in a function)
  134. v:name variable predefined by Vim
  135. DELETING VARIABLES
  136. Variables take up memory and show up in the output of the ":let" command. To
  137. delete a variable use the ":unlet" command. Example: >
  138. :unlet s:count
  139. This deletes the script-local variable "s:count" to free up the memory it
  140. uses. If you are not sure if the variable exists, and don't want an error
  141. message when it doesn't, append !: >
  142. :unlet! s:count
  143. When a script finishes, the local variables used there will not be
  144. automatically freed. The next time the script executes, it can still use the
  145. old value. Example: >
  146. :if !exists("s:call_count")
  147. : let s:call_count = 0
  148. :endif
  149. :let s:call_count = s:call_count + 1
  150. :echo "called" s:call_count "times"
  151. The "exists()" function checks if a variable has already been defined. Its
  152. argument is the name of the variable you want to check. Not the variable
  153. itself! If you would do this: >
  154. :if !exists(s:call_count)
  155. Then the value of s:call_count will be used as the name of the variable that
  156. exists() checks. That's not what you want.
  157. The exclamation mark ! negates a value. When the value was true, it
  158. becomes false. When it was false, it becomes true. You can read it as "not".
  159. Thus "if !exists()" can be read as "if not exists()".
  160. What Vim calls true is anything that is not zero. Zero is false.
  161. Note:
  162. Vim automatically converts a string to a number when it is looking for
  163. a number. When using a string that doesn't start with a digit the
  164. resulting number is zero. Thus look out for this: >
  165. :if "true"
  166. < The "true" will be interpreted as a zero, thus as false!
  167. STRING VARIABLES AND CONSTANTS
  168. So far only numbers were used for the variable value. Strings can be used as
  169. well. Numbers and strings are the basic types of variables that Vim supports.
  170. The type is dynamic, it is set each time when assigning a value to the
  171. variable with ":let". More about types in |41.8|.
  172. To assign a string value to a variable, you need to use a string constant.
  173. There are two types of these. First the string in double quotes: >
  174. :let name = "peter"
  175. :echo name
  176. < peter ~
  177. If you want to include a double quote inside the string, put a backslash in
  178. front of it: >
  179. :let name = "\"peter\""
  180. :echo name
  181. < "peter" ~
  182. To avoid the need for a backslash, you can use a string in single quotes: >
  183. :let name = '"peter"'
  184. :echo name
  185. < "peter" ~
  186. Inside a single-quote string all the characters are as they are. Only the
  187. single quote itself is special: you need to use two to get one. A backslash
  188. is taken literally, thus you can't use it to change the meaning of the
  189. character after it.
  190. In double-quote strings it is possible to use special characters. Here are
  191. a few useful ones:
  192. \t <Tab>
  193. \n <NL>, line break
  194. \r <CR>, <Enter>
  195. \e <Esc>
  196. \b <BS>, backspace
  197. \" "
  198. \\ \, backslash
  199. \<Esc> <Esc>
  200. \<C-W> CTRL-W
  201. The last two are just examples. The "\<name>" form can be used to include
  202. the special key "name".
  203. See |expr-quote| for the full list of special items in a string.
  204. ==============================================================================
  205. *41.3* Expressions
  206. Vim has a rich, yet simple way to handle expressions. You can read the
  207. definition here: |expression-syntax|. Here we will show the most common
  208. items.
  209. The numbers, strings and variables mentioned above are expressions by
  210. themselves. Thus everywhere an expression is expected, you can use a number,
  211. string or variable. Other basic items in an expression are:
  212. $NAME environment variable
  213. &name option
  214. @r register
  215. Examples: >
  216. :echo "The value of 'tabstop' is" &ts
  217. :echo "Your home directory is" $HOME
  218. :if @a > 5
  219. The &name form can be used to save an option value, set it to a new value,
  220. do something and restore the old value. Example: >
  221. :let save_ic = &ic
  222. :set noic
  223. :/The Start/,$delete
  224. :let &ic = save_ic
  225. This makes sure the "The Start" pattern is used with the 'ignorecase' option
  226. off. Still, it keeps the value that the user had set. (Another way to do
  227. this would be to add "\C" to the pattern, see |/\C|.)
  228. MATHEMATICS
  229. It becomes more interesting if we combine these basic items. Let's start with
  230. mathematics on numbers:
  231. a + b add
  232. a - b subtract
  233. a * b multiply
  234. a / b divide
  235. a % b modulo
  236. The usual precedence is used. Example: >
  237. :echo 10 + 5 * 2
  238. < 20 ~
  239. Grouping is done with parentheses. No surprises here. Example: >
  240. :echo (10 + 5) * 2
  241. < 30 ~
  242. Strings can be concatenated with ".". Example: >
  243. :echo "foo" . "bar"
  244. < foobar ~
  245. When the ":echo" command gets multiple arguments, it separates them with a
  246. space. In the example the argument is a single expression, thus no space is
  247. inserted.
  248. Borrowed from the C language is the conditional expression:
  249. a ? b : c
  250. If "a" evaluates to true "b" is used, otherwise "c" is used. Example: >
  251. :let i = 4
  252. :echo i > 5 ? "i is big" : "i is small"
  253. < i is small ~
  254. The three parts of the constructs are always evaluated first, thus you could
  255. see it work as:
  256. (a) ? (b) : (c)
  257. ==============================================================================
  258. *41.4* Conditionals
  259. The ":if" commands executes the following statements, until the matching
  260. ":endif", only when a condition is met. The generic form is:
  261. :if {condition}
  262. {statements}
  263. :endif
  264. Only when the expression {condition} evaluates to true (non-zero) will the
  265. {statements} be executed. These must still be valid commands. If they
  266. contain garbage, Vim won't be able to find the ":endif".
  267. You can also use ":else". The generic form for this is:
  268. :if {condition}
  269. {statements}
  270. :else
  271. {statements}
  272. :endif
  273. The second {statements} is only executed if the first one isn't.
  274. Finally, there is ":elseif":
  275. :if {condition}
  276. {statements}
  277. :elseif {condition}
  278. {statements}
  279. :endif
  280. This works just like using ":else" and then "if", but without the need for an
  281. extra ":endif".
  282. A useful example for your vimrc file is checking the 'term' option and
  283. doing something depending upon its value: >
  284. :if &term == "xterm"
  285. : " Do stuff for xterm
  286. :elseif &term == "vt100"
  287. : " Do stuff for a vt100 terminal
  288. :else
  289. : " Do something for other terminals
  290. :endif
  291. LOGIC OPERATIONS
  292. We already used some of them in the examples. These are the most often used
  293. ones:
  294. a == b equal to
  295. a != b not equal to
  296. a > b greater than
  297. a >= b greater than or equal to
  298. a < b less than
  299. a <= b less than or equal to
  300. The result is one if the condition is met and zero otherwise. An example: >
  301. :if v:version >= 700
  302. : echo "congratulations"
  303. :else
  304. : echo "you are using an old version, upgrade!"
  305. :endif
  306. Here "v:version" is a variable defined by Vim, which has the value of the Vim
  307. version. 600 is for version 6.0. Version 6.1 has the value 601. This is
  308. very useful to write a script that works with multiple versions of Vim.
  309. |v:version|
  310. The logic operators work both for numbers and strings. When comparing two
  311. strings, the mathematical difference is used. This compares byte values,
  312. which may not be right for some languages.
  313. When comparing a string with a number, the string is first converted to a
  314. number. This is a bit tricky, because when a string doesn't look like a
  315. number, the number zero is used. Example: >
  316. :if 0 == "one"
  317. : echo "yes"
  318. :endif
  319. This will echo "yes", because "one" doesn't look like a number, thus it is
  320. converted to the number zero.
  321. For strings there are two more items:
  322. a =~ b matches with
  323. a !~ b does not match with
  324. The left item "a" is used as a string. The right item "b" is used as a
  325. pattern, like what's used for searching. Example: >
  326. :if str =~ " "
  327. : echo "str contains a space"
  328. :endif
  329. :if str !~ '\.$'
  330. : echo "str does not end in a full stop"
  331. :endif
  332. Notice the use of a single-quote string for the pattern. This is useful,
  333. because backslashes would need to be doubled in a double-quote string and
  334. patterns tend to contain many backslashes.
  335. The 'ignorecase' option is used when comparing strings. When you don't want
  336. that, append "#" to match case and "?" to ignore case. Thus "==?" compares
  337. two strings to be equal while ignoring case. And "!~#" checks if a pattern
  338. doesn't match, also checking the case of letters. For the full table see
  339. |expr-==|.
  340. MORE LOOPING
  341. The ":while" command was already mentioned. Two more statements can be used
  342. in between the ":while" and the ":endwhile":
  343. :continue Jump back to the start of the while loop; the
  344. loop continues.
  345. :break Jump forward to the ":endwhile"; the loop is
  346. discontinued.
  347. Example: >
  348. :while counter < 40
  349. : call do_something()
  350. : if skip_flag
  351. : continue
  352. : endif
  353. : if finished_flag
  354. : break
  355. : endif
  356. : sleep 50m
  357. :endwhile
  358. The ":sleep" command makes Vim take a nap. The "50m" specifies fifty
  359. milliseconds. Another example is ":sleep 4", which sleeps for four seconds.
  360. Even more looping can be done with the ":for" command, see below in |41.8|.
  361. ==============================================================================
  362. *41.5* Executing an expression
  363. So far the commands in the script were executed by Vim directly. The
  364. ":execute" command allows executing the result of an expression. This is a
  365. very powerful way to build commands and execute them.
  366. An example is to jump to a tag, which is contained in a variable: >
  367. :execute "tag " . tag_name
  368. The "." is used to concatenate the string "tag " with the value of variable
  369. "tag_name". Suppose "tag_name" has the value "get_cmd", then the command that
  370. will be executed is: >
  371. :tag get_cmd
  372. The ":execute" command can only execute colon commands. The ":normal" command
  373. executes Normal mode commands. However, its argument is not an expression but
  374. the literal command characters. Example: >
  375. :normal gg=G
  376. This jumps to the first line and formats all lines with the "=" operator.
  377. To make ":normal" work with an expression, combine ":execute" with it.
  378. Example: >
  379. :execute "normal " . normal_commands
  380. The variable "normal_commands" must contain the Normal mode commands.
  381. Make sure that the argument for ":normal" is a complete command. Otherwise
  382. Vim will run into the end of the argument and abort the command. For example,
  383. if you start Insert mode, you must leave Insert mode as well. This works: >
  384. :execute "normal Inew text \<Esc>"
  385. This inserts "new text " in the current line. Notice the use of the special
  386. key "\<Esc>". This avoids having to enter a real <Esc> character in your
  387. script.
  388. If you don't want to execute a string but evaluate it to get its expression
  389. value, you can use the eval() function: >
  390. :let optname = "path"
  391. :let optval = eval('&' . optname)
  392. A "&" character is prepended to "path", thus the argument to eval() is
  393. "&path". The result will then be the value of the 'path' option.
  394. The same thing can be done with: >
  395. :exe 'let optval = &' . optname
  396. ==============================================================================
  397. *41.6* Using functions
  398. Vim defines many functions and provides a large amount of functionality that
  399. way. A few examples will be given in this section. You can find the whole
  400. list here: |functions|.
  401. A function is called with the ":call" command. The parameters are passed in
  402. between parentheses separated by commas. Example: >
  403. :call search("Date: ", "W")
  404. This calls the search() function, with arguments "Date: " and "W". The
  405. search() function uses its first argument as a search pattern and the second
  406. one as flags. The "W" flag means the search doesn't wrap around the end of
  407. the file.
  408. A function can be called in an expression. Example: >
  409. :let line = getline(".")
  410. :let repl = substitute(line, '\a', "*", "g")
  411. :call setline(".", repl)
  412. The getline() function obtains a line from the current buffer. Its argument
  413. is a specification of the line number. In this case "." is used, which means
  414. the line where the cursor is.
  415. The substitute() function does something similar to the ":substitute"
  416. command. The first argument is the string on which to perform the
  417. substitution. The second argument is the pattern, the third the replacement
  418. string. Finally, the last arguments are the flags.
  419. The setline() function sets the line, specified by the first argument, to a
  420. new string, the second argument. In this example the line under the cursor is
  421. replaced with the result of the substitute(). Thus the effect of the three
  422. statements is equal to: >
  423. :substitute/\a/*/g
  424. Using the functions becomes more interesting when you do more work before and
  425. after the substitute() call.
  426. FUNCTIONS *function-list*
  427. There are many functions. We will mention them here, grouped by what they are
  428. used for. You can find an alphabetical list here: |functions|. Use CTRL-] on
  429. the function name to jump to detailed help on it.
  430. String manipulation: *string-functions*
  431. nr2char() get a character by its ASCII value
  432. char2nr() get ASCII value of a character
  433. str2nr() convert a string to a Number
  434. str2float() convert a string to a Float
  435. printf() format a string according to % items
  436. escape() escape characters in a string with a '\'
  437. shellescape() escape a string for use with a shell command
  438. fnameescape() escape a file name for use with a Vim command
  439. tr() translate characters from one set to another
  440. strtrans() translate a string to make it printable
  441. tolower() turn a string to lowercase
  442. toupper() turn a string to uppercase
  443. match() position where a pattern matches in a string
  444. matchend() position where a pattern match ends in a string
  445. matchstr() match of a pattern in a string
  446. matchstrpos() match and positions of a pattern in a string
  447. matchlist() like matchstr() and also return submatches
  448. stridx() first index of a short string in a long string
  449. strridx() last index of a short string in a long string
  450. strlen() length of a string in bytes
  451. strchars() length of a string in characters
  452. strwidth() size of string when displayed
  453. strdisplaywidth() size of string when displayed, deals with tabs
  454. substitute() substitute a pattern match with a string
  455. submatch() get a specific match in ":s" and substitute()
  456. strpart() get part of a string using byte index
  457. strcharpart() get part of a string using char index
  458. strgetchar() get character from a string using char index
  459. expand() expand special keywords
  460. iconv() convert text from one encoding to another
  461. byteidx() byte index of a character in a string
  462. byteidxcomp() like byteidx() but count composing characters
  463. repeat() repeat a string multiple times
  464. eval() evaluate a string expression
  465. execute() execute an Ex command and get the output
  466. win_execute() like execute() but in a specified window
  467. trim() trim characters from a string
  468. List manipulation: *list-functions*
  469. get() get an item without error for wrong index
  470. len() number of items in a List
  471. empty() check if List is empty
  472. insert() insert an item somewhere in a List
  473. add() append an item to a List
  474. extend() append a List to a List
  475. remove() remove one or more items from a List
  476. copy() make a shallow copy of a List
  477. deepcopy() make a full copy of a List
  478. filter() remove selected items from a List
  479. map() change each List item
  480. sort() sort a List
  481. reverse() reverse the order of a List
  482. uniq() remove copies of repeated adjacent items
  483. split() split a String into a List
  484. join() join List items into a String
  485. range() return a List with a sequence of numbers
  486. string() String representation of a List
  487. call() call a function with List as arguments
  488. index() index of a value in a List
  489. max() maximum value in a List
  490. min() minimum value in a List
  491. count() count number of times a value appears in a List
  492. repeat() repeat a List multiple times
  493. Dictionary manipulation: *dict-functions*
  494. get() get an entry without an error for a wrong key
  495. len() number of entries in a Dictionary
  496. has_key() check whether a key appears in a Dictionary
  497. empty() check if Dictionary is empty
  498. remove() remove an entry from a Dictionary
  499. extend() add entries from one Dictionary to another
  500. filter() remove selected entries from a Dictionary
  501. map() change each Dictionary entry
  502. keys() get List of Dictionary keys
  503. values() get List of Dictionary values
  504. items() get List of Dictionary key-value pairs
  505. copy() make a shallow copy of a Dictionary
  506. deepcopy() make a full copy of a Dictionary
  507. string() String representation of a Dictionary
  508. max() maximum value in a Dictionary
  509. min() minimum value in a Dictionary
  510. count() count number of times a value appears
  511. Floating point computation: *float-functions*
  512. float2nr() convert Float to Number
  513. abs() absolute value (also works for Number)
  514. round() round off
  515. ceil() round up
  516. floor() round down
  517. trunc() remove value after decimal point
  518. fmod() remainder of division
  519. exp() exponential
  520. log() natural logarithm (logarithm to base e)
  521. log10() logarithm to base 10
  522. pow() value of x to the exponent y
  523. sqrt() square root
  524. sin() sine
  525. cos() cosine
  526. tan() tangent
  527. asin() arc sine
  528. acos() arc cosine
  529. atan() arc tangent
  530. atan2() arc tangent
  531. sinh() hyperbolic sine
  532. cosh() hyperbolic cosine
  533. tanh() hyperbolic tangent
  534. Other computation: *bitwise-function*
  535. and() bitwise AND
  536. invert() bitwise invert
  537. or() bitwise OR
  538. xor() bitwise XOR
  539. sha256() SHA-256 hash
  540. Variables: *var-functions*
  541. type() type of a variable
  542. islocked() check if a variable is locked
  543. funcref() get a Funcref for a function reference
  544. function() get a Funcref for a function name
  545. getbufvar() get a variable value from a specific buffer
  546. setbufvar() set a variable in a specific buffer
  547. getwinvar() get a variable from specific window
  548. gettabvar() get a variable from specific tab page
  549. gettabwinvar() get a variable from specific window & tab page
  550. setwinvar() set a variable in a specific window
  551. settabvar() set a variable in a specific tab page
  552. settabwinvar() set a variable in a specific window & tab page
  553. garbagecollect() possibly free memory
  554. Cursor and mark position: *cursor-functions* *mark-functions*
  555. col() column number of the cursor or a mark
  556. virtcol() screen column of the cursor or a mark
  557. line() line number of the cursor or mark
  558. wincol() window column number of the cursor
  559. winline() window line number of the cursor
  560. cursor() position the cursor at a line/column
  561. screencol() get screen column of the cursor
  562. screenrow() get screen row of the cursor
  563. getcurpos() get position of the cursor
  564. getpos() get position of cursor, mark, etc.
  565. setpos() set position of cursor, mark, etc.
  566. byte2line() get line number at a specific byte count
  567. line2byte() byte count at a specific line
  568. diff_filler() get the number of filler lines above a line
  569. screenattr() get attribute at a screen line/row
  570. screenchar() get character code at a screen line/row
  571. Working with text in the current buffer: *text-functions*
  572. getline() get a line or list of lines from the buffer
  573. setline() replace a line in the buffer
  574. append() append line or list of lines in the buffer
  575. indent() indent of a specific line
  576. cindent() indent according to C indenting
  577. lispindent() indent according to Lisp indenting
  578. nextnonblank() find next non-blank line
  579. prevnonblank() find previous non-blank line
  580. search() find a match for a pattern
  581. searchpos() find a match for a pattern
  582. searchpair() find the other end of a start/skip/end
  583. searchpairpos() find the other end of a start/skip/end
  584. searchdecl() search for the declaration of a name
  585. getcharsearch() return character search information
  586. setcharsearch() set character search information
  587. *system-functions* *file-functions*
  588. System functions and manipulation of files:
  589. glob() expand wildcards
  590. globpath() expand wildcards in a number of directories
  591. glob2regpat() convert a glob pattern into a search pattern
  592. findfile() find a file in a list of directories
  593. finddir() find a directory in a list of directories
  594. resolve() find out where a shortcut points to
  595. fnamemodify() modify a file name
  596. pathshorten() shorten directory names in a path
  597. simplify() simplify a path without changing its meaning
  598. executable() check if an executable program exists
  599. exepath() full path of an executable program
  600. filereadable() check if a file can be read
  601. filewritable() check if a file can be written to
  602. getfperm() get the permissions of a file
  603. setfperm() set the permissions of a file
  604. getftype() get the kind of a file
  605. isdirectory() check if a directory exists
  606. getfsize() get the size of a file
  607. getcwd() get the current working directory
  608. haslocaldir() check if current window used |:lcd|
  609. tempname() get the name of a temporary file
  610. mkdir() create a new directory
  611. delete() delete a file
  612. rename() rename a file
  613. system() get the result of a shell command as a string
  614. systemlist() get the result of a shell command as a list
  615. environ() get all environment variables
  616. getenv() get one environment variable
  617. setenv() set an environment variable
  618. hostname() name of the system
  619. readfile() read a file into a List of lines
  620. readdir() get a List of file names in a directory
  621. writefile() write a List of lines or Blob into a file
  622. Date and Time: *date-functions* *time-functions*
  623. getftime() get last modification time of a file
  624. localtime() get current time in seconds
  625. strftime() convert time to a string
  626. reltime() get the current or elapsed time accurately
  627. reltimestr() convert reltime() result to a string
  628. reltimefloat() convert reltime() result to a Float
  629. *buffer-functions* *window-functions* *arg-functions*
  630. Buffers, windows and the argument list:
  631. argc() number of entries in the argument list
  632. argidx() current position in the argument list
  633. arglistid() get id of the argument list
  634. argv() get one entry from the argument list
  635. bufexists() check if a buffer exists
  636. buflisted() check if a buffer exists and is listed
  637. bufloaded() check if a buffer exists and is loaded
  638. bufname() get the name of a specific buffer
  639. bufnr() get the buffer number of a specific buffer
  640. tabpagebuflist() return List of buffers in a tab page
  641. tabpagenr() get the number of a tab page
  642. tabpagewinnr() like winnr() for a specified tab page
  643. winnr() get the window number for the current window
  644. bufwinid() get the window ID of a specific buffer
  645. bufwinnr() get the window number of a specific buffer
  646. winbufnr() get the buffer number of a specific window
  647. getbufline() get a list of lines from the specified buffer
  648. setbufline() replace a line in the specified buffer
  649. appendbufline() append a list of lines in the specified buffer
  650. deletebufline() delete lines from a specified buffer
  651. win_findbuf() find windows containing a buffer
  652. win_getid() get window ID of a window
  653. win_gotoid() go to window with ID
  654. win_id2tabwin() get tab and window nr from window ID
  655. win_id2win() get window nr from window ID
  656. getbufinfo() get a list with buffer information
  657. gettabinfo() get a list with tab page information
  658. getwininfo() get a list with window information
  659. getchangelist() get a list of change list entries
  660. getjumplist() get a list of jump list entries
  661. swapinfo() information about a swap file
  662. swapname() get the swap file path of a buffer
  663. Command line: *command-line-functions*
  664. getcmdline() get the current command line
  665. getcmdpos() get position of the cursor in the command line
  666. setcmdpos() set position of the cursor in the command line
  667. getcmdtype() return the current command-line type
  668. getcmdwintype() return the current command-line window type
  669. getcompletion() list of command-line completion matches
  670. Quickfix and location lists: *quickfix-functions*
  671. getqflist() list of quickfix errors
  672. setqflist() modify a quickfix list
  673. getloclist() list of location list items
  674. setloclist() modify a location list
  675. Insert mode completion: *completion-functions*
  676. complete() set found matches
  677. complete_add() add to found matches
  678. complete_check() check if completion should be aborted
  679. complete_info() get current completion information
  680. pumvisible() check if the popup menu is displayed
  681. Folding: *folding-functions*
  682. foldclosed() check for a closed fold at a specific line
  683. foldclosedend() like foldclosed() but return the last line
  684. foldlevel() check for the fold level at a specific line
  685. foldtext() generate the line displayed for a closed fold
  686. foldtextresult() get the text displayed for a closed fold
  687. Syntax and highlighting: *syntax-functions* *highlighting-functions*
  688. clearmatches() clear all matches defined by |matchadd()| and
  689. the |:match| commands
  690. getmatches() get all matches defined by |matchadd()| and
  691. the |:match| commands
  692. hlexists() check if a highlight group exists
  693. hlID() get ID of a highlight group
  694. synID() get syntax ID at a specific position
  695. synIDattr() get a specific attribute of a syntax ID
  696. synIDtrans() get translated syntax ID
  697. synstack() get list of syntax IDs at a specific position
  698. synconcealed() get info about concealing
  699. diff_hlID() get highlight ID for diff mode at a position
  700. matchadd() define a pattern to highlight (a "match")
  701. matchaddpos() define a list of positions to highlight
  702. matcharg() get info about |:match| arguments
  703. matchdelete() delete a match defined by |matchadd()| or a
  704. |:match| command
  705. setmatches() restore a list of matches saved by
  706. |getmatches()|
  707. Spelling: *spell-functions*
  708. spellbadword() locate badly spelled word at or after cursor
  709. spellsuggest() return suggested spelling corrections
  710. soundfold() return the sound-a-like equivalent of a word
  711. History: *history-functions*
  712. histadd() add an item to a history
  713. histdel() delete an item from a history
  714. histget() get an item from a history
  715. histnr() get highest index of a history list
  716. Interactive: *interactive-functions*
  717. browse() put up a file requester
  718. browsedir() put up a directory requester
  719. confirm() let the user make a choice
  720. getchar() get a character from the user
  721. getcharmod() get modifiers for the last typed character
  722. feedkeys() put characters in the typeahead queue
  723. input() get a line from the user
  724. inputlist() let the user pick an entry from a list
  725. inputsecret() get a line from the user without showing it
  726. inputdialog() get a line from the user in a dialog
  727. inputsave() save and clear typeahead
  728. inputrestore() restore typeahead
  729. GUI: *gui-functions*
  730. getfontname() get name of current font being used
  731. getwinpos() position of the Vim window
  732. getwinposx() X position of the Vim window
  733. getwinposy() Y position of the Vim window
  734. balloon_show() set the balloon content
  735. balloon_split() split a message for a balloon
  736. balloon_gettext() get the text in the balloon
  737. Vim server: *server-functions*
  738. serverlist() return the list of server names
  739. remote_startserver() run a server
  740. remote_send() send command characters to a Vim server
  741. remote_expr() evaluate an expression in a Vim server
  742. server2client() send a reply to a client of a Vim server
  743. remote_peek() check if there is a reply from a Vim server
  744. remote_read() read a reply from a Vim server
  745. foreground() move the Vim window to the foreground
  746. remote_foreground() move the Vim server window to the foreground
  747. Window size and position: *window-size-functions*
  748. winheight() get height of a specific window
  749. winwidth() get width of a specific window
  750. win_screenpos() get screen position of a window
  751. winlayout() get layout of windows in a tab page
  752. winrestcmd() return command to restore window sizes
  753. winsaveview() get view of current window
  754. winrestview() restore saved view of current window
  755. Mappings: *mapping-functions*
  756. hasmapto() check if a mapping exists
  757. mapcheck() check if a matching mapping exists
  758. maparg() get rhs of a mapping
  759. wildmenumode() check if the wildmode is active
  760. Signs: *sign-functions*
  761. sign_define() define or update a sign
  762. sign_getdefined() get a list of defined signs
  763. sign_getplaced() get a list of placed signs
  764. sign_jump() jump to a sign
  765. sign_place() place a sign
  766. sign_undefine() undefine a sign
  767. sign_unplace() unplace a sign
  768. Testing: *test-functions*
  769. assert_equal() assert that two expressions values are equal
  770. assert_equalfile() assert that two file contents are equal
  771. assert_notequal() assert that two expressions values are not equal
  772. assert_inrange() assert that an expression is inside a range
  773. assert_match() assert that a pattern matches the value
  774. assert_notmatch() assert that a pattern does not match the value
  775. assert_false() assert that an expression is false
  776. assert_true() assert that an expression is true
  777. assert_exception() assert that a command throws an exception
  778. assert_beeps() assert that a command beeps
  779. assert_fails() assert that a command fails
  780. Timers: *timer-functions*
  781. timer_start() create a timer
  782. timer_pause() pause or unpause a timer
  783. timer_stop() stop a timer
  784. timer_stopall() stop all timers
  785. timer_info() get information about timers
  786. wait() wait for a condition
  787. Tags: *tag-functions*
  788. taglist() get list of matching tags
  789. tagfiles() get a list of tags files
  790. gettagstack() get the tag stack of a window
  791. settagstack() modify the tag stack of a window
  792. Prompt Buffer: *promptbuffer-functions*
  793. prompt_setcallback() set prompt callback for a buffer
  794. prompt_setinterrupt() set interrupt callback for a buffer
  795. prompt_setprompt() set the prompt text for a buffer
  796. Context Stack: *ctx-functions*
  797. ctxget() return context at given index from top
  798. ctxpop() pop and restore top context
  799. ctxpush() push given context
  800. ctxset() set context at given index from top
  801. ctxsize() return context stack size
  802. Various: *various-functions*
  803. mode() get current editing mode
  804. visualmode() last visual mode used
  805. exists() check if a variable, function, etc. exists
  806. has() check if a feature is supported in Vim
  807. changenr() return number of most recent change
  808. cscope_connection() check if a cscope connection exists
  809. did_filetype() check if a FileType autocommand was used
  810. eventhandler() check if invoked by an event handler
  811. getpid() get process ID of Vim
  812. libcall() call a function in an external library
  813. libcallnr() idem, returning a number
  814. undofile() get the name of the undo file
  815. undotree() return the state of the undo tree
  816. getreg() get contents of a register
  817. getregtype() get type of a register
  818. setreg() set contents and type of a register
  819. reg_executing() return the name of the register being executed
  820. reg_recording() return the name of the register being recorded
  821. shiftwidth() effective value of 'shiftwidth'
  822. wordcount() get byte/word/char count of buffer
  823. luaeval() evaluate Lua expression
  824. py3eval() evaluate Python expression (|+python3|)
  825. pyeval() evaluate Python expression (|+python|)
  826. pyxeval() evaluate |python_x| expression
  827. debugbreak() interrupt a program being debugged
  828. ==============================================================================
  829. *41.7* Defining a function
  830. Vim enables you to define your own functions. The basic function declaration
  831. begins as follows: >
  832. :function {name}({var1}, {var2}, ...)
  833. : {body}
  834. :endfunction
  835. <
  836. Note:
  837. Function names must begin with a capital letter.
  838. Let's define a short function to return the smaller of two numbers. It starts
  839. with this line: >
  840. :function Min(num1, num2)
  841. This tells Vim that the function is named "Min" and it takes two arguments:
  842. "num1" and "num2".
  843. The first thing you need to do is to check to see which number is smaller:
  844. >
  845. : if a:num1 < a:num2
  846. The special prefix "a:" tells Vim that the variable is a function argument.
  847. Let's assign the variable "smaller" the value of the smallest number: >
  848. : if a:num1 < a:num2
  849. : let smaller = a:num1
  850. : else
  851. : let smaller = a:num2
  852. : endif
  853. The variable "smaller" is a local variable. Variables used inside a function
  854. are local unless prefixed by something like "g:", "a:", or "s:".
  855. Note:
  856. To access a global variable from inside a function you must prepend
  857. "g:" to it. Thus "g:today" inside a function is used for the global
  858. variable "today", and "today" is another variable, local to the
  859. function.
  860. You now use the ":return" statement to return the smallest number to the user.
  861. Finally, you end the function: >
  862. : return smaller
  863. :endfunction
  864. The complete function definition is as follows: >
  865. :function Min(num1, num2)
  866. : if a:num1 < a:num2
  867. : let smaller = a:num1
  868. : else
  869. : let smaller = a:num2
  870. : endif
  871. : return smaller
  872. :endfunction
  873. For people who like short functions, this does the same thing: >
  874. :function Min(num1, num2)
  875. : if a:num1 < a:num2
  876. : return a:num1
  877. : endif
  878. : return a:num2
  879. :endfunction
  880. A user defined function is called in exactly the same way as a built-in
  881. function. Only the name is different. The Min function can be used like
  882. this: >
  883. :echo Min(5, 8)
  884. Only now will the function be executed and the lines be interpreted by Vim.
  885. If there are mistakes, like using an undefined variable or function, you will
  886. now get an error message. When defining the function these errors are not
  887. detected.
  888. When a function reaches ":endfunction" or ":return" is used without an
  889. argument, the function returns zero.
  890. To redefine a function that already exists, use the ! for the ":function"
  891. command: >
  892. :function! Min(num1, num2, num3)
  893. USING A RANGE
  894. The ":call" command can be given a line range. This can have one of two
  895. meanings. When a function has been defined with the "range" keyword, it will
  896. take care of the line range itself.
  897. The function will be passed the variables "a:firstline" and "a:lastline".
  898. These will have the line numbers from the range the function was called with.
  899. Example: >
  900. :function Count_words() range
  901. : let lnum = a:firstline
  902. : let n = 0
  903. : while lnum <= a:lastline
  904. : let n = n + len(split(getline(lnum)))
  905. : let lnum = lnum + 1
  906. : endwhile
  907. : echo "found " . n . " words"
  908. :endfunction
  909. You can call this function with: >
  910. :10,30call Count_words()
  911. It will be executed once and echo the number of words.
  912. The other way to use a line range is by defining a function without the
  913. "range" keyword. The function will be called once for every line in the
  914. range, with the cursor in that line. Example: >
  915. :function Number()
  916. : echo "line " . line(".") . " contains: " . getline(".")
  917. :endfunction
  918. If you call this function with: >
  919. :10,15call Number()
  920. The function will be called six times.
  921. VARIABLE NUMBER OF ARGUMENTS
  922. Vim enables you to define functions that have a variable number of arguments.
  923. The following command, for instance, defines a function that must have 1
  924. argument (start) and can have up to 20 additional arguments: >
  925. :function Show(start, ...)
  926. The variable "a:1" contains the first optional argument, "a:2" the second, and
  927. so on. The variable "a:0" contains the number of extra arguments.
  928. For example: >
  929. :function Show(start, ...)
  930. : echohl Title
  931. : echo "start is " . a:start
  932. : echohl None
  933. : let index = 1
  934. : while index <= a:0
  935. : echo " Arg " . index . " is " . a:{index}
  936. : let index = index + 1
  937. : endwhile
  938. : echo ""
  939. :endfunction
  940. This uses the ":echohl" command to specify the highlighting used for the
  941. following ":echo" command. ":echohl None" stops it again. The ":echon"
  942. command works like ":echo", but doesn't output a line break.
  943. You can also use the a:000 variable, it is a List of all the "..." arguments.
  944. See |a:000|.
  945. LISTING FUNCTIONS
  946. The ":function" command lists the names and arguments of all user-defined
  947. functions: >
  948. :function
  949. < function Show(start, ...) ~
  950. function GetVimIndent() ~
  951. function SetSyn(name) ~
  952. To see what a function does, use its name as an argument for ":function": >
  953. :function SetSyn
  954. < 1 if &syntax == '' ~
  955. 2 let &syntax = a:name ~
  956. 3 endif ~
  957. endfunction ~
  958. DEBUGGING
  959. The line number is useful for when you get an error message or when debugging.
  960. See |debug-scripts| about debugging mode.
  961. You can also set the 'verbose' option to 12 or higher to see all function
  962. calls. Set it to 15 or higher to see every executed line.
  963. DELETING A FUNCTION
  964. To delete the Show() function: >
  965. :delfunction Show
  966. You get an error when the function doesn't exist.
  967. FUNCTION REFERENCES
  968. Sometimes it can be useful to have a variable point to one function or
  969. another. You can do it with the function() function. It turns the name of a
  970. function into a reference: >
  971. :let result = 0 " or 1
  972. :function! Right()
  973. : return 'Right!'
  974. :endfunc
  975. :function! Wrong()
  976. : return 'Wrong!'
  977. :endfunc
  978. :
  979. :if result == 1
  980. : let Afunc = function('Right')
  981. :else
  982. : let Afunc = function('Wrong')
  983. :endif
  984. :echo call(Afunc, [])
  985. < Wrong! ~
  986. Note that the name of a variable that holds a function reference must start
  987. with a capital. Otherwise it could be confused with the name of a builtin
  988. function.
  989. The way to invoke a function that a variable refers to is with the call()
  990. function. Its first argument is the function reference, the second argument
  991. is a List with arguments.
  992. Function references are most useful in combination with a Dictionary, as is
  993. explained in the next section.
  994. ==============================================================================
  995. *41.8* Lists and Dictionaries
  996. So far we have used the basic types String and Number. Vim also supports two
  997. composite types: List and Dictionary.
  998. A List is an ordered sequence of things. The things can be any kind of value,
  999. thus you can make a List of numbers, a List of Lists and even a List of mixed
  1000. items. To create a List with three strings: >
  1001. :let alist = ['aap', 'mies', 'noot']
  1002. The List items are enclosed in square brackets and separated by commas. To
  1003. create an empty List: >
  1004. :let alist = []
  1005. You can add items to a List with the add() function: >
  1006. :let alist = []
  1007. :call add(alist, 'foo')
  1008. :call add(alist, 'bar')
  1009. :echo alist
  1010. < ['foo', 'bar'] ~
  1011. List concatenation is done with +: >
  1012. :echo alist + ['foo', 'bar']
  1013. < ['foo', 'bar', 'foo', 'bar'] ~
  1014. Or, if you want to extend a List directly: >
  1015. :let alist = ['one']
  1016. :call extend(alist, ['two', 'three'])
  1017. :echo alist
  1018. < ['one', 'two', 'three'] ~
  1019. Notice that using add() will have a different effect: >
  1020. :let alist = ['one']
  1021. :call add(alist, ['two', 'three'])
  1022. :echo alist
  1023. < ['one', ['two', 'three']] ~
  1024. The second argument of add() is added as a single item.
  1025. FOR LOOP
  1026. One of the nice things you can do with a List is iterate over it: >
  1027. :let alist = ['one', 'two', 'three']
  1028. :for n in alist
  1029. : echo n
  1030. :endfor
  1031. < one ~
  1032. two ~
  1033. three ~
  1034. This will loop over each element in List "alist", assigning the value to
  1035. variable "n". The generic form of a for loop is: >
  1036. :for {varname} in {listexpression}
  1037. : {commands}
  1038. :endfor
  1039. To loop a certain number of times you need a List of a specific length. The
  1040. range() function creates one for you: >
  1041. :for a in range(3)
  1042. : echo a
  1043. :endfor
  1044. < 0 ~
  1045. 1 ~
  1046. 2 ~
  1047. Notice that the first item of the List that range() produces is zero, thus the
  1048. last item is one less than the length of the list.
  1049. You can also specify the maximum value, the stride and even go backwards: >
  1050. :for a in range(8, 4, -2)
  1051. : echo a
  1052. :endfor
  1053. < 8 ~
  1054. 6 ~
  1055. 4 ~
  1056. A more useful example, looping over lines in the buffer: >
  1057. :for line in getline(1, 20)
  1058. : if line =~ "Date: "
  1059. : echo matchstr(line, 'Date: \zs.*')
  1060. : endif
  1061. :endfor
  1062. This looks into lines 1 to 20 (inclusive) and echoes any date found in there.
  1063. DICTIONARIES
  1064. A Dictionary stores key-value pairs. You can quickly lookup a value if you
  1065. know the key. A Dictionary is created with curly braces: >
  1066. :let uk2nl = {'one': 'een', 'two': 'twee', 'three': 'drie'}
  1067. Now you can lookup words by putting the key in square brackets: >
  1068. :echo uk2nl['two']
  1069. < twee ~
  1070. The generic form for defining a Dictionary is: >
  1071. {<key> : <value>, ...}
  1072. An empty Dictionary is one without any keys: >
  1073. {}
  1074. The possibilities with Dictionaries are numerous. There are various functions
  1075. for them as well. For example, you can obtain a list of the keys and loop
  1076. over them: >
  1077. :for key in keys(uk2nl)
  1078. : echo key
  1079. :endfor
  1080. < three ~
  1081. one ~
  1082. two ~
  1083. You will notice the keys are not ordered. You can sort the list to get a
  1084. specific order: >
  1085. :for key in sort(keys(uk2nl))
  1086. : echo key
  1087. :endfor
  1088. < one ~
  1089. three ~
  1090. two ~
  1091. But you can never get back the order in which items are defined. For that you
  1092. need to use a List, it stores items in an ordered sequence.
  1093. DICTIONARY FUNCTIONS
  1094. The items in a Dictionary can normally be obtained with an index in square
  1095. brackets: >
  1096. :echo uk2nl['one']
  1097. < een ~
  1098. A method that does the same, but without so many punctuation characters: >
  1099. :echo uk2nl.one
  1100. < een ~
  1101. This only works for a key that is made of ASCII letters, digits and the
  1102. underscore. You can also assign a new value this way: >
  1103. :let uk2nl.four = 'vier'
  1104. :echo uk2nl
  1105. < {'three': 'drie', 'four': 'vier', 'one': 'een', 'two': 'twee'} ~
  1106. And now for something special: you can directly define a function and store a
  1107. reference to it in the dictionary: >
  1108. :function uk2nl.translate(line) dict
  1109. : return join(map(split(a:line), 'get(self, v:val, "???")'))
  1110. :endfunction
  1111. Let's first try it out: >
  1112. :echo uk2nl.translate('three two five one')
  1113. < drie twee ??? een ~
  1114. The first special thing you notice is the "dict" at the end of the ":function"
  1115. line. This marks the function as being used from a Dictionary. The "self"
  1116. local variable will then refer to that Dictionary.
  1117. Now let's break up the complicated return command: >
  1118. split(a:line)
  1119. The split() function takes a string, chops it into whitespace separated words
  1120. and returns a list with these words. Thus in the example it returns: >
  1121. :echo split('three two five one')
  1122. < ['three', 'two', 'five', 'one'] ~
  1123. This list is the first argument to the map() function. This will go through
  1124. the list, evaluating its second argument with "v:val" set to the value of each
  1125. item. This is a shortcut to using a for loop. This command: >
  1126. :let alist = map(split(a:line), 'get(self, v:val, "???")')
  1127. Is equivalent to: >
  1128. :let alist = split(a:line)
  1129. :for idx in range(len(alist))
  1130. : let alist[idx] = get(self, alist[idx], "???")
  1131. :endfor
  1132. The get() function checks if a key is present in a Dictionary. If it is, then
  1133. the value is retrieved. If it isn't, then the default value is returned, in
  1134. the example it's '???'. This is a convenient way to handle situations where a
  1135. key may not be present and you don't want an error message.
  1136. The join() function does the opposite of split(): it joins together a list of
  1137. words, putting a space in between.
  1138. This combination of split(), map() and join() is a nice way to filter a line
  1139. of words in a very compact way.
  1140. OBJECT ORIENTED PROGRAMMING
  1141. Now that you can put both values and functions in a Dictionary, you can
  1142. actually use a Dictionary like an object.
  1143. Above we used a Dictionary for translating Dutch to English. We might want
  1144. to do the same for other languages. Let's first make an object (aka
  1145. Dictionary) that has the translate function, but no words to translate: >
  1146. :let transdict = {}
  1147. :function transdict.translate(line) dict
  1148. : return join(map(split(a:line), 'get(self.words, v:val, "???")'))
  1149. :endfunction
  1150. It's slightly different from the function above, using 'self.words' to lookup
  1151. word translations. But we don't have a self.words. Thus you could call this
  1152. an abstract class.
  1153. Now we can instantiate a Dutch translation object: >
  1154. :let uk2nl = copy(transdict)
  1155. :let uk2nl.words = {'one': 'een', 'two': 'twee', 'three': 'drie'}
  1156. :echo uk2nl.translate('three one')
  1157. < drie een ~
  1158. And a German translator: >
  1159. :let uk2de = copy(transdict)
  1160. :let uk2de.words = {'one': 'eins', 'two': 'zwei', 'three': 'drei'}
  1161. :echo uk2de.translate('three one')
  1162. < drei eins ~
  1163. You see that the copy() function is used to make a copy of the "transdict"
  1164. Dictionary and then the copy is changed to add the words. The original
  1165. remains the same, of course.
  1166. Now you can go one step further, and use your preferred translator: >
  1167. :if $LANG =~ "de"
  1168. : let trans = uk2de
  1169. :else
  1170. : let trans = uk2nl
  1171. :endif
  1172. :echo trans.translate('one two three')
  1173. < een twee drie ~
  1174. Here "trans" refers to one of the two objects (Dictionaries). No copy is
  1175. made. More about List and Dictionary identity can be found at |list-identity|
  1176. and |dict-identity|.
  1177. Now you might use a language that isn't supported. You can overrule the
  1178. translate() function to do nothing: >
  1179. :let uk2uk = copy(transdict)
  1180. :function! uk2uk.translate(line)
  1181. : return a:line
  1182. :endfunction
  1183. :echo uk2uk.translate('three one wladiwostok')
  1184. < three one wladiwostok ~
  1185. Notice that a ! was used to overwrite the existing function reference. Now
  1186. use "uk2uk" when no recognized language is found: >
  1187. :if $LANG =~ "de"
  1188. : let trans = uk2de
  1189. :elseif $LANG =~ "nl"
  1190. : let trans = uk2nl
  1191. :else
  1192. : let trans = uk2uk
  1193. :endif
  1194. :echo trans.translate('one two three')
  1195. < one two three ~
  1196. For further reading see |Lists| and |Dictionaries|.
  1197. ==============================================================================
  1198. *41.9* Exceptions
  1199. Let's start with an example: >
  1200. :try
  1201. : read ~/templates/pascal.tmpl
  1202. :catch /E484:/
  1203. : echo "Sorry, the Pascal template file cannot be found."
  1204. :endtry
  1205. The ":read" command will fail if the file does not exist. Instead of
  1206. generating an error message, this code catches the error and gives the user a
  1207. nice message.
  1208. For the commands in between ":try" and ":endtry" errors are turned into
  1209. exceptions. An exception is a string. In the case of an error the string
  1210. contains the error message. And every error message has a number. In this
  1211. case, the error we catch contains "E484:". This number is guaranteed to stay
  1212. the same (the text may change, e.g., it may be translated).
  1213. When the ":read" command causes another error, the pattern "E484:" will not
  1214. match in it. Thus this exception will not be caught and result in the usual
  1215. error message.
  1216. You might be tempted to do this: >
  1217. :try
  1218. : read ~/templates/pascal.tmpl
  1219. :catch
  1220. : echo "Sorry, the Pascal template file cannot be found."
  1221. :endtry
  1222. This means all errors are caught. But then you will not see errors that are
  1223. useful, such as "E21: Cannot make changes, 'modifiable' is off".
  1224. Another useful mechanism is the ":finally" command: >
  1225. :let tmp = tempname()
  1226. :try
  1227. : exe ".,$write " . tmp
  1228. : exe "!filter " . tmp
  1229. : .,$delete
  1230. : exe "$read " . tmp
  1231. :finally
  1232. : call delete(tmp)
  1233. :endtry
  1234. This filters the lines from the cursor until the end of the file through the
  1235. "filter" command, which takes a file name argument. No matter if the
  1236. filtering works, something goes wrong in between ":try" and ":finally" or the
  1237. user cancels the filtering by pressing CTRL-C, the "call delete(tmp)" is
  1238. always executed. This makes sure you don't leave the temporary file behind.
  1239. More information about exception handling can be found in the reference
  1240. manual: |exception-handling|.
  1241. ==============================================================================
  1242. *41.10* Various remarks
  1243. Here is a summary of items that apply to Vim scripts. They are also mentioned
  1244. elsewhere, but form a nice checklist.
  1245. The end-of-line character depends on the system. For Unix a single <NL>
  1246. character is used. For Windows <CR><LF> is used. This is important when
  1247. using mappings that end in a <CR>. See |:source_crnl|.
  1248. WHITE SPACE
  1249. Blank lines are allowed and ignored.
  1250. Leading whitespace characters (blanks and TABs) are always ignored. The
  1251. whitespaces between parameters (e.g. between the "set" and the "cpoptions" in
  1252. the example below) are reduced to one blank character and plays the role of a
  1253. separator, the whitespaces after the last (visible) character may or may not
  1254. be ignored depending on the situation, see below.
  1255. For a ":set" command involving the "=" (equal) sign, such as in: >
  1256. :set cpoptions =aABceFst
  1257. the whitespace immediately before the "=" sign is ignored. But there can be
  1258. no whitespace after the "=" sign!
  1259. To include a whitespace character in the value of an option, it must be
  1260. escaped by a "\" (backslash) as in the following example: >
  1261. :set tags=my\ nice\ file
  1262. The same example written as: >
  1263. :set tags=my nice file
  1264. will issue an error, because it is interpreted as: >
  1265. :set tags=my
  1266. :set nice
  1267. :set file
  1268. COMMENTS
  1269. The character " (the double quote mark) starts a comment. Everything after
  1270. and including this character until the end-of-line is considered a comment and
  1271. is ignored, except for commands that don't consider comments, as shown in
  1272. examples below. A comment can start on any character position on the line.
  1273. There is a little "catch" with comments for some commands. Examples: >
  1274. :abbrev dev development " shorthand
  1275. :map <F3> o#include " insert include
  1276. :execute cmd " do it
  1277. :!ls *.c " list C files
  1278. The abbreviation 'dev' will be expanded to 'development " shorthand'. The
  1279. mapping of <F3> will actually be the whole line after the 'o# ....' including
  1280. the '" insert include'. The "execute" command will give an error. The "!"
  1281. command will send everything after it to the shell, causing an error for an
  1282. unmatched '"' character.
  1283. There can be no comment after ":map", ":abbreviate", ":execute" and "!"
  1284. commands (there are a few more commands with this restriction). For the
  1285. ":map", ":abbreviate" and ":execute" commands there is a trick: >
  1286. :abbrev dev development|" shorthand
  1287. :map <F3> o#include|" insert include
  1288. :execute cmd |" do it
  1289. With the '|' character the command is separated from the next one. And that
  1290. next command is only a comment. For the last command you need to do two
  1291. things: |:execute| and use '|': >
  1292. :exe '!ls *.c' |" list C files
  1293. Notice that there is no white space before the '|' in the abbreviation and
  1294. mapping. For these commands, any character until the end-of-line or '|' is
  1295. included. As a consequence of this behavior, you don't always see that
  1296. trailing whitespace is included: >
  1297. :map <F4> o#include
  1298. To spot these problems, you can set the 'list' option when editing vimrc
  1299. files.
  1300. For Unix there is one special way to comment a line, that allows making a Vim
  1301. script executable: >
  1302. #!/usr/bin/env vim -S
  1303. echo "this is a Vim script"
  1304. quit
  1305. The "#" command by itself lists a line with the line number. Adding an
  1306. exclamation mark changes it into doing nothing, so that you can add the shell
  1307. command to execute the rest of the file. |:#!| |-S|
  1308. PITFALLS
  1309. Even bigger problem arises in the following example: >
  1310. :map ,ab o#include
  1311. :unmap ,ab
  1312. Here the unmap command will not work, because it tries to unmap ",ab ". This
  1313. does not exist as a mapped sequence. An error will be issued, which is very
  1314. hard to identify, because the ending whitespace character in ":unmap ,ab " is
  1315. not visible.
  1316. And this is the same as what happens when one uses a comment after an 'unmap'
  1317. command: >
  1318. :unmap ,ab " comment
  1319. Here the comment part will be ignored. However, Vim will try to unmap
  1320. ',ab ', which does not exist. Rewrite it as: >
  1321. :unmap ,ab| " comment
  1322. RESTORING THE VIEW
  1323. Sometimes you want to make a change and go back to where the cursor was.
  1324. Restoring the relative position would also be nice, so that the same line
  1325. appears at the top of the window.
  1326. This example yanks the current line, puts it above the first line in the
  1327. file and then restores the view: >
  1328. map ,p ma"aYHmbgg"aP`bzt`a
  1329. What this does: >
  1330. ma"aYHmbgg"aP`bzt`a
  1331. < ma set mark a at cursor position
  1332. "aY yank current line into register a
  1333. Hmb go to top line in window and set mark b there
  1334. gg go to first line in file
  1335. "aP put the yanked line above it
  1336. `b go back to top line in display
  1337. zt position the text in the window as before
  1338. `a go back to saved cursor position
  1339. PACKAGING
  1340. To avoid your function names to interfere with functions that you get from
  1341. others, use this scheme:
  1342. - Prepend a unique string before each function name. I often use an
  1343. abbreviation. For example, "OW_" is used for the option window functions.
  1344. - Put the definition of your functions together in a file. Set a global
  1345. variable to indicate that the functions have been loaded. When sourcing the
  1346. file again, first unload the functions.
  1347. Example: >
  1348. " This is the XXX package
  1349. if exists("XXX_loaded")
  1350. delfun XXX_one
  1351. delfun XXX_two
  1352. endif
  1353. function XXX_one(a)
  1354. ... body of function ...
  1355. endfun
  1356. function XXX_two(b)
  1357. ... body of function ...
  1358. endfun
  1359. let XXX_loaded = 1
  1360. ==============================================================================
  1361. *41.11* Writing a plugin *write-plugin*
  1362. You can write a Vim script in such a way that many people can use it. This is
  1363. called a plugin. Vim users can drop your script in their plugin directory and
  1364. use its features right away |add-plugin|.
  1365. There are actually two types of plugins:
  1366. global plugins: For all types of files.
  1367. filetype plugins: Only for files of a specific type.
  1368. In this section the first type is explained. Most items are also relevant for
  1369. writing filetype plugins. The specifics for filetype plugins are in the next
  1370. section |write-filetype-plugin|.
  1371. NAME
  1372. First of all you must choose a name for your plugin. The features provided
  1373. by the plugin should be clear from its name. And it should be unlikely that
  1374. someone else writes a plugin with the same name but which does something
  1375. different. And please limit the name to 8 characters, to avoid problems on
  1376. old Windows systems.
  1377. A script that corrects typing mistakes could be called "typecorr.vim". We
  1378. will use it here as an example.
  1379. For the plugin to work for everybody, it should follow a few guidelines. This
  1380. will be explained step-by-step. The complete example plugin is at the end.
  1381. BODY
  1382. Let's start with the body of the plugin, the lines that do the actual work: >
  1383. 14 iabbrev teh the
  1384. 15 iabbrev otehr other
  1385. 16 iabbrev wnat want
  1386. 17 iabbrev synchronisation
  1387. 18 \ synchronization
  1388. 19 let s:count = 4
  1389. The actual list should be much longer, of course.
  1390. The line numbers have only been added to explain a few things, don't put them
  1391. in your plugin file!
  1392. HEADER
  1393. You will probably add new corrections to the plugin and soon have several
  1394. versions lying around. And when distributing this file, people will want to
  1395. know who wrote this wonderful plugin and where they can send remarks.
  1396. Therefore, put a header at the top of your plugin: >
  1397. 1 " Vim global plugin for correcting typing mistakes
  1398. 2 " Last Change: 2000 Oct 15
  1399. 3 " Maintainer: Bram Moolenaar <Bram@vim.org>
  1400. About copyright and licensing: Since plugins are very useful and it's hardly
  1401. worth restricting their distribution, please consider making your plugin
  1402. either public domain or use the Vim |license|. A short note about this near
  1403. the top of the plugin should be sufficient. Example: >
  1404. 4 " License: This file is placed in the public domain.
  1405. LINE CONTINUATION, AVOIDING SIDE EFFECTS *use-cpo-save*
  1406. In line 18 above, the line-continuation mechanism is used |line-continuation|.
  1407. Users with 'compatible' set will run into trouble here, they will get an error
  1408. message. We can't just reset 'compatible', because that has a lot of side
  1409. effects. To avoid this, we will set the 'cpoptions' option to its Vim default
  1410. value and restore it later. That will allow the use of line-continuation and
  1411. make the script work for most people. It is done like this: >
  1412. 11 let s:save_cpo = &cpo
  1413. 12 set cpo&vim
  1414. ..
  1415. 42 let &cpo = s:save_cpo
  1416. 43 unlet s:save_cpo
  1417. We first store the old value of 'cpoptions' in the s:save_cpo variable. At
  1418. the end of the plugin this value is restored.
  1419. Notice that a script-local variable is used |s:var|. A global variable could
  1420. already be in use for something else. Always use script-local variables for
  1421. things that are only used in the script.
  1422. NOT LOADING
  1423. It's possible that a user doesn't always want to load this plugin. Or the
  1424. system administrator has dropped it in the system-wide plugin directory, but a
  1425. user has his own plugin he wants to use. Then the user must have a chance to
  1426. disable loading this specific plugin. This will make it possible: >
  1427. 6 if exists("g:loaded_typecorr")
  1428. 7 finish
  1429. 8 endif
  1430. 9 let g:loaded_typecorr = 1
  1431. This also avoids that when the script is loaded twice it would cause error
  1432. messages for redefining functions and cause trouble for autocommands that are
  1433. added twice.
  1434. The name is recommended to start with "loaded_" and then the file name of the
  1435. plugin, literally. The "g:" is prepended just to avoid mistakes when using
  1436. the variable in a function (without "g:" it would be a variable local to the
  1437. function).
  1438. Using "finish" stops Vim from reading the rest of the file, it's much quicker
  1439. than using if-endif around the whole file.
  1440. MAPPING
  1441. Now let's make the plugin more interesting: We will add a mapping that adds a
  1442. correction for the word under the cursor. We could just pick a key sequence
  1443. for this mapping, but the user might already use it for something else. To
  1444. allow the user to define which keys a mapping in a plugin uses, the <Leader>
  1445. item can be used: >
  1446. 22 map <unique> <Leader>a <Plug>TypecorrAdd
  1447. The "<Plug>TypecorrAdd" thing will do the work, more about that further on.
  1448. The user can set the "mapleader" variable to the key sequence that he wants
  1449. this mapping to start with. Thus if the user has done: >
  1450. let mapleader = "_"
  1451. the mapping will define "_a". If the user didn't do this, the default value
  1452. will be used, which is a backslash. Then a map for "\a" will be defined.
  1453. Note that <unique> is used, this will cause an error message if the mapping
  1454. already happened to exist. |:map-<unique>|
  1455. But what if the user wants to define his own key sequence? We can allow that
  1456. with this mechanism: >
  1457. 21 if !hasmapto('<Plug>TypecorrAdd')
  1458. 22 map <unique> <Leader>a <Plug>TypecorrAdd
  1459. 23 endif
  1460. This checks if a mapping to "<Plug>TypecorrAdd" already exists, and only
  1461. defines the mapping from "<Leader>a" if it doesn't. The user then has a
  1462. chance of putting this in his vimrc file: >
  1463. map ,c <Plug>TypecorrAdd
  1464. Then the mapped key sequence will be ",c" instead of "_a" or "\a".
  1465. PIECES
  1466. If a script gets longer, you often want to break up the work in pieces. You
  1467. can use functions or mappings for this. But you don't want these functions
  1468. and mappings to interfere with the ones from other scripts. For example, you
  1469. could define a function Add(), but another script could try to define the same
  1470. function. To avoid this, we define the function local to the script by
  1471. prepending it with "s:".
  1472. We will define a function that adds a new typing correction: >
  1473. 30 function s:Add(from, correct)
  1474. 31 let to = input("type the correction for " . a:from . ": ")
  1475. 32 exe ":iabbrev " . a:from . " " . to
  1476. ..
  1477. 36 endfunction
  1478. Now we can call the function s:Add() from within this script. If another
  1479. script also defines s:Add(), it will be local to that script and can only
  1480. be called from the script it was defined in. There can also be a global Add()
  1481. function (without the "s:"), which is again another function.
  1482. <SID> can be used with mappings. It generates a script ID, which identifies
  1483. the current script. In our typing correction plugin we use it like this: >
  1484. 24 noremap <unique> <script> <Plug>TypecorrAdd <SID>Add
  1485. ..
  1486. 28 noremap <SID>Add :call <SID>Add(expand("<cword>"), 1)<CR>
  1487. Thus when a user types "\a", this sequence is invoked: >
  1488. \a -> <Plug>TypecorrAdd -> <SID>Add -> :call <SID>Add()
  1489. If another script would also map <SID>Add, it would get another script ID and
  1490. thus define another mapping.
  1491. Note that instead of s:Add() we use <SID>Add() here. That is because the
  1492. mapping is typed by the user, thus outside of the script. The <SID> is
  1493. translated to the script ID, so that Vim knows in which script to look for
  1494. the Add() function.
  1495. This is a bit complicated, but it's required for the plugin to work together
  1496. with other plugins. The basic rule is that you use <SID>Add() in mappings and
  1497. s:Add() in other places (the script itself, autocommands, user commands).
  1498. We can also add a menu entry to do the same as the mapping: >
  1499. 26 noremenu <script> Plugin.Add\ Correction <SID>Add
  1500. The "Plugin" menu is recommended for adding menu items for plugins. In this
  1501. case only one item is used. When adding more items, creating a submenu is
  1502. recommended. For example, "Plugin.CVS" could be used for a plugin that offers
  1503. CVS operations "Plugin.CVS.checkin", "Plugin.CVS.checkout", etc.
  1504. Note that in line 28 ":noremap" is used to avoid that any other mappings cause
  1505. trouble. Someone may have remapped ":call", for example. In line 24 we also
  1506. use ":noremap", but we do want "<SID>Add" to be remapped. This is why
  1507. "<script>" is used here. This only allows mappings which are local to the
  1508. script. |:map-<script>| The same is done in line 26 for ":noremenu".
  1509. |:menu-<script>|
  1510. <SID> AND <Plug> *using-<Plug>*
  1511. Both <SID> and <Plug> are used to avoid that mappings of typed keys interfere
  1512. with mappings that are only to be used from other mappings. Note the
  1513. difference between using <SID> and <Plug>:
  1514. <Plug> is visible outside of the script. It is used for mappings which the
  1515. user might want to map a key sequence to. <Plug> is a special code
  1516. that a typed key will never produce.
  1517. To make it very unlikely that other plugins use the same sequence of
  1518. characters, use this structure: <Plug> scriptname mapname
  1519. In our example the scriptname is "Typecorr" and the mapname is "Add".
  1520. This results in "<Plug>TypecorrAdd". Only the first character of
  1521. scriptname and mapname is uppercase, so that we can see where mapname
  1522. starts.
  1523. <SID> is the script ID, a unique identifier for a script.
  1524. Internally Vim translates <SID> to "<SNR>123_", where "123" can be any
  1525. number. Thus a function "<SID>Add()" will have a name "<SNR>11_Add()"
  1526. in one script, and "<SNR>22_Add()" in another. You can see this if
  1527. you use the ":function" command to get a list of functions. The
  1528. translation of <SID> in mappings is exactly the same, that's how you
  1529. can call a script-local function from a mapping.
  1530. USER COMMAND
  1531. Now let's add a user command to add a correction: >
  1532. 38 if !exists(":Correct")
  1533. 39 command -nargs=1 Correct :call s:Add(<q-args>, 0)
  1534. 40 endif
  1535. The user command is defined only if no command with the same name already
  1536. exists. Otherwise we would get an error here. Overriding the existing user
  1537. command with ":command!" is not a good idea, this would probably make the user
  1538. wonder why the command he defined himself doesn't work. |:command|
  1539. SCRIPT VARIABLES
  1540. When a variable starts with "s:" it is a script variable. It can only be used
  1541. inside a script. Outside the script it's not visible. This avoids trouble
  1542. with using the same variable name in different scripts. The variables will be
  1543. kept as long as Vim is running. And the same variables are used when sourcing
  1544. the same script again. |s:var|
  1545. The fun is that these variables can also be used in functions, autocommands
  1546. and user commands that are defined in the script. In our example we can add
  1547. a few lines to count the number of corrections: >
  1548. 19 let s:count = 4
  1549. ..
  1550. 30 function s:Add(from, correct)
  1551. ..
  1552. 34 let s:count = s:count + 1
  1553. 35 echo s:count . " corrections now"
  1554. 36 endfunction
  1555. First s:count is initialized to 4 in the script itself. When later the
  1556. s:Add() function is called, it increments s:count. It doesn't matter from
  1557. where the function was called, since it has been defined in the script, it
  1558. will use the local variables from this script.
  1559. THE RESULT
  1560. Here is the resulting complete example: >
  1561. 1 " Vim global plugin for correcting typing mistakes
  1562. 2 " Last Change: 2000 Oct 15
  1563. 3 " Maintainer: Bram Moolenaar <Bram@vim.org>
  1564. 4 " License: This file is placed in the public domain.
  1565. 5
  1566. 6 if exists("g:loaded_typecorr")
  1567. 7 finish
  1568. 8 endif
  1569. 9 let g:loaded_typecorr = 1
  1570. 10
  1571. 11 let s:save_cpo = &cpo
  1572. 12 set cpo&vim
  1573. 13
  1574. 14 iabbrev teh the
  1575. 15 iabbrev otehr other
  1576. 16 iabbrev wnat want
  1577. 17 iabbrev synchronisation
  1578. 18 \ synchronization
  1579. 19 let s:count = 4
  1580. 20
  1581. 21 if !hasmapto('<Plug>TypecorrAdd')
  1582. 22 map <unique> <Leader>a <Plug>TypecorrAdd
  1583. 23 endif
  1584. 24 noremap <unique> <script> <Plug>TypecorrAdd <SID>Add
  1585. 25
  1586. 26 noremenu <script> Plugin.Add\ Correction <SID>Add
  1587. 27
  1588. 28 noremap <SID>Add :call <SID>Add(expand("<cword>"), 1)<CR>
  1589. 29
  1590. 30 function s:Add(from, correct)
  1591. 31 let to = input("type the correction for " . a:from . ": ")
  1592. 32 exe ":iabbrev " . a:from . " " . to
  1593. 33 if a:correct | exe "normal viws\<C-R>\" \b\e" | endif
  1594. 34 let s:count = s:count + 1
  1595. 35 echo s:count . " corrections now"
  1596. 36 endfunction
  1597. 37
  1598. 38 if !exists(":Correct")
  1599. 39 command -nargs=1 Correct :call s:Add(<q-args>, 0)
  1600. 40 endif
  1601. 41
  1602. 42 let &cpo = s:save_cpo
  1603. 43 unlet s:save_cpo
  1604. Line 33 wasn't explained yet. It applies the new correction to the word under
  1605. the cursor. The |:normal| command is used to use the new abbreviation. Note
  1606. that mappings and abbreviations are expanded here, even though the function
  1607. was called from a mapping defined with ":noremap".
  1608. Using "unix" for the 'fileformat' option is recommended. The Vim scripts will
  1609. then work everywhere. Scripts with 'fileformat' set to "dos" do not work on
  1610. Unix. Also see |:source_crnl|. To be sure it is set right, do this before
  1611. writing the file: >
  1612. :set fileformat=unix
  1613. DOCUMENTATION *write-local-help*
  1614. It's a good idea to also write some documentation for your plugin. Especially
  1615. when its behavior can be changed by the user. See |add-local-help| for how
  1616. they are installed.
  1617. Here is a simple example for a plugin help file, called "typecorr.txt": >
  1618. 1 *typecorr.txt* Plugin for correcting typing mistakes
  1619. 2
  1620. 3 If you make typing mistakes, this plugin will have them corrected
  1621. 4 automatically.
  1622. 5
  1623. 6 There are currently only a few corrections. Add your own if you like.
  1624. 7
  1625. 8 Mappings:
  1626. 9 <Leader>a or <Plug>TypecorrAdd
  1627. 10 Add a correction for the word under the cursor.
  1628. 11
  1629. 12 Commands:
  1630. 13 :Correct {word}
  1631. 14 Add a correction for {word}.
  1632. 15
  1633. 16 *typecorr-settings*
  1634. 17 This plugin doesn't have any settings.
  1635. The first line is actually the only one for which the format matters. It will
  1636. be extracted from the help file to be put in the "LOCAL ADDITIONS:" section of
  1637. help.txt |local-additions|. The first "*" must be in the first column of the
  1638. first line. After adding your help file do ":help" and check that the entries
  1639. line up nicely.
  1640. You can add more tags inside ** in your help file. But be careful not to use
  1641. existing help tags. You would probably use the name of your plugin in most of
  1642. them, like "typecorr-settings" in the example.
  1643. Using references to other parts of the help in || is recommended. This makes
  1644. it easy for the user to find associated help.
  1645. FILETYPE DETECTION *plugin-filetype*
  1646. If your filetype is not already detected by Vim, you should create a filetype
  1647. detection snippet in a separate file. It is usually in the form of an
  1648. autocommand that sets the filetype when the file name matches a pattern.
  1649. Example: >
  1650. au BufNewFile,BufRead *.foo set filetype=foofoo
  1651. Write this single-line file as "ftdetect/foofoo.vim" in the first directory
  1652. that appears in 'runtimepath'. For Unix that would be
  1653. "~/.config/nvim/ftdetect/foofoo.vim". The convention is to use the name of
  1654. the filetype for the script name.
  1655. You can make more complicated checks if you like, for example to inspect the
  1656. contents of the file to recognize the language. Also see |new-filetype|.
  1657. SUMMARY *plugin-special*
  1658. Summary of special things to use in a plugin:
  1659. s:name Variables local to the script.
  1660. <SID> Script-ID, used for mappings and functions local to
  1661. the script.
  1662. hasmapto() Function to test if the user already defined a mapping
  1663. for functionality the script offers.
  1664. <Leader> Value of "mapleader", which the user defines as the
  1665. keys that plugin mappings start with.
  1666. :map <unique> Give a warning if a mapping already exists.
  1667. :noremap <script> Use only mappings local to the script, not global
  1668. mappings.
  1669. exists(":Cmd") Check if a user command already exists.
  1670. ==============================================================================
  1671. *41.12* Writing a filetype plugin *write-filetype-plugin* *ftplugin*
  1672. A filetype plugin is like a global plugin, except that it sets options and
  1673. defines mappings for the current buffer only. See |add-filetype-plugin| for
  1674. how this type of plugin is used.
  1675. First read the section on global plugins above |41.11|. All that is said there
  1676. also applies to filetype plugins. There are a few extras, which are explained
  1677. here. The essential thing is that a filetype plugin should only have an
  1678. effect on the current buffer.
  1679. DISABLING
  1680. If you are writing a filetype plugin to be used by many people, they need a
  1681. chance to disable loading it. Put this at the top of the plugin: >
  1682. " Only do this when not done yet for this buffer
  1683. if exists("b:did_ftplugin")
  1684. finish
  1685. endif
  1686. let b:did_ftplugin = 1
  1687. This also needs to be used to avoid that the same plugin is executed twice for
  1688. the same buffer (happens when using an ":edit" command without arguments).
  1689. Now users can disable loading the default plugin completely by making a
  1690. filetype plugin with only this line: >
  1691. let b:did_ftplugin = 1
  1692. This does require that the filetype plugin directory comes before $VIMRUNTIME
  1693. in 'runtimepath'!
  1694. If you do want to use the default plugin, but overrule one of the settings,
  1695. you can write the different setting in a script: >
  1696. setlocal textwidth=70
  1697. Now write this in the "after" directory, so that it gets sourced after the
  1698. distributed "vim.vim" ftplugin |after-directory|. For Unix this would be
  1699. "~/.config/nvim/after/ftplugin/vim.vim". Note that the default plugin will
  1700. have set "b:did_ftplugin", but it is ignored here.
  1701. OPTIONS
  1702. To make sure the filetype plugin only affects the current buffer use the >
  1703. :setlocal
  1704. command to set options. And only set options which are local to a buffer (see
  1705. the help for the option to check that). When using |:setlocal| for global
  1706. options or options local to a window, the value will change for many buffers,
  1707. and that is not what a filetype plugin should do.
  1708. When an option has a value that is a list of flags or items, consider using
  1709. "+=" and "-=" to keep the existing value. Be aware that the user may have
  1710. changed an option value already. First resetting to the default value and
  1711. then changing it is often a good idea. Example: >
  1712. :setlocal formatoptions& formatoptions+=ro
  1713. MAPPINGS
  1714. To make sure mappings will only work in the current buffer use the >
  1715. :map <buffer>
  1716. command. This needs to be combined with the two-step mapping explained above.
  1717. An example of how to define functionality in a filetype plugin: >
  1718. if !hasmapto('<Plug>JavaImport')
  1719. map <buffer> <unique> <LocalLeader>i <Plug>JavaImport
  1720. endif
  1721. noremap <buffer> <unique> <Plug>JavaImport oimport ""<Left><Esc>
  1722. |hasmapto()| is used to check if the user has already defined a map to
  1723. <Plug>JavaImport. If not, then the filetype plugin defines the default
  1724. mapping. This starts with |<LocalLeader>|, which allows the user to select
  1725. the key(s) he wants filetype plugin mappings to start with. The default is a
  1726. backslash.
  1727. "<unique>" is used to give an error message if the mapping already exists or
  1728. overlaps with an existing mapping.
  1729. |:noremap| is used to avoid that any other mappings that the user has defined
  1730. interferes. You might want to use ":noremap <script>" to allow remapping
  1731. mappings defined in this script that start with <SID>.
  1732. The user must have a chance to disable the mappings in a filetype plugin,
  1733. without disabling everything. Here is an example of how this is done for a
  1734. plugin for the mail filetype: >
  1735. " Add mappings, unless the user didn't want this.
  1736. if !exists("no_plugin_maps") && !exists("no_mail_maps")
  1737. " Quote text by inserting "> "
  1738. if !hasmapto('<Plug>MailQuote')
  1739. vmap <buffer> <LocalLeader>q <Plug>MailQuote
  1740. nmap <buffer> <LocalLeader>q <Plug>MailQuote
  1741. endif
  1742. vnoremap <buffer> <Plug>MailQuote :s/^/> /<CR>
  1743. nnoremap <buffer> <Plug>MailQuote :.,$s/^/> /<CR>
  1744. endif
  1745. Two global variables are used:
  1746. |no_plugin_maps| disables mappings for all filetype plugins
  1747. |no_mail_maps| disables mappings for the "mail" filetype
  1748. USER COMMANDS
  1749. To add a user command for a specific file type, so that it can only be used in
  1750. one buffer, use the "-buffer" argument to |:command|. Example: >
  1751. :command -buffer Make make %:r.s
  1752. VARIABLES
  1753. A filetype plugin will be sourced for each buffer of the type it's for. Local
  1754. script variables |s:var| will be shared between all invocations. Use local
  1755. buffer variables |b:var| if you want a variable specifically for one buffer.
  1756. FUNCTIONS
  1757. When defining a function, this only needs to be done once. But the filetype
  1758. plugin will be sourced every time a file with this filetype will be opened.
  1759. This construct makes sure the function is only defined once: >
  1760. :if !exists("*s:Func")
  1761. : function s:Func(arg)
  1762. : ...
  1763. : endfunction
  1764. :endif
  1765. <
  1766. UNDO *undo_indent* *undo_ftplugin*
  1767. When the user does ":setfiletype xyz" the effect of the previous filetype
  1768. should be undone. Set the b:undo_ftplugin variable to the commands that will
  1769. undo the settings in your filetype plugin. Example: >
  1770. let b:undo_ftplugin = "setlocal fo< com< tw< commentstring<"
  1771. \ . "| unlet b:match_ignorecase b:match_words b:match_skip"
  1772. Using ":setlocal" with "<" after the option name resets the option to its
  1773. global value. That is mostly the best way to reset the option value.
  1774. This does require removing the "C" flag from 'cpoptions' to allow line
  1775. continuation, as mentioned above |use-cpo-save|.
  1776. For undoing the effect of an indent script, the b:undo_indent variable should
  1777. be set accordingly.
  1778. FILE NAME
  1779. The filetype must be included in the file name |ftplugin-name|. Use one of
  1780. these three forms:
  1781. .../ftplugin/stuff.vim
  1782. .../ftplugin/stuff_foo.vim
  1783. .../ftplugin/stuff/bar.vim
  1784. "stuff" is the filetype, "foo" and "bar" are arbitrary names.
  1785. SUMMARY *ftplugin-special*
  1786. Summary of special things to use in a filetype plugin:
  1787. <LocalLeader> Value of "maplocalleader", which the user defines as
  1788. the keys that filetype plugin mappings start with.
  1789. :map <buffer> Define a mapping local to the buffer.
  1790. :noremap <script> Only remap mappings defined in this script that start
  1791. with <SID>.
  1792. :setlocal Set an option for the current buffer only.
  1793. :command -buffer Define a user command local to the buffer.
  1794. exists("*s:Func") Check if a function was already defined.
  1795. Also see |plugin-special|, the special things used for all plugins.
  1796. ==============================================================================
  1797. *41.13* Writing a compiler plugin *write-compiler-plugin*
  1798. A compiler plugin sets options for use with a specific compiler. The user can
  1799. load it with the |:compiler| command. The main use is to set the
  1800. 'errorformat' and 'makeprg' options.
  1801. Easiest is to have a look at examples. This command will edit all the default
  1802. compiler plugins: >
  1803. :next $VIMRUNTIME/compiler/*.vim
  1804. Use |:next| to go to the next plugin file.
  1805. There are two special items about these files. First is a mechanism to allow
  1806. a user to overrule or add to the default file. The default files start with: >
  1807. :if exists("current_compiler")
  1808. : finish
  1809. :endif
  1810. :let current_compiler = "mine"
  1811. When you write a compiler file and put it in your personal runtime directory
  1812. (e.g., ~/.config/nvim/compiler for Unix), you set the "current_compiler"
  1813. variable to make the default file skip the settings.
  1814. *:CompilerSet*
  1815. The second mechanism is to use ":set" for ":compiler!" and ":setlocal" for
  1816. ":compiler". Vim defines the ":CompilerSet" user command for this. However,
  1817. older Vim versions don't, thus your plugin should define it then. This is an
  1818. example: >
  1819. if exists(":CompilerSet") != 2
  1820. command -nargs=* CompilerSet setlocal <args>
  1821. endif
  1822. CompilerSet errorformat& " use the default 'errorformat'
  1823. CompilerSet makeprg=nmake
  1824. When you write a compiler plugin for the Vim distribution or for a system-wide
  1825. runtime directory, use the mechanism mentioned above. When
  1826. "current_compiler" was already set by a user plugin nothing will be done.
  1827. When you write a compiler plugin to overrule settings from a default plugin,
  1828. don't check "current_compiler". This plugin is supposed to be loaded
  1829. last, thus it should be in a directory at the end of 'runtimepath'. For Unix
  1830. that could be ~/.config/nvim/after/compiler.
  1831. ==============================================================================
  1832. *41.14* Writing a plugin that loads quickly *write-plugin-quickload*
  1833. A plugin may grow and become quite long. The startup delay may become
  1834. noticeable, while you hardly ever use the plugin. Then it's time for a
  1835. quickload plugin.
  1836. The basic idea is that the plugin is loaded twice. The first time user
  1837. commands and mappings are defined that offer the functionality. The second
  1838. time the functions that implement the functionality are defined.
  1839. It may sound surprising that quickload means loading a script twice. What we
  1840. mean is that it loads quickly the first time, postponing the bulk of the
  1841. script to the second time, which only happens when you actually use it. When
  1842. you always use the functionality it actually gets slower!
  1843. Note that since Vim 7 there is an alternative: use the |autoload|
  1844. functionality |41.15|.
  1845. The following example shows how it's done: >
  1846. " Vim global plugin for demonstrating quick loading
  1847. " Last Change: 2005 Feb 25
  1848. " Maintainer: Bram Moolenaar <Bram@vim.org>
  1849. " License: This file is placed in the public domain.
  1850. if !exists("s:did_load")
  1851. command -nargs=* BNRead call BufNetRead(<f-args>)
  1852. map <F19> :call BufNetWrite('something')<CR>
  1853. let s:did_load = 1
  1854. exe 'au FuncUndefined BufNet* source ' . expand('<sfile>')
  1855. finish
  1856. endif
  1857. function BufNetRead(...)
  1858. echo 'BufNetRead(' . string(a:000) . ')'
  1859. " read functionality here
  1860. endfunction
  1861. function BufNetWrite(...)
  1862. echo 'BufNetWrite(' . string(a:000) . ')'
  1863. " write functionality here
  1864. endfunction
  1865. When the script is first loaded "s:did_load" is not set. The commands between
  1866. the "if" and "endif" will be executed. This ends in a |:finish| command, thus
  1867. the rest of the script is not executed.
  1868. The second time the script is loaded "s:did_load" exists and the commands
  1869. after the "endif" are executed. This defines the (possible long)
  1870. BufNetRead() and BufNetWrite() functions.
  1871. If you drop this script in your plugin directory Vim will execute it on
  1872. startup. This is the sequence of events that happens:
  1873. 1. The "BNRead" command is defined and the <F19> key is mapped when the script
  1874. is sourced at startup. A |FuncUndefined| autocommand is defined. The
  1875. ":finish" command causes the script to terminate early.
  1876. 2. The user types the BNRead command or presses the <F19> key. The
  1877. BufNetRead() or BufNetWrite() function will be called.
  1878. 3. Vim can't find the function and triggers the |FuncUndefined| autocommand
  1879. event. Since the pattern "BufNet*" matches the invoked function, the
  1880. command "source fname" will be executed. "fname" will be equal to the name
  1881. of the script, no matter where it is located, because it comes from
  1882. expanding "<sfile>" (see |expand()|).
  1883. 4. The script is sourced again, the "s:did_load" variable exists and the
  1884. functions are defined.
  1885. Notice that the functions that are loaded afterwards match the pattern in the
  1886. |FuncUndefined| autocommand. You must make sure that no other plugin defines
  1887. functions that match this pattern.
  1888. ==============================================================================
  1889. *41.15* Writing library scripts *write-library-script*
  1890. Some functionality will be required in several places. When this becomes more
  1891. than a few lines you will want to put it in one script and use it from many
  1892. scripts. We will call that one script a library script.
  1893. Manually loading a library script is possible, so long as you avoid loading it
  1894. when it's already done. You can do this with the |exists()| function.
  1895. Example: >
  1896. if !exists('*MyLibFunction')
  1897. runtime library/mylibscript.vim
  1898. endif
  1899. call MyLibFunction(arg)
  1900. Here you need to know that MyLibFunction() is defined in a script
  1901. "library/mylibscript.vim" in one of the directories in 'runtimepath'.
  1902. To make this a bit simpler Vim offers the autoload mechanism. Then the
  1903. example looks like this: >
  1904. call mylib#myfunction(arg)
  1905. That's a lot simpler, isn't it? Vim will recognize the function name and when
  1906. it's not defined search for the script "autoload/mylib.vim" in 'runtimepath'.
  1907. That script must define the "mylib#myfunction()" function.
  1908. You can put many other functions in the mylib.vim script, you are free to
  1909. organize your functions in library scripts. But you must use function names
  1910. where the part before the '#' matches the script name. Otherwise Vim would
  1911. not know what script to load.
  1912. If you get really enthusiastic and write lots of library scripts, you may
  1913. want to use subdirectories. Example: >
  1914. call netlib#ftp#read('somefile')
  1915. For Unix the library script used for this could be:
  1916. ~/.config/nvim/autoload/netlib/ftp.vim
  1917. Where the function is defined like this: >
  1918. function netlib#ftp#read(fname)
  1919. " Read the file fname through ftp
  1920. endfunction
  1921. Notice that the name the function is defined with is exactly the same as the
  1922. name used for calling the function. And the part before the last '#'
  1923. exactly matches the subdirectory and script name.
  1924. You can use the same mechanism for variables: >
  1925. let weekdays = dutch#weekdays
  1926. This will load the script "autoload/dutch.vim", which should contain something
  1927. like: >
  1928. let dutch#weekdays = ['zondag', 'maandag', 'dinsdag', 'woensdag',
  1929. \ 'donderdag', 'vrijdag', 'zaterdag']
  1930. Further reading: |autoload|.
  1931. ==============================================================================
  1932. *41.16* Distributing Vim scripts *distribute-script*
  1933. Vim users will look for scripts on the Vim website: http://www.vim.org.
  1934. If you made something that is useful for others, share it!
  1935. Vim scripts can be used on any system. There might not be a tar or gzip
  1936. command. If you want to pack files together and/or compress them the "zip"
  1937. utility is recommended.
  1938. ==============================================================================
  1939. Next chapter: |usr_42.txt| Add new menus
  1940. Copyright: see |manual-copyright| vim:tw=78:ts=8:noet:ft=help:norl: