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