blob: d90c24abfd8d1747d03d186f70394f027fccc7cd [file] [log] [blame]
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00001*usr_41.txt* For Vim version 7.0aa. Last change: 2005 Feb 04
Bram Moolenaar071d4272004-06-13 20:20:40 +00002
3 VIM USER MANUAL - by Bram Moolenaar
4
5 Write a Vim script
6
7
8The Vim script language is used for the startup vimrc file, syntax files, and
9many other things. This chapter explains the items that can be used in a Vim
10script. There are a lot of them, thus this is a long chapter.
11
12|41.1| Introduction
13|41.2| Variables
14|41.3| Expressions
15|41.4| Conditionals
16|41.5| Executing an expression
17|41.6| Using functions
18|41.7| Defining a function
19|41.8| Exceptions
20|41.9| Various remarks
21|41.10| Writing a plugin
22|41.11| Writing a filetype plugin
23|41.12| Writing a compiler plugin
24
25 Next chapter: |usr_42.txt| Add new menus
26 Previous chapter: |usr_40.txt| Make new commands
27Table of contents: |usr_toc.txt|
28
29==============================================================================
Bram Moolenaar9d75c832005-01-25 21:57:23 +000030*41.1* Introduction *vim-script-intro* *script*
Bram Moolenaar071d4272004-06-13 20:20:40 +000031
32Your first experience with Vim scripts is the vimrc file. Vim reads it when
33it starts up and executes the commands. You can set options to values you
34prefer. And you can use any colon command in it (commands that start with a
35":"; these are sometimes referred to as Ex commands or command-line commands).
36 Syntax files are also Vim scripts. As are files that set options for a
37specific file type. A complicated macro can be defined by a separate Vim
38script file. You can think of other uses yourself.
39
40Let's start with a simple example: >
41
42 :let i = 1
43 :while i < 5
44 : echo "count is" i
45 : let i = i + 1
46 :endwhile
47<
48 Note:
49 The ":" characters are not really needed here. You only need to use
50 them when you type a command. In a Vim script file they can be left
51 out. We will use them here anyway to make clear these are colon
52 commands and make them stand out from Normal mode commands.
53
54The ":let" command assigns a value to a variable. The generic form is: >
55
56 :let {variable} = {expression}
57
58In this case the variable name is "i" and the expression is a simple value,
59the number one.
60 The ":while" command starts a loop. The generic form is: >
61
62 :while {condition}
63 : {statements}
64 :endwhile
65
66The statements until the matching ":endwhile" are executed for as long as the
67condition is true. The condition used here is the expression "i < 5". This
68is true when the variable i is smaller than five.
69 The ":echo" command prints its arguments. In this case the string "count
70is" and the value of the variable i. Since i is one, this will print:
71
72 count is 1 ~
73
74Then there is another ":let i =" command. The value used is the expression "i
75+ 1". This adds one to the variable i and assigns the new value to the same
76variable.
77 The output of the example code is:
78
79 count is 1 ~
80 count is 2 ~
81 count is 3 ~
82 count is 4 ~
83
84 Note:
85 If you happen to write a while loop that keeps on running, you can
86 interrupt it by pressing CTRL-C (CTRL-Break on MS-Windows).
Bram Moolenaarb7fcef52005-01-02 11:31:05 +000087 Note:
88 You can try out the examples by yanking the lines from the text here
89 and executing them with :@"
Bram Moolenaar071d4272004-06-13 20:20:40 +000090
Bram Moolenaaraf7f6412005-01-17 22:11:23 +000091The example was given to explain the commands, but you would really want to
92make such a loop it can be written much more compact: >
93
94 :for i in range(1, 4)
95 : echo "count is" i
96 :endfor
97
98We won't explain how |:for| and |range()| work right now. Follow the links if
99you are impatient.
100
Bram Moolenaar071d4272004-06-13 20:20:40 +0000101
102THREE KINDS OF NUMBERS
103
104Numbers can be decimal, hexadecimal or octal. A hexadecimal number starts
105with "0x" or "0X". For example "0x1f" is 31. An octal number starts with a
106zero. "017" is 15. Careful: don't put a zero before a decimal number, it
107will be interpreted as an octal number!
108 The ":echo" command always prints decimal numbers. Example: >
109
110 :echo 0x7f 036
111< 127 30 ~
112
113A number is made negative with a minus sign. This also works for hexadecimal
114and octal numbers. A minus sign is also for subtraction. Compare this with
115the previous example: >
116
117 :echo 0x7f -036
118< 97 ~
119
120White space in an expression is ignored. However, it's recommended to use it
121for separating items, to make the expression easier to read. For example, to
122avoid the confusion with a negative number, put a space between the minus sign
123and the following number: >
124
125 :echo 0x7f - 036
126
127==============================================================================
128*41.2* Variables
129
130A variable name consists of ASCII letters, digits and the underscore. It
131cannot start with a digit. Valid variable names are:
132
133 counter
134 _aap3
135 very_long_variable_name_with_underscores
136 FuncLength
137 LENGTH
138
139Invalid names are "foo+bar" and "6var".
140 These variables are global. To see a list of currently defined variables
141use this command: >
142
143 :let
144
145You can use global variables everywhere. This also means that when the
146variable "count" is used in one script file, it might also be used in another
147file. This leads to confusion at least, and real problems at worst. To avoid
148this, you can use a variable local to a script file by prepending "s:". For
149example, one script contains this code: >
150
151 :let s:count = 1
152 :while s:count < 5
153 : source other.vim
154 : let s:count = s:count + 1
155 :endwhile
156
157Since "s:count" is local to this script, you can be sure that sourcing the
158"other.vim" script will not change this variable. If "other.vim" also uses an
159"s:count" variable, it will be a different copy, local to that script. More
160about script-local variables here: |script-variable|.
161
162There are more kinds of variables, see |internal-variables|. The most often
163used ones are:
164
165 b:name variable local to a buffer
166 w:name variable local to a window
167 g:name global variable (also in a function)
168 v:name variable predefined by Vim
169
170
171DELETING VARIABLES
172
173Variables take up memory and show up in the output of the ":let" command. To
174delete a variable use the ":unlet" command. Example: >
175
176 :unlet s:count
177
178This deletes the script-local variable "s:count" to free up the memory it
179uses. If you are not sure if the variable exists, and don't want an error
180message when it doesn't, append !: >
181
182 :unlet! s:count
183
184When a script finishes, the local variables used there will not be
185automatically freed. The next time the script executes, it can still use the
186old value. Example: >
187
188 :if !exists("s:call_count")
189 : let s:call_count = 0
190 :endif
191 :let s:call_count = s:call_count + 1
192 :echo "called" s:call_count "times"
193
194The "exists()" function checks if a variable has already been defined. Its
195argument is the name of the variable you want to check. Not the variable
196itself! If you would do this: >
197
198 :if !exists(s:call_count)
199
200Then the value of s:call_count will be used as the name of the variable that
201exists() checks. That's not what you want.
202 The exclamation mark ! negates a value. When the value was true, it
203becomes false. When it was false, it becomes true. You can read it as "not".
204Thus "if !exists()" can be read as "if not exists()".
205 What Vim calls true is anything that is not zero. Only zero is false.
206
207
208STRING VARIABLES AND CONSTANTS
209
210So far only numbers were used for the variable value. Strings can be used as
211well. Numbers and strings are the only two types of variables that Vim
212supports. The type is dynamic, it is set each time when assigning a value to
213the variable with ":let".
214 To assign a string value to a variable, you need to use a string constant.
215There are two types of these. First the string in double quotes: >
216
217 :let name = "peter"
218 :echo name
219< peter ~
220
221If you want to include a double quote inside the string, put a backslash in
222front of it: >
223
224 :let name = "\"peter\""
225 :echo name
226< "peter" ~
227
228To avoid the need for a backslash, you can use a string in single quotes: >
229
230 :let name = '"peter"'
231 :echo name
232< "peter" ~
233
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000234Inside a single-quote string all the characters are as they are. The drawback
235is that it's impossible to include a single quote. A backslash is taken
236literally as well, thus you can't use it to change the meaning of the
Bram Moolenaar071d4272004-06-13 20:20:40 +0000237character after it.
238 In double-quote strings it is possible to use special characters. Here are
239a few useful ones:
240
241 \t <Tab>
242 \n <NL>, line break
243 \r <CR>, <Enter>
244 \e <Esc>
245 \b <BS>, backspace
246 \" "
247 \\ \, backslash
248 \<Esc> <Esc>
249 \<C-W> CTRL-W
250
251The last two are just examples. The "\<name>" form can be used to include
252the special key "name".
253 See |expr-quote| for the full list of special items in a string.
254
255==============================================================================
256*41.3* Expressions
257
258Vim has a rich, yet simple way to handle expressions. You can read the
259definition here: |expression-syntax|. Here we will show the most common
260items.
261 The numbers, strings and variables mentioned above are expressions by
262themselves. Thus everywhere an expression is expected, you can use a number,
263string or variable. Other basic items in an expression are:
264
265 $NAME environment variable
266 &name option
267 @r register
268
269Examples: >
270
271 :echo "The value of 'tabstop' is" &ts
272 :echo "Your home directory is" $HOME
273 :if @a > 5
274
275The &name form can be used to save an option value, set it to a new value,
276do something and restore the old value. Example: >
277
278 :let save_ic = &ic
279 :set noic
280 :/The Start/,$delete
281 :let &ic = save_ic
282
283This makes sure the "The Start" pattern is used with the 'ignorecase' option
284off. Still, it keeps the value that the user had set.
285
286
287MATHEMATICS
288
289It becomes more interesting if we combine these basic items. Let's start with
290mathematics on numbers:
291
292 a + b add
293 a - b subtract
294 a * b multiply
295 a / b divide
296 a % b modulo
297
298The usual precedence is used. Example: >
299
300 :echo 10 + 5 * 2
301< 20 ~
302
303Grouping is done with braces. No surprises here. Example: >
304
305 :echo (10 + 5) * 2
306< 30 ~
307
308Strings can be concatenated with ".". Example: >
309
310 :echo "foo" . "bar"
311< foobar ~
312
313When the ":echo" command gets multiple arguments, it separates them with a
314space. In the example the argument is a single expression, thus no space is
315inserted.
316
317Borrowed from the C language is the conditional expression:
318
319 a ? b : c
320
321If "a" evaluates to true "b" is used, otherwise "c" is used. Example: >
322
323 :let i = 4
324 :echo i > 5 ? "i is big" : "i is small"
325< i is small ~
326
327The three parts of the constructs are always evaluated first, thus you could
328see it work as:
329
330 (a) ? (b) : (c)
331
332==============================================================================
333*41.4* Conditionals
334
335The ":if" commands executes the following statements, until the matching
336":endif", only when a condition is met. The generic form is:
337
338 :if {condition}
339 {statements}
340 :endif
341
342Only when the expression {condition} evaluates to true (non-zero) will the
343{statements} be executed. These must still be valid commands. If they
344contain garbage, Vim won't be able to find the ":endif".
345 You can also use ":else". The generic form for this is:
346
347 :if {condition}
348 {statements}
349 :else
350 {statements}
351 :endif
352
353The second {statements} is only executed if the first one isn't.
354 Finally, there is ":elseif":
355
356 :if {condition}
357 {statements}
358 :elseif {condition}
359 {statements}
360 :endif
361
362This works just like using ":else" and then "if", but without the need for an
363extra ":endif".
364 A useful example for your vimrc file is checking the 'term' option and
365doing something depending upon its value: >
366
367 :if &term == "xterm"
368 : " Do stuff for xterm
369 :elseif &term == "vt100"
370 : " Do stuff for a vt100 terminal
371 :else
372 : " Do something for other terminals
373 :endif
374
375
376LOGIC OPERATIONS
377
378We already used some of them in the examples. These are the most often used
379ones:
380
381 a == b equal to
382 a != b not equal to
383 a > b greater than
384 a >= b greater than or equal to
385 a < b less than
386 a <= b less than or equal to
387
388The result is one if the condition is met and zero otherwise. An example: >
389
390 :if v:version >= 600
391 : echo "congratulations"
392 :else
393 : echo "you are using an old version, upgrade!"
394 :endif
395
396Here "v:version" is a variable defined by Vim, which has the value of the Vim
397version. 600 is for version 6.0. Version 6.1 has the value 601. This is
398very useful to write a script that works with multiple versions of Vim.
399|v:version|
400
401The logic operators work both for numbers and strings. When comparing two
402strings, the mathematical difference is used. This compares byte values,
403which may not be right for some languages.
404 When comparing a string with a number, the string is first converted to a
405number. This is a bit tricky, because when a string doesn't look like a
406number, the number zero is used. Example: >
407
408 :if 0 == "one"
409 : echo "yes"
410 :endif
411
412This will echo "yes", because "one" doesn't look like a number, thus it is
413converted to the number zero.
414
415For strings there are two more items:
416
417 a =~ b matches with
418 a !~ b does not match with
419
420The left item "a" is used as a string. The right item "b" is used as a
421pattern, like what's used for searching. Example: >
422
423 :if str =~ " "
424 : echo "str contains a space"
425 :endif
426 :if str !~ '\.$'
427 : echo "str does not end in a full stop"
428 :endif
429
430Notice the use of a single-quote string for the pattern. This is useful,
431because backslashes need to be doubled in a double-quote string and patterns
432tend to contain many backslashes.
433
434The 'ignorecase' option is used when comparing strings. When you don't want
435that, append "#" to match case and "?" to ignore case. Thus "==?" compares
436two strings to be equal while ignoring case. And "!~#" checks if a pattern
437doesn't match, also checking the case of letters. For the full table see
438|expr-==|.
439
440
441MORE LOOPING
442
443The ":while" command was already mentioned. Two more statements can be used
444in between the ":while" and the ":endwhile":
445
446 :continue Jump back to the start of the while loop; the
447 loop continues.
448 :break Jump forward to the ":endwhile"; the loop is
449 discontinued.
450
451Example: >
452
453 :while counter < 40
454 : call do_something()
455 : if skip_flag
456 : continue
457 : endif
458 : if finished_flag
459 : break
460 : endif
461 : sleep 50m
462 :endwhile
463
464The ":sleep" command makes Vim take a nap. The "50m" specifies fifty
465milliseconds. Another example is ":sleep 4", which sleeps for four seconds.
466
467==============================================================================
468*41.5* Executing an expression
469
470So far the commands in the script were executed by Vim directly. The
471":execute" command allows executing the result of an expression. This is a
472very powerful way to build commands and execute them.
473 An example is to jump to a tag, which is contained in a variable: >
474
475 :execute "tag " . tag_name
476
477The "." is used to concatenate the string "tag " with the value of variable
478"tag_name". Suppose "tag_name" has the value "get_cmd", then the command that
479will be executed is: >
480
481 :tag get_cmd
482
483The ":execute" command can only execute colon commands. The ":normal" command
484executes Normal mode commands. However, its argument is not an expression but
485the literal command characters. Example: >
486
487 :normal gg=G
488
489This jumps to the first line and formats all lines with the "=" operator.
490 To make ":normal" work with an expression, combine ":execute" with it.
491Example: >
492
493 :execute "normal " . normal_commands
494
495The variable "normal_commands" must contain the Normal mode commands.
496 Make sure that the argument for ":normal" is a complete command. Otherwise
497Vim will run into the end of the argument and abort the command. For example,
498if you start Insert mode, you must leave Insert mode as well. This works: >
499
500 :execute "normal Inew text \<Esc>"
501
502This inserts "new text " in the current line. Notice the use of the special
503key "\<Esc>". This avoids having to enter a real <Esc> character in your
504script.
505
506==============================================================================
507*41.6* Using functions
508
509Vim defines many functions and provides a large amount of functionality that
510way. A few examples will be given in this section. You can find the whole
511list here: |functions|.
512
513A function is called with the ":call" command. The parameters are passed in
514between braces, separated by commas. Example: >
515
516 :call search("Date: ", "W")
517
518This calls the search() function, with arguments "Date: " and "W". The
519search() function uses its first argument as a search pattern and the second
520one as flags. The "W" flag means the search doesn't wrap around the end of
521the file.
522
523A function can be called in an expression. Example: >
524
525 :let line = getline(".")
526 :let repl = substitute(line, '\a', "*", "g")
527 :call setline(".", repl)
528
529The getline() function obtains a line from the current file. Its argument is
530a specification of the line number. In this case "." is used, which means the
531line where the cursor is.
532 The substitute() function does something similar to the ":substitute"
533command. The first argument is the string on which to perform the
534substitution. The second argument is the pattern, the third the replacement
535string. Finally, the last arguments are the flags.
536 The setline() function sets the line, specified by the first argument, to a
537new string, the second argument. In this example the line under the cursor is
538replaced with the result of the substitute(). Thus the effect of the three
539statements is equal to: >
540
541 :substitute/\a/*/g
542
543Using the functions becomes more interesting when you do more work before and
544after the substitute() call.
545
546
547FUNCTIONS *function-list*
548
549There are many functions. We will mention them here, grouped by what they are
550used for. You can find an alphabetical list here: |functions|. Use CTRL-] on
551the function name to jump to detailed help on it.
552
553String manipulation:
554 char2nr() get ASCII value of a character
555 nr2char() get a character by its ASCII value
556 escape() escape characters in a string with a '\'
557 strtrans() translate a string to make it printable
558 tolower() turn a string to lowercase
559 toupper() turn a string to uppercase
560 match() position where a pattern matches in a string
561 matchend() position where a pattern match ends in a string
562 matchstr() match of a pattern in a string
563 stridx() first index of a short string in a long string
564 strridx() last index of a short string in a long string
565 strlen() length of a string
566 substitute() substitute a pattern match with a string
567 submatch() get a specific match in a ":substitute"
568 strpart() get part of a string
569 expand() expand special keywords
570 type() type of a variable
571 iconv() convert text from one encoding to another
572
Bram Moolenaaraf7f6412005-01-17 22:11:23 +0000573List manipulation:
574 get() get an item without error for wrong index
575 len() number of items in a List
576 empty() check if List is empty
577 insert() insert an item somewhere in a List
578 add() append an item to a List
579 extend() append a List to a List
580 remove() remove one or more items from a List
581 copy() make a shallow copy of a List
582 deepcopy() make a full copy of a List
583 filter() remove selected items from a List
584 map() change each List item
585 sort() sort a List
586 reverse() reverse the order of a List
587 split() split a String into a List
588 join() join List items into a String
589 string() String representation of a List
590 call() call a function with List as arguments
591 max() maximum value in a List
592 min() minimum value in a List
593 count() count number of times a value appears in a List
594 getline() get List with buffer lines
595 append() append List of lines to the buffer
596
597Dictionary manipulation:
598 get() get an entries without error for wrong key
599 len() number of entries in a Dictionary
600 has_key() check whether a key appears in a Dictionary
601 empty() check if Dictionary is empty
602 remove() remove an entry from a Dictionary
603 extend() add entries from one Dictionary to another
604 filter() remove selected entries from a Dictionary
605 map() change each Dictionary entry
606 keys() get List of Dictionary keys
607 values() get List of Dictionary values
608 items() get List of Dictionary key-value pairs
609 copy() make a shallow copy of a Dictionary
610 deepcopy() make a full copy of a Dictionary
611 string() String representation of a Dictionary
612 max() maximum value in a Dictionary
613 min() minimum value in a Dictionary
614 count() count number of times a value appears
615
Bram Moolenaar071d4272004-06-13 20:20:40 +0000616Working with text in the current buffer:
617 byte2line() get line number at a specific byte count
618 line2byte() byte count at a specific line
619 col() column number of the cursor or a mark
620 virtcol() screen column of the cursor or a mark
621 line() line number of the cursor or mark
622 wincol() window column number of the cursor
623 winline() window line number of the cursor
624 cursor() position the cursor at a line/column
625 getline() get a line from the buffer
626 setline() replace a line in the buffer
627 append() append {string} below line {lnum}
628 indent() indent of a specific line
629 cindent() indent according to C indenting
630 lispindent() indent according to Lisp indenting
631 nextnonblank() find next non-blank line
632 prevnonblank() find previous non-blank line
633 search() find a match for a pattern
634 searchpair() find the other end of a start/skip/end
635
636System functions and manipulation of files:
637 browse() put up a file requester
638 glob() expand wildcards
639 globpath() expand wildcards in a number of directories
640 resolve() find out where a shortcut points to
641 fnamemodify() modify a file name
642 executable() check if an executable program exists
643 filereadable() check if a file can be read
644 filewritable() check if a file can be written to
645 isdirectory() check if a directory exists
646 getcwd() get the current working directory
647 getfsize() get the size of a file
648 getftime() get last modification time of a file
649 localtime() get current time
650 strftime() convert time to a string
651 tempname() get the name of a temporary file
652 delete() delete a file
653 rename() rename a file
654 system() get the result of a shell command
655 hostname() name of the system
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +0000656 readfile() read a file into a List of lines
657 writefile() write a List of lines into a file
Bram Moolenaar071d4272004-06-13 20:20:40 +0000658
659Buffers, windows and the argument list:
660 argc() number of entries in the argument list
661 argidx() current position in the argument list
662 argv() get one entry from the argument list
663 bufexists() check if a buffer exists
664 buflisted() check if a buffer exists and is listed
665 bufloaded() check if a buffer exists and is loaded
666 bufname() get the name of a specific buffer
667 bufnr() get the buffer number of a specific buffer
668 winnr() get the window number for the current window
669 bufwinnr() get the window number of a specific buffer
670 winbufnr() get the buffer number of a specific window
671 getbufvar() get a variable value from a specific buffer
672 setbufvar() set a variable in a specific buffer
673 getwinvar() get a variable value from a specific window
674 setwinvar() set a variable in a specific window
675
676Folding:
677 foldclosed() check for a closed fold at a specific line
678 foldclosedend() like foldclosed() but return the last line
679 foldlevel() check for the fold level at a specific line
680 foldtext() generate the line displayed for a closed fold
681
682Syntax highlighting:
683 hlexists() check if a highlight group exists
684 hlID() get ID of a highlight group
685 synID() get syntax ID at a specific position
686 synIDattr() get a specific attribute of a syntax ID
687 synIDtrans() get translated syntax ID
688
689History:
690 histadd() add an item to a history
691 histdel() delete an item from a history
692 histget() get an item from a history
693 histnr() get highest index of a history list
694
695Interactive:
696 confirm() let the user make a choice
697 getchar() get a character from the user
698 getcharmod() get modifiers for the last typed character
699 input() get a line from the user
700 inputsecret() get a line from the user without showing it
701 inputdialog() get a line from the user in a dialog
702 inputresave save and clear typeahead
703 inputrestore() restore typeahead
704
705Vim server:
706 serverlist() return the list of server names
707 remote_send() send command characters to a Vim server
708 remote_expr() evaluate an expression in a Vim server
709 server2client() send a reply to a client of a Vim server
710 remote_peek() check if there is a reply from a Vim server
711 remote_read() read a reply from a Vim server
712 foreground() move the Vim window to the foreground
713 remote_foreground() move the Vim server window to the foreground
714
715Various:
716 mode() get current editing mode
717 visualmode() last visual mode used
718 hasmapto() check if a mapping exists
719 mapcheck() check if a matching mapping exists
720 maparg() get rhs of a mapping
721 exists() check if a variable, function, etc. exists
722 has() check if a feature is supported in Vim
723 cscope_connection() check if a cscope connection exists
724 did_filetype() check if a FileType autocommand was used
725 eventhandler() check if invoked by an event handler
726 getwinposx() X position of the GUI Vim window
727 getwinposy() Y position of the GUI Vim window
728 winheight() get height of a specific window
729 winwidth() get width of a specific window
730 libcall() call a function in an external library
731 libcallnr() idem, returning a number
732 getreg() get contents of a register
733 getregtype() get type of a register
734 setreg() set contents and type of a register
735
736==============================================================================
737*41.7* Defining a function
738
739Vim enables you to define your own functions. The basic function declaration
740begins as follows: >
741
742 :function {name}({var1}, {var2}, ...)
743 : {body}
744 :endfunction
745<
746 Note:
747 Function names must begin with a capital letter.
748
749Let's define a short function to return the smaller of two numbers. It starts
750with this line: >
751
752 :function Min(num1, num2)
753
754This tells Vim that the function is named "Min" and it takes two arguments:
755"num1" and "num2".
756 The first thing you need to do is to check to see which number is smaller:
757 >
758 : if a:num1 < a:num2
759
760The special prefix "a:" tells Vim that the variable is a function argument.
761Let's assign the variable "smaller" the value of the smallest number: >
762
763 : if a:num1 < a:num2
764 : let smaller = a:num1
765 : else
766 : let smaller = a:num2
767 : endif
768
769The variable "smaller" is a local variable. Variables used inside a function
770are local unless prefixed by something like "g:", "a:", or "s:".
771
772 Note:
773 To access a global variable from inside a function you must prepend
774 "g:" to it. Thus "g:count" inside a function is used for the global
775 variable "count", and "count" is another variable, local to the
776 function.
777
778You now use the ":return" statement to return the smallest number to the user.
779Finally, you end the function: >
780
781 : return smaller
782 :endfunction
783
784The complete function definition is as follows: >
785
786 :function Min(num1, num2)
787 : if a:num1 < a:num2
788 : let smaller = a:num1
789 : else
790 : let smaller = a:num2
791 : endif
792 : return smaller
793 :endfunction
794
795A user defined function is called in exactly the same way as a builtin
796function. Only the name is different. The Min function can be used like
797this: >
798
799 :echo Min(5, 8)
800
801Only now will the function be executed and the lines be interpreted by Vim.
802If there are mistakes, like using an undefined variable or function, you will
803now get an error message. When defining the function these errors are not
804detected.
805
806When a function reaches ":endfunction" or ":return" is used without an
807argument, the function returns zero.
808
809To redefine a function that already exists, use the ! for the ":function"
810command: >
811
812 :function! Min(num1, num2, num3)
813
814
815USING A RANGE
816
817The ":call" command can be given a line range. This can have one of two
818meanings. When a function has been defined with the "range" keyword, it will
819take care of the line range itself.
820 The function will be passed the variables "a:firstline" and "a:lastline".
821These will have the line numbers from the range the function was called with.
822Example: >
823
824 :function Count_words() range
825 : let n = a:firstline
826 : let count = 0
827 : while n <= a:lastline
828 : let count = count + Wordcount(getline(n))
829 : let n = n + 1
830 : endwhile
831 : echo "found " . count . " words"
832 :endfunction
833
834You can call this function with: >
835
836 :10,30call Count_words()
837
838It will be executed once and echo the number of words.
839 The other way to use a line range is by defining a function without the
840"range" keyword. The function will be called once for every line in the
841range, with the cursor in that line. Example: >
842
843 :function Number()
844 : echo "line " . line(".") . " contains: " . getline(".")
845 :endfunction
846
847If you call this function with: >
848
849 :10,15call Number()
850
851The function will be called six times.
852
853
854VARIABLE NUMBER OF ARGUMENTS
855
856Vim enables you to define functions that have a variable number of arguments.
857The following command, for instance, defines a function that must have 1
858argument (start) and can have up to 20 additional arguments: >
859
860 :function Show(start, ...)
861
862The variable "a:1" contains the first optional argument, "a:2" the second, and
863so on. The variable "a:0" contains the number of extra arguments.
864 For example: >
865
866 :function Show(start, ...)
867 : echohl Title
868 : echo "Show is " . a:start
869 : echohl None
870 : let index = 1
871 : while index <= a:0
872 : echo " Arg " . index . " is " . a:{index}
873 : let index = index + 1
874 : endwhile
875 : echo ""
876 :endfunction
877
878This uses the ":echohl" command to specify the highlighting used for the
879following ":echo" command. ":echohl None" stops it again. The ":echon"
880command works like ":echo", but doesn't output a line break.
881
882
883LISTING FUNCTIONS
884
885The ":function" command lists the names and arguments of all user-defined
886functions: >
887
888 :function
889< function Show(start, ...) ~
890 function GetVimIndent() ~
891 function SetSyn(name) ~
892
893To see what a function does, use its name as an argument for ":function": >
894
895 :function SetSyn
896< 1 if &syntax == '' ~
897 2 let &syntax = a:name ~
898 3 endif ~
899 endfunction ~
900
901
902DEBUGGING
903
904The line number is useful for when you get an error message or when debugging.
905See |debug-scripts| about debugging mode.
906 You can also set the 'verbose' option to 12 or higher to see all function
907calls. Set it to 15 or higher to see every executed line.
908
909
910DELETING A FUNCTION
911
912To delete the Show() function: >
913
914 :delfunction Show
915
916You get an error when the function doesn't exist.
917
918==============================================================================
919*41.8* Exceptions
920
921Let's start with an example: >
922
923 :try
924 : read ~/templates/pascal.tmpl
925 :catch /E484:/
926 : echo "Sorry, the Pascal template file cannot be found."
927 :endtry
928
929The ":read" command will fail if the file does not exist. Instead of
930generating an error message, this code catches the error and gives the user a
931nice message instead.
932
933For the commands in between ":try" and ":endtry" errors are turned into
934exceptions. An exception is a string. In the case of an error the string
935contains the error message. And every error message has a number. In this
936case, the error we catch contains "E484:". This number is guaranteed to stay
937the same (the text may change, e.g., it may be translated).
938
939When the ":read" command causes another error, the pattern "E484:" will not
940match in it. Thus this exception will not be caught and result in the usual
941error message.
942
943You might be tempted to do this: >
944
945 :try
946 : read ~/templates/pascal.tmpl
947 :catch
948 : echo "Sorry, the Pascal template file cannot be found."
949 :endtry
950
951This means all errors are caught. But then you will not see errors that are
952useful, such as "E21: Cannot make changes, 'modifiable' is off".
953
954Another useful mechanism is the ":finally" command: >
955
956 :let tmp = tempname()
957 :try
958 : exe ".,$write " . tmp
959 : exe "!filter " . tmp
960 : .,$delete
961 : exe "$read " . tmp
962 :finally
963 : call delete(tmp)
964 :endtry
965
966This filters the lines from the cursor until the end of the file through the
967"filter" command, which takes a file name argument. No matter if the
968filtering works, something goes wrong in between ":try" and ":finally" or the
969user cancels the filtering by pressing CTRL-C, the "call delete(tmp)" is
970always executed. This makes sure you don't leave the temporary file behind.
971
972More information about exception handling can be found in the reference
973manual: |exception-handling|.
974
975==============================================================================
976*41.9* Various remarks
977
978Here is a summary of items that apply to Vim scripts. They are also mentioned
979elsewhere, but form a nice checklist.
980
981The end-of-line character depends on the system. For Unix a single <NL>
982character is used. For MS-DOS, Windows, OS/2 and the like, <CR><LF> is used.
983This is important when using mappings that end in a <CR>. See |:source_crnl|.
984
985
986WHITE SPACE
987
988Blank lines are allowed and ignored.
989
990Leading whitespace characters (blanks and TABs) are always ignored. The
991whitespaces between parameters (e.g. between the 'set' and the 'cpoptions' in
992the example below) are reduced to one blank character and plays the role of a
993separator, the whitespaces after the last (visible) character may or may not
994be ignored depending on the situation, see below.
995
996For a ":set" command involving the "=" (equal) sign, such as in: >
997
998 :set cpoptions =aABceFst
999
1000the whitespace immediately before the "=" sign is ignored. But there can be
1001no whitespace after the "=" sign!
1002
1003To include a whitespace character in the value of an option, it must be
1004escaped by a "\" (backslash) as in the following example: >
1005
1006 :set tags=my\ nice\ file
1007
1008The same example written as >
1009
1010 :set tags=my nice file
1011
1012will issue an error, because it is interpreted as: >
1013
1014 :set tags=my
1015 :set nice
1016 :set file
1017
1018
1019COMMENTS
1020
1021The character " (the double quote mark) starts a comment. Everything after
1022and including this character until the end-of-line is considered a comment and
1023is ignored, except for commands that don't consider comments, as shown in
1024examples below. A comment can start on any character position on the line.
1025
1026There is a little "catch" with comments for some commands. Examples: >
1027
1028 :abbrev dev development " shorthand
1029 :map <F3> o#include " insert include
1030 :execute cmd " do it
1031 :!ls *.c " list C files
1032
1033The abbreviation 'dev' will be expanded to 'development " shorthand'. The
1034mapping of <F3> will actually be the whole line after the 'o# ....' including
1035the '" insert include'. The "execute" command will give an error. The "!"
1036command will send everything after it to the shell, causing an error for an
1037unmatched '"' character.
1038 There can be no comment after ":map", ":abbreviate", ":execute" and "!"
1039commands (there are a few more commands with this restriction). For the
1040":map", ":abbreviate" and ":execute" commands there is a trick: >
1041
1042 :abbrev dev development|" shorthand
1043 :map <F3> o#include|" insert include
1044 :execute cmd |" do it
1045
1046With the '|' character the command is separated from the next one. And that
1047next command is only a comment.
1048
1049Notice that there is no white space before the '|' in the abbreviation and
1050mapping. For these commands, any character until the end-of-line or '|' is
1051included. As a consequence of this behavior, you don't always see that
1052trailing whitespace is included: >
1053
1054 :map <F4> o#include
1055
1056To avoid these problems, you can set the 'list' option when editing vimrc
1057files.
1058
1059
1060PITFALLS
1061
1062Even bigger problem arises in the following example: >
1063
1064 :map ,ab o#include
1065 :unmap ,ab
1066
1067Here the unmap command will not work, because it tries to unmap ",ab ". This
1068does not exist as a mapped sequence. An error will be issued, which is very
1069hard to identify, because the ending whitespace character in ":unmap ,ab " is
1070not visible.
1071
1072And this is the same as what happens when one uses a comment after an 'unmap'
1073command: >
1074
1075 :unmap ,ab " comment
1076
1077Here the comment part will be ignored. However, Vim will try to unmap
1078',ab ', which does not exist. Rewrite it as: >
1079
1080 :unmap ,ab| " comment
1081
1082
1083RESTORING THE VIEW
1084
1085Sometimes you want to make a change and go back to where cursor was.
1086Restoring the relative position would also be nice, so that the same line
1087appears at the top of the window.
1088 This example yanks the current line, puts it above the first line in the
1089file and then restores the view: >
1090
1091 map ,p ma"aYHmbgg"aP`bzt`a
1092
1093What this does: >
1094 ma"aYHmbgg"aP`bzt`a
1095< ma set mark a at cursor position
1096 "aY yank current line into register a
1097 Hmb go to top line in window and set mark b there
1098 gg go to first line in file
1099 "aP put the yanked line above it
1100 `b go back to top line in display
1101 zt position the text in the window as before
1102 `a go back to saved cursor position
1103
1104
1105PACKAGING
1106
1107To avoid your function names to interfere with functions that you get from
1108others, use this scheme:
1109- Prepend a unique string before each function name. I often use an
1110 abbreviation. For example, "OW_" is used for the option window functions.
1111- Put the definition of your functions together in a file. Set a global
1112 variable to indicate that the functions have been loaded. When sourcing the
1113 file again, first unload the functions.
1114Example: >
1115
1116 " This is the XXX package
1117
1118 if exists("XXX_loaded")
1119 delfun XXX_one
1120 delfun XXX_two
1121 endif
1122
1123 function XXX_one(a)
1124 ... body of function ...
1125 endfun
1126
1127 function XXX_two(b)
1128 ... body of function ...
1129 endfun
1130
1131 let XXX_loaded = 1
1132
1133==============================================================================
1134*41.10* Writing a plugin *write-plugin*
1135
1136You can write a Vim script in such a way that many people can use it. This is
1137called a plugin. Vim users can drop your script in their plugin directory and
1138use its features right away |add-plugin|.
1139
1140There are actually two types of plugins:
1141
1142 global plugins: For all types of files.
1143filetype plugins: Only for files of a specific type.
1144
1145In this section the first type is explained. Most items are also relevant for
1146writing filetype plugins. The specifics for filetype plugins are in the next
1147section |write-filetype-plugin|.
1148
1149
1150NAME
1151
1152First of all you must choose a name for your plugin. The features provided
1153by the plugin should be clear from its name. And it should be unlikely that
1154someone else writes a plugin with the same name but which does something
1155different. And please limit the name to 8 characters, to avoid problems on
1156old Windows systems.
1157
1158A script that corrects typing mistakes could be called "typecorr.vim". We
1159will use it here as an example.
1160
1161For the plugin to work for everybody, it should follow a few guidelines. This
1162will be explained step-by-step. The complete example plugin is at the end.
1163
1164
1165BODY
1166
1167Let's start with the body of the plugin, the lines that do the actual work: >
1168
1169 14 iabbrev teh the
1170 15 iabbrev otehr other
1171 16 iabbrev wnat want
1172 17 iabbrev synchronisation
1173 18 \ synchronization
1174 19 let s:count = 4
1175
1176The actual list should be much longer, of course.
1177
1178The line numbers have only been added to explain a few things, don't put them
1179in your plugin file!
1180
1181
1182HEADER
1183
1184You will probably add new corrections to the plugin and soon have several
1185versions laying around. And when distributing this file, people will want to
1186know who wrote this wonderful plugin and where they can send remarks.
1187Therefore, put a header at the top of your plugin: >
1188
1189 1 " Vim global plugin for correcting typing mistakes
1190 2 " Last Change: 2000 Oct 15
1191 3 " Maintainer: Bram Moolenaar <Bram@vim.org>
1192
1193About copyright and licensing: Since plugins are very useful and it's hardly
1194worth restricting their distribution, please consider making your plugin
1195either public domain or use the Vim |license|. A short note about this near
1196the top of the plugin should be sufficient. Example: >
1197
1198 4 " License: This file is placed in the public domain.
1199
1200
1201LINE CONTINUATION, AVOIDING SIDE EFFECTS *use-cpo-save*
1202
1203In line 18 above, the line-continuation mechanism is used |line-continuation|.
1204Users with 'compatible' set will run into trouble here, they will get an error
1205message. We can't just reset 'compatible', because that has a lot of side
1206effects. To avoid this, we will set the 'cpoptions' option to its Vim default
1207value and restore it later. That will allow the use of line-continuation and
1208make the script work for most people. It is done like this: >
1209
1210 11 let s:save_cpo = &cpo
1211 12 set cpo&vim
1212 ..
1213 42 let &cpo = s:save_cpo
1214
1215We first store the old value of 'cpoptions' in the s:save_cpo variable. At
1216the end of the plugin this value is restored.
1217
1218Notice that a script-local variable is used |s:var|. A global variable could
1219already be in use for something else. Always use script-local variables for
1220things that are only used in the script.
1221
1222
1223NOT LOADING
1224
1225It's possible that a user doesn't always want to load this plugin. Or the
1226system administrator has dropped it in the system-wide plugin directory, but a
1227user has his own plugin he wants to use. Then the user must have a chance to
1228disable loading this specific plugin. This will make it possible: >
1229
1230 6 if exists("loaded_typecorr")
1231 7 finish
1232 8 endif
1233 9 let loaded_typecorr = 1
1234
1235This also avoids that when the script is loaded twice it would cause error
1236messages for redefining functions and cause trouble for autocommands that are
1237added twice.
1238
1239
1240MAPPING
1241
1242Now let's make the plugin more interesting: We will add a mapping that adds a
1243correction for the word under the cursor. We could just pick a key sequence
1244for this mapping, but the user might already use it for something else. To
1245allow the user to define which keys a mapping in a plugin uses, the <Leader>
1246item can be used: >
1247
1248 22 map <unique> <Leader>a <Plug>TypecorrAdd
1249
1250The "<Plug>TypecorrAdd" thing will do the work, more about that further on.
1251
1252The user can set the "mapleader" variable to the key sequence that he wants
1253this mapping to start with. Thus if the user has done: >
1254
1255 let mapleader = "_"
1256
1257the mapping will define "_a". If the user didn't do this, the default value
1258will be used, which is a backslash. Then a map for "\a" will be defined.
1259
1260Note that <unique> is used, this will cause an error message if the mapping
1261already happened to exist. |:map-<unique>|
1262
1263But what if the user wants to define his own key sequence? We can allow that
1264with this mechanism: >
1265
1266 21 if !hasmapto('<Plug>TypecorrAdd')
1267 22 map <unique> <Leader>a <Plug>TypecorrAdd
1268 23 endif
1269
1270This checks if a mapping to "<Plug>TypecorrAdd" already exists, and only
1271defines the mapping from "<Leader>a" if it doesn't. The user then has a
1272chance of putting this in his vimrc file: >
1273
1274 map ,c <Plug>TypecorrAdd
1275
1276Then the mapped key sequence will be ",c" instead of "_a" or "\a".
1277
1278
1279PIECES
1280
1281If a script gets longer, you often want to break up the work in pieces. You
1282can use functions or mappings for this. But you don't want these functions
1283and mappings to interfere with the ones from other scripts. For example, you
1284could define a function Add(), but another script could try to define the same
1285function. To avoid this, we define the function local to the script by
1286prepending it with "s:".
1287
1288We will define a function that adds a new typing correction: >
1289
1290 30 function s:Add(from, correct)
1291 31 let to = input("type the correction for " . a:from . ": ")
1292 32 exe ":iabbrev " . a:from . " " . to
1293 ..
1294 36 endfunction
1295
1296Now we can call the function s:Add() from within this script. If another
1297script also defines s:Add(), it will be local to that script and can only
1298be called from the script it was defined in. There can also be a global Add()
1299function (without the "s:"), which is again another function.
1300
1301<SID> can be used with mappings. It generates a script ID, which identifies
1302the current script. In our typing correction plugin we use it like this: >
1303
1304 24 noremap <unique> <script> <Plug>TypecorrAdd <SID>Add
1305 ..
1306 28 noremap <SID>Add :call <SID>Add(expand("<cword>"), 1)<CR>
1307
1308Thus when a user types "\a", this sequence is invoked: >
1309
1310 \a -> <Plug>TypecorrAdd -> <SID>Add -> :call <SID>Add()
1311
1312If another script would also map <SID>Add, it would get another script ID and
1313thus define another mapping.
1314
1315Note that instead of s:Add() we use <SID>Add() here. That is because the
1316mapping is typed by the user, thus outside of the script. The <SID> is
1317translated to the script ID, so that Vim knows in which script to look for
1318the Add() function.
1319
1320This is a bit complicated, but it's required for the plugin to work together
1321with other plugins. The basic rule is that you use <SID>Add() in mappings and
1322s:Add() in other places (the script itself, autocommands, user commands).
1323
1324We can also add a menu entry to do the same as the mapping: >
1325
1326 26 noremenu <script> Plugin.Add\ Correction <SID>Add
1327
1328The "Plugin" menu is recommended for adding menu items for plugins. In this
1329case only one item is used. When adding more items, creating a submenu is
1330recommended. For example, "Plugin.CVS" could be used for a plugin that offers
1331CVS operations "Plugin.CVS.checkin", "Plugin.CVS.checkout", etc.
1332
1333Note that in line 28 ":noremap" is used to avoid that any other mappings cause
1334trouble. Someone may have remapped ":call", for example. In line 24 we also
1335use ":noremap", but we do want "<SID>Add" to be remapped. This is why
1336"<script>" is used here. This only allows mappings which are local to the
1337script. |:map-<script>| The same is done in line 26 for ":noremenu".
1338|:menu-<script>|
1339
1340
1341<SID> AND <Plug> *using-<Plug>*
1342
1343Both <SID> and <Plug> are used to avoid that mappings of typed keys interfere
1344with mappings that are only to be used from other mappings. Note the
1345difference between using <SID> and <Plug>:
1346
1347<Plug> is visible outside of the script. It is used for mappings which the
1348 user might want to map a key sequence to. <Plug> is a special code
1349 that a typed key will never produce.
1350 To make it very unlikely that other plugins use the same sequence of
1351 characters, use this structure: <Plug> scriptname mapname
1352 In our example the scriptname is "Typecorr" and the mapname is "Add".
1353 This results in "<Plug>TypecorrAdd". Only the first character of
1354 scriptname and mapname is uppercase, so that we can see where mapname
1355 starts.
1356
1357<SID> is the script ID, a unique identifier for a script.
1358 Internally Vim translates <SID> to "<SNR>123_", where "123" can be any
1359 number. Thus a function "<SID>Add()" will have a name "<SNR>11_Add()"
1360 in one script, and "<SNR>22_Add()" in another. You can see this if
1361 you use the ":function" command to get a list of functions. The
1362 translation of <SID> in mappings is exactly the same, that's how you
1363 can call a script-local function from a mapping.
1364
1365
1366USER COMMAND
1367
1368Now let's add a user command to add a correction: >
1369
1370 38 if !exists(":Correct")
1371 39 command -nargs=1 Correct :call s:Add(<q-args>, 0)
1372 40 endif
1373
1374The user command is defined only if no command with the same name already
1375exists. Otherwise we would get an error here. Overriding the existing user
1376command with ":command!" is not a good idea, this would probably make the user
1377wonder why the command he defined himself doesn't work. |:command|
1378
1379
1380SCRIPT VARIABLES
1381
1382When a variable starts with "s:" it is a script variable. It can only be used
1383inside a script. Outside the script it's not visible. This avoids trouble
1384with using the same variable name in different scripts. The variables will be
1385kept as long as Vim is running. And the same variables are used when sourcing
1386the same script again. |s:var|
1387
1388The fun is that these variables can also be used in functions, autocommands
1389and user commands that are defined in the script. In our example we can add
1390a few lines to count the number of corrections: >
1391
1392 19 let s:count = 4
1393 ..
1394 30 function s:Add(from, correct)
1395 ..
1396 34 let s:count = s:count + 1
1397 35 echo s:count . " corrections now"
1398 36 endfunction
1399
1400First s:count is initialized to 4 in the script itself. When later the
1401s:Add() function is called, it increments s:count. It doesn't matter from
1402where the function was called, since it has been defined in the script, it
1403will use the local variables from this script.
1404
1405
1406THE RESULT
1407
1408Here is the resulting complete example: >
1409
1410 1 " Vim global plugin for correcting typing mistakes
1411 2 " Last Change: 2000 Oct 15
1412 3 " Maintainer: Bram Moolenaar <Bram@vim.org>
1413 4 " License: This file is placed in the public domain.
1414 5
1415 6 if exists("loaded_typecorr")
1416 7 finish
1417 8 endif
1418 9 let loaded_typecorr = 1
1419 10
1420 11 let s:save_cpo = &cpo
1421 12 set cpo&vim
1422 13
1423 14 iabbrev teh the
1424 15 iabbrev otehr other
1425 16 iabbrev wnat want
1426 17 iabbrev synchronisation
1427 18 \ synchronization
1428 19 let s:count = 4
1429 20
1430 21 if !hasmapto('<Plug>TypecorrAdd')
1431 22 map <unique> <Leader>a <Plug>TypecorrAdd
1432 23 endif
1433 24 noremap <unique> <script> <Plug>TypecorrAdd <SID>Add
1434 25
1435 26 noremenu <script> Plugin.Add\ Correction <SID>Add
1436 27
1437 28 noremap <SID>Add :call <SID>Add(expand("<cword>"), 1)<CR>
1438 29
1439 30 function s:Add(from, correct)
1440 31 let to = input("type the correction for " . a:from . ": ")
1441 32 exe ":iabbrev " . a:from . " " . to
1442 33 if a:correct | exe "normal viws\<C-R>\" \b\e" | endif
1443 34 let s:count = s:count + 1
1444 35 echo s:count . " corrections now"
1445 36 endfunction
1446 37
1447 38 if !exists(":Correct")
1448 39 command -nargs=1 Correct :call s:Add(<q-args>, 0)
1449 40 endif
1450 41
1451 42 let &cpo = s:save_cpo
1452
1453Line 33 wasn't explained yet. It applies the new correction to the word under
1454the cursor. The |:normal| command is used to use the new abbreviation. Note
1455that mappings and abbreviations are expanded here, even though the function
1456was called from a mapping defined with ":noremap".
1457
1458Using "unix" for the 'fileformat' option is recommended. The Vim scripts will
1459then work everywhere. Scripts with 'fileformat' set to "dos" do not work on
1460Unix. Also see |:source_crnl|. To be sure it is set right, do this before
1461writing the file: >
1462
1463 :set fileformat=unix
1464
1465
1466DOCUMENTATION *write-local-help*
1467
1468It's a good idea to also write some documentation for your plugin. Especially
1469when its behavior can be changed by the user. See |add-local-help| for how
1470they are installed.
1471
1472Here is a simple example for a plugin help file, called "typecorr.txt": >
1473
1474 1 *typecorr.txt* Plugin for correcting typing mistakes
1475 2
1476 3 If you make typing mistakes, this plugin will have them corrected
1477 4 automatically.
1478 5
1479 6 There are currently only a few corrections. Add your own if you like.
1480 7
1481 8 Mappings:
1482 9 <Leader>a or <Plug>TypecorrAdd
1483 10 Add a correction for the word under the cursor.
1484 11
1485 12 Commands:
1486 13 :Correct {word}
1487 14 Add a correction for {word}.
1488 15
1489 16 *typecorr-settings*
1490 17 This plugin doesn't have any settings.
1491
1492The first line is actually the only one for which the format matters. It will
1493be extracted from the help file to be put in the "LOCAL ADDITIONS:" section of
1494help.txt |local-additions|. The first "*" must be in the first column of the
1495first line. After adding your help file do ":help" and check that the entries
1496line up nicely.
1497
1498You can add more tags inside ** in your help file. But be careful not to use
1499existing help tags. You would probably use the name of your plugin in most of
1500them, like "typecorr-settings" in the example.
1501
1502Using references to other parts of the help in || is recommended. This makes
1503it easy for the user to find associated help.
1504
1505
1506FILETYPE DETECTION *plugin-filetype*
1507
1508If your filetype is not already detected by Vim, you should create a filetype
1509detection snippet in a separate file. It is usually in the form of an
1510autocommand that sets the filetype when the file name matches a pattern.
1511Example: >
1512
1513 au BufNewFile,BufRead *.foo set filetype=foofoo
1514
1515Write this single-line file as "ftdetect/foofoo.vim" in the first directory
1516that appears in 'runtimepath'. For Unix that would be
1517"~/.vim/ftdetect/foofoo.vim". The convention is to use the name of the
1518filetype for the script name.
1519
1520You can make more complicated checks if you like, for example to inspect the
1521contents of the file to recognize the language. Also see |new-filetype|.
1522
1523
1524SUMMARY *plugin-special*
1525
1526Summary of special things to use in a plugin:
1527
1528s:name Variables local to the script.
1529
1530<SID> Script-ID, used for mappings and functions local to
1531 the script.
1532
1533hasmapto() Function to test if the user already defined a mapping
1534 for functionality the script offers.
1535
1536<Leader> Value of "mapleader", which the user defines as the
1537 keys that plugin mappings start with.
1538
1539:map <unique> Give a warning if a mapping already exists.
1540
1541:noremap <script> Use only mappings local to the script, not global
1542 mappings.
1543
1544exists(":Cmd") Check if a user command already exists.
1545
1546==============================================================================
1547*41.11* Writing a filetype plugin *write-filetype-plugin* *ftplugin*
1548
1549A filetype plugin is like a global plugin, except that it sets options and
1550defines mappings for the current buffer only. See |add-filetype-plugin| for
1551how this type of plugin is used.
1552
1553First read the section on global plugins above |41.10|. All that is said there
1554also applies to filetype plugins. There are a few extras, which are explained
1555here. The essential thing is that a filetype plugin should only have an
1556effect on the current buffer.
1557
1558
1559DISABLING
1560
1561If you are writing a filetype plugin to be used by many people, they need a
1562chance to disable loading it. Put this at the top of the plugin: >
1563
1564 " Only do this when not done yet for this buffer
1565 if exists("b:did_ftplugin")
1566 finish
1567 endif
1568 let b:did_ftplugin = 1
1569
1570This also needs to be used to avoid that the same plugin is executed twice for
1571the same buffer (happens when using an ":edit" command without arguments).
1572
1573Now users can disable loading the default plugin completely by making a
1574filetype plugin with only this line: >
1575
1576 let b:did_ftplugin = 1
1577
1578This does require that the filetype plugin directory comes before $VIMRUNTIME
1579in 'runtimepath'!
1580
1581If you do want to use the default plugin, but overrule one of the settings,
1582you can write the different setting in a script: >
1583
1584 setlocal textwidth=70
1585
1586Now write this in the "after" directory, so that it gets sourced after the
1587distributed "vim.vim" ftplugin |after-directory|. For Unix this would be
1588"~/.vim/after/ftplugin/vim.vim". Note that the default plugin will have set
1589"b:did_ftplugin", but it is ignored here.
1590
1591
1592OPTIONS
1593
1594To make sure the filetype plugin only affects the current buffer use the >
1595
1596 :setlocal
1597
1598command to set options. And only set options which are local to a buffer (see
1599the help for the option to check that). When using |:setlocal| for global
1600options or options local to a window, the value will change for many buffers,
1601and that is not what a filetype plugin should do.
1602
1603When an option has a value that is a list of flags or items, consider using
1604"+=" and "-=" to keep the existing value. Be aware that the user may have
1605changed an option value already. First resetting to the default value and
1606then changing it often a good idea. Example: >
1607
1608 :setlocal formatoptions& formatoptions+=ro
1609
1610
1611MAPPINGS
1612
1613To make sure mappings will only work in the current buffer use the >
1614
1615 :map <buffer>
1616
1617command. This needs to be combined with the two-step mapping explained above.
1618An example of how to define functionality in a filetype plugin: >
1619
1620 if !hasmapto('<Plug>JavaImport')
1621 map <buffer> <unique> <LocalLeader>i <Plug>JavaImport
1622 endif
1623 noremap <buffer> <unique> <Plug>JavaImport oimport ""<Left><Esc>
1624
1625|hasmapto()| is used to check if the user has already defined a map to
1626<Plug>JavaImport. If not, then the filetype plugin defines the default
1627mapping. This starts with |<LocalLeader>|, which allows the user to select
1628the key(s) he wants filetype plugin mappings to start with. The default is a
1629backslash.
1630"<unique>" is used to give an error message if the mapping already exists or
1631overlaps with an existing mapping.
1632|:noremap| is used to avoid that any other mappings that the user has defined
1633interferes. You might want to use ":noremap <script>" to allow remapping
1634mappings defined in this script that start with <SID>.
1635
1636The user must have a chance to disable the mappings in a filetype plugin,
1637without disabling everything. Here is an example of how this is done for a
1638plugin for the mail filetype: >
1639
1640 " Add mappings, unless the user didn't want this.
1641 if !exists("no_plugin_maps") && !exists("no_mail_maps")
1642 " Quote text by inserting "> "
1643 if !hasmapto('<Plug>MailQuote')
1644 vmap <buffer> <LocalLeader>q <Plug>MailQuote
1645 nmap <buffer> <LocalLeader>q <Plug>MailQuote
1646 endif
1647 vnoremap <buffer> <Plug>MailQuote :s/^/> /<CR>
1648 nnoremap <buffer> <Plug>MailQuote :.,$s/^/> /<CR>
1649 endif
1650
1651Two global variables are used:
1652no_plugin_maps disables mappings for all filetype plugins
1653no_mail_maps disables mappings for a specific filetype
1654
1655
1656USER COMMANDS
1657
1658To add a user command for a specific file type, so that it can only be used in
1659one buffer, use the "-buffer" argument to |:command|. Example: >
1660
1661 :command -buffer Make make %:r.s
1662
1663
1664VARIABLES
1665
1666A filetype plugin will be sourced for each buffer of the type it's for. Local
1667script variables |s:var| will be shared between all invocations. Use local
1668buffer variables |b:var| if you want a variable specifically for one buffer.
1669
1670
1671FUNCTIONS
1672
1673When defining a function, this only needs to be done once. But the filetype
1674plugin will be sourced every time a file with this filetype will be opened.
1675This construct make sure the function is only defined once: >
1676
1677 :if !exists("*s:Func")
1678 : function s:Func(arg)
1679 : ...
1680 : endfunction
1681 :endif
1682<
1683
1684UNDO *undo_ftplugin*
1685
1686When the user does ":setfiletype xyz" the effect of the previous filetype
1687should be undone. Set the b:undo_ftplugin variable to the commands that will
1688undo the settings in your filetype plugin. Example: >
1689
1690 let b:undo_ftplugin = "setlocal fo< com< tw< commentstring<"
1691 \ . "| unlet b:match_ignorecase b:match_words b:match_skip"
1692
1693Using ":setlocal" with "<" after the option name resets the option to its
1694global value. That is mostly the best way to reset the option value.
1695
1696This does require removing the "C" flag from 'cpoptions' to allow line
1697continuation, as mentioned above |use-cpo-save|.
1698
1699
1700FILE NAME
1701
1702The filetype must be included in the file name |ftplugin-name|. Use one of
1703these three forms:
1704
1705 .../ftplugin/stuff.vim
1706 .../ftplugin/stuff_foo.vim
1707 .../ftplugin/stuff/bar.vim
1708
1709"stuff" is the filetype, "foo" and "bar" are arbitrary names.
1710
1711
1712SUMMARY *ftplugin-special*
1713
1714Summary of special things to use in a filetype plugin:
1715
1716<LocalLeader> Value of "maplocalleader", which the user defines as
1717 the keys that filetype plugin mappings start with.
1718
1719:map <buffer> Define a mapping local to the buffer.
1720
1721:noremap <script> Only remap mappings defined in this script that start
1722 with <SID>.
1723
1724:setlocal Set an option for the current buffer only.
1725
1726:command -buffer Define a user command local to the buffer.
1727
1728exists("*s:Func") Check if a function was already defined.
1729
1730Also see |plugin-special|, the special things used for all plugins.
1731
1732==============================================================================
1733*41.12* Writing a compiler plugin *write-compiler-plugin*
1734
1735A compiler plugin sets options for use with a specific compiler. The user can
1736load it with the |:compiler| command. The main use is to set the
1737'errorformat' and 'makeprg' options.
1738
1739Easiest is to have a look at examples. This command will edit all the default
1740compiler plugins: >
1741
1742 :next $VIMRUNTIME/compiler/*.vim
1743
1744Use |:next| to go to the next plugin file.
1745
1746There are two special items about these files. First is a mechanism to allow
1747a user to overrule or add to the default file. The default files start with: >
1748
1749 :if exists("current_compiler")
1750 : finish
1751 :endif
1752 :let current_compiler = "mine"
1753
1754When you write a compiler file and put it in your personal runtime directory
1755(e.g., ~/.vim/compiler for Unix), you set the "current_compiler" variable to
1756make the default file skip the settings.
1757
1758The second mechanism is to use ":set" for ":compiler!" and ":setlocal" for
1759":compiler". Vim defines the ":CompilerSet" user command for this. However,
1760older Vim versions don't, thus your plugin should define it then. This is an
1761example: >
1762
1763 if exists(":CompilerSet") != 2
1764 command -nargs=* CompilerSet setlocal <args>
1765 endif
1766 CompilerSet errorformat& " use the default 'errorformat'
1767 CompilerSet makeprg=nmake
1768
1769When you write a compiler plugin for the Vim distribution or for a system-wide
1770runtime directory, use the mechanism mentioned above. When
1771"current_compiler" was already set by a user plugin nothing will be done.
1772
1773When you write a compiler plugin to overrule settings from a default plugin,
1774don't check "current_compiler". This plugin is supposed to be loaded
1775last, thus it should be in a directory at the end of 'runtimepath'. For Unix
1776that could be ~/.vim/after/compiler.
1777
1778==============================================================================
1779
1780Next chapter: |usr_42.txt| Add new menus
1781
1782Copyright: see |manual-copyright| vim:tw=78:ts=8:ft=help:norl: