blob: fe7e906ccbe2ce6fb02d0009dcfb30132fce972b [file] [log] [blame]
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +00001*userfunc.txt* For Vim version 9.0. Last change: 2023 Jan 09
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
214be used as "a:name" ("a:" for argument).
215 *a:0* *a:1* *a:000* *E740* *...*
216Up to 20 arguments can be given, separated by commas. After the named
217arguments an argument "..." can be specified, which means that more arguments
218may optionally be following. In the function the extra arguments can be used
219as "a:1", "a:2", etc. "a:0" is set to the number of extra arguments (which
220can be 0). "a:000" is set to a |List| that contains these arguments. Note
221that "a:1" is the same as "a:000[0]".
222 *E742* *E1090*
223The a: scope and the variables in it cannot be changed, they are fixed.
224However, if a composite type is used, such as |List| or |Dictionary| , you can
225change their contents. Thus you can pass a |List| to a function and have the
226function add an item to it. If you want to make sure the function cannot
227change a |List| or |Dictionary| use |:lockvar|.
228
229It is also possible to define a function without any arguments. You must
230still supply the () then.
231
232It is allowed to define another function inside a function body.
233
234 *optional-function-argument*
235You can provide default values for positional named arguments. This makes
236them optional for function calls. When a positional argument is not
237specified at a call, the default expression is used to initialize it.
238This only works for functions declared with `:function` or `:def`, not for
239lambda expressions |expr-lambda|.
240
241Example: >
242 function Something(key, value = 10)
243 echo a:key .. ": " .. a:value
244 endfunction
245 call Something('empty') "empty: 10"
246 call Something('key', 20) "key: 20"
247
248The argument default expressions are evaluated at the time of the function
249call, not definition. Thus it is possible to use an expression which is
250invalid the moment the function is defined. The expressions are also only
251evaluated when arguments are not specified during a call.
252 *none-function_argument*
253You can pass |v:none| to use the default expression. Note that this means you
254cannot pass v:none as an ordinary value when an argument has a default
255expression.
256
257Example: >
258 function Something(a = 10, b = 20, c = 30)
259 endfunction
260 call Something(1, v:none, 3) " b = 20
261<
262 *E989*
263Optional arguments with default expressions must occur after any mandatory
264arguments. You can use "..." after all optional named arguments.
265
266It is possible for later argument defaults to refer to prior arguments,
267but not the other way around. They must be prefixed with "a:", as with all
268arguments.
269
270Example that works: >
271 :function Okay(mandatory, optional = a:mandatory)
272 :endfunction
273Example that does NOT work: >
274 :function NoGood(first = a:second, second = 10)
275 :endfunction
276<
277When not using "...", the number of arguments in a function call must be at
278least equal to the number of mandatory named arguments. When using "...", the
279number of arguments may be larger than the total of mandatory and optional
280arguments.
281
282 *local-variables*
283Inside a function local variables can be used. These will disappear when the
284function returns. Global variables need to be accessed with "g:".
285Inside functions local variables are accessed without prepending anything.
286But you can also prepend "l:" if you like. This is required for some reserved
287names, such as "count".
288
289Example: >
290 :function Table(title, ...)
291 : echohl Title
292 : echo a:title
293 : echohl None
294 : echo a:0 .. " items:"
295 : for s in a:000
296 : echon ' ' .. s
297 : endfor
298 :endfunction
299
300This function can then be called with: >
301 call Table("Table", "line1", "line2")
302 call Table("Empty Table")
303
304To return more than one value, return a |List|: >
305 :function Compute(n1, n2)
306 : if a:n2 == 0
307 : return ["fail", 0]
308 : endif
309 : return ["ok", a:n1 / a:n2]
310 :endfunction
311
312This function can then be called with: >
313 :let [success, div] = Compute(102, 6)
314 :if success == "ok"
315 : echo div
316 :endif
317<
318==============================================================================
319
Bram Moolenaar9712ff12022-09-18 13:04:22 +01003202. Calling a function ~
Bram Moolenaar0daafaa2022-09-04 17:45:43 +0100321 *:cal* *:call* *E107*
322:[range]cal[l] {name}([arguments])
323 Call a function. The name of the function and its arguments
324 are as specified with `:function`. Up to 20 arguments can be
325 used. The returned value is discarded.
326 In |Vim9| script using `:call` is optional, these two lines do
327 the same thing: >
328 call SomeFunc(arg)
329 SomeFunc(arg)
330< Without a range and for functions that accept a range, the
331 function is called once. When a range is given the cursor is
332 positioned at the start of the first line before executing the
333 function.
334 When a range is given and the function doesn't handle it
335 itself, the function is executed for each line in the range,
336 with the cursor in the first column of that line. The cursor
337 is left at the last line (possibly moved by the last function
338 call). The arguments are re-evaluated for each line. Thus
339 this works:
340 *function-range-example* >
341 :function Mynumber(arg)
342 : echo line(".") .. " " .. a:arg
343 :endfunction
344 :1,5call Mynumber(getline("."))
345<
346 The "a:firstline" and "a:lastline" are defined anyway, they
347 can be used to do something different at the start or end of
348 the range.
349
350 Example of a function that handles the range itself: >
351
352 :function Cont() range
353 : execute (a:firstline + 1) .. "," .. a:lastline .. 's/^/\t\\ '
354 :endfunction
355 :4,8call Cont()
356<
357 This function inserts the continuation character "\" in front
358 of all the lines in the range, except the first one.
359
360 When the function returns a composite value it can be further
361 dereferenced, but the range will not be used then. Example: >
362 :4,8call GetDict().method()
363< Here GetDict() gets the range but method() does not.
364
365 *E117*
366When a function cannot be found the error "E117: Unknown function" will be
367given. If the function was using an autoload path or an autoload import and
368the script is a |Vim9| script, this may also be caused by the function not
369being exported.
370
371 *E132*
372The recursiveness of user functions is restricted with the |'maxfuncdepth'|
373option.
374
375It is also possible to use `:eval`. It does not support a range, but does
376allow for method chaining, e.g.: >
377 eval GetList()->Filter()->append('$')
378
379A function can also be called as part of evaluating an expression or when it
380is used as a method: >
381 let x = GetList()
382 let y = GetList()->Filter()
383
384==============================================================================
385
3863. Cleaning up in a function ~
387 *:defer*
388:defer {func}({args}) Call {func} when the current function is done.
389 {args} are evaluated here.
390
391Quite often a command in a function has a global effect, which must be undone
392when the function finishes. Handling this in all kinds of situations can be a
393hassle. Especially when an unexpected error is encountered. This can be done
394with `try` / `finally` blocks, but this gets complicated when there is more
395than one.
396
397A much simpler solution is using `defer`. It schedules a function call when
398the function is returning, no matter if there is an error. Example: >
399 func Filter(text) abort
400 call writefile(a:text, 'Tempfile')
401 call system('filter < Tempfile > Outfile')
402 call Handle('Outfile')
403 call delete('Tempfile')
404 call delete('Outfile')
405 endfunc
406
407Here 'Tempfile' and 'Outfile' will not be deleted if something causes the
408function to abort. `:defer` can be used to avoid that: >
409 func Filter(text) abort
410 call writefile(a:text, 'Tempfile')
411 defer delete('Tempfile')
412 defer delete('Outfile')
413 call system('filter < Tempfile > Outfile')
414 call Handle('Outfile')
415 endfunc
416
Bram Moolenaar76db9e02022-11-09 21:21:04 +0000417Note that deleting "Outfile" is scheduled before calling `system()`, since it
Bram Moolenaar0daafaa2022-09-04 17:45:43 +0100418can be created even when `system()` fails.
419
420The deferred functions are called in reverse order, the last one added is
421executed first. A useless example: >
422 func Useless() abort
423 for s in range(3)
424 defer execute('echomsg "number ' .. s .. '"')
425 endfor
426 endfunc
427
428Now `:messages` shows:
429 number 2
430 number 1
431 number 0
432
433Any return value of the deferred function is discarded. The function cannot
434be followed by anything, such as "->func" or ".member". Currently `:defer
435GetArg()->TheFunc()` does not work, it may work in a later version.
436
437Errors are reported but do not cause aborting execution of deferred functions.
438
Bram Moolenaar71b6d332022-09-10 13:13:14 +0100439No range is accepted. The function can be a partial with extra arguments, but
440not with a dictionary. *E1300*
Bram Moolenaar0daafaa2022-09-04 17:45:43 +0100441
442==============================================================================
443
4444. Automatically loading functions ~
445 *autoload-functions*
446When using many or large functions, it's possible to automatically define them
447only when they are used. There are two methods: with an autocommand and with
448the "autoload" directory in 'runtimepath'.
449
450In |Vim9| script there is also an autoload mechanism for imported scripts, see
451|import-autoload|.
452
453
454Using an autocommand ~
455
456This is introduced in the user manual, section |51.4|.
457
458The autocommand is useful if you have a plugin that is a long Vim script file.
459You can define the autocommand and quickly quit the script with `:finish`.
460That makes Vim startup faster. The autocommand should then load the same file
461again, setting a variable to skip the `:finish` command.
462
463Use the FuncUndefined autocommand event with a pattern that matches the
464function(s) to be defined. Example: >
465
466 :au FuncUndefined BufNet* source ~/vim/bufnetfuncs.vim
467
468The file "~/vim/bufnetfuncs.vim" should then define functions that start with
469"BufNet". Also see |FuncUndefined|.
470
471
472Using an autoload script ~
473 *autoload* *E746*
474This is introduced in the user manual, section |52.2|.
475
476Using a script in the "autoload" directory is simpler, but requires using
477exactly the right file name. A function that can be autoloaded has a name
478like this: >
479
480 :call filename#funcname()
481
482These functions are always global, in Vim9 script "g:" needs to be used: >
483 :call g:filename#funcname()
484
485When such a function is called, and it is not defined yet, Vim will search the
486"autoload" directories in 'runtimepath' for a script file called
487"filename.vim". For example "~/.vim/autoload/filename.vim". That file should
488then define the function like this: >
489
490 function filename#funcname()
491 echo "Done!"
492 endfunction
493
Bram Moolenaar3c053a12022-10-16 13:11:12 +0100494If the file doesn't exist, Vim will also search in 'packpath' (under "start")
495to allow calling packages' functions from your .vimrc when the packages have
496not been added to 'runtimepath' yet (see |packages|).
497
Bram Moolenaar0daafaa2022-09-04 17:45:43 +0100498The file name and the name used before the # in the function must match
499exactly, and the defined function must have the name exactly as it will be
500called. In Vim9 script the "g:" prefix must be used: >
501 function g:filename#funcname()
502
503or for a compiled function: >
504 def g:filename#funcname()
505
506It is possible to use subdirectories. Every # in the function name works like
507a path separator. Thus when calling a function: >
508
509 :call foo#bar#func()
510
511Vim will look for the file "autoload/foo/bar.vim" in 'runtimepath'.
512
513This also works when reading a variable that has not been set yet: >
514
515 :let l = foo#bar#lvar
516
517However, when the autoload script was already loaded it won't be loaded again
518for an unknown variable.
519
520When assigning a value to such a variable nothing special happens. This can
521be used to pass settings to the autoload script before it's loaded: >
522
523 :let foo#bar#toggle = 1
524 :call foo#bar#func()
525
526Note that when you make a mistake and call a function that is supposed to be
527defined in an autoload script, but the script doesn't actually define the
528function, you will get an error message for the missing function. If you fix
529the autoload script it won't be automatically loaded again. Either restart
530Vim or manually source the script.
531
532Also note that if you have two script files, and one calls a function in the
533other and vice versa, before the used function is defined, it won't work.
534Avoid using the autoload functionality at the toplevel.
535
536In |Vim9| script you will get error *E1263* if you define a function with
537a "#" character in the name. You should use a name without "#" and use
538`:export`.
539
540Hint: If you distribute a bunch of scripts you can pack them together with the
541|vimball| utility. Also read the user manual |distribute-script|.
542
543
544 vim:tw=78:ts=8:noet:ft=help:norl: