Bram Moolenaar | af7f641 | 2005-01-17 22:11:23 +0000 | [diff] [blame] | 1 | *usr_41.txt* For Vim version 7.0aa. Last change: 2005 Jan 17 |
Bram Moolenaar | 071d427 | 2004-06-13 20:20:40 +0000 | [diff] [blame] | 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). |
Bram Moolenaar | b7fcef5 | 2005-01-02 11:31:05 +0000 | [diff] [blame] | 87 | Note: |
| 88 | You can try out the examples by yanking the lines from the text here |
| 89 | and executing them with :@" |
Bram Moolenaar | 071d427 | 2004-06-13 20:20:40 +0000 | [diff] [blame] | 90 | |
Bram Moolenaar | af7f641 | 2005-01-17 22:11:23 +0000 | [diff] [blame] | 91 | The example was given to explain the commands, but you would really want to |
| 92 | make 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 | |
| 98 | We won't explain how |:for| and |range()| work right now. Follow the links if |
| 99 | you are impatient. |
| 100 | |
Bram Moolenaar | 071d427 | 2004-06-13 20:20:40 +0000 | [diff] [blame] | 101 | |
| 102 | THREE KINDS OF NUMBERS |
| 103 | |
| 104 | Numbers can be decimal, hexadecimal or octal. A hexadecimal number starts |
| 105 | with "0x" or "0X". For example "0x1f" is 31. An octal number starts with a |
| 106 | zero. "017" is 15. Careful: don't put a zero before a decimal number, it |
| 107 | will be interpreted as an octal number! |
| 108 | The ":echo" command always prints decimal numbers. Example: > |
| 109 | |
| 110 | :echo 0x7f 036 |
| 111 | < 127 30 ~ |
| 112 | |
| 113 | A number is made negative with a minus sign. This also works for hexadecimal |
| 114 | and octal numbers. A minus sign is also for subtraction. Compare this with |
| 115 | the previous example: > |
| 116 | |
| 117 | :echo 0x7f -036 |
| 118 | < 97 ~ |
| 119 | |
| 120 | White space in an expression is ignored. However, it's recommended to use it |
| 121 | for separating items, to make the expression easier to read. For example, to |
| 122 | avoid the confusion with a negative number, put a space between the minus sign |
| 123 | and the following number: > |
| 124 | |
| 125 | :echo 0x7f - 036 |
| 126 | |
| 127 | ============================================================================== |
| 128 | *41.2* Variables |
| 129 | |
| 130 | A variable name consists of ASCII letters, digits and the underscore. It |
| 131 | cannot 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 | |
| 139 | Invalid names are "foo+bar" and "6var". |
| 140 | These variables are global. To see a list of currently defined variables |
| 141 | use this command: > |
| 142 | |
| 143 | :let |
| 144 | |
| 145 | You can use global variables everywhere. This also means that when the |
| 146 | variable "count" is used in one script file, it might also be used in another |
| 147 | file. This leads to confusion at least, and real problems at worst. To avoid |
| 148 | this, you can use a variable local to a script file by prepending "s:". For |
| 149 | example, 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 | |
| 157 | Since "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 |
| 160 | about script-local variables here: |script-variable|. |
| 161 | |
| 162 | There are more kinds of variables, see |internal-variables|. The most often |
| 163 | used 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 | |
| 171 | DELETING VARIABLES |
| 172 | |
| 173 | Variables take up memory and show up in the output of the ":let" command. To |
| 174 | delete a variable use the ":unlet" command. Example: > |
| 175 | |
| 176 | :unlet s:count |
| 177 | |
| 178 | This deletes the script-local variable "s:count" to free up the memory it |
| 179 | uses. If you are not sure if the variable exists, and don't want an error |
| 180 | message when it doesn't, append !: > |
| 181 | |
| 182 | :unlet! s:count |
| 183 | |
| 184 | When a script finishes, the local variables used there will not be |
| 185 | automatically freed. The next time the script executes, it can still use the |
| 186 | old 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 | |
| 194 | The "exists()" function checks if a variable has already been defined. Its |
| 195 | argument is the name of the variable you want to check. Not the variable |
| 196 | itself! If you would do this: > |
| 197 | |
| 198 | :if !exists(s:call_count) |
| 199 | |
| 200 | Then the value of s:call_count will be used as the name of the variable that |
| 201 | exists() checks. That's not what you want. |
| 202 | The exclamation mark ! negates a value. When the value was true, it |
| 203 | becomes false. When it was false, it becomes true. You can read it as "not". |
| 204 | Thus "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 | |
| 208 | STRING VARIABLES AND CONSTANTS |
| 209 | |
| 210 | So far only numbers were used for the variable value. Strings can be used as |
| 211 | well. Numbers and strings are the only two types of variables that Vim |
| 212 | supports. The type is dynamic, it is set each time when assigning a value to |
| 213 | the variable with ":let". |
| 214 | To assign a string value to a variable, you need to use a string constant. |
| 215 | There are two types of these. First the string in double quotes: > |
| 216 | |
| 217 | :let name = "peter" |
| 218 | :echo name |
| 219 | < peter ~ |
| 220 | |
| 221 | If you want to include a double quote inside the string, put a backslash in |
| 222 | front of it: > |
| 223 | |
| 224 | :let name = "\"peter\"" |
| 225 | :echo name |
| 226 | < "peter" ~ |
| 227 | |
| 228 | To 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 Moolenaar | 3fdfa4a | 2004-10-07 21:02:47 +0000 | [diff] [blame] | 234 | Inside a single-quote string all the characters are as they are. The drawback |
| 235 | is that it's impossible to include a single quote. A backslash is taken |
| 236 | literally as well, thus you can't use it to change the meaning of the |
Bram Moolenaar | 071d427 | 2004-06-13 20:20:40 +0000 | [diff] [blame] | 237 | character after it. |
| 238 | In double-quote strings it is possible to use special characters. Here are |
| 239 | a 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 | |
| 251 | The last two are just examples. The "\<name>" form can be used to include |
| 252 | the special key "name". |
| 253 | See |expr-quote| for the full list of special items in a string. |
| 254 | |
| 255 | ============================================================================== |
| 256 | *41.3* Expressions |
| 257 | |
| 258 | Vim has a rich, yet simple way to handle expressions. You can read the |
| 259 | definition here: |expression-syntax|. Here we will show the most common |
| 260 | items. |
| 261 | The numbers, strings and variables mentioned above are expressions by |
| 262 | themselves. Thus everywhere an expression is expected, you can use a number, |
| 263 | string or variable. Other basic items in an expression are: |
| 264 | |
| 265 | $NAME environment variable |
| 266 | &name option |
| 267 | @r register |
| 268 | |
| 269 | Examples: > |
| 270 | |
| 271 | :echo "The value of 'tabstop' is" &ts |
| 272 | :echo "Your home directory is" $HOME |
| 273 | :if @a > 5 |
| 274 | |
| 275 | The &name form can be used to save an option value, set it to a new value, |
| 276 | do 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 | |
| 283 | This makes sure the "The Start" pattern is used with the 'ignorecase' option |
| 284 | off. Still, it keeps the value that the user had set. |
| 285 | |
| 286 | |
| 287 | MATHEMATICS |
| 288 | |
| 289 | It becomes more interesting if we combine these basic items. Let's start with |
| 290 | mathematics on numbers: |
| 291 | |
| 292 | a + b add |
| 293 | a - b subtract |
| 294 | a * b multiply |
| 295 | a / b divide |
| 296 | a % b modulo |
| 297 | |
| 298 | The usual precedence is used. Example: > |
| 299 | |
| 300 | :echo 10 + 5 * 2 |
| 301 | < 20 ~ |
| 302 | |
| 303 | Grouping is done with braces. No surprises here. Example: > |
| 304 | |
| 305 | :echo (10 + 5) * 2 |
| 306 | < 30 ~ |
| 307 | |
| 308 | Strings can be concatenated with ".". Example: > |
| 309 | |
| 310 | :echo "foo" . "bar" |
| 311 | < foobar ~ |
| 312 | |
| 313 | When the ":echo" command gets multiple arguments, it separates them with a |
| 314 | space. In the example the argument is a single expression, thus no space is |
| 315 | inserted. |
| 316 | |
| 317 | Borrowed from the C language is the conditional expression: |
| 318 | |
| 319 | a ? b : c |
| 320 | |
| 321 | If "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 | |
| 327 | The three parts of the constructs are always evaluated first, thus you could |
| 328 | see it work as: |
| 329 | |
| 330 | (a) ? (b) : (c) |
| 331 | |
| 332 | ============================================================================== |
| 333 | *41.4* Conditionals |
| 334 | |
| 335 | The ":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 | |
| 342 | Only when the expression {condition} evaluates to true (non-zero) will the |
| 343 | {statements} be executed. These must still be valid commands. If they |
| 344 | contain 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 | |
| 353 | The 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 | |
| 362 | This works just like using ":else" and then "if", but without the need for an |
| 363 | extra ":endif". |
| 364 | A useful example for your vimrc file is checking the 'term' option and |
| 365 | doing 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 | |
| 376 | LOGIC OPERATIONS |
| 377 | |
| 378 | We already used some of them in the examples. These are the most often used |
| 379 | ones: |
| 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 | |
| 388 | The 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 | |
| 396 | Here "v:version" is a variable defined by Vim, which has the value of the Vim |
| 397 | version. 600 is for version 6.0. Version 6.1 has the value 601. This is |
| 398 | very useful to write a script that works with multiple versions of Vim. |
| 399 | |v:version| |
| 400 | |
| 401 | The logic operators work both for numbers and strings. When comparing two |
| 402 | strings, the mathematical difference is used. This compares byte values, |
| 403 | which may not be right for some languages. |
| 404 | When comparing a string with a number, the string is first converted to a |
| 405 | number. This is a bit tricky, because when a string doesn't look like a |
| 406 | number, the number zero is used. Example: > |
| 407 | |
| 408 | :if 0 == "one" |
| 409 | : echo "yes" |
| 410 | :endif |
| 411 | |
| 412 | This will echo "yes", because "one" doesn't look like a number, thus it is |
| 413 | converted to the number zero. |
| 414 | |
| 415 | For strings there are two more items: |
| 416 | |
| 417 | a =~ b matches with |
| 418 | a !~ b does not match with |
| 419 | |
| 420 | The left item "a" is used as a string. The right item "b" is used as a |
| 421 | pattern, 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 | |
| 430 | Notice the use of a single-quote string for the pattern. This is useful, |
| 431 | because backslashes need to be doubled in a double-quote string and patterns |
| 432 | tend to contain many backslashes. |
| 433 | |
| 434 | The 'ignorecase' option is used when comparing strings. When you don't want |
| 435 | that, append "#" to match case and "?" to ignore case. Thus "==?" compares |
| 436 | two strings to be equal while ignoring case. And "!~#" checks if a pattern |
| 437 | doesn't match, also checking the case of letters. For the full table see |
| 438 | |expr-==|. |
| 439 | |
| 440 | |
| 441 | MORE LOOPING |
| 442 | |
| 443 | The ":while" command was already mentioned. Two more statements can be used |
| 444 | in 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 | |
| 451 | Example: > |
| 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 | |
| 464 | The ":sleep" command makes Vim take a nap. The "50m" specifies fifty |
| 465 | milliseconds. Another example is ":sleep 4", which sleeps for four seconds. |
| 466 | |
| 467 | ============================================================================== |
| 468 | *41.5* Executing an expression |
| 469 | |
| 470 | So 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 |
| 472 | very 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 | |
| 477 | The "." 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 |
| 479 | will be executed is: > |
| 480 | |
| 481 | :tag get_cmd |
| 482 | |
| 483 | The ":execute" command can only execute colon commands. The ":normal" command |
| 484 | executes Normal mode commands. However, its argument is not an expression but |
| 485 | the literal command characters. Example: > |
| 486 | |
| 487 | :normal gg=G |
| 488 | |
| 489 | This jumps to the first line and formats all lines with the "=" operator. |
| 490 | To make ":normal" work with an expression, combine ":execute" with it. |
| 491 | Example: > |
| 492 | |
| 493 | :execute "normal " . normal_commands |
| 494 | |
| 495 | The variable "normal_commands" must contain the Normal mode commands. |
| 496 | Make sure that the argument for ":normal" is a complete command. Otherwise |
| 497 | Vim will run into the end of the argument and abort the command. For example, |
| 498 | if you start Insert mode, you must leave Insert mode as well. This works: > |
| 499 | |
| 500 | :execute "normal Inew text \<Esc>" |
| 501 | |
| 502 | This inserts "new text " in the current line. Notice the use of the special |
| 503 | key "\<Esc>". This avoids having to enter a real <Esc> character in your |
| 504 | script. |
| 505 | |
| 506 | ============================================================================== |
| 507 | *41.6* Using functions |
| 508 | |
| 509 | Vim defines many functions and provides a large amount of functionality that |
| 510 | way. A few examples will be given in this section. You can find the whole |
| 511 | list here: |functions|. |
| 512 | |
| 513 | A function is called with the ":call" command. The parameters are passed in |
| 514 | between braces, separated by commas. Example: > |
| 515 | |
| 516 | :call search("Date: ", "W") |
| 517 | |
| 518 | This calls the search() function, with arguments "Date: " and "W". The |
| 519 | search() function uses its first argument as a search pattern and the second |
| 520 | one as flags. The "W" flag means the search doesn't wrap around the end of |
| 521 | the file. |
| 522 | |
| 523 | A 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 | |
| 529 | The getline() function obtains a line from the current file. Its argument is |
| 530 | a specification of the line number. In this case "." is used, which means the |
| 531 | line where the cursor is. |
| 532 | The substitute() function does something similar to the ":substitute" |
| 533 | command. The first argument is the string on which to perform the |
| 534 | substitution. The second argument is the pattern, the third the replacement |
| 535 | string. Finally, the last arguments are the flags. |
| 536 | The setline() function sets the line, specified by the first argument, to a |
| 537 | new string, the second argument. In this example the line under the cursor is |
| 538 | replaced with the result of the substitute(). Thus the effect of the three |
| 539 | statements is equal to: > |
| 540 | |
| 541 | :substitute/\a/*/g |
| 542 | |
| 543 | Using the functions becomes more interesting when you do more work before and |
| 544 | after the substitute() call. |
| 545 | |
| 546 | |
| 547 | FUNCTIONS *function-list* |
| 548 | |
| 549 | There are many functions. We will mention them here, grouped by what they are |
| 550 | used for. You can find an alphabetical list here: |functions|. Use CTRL-] on |
| 551 | the function name to jump to detailed help on it. |
| 552 | |
| 553 | String 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 Moolenaar | af7f641 | 2005-01-17 22:11:23 +0000 | [diff] [blame] | 573 | List 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 | |
| 597 | Dictionary 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 Moolenaar | 071d427 | 2004-06-13 20:20:40 +0000 | [diff] [blame] | 616 | Working 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 | |
| 636 | System 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 | |
| 657 | Buffers, 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 | |
| 674 | Folding: |
| 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 | |
| 680 | Syntax 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 | |
| 687 | History: |
| 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 | |
| 693 | Interactive: |
| 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 | |
| 703 | Vim 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 | |
| 713 | Various: |
| 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 | |
| 737 | Vim enables you to define your own functions. The basic function declaration |
| 738 | begins 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 | |
| 747 | Let's define a short function to return the smaller of two numbers. It starts |
| 748 | with this line: > |
| 749 | |
| 750 | :function Min(num1, num2) |
| 751 | |
| 752 | This 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 | |
| 758 | The special prefix "a:" tells Vim that the variable is a function argument. |
| 759 | Let'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 | |
| 767 | The variable "smaller" is a local variable. Variables used inside a function |
| 768 | are 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 | |
| 776 | You now use the ":return" statement to return the smallest number to the user. |
| 777 | Finally, you end the function: > |
| 778 | |
| 779 | : return smaller |
| 780 | :endfunction |
| 781 | |
| 782 | The 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 | |
| 793 | A user defined function is called in exactly the same way as a builtin |
| 794 | function. Only the name is different. The Min function can be used like |
| 795 | this: > |
| 796 | |
| 797 | :echo Min(5, 8) |
| 798 | |
| 799 | Only now will the function be executed and the lines be interpreted by Vim. |
| 800 | If there are mistakes, like using an undefined variable or function, you will |
| 801 | now get an error message. When defining the function these errors are not |
| 802 | detected. |
| 803 | |
| 804 | When a function reaches ":endfunction" or ":return" is used without an |
| 805 | argument, the function returns zero. |
| 806 | |
| 807 | To redefine a function that already exists, use the ! for the ":function" |
| 808 | command: > |
| 809 | |
| 810 | :function! Min(num1, num2, num3) |
| 811 | |
| 812 | |
| 813 | USING A RANGE |
| 814 | |
| 815 | The ":call" command can be given a line range. This can have one of two |
| 816 | meanings. When a function has been defined with the "range" keyword, it will |
| 817 | take care of the line range itself. |
| 818 | The function will be passed the variables "a:firstline" and "a:lastline". |
| 819 | These will have the line numbers from the range the function was called with. |
| 820 | Example: > |
| 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 | |
| 832 | You can call this function with: > |
| 833 | |
| 834 | :10,30call Count_words() |
| 835 | |
| 836 | It 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 |
| 839 | range, with the cursor in that line. Example: > |
| 840 | |
| 841 | :function Number() |
| 842 | : echo "line " . line(".") . " contains: " . getline(".") |
| 843 | :endfunction |
| 844 | |
| 845 | If you call this function with: > |
| 846 | |
| 847 | :10,15call Number() |
| 848 | |
| 849 | The function will be called six times. |
| 850 | |
| 851 | |
| 852 | VARIABLE NUMBER OF ARGUMENTS |
| 853 | |
| 854 | Vim enables you to define functions that have a variable number of arguments. |
| 855 | The following command, for instance, defines a function that must have 1 |
| 856 | argument (start) and can have up to 20 additional arguments: > |
| 857 | |
| 858 | :function Show(start, ...) |
| 859 | |
| 860 | The variable "a:1" contains the first optional argument, "a:2" the second, and |
| 861 | so 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 | |
| 876 | This uses the ":echohl" command to specify the highlighting used for the |
| 877 | following ":echo" command. ":echohl None" stops it again. The ":echon" |
| 878 | command works like ":echo", but doesn't output a line break. |
| 879 | |
| 880 | |
| 881 | LISTING FUNCTIONS |
| 882 | |
| 883 | The ":function" command lists the names and arguments of all user-defined |
| 884 | functions: > |
| 885 | |
| 886 | :function |
| 887 | < function Show(start, ...) ~ |
| 888 | function GetVimIndent() ~ |
| 889 | function SetSyn(name) ~ |
| 890 | |
| 891 | To 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 | |
| 900 | DEBUGGING |
| 901 | |
| 902 | The line number is useful for when you get an error message or when debugging. |
| 903 | See |debug-scripts| about debugging mode. |
| 904 | You can also set the 'verbose' option to 12 or higher to see all function |
| 905 | calls. Set it to 15 or higher to see every executed line. |
| 906 | |
| 907 | |
| 908 | DELETING A FUNCTION |
| 909 | |
| 910 | To delete the Show() function: > |
| 911 | |
| 912 | :delfunction Show |
| 913 | |
| 914 | You get an error when the function doesn't exist. |
| 915 | |
| 916 | ============================================================================== |
| 917 | *41.8* Exceptions |
| 918 | |
| 919 | Let'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 | |
| 927 | The ":read" command will fail if the file does not exist. Instead of |
| 928 | generating an error message, this code catches the error and gives the user a |
| 929 | nice message instead. |
| 930 | |
| 931 | For the commands in between ":try" and ":endtry" errors are turned into |
| 932 | exceptions. An exception is a string. In the case of an error the string |
| 933 | contains the error message. And every error message has a number. In this |
| 934 | case, the error we catch contains "E484:". This number is guaranteed to stay |
| 935 | the same (the text may change, e.g., it may be translated). |
| 936 | |
| 937 | When the ":read" command causes another error, the pattern "E484:" will not |
| 938 | match in it. Thus this exception will not be caught and result in the usual |
| 939 | error message. |
| 940 | |
| 941 | You 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 | |
| 949 | This means all errors are caught. But then you will not see errors that are |
| 950 | useful, such as "E21: Cannot make changes, 'modifiable' is off". |
| 951 | |
| 952 | Another 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 | |
| 964 | This 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 |
| 966 | filtering works, something goes wrong in between ":try" and ":finally" or the |
| 967 | user cancels the filtering by pressing CTRL-C, the "call delete(tmp)" is |
| 968 | always executed. This makes sure you don't leave the temporary file behind. |
| 969 | |
| 970 | More information about exception handling can be found in the reference |
| 971 | manual: |exception-handling|. |
| 972 | |
| 973 | ============================================================================== |
| 974 | *41.9* Various remarks |
| 975 | |
| 976 | Here is a summary of items that apply to Vim scripts. They are also mentioned |
| 977 | elsewhere, but form a nice checklist. |
| 978 | |
| 979 | The end-of-line character depends on the system. For Unix a single <NL> |
| 980 | character is used. For MS-DOS, Windows, OS/2 and the like, <CR><LF> is used. |
| 981 | This is important when using mappings that end in a <CR>. See |:source_crnl|. |
| 982 | |
| 983 | |
| 984 | WHITE SPACE |
| 985 | |
| 986 | Blank lines are allowed and ignored. |
| 987 | |
| 988 | Leading whitespace characters (blanks and TABs) are always ignored. The |
| 989 | whitespaces between parameters (e.g. between the 'set' and the 'cpoptions' in |
| 990 | the example below) are reduced to one blank character and plays the role of a |
| 991 | separator, the whitespaces after the last (visible) character may or may not |
| 992 | be ignored depending on the situation, see below. |
| 993 | |
| 994 | For a ":set" command involving the "=" (equal) sign, such as in: > |
| 995 | |
| 996 | :set cpoptions =aABceFst |
| 997 | |
| 998 | the whitespace immediately before the "=" sign is ignored. But there can be |
| 999 | no whitespace after the "=" sign! |
| 1000 | |
| 1001 | To include a whitespace character in the value of an option, it must be |
| 1002 | escaped by a "\" (backslash) as in the following example: > |
| 1003 | |
| 1004 | :set tags=my\ nice\ file |
| 1005 | |
| 1006 | The same example written as > |
| 1007 | |
| 1008 | :set tags=my nice file |
| 1009 | |
| 1010 | will issue an error, because it is interpreted as: > |
| 1011 | |
| 1012 | :set tags=my |
| 1013 | :set nice |
| 1014 | :set file |
| 1015 | |
| 1016 | |
| 1017 | COMMENTS |
| 1018 | |
| 1019 | The character " (the double quote mark) starts a comment. Everything after |
| 1020 | and including this character until the end-of-line is considered a comment and |
| 1021 | is ignored, except for commands that don't consider comments, as shown in |
| 1022 | examples below. A comment can start on any character position on the line. |
| 1023 | |
| 1024 | There 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 | |
| 1031 | The abbreviation 'dev' will be expanded to 'development " shorthand'. The |
| 1032 | mapping of <F3> will actually be the whole line after the 'o# ....' including |
| 1033 | the '" insert include'. The "execute" command will give an error. The "!" |
| 1034 | command will send everything after it to the shell, causing an error for an |
| 1035 | unmatched '"' character. |
| 1036 | There can be no comment after ":map", ":abbreviate", ":execute" and "!" |
| 1037 | commands (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 | |
| 1044 | With the '|' character the command is separated from the next one. And that |
| 1045 | next command is only a comment. |
| 1046 | |
| 1047 | Notice that there is no white space before the '|' in the abbreviation and |
| 1048 | mapping. For these commands, any character until the end-of-line or '|' is |
| 1049 | included. As a consequence of this behavior, you don't always see that |
| 1050 | trailing whitespace is included: > |
| 1051 | |
| 1052 | :map <F4> o#include |
| 1053 | |
| 1054 | To avoid these problems, you can set the 'list' option when editing vimrc |
| 1055 | files. |
| 1056 | |
| 1057 | |
| 1058 | PITFALLS |
| 1059 | |
| 1060 | Even bigger problem arises in the following example: > |
| 1061 | |
| 1062 | :map ,ab o#include |
| 1063 | :unmap ,ab |
| 1064 | |
| 1065 | Here the unmap command will not work, because it tries to unmap ",ab ". This |
| 1066 | does not exist as a mapped sequence. An error will be issued, which is very |
| 1067 | hard to identify, because the ending whitespace character in ":unmap ,ab " is |
| 1068 | not visible. |
| 1069 | |
| 1070 | And this is the same as what happens when one uses a comment after an 'unmap' |
| 1071 | command: > |
| 1072 | |
| 1073 | :unmap ,ab " comment |
| 1074 | |
| 1075 | Here 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 | |
| 1081 | RESTORING THE VIEW |
| 1082 | |
| 1083 | Sometimes you want to make a change and go back to where cursor was. |
| 1084 | Restoring the relative position would also be nice, so that the same line |
| 1085 | appears at the top of the window. |
| 1086 | This example yanks the current line, puts it above the first line in the |
| 1087 | file and then restores the view: > |
| 1088 | |
| 1089 | map ,p ma"aYHmbgg"aP`bzt`a |
| 1090 | |
| 1091 | What 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 | |
| 1103 | PACKAGING |
| 1104 | |
| 1105 | To avoid your function names to interfere with functions that you get from |
| 1106 | others, 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. |
| 1112 | Example: > |
| 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 | |
| 1134 | You can write a Vim script in such a way that many people can use it. This is |
| 1135 | called a plugin. Vim users can drop your script in their plugin directory and |
| 1136 | use its features right away |add-plugin|. |
| 1137 | |
| 1138 | There are actually two types of plugins: |
| 1139 | |
| 1140 | global plugins: For all types of files. |
| 1141 | filetype plugins: Only for files of a specific type. |
| 1142 | |
| 1143 | In this section the first type is explained. Most items are also relevant for |
| 1144 | writing filetype plugins. The specifics for filetype plugins are in the next |
| 1145 | section |write-filetype-plugin|. |
| 1146 | |
| 1147 | |
| 1148 | NAME |
| 1149 | |
| 1150 | First of all you must choose a name for your plugin. The features provided |
| 1151 | by the plugin should be clear from its name. And it should be unlikely that |
| 1152 | someone else writes a plugin with the same name but which does something |
| 1153 | different. And please limit the name to 8 characters, to avoid problems on |
| 1154 | old Windows systems. |
| 1155 | |
| 1156 | A script that corrects typing mistakes could be called "typecorr.vim". We |
| 1157 | will use it here as an example. |
| 1158 | |
| 1159 | For the plugin to work for everybody, it should follow a few guidelines. This |
| 1160 | will be explained step-by-step. The complete example plugin is at the end. |
| 1161 | |
| 1162 | |
| 1163 | BODY |
| 1164 | |
| 1165 | Let'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 | |
| 1174 | The actual list should be much longer, of course. |
| 1175 | |
| 1176 | The line numbers have only been added to explain a few things, don't put them |
| 1177 | in your plugin file! |
| 1178 | |
| 1179 | |
| 1180 | HEADER |
| 1181 | |
| 1182 | You will probably add new corrections to the plugin and soon have several |
| 1183 | versions laying around. And when distributing this file, people will want to |
| 1184 | know who wrote this wonderful plugin and where they can send remarks. |
| 1185 | Therefore, 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 | |
| 1191 | About copyright and licensing: Since plugins are very useful and it's hardly |
| 1192 | worth restricting their distribution, please consider making your plugin |
| 1193 | either public domain or use the Vim |license|. A short note about this near |
| 1194 | the top of the plugin should be sufficient. Example: > |
| 1195 | |
| 1196 | 4 " License: This file is placed in the public domain. |
| 1197 | |
| 1198 | |
| 1199 | LINE CONTINUATION, AVOIDING SIDE EFFECTS *use-cpo-save* |
| 1200 | |
| 1201 | In line 18 above, the line-continuation mechanism is used |line-continuation|. |
| 1202 | Users with 'compatible' set will run into trouble here, they will get an error |
| 1203 | message. We can't just reset 'compatible', because that has a lot of side |
| 1204 | effects. To avoid this, we will set the 'cpoptions' option to its Vim default |
| 1205 | value and restore it later. That will allow the use of line-continuation and |
| 1206 | make 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 | |
| 1213 | We first store the old value of 'cpoptions' in the s:save_cpo variable. At |
| 1214 | the end of the plugin this value is restored. |
| 1215 | |
| 1216 | Notice that a script-local variable is used |s:var|. A global variable could |
| 1217 | already be in use for something else. Always use script-local variables for |
| 1218 | things that are only used in the script. |
| 1219 | |
| 1220 | |
| 1221 | NOT LOADING |
| 1222 | |
| 1223 | It's possible that a user doesn't always want to load this plugin. Or the |
| 1224 | system administrator has dropped it in the system-wide plugin directory, but a |
| 1225 | user has his own plugin he wants to use. Then the user must have a chance to |
| 1226 | disable 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 | |
| 1233 | This also avoids that when the script is loaded twice it would cause error |
| 1234 | messages for redefining functions and cause trouble for autocommands that are |
| 1235 | added twice. |
| 1236 | |
| 1237 | |
| 1238 | MAPPING |
| 1239 | |
| 1240 | Now let's make the plugin more interesting: We will add a mapping that adds a |
| 1241 | correction for the word under the cursor. We could just pick a key sequence |
| 1242 | for this mapping, but the user might already use it for something else. To |
| 1243 | allow the user to define which keys a mapping in a plugin uses, the <Leader> |
| 1244 | item can be used: > |
| 1245 | |
| 1246 | 22 map <unique> <Leader>a <Plug>TypecorrAdd |
| 1247 | |
| 1248 | The "<Plug>TypecorrAdd" thing will do the work, more about that further on. |
| 1249 | |
| 1250 | The user can set the "mapleader" variable to the key sequence that he wants |
| 1251 | this mapping to start with. Thus if the user has done: > |
| 1252 | |
| 1253 | let mapleader = "_" |
| 1254 | |
| 1255 | the mapping will define "_a". If the user didn't do this, the default value |
| 1256 | will be used, which is a backslash. Then a map for "\a" will be defined. |
| 1257 | |
| 1258 | Note that <unique> is used, this will cause an error message if the mapping |
| 1259 | already happened to exist. |:map-<unique>| |
| 1260 | |
| 1261 | But what if the user wants to define his own key sequence? We can allow that |
| 1262 | with this mechanism: > |
| 1263 | |
| 1264 | 21 if !hasmapto('<Plug>TypecorrAdd') |
| 1265 | 22 map <unique> <Leader>a <Plug>TypecorrAdd |
| 1266 | 23 endif |
| 1267 | |
| 1268 | This checks if a mapping to "<Plug>TypecorrAdd" already exists, and only |
| 1269 | defines the mapping from "<Leader>a" if it doesn't. The user then has a |
| 1270 | chance of putting this in his vimrc file: > |
| 1271 | |
| 1272 | map ,c <Plug>TypecorrAdd |
| 1273 | |
| 1274 | Then the mapped key sequence will be ",c" instead of "_a" or "\a". |
| 1275 | |
| 1276 | |
| 1277 | PIECES |
| 1278 | |
| 1279 | If a script gets longer, you often want to break up the work in pieces. You |
| 1280 | can use functions or mappings for this. But you don't want these functions |
| 1281 | and mappings to interfere with the ones from other scripts. For example, you |
| 1282 | could define a function Add(), but another script could try to define the same |
| 1283 | function. To avoid this, we define the function local to the script by |
| 1284 | prepending it with "s:". |
| 1285 | |
| 1286 | We 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 | |
| 1294 | Now we can call the function s:Add() from within this script. If another |
| 1295 | script also defines s:Add(), it will be local to that script and can only |
| 1296 | be called from the script it was defined in. There can also be a global Add() |
| 1297 | function (without the "s:"), which is again another function. |
| 1298 | |
| 1299 | <SID> can be used with mappings. It generates a script ID, which identifies |
| 1300 | the 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 | |
| 1306 | Thus when a user types "\a", this sequence is invoked: > |
| 1307 | |
| 1308 | \a -> <Plug>TypecorrAdd -> <SID>Add -> :call <SID>Add() |
| 1309 | |
| 1310 | If another script would also map <SID>Add, it would get another script ID and |
| 1311 | thus define another mapping. |
| 1312 | |
| 1313 | Note that instead of s:Add() we use <SID>Add() here. That is because the |
| 1314 | mapping is typed by the user, thus outside of the script. The <SID> is |
| 1315 | translated to the script ID, so that Vim knows in which script to look for |
| 1316 | the Add() function. |
| 1317 | |
| 1318 | This is a bit complicated, but it's required for the plugin to work together |
| 1319 | with other plugins. The basic rule is that you use <SID>Add() in mappings and |
| 1320 | s:Add() in other places (the script itself, autocommands, user commands). |
| 1321 | |
| 1322 | We can also add a menu entry to do the same as the mapping: > |
| 1323 | |
| 1324 | 26 noremenu <script> Plugin.Add\ Correction <SID>Add |
| 1325 | |
| 1326 | The "Plugin" menu is recommended for adding menu items for plugins. In this |
| 1327 | case only one item is used. When adding more items, creating a submenu is |
| 1328 | recommended. For example, "Plugin.CVS" could be used for a plugin that offers |
| 1329 | CVS operations "Plugin.CVS.checkin", "Plugin.CVS.checkout", etc. |
| 1330 | |
| 1331 | Note that in line 28 ":noremap" is used to avoid that any other mappings cause |
| 1332 | trouble. Someone may have remapped ":call", for example. In line 24 we also |
| 1333 | use ":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 |
| 1335 | script. |:map-<script>| The same is done in line 26 for ":noremenu". |
| 1336 | |:menu-<script>| |
| 1337 | |
| 1338 | |
| 1339 | <SID> AND <Plug> *using-<Plug>* |
| 1340 | |
| 1341 | Both <SID> and <Plug> are used to avoid that mappings of typed keys interfere |
| 1342 | with mappings that are only to be used from other mappings. Note the |
| 1343 | difference 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 | |
| 1364 | USER COMMAND |
| 1365 | |
| 1366 | Now 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 | |
| 1372 | The user command is defined only if no command with the same name already |
| 1373 | exists. Otherwise we would get an error here. Overriding the existing user |
| 1374 | command with ":command!" is not a good idea, this would probably make the user |
| 1375 | wonder why the command he defined himself doesn't work. |:command| |
| 1376 | |
| 1377 | |
| 1378 | SCRIPT VARIABLES |
| 1379 | |
| 1380 | When a variable starts with "s:" it is a script variable. It can only be used |
| 1381 | inside a script. Outside the script it's not visible. This avoids trouble |
| 1382 | with using the same variable name in different scripts. The variables will be |
| 1383 | kept as long as Vim is running. And the same variables are used when sourcing |
| 1384 | the same script again. |s:var| |
| 1385 | |
| 1386 | The fun is that these variables can also be used in functions, autocommands |
| 1387 | and user commands that are defined in the script. In our example we can add |
| 1388 | a 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 | |
| 1398 | First s:count is initialized to 4 in the script itself. When later the |
| 1399 | s:Add() function is called, it increments s:count. It doesn't matter from |
| 1400 | where the function was called, since it has been defined in the script, it |
| 1401 | will use the local variables from this script. |
| 1402 | |
| 1403 | |
| 1404 | THE RESULT |
| 1405 | |
| 1406 | Here 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 | |
| 1451 | Line 33 wasn't explained yet. It applies the new correction to the word under |
| 1452 | the cursor. The |:normal| command is used to use the new abbreviation. Note |
| 1453 | that mappings and abbreviations are expanded here, even though the function |
| 1454 | was called from a mapping defined with ":noremap". |
| 1455 | |
| 1456 | Using "unix" for the 'fileformat' option is recommended. The Vim scripts will |
| 1457 | then work everywhere. Scripts with 'fileformat' set to "dos" do not work on |
| 1458 | Unix. Also see |:source_crnl|. To be sure it is set right, do this before |
| 1459 | writing the file: > |
| 1460 | |
| 1461 | :set fileformat=unix |
| 1462 | |
| 1463 | |
| 1464 | DOCUMENTATION *write-local-help* |
| 1465 | |
| 1466 | It's a good idea to also write some documentation for your plugin. Especially |
| 1467 | when its behavior can be changed by the user. See |add-local-help| for how |
| 1468 | they are installed. |
| 1469 | |
| 1470 | Here 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 | |
| 1490 | The first line is actually the only one for which the format matters. It will |
| 1491 | be extracted from the help file to be put in the "LOCAL ADDITIONS:" section of |
| 1492 | help.txt |local-additions|. The first "*" must be in the first column of the |
| 1493 | first line. After adding your help file do ":help" and check that the entries |
| 1494 | line up nicely. |
| 1495 | |
| 1496 | You can add more tags inside ** in your help file. But be careful not to use |
| 1497 | existing help tags. You would probably use the name of your plugin in most of |
| 1498 | them, like "typecorr-settings" in the example. |
| 1499 | |
| 1500 | Using references to other parts of the help in || is recommended. This makes |
| 1501 | it easy for the user to find associated help. |
| 1502 | |
| 1503 | |
| 1504 | FILETYPE DETECTION *plugin-filetype* |
| 1505 | |
| 1506 | If your filetype is not already detected by Vim, you should create a filetype |
| 1507 | detection snippet in a separate file. It is usually in the form of an |
| 1508 | autocommand that sets the filetype when the file name matches a pattern. |
| 1509 | Example: > |
| 1510 | |
| 1511 | au BufNewFile,BufRead *.foo set filetype=foofoo |
| 1512 | |
| 1513 | Write this single-line file as "ftdetect/foofoo.vim" in the first directory |
| 1514 | that appears in 'runtimepath'. For Unix that would be |
| 1515 | "~/.vim/ftdetect/foofoo.vim". The convention is to use the name of the |
| 1516 | filetype for the script name. |
| 1517 | |
| 1518 | You can make more complicated checks if you like, for example to inspect the |
| 1519 | contents of the file to recognize the language. Also see |new-filetype|. |
| 1520 | |
| 1521 | |
| 1522 | SUMMARY *plugin-special* |
| 1523 | |
| 1524 | Summary of special things to use in a plugin: |
| 1525 | |
| 1526 | s:name Variables local to the script. |
| 1527 | |
| 1528 | <SID> Script-ID, used for mappings and functions local to |
| 1529 | the script. |
| 1530 | |
| 1531 | hasmapto() 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 | |
| 1542 | exists(":Cmd") Check if a user command already exists. |
| 1543 | |
| 1544 | ============================================================================== |
| 1545 | *41.11* Writing a filetype plugin *write-filetype-plugin* *ftplugin* |
| 1546 | |
| 1547 | A filetype plugin is like a global plugin, except that it sets options and |
| 1548 | defines mappings for the current buffer only. See |add-filetype-plugin| for |
| 1549 | how this type of plugin is used. |
| 1550 | |
| 1551 | First read the section on global plugins above |41.10|. All that is said there |
| 1552 | also applies to filetype plugins. There are a few extras, which are explained |
| 1553 | here. The essential thing is that a filetype plugin should only have an |
| 1554 | effect on the current buffer. |
| 1555 | |
| 1556 | |
| 1557 | DISABLING |
| 1558 | |
| 1559 | If you are writing a filetype plugin to be used by many people, they need a |
| 1560 | chance 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 | |
| 1568 | This also needs to be used to avoid that the same plugin is executed twice for |
| 1569 | the same buffer (happens when using an ":edit" command without arguments). |
| 1570 | |
| 1571 | Now users can disable loading the default plugin completely by making a |
| 1572 | filetype plugin with only this line: > |
| 1573 | |
| 1574 | let b:did_ftplugin = 1 |
| 1575 | |
| 1576 | This does require that the filetype plugin directory comes before $VIMRUNTIME |
| 1577 | in 'runtimepath'! |
| 1578 | |
| 1579 | If you do want to use the default plugin, but overrule one of the settings, |
| 1580 | you can write the different setting in a script: > |
| 1581 | |
| 1582 | setlocal textwidth=70 |
| 1583 | |
| 1584 | Now write this in the "after" directory, so that it gets sourced after the |
| 1585 | distributed "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 | |
| 1590 | OPTIONS |
| 1591 | |
| 1592 | To make sure the filetype plugin only affects the current buffer use the > |
| 1593 | |
| 1594 | :setlocal |
| 1595 | |
| 1596 | command to set options. And only set options which are local to a buffer (see |
| 1597 | the help for the option to check that). When using |:setlocal| for global |
| 1598 | options or options local to a window, the value will change for many buffers, |
| 1599 | and that is not what a filetype plugin should do. |
| 1600 | |
| 1601 | When 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 |
| 1603 | changed an option value already. First resetting to the default value and |
| 1604 | then changing it often a good idea. Example: > |
| 1605 | |
| 1606 | :setlocal formatoptions& formatoptions+=ro |
| 1607 | |
| 1608 | |
| 1609 | MAPPINGS |
| 1610 | |
| 1611 | To make sure mappings will only work in the current buffer use the > |
| 1612 | |
| 1613 | :map <buffer> |
| 1614 | |
| 1615 | command. This needs to be combined with the two-step mapping explained above. |
| 1616 | An 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 |
| 1625 | mapping. This starts with |<LocalLeader>|, which allows the user to select |
| 1626 | the key(s) he wants filetype plugin mappings to start with. The default is a |
| 1627 | backslash. |
| 1628 | "<unique>" is used to give an error message if the mapping already exists or |
| 1629 | overlaps with an existing mapping. |
| 1630 | |:noremap| is used to avoid that any other mappings that the user has defined |
| 1631 | interferes. You might want to use ":noremap <script>" to allow remapping |
| 1632 | mappings defined in this script that start with <SID>. |
| 1633 | |
| 1634 | The user must have a chance to disable the mappings in a filetype plugin, |
| 1635 | without disabling everything. Here is an example of how this is done for a |
| 1636 | plugin 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 | |
| 1649 | Two global variables are used: |
| 1650 | no_plugin_maps disables mappings for all filetype plugins |
| 1651 | no_mail_maps disables mappings for a specific filetype |
| 1652 | |
| 1653 | |
| 1654 | USER COMMANDS |
| 1655 | |
| 1656 | To add a user command for a specific file type, so that it can only be used in |
| 1657 | one buffer, use the "-buffer" argument to |:command|. Example: > |
| 1658 | |
| 1659 | :command -buffer Make make %:r.s |
| 1660 | |
| 1661 | |
| 1662 | VARIABLES |
| 1663 | |
| 1664 | A filetype plugin will be sourced for each buffer of the type it's for. Local |
| 1665 | script variables |s:var| will be shared between all invocations. Use local |
| 1666 | buffer variables |b:var| if you want a variable specifically for one buffer. |
| 1667 | |
| 1668 | |
| 1669 | FUNCTIONS |
| 1670 | |
| 1671 | When defining a function, this only needs to be done once. But the filetype |
| 1672 | plugin will be sourced every time a file with this filetype will be opened. |
| 1673 | This 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 | |
| 1682 | UNDO *undo_ftplugin* |
| 1683 | |
| 1684 | When the user does ":setfiletype xyz" the effect of the previous filetype |
| 1685 | should be undone. Set the b:undo_ftplugin variable to the commands that will |
| 1686 | undo 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 | |
| 1691 | Using ":setlocal" with "<" after the option name resets the option to its |
| 1692 | global value. That is mostly the best way to reset the option value. |
| 1693 | |
| 1694 | This does require removing the "C" flag from 'cpoptions' to allow line |
| 1695 | continuation, as mentioned above |use-cpo-save|. |
| 1696 | |
| 1697 | |
| 1698 | FILE NAME |
| 1699 | |
| 1700 | The filetype must be included in the file name |ftplugin-name|. Use one of |
| 1701 | these 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 | |
| 1710 | SUMMARY *ftplugin-special* |
| 1711 | |
| 1712 | Summary 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 | |
| 1726 | exists("*s:Func") Check if a function was already defined. |
| 1727 | |
| 1728 | Also see |plugin-special|, the special things used for all plugins. |
| 1729 | |
| 1730 | ============================================================================== |
| 1731 | *41.12* Writing a compiler plugin *write-compiler-plugin* |
| 1732 | |
| 1733 | A compiler plugin sets options for use with a specific compiler. The user can |
| 1734 | load it with the |:compiler| command. The main use is to set the |
| 1735 | 'errorformat' and 'makeprg' options. |
| 1736 | |
| 1737 | Easiest is to have a look at examples. This command will edit all the default |
| 1738 | compiler plugins: > |
| 1739 | |
| 1740 | :next $VIMRUNTIME/compiler/*.vim |
| 1741 | |
| 1742 | Use |:next| to go to the next plugin file. |
| 1743 | |
| 1744 | There are two special items about these files. First is a mechanism to allow |
| 1745 | a 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 | |
| 1752 | When 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 |
| 1754 | make the default file skip the settings. |
| 1755 | |
| 1756 | The second mechanism is to use ":set" for ":compiler!" and ":setlocal" for |
| 1757 | ":compiler". Vim defines the ":CompilerSet" user command for this. However, |
| 1758 | older Vim versions don't, thus your plugin should define it then. This is an |
| 1759 | example: > |
| 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 | |
| 1767 | When you write a compiler plugin for the Vim distribution or for a system-wide |
| 1768 | runtime directory, use the mechanism mentioned above. When |
| 1769 | "current_compiler" was already set by a user plugin nothing will be done. |
| 1770 | |
| 1771 | When you write a compiler plugin to overrule settings from a default plugin, |
| 1772 | don't check "current_compiler". This plugin is supposed to be loaded |
| 1773 | last, thus it should be in a directory at the end of 'runtimepath'. For Unix |
| 1774 | that could be ~/.vim/after/compiler. |
| 1775 | |
| 1776 | ============================================================================== |
| 1777 | |
| 1778 | Next chapter: |usr_42.txt| Add new menus |
| 1779 | |
| 1780 | Copyright: see |manual-copyright| vim:tw=78:ts=8:ft=help:norl: |