Home Explore Blog CI



neovim

6th chunk of `runtime/doc/userfunc.txt`
1bb25fe73a9ab8d0d0533289c2373b2bd8bb71596ef801e300000001000008a3
 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
or altering execution outside of deferred functions.

No range is accepted.  The function can be a partial with extra arguments, but
not with a dictionary. *E1300*

==============================================================================

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'.


Using an autocommand ~

This is introduced in the user manual, section |41.14|.

The autocommand is useful if you have a plugin that is a long Vim script file.
You can define the autocommand and quickly quit the script with `:finish`.
That makes Vim startup faster.  The autocommand should then load the same 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

Title: `:defer` Usage Details and Autoloading Functions
Summary
This section further explains the usage of the `:defer` command for scheduling function calls on return, providing an example of how it prevents issues with temporary files not being deleted. It notes that deferred functions are called in reverse order and that their return values are discarded. It also mentions limitations, such as the inability to use method chaining directly with `:defer`. The section then introduces methods for automatically loading functions: using the FuncUndefined autocommand and using the "autoload" directory in 'runtimepath'.