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