neovim

Neovim text editor
git clone https://git.dasho.dev/neovim.git
Log | Files | Refs | README

userfunc.txt (18862B)


      1 *userfunc.txt*	Nvim
      2 
      3 
      4 	  VIM REFERENCE MANUAL	  by Bram Moolenaar
      5 
      6 
      7 Defining and using functions.
      8 
      9 This is introduced in section |41.7| of the user manual.
     10 
     11 			      Type |gO| to see the table of contents.
     12 
     13 ==============================================================================
     14 
     15 1. Defining a function ~
     16 					*define-function*
     17 New functions can be defined.  These can be called just like builtin
     18 functions.  The function executes a sequence of Ex commands.  Normal mode
     19 commands can be executed with the |:normal| command.
     20 
     21 The function name must start with an uppercase letter, to avoid confusion with
     22 builtin functions.  To prevent from using the same name in different scripts
     23 make them script-local.  If you do use a global function then avoid obvious,
     24 short names.  A good habit is to start the function name with the name of the
     25 script, e.g., "HTMLcolor()".
     26 
     27 It is also possible to use curly braces, see |curly-braces-names|.
     28 
     29 The |autoload| facility is useful to define a function only when it's called.
     30 
     31 						*local-function*
     32 A function local to a script must start with "s:".  A local script function
     33 can only be called from within the script and from functions, user commands
     34 and autocommands defined in the script.  It is also possible to call the
     35 function from a mapping defined in the script, but then |<SID>| must be used
     36 instead of "s:" when the mapping is expanded outside of the script.
     37 There are only script-local functions, no buffer-local or window-local
     38 functions.
     39 
     40 				*:fu* *:function* *E128* *E129* *E123*
     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*
     60 When 'verbose' is non-zero, listing a function will also display where it was
     61 last defined.  Example: >
     62 
     63    :verbose function SetFileTypeSH
     64 function SetFileTypeSH(name)
     65     Last set from /usr/share/vim/vim-7.0/filetype.vim
     66 <
     67 See |: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* *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*
    207 An argument can be defined by giving its name.  In the function this can then
    208 be used as "a:name" ("a:" for argument).
    209 				*a:0* *a:1* *a:000* *E740* *...*
    210 Up to 20 arguments can be given, separated by commas.  After the named
    211 arguments an argument "..." can be specified, which means that more arguments
    212 may optionally be following.  In the function the extra arguments can be used
    213 as "a:1", "a:2", etc.  "a:0" is set to the number of extra arguments (which
    214 can be 0).  "a:000" is set to a |List| that contains these arguments.  Note
    215 that "a:1" is the same as "a:000[0]".
    216 							*E742*
    217 The a: scope and the variables in it cannot be changed, they are fixed.
    218 However, if a composite type is used, such as |List| or |Dictionary| , you can
    219 change their contents.  Thus you can pass a |List| to a function and have the
    220 function add an item to it.  If you want to make sure the function cannot
    221 change a |List| or |Dictionary| use |:lockvar|.
    222 
    223 It is also possible to define a function without any arguments.  You must
    224 still supply the () then.
    225 
    226 It is allowed to define another function inside a function body.
    227 
    228 					*optional-function-argument*
    229 You can provide default values for positional named arguments.  This makes
    230 them optional for function calls.  When a positional argument is not
    231 specified at a call, the default expression is used to initialize it.
    232 This only works for functions declared with `:function`, not for
    233 lambda expressions |expr-lambda|.
    234 
    235 Example: >
    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 
    242 The argument default expressions are evaluated at the time of the function
    243 call, not when the function is defined.  Thus it is possible to use an
    244 expression which is invalid the moment the function is defined.  The
    245 expressions are also only evaluated when arguments are not specified during a
    246 call.
    247 
    248 							*E989*
    249 Optional arguments with default expressions must occur after any mandatory
    250 arguments.  You can use "..." after all optional named arguments.
    251 
    252 It is possible for later argument defaults to refer to prior arguments,
    253 but not the other way around.  They must be prefixed with "a:", as with all
    254 arguments.
    255 
    256 Example that works: >
    257  :function Okay(mandatory, optional = a:mandatory)
    258  :endfunction
    259 Example that does NOT work: >
    260  :function NoGood(first = a:second, second = 10)
    261  :endfunction
    262 <
    263 When not using "...", the number of arguments in a function call must be at
    264 least equal to the number of mandatory named arguments.  When using "...", the
    265 number of arguments may be larger than the total of mandatory and optional
    266 arguments.
    267 
    268 						*local-variables*
    269 Inside a function local variables can be used.  These will disappear when the
    270 function returns. Global variables need to be accessed with "g:". Inside
    271 functions local variables are accessed without prepending anything. But you
    272 can also prepend "l:" if you like.  This is required for some reserved names,
    273 such as "version".
    274 
    275 Example: >
    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 
    286 This function can then be called with: >
    287  call Table("Table", "line1", "line2")
    288  call Table("Empty Table")
    289 
    290 To 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 
    298 This 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 
    306 2. 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*
    348 The recursiveness of user functions is restricted with the 'maxfuncdepth'
    349 option.
    350 
    351 It is also possible to use `:eval`.  It does not support a range, but does
    352 allow for method chaining, e.g.: >
    353 eval GetList()->Filter()->append('$')
    354 
    355 A function can also be called as part of evaluating an expression or when it
    356 is used as a method: >
    357 let x = GetList()
    358 let y = GetList()->Filter()
    359 <
    360 ==============================================================================
    361 
    362 3. 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 
    367 Quite often a command in a function has a global effect, which must be undone
    368 when the function finishes.  Handling this in all kinds of situations can be a
    369 hassle.  Especially when an unexpected error is encountered.  This can be done
    370 with `try` / `finally` blocks, but this gets complicated when there is more
    371 than one.
    372 
    373 A much simpler solution is using `defer`.  It schedules a function call when
    374 the 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 
    383 Here 'Tempfile' and 'Outfile' will not be deleted if something causes the
    384 function 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 
    393 Note that deleting "Outfile" is scheduled before calling `system()`, since it
    394 can be created even when `system()` fails.
    395 
    396 The deferred functions are called in reverse order, the last one added is
    397 executed 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 
    404 Now `:messages` shows:
    405 number 2
    406 number 1
    407 number 0
    408 
    409 Any return value of the deferred function is discarded.  The function cannot
    410 be followed by anything, such as "->func" or ".member".  Currently
    411 `:defer GetArg()->TheFunc()` does not work, it may work in a later version.
    412 
    413 Errors are reported but do not cause aborting execution of deferred functions
    414 or altering execution outside of deferred functions.
    415 
    416 No range is accepted.  The function can be a partial with extra arguments, but
    417 not with a dictionary. *E1300*
    418 
    419 ==============================================================================
    420 
    421 4. Automatically loading functions ~
    422 						*autoload-functions*
    423 When using many or large functions, it's possible to automatically define them
    424 only when they are used.  There are two methods: with an autocommand and with
    425 the "autoload" directory in 'runtimepath'.
    426 
    427 
    428 Using an autocommand ~
    429 
    430 This is introduced in the user manual, section |41.14|.
    431 
    432 The autocommand is useful if you have a plugin that is a long Vim script file.
    433 You can define the autocommand and quickly quit the script with `:finish`.
    434 That makes Vim startup faster.  The autocommand should then load the same file
    435 again, setting a variable to skip the `:finish` command.
    436 
    437 Use the FuncUndefined autocommand event with a pattern that matches the
    438 function(s) to be defined.  Example: >
    439 
    440 :au FuncUndefined BufNet* source ~/vim/bufnetfuncs.vim
    441 
    442 The file "~/vim/bufnetfuncs.vim" should then define functions that start with
    443 "BufNet".  Also see |FuncUndefined|.
    444 
    445 
    446 Using an autoload script ~
    447 						*autoload* *E746*
    448 This is introduced in the user manual, section |41.15|.
    449 
    450 Using a script in the "autoload" directory is simpler, but requires using
    451 exactly the right file name.  A function that can be autoloaded has a name
    452 like this: >
    453 
    454 :call filename#funcname()
    455 
    456 When 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
    459 file should then define the function like this: >
    460 
    461 function filename#funcname()
    462    echo "Done!"
    463 endfunction
    464 
    465 If the file doesn't exist, Vim will also search in 'packpath' (under "start")
    466 to allow calling packages' functions from your |vimrc| when the packages have
    467 not been added to 'runtimepath' yet (see |packages|).
    468 
    469 The file name and the name used before the # in the function must match
    470 exactly, and the defined function must have the name exactly as it will be
    471 called.
    472 
    473 It is possible to use subdirectories.  Every # in the function name works like
    474 a path separator.  Thus when calling a function: >
    475 
    476 :call foo#bar#func()
    477 
    478 Vim will look for the file "autoload/foo/bar.vim" in 'runtimepath'.
    479 
    480 This also works when reading a variable that has not been set yet: >
    481 
    482 :let l = foo#bar#lvar
    483 
    484 However, when the autoload script was already loaded it won't be loaded again
    485 for an unknown variable.
    486 
    487 When assigning a value to such a variable nothing special happens.  This can
    488 be 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 
    493 Note that when you make a mistake and call a function that is supposed to be
    494 defined in an autoload script, but the script doesn't actually define the
    495 function, you will get an error message for the missing function.  If you fix
    496 the autoload script it won't be automatically loaded again.  Either restart
    497 Vim or manually source the script.
    498 
    499 Also note that if you have two script files, and one calls a function in the
    500 other and vice versa, before the used function is defined, it won't work.
    501 Avoid using the autoload functionality at the toplevel.
    502 
    503 Hint: If you distribute a bunch of scripts read |distribute-script|.
    504 
    505 
    506 vim:tw=78:ts=8:noet:ft=help:norl: