usr_41.txt 89 KB

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