Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
usr_51.txt696 linesDownload Raw Back to doc
1*usr_51.txt*	For Vim version 9.2.  Last change: 2026 Feb 142 3 4		     VIM USER MANUAL	by Bram Moolenaar5 6 7			      Write plugins8 9 10Plugins can be used to define settings for a specific type of file, syntax11highlighting and many other things.  This chapter explains how to write the12most common Vim plugins.13 14|51.1|	Writing a generic plugin15|51.2|	Writing a filetype plugin16|51.3|	Writing a compiler plugin17|51.4|	Distributing Vim scripts18 19     Next chapter: |usr_52.txt|  Write large plugins20 Previous chapter: |usr_50.txt|  Advanced Vim script writing21Table of contents: |usr_toc.txt|22 23==============================================================================24*51.1*	Writing a generic plugin			*write-plugin*25 26You can write a Vim script in such a way that many people can use it.  This is27called a plugin.  Vim users can drop your script in their plugin directory and28use its features right away |add-plugin|.29 30There are actually two types of plugins:31 32  global plugins: For all types of files.33filetype plugins: Only for files of a specific type.34 35In this section the first type is explained.  Most items are also relevant for36writing filetype plugins.  The specifics for filetype plugins are in the next37section |write-filetype-plugin|.38 39We will use |Vim9| syntax here, the recommended way to write new plugins.40Make sure the file starts with the `vim9script` command.41 42 43NAME44 45First of all you must choose a name for your plugin.  The features provided46by the plugin should be clear from its name.  And it should be unlikely that47someone else writes a plugin with the same name but which does something48different.49 50A script that corrects typing mistakes could be called "typecorrect.vim".  We51will use it here as an example.52 53For the plugin to work for everybody, it should follow a few guidelines.  This54will be explained step-by-step.  The complete example plugin is at the end.55 56 57BODY58 59Let's start with the body of the plugin, the lines that do the actual work: >60 61 12	iabbrev teh the62 13	iabbrev otehr other63 14	iabbrev wnat want64 15	iabbrev synchronisation65 16		\ synchronization66 67The actual list should be much longer, of course.68 69The line numbers have only been added to explain a few things, don't put them70in your plugin file!71 72 73FIRST LINE74>75  1	vim9script noclear76 77You need to use `vim9script` as the very first command.  Best is to put it in78the very first line.79 80The script we are writing will have a `finish` command to bail out when it is81loaded a second time.  To avoid that the items defined in the script are lost82the "noclear" argument is used.  More info about this at |vim9-reload|.83 84 85HEADER86 87You will probably add new corrections to the plugin and soon have several88versions lying around.  And when distributing this file, people will want to89know who wrote this wonderful plugin and where they can send remarks.90Therefore, put a header at the top of your plugin: >91 92  2	# Vim global plugin for correcting typing mistakes93  3	# Last Change:	2021 Dec 3094  4	# Maintainer:	Bram Moolenaar <Bram@vim.org>95 96About copyright and licensing: Since plugins are very useful and it's hardly97worth restricting their distribution, please consider making your plugin98either public domain or use the Vim |license|.  A short note about this near99the top of the plugin should be sufficient.  Example: >100 101  5	# License:	This file is placed in the public domain.102 103 104NOT LOADING105 106It is possible that a user doesn't always want to load this plugin.  Or the107system administrator has dropped it in the system-wide plugin directory, but a108user has their own plugin they want to use.  Then the user must have a chance109to disable loading this specific plugin.  These lines will make it possible: >110 111  7	if exists("g:loaded_typecorrect")112  8	  finish113  9	endif114 10	g:loaded_typecorrect = 1115 116This also avoids that when the script is loaded twice it would pointlessly117redefine functions and cause trouble for autocommands that are added twice.118 119The name is recommended to start with "g:loaded_" and then the file name of120the plugin, literally.  The "g:" is prepended to make the variable global, so121that other places can check whether its functionality is available.  Without122"g:" it would be local to the script.123 124Using `finish` stops Vim from reading the rest of the file, it's much quicker125than using if-endif around the whole file, since Vim would still need to parse126the commands to find the `endif`.127 128 129MAPPING130 131Now let's make the plugin more interesting: We will add a mapping that adds a132correction for the word under the cursor.  We could just pick a key sequence133for this mapping, but the user might already use it for something else.  To134allow the user to define which keys a mapping in a plugin uses, the <Leader>135item can be used: >136 137 20	  map <unique> <Leader>a  <Plug>TypecorrAdd;138 139The "<Plug>TypecorrAdd;" thing will do the work, more about that further on.140 141The user can set the "g:mapleader" variable to the key sequence that they want142plugin mappings to start with.  Thus if the user has done: >143 144	g:mapleader = "_"145 146the mapping will define "_a".  If the user didn't do this, the default value147will be used, which is a backslash.  Then a map for "\a" will be defined.148 149Note that <unique> is used, this will cause an error message if the mapping150already happened to exist. |:map-<unique>|151 152But what if the user wants to define their own key sequence?  We can allow153that with this mechanism: >154 155 19	if !hasmapto('<Plug>TypecorrAdd;')156 20	  map <unique> <Leader>a  <Plug>TypecorrAdd;157 21	endif158 159This checks if a mapping to "<Plug>TypecorrAdd;" already exists, and only160defines the mapping from "<Leader>a" if it doesn't.  The user then has a161chance of putting this in their vimrc file: >162 163	map ,c  <Plug>TypecorrAdd;164 165Then the mapped key sequence will be ",c" instead of "_a" or "\a".166 167 168PIECES169 170If a script gets longer, you often want to break up the work in pieces.  You171can use functions or mappings for this.  But you don't want these functions172and mappings to interfere with the ones from other scripts.  For example, you173could define a function Add(), but another script could try to define the same174function.  To avoid this, we define the function local to the script.175Fortunately, in |Vim9| script this is the default.  In a legacy script you176would need to prefix the name with "s:".177 178We will define a function that adds a new typing correction: >179 180 28	def Add(from: string, correct: bool)181 29	  var to = input($"type the correction for {from}: ")182 30	  exe $":iabbrev {from} {to}"183 ...184 34	enddef185 186Now we can call the function Add() from within this script.  If another187script also defines Add(), it will be local to that script and can only188be called from that script.  There can also be a global g:Add() function,189which is again another function.190 191<SID> can be used with mappings.  It generates a script ID, which identifies192the current script.  In our typing correction plugin we use it like this: >193 194 22	noremap <unique> <script> <Plug>TypecorrAdd;  <SID>Add195 ...196 26	noremap <SID>Add  :call <SID>Add(expand("<cword>"), true)<CR>197 198Thus when a user types "\a", this sequence is invoked: >199 200	\a  ->  <Plug>TypecorrAdd;  ->  <SID>Add  ->  :call <SID>Add(...)201 202If another script also maps <SID>Add, it will get another script ID and203thus define another mapping.204 205Note that instead of Add() we use <SID>Add() here.  That is because the206mapping is typed by the user, thus outside of the script context.  The <SID>207is translated to the script ID, so that Vim knows in which script to look for208the Add() function.209 210This is a bit complicated, but it's required for the plugin to work together211with other plugins.  The basic rule is that you use <SID>Add() in mappings and212Add() in other places (the script itself, autocommands, user commands).213 214We can also add a menu entry to do the same as the mapping: >215 216 24	noremenu <script> Plugin.Add\ Correction      <SID>Add217 218The "Plugin" menu is recommended for adding menu items for plugins.  In this219case only one item is used.  When adding more items, creating a submenu is220recommended.  For example, "Plugin.CVS" could be used for a plugin that offers221CVS operations "Plugin.CVS.checkin", "Plugin.CVS.checkout", etc.222 223Note that in line 28 ":noremap" is used to avoid that any other mappings cause224trouble.  Someone may have remapped ":call", for example.  In line 24 we also225use ":noremap", but we do want "<SID>Add" to be remapped.  This is why226"<script>" is used here.  This only allows mappings which are local to the227script. |:map-<script>|  The same is done in line 26 for ":noremenu".228|:menu-<script>|229 230 231<SID> AND <Plug>					*using-<Plug>*232 233Both <SID> and <Plug> are used to avoid that mappings of typed keys interfere234with mappings that are only to be used from other mappings.  Note the235difference between using <SID> and <Plug>:236 237<Plug>	is visible outside of the script.  It is used for mappings which the238	user might want to map a key sequence to.  <Plug> is a special code239	that a typed key will never produce.240	To make it very unlikely that other plugins use the same sequence of241	characters, use this structure: <Plug> scriptname mapname242	In our example the scriptname is "Typecorr" and the mapname is "Add".243	We add a semicolon as the terminator.  This results in244	"<Plug>TypecorrAdd;".  Only the first character of scriptname and245	mapname is uppercase, so that we can see where mapname starts.246 247<SID>	is the script ID, a unique identifier for a script.248	Internally Vim translates <SID> to "<SNR>123_", where "123" can be any249	number.  Thus a function "<SID>Add()" will have a name "<SNR>11_Add()"250	in one script, and "<SNR>22_Add()" in another.  You can see this if251	you use the ":function" command to get a list of functions.  The252	translation of <SID> in mappings is exactly the same, that's how you253	can call a script-local function from a mapping.254 255 256USER COMMAND257 258Now let's add a user command to add a correction: >259 260 36	if !exists(":Correct")261 37	  command -nargs=1  Correct  :call Add(<q-args>, false)262 38	endif263 264The user command is defined only if no command with the same name already265exists.  Otherwise we would get an error here.  Overriding the existing user266command with ":command!" is not a good idea, this would probably make the user267wonder why the command they defined themselves doesn't work.  |:command|268If it did happen you can find out who to blame with: >269 270	verbose command Correct271 272 273SCRIPT VARIABLES274 275When a variable starts with "s:" it is a script variable.  It can only be used276inside a script.  Outside the script it's not visible.  This avoids trouble277with using the same variable name in different scripts.  The variables will be278kept as long as Vim is running.  And the same variables are used when sourcing279the same script again. |s:var|280 281The nice thing about |Vim9| script is that variables are local to the script282by default.  You can prepend "s:" if you like, but you do not need to.  And283functions in the script can also use the script variables without a prefix284(they must be declared before the function for this to work).285 286Script-local variables can also be used in functions, autocommands and user287commands that are defined in the script.  Thus they are the perfect way to288share information between parts of your plugin, without it leaking out.  In289our example we can add a few lines to count the number of corrections: >290 291 17	var count = 4292 ...293 28	def Add(from: string, correct: bool)294 ...295 32	  count += 1296 33	  echo "you now have " .. count .. " corrections"297 34	enddef298 299"count" is declared and initialized to 4 in the script itself.  When later300the Add() function is called, it increments "count".  It doesn't matter from301where the function was called, since it has been defined in the script, it302will use the local variables from this script.303 304 305THE RESULT306 307Here is the resulting complete example: >308 309  1	vim9script noclear310  2	# Vim global plugin for correcting typing mistakes311  3	# Last Change:	2021 Dec 30312  4	# Maintainer:	Bram Moolenaar <Bram@vim.org>313  5	# License:	This file is placed in the public domain.314  6315  7	if exists("g:loaded_typecorrect")316  8	  finish317  9	endif318 10	g:loaded_typecorrect = 1319 11320 12	iabbrev teh the321 13	iabbrev otehr other322 14	iabbrev wnat want323 15	iabbrev synchronisation324 16		\ synchronization325 17	var count = 4326 18327 19	if !hasmapto('<Plug>TypecorrAdd;')328 20	  map <unique> <Leader>a  <Plug>TypecorrAdd;329 21	endif330 22	noremap <unique> <script> <Plug>TypecorrAdd;  <SID>Add331 23332 24	noremenu <script> Plugin.Add\ Correction      <SID>Add333 25334 26	noremap <SID>Add  :call <SID>Add(expand("<cword>"), true)<CR>335 27336 28	def Add(from: string, correct: bool)337 29	  var to = input("type the correction for " .. from .. ": ")338 30	  exe ":iabbrev " .. from .. " " .. to339 31	  if correct | exe "normal viws\<C-R>\" \b\e" | endif340 32	  count += 1341 33	  echo "you now have " .. count .. " corrections"342 34	enddef343 35344 36	if !exists(":Correct")345 37	  command -nargs=1  Correct  call Add(<q-args>, false)346 38	endif347 348Line 31 wasn't explained yet.  It applies the new correction to the word under349the cursor.  The |:normal| command is used to use the new abbreviation.  Note350that mappings and abbreviations are expanded here, even though the function351was called from a mapping defined with ":noremap".352 353 354DOCUMENTATION						*write-local-help*355 356It's a good idea to also write some documentation for your plugin.  Especially357when its behavior can be changed by the user.  See |help-writing| for the358syntax used by the help files and |add-local-help| for how local help files359are installed.360 361Here is a simple example for a plugin help file, called "typecorrect.txt": >362 363  1	*typecorrect.txt*	Plugin for correcting typing mistakes364  2365  3	If you make typing mistakes, this plugin will have them corrected366  4	automatically.367  5368  6	There are currently only a few corrections.  Add your own if you like.369  7370  8	Mappings:371  9	<Leader>a   or   <Plug>TypecorrAdd;372 10		Add a correction for the word under the cursor.373 11374 12	Commands:375 13	:Correct {word}376 14		Add a correction for {word}.377 15378 16							*typecorrect-settings*379 17	This plugin doesn't have any settings.380 381The first line is actually the only one for which the format matters.  It will382be extracted from the help file to be put in the "LOCAL ADDITIONS:" section of383help.txt |local-additions|.  The first "*" must be in the first column of the384first line.  After adding your help file do ":help" and check that the entries385line up nicely.386 387You can add more tags inside ** in your help file.  But be careful not to use388existing help tags.  You would probably use the name of your plugin in most of389them, like "typecorrect-settings" in the example.390 391Using references to other parts of the help in || is recommended.  This makes392it easy for the user to find associated help.393 394 395SUMMARY							*plugin-special*396 397Summary of special things to use in a plugin:398 399var name		Variable local to the script.400 401<SID>			Script-ID, used for mappings and functions local to402			the script.403 404hasmapto()		Function to test if the user already defined a mapping405			for functionality the script offers.406 407<Leader>		Value of "mapleader", which the user defines as the408			keys that plugin mappings start with.409 410map <unique>		Give a warning if a mapping already exists.411 412noremap <script>	Use only mappings local to the script, not global413			mappings.414 415exists(":Cmd")		Check if a user command already exists.416 417==============================================================================418*51.2*	Writing a filetype plugin	*write-filetype-plugin* *ftplugin*419 420A filetype plugin is like a global plugin, except that it sets options and421defines mappings for the current buffer only.  See |add-filetype-plugin| for422how this type of plugin is used.423 424First read the section on global plugins above |51.1|.  All that is said there425also applies to filetype plugins.  There are a few extras, which are explained426here.  The essential thing is that a filetype plugin should only have an427effect on the current buffer.428 429 430DISABLING431 432If you are writing a filetype plugin to be used by many people, they need a433chance to disable loading it.  Put this at the top of the plugin: >434 435	# Only do this when not done yet for this buffer436	if exists("b:did_ftplugin")437	  finish438	endif439	b:did_ftplugin = 1440 441This also needs to be used to avoid that the same plugin is executed twice for442the same buffer (happens when using an ":edit" command without arguments).443 444Now users can disable loading the default plugin completely by making a445filetype plugin with only these lines: >446 447	vim9script448	b:did_ftplugin = 1449 450This does require that the filetype plugin directory comes before $VIMRUNTIME451in 'runtimepath'!452 453If you do want to use the default plugin, but overrule one of the settings,454you can write the different setting in a script: >455 456	setlocal textwidth=70457 458Now write this in the "after" directory, so that it gets sourced after the459distributed "vim.vim" ftplugin |after-directory|.  For Unix this would be460"~/.vim/after/ftplugin/vim.vim".  Note that the default plugin will have set461"b:did_ftplugin", it is ignored here.462 463 464OPTIONS465 466To make sure the filetype plugin only affects the current buffer use the >467 468	setlocal469 470command to set options.  And only set options which are local to a buffer (see471the help for the option to check that).  When using `:setlocal` for global472options or options local to a window, the value will change for many buffers,473and that is not what a filetype plugin should do.474 475When an option has a value that is a list of flags or items, consider using476"+=" and "-=" to keep the existing value.  Be aware that the user may have477changed an option value already.  First resetting to the default value and478then changing it is often a good idea.  Example: >479 480	setlocal formatoptions& formatoptions+=ro481 482 483MAPPINGS484 485To make sure mappings will only work in the current buffer use the >486 487	map <buffer>488 489command.  This needs to be combined with the two-step mapping explained above.490An example of how to define functionality in a filetype plugin: >491 492	if !hasmapto('<Plug>JavaImport;')493	  map <buffer> <unique> <LocalLeader>i <Plug>JavaImport;494	endif495	noremap <buffer> <unique> <Plug>JavaImport; oimport ""<Left><Esc>496 497|hasmapto()| is used to check if the user has already defined a map to498<Plug>JavaImport;.  If not, then the filetype plugin defines the default499mapping.  This starts with |<LocalLeader>|, which allows the user to select500the key(s) they want filetype plugin mappings to start with.  The default is a501backslash.502"<unique>" is used to give an error message if the mapping already exists or503overlaps with an existing mapping.504|:noremap| is used to avoid that any other mappings that the user has defined505interferes.  You might want to use ":noremap <script>" to allow remapping506mappings defined in this script that start with <SID>.507 508The user must have a chance to disable the mappings in a filetype plugin,509without disabling everything.  Here is an example of how this is done for a510plugin for the mail filetype: >511 512	# Add mappings, unless the user didn't want this.513	if !exists("g:no_plugin_maps") && !exists("g:no_mail_maps")514	  # Quote text by inserting "> "515	  if !hasmapto('<Plug>MailQuote;')516	    vmap <buffer> <LocalLeader>q <Plug>MailQuote;517	    nmap <buffer> <LocalLeader>q <Plug>MailQuote;518	  endif519	  vnoremap <buffer> <Plug>MailQuote; :s/^/> /<CR>520	  nnoremap <buffer> <Plug>MailQuote; :.,$s/^/> /<CR>521	endif522 523Two global variables are used:524|g:no_plugin_maps|	disables mappings for all filetype plugins525|g:no_mail_maps|	disables mappings for the "mail" filetype526 527 528USER COMMANDS529 530To add a user command for a specific file type, so that it can only be used in531one buffer, use the "-buffer" argument to |:command|.  Example: >532 533	command -buffer  Make  make %:r.s534 535 536VARIABLES537 538A filetype plugin will be sourced for each buffer of the type it's for.  Local539script variables will be shared between all invocations.  Use local buffer540variables |b:var| if you want a variable specifically for one buffer.541 542 543FUNCTIONS544 545When defining a function, this only needs to be done once.  But the filetype546plugin will be sourced every time a file with this filetype will be opened.547This construct makes sure the function is only defined once: >548 549	if !exists("*Func")550	  def Func(arg)551	    ...552	  enddef553	endif554<555Don't forget to use "noclear" with the `vim9script` command to avoid that the556function is deleted when the script is sourced a second time.557 558 559UNDO						*undo_indent* *undo_ftplugin*560 561When the user does ":setfiletype xyz" the effect of the previous filetype562should be undone.  Set the b:undo_ftplugin variable to the commands that will563undo the settings in your filetype plugin.  Example: >564 565	b:undo_ftplugin = "setlocal fo< com< tw< commentstring<"566		\ .. "| unlet b:match_ignorecase b:match_words b:match_skip"567 568Using ":setlocal" with "<" after the option name resets the option to its569global value.  That is mostly the best way to reset the option value.570 571For undoing the effect of an indent script, the b:undo_indent variable should572be set accordingly.573 574Both these variables use legacy script syntax, not |Vim9| syntax.575 576 577FILE NAME578 579The filetype must be included in the file name |ftplugin-name|.  Use one of580these three forms:581 582	.../ftplugin/stuff.vim583	.../ftplugin/stuff_foo.vim584	.../ftplugin/stuff/bar.vim585 586"stuff" is the filetype, "foo" and "bar" are arbitrary names.587 588 589FILETYPE DETECTION					*plugin-filetype*590 591If your filetype is not already detected by Vim, you should create a filetype592detection snippet in a separate file.  It is usually in the form of an593autocommand that sets the filetype when the file name matches a pattern.594Example: >595 596	au BufNewFile,BufRead *.foo		setlocal filetype=foofoo597 598Write this single-line file as "ftdetect/foofoo.vim" in the first directory599that appears in 'runtimepath'.  For Unix that would be600"~/.vim/ftdetect/foofoo.vim".  The convention is to use the name of the601filetype for the script name.602 603You can make more complicated checks if you like, for example to inspect the604contents of the file to recognize the language.  Also see |new-filetype|.605 606 607SUMMARY							*ftplugin-special*608 609Summary of special things to use in a filetype plugin:610 611<LocalLeader>		Value of "maplocalleader", which the user defines as612			the keys that filetype plugin mappings start with.613 614map <buffer>		Define a mapping local to the buffer.615 616noremap <script>	Only remap mappings defined in this script that start617			with <SID>.618 619setlocal		Set an option for the current buffer only.620 621command -buffer		Define a user command local to the buffer.622 623exists("*s:Func")	Check if a function was already defined.624 625Also see |plugin-special|, the special things used for all plugins.626 627==============================================================================628*51.3*	Writing a compiler plugin		*write-compiler-plugin*629 630A compiler plugin sets options for use with a specific compiler.  The user can631load it with the |:compiler| command.  The main use is to set the632'errorformat' and 'makeprg' options.633 634Easiest is to have a look at examples.  This command will edit all the default635compiler plugins: >636 637	next $VIMRUNTIME/compiler/*.vim638 639Type `:next` to go to the next plugin file.640 641There are two special items about these files.  First is a mechanism to allow642a user to overrule or add to the default file.  The default files start with: >643 644	vim9script645	if exists("g:current_compiler")646	  finish647	endif648	g:current_compiler = "mine"649 650When you write a compiler file and put it in your personal runtime directory651(e.g., ~/.vim/compiler for Unix), you set the "current_compiler" variable to652make the default file skip the settings.653							*:CompilerSet*654The second mechanism is to use ":set" for ":compiler!" and ":setlocal" for655":compiler".  Vim defines the ":CompilerSet" user command for this.  This is656an example: >657 658  CompilerSet errorformat&		" use the default 'errorformat'659  CompilerSet makeprg=nmake660 661Note: arguments need to be escaped according to |option-backslash|.662 663When you write a compiler plugin for the Vim distribution or for a system-wide664runtime directory, use the mechanism mentioned above.  When665"current_compiler" was already set by a user plugin nothing will be done.666 667When you write a compiler plugin to overrule settings from a default plugin,668don't check "current_compiler".  This plugin is supposed to be loaded669last, thus it should be in a directory at the end of 'runtimepath'.  For Unix670that could be ~/.vim/after/compiler.671 672==============================================================================673*51.4*	Distributing Vim scripts			*distribute-script*674 675Vim users will look for scripts on the Vim website: http://www.vim.org.676If you made something that is useful for others, share it!677 678Another place is github.  But there you need to know where to find it!  The679advantage is that most plugin managers fetch plugins from github.  You'll have680to use your favorite search engine to find them.681 682Vim scripts can be used on any system.  However, there might not be a tar or683gzip command.  If you want to pack files together and/or compress them the684"zip" utility is recommended.685 686For utmost portability use Vim itself to pack scripts together.  This can be687done with the Vimball utility.  See |vimball|.688 689It's good if you add a line to allow automatic updating.  See |glvs-plugins|.690 691==============================================================================692 693Next chapter: |usr_52.txt|  Write large plugins694 695Copyright: see |manual-copyright|  vim:tw=78:ts=8:noet:ft=help:norl:696 
codekingpro/portable-devtools · Team Ai