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