comparison runtime/doc/usr_41.txt @ 7:3fc0f57ecb91 v7.0001

updated for version 7.0001
author vimboss
date Sun, 13 Jun 2004 20:20:40 +0000
parents
children cc049b00ee70
comparison
equal deleted inserted replaced
6:c2daee826b8f 7:3fc0f57ecb91
1 *usr_41.txt* For Vim version 7.0aa. Last change: 2004 May 06
2
3 VIM USER MANUAL - by Bram Moolenaar
4
5 Write a Vim script
6
7
8 The Vim script language is used for the startup vimrc file, syntax files, and
9 many other things. This chapter explains the items that can be used in a Vim
10 script. 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
27 Table of contents: |usr_toc.txt|
28
29 ==============================================================================
30 *41.1* Introduction *vim-script-intro*
31
32 Your first experience with Vim scripts is the vimrc file. Vim reads it when
33 it starts up and executes the commands. You can set options to values you
34 prefer. 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
37 specific file type. A complicated macro can be defined by a separate Vim
38 script file. You can think of other uses yourself.
39
40 Let'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
54 The ":let" command assigns a value to a variable. The generic form is: >
55
56 :let {variable} = {expression}
57
58 In this case the variable name is "i" and the expression is a simple value,
59 the number one.
60 The ":while" command starts a loop. The generic form is: >
61
62 :while {condition}
63 : {statements}
64 :endwhile
65
66 The statements until the matching ":endwhile" are executed for as long as the
67 condition is true. The condition used here is the expression "i < 5". This
68 is true when the variable i is smaller than five.
69 The ":echo" command prints its arguments. In this case the string "count
70 is" and the value of the variable i. Since i is one, this will print:
71
72 count is 1 ~
73
74 Then 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
76 variable.
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
89 THREE KINDS OF NUMBERS
90
91 Numbers can be decimal, hexadecimal or octal. A hexadecimal number starts
92 with "0x" or "0X". For example "0x1f" is 31. An octal number starts with a
93 zero. "017" is 15. Careful: don't put a zero before a decimal number, it
94 will be interpreted as an octal number!
95 The ":echo" command always prints decimal numbers. Example: >
96
97 :echo 0x7f 036
98 < 127 30 ~
99
100 A number is made negative with a minus sign. This also works for hexadecimal
101 and octal numbers. A minus sign is also for subtraction. Compare this with
102 the previous example: >
103
104 :echo 0x7f -036
105 < 97 ~
106
107 White space in an expression is ignored. However, it's recommended to use it
108 for separating items, to make the expression easier to read. For example, to
109 avoid the confusion with a negative number, put a space between the minus sign
110 and the following number: >
111
112 :echo 0x7f - 036
113
114 ==============================================================================
115 *41.2* Variables
116
117 A variable name consists of ASCII letters, digits and the underscore. It
118 cannot 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
126 Invalid names are "foo+bar" and "6var".
127 These variables are global. To see a list of currently defined variables
128 use this command: >
129
130 :let
131
132 You can use global variables everywhere. This also means that when the
133 variable "count" is used in one script file, it might also be used in another
134 file. This leads to confusion at least, and real problems at worst. To avoid
135 this, you can use a variable local to a script file by prepending "s:". For
136 example, 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
144 Since "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
147 about script-local variables here: |script-variable|.
148
149 There are more kinds of variables, see |internal-variables|. The most often
150 used 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
158 DELETING VARIABLES
159
160 Variables take up memory and show up in the output of the ":let" command. To
161 delete a variable use the ":unlet" command. Example: >
162
163 :unlet s:count
164
165 This deletes the script-local variable "s:count" to free up the memory it
166 uses. If you are not sure if the variable exists, and don't want an error
167 message when it doesn't, append !: >
168
169 :unlet! s:count
170
171 When a script finishes, the local variables used there will not be
172 automatically freed. The next time the script executes, it can still use the
173 old 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
181 The "exists()" function checks if a variable has already been defined. Its
182 argument is the name of the variable you want to check. Not the variable
183 itself! If you would do this: >
184
185 :if !exists(s:call_count)
186
187 Then the value of s:call_count will be used as the name of the variable that
188 exists() checks. That's not what you want.
189 The exclamation mark ! negates a value. When the value was true, it
190 becomes false. When it was false, it becomes true. You can read it as "not".
191 Thus "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
195 STRING VARIABLES AND CONSTANTS
196
197 So far only numbers were used for the variable value. Strings can be used as
198 well. Numbers and strings are the only two types of variables that Vim
199 supports. The type is dynamic, it is set each time when assigning a value to
200 the variable with ":let".
201 To assign a string value to a variable, you need to use a string constant.
202 There are two types of these. First the string in double quotes: >
203
204 :let name = "peter"
205 :echo name
206 < peter ~
207
208 If you want to include a double quote inside the string, put a backslash in
209 front of it: >
210
211 :let name = "\"peter\""
212 :echo name
213 < "peter" ~
214
215 To 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
221 Inside a single-quote string all the characters are taken literally. The
222 drawback is that it's impossible to include a single quote. A backslash is
223 taken literally as well, thus you can't use it to change the meaning of the
224 character after it.
225 In double-quote strings it is possible to use special characters. Here are
226 a 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
238 The last two are just examples. The "\<name>" form can be used to include
239 the special key "name".
240 See |expr-quote| for the full list of special items in a string.
241
242 ==============================================================================
243 *41.3* Expressions
244
245 Vim has a rich, yet simple way to handle expressions. You can read the
246 definition here: |expression-syntax|. Here we will show the most common
247 items.
248 The numbers, strings and variables mentioned above are expressions by
249 themselves. Thus everywhere an expression is expected, you can use a number,
250 string or variable. Other basic items in an expression are:
251
252 $NAME environment variable
253 &name option
254 @r register
255
256 Examples: >
257
258 :echo "The value of 'tabstop' is" &ts
259 :echo "Your home directory is" $HOME
260 :if @a > 5
261
262 The &name form can be used to save an option value, set it to a new value,
263 do 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
270 This makes sure the "The Start" pattern is used with the 'ignorecase' option
271 off. Still, it keeps the value that the user had set.
272
273
274 MATHEMATICS
275
276 It becomes more interesting if we combine these basic items. Let's start with
277 mathematics on numbers:
278
279 a + b add
280 a - b subtract
281 a * b multiply
282 a / b divide
283 a % b modulo
284
285 The usual precedence is used. Example: >
286
287 :echo 10 + 5 * 2
288 < 20 ~
289
290 Grouping is done with braces. No surprises here. Example: >
291
292 :echo (10 + 5) * 2
293 < 30 ~
294
295 Strings can be concatenated with ".". Example: >
296
297 :echo "foo" . "bar"
298 < foobar ~
299
300 When the ":echo" command gets multiple arguments, it separates them with a
301 space. In the example the argument is a single expression, thus no space is
302 inserted.
303
304 Borrowed from the C language is the conditional expression:
305
306 a ? b : c
307
308 If "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
314 The three parts of the constructs are always evaluated first, thus you could
315 see it work as:
316
317 (a) ? (b) : (c)
318
319 ==============================================================================
320 *41.4* Conditionals
321
322 The ":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
329 Only when the expression {condition} evaluates to true (non-zero) will the
330 {statements} be executed. These must still be valid commands. If they
331 contain 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
340 The 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
349 This works just like using ":else" and then "if", but without the need for an
350 extra ":endif".
351 A useful example for your vimrc file is checking the 'term' option and
352 doing 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
363 LOGIC OPERATIONS
364
365 We already used some of them in the examples. These are the most often used
366 ones:
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
375 The 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
383 Here "v:version" is a variable defined by Vim, which has the value of the Vim
384 version. 600 is for version 6.0. Version 6.1 has the value 601. This is
385 very useful to write a script that works with multiple versions of Vim.
386 |v:version|
387
388 The logic operators work both for numbers and strings. When comparing two
389 strings, the mathematical difference is used. This compares byte values,
390 which may not be right for some languages.
391 When comparing a string with a number, the string is first converted to a
392 number. This is a bit tricky, because when a string doesn't look like a
393 number, the number zero is used. Example: >
394
395 :if 0 == "one"
396 : echo "yes"
397 :endif
398
399 This will echo "yes", because "one" doesn't look like a number, thus it is
400 converted to the number zero.
401
402 For strings there are two more items:
403
404 a =~ b matches with
405 a !~ b does not match with
406
407 The left item "a" is used as a string. The right item "b" is used as a
408 pattern, 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
417 Notice the use of a single-quote string for the pattern. This is useful,
418 because backslashes need to be doubled in a double-quote string and patterns
419 tend to contain many backslashes.
420
421 The 'ignorecase' option is used when comparing strings. When you don't want
422 that, append "#" to match case and "?" to ignore case. Thus "==?" compares
423 two strings to be equal while ignoring case. And "!~#" checks if a pattern
424 doesn't match, also checking the case of letters. For the full table see
425 |expr-==|.
426
427
428 MORE LOOPING
429
430 The ":while" command was already mentioned. Two more statements can be used
431 in 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
438 Example: >
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
451 The ":sleep" command makes Vim take a nap. The "50m" specifies fifty
452 milliseconds. Another example is ":sleep 4", which sleeps for four seconds.
453
454 ==============================================================================
455 *41.5* Executing an expression
456
457 So 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
459 very 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
464 The "." 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
466 will be executed is: >
467
468 :tag get_cmd
469
470 The ":execute" command can only execute colon commands. The ":normal" command
471 executes Normal mode commands. However, its argument is not an expression but
472 the literal command characters. Example: >
473
474 :normal gg=G
475
476 This jumps to the first line and formats all lines with the "=" operator.
477 To make ":normal" work with an expression, combine ":execute" with it.
478 Example: >
479
480 :execute "normal " . normal_commands
481
482 The variable "normal_commands" must contain the Normal mode commands.
483 Make sure that the argument for ":normal" is a complete command. Otherwise
484 Vim will run into the end of the argument and abort the command. For example,
485 if you start Insert mode, you must leave Insert mode as well. This works: >
486
487 :execute "normal Inew text \<Esc>"
488
489 This inserts "new text " in the current line. Notice the use of the special
490 key "\<Esc>". This avoids having to enter a real <Esc> character in your
491 script.
492
493 ==============================================================================
494 *41.6* Using functions
495
496 Vim defines many functions and provides a large amount of functionality that
497 way. A few examples will be given in this section. You can find the whole
498 list here: |functions|.
499
500 A function is called with the ":call" command. The parameters are passed in
501 between braces, separated by commas. Example: >
502
503 :call search("Date: ", "W")
504
505 This calls the search() function, with arguments "Date: " and "W". The
506 search() function uses its first argument as a search pattern and the second
507 one as flags. The "W" flag means the search doesn't wrap around the end of
508 the file.
509
510 A 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
516 The getline() function obtains a line from the current file. Its argument is
517 a specification of the line number. In this case "." is used, which means the
518 line where the cursor is.
519 The substitute() function does something similar to the ":substitute"
520 command. The first argument is the string on which to perform the
521 substitution. The second argument is the pattern, the third the replacement
522 string. Finally, the last arguments are the flags.
523 The setline() function sets the line, specified by the first argument, to a
524 new string, the second argument. In this example the line under the cursor is
525 replaced with the result of the substitute(). Thus the effect of the three
526 statements is equal to: >
527
528 :substitute/\a/*/g
529
530 Using the functions becomes more interesting when you do more work before and
531 after the substitute() call.
532
533
534 FUNCTIONS *function-list*
535
536 There are many functions. We will mention them here, grouped by what they are
537 used for. You can find an alphabetical list here: |functions|. Use CTRL-] on
538 the function name to jump to detailed help on it.
539
540 String 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
560 Working 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
580 System 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
601 Buffers, 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
618 Folding:
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
624 Syntax 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
631 History:
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
637 Interactive:
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
647 Vim 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
657 Various:
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
681 Vim enables you to define your own functions. The basic function declaration
682 begins 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
691 Let's define a short function to return the smaller of two numbers. It starts
692 with this line: >
693
694 :function Min(num1, num2)
695
696 This 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
702 The special prefix "a:" tells Vim that the variable is a function argument.
703 Let'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
711 The variable "smaller" is a local variable. Variables used inside a function
712 are 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
720 You now use the ":return" statement to return the smallest number to the user.
721 Finally, you end the function: >
722
723 : return smaller
724 :endfunction
725
726 The 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
737 A user defined function is called in exactly the same way as a builtin
738 function. Only the name is different. The Min function can be used like
739 this: >
740
741 :echo Min(5, 8)
742
743 Only now will the function be executed and the lines be interpreted by Vim.
744 If there are mistakes, like using an undefined variable or function, you will
745 now get an error message. When defining the function these errors are not
746 detected.
747
748 When a function reaches ":endfunction" or ":return" is used without an
749 argument, the function returns zero.
750
751 To redefine a function that already exists, use the ! for the ":function"
752 command: >
753
754 :function! Min(num1, num2, num3)
755
756
757 USING A RANGE
758
759 The ":call" command can be given a line range. This can have one of two
760 meanings. When a function has been defined with the "range" keyword, it will
761 take care of the line range itself.
762 The function will be passed the variables "a:firstline" and "a:lastline".
763 These will have the line numbers from the range the function was called with.
764 Example: >
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
776 You can call this function with: >
777
778 :10,30call Count_words()
779
780 It 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
783 range, with the cursor in that line. Example: >
784
785 :function Number()
786 : echo "line " . line(".") . " contains: " . getline(".")
787 :endfunction
788
789 If you call this function with: >
790
791 :10,15call Number()
792
793 The function will be called six times.
794
795
796 VARIABLE NUMBER OF ARGUMENTS
797
798 Vim enables you to define functions that have a variable number of arguments.
799 The following command, for instance, defines a function that must have 1
800 argument (start) and can have up to 20 additional arguments: >
801
802 :function Show(start, ...)
803
804 The variable "a:1" contains the first optional argument, "a:2" the second, and
805 so 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
820 This uses the ":echohl" command to specify the highlighting used for the
821 following ":echo" command. ":echohl None" stops it again. The ":echon"
822 command works like ":echo", but doesn't output a line break.
823
824
825 LISTING FUNCTIONS
826
827 The ":function" command lists the names and arguments of all user-defined
828 functions: >
829
830 :function
831 < function Show(start, ...) ~
832 function GetVimIndent() ~
833 function SetSyn(name) ~
834
835 To 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
844 DEBUGGING
845
846 The line number is useful for when you get an error message or when debugging.
847 See |debug-scripts| about debugging mode.
848 You can also set the 'verbose' option to 12 or higher to see all function
849 calls. Set it to 15 or higher to see every executed line.
850
851
852 DELETING A FUNCTION
853
854 To delete the Show() function: >
855
856 :delfunction Show
857
858 You get an error when the function doesn't exist.
859
860 ==============================================================================
861 *41.8* Exceptions
862
863 Let'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
871 The ":read" command will fail if the file does not exist. Instead of
872 generating an error message, this code catches the error and gives the user a
873 nice message instead.
874
875 For the commands in between ":try" and ":endtry" errors are turned into
876 exceptions. An exception is a string. In the case of an error the string
877 contains the error message. And every error message has a number. In this
878 case, the error we catch contains "E484:". This number is guaranteed to stay
879 the same (the text may change, e.g., it may be translated).
880
881 When the ":read" command causes another error, the pattern "E484:" will not
882 match in it. Thus this exception will not be caught and result in the usual
883 error message.
884
885 You 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
893 This means all errors are caught. But then you will not see errors that are
894 useful, such as "E21: Cannot make changes, 'modifiable' is off".
895
896 Another 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
908 This 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
910 filtering works, something goes wrong in between ":try" and ":finally" or the
911 user cancels the filtering by pressing CTRL-C, the "call delete(tmp)" is
912 always executed. This makes sure you don't leave the temporary file behind.
913
914 More information about exception handling can be found in the reference
915 manual: |exception-handling|.
916
917 ==============================================================================
918 *41.9* Various remarks
919
920 Here is a summary of items that apply to Vim scripts. They are also mentioned
921 elsewhere, but form a nice checklist.
922
923 The end-of-line character depends on the system. For Unix a single <NL>
924 character is used. For MS-DOS, Windows, OS/2 and the like, <CR><LF> is used.
925 This is important when using mappings that end in a <CR>. See |:source_crnl|.
926
927
928 WHITE SPACE
929
930 Blank lines are allowed and ignored.
931
932 Leading whitespace characters (blanks and TABs) are always ignored. The
933 whitespaces between parameters (e.g. between the 'set' and the 'cpoptions' in
934 the example below) are reduced to one blank character and plays the role of a
935 separator, the whitespaces after the last (visible) character may or may not
936 be ignored depending on the situation, see below.
937
938 For a ":set" command involving the "=" (equal) sign, such as in: >
939
940 :set cpoptions =aABceFst
941
942 the whitespace immediately before the "=" sign is ignored. But there can be
943 no whitespace after the "=" sign!
944
945 To include a whitespace character in the value of an option, it must be
946 escaped by a "\" (backslash) as in the following example: >
947
948 :set tags=my\ nice\ file
949
950 The same example written as >
951
952 :set tags=my nice file
953
954 will issue an error, because it is interpreted as: >
955
956 :set tags=my
957 :set nice
958 :set file
959
960
961 COMMENTS
962
963 The character " (the double quote mark) starts a comment. Everything after
964 and including this character until the end-of-line is considered a comment and
965 is ignored, except for commands that don't consider comments, as shown in
966 examples below. A comment can start on any character position on the line.
967
968 There 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
975 The abbreviation 'dev' will be expanded to 'development " shorthand'. The
976 mapping of <F3> will actually be the whole line after the 'o# ....' including
977 the '" insert include'. The "execute" command will give an error. The "!"
978 command will send everything after it to the shell, causing an error for an
979 unmatched '"' character.
980 There can be no comment after ":map", ":abbreviate", ":execute" and "!"
981 commands (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
988 With the '|' character the command is separated from the next one. And that
989 next command is only a comment.
990
991 Notice that there is no white space before the '|' in the abbreviation and
992 mapping. For these commands, any character until the end-of-line or '|' is
993 included. As a consequence of this behavior, you don't always see that
994 trailing whitespace is included: >
995
996 :map <F4> o#include
997
998 To avoid these problems, you can set the 'list' option when editing vimrc
999 files.
1000
1001
1002 PITFALLS
1003
1004 Even bigger problem arises in the following example: >
1005
1006 :map ,ab o#include
1007 :unmap ,ab
1008
1009 Here the unmap command will not work, because it tries to unmap ",ab ". This
1010 does not exist as a mapped sequence. An error will be issued, which is very
1011 hard to identify, because the ending whitespace character in ":unmap ,ab " is
1012 not visible.
1013
1014 And this is the same as what happens when one uses a comment after an 'unmap'
1015 command: >
1016
1017 :unmap ,ab " comment
1018
1019 Here 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
1025 RESTORING THE VIEW
1026
1027 Sometimes you want to make a change and go back to where cursor was.
1028 Restoring the relative position would also be nice, so that the same line
1029 appears at the top of the window.
1030 This example yanks the current line, puts it above the first line in the
1031 file and then restores the view: >
1032
1033 map ,p ma"aYHmbgg"aP`bzt`a
1034
1035 What 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
1047 PACKAGING
1048
1049 To avoid your function names to interfere with functions that you get from
1050 others, 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.
1056 Example: >
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
1078 You can write a Vim script in such a way that many people can use it. This is
1079 called a plugin. Vim users can drop your script in their plugin directory and
1080 use its features right away |add-plugin|.
1081
1082 There are actually two types of plugins:
1083
1084 global plugins: For all types of files.
1085 filetype plugins: Only for files of a specific type.
1086
1087 In this section the first type is explained. Most items are also relevant for
1088 writing filetype plugins. The specifics for filetype plugins are in the next
1089 section |write-filetype-plugin|.
1090
1091
1092 NAME
1093
1094 First of all you must choose a name for your plugin. The features provided
1095 by the plugin should be clear from its name. And it should be unlikely that
1096 someone else writes a plugin with the same name but which does something
1097 different. And please limit the name to 8 characters, to avoid problems on
1098 old Windows systems.
1099
1100 A script that corrects typing mistakes could be called "typecorr.vim". We
1101 will use it here as an example.
1102
1103 For the plugin to work for everybody, it should follow a few guidelines. This
1104 will be explained step-by-step. The complete example plugin is at the end.
1105
1106
1107 BODY
1108
1109 Let'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
1118 The actual list should be much longer, of course.
1119
1120 The line numbers have only been added to explain a few things, don't put them
1121 in your plugin file!
1122
1123
1124 HEADER
1125
1126 You will probably add new corrections to the plugin and soon have several
1127 versions laying around. And when distributing this file, people will want to
1128 know who wrote this wonderful plugin and where they can send remarks.
1129 Therefore, 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
1135 About copyright and licensing: Since plugins are very useful and it's hardly
1136 worth restricting their distribution, please consider making your plugin
1137 either public domain or use the Vim |license|. A short note about this near
1138 the top of the plugin should be sufficient. Example: >
1139
1140 4 " License: This file is placed in the public domain.
1141
1142
1143 LINE CONTINUATION, AVOIDING SIDE EFFECTS *use-cpo-save*
1144
1145 In line 18 above, the line-continuation mechanism is used |line-continuation|.
1146 Users with 'compatible' set will run into trouble here, they will get an error
1147 message. We can't just reset 'compatible', because that has a lot of side
1148 effects. To avoid this, we will set the 'cpoptions' option to its Vim default
1149 value and restore it later. That will allow the use of line-continuation and
1150 make 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
1157 We first store the old value of 'cpoptions' in the s:save_cpo variable. At
1158 the end of the plugin this value is restored.
1159
1160 Notice that a script-local variable is used |s:var|. A global variable could
1161 already be in use for something else. Always use script-local variables for
1162 things that are only used in the script.
1163
1164
1165 NOT LOADING
1166
1167 It's possible that a user doesn't always want to load this plugin. Or the
1168 system administrator has dropped it in the system-wide plugin directory, but a
1169 user has his own plugin he wants to use. Then the user must have a chance to
1170 disable 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
1177 This also avoids that when the script is loaded twice it would cause error
1178 messages for redefining functions and cause trouble for autocommands that are
1179 added twice.
1180
1181
1182 MAPPING
1183
1184 Now let's make the plugin more interesting: We will add a mapping that adds a
1185 correction for the word under the cursor. We could just pick a key sequence
1186 for this mapping, but the user might already use it for something else. To
1187 allow the user to define which keys a mapping in a plugin uses, the <Leader>
1188 item can be used: >
1189
1190 22 map <unique> <Leader>a <Plug>TypecorrAdd
1191
1192 The "<Plug>TypecorrAdd" thing will do the work, more about that further on.
1193
1194 The user can set the "mapleader" variable to the key sequence that he wants
1195 this mapping to start with. Thus if the user has done: >
1196
1197 let mapleader = "_"
1198
1199 the mapping will define "_a". If the user didn't do this, the default value
1200 will be used, which is a backslash. Then a map for "\a" will be defined.
1201
1202 Note that <unique> is used, this will cause an error message if the mapping
1203 already happened to exist. |:map-<unique>|
1204
1205 But what if the user wants to define his own key sequence? We can allow that
1206 with this mechanism: >
1207
1208 21 if !hasmapto('<Plug>TypecorrAdd')
1209 22 map <unique> <Leader>a <Plug>TypecorrAdd
1210 23 endif
1211
1212 This checks if a mapping to "<Plug>TypecorrAdd" already exists, and only
1213 defines the mapping from "<Leader>a" if it doesn't. The user then has a
1214 chance of putting this in his vimrc file: >
1215
1216 map ,c <Plug>TypecorrAdd
1217
1218 Then the mapped key sequence will be ",c" instead of "_a" or "\a".
1219
1220
1221 PIECES
1222
1223 If a script gets longer, you often want to break up the work in pieces. You
1224 can use functions or mappings for this. But you don't want these functions
1225 and mappings to interfere with the ones from other scripts. For example, you
1226 could define a function Add(), but another script could try to define the same
1227 function. To avoid this, we define the function local to the script by
1228 prepending it with "s:".
1229
1230 We 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
1238 Now we can call the function s:Add() from within this script. If another
1239 script also defines s:Add(), it will be local to that script and can only
1240 be called from the script it was defined in. There can also be a global Add()
1241 function (without the "s:"), which is again another function.
1242
1243 <SID> can be used with mappings. It generates a script ID, which identifies
1244 the 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
1250 Thus when a user types "\a", this sequence is invoked: >
1251
1252 \a -> <Plug>TypecorrAdd -> <SID>Add -> :call <SID>Add()
1253
1254 If another script would also map <SID>Add, it would get another script ID and
1255 thus define another mapping.
1256
1257 Note that instead of s:Add() we use <SID>Add() here. That is because the
1258 mapping is typed by the user, thus outside of the script. The <SID> is
1259 translated to the script ID, so that Vim knows in which script to look for
1260 the Add() function.
1261
1262 This is a bit complicated, but it's required for the plugin to work together
1263 with other plugins. The basic rule is that you use <SID>Add() in mappings and
1264 s:Add() in other places (the script itself, autocommands, user commands).
1265
1266 We can also add a menu entry to do the same as the mapping: >
1267
1268 26 noremenu <script> Plugin.Add\ Correction <SID>Add
1269
1270 The "Plugin" menu is recommended for adding menu items for plugins. In this
1271 case only one item is used. When adding more items, creating a submenu is
1272 recommended. For example, "Plugin.CVS" could be used for a plugin that offers
1273 CVS operations "Plugin.CVS.checkin", "Plugin.CVS.checkout", etc.
1274
1275 Note that in line 28 ":noremap" is used to avoid that any other mappings cause
1276 trouble. Someone may have remapped ":call", for example. In line 24 we also
1277 use ":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
1279 script. |:map-<script>| The same is done in line 26 for ":noremenu".
1280 |:menu-<script>|
1281
1282
1283 <SID> AND <Plug> *using-<Plug>*
1284
1285 Both <SID> and <Plug> are used to avoid that mappings of typed keys interfere
1286 with mappings that are only to be used from other mappings. Note the
1287 difference 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
1308 USER COMMAND
1309
1310 Now 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
1316 The user command is defined only if no command with the same name already
1317 exists. Otherwise we would get an error here. Overriding the existing user
1318 command with ":command!" is not a good idea, this would probably make the user
1319 wonder why the command he defined himself doesn't work. |:command|
1320
1321
1322 SCRIPT VARIABLES
1323
1324 When a variable starts with "s:" it is a script variable. It can only be used
1325 inside a script. Outside the script it's not visible. This avoids trouble
1326 with using the same variable name in different scripts. The variables will be
1327 kept as long as Vim is running. And the same variables are used when sourcing
1328 the same script again. |s:var|
1329
1330 The fun is that these variables can also be used in functions, autocommands
1331 and user commands that are defined in the script. In our example we can add
1332 a 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
1342 First s:count is initialized to 4 in the script itself. When later the
1343 s:Add() function is called, it increments s:count. It doesn't matter from
1344 where the function was called, since it has been defined in the script, it
1345 will use the local variables from this script.
1346
1347
1348 THE RESULT
1349
1350 Here 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
1395 Line 33 wasn't explained yet. It applies the new correction to the word under
1396 the cursor. The |:normal| command is used to use the new abbreviation. Note
1397 that mappings and abbreviations are expanded here, even though the function
1398 was called from a mapping defined with ":noremap".
1399
1400 Using "unix" for the 'fileformat' option is recommended. The Vim scripts will
1401 then work everywhere. Scripts with 'fileformat' set to "dos" do not work on
1402 Unix. Also see |:source_crnl|. To be sure it is set right, do this before
1403 writing the file: >
1404
1405 :set fileformat=unix
1406
1407
1408 DOCUMENTATION *write-local-help*
1409
1410 It's a good idea to also write some documentation for your plugin. Especially
1411 when its behavior can be changed by the user. See |add-local-help| for how
1412 they are installed.
1413
1414 Here 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
1434 The first line is actually the only one for which the format matters. It will
1435 be extracted from the help file to be put in the "LOCAL ADDITIONS:" section of
1436 help.txt |local-additions|. The first "*" must be in the first column of the
1437 first line. After adding your help file do ":help" and check that the entries
1438 line up nicely.
1439
1440 You can add more tags inside ** in your help file. But be careful not to use
1441 existing help tags. You would probably use the name of your plugin in most of
1442 them, like "typecorr-settings" in the example.
1443
1444 Using references to other parts of the help in || is recommended. This makes
1445 it easy for the user to find associated help.
1446
1447
1448 FILETYPE DETECTION *plugin-filetype*
1449
1450 If your filetype is not already detected by Vim, you should create a filetype
1451 detection snippet in a separate file. It is usually in the form of an
1452 autocommand that sets the filetype when the file name matches a pattern.
1453 Example: >
1454
1455 au BufNewFile,BufRead *.foo set filetype=foofoo
1456
1457 Write this single-line file as "ftdetect/foofoo.vim" in the first directory
1458 that appears in 'runtimepath'. For Unix that would be
1459 "~/.vim/ftdetect/foofoo.vim". The convention is to use the name of the
1460 filetype for the script name.
1461
1462 You can make more complicated checks if you like, for example to inspect the
1463 contents of the file to recognize the language. Also see |new-filetype|.
1464
1465
1466 SUMMARY *plugin-special*
1467
1468 Summary of special things to use in a plugin:
1469
1470 s:name Variables local to the script.
1471
1472 <SID> Script-ID, used for mappings and functions local to
1473 the script.
1474
1475 hasmapto() 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
1486 exists(":Cmd") Check if a user command already exists.
1487
1488 ==============================================================================
1489 *41.11* Writing a filetype plugin *write-filetype-plugin* *ftplugin*
1490
1491 A filetype plugin is like a global plugin, except that it sets options and
1492 defines mappings for the current buffer only. See |add-filetype-plugin| for
1493 how this type of plugin is used.
1494
1495 First read the section on global plugins above |41.10|. All that is said there
1496 also applies to filetype plugins. There are a few extras, which are explained
1497 here. The essential thing is that a filetype plugin should only have an
1498 effect on the current buffer.
1499
1500
1501 DISABLING
1502
1503 If you are writing a filetype plugin to be used by many people, they need a
1504 chance 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
1512 This also needs to be used to avoid that the same plugin is executed twice for
1513 the same buffer (happens when using an ":edit" command without arguments).
1514
1515 Now users can disable loading the default plugin completely by making a
1516 filetype plugin with only this line: >
1517
1518 let b:did_ftplugin = 1
1519
1520 This does require that the filetype plugin directory comes before $VIMRUNTIME
1521 in 'runtimepath'!
1522
1523 If you do want to use the default plugin, but overrule one of the settings,
1524 you can write the different setting in a script: >
1525
1526 setlocal textwidth=70
1527
1528 Now write this in the "after" directory, so that it gets sourced after the
1529 distributed "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
1534 OPTIONS
1535
1536 To make sure the filetype plugin only affects the current buffer use the >
1537
1538 :setlocal
1539
1540 command to set options. And only set options which are local to a buffer (see
1541 the help for the option to check that). When using |:setlocal| for global
1542 options or options local to a window, the value will change for many buffers,
1543 and that is not what a filetype plugin should do.
1544
1545 When 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
1547 changed an option value already. First resetting to the default value and
1548 then changing it often a good idea. Example: >
1549
1550 :setlocal formatoptions& formatoptions+=ro
1551
1552
1553 MAPPINGS
1554
1555 To make sure mappings will only work in the current buffer use the >
1556
1557 :map <buffer>
1558
1559 command. This needs to be combined with the two-step mapping explained above.
1560 An 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
1569 mapping. This starts with |<LocalLeader>|, which allows the user to select
1570 the key(s) he wants filetype plugin mappings to start with. The default is a
1571 backslash.
1572 "<unique>" is used to give an error message if the mapping already exists or
1573 overlaps with an existing mapping.
1574 |:noremap| is used to avoid that any other mappings that the user has defined
1575 interferes. You might want to use ":noremap <script>" to allow remapping
1576 mappings defined in this script that start with <SID>.
1577
1578 The user must have a chance to disable the mappings in a filetype plugin,
1579 without disabling everything. Here is an example of how this is done for a
1580 plugin 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
1593 Two global variables are used:
1594 no_plugin_maps disables mappings for all filetype plugins
1595 no_mail_maps disables mappings for a specific filetype
1596
1597
1598 USER COMMANDS
1599
1600 To add a user command for a specific file type, so that it can only be used in
1601 one buffer, use the "-buffer" argument to |:command|. Example: >
1602
1603 :command -buffer Make make %:r.s
1604
1605
1606 VARIABLES
1607
1608 A filetype plugin will be sourced for each buffer of the type it's for. Local
1609 script variables |s:var| will be shared between all invocations. Use local
1610 buffer variables |b:var| if you want a variable specifically for one buffer.
1611
1612
1613 FUNCTIONS
1614
1615 When defining a function, this only needs to be done once. But the filetype
1616 plugin will be sourced every time a file with this filetype will be opened.
1617 This 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
1626 UNDO *undo_ftplugin*
1627
1628 When the user does ":setfiletype xyz" the effect of the previous filetype
1629 should be undone. Set the b:undo_ftplugin variable to the commands that will
1630 undo 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
1635 Using ":setlocal" with "<" after the option name resets the option to its
1636 global value. That is mostly the best way to reset the option value.
1637
1638 This does require removing the "C" flag from 'cpoptions' to allow line
1639 continuation, as mentioned above |use-cpo-save|.
1640
1641
1642 FILE NAME
1643
1644 The filetype must be included in the file name |ftplugin-name|. Use one of
1645 these 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
1654 SUMMARY *ftplugin-special*
1655
1656 Summary 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
1670 exists("*s:Func") Check if a function was already defined.
1671
1672 Also see |plugin-special|, the special things used for all plugins.
1673
1674 ==============================================================================
1675 *41.12* Writing a compiler plugin *write-compiler-plugin*
1676
1677 A compiler plugin sets options for use with a specific compiler. The user can
1678 load it with the |:compiler| command. The main use is to set the
1679 'errorformat' and 'makeprg' options.
1680
1681 Easiest is to have a look at examples. This command will edit all the default
1682 compiler plugins: >
1683
1684 :next $VIMRUNTIME/compiler/*.vim
1685
1686 Use |:next| to go to the next plugin file.
1687
1688 There are two special items about these files. First is a mechanism to allow
1689 a 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
1696 When 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
1698 make the default file skip the settings.
1699
1700 The second mechanism is to use ":set" for ":compiler!" and ":setlocal" for
1701 ":compiler". Vim defines the ":CompilerSet" user command for this. However,
1702 older Vim versions don't, thus your plugin should define it then. This is an
1703 example: >
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
1711 When you write a compiler plugin for the Vim distribution or for a system-wide
1712 runtime directory, use the mechanism mentioned above. When
1713 "current_compiler" was already set by a user plugin nothing will be done.
1714
1715 When you write a compiler plugin to overrule settings from a default plugin,
1716 don't check "current_compiler". This plugin is supposed to be loaded
1717 last, thus it should be in a directory at the end of 'runtimepath'. For Unix
1718 that could be ~/.vim/after/compiler.
1719
1720 ==============================================================================
1721
1722 Next chapter: |usr_42.txt| Add new menus
1723
1724 Copyright: see |manual-copyright| vim:tw=78:ts=8:ft=help:norl: