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