robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

zeertzjqvim-patch:8.2.2440: documentation based on patches is outdated (#39144)39410ef42b

master
18.4 KiB506 linesraw
1*userfunc.txt*	Nvim
2
3
4		  VIM REFERENCE MANUAL	  by Bram Moolenaar
5
6
7Defining and using functions.
8
9This is introduced in section |41.7| of the user manual.
10
11				      Type |gO| to see the table of contents.
12
13==============================================================================
14
151. Defining a function ~
16						*define-function*
17New functions can be defined.  These can be called just like builtin
18functions.  The function executes a sequence of Ex commands.  Normal mode
19commands can be executed with the |:normal| command.
20
21The function name must start with an uppercase letter, to avoid confusion with
22builtin functions.  To prevent from using the same name in different scripts
23make them script-local.  If you do use a global function then avoid obvious,
24short names.  A good habit is to start the function name with the name of the
25script, e.g., "HTMLcolor()".
26
27It is also possible to use curly braces, see |curly-braces-names|.
28
29The |autoload| facility is useful to define a function only when it's called.
30
31							*local-function*
32A function local to a script must start with "s:".  A local script function
33can only be called from within the script and from functions, user commands
34and autocommands defined in the script.  It is also possible to call the
35function from a mapping defined in the script, but then |<SID>| must be used
36instead of "s:" when the mapping is expanded outside of the script.
37There are only script-local functions, no buffer-local or window-local
38functions.
39
40			*:fu* *:function* *E128* *E129* *E123* *E454* *E1058* *E1068*
41:fu[nction]		List all functions and their arguments.
42
43:fu[nction][!] {name}	List function {name}, annotated with line numbers
44			unless "!" is given.
45			{name} may be a |Dictionary| |Funcref| entry: >
46				:function dict.init
47<			Note that {name} is not an expression, you cannot use
48			a variable that is a function reference.  You can use
49			this dirty trick to list the function referred to with
50			variable "Funcref": >
51				let g:MyFuncref = Funcref
52				func g:MyFuncref
53				unlet g:MyFuncref
54
55:fu[nction] /{pattern}	List functions with a name matching {pattern}.
56			Example that lists all functions ending with "File": >
57				:function /File$
58<
59							*:function-verbose*
60When 'verbose' is non-zero, listing a function will also display where it was
61last defined.  Example: >
62
63    :verbose function SetFileTypeSH
64	function SetFileTypeSH(name)
65	    Last set from /usr/share/vim/vim-7.0/filetype.vim
66<
67See |:verbose-cmd| for more information.
68
69						*E124* *E125* *E853* *E884*
70:fu[nction][!] {name}([arguments]) [range] [abort] [dict] [closure]
71			Define a new function by the name {name}.  The body of
72			the function follows in the next lines, until the
73			matching |:endfunction|.
74
75			The name must be made of alphanumeric characters and
76			'_' and must start with a capital or "s:" (see above).
77			Note that using "b:", "l:", etc. is not allowed (since
78			patch 7.4.260 E884 is given if the function name has a
79			colon, e.g. for "foo:bar()"), while a leading "g:" is
80			skipped and still requires a following capital letter.
81
82			{name} may be a |Dictionary| |Funcref| entry: >
83				:function dict.init(arg)
84<			"dict" must be an existing dictionary.  The entry
85			"init" is added if it didn't exist yet.  Otherwise [!]
86			is required to overwrite an existing function.  The
87			result is a |Funcref| to a numbered function.  The
88			function can only be used with a |Funcref| and will be
89			deleted if there are no more references to it.
90								*E127* *E122*
91			When a function by this name already exists and [!] is
92			not used an error message is given.  There is one
93			exception: When sourcing a script again, a function
94			that was previously defined in that script will be
95			silently replaced.
96			When [!] is used, an existing function is silently
97			replaced.  Unless it is currently being executed, that
98			is an error.
99			NOTE: Use ! wisely.  If used without care it can cause
100			an existing function to be replaced unexpectedly,
101			which is hard to debug.
102
103			For the {arguments} see |function-argument|.
104
105					*:func-range* *a:firstline* *a:lastline*
106			When the [range] argument is added, the function is
107			expected to take care of a range itself.  The range is
108			passed as "a:firstline" and "a:lastline".  If [range]
109			is excluded, ":{range}call" will call the function for
110			each line in the range, with the cursor on the start
111			of each line.  See |function-range-example|.
112			The cursor is still moved to the first line of the
113			range, as is the case with all Ex commands.
114								*:func-abort*
115			When the [abort] argument is added, the function will
116			abort as soon as an error is detected.
117								*:func-dict*
118			When the [dict] argument is added, the function must
119			be invoked through an entry in a |Dictionary|.  The
120			local variable "self" will then be set to the
121			dictionary.  See |Dictionary-function|.
122						*:func-closure* *E932*
123			When the [closure] argument is added, the function
124			can access variables and arguments from the outer
125			scope.  This is usually called a closure.  In this
126			example Bar() uses "x" from the scope of Foo().  It
127			remains referenced even after Foo() returns: >
128				:function! Foo()
129				:  let x = 0
130				:  function! Bar() closure
131				:    let x += 1
132				:    return x
133				:  endfunction
134				:  return funcref('Bar')
135				:endfunction
136
137				:let F = Foo()
138				:echo F()
139<				1 >
140				:echo F()
141<				2 >
142				:echo F()
143<				3
144
145						*function-search-undo*
146			The last used search pattern and the redo command "."
147			will not be changed by the function.  This also
148			implies that the effect of |:nohlsearch| is undone
149			when the function returns.
150
151				*:endf* *:endfunction* *E126* *E193* *W22*
152:endf[unction] [argument]
153			The end of a function definition.  Best is to put it
154			on a line by its own, without [argument].
155
156			[argument] can be:
157				| command	command to execute next
158				\n command	command to execute next
159				" comment	always ignored
160				anything else	ignored, warning given when
161						'verbose' is non-zero
162			The support for a following command was added in Vim
163			8.0.0654, before that any argument was silently
164			ignored.
165
166			To be able to define a function inside an `:execute`
167			command, use line breaks instead of |:bar|: >
168				:exe "func Foo()\necho 'foo'\nendfunc"
169<
170				*:delf* *:delfunction* *E130* *E131* *E933*
171:delf[unction][!] {name}
172			Delete function {name}.
173			{name} can also be a |Dictionary| entry that is a
174			|Funcref|: >
175				:delfunc dict.init
176<			This will remove the "init" entry from "dict".  The
177			function is deleted if there are no more references to
178			it.
179			With the ! there is no error if the function does not
180			exist.
181							*:retu* *:return* *E133*
182:retu[rn] [expr]	Return from a function.  When [expr] is given, it is
183			evaluated and returned as the result of the function.
184			If [expr] is not given, the number 0 is returned.
185			When a function ends without an explicit ":return",
186			the number 0 is returned.
187			Note that there is no check for unreachable lines,
188			thus there is no warning if commands follow ":return".
189			Also, there is no check if the following
190			line contains a valid command.  Forgetting the line
191			continuation backslash may go unnoticed: >
192				return 'some text'
193				       .. ' some more text'
194<			Will happily return "some text" without an error.  It
195			should have been: >
196				return 'some text'
197				       \ .. ' some more text'
198<
199			If the ":return" is used after a |:try| but before the
200			matching |:finally| (if present), the commands
201			following the ":finally" up to the matching |:endtry|
202			are executed first.  This process applies to all
203			nested ":try"s inside the function.  The function
204			returns at the outermost ":endtry".
205
206						*function-argument* *a:var*
207An argument can be defined by giving its name.  In the function this can then
208be used as "a:name" ("a:" for argument).
209					*a:0* *a:1* *a:000* *E740* *...*
210Up to 20 arguments can be given, separated by commas.  After the named
211arguments an argument "..." can be specified, which means that more arguments
212may optionally be following.  In the function the extra arguments can be used
213as "a:1", "a:2", etc.  "a:0" is set to the number of extra arguments (which
214can be 0).  "a:000" is set to a |List| that contains these arguments.  Note
215that "a:1" is the same as "a:000[0]".
216								*E742*
217The a: scope and the variables in it cannot be changed, they are fixed.
218However, if a composite type is used, such as |List| or |Dictionary| , you can
219change their contents.  Thus you can pass a |List| to a function and have the
220function add an item to it.  If you want to make sure the function cannot
221change a |List| or |Dictionary| use |:lockvar|.
222
223It is also possible to define a function without any arguments.  You must
224still supply the () then.
225
226It is allowed to define another function inside a function body.
227
228						*optional-function-argument*
229You can provide default values for positional named arguments.  This makes
230them optional for function calls.  When a positional argument is not
231specified at a call, the default expression is used to initialize it.
232This only works for functions declared with `:function`, not for
233lambda expressions |expr-lambda|.
234
235Example: >
236  function Something(key, value = 10)
237     echo a:key .. ": " .. a:value
238  endfunction
239  call Something('empty')	"empty: 10"
240  call Something('key', 20)	"key: 20"
241
242The argument default expressions are evaluated at the time of the function
243call, not when the function is defined.  Thus it is possible to use an
244expression which is invalid the moment the function is defined.  The
245expressions are also only evaluated when arguments are not specified during a
246call.
247
248								*E989*
249Optional arguments with default expressions must occur after any mandatory
250arguments.  You can use "..." after all optional named arguments.
251
252It is possible for later argument defaults to refer to prior arguments,
253but not the other way around.  They must be prefixed with "a:", as with all
254arguments.
255
256Example that works: >
257  :function Okay(mandatory, optional = a:mandatory)
258  :endfunction
259Example that does NOT work: >
260  :function NoGood(first = a:second, second = 10)
261  :endfunction
262<
263When not using "...", the number of arguments in a function call must be at
264least equal to the number of mandatory named arguments.  When using "...", the
265number of arguments may be larger than the total of mandatory and optional
266arguments.
267
268							*local-variables*
269Inside a function local variables can be used.  These will disappear when the
270function returns. Global variables need to be accessed with "g:". Inside
271functions local variables are accessed without prepending anything. But you
272can also prepend "l:" if you like.  This is required for some reserved names,
273such as "version".
274
275Example: >
276  :function Table(title, ...)
277  :  echohl Title
278  :  echo a:title
279  :  echohl None
280  :  echo a:0 .. " items:"
281  :  for s in a:000
282  :    echon ' ' .. s
283  :  endfor
284  :endfunction
285
286This function can then be called with: >
287  call Table("Table", "line1", "line2")
288  call Table("Empty Table")
289
290To return more than one value, return a |List|: >
291  :function Compute(n1, n2)
292  :  if a:n2 == 0
293  :    return ["fail", 0]
294  :  endif
295  :  return ["ok", a:n1 / a:n2]
296  :endfunction
297
298This function can then be called with: >
299  :let [success, div] = Compute(102, 6)
300  :if success == "ok"
301  :  echo div
302  :endif
303<
304==============================================================================
305
3062. Calling a function ~
307						*:cal* *:call* *E107* *E117*
308:[range]cal[l] {name}([arguments])
309		Call a function.  The name of the function and its arguments
310		are as specified with `:function`.  Up to 20 arguments can be
311		used.  The returned value is discarded.
312		Without a range and for functions that accept a range, the
313		function is called once.  When a range is given the cursor is
314		positioned at the start of the first line before executing the
315		function.
316		When a range is given and the function doesn't handle it
317		itself, the function is executed for each line in the range,
318		with the cursor in the first column of that line.  The cursor
319		is left at the last line (possibly moved by the last function
320		call).  The arguments are re-evaluated for each line.  Thus
321		this works:
322						*function-range-example*  >
323	:function Mynumber(arg)
324	:  echo line(".") .. " " .. a:arg
325	:endfunction
326	:1,5call Mynumber(getline("."))
327<
328		The "a:firstline" and "a:lastline" are defined anyway, they
329		can be used to do something different at the start or end of
330		the range.
331
332		Example of a function that handles the range itself: >
333
334	:function Cont() range
335	:  execute (a:firstline + 1) .. "," .. a:lastline .. 's/^/\t\\ '
336	:endfunction
337	:4,8call Cont()
338<
339		This function inserts the continuation character "\" in front
340		of all the lines in the range, except the first one.
341
342		When the function returns a composite value it can be further
343		dereferenced, but the range will not be used then.  Example: >
344	:4,8call GetDict().method()
345<		Here GetDict() gets the range but method() does not.
346
347								*E132*
348The recursiveness of user functions is restricted with the 'maxfuncdepth'
349option.
350
351It is also possible to use `:eval`.  It does not support a range, but does
352allow for method chaining, e.g.: >
353	eval GetList()->Filter()->append('$')
354
355A function can also be called as part of evaluating an expression or when it
356is used as a method: >
357	let x = GetList()
358	let y = GetList()->Filter()
359<
360==============================================================================
361
3623. Cleaning up in a function ~
363							*:defe* *:defer*
364:defe[r] {func}({args})	Call {func} when the current function is done.
365			{args} are evaluated here.
366
367Quite often a command in a function has a global effect, which must be undone
368when the function finishes.  Handling this in all kinds of situations can be a
369hassle.  Especially when an unexpected error is encountered.  This can be done
370with `try` / `finally` blocks, but this gets complicated when there is more
371than one.
372
373A much simpler solution is using `defer`.  It schedules a function call when
374the function is returning, no matter if there is an error.  Example: >
375	func Filter(text) abort
376	  call writefile(a:text, 'Tempfile')
377	  call system('filter < Tempfile > Outfile')
378	  call Handle('Outfile')
379	  call delete('Tempfile')
380	  call delete('Outfile')
381	endfunc
382
383Here 'Tempfile' and 'Outfile' will not be deleted if something causes the
384function to abort.  `:defer` can be used to avoid that: >
385	func Filter(text) abort
386	  call writefile(a:text, 'Tempfile')
387	  defer delete('Tempfile')
388	  defer delete('Outfile')
389	  call system('filter < Tempfile > Outfile')
390	  call Handle('Outfile')
391	endfunc
392
393Note that deleting "Outfile" is scheduled before calling `system()`, since it
394can be created even when `system()` fails.
395
396The deferred functions are called in reverse order, the last one added is
397executed first.  A useless example: >
398	func Useless() abort
399	  for s in range(3)
400	    defer execute('echomsg "number ' .. s .. '"')
401	  endfor
402	endfunc
403
404Now `:messages` shows:
405	number 2
406	number 1
407	number 0
408
409Any return value of the deferred function is discarded.  The function cannot
410be followed by anything, such as "->func" or ".member".  Currently
411`:defer GetArg()->TheFunc()` does not work, it may work in a later version.
412
413Errors are reported but do not cause aborting execution of deferred functions
414or altering execution outside of deferred functions.
415
416No range is accepted.  The function can be a partial with extra arguments, but
417not with a dictionary. *E1300*
418
419==============================================================================
420
4214. Automatically loading functions ~
422							*autoload-functions*
423When using many or large functions, it's possible to automatically define them
424only when they are used.  There are two methods: with an autocommand and with
425the "autoload" directory in 'runtimepath'.
426
427
428Using an autocommand ~
429
430This is introduced in the user manual, section |41.14|.
431
432The autocommand is useful if you have a plugin that is a long Vim script file.
433You can define the autocommand and quickly quit the script with `:finish`.
434That makes Vim startup faster.  The autocommand should then load the same file
435again, setting a variable to skip the `:finish` command.
436
437Use the FuncUndefined autocommand event with a pattern that matches the
438function(s) to be defined.  Example: >
439
440	:au FuncUndefined BufNet* source ~/vim/bufnetfuncs.vim
441
442The file "~/vim/bufnetfuncs.vim" should then define functions that start with
443"BufNet".  Also see |FuncUndefined|.
444
445
446Using an autoload script ~
447							*autoload* *E746*
448This is introduced in the user manual, section |41.15|.
449
450Using a script in the "autoload" directory is simpler, but requires using
451exactly the right file name.  A function that can be autoloaded has a name
452like this: >
453
454	:call filename#funcname()
455
456When such a function is called, and it is not defined yet, Vim will search the
457"autoload" directories in 'runtimepath' for a script file called
458"filename.vim".  For example "~/.config/nvim/autoload/filename.vim".  That
459file should then define the function like this: >
460
461	function filename#funcname()
462	   echo "Done!"
463	endfunction
464
465If the file doesn't exist, Vim will also search in 'packpath' (under "start")
466to allow calling packages' functions from your |vimrc| when the packages have
467not been added to 'runtimepath' yet (see |packages|).
468
469The file name and the name used before the # in the function must match
470exactly, and the defined function must have the name exactly as it will be
471called.
472
473It is possible to use subdirectories.  Every # in the function name works like
474a path separator.  Thus when calling a function: >
475
476	:call foo#bar#func()
477
478Vim will look for the file "autoload/foo/bar.vim" in 'runtimepath'.
479
480This also works when reading a variable that has not been set yet: >
481
482	:let l = foo#bar#lvar
483
484However, when the autoload script was already loaded it won't be loaded again
485for an unknown variable.
486
487When assigning a value to such a variable nothing special happens.  This can
488be used to pass settings to the autoload script before it's loaded: >
489
490	:let foo#bar#toggle = 1
491	:call foo#bar#func()
492
493Note that when you make a mistake and call a function that is supposed to be
494defined in an autoload script, but the script doesn't actually define the
495function, you will get an error message for the missing function.  If you fix
496the autoload script it won't be automatically loaded again.  Either restart
497Vim or manually source the script.
498
499Also note that if you have two script files, and one calls a function in the
500other and vice versa, before the used function is defined, it won't work.
501Avoid using the autoload functionality at the toplevel.
502
503Hint: If you distribute a bunch of scripts read |distribute-script|.
504
505
506 vim:tw=78:ts=8:noet:ft=help:norl: