userfunc.txt 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. *userfunc.txt* Nvim
  2. VIM REFERENCE MANUAL by Bram Moolenaar
  3. Defining and using functions.
  4. This is introduced in section |41.7| of the user manual.
  5. Type |gO| to see the table of contents.
  6. ==============================================================================
  7. 1. Defining a function ~
  8. *define-function*
  9. New functions can be defined. These can be called just like builtin
  10. functions. The function executes a sequence of Ex commands. Normal mode
  11. commands can be executed with the |:normal| command.
  12. The function name must start with an uppercase letter, to avoid confusion with
  13. builtin functions. To prevent from using the same name in different scripts
  14. make them script-local. If you do use a global function then avoid obvious,
  15. short names. A good habit is to start the function name with the name of the
  16. script, e.g., "HTMLcolor()".
  17. It is also possible to use curly braces, see |curly-braces-names|.
  18. The |autoload| facility is useful to define a function only when it's called.
  19. *local-function*
  20. A function local to a script must start with "s:". A local script function
  21. can only be called from within the script and from functions, user commands
  22. and autocommands defined in the script. It is also possible to call the
  23. function from a mapping defined in the script, but then |<SID>| must be used
  24. instead of "s:" when the mapping is expanded outside of the script.
  25. There are only script-local functions, no buffer-local or window-local
  26. functions.
  27. *:fu* *:function* *E128* *E129* *E123*
  28. :fu[nction] List all functions and their arguments.
  29. :fu[nction][!] {name} List function {name}, annotated with line numbers
  30. unless "!" is given.
  31. {name} may be a |Dictionary| |Funcref| entry: >
  32. :function dict.init
  33. < Note that {name} is not an expression, you cannot use
  34. a variable that is a function reference. You can use
  35. this dirty trick to list the function referred to with
  36. variable "Funcref": >
  37. let g:MyFuncref = Funcref
  38. func g:MyFuncref
  39. unlet g:MyFuncref
  40. :fu[nction] /{pattern} List functions with a name matching {pattern}.
  41. Example that lists all functions ending with "File": >
  42. :function /File$
  43. <
  44. *:function-verbose*
  45. When 'verbose' is non-zero, listing a function will also display where it was
  46. last defined. Example: >
  47. :verbose function SetFileTypeSH
  48. function SetFileTypeSH(name)
  49. Last set from /usr/share/vim/vim-7.0/filetype.vim
  50. <
  51. See |:verbose-cmd| for more information.
  52. *E124* *E125* *E853* *E884*
  53. :fu[nction][!] {name}([arguments]) [range] [abort] [dict] [closure]
  54. Define a new function by the name {name}. The body of
  55. the function follows in the next lines, until the
  56. matching |:endfunction|.
  57. The name must be made of alphanumeric characters and
  58. '_', and must start with a capital or "s:" (see
  59. above). Note that using "b:" or "g:" is not allowed.
  60. (since patch 7.4.260 E884 is given if the function
  61. name has a colon in the name, e.g. for "foo:bar()".
  62. Before that patch no error was given).
  63. {name} may be a |Dictionary| |Funcref| entry: >
  64. :function dict.init(arg)
  65. < "dict" must be an existing dictionary. The entry
  66. "init" is added if it didn't exist yet. Otherwise [!]
  67. is required to overwrite an existing function. The
  68. result is a |Funcref| to a numbered function. The
  69. function can only be used with a |Funcref| and will be
  70. deleted if there are no more references to it.
  71. *E127* *E122*
  72. When a function by this name already exists and [!] is
  73. not used an error message is given. There is one
  74. exception: When sourcing a script again, a function
  75. that was previously defined in that script will be
  76. silently replaced.
  77. When [!] is used, an existing function is silently
  78. replaced. Unless it is currently being executed, that
  79. is an error.
  80. NOTE: Use ! wisely. If used without care it can cause
  81. an existing function to be replaced unexpectedly,
  82. which is hard to debug.
  83. For the {arguments} see |function-argument|.
  84. *:func-range* *a:firstline* *a:lastline*
  85. When the [range] argument is added, the function is
  86. expected to take care of a range itself. The range is
  87. passed as "a:firstline" and "a:lastline". If [range]
  88. is excluded, ":{range}call" will call the function for
  89. each line in the range, with the cursor on the start
  90. of each line. See |function-range-example|.
  91. The cursor is still moved to the first line of the
  92. range, as is the case with all Ex commands.
  93. *:func-abort*
  94. When the [abort] argument is added, the function will
  95. abort as soon as an error is detected.
  96. *:func-dict*
  97. When the [dict] argument is added, the function must
  98. be invoked through an entry in a |Dictionary|. The
  99. local variable "self" will then be set to the
  100. dictionary. See |Dictionary-function|.
  101. *:func-closure* *E932*
  102. When the [closure] argument is added, the function
  103. can access variables and arguments from the outer
  104. scope. This is usually called a closure. In this
  105. example Bar() uses "x" from the scope of Foo(). It
  106. remains referenced even after Foo() returns: >
  107. :function! Foo()
  108. : let x = 0
  109. : function! Bar() closure
  110. : let x += 1
  111. : return x
  112. : endfunction
  113. : return funcref('Bar')
  114. :endfunction
  115. :let F = Foo()
  116. :echo F()
  117. < 1 >
  118. :echo F()
  119. < 2 >
  120. :echo F()
  121. < 3
  122. *function-search-undo*
  123. The last used search pattern and the redo command "."
  124. will not be changed by the function. This also
  125. implies that the effect of |:nohlsearch| is undone
  126. when the function returns.
  127. *:endf* *:endfunction* *E126* *E193* *W22*
  128. :endf[unction] [argument]
  129. The end of a function definition. Best is to put it
  130. on a line by its own, without [argument].
  131. [argument] can be:
  132. | command command to execute next
  133. \n command command to execute next
  134. " comment always ignored
  135. anything else ignored, warning given when
  136. 'verbose' is non-zero
  137. The support for a following command was added in Vim
  138. 8.0.0654, before that any argument was silently
  139. ignored.
  140. To be able to define a function inside an `:execute`
  141. command, use line breaks instead of |:bar|: >
  142. :exe "func Foo()\necho 'foo'\nendfunc"
  143. <
  144. *:delf* *:delfunction* *E131* *E933*
  145. :delf[unction][!] {name}
  146. Delete function {name}.
  147. {name} can also be a |Dictionary| entry that is a
  148. |Funcref|: >
  149. :delfunc dict.init
  150. < This will remove the "init" entry from "dict". The
  151. function is deleted if there are no more references to
  152. it.
  153. With the ! there is no error if the function does not
  154. exist.
  155. *:retu* *:return* *E133*
  156. :retu[rn] [expr] Return from a function. When "[expr]" is given, it is
  157. evaluated and returned as the result of the function.
  158. If "[expr]" is not given, the number 0 is returned.
  159. When a function ends without an explicit ":return",
  160. the number 0 is returned.
  161. Note that there is no check for unreachable lines,
  162. thus there is no warning if commands follow ":return".
  163. Also, there is no check if the following
  164. line contains a valid command. Forgetting the line
  165. continuation backslash may go unnoticed: >
  166. return 'some text'
  167. .. ' some more text'
  168. < Will happily return "some text" without an error. It
  169. should have been: >
  170. return 'some text'
  171. \ .. ' some more text'
  172. <
  173. If the ":return" is used after a |:try| but before the
  174. matching |:finally| (if present), the commands
  175. following the ":finally" up to the matching |:endtry|
  176. are executed first. This process applies to all
  177. nested ":try"s inside the function. The function
  178. returns at the outermost ":endtry".
  179. *function-argument* *a:var*
  180. An argument can be defined by giving its name. In the function this can then
  181. be used as "a:name" ("a:" for argument).
  182. *a:0* *a:1* *a:000* *E740* *...*
  183. Up to 20 arguments can be given, separated by commas. After the named
  184. arguments an argument "..." can be specified, which means that more arguments
  185. may optionally be following. In the function the extra arguments can be used
  186. as "a:1", "a:2", etc. "a:0" is set to the number of extra arguments (which
  187. can be 0). "a:000" is set to a |List| that contains these arguments. Note
  188. that "a:1" is the same as "a:000[0]".
  189. *E742*
  190. The a: scope and the variables in it cannot be changed, they are fixed.
  191. However, if a composite type is used, such as |List| or |Dictionary| , you can
  192. change their contents. Thus you can pass a |List| to a function and have the
  193. function add an item to it. If you want to make sure the function cannot
  194. change a |List| or |Dictionary| use |:lockvar|.
  195. It is also possible to define a function without any arguments. You must
  196. still supply the () then.
  197. It is allowed to define another function inside a function body.
  198. *optional-function-argument*
  199. You can provide default values for positional named arguments. This makes
  200. them optional for function calls. When a positional argument is not
  201. specified at a call, the default expression is used to initialize it.
  202. This only works for functions declared with `:function`, not for
  203. lambda expressions |expr-lambda|.
  204. Example: >
  205. function Something(key, value = 10)
  206. echo a:key .. ": " .. a:value
  207. endfunction
  208. call Something('empty') "empty: 10"
  209. call Something('key', 20) "key: 20"
  210. The argument default expressions are evaluated at the time of the function
  211. call, not when the function is defined. Thus it is possible to use an
  212. expression which is invalid the moment the function is defined. The
  213. expressions are also only evaluated when arguments are not specified during a
  214. call.
  215. *E989*
  216. Optional arguments with default expressions must occur after any mandatory
  217. arguments. You can use "..." after all optional named arguments.
  218. It is possible for later argument defaults to refer to prior arguments,
  219. but not the other way around. They must be prefixed with "a:", as with all
  220. arguments.
  221. Example that works: >
  222. :function Okay(mandatory, optional = a:mandatory)
  223. :endfunction
  224. Example that does NOT work: >
  225. :function NoGood(first = a:second, second = 10)
  226. :endfunction
  227. <
  228. When not using "...", the number of arguments in a function call must be at
  229. least equal to the number of mandatory named arguments. When using "...", the
  230. number of arguments may be larger than the total of mandatory and optional
  231. arguments.
  232. *local-variables*
  233. Inside a function local variables can be used. These will disappear when the
  234. function returns. Global variables need to be accessed with "g:". Inside
  235. functions local variables are accessed without prepending anything. But you
  236. can also prepend "l:" if you like. This is required for some reserved names,
  237. such as "version".
  238. Example: >
  239. :function Table(title, ...)
  240. : echohl Title
  241. : echo a:title
  242. : echohl None
  243. : echo a:0 .. " items:"
  244. : for s in a:000
  245. : echon ' ' .. s
  246. : endfor
  247. :endfunction
  248. This function can then be called with: >
  249. call Table("Table", "line1", "line2")
  250. call Table("Empty Table")
  251. To return more than one value, return a |List|: >
  252. :function Compute(n1, n2)
  253. : if a:n2 == 0
  254. : return ["fail", 0]
  255. : endif
  256. : return ["ok", a:n1 / a:n2]
  257. :endfunction
  258. This function can then be called with: >
  259. :let [success, div] = Compute(102, 6)
  260. :if success == "ok"
  261. : echo div
  262. :endif
  263. <
  264. ==============================================================================
  265. 2. Calling a function ~
  266. *:cal* *:call* *E107* *E117*
  267. :[range]cal[l] {name}([arguments])
  268. Call a function. The name of the function and its arguments
  269. are as specified with `:function`. Up to 20 arguments can be
  270. used. The returned value is discarded.
  271. Without a range and for functions that accept a range, the
  272. function is called once. When a range is given the cursor is
  273. positioned at the start of the first line before executing the
  274. function.
  275. When a range is given and the function doesn't handle it
  276. itself, the function is executed for each line in the range,
  277. with the cursor in the first column of that line. The cursor
  278. is left at the last line (possibly moved by the last function
  279. call). The arguments are re-evaluated for each line. Thus
  280. this works:
  281. *function-range-example* >
  282. :function Mynumber(arg)
  283. : echo line(".") .. " " .. a:arg
  284. :endfunction
  285. :1,5call Mynumber(getline("."))
  286. <
  287. The "a:firstline" and "a:lastline" are defined anyway, they
  288. can be used to do something different at the start or end of
  289. the range.
  290. Example of a function that handles the range itself: >
  291. :function Cont() range
  292. : execute (a:firstline + 1) .. "," .. a:lastline .. 's/^/\t\\ '
  293. :endfunction
  294. :4,8call Cont()
  295. <
  296. This function inserts the continuation character "\" in front
  297. of all the lines in the range, except the first one.
  298. When the function returns a composite value it can be further
  299. dereferenced, but the range will not be used then. Example: >
  300. :4,8call GetDict().method()
  301. < Here GetDict() gets the range but method() does not.
  302. *E132*
  303. The recursiveness of user functions is restricted with the |'maxfuncdepth'|
  304. option.
  305. It is also possible to use `:eval`. It does not support a range, but does
  306. allow for method chaining, e.g.: >
  307. eval GetList()->Filter()->append('$')
  308. A function can also be called as part of evaluating an expression or when it
  309. is used as a method: >
  310. let x = GetList()
  311. let y = GetList()->Filter()
  312. <
  313. ==============================================================================
  314. 3. Cleaning up in a function ~
  315. *:defer*
  316. :defer {func}({args}) Call {func} when the current function is done.
  317. {args} are evaluated here.
  318. Quite often a command in a function has a global effect, which must be undone
  319. when the function finishes. Handling this in all kinds of situations can be a
  320. hassle. Especially when an unexpected error is encountered. This can be done
  321. with `try` / `finally` blocks, but this gets complicated when there is more
  322. than one.
  323. A much simpler solution is using `defer`. It schedules a function call when
  324. the function is returning, no matter if there is an error. Example: >
  325. func Filter(text) abort
  326. call writefile(a:text, 'Tempfile')
  327. call system('filter < Tempfile > Outfile')
  328. call Handle('Outfile')
  329. call delete('Tempfile')
  330. call delete('Outfile')
  331. endfunc
  332. Here 'Tempfile' and 'Outfile' will not be deleted if something causes the
  333. function to abort. `:defer` can be used to avoid that: >
  334. func Filter(text) abort
  335. call writefile(a:text, 'Tempfile')
  336. defer delete('Tempfile')
  337. defer delete('Outfile')
  338. call system('filter < Tempfile > Outfile')
  339. call Handle('Outfile')
  340. endfunc
  341. Note that deleting "Outfile" is scheduled before calling `system()`, since it
  342. can be created even when `system()` fails.
  343. The deferred functions are called in reverse order, the last one added is
  344. executed first. A useless example: >
  345. func Useless() abort
  346. for s in range(3)
  347. defer execute('echomsg "number ' .. s .. '"')
  348. endfor
  349. endfunc
  350. Now `:messages` shows:
  351. number 2
  352. number 1
  353. number 0
  354. Any return value of the deferred function is discarded. The function cannot
  355. be followed by anything, such as "->func" or ".member". Currently `:defer
  356. GetArg()->TheFunc()` does not work, it may work in a later version.
  357. Errors are reported but do not cause aborting execution of deferred functions
  358. or altering execution outside of deferred functions.
  359. No range is accepted. The function can be a partial with extra arguments, but
  360. not with a dictionary. *E1300*
  361. ==============================================================================
  362. 4. Automatically loading functions ~
  363. *autoload-functions*
  364. When using many or large functions, it's possible to automatically define them
  365. only when they are used. There are two methods: with an autocommand and with
  366. the "autoload" directory in 'runtimepath'.
  367. Using an autocommand ~
  368. This is introduced in the user manual, section |41.14|.
  369. The autocommand is useful if you have a plugin that is a long Vim script file.
  370. You can define the autocommand and quickly quit the script with `:finish`.
  371. That makes Vim startup faster. The autocommand should then load the same file
  372. again, setting a variable to skip the `:finish` command.
  373. Use the FuncUndefined autocommand event with a pattern that matches the
  374. function(s) to be defined. Example: >
  375. :au FuncUndefined BufNet* source ~/vim/bufnetfuncs.vim
  376. The file "~/vim/bufnetfuncs.vim" should then define functions that start with
  377. "BufNet". Also see |FuncUndefined|.
  378. Using an autoload script ~
  379. *autoload* *E746*
  380. This is introduced in the user manual, section |41.15|.
  381. Using a script in the "autoload" directory is simpler, but requires using
  382. exactly the right file name. A function that can be autoloaded has a name
  383. like this: >
  384. :call filename#funcname()
  385. When such a function is called, and it is not defined yet, Vim will search the
  386. "autoload" directories in 'runtimepath' for a script file called
  387. "filename.vim". For example "~/.config/nvim/autoload/filename.vim". That
  388. file should then define the function like this: >
  389. function filename#funcname()
  390. echo "Done!"
  391. endfunction
  392. If the file doesn't exist, Vim will also search in 'packpath' (under "start")
  393. to allow calling packages' functions from your |vimrc| when the packages have
  394. not been added to 'runtimepath' yet (see |packages|).
  395. The file name and the name used before the # in the function must match
  396. exactly, and the defined function must have the name exactly as it will be
  397. called.
  398. It is possible to use subdirectories. Every # in the function name works like
  399. a path separator. Thus when calling a function: >
  400. :call foo#bar#func()
  401. Vim will look for the file "autoload/foo/bar.vim" in 'runtimepath'.
  402. This also works when reading a variable that has not been set yet: >
  403. :let l = foo#bar#lvar
  404. However, when the autoload script was already loaded it won't be loaded again
  405. for an unknown variable.
  406. When assigning a value to such a variable nothing special happens. This can
  407. be used to pass settings to the autoload script before it's loaded: >
  408. :let foo#bar#toggle = 1
  409. :call foo#bar#func()
  410. Note that when you make a mistake and call a function that is supposed to be
  411. defined in an autoload script, but the script doesn't actually define the
  412. function, you will get an error message for the missing function. If you fix
  413. the autoload script it won't be automatically loaded again. Either restart
  414. Vim or manually source the script.
  415. Also note that if you have two script files, and one calls a function in the
  416. other and vice versa, before the used function is defined, it won't work.
  417. Avoid using the autoload functionality at the toplevel.
  418. Hint: If you distribute a bunch of scripts read |distribute-script|.
  419. vim:tw=78:ts=8:noet:ft=help:norl: