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