vim

Fork of vim, an acceptable text editor
git clone git://git.laack.co/vim.git
Log | Files | Refs | README | LICENSE

usr_52.txt (16419B)


      1 *usr_52.txt*	For Vim version 9.2.  Last change: 2026 Jul 27
      2 
      3 
      4 		     VIM USER MANUAL	by Bram Moolenaar
      5 
      6 
      7 		       Write larger plugins
      8 
      9 When plugins do more than simple things, they tend to grow big.  This file
     10 explains how to make sure they still load fast and how to split them up in
     11 smaller parts.
     12 
     13 |52.1|	Export and import
     14 |52.2|	Autoloading
     15 |52.3|	Autoloading without import/export
     16 |52.4|	Other mechanisms to use
     17 |52.5|	Using a Vim9 script from legacy script
     18 |52.6|	Vim9 examples: comment and highlight-yank plugin
     19 
     20      Next chapter: |usr_90.txt|  Installing Vim
     21  Previous chapter: |usr_51.txt|  Create a plugin
     22 Table of contents: |usr_toc.txt|
     23 
     24 ==============================================================================
     25 *52.1*	Export and import
     26 
     27 Vim9 script was designed to make it easier to write large Vim scripts.  It
     28 looks more like other script languages, especially Typescript.  Also,
     29 functions are compiled into instructions that can be executed quickly.  This
     30 makes Vim9 script a lot faster, up to a 100 times.
     31 
     32 The basic idea is that a script file has items that are private, only used
     33 inside the script file, and items that are exported, which can be used by
     34 scripts that import them.  That makes very clear what is defined where.
     35 
     36 Let's start with an example, a script that exports one function and has one
     37 private function: >
     38 
     39 	vim9script
     40 
     41 	export def GetMessage(count: string): string
     42 	   var nr = str2nr(count)
     43 	   var result = $'To {nr} we say '
     44 	   result ..= GetReply(nr)
     45 	   return result
     46 	enddef
     47 
     48 	def GetReply(nr: number): string
     49 	  if nr == 42
     50 	     return 'yes'
     51 	  elseif nr == 22
     52 	     return 'maybe'
     53 	  else
     54 	     return 'no'
     55 	  endif
     56 	enddef
     57 
     58 The `vim9script` command is required, `export` only works in a |Vim9| script.
     59 
     60 The `export def GetMessage(...` line starts with `export`, meaning that this
     61 function can be called by other scripts.  The line `def GetReply(...` does not
     62 start with `export`, this is a script-local function, it can only be used
     63 inside this script file.
     64 
     65 Now about the script where this is imported.  In this example we use this
     66 layout, which works well for a plugin below the "pack" directory:
     67 	.../plugin/theplugin.vim
     68 	.../lib/getmessage.vim
     69 
     70 Assuming the "..." directory has been added to 'runtimepath', Vim will look
     71 for plugins in the "plugin" directory and source "theplugin.vim".  Vim does
     72 not recognize the "lib" directory, you can put any scripts there.
     73 
     74 The above script that exports GetMessage() goes in lib/getmessage.vim.  The
     75 GetMessage() function is used in plugin/theplugin.vim: >
     76 
     77 	vim9script
     78 
     79 	import "../lib/getmessage.vim"
     80 	command -nargs=1 ShowMessage echomsg getmessage.GetMessage(<f-args>)
     81 
     82 The `import` command uses a relative path, it starts with "../", which means
     83 to go one directory up.  For other kinds of paths see the `:import` command.
     84 
     85 How we can try out the command that the plugin provides: >
     86 	ShowMessage 1
     87 <	To 1 we say no ~
     88 >
     89 	ShowMessage 22
     90 <	To 22 we say maybe ~
     91 
     92 Notice that the function GetMessage() is prefixed with the imported script
     93 name "getmessage".  That way, for every imported function used, you know what
     94 script it was imported from.  If you import several scripts each of them could
     95 define a GetMessage() function: >
     96 
     97 	vim9script
     98 
     99 	import "../lib/getmessage.vim"
    100 	import "../lib/getother.vim"
    101 	command -nargs=1 ShowMessage echomsg getmessage.GetMessage(<f-args>)
    102 	command -nargs=1 ShowOther echomsg getother.GetMessage(<f-args>)
    103 
    104 If the imported script name is long or you use it in many places, you can
    105 shorten it by adding an "as" argument: >
    106 	import "../lib/getmessage.vim" as msg
    107 	command -nargs=1 ShowMessage echomsg msg.GetMessage(<f-args>)
    108 
    109 
    110 RELOADING
    111 
    112 One thing to keep in mind: the imported "lib/getmessage.vim" script will be
    113 sourced only once.  When it is imported a second time sourcing it will be
    114 skipped, since the items in it have already been created.  It does not matter
    115 if this import command is in another script, or in the same script that is
    116 sourced again.
    117 
    118 This is efficient when using a plugin, but when still developing a plugin it
    119 means that changing "lib/getmessage.vim" after it has been imported will have
    120 no effect.  You need to quit Vim and start it again. (Rationale: the items
    121 defined in the script could be used in a compiled function, sourcing the
    122 script again may break those functions).
    123 
    124 
    125 USING GLOBALS
    126 
    127 Sometimes you will want to use global variables or functions, so that they can
    128 be used anywhere.  A good example is a global variable that passes a
    129 preference to a plugin.  To avoid other scripts using the same name, use a
    130 prefix that is very unlikely to be used elsewhere.  For example, if you have a
    131 "mytags" plugin, you could use: >
    132 
    133 	g:mytags_location = '$HOME/project'
    134 	g:mytags_style = 'fast'
    135 
    136 ==============================================================================
    137 *52.2*	Autoloading
    138 
    139 After splitting a large script into pieces, an imported script is loaded and
    140 executed at the moment the importing script is sourced.  Every |:import| loads
    141 the imported script to find the items defined there.  However, if an imported
    142 script is large, then the startup time may become noticeably slower, but on
    143 the other hand if there are errors they will be detected at import time.
    144 
    145 To avoid long startup times, the loading of an imported script may be deferred
    146 until it is actually needed.  This is done with the `autoload` keyword. Using
    147 the example above, only one change is needed in `plugin/theplugin.vim`:
    148 >
    149 	import autoload "../lib/getmessage.vim"
    150 <
    151 Nothing in the rest of the script needs to change.  However, the types will
    152 not be checked, and "../lib/getmessage.vim" is not loaded at import time; Vim
    153 only verifies that the file exists and is readable.  Not even the existence of
    154 the GetMessage() function is checked until it is used.  As a result, errors in
    155 the "getmessage.vim" script are detected only at runtime.
    156 
    157 You will have to decide what is more important for your script: fast startup
    158 or getting errors early.
    159 
    160 A practical strategy is to omit the `autoload` keyword during development and
    161 debugging so that errors are reported immediately, then add it back before
    162 distributing your plugin to improve startup performance.
    163 
    164 
    165 AUTOLOAD DIRECTORIES
    166 
    167 Another way to lazily load scripts is to `import autoload` a script without
    168 specifying any relative or absolute path, like in the following example: >
    169 
    170 	import autoload "monthlib.vim"
    171 <
    172 Vim searches for the script in the "autoload" directories under 'runtimepath'.
    173 This means that the script must reside in an "autoload" folder.  On Unix
    174 systems, one such directory is often `~/.vim/autoload`.  It will also search
    175 under 'packpath', under "start".
    176 
    177 When a script is imported this way, its exported symbols are referenced
    178 through a global autoload namespace rather than remaining local to the
    179 importing script.
    180 
    181 Since Vim searches every "autoload" directory in 'runtimepath', choose a
    182 unique script name.  Plugin managers often add multiple directories to
    183 'runtimepath', each of which may contain an "autoload" directory.
    184 
    185 The two forms of `import autoload` are summarized as follows:
    186 
    187 - `import autoload "foo.vim"`
    188   Vim searches 'runtimepath' for the script.  Because such scripts must reside
    189   under an "autoload" directory, exported symbols are available through the
    190   global autoload namespace.
    191 
    192 - `import autoload "/some/path/foo.vim"`
    193   If the resolved path falls under an "autoload" directory, exported symbols
    194   are likewise in the global autoload namespace; otherwise they remain local
    195   to the importing script.
    196 
    197 The main advantage of accessing symbols through the global autoload namespace
    198 is that the script can be easily imported by other scripts, and symbols can
    199 be used straight away.  However, this has some drawbacks when reloading a
    200 script, see |vim9-reload| for more info.
    201 
    202 When symbols are in script-local scope, sharing them across scripts is more
    203 involved and there is no general rule: the right approach depends on the
    204 plugin layout.
    205 
    206 Finally, when a script is imported without `autoload` and without path, like
    207 the following example: >
    208 	import "monthlib.vim"
    209 <
    210 Vim will search for the script "monthlib.vim" in the import directories of
    211 'runtimepath'.
    212 
    213 In this case, adding or removing the `autoload` keyword changes where Vim
    214 searches for the script.  When a relative or absolute path is used, then the
    215 location does not change.
    216 
    217 ==============================================================================
    218 *52.3*	Autoloading without import/export
    219 
    220 						*write-library-script*
    221 A mechanism from before import/export is still useful and some users may find
    222 it a bit simpler.  The idea is that you call a function with a special name.
    223 That function is then in an autoload script.  We will call that one script a
    224 library script.
    225 
    226 The autoload mechanism is based on a function name that has "#" characters: >
    227 
    228 	mylib#myfunction(arg)
    229 
    230 Vim will recognize the function name by the embedded "#" character and when
    231 it is not defined yet search for the script "autoload/mylib.vim" in
    232 'runtimepath'.  That script must define the "mylib#myfunction()" function.
    233 Obviously the name "mylib" is the part before the "#" and is used as the name
    234 of the script, adding ".vim".
    235 
    236 You can put many other functions in the mylib.vim script, you are free to
    237 organize your functions in library scripts.  But you must use function names
    238 where the part before the '#' matches the script name.  Otherwise Vim would
    239 not know what script to load.  This is where it differs from the import/export
    240 mechanism.
    241 
    242 If you get really enthusiastic and write lots of library scripts, you may
    243 want to use subdirectories.  Example: >
    244 
    245 	netlib#ftp#read('somefile')
    246 
    247 Here the script name is taken from the function name up to the last "#". The
    248 "#" in the middle are replaced by a slash, the last one by ".vim".  Thus you
    249 get "netlib/ftp.vim".  For Unix the library script used for this could be:
    250 
    251 	~/.vim/autoload/netlib/ftp.vim
    252 
    253 Where the function is defined like this: >
    254 
    255 	def netlib#ftp#read(fname: string)
    256 		#  Read the file fname through ftp
    257 	enddef
    258 
    259 Notice that the name the function is defined with is exactly the same as the
    260 name used for calling the function.  And the part before the last '#'
    261 exactly matches the subdirectory and script name.
    262 
    263 You can use the same mechanism for variables: >
    264 
    265 	var weekdays = dutch#weekdays
    266 
    267 This will load the script "autoload/dutch.vim", which should contain something
    268 like: >
    269 
    270 	var dutch#weekdays = ['zondag', 'maandag', 'dinsdag', 'woensdag',
    271 		\ 'donderdag', 'vrijdag', 'zaterdag']
    272 
    273 Further reading: |autoload|.
    274 
    275 ==============================================================================
    276 *52.4*	Other mechanisms to use
    277 
    278 Some may find the use of several files a hassle and prefer to keep everything
    279 together in one script.  To avoid this resulting in slow startup there is a
    280 mechanism that only defines a small part and postpones the rest to when it is
    281 actually used.  *write-plugin-quickload*
    282 
    283 The basic idea is that the plugin is loaded twice.  The first time user
    284 commands and mappings are defined that offer the functionality.  The second
    285 time the functions that implement the functionality are defined.
    286 
    287 It may sound surprising that quickload means loading a script twice.  What we
    288 mean is that it loads quickly the first time, postponing the bulk of the
    289 script to the second time, which only happens when you actually use it.  When
    290 you always use the functionality it actually gets slower!
    291 
    292 This uses a FuncUndefined autocommand.  This works differently from the
    293 |autoload| functionality explained above.
    294 
    295 The following example shows how it's done: >
    296 
    297 	" Vim global plugin for demonstrating quick loading
    298 	" Last Change:	2005 Feb 25
    299 	" Maintainer:	Bram Moolenaar <Bram@vim.org>
    300 	" License:	This file is placed in the public domain.
    301 
    302 	if !exists("s:did_load")
    303 		command -nargs=* BNRead  call BufNetRead(<f-args>)
    304 		map <F19> :call BufNetWrite('something')<CR>
    305 
    306 		let s:did_load = 1
    307 		exe 'au FuncUndefined BufNet* source ' .. expand('<sfile>')
    308 		finish
    309 	endif
    310 
    311 	function BufNetRead(...)
    312 		echo 'BufNetRead(' .. string(a:000) .. ')'
    313 		" read functionality here
    314 	endfunction
    315 
    316 	function BufNetWrite(...)
    317 		echo 'BufNetWrite(' .. string(a:000) .. ')'
    318 		" write functionality here
    319 	endfunction
    320 
    321 When the script is first loaded "s:did_load" is not set.  The commands between
    322 the "if" and "endif" will be executed.  This ends in a |:finish| command, thus
    323 the rest of the script is not executed.
    324 
    325 The second time the script is loaded "s:did_load" exists and the commands
    326 after the "endif" are executed.  This defines the (possible long)
    327 BufNetRead() and BufNetWrite() functions.
    328 
    329 If you drop this script in your plugin directory Vim will execute it on
    330 startup.  This is the sequence of events that happens:
    331 
    332 1. The "BNRead" command is defined and the <F19> key is mapped when the script
    333    is sourced at startup.  A |FuncUndefined| autocommand is defined.  The
    334    ":finish" command causes the script to terminate early.
    335 
    336 2. The user types the BNRead command or presses the <F19> key.  The
    337    BufNetRead() or BufNetWrite() function will be called.
    338 
    339 3. Vim can't find the function and triggers the |FuncUndefined| autocommand
    340    event.  Since the pattern "BufNet*" matches the invoked function, the
    341    command "source fname" will be executed.  "fname" will be equal to the name
    342    of the script, no matter where it is located, because it comes from
    343    expanding "<sfile>" (see |expand()|).
    344 
    345 4. The script is sourced again, the "s:did_load" variable exists and the
    346    functions are defined.
    347 
    348 Notice that the functions that are loaded afterwards match the pattern in the
    349 |FuncUndefined| autocommand.  You must make sure that no other plugin defines
    350 functions that match this pattern.
    351 
    352 ==============================================================================
    353 *52.5*	Using a Vim9 script from legacy script		*source-vim9-script*
    354 
    355 In some cases you have a legacy Vim script where you want to use items from a
    356 Vim9 script.  For example in your .vimrc you want to initialize a plugin.  The
    357 best way to do this is to use `:import`.  For example: >
    358 
    359 	import 'myNicePlugin.vim'
    360 	call myNicePlugin.NiceInit('today')
    361 
    362 This finds the exported function "NiceInit" in the Vim9 script file and makes
    363 it available as script-local item "myNicePlugin.NiceInit". `:import` always
    364 uses the script namespace, even when "s:" is not given.  If "myNicePlugin.vim"
    365 was already sourced it is not sourced again.
    366 
    367 Besides avoiding putting any items in the global namespace (where name clashes
    368 can cause unexpected errors), this also means the script is sourced only once,
    369 no matter how many times items from it are imported.
    370 
    371 In some cases, e.g. for testing, you may just want to source the Vim9 script.
    372 That is OK, but then only global items will be available.  The Vim9 script
    373 will have to make sure to use a unique name for these global items. Example: >
    374 	source ~/.vim/extra/myNicePlugin.vim
    375 	call g:NicePluginTest()
    376 
    377 ==============================================================================
    378 *52.6*	Vim9 examples: comment and highlight-yank plugin
    379 
    380 COMMENT PACKAGE
    381 
    382 Vim comes with a comment plugin, written in Vim9 script.  |comment-install|
    383 Have a look at the package located at $VIMRUNTIME/pack/dist/opt/comment/
    384 
    385 HIGHLIGHT YANK PLUGIN
    386 
    387 Vim comes with the highlight-yank plugin, written in Vim9 script
    388 |hlyank-install|, here is a simplified implementation: >vim9
    389 
    390 	vim9script
    391 
    392 	def HighlightedYank(hlgroup = 'IncSearch', duration = 300, in_visual = true)
    393 	  if v:event.operator ==? 'y'
    394 	    if !in_visual && visualmode() != null_string
    395 	      visualmode(1)
    396 	      return
    397 	    endif
    398 	    var [beg, end] = [getpos("'["), getpos("']")]
    399 	    var type = v:event.regtype ?? 'v'
    400 	    var pos = getregionpos(beg, end, {type: type, exclusive: false})
    401 	    var m = matchaddpos(hlgroup, pos->mapnew((_, v) => {
    402 	      var col_beg = v[0][2] + v[0][3]
    403 	      var col_end = v[1][2] + v[1][3] + 1
    404 	      return [v[0][1], col_beg, col_end - col_beg]
    405 	    }))
    406 	    var winid = win_getid()
    407 	    timer_start(duration, (_) => m->matchdelete(winid))
    408 	  endif
    409 	enddef
    410 
    411 	autocmd TextYankPost * HighlightedYank()
    412 <
    413 For the complete example, have a look into the package located at
    414 `$VIMRUNTIME/pack/dist/opt/hlyank/`
    415 
    416 ==============================================================================
    417 
    418 Next chapter: |usr_90.txt|  Installing Vim
    419 
    420 
    421 Copyright: see |manual-copyright|  vim:tw=78:ts=8:noet:ft=help:norl: