Movatterモバイル変換


[0]ホーム

URL:


Userfunc

Nvim:help pages,generated fromsource using thetree-sitter-vimdoc parser.


Defining and using functions.
This is introduced in section41.7 of the user manual.
1. Defining a function
New functions can be defined. These can be called just like builtinfunctions. The function executes a sequence of Ex commands. Normal modecommands can be executed with the:normal command.
The function name must start with an uppercase letter, to avoid confusion withbuiltin functions. To prevent from using the same name in different scriptsmake them script-local. If you do use a global function then avoid obvious,short names. A good habit is to start the function name with the name of thescript, e.g., "HTMLcolor()".
It is also possible to use curly braces, seecurly-braces-names.
Theautoload facility is useful to define a function only when it's called.
local-function
A function local to a script must start with "s:". A local script functioncan only be called from within the script and from functions, user commandsand autocommands defined in the script. It is also possible to call thefunction from a mapping defined in the script, but then<SID> must be usedinstead of "s:" when the mapping is expanded outside of the script.There are only script-local functions, no buffer-local or window-localfunctions.
:fu:functionE128E129E123:fu[nction]List all functions and their arguments.
:fu[nction][!]{name}List function{name}, annotated with line numbersunless "!" is given.{name} may be aDictionaryFuncref entry:
:function dict.init
Note that{name} is not an expression, you cannot usea variable that is a function reference. You can usethis dirty trick to list the function referred to withvariable "Funcref":
let g:MyFuncref = Funcreffunc g:MyFuncrefunlet g:MyFuncref
:fu[nction] /{pattern}List functions with a name matching{pattern}.Example that lists all functions ending with "File":
:function /File$
:function-verbose
When'verbose' is non-zero, listing a function will also display where it waslast defined. Example:
:verbose function SetFileTypeSH    function SetFileTypeSH(name)        Last set from /usr/share/vim/vim-7.0/filetype.vim
See:verbose-cmd for more information.
E124E125E853E884:fu[nction][!]{name}([arguments]) [range] [abort] [dict] [closure]Define a new function by the name{name}. The body ofthe function follows in the next lines, until thematching:endfunction.
The name must be made of alphanumeric characters and'_', and must start with a capital or "s:" (seeabove). Note that using "b:" or "g:" is not allowed.(since patch 7.4.260 E884 is given if the functionname has a colon in the name, e.g. for "foo:bar()".Before that patch no error was given).
{name} may be aDictionaryFuncref entry:
:function dict.init(arg)
"dict" must be an existing dictionary. The entry"init" is added if it didn't exist yet. Otherwise [!]is required to overwrite an existing function. Theresult is aFuncref to a numbered function. Thefunction can only be used with aFuncref and will bedeleted if there are no more references to it.E127E122When a function by this name already exists and [!] isnot used an error message is given. There is oneexception: When sourcing a script again, a functionthat was previously defined in that script will besilently replaced.When [!] is used, an existing function is silentlyreplaced. Unless it is currently being executed, thatis an error.NOTE: Use ! wisely. If used without care it can causean existing function to be replaced unexpectedly,which is hard to debug.
For the{arguments} seefunction-argument.
:func-rangea:firstlinea:lastlineWhen the [range] argument is added, the function isexpected to take care of a range itself. The range ispassed as "a:firstline" and "a:lastline". If [range]is excluded, ":{range}call" will call the function foreach line in the range, with the cursor on the startof each line. Seefunction-range-example.The cursor is still moved to the first line of therange, as is the case with all Ex commands.:func-abort
When the [abort] argument is added, the function willabort as soon as an error is detected.:func-dict
When the [dict] argument is added, the function mustbe invoked through an entry in aDictionary. Thelocal variable "self" will then be set to thedictionary. SeeDictionary-function.:func-closureE932When the [closure] argument is added, the functioncan access variables and arguments from the outerscope. This is usually called a closure. In thisexample Bar() uses "x" from the scope of Foo(). Itremains referenced even after Foo() returns:
:function! Foo():  let x = 0:  function! Bar() closure:    let x += 1:    return x:  endfunction:  return funcref('Bar'):endfunction:let F = Foo():echo F()
1
:echo F()
2
:echo F()
3
function-search-undo
The last used search pattern and the redo command "."will not be changed by the function. This alsoimplies that the effect of:nohlsearch is undonewhen the function returns.
:endf:endfunctionE126E193W22:endf[unction] [argument]The end of a function definition. Best is to put iton a line by its own, without [argument].
[argument] can be:| commandcommand to execute next\n commandcommand to execute next" commentalways ignoredanything elseignored, warning given when'verbose' is non-zeroThe support for a following command was added in Vim8.0.0654, before that any argument was silentlyignored.
To be able to define a function inside an:executecommand, use line breaks instead of:bar:
:exe "func Foo()\necho 'foo'\nendfunc"
:delf:delfunctionE131E933:delf[unction][!]{name}Delete function{name}.{name} can also be aDictionary entry that is aFuncref:
:delfunc dict.init
This will remove the "init" entry from "dict". Thefunction is deleted if there are no more references toit.With the ! there is no error if the function does notexist.:retu:returnE133:retu[rn] [expr]Return from a function. When [expr] is given, it isevaluated and returned as the result of the function.If [expr] is not given, the number 0 is returned.When a function ends without an explicit ":return",the number 0 is returned.Note that there is no check for unreachable lines,thus there is no warning if commands follow ":return".Also, there is no check if the followingline contains a valid command. Forgetting the linecontinuation backslash may go unnoticed:
return 'some text'       .. ' some more text'
Will happily return "some text" without an error. Itshould have been:
return 'some text'       \ .. ' some more text'
If the ":return" is used after a:try but before thematching:finally (if present), the commandsfollowing the ":finally" up to the matching:endtryare executed first. This process applies to allnested ":try"s inside the function. The functionreturns at the outermost ":endtry".
function-argumenta:varAn argument can be defined by giving its name. In the function this can thenbe used as "a:name" ("a:" for argument).a:0a:1a:000E740...Up to 20 arguments can be given, separated by commas. After the namedarguments an argument "..." can be specified, which means that more argumentsmay optionally be following. In the function the extra arguments can be usedas "a:1", "a:2", etc. "a:0" is set to the number of extra arguments (whichcan be 0). "a:000" is set to aList that contains these arguments. Notethat "a:1" is the same as "a:000[0]".E742
The a: scope and the variables in it cannot be changed, they are fixed.However, if a composite type is used, such asList orDictionary , you canchange their contents. Thus you can pass aList to a function and have thefunction add an item to it. If you want to make sure the function cannotchange aList orDictionary use:lockvar.
It is also possible to define a function without any arguments. You muststill supply the () then.
It is allowed to define another function inside a function body.
optional-function-argument
You can provide default values for positional named arguments. This makesthem optional for function calls. When a positional argument is notspecified at a call, the default expression is used to initialize it.This only works for functions declared with:function, not forlambda expressionsexpr-lambda.
Example:
function Something(key, value = 10)   echo a:key .. ": " .. a:valueendfunctioncall Something('empty')"empty: 10"call Something('key', 20)"key: 20"
The argument default expressions are evaluated at the time of the functioncall, not when the function is defined. Thus it is possible to use anexpression which is invalid the moment the function is defined. Theexpressions are also only evaluated when arguments are not specified during acall.
E989
Optional arguments with default expressions must occur after any mandatoryarguments. You can use "..." after all optional named arguments.
It is possible for later argument defaults to refer to prior arguments,but not the other way around. They must be prefixed with "a:", as with allarguments.
Example that works:
:function Okay(mandatory, optional = a:mandatory):endfunction
Example that does NOT work:
:function NoGood(first = a:second, second = 10):endfunction
When not using "...", the number of arguments in a function call must be atleast equal to the number of mandatory named arguments. When using "...", thenumber of arguments may be larger than the total of mandatory and optionalarguments.
local-variables
Inside a function local variables can be used. These will disappear when thefunction returns. Global variables need to be accessed with "g:". Insidefunctions local variables are accessed without prepending anything. But youcan also prepend "l:" if you like. This is required for some reserved names,such as "version".
Example:
:function Table(title, ...):  echohl Title:  echo a:title:  echohl None:  echo a:0 .. " items:":  for s in a:000:    echon ' ' .. s:  endfor:endfunction
This function can then be called with:
call Table("Table", "line1", "line2")call Table("Empty Table")
To return more than one value, return aList:
:function Compute(n1, n2):  if a:n2 == 0:    return ["fail", 0]:  endif:  return ["ok", a:n1 / a:n2]:endfunction
This function can then be called with:
:let [success, div] = Compute(102, 6):if success == "ok":  echo div:endif
2. Calling a function
:cal:callE107E117:[range]cal[l]{name}([arguments])Call a function. The name of the function and its argumentsare as specified with:function. Up to 20 arguments can beused. The returned value is discarded.Without a range and for functions that accept a range, thefunction is called once. When a range is given the cursor ispositioned at the start of the first line before executing thefunction.When a range is given and the function doesn't handle ititself, the function is executed for each line in the range,with the cursor in the first column of that line. The cursoris left at the last line (possibly moved by the last functioncall). The arguments are re-evaluated for each line. Thusthis works:function-range-example
:function Mynumber(arg):  echo line(".") .. " " .. a:arg:endfunction:1,5call Mynumber(getline("."))
The "a:firstline" and "a:lastline" are defined anyway, theycan be used to do something different at the start or end ofthe range.
Example of a function that handles the range itself:
:function Cont() range:  execute (a:firstline + 1) .. "," .. a:lastline .. 's/^/\t\\ ':endfunction:4,8call Cont()
This function inserts the continuation character "\" in frontof all the lines in the range, except the first one.
When the function returns a composite value it can be furtherdereferenced, but the range will not be used then. Example:
:4,8call GetDict().method()
Here GetDict() gets the range but method() does not.
E132
The recursiveness of user functions is restricted with the'maxfuncdepth'option.
It is also possible to use:eval. It does not support a range, but doesallow for method chaining, e.g.:
eval GetList()->Filter()->append('$')
A function can also be called as part of evaluating an expression or when itis used as a method:
let x = GetList()let y = GetList()->Filter()
3. Cleaning up in a function
:defe:defer:defe[r]{func}({args})Call{func} when the current function is done.{args} are evaluated here.
Quite often a command in a function has a global effect, which must be undonewhen the function finishes. Handling this in all kinds of situations can be ahassle. Especially when an unexpected error is encountered. This can be donewithtry /finally blocks, but this gets complicated when there is morethan one.
A much simpler solution is usingdefer. It schedules a function call whenthe function is returning, no matter if there is an error. Example:
func Filter(text) abort  call writefile(a:text, 'Tempfile')  call system('filter < Tempfile > Outfile')  call Handle('Outfile')  call delete('Tempfile')  call delete('Outfile')endfunc
Here 'Tempfile' and 'Outfile' will not be deleted if something causes thefunction to abort.:defer can be used to avoid that:
func Filter(text) abort  call writefile(a:text, 'Tempfile')  defer delete('Tempfile')  defer delete('Outfile')  call system('filter < Tempfile > Outfile')  call Handle('Outfile')endfunc
Note that deleting "Outfile" is scheduled before callingsystem(), since itcan be created even whensystem() fails.
The deferred functions are called in reverse order, the last one added isexecuted first. A useless example:
func Useless() abort  for s in range(3)    defer execute('echomsg "number ' .. s .. '"')  endforendfunc
Now:messages shows:number 2number 1number 0
Any return value of the deferred function is discarded. The function cannotbe followed by anything, such as "->func" or ".member". Currently:defer GetArg()->TheFunc() does not work, it may work in a later version.
Errors are reported but do not cause aborting execution of deferred functionsor altering execution outside of deferred functions.
No range is accepted. The function can be a partial with extra arguments, butnot with a dictionary.E1300
4. Automatically loading functions
autoload-functions
When using many or large functions, it's possible to automatically define themonly when they are used. There are two methods: with an autocommand and withthe "autoload" directory in'runtimepath'.
Using an autocommand
This is introduced in the user manual, section41.14.
The autocommand is useful if you have a plugin that is a long Vim script file.You can define the autocommand and quickly quit the script with:finish.That makes Vim startup faster. The autocommand should then load the same fileagain, setting a variable to skip the:finish command.
Use the FuncUndefined autocommand event with a pattern that matches thefunction(s) to be defined. Example:
:au FuncUndefined BufNet* source ~/vim/bufnetfuncs.vim
The file "~/vim/bufnetfuncs.vim" should then define functions that start with"BufNet". Also seeFuncUndefined.
Using an autoload script
autoloadE746This is introduced in the user manual, section41.15.
Using a script in the "autoload" directory is simpler, but requires usingexactly the right file name. A function that can be autoloaded has a namelike this:
:call filename#funcname()
When such a function is called, and it is not defined yet, Vim will search the"autoload" directories in'runtimepath' for a script file called"filename.vim". For example "~/.config/nvim/autoload/filename.vim". Thatfile should then define the function like this:
function filename#funcname()   echo "Done!"endfunction
If the file doesn't exist, Vim will also search in'packpath' (under "start")to allow calling packages' functions from yourvimrc when the packages havenot been added to'runtimepath' yet (seepackages).
The file name and the name used before the # in the function must matchexactly, and the defined function must have the name exactly as it will becalled.
It is possible to use subdirectories. Every # in the function name works likea path separator. Thus when calling a function:
:call foo#bar#func()
Vim will look for the file "autoload/foo/bar.vim" in'runtimepath'.
This also works when reading a variable that has not been set yet:
:let l = foo#bar#lvar
However, when the autoload script was already loaded it won't be loaded againfor an unknown variable.
When assigning a value to such a variable nothing special happens. This canbe used to pass settings to the autoload script before it's loaded:
:let foo#bar#toggle = 1:call foo#bar#func()
Note that when you make a mistake and call a function that is supposed to bedefined in an autoload script, but the script doesn't actually define thefunction, you will get an error message for the missing function. If you fixthe autoload script it won't be automatically loaded again. Either restartVim or manually source the script.
Also note that if you have two script files, and one calls a function in theother and vice versa, before the used function is defined, it won't work.Avoid using the autoload functionality at the toplevel.
Hint: If you distribute a bunch of scripts readdistribute-script.
Main
Commands index
Quick reference


[8]ページ先頭

©2009-2025 Movatter.jp