userfunc.txt 19 KB

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