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