neovim

Neovim text editor
git clone https://git.dasho.dev/neovim.git
Log | Files | Refs | README

usr_41.txt (93557B)


      1 *usr_41.txt*	Nvim
      2 
      3 
      4 	     VIM USER MANUAL	by Bram Moolenaar
      5 
      6 
      7 		      Write a Vim script
      8 
      9 
     10 The Vim script language is used for the startup vimrc file, syntax files, and
     11 many other things.  This chapter explains the items that can be used in a Vim
     12 script.  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
     33 Table of contents: |usr_toc.txt|
     34 
     35 ==============================================================================
     36 *41.1*	Introduction				*vimscript-intro*
     37 
     38 Your first experience with Vim scripts is the vimrc file.  Vim reads it when
     39 it starts up and executes the commands.  You can set options to values you
     40 prefer.  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
     43 specific file type.  A complicated macro can be defined by a separate Vim
     44 script 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 
     52 Let'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 
     69 The output of the example code is:
     70 
     71 count is 1 ~
     72 count is 2 ~
     73 count is 3 ~
     74 count is 4 ~
     75 
     76 In the first line the ":let" command assigns a value to a variable.  The
     77 generic form is: >
     78 
     79 :let {variable} = {expression}
     80 
     81 In this case the variable name is "i" and the expression is a simple value,
     82 the number one.
     83   The ":while" command starts a loop.  The generic form is: >
     84 
     85 :while {condition}
     86 :  {statements}
     87 :endwhile
     88 
     89 The statements until the matching ":endwhile" are executed for as long as the
     90 condition is true.  The condition used here is the expression "i < 5".  This
     91 is 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 
     96 The ":echo" command prints its arguments.  In this case the string "count is"
     97 and the value of the variable i.  Since i is one, this will print:
     98 
     99 count is 1 ~
    100 
    101 Then 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
    103 to the same variable.
    104 
    105 The example was given to explain the commands, but would you really want to
    106 make 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 
    112 We won't explain how |:for| and |range()| work until later.  Follow the links
    113 if you are impatient.
    114 
    115 
    116 FOUR KINDS OF NUMBERS
    117 
    118 Numbers can be decimal, hexadecimal, octal or binary.
    119 
    120 A hexadecimal number starts with "0x" or "0X".  For example "0x1f" is decimal
    121 31.
    122 
    123 An octal number starts with "0o", "0O" or a zero and another digit.  "0o17" is
    124 decimal 15.
    125 
    126 A binary number starts with "0b" or "0B".  For example "0b101" is decimal 5.
    127 
    128 A decimal number is just digits.  Careful: don't put a zero before a decimal
    129 number, it will be interpreted as an octal number!
    130 
    131 The ":echo" command always prints decimal numbers.  Example: >
    132 
    133 :echo 0x7f 0o36
    134 <	127 30 ~
    135 
    136 A number is made negative with a minus sign.  This also works for hexadecimal,
    137 octal and binary numbers.  A minus sign is also used for subtraction.  Compare
    138 this with the previous example: >
    139 
    140 :echo 0x7f -0o36
    141 <	97 ~
    142 
    143 White space in an expression is ignored.  However, it's recommended to use it
    144 for separating items, to make the expression easier to read.  For example, to
    145 avoid the confusion with a negative number above, put a space between the
    146 minus sign and the following number: >
    147 
    148 :echo 0x7f - 0o36
    149 
    150 ==============================================================================
    151 *41.2*	Variables
    152 
    153 A variable name consists of ASCII letters, digits and the underscore.  It
    154 cannot 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 
    162 Invalid names are "foo.bar" and "6var".
    163   These variables are global.  To see a list of currently defined variables
    164 use this command: >
    165 
    166 :let
    167 
    168 You can use global variables everywhere.  This also means that when the
    169 variable "count" is used in one script file, it might also be used in another
    170 file.  This leads to confusion at least, and real problems at worst.  To avoid
    171 this, you can use a variable local to a script file by prepending "s:".  For
    172 example, 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 
    180 Since "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
    183 about script-local variables here: |script-variable|.
    184 
    185 There are more kinds of variables, see |internal-variables|.  The most often
    186 used 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 
    194 DELETING VARIABLES
    195 
    196 Variables take up memory and show up in the output of the ":let" command.  To
    197 delete a variable use the ":unlet" command.  Example: >
    198 
    199 :unlet s:count
    200 
    201 This deletes the script-local variable "s:count" to free up the memory it
    202 uses.  If you are not sure if the variable exists, and don't want an error
    203 message when it doesn't, append !: >
    204 
    205 :unlet! s:count
    206 
    207 When a script has been processed to the end, the local variables declared
    208 there will not be deleted.  Functions defined in the script can use them.
    209 Example:
    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 
    217 The "exists()" function checks if a variable has already been defined.  Its
    218 argument is the name of the variable you want to check.  Not the variable
    219 itself!  If you would do this: >
    220 
    221 :if !exists(s:call_count)
    222 
    223 Then the value of s:call_count will be used as the name of the variable that
    224 exists() checks.  That's not what you want.
    225   The exclamation mark ! negates a value.  When the value was true, it
    226 becomes false.  When it was false, it becomes true.  You can read it as "not".
    227 Thus "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 
    237 STRING VARIABLES AND CONSTANTS
    238 
    239 So far only numbers were used for the variable value.  Strings can be used as
    240 well.  Numbers and strings are the basic types of variables that Vim supports.
    241 The type is dynamic, it is set each time when assigning a value to the
    242 variable with ":let".  More about types in |41.8|.
    243   To assign a string value to a variable, you need to use a string constant.
    244 There are two types of these.  First the string in double quotes: >
    245 
    246 :let name = "peter"
    247 :echo name
    248 <	peter ~
    249 
    250 If you want to include a double quote inside the string, put a backslash in
    251 front of it: >
    252 
    253 :let name = "\"peter\""
    254 :echo name
    255 <	"peter" ~
    256 
    257 To 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 
    263 Inside a single-quote string all the characters are as they are.  Only the
    264 single quote itself is special: you need to use two to get one.  A backslash
    265 is taken literally, thus you can't use it to change the meaning of the
    266 character after it.
    267   In double-quote strings it is possible to use special characters.  Here are
    268 a 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 
    280 The last two are just examples.  The  "\<name>" form can be used to include
    281 the special key "name".
    282   See |expr-quote| for the full list of special items in a string.
    283 
    284 ==============================================================================
    285 *41.3*	Expressions
    286 
    287 Vim has a rich, yet simple way to handle expressions.  You can read the
    288 definition here: |expression-syntax|.  Here we will show the most common
    289 items.
    290   The numbers, strings and variables mentioned above are expressions by
    291 themselves.  Thus everywhere an expression is expected, you can use a number,
    292 string or variable.  Other basic items in an expression are:
    293 
    294 $NAME		environment variable
    295 &name		option
    296 @r		register
    297 
    298 Examples: >
    299 
    300 :echo "The value of 'tabstop' is" &ts
    301 :echo "Your home directory is" $HOME
    302 :if @a > 5
    303 
    304 The &name form can be used to save an option value, set it to a new value,
    305 do 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 
    312 This makes sure the "The Start" pattern is used with the 'ignorecase' option
    313 off.  Still, it keeps the value that the user had set.  (Another way to do
    314 this would be to add "\C" to the pattern, see |/\C|.)
    315 
    316 
    317 MATHEMATICS
    318 
    319 It becomes more interesting if we combine these basic items.  Let's start with
    320 mathematics on numbers:
    321 
    322 a + b		add
    323 a - b		subtract
    324 a * b		multiply
    325 a / b		divide
    326 a % b		modulo
    327 
    328 The usual precedence is used.  Example: >
    329 
    330 :echo 10 + 5 * 2
    331 <	20 ~
    332 
    333 Grouping is done with parentheses.  No surprises here.  Example: >
    334 
    335 :echo (10 + 5) * 2
    336 <	30 ~
    337 
    338 Strings can be concatenated with ".." (see |expr6|).  Example: >
    339 
    340 :echo "foo" .. "bar"
    341 <	foobar ~
    342 
    343 When the ":echo" command gets multiple arguments, it separates them with a
    344 space.  In the example the argument is a single expression, thus no space is
    345 inserted.
    346 
    347 Borrowed from the C language is the conditional expression:
    348 
    349 a ? b : c
    350 
    351 If "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 
    357 The three parts of the constructs are always evaluated first, thus you could
    358 see it work as:
    359 
    360 (a) ? (b) : (c)
    361 
    362 ==============================================================================
    363 *41.4*	Conditionals
    364 
    365 The ":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 
    372 Only when the expression {condition} evaluates to true (non-zero) will the
    373 {statements} be executed.  These must still be valid commands.  If they
    374 contain 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 
    383 The 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 
    392 This works just like using ":else" and then "if", but without the need for an
    393 extra ":endif".
    394   A useful example for your vimrc file is checking the 'term' option and
    395 doing 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 
    406 LOGIC OPERATIONS
    407 
    408 We already used some of them in the examples.  These are the most often used
    409 ones:
    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 
    418 The 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 
    426 Here "v:version" is a variable defined by Vim, which has the value of the Vim
    427 version.  600 is for version 6.0.  Version 6.1 has the value 601.  This is
    428 very useful to write a script that works with multiple versions of Vim.
    429 |v:version|
    430 
    431 The logic operators work both for numbers and strings.  When comparing two
    432 strings, the mathematical difference is used.  This compares byte values,
    433 which may not be right for some languages.
    434   When comparing a string with a number, the string is first converted to a
    435 number.  This is a bit tricky, because when a string doesn't look like a
    436 number, the number zero is used.  Example: >
    437 
    438 :if 0 == "one"
    439 :  echo "yes"
    440 :endif
    441 
    442 This will echo "yes", because "one" doesn't look like a number, thus it is
    443 converted to the number zero.
    444 
    445 For strings there are two more items:
    446 
    447 a =~ b		matches with
    448 a !~ b		does not match with
    449 
    450 The left item "a" is used as a string.  The right item "b" is used as a
    451 pattern, 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 
    460 Notice the use of a single-quote string for the pattern.  This is useful,
    461 because backslashes would need to be doubled in a double-quote string and
    462 patterns tend to contain many backslashes.
    463 
    464 The 'ignorecase' option is used when comparing strings.  When you don't want
    465 that, append "#" to match case and "?" to ignore case.  Thus "==?" compares
    466 two strings to be equal while ignoring case.  And "!~#" checks if a pattern
    467 doesn't match, also checking the case of letters.  For the full table see
    468 |expr-==|.
    469 
    470 
    471 MORE LOOPING
    472 
    473 The ":while" command was already mentioned.  Two more statements can be used
    474 in 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 
    481 Example: >
    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 
    494 The ":sleep" command makes Vim take a nap.  The "50m" specifies fifty
    495 milliseconds.  Another example is ":sleep 4", which sleeps for four seconds.
    496 
    497 Even more looping can be done with the ":for" command, see below in |41.8|.
    498 
    499 ==============================================================================
    500 *41.5*	Executing an expression
    501 
    502 So 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
    504 very 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 
    509 The ".." 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
    511 will be executed is: >
    512 
    513 :tag get_cmd
    514 
    515 The ":execute" command can only execute colon commands.  The ":normal" command
    516 executes Normal mode commands.  However, its argument is not an expression but
    517 the literal command characters.  Example: >
    518 
    519 :normal gg=G
    520 
    521 This jumps to the first line and formats all lines with the "=" operator.
    522   To make ":normal" work with an expression, combine ":execute" with it.
    523 Example: >
    524 
    525 :execute "normal " .. normal_commands
    526 
    527 The variable "normal_commands" must contain the Normal mode commands.
    528   Make sure that the argument for ":normal" is a complete command.  Otherwise
    529 Vim will run into the end of the argument and abort the command.  For example,
    530 if you start Insert mode, you must leave Insert mode as well.  This works: >
    531 
    532 :execute "normal Inew text \<Esc>"
    533 
    534 This inserts "new text " in the current line.  Notice the use of the special
    535 key "\<Esc>".  This avoids having to enter a real <Esc> character in your
    536 script.
    537 
    538 If you don't want to execute a string but evaluate it to get its expression
    539 value, you can use the eval() function: >
    540 
    541 :let optname = "path"
    542 :let optval = eval('&' .. optname)
    543 
    544 A "&" 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 
    552 Vim defines many functions and provides a large amount of functionality that
    553 way.  A few examples will be given in this section.  You can find the whole
    554 list below: |function-list|.
    555 
    556 A function is called with the ":call" command.  The parameters are passed in
    557 between parentheses separated by commas.  Example: >
    558 
    559 :call search("Date: ", "W")
    560 
    561 This calls the search() function, with arguments "Date: " and "W".  The
    562 search() function uses its first argument as a search pattern and the second
    563 one as flags.  The "W" flag means the search doesn't wrap around the end of
    564 the file.
    565 
    566 A 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 
    572 The getline() function obtains a line from the current buffer.  Its argument
    573 is a specification of the line number.  In this case "." is used, which means
    574 the line where the cursor is.
    575   The substitute() function does something similar to the ":substitute"
    576 command.  The first argument is the string on which to perform the
    577 substitution.  The second argument is the pattern, the third the replacement
    578 string.  Finally, the last arguments are the flags.
    579   The setline() function sets the line, specified by the first argument, to a
    580 new string, the second argument.  In this example the line under the cursor is
    581 replaced with the result of the substitute().  Thus the effect of the three
    582 statements is equal to: >
    583 
    584 :substitute/\a/*/g
    585 
    586 Using the functions becomes interesting when you do more work before and
    587 after the substitute() call.
    588 
    589 
    590 FUNCTIONS						*function-list*
    591 
    592 There are many functions.  We will mention them here, grouped by what they are
    593 used for.  You can find an alphabetical list here: |vimscript-functions|.
    594 Use CTRL-] on the function name to jump to detailed help on it.
    595 
    596 String 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 
    658 List 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 
    694 Dictionary 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 
    716 Floating 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 
    742 Blob 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 
    750 Other 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 
    759 Variables:						*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 
    774 Cursor 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 
    802 Working 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 
    822 Working 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*
    830 System 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 
    869 Date 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*
    879 Buffers, 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 
    916 Command 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 
    936 Quickfix 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 
    942 Insert 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 
    951 Folding:					*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 
    958 Syntax 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 
    979 Spelling:					*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 
    984 History:					*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 
    990 Interactive:					*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 getcharmod()		get modifiers for the last typed character
    996 getmousepos()		get last known mouse position
    997 feedkeys()		put characters in the typeahead queue
    998 input()			get a line from the user
    999 inputlist()		let the user pick an entry from a list
   1000 inputsecret()		get a line from the user without showing it
   1001 inputdialog()		get a line from the user in a dialog
   1002 inputsave()		save and clear typeahead
   1003 inputrestore()		restore typeahead
   1004 
   1005 GUI:						*gui-functions*
   1006 getfontname()		get name of current font being used
   1007 getwinpos()		position of the Vim window
   1008 getwinposx()		X position of the Vim window
   1009 getwinposy()		Y position of the Vim window
   1010 balloon_show()		set the balloon content
   1011 balloon_split()		split a message for a balloon
   1012 balloon_gettext()	get the text in the balloon
   1013 
   1014 Vim server:					*server-functions*
   1015 serverlist()		return the list of server names
   1016 remote_startserver()	run a server
   1017 remote_send()		send command characters to a Vim server
   1018 remote_expr()		evaluate an expression in a Vim server
   1019 server2client()		send a reply to a client of a Vim server
   1020 remote_peek()		check if there is a reply from a Vim server
   1021 remote_read()		read a reply from a Vim server
   1022 foreground()		move the Vim window to the foreground
   1023 remote_foreground()	move the Vim server window to the foreground
   1024 
   1025 Window size and position:			*window-size-functions*
   1026 winheight()		get height of a specific window
   1027 winwidth()		get width of a specific window
   1028 win_screenpos()		get screen position of a window
   1029 winlayout()		get layout of windows in a tab page
   1030 winrestcmd()		return command to restore window sizes
   1031 winsaveview()		get view of current window
   1032 winrestview()		restore saved view of current window
   1033 
   1034 Mappings and Menus:			    *mapping-functions*
   1035 digraph_get()		get |digraph|
   1036 digraph_getlist()	get all |digraph|s
   1037 digraph_set()		register |digraph|
   1038 digraph_setlist()	register multiple |digraph|s
   1039 hasmapto()		check if a mapping exists
   1040 mapcheck()		check if a matching mapping exists
   1041 maparg()		get rhs of a mapping
   1042 maplist()		get list of all mappings
   1043 mapset()		restore a mapping
   1044 menu_info()		get information about a menu item
   1045 wildmenumode()		check if the wildmode is active
   1046 wildtrigger()		start wildcard expansion
   1047 
   1048 Signs:						*sign-functions*
   1049 sign_define()		define or update a sign
   1050 sign_getdefined()	get a list of defined signs
   1051 sign_getplaced()	get a list of placed signs
   1052 sign_jump()		jump to a sign
   1053 sign_place()		place a sign
   1054 sign_placelist()	place a list of signs
   1055 sign_undefine()		undefine a sign
   1056 sign_unplace()		unplace a sign
   1057 sign_unplacelist()	unplace a list of signs
   1058 
   1059 Testing:				    *test-functions*
   1060 assert_equal()		assert that two expressions values are equal
   1061 assert_equalfile()	assert that two file contents are equal
   1062 assert_notequal()	assert that two expressions values are not
   1063 			equal
   1064 assert_inrange()	assert that an expression is inside a range
   1065 assert_match()		assert that a pattern matches the value
   1066 assert_notmatch()	assert that a pattern does not match the value
   1067 assert_false()		assert that an expression is false
   1068 assert_true()		assert that an expression is true
   1069 assert_exception()	assert that a command throws an exception
   1070 assert_beeps()		assert that a command beeps
   1071 assert_nobeep()		assert that a command does not cause a beep
   1072 assert_fails()		assert that a command fails
   1073 assert_report()		report a test failure
   1074 
   1075 Timers:						*timer-functions*
   1076 timer_start()		create a timer
   1077 timer_pause()		pause or unpause a timer
   1078 timer_stop()		stop a timer
   1079 timer_stopall()		stop all timers
   1080 timer_info()		get information about timers
   1081 wait()			wait for a condition
   1082 
   1083 Tags:						*tag-functions*
   1084 taglist()		get list of matching tags
   1085 tagfiles()		get a list of tags files
   1086 gettagstack()		get the tag stack of a window
   1087 settagstack()		modify the tag stack of a window
   1088 
   1089 Prompt Buffer:					*promptbuffer-functions*
   1090 prompt_getprompt()	get the effective prompt text for a buffer
   1091 prompt_setcallback()	set prompt callback for a buffer
   1092 prompt_setinterrupt()	set interrupt callback for a buffer
   1093 prompt_setprompt()	set the prompt text for a buffer
   1094 
   1095 Registers:					*register-functions*
   1096 getreg()		get contents of a register
   1097 getreginfo()		get information about a register
   1098 getregtype()		get type of a register
   1099 setreg()		set contents and type of a register
   1100 reg_executing()		return the name of the register being executed
   1101 reg_recording()		return the name of the register being recorded
   1102 
   1103 Context Stack:					*ctx-functions*
   1104 ctxget()		return context at given index from top
   1105 ctxpop()		pop and restore top context
   1106 ctxpush()		push given context
   1107 ctxset()		set context at given index from top
   1108 ctxsize()		return context stack size
   1109 
   1110 Various:					*various-functions*
   1111 mode()			get current editing mode
   1112 visualmode()		last visual mode used
   1113 exists()		check if a variable, function, etc. exists
   1114 has()			check if a feature is supported in Vim
   1115 changenr()		return number of most recent change
   1116 did_filetype()		check if a FileType autocommand was used
   1117 eventhandler()		check if invoked by an event handler
   1118 getpid()		get process ID of Vim
   1119 getscriptinfo()		get list of sourced Vim scripts
   1120 getstacktrace()		get current stack trace of Vim scripts
   1121 
   1122 libcall()		call a function in an external library
   1123 libcallnr()		idem, returning a number
   1124 
   1125 undofile()		get the name of the undo file
   1126 undotree()		return the state of the undo tree for a buffer
   1127 
   1128 shiftwidth()		effective value of 'shiftwidth'
   1129 
   1130 wordcount()		get byte/word/char count of buffer
   1131 
   1132 luaeval()		evaluate |Lua| expression
   1133 py3eval()		evaluate |Python| expression
   1134 pyeval()		evaluate |Python| expression
   1135 pyxeval()		evaluate |python_x| expression
   1136 rubyeval()		evaluate |Ruby| expression
   1137 
   1138 debugbreak()		interrupt a program being debugged
   1139 
   1140 ==============================================================================
   1141 *41.7*	Defining a function
   1142 
   1143 Vim enables you to define your own functions.  The basic function declaration
   1144 begins as follows: >
   1145 
   1146 :function {name}({var1}, {var2}, ...)
   1147 :  {body}
   1148 :endfunction
   1149 <
   1150 Note:
   1151 Function names must begin with a capital letter.
   1152 
   1153 Let's define a short function to return the smaller of two numbers.  It starts
   1154 with this line: >
   1155 
   1156 :function Min(num1, num2)
   1157 
   1158 This tells Vim that the function is named "Min" and it takes two arguments:
   1159 "num1" and "num2".
   1160   The first thing you need to do is to check to see which number is smaller:
   1161   >
   1162 :  if a:num1 < a:num2
   1163 
   1164 The special prefix "a:" tells Vim that the variable is a function argument.
   1165 Let's assign the variable "smaller" the value of the smallest number: >
   1166 
   1167 :  if a:num1 < a:num2
   1168 :    let smaller = a:num1
   1169 :  else
   1170 :    let smaller = a:num2
   1171 :  endif
   1172 
   1173 The variable "smaller" is a local variable.  Variables used inside a function
   1174 are local unless prefixed by something like "g:", "a:", or "s:".
   1175 
   1176 Note:
   1177 To access a global variable from inside a function you must prepend
   1178 "g:" to it.  Thus "g:today" inside a function is used for the global
   1179 variable "today", and "today" is another variable, local to the
   1180 function.
   1181 
   1182 You now use the ":return" statement to return the smallest number to the user.
   1183 Finally, you end the function: >
   1184 
   1185 :  return smaller
   1186 :endfunction
   1187 
   1188 The complete function definition is as follows: >
   1189 
   1190 :function Min(num1, num2)
   1191 :  if a:num1 < a:num2
   1192 :    let smaller = a:num1
   1193 :  else
   1194 :    let smaller = a:num2
   1195 :  endif
   1196 :  return smaller
   1197 :endfunction
   1198 
   1199 For people who like short functions, this does the same thing: >
   1200 
   1201 :function Min(num1, num2)
   1202 :  if a:num1 < a:num2
   1203 :    return a:num1
   1204 :  endif
   1205 :  return a:num2
   1206 :endfunction
   1207 
   1208 A user defined function is called in exactly the same way as a built-in
   1209 function.  Only the name is different.  The Min function can be used like
   1210 this: >
   1211 
   1212 :echo Min(5, 8)
   1213 
   1214 Only now will the function be executed and the lines be interpreted by Vim.
   1215 If there are mistakes, like using an undefined variable or function, you will
   1216 now get an error message.  When defining the function these errors are not
   1217 detected.
   1218 
   1219 When a function reaches ":endfunction" or ":return" is used without an
   1220 argument, the function returns zero.
   1221 
   1222 To redefine a function that already exists, use the ! for the ":function"
   1223 command: >
   1224 
   1225 :function!  Min(num1, num2, num3)
   1226 
   1227 
   1228 USING A RANGE
   1229 
   1230 The ":call" command can be given a line range.  This can have one of two
   1231 meanings.  When a function has been defined with the "range" keyword, it will
   1232 take care of the line range itself.
   1233  The function will be passed the variables "a:firstline" and "a:lastline".
   1234 These will have the line numbers from the range the function was called with.
   1235 Example: >
   1236 
   1237 :function Count_words() range
   1238 :  let lnum = a:firstline
   1239 :  let n = 0
   1240 :  while lnum <= a:lastline
   1241 :    let n = n + len(split(getline(lnum)))
   1242 :    let lnum = lnum + 1
   1243 :  endwhile
   1244 :  echo "found " .. n .. " words"
   1245 :endfunction
   1246 
   1247 You can call this function with: >
   1248 
   1249 :10,30call Count_words()
   1250 
   1251 It will be executed once and echo the number of words.
   1252   The other way to use a line range is by defining a function without the
   1253 "range" keyword.  The function will be called once for every line in the
   1254 range, with the cursor in that line.  Example: >
   1255 
   1256 :function  Number()
   1257 :  echo "line " .. line(".") .. " contains: " .. getline(".")
   1258 :endfunction
   1259 
   1260 If you call this function with: >
   1261 
   1262 :10,15call Number()
   1263 
   1264 The function will be called six times.
   1265 
   1266 
   1267 VARIABLE NUMBER OF ARGUMENTS
   1268 
   1269 Vim enables you to define functions that have a variable number of arguments.
   1270 The following command, for instance, defines a function that must have 1
   1271 argument (start) and can have up to 20 additional arguments: >
   1272 
   1273 :function Show(start, ...)
   1274 
   1275 The variable "a:1" contains the first optional argument, "a:2" the second, and
   1276 so on.  The variable "a:0" contains the number of extra arguments.
   1277   For example: >
   1278 
   1279 :function Show(start, ...)
   1280 :  echohl Title
   1281 :  echo "start is " .. a:start
   1282 :  echohl None
   1283 :  let index = 1
   1284 :  while index <= a:0
   1285 :    echo "  Arg " .. index .. " is " .. a:{index}
   1286 :    let index = index + 1
   1287 :  endwhile
   1288 :  echo ""
   1289 :endfunction
   1290 
   1291 This uses the ":echohl" command to specify the highlighting used for the
   1292 following ":echo" command.  ":echohl None" stops it again.  The ":echon"
   1293 command works like ":echo", but doesn't output a line break.
   1294 
   1295 You can also use the a:000 variable, it is a List of all the "..." arguments.
   1296 See |a:000|.
   1297 
   1298 
   1299 LISTING FUNCTIONS
   1300 
   1301 The ":function" command lists the names and arguments of all user-defined
   1302 functions: >
   1303 
   1304 :function
   1305 <	function Show(start, ...) ~
   1306 function GetVimIndent() ~
   1307 function SetSyn(name) ~
   1308 
   1309 To see what a function does, use its name as an argument for ":function": >
   1310 
   1311 :function SetSyn
   1312 <	1     if &syntax == '' ~
   1313 2       let &syntax = a:name ~
   1314 3     endif ~
   1315    endfunction ~
   1316 
   1317 
   1318 DEBUGGING
   1319 
   1320 The line number is useful for when you get an error message or when debugging.
   1321 See |debug-scripts| about debugging mode.
   1322   You can also set the 'verbose' option to 12 or higher to see all function
   1323 calls.  Set it to 15 or higher to see every executed line.
   1324 
   1325 
   1326 DELETING A FUNCTION
   1327 
   1328 To delete the Show() function: >
   1329 
   1330 :delfunction Show
   1331 
   1332 You get an error when the function doesn't exist.
   1333 
   1334 
   1335 FUNCTION REFERENCES
   1336 
   1337 Sometimes it can be useful to have a variable point to one function or
   1338 another.  You can do it with the function() function.  It turns the name of a
   1339 function into a reference: >
   1340 
   1341 :let result = 0		" or 1
   1342 :function! Right()
   1343 :  return 'Right!'
   1344 :endfunc
   1345 :function! Wrong()
   1346 :  return 'Wrong!'
   1347 :endfunc
   1348 :
   1349 :if result == 1
   1350 :  let Afunc = function('Right')
   1351 :else
   1352 :  let Afunc = function('Wrong')
   1353 :endif
   1354 :echo call(Afunc, [])
   1355 <	Wrong! ~
   1356 
   1357 Note that the name of a variable that holds a function reference must start
   1358 with a capital.  Otherwise it could be confused with the name of a builtin
   1359 function.
   1360   The way to invoke a function that a variable refers to is with the call()
   1361 function.  Its first argument is the function reference, the second argument
   1362 is a List with arguments.
   1363 
   1364 Function references are most useful in combination with a Dictionary, as is
   1365 explained in the next section.
   1366 
   1367 More information about defining your own functions here: |user-function|.
   1368 
   1369 ==============================================================================
   1370 *41.8*	Lists and Dictionaries
   1371 
   1372 So far we have used the basic types String and Number.  Vim also supports two
   1373 composite types: List and Dictionary.
   1374 
   1375 A List is an ordered sequence of things.  The things can be any kind of value,
   1376 thus you can make a List of numbers, a List of Lists and even a List of mixed
   1377 items.  To create a List with three strings: >
   1378 
   1379 :let alist = ['aap', 'mies', 'noot']
   1380 
   1381 The List items are enclosed in square brackets and separated by commas.  To
   1382 create an empty List: >
   1383 
   1384 :let alist = []
   1385 
   1386 You can add items to a List with the add() function: >
   1387 
   1388 :let alist = []
   1389 :call add(alist, 'foo')
   1390 :call add(alist, 'bar')
   1391 :echo alist
   1392 <	['foo', 'bar'] ~
   1393 
   1394 List concatenation is done with +: >
   1395 
   1396 :echo alist + ['foo', 'bar']
   1397 <	['foo', 'bar', 'foo', 'bar'] ~
   1398 
   1399 Or, if you want to extend a List directly: >
   1400 
   1401 :let alist = ['one']
   1402 :call extend(alist, ['two', 'three'])
   1403 :echo alist
   1404 <	['one', 'two', 'three'] ~
   1405 
   1406 Notice that using add() will have a different effect: >
   1407 
   1408 :let alist = ['one']
   1409 :call add(alist, ['two', 'three'])
   1410 :echo alist
   1411 <	['one', ['two', 'three']] ~
   1412 
   1413 The second argument of add() is added as a single item.
   1414 
   1415 
   1416 FOR LOOP
   1417 
   1418 One of the nice things you can do with a List is iterate over it: >
   1419 
   1420 :let alist = ['one', 'two', 'three']
   1421 :for n in alist
   1422 :  echo n
   1423 :endfor
   1424 <	one ~
   1425 two ~
   1426 three ~
   1427 
   1428 This will loop over each element in List "alist", assigning the value to
   1429 variable "n".  The generic form of a for loop is: >
   1430 
   1431 :for {varname} in {listexpression}
   1432 :  {commands}
   1433 :endfor
   1434 
   1435 To loop a certain number of times you need a List of a specific length.  The
   1436 range() function creates one for you: >
   1437 
   1438 :for a in range(3)
   1439 :  echo a
   1440 :endfor
   1441 <	0 ~
   1442 1 ~
   1443 2 ~
   1444 
   1445 Notice that the first item of the List that range() produces is zero, thus the
   1446 last item is one less than the length of the list.
   1447   You can also specify the maximum value, the stride and even go backwards: >
   1448 
   1449 :for a in range(8, 4, -2)
   1450 :  echo a
   1451 :endfor
   1452 <	8 ~
   1453 6 ~
   1454 4 ~
   1455 
   1456 A more useful example, looping over lines in the buffer: >
   1457 
   1458 :for line in getline(1, 20)
   1459 :  if line =~ "Date: "
   1460 :    echo matchstr(line, 'Date: \zs.*')
   1461 :  endif
   1462 :endfor
   1463 
   1464 This looks into lines 1 to 20 (inclusive) and echoes any date found in there.
   1465 
   1466 
   1467 DICTIONARIES
   1468 
   1469 A Dictionary stores key-value pairs.  You can quickly lookup a value if you
   1470 know the key.  A Dictionary is created with curly braces: >
   1471 
   1472 :let uk2nl = {'one': 'een', 'two': 'twee', 'three': 'drie'}
   1473 
   1474 Now you can lookup words by putting the key in square brackets: >
   1475 
   1476 :echo uk2nl['two']
   1477 <	twee ~
   1478 
   1479 The generic form for defining a Dictionary is: >
   1480 
   1481 {<key> : <value>, ...}
   1482 
   1483 An empty Dictionary is one without any keys: >
   1484 
   1485 {}
   1486 
   1487 The possibilities with Dictionaries are numerous.  There are various functions
   1488 for them as well.  For example, you can obtain a list of the keys and loop
   1489 over them: >
   1490 
   1491 :for key in keys(uk2nl)
   1492 :  echo key
   1493 :endfor
   1494 <	three ~
   1495 one ~
   1496 two ~
   1497 
   1498 You will notice the keys are not ordered.  You can sort the list to get a
   1499 specific order: >
   1500 
   1501 :for key in sort(keys(uk2nl))
   1502 :  echo key
   1503 :endfor
   1504 <	one ~
   1505 three ~
   1506 two ~
   1507 
   1508 But you can never get back the order in which items are defined.  For that you
   1509 need to use a List, it stores items in an ordered sequence.
   1510 
   1511 
   1512 DICTIONARY FUNCTIONS
   1513 
   1514 The items in a Dictionary can normally be obtained with an index in square
   1515 brackets: >
   1516 
   1517 :echo uk2nl['one']
   1518 <	een ~
   1519 
   1520 A method that does the same, but without so many punctuation characters: >
   1521 
   1522 :echo uk2nl.one
   1523 <	een ~
   1524 
   1525 This only works for a key that is made of ASCII letters, digits and the
   1526 underscore.  You can also assign a new value this way: >
   1527 
   1528 :let uk2nl.four = 'vier'
   1529 :echo uk2nl
   1530 <	{'three': 'drie', 'four': 'vier', 'one': 'een', 'two': 'twee'} ~
   1531 
   1532 And now for something special: you can directly define a function and store a
   1533 reference to it in the dictionary: >
   1534 
   1535 :function uk2nl.translate(line) dict
   1536 :  return join(map(split(a:line), 'get(self, v:val, "???")'))
   1537 :endfunction
   1538 
   1539 Let's first try it out: >
   1540 
   1541 :echo uk2nl.translate('three two five one')
   1542 <	drie twee ??? een ~
   1543 
   1544 The first special thing you notice is the "dict" at the end of the ":function"
   1545 line.  This marks the function as being used from a Dictionary.  The "self"
   1546 local variable will then refer to that Dictionary.
   1547   Now let's break up the complicated return command: >
   1548 
   1549 split(a:line)
   1550 
   1551 The split() function takes a string, chops it into whitespace separated words
   1552 and returns a list with these words.  Thus in the example it returns: >
   1553 
   1554 :echo split('three two five one')
   1555 <	['three', 'two', 'five', 'one'] ~
   1556 
   1557 This list is the first argument to the map() function.  This will go through
   1558 the list, evaluating its second argument with "v:val" set to the value of each
   1559 item.  This is a shortcut to using a for loop.  This command: >
   1560 
   1561 :let alist = map(split(a:line), 'get(self, v:val, "???")')
   1562 
   1563 Is equivalent to: >
   1564 
   1565 :let alist = split(a:line)
   1566 :for idx in range(len(alist))
   1567 :  let alist[idx] = get(self, alist[idx], "???")
   1568 :endfor
   1569 
   1570 The get() function checks if a key is present in a Dictionary.  If it is, then
   1571 the value is retrieved.  If it isn't, then the default value is returned, in
   1572 the example it's '???'.  This is a convenient way to handle situations where a
   1573 key may not be present and you don't want an error message.
   1574 
   1575 The join() function does the opposite of split(): it joins together a list of
   1576 words, putting a space in between.
   1577  This combination of split(), map() and join() is a nice way to filter a line
   1578 of words in a very compact way.
   1579 
   1580 
   1581 OBJECT ORIENTED PROGRAMMING
   1582 
   1583 Now that you can put both values and functions in a Dictionary, you can
   1584 actually use a Dictionary like an object.
   1585   Above we used a Dictionary for translating Dutch to English.  We might want
   1586 to do the same for other languages.  Let's first make an object (aka
   1587 Dictionary) that has the translate function, but no words to translate: >
   1588 
   1589 :let transdict = {}
   1590 :function transdict.translate(line) dict
   1591 :  return join(map(split(a:line), 'get(self.words, v:val, "???")'))
   1592 :endfunction
   1593 
   1594 It's slightly different from the function above, using 'self.words' to lookup
   1595 word translations.  But we don't have a self.words.  Thus you could call this
   1596 an abstract class.
   1597 
   1598 Now we can instantiate a Dutch translation object: >
   1599 
   1600 :let uk2nl = copy(transdict)
   1601 :let uk2nl.words = {'one': 'een', 'two': 'twee', 'three': 'drie'}
   1602 :echo uk2nl.translate('three one')
   1603 <	drie een ~
   1604 
   1605 And a German translator: >
   1606 
   1607 :let uk2de = copy(transdict)
   1608 :let uk2de.words = {'one': 'eins', 'two': 'zwei', 'three': 'drei'}
   1609 :echo uk2de.translate('three one')
   1610 <	drei eins ~
   1611 
   1612 You see that the copy() function is used to make a copy of the "transdict"
   1613 Dictionary and then the copy is changed to add the words.  The original
   1614 remains the same, of course.
   1615 
   1616 Now you can go one step further, and use your preferred translator: >
   1617 
   1618 :if $LANG =~ "de"
   1619 :  let trans = uk2de
   1620 :else
   1621 :  let trans = uk2nl
   1622 :endif
   1623 :echo trans.translate('one two three')
   1624 <	een twee drie ~
   1625 
   1626 Here "trans" refers to one of the two objects (Dictionaries).  No copy is
   1627 made.  More about List and Dictionary identity can be found at |list-identity|
   1628 and |dict-identity|.
   1629 
   1630 Now you might use a language that isn't supported.  You can overrule the
   1631 translate() function to do nothing: >
   1632 
   1633 :let uk2uk = copy(transdict)
   1634 :function! uk2uk.translate(line)
   1635 :  return a:line
   1636 :endfunction
   1637 :echo uk2uk.translate('three one wladiwostok')
   1638 <	three one wladiwostok ~
   1639 
   1640 Notice that a ! was used to overwrite the existing function reference.  Now
   1641 use "uk2uk" when no recognized language is found: >
   1642 
   1643 :if $LANG =~ "de"
   1644 :  let trans = uk2de
   1645 :elseif $LANG =~ "nl"
   1646 :  let trans = uk2nl
   1647 :else
   1648 :  let trans = uk2uk
   1649 :endif
   1650 :echo trans.translate('one two three')
   1651 <	one two three ~
   1652 
   1653 For further reading see |Lists| and |Dictionaries|.
   1654 
   1655 ==============================================================================
   1656 *41.9*	Exceptions
   1657 
   1658 Let's start with an example: >
   1659 
   1660 :try
   1661 :   read ~/templates/pascal.tmpl
   1662 :catch /E484:/
   1663 :   echo "Sorry, the Pascal template file cannot be found."
   1664 :endtry
   1665 
   1666 The ":read" command will fail if the file does not exist.  Instead of
   1667 generating an error message, this code catches the error and gives the user a
   1668 nice message.
   1669 
   1670 For the commands in between ":try" and ":endtry" errors are turned into
   1671 exceptions.  An exception is a string.  In the case of an error the string
   1672 contains the error message.  And every error message has a number.  In this
   1673 case, the error we catch contains "E484:".  This number is guaranteed to stay
   1674 the same (the text may change, e.g., it may be translated).
   1675 
   1676 When the ":read" command causes another error, the pattern "E484:" will not
   1677 match in it.  Thus this exception will not be caught and result in the usual
   1678 error message and execution is aborted.
   1679 
   1680 You might be tempted to do this: >
   1681 
   1682 :try
   1683 :   read ~/templates/pascal.tmpl
   1684 :catch
   1685 :   echo "Sorry, the Pascal template file cannot be found."
   1686 :endtry
   1687 
   1688 This means all errors are caught.  But then you will not see errors that are
   1689 useful, such as "E21: Cannot make changes, 'modifiable' is off".
   1690 
   1691 Another useful mechanism is the ":finally" command: >
   1692 
   1693 :let tmp = tempname()
   1694 :try
   1695 :   exe ".,$write " .. tmp
   1696 :   exe "!filter " .. tmp
   1697 :   .,$delete
   1698 :   exe "$read " .. tmp
   1699 :finally
   1700 :   call delete(tmp)
   1701 :endtry
   1702 
   1703 This filters the lines from the cursor until the end of the file through the
   1704 "filter" command, which takes a file name argument.  No matter if the
   1705 filtering works, something goes wrong in between ":try" and ":finally" or the
   1706 user cancels the filtering by pressing CTRL-C, the "call delete(tmp)" is
   1707 always executed.  This makes sure you don't leave the temporary file behind.
   1708 
   1709 More information about exception handling can be found in the reference
   1710 manual: |exception-handling|.
   1711 
   1712 ==============================================================================
   1713 *41.10*	Various remarks
   1714 
   1715 Here is a summary of items that apply to Vim scripts.  They are also mentioned
   1716 elsewhere, but form a nice checklist.
   1717 
   1718 The end-of-line character depends on the system.  For Vim scripts it is
   1719 recommended to always use the Unix fileformat.  Lines are then separated with
   1720 the Newline character.  This also works on any other system.  That way you can
   1721 copy your Vim scripts from MS-Windows to Unix and they still work.  See
   1722 |:source_crnl|.  To be sure it is set right, do this before writing the file:
   1723 >
   1724 :setlocal fileformat=unix
   1725 
   1726 When using "dos" fileformat, lines are separated with CR-NL, two characters.
   1727 The CR character causes various problems, better avoid this.
   1728 
   1729 
   1730 WHITE SPACE
   1731 
   1732 Blank lines are allowed in a script and ignored.
   1733 
   1734 Leading whitespace characters (blanks and TABs) are ignored, except when using
   1735 |:let-heredoc| without "trim".
   1736 
   1737 Trailing whitespace is often ignored, but not always.  One command that
   1738 includes it is `map`.  You have to watch out for that, it can cause hard to
   1739 understand mistakes.  A generic solution is to never use trailing white space,
   1740 unless you really need it.
   1741 
   1742 To include a whitespace character in the value of an option, it must be
   1743 escaped by a "\" (backslash)  as in the following example: >
   1744 
   1745 :set tags=my\ nice\ file
   1746 
   1747 The same example written as: >
   1748 
   1749 :set tags=my nice file
   1750 
   1751 will issue an error, because it is interpreted as: >
   1752 
   1753 :set tags=my
   1754 :set nice
   1755 :set file
   1756 
   1757 
   1758 COMMENTS
   1759 
   1760 The character " (the double quote mark) starts a comment.  Everything after
   1761 and including this character until the end-of-line is considered a comment and
   1762 is ignored, except for commands that don't consider comments, as shown in
   1763 examples below.  A comment can start on any character position on the line.
   1764 
   1765 There is a little "catch" with comments for some commands.  Examples: >
   1766 
   1767 :abbrev dev development		" shorthand
   1768 :map <F3> o#include		" insert include
   1769 :execute cmd			" do it
   1770 :!ls *.c			" list C files
   1771 
   1772 The abbreviation "dev" will be expanded to 'development     " shorthand'.  The
   1773 mapping of <F3> will actually be the whole line after the 'o# ....' including
   1774 the '" insert include'.  The "execute" command will give an error.  The "!"
   1775 command will send everything after it to the shell, causing an error for an
   1776 unmatched '"' character.
   1777   There can be no comment after ":map", ":abbreviate", ":execute" and "!"
   1778 commands (there are a few more commands with this restriction).  For the
   1779 ":map", ":abbreviate" and ":execute" commands there is a trick: >
   1780 
   1781 :abbrev dev development|" shorthand
   1782 :map <F3> o#include|" insert include
   1783 :execute cmd			|" do it
   1784 
   1785 With the '|' character the command is separated from the next one.  And that
   1786 next command is only a comment.  For the last command you need to do two
   1787 things: |:execute| and use '|': >
   1788 :exe '!ls *.c'			|" list C files
   1789 
   1790 Notice that there is no white space before the '|' in the abbreviation and
   1791 mapping.  For these commands, any character until the end-of-line or '|' is
   1792 included.  As a consequence of this behavior, you don't always see that
   1793 trailing whitespace is included: >
   1794 
   1795 :map <F4> o#include  
   1796 
   1797 To spot these problems, you can set the 'list' option when editing vimrc
   1798 files.
   1799 
   1800 For Unix there is one special way to comment a line, that allows making a Vim
   1801 script executable: >
   1802 #!/usr/bin/env vim -S
   1803 echo "this is a Vim script"
   1804 quit
   1805 
   1806 The "#" command by itself lists a line with the line number.  Adding an
   1807 exclamation mark changes it into doing nothing, so that you can add the shell
   1808 command to execute the rest of the file. |:#!| |-S|
   1809 
   1810 
   1811 PITFALLS
   1812 
   1813 Even bigger problem arises in the following example: >
   1814 
   1815 :map ,ab o#include
   1816 :unmap ,ab
   1817 
   1818 Here the unmap command will not work, because it tries to unmap ",ab ".  This
   1819 does not exist as a mapped sequence.  An error will be issued, which is very
   1820 hard to identify, because the ending whitespace character in ":unmap ,ab " is
   1821 not visible.
   1822 
   1823 And this is the same as what happens when one uses a comment after an "unmap"
   1824 command: >
   1825 
   1826 :unmap ,ab     " comment
   1827 
   1828 Here the comment part will be ignored.  However, Vim will try to unmap
   1829 ',ab     ', which does not exist.  Rewrite it as: >
   1830 
   1831 :unmap ,ab|    " comment
   1832 
   1833 
   1834 RESTORING THE VIEW
   1835 
   1836 Sometimes you want to make a change and go back to where the cursor was.
   1837 Restoring the relative position would also be nice, so that the same line
   1838 appears at the top of the window.
   1839   This example yanks the current line, puts it above the first line in the
   1840 file and then restores the view: >
   1841 
   1842 map ,p ma"aYHmbgg"aP`bzt`a
   1843 
   1844 What this does: >
   1845 ma"aYHmbgg"aP`bzt`a
   1846 <	ma			set mark a at cursor position
   1847   "aY			yank current line into register a
   1848      Hmb		go to top line in window and set mark b there
   1849 	gg		go to first line in file
   1850 	  "aP		put the yanked line above it
   1851 	     `b		go back to top line in display
   1852 	       zt	position the text in the window as before
   1853 		 `a	go back to saved cursor position
   1854 
   1855 
   1856 PACKAGING
   1857 
   1858 To avoid your function names to interfere with functions that you get from
   1859 others, use this scheme:
   1860 - Prepend a unique string before each function name.  I often use an
   1861  abbreviation.  For example, "OW_" is used for the option window functions.
   1862 - Put the definition of your functions together in a file.  Set a global
   1863  variable to indicate that the functions have been loaded.  When sourcing the
   1864  file again, first unload the functions.
   1865 Example: >
   1866 
   1867 " This is the XXX package
   1868 
   1869 if exists("XXX_loaded")
   1870   delfun XXX_one
   1871   delfun XXX_two
   1872 endif
   1873 
   1874 function XXX_one(a)
   1875 	... body of function ...
   1876 endfun
   1877 
   1878 function XXX_two(b)
   1879 	... body of function ...
   1880 endfun
   1881 
   1882 let XXX_loaded = 1
   1883 
   1884 ==============================================================================
   1885 *41.11*	Writing a plugin				*write-plugin*
   1886 
   1887 You can write a Vim script in such a way that many people can use it.  This is
   1888 called a plugin.  Vim users can drop your script in their plugin directory and
   1889 use its features right away |add-plugin|.
   1890 
   1891 There are actually two types of plugins:
   1892 
   1893  global plugins: For all types of files.
   1894 filetype plugins: Only for files of a specific type.
   1895 
   1896 In this section the first type is explained.  Most items are also relevant for
   1897 writing filetype plugins.  The specifics for filetype plugins are in the next
   1898 section |write-filetype-plugin|.
   1899 
   1900 
   1901 NAME
   1902 
   1903 First of all you must choose a name for your plugin.  The features provided
   1904 by the plugin should be clear from its name.  And it should be unlikely that
   1905 someone else writes a plugin with the same name but which does something
   1906 different.  And please limit the name to 8 characters, to avoid problems on
   1907 old MS-Windows systems.
   1908 
   1909 A script that corrects typing mistakes could be called "typecorr.vim".  We
   1910 will use it here as an example.
   1911 
   1912 For the plugin to work for everybody, it should follow a few guidelines.  This
   1913 will be explained step-by-step.  The complete example plugin is at the end.
   1914 
   1915 
   1916 BODY
   1917 
   1918 Let's start with the body of the plugin, the lines that do the actual work: >
   1919 
   1920 14	iabbrev teh the
   1921 15	iabbrev otehr other
   1922 16	iabbrev wnat want
   1923 17	iabbrev synchronisation
   1924 18		\ synchronization
   1925 19	let s:count = 4
   1926 
   1927 The actual list should be much longer, of course.
   1928 
   1929 The line numbers have only been added to explain a few things, don't put them
   1930 in your plugin file!
   1931 
   1932 
   1933 HEADER
   1934 
   1935 You will probably add new corrections to the plugin and soon have several
   1936 versions lying around.  And when distributing this file, people will want to
   1937 know who wrote this wonderful plugin and where they can send remarks.
   1938 Therefore, put a header at the top of your plugin: >
   1939 
   1940  1	" Vim global plugin for correcting typing mistakes
   1941  2	" Last Change:	2000 Oct 15
   1942  3	" Maintainer:	Bram Moolenaar <Bram@vim.org>
   1943 
   1944 About copyright and licensing: Since plugins are very useful and it's hardly
   1945 worth restricting their distribution, please consider making your plugin
   1946 either public domain or use the Vim |license|.  A short note about this near
   1947 the top of the plugin should be sufficient.  Example: >
   1948 
   1949  4	" License:	This file is placed in the public domain.
   1950 
   1951 
   1952 LINE CONTINUATION, AVOIDING SIDE EFFECTS		*use-cpo-save*
   1953 
   1954 In line 18 above, the line-continuation mechanism is used |line-continuation|.
   1955 Users with 'compatible' set will run into trouble here, they will get an error
   1956 message.  We can't just reset 'compatible', because that has a lot of side
   1957 effects.  To avoid this, we will set the 'cpoptions' option to its Vim default
   1958 value and restore it later.  That will allow the use of line-continuation and
   1959 make the script work for most people.  It is done like this: >
   1960 
   1961 11	let s:save_cpo = &cpo
   1962 12	set cpo&vim
   1963 ..
   1964 42	let &cpo = s:save_cpo
   1965 43	unlet s:save_cpo
   1966 
   1967 We first store the old value of 'cpoptions' in the s:save_cpo variable.  At
   1968 the end of the plugin this value is restored.
   1969 
   1970 Notice that a script-local variable is used |s:var|.  A global variable could
   1971 already be in use for something else.  Always use script-local variables for
   1972 things that are only used in the script.
   1973 
   1974 
   1975 NOT LOADING
   1976 
   1977 It's possible that a user doesn't always want to load this plugin.  Or the
   1978 system administrator has dropped it in the system-wide plugin directory, but a
   1979 user has their own plugin they want to use.  Then the user must have a chance to
   1980 disable loading this specific plugin.  This will make it possible: >
   1981 
   1982  6	if exists("g:loaded_typecorr")
   1983  7	  finish
   1984  8	endif
   1985  9	let g:loaded_typecorr = 1
   1986 
   1987 This also avoids that when the script is loaded twice it would cause error
   1988 messages for redefining functions and cause trouble for autocommands that are
   1989 added twice.
   1990 
   1991 The name is recommended to start with "loaded_" and then the file name of the
   1992 plugin, literally.  The "g:" is prepended just to avoid mistakes when using
   1993 the variable in a function (without "g:" it would be a variable local to the
   1994 function).
   1995 
   1996 Using "finish" stops Vim from reading the rest of the file, it's much quicker
   1997 than using if-endif around the whole file.
   1998 
   1999 
   2000 MAPPING
   2001 
   2002 Now let's make the plugin more interesting: We will add a mapping that adds a
   2003 correction for the word under the cursor.  We could just pick a key sequence
   2004 for this mapping, but the user might already use it for something else.  To
   2005 allow the user to define which keys a mapping in a plugin uses, the <Leader>
   2006 item can be used: >
   2007 
   2008 22	  map <unique> <Leader>a  <Plug>TypecorrAdd;
   2009 
   2010 The "<Plug>TypecorrAdd;" thing will do the work, more about that further on.
   2011 
   2012 The user can set the "mapleader" variable to the key sequence that they want
   2013 this mapping to start with.  Thus if the user has done: >
   2014 
   2015 let mapleader = "_"
   2016 
   2017 the mapping will define "_a".  If the user didn't do this, the default value
   2018 will be used, which is a backslash.  Then a map for "\a" will be defined.
   2019 
   2020 Note that <unique> is used, this will cause an error message if the mapping
   2021 already happened to exist. |:map-<unique>|
   2022 
   2023 But what if the user wants to define their own key sequence?  We can allow that
   2024 with this mechanism: >
   2025 
   2026 21	if !hasmapto('<Plug>TypecorrAdd;')
   2027 22	  map <unique> <Leader>a  <Plug>TypecorrAdd;
   2028 23	endif
   2029 
   2030 This checks if a mapping to "<Plug>TypecorrAdd;" already exists, and only
   2031 defines the mapping from "<Leader>a" if it doesn't.  The user then has a
   2032 chance of putting this in their vimrc file: >
   2033 
   2034 map ,c  <Plug>TypecorrAdd;
   2035 
   2036 Then the mapped key sequence will be ",c" instead of "_a" or "\a".
   2037 
   2038 
   2039 PIECES
   2040 
   2041 If a script gets longer, you often want to break up the work in pieces.  You
   2042 can use functions or mappings for this.  But you don't want these functions
   2043 and mappings to interfere with the ones from other scripts.  For example, you
   2044 could define a function Add(), but another script could try to define the same
   2045 function.  To avoid this, we define the function local to the script by
   2046 prepending it with "s:".
   2047 
   2048 We will define a function that adds a new typing correction: >
   2049 
   2050 30	function s:Add(from, correct)
   2051 31	  let to = input("type the correction for " .. a:from .. ": ")
   2052 32	  exe ":iabbrev " .. a:from .. " " .. to
   2053 ..
   2054 36	endfunction
   2055 
   2056 Now we can call the function s:Add() from within this script.  If another
   2057 script also defines s:Add(), it will be local to that script and can only
   2058 be called from the script it was defined in.  There can also be a global Add()
   2059 function (without the "s:"), which is again another function.
   2060 
   2061 <SID> can be used with mappings.  It generates a script ID, which identifies
   2062 the current script.  In our typing correction plugin we use it like this: >
   2063 
   2064 24	noremap <unique> <script> <Plug>TypecorrAdd;  <SID>Add
   2065 ..
   2066 28	noremap <SID>Add  :call <SID>Add(expand("<cword>"), 1)<CR>
   2067 
   2068 Thus when a user types "\a", this sequence is invoked: >
   2069 
   2070 \a  ->  <Plug>TypecorrAdd;  ->  <SID>Add  ->  :call <SID>Add()
   2071 
   2072 If another script also maps <SID>Add, it will get another script ID and
   2073 thus define another mapping.
   2074 
   2075 Note that instead of s:Add() we use <SID>Add() here.  That is because the
   2076 mapping is typed by the user, thus outside of the script.  The <SID> is
   2077 translated to the script ID, so that Vim knows in which script to look for
   2078 the Add() function.
   2079 
   2080 This is a bit complicated, but it's required for the plugin to work together
   2081 with other plugins.  The basic rule is that you use <SID>Add() in mappings and
   2082 s:Add() in other places (the script itself, autocommands, user commands).
   2083 
   2084 We can also add a menu entry to do the same as the mapping: >
   2085 
   2086 26	noremenu <script> Plugin.Add\ Correction      <SID>Add
   2087 
   2088 The "Plugin" menu is recommended for adding menu items for plugins.  In this
   2089 case only one item is used.  When adding more items, creating a submenu is
   2090 recommended.  For example, "Plugin.CVS" could be used for a plugin that offers
   2091 CVS operations "Plugin.CVS.checkin", "Plugin.CVS.checkout", etc.
   2092 
   2093 Note that in line 28 ":noremap" is used to avoid that any other mappings cause
   2094 trouble.  Someone may have remapped ":call", for example.  In line 24 we also
   2095 use ":noremap", but we do want "<SID>Add" to be remapped.  This is why
   2096 "<script>" is used here.  This only allows mappings which are local to the
   2097 script. |:map-<script>|  The same is done in line 26 for ":noremenu".
   2098 |:menu-<script>|
   2099 
   2100 
   2101 <SID> AND <Plug>					*using-<Plug>*
   2102 
   2103 Both <SID> and <Plug> are used to avoid that mappings of typed keys interfere
   2104 with mappings that are only to be used from other mappings.  Note the
   2105 difference between using <SID> and <Plug>:
   2106 
   2107 <Plug>	is visible outside of the script.  It is used for mappings which the
   2108 user might want to map a key sequence to.  <Plug> is a special code
   2109 that a typed key will never produce.
   2110 To make it very unlikely that other plugins use the same sequence of
   2111 characters, use this structure: <Plug> scriptname mapname
   2112 In our example the scriptname is "Typecorr" and the mapname is "Add".
   2113 We add a semicolon as the terminator.  This results in
   2114 "<Plug>TypecorrAdd;".  Only the first character of scriptname and
   2115 mapname is uppercase, so that we can see where mapname starts.
   2116 
   2117 <SID>	is the script ID, a unique identifier for a script.
   2118 Internally Vim translates <SID> to "<SNR>123_", where "123" can be any
   2119 number.  Thus a function "<SID>Add()" will have a name "<SNR>11_Add()"
   2120 in one script, and "<SNR>22_Add()" in another.  You can see this if
   2121 you use the ":function" command to get a list of functions.  The
   2122 translation of <SID> in mappings is exactly the same, that's how you
   2123 can call a script-local function from a mapping.
   2124 
   2125 
   2126 USER COMMAND
   2127 
   2128 Now let's add a user command to add a correction: >
   2129 
   2130 38	if !exists(":Correct")
   2131 39	  command -nargs=1  Correct  :call s:Add(<q-args>, 0)
   2132 40	endif
   2133 
   2134 The user command is defined only if no command with the same name already
   2135 exists.  Otherwise we would get an error here.  Overriding the existing user
   2136 command with ":command!" is not a good idea, this would probably make the user
   2137 wonder why the command they defined themself doesn't work.  |:command|
   2138 
   2139 
   2140 SCRIPT VARIABLES
   2141 
   2142 When a variable starts with "s:" it is a script variable.  It can only be used
   2143 inside a script.  Outside the script it's not visible.  This avoids trouble
   2144 with using the same variable name in different scripts.  The variables will be
   2145 kept as long as Vim is running.  And the same variables are used when sourcing
   2146 the same script again. |s:var|
   2147 
   2148 The fun is that these variables can also be used in functions, autocommands
   2149 and user commands that are defined in the script.  In our example we can add
   2150 a few lines to count the number of corrections: >
   2151 
   2152 19	let s:count = 4
   2153 ..
   2154 30	function s:Add(from, correct)
   2155 ..
   2156 34	  let s:count = s:count + 1
   2157 35	  echo s:count .. " corrections now"
   2158 36	endfunction
   2159 
   2160 First s:count is initialized to 4 in the script itself.  When later the
   2161 s:Add() function is called, it increments s:count.  It doesn't matter from
   2162 where the function was called, since it has been defined in the script, it
   2163 will use the local variables from this script.
   2164 
   2165 
   2166 THE RESULT
   2167 
   2168 Here is the resulting complete example: >
   2169 
   2170  1	" Vim global plugin for correcting typing mistakes
   2171  2	" Last Change:	2000 Oct 15
   2172  3	" Maintainer:	Bram Moolenaar <Bram@vim.org>
   2173  4	" License:	This file is placed in the public domain.
   2174  5
   2175  6	if exists("g:loaded_typecorr")
   2176  7	  finish
   2177  8	endif
   2178  9	let g:loaded_typecorr = 1
   2179 10
   2180 11	let s:save_cpo = &cpo
   2181 12	set cpo&vim
   2182 13
   2183 14	iabbrev teh the
   2184 15	iabbrev otehr other
   2185 16	iabbrev wnat want
   2186 17	iabbrev synchronisation
   2187 18		\ synchronization
   2188 19	let s:count = 4
   2189 20
   2190 21	if !hasmapto('<Plug>TypecorrAdd;')
   2191 22	  map <unique> <Leader>a  <Plug>TypecorrAdd;
   2192 23	endif
   2193 24	noremap <unique> <script> <Plug>TypecorrAdd;  <SID>Add
   2194 25
   2195 26	noremenu <script> Plugin.Add\ Correction      <SID>Add
   2196 27
   2197 28	noremap <SID>Add  :call <SID>Add(expand("<cword>"), 1)<CR>
   2198 29
   2199 30	function s:Add(from, correct)
   2200 31	  let to = input("type the correction for " .. a:from .. ": ")
   2201 32	  exe ":iabbrev " .. a:from .. " " .. to
   2202 33	  if a:correct | exe "normal viws\<C-R>\" \b\e" | endif
   2203 34	  let s:count = s:count + 1
   2204 35	  echo s:count .. " corrections now"
   2205 36	endfunction
   2206 37
   2207 38	if !exists(":Correct")
   2208 39	  command -nargs=1  Correct  :call s:Add(<q-args>, 0)
   2209 40	endif
   2210 41
   2211 42	let &cpo = s:save_cpo
   2212 43	unlet s:save_cpo
   2213 
   2214 Line 33 wasn't explained yet.  It applies the new correction to the word under
   2215 the cursor.  The |:normal| command is used to use the new abbreviation.  Note
   2216 that mappings and abbreviations are expanded here, even though the function
   2217 was called from a mapping defined with ":noremap".
   2218 
   2219 Using "unix" for the 'fileformat' option is recommended.  The Vim scripts will
   2220 then work everywhere.  Scripts with 'fileformat' set to "dos" do not work on
   2221 Unix.  Also see |:source_crnl|.  To be sure it is set right, do this before
   2222 writing the file: >
   2223 
   2224 :set fileformat=unix
   2225 
   2226 
   2227 DOCUMENTATION						*write-local-help*
   2228 
   2229 It's a good idea to also write some documentation for your plugin.  Especially
   2230 when its behavior can be changed by the user.  See |add-local-help| for how
   2231 they are installed.
   2232 
   2233 Here is a simple example for a plugin help file, called "typecorr.txt": >
   2234 
   2235  1	*typecorr.txt*	Plugin for correcting typing mistakes
   2236  2
   2237  3	If you make typing mistakes, this plugin will have them corrected
   2238  4	automatically.
   2239  5
   2240  6	There are currently only a few corrections.  Add your own if you like.
   2241  7
   2242  8	Mappings:
   2243  9	<Leader>a   or   <Plug>TypecorrAdd;
   2244 10		Add a correction for the word under the cursor.
   2245 11
   2246 12	Commands:
   2247 13	:Correct {word}
   2248 14		Add a correction for {word}.
   2249 15
   2250 16							*typecorr-settings*
   2251 17	This plugin doesn't have any settings.
   2252 
   2253 The first line is actually the only one for which the format matters.  It will
   2254 be extracted from the help file to be put in the "LOCAL ADDITIONS:" section of
   2255 help.txt |local-additions|.  The first "*" must be in the first column of the
   2256 first line.  After adding your help file do ":help" and check that the entries
   2257 line up nicely.
   2258 
   2259 You can add more tags inside ** in your help file.  But be careful not to use
   2260 existing help tags.  You would probably use the name of your plugin in most of
   2261 them, like "typecorr-settings" in the example.
   2262 
   2263 Using references to other parts of the help in || is recommended.  This makes
   2264 it easy for the user to find associated help.
   2265 
   2266 
   2267 FILETYPE DETECTION					*plugin-filetype*
   2268 
   2269 If your filetype is not already detected by Vim, you should create a filetype
   2270 detection snippet in a separate file.  It is usually in the form of an
   2271 autocommand that sets the filetype when the file name matches a pattern.
   2272 Example: >
   2273 
   2274 au BufNewFile,BufRead *.foo			set filetype=foofoo
   2275 
   2276 Write this single-line file as "ftdetect/foofoo.vim" in the first directory
   2277 that appears in 'runtimepath'.  For Unix that would be
   2278 "~/.config/nvim/ftdetect/foofoo.vim".  The convention is to use the name of
   2279 the filetype for the script name.
   2280 
   2281 You can make more complicated checks if you like, for example to inspect the
   2282 contents of the file to recognize the language.  Also see |new-filetype|.
   2283 
   2284 
   2285 SUMMARY							*plugin-special*
   2286 
   2287 Summary of special things to use in a plugin:
   2288 
   2289 s:name			Variables local to the script.
   2290 
   2291 <SID>			Script-ID, used for mappings and functions local to
   2292 		the script.
   2293 
   2294 hasmapto()		Function to test if the user already defined a mapping
   2295 		for functionality the script offers.
   2296 
   2297 <Leader>		Value of "mapleader", which the user defines as the
   2298 		keys that plugin mappings start with.
   2299 
   2300 :map <unique>		Give a warning if a mapping already exists.
   2301 
   2302 :noremap <script>	Use only mappings local to the script, not global
   2303 		mappings.
   2304 
   2305 exists(":Cmd")		Check if a user command already exists.
   2306 
   2307 ==============================================================================
   2308 *41.12*	Writing a filetype plugin	*write-filetype-plugin* *ftplugin*
   2309 
   2310 A filetype plugin is like a global plugin, except that it sets options and
   2311 defines mappings for the current buffer only.  See |add-filetype-plugin| for
   2312 how this type of plugin is used.
   2313 
   2314 First read the section on global plugins above |41.11|.  All that is said there
   2315 also applies to filetype plugins.  There are a few extras, which are explained
   2316 here.  The essential thing is that a filetype plugin should only have an
   2317 effect on the current buffer.
   2318 
   2319 
   2320 DISABLING
   2321 
   2322 If you are writing a filetype plugin to be used by many people, they need a
   2323 chance to disable loading it.  Put this at the top of the plugin: >
   2324 
   2325 " Only do this when not done yet for this buffer
   2326 if exists("b:did_ftplugin")
   2327   finish
   2328 endif
   2329 let b:did_ftplugin = 1
   2330 
   2331 This also needs to be used to avoid that the same plugin is executed twice for
   2332 the same buffer (happens when using an ":edit" command without arguments).
   2333 
   2334 Now users can disable loading the default plugin completely by making a
   2335 filetype plugin with only this line: >
   2336 
   2337 let b:did_ftplugin = 1
   2338 
   2339 This does require that the filetype plugin directory comes before $VIMRUNTIME
   2340 in 'runtimepath'!
   2341 
   2342 If you do want to use the default plugin, but overrule one of the settings,
   2343 you can write the different setting in a script: >
   2344 
   2345 setlocal textwidth=70
   2346 
   2347 Now write this in the "after" directory, so that it gets sourced after the
   2348 distributed "vim.vim" ftplugin |after-directory|.  For Unix this would be
   2349 "~/.config/nvim/after/ftplugin/vim.vim".  Note that the default plugin will
   2350 have set "b:did_ftplugin", but it is ignored here.
   2351 
   2352 
   2353 OPTIONS
   2354 
   2355 To make sure the filetype plugin only affects the current buffer use the >
   2356 
   2357 :setlocal
   2358 
   2359 command to set options.  And only set options which are local to a buffer (see
   2360 the help for the option to check that).  When using |:setlocal| for global
   2361 options or options local to a window, the value will change for many buffers,
   2362 and that is not what a filetype plugin should do.
   2363 
   2364 When an option has a value that is a list of flags or items, consider using
   2365 "+=" and "-=" to keep the existing value.  Be aware that the user may have
   2366 changed an option value already.  First resetting to the default value and
   2367 then changing it is often a good idea.  Example: >
   2368 
   2369 :setlocal formatoptions& formatoptions+=ro
   2370 
   2371 
   2372 MAPPINGS
   2373 
   2374 To make sure mappings will only work in the current buffer use the >
   2375 
   2376 :map <buffer>
   2377 
   2378 command.  This needs to be combined with the two-step mapping explained above.
   2379 An example of how to define functionality in a filetype plugin: >
   2380 
   2381 if !hasmapto('<Plug>JavaImport;')
   2382   map <buffer> <unique> <LocalLeader>i <Plug>JavaImport;
   2383 endif
   2384 noremap <buffer> <unique> <Plug>JavaImport; oimport ""<Left><Esc>
   2385 
   2386 |hasmapto()| is used to check if the user has already defined a map to
   2387 <Plug>JavaImport;.  If not, then the filetype plugin defines the default
   2388 mapping.  This starts with |<LocalLeader>|, which allows the user to select
   2389 the key(s) they want filetype plugin mappings to start with.  The default is a
   2390 backslash.
   2391 "<unique>" is used to give an error message if the mapping already exists or
   2392 overlaps with an existing mapping.
   2393 |:noremap| is used to avoid that any other mappings that the user has defined
   2394 interferes.  You might want to use ":noremap <script>" to allow remapping
   2395 mappings defined in this script that start with <SID>.
   2396 
   2397 The user must have a chance to disable the mappings in a filetype plugin,
   2398 without disabling everything.  Here is an example of how this is done for a
   2399 plugin for the mail filetype: >
   2400 
   2401 " Add mappings, unless the user didn't want this.
   2402 if !exists("no_plugin_maps") && !exists("no_mail_maps")
   2403   " Quote text by inserting "> "
   2404   if !hasmapto('<Plug>MailQuote;')
   2405     vmap <buffer> <LocalLeader>q <Plug>MailQuote;
   2406     nmap <buffer> <LocalLeader>q <Plug>MailQuote;
   2407   endif
   2408   vnoremap <buffer> <Plug>MailQuote; :s/^/> /<CR>
   2409   nnoremap <buffer> <Plug>MailQuote; :.,$s/^/> /<CR>
   2410 endif
   2411 
   2412 Two global variables are used:
   2413 |no_plugin_maps|	disables mappings for all filetype plugins
   2414 |no_mail_maps|		disables mappings for the "mail" filetype
   2415 
   2416 
   2417 USER COMMANDS
   2418 
   2419 To add a user command for a specific file type, so that it can only be used in
   2420 one buffer, use the "-buffer" argument to |:command|.  Example: >
   2421 
   2422 :command -buffer  Make  make %:r.s
   2423 
   2424 
   2425 VARIABLES
   2426 
   2427 A filetype plugin will be sourced for each buffer of the type it's for.  Local
   2428 script variables |s:var| will be shared between all invocations.  Use local
   2429 buffer variables |b:var| if you want a variable specifically for one buffer.
   2430 
   2431 
   2432 FUNCTIONS
   2433 
   2434 When defining a function, this only needs to be done once.  But the filetype
   2435 plugin will be sourced every time a file with this filetype will be opened.
   2436 This construct makes sure the function is only defined once: >
   2437 
   2438 :if !exists("*s:Func")
   2439 :  function s:Func(arg)
   2440 :    ...
   2441 :  endfunction
   2442 :endif
   2443 <
   2444 
   2445 UNDO						*undo_indent* *undo_ftplugin*
   2446 
   2447 When the user does ":setfiletype xyz" the effect of the previous filetype
   2448 should be undone.  Set the b:undo_ftplugin variable to the commands that will
   2449 undo the settings in your filetype plugin.  Example: >
   2450 
   2451 let b:undo_ftplugin = "setlocal fo< com< tw< commentstring<"
   2452 	\ .. "| unlet b:match_ignorecase b:match_words b:match_skip"
   2453 
   2454 Using ":setlocal" with "<" after the option name resets the option to its
   2455 global value.  That is mostly the best way to reset the option value.
   2456 
   2457 This does require removing the "C" flag from 'cpoptions' to allow line
   2458 continuation, as mentioned above |use-cpo-save|.
   2459 
   2460 For undoing the effect of an indent script, the b:undo_indent variable should
   2461 be set accordingly.
   2462 
   2463 
   2464 FILE NAME
   2465 
   2466 The filetype must be included in the file name |ftplugin-name|.  Use one of
   2467 these three forms:
   2468 
   2469 .../ftplugin/stuff.vim
   2470 .../ftplugin/stuff_foo.vim
   2471 .../ftplugin/stuff/bar.vim
   2472 
   2473 "stuff" is the filetype, "foo" and "bar" are arbitrary names.
   2474 
   2475 
   2476 SUMMARY							*ftplugin-special*
   2477 
   2478 Summary of special things to use in a filetype plugin:
   2479 
   2480 <LocalLeader>		Value of "maplocalleader", which the user defines as
   2481 		the keys that filetype plugin mappings start with.
   2482 
   2483 :map <buffer>		Define a mapping local to the buffer.
   2484 
   2485 :noremap <script>	Only remap mappings defined in this script that start
   2486 		with <SID>.
   2487 
   2488 :setlocal		Set an option for the current buffer only.
   2489 
   2490 :command -buffer	Define a user command local to the buffer.
   2491 
   2492 exists("*s:Func")	Check if a function was already defined.
   2493 
   2494 Also see |plugin-special|, the special things used for all plugins.
   2495 
   2496 ==============================================================================
   2497 *41.13*	Writing a compiler plugin		*write-compiler-plugin*
   2498 
   2499 A compiler plugin sets options for use with a specific compiler.  The user can
   2500 load it with the |:compiler| command.  The main use is to set the
   2501 'errorformat' and 'makeprg' options.
   2502 
   2503 Easiest is to have a look at examples.  This command will edit all the default
   2504 compiler plugins: >
   2505 
   2506 :next $VIMRUNTIME/compiler/*.vim
   2507 
   2508 Use |:next| to go to the next plugin file.
   2509 
   2510 There are two special items about these files.  First is a mechanism to allow
   2511 a user to overrule or add to the default file.  The default files start with: >
   2512 
   2513 :if exists("current_compiler")
   2514 :  finish
   2515 :endif
   2516 :let current_compiler = "mine"
   2517 
   2518 When you write a compiler file and put it in your personal runtime directory
   2519 (e.g., ~/.config/nvim/compiler for Unix), you set the "current_compiler"
   2520 variable to make the default file skip the settings.
   2521 						*:CompilerSet*
   2522 The second mechanism is to use ":set" for ":compiler!" and ":setlocal" for
   2523 ":compiler".  Vim defines the ":CompilerSet" user command for this.  This is
   2524 an example: >
   2525 
   2526  CompilerSet errorformat&		" use the default 'errorformat'
   2527  CompilerSet makeprg=nmake
   2528 
   2529 When you write a compiler plugin for the Vim distribution or for a system-wide
   2530 runtime directory, use the mechanism mentioned above.  When
   2531 "current_compiler" was already set by a user plugin nothing will be done.
   2532 
   2533 When you write a compiler plugin to overrule settings from a default plugin,
   2534 don't check "current_compiler".  This plugin is supposed to be loaded
   2535 last, thus it should be in a directory at the end of 'runtimepath'.  For Unix
   2536 that could be ~/.config/nvim/after/compiler.
   2537 
   2538 ==============================================================================
   2539 *41.14*	Writing a plugin that loads quickly	*write-plugin-quickload*
   2540 
   2541 A plugin may grow and become quite long.  The startup delay may become
   2542 noticeable, while you hardly ever use the plugin.  Then it's time for a
   2543 quickload plugin.
   2544 
   2545 The basic idea is that the plugin is loaded twice.  The first time user
   2546 commands and mappings are defined that offer the functionality.  The second
   2547 time the functions that implement the functionality are defined.
   2548 
   2549 It may sound surprising that quickload means loading a script twice.  What we
   2550 mean is that it loads quickly the first time, postponing the bulk of the
   2551 script to the second time, which only happens when you actually use it.  When
   2552 you always use the functionality it actually gets slower!
   2553 
   2554 Note that since Vim 7 there is an alternative: use the |autoload|
   2555 functionality |41.15|.
   2556 
   2557 The following example shows how it's done: >
   2558 
   2559 " Vim global plugin for demonstrating quick loading
   2560 " Last Change:	2005 Feb 25
   2561 " Maintainer:	Bram Moolenaar <Bram@vim.org>
   2562 " License:	This file is placed in the public domain.
   2563 
   2564 if !exists("s:did_load")
   2565 	command -nargs=* BNRead  call BufNetRead(<f-args>)
   2566 	map <F19> :call BufNetWrite('something')<CR>
   2567 
   2568 	let s:did_load = 1
   2569 	exe 'au FuncUndefined BufNet* source ' .. expand('<script>')
   2570 	finish
   2571 endif
   2572 
   2573 function BufNetRead(...)
   2574 	echo 'BufNetRead(' .. string(a:000) .. ')'
   2575 	" read functionality here
   2576 endfunction
   2577 
   2578 function BufNetWrite(...)
   2579 	echo 'BufNetWrite(' .. string(a:000) .. ')'
   2580 	" write functionality here
   2581 endfunction
   2582 
   2583 When the script is first loaded "s:did_load" is not set.  The commands between
   2584 the "if" and "endif" will be executed.  This ends in a |:finish| command, thus
   2585 the rest of the script is not executed.
   2586 
   2587 The second time the script is loaded "s:did_load" exists and the commands
   2588 after the "endif" are executed.  This defines the (possible long)
   2589 BufNetRead() and BufNetWrite() functions.
   2590 
   2591 If you drop this script in your plugin directory Vim will execute it on
   2592 startup.  This is the sequence of events that happens:
   2593 
   2594 1. The "BNRead" command is defined and the <F19> key is mapped when the script
   2595   is sourced at startup.  A |FuncUndefined| autocommand is defined.  The
   2596   ":finish" command causes the script to terminate early.
   2597 
   2598 2. The user types the BNRead command or presses the <F19> key.  The
   2599   BufNetRead() or BufNetWrite() function will be called.
   2600 
   2601 3. Vim can't find the function and triggers the |FuncUndefined| autocommand
   2602   event.  Since the pattern "BufNet*" matches the invoked function, the
   2603   command "source fname" will be executed.  "fname" will be equal to the name
   2604   of the script, no matter where it is located, because it comes from
   2605   expanding "<script>" (see |expand()|).
   2606 
   2607 4. The script is sourced again, the "s:did_load" variable exists and the
   2608   functions are defined.
   2609 
   2610 Notice that the functions that are loaded afterwards match the pattern in the
   2611 |FuncUndefined| autocommand.  You must make sure that no other plugin defines
   2612 functions that match this pattern.
   2613 
   2614 ==============================================================================
   2615 *41.15*	Writing library scripts			*write-library-script*
   2616 
   2617 Some functionality will be required in several places.  When this becomes more
   2618 than a few lines you will want to put it in one script and use it from many
   2619 scripts.  We will call that one script a library script.
   2620 
   2621 Manually loading a library script is possible, so long as you avoid loading it
   2622 when it's already done.  You can do this with the |exists()| function.
   2623 Example: >
   2624 
   2625 if !exists('*MyLibFunction')
   2626    runtime library/mylibscript.vim
   2627 endif
   2628 call MyLibFunction(arg)
   2629 
   2630 Here you need to know that MyLibFunction() is defined in a script
   2631 "library/mylibscript.vim" in one of the directories in 'runtimepath'.
   2632 
   2633 To make this a bit simpler Vim offers the autoload mechanism.  Then the
   2634 example looks like this: >
   2635 
   2636 call mylib#myfunction(arg)
   2637 
   2638 That's a lot simpler, isn't it?  Vim will recognize the function name and when
   2639 it's not defined search for the script "autoload/mylib.vim" in 'runtimepath'.
   2640 That script must define the "mylib#myfunction()" function.
   2641 
   2642 You can put many other functions in the mylib.vim script, you are free to
   2643 organize your functions in library scripts.  But you must use function names
   2644 where the part before the '#' matches the script name.  Otherwise Vim would
   2645 not know what script to load.
   2646 
   2647 If you get really enthusiastic and write lots of library scripts, you may
   2648 want to use subdirectories.  Example: >
   2649 
   2650 call netlib#ftp#read('somefile')
   2651 
   2652 For Unix the library script used for this could be:
   2653 
   2654 ~/.config/nvim/autoload/netlib/ftp.vim
   2655 
   2656 Where the function is defined like this: >
   2657 
   2658 function netlib#ftp#read(fname)
   2659 	"  Read the file fname through ftp
   2660 endfunction
   2661 
   2662 Notice that the name the function is defined with is exactly the same as the
   2663 name used for calling the function.  And the part before the last '#'
   2664 exactly matches the subdirectory and script name.
   2665 
   2666 You can use the same mechanism for variables: >
   2667 
   2668 let weekdays = dutch#weekdays
   2669 
   2670 This will load the script "autoload/dutch.vim", which should contain something
   2671 like: >
   2672 
   2673 let dutch#weekdays = ['zondag', 'maandag', 'dinsdag', 'woensdag',
   2674 	\ 'donderdag', 'vrijdag', 'zaterdag']
   2675 
   2676 Further reading: |autoload|.
   2677 
   2678 ==============================================================================
   2679 *41.16*	Distributing Vim scripts			*distribute-script*
   2680 
   2681 Vim users will look for scripts on the Vim website: https://www.vim.org.
   2682 If you made something that is useful for others, share it!
   2683 
   2684 Vim scripts can be used on any system.  There might not be a tar or gzip
   2685 command.  If you want to pack files together and/or compress them the "zip"
   2686 utility is recommended.
   2687 
   2688 ==============================================================================
   2689 
   2690 Next chapter: |usr_42.txt|  Add new menus
   2691 
   2692 Copyright: see |manual-copyright|  vim:tw=78:ts=8:noet:ft=help:norl: