userfunc.txt 16 KB

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