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