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