1
0
forked from aniani/vim

Update runtime files

This commit is contained in:
Bram Moolenaar
2022-09-04 17:45:43 +01:00
parent 806a273f3c
commit 0daafaa7d9
39 changed files with 922 additions and 687 deletions

View File

@@ -115,6 +115,7 @@ DOCS = \
todo.txt \
uganda.txt \
undo.txt \
userfunc.txt \
usr_01.txt \
usr_02.txt \
usr_03.txt \
@@ -265,6 +266,7 @@ HTMLS = \
todo.html \
uganda.html \
undo.html \
userfunc.html \
usr_01.html \
usr_02.html \
usr_03.html \

View File

@@ -640,6 +640,8 @@ CmdwinLeave Before leaving the command-line window.
|cmdwin-char|
*ColorScheme*
ColorScheme After loading a color scheme. |:colorscheme|
Not triggered if the color scheme is not
found.
The pattern is matched against the
colorscheme name. <afile> can be used for the
name of the actual file where this option was

View File

@@ -1671,7 +1671,7 @@ complete_info([{what}]) *complete_info()*
typed text only, or the last completion after
no item is selected when using the <Up> or
<Down> keys)
inserted Inserted string. [NOT IMPLEMENT YET]
inserted Inserted string. [NOT IMPLEMENTED YET]
*complete_info_mode*
mode values are:
@@ -3038,10 +3038,10 @@ function({name} [, {arglist}] [, {dict}])
Funcref. The extra arguments are appended to the list of
arguments. Example: >
func Callback(arg1, arg2, name)
...
"...
let Func = function('Callback', ['one'])
let Func2 = function(Func, ['two'])
...
"...
call Func2('name')
< Invokes the function as with: >
call Callback('one', 'two', 'name')
@@ -3051,22 +3051,23 @@ function({name} [, {arglist}] [, {dict}])
function Callback() dict
echo "called for " .. self.name
endfunction
...
"...
let context = {"name": "example"}
let Func = function('Callback', context)
...
"...
call Func() " will echo: called for example
< The use of function() is not needed when there are no extra
arguments, these two are equivalent: >
arguments, these two are equivalent, if Callback() is defined
as context.Callback(): >
let Func = function('Callback', context)
let Func = context.Callback
< The argument list and the Dictionary can be combined: >
function Callback(arg1, count) dict
...
"...
let context = {"name": "example"}
let Func = function('Callback', ['one'], context)
...
"...
call Func(500)
< Invokes the function as with: >
call context.Callback('one', 500)

View File

@@ -2629,503 +2629,12 @@ help file: |builtin-functions|.
5. Defining functions *user-functions*
New functions can be defined. These can be called just like builtin
functions. The function executes a sequence of Ex commands. Normal mode
commands can be executed with the |:normal| command.
functions. The function takes arguments, executes a sequence of Ex commands
and can return a value.
This section is about the legacy functions. For the Vim9 functions, which
execute much faster, support type checking and more, see |vim9.txt|.
The function name must start with an uppercase letter, to avoid confusion with
builtin functions. To prevent from using the same name in different scripts
avoid obvious, short names. A good habit is to start the function name with
the name of the script, e.g., "HTMLcolor()".
In legacy script it is also possible to use curly braces, see
|curly-braces-names|.
The |autoload| facility is useful to define a function only when it's called.
*local-function*
A function local to a legacy script must start with "s:". A local script
function can only be called from within the script and from functions, user
commands and autocommands defined in the script. It is also possible to call
the function from a mapping defined in the script, but then |<SID>| must be
used instead of "s:" when the mapping is expanded outside of the script.
There are only script-local functions, no buffer-local or window-local
functions.
In |Vim9| script functions are local to the script by default, prefix "g:" to
define a global function.
*:fu* *:function* *E128* *E129* *E123* *E454*
:fu[nction] List all functions and their arguments.
:fu[nction] {name} List function {name}.
{name} can also be a |Dictionary| entry that is a
|Funcref|: >
:function dict.init
: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 was
last 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.
*E124* *E125* *E853* *E884*
:fu[nction][!] {name}([arguments]) [range] [abort] [dict] [closure]
Define a new function by the name {name}. The body of
the function follows in the next lines, until the
matching |:endfunction|.
*E1267*
The name must be made of alphanumeric characters and
'_', and must start with a capital or "s:" (see
above). Note that using "b:" or "g:" is not allowed.
(since patch 7.4.260 E884 is given if the function
name has a colon in the name, e.g. for "foo:bar()".
Before that patch no error was given).
{name} can also be a |Dictionary| entry that is a
|Funcref|: >
: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. The
result is a |Funcref| to a numbered function. The
function can only be used with a |Funcref| and will be
deleted if there are no more references to it.
*E127* *E122*
When a function by this name already exists and [!] is
not used an error message is given. There is one
exception: When sourcing a script again, a function
that was previously defined in that script will be
silently replaced.
When [!] is used, an existing function is silently
replaced. Unless it is currently being executed, that
is an error.
NOTE: Use ! wisely. If used without care it can cause
an existing function to be replaced unexpectedly,
which is hard to debug.
NOTE: In Vim9 script script-local functions cannot be
deleted or redefined.
For the {arguments} see |function-argument|.
*:func-range* *a:firstline* *a:lastline*
When the [range] argument is added, the function is
expected to take care of a range itself. The range is
passed as "a:firstline" and "a:lastline". If [range]
is excluded, ":{range}call" will call the function for
each line in the range, with the cursor on the start
of each line. See |function-range-example|.
The cursor is still moved to the first line of the
range, as is the case with all Ex commands.
*:func-abort*
When the [abort] argument is added, the function will
abort as soon as an error is detected.
*:func-dict*
When the [dict] argument is added, the function must
be invoked through an entry in a |Dictionary|. The
local variable "self" will then be set to the
dictionary. See |Dictionary-function|.
*:func-closure* *E932*
When the [closure] argument is added, the function
can access variables and arguments from the outer
scope. This is usually called a closure. In this
example Bar() uses "x" from the scope of Foo(). It
remains 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 also
implies that the effect of |:nohlsearch| is undone
when the function returns.
*:endf* *:endfunction* *E126* *E193* *W22* *E1151*
:endf[unction] [argument]
The end of a function definition. Best is to put it
on a line by its own, without [argument].
[argument] can be:
| command command to execute next
\n command command to execute next
" comment always ignored
anything else ignored, warning given when
'verbose' is non-zero
The support for a following command was added in Vim
8.0.0654, before that any argument was silently
ignored.
To be able to define a function inside an `:execute`
command, use line breaks instead of |:bar|: >
:exe "func Foo()\necho 'foo'\nendfunc"
<
*:delf* *:delfunction* *E131* *E933* *E1084*
:delf[unction][!] {name}
Delete function {name}.
{name} can also be a |Dictionary| entry that is a
|Funcref|: >
:delfunc dict.init
< This will remove the "init" entry from "dict". The
function is deleted if there are no more references to
it.
With the ! there is no error if the function does not
exist.
*:retu* *:return* *E133*
:retu[rn] [expr] Return from a function. When "[expr]" is given, it is
evaluated 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.
In a :def function *E1095* is given if unreachable
code follows after the `:return`.
In legacy script there is no check for unreachable
lines, thus there is no warning if commands follow
`:return`.
If the ":return" is used after a |:try| but before the
matching |:finally| (if present), the commands
following the ":finally" up to the matching |:endtry|
are executed first. This process applies to all
nested ":try"s inside the function. The function
returns at the outermost ":endtry".
*function-argument* *a:var*
An argument can be defined by giving its name. In the function this can then
be used as "a:name" ("a:" for argument).
*a:0* *a:1* *a:000* *E740* *...*
Up to 20 arguments can be given, separated by commas. After the named
arguments an argument "..." can be specified, which means that more arguments
may optionally be following. In the function the extra arguments can be used
as "a:1", "a:2", etc. "a:0" is set to the number of extra arguments (which
can be 0). "a:000" is set to a |List| that contains these arguments. Note
that "a:1" is the same as "a:000[0]".
*E742* *E1090*
The a: scope and the variables in it cannot be changed, they are fixed.
However, if a composite type is used, such as |List| or |Dictionary| , you can
change their contents. Thus you can pass a |List| to a function and have the
function add an item to it. If you want to make sure the function cannot
change a |List| or |Dictionary| use |:lockvar|.
It is also possible to define a function without any arguments. You must
still 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 makes
them optional for function calls. When a positional argument is not
specified at a call, the default expression is used to initialize it.
This only works for functions declared with `:function` or `:def`, not for
lambda expressions |expr-lambda|.
Example: >
function Something(key, value = 10)
echo a:key .. ": " .. a:value
endfunction
call Something('empty') "empty: 10"
call Something('key', 20) "key: 20"
The argument default expressions are evaluated at the time of the function
call, not definition. Thus it is possible to use an expression which is
invalid the moment the function is defined. The expressions are also only
evaluated when arguments are not specified during a call.
*none-function_argument*
You can pass |v:none| to use the default expression. Note that this means you
cannot pass v:none as an ordinary value when an argument has a default
expression.
Example: >
function Something(a = 10, b = 20, c = 30)
endfunction
call Something(1, v:none, 3) " b = 20
<
*E989*
Optional arguments with default expressions must occur after any mandatory
arguments. 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 all
arguments.
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 at
least equal to the number of mandatory named arguments. When using "...", the
number of arguments may be larger than the total of mandatory and optional
arguments.
*local-variables*
Inside a function local variables can be used. These will disappear when the
function returns. Global variables need to be accessed with "g:".
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 a |List|: >
: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
<
*:cal* *:call* *E107*
:[range]cal[l] {name}([arguments])
Call a function. The name of the function and its arguments
are as specified with `:function`. Up to 20 arguments can be
used. The returned value is discarded.
In |Vim9| script using `:call` is optional, these two lines do
the same thing: >
call SomeFunc(arg)
SomeFunc(arg)
< Without a range and for functions that accept a range, the
function is called once. When a range is given the cursor is
positioned at the start of the first line before executing the
function.
When a range is given and the function doesn't handle it
itself, the function is executed for each line in the range,
with the cursor in the first column of that line. The cursor
is left at the last line (possibly moved by the last function
call). The arguments are re-evaluated for each line. Thus
this 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, they
can be used to do something different at the start or end of
the 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 front
of all the lines in the range, except the first one.
When the function returns a composite value it can be further
dereferenced, but the range will not be used then. Example: >
:4,8call GetDict().method()
< Here GetDict() gets the range but method() does not.
*E117*
When a function cannot be found the error "E117: Unknown function" will be
given. If the function was using an autoload path or an autoload import and
the script is a |Vim9| script, this may also be caused by the function not
being exported.
*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 does
allow for method chaining, e.g.: >
eval GetList()->Filter()->append('$')
A function can also be called as part of evaluating an expression or when it
is used as a method: >
let x = GetList()
let y = GetList()->Filter()
CLEANING UP IN A FUNCTION ~
*:defer*
:defer {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 undone
when the function finishes. Handling this in all kinds of situations can be a
hassle. Especially when an unexpected error is encountered. This can be done
with `try` / `finally` blocks, but this gets complicated when there is more
than one.
A much simpler solution is using `defer`. It schedules a function call when
the function is returning, no matter if there is an error. Example: >
func Filter(text)
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 the
function to abort. `:defer` can be used to avoid that: >
func Filter(text)
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 calling system(), since it
can be created even when `system()` fails.
The defered functions are called in reverse order, the last one added is
executed first. A useless example: >
func Useless()
for s in range(3)
defer execute('echomsg "number ' .. s .. '"')
endfor
endfunc
Now `:messages` shows:
number 2
number 1
number 0
Any return value of the deferred function is discarded. The function cannot
be 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 functions.
No range is accepted.
AUTOMATICALLY LOADING FUNCTIONS ~
*autoload-functions*
When using many or large functions, it's possible to automatically define them
only when they are used. There are two methods: with an autocommand and with
the "autoload" directory in 'runtimepath'.
Using an autocommand ~
This is introduced in the user manual, section |51.4|.
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 file
again, setting a variable to skip the `:finish` command.
Use the FuncUndefined autocommand event with a pattern that matches the
function(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 see |FuncUndefined|.
Using an autoload script ~
*autoload* *E746*
This is introduced in the user manual, section |52.2|.
Using a script in the "autoload" directory is simpler, but requires using
exactly the right file name. A function that can be autoloaded has a name
like this: >
:call filename#funcname()
These functions are always global, in Vim9 script "g:" needs to be used: >
:call g: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 "~/.vim/autoload/filename.vim". That file should
then define the function like this: >
function filename#funcname()
echo "Done!"
endfunction
The file name and the name used before the # in the function must match
exactly, and the defined function must have the name exactly as it will be
called. In Vim9 script the "g:" prefix must be used: >
function g:filename#funcname()
or for a compiled function: >
def g:filename#funcname()
It is possible to use subdirectories. Every # in the function name works like
a 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 again
for an unknown variable.
When assigning a value to such a variable nothing special happens. This can
be 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 be
defined in an autoload script, but the script doesn't actually define the
function, you will get an error message for the missing function. If you fix
the autoload script it won't be automatically loaded again. Either restart
Vim or manually source the script.
Also note that if you have two script files, and one calls a function in the
other and vice versa, before the used function is defined, it won't work.
Avoid using the autoload functionality at the toplevel.
In |Vim9| script you will get error *E1263* if you define a function with
a "#" character in the name. You should use a name without "#" and use
`:export`.
Hint: If you distribute a bunch of scripts you can pack them together with the
|vimball| utility. Also read the user manual |distribute-script|.
You can find most information about defining functions in |userfunc.txt|.
For Vim9 functions, which execute much faster, support type checking and more,
see |vim9.txt|.
==============================================================================
6. Curly braces names *curly-braces-names*

View File

@@ -141,6 +141,7 @@ Advanced editing ~
|autocmd.txt| automatically executing commands on an event
|eval.txt| expression evaluation, conditional commands
|builtin.txt| builtin functions
|userfunc.txt| defining user functions
|channel.txt| Jobs, Channels, inter-process communication
|fold.txt| hide (fold) ranges of lines

View File

@@ -1582,7 +1582,7 @@ $quote eval.txt /*$quote*
-xrm gui_x11.txt /*-xrm*
-y starting.txt /*-y*
. repeat.txt /*.*
... eval.txt /*...*
... userfunc.txt /*...*
.Xdefaults gui_x11.txt /*.Xdefaults*
.aff spell.txt /*.aff*
.dic spell.txt /*.dic*
@@ -2260,8 +2260,8 @@ $quote eval.txt /*$quote*
:caddfile quickfix.txt /*:caddfile*
:caf quickfix.txt /*:caf*
:cafter quickfix.txt /*:cafter*
:cal eval.txt /*:cal*
:call eval.txt /*:call*
:cal userfunc.txt /*:cal*
:call userfunc.txt /*:call*
:cat eval.txt /*:cat*
:catch eval.txt /*:catch*
:cb quickfix.txt /*:cb*
@@ -2405,13 +2405,14 @@ $quote eval.txt /*$quote*
:def vim9.txt /*:def*
:defc vim9.txt /*:defc*
:defcompile vim9.txt /*:defcompile*
:defer userfunc.txt /*:defer*
:del change.txt /*:del*
:delc map.txt /*:delc*
:delcommand map.txt /*:delcommand*
:delcr todo.txt /*:delcr*
:delete change.txt /*:delete*
:delf eval.txt /*:delf*
:delfunction eval.txt /*:delfunction*
:delf userfunc.txt /*:delf*
:delfunction userfunc.txt /*:delfunction*
:delm motion.txt /*:delm*
:delmarks motion.txt /*:delmarks*
:di change.txt /*:di*
@@ -2488,10 +2489,10 @@ $quote eval.txt /*$quote*
:endclass vim9.txt /*:endclass*
:enddef vim9.txt /*:enddef*
:endenum vim9.txt /*:endenum*
:endf eval.txt /*:endf*
:endf userfunc.txt /*:endf*
:endfo eval.txt /*:endfo*
:endfor eval.txt /*:endfor*
:endfunction eval.txt /*:endfunction*
:endfunction userfunc.txt /*:endfunction*
:endif eval.txt /*:endif*
:endinterface vim9.txt /*:endinterface*
:endt eval.txt /*:endt*
@@ -2553,13 +2554,13 @@ $quote eval.txt /*$quote*
:foldo fold.txt /*:foldo*
:foldopen fold.txt /*:foldopen*
:for eval.txt /*:for*
:fu eval.txt /*:fu*
:func-abort eval.txt /*:func-abort*
:func-closure eval.txt /*:func-closure*
:func-dict eval.txt /*:func-dict*
:func-range eval.txt /*:func-range*
:function eval.txt /*:function*
:function-verbose eval.txt /*:function-verbose*
:fu userfunc.txt /*:fu*
:func-abort userfunc.txt /*:func-abort*
:func-closure userfunc.txt /*:func-closure*
:func-dict userfunc.txt /*:func-dict*
:func-range userfunc.txt /*:func-range*
:function userfunc.txt /*:function*
:function-verbose userfunc.txt /*:function-verbose*
:g repeat.txt /*:g*
:global repeat.txt /*:global*
:go motion.txt /*:go*
@@ -2599,6 +2600,8 @@ $quote eval.txt /*$quote*
:his cmdline.txt /*:his*
:history cmdline.txt /*:history*
:history-indexing cmdline.txt /*:history-indexing*
:hor windows.txt /*:hor*
:horizontal windows.txt /*:horizontal*
:i insert.txt /*:i*
:ia map.txt /*:ia*
:iabbrev map.txt /*:iabbrev*
@@ -3049,8 +3052,8 @@ $quote eval.txt /*$quote*
:ret change.txt /*:ret*
:retab change.txt /*:retab*
:retab! change.txt /*:retab!*
:retu eval.txt /*:retu*
:return eval.txt /*:return*
:retu userfunc.txt /*:retu*
:return userfunc.txt /*:return*
:rew editing.txt /*:rew*
:rewind editing.txt /*:rewind*
:ri change.txt /*:ri*
@@ -4078,7 +4081,7 @@ E1066 vim9.txt /*E1066*
E1067 eval.txt /*E1067*
E1068 vim9.txt /*E1068*
E1069 vim9.txt /*E1069*
E107 eval.txt /*E107*
E107 userfunc.txt /*E107*
E1071 vim9.txt /*E1071*
E1072 eval.txt /*E1072*
E1073 vim9.txt /*E1073*
@@ -4093,18 +4096,18 @@ E1080 vim9.txt /*E1080*
E1081 eval.txt /*E1081*
E1082 vim9.txt /*E1082*
E1083 editing.txt /*E1083*
E1084 eval.txt /*E1084*
E1084 userfunc.txt /*E1084*
E1085 eval.txt /*E1085*
E1087 vim9.txt /*E1087*
E1088 vim9.txt /*E1088*
E1089 eval.txt /*E1089*
E109 eval.txt /*E109*
E1090 eval.txt /*E1090*
E1090 userfunc.txt /*E1090*
E1091 vim9.txt /*E1091*
E1092 various.txt /*E1092*
E1093 eval.txt /*E1093*
E1094 vim9.txt /*E1094*
E1095 eval.txt /*E1095*
E1095 userfunc.txt /*E1095*
E1096 vim9.txt /*E1096*
E1097 vim9.txt /*E1097*
E1098 eval.txt /*E1098*
@@ -4167,7 +4170,7 @@ E1148 eval.txt /*E1148*
E1149 vim9.txt /*E1149*
E115 eval.txt /*E115*
E1150 vim9.txt /*E1150*
E1151 eval.txt /*E1151*
E1151 userfunc.txt /*E1151*
E1152 vim9.txt /*E1152*
E1153 eval.txt /*E1153*
E1154 eval.txt /*E1154*
@@ -4187,7 +4190,7 @@ E1166 eval.txt /*E1166*
E1167 vim9.txt /*E1167*
E1168 vim9.txt /*E1168*
E1169 eval.txt /*E1169*
E117 eval.txt /*E117*
E117 userfunc.txt /*E117*
E1170 vim9.txt /*E1170*
E1171 vim9.txt /*E1171*
E1172 vim9.txt /*E1172*
@@ -4243,7 +4246,7 @@ E1216 builtin.txt /*E1216*
E1217 vim9.txt /*E1217*
E1218 vim9.txt /*E1218*
E1219 vim9.txt /*E1219*
E122 eval.txt /*E122*
E122 userfunc.txt /*E122*
E1220 vim9.txt /*E1220*
E1221 vim9.txt /*E1221*
E1222 vim9.txt /*E1222*
@@ -4254,7 +4257,7 @@ E1226 vim9.txt /*E1226*
E1227 vim9.txt /*E1227*
E1228 vim9.txt /*E1228*
E1229 eval.txt /*E1229*
E123 eval.txt /*E123*
E123 userfunc.txt /*E123*
E1230 options.txt /*E1230*
E1231 map.txt /*E1231*
E1232 builtin.txt /*E1232*
@@ -4264,7 +4267,7 @@ E1236 vim9.txt /*E1236*
E1237 map.txt /*E1237*
E1238 vim9.txt /*E1238*
E1239 builtin.txt /*E1239*
E124 eval.txt /*E124*
E124 userfunc.txt /*E124*
E1240 change.txt /*E1240*
E1241 change.txt /*E1241*
E1242 change.txt /*E1242*
@@ -4275,7 +4278,7 @@ E1246 eval.txt /*E1246*
E1247 cmdline.txt /*E1247*
E1248 vim9.txt /*E1248*
E1249 syntax.txt /*E1249*
E125 eval.txt /*E125*
E125 userfunc.txt /*E125*
E1250 vim9.txt /*E1250*
E1251 vim9.txt /*E1251*
E1252 vim9.txt /*E1252*
@@ -4286,18 +4289,18 @@ E1256 vim9.txt /*E1256*
E1257 vim9.txt /*E1257*
E1258 vim9.txt /*E1258*
E1259 vim9.txt /*E1259*
E126 eval.txt /*E126*
E126 userfunc.txt /*E126*
E1260 vim9.txt /*E1260*
E1261 vim9.txt /*E1261*
E1262 vim9.txt /*E1262*
E1263 eval.txt /*E1263*
E1263 userfunc.txt /*E1263*
E1264 vim9.txt /*E1264*
E1265 eval.txt /*E1265*
E1266 if_pyth.txt /*E1266*
E1267 eval.txt /*E1267*
E1267 userfunc.txt /*E1267*
E1268 vim9.txt /*E1268*
E1269 vim9.txt /*E1269*
E127 eval.txt /*E127*
E127 userfunc.txt /*E127*
E1270 change.txt /*E1270*
E1271 vim9.txt /*E1271*
E1272 vim9.txt /*E1272*
@@ -4308,7 +4311,7 @@ E1276 builtin.txt /*E1276*
E1277 channel.txt /*E1277*
E1278 eval.txt /*E1278*
E1279 eval.txt /*E1279*
E128 eval.txt /*E128*
E128 userfunc.txt /*E128*
E1280 spell.txt /*E1280*
E1281 pattern.txt /*E1281*
E1282 eval.txt /*E1282*
@@ -4319,7 +4322,7 @@ E1286 builtin.txt /*E1286*
E1287 builtin.txt /*E1287*
E1288 builtin.txt /*E1288*
E1289 builtin.txt /*E1289*
E129 eval.txt /*E129*
E129 userfunc.txt /*E129*
E1290 change.txt /*E1290*
E1291 testing.txt /*E1291*
E1292 cmdline.txt /*E1292*
@@ -4328,10 +4331,11 @@ E1294 textprop.txt /*E1294*
E1295 textprop.txt /*E1295*
E1296 textprop.txt /*E1296*
E1297 vim9.txt /*E1297*
E1298 vim9.txt /*E1298*
E13 message.txt /*E13*
E131 eval.txt /*E131*
E132 eval.txt /*E132*
E133 eval.txt /*E133*
E131 userfunc.txt /*E131*
E132 userfunc.txt /*E132*
E133 userfunc.txt /*E133*
E134 change.txt /*E134*
E135 autocmd.txt /*E135*
E136 starting.txt /*E136*
@@ -4396,7 +4400,7 @@ E19 message.txt /*E19*
E190 message.txt /*E190*
E191 motion.txt /*E191*
E192 message.txt /*E192*
E193 eval.txt /*E193*
E193 userfunc.txt /*E193*
E194 message.txt /*E194*
E195 starting.txt /*E195*
E196 various.txt /*E196*
@@ -4675,7 +4679,7 @@ E450 popup.txt /*E450*
E451 eval.txt /*E451*
E452 eval.txt /*E452*
E453 syntax.txt /*E453*
E454 eval.txt /*E454*
E454 userfunc.txt /*E454*
E455 print.txt /*E455*
E456 print.txt /*E456*
E457 print.txt /*E457*
@@ -4978,13 +4982,13 @@ E737 builtin.txt /*E737*
E738 eval.txt /*E738*
E739 builtin.txt /*E739*
E74 message.txt /*E74*
E740 eval.txt /*E740*
E740 userfunc.txt /*E740*
E741 eval.txt /*E741*
E742 eval.txt /*E742*
E742 userfunc.txt /*E742*
E743 eval.txt /*E743*
E744 netbeans.txt /*E744*
E745 eval.txt /*E745*
E746 eval.txt /*E746*
E746 userfunc.txt /*E746*
E747 editing.txt /*E747*
E748 repeat.txt /*E748*
E749 various.txt /*E749*
@@ -5101,7 +5105,7 @@ E85 options.txt /*E85*
E850 change.txt /*E850*
E851 gui_x11.txt /*E851*
E852 gui_x11.txt /*E852*
E853 eval.txt /*E853*
E853 userfunc.txt /*E853*
E854 options.txt /*E854*
E855 autocmd.txt /*E855*
E856 testing.txt /*E856*
@@ -5135,7 +5139,7 @@ E880 if_pyth.txt /*E880*
E881 autocmd.txt /*E881*
E882 builtin.txt /*E882*
E883 builtin.txt /*E883*
E884 eval.txt /*E884*
E884 userfunc.txt /*E884*
E885 sign.txt /*E885*
E886 starting.txt /*E886*
E887 if_pyth.txt /*E887*
@@ -5188,8 +5192,8 @@ E929 starting.txt /*E929*
E93 windows.txt /*E93*
E930 builtin.txt /*E930*
E931 message.txt /*E931*
E932 eval.txt /*E932*
E933 eval.txt /*E933*
E932 userfunc.txt /*E932*
E933 userfunc.txt /*E933*
E934 sign.txt /*E934*
E935 builtin.txt /*E935*
E936 autocmd.txt /*E936*
@@ -5250,7 +5254,7 @@ E985 eval.txt /*E985*
E986 tagsrch.txt /*E986*
E987 tagsrch.txt /*E987*
E988 gui_w32.txt /*E988*
E989 eval.txt /*E989*
E989 userfunc.txt /*E989*
E99 diff.txt /*E99*
E990 eval.txt /*E990*
E991 eval.txt /*E991*
@@ -5572,7 +5576,7 @@ W18 syntax.txt /*W18*
W19 autocmd.txt /*W19*
W20 if_pyth.txt /*W20*
W21 if_pyth.txt /*W21*
W22 eval.txt /*W22*
W22 userfunc.txt /*W22*
WORD motion.txt /*WORD*
WSL os_win32.txt /*WSL*
WWW intro.txt /*WWW*
@@ -5707,12 +5711,12 @@ a' motion.txt /*a'*
a( motion.txt /*a(*
a) motion.txt /*a)*
a4 print.txt /*a4*
a:0 eval.txt /*a:0*
a:000 eval.txt /*a:000*
a:1 eval.txt /*a:1*
a:firstline eval.txt /*a:firstline*
a:lastline eval.txt /*a:lastline*
a:var eval.txt /*a:var*
a:0 userfunc.txt /*a:0*
a:000 userfunc.txt /*a:000*
a:1 userfunc.txt /*a:1*
a:firstline userfunc.txt /*a:firstline*
a:lastline userfunc.txt /*a:lastline*
a:var userfunc.txt /*a:var*
a< motion.txt /*a<*
a> motion.txt /*a>*
aB motion.txt /*aB*
@@ -5858,8 +5862,8 @@ autocommand-events autocmd.txt /*autocommand-events*
autocommand-pattern autocmd.txt /*autocommand-pattern*
autocommands autocmd.txt /*autocommands*
autoformat change.txt /*autoformat*
autoload eval.txt /*autoload*
autoload-functions eval.txt /*autoload-functions*
autoload userfunc.txt /*autoload*
autoload-functions userfunc.txt /*autoload-functions*
avoid-hit-enter version5.txt /*avoid-hit-enter*
aw motion.txt /*aw*
a{ motion.txt /*a{*
@@ -6493,6 +6497,7 @@ decada_members ft_ada.txt /*decada_members*
deepcopy() builtin.txt /*deepcopy()*
defaults.vim starting.txt /*defaults.vim*
defaults.vim-explained usr_05.txt /*defaults.vim-explained*
define-function userfunc.txt /*define-function*
definition-search tagsrch.txt /*definition-search*
definitions intro.txt /*definitions*
delete() builtin.txt /*delete()*
@@ -7131,11 +7136,11 @@ ftplugins usr_05.txt /*ftplugins*
fullcommand() builtin.txt /*fullcommand()*
funcref() builtin.txt /*funcref()*
function() builtin.txt /*function()*
function-argument eval.txt /*function-argument*
function-argument userfunc.txt /*function-argument*
function-key intro.txt /*function-key*
function-list usr_41.txt /*function-list*
function-range-example eval.txt /*function-range-example*
function-search-undo eval.txt /*function-search-undo*
function-range-example userfunc.txt /*function-range-example*
function-search-undo userfunc.txt /*function-search-undo*
function_key intro.txt /*function_key*
functions eval.txt /*functions*
fuzzy-matching pattern.txt /*fuzzy-matching*
@@ -8182,10 +8187,10 @@ lnum-variable eval.txt /*lnum-variable*
load-plugins starting.txt /*load-plugins*
load-vim-script repeat.txt /*load-vim-script*
local-additions help.txt /*local-additions*
local-function eval.txt /*local-function*
local-function userfunc.txt /*local-function*
local-options options.txt /*local-options*
local-variable eval.txt /*local-variable*
local-variables eval.txt /*local-variables*
local-variables userfunc.txt /*local-variables*
local_markfilelist pi_netrw.txt /*local_markfilelist*
locale mbyte.txt /*locale*
locale-name mbyte.txt /*locale-name*
@@ -8797,7 +8802,7 @@ no_plugin_maps filetype.txt /*no_plugin_maps*
nocombine syntax.txt /*nocombine*
non-greedy pattern.txt /*non-greedy*
non-zero-arg eval.txt /*non-zero-arg*
none-function_argument eval.txt /*none-function_argument*
none-function_argument userfunc.txt /*none-function_argument*
none-variable eval.txt /*none-variable*
normal-index index.txt /*normal-index*
not-compatible usr_01.txt /*not-compatible*
@@ -8851,7 +8856,7 @@ option-value-function options.txt /*option-value-function*
option-window options.txt /*option-window*
option_restore() todo.txt /*option_restore()*
option_save() todo.txt /*option_save()*
optional-function-argument eval.txt /*optional-function-argument*
optional-function-argument userfunc.txt /*optional-function-argument*
options options.txt /*options*
options-changed version5.txt /*options-changed*
options-in-terminal terminal.txt /*options-in-terminal*
@@ -10326,6 +10331,7 @@ user-cmd-ambiguous map.txt /*user-cmd-ambiguous*
user-commands map.txt /*user-commands*
user-functions eval.txt /*user-functions*
user-manual usr_toc.txt /*user-manual*
userfunc.txt userfunc.txt /*userfunc.txt*
using-<Plug> usr_51.txt /*using-<Plug>*
using-menus gui.txt /*using-menus*
using-scripts repeat.txt /*using-scripts*

View File

@@ -38,12 +38,17 @@ browser use: https://github.com/vim/vim/issues/1234
*known-bugs*
-------------------- Known bugs and current work -----------------------
cmdheight=0:
- :g/pattern should not use message window #11012
When using :echomessage do use msg_row and msg_col, but save and restore.
How to test any failure?
*.sil detection with FTsil() (lacygoill, Aug 25)
Improve :defer command:
- Use "D" flag of writefile() in tests.
- test "defer func()->funcouter()" fails (or use "funcouter")
- test "defer func().arg" fails
- test partial fails
- check arguments at :defer command
- Also when function does "qa!" or "cq"?
Avoid using "Xfile" and "Xdir" in tests, use specific names.
Further Vim9 improvements, possibly after launch:
- Use Vim9 for more runtime files.
@@ -183,10 +188,7 @@ Terminal emulator window:
- When 'encoding' is not utf-8, or the job is using another encoding, setup
conversions.
Cleanup:
- Remove FEAT_FOOTER ?
Add 'splitscroll' #10682 Useful? Any remaining trouble?
Add 'splitscroll' #10682 Anything remaining
Autoconf: must use autoconf 2.69, later version generates lots of warnings
- try using autoconf 2.71 and fix all "obsolete" warnings
@@ -196,6 +198,8 @@ Can deref_func_name() and deref_function_name() be merged?
After patch 8.2.4915 w_botline is computed much more often. Can this be
reduced?
Add BufDeletePost. #11041
NFA regexp does not handle composing characters well: #10286
[ɔ̃] matches both ɔ and ɔ̃
\(ɔ\|ɔ̃\) matches ɔ and not ɔ̃
@@ -3753,6 +3757,7 @@ Syntax highlighting:
- use treesitter, NeoVim uses it - Many people don't like it.
After changes requires rebuilding the library.
- use TextMate, vscode uses it. #9087 - Other people don't like it.
https://github.com/icedman/vim-textmate
Vscode is asked to switch to treesitter:
https://github.com/microsoft/vscode/issues/50140
- sublime grammar?

530
runtime/doc/userfunc.txt Normal file
View File

@@ -0,0 +1,530 @@
*userfunc.txt* For Vim version 9.0. Last change: 2022 Jun 17
VIM REFERENCE MANUAL by Bram Moolenaar
Defining and using functions.
This is introduced in section |41.7| of the user manual.
1. Defining a fuction |define-function|
2. Calling a fuction |:call|
3. Cleaning up in a function |:defer|
4. Automatically loading functions |autoload-functions|
==============================================================================
1. Defining a fuction ~
*define-function*
New functions can be defined. These can be called just like builtin
functions. The function executes a sequence of Ex commands. Normal mode
commands can be executed with the |:normal| command.
The function name must start with an uppercase letter, to avoid confusion with
builtin functions. To prevent from using the same name in different scripts
make them script-local. If you do use a global function the avoid obvious,
short names. A good habit is to start the function name with the name of the
script, e.g., "HTMLcolor()".
In legacy script it is also possible to use curly braces, see
|curly-braces-names|.
The |autoload| facility is useful to define a function only when it's called.
*local-function*
A function local to a legacy script must start with "s:". A local script
function can only be called from within the script and from functions, user
commands and autocommands defined in the script. It is also possible to call
the function from a mapping defined in the script, but then |<SID>| must be
used instead of "s:" when the mapping is expanded outside of the script.
There are only script-local functions, no buffer-local or window-local
functions.
In |Vim9| script functions are local to the script by default, prefix "g:" to
define a global function.
*:fu* *:function* *E128* *E129* *E123* *E454*
:fu[nction] List all functions and their arguments.
:fu[nction] {name} List function {name}.
{name} can also be a |Dictionary| entry that is a
|Funcref|: >
:function dict.init
: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 was
last 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.
*E124* *E125* *E853* *E884*
:fu[nction][!] {name}([arguments]) [range] [abort] [dict] [closure]
Define a new function by the name {name}. The body of
the function follows in the next lines, until the
matching |:endfunction|.
*E1267*
The name must be made of alphanumeric characters and
'_', and must start with a capital or "s:" (see
above). Note that using "b:" or "g:" is not allowed.
(since patch 7.4.260 E884 is given if the function
name has a colon in the name, e.g. for "foo:bar()".
Before that patch no error was given).
{name} can also be a |Dictionary| entry that is a
|Funcref|: >
: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. The
result is a |Funcref| to a numbered function. The
function can only be used with a |Funcref| and will be
deleted if there are no more references to it.
*E127* *E122*
When a function by this name already exists and [!] is
not used an error message is given. There is one
exception: When sourcing a script again, a function
that was previously defined in that script will be
silently replaced.
When [!] is used, an existing function is silently
replaced. Unless it is currently being executed, that
is an error.
NOTE: Use ! wisely. If used without care it can cause
an existing function to be replaced unexpectedly,
which is hard to debug.
NOTE: In Vim9 script script-local functions cannot be
deleted or redefined.
For the {arguments} see |function-argument|.
*:func-range* *a:firstline* *a:lastline*
When the [range] argument is added, the function is
expected to take care of a range itself. The range is
passed as "a:firstline" and "a:lastline". If [range]
is excluded, ":{range}call" will call the function for
each line in the range, with the cursor on the start
of each line. See |function-range-example|.
The cursor is still moved to the first line of the
range, as is the case with all Ex commands.
*:func-abort*
When the [abort] argument is added, the function will
abort as soon as an error is detected.
*:func-dict*
When the [dict] argument is added, the function must
be invoked through an entry in a |Dictionary|. The
local variable "self" will then be set to the
dictionary. See |Dictionary-function|.
*:func-closure* *E932*
When the [closure] argument is added, the function
can access variables and arguments from the outer
scope. This is usually called a closure. In this
example Bar() uses "x" from the scope of Foo(). It
remains 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 also
implies that the effect of |:nohlsearch| is undone
when the function returns.
*:endf* *:endfunction* *E126* *E193* *W22* *E1151*
:endf[unction] [argument]
The end of a function definition. Best is to put it
on a line by its own, without [argument].
[argument] can be:
| command command to execute next
\n command command to execute next
" comment always ignored
anything else ignored, warning given when
'verbose' is non-zero
The support for a following command was added in Vim
8.0.0654, before that any argument was silently
ignored.
To be able to define a function inside an `:execute`
command, use line breaks instead of |:bar|: >
:exe "func Foo()\necho 'foo'\nendfunc"
<
*:delf* *:delfunction* *E131* *E933* *E1084*
:delf[unction][!] {name}
Delete function {name}.
{name} can also be a |Dictionary| entry that is a
|Funcref|: >
:delfunc dict.init
< This will remove the "init" entry from "dict". The
function is deleted if there are no more references to
it.
With the ! there is no error if the function does not
exist.
*:retu* *:return* *E133*
:retu[rn] [expr] Return from a function. When "[expr]" is given, it is
evaluated 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.
In a :def function *E1095* is given if unreachable
code follows after the `:return`.
In legacy script there is no check for unreachable
lines, thus there is no warning if commands follow
`:return`.
If the ":return" is used after a |:try| but before the
matching |:finally| (if present), the commands
following the ":finally" up to the matching |:endtry|
are executed first. This process applies to all
nested ":try"s inside the function. The function
returns at the outermost ":endtry".
*function-argument* *a:var*
An argument can be defined by giving its name. In the function this can then
be used as "a:name" ("a:" for argument).
*a:0* *a:1* *a:000* *E740* *...*
Up to 20 arguments can be given, separated by commas. After the named
arguments an argument "..." can be specified, which means that more arguments
may optionally be following. In the function the extra arguments can be used
as "a:1", "a:2", etc. "a:0" is set to the number of extra arguments (which
can be 0). "a:000" is set to a |List| that contains these arguments. Note
that "a:1" is the same as "a:000[0]".
*E742* *E1090*
The a: scope and the variables in it cannot be changed, they are fixed.
However, if a composite type is used, such as |List| or |Dictionary| , you can
change their contents. Thus you can pass a |List| to a function and have the
function add an item to it. If you want to make sure the function cannot
change a |List| or |Dictionary| use |:lockvar|.
It is also possible to define a function without any arguments. You must
still 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 makes
them optional for function calls. When a positional argument is not
specified at a call, the default expression is used to initialize it.
This only works for functions declared with `:function` or `:def`, not for
lambda expressions |expr-lambda|.
Example: >
function Something(key, value = 10)
echo a:key .. ": " .. a:value
endfunction
call Something('empty') "empty: 10"
call Something('key', 20) "key: 20"
The argument default expressions are evaluated at the time of the function
call, not definition. Thus it is possible to use an expression which is
invalid the moment the function is defined. The expressions are also only
evaluated when arguments are not specified during a call.
*none-function_argument*
You can pass |v:none| to use the default expression. Note that this means you
cannot pass v:none as an ordinary value when an argument has a default
expression.
Example: >
function Something(a = 10, b = 20, c = 30)
endfunction
call Something(1, v:none, 3) " b = 20
<
*E989*
Optional arguments with default expressions must occur after any mandatory
arguments. 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 all
arguments.
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 at
least equal to the number of mandatory named arguments. When using "...", the
number of arguments may be larger than the total of mandatory and optional
arguments.
*local-variables*
Inside a function local variables can be used. These will disappear when the
function returns. Global variables need to be accessed with "g:".
Inside functions local variables are accessed without prepending anything.
But you can also prepend "l:" if you like. This is required for some reserved
names, such as "count".
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 a |List|: >
: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 fuction ~
*:cal* *:call* *E107*
:[range]cal[l] {name}([arguments])
Call a function. The name of the function and its arguments
are as specified with `:function`. Up to 20 arguments can be
used. The returned value is discarded.
In |Vim9| script using `:call` is optional, these two lines do
the same thing: >
call SomeFunc(arg)
SomeFunc(arg)
< Without a range and for functions that accept a range, the
function is called once. When a range is given the cursor is
positioned at the start of the first line before executing the
function.
When a range is given and the function doesn't handle it
itself, the function is executed for each line in the range,
with the cursor in the first column of that line. The cursor
is left at the last line (possibly moved by the last function
call). The arguments are re-evaluated for each line. Thus
this 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, they
can be used to do something different at the start or end of
the 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 front
of all the lines in the range, except the first one.
When the function returns a composite value it can be further
dereferenced, but the range will not be used then. Example: >
:4,8call GetDict().method()
< Here GetDict() gets the range but method() does not.
*E117*
When a function cannot be found the error "E117: Unknown function" will be
given. If the function was using an autoload path or an autoload import and
the script is a |Vim9| script, this may also be caused by the function not
being exported.
*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 does
allow for method chaining, e.g.: >
eval GetList()->Filter()->append('$')
A function can also be called as part of evaluating an expression or when it
is used as a method: >
let x = GetList()
let y = GetList()->Filter()
==============================================================================
3. Cleaning up in a function ~
*:defer*
:defer {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 undone
when the function finishes. Handling this in all kinds of situations can be a
hassle. Especially when an unexpected error is encountered. This can be done
with `try` / `finally` blocks, but this gets complicated when there is more
than one.
A much simpler solution is using `defer`. It schedules a function call when
the 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 the
function 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 calling system(), since it
can be created even when `system()` fails.
The deferred functions are called in reverse order, the last one added is
executed first. A useless example: >
func Useless() abort
for s in range(3)
defer execute('echomsg "number ' .. s .. '"')
endfor
endfunc
Now `:messages` shows:
number 2
number 1
number 0
Any return value of the deferred function is discarded. The function cannot
be 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 functions.
No range is accepted.
==============================================================================
4. Automatically loading functions ~
*autoload-functions*
When using many or large functions, it's possible to automatically define them
only when they are used. There are two methods: with an autocommand and with
the "autoload" directory in 'runtimepath'.
In |Vim9| script there is also an autoload mechanism for imported scripts, see
|import-autoload|.
Using an autocommand ~
This is introduced in the user manual, section |51.4|.
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 file
again, setting a variable to skip the `:finish` command.
Use the FuncUndefined autocommand event with a pattern that matches the
function(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 see |FuncUndefined|.
Using an autoload script ~
*autoload* *E746*
This is introduced in the user manual, section |52.2|.
Using a script in the "autoload" directory is simpler, but requires using
exactly the right file name. A function that can be autoloaded has a name
like this: >
:call filename#funcname()
These functions are always global, in Vim9 script "g:" needs to be used: >
:call g: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 "~/.vim/autoload/filename.vim". That file should
then define the function like this: >
function filename#funcname()
echo "Done!"
endfunction
The file name and the name used before the # in the function must match
exactly, and the defined function must have the name exactly as it will be
called. In Vim9 script the "g:" prefix must be used: >
function g:filename#funcname()
or for a compiled function: >
def g:filename#funcname()
It is possible to use subdirectories. Every # in the function name works like
a 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 again
for an unknown variable.
When assigning a value to such a variable nothing special happens. This can
be 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 be
defined in an autoload script, but the script doesn't actually define the
function, you will get an error message for the missing function. If you fix
the autoload script it won't be automatically loaded again. Either restart
Vim or manually source the script.
Also note that if you have two script files, and one calls a function in the
other and vice versa, before the used function is defined, it won't work.
Avoid using the autoload functionality at the toplevel.
In |Vim9| script you will get error *E1263* if you define a function with
a "#" character in the name. You should use a name without "#" and use
`:export`.
Hint: If you distribute a bunch of scripts you can pack them together with the
|vimball| utility. Also read the user manual |distribute-script|.
vim:tw=78:ts=8:noet:ft=help:norl:

View File

@@ -257,13 +257,13 @@ and 'winminwidth' are relevant.
:vert[ical] {cmd}
Execute {cmd}. If it contains a command that splits a window,
it will be split vertically. For `vertical wincmd =` windows
will be equialized only vertically.
will be equalized only vertically.
Doesn't work for |:execute| and |:normal|.
*:hor* *:horizontal*
:hor[izontal] {cmd}
Execute {cmd}. Currently only makes a difference for
`horizontal wincmd =`, which will equal windows only
`horizontal wincmd =`, which will equalize windows only
horizontally.
:lefta[bove] {cmd} *:lefta* *:leftabove*