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