robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

Justin M. Keyesrefactor(vimscript)!: drop ctxget(), ctxpush(), etc #40724eb94149a29

master
93.0 KiB2733 linesraw
1*usr_41.txt*	Nvim
2
3
4		     VIM USER MANUAL	by Bram Moolenaar
5
6
7			      Write a Vim script
8
9
10The Vim script language is used for the startup vimrc file, syntax files, and
11many other things.  This chapter explains the items that can be used in a Vim
12script.  There are a lot of them, thus this is a long chapter.
13
14|41.1|	Introduction
15|41.2|	Variables
16|41.3|	Expressions
17|41.4|	Conditionals
18|41.5|	Executing an expression
19|41.6|	Using functions
20|41.7|	Defining a function
21|41.8|	Lists and Dictionaries
22|41.9|	Exceptions
23|41.10|	Various remarks
24|41.11|	Writing a plugin
25|41.12|	Writing a filetype plugin
26|41.13|	Writing a compiler plugin
27|41.14|	Writing a plugin that loads quickly
28|41.15|	Writing library scripts
29|41.16|	Distributing Vim scripts
30
31     Next chapter: |usr_42.txt|  Add new menus
32 Previous chapter: |usr_40.txt|  Make new commands
33Table of contents: |usr_toc.txt|
34
35==============================================================================
36*41.1*	Introduction				*vimscript-intro*
37
38Your first experience with Vim scripts is the vimrc file.  Vim reads it when
39it starts up and executes the commands.  You can set options to values you
40prefer.  And you can use any colon command in it (commands that start with a
41":"; these are sometimes referred to as Ex commands or command-line commands).
42   Syntax files are also Vim scripts.  As are files that set options for a
43specific file type.  A complicated macro can be defined by a separate Vim
44script file.  You can think of other uses yourself.
45
46	If you are familiar with Python, you can find a comparison between
47	Python and Vim script here, with pointers to other documents:
48	   https://gist.github.com/yegappan/16d964a37ead0979b05e655aa036cad0
49	And if you are familiar with JavaScript:
50	   https://w0rp.com/blog/post/vim-script-for-the-javascripter/
51
52Let's start with a simple example: >
53
54	:let i = 1
55	:while i < 5
56	:  echo "count is" i
57	:  let i += 1
58	:endwhile
59<
60	Note:
61	The ":" characters are not really needed here.  You only need to use
62	them when you type a command.  In a Vim script file they can be left
63	out.  We will use them here anyway to make clear these are colon
64	commands and make them stand out from Normal mode commands.
65	Note:
66	You can try out the examples by yanking the lines from the text here
67	and executing them with :@"
68
69The output of the example code is:
70
71	count is 1 ~
72	count is 2 ~
73	count is 3 ~
74	count is 4 ~
75
76In the first line the ":let" command assigns a value to a variable.  The
77generic form is: >
78
79	:let {variable} = {expression}
80
81In this case the variable name is "i" and the expression is a simple value,
82the number one.
83   The ":while" command starts a loop.  The generic form is: >
84
85	:while {condition}
86	:  {statements}
87	:endwhile
88
89The statements until the matching ":endwhile" are executed for as long as the
90condition is true.  The condition used here is the expression "i < 5".  This
91is true when the variable i is smaller than five.
92	Note:
93	If you happen to write a while loop that keeps on running, you can
94	interrupt it by pressing CTRL-C (CTRL-Break on MS-Windows).
95
96The ":echo" command prints its arguments.  In this case the string "count is"
97and the value of the variable i.  Since i is one, this will print:
98
99	count is 1 ~
100
101Then there is the ":let i += 1" command.  This does the same thing as
102":let i = i + 1".  This adds one to the variable i and assigns the new value
103to the same variable.
104
105The example was given to explain the commands, but would you really want to
106make such a loop, it can be written much more compact: >
107
108	:for i in range(1, 4)
109	:  echo "count is" i
110	:endfor
111
112We won't explain how |:for| and |range()| work until later.  Follow the links
113if you are impatient.
114
115
116FOUR KINDS OF NUMBERS
117
118Numbers can be decimal, hexadecimal, octal or binary.
119
120A hexadecimal number starts with "0x" or "0X".  For example "0x1f" is decimal
12131.
122
123An octal number starts with "0o", "0O" or a zero and another digit.  "0o17" is
124decimal 15.
125
126A binary number starts with "0b" or "0B".  For example "0b101" is decimal 5.
127
128A decimal number is just digits.  Careful: don't put a zero before a decimal
129number, it will be interpreted as an octal number!
130
131The ":echo" command always prints decimal numbers.  Example: >
132
133	:echo 0x7f 0o36
134<	127 30 ~
135
136A number is made negative with a minus sign.  This also works for hexadecimal,
137octal and binary numbers.  A minus sign is also used for subtraction.  Compare
138this with the previous example: >
139
140	:echo 0x7f -0o36
141<	97 ~
142
143White space in an expression is ignored.  However, it's recommended to use it
144for separating items, to make the expression easier to read.  For example, to
145avoid the confusion with a negative number above, put a space between the
146minus sign and the following number: >
147
148	:echo 0x7f - 0o36
149
150==============================================================================
151*41.2*	Variables
152
153A variable name consists of ASCII letters, digits and the underscore.  It
154cannot start with a digit.  Valid variable names are:
155
156	counter
157	_aap3
158	very_long_variable_name_with_underscores
159	FuncLength
160	LENGTH
161
162Invalid names are "foo.bar" and "6var".
163   These variables are global.  To see a list of currently defined variables
164use this command: >
165
166	:let
167
168You can use global variables everywhere.  This also means that when the
169variable "count" is used in one script file, it might also be used in another
170file.  This leads to confusion at least, and real problems at worst.  To avoid
171this, you can use a variable local to a script file by prepending "s:".  For
172example, one script contains this code: >
173
174	:let s:count = 1
175	:while s:count < 5
176	:  source other.vim
177	:  let s:count += 1
178	:endwhile
179
180Since "s:count" is local to this script, you can be sure that sourcing the
181"other.vim" script will not change this variable.  If "other.vim" also uses an
182"s:count" variable, it will be a different copy, local to that script.  More
183about script-local variables here: |script-variable|.
184
185There are more kinds of variables, see |internal-variables|.  The most often
186used ones are:
187
188	b:name		variable local to a buffer
189	w:name		variable local to a window
190	g:name		global variable (also in a function)
191	v:name		variable predefined by Vim
192
193
194DELETING VARIABLES
195
196Variables take up memory and show up in the output of the ":let" command.  To
197delete a variable use the ":unlet" command.  Example: >
198
199	:unlet s:count
200
201This deletes the script-local variable "s:count" to free up the memory it
202uses.  If you are not sure if the variable exists, and don't want an error
203message when it doesn't, append !: >
204
205	:unlet! s:count
206
207When a script has been processed to the end, the local variables declared
208there will not be deleted.  Functions defined in the script can use them.
209Example:
210
211	:if !exists("s:call_count")
212	:  let s:call_count = 0
213	:endif
214	:let s:call_count = s:call_count + 1
215	:echo "called" s:call_count "times"
216
217The "exists()" function checks if a variable has already been defined.  Its
218argument is the name of the variable you want to check.  Not the variable
219itself!  If you would do this: >
220
221	:if !exists(s:call_count)
222
223Then the value of s:call_count will be used as the name of the variable that
224exists() checks.  That's not what you want.
225   The exclamation mark ! negates a value.  When the value was true, it
226becomes false.  When it was false, it becomes true.  You can read it as "not".
227Thus "if !exists()" can be read as "if not exists()".
228   What Vim calls true is anything that is not zero.  Zero is false.
229	Note:
230	Vim automatically converts a string to a number when it is looking for
231	a number.  When using a string that doesn't start with a digit the
232	resulting number is zero.  Thus look out for this: >
233		:if "true"
234<	The "true" will be interpreted as a zero, thus as false!
235
236
237STRING VARIABLES AND CONSTANTS
238
239So far only numbers were used for the variable value.  Strings can be used as
240well.  Numbers and strings are the basic types of variables that Vim supports.
241The type is dynamic, it is set each time when assigning a value to the
242variable with ":let".  More about types in |41.8|.
243   To assign a string value to a variable, you need to use a string constant.
244There are two types of these.  First the string in double quotes: >
245
246	:let name = "peter"
247	:echo name
248<	peter ~
249
250If you want to include a double quote inside the string, put a backslash in
251front of it: >
252
253	:let name = "\"peter\""
254	:echo name
255<	"peter" ~
256
257To avoid the need for a backslash, you can use a string in single quotes: >
258
259	:let name = '"peter"'
260	:echo name
261<	"peter" ~
262
263Inside a single-quote string all the characters are as they are.  Only the
264single quote itself is special: you need to use two to get one.  A backslash
265is taken literally, thus you can't use it to change the meaning of the
266character after it.
267   In double-quote strings it is possible to use special characters.  Here are
268a few useful ones:
269
270	\t		<Tab>
271	\n		<NL>, line break
272	\r		<CR>, <Enter>
273	\e		<Esc>
274	\b		<BS>, backspace
275	\"		"
276	\\		\, backslash
277	\<Esc>		<Esc>
278	\<C-W>		CTRL-W
279
280The last two are just examples.  The  "\<name>" form can be used to include
281the special key "name".
282   See |expr-quote| for the full list of special items in a string.
283
284==============================================================================
285*41.3*	Expressions
286
287Vim has a rich, yet simple way to handle expressions.  You can read the
288definition here: |expression-syntax|.  Here we will show the most common
289items.
290   The numbers, strings and variables mentioned above are expressions by
291themselves.  Thus everywhere an expression is expected, you can use a number,
292string or variable.  Other basic items in an expression are:
293
294	$NAME		environment variable
295	&name		option
296	@r		register
297
298Examples: >
299
300	:echo "The value of 'tabstop' is" &ts
301	:echo "Your home directory is" $HOME
302	:if @a > 5
303
304The &name form can be used to save an option value, set it to a new value,
305do something and restore the old value.  Example: >
306
307	:let save_ic = &ic
308	:set noic
309	:/The Start/,$delete
310	:let &ic = save_ic
311
312This makes sure the "The Start" pattern is used with the 'ignorecase' option
313off.  Still, it keeps the value that the user had set.  (Another way to do
314this would be to add "\C" to the pattern, see |/\C|.)
315
316
317MATHEMATICS
318
319It becomes more interesting if we combine these basic items.  Let's start with
320mathematics on numbers:
321
322	a + b		add
323	a - b		subtract
324	a * b		multiply
325	a / b		divide
326	a % b		modulo
327
328The usual precedence is used.  Example: >
329
330	:echo 10 + 5 * 2
331<	20 ~
332
333Grouping is done with parentheses.  No surprises here.  Example: >
334
335	:echo (10 + 5) * 2
336<	30 ~
337
338Strings can be concatenated with ".." (see |expr6|).  Example: >
339
340	:echo "foo" .. "bar"
341<	foobar ~
342
343When the ":echo" command gets multiple arguments, it separates them with a
344space.  In the example the argument is a single expression, thus no space is
345inserted.
346
347Borrowed from the C language is the conditional expression:
348
349	a ? b : c
350
351If "a" evaluates to true "b" is used, otherwise "c" is used.  Example: >
352
353	:let i = 4
354	:echo i > 5 ? "i is big" : "i is small"
355<	i is small ~
356
357The three parts of the constructs are always evaluated first, thus you could
358see it work as:
359
360	(a) ? (b) : (c)
361
362==============================================================================
363*41.4*	Conditionals
364
365The ":if" commands executes the following statements, until the matching
366":endif", only when a condition is met.  The generic form is:
367
368	:if {condition}
369	   {statements}
370	:endif
371
372Only when the expression {condition} evaluates to true (non-zero) will the
373{statements} be executed.  These must still be valid commands.  If they
374contain garbage, Vim won't be able to find the ":endif".
375   You can also use ":else".  The generic form for this is:
376
377	:if {condition}
378	   {statements}
379	:else
380	   {statements}
381	:endif
382
383The second {statements} is only executed if the first one isn't.
384   Finally, there is ":elseif":
385
386	:if {condition}
387	   {statements}
388	:elseif {condition}
389	   {statements}
390	:endif
391
392This works just like using ":else" and then "if", but without the need for an
393extra ":endif".
394   A useful example for your vimrc file is checking the 'term' option and
395doing something depending upon its value: >
396
397	:if &term == "xterm"
398	:  " Do stuff for xterm
399	:elseif &term == "vt100"
400	:  " Do stuff for a vt100 terminal
401	:else
402	:  " Do something for other terminals
403	:endif
404
405
406LOGIC OPERATIONS
407
408We already used some of them in the examples.  These are the most often used
409ones:
410
411	a == b		equal to
412	a != b		not equal to
413	a >  b		greater than
414	a >= b		greater than or equal to
415	a <  b		less than
416	a <= b		less than or equal to
417
418The result is one if the condition is met and zero otherwise.  An example: >
419
420	:if v:version >= 700
421	:  echo "congratulations"
422	:else
423	:  echo "you are using an old version, upgrade!"
424	:endif
425
426Here "v:version" is a variable defined by Vim, which has the value of the Vim
427version.  600 is for version 6.0.  Version 6.1 has the value 601.  This is
428very useful to write a script that works with multiple versions of Vim.
429|v:version|
430
431The logic operators work both for numbers and strings.  When comparing two
432strings, the mathematical difference is used.  This compares byte values,
433which may not be right for some languages.
434   When comparing a string with a number, the string is first converted to a
435number.  This is a bit tricky, because when a string doesn't look like a
436number, the number zero is used.  Example: >
437
438	:if 0 == "one"
439	:  echo "yes"
440	:endif
441
442This will echo "yes", because "one" doesn't look like a number, thus it is
443converted to the number zero.
444
445For strings there are two more items:
446
447	a =~ b		matches with
448	a !~ b		does not match with
449
450The left item "a" is used as a string.  The right item "b" is used as a
451pattern, like what's used for searching.  Example: >
452
453	:if str =~ " "
454	:  echo "str contains a space"
455	:endif
456	:if str !~ '\.$'
457	:  echo "str does not end in a full stop"
458	:endif
459
460Notice the use of a single-quote string for the pattern.  This is useful,
461because backslashes would need to be doubled in a double-quote string and
462patterns tend to contain many backslashes.
463
464The 'ignorecase' option is used when comparing strings.  When you don't want
465that, append "#" to match case and "?" to ignore case.  Thus "==?" compares
466two strings to be equal while ignoring case.  And "!~#" checks if a pattern
467doesn't match, also checking the case of letters.  For the full table see
468|expr-==|.
469
470
471MORE LOOPING
472
473The ":while" command was already mentioned.  Two more statements can be used
474in between the ":while" and the ":endwhile":
475
476	:continue		Jump back to the start of the while loop; the
477				loop continues.
478	:break			Jump forward to the ":endwhile"; the loop is
479				discontinued.
480
481Example: >
482
483	:while counter < 40
484	:  call do_something()
485	:  if skip_flag
486	:    continue
487	:  endif
488	:  if finished_flag
489	:    break
490	:  endif
491	:  sleep 50m
492	:endwhile
493
494The ":sleep" command makes Vim take a nap.  The "50m" specifies fifty
495milliseconds.  Another example is ":sleep 4", which sleeps for four seconds.
496
497Even more looping can be done with the ":for" command, see below in |41.8|.
498
499==============================================================================
500*41.5*	Executing an expression
501
502So far the commands in the script were executed by Vim directly.  The
503":execute" command allows executing the result of an expression.  This is a
504very powerful way to build commands and execute them.
505   An example is to jump to a tag, which is contained in a variable: >
506
507	:execute "tag " .. tag_name
508
509The ".." is used to concatenate the string "tag " with the value of variable
510"tag_name".  Suppose "tag_name" has the value "get_cmd", then the command that
511will be executed is: >
512
513	:tag get_cmd
514
515The ":execute" command can only execute colon commands.  The ":normal" command
516executes Normal mode commands.  However, its argument is not an expression but
517the literal command characters.  Example: >
518
519	:normal gg=G
520
521This jumps to the first line and formats all lines with the "=" operator.
522   To make ":normal" work with an expression, combine ":execute" with it.
523Example: >
524
525	:execute "normal " .. normal_commands
526
527The variable "normal_commands" must contain the Normal mode commands.
528   Make sure that the argument for ":normal" is a complete command.  Otherwise
529Vim will run into the end of the argument and abort the command.  For example,
530if you start Insert mode, you must leave Insert mode as well.  This works: >
531
532	:execute "normal Inew text \<Esc>"
533
534This inserts "new text " in the current line.  Notice the use of the special
535key "\<Esc>".  This avoids having to enter a real <Esc> character in your
536script.
537
538If you don't want to execute a string but evaluate it to get its expression
539value, you can use the eval() function: >
540
541	:let optname = "path"
542	:let optval = eval('&' .. optname)
543
544A "&" character is prepended to "path", thus the argument to eval() is
545"&path".  The result will then be the value of the 'path' option.
546   The same thing can be done with: >
547	:exe 'let optval = &' .. optname
548
549==============================================================================
550*41.6*	Using functions
551
552Vim defines many functions and provides a large amount of functionality that
553way.  A few examples will be given in this section.  You can find the whole
554list below: |function-list|.
555
556A function is called with the ":call" command.  The parameters are passed in
557between parentheses separated by commas.  Example: >
558
559	:call search("Date: ", "W")
560
561This calls the search() function, with arguments "Date: " and "W".  The
562search() function uses its first argument as a search pattern and the second
563one as flags.  The "W" flag means the search doesn't wrap around the end of
564the file.
565
566A function can be called in an expression.  Example: >
567
568	:let line = getline(".")
569	:let repl = substitute(line, '\a', "*", "g")
570	:call setline(".", repl)
571
572The getline() function obtains a line from the current buffer.  Its argument
573is a specification of the line number.  In this case "." is used, which means
574the line where the cursor is.
575   The substitute() function does something similar to the ":substitute"
576command.  The first argument is the string on which to perform the
577substitution.  The second argument is the pattern, the third the replacement
578string.  Finally, the last arguments are the flags.
579   The setline() function sets the line, specified by the first argument, to a
580new string, the second argument.  In this example the line under the cursor is
581replaced with the result of the substitute().  Thus the effect of the three
582statements is equal to: >
583
584	:substitute/\a/*/g
585
586Using the functions becomes interesting when you do more work before and
587after the substitute() call.
588
589
590FUNCTIONS						*function-list*
591
592There are many functions.  We will mention them here, grouped by what they are
593used for.  You can find an alphabetical list here: |vimscript-functions|.
594Use CTRL-] on the function name to jump to detailed help on it.
595
596String manipulation:					*string-functions*
597	nr2char()		get a character by its number value
598	list2str()		get a character string from a list of numbers
599	char2nr()		get number value of a character
600	str2list()		get list of numbers from a string
601	str2nr()		convert a string to a Number
602	str2float()		convert a string to a Float
603	printf()		format a string according to "%" items
604	escape()		escape characters in a string with a '\'
605	shellescape()		escape a string for use with a shell command
606	fnameescape()		escape a file name for use with a Vim command
607	tr()			translate characters from one set to another
608	strtrans()		translate a string to make it printable
609	keytrans()		translate internal keycodes to a form that
610				can be used by |:map|
611	tolower()		turn a string to lowercase
612	toupper()		turn a string to uppercase
613	charclass()		class of a character
614	match()			position where a pattern matches in a string
615	matchbufline()		all the matches of a pattern in a buffer
616	matchend()		position where a pattern match ends in a
617				string
618	matchfuzzy()		fuzzy matches a string in a list of strings
619	matchfuzzypos()		fuzzy matches a string in a list of strings
620	matchstr()		match of a pattern in a string
621	matchstrlist()		all the matches of a pattern in a List of
622				strings
623	matchstrpos()		match and positions of a pattern in a string
624	matchlist()		like matchstr() and also return submatches
625	stridx()		first index of a short string in a long string
626	strridx()		last index of a short string in a long string
627	strlen()		length of a string in bytes
628	strcharlen()		length of a string in characters
629	strchars()		number of characters in a string
630	strutf16len()		number of UTF-16 code units in a string
631	strwidth()		size of string when displayed
632	strdisplaywidth()	size of string when displayed, deals with tabs
633	setcellwidths()		set character cell width overrides
634	getcellwidths()		get character cell width overrides
635	reverse()		reverse the order of characters in a string
636	substitute()		substitute a pattern match with a string
637	submatch()		get a specific match in ":s" and substitute()
638	strpart()		get part of a string using byte index
639	strcharpart()		get part of a string using char index
640	slice()			take a slice of a string, using char index in
641				Vim9 script
642	strgetchar()		get character from a string using char index
643	expand()		expand special keywords
644	expandcmd()		expand a command like done for `:edit`
645	iconv()			convert text from one encoding to another
646	byteidx()		byte index of a character in a string
647	byteidxcomp()		like byteidx() but count composing characters
648	charidx()		character index of a byte in a string
649	utf16idx()		UTF-16 index of a byte in a string
650	repeat()		repeat a string multiple times
651	eval()			evaluate a string expression
652	execute()		execute an Ex command and get the output
653	win_execute()		like execute() but in a specified window
654	trim()			trim characters from a string
655	gettext()		lookup message translation
656	items()			get List of String index-character pairs
657
658List manipulation:					*list-functions*
659	get()			get an item without error for wrong index
660	len()			number of items in a List
661	empty()			check if List is empty
662	insert()		insert an item somewhere in a List
663	add()			append an item to a List
664	extend()		append a List to a List
665	extendnew()		make a new List and append items
666	remove()		remove one or more items from a List
667	copy()			make a shallow copy of a List
668	deepcopy()		make a full copy of a List
669	filter()		remove selected items from a List
670	map()			change each List item
671	mapnew()		make a new List with changed items
672	foreach()		apply function to List items
673	reduce()		reduce a List to a value
674	slice()			take a slice of a List
675	sort()			sort a List
676	reverse()		reverse the order of items in a List
677	uniq()			remove copies of repeated adjacent items
678	split()			split a String into a List
679	join()			join List items into a String
680	range()			return a List with a sequence of numbers
681	string()		String representation of a List
682	call()			call a function with List as arguments
683	index()			index of a value in a List
684	indexof()		index in a List where an expression is true
685	max()			maximum value in a List
686	min()			minimum value in a List
687	count()			count number of times a value appears in a
688				List
689	repeat()		repeat a List multiple times
690	flatten()		flatten a List
691	flattennew()		flatten a copy of a List
692	items()			get List of List index-value pairs
693
694Dictionary manipulation:				*dict-functions*
695	get()			get an entry without an error for a wrong key
696	len()			number of entries in a Dictionary
697	has_key()		check whether a key appears in a Dictionary
698	empty()			check if Dictionary is empty
699	remove()		remove an entry from a Dictionary
700	extend()		add entries from one Dictionary to another
701	extendnew()		make a new Dictionary and append items
702	filter()		remove selected entries from a Dictionary
703	map()			change each Dictionary entry
704	mapnew()		make a new Dictionary with changed items
705	foreach()		apply function to Dictionary items
706	keys()			get List of Dictionary keys
707	values()		get List of Dictionary values
708	items()			get List of Dictionary key-value pairs
709	copy()			make a shallow copy of a Dictionary
710	deepcopy()		make a full copy of a Dictionary
711	string()		String representation of a Dictionary
712	max()			maximum value in a Dictionary
713	min()			minimum value in a Dictionary
714	count()			count number of times a value appears
715
716Floating point computation:				*float-functions*
717	float2nr()		convert Float to Number
718	abs()			absolute value (also works for Number)
719	round()			round off
720	ceil()			round up
721	floor()			round down
722	trunc()			remove value after decimal point
723	fmod()			remainder of division
724	exp()			exponential
725	log()			natural logarithm (logarithm to base e)
726	log10()			logarithm to base 10
727	pow()			value of x to the exponent y
728	sqrt()			square root
729	sin()			sine
730	cos()			cosine
731	tan()			tangent
732	asin()			arc sine
733	acos()			arc cosine
734	atan()			arc tangent
735	atan2()			arc tangent
736	sinh()			hyperbolic sine
737	cosh()			hyperbolic cosine
738	tanh()			hyperbolic tangent
739	isinf()			check for infinity
740	isnan()			check for not a number
741
742Blob manipulation:					*blob-functions*
743	blob2list()		get a list of numbers from a blob
744	list2blob()		get a blob from a list of numbers
745	reverse()		reverse the order of numbers in a blob
746	index()			index of a value in a Blob
747	indexof()		index in a Blob where an expression is true
748	items()			get List of Blob index-value pairs
749
750Other computation:					*bitwise-function*
751	and()			bitwise AND
752	invert()		bitwise invert
753	or()			bitwise OR
754	xor()			bitwise XOR
755	sha256()		SHA-256 hash
756	rand()			get a pseudo-random number
757	srand()			initialize seed used by rand()
758
759Variables:						*var-functions*
760	type()			type of a variable
761	islocked()		check if a variable is locked
762	funcref()		get a Funcref for a function reference
763	function()		get a Funcref for a function name
764	getbufvar()		get a variable value from a specific buffer
765	setbufvar()		set a variable in a specific buffer
766	getwinvar()		get a variable from specific window
767	gettabvar()		get a variable from specific tab page
768	gettabwinvar()		get a variable from specific window & tab page
769	setwinvar()		set a variable in a specific window
770	settabvar()		set a variable in a specific tab page
771	settabwinvar()		set a variable in a specific window & tab page
772	garbagecollect()	possibly free memory
773
774Cursor and mark position:		*cursor-functions* *mark-functions*
775	col()			column number of the cursor or a mark
776	virtcol()		screen column of the cursor or a mark
777	line()			line number of the cursor or mark
778	wincol()		window column number of the cursor
779	winline()		window line number of the cursor
780	cursor()		position the cursor at a line/column
781	screencol()		get screen column of the cursor
782	screenrow()		get screen row of the cursor
783	screenpos()		screen row and col of a text character
784	virtcol2col()		byte index of a text character on screen
785	getcurpos()		get position of the cursor
786	getpos()		get position of cursor, mark, etc.
787	setpos()		set position of cursor, mark, etc.
788	getmarklist()		list of global/local marks
789	byte2line()		get line number at a specific byte count
790	line2byte()		byte count at a specific line
791	diff_filler()		get the number of filler lines above a line
792	screenattr()		get attribute at a screen line/row
793	screenchar()		get character code at a screen line/row
794	screenchars()		get character codes at a screen line/row
795	screenstring()		get string of characters at a screen line/row
796	charcol()		character number of the cursor or a mark
797	getcharpos()		get character position of cursor, mark, etc.
798	setcharpos()		set character position of cursor, mark, etc.
799	getcursorcharpos()	get character position of the cursor
800	setcursorcharpos()	set character position of the cursor
801
802Working with text in the current buffer:		*text-functions*
803	getline()		get a line or list of lines from the buffer
804	getregion()		get a region of text from the buffer
805	getregionpos()		get a list of positions for a region
806	setline()		replace a line in the buffer
807	append()		append line or list of lines in the buffer
808	indent()		indent of a specific line
809	cindent()		indent according to C indenting
810	lispindent()		indent according to Lisp indenting
811	nextnonblank()		find next non-blank line
812	prevnonblank()		find previous non-blank line
813	search()		find a match for a pattern
814	searchpos()		find a match for a pattern
815	searchcount()		get number of matches before/after the cursor
816	searchpair()		find the other end of a start/skip/end
817	searchpairpos()		find the other end of a start/skip/end
818	searchdecl()		search for the declaration of a name
819	getcharsearch()		return character search information
820	setcharsearch()		set character search information
821
822Working with text in another buffer:
823	getbufline()		get a list of lines from the specified buffer
824	getbufoneline()		get a one line from the specified buffer
825	setbufline()		replace a line in the specified buffer
826	appendbufline()		append a list of lines in the specified buffer
827	deletebufline()		delete lines from a specified buffer
828
829					*system-functions* *file-functions*
830System functions and manipulation of files:
831	glob()			expand wildcards
832	globpath()		expand wildcards in a number of directories
833	glob2regpat()		convert a glob pattern into a search pattern
834	findfile()		find a file in a list of directories
835	finddir()		find a directory in a list of directories
836	resolve()		find out where a shortcut points to
837	fnamemodify()		modify a file name
838	pathshorten()		shorten directory names in a path
839	simplify()		simplify a path without changing its meaning
840	executable()		check if an executable program exists
841	exepath()		full path of an executable program
842	filereadable()		check if a file can be read
843	filewritable()		check if a file can be written to
844	getfperm()		get the permissions of a file
845	setfperm()		set the permissions of a file
846	getftype()		get the kind of a file
847	isabsolutepath()	check if a path is absolute
848	isdirectory()		check if a directory exists
849	getfsize()		get the size of a file
850	getcwd()		get the current working directory
851	haslocaldir()		check if current window used |:lcd| or |:tcd|
852	tempname()		get the name of a temporary file
853	mkdir()			create a new directory
854	chdir()			change current working directory
855	delete()		delete a file
856	rename()		rename a file
857	system()		get the result of a shell command as a string
858	systemlist()		get the result of a shell command as a list
859	environ()		get all environment variables
860	getenv()		get one environment variable
861	setenv()		set an environment variable
862	hostname()		name of the system
863	readfile()		read a file into a List of lines
864	readblob()		read a file into a Blob
865	readdir()		get a List of file names in a directory
866	writefile()		write a List of lines or Blob into a file
867	filecopy()		copy a file {from} to {to}
868
869Date and Time:				*date-functions* *time-functions*
870	getftime()		get last modification time of a file
871	localtime()		get current time in seconds
872	strftime()		convert time to a string
873	strptime()		convert a date/time string to time
874	reltime()		get the current or elapsed time accurately
875	reltimestr()		convert reltime() result to a string
876	reltimefloat()		convert reltime() result to a Float
877
878			*buffer-functions* *window-functions* *arg-functions*
879Buffers, windows and the argument list:
880	argc()			number of entries in the argument list
881	argidx()		current position in the argument list
882	arglistid()		get id of the argument list
883	argv()			get one entry from the argument list
884	bufadd()		add a file to the list of buffers
885	bufexists()		check if a buffer exists
886	buflisted()		check if a buffer exists and is listed
887	bufload()		ensure a buffer is loaded
888	bufloaded()		check if a buffer exists and is loaded
889	bufname()		get the name of a specific buffer
890	bufnr()			get the buffer number of a specific buffer
891	tabpagebuflist()	return List of buffers in a tab page
892	tabpagenr()		get the number of a tab page
893	tabpagewinnr()		like winnr() for a specified tab page
894	winnr()			get the window number for the current window
895	bufwinid()		get the window ID of a specific buffer
896	bufwinnr()		get the window number of a specific buffer
897	winbufnr()		get the buffer number of a specific window
898	win_findbuf()		find windows containing a buffer
899	win_getid()		get window ID of a window
900	win_gettype()		get type of window
901	win_gotoid()		go to window with ID
902	win_id2tabwin()		get tab and window nr from window ID
903	win_id2win()		get window nr from window ID
904	win_move_separator()	move window vertical separator
905	win_move_statusline()	move window status line
906	win_splitmove()		move window to a split of another window
907	getbufinfo()		get a list with buffer information
908	gettabinfo()		get a list with tab page information
909	getwininfo()		get a list with window information
910	getchangelist()		get a list of change list entries
911	getjumplist()		get a list of jump list entries
912	swapfilelist()		list of existing swap files in 'directory'
913	swapinfo()		information about a swap file
914	swapname()		get the swap file path of a buffer
915
916Command line:					*command-line-functions*
917	getcmdcomplpat()	get completion pattern of the current command
918				line
919	getcmdcompltype()	get the type of the current command line
920				completion
921	getcmdline()		get the current command line input
922	getcmdprompt()		get the current command line prompt
923	getcmdpos()		get position of the cursor in the command line
924	getcmdscreenpos()	get screen position of the cursor in the
925				command line
926	setcmdline()		set the current command line
927	setcmdpos()		set position of the cursor in the command line
928	getcmdtype()		return the current command-line type
929	getcmdwintype()		return the current command-line window type
930	getcompletion()		list of command-line completion matches
931	getcompletiontype()	get the type of the command-line completion
932				for specified string
933	fullcommand()		get full command name
934	cmdcomplete_info()	get command-line completion information
935
936Quickfix and location lists:			*quickfix-functions*
937	getqflist()		list of quickfix errors
938	setqflist()		modify a quickfix list
939	getloclist()		list of location list items
940	setloclist()		modify a location list
941
942Insert mode completion:				*completion-functions*
943	complete()		set found matches
944	complete_add()		add to found matches
945	complete_check()	check if completion should be aborted
946	complete_info()		get current completion information
947	preinserted()		check if text is inserted after cursor
948	pumvisible()		check if the popup menu is displayed
949	pum_getpos()		position and size of popup menu if visible
950
951Folding:					*folding-functions*
952	foldclosed()		check for a closed fold at a specific line
953	foldclosedend()		like foldclosed() but return the last line
954	foldlevel()		check for the fold level at a specific line
955	foldtext()		generate the line displayed for a closed fold
956	foldtextresult()	get the text displayed for a closed fold
957
958Syntax and highlighting:	  *syntax-functions* *highlighting-functions*
959	clearmatches()		clear all matches defined by |matchadd()| and
960				the |:match| commands
961	getmatches()		get all matches defined by |matchadd()| and
962				the |:match| commands
963	hlexists()		check if a highlight group exists
964	hlID()			get ID of a highlight group
965	synID()			get syntax ID at a specific position
966	synIDattr()		get a specific attribute of a syntax ID
967	synIDtrans()		get translated syntax ID
968	synstack()		get list of syntax IDs at a specific position
969	synconcealed()		get info about (syntax) concealing
970	diff_hlID()		get highlight ID for diff mode at a position
971	matchadd()		define a pattern to highlight (a "match")
972	matchaddpos()		define a list of positions to highlight
973	matcharg()		get info about |:match| arguments
974	matchdelete()		delete a match defined by |matchadd()| or a
975				|:match| command
976	setmatches()		restore a list of matches saved by
977				|getmatches()|
978
979Spelling:					*spell-functions*
980	spellbadword()		locate badly spelled word at or after cursor
981	spellsuggest()		return suggested spelling corrections
982	soundfold()		return the sound-a-like equivalent of a word
983
984History:					*history-functions*
985	histadd()		add an item to a history
986	histdel()		delete an item from a history
987	histget()		get an item from a history
988	histnr()		get highest index of a history list
989
990Interactive:					*interactive-functions*
991	browse()		put up a file requester
992	browsedir()		put up a directory requester
993	confirm()		let the user make a choice
994	getchar()		get a character from the user
995	getcharstr()		get a character from the user as a string
996	getcharmod()		get modifiers for the last typed character
997	getmousepos()		get last known mouse position
998	feedkeys()		put characters in the typeahead queue
999	input()			get a line from the user
1000	inputlist()		let the user pick an entry from a list
1001	inputsecret()		get a line from the user without showing it
1002	inputdialog()		get a line from the user in a dialog
1003	inputsave()		save and clear typeahead
1004	inputrestore()		restore typeahead
1005
1006GUI:						*gui-functions*
1007	getfontname()		get name of current font being used
1008	getwinpos()		position of the Vim window
1009	getwinposx()		X position of the Vim window
1010	getwinposy()		Y position of the Vim window
1011	balloon_show()		set the balloon content
1012	balloon_split()		split a message for a balloon
1013	balloon_gettext()	get the text in the balloon
1014
1015Vim server:					*server-functions*
1016	serverlist()		return the list of server names
1017	remote_startserver()	run a server
1018	remote_send()		send command characters to a Vim server
1019	remote_expr()		evaluate an expression in a Vim server
1020	server2client()		send a reply to a client of a Vim server
1021	remote_peek()		check if there is a reply from a Vim server
1022	remote_read()		read a reply from a Vim server
1023	foreground()		move the Vim window to the foreground
1024	remote_foreground()	move the Vim server window to the foreground
1025
1026Window size and position:			*window-size-functions*
1027	winheight()		get height of a specific window
1028	winwidth()		get width of a specific window
1029	win_screenpos()		get screen position of a window
1030	winlayout()		get layout of windows in a tab page
1031	winrestcmd()		return command to restore window sizes
1032	winsaveview()		get view of current window
1033	winrestview()		restore saved view of current window
1034
1035Mappings and Menus:			    *mapping-functions*
1036	digraph_get()		get |digraph|
1037	digraph_getlist()	get all |digraph|s
1038	digraph_set()		register |digraph|
1039	digraph_setlist()	register multiple |digraph|s
1040	hasmapto()		check if a mapping exists
1041	mapcheck()		check if a matching mapping exists
1042	maparg()		get rhs of a mapping
1043	maplist()		get list of all mappings
1044	mapset()		restore a mapping
1045	menu_info()		get information about a menu item
1046	wildmenumode()		check if the wildmode is active
1047	wildtrigger()		start wildcard expansion
1048
1049Signs:						*sign-functions*
1050	sign_define()		define or update a sign
1051	sign_getdefined()	get a list of defined signs
1052	sign_getplaced()	get a list of placed signs
1053	sign_jump()		jump to a sign
1054	sign_place()		place a sign
1055	sign_placelist()	place a list of signs
1056	sign_undefine()		undefine a sign
1057	sign_unplace()		unplace a sign
1058	sign_unplacelist()	unplace a list of signs
1059
1060Testing:				    *test-functions*
1061	assert_equal()		assert that two expressions values are equal
1062	assert_equalfile()	assert that two file contents are equal
1063	assert_notequal()	assert that two expressions values are not
1064				equal
1065	assert_inrange()	assert that an expression is inside a range
1066	assert_match()		assert that a pattern matches the value
1067	assert_notmatch()	assert that a pattern does not match the value
1068	assert_false()		assert that an expression is false
1069	assert_true()		assert that an expression is true
1070	assert_exception()	assert that a command throws an exception
1071	assert_beeps()		assert that a command beeps
1072	assert_nobeep()		assert that a command does not cause a beep
1073	assert_fails()		assert that a command fails
1074	assert_report()		report a test failure
1075
1076Timers:						*timer-functions*
1077	timer_start()		create a timer
1078	timer_pause()		pause or unpause a timer
1079	timer_stop()		stop a timer
1080	timer_stopall()		stop all timers
1081	timer_info()		get information about timers
1082	wait()			wait for a condition
1083
1084Tags:						*tag-functions*
1085	taglist()		get list of matching tags
1086	tagfiles()		get a list of tags files
1087	gettagstack()		get the tag stack of a window
1088	settagstack()		modify the tag stack of a window
1089
1090Prompt Buffer:					*promptbuffer-functions*
1091	prompt_getprompt()	get the effective prompt text for a buffer
1092	prompt_setcallback()	set prompt callback for a buffer
1093	prompt_setinterrupt()	set interrupt callback for a buffer
1094	prompt_setprompt()	set the prompt text for a buffer
1095
1096Registers:					*register-functions*
1097	getreg()		get contents of a register
1098	getreginfo()		get information about a register
1099	getregtype()		get type of a register
1100	setreg()		set contents and type of a register
1101	reg_executing()		return the name of the register being executed
1102	reg_recording()		return the name of the register being recorded
1103
1104Various:					*various-functions*
1105	mode()			get current editing mode
1106	visualmode()		last visual mode used
1107	exists()		check if a variable, function, etc. exists
1108	has()			check if a feature is supported in Vim
1109	changenr()		return number of most recent change
1110	did_filetype()		check if a FileType autocommand was used
1111	eventhandler()		check if invoked by an event handler
1112	getpid()		get process ID of Vim
1113	getscriptinfo()		get list of sourced Vim scripts
1114	getstacktrace()		get current stack trace of Vim scripts
1115
1116	libcall()		call a function in an external library
1117	libcallnr()		idem, returning a number
1118
1119	undofile()		get the name of the undo file
1120	undotree()		return the state of the undo tree for a buffer
1121
1122	shiftwidth()		effective value of 'shiftwidth'
1123
1124	wordcount()		get byte/word/char count of buffer
1125
1126	luaeval()		evaluate |Lua| expression
1127	py3eval()		evaluate |Python| expression
1128	pyeval()		evaluate |Python| expression
1129	pyxeval()		evaluate |python_x| expression
1130	rubyeval()		evaluate |Ruby| expression
1131
1132	debugbreak()		interrupt a program being debugged
1133
1134==============================================================================
1135*41.7*	Defining a function
1136
1137Vim enables you to define your own functions.  The basic function declaration
1138begins as follows: >
1139
1140	:function {name}({var1}, {var2}, ...)
1141	:  {body}
1142	:endfunction
1143<
1144	Note:
1145	Function names must begin with a capital letter.
1146
1147Let's define a short function to return the smaller of two numbers.  It starts
1148with this line: >
1149
1150	:function Min(num1, num2)
1151
1152This tells Vim that the function is named "Min" and it takes two arguments:
1153"num1" and "num2".
1154   The first thing you need to do is to check to see which number is smaller:
1155   >
1156	:  if a:num1 < a:num2
1157
1158The special prefix "a:" tells Vim that the variable is a function argument.
1159Let's assign the variable "smaller" the value of the smallest number: >
1160
1161	:  if a:num1 < a:num2
1162	:    let smaller = a:num1
1163	:  else
1164	:    let smaller = a:num2
1165	:  endif
1166
1167The variable "smaller" is a local variable.  Variables used inside a function
1168are local unless prefixed by something like "g:", "a:", or "s:".
1169
1170	Note:
1171	To access a global variable from inside a function you must prepend
1172	"g:" to it.  Thus "g:today" inside a function is used for the global
1173	variable "today", and "today" is another variable, local to the
1174	function.
1175
1176You now use the ":return" statement to return the smallest number to the user.
1177Finally, you end the function: >
1178
1179	:  return smaller
1180	:endfunction
1181
1182The complete function definition is as follows: >
1183
1184	:function Min(num1, num2)
1185	:  if a:num1 < a:num2
1186	:    let smaller = a:num1
1187	:  else
1188	:    let smaller = a:num2
1189	:  endif
1190	:  return smaller
1191	:endfunction
1192
1193For people who like short functions, this does the same thing: >
1194
1195	:function Min(num1, num2)
1196	:  if a:num1 < a:num2
1197	:    return a:num1
1198	:  endif
1199	:  return a:num2
1200	:endfunction
1201
1202A user defined function is called in exactly the same way as a built-in
1203function.  Only the name is different.  The Min function can be used like
1204this: >
1205
1206	:echo Min(5, 8)
1207
1208Only now will the function be executed and the lines be interpreted by Vim.
1209If there are mistakes, like using an undefined variable or function, you will
1210now get an error message.  When defining the function these errors are not
1211detected.
1212
1213When a function reaches ":endfunction" or ":return" is used without an
1214argument, the function returns zero.
1215
1216To redefine a function that already exists, use the ! for the ":function"
1217command: >
1218
1219	:function!  Min(num1, num2, num3)
1220
1221
1222USING A RANGE
1223
1224The ":call" command can be given a line range.  This can have one of two
1225meanings.  When a function has been defined with the "range" keyword, it will
1226take care of the line range itself.
1227  The function will be passed the variables "a:firstline" and "a:lastline".
1228These will have the line numbers from the range the function was called with.
1229Example: >
1230
1231	:function Count_words() range
1232	:  let lnum = a:firstline
1233	:  let n = 0
1234	:  while lnum <= a:lastline
1235	:    let n = n + len(split(getline(lnum)))
1236	:    let lnum = lnum + 1
1237	:  endwhile
1238	:  echo "found " .. n .. " words"
1239	:endfunction
1240
1241You can call this function with: >
1242
1243	:10,30call Count_words()
1244
1245It will be executed once and echo the number of words.
1246   The other way to use a line range is by defining a function without the
1247"range" keyword.  The function will be called once for every line in the
1248range, with the cursor in that line.  Example: >
1249
1250	:function  Number()
1251	:  echo "line " .. line(".") .. " contains: " .. getline(".")
1252	:endfunction
1253
1254If you call this function with: >
1255
1256	:10,15call Number()
1257
1258The function will be called six times.
1259
1260
1261VARIABLE NUMBER OF ARGUMENTS
1262
1263Vim enables you to define functions that have a variable number of arguments.
1264The following command, for instance, defines a function that must have 1
1265argument (start) and can have up to 20 additional arguments: >
1266
1267	:function Show(start, ...)
1268
1269The variable "a:1" contains the first optional argument, "a:2" the second, and
1270so on.  The variable "a:0" contains the number of extra arguments.
1271   For example: >
1272
1273	:function Show(start, ...)
1274	:  echohl Title
1275	:  echo "start is " .. a:start
1276	:  echohl None
1277	:  let index = 1
1278	:  while index <= a:0
1279	:    echo "  Arg " .. index .. " is " .. a:{index}
1280	:    let index = index + 1
1281	:  endwhile
1282	:  echo ""
1283	:endfunction
1284
1285This uses the ":echohl" command to specify the highlighting used for the
1286following ":echo" command.  ":echohl None" stops it again.  The ":echon"
1287command works like ":echo", but doesn't output a line break.
1288
1289You can also use the a:000 variable, it is a List of all the "..." arguments.
1290See |a:000|.
1291
1292
1293LISTING FUNCTIONS
1294
1295The ":function" command lists the names and arguments of all user-defined
1296functions: >
1297
1298	:function
1299<	function Show(start, ...) ~
1300	function GetVimIndent() ~
1301	function SetSyn(name) ~
1302
1303To see what a function does, use its name as an argument for ":function": >
1304
1305	:function SetSyn
1306<	1     if &syntax == '' ~
1307	2       let &syntax = a:name ~
1308	3     endif ~
1309	   endfunction ~
1310
1311
1312DEBUGGING
1313
1314The line number is useful for when you get an error message or when debugging.
1315See |debug-scripts| about debugging mode.
1316   You can also set the 'verbose' option to 12 or higher to see all function
1317calls.  Set it to 15 or higher to see every executed line.
1318
1319
1320DELETING A FUNCTION
1321
1322To delete the Show() function: >
1323
1324	:delfunction Show
1325
1326You get an error when the function doesn't exist.
1327
1328
1329FUNCTION REFERENCES
1330
1331Sometimes it can be useful to have a variable point to one function or
1332another.  You can do it with the function() function.  It turns the name of a
1333function into a reference: >
1334
1335	:let result = 0		" or 1
1336	:function! Right()
1337	:  return 'Right!'
1338	:endfunc
1339	:function! Wrong()
1340	:  return 'Wrong!'
1341	:endfunc
1342	:
1343	:if result == 1
1344	:  let Afunc = function('Right')
1345	:else
1346	:  let Afunc = function('Wrong')
1347	:endif
1348	:echo call(Afunc, [])
1349<	Wrong! ~
1350
1351Note that the name of a variable that holds a function reference must start
1352with a capital.  Otherwise it could be confused with the name of a builtin
1353function.
1354   The way to invoke a function that a variable refers to is with the call()
1355function.  Its first argument is the function reference, the second argument
1356is a List with arguments.
1357
1358Function references are most useful in combination with a Dictionary, as is
1359explained in the next section.
1360
1361More information about defining your own functions here: |user-function|.
1362
1363==============================================================================
1364*41.8*	Lists and Dictionaries
1365
1366So far we have used the basic types String and Number.  Vim also supports two
1367composite types: List and Dictionary.
1368
1369A List is an ordered sequence of things.  The things can be any kind of value,
1370thus you can make a List of numbers, a List of Lists and even a List of mixed
1371items.  To create a List with three strings: >
1372
1373	:let alist = ['aap', 'mies', 'noot']
1374
1375The List items are enclosed in square brackets and separated by commas.  To
1376create an empty List: >
1377
1378	:let alist = []
1379
1380You can add items to a List with the add() function: >
1381
1382	:let alist = []
1383	:call add(alist, 'foo')
1384	:call add(alist, 'bar')
1385	:echo alist
1386<	['foo', 'bar'] ~
1387
1388List concatenation is done with +: >
1389
1390	:echo alist + ['foo', 'bar']
1391<	['foo', 'bar', 'foo', 'bar'] ~
1392
1393Or, if you want to extend a List directly: >
1394
1395	:let alist = ['one']
1396	:call extend(alist, ['two', 'three'])
1397	:echo alist
1398<	['one', 'two', 'three'] ~
1399
1400Notice that using add() will have a different effect: >
1401
1402	:let alist = ['one']
1403	:call add(alist, ['two', 'three'])
1404	:echo alist
1405<	['one', ['two', 'three']] ~
1406
1407The second argument of add() is added as a single item.
1408
1409
1410FOR LOOP
1411
1412One of the nice things you can do with a List is iterate over it: >
1413
1414	:let alist = ['one', 'two', 'three']
1415	:for n in alist
1416	:  echo n
1417	:endfor
1418<	one ~
1419	two ~
1420	three ~
1421
1422This will loop over each element in List "alist", assigning the value to
1423variable "n".  The generic form of a for loop is: >
1424
1425	:for {varname} in {listexpression}
1426	:  {commands}
1427	:endfor
1428
1429To loop a certain number of times you need a List of a specific length.  The
1430range() function creates one for you: >
1431
1432	:for a in range(3)
1433	:  echo a
1434	:endfor
1435<	0 ~
1436	1 ~
1437	2 ~
1438
1439Notice that the first item of the List that range() produces is zero, thus the
1440last item is one less than the length of the list.
1441   You can also specify the maximum value, the stride and even go backwards: >
1442
1443	:for a in range(8, 4, -2)
1444	:  echo a
1445	:endfor
1446<	8 ~
1447	6 ~
1448	4 ~
1449
1450A more useful example, looping over lines in the buffer: >
1451
1452	:for line in getline(1, 20)
1453	:  if line =~ "Date: "
1454	:    echo matchstr(line, 'Date: \zs.*')
1455	:  endif
1456	:endfor
1457
1458This looks into lines 1 to 20 (inclusive) and echoes any date found in there.
1459
1460
1461DICTIONARIES
1462
1463A Dictionary stores key-value pairs.  You can quickly lookup a value if you
1464know the key.  A Dictionary is created with curly braces: >
1465
1466	:let uk2nl = {'one': 'een', 'two': 'twee', 'three': 'drie'}
1467
1468Now you can lookup words by putting the key in square brackets: >
1469
1470	:echo uk2nl['two']
1471<	twee ~
1472
1473The generic form for defining a Dictionary is: >
1474
1475	{<key> : <value>, ...}
1476
1477An empty Dictionary is one without any keys: >
1478
1479	{}
1480
1481The possibilities with Dictionaries are numerous.  There are various functions
1482for them as well.  For example, you can obtain a list of the keys and loop
1483over them: >
1484
1485	:for key in keys(uk2nl)
1486	:  echo key
1487	:endfor
1488<	three ~
1489	one ~
1490	two ~
1491
1492You will notice the keys are not ordered.  You can sort the list to get a
1493specific order: >
1494
1495	:for key in sort(keys(uk2nl))
1496	:  echo key
1497	:endfor
1498<	one ~
1499	three ~
1500	two ~
1501
1502But you can never get back the order in which items are defined.  For that you
1503need to use a List, it stores items in an ordered sequence.
1504
1505
1506DICTIONARY FUNCTIONS
1507
1508The items in a Dictionary can normally be obtained with an index in square
1509brackets: >
1510
1511	:echo uk2nl['one']
1512<	een ~
1513
1514A method that does the same, but without so many punctuation characters: >
1515
1516	:echo uk2nl.one
1517<	een ~
1518
1519This only works for a key that is made of ASCII letters, digits and the
1520underscore.  You can also assign a new value this way: >
1521
1522	:let uk2nl.four = 'vier'
1523	:echo uk2nl
1524<	{'three': 'drie', 'four': 'vier', 'one': 'een', 'two': 'twee'} ~
1525
1526And now for something special: you can directly define a function and store a
1527reference to it in the dictionary: >
1528
1529	:function uk2nl.translate(line) dict
1530	:  return join(map(split(a:line), 'get(self, v:val, "???")'))
1531	:endfunction
1532
1533Let's first try it out: >
1534
1535	:echo uk2nl.translate('three two five one')
1536<	drie twee ??? een ~
1537
1538The first special thing you notice is the "dict" at the end of the ":function"
1539line.  This marks the function as being used from a Dictionary.  The "self"
1540local variable will then refer to that Dictionary.
1541   Now let's break up the complicated return command: >
1542
1543	split(a:line)
1544
1545The split() function takes a string, chops it into whitespace separated words
1546and returns a list with these words.  Thus in the example it returns: >
1547
1548	:echo split('three two five one')
1549<	['three', 'two', 'five', 'one'] ~
1550
1551This list is the first argument to the map() function.  This will go through
1552the list, evaluating its second argument with "v:val" set to the value of each
1553item.  This is a shortcut to using a for loop.  This command: >
1554
1555	:let alist = map(split(a:line), 'get(self, v:val, "???")')
1556
1557Is equivalent to: >
1558
1559	:let alist = split(a:line)
1560	:for idx in range(len(alist))
1561	:  let alist[idx] = get(self, alist[idx], "???")
1562	:endfor
1563
1564The get() function checks if a key is present in a Dictionary.  If it is, then
1565the value is retrieved.  If it isn't, then the default value is returned, in
1566the example it's '???'.  This is a convenient way to handle situations where a
1567key may not be present and you don't want an error message.
1568
1569The join() function does the opposite of split(): it joins together a list of
1570words, putting a space in between.
1571  This combination of split(), map() and join() is a nice way to filter a line
1572of words in a very compact way.
1573
1574
1575OBJECT ORIENTED PROGRAMMING
1576
1577Now that you can put both values and functions in a Dictionary, you can
1578actually use a Dictionary like an object.
1579   Above we used a Dictionary for translating Dutch to English.  We might want
1580to do the same for other languages.  Let's first make an object (aka
1581Dictionary) that has the translate function, but no words to translate: >
1582
1583	:let transdict = {}
1584	:function transdict.translate(line) dict
1585	:  return join(map(split(a:line), 'get(self.words, v:val, "???")'))
1586	:endfunction
1587
1588It's slightly different from the function above, using 'self.words' to lookup
1589word translations.  But we don't have a self.words.  Thus you could call this
1590an abstract class.
1591
1592Now we can instantiate a Dutch translation object: >
1593
1594	:let uk2nl = copy(transdict)
1595	:let uk2nl.words = {'one': 'een', 'two': 'twee', 'three': 'drie'}
1596	:echo uk2nl.translate('three one')
1597<	drie een ~
1598
1599And a German translator: >
1600
1601	:let uk2de = copy(transdict)
1602	:let uk2de.words = {'one': 'eins', 'two': 'zwei', 'three': 'drei'}
1603	:echo uk2de.translate('three one')
1604<	drei eins ~
1605
1606You see that the copy() function is used to make a copy of the "transdict"
1607Dictionary and then the copy is changed to add the words.  The original
1608remains the same, of course.
1609
1610Now you can go one step further, and use your preferred translator: >
1611
1612	:if $LANG =~ "de"
1613	:  let trans = uk2de
1614	:else
1615	:  let trans = uk2nl
1616	:endif
1617	:echo trans.translate('one two three')
1618<	een twee drie ~
1619
1620Here "trans" refers to one of the two objects (Dictionaries).  No copy is
1621made.  More about List and Dictionary identity can be found at |list-identity|
1622and |dict-identity|.
1623
1624Now you might use a language that isn't supported.  You can overrule the
1625translate() function to do nothing: >
1626
1627	:let uk2uk = copy(transdict)
1628	:function! uk2uk.translate(line)
1629	:  return a:line
1630	:endfunction
1631	:echo uk2uk.translate('three one wladiwostok')
1632<	three one wladiwostok ~
1633
1634Notice that a ! was used to overwrite the existing function reference.  Now
1635use "uk2uk" when no recognized language is found: >
1636
1637	:if $LANG =~ "de"
1638	:  let trans = uk2de
1639	:elseif $LANG =~ "nl"
1640	:  let trans = uk2nl
1641	:else
1642	:  let trans = uk2uk
1643	:endif
1644	:echo trans.translate('one two three')
1645<	one two three ~
1646
1647For further reading see |Lists| and |Dictionaries|.
1648
1649==============================================================================
1650*41.9*	Exceptions
1651
1652Let's start with an example: >
1653
1654	:try
1655	:   read ~/templates/pascal.tmpl
1656	:catch /E484:/
1657	:   echo "Sorry, the Pascal template file cannot be found."
1658	:endtry
1659
1660The ":read" command will fail if the file does not exist.  Instead of
1661generating an error message, this code catches the error and gives the user a
1662nice message.
1663
1664For the commands in between ":try" and ":endtry" errors are turned into
1665exceptions.  An exception is a string.  In the case of an error the string
1666contains the error message.  And every error message has a number.  In this
1667case, the error we catch contains "E484:".  This number is guaranteed to stay
1668the same (the text may change, e.g., it may be translated).
1669
1670When the ":read" command causes another error, the pattern "E484:" will not
1671match in it.  Thus this exception will not be caught and result in the usual
1672error message and execution is aborted.
1673
1674You might be tempted to do this: >
1675
1676	:try
1677	:   read ~/templates/pascal.tmpl
1678	:catch
1679	:   echo "Sorry, the Pascal template file cannot be found."
1680	:endtry
1681
1682This means all errors are caught.  But then you will not see errors that are
1683useful, such as "E21: Cannot make changes, 'modifiable' is off".
1684
1685Another useful mechanism is the ":finally" command: >
1686
1687	:let tmp = tempname()
1688	:try
1689	:   exe ".,$write " .. tmp
1690	:   exe "!filter " .. tmp
1691	:   .,$delete
1692	:   exe "$read " .. tmp
1693	:finally
1694	:   call delete(tmp)
1695	:endtry
1696
1697This filters the lines from the cursor until the end of the file through the
1698"filter" command, which takes a file name argument.  No matter if the
1699filtering works, something goes wrong in between ":try" and ":finally" or the
1700user cancels the filtering by pressing CTRL-C, the "call delete(tmp)" is
1701always executed.  This makes sure you don't leave the temporary file behind.
1702
1703More information about exception handling can be found in the reference
1704manual: |exception-handling|.
1705
1706==============================================================================
1707*41.10*	Various remarks
1708
1709Here is a summary of items that apply to Vim scripts.  They are also mentioned
1710elsewhere, but form a nice checklist.
1711
1712The end-of-line character depends on the system.  For Vim scripts it is
1713recommended to always use the Unix fileformat.  Lines are then separated with
1714the Newline character.  This also works on any other system.  That way you can
1715copy your Vim scripts from MS-Windows to Unix and they still work.  See
1716|:source_crnl|.  To be sure it is set right, do this before writing the file:
1717 >
1718	:setlocal fileformat=unix
1719
1720When using "dos" fileformat, lines are separated with CR-NL, two characters.
1721The CR character causes various problems, better avoid this.
1722
1723
1724WHITE SPACE
1725
1726Blank lines are allowed in a script and ignored.
1727
1728Leading whitespace characters (blanks and TABs) are ignored, except when using
1729|:let-heredoc| without "trim".
1730
1731Trailing whitespace is often ignored, but not always.  One command that
1732includes it is `map`.  You have to watch out for that, it can cause hard to
1733understand mistakes.  A generic solution is to never use trailing white space,
1734unless you really need it.
1735
1736To include a whitespace character in the value of an option, it must be
1737escaped by a "\" (backslash)  as in the following example: >
1738
1739	:set tags=my\ nice\ file
1740
1741The same example written as: >
1742
1743	:set tags=my nice file
1744
1745will issue an error, because it is interpreted as: >
1746
1747	:set tags=my
1748	:set nice
1749	:set file
1750
1751
1752COMMENTS
1753
1754The character " (the double quote mark) starts a comment.  Everything after
1755and including this character until the end-of-line is considered a comment and
1756is ignored, except for commands that don't consider comments, as shown in
1757examples below.  A comment can start on any character position on the line.
1758
1759There is a little "catch" with comments for some commands.  Examples: >
1760
1761	:abbrev dev development		" shorthand
1762	:map <F3> o#include		" insert include
1763	:execute cmd			" do it
1764	:!ls *.c			" list C files
1765
1766The abbreviation "dev" will be expanded to 'development     " shorthand'.  The
1767mapping of <F3> will actually be the whole line after the 'o# ....' including
1768the '" insert include'.  The "execute" command will give an error.  The "!"
1769command will send everything after it to the shell, causing an error for an
1770unmatched '"' character.
1771   There can be no comment after ":map", ":abbreviate", ":execute" and "!"
1772commands (there are a few more commands with this restriction).  For the
1773":map", ":abbreviate" and ":execute" commands there is a trick: >
1774
1775	:abbrev dev development|" shorthand
1776	:map <F3> o#include|" insert include
1777	:execute cmd			|" do it
1778
1779With the '|' character the command is separated from the next one.  And that
1780next command is only a comment.  For the last command you need to do two
1781things: |:execute| and use '|': >
1782	:exe '!ls *.c'			|" list C files
1783
1784Notice that there is no white space before the '|' in the abbreviation and
1785mapping.  For these commands, any character until the end-of-line or '|' is
1786included.  As a consequence of this behavior, you don't always see that
1787trailing whitespace is included: >
1788
1789	:map <F4> o#include  
1790
1791To spot these problems, you can set the 'list' option when editing vimrc
1792files.
1793
1794For Unix there is one special way to comment a line, that allows making a Vim
1795script executable: >
1796	#!/usr/bin/env vim -S
1797	echo "this is a Vim script"
1798	quit
1799
1800The "#" command by itself lists a line with the line number.  Adding an
1801exclamation mark changes it into doing nothing, so that you can add the shell
1802command to execute the rest of the file. |:#!| |-S|
1803
1804
1805PITFALLS
1806
1807Even bigger problem arises in the following example: >
1808
1809	:map ,ab o#include
1810	:unmap ,ab
1811
1812Here the unmap command will not work, because it tries to unmap ",ab ".  This
1813does not exist as a mapped sequence.  An error will be issued, which is very
1814hard to identify, because the ending whitespace character in ":unmap ,ab " is
1815not visible.
1816
1817And this is the same as what happens when one uses a comment after an "unmap"
1818command: >
1819
1820	:unmap ,ab     " comment
1821
1822Here the comment part will be ignored.  However, Vim will try to unmap
1823',ab     ', which does not exist.  Rewrite it as: >
1824
1825	:unmap ,ab|    " comment
1826
1827
1828RESTORING THE VIEW
1829
1830Sometimes you want to make a change and go back to where the cursor was.
1831Restoring the relative position would also be nice, so that the same line
1832appears at the top of the window.
1833   This example yanks the current line, puts it above the first line in the
1834file and then restores the view: >
1835
1836	map ,p ma"aYHmbgg"aP`bzt`a
1837
1838What this does: >
1839	ma"aYHmbgg"aP`bzt`a
1840<	ma			set mark a at cursor position
1841	  "aY			yank current line into register a
1842	     Hmb		go to top line in window and set mark b there
1843		gg		go to first line in file
1844		  "aP		put the yanked line above it
1845		     `b		go back to top line in display
1846		       zt	position the text in the window as before
1847			 `a	go back to saved cursor position
1848
1849
1850PACKAGING
1851
1852To avoid your function names to interfere with functions that you get from
1853others, use this scheme:
1854- Prepend a unique string before each function name.  I often use an
1855  abbreviation.  For example, "OW_" is used for the option window functions.
1856- Put the definition of your functions together in a file.  Set a global
1857  variable to indicate that the functions have been loaded.  When sourcing the
1858  file again, first unload the functions.
1859Example: >
1860
1861	" This is the XXX package
1862
1863	if exists("XXX_loaded")
1864	  delfun XXX_one
1865	  delfun XXX_two
1866	endif
1867
1868	function XXX_one(a)
1869		... body of function ...
1870	endfun
1871
1872	function XXX_two(b)
1873		... body of function ...
1874	endfun
1875
1876	let XXX_loaded = 1
1877
1878==============================================================================
1879*41.11*	Writing a plugin				*write-plugin*
1880
1881You can write a Vim script in such a way that many people can use it.  This is
1882called a plugin.  Vim users can drop your script in their plugin directory and
1883use its features right away |add-plugin|.
1884
1885There are actually two types of plugins:
1886
1887  global plugins: For all types of files.
1888filetype plugins: Only for files of a specific type.
1889
1890In this section the first type is explained.  Most items are also relevant for
1891writing filetype plugins.  The specifics for filetype plugins are in the next
1892section |write-filetype-plugin|.
1893
1894
1895NAME
1896
1897First of all you must choose a name for your plugin.  The features provided
1898by the plugin should be clear from its name.  And it should be unlikely that
1899someone else writes a plugin with the same name but which does something
1900different.  And please limit the name to 8 characters, to avoid problems on
1901old MS-Windows systems.
1902
1903A script that corrects typing mistakes could be called "typecorr.vim".  We
1904will use it here as an example.
1905
1906For the plugin to work for everybody, it should follow a few guidelines.  This
1907will be explained step-by-step.  The complete example plugin is at the end.
1908
1909
1910BODY
1911
1912Let's start with the body of the plugin, the lines that do the actual work: >
1913
1914 14	iabbrev teh the
1915 15	iabbrev otehr other
1916 16	iabbrev wnat want
1917 17	iabbrev synchronisation
1918 18		\ synchronization
1919 19	let s:count = 4
1920
1921The actual list should be much longer, of course.
1922
1923The line numbers have only been added to explain a few things, don't put them
1924in your plugin file!
1925
1926
1927HEADER
1928
1929You will probably add new corrections to the plugin and soon have several
1930versions lying around.  And when distributing this file, people will want to
1931know who wrote this wonderful plugin and where they can send remarks.
1932Therefore, put a header at the top of your plugin: >
1933
1934  1	" Vim global plugin for correcting typing mistakes
1935  2	" Last Change:	2000 Oct 15
1936  3	" Maintainer:	Bram Moolenaar <Bram@vim.org>
1937
1938About copyright and licensing: Since plugins are very useful and it's hardly
1939worth restricting their distribution, please consider making your plugin
1940either public domain or use the Vim |license|.  A short note about this near
1941the top of the plugin should be sufficient.  Example: >
1942
1943  4	" License:	This file is placed in the public domain.
1944
1945
1946LINE CONTINUATION, AVOIDING SIDE EFFECTS		*use-cpo-save*
1947
1948In line 18 above, the line-continuation mechanism is used |line-continuation|.
1949Users with 'compatible' set will run into trouble here, they will get an error
1950message.  We can't just reset 'compatible', because that has a lot of side
1951effects.  To avoid this, we will set the 'cpoptions' option to its Vim default
1952value and restore it later.  That will allow the use of line-continuation and
1953make the script work for most people.  It is done like this: >
1954
1955 11	let s:save_cpo = &cpo
1956 12	set cpo&vim
1957 ..
1958 42	let &cpo = s:save_cpo
1959 43	unlet s:save_cpo
1960
1961We first store the old value of 'cpoptions' in the s:save_cpo variable.  At
1962the end of the plugin this value is restored.
1963
1964Notice that a script-local variable is used |s:var|.  A global variable could
1965already be in use for something else.  Always use script-local variables for
1966things that are only used in the script.
1967
1968
1969NOT LOADING
1970
1971It's possible that a user doesn't always want to load this plugin.  Or the
1972system administrator has dropped it in the system-wide plugin directory, but a
1973user has their own plugin they want to use.  Then the user must have a chance to
1974disable loading this specific plugin.  This will make it possible: >
1975
1976  6	if exists("g:loaded_typecorr")
1977  7	  finish
1978  8	endif
1979  9	let g:loaded_typecorr = 1
1980
1981This also avoids that when the script is loaded twice it would cause error
1982messages for redefining functions and cause trouble for autocommands that are
1983added twice.
1984
1985The name is recommended to start with "loaded_" and then the file name of the
1986plugin, literally.  The "g:" is prepended just to avoid mistakes when using
1987the variable in a function (without "g:" it would be a variable local to the
1988function).
1989
1990Using "finish" stops Vim from reading the rest of the file, it's much quicker
1991than using if-endif around the whole file.
1992
1993
1994MAPPING
1995
1996Now let's make the plugin more interesting: We will add a mapping that adds a
1997correction for the word under the cursor.  We could just pick a key sequence
1998for this mapping, but the user might already use it for something else.  To
1999allow the user to define which keys a mapping in a plugin uses, the <Leader>
2000item can be used: >
2001
2002 22	  map <unique> <Leader>a  <Plug>(TypecorrAdd)
2003
2004The "<Plug>(TypecorrAdd)" thing will do the work, more about that further on.
2005
2006The user can set the "mapleader" variable to the key sequence that they want
2007this mapping to start with.  Thus if the user has done: >
2008
2009	let mapleader = "_"
2010
2011the mapping will define "_a".  If the user didn't do this, the default value
2012will be used, which is a backslash.  Then a map for "\a" will be defined.
2013
2014Note that <unique> is used, this will cause an error message if the mapping
2015already happened to exist. |:map-<unique>|
2016
2017But what if the user wants to define their own key sequence?  We can allow that
2018with this mechanism: >
2019
2020 21	if !hasmapto('<Plug>(TypecorrAdd)')
2021 22	  map <unique> <Leader>a  <Plug>(TypecorrAdd)
2022 23	endif
2023
2024This checks if a mapping to "<Plug>(TypecorrAdd)" already exists, and only
2025defines the mapping from "<Leader>a" if it doesn't.  The user then has a
2026chance of putting this in their vimrc file: >
2027
2028	map ,c  <Plug>(TypecorrAdd)
2029
2030Then the mapped key sequence will be ",c" instead of "_a" or "\a".
2031
2032
2033PIECES
2034
2035If a script gets longer, you often want to break up the work in pieces.  You
2036can use functions or mappings for this.  But you don't want these functions
2037and mappings to interfere with the ones from other scripts.  For example, you
2038could define a function Add(), but another script could try to define the same
2039function.  To avoid this, we define the function local to the script by
2040prepending it with "s:".
2041
2042We will define a function that adds a new typing correction: >
2043
2044 30	function s:Add(from, correct)
2045 31	  let to = input("type the correction for " .. a:from .. ": ")
2046 32	  exe ":iabbrev " .. a:from .. " " .. to
2047 ..
2048 36	endfunction
2049
2050Now we can call the function s:Add() from within this script.  If another
2051script also defines s:Add(), it will be local to that script and can only
2052be called from the script it was defined in.  There can also be a global Add()
2053function (without the "s:"), which is again another function.
2054
2055<SID> can be used with mappings.  It generates a script ID, which identifies
2056the current script.  In our typing correction plugin we use it like this: >
2057
2058 24	noremap <unique> <script> <Plug>(TypecorrAdd)  <SID>Add
2059 ..
2060 28	noremap <SID>Add  :call <SID>Add(expand("<cword>"), 1)<CR>
2061
2062Thus when a user types "\a", this sequence is invoked: >
2063
2064	\a  ->  <Plug>(TypecorrAdd)  ->  <SID>Add  ->  :call <SID>Add()
2065
2066If another script also maps <SID>Add, it will get another script ID and
2067thus define another mapping.
2068
2069Note that instead of s:Add() we use <SID>Add() here.  That is because the
2070mapping is typed by the user, thus outside of the script.  The <SID> is
2071translated to the script ID, so that Vim knows in which script to look for
2072the Add() function.
2073
2074This is a bit complicated, but it's required for the plugin to work together
2075with other plugins.  The basic rule is that you use <SID>Add() in mappings and
2076s:Add() in other places (the script itself, autocommands, user commands).
2077
2078We can also add a menu entry to do the same as the mapping: >
2079
2080 26	noremenu <script> Plugin.Add\ Correction      <SID>Add
2081
2082The "Plugin" menu is recommended for adding menu items for plugins.  In this
2083case only one item is used.  When adding more items, creating a submenu is
2084recommended.  For example, "Plugin.CVS" could be used for a plugin that offers
2085CVS operations "Plugin.CVS.checkin", "Plugin.CVS.checkout", etc.
2086
2087Note that in line 28 ":noremap" is used to avoid that any other mappings cause
2088trouble.  Someone may have remapped ":call", for example.  In line 24 we also
2089use ":noremap", but we do want "<SID>Add" to be remapped.  This is why
2090"<script>" is used here.  This only allows mappings which are local to the
2091script. |:map-<script>|  The same is done in line 26 for ":noremenu".
2092|:menu-<script>|
2093
2094
2095<SID> AND <Plug>					*using-<Plug>*
2096
2097Both <SID> and <Plug> are used to avoid that mappings of typed keys interfere
2098with mappings that are only to be used from other mappings.  Note the
2099difference between using <SID> and <Plug>:
2100
2101<Plug>	is visible outside of the script.  It is used for mappings which the
2102	user might want to map a key sequence to.  <Plug> is a special code
2103	that a typed key will never produce.
2104	To make it very unlikely that other plugins use the same sequence of
2105	characters, use this structure: <Plug> scriptname mapname
2106	In our example the scriptname is "Typecorr" and the mapname is "Add".
2107	We wrap the name in parentheses.  This results in
2108	"<Plug>(TypecorrAdd)".  The convention of using PascalCase helps
2109	telling scriptname apart from mapname.
2110
2111	Note: the text after "<Plug>" is chosen by the plugin author and is
2112	entirely arbitrary.  Wrapping the name in parentheses, using
2113	PascalCase, or adding a ";" terminator like "<Plug>TypecorrAdd;" are
2114	only conventions to keep the name readable and unlikely to clash with
2115	other plugins.  None of them are required: all that matters is that
2116	the sequence starts with "<Plug>" and is unique.
2117	A mapping whose {lhs} starts with <Plug> is always applied to the
2118	{rhs} of another mapping, even if remapping is explicitly disallowed.
2119	|:nore|
2120
2121<SID>	is the script ID, a unique identifier for a script.
2122	Internally Vim translates <SID> to "<SNR>123_", where "123" can be any
2123	number.  Thus a function "<SID>Add()" will have a name "<SNR>11_Add()"
2124	in one script, and "<SNR>22_Add()" in another.  You can see this if
2125	you use the ":function" command to get a list of functions.  The
2126	translation of <SID> in mappings is exactly the same, that's how you
2127	can call a script-local function from a mapping.
2128	Note: when <SID> appears in the {rhs} of a mapping, you might consider
2129	using <script>. |:map-<script>|
2130
2131
2132USER COMMAND
2133
2134Now let's add a user command to add a correction: >
2135
2136 38	if !exists(":Correct")
2137 39	  command -nargs=1  Correct  :call s:Add(<q-args>, 0)
2138 40	endif
2139
2140The user command is defined only if no command with the same name already
2141exists.  Otherwise we would get an error here.  Overriding the existing user
2142command with ":command!" is not a good idea, this would probably make the user
2143wonder why the command they defined themself doesn't work.  |:command|
2144
2145
2146SCRIPT VARIABLES
2147
2148When a variable starts with "s:" it is a script variable.  It can only be used
2149inside a script.  Outside the script it's not visible.  This avoids trouble
2150with using the same variable name in different scripts.  The variables will be
2151kept as long as Vim is running.  And the same variables are used when sourcing
2152the same script again. |s:var|
2153
2154The fun is that these variables can also be used in functions, autocommands
2155and user commands that are defined in the script.  In our example we can add
2156a few lines to count the number of corrections: >
2157
2158 19	let s:count = 4
2159 ..
2160 30	function s:Add(from, correct)
2161 ..
2162 34	  let s:count = s:count + 1
2163 35	  echo s:count .. " corrections now"
2164 36	endfunction
2165
2166First s:count is initialized to 4 in the script itself.  When later the
2167s:Add() function is called, it increments s:count.  It doesn't matter from
2168where the function was called, since it has been defined in the script, it
2169will use the local variables from this script.
2170
2171
2172THE RESULT
2173
2174Here is the resulting complete example: >
2175
2176  1	" Vim global plugin for correcting typing mistakes
2177  2	" Last Change:	2000 Oct 15
2178  3	" Maintainer:	Bram Moolenaar <Bram@vim.org>
2179  4	" License:	This file is placed in the public domain.
2180  5
2181  6	if exists("g:loaded_typecorr")
2182  7	  finish
2183  8	endif
2184  9	let g:loaded_typecorr = 1
2185 10
2186 11	let s:save_cpo = &cpo
2187 12	set cpo&vim
2188 13
2189 14	iabbrev teh the
2190 15	iabbrev otehr other
2191 16	iabbrev wnat want
2192 17	iabbrev synchronisation
2193 18		\ synchronization
2194 19	let s:count = 4
2195 20
2196 21	if !hasmapto('<Plug>(TypecorrAdd)')
2197 22	  map <unique> <Leader>a  <Plug>(TypecorrAdd)
2198 23	endif
2199 24	noremap <unique> <script> <Plug>(TypecorrAdd)  <SID>Add
2200 25
2201 26	noremenu <script> Plugin.Add\ Correction      <SID>Add
2202 27
2203 28	noremap <SID>Add  :call <SID>Add(expand("<cword>"), 1)<CR>
2204 29
2205 30	function s:Add(from, correct)
2206 31	  let to = input("type the correction for " .. a:from .. ": ")
2207 32	  exe ":iabbrev " .. a:from .. " " .. to
2208 33	  if a:correct | exe "normal viws\<C-R>\" \b\e" | endif
2209 34	  let s:count = s:count + 1
2210 35	  echo s:count .. " corrections now"
2211 36	endfunction
2212 37
2213 38	if !exists(":Correct")
2214 39	  command -nargs=1  Correct  :call s:Add(<q-args>, 0)
2215 40	endif
2216 41
2217 42	let &cpo = s:save_cpo
2218 43	unlet s:save_cpo
2219
2220Line 33 wasn't explained yet.  It applies the new correction to the word under
2221the cursor.  The |:normal| command is used to use the new abbreviation.  Note
2222that mappings and abbreviations are expanded here, even though the function
2223was called from a mapping defined with ":noremap".
2224
2225Using "unix" for the 'fileformat' option is recommended.  The Vim scripts will
2226then work everywhere.  Scripts with 'fileformat' set to "dos" do not work on
2227Unix.  Also see |:source_crnl|.  To be sure it is set right, do this before
2228writing the file: >
2229
2230	:set fileformat=unix
2231
2232
2233DOCUMENTATION						*write-local-help*
2234
2235It's a good idea to also write some documentation for your plugin.  Especially
2236when its behavior can be changed by the user.  See |add-local-help| for how
2237they are installed.
2238
2239Here is a simple example for a plugin help file, called "typecorr.txt": >
2240
2241  1	*typecorr.txt*	Plugin for correcting typing mistakes
2242  2
2243  3	If you make typing mistakes, this plugin will have them corrected
2244  4	automatically.
2245  5
2246  6	There are currently only a few corrections.  Add your own if you like.
2247  7
2248  8	Mappings:
2249  9	<Leader>a   or   <Plug>(TypecorrAdd)
2250 10		Add a correction for the word under the cursor.
2251 11
2252 12	Commands:
2253 13	:Correct {word}
2254 14		Add a correction for {word}.
2255 15
2256 16							*typecorr-settings*
2257 17	This plugin doesn't have any settings.
2258
2259The first line is actually the only one for which the format matters.  It will
2260be extracted from the help file to be put in the "LOCAL ADDITIONS:" section of
2261help.txt |local-additions|.  The first "*" must be in the first column of the
2262first line.  After adding your help file do ":help" and check that the entries
2263line up nicely.
2264
2265You can add more tags inside ** in your help file.  But be careful not to use
2266existing help tags.  You would probably use the name of your plugin in most of
2267them, like "typecorr-settings" in the example.
2268
2269Using references to other parts of the help in || is recommended.  This makes
2270it easy for the user to find associated help.
2271
2272
2273FILETYPE DETECTION					*plugin-filetype*
2274
2275If your filetype is not already detected by Vim, you should create a filetype
2276detection snippet in a separate file.  It is usually in the form of an
2277autocommand that sets the filetype when the file name matches a pattern.
2278Example: >
2279
2280	au BufNewFile,BufRead *.foo			set filetype=foofoo
2281
2282Write this single-line file as "ftdetect/foofoo.vim" in the first directory
2283that appears in 'runtimepath'.  For Unix that would be
2284"~/.config/nvim/ftdetect/foofoo.vim".  The convention is to use the name of
2285the filetype for the script name.
2286
2287You can make more complicated checks if you like, for example to inspect the
2288contents of the file to recognize the language.  Also see |new-filetype|.
2289
2290
2291SUMMARY							*plugin-special*
2292
2293Summary of special things to use in a plugin:
2294
2295s:name			Variables local to the script.
2296
2297<SID>			Script-ID, used for mappings and functions local to
2298			the script.
2299
2300hasmapto()		Function to test if the user already defined a mapping
2301			for functionality the script offers.
2302
2303<Leader>		Value of "mapleader", which the user defines as the
2304			keys that plugin mappings start with.
2305
2306:map <unique>		Give a warning if a mapping already exists.
2307
2308:noremap <script>	Only remap mappings defined in this script that start
2309			with <SID>.
2310
2311exists(":Cmd")		Check if a user command already exists.
2312
2313==============================================================================
2314*41.12*	Writing a filetype plugin	*write-filetype-plugin* *ftplugin*
2315
2316A filetype plugin is like a global plugin, except that it sets options and
2317defines mappings for the current buffer only.  See |add-filetype-plugin| for
2318how this type of plugin is used.
2319
2320First read the section on global plugins above |41.11|.  All that is said there
2321also applies to filetype plugins.  There are a few extras, which are explained
2322here.  The essential thing is that a filetype plugin should only have an
2323effect on the current buffer.
2324
2325
2326DISABLING
2327
2328If you are writing a filetype plugin to be used by many people, they need a
2329chance to disable loading it.  Put this at the top of the plugin: >
2330
2331	" Only do this when not done yet for this buffer
2332	if exists("b:did_ftplugin")
2333	  finish
2334	endif
2335	let b:did_ftplugin = 1
2336
2337This also needs to be used to avoid that the same plugin is executed twice for
2338the same buffer (happens when using an ":edit" command without arguments).
2339
2340Now users can disable loading the default plugin completely by making a
2341filetype plugin with only this line: >
2342
2343	let b:did_ftplugin = 1
2344
2345This does require that the filetype plugin directory comes before $VIMRUNTIME
2346in 'runtimepath'!
2347
2348If you do want to use the default plugin, but overrule one of the settings,
2349you can write the different setting in a script: >
2350
2351	setlocal textwidth=70
2352
2353Now write this in the "after" directory, so that it gets sourced after the
2354distributed "vim.vim" ftplugin |after-directory|.  For Unix this would be
2355"~/.config/nvim/after/ftplugin/vim.vim".  Note that the default plugin will
2356have set "b:did_ftplugin", but it is ignored here.
2357
2358
2359OPTIONS
2360
2361To make sure the filetype plugin only affects the current buffer use the >
2362
2363	:setlocal
2364
2365command to set options.  And only set options which are local to a buffer (see
2366the help for the option to check that).  When using |:setlocal| for global
2367options or options local to a window, the value will change for many buffers,
2368and that is not what a filetype plugin should do.
2369
2370When an option has a value that is a list of flags or items, consider using
2371"+=" and "-=" to keep the existing value.  Be aware that the user may have
2372changed an option value already.  First resetting to the default value and
2373then changing it is often a good idea.  Example: >
2374
2375	:setlocal formatoptions& formatoptions+=ro
2376
2377
2378MAPPINGS
2379
2380To make sure mappings will only work in the current buffer use the >
2381
2382	:map <buffer>
2383
2384command.  This needs to be combined with the two-step mapping explained above.
2385An example of how to define functionality in a filetype plugin: >
2386
2387	if !hasmapto('<Plug>JavaImport;')
2388	  map <buffer> <unique> <LocalLeader>i <Plug>JavaImport;
2389	endif
2390	noremap <buffer> <unique> <Plug>JavaImport; oimport ""<Left><Esc>
2391
2392|hasmapto()| is used to check if the user has already defined a map to
2393<Plug>JavaImport;.  If not, then the filetype plugin defines the default
2394mapping.  This starts with |<LocalLeader>|, which allows the user to select
2395the key(s) they want filetype plugin mappings to start with.  The default is a
2396backslash.
2397"<unique>" is used to give an error message if the mapping already exists or
2398overlaps with an existing mapping.
2399|:noremap| is used to avoid that any other mappings that the user has defined
2400interferes.  You might want to use ":noremap <script>" to allow remapping
2401mappings defined in this script that start with <SID>.
2402
2403The user must have a chance to disable the mappings in a filetype plugin,
2404without disabling everything.  Here is an example of how this is done for a
2405plugin for the mail filetype: >
2406
2407	" Add mappings, unless the user didn't want this.
2408	if !exists("no_plugin_maps") && !exists("no_mail_maps")
2409	  " Quote text by inserting "> "
2410	  if !hasmapto('<Plug>MailQuote;')
2411	    vmap <buffer> <LocalLeader>q <Plug>MailQuote;
2412	    nmap <buffer> <LocalLeader>q <Plug>MailQuote;
2413	  endif
2414	  vnoremap <buffer> <Plug>MailQuote; :s/^/> /<CR>
2415	  nnoremap <buffer> <Plug>MailQuote; :.,$s/^/> /<CR>
2416	endif
2417
2418Two global variables are used:
2419|no_plugin_maps|	disables mappings for all filetype plugins
2420|no_mail_maps|		disables mappings for the "mail" filetype
2421
2422
2423USER COMMANDS
2424
2425To add a user command for a specific file type, so that it can only be used in
2426one buffer, use the "-buffer" argument to |:command|.  Example: >
2427
2428	:command -buffer  Make  make %:r.s
2429
2430
2431VARIABLES
2432
2433A filetype plugin will be sourced for each buffer of the type it's for.  Local
2434script variables |s:var| will be shared between all invocations.  Use local
2435buffer variables |b:var| if you want a variable specifically for one buffer.
2436
2437
2438FUNCTIONS
2439
2440When defining a function, this only needs to be done once.  But the filetype
2441plugin will be sourced every time a file with this filetype will be opened.
2442This construct makes sure the function is only defined once: >
2443
2444	:if !exists("*s:Func")
2445	:  function s:Func(arg)
2446	:    ...
2447	:  endfunction
2448	:endif
2449<
2450
2451UNDO						*undo_indent* *undo_ftplugin*
2452
2453When the user does ":setfiletype xyz" the effect of the previous filetype
2454should be undone.  Set the b:undo_ftplugin variable to the commands that will
2455undo the settings in your filetype plugin.  Example: >
2456
2457	let b:undo_ftplugin = "setlocal fo< com< tw< commentstring<"
2458		\ .. "| unlet b:match_ignorecase b:match_words b:match_skip"
2459
2460Using ":setlocal" with "<" after the option name resets the option to its
2461global value.  That is mostly the best way to reset the option value.
2462
2463This does require removing the "C" flag from 'cpoptions' to allow line
2464continuation, as mentioned above |use-cpo-save|.
2465
2466For undoing the effect of an indent script, the b:undo_indent variable should
2467be set accordingly.
2468
2469RECOMMENDED STYLE				*ft_recommended_style*
2470
2471A filetype plugin or indent script may set options that reflect a
2472recommended or commonly used style for that filetype, rather than a strict
2473requirement of the language.  Since not every user wants these stylistic
2474settings, guard them so they can be disabled.
2475
2476Check two variables, the filetype-specific one first, then the general one,
2477defaulting to enabled (1): >
2478
2479	if get(g:, '<filetype>_recommended_style',
2480		\ get(g:, 'filetype_recommended_style', 1))
2481	  " set the recommended style options here
2482	endif
2483
2484Replace <filetype> with the actual filetype name, e.g. "python" gives
2485g:python_recommended_style.
2486
2487This lets the user turn recommended style settings off for all filetypes: >
2488
2489	let g:filetype_recommended_style = 0
2490
2491or for one filetype while leaving the rest enabled: >
2492
2493	let g:python_recommended_style = 0
2494
2495The filetype-specific variable takes precedence over the general one, so a
2496user can disable styling everywhere with g:filetype_recommended_style and
2497re-enable it for a single filetype by setting g:<filetype>_recommended_style
2498to 1 (or vice versa).
2499
2500Settings that are required for the language to work correctly (not merely
2501stylistic) should not be placed behind this guard.
2502
2503FILE NAME
2504
2505The filetype must be included in the file name |ftplugin-name|.  Use one of
2506these three forms:
2507
2508	.../ftplugin/stuff.vim
2509	.../ftplugin/stuff_foo.vim
2510	.../ftplugin/stuff/bar.vim
2511
2512"stuff" is the filetype, "foo" and "bar" are arbitrary names.
2513
2514
2515SUMMARY							*ftplugin-special*
2516
2517Summary of special things to use in a filetype plugin:
2518
2519<LocalLeader>		Value of "maplocalleader", which the user defines as
2520			the keys that filetype plugin mappings start with.
2521
2522:map <buffer>		Define a mapping local to the buffer.
2523
2524:noremap <script>	Only remap mappings defined in this script that start
2525			with <SID>.
2526
2527:setlocal		Set an option for the current buffer only.
2528
2529:command -buffer	Define a user command local to the buffer.
2530
2531exists("*s:Func")	Check if a function was already defined.
2532
2533Also see |plugin-special|, the special things used for all plugins.
2534
2535==============================================================================
2536*41.13*	Writing a compiler plugin		*write-compiler-plugin*
2537
2538A compiler plugin sets options for use with a specific compiler.  The user can
2539load it with the |:compiler| command.  The main use is to set the
2540'errorformat' and 'makeprg' options.
2541
2542Easiest is to have a look at examples.  This command will edit all the default
2543compiler plugins: >
2544
2545	:next $VIMRUNTIME/compiler/*.vim
2546
2547Use |:next| to go to the next plugin file.
2548
2549There are two special items about these files.  First is a mechanism to allow
2550a user to overrule or add to the default file.  The default files start with: >
2551
2552	:if exists("current_compiler")
2553	:  finish
2554	:endif
2555	:let current_compiler = "mine"
2556
2557When you write a compiler file and put it in your personal runtime directory
2558(e.g., ~/.config/nvim/compiler for Unix), you set the "current_compiler"
2559variable to make the default file skip the settings.
2560							*:CompilerSet*
2561The second mechanism is to use ":set" for ":compiler!" and ":setlocal" for
2562":compiler".  Vim defines the ":CompilerSet" user command for this.  This is
2563an example: >
2564
2565  CompilerSet errorformat&		" use the default 'errorformat'
2566  CompilerSet makeprg=nmake
2567
2568When you write a compiler plugin for the Vim distribution or for a system-wide
2569runtime directory, use the mechanism mentioned above.  When
2570"current_compiler" was already set by a user plugin nothing will be done.
2571
2572When you write a compiler plugin to overrule settings from a default plugin,
2573don't check "current_compiler".  This plugin is supposed to be loaded
2574last, thus it should be in a directory at the end of 'runtimepath'.  For Unix
2575that could be ~/.config/nvim/after/compiler.
2576
2577==============================================================================
2578*41.14*	Writing a plugin that loads quickly	*write-plugin-quickload*
2579
2580A plugin may grow and become quite long.  The startup delay may become
2581noticeable, while you hardly ever use the plugin.  Then it's time for a
2582quickload plugin.
2583
2584The basic idea is that the plugin is loaded twice.  The first time user
2585commands and mappings are defined that offer the functionality.  The second
2586time the functions that implement the functionality are defined.
2587
2588It may sound surprising that quickload means loading a script twice.  What we
2589mean is that it loads quickly the first time, postponing the bulk of the
2590script to the second time, which only happens when you actually use it.  When
2591you always use the functionality it actually gets slower!
2592
2593Note that since Vim 7 there is an alternative: use the |autoload|
2594functionality |41.15|.
2595
2596The following example shows how it's done: >
2597
2598	" Vim global plugin for demonstrating quick loading
2599	" Last Change:	2005 Feb 25
2600	" Maintainer:	Bram Moolenaar <Bram@vim.org>
2601	" License:	This file is placed in the public domain.
2602
2603	if !exists("s:did_load")
2604		command -nargs=* BNRead  call BufNetRead(<f-args>)
2605		map <F19> :call BufNetWrite('something')<CR>
2606
2607		let s:did_load = 1
2608		exe 'au FuncUndefined BufNet* source ' .. expand('<script>')
2609		finish
2610	endif
2611
2612	function BufNetRead(...)
2613		echo 'BufNetRead(' .. string(a:000) .. ')'
2614		" read functionality here
2615	endfunction
2616
2617	function BufNetWrite(...)
2618		echo 'BufNetWrite(' .. string(a:000) .. ')'
2619		" write functionality here
2620	endfunction
2621
2622When the script is first loaded "s:did_load" is not set.  The commands between
2623the "if" and "endif" will be executed.  This ends in a |:finish| command, thus
2624the rest of the script is not executed.
2625
2626The second time the script is loaded "s:did_load" exists and the commands
2627after the "endif" are executed.  This defines the (possible long)
2628BufNetRead() and BufNetWrite() functions.
2629
2630If you drop this script in your plugin directory Vim will execute it on
2631startup.  This is the sequence of events that happens:
2632
26331. The "BNRead" command is defined and the <F19> key is mapped when the script
2634   is sourced at startup.  A |FuncUndefined| autocommand is defined.  The
2635   ":finish" command causes the script to terminate early.
2636
26372. The user types the BNRead command or presses the <F19> key.  The
2638   BufNetRead() or BufNetWrite() function will be called.
2639
26403. Vim can't find the function and triggers the |FuncUndefined| autocommand
2641   event.  Since the pattern "BufNet*" matches the invoked function, the
2642   command "source fname" will be executed.  "fname" will be equal to the name
2643   of the script, no matter where it is located, because it comes from
2644   expanding "<script>" (see |expand()|).
2645
26464. The script is sourced again, the "s:did_load" variable exists and the
2647   functions are defined.
2648
2649Notice that the functions that are loaded afterwards match the pattern in the
2650|FuncUndefined| autocommand.  You must make sure that no other plugin defines
2651functions that match this pattern.
2652
2653==============================================================================
2654*41.15*	Writing library scripts			*write-library-script*
2655
2656Some functionality will be required in several places.  When this becomes more
2657than a few lines you will want to put it in one script and use it from many
2658scripts.  We will call that one script a library script.
2659
2660Manually loading a library script is possible, so long as you avoid loading it
2661when it's already done.  You can do this with the |exists()| function.
2662Example: >
2663
2664	if !exists('*MyLibFunction')
2665	   runtime library/mylibscript.vim
2666	endif
2667	call MyLibFunction(arg)
2668
2669Here you need to know that MyLibFunction() is defined in a script
2670"library/mylibscript.vim" in one of the directories in 'runtimepath'.
2671
2672To make this a bit simpler Vim offers the autoload mechanism.  Then the
2673example looks like this: >
2674
2675	call mylib#myfunction(arg)
2676
2677That's a lot simpler, isn't it?  Vim will recognize the function name and when
2678it's not defined search for the script "autoload/mylib.vim" in 'runtimepath'.
2679That script must define the "mylib#myfunction()" function.
2680
2681You can put many other functions in the mylib.vim script, you are free to
2682organize your functions in library scripts.  But you must use function names
2683where the part before the '#' matches the script name.  Otherwise Vim would
2684not know what script to load.
2685
2686If you get really enthusiastic and write lots of library scripts, you may
2687want to use subdirectories.  Example: >
2688
2689	call netlib#ftp#read('somefile')
2690
2691For Unix the library script used for this could be:
2692
2693	~/.config/nvim/autoload/netlib/ftp.vim
2694
2695Where the function is defined like this: >
2696
2697	function netlib#ftp#read(fname)
2698		"  Read the file fname through ftp
2699	endfunction
2700
2701Notice that the name the function is defined with is exactly the same as the
2702name used for calling the function.  And the part before the last '#'
2703exactly matches the subdirectory and script name.
2704
2705You can use the same mechanism for variables: >
2706
2707	let weekdays = dutch#weekdays
2708
2709This will load the script "autoload/dutch.vim", which should contain something
2710like: >
2711
2712	let dutch#weekdays = ['zondag', 'maandag', 'dinsdag', 'woensdag',
2713		\ 'donderdag', 'vrijdag', 'zaterdag']
2714
2715Further reading: |autoload|.
2716
2717==============================================================================
2718*41.16*	Distributing Vim scripts			*distribute-script*
2719
2720Vim users will look for scripts on the Vim website: https://www.vim.org.
2721If you made something that is useful for others, share it!
2722
2723Vim scripts can be used on any system.  There might not be a tar or gzip
2724command.  If you want to pack files together and/or compress them the "zip"
2725utility is recommended.
2726
2727==============================================================================
2728
2729Next chapter: |usr_42.txt|  Add new menus
2730
2731Copyright: see |manual-copyright|
2732
2733vim:tw=78:ts=8:noet:ft=help:norl: