codekingpro/portable-devtools
114k
1*usr_52.txt* For Vim version 9.2. Last change: 2026 Feb 142 3 4 VIM USER MANUAL by Bram Moolenaar5 6 7 Write larger plugins8 9When plugins do more than simple things, they tend to grow big. This file10explains how to make sure they still load fast and how to split them up in11smaller parts.12 13|52.1| Export and import14|52.2| Autoloading15|52.3| Autoloading without import/export16|52.4| Other mechanisms to use17|52.5| Using a Vim9 script from legacy script18|52.6| Vim9 examples: comment and highlight-yank plugin19 20 Next chapter: |usr_90.txt| Installing Vim21 Previous chapter: |usr_51.txt| Create a plugin22Table of contents: |usr_toc.txt|23 24==============================================================================25*52.1* Export and import26 27Vim9 script was designed to make it easier to write large Vim scripts. It28looks more like other script languages, especially Typescript. Also,29functions are compiled into instructions that can be executed quickly. This30makes Vim9 script a lot faster, up to a 100 times.31 32The basic idea is that a script file has items that are private, only used33inside the script file, and items that are exported, which can be used by34scripts that import them. That makes very clear what is defined where.35 36Let's start with an example, a script that exports one function and has one37private function: >38 39 vim9script40 41 export def GetMessage(count: string): string42 var nr = str2nr(count)43 var result = $'To {nr} we say '44 result ..= GetReply(nr)45 return result46 enddef47 48 def GetReply(nr: number): string49 if nr == 4250 return 'yes'51 elseif nr == 2252 return 'maybe'53 else54 return 'no'55 endif56 enddef57 58The `vim9script` command is required, `export` only works in a |Vim9| script.59 60The `export def GetMessage(...` line starts with `export`, meaning that this61function can be called by other scripts. The line `def GetReply(...` does not62start with `export`, this is a script-local function, it can only be used63inside this script file.64 65Now about the script where this is imported. In this example we use this66layout, which works well for a plugin below the "pack" directory:67 .../plugin/theplugin.vim68 .../lib/getmessage.vim69 70Assuming the "..." directory has been added to 'runtimepath', Vim will look71for plugins in the "plugin" directory and source "theplugin.vim". Vim does72not recognize the "lib" directory, you can put any scripts there.73 74The above script that exports GetMessage() goes in lib/getmessage.vim. The75GetMessage() function is used in plugin/theplugin.vim: >76 77 vim9script78 79 import "../lib/getmessage.vim"80 command -nargs=1 ShowMessage echomsg getmessage.GetMessage(<f-args>)81 82The `import` command uses a relative path, it starts with "../", which means83to go one directory up. For other kinds of paths see the `:import` command.84 85How we can try out the command that the plugin provides: >86 ShowMessage 187< To 1 we say no ~88>89 ShowMessage 2290< To 22 we say maybe ~91 92Notice that the function GetMessage() is prefixed with the imported script93name "getmessage". That way, for every imported function used, you know what94script it was imported from. If you import several scripts each of them could95define a GetMessage() function: >96 97 vim9script98 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 104If the imported script name is long or you use it in many places, you can105shorten it by adding an "as" argument: >106 import "../lib/getmessage.vim" as msg107 command -nargs=1 ShowMessage echomsg msg.GetMessage(<f-args>)108 109 110RELOADING111 112One thing to keep in mind: the imported "lib/getmessage.vim" script will be113sourced only once. When it is imported a second time sourcing it will be114skipped, since the items in it have already been created. It does not matter115if this import command is in another script, or in the same script that is116sourced again.117 118This is efficient when using a plugin, but when still developing a plugin it119means that changing "lib/getmessage.vim" after it has been imported will have120no effect. You need to quit Vim and start it again. (Rationale: the items121defined in the script could be used in a compiled function, sourcing the122script again may break those functions).123 124 125USING GLOBALS126 127Sometimes you will want to use global variables or functions, so that they can128be used anywhere. A good example is a global variable that passes a129preference to a plugin. To avoid other scripts using the same name, use a130prefix that is very unlikely to be used elsewhere. For example, if you have a131"mytags" plugin, you could use: >132 133 g:mytags_location = '$HOME/project'134 g:mytags_style = 'fast'135 136==============================================================================137*52.2* Autoloading138 139After splitting your large script into pieces, all the lines will still be140loaded and executed the moment the script is used. Every `import` loads the141imported script to find the items defined there. Although that is good for142finding errors early, it also takes time. Which is wasted if the143functionality is not often used.144 145Instead of having `import` load the script immediately, it can be postponed146until needed. Using the example above, only one change needs to be made in147the plugin/theplugin.vim script: >148 import autoload "../lib/getmessage.vim"149 150Nothing in the rest of the script needs to change. However, the types will151not be checked. Not even the existence of the GetMessage() function is152checked until it is used. You will have to decide what is more important for153your script: fast startup or getting errors early. You can also add the154"autoload" argument later, after you have checked everything works.155 156 157AUTOLOAD DIRECTORY158 159Another form is to use autoload with a script name that is not an absolute or160relative path: >161 import autoload "monthlib.vim"162 163This will search for the script "monthlib.vim" in the autoload directories of164'runtimepath'. With Unix one of the directories often is "~/.vim/autoload".165It will also search under 'packpath', under "start".166 167The main advantage of this is that this script can be easily shared with other168scripts. You do need to make sure that the script name is unique, since Vim169will search all the "autoload" directories in 'runtimepath', and if you are170using several plugins with a plugin manager, it may add a directory to171'runtimepath', each of which might have an "autoload" directory.172 173Without autoload: >174 import "monthlib.vim"175 176Vim will search for the script "monthlib.vim" in the import directories of177'runtimepath'. Note that in this case adding or removing "autoload" changes178where the script is found. With a relative or absolute path the location does179not change.180 181==============================================================================182*52.3* Autoloading without import/export183 184 *write-library-script*185A mechanism from before import/export is still useful and some users may find186it a bit simpler. The idea is that you call a function with a special name.187That function is then in an autoload script. We will call that one script a188library script.189 190The autoload mechanism is based on a function name that has "#" characters: >191 192 mylib#myfunction(arg)193 194Vim will recognize the function name by the embedded "#" character and when195it is not defined yet search for the script "autoload/mylib.vim" in196'runtimepath'. That script must define the "mylib#myfunction()" function.197Obviously the name "mylib" is the part before the "#" and is used as the name198of the script, adding ".vim".199 200You can put many other functions in the mylib.vim script, you are free to201organize your functions in library scripts. But you must use function names202where the part before the '#' matches the script name. Otherwise Vim would203not know what script to load. This is where it differs from the import/export204mechanism.205 206If you get really enthusiastic and write lots of library scripts, you may207want to use subdirectories. Example: >208 209 netlib#ftp#read('somefile')210 211Here the script name is taken from the function name up to the last "#". The212"#" in the middle are replaced by a slash, the last one by ".vim". Thus you213get "netlib/ftp.vim". For Unix the library script used for this could be:214 215 ~/.vim/autoload/netlib/ftp.vim216 217Where the function is defined like this: >218 219 def netlib#ftp#read(fname: string)220 # Read the file fname through ftp221 enddef222 223Notice that the name the function is defined with is exactly the same as the224name used for calling the function. And the part before the last '#'225exactly matches the subdirectory and script name.226 227You can use the same mechanism for variables: >228 229 var weekdays = dutch#weekdays230 231This will load the script "autoload/dutch.vim", which should contain something232like: >233 234 var dutch#weekdays = ['zondag', 'maandag', 'dinsdag', 'woensdag',235 \ 'donderdag', 'vrijdag', 'zaterdag']236 237Further reading: |autoload|.238 239==============================================================================240*52.4* Other mechanisms to use241 242Some may find the use of several files a hassle and prefer to keep everything243together in one script. To avoid this resulting in slow startup there is a244mechanism that only defines a small part and postpones the rest to when it is245actually used. *write-plugin-quickload*246 247The basic idea is that the plugin is loaded twice. The first time user248commands and mappings are defined that offer the functionality. The second249time the functions that implement the functionality are defined.250 251It may sound surprising that quickload means loading a script twice. What we252mean is that it loads quickly the first time, postponing the bulk of the253script to the second time, which only happens when you actually use it. When254you always use the functionality it actually gets slower!255 256This uses a FuncUndefined autocommand. This works differently from the257|autoload| functionality explained above.258 259The following example shows how it's done: >260 261 " Vim global plugin for demonstrating quick loading262 " Last Change: 2005 Feb 25263 " Maintainer: Bram Moolenaar <Bram@vim.org>264 " License: This file is placed in the public domain.265 266 if !exists("s:did_load")267 command -nargs=* BNRead call BufNetRead(<f-args>)268 map <F19> :call BufNetWrite('something')<CR>269 270 let s:did_load = 1271 exe 'au FuncUndefined BufNet* source ' .. expand('<sfile>')272 finish273 endif274 275 function BufNetRead(...)276 echo 'BufNetRead(' .. string(a:000) .. ')'277 " read functionality here278 endfunction279 280 function BufNetWrite(...)281 echo 'BufNetWrite(' .. string(a:000) .. ')'282 " write functionality here283 endfunction284 285When the script is first loaded "s:did_load" is not set. The commands between286the "if" and "endif" will be executed. This ends in a |:finish| command, thus287the rest of the script is not executed.288 289The second time the script is loaded "s:did_load" exists and the commands290after the "endif" are executed. This defines the (possible long)291BufNetRead() and BufNetWrite() functions.292 293If you drop this script in your plugin directory Vim will execute it on294startup. This is the sequence of events that happens:295 2961. The "BNRead" command is defined and the <F19> key is mapped when the script297 is sourced at startup. A |FuncUndefined| autocommand is defined. The298 ":finish" command causes the script to terminate early.299 3002. The user types the BNRead command or presses the <F19> key. The301 BufNetRead() or BufNetWrite() function will be called.302 3033. Vim can't find the function and triggers the |FuncUndefined| autocommand304 event. Since the pattern "BufNet*" matches the invoked function, the305 command "source fname" will be executed. "fname" will be equal to the name306 of the script, no matter where it is located, because it comes from307 expanding "<sfile>" (see |expand()|).308 3094. The script is sourced again, the "s:did_load" variable exists and the310 functions are defined.311 312Notice that the functions that are loaded afterwards match the pattern in the313|FuncUndefined| autocommand. You must make sure that no other plugin defines314functions that match this pattern.315 316==============================================================================317*52.5* Using a Vim9 script from legacy script *source-vim9-script*318 319In some cases you have a legacy Vim script where you want to use items from a320Vim9 script. For example in your .vimrc you want to initialize a plugin. The321best way to do this is to use `:import`. For example: >322 323 import 'myNicePlugin.vim'324 call myNicePlugin.NiceInit('today')325 326This finds the exported function "NiceInit" in the Vim9 script file and makes327it available as script-local item "myNicePlugin.NiceInit". `:import` always328uses the script namespace, even when "s:" is not given. If "myNicePlugin.vim"329was already sourced it is not sourced again.330 331Besides avoiding putting any items in the global namespace (where name clashes332can cause unexpected errors), this also means the script is sourced only once,333no matter how many times items from it are imported.334 335In some cases, e.g. for testing, you may just want to source the Vim9 script.336That is OK, but then only global items will be available. The Vim9 script337will have to make sure to use a unique name for these global items. Example: >338 source ~/.vim/extra/myNicePlugin.vim339 call g:NicePluginTest()340 341==============================================================================342*52.6* Vim9 examples: comment and highlight-yank plugin343 344COMMENT PACKAGE345 346Vim comes with a comment plugin, written in Vim9 script. |comment-install|347Have a look at the package located at $VIMRUNTIME/pack/dist/opt/comment/348 349HIGHLIGHT YANK PLUGIN350 351Vim comes with the highlight-yank plugin, written in Vim9 script352|hlyank-install|, here is a simplified implementation: >vim9353 354 vim9script355 356 def HighlightedYank(hlgroup = 'IncSearch', duration = 300, in_visual = true)357 if v:event.operator ==? 'y'358 if !in_visual && visualmode() != null_string359 visualmode(1)360 return361 endif362 var [beg, end] = [getpos("'["), getpos("']")]363 var type = v:event.regtype ?? 'v'364 var pos = getregionpos(beg, end, {type: type, exclusive: false})365 var m = matchaddpos(hlgroup, pos->mapnew((_, v) => {366 var col_beg = v[0][2] + v[0][3]367 var col_end = v[1][2] + v[1][3] + 1368 return [v[0][1], col_beg, col_end - col_beg]369 }))370 var winid = win_getid()371 timer_start(duration, (_) => m->matchdelete(winid))372 endif373 enddef374 375 autocmd TextYankPost * HighlightedYank()376<377For the complete example, have a look into the package located at378`$VIMRUNTIME/pack/dist/opt/hlyank/`379 380==============================================================================381 382Next chapter: |usr_90.txt| Installing Vim383 384 385Copyright: see |manual-copyright| vim:tw=78:ts=8:noet:ft=help:norl:386 