32004
|
1 *userfunc.txt* For Vim version 9.0. Last change: 2023 Feb 02
|
30085
|
2
|
|
3
|
|
4 VIM REFERENCE MANUAL by Bram Moolenaar
|
|
5
|
|
6
|
|
7 Defining and using functions.
|
|
8
|
|
9 This is introduced in section |41.7| of the user manual.
|
|
10
|
31139
|
11 1. Defining a function |define-function|
|
|
12 2. Calling a function |:call|
|
30085
|
13 3. Cleaning up in a function |:defer|
|
|
14 4. Automatically loading functions |autoload-functions|
|
|
15
|
|
16 ==============================================================================
|
|
17
|
30324
|
18 1. Defining a function ~
|
30085
|
19 *define-function*
|
|
20 New functions can be defined. These can be called just like builtin
|
|
21 functions. The function executes a sequence of Ex commands. Normal mode
|
|
22 commands can be executed with the |:normal| command.
|
|
23
|
|
24 The function name must start with an uppercase letter, to avoid confusion with
|
|
25 builtin functions. To prevent from using the same name in different scripts
|
30202
|
26 make them script-local. If you do use a global function then avoid obvious,
|
30085
|
27 short names. A good habit is to start the function name with the name of the
|
|
28 script, e.g., "HTMLcolor()".
|
|
29
|
|
30 In legacy script it is also possible to use curly braces, see
|
|
31 |curly-braces-names|.
|
|
32
|
|
33 The |autoload| facility is useful to define a function only when it's called.
|
|
34
|
|
35 *local-function*
|
|
36 A function local to a legacy script must start with "s:". A local script
|
|
37 function can only be called from within the script and from functions, user
|
|
38 commands and autocommands defined in the script. It is also possible to call
|
|
39 the function from a mapping defined in the script, but then |<SID>| must be
|
|
40 used instead of "s:" when the mapping is expanded outside of the script.
|
|
41 There are only script-local functions, no buffer-local or window-local
|
|
42 functions.
|
|
43
|
|
44 In |Vim9| script functions are local to the script by default, prefix "g:" to
|
|
45 define 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*
|
|
60 When 'verbose' is non-zero, listing a function will also display where it was
|
|
61 last defined. Example: >
|
|
62
|
|
63 :verbose function SetFileTypeSH
|
|
64 function SetFileTypeSH(name)
|
|
65 Last set from /usr/share/vim/vim-7.0/filetype.vim
|
|
66 <
|
|
67 See |: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.
|
31671
|
190
|
30085
|
191 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
|
31671
|
195 `: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 <
|
30085
|
205 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*
|
|
213 An argument can be defined by giving its name. In the function this can then
|
32004
|
214 be used as "a:name" ("a:" for argument) (in a `:def` function "a:" is not
|
|
215 used).
|
30085
|
216 *a:0* *a:1* *a:000* *E740* *...*
|
|
217 Up to 20 arguments can be given, separated by commas. After the named
|
|
218 arguments an argument "..." can be specified, which means that more arguments
|
|
219 may optionally be following. In the function the extra arguments can be used
|
|
220 as "a:1", "a:2", etc. "a:0" is set to the number of extra arguments (which
|
|
221 can be 0). "a:000" is set to a |List| that contains these arguments. Note
|
|
222 that "a:1" is the same as "a:000[0]".
|
|
223 *E742* *E1090*
|
|
224 The a: scope and the variables in it cannot be changed, they are fixed.
|
|
225 However, if a composite type is used, such as |List| or |Dictionary| , you can
|
|
226 change their contents. Thus you can pass a |List| to a function and have the
|
|
227 function add an item to it. If you want to make sure the function cannot
|
|
228 change a |List| or |Dictionary| use |:lockvar|.
|
|
229
|
|
230 It is also possible to define a function without any arguments. You must
|
|
231 still supply the () then.
|
|
232
|
|
233 It is allowed to define another function inside a function body.
|
|
234
|
|
235 *optional-function-argument*
|
|
236 You can provide default values for positional named arguments. This makes
|
|
237 them optional for function calls. When a positional argument is not
|
|
238 specified at a call, the default expression is used to initialize it.
|
|
239 This only works for functions declared with `:function` or `:def`, not for
|
|
240 lambda expressions |expr-lambda|.
|
|
241
|
|
242 Example: >
|
|
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
|
|
249 The argument default expressions are evaluated at the time of the function
|
32004
|
250 call, not when the function is defined. Thus it is possible to use an
|
|
251 expression which is invalid the moment the function is defined. The
|
|
252 expressions are also only evaluated when arguments are not specified during a
|
|
253 call.
|
30085
|
254 *none-function_argument*
|
|
255 You can pass |v:none| to use the default expression. Note that this means you
|
|
256 cannot pass v:none as an ordinary value when an argument has a default
|
|
257 expression.
|
|
258
|
|
259 Example: >
|
|
260 function Something(a = 10, b = 20, c = 30)
|
|
261 endfunction
|
|
262 call Something(1, v:none, 3) " b = 20
|
|
263 <
|
|
264 *E989*
|
|
265 Optional arguments with default expressions must occur after any mandatory
|
|
266 arguments. You can use "..." after all optional named arguments.
|
|
267
|
|
268 It is possible for later argument defaults to refer to prior arguments,
|
|
269 but not the other way around. They must be prefixed with "a:", as with all
|
|
270 arguments.
|
|
271
|
|
272 Example that works: >
|
|
273 :function Okay(mandatory, optional = a:mandatory)
|
|
274 :endfunction
|
|
275 Example that does NOT work: >
|
|
276 :function NoGood(first = a:second, second = 10)
|
|
277 :endfunction
|
|
278 <
|
|
279 When not using "...", the number of arguments in a function call must be at
|
|
280 least equal to the number of mandatory named arguments. When using "...", the
|
|
281 number of arguments may be larger than the total of mandatory and optional
|
|
282 arguments.
|
|
283
|
|
284 *local-variables*
|
|
285 Inside a function local variables can be used. These will disappear when the
|
|
286 function returns. Global variables need to be accessed with "g:".
|
|
287 Inside functions local variables are accessed without prepending anything.
|
|
288 But you can also prepend "l:" if you like. This is required for some reserved
|
|
289 names, such as "count".
|
|
290
|
|
291 Example: >
|
|
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
|
|
302 This function can then be called with: >
|
|
303 call Table("Table", "line1", "line2")
|
|
304 call Table("Empty Table")
|
|
305
|
|
306 To 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
|
|
314 This 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
|
30324
|
322 2. Calling a function ~
|
30085
|
323 *: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*
|
|
368 When a function cannot be found the error "E117: Unknown function" will be
|
|
369 given. If the function was using an autoload path or an autoload import and
|
|
370 the script is a |Vim9| script, this may also be caused by the function not
|
|
371 being exported.
|
|
372
|
|
373 *E132*
|
|
374 The recursiveness of user functions is restricted with the |'maxfuncdepth'|
|
|
375 option.
|
|
376
|
|
377 It is also possible to use `:eval`. It does not support a range, but does
|
|
378 allow for method chaining, e.g.: >
|
|
379 eval GetList()->Filter()->append('$')
|
|
380
|
|
381 A function can also be called as part of evaluating an expression or when it
|
|
382 is used as a method: >
|
|
383 let x = GetList()
|
|
384 let y = GetList()->Filter()
|
|
385
|
|
386 ==============================================================================
|
|
387
|
|
388 3. 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
|
|
393 Quite often a command in a function has a global effect, which must be undone
|
|
394 when the function finishes. Handling this in all kinds of situations can be a
|
|
395 hassle. Especially when an unexpected error is encountered. This can be done
|
|
396 with `try` / `finally` blocks, but this gets complicated when there is more
|
|
397 than one.
|
|
398
|
|
399 A much simpler solution is using `defer`. It schedules a function call when
|
|
400 the 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
|
|
409 Here 'Tempfile' and 'Outfile' will not be deleted if something causes the
|
|
410 function 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
|
31028
|
419 Note that deleting "Outfile" is scheduled before calling `system()`, since it
|
30085
|
420 can be created even when `system()` fails.
|
|
421
|
|
422 The deferred functions are called in reverse order, the last one added is
|
|
423 executed 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
|
|
430 Now `:messages` shows:
|
|
431 number 2
|
|
432 number 1
|
|
433 number 0
|
|
434
|
|
435 Any return value of the deferred function is discarded. The function cannot
|
|
436 be followed by anything, such as "->func" or ".member". Currently `:defer
|
|
437 GetArg()->TheFunc()` does not work, it may work in a later version.
|
|
438
|
|
439 Errors are reported but do not cause aborting execution of deferred functions.
|
|
440
|
30202
|
441 No range is accepted. The function can be a partial with extra arguments, but
|
|
442 not with a dictionary. *E1300*
|
30085
|
443
|
|
444 ==============================================================================
|
|
445
|
|
446 4. Automatically loading functions ~
|
|
447 *autoload-functions*
|
|
448 When using many or large functions, it's possible to automatically define them
|
|
449 only when they are used. There are two methods: with an autocommand and with
|
|
450 the "autoload" directory in 'runtimepath'.
|
|
451
|
|
452 In |Vim9| script there is also an autoload mechanism for imported scripts, see
|
|
453 |import-autoload|.
|
|
454
|
|
455
|
|
456 Using an autocommand ~
|
|
457
|
|
458 This is introduced in the user manual, section |51.4|.
|
|
459
|
|
460 The autocommand is useful if you have a plugin that is a long Vim script file.
|
|
461 You can define the autocommand and quickly quit the script with `:finish`.
|
|
462 That makes Vim startup faster. The autocommand should then load the same file
|
|
463 again, setting a variable to skip the `:finish` command.
|
|
464
|
|
465 Use the FuncUndefined autocommand event with a pattern that matches the
|
|
466 function(s) to be defined. Example: >
|
|
467
|
|
468 :au FuncUndefined BufNet* source ~/vim/bufnetfuncs.vim
|
|
469
|
|
470 The file "~/vim/bufnetfuncs.vim" should then define functions that start with
|
|
471 "BufNet". Also see |FuncUndefined|.
|
|
472
|
|
473
|
|
474 Using an autoload script ~
|
|
475 *autoload* *E746*
|
|
476 This is introduced in the user manual, section |52.2|.
|
|
477
|
|
478 Using a script in the "autoload" directory is simpler, but requires using
|
|
479 exactly the right file name. A function that can be autoloaded has a name
|
|
480 like this: >
|
|
481
|
|
482 :call filename#funcname()
|
|
483
|
|
484 These functions are always global, in Vim9 script "g:" needs to be used: >
|
|
485 :call g:filename#funcname()
|
|
486
|
|
487 When 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
|
|
490 then define the function like this: >
|
|
491
|
|
492 function filename#funcname()
|
|
493 echo "Done!"
|
|
494 endfunction
|
|
495
|
30875
|
496 If the file doesn't exist, Vim will also search in 'packpath' (under "start")
|
|
497 to allow calling packages' functions from your .vimrc when the packages have
|
|
498 not been added to 'runtimepath' yet (see |packages|).
|
|
499
|
30085
|
500 The file name and the name used before the # in the function must match
|
|
501 exactly, and the defined function must have the name exactly as it will be
|
|
502 called. In Vim9 script the "g:" prefix must be used: >
|
|
503 function g:filename#funcname()
|
|
504
|
|
505 or for a compiled function: >
|
|
506 def g:filename#funcname()
|
|
507
|
|
508 It is possible to use subdirectories. Every # in the function name works like
|
|
509 a path separator. Thus when calling a function: >
|
|
510
|
|
511 :call foo#bar#func()
|
|
512
|
|
513 Vim will look for the file "autoload/foo/bar.vim" in 'runtimepath'.
|
|
514
|
|
515 This also works when reading a variable that has not been set yet: >
|
|
516
|
|
517 :let l = foo#bar#lvar
|
|
518
|
|
519 However, when the autoload script was already loaded it won't be loaded again
|
|
520 for an unknown variable.
|
|
521
|
|
522 When assigning a value to such a variable nothing special happens. This can
|
|
523 be 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
|
|
528 Note that when you make a mistake and call a function that is supposed to be
|
|
529 defined in an autoload script, but the script doesn't actually define the
|
|
530 function, you will get an error message for the missing function. If you fix
|
|
531 the autoload script it won't be automatically loaded again. Either restart
|
|
532 Vim or manually source the script.
|
|
533
|
|
534 Also note that if you have two script files, and one calls a function in the
|
|
535 other and vice versa, before the used function is defined, it won't work.
|
|
536 Avoid using the autoload functionality at the toplevel.
|
|
537
|
|
538 In |Vim9| script you will get error *E1263* if you define a function with
|
|
539 a "#" character in the name. You should use a name without "#" and use
|
|
540 `:export`.
|
|
541
|
|
542 Hint: 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:
|