usr_41.txt 91 KB

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