*41.2* Variables A variable name consists of ASCII letters, digits and the underscore. It cannot start with a digit. Valid variable names are: counter _aap3 very_long_variable_name_with_dashes FuncLength LENGTH Invalid names are "foo+bar" and "6var". These variables are global. To see a list of currently defined variables use this command: > :let You can use global variables everywhere. This also means that when the variable "count" is used in one script file, it might also be used in another file. This leads to confusion at least, and real problems at worst. To avoid this, you can use a variable local to a script file by prepending "s:". For example, one script contains this code: > :let s:count = 1 :while s:count < 5 : source other.vim : let s:count = s:count + 1 :endwhile Since "s:count" is local to this script, you can be sure that sourcing the "other.vim" script will not change this variable. If "other.vim" also uses an "s:count" variable, it will be a different copy, local to that script. More about script-local variables here: |script-variable|. There are more kinds of variables, see |internal-variables|. The most often used ones are: b:name variable local to a buffer w:name variable local to a window g:name global variable (also in a function) v:name variable predefined by Vim DELETING VARIABLES Variables take up memory and show up in the output of the ":let" command. To delete a variable use the ":unlet" command. Example: > :unlet s:count This deletes the script-local variable "s:count" to free up the memory it uses. If you are not sure if the variable exists, and don't want an error message when it doesn't, append !: > :unlet! s:count When a script finishes, the local variables used there will not be automatically freed. The next time the script executes, it can still use the old value. Example: > :if !exists("s:call_count") : let s:call_count = 0 :endif :let s:call_count = s:call_count + 1 :echo "called" s:call_count "times" The "exists()" function checks if a variable has already been defined. Its argument is the name of the variable you want to check. Not the variable itself! If you would do this: > :if !exists(s:call_count) Then the value of s:call_count will be used as the name of the variable that exists() checks. That's not what you want. The exclamation mark ! negates a value. When the value was true, it becomes false. When it was false, it becomes true. You can read it as "not". Thus "if !exists()" can be read as "if not exists()". What Vim calls true is anything that is not zero. Only zero is false. STRING VARIABLES AND CONSTANTS So far only numbers were used for the variable value. Strings can be used as well. Numbers and strings are the only two types of variables that Vim supports. The type is dynamic, it is set each time when assigning a value to the variable with ":let". To assign a string value to a variable, you need to use a string constant. There are two types of these. First the string in double quotes: > :let name = "peter" :echo name < peter ~ If you want to include a double quote inside the string, put a backslash in front of it: > :let name = "\"peter\"" :echo name < "peter" ~ To avoid the need for a backslash, you can use a string in single quotes: > :let name = '"peter"' :echo name < "peter" ~ Inside a single-quote string all the characters are taken literally. The drawback is that it's impossible to include a single quote. A backslash is taken literally as well, thus you can't use it to change the meaning of the character after it. In double-quote strings it is possible to use special characters. Here are a few useful ones: \t <Tab> \n <NL>, line break \r <CR>, <Enter> \e <Esc> \b <BS>, backspace \" " \\ \, backslash \<Esc> <Esc> \<C-W> CTRL-W The last two are just examples. The "\<name>" form can be used to include the special key "name". See |expr-quote| for the full list of special items in a string.
*41.3* Expressions Vim has a rich, yet simple way to handle expressions. You can read the definition here: |expression-syntax|. Here we will show the most common items. The numbers, strings and variables mentioned above are expressions by themselves. Thus everywhere an expression is expected, you can use a number, string or variable. Other basic items in an expression are: $NAME environment variable &name option @r register Examples: > :echo "The value of 'tabstop' is" &ts :echo "Your home directory is" $HOME :if @a > 5 The &option form can be used to save an option value, set it to a new value, do something and restore the old value. Example: > :let save_ic = &ic :set noic :/The Start/,$delete :let &ic = save_ic This makes sure the "The Start" pattern is used with the 'ignorecase' option off. Still, it keeps the value that the user had set. MATHEMATICS It becomes more interesting if we combine these basic items. Let's start with mathematics on numbers: a + b add a - b subtract a * b multiply a / b divide a % b modulo The usual precedence is used. Example: > :echo 10 + 5 * 2 < 20 ~ Grouping is done with braces. No suprises here. Example: > :echo (10 + 5) * 2 < 30 ~ Strings can be concatenated with ".". Example: > :echo "foo" . "bar" < foobar ~ When the ":echo" command gets multiple arguments, it separates them with a space. In the example the argument is a single expression, thus no space is inserted. Borrowed from the C language is the conditional expression: a ? b : c If "a" evaluates to true "b" is used, otherwise "c" is used. Example: > :let i = 4 :echo i > 5 ? "i is big" : "i is small" < i is small ~ The three parts of the constructs are always evaluated first, thus you could see it work as: (a) ? (b) : (c)
*41.4* Conditionals The ":if" commands executes the following statements, until the matching ":endif", only when a condition is met. The generic form is: :if {condition} {statements} :endif Only when the expression {condition} evaluates to true (non-zero) will the {statements} be executed. These must still be valid commands. If they contain garbage, Vim won't be able to find the ":endif". You can also use ":else". The generic form for this is: :if {condition} {statements} :else {statements} :endif The second {statements} is only executed if the first one isn't. Finally, there is ":elseif": :if {condition} {statements} :elseif {condition} {statements} :endif This works just like using ":else" and then "if", but without the need for an extra ":endif". A useful example for your vimrc file is checking the 'term' option and doing something depending upon its value: > :if &term == "xterm" : " Do stuff for xterm :elseif &term == "vt100" : " Do stuff for a vt100 terminal :else : " Do something for other terminals :endif LOGIC OPERATIONS We already used some of them in the examples. These are the most often used ones: a == b equal to a != b not equal to a > b greater than a >= b greater than or equal to a < b less than a <= b less than or equal to The result is one if the condition is met and zero otherwise. An example: > :if v:version >= 600 : echo "congratulations" :else : echo "you are using an old version, upgrade!" :endif Here "v:version" is a variable defined by Vim, which has the value of the Vim version. 600 is for version 6.0. Version 6.1 will have the value 601. This is very useful to write a script that works with multiple versions of Vim. |v:version| The logic operators work both for numbers and strings. When comparing two strings, the mathematical difference is used. This compares byte values, which may not be right for some languages. When comparing a string with a number, the string is first converted to a number. This is a bit tricky, because when a string doesn't look like a number, the number zero is used. Example: > :if 0 == "one" : echo "yes" :endif This will echo "yes", because "one" doesn't look like a number, thus it is converted to the number zero. For strings there are two more items: a =~ b matches with a !~ b does not match with The left item "a" is used as a string. The right item "b" is used as a pattern, like what's used for searching. Example: > :if str =~ " " : echo "str contains a space" :elseif str !~ '\.$' : echo "str ends in a full stop" :endif Notice the use of a single-quote string for the pattern. This is useful, because backslashes need to be doubled in a double-quote string and patterns tend to contain many backslashes. The 'ignorecase' option is used when comparing strings. When you don't want that, append "#" to match case and "?" to ignore case. Thus "==?" compares two strings to be equal while ignoring case. And "!~#" checks if a pattern doesn't match, also checking the case of letters. For the full table see |expr-==|. MORE LOOPING The ":while" command was already mentioned. Two more statements can be used in between the ":while" and the ":endwhile": :continue Jump back to the start of the while loop; the loop continues. :break Jump forward to the ":endwhile"; the loop is discontinued. Example: > :while counter < 40 : call do_something() : if skip_flag : continue : endif : if finished_flag : break : endif : sleep 50m :endwhile The ":sleep" command makes Vim take a nap. The "50m" specifies fifty milliseconds. Another example is ":sleep 4", which sleeps for four seconds.
*41.5* Executing an expression So far the commands in the script were executed by Vim directly. The ":execute" command allows executing the result of an expression. This is a very powerful way to build commands and execute them. An example is to jump to a tag, which is contained in a variable: > :execute "tag " . tag_name The "." is used to concatenate the string "tag " with the value of variable "tag_name". Suppose "tag_name" has the value "get_cmd", then the command that will be executed is: > :tag get_cmd The ":execute" command can only execute colon commands. The ":normal" command executes Normal mode commands. However, its argument is not an expression but the literal command characters. Example: > :normal gg=G This jumps to the first line and formats all lines with the "=" operator. To make ":normal" work with an expression, combine ":execute" with it. Example: > :execute "normal " . normal_commands The variable "normal_commands" must contain the Normal mode commands. Make sure that the argument for ":normal" is a complete command. Otherwise Vim will run into the end of the argument and abort the command. For example, if you start Insert mode, you must leave Insert mode as well. This works: > :execute "normal Inew text \<Esc>" This inserts "new text " in the current line. Notice the use of the special key "\<Esc>". This avoids having to enter a real <Esc> character in your script.
*41.6* Using functions Vim defines many functions and provides a large amount of functionality that way. A few examples will be given in this section. You can find the whole list here: |functions|. A function is called with the ":call" command. The parameters are passed in between braces, separated by commas. Example: > :call search("Date: ", "W") This calls the search() function, with arguments "Date: " and "W". The search() function uses its first argument as a search pattern and the second one as flags. The "W" flag means the search doesn't wrap around the end of the file. A function can be called in an expression. Example: > :let line = getline(".") :let repl = substitute(line, '\a', "*", "g") :call setline(".", repl) The getline() function obtains a line from the current file. Its argument is a specification of the line number. In this case "." is used, which means the line where the cursor. The substitute() function does something similar to the ":substitute" command. The first argument is the string on which to perform the substitution. The second argument is the pattern, the third the replacement string. Finally, the last arguments are the flags. The setline() function sets the line, specified by the first argument, to a new string, the second argument. In this example the line under the cursor is replaced with the result of the substitute(). Thus the effect of the three statements is equal to: > :substitute/\a/*/g Using the functions becomes more interesting when you do more work before and after the substitute() call. FUNCTIONS *function-list* There are many functions. We will mention them here, grouped by what they are used for. You can find an alphabetical list here: |functions|. Use CTRL-] on the function name to jump to detailed help on it. String manipulation: char2nr() get ASCII value of a character nr2char() get a character by its ASCII value escape() escape characters in a string with a '\' strtrans() translate a string to make it printable tolower() turn a string to lowercase toupper() turn a string to uppercase match() position where a pattern matches in a string matchend() position where a pattern match ends in a string matchstr() match of a pattern in a string stridx() first index of a short string in a long string strridx() last index of a short string in a long string strlen() length of a string substitute() substitute a pattern match with a string submatch() get a specific match in a ":substitute" strpart() get part of a string expand() expand special keywords type() type of a variable Working with text in the current buffer: byte2line() get line number at a specific byte count line2byte() byte count at a specific line col() column number of the cursor or a mark virtcol() screen column of the cursor or a mark line() line number of the cursor or mark wincol() window column number of the cursor winline() window line number of the cursor getline() get a line from the buffer setline() replace a line in the buffer append() append {string} below line {lnum} indent() indent of a specific line cindent() indent according to C indenting lispindent() indent according to Lisp indenting nextnonblank() find next non-blank line prevnonblank() find previous non-blank line search() find a match for a pattern searchpair() find the other end of a start/skip/end System functions and manipulation of files: browse() put up a file requester glob() expand wildcards globpath() expand wildcards in a number of directories resolve() find out where a shortcut points to fnamemodify() modify a file name executable() check if an executable program exists filereadable() check if a file can be read isdirectory() check if a directory exists getcwd() get the current working directory getfsize() get the size of a file getftime() get last modification time of a file localtime() get current time strftime() convert time to a string tempname() get the name of a temporary file delete() delete a file rename() rename a file system() get the result of a shell command hostname() name of the system Buffers, windows and the argument list: argc() number of entries in the argument list argidx() current position in the argument list argv() get one entry from the argument list bufexists() check if a buffer exists buflisted() check if a buffer exists and is listed bufloaded() check if a buffer exists and is loaded bufname() get the name of a specific buffer bufnr() get the buffer number of a specific buffer winnr() get the window number for the current window bufwinnr() get the window number of a specific buffer winbufnr() get the buffer number of a specific window getbufvar() get a variable value from a specific buffer setbufvar() set a variable in a specific buffer getwinvar() get a variable value from a specific window setwinvar() set a variable in a specific buffer Folding: foldclosed() check for a closed fold at a specific line foldlevel() check for the fold level at a specific line foldtext() generate the line displayed for a closed fold Syntax highlighting: hlexists() check if a highlight group exists hlID() get ID of a highlight group synID() get syntax ID at a specific position synIDattr() get a specific attribute of a syntax ID synIDtrans() get translated syntax ID History: histadd() add an item to a history histdel() delete an item from a history histget() get an item from a history histnr() get highest index of a history list Interactive: confirm() let the user make a choice getchar() get a character from the user getcharmod() get modifiers for the last typed character input() get a line from the user inputsecret() get a line from the user without showing it inputdialog() get a line from the user in a dialog Vim server: serverlist() return the list of server names remote_send() send command characters to a Vim server remote_expr() evaluate an expression in a Vim server server2client() send a reply to a client of a Vim server remote_peek() check if there is a reply from a Vim server remote_read() read a reply from a Vim server foreground() move the Vim window to the foreground remote_foreground() move the Vim server window to the foreground Various: mode() get current editing mode visualmode() last visual mode used hasmapto() check if a mapping exists mapcheck() check if a matching mapping exists maparg() get rhs of a mapping exists() check if a variable, function, etc. exists has() check if a feature is supported in Vim cscope_connection() check if a cscope connection exists did_filetype() check if a FileType autocommand was used eventhandler() check if invoked by an event handler getwinposx() X position of the GUI Vim window getwinposy() Y position of the GUI Vim window winheight() get height of a specific window winwidth() get width of a specific window libcall() call a function in an external library libcallnr() idem, returning a number
*41.7* Defining a function Vim enables you to define your own functions. The basic function declaration begins as follows: > :function {name}({var1}, {var2}, ...) : {body} :endfunction < Note: Function names must begin with a capital letter. Let's define a short function to return the smaller of two numbers. It starts with this line: > :function Min(num1, num2) This tells Vim that the function is named "Min" and it takes two arguments: "num1" and "num2". The first thing you need to do is to check to see which number is smaller: > : if a:num1 < a:num2 The special prefix "a:" tells Vim that the variable is a function argument. Let's assign the variable smaller the value of the smallest number: > : if a:num1 < a:num2 : let smaller = a:num1 : else : let smaller = a:num2 : endif The variable "smaller" is a local variable. Variables used inside a function are local unless prefixed by something like "g:", "a:", or "s:". Note: To access a global variable from inside a function you must prepend "g:" to it. Thus "g:count" inside a function is used for the global variable "count", and "count" is another variable, local to the function. You now use the ":return" statement to return the smallest number to the user. Finally, you end the function: > : return smaller :endfunction The complete function definition is as follows: > :function Min(num1, num2) : if a:num1 < a:num2 : let smaller = a:num1 : else : let smaller = a:num2 : endif : return smaller :endfunction A user defined function is called in exactly the same way as a builtin function. Only the name is different. The Min function can be used like this: > :echo Min(5, 8) Only now will the function be executed and the lines be interpreted by Vim. If there are mistakes, like using an undefined variable or function, you will now get an error message. When defining the function these errors are not detected. When a function reaches ":endfunction" or ":return" is used without an argument, the function returns zero. To redefine a function that already exists, use the ! for the ":function" command: > :function! Min(num1, num2, num3) USING A RANGE The ":call" command can be given a line range. This can have one of two meanings. When a function has been defined with the "range" keyword, it will take care of the line range itself. The function will be passed the variables "a:firstline" and "a:lastline". These will have the line numbers from the range the function was called with. Example: > :function Count_words() range : let n = a:firstline : let count = 0 : while n <= a:lastline : let count = count + Wordcount(getline(n)) : endwhile : echo "found " . count . " words" :endfunction You can call this function with: > :10,30call Count_words() It will be executed once and echo the number of words. The other way to use a line range is by defining a function without the "range" keyword. The function will be called once for every line in the range, with the cursor in that line. Example: > :function Number() : echo "line " . line(".") . " contains: " . getline(".") :endfunction If you call this function with: > :10,15call Number() The function will be called six times. VARIABLE NUMBER OF ARGUMENTS Vim enables you to define functions that have a variable number of arguments. The following command, for instance, defines a function that must have 1 argument (start) and can have up to 20 additional arguments: > :function Show(start, ...) The variable "a:1" contains the first optional argument, "a:2" the second, and so on. The variable "a:0" contains the number of extra arguments. For example: > :function Show(start, ...) : echohl Title : echo "Show is " . a:start : echohl None : let index = 1 : while index <= a:0 : execute 'echon " Arg " . index . " is " . a:' . index : let index = index + 1 : endwhile : echo "" :endfunction This uses the ":echohl" command to specify the highlighting used for the following ":echo" command. ":echohl None" stops it again. The ":echon" command works like ":echo", but doesn't output a line break. LISTING FUNCTIONS The ":function" command lists the names and arguments of all user-defined functions: > :function < function Show(start, ...) ~ function GetVimIndent()~ function SetSyn(name) ~ To see what a function does, use its name as an argument for ":function": > :function Show < 1 : echo "Show is " . a:start ~ 2 : let index = 1 ~ 3 : while index <= a:0 ~ 4 : execute 'echo "Arg " . index . " is " . a:' . index ~ 5 : let index = index + 1 ~ 6 : endwhile ~ endfunction ~ DEBUGGING The line number is useful for when you get an error message or when debugging. See |debug-scripts| about debugging mode. You can also set the 'verbose' option to 12 or higher to see all function calls. Set it to 15 or higher to see every executed line. DELETING A FUNCTION To delete the Show() function: > :delfunction Show You get an error when the function doesn't exist.
*41.8* Various remarks Here is a summary of items that apply to Vim scripts. They are also mentioned elsewhere, but form a nice checklist. The end-of-line character depends on the system. For Unix a single <NL> character is used. For MS-DOS, Windows, OS/2 and the like, <CR><LF> is used. This is important when using mappings that end in a <CR>. See |:source_crnl|. WHITE SPACE Blank lines are allowed and ignored. Leading whitespace characters (blanks and TABs) are always ignored. The whitespaces between parameters (e.g. between the 'set' and the 'cpoptions' in the example below) are reduced to one blank character and plays the role of a separator, the whitespaces after the last (visible) character may or may not be ignored depending on the situation, see below. For a ":set" command involving the "=" (equal) sign, such as in: > :set cpoptions =aABceFst The whitespace immediately before the "=" sign is ignored. But there can be no whitespace after the "=" sign! To include a whitespace character in the value of an option, it must be escaped by a "\" (backslash) as in the following example: > :set tags=my\ nice\ file The same example written as > :set tags=my nice file will issue an error, because it is interpreted as: > :set tags=my :set nice :set file COMMENTS The character " (the double quote mark) starts a comment. Everything after and including this character until the end-of-line is considered a comment and is ignored, except for commands that don't consider comments, as shown in examples below. A comment can start on any character position on the line. There is a little "catch" with comments for some commands. Examples: > :abbrev dev development " shorthand :map <F3> o#include " insert include :execute cmd " do it :!ls *.c " list C files The abbreviation 'dev' will be expanded to 'development " shorthand'. The mapping of <F3> will actually be the whole line after the 'o# ....' including the '" insert include'. The "execute" command will give an error. The "!" command will send everything after it to the shell, causing an error for an unmatched '"' character. There can be no comment after ":map", ":abbreviate", ":execute" and "!" commands (there are a few more commands with this restriction). For the "map", ":abbreviate" and "execute" commands there is a trick: > :abbrev dev development|" shorthand :map <F3> o#include|" insert include :execute cmd |" do it With the '|' character the command is separated from the next one. And that next command is only a comment. Notice that there is no white space before the '|' in the abbreviation and mapping. For these commands, any character until the end-of-line or '|' is included. As a consequence of this behavior, you don't always see that trailing whitespace is included: > :map <F4> o#include To avoid these problems, you can set the 'list' option when editing vimrc files. PITFALLS Even bigger problem arises in the following example: > :map ,ab o#include :unmap ,ab Here the unmap command will not work, because it tries to unmap ",ab ". This does not exist as a mapped sequence. An error will be issued, which is very hard to identify, because the ending whitespace character on the 'unmap ,ab ' is not visible. And this is the same as what happens when one uses a comment after an 'unmap' command: > :unmap ,ab " comment Here the comment part will be ignored. However, Vim will try to unmap ',ab ', which does not exist. Rewreite it as: > :unmap ,ab|" comment RESTORING THE VIEW Sometimes you want to make a change and go back to where cursor was. Restoring the relative position would also be nice, so that the same line appears at the top of the window. This example yanks the current line, puts it above the first line in the file and then restores the view: > map ,p ma"aYHmbgg"aP`bzt`a What this does: > ma"aYHmbgg"aP`bzt`a < ma set mark a at cursor position "aY yank current line into register a Hmb go to top line in window and set mark b there gg go to first line in file "aP put the yanked line above it `b go back to top line in display zt position the text in the window as before `a go back to saved cursor position PACKAGING To avoid your function names to interfere with functions that you get from others, use this scheme: - Prepend a unique string before each function name. I often use an abbreviation. For example, "OW_" is used for the option window functions. - Put the definition of your functions together in a file. Set a global variable to indicate that the functions have been loaded. When sourcing the file again, first unload the functions. Example: > " This is the XXX package if exists("XXX_loaded") delfun XXX_one delfun XXX_two endif function XXX_one(a) ... body of function ... endfun function XXX_two(b) ... body of function ... endfun let XXX_loaded = 1
*41.9* Writing a plugin *write-plugin* You can write a Vim script in such a way that many people can use it. This is called a plugin. Vim users can drop your script in their plugin directory and use its features right away |add-plugin|. There are actually two types of plugins: global plugins: For all types of files. filetype plugins: Only for files of a specific type. In this section the first type is explained. Most items are also relevant for writing filetype plugins. The specifics for filetype plugins are in the next section |write-filetype-plugin|. NAME First of all you must choose a name for your plugin. The features provided by the plugin should be clear from its name. And it should be unlikely that someone else writes a plugin with the same name but which does something different. And please limit the name to 8 characters, to avoid problems on old Windows systems. A script that corrects typing mistakes could be called "typecorr.vim". We will use it here as an example. For the plugin to work for everybody, it should follow a few guidelines. This will be explained step-by-step. The complete example plugin is at the end. BODY Let's start with the body of the plugin, the lines that do the actual work: > 13 iabbrev teh the 14 iabbrev otehr other 15 iabbrev wnat want 16 iabbrev synchronisation 17 \ synchronization 18 let s:count = 4 The actual list should be much longer, of course. The line numbers have only been added to explain a few things, don't put them in your plugin file! HEADER You will probably add new corrections to the plugin and soon have several versions laying around. And when distributing this file, people will want to know who wrote this wonderful plugin and where they can send remarks. Therefore, put a header at the top of your plugin: > 1 " Vim global plugin for correcting typing mistakes 2 " Last Change: 2000 Oct 15 3 " Maintainer: Bram Moolenaar<EMAIL_ADDRESS>LINE CONTINUATION, AVOIDING SIDE EFFECTS In line 17 above, the line-continuation mechanism is used |line-continuation|. Users with 'compatible' set will run into trouble here, they will get an error message. We can't just reset 'compatible', because that has a lot of side effects. To avoid this, we will set the 'cpoptions' option to its Vim default value and restore it later. That will allow the use of line-continuation and make the script work for most people. It is done like this: > 10 let s:save_cpo = &cpo 11 set cpo&vim .. 41 let &cpo = s:save_cpo We first store the old value of 'cpoptions' in the s:save_cpo variable. At the end of the plugin this value is restored. Notice that a script-local variable is used |s:var|. A global variable could already be in use for something else. Always use script-local variables for things that are only used in the script. NOT LOADING It's possible that a user doesn't always want to load this plugin. Or the system administrator has dropped it in the system-wide plugin directory, but a user has his own plugin he wants to use. Then the user must have a chance to disable loading this specific plugin. This will make it possible: > 5 if exists("loaded_typecorr") 6 finish 7 endif 8 let loaded_typecorr = 1 This also avoids that when the script is loaded twice it would cause error messages for redefining functions and cause trouble for autocommands that are added twice. MAPPING Now let's make the plugin more interesting: We will add a mapping that adds a correction for the word under the cursor. We could just pick a key sequence for this mapping, but the user might already use it for something else. To allow the user to define which keys a mapping in a plugin uses, the <Leader> item can be used: > 21 map <unique> <Leader>a <Plug>TypecorrAdd The "<Plug>TypecorrAdd" thing will do the work, more about that further on. The user can set the "mapleader" variable to the key sequence that he wants this mapping to start with. Thus if the user has done: > let mapleader = "_" the mapping will define "_a". If the user didn't do this, the default value will be used, which is a backslash. Then a map for "\a" will be defined. Note that <unique> is used, this will cause an error message if the mapping already happened to exist. |:map-<unique>| But what if the user wants to define his own key sequence? We can allow that with this mechanism: > 20 if !hasmapto('<Plug>TypecorrAdd') 21 map <unique> <Leader>a <Plug>TypecorrAdd 22 endif This checks if a mapping to "<Plug>TypecorrAdd" already exists, and only defines the mapping from "<Leader>a" if it doesn't. The user then has a chance of putting this in his vimrc file: > map ,c <Plug>TypecorrAdd Then the mapped key sequence will be ",c" instead of "_a" or "\a". PIECES If a script gets longer, you often want to break up the work in pieces. You can use functions or mappings for this. But you don't want these functions and mappings to interfere with the ones from other scripts. For example, you could define a function Add(), but another script could try to define the same function. To avoid this, we define the function local to the script by prepending it with "s:". We will define a function that adds a new typing correction: > 29 function s:Add(from, correct) 30 let to = input("type the correction for " . a:from . ": ") 31 exe ":iabbrev " . a:from . " " . to .. 35 endfunction Now we can call the function s:Add() from within this script. If another script also defines s:Add(), it will be local to that script and can only be called from the script it was defined in. There can also be a global Add() function (without the "s:"), which is again another function. <SID> can be used with mappings. It generates a script ID, which identifies the current script. In our typing correction plugin we use it like this: > 23 noremap <unique> <script> <Plug>TypecorrAdd <SID>Add .. 27 noremap <SID>Add :call <SID>Add(expand("<cword>"), 1)<CR> Thus when a user types "\a", this sequence is invoked: > \a -> <Plug>TypecorrAdd -> <SID>Add -> :call <SID>Add() If another script would also map <SID>Add, it would get another script ID and thus define another mapping. Note that instead of s:Add() we use <SID>Add() here. That is because the mapping is typed by the user, thus outside of the script. The <SID> is translated to the script ID, so that Vim knows in which script to look for the Add() function. This is a bit complicated, but it's required for the plugin to work together with other plugins. The basic rule is that you use <SID>Add() in mappings and s:Add() in other places (the script itself, autocommands, user commands). We can also add a menu entry to do the same as the mapping: > 25 noremenu <script> Plugin.Add\ Correction <SID>Add The "Plugin" menu is recommended for adding menu items for plugins. In this case only one item is used. When adding more items, creating a submenu is recommended. For example, "Plugin.CVS" could be used for a plugin that offers CVS operations "Plugin.CVS.checkin", "Plugin.CVS.checkout", etc. Note that in line 27 ":noremap" is used to avoid that any other mappings cause trouble. Someone may have remapped ":call", for example. In line 23 we also use ":noremap", but we do want "<SID>Add" to be remapped. This is why "<script>" is used here. This only allows mappings which are local to the script. |:map-<script>| The same is done in line 25 for ":noremenu". |:menu-<script>| <SID> AND <Plug> Both <SID> and <Plug> are used to avoid that mappings of typed keys interfere with mappings that are only to be used from other mappings. Note the difference between using <SID> and <Plug>: <Plug> is visible outside of the script. It is used for mappings which the user might want to map a key sequence to. <Plug> is a special code that a typed key will never produce. To make it very unlikely that other plugins use the same sequence of characters, use this structure: <Plug> scriptname mapname In our example the scriptname is "Typecorr" and the mapname is "Add". This results in "<Plug>TypecorrAdd". Only the first character of scriptname and mapname is uppercase, so that we can see where mapname starts. <SID> is the script ID, a unique identifier for a script. Internally Vim translates <SID> to "<SNR>123_", where "123" can be any number. Thus a function "<SID>Add()" will have a name "<SNR>11_Add()" in one script, and "<SNR>22_Add()" in another. You can see this if you use the ":function" command to get a list of functions. The translation of <SID> in mappings is exactly the same, that's how you can call a script-local function from a mapping. USER COMMAND Now let's add a user command to add a correction: > 37 if !exists(":Correct") 38 command -nargs=1 Correct :call s:Add(<q-args>, 0) 39 endif The user command is defined only if no command with the same name already exists. Otherwise we would get an error here. Overriding the existing user command with ":command!" is not a good idea, this would probably make the user wonder why the command he defined himself doesn't work. |:command| SCRIPT VARIABLES When a variable starts with "s:" it is a script variable. It can only be used inside a script. Outside the script it's not visible This avoids trouble with using the same variable name in different scripts. The variables will be kept as long as Vim is running. And the same variables are used when sourcing the same script again. |s:var| The fun is that these variables can also be used in functions, autocommands and user commands that are defined in the script. In our example we can add a few lines to count the number of corrections: > 18 let s:count = 4 .. 29 function s:Add(from, correct) .. 33 let s:count = s:count + 1 34 echo s:count . " corrections now" 35 endfunction First s:count is initialized to 4 in the script itself. When later the s:Add() function is called, it increments s:count. It doesn't matter from where the function was called, since it has been defined in the script, it will use the local variables from this script. THE RESULT Here is the resulting complete example: > 1 " Vim global plugin for correcting typing mistakes 2 " Last Change: 2000 Oct 15 3 " Maintainer: Bram Moolenaar<EMAIL_ADDRESS>4 5 if exists("loaded_typecorr") 6 finish 7 endif 8 let loaded_typecorr = 1 9 10 let s:save_cpo = &cpo 11 set cpo&vim 12 13 iabbrev teh the 14 iabbrev otehr other 15 iabbrev wnat want 16 iabbrev synchronisation 17 \ synchronization 18 let s:count = 4 19 20 if !hasmapto('<Plug>TypecorrAdd') 21 map <unique> <Leader>a <Plug>TypecorrAdd 22 endif 23 noremap <unique> <script> <Plug>TypecorrAdd <SID>Add 24 25 noremenu <script> Plugin.Add\ Correction <SID>Add 26 27 noremap <SID>Add :call <SID>Add(expand("<cword>"), 1)<CR> 28 29 function s:Add(from, correct) 30 let to = input("type the correction for " . a:from . ": ") 31 exe ":iabbrev " . a:from . " " . to 32 if a:correct | exe "normal viws\<C-R>\" \b\e" | endif 33 let s:count = s:count + 1 34 echo s:count . " corrections now" 35 endfunction 36 37 if !exists(":Correct") 38 command -nargs=1 Correct :call s:Add(<q-args>, 0) 39 endif 40 41 let &cpo = s:save_cpo Line 32 wasn't explained yet. It applies the new correction to the word under the cursor. The |:normal| command is used to use the new abbreviation. Note that mappings and abbreviations are expanded here, even though the function was called from a mapping defined with ":noremap". DOCUMENTATION *write-local-help* It's a good idea to also write some documentation for your plugin. Especially when its behavior can be changed by the user. See |add-local-help| for how they are installed. Here is a simple example for a plugin help file, called "typecorr.txt": > 1 *typecorr.txt* Plugin for correcting typing mistakes 2 3 If you make typing mistakes, this plugin will have them corrected 4 automatically. 5 6 There are currently only a few corrections. Add your own if you like. 7 8 Mappings: 9 <Leader>a or <Plug>TypecorrAdd 10 Add a correction for the word under the cursor. 11 12 Commands: 13 :Correct {word} 14 Add a correction for {word}. 15 16 *typecorr-settings* 17 This plugin doesn't have any settings. The first line is actually the only one for which the format matters. It will be extracted from the help file to be put in the "LOCAL ADDITIONS:" section of help.txt. The first "*" must be in the first column of the first line. You can add more tags inside ** in your help file. But be careful not to use existing help tags. You would probably use the name of your plugin in most of them, like "typecorr-settings" in the example. Using references to other parts of the help in || is recommended. This makes it easy for the user to find associated help. SUMMARY *plugin-special* Summary of special things to use in a plugin: s:name Variables local to the script. <SID> Script-ID, used for mappings and functions local to the script. hasmapto() Function to test if the user already defined a mapping for functionality the script offers. <Leader> Value of "mapleader", which the user defines as the keys that plugin mappings start with. :map <unique> Give a warning if a mapping already exists. :noremap <script> Use only mappings local to the script, not global mappings. exists(":Cmd") Check if a user command already exists.
*41.10* Writing a filetype plugin *write-filetype-plugin* *ftplugin* A filetype plugin is like a global plugin, except that it sets options and defines mappings for the current buffer only. See |add-filetype-plugin| for how this type of plugin is used. First read the section on global plugins above |41.9|. All that is said there also applies to filetype plugins. There are a few extras, which are explained here. The essential thing is that a filetype plugin should only have an effect on the current buffer. DISABLING If you are writing a filetype plugin to be used by many people, they need a chance to disable loading it. Put this at the top of the plugin: > " Only do this when not done yet for this buffer if exists("b:did_ftplugin") finish endif let b:did_ftplugin = 1 This also needs to be used to avoid that the same plugin is executed twice for the same buffer (happens when using an ":edit" command without arguments). Now users can disable loading the default plugin completely by making a filetype plugin with only this line: > let b:did_ftplugin = 1 This does require that the filetype plugin directory comes before $VIMRUNTIME in 'runtimepath'! If you do want to use the default plugin, but overrule one of the settings, you can make a filetype plugin like this: > source $VIMRUNTIME/ftplugin/vim.vim set textwidth=70 This first loads the default filetype plugin to get all its settings. Then the value for the 'textwidth' option is changed to "70". Note that the default plugin will have set "b:did_ftplugin", thus when it's sourced later, it won't do anything. OPTIONS To make sure the filetype plugin only affects the current buffer use the > :setlocal command to set options. And only set options which are local to a buffer (see the help for the option to check that). When using |:setlocal| for global options or options local to a window, the value will change for many buffers, and that is not what a filetype plugin should do. When an option has a value that is a list of flags or items, consider using "+=" and "-=" to keep the existing value. Be aware that the user may have changed an option value already. First resetting to the default value and then changing it often a good idea. Example: > :setlocal formatoptions& formatoptions+=ro MAPPINGS To make sure mappings will only work in the current buffer use the > :map <buffer> command. This needs to be combined with the two-step mapping explained above. An example of how to define funcionality in a filetype plugin: > if !hasmapto('<Plug>JavaImport') map <buffer> <unique> <LocalLeader>i <Plug>JavaImport endif noremap <buffer> <unique> <Plug>JavaImport oimport ""<Left><Esc> |hasmapto()| is used to check if the user has already defined a map to <Plug>JavaImport. If not, then the filetype plugin defines the default mapping. This starts with |<LocalLeader>|, which allows the user to select the key(s) he wants filetype plugin mappings to start with. The default is a backslash. "<unique>" is used to give an error message if the mapping already exists or overlaps with an existing mapping. |:noremap| is used to avoid that any other mappings that the user has defined interferes. You might want to use ":noremap <script>" to allow remapping mappings defined in this script that start with <SID>. The user must have a chance to disable the mappings in a filetype plugin, without disabling everything. Here is an example of how this is done for a plugin for the mail filetype: > " Add mappings, unless the user didn't want this. if !exists("no_plugin_maps") && !exists("no_mail_maps") " Quote text by inserting "> " if !hasmapto('<Plug>MailQuote') vmap <buffer> <LocalLeader>q <Plug>MailQuote nmap <buffer> <LocalLeader>q <Plug>MailQuote endif vnoremap <buffer> <Plug>MailQuote :s/^/> /<CR> nnoremap <buffer> <Plug>MailQuote :.,$s/^/> /<CR> endif Two global variables are used: no_plugin_maps disables mappings for all filetype plugins no_mail_maps disables mappings for a specific filetype USER COMMANDS To add a user command for a specific file type, so that it can only be used in one buffer, use the "-buffer" argument to |:command|. Example: > :command -buffer Make make %:r.s VARIABLES A filetype plugin will be sourced for each buffer of the type it's for. Local script variables |s:var| will be shared between all invocations. Use local buffer variables |b:var| if you want a variable specifically for one buffer. FUNCTIONS When defining a function, this only needs to be done once. But the filetype plugin will be sourced every time a file with this filetype will be opened. This construct make sure the function is only defined once: > :if !exists("*s:Func") : function s:Func(arg) : ... : endfunction :endif < SUMMARY *ftplugin-special* Summary of special things to use in a filetype plugin: <LocalLeader> Value of "maplocalleader", which the user defines as the keys that filetype plugin mappings start with. :map <buffer> Define a mapping local to the buffer. :noremap <script> Only remap mappings defined in this script that start with <SID>. :setlocal Set an option for the current buffer only. :command -buffer Define a user command local to the buffer. exists("*s:Func") Check if a function was already defined. Also see |plugin-special|, the special things used for all plugins.
*41.11* Writing a compiler plugin *write-compiler-plugin* A compiler plugin sets options for use with a specific compiler. The user can load it with the |:compiler| command. The main use is to set the 'errorformat' and 'makeprg' options. The only special item about these files is a mechanism to allow a user to overrule or add to the default file. The default files start with: > :if exists("current_compiler") : finish :endif :let current_compiler = "mine" When you write a compiler file and put it in your personal runtime directory (e.g., ~/.vim/runtime/compiler for Unix), you set the "current_compiler" variable to make the default file skip the settings. When you write a compiler plugin for the Vim distribution or for a system-wide runtime directory, use the mechanism mentioned above. When "current_compiler" was already set by a user plugin nothing will be done. When you write a compiler plugin to overrule settings from a default plugin, don't check "current_compiler". This plugin is supposed to be loaded last, thus it should be in a directory at the end of 'runtimepath'. For Unix that could be ~/.vim/runtime/after/compiler.
*usr_42.txt* For Vim version 6.1. Last change: 2002 Jan 23 Add new menus By now you know that Vim is very flexible. This includes the menus used in the GUI. You can define your own menu entries to make certain commands easily accessible. This is for mouse-happy users only. |42.1| Introduction |42.2| Menu commands |42.3| Various |42.4| Toolbar and popup menus
*42.1* Introduction The menus that Vim uses are defined in the file "$VIMRUNTIME/menu.vim". If you want to write your own menus, you might first want to look through that file. To define a menu item, use the ":menu" command. The basic form of this command is as follows: > :menu {menu-item} {keys} The {menu-item} describes where on the menu to put the item. A typical {menu-item} is "File.Save", which represents the item "Save" under the "File" menu. A dot is used to separate the names. Example: > :menu File.Save :update<CR> The ":update" command writes the file when it was modified. You can add another level: "Edit.Settings.Shiftwidth" defines a submenu "Settings" under the "Edit" menu, with an item "Shiftwidth". You could use even deeper levels. Don't use this too much, you need to move the mouse quite a bit to use such an item. The ":menu" command is very similar to the :map command: the left side specifies how the item is triggered and the right hand side defines the characters that are executed. {keys} are characters, they are used just like you would have typed them. Thus in Insert mode, when {keys} is plain text, that text is inserted. ACCELERATORS The ampersand character (&) is used to indicate an accelerator. For instance, you can use Alt-F to select "File" and S to select "Save". (the 'winaltkeys' option may disable this though!). Therefore, the {menu-item} looks like "&File.&Save". The accelerator characters will be underlined in the menu. You must take care that each key is used only once in each menu. Otherwise you will not know which of the two will actually be used. Vim doesn't warn you for this. PRIORITIES The actual definition of the File.Save menu item is as follows: > :menu 10.340 &File.&Save<Tab>:w :confirm w<CR> The number 10.340 is called the priority number. It is used by the editor to decide where it places the menu item. The first number (10) indicates the position on the menu bar. Lower numbered menus are positioned to the left, higher numbers to the right. These are the priorities used for the standard menus: 10 20 40 50 60 70 9999 +------------------------------------------------------------+ | File Edit Tools Syntax Buffers Window Help | +------------------------------------------------------------+ Notice that the Help menu is given a very high number, to make it appear on the far right. The second number (340) determines the location of the item within the pull-down menu. Lower numbers go on top, higher number on the bottom. These are the priorities in the File menu: +-----------------+ 10.310 |Open... | 10.320 |Split-Open... | 10.325 |New | 10.330 |Close | 10.335 |---------------- | 10.340 |Save | 10.350 |Save As... | 10.400 |---------------- | 10.410 |Split Diff with | 10.420 |Split Patched By | 10.500 |---------------- | 10.510 |Print | 10.600 |---------------- | 10.610 |Save-Exit | 10.620 |Exit | +-----------------+ Notice that there is room in between the numbers. This is where you can insert your own items, if you really want to (it's often better to leave the standard menus alone and add a new menu for your own items). When you create a submenu, you can add another ".number" to the priority. Thus each name in {menu-item} has its priority number. SPECIAL CHARACTERS The {menu-item} in this example is "&File.&Save<Tab>:w". This brings up an important point: {menu-item} must be one word. If you want to put a dot, space or tabs in the name, you either use the <> notation (<space> and <tab>, for instance) or use the backslash (\) escape. > :menu 10.305 &File.&Do\ It\.\.\. :exit<CR> In this example, the name of the menu item "Do It..." contains a space and the command is ":exit<CR>". The <Tab> character in a menu name is used to separate the part that defines the menu name from the part that gives a hint to the user. The part after the <Tab> is displayed right aligned in the menu. In the File.Save menu the name used is "&File.&Save<Tab>:w". Thus the menu name is "File.Save" and the hint is ":w". SEPARATORS The separator lines, used to group related menu items together, can be defined by using a name that starts and ends in a '-'. For example "-sep-". When using several separators the names must be different. Otherwise the names don't matter. The command from a separator will never be executed, but you have to define one anyway. A single colon will do. Example: > :amenu 20.510 Edit.-sep3- :
*42.2* Menu commands You can define menu items that exist for only certain modes. This works just like the variations on the ":map" command: :menu Normal, Visual and Operator-pending mode :nmenu Normal mode :vmenu Visual mode :omenu Operator-pending mode :menu! Insert and Command-line mode :imenu Insert mode :cmenu Command-line mode :amenu All modes To avoid that the commands of a menu item are being mapped, use the command ":noremenu", ":nnoremenu", "anoremenu", etc. USING :AMENU The ":amenu" command is a bit different. It assumes that the {keys} you give are to be executed in Normal mode. When Vim is in Visual or Insert mode when the menu is used, Vim first has to go back to Normal mode. ":amenu" inserts a CTRL-C or CTRL-O for you. For example, if you use this command: > :amenu 90.100 Mine.Find\ Word * Then the resulting menu commands will be: Normal mode: * Visual mode: CTRL-C * Operator-pending mode: CTRL-C * Insert mode: CTRL-O * Command-line mode: CTRL-C * When in Command-line mode the CTRL-C will abandon the command typed so far. In Visual and Operator-pending mode CTRL-C will stop the mode. The CTRL-O in Insert mode will execute the command and then return to Insert mode. CTRL-O only works for one command. If you need to use two or more commands, put them in a function and call that function. Example: > :amenu Mine.Next\ File :call <SID>NextFile()<CR> :function <SID>NextFile() : next : 1/^Code :endfunction This menu entry goes to the next file in the argument list with ":next". Then it searches for the line that starts with "Code". The <SID> before the function name is the script ID. This makes the function local to the current Vim script file. This avoids problems when a function with the same name is defined in another script file. See |<SID>|. SILENT MENUS The menu executes the {keys} as if you typed them. For a ":" command this means you will see the command being echoed on the command line. If it's a long command, the hit-Enter prompt will appear. That can be very annoying! To avoid this, make the menu silent. This is done with the <silent> argument. For example, take the call to NextFile() in the previous example. When you use this menu, you will see this on the command line: :call <SNR>34_NextFile() ~ To avoid this text on the command line, insert "<silent>" as the first argument: > :amenu <silent> Mine.Next\ File :call <SID>NextFile()<CR> Don't use "<silent>" too often. It is not needed for short commands. If you make a menu for someone else, being able the see the executed command will give him a hint about what he could have typed, instead of using the mouse. LISTING MENUS When a menu command is used without a {keys} part, it lists the already defined menus. You can specify a {menu-item}, or part of it, to list specific menus. Example: > :amenu This lists all menus. That's a long list! Better specify the name of a menu to get a shorter list: > :amenu Edit This lists only the "Edit" menu items for all modes. To list only one specific menu item for Insert mode: > :imenu Edit.Undo Take care that you type exactly the right name. Case matters here. But the '&' for accelerators can be omitted. The <Tab> and what comes after it can be left out as well. DELETING MENUS To delete a menu, the same command is used as for listing, but with "menu" changed to "unmenu". Thus ":menu" becomes, ":unmenu", ":nmenu" becomes ":nunmenu", etc. To delete the "Tools.Make" item for Insert mode: > :iunmenu Tools.Make You can delete a whole menu, with all its items, by using the menu name. Example: > :aunmenu Syntax This deletes the Syntax menu and all the items in it.
*42.3* Various You can change the appearance of the menus with flags in 'guioptions'. In the default value they are all included. You can remove a flag with a command like: > :set guioptions-=m < m When removed the menubar is not displayed. M When removed the default menus are not loaded. g When removed the inactive menu items are not made grey but are completely removed. (Does not work on all systems.) t When removed the tearoff feature is not enabled. The dotted line at the top of a menu is not a separator line. When you select this item, the menu is "teared-off": It is displayed in a separate window. This is called a tearoff menu. This is useful when you use the same menu often. For translating menu items, see |:menutrans|. Since the mouse has to be used to select a menu item, it is a good idea to use the ":browse" command for selecting a file. And ":confirm" to get a dialog instead of an error message, e.g., when the current buffer contains changes. These two can be combined: > :amenu File.Open :browse confirm edit<CR> The ":browse" makes a file browser appear to select the file to edit. The ":confirm" will pop up a dialog when the current buffer has changes. You can then select to save the changes, throw them away or cancel the command. For more complicated items, the confirm() and inputdialog() functions can be used. The default menus contain a few examples.
*42.4* Toolbar and popup menus There are two special menus: ToolBar and PopUp. Items that start with these names do not appear in the normal menu bar. TOOLBAR The toolbar appears only when the "T" flag is included in the 'guioptions' option. The toolbar uses icons rather than text to represent the command. For example, the {menu-item} named "ToolBar.New" causes the "New" icon to appear on the toolbar. The Vim editor has 28 built-in icons. You can find a table here: |builtin-tools|. Most of them are used in the default toolbar. You can redefine what these items do (after the default menus are setup). You can add another bitmap for a toolbar item. Or define a new toolbar item with a bitmap. For example, define a new toolbar item with: > :tmenu ToolBar.Compile Compile the current file :amenu ToolBar.Compile :!cc % -o %:r<CR> Now you need to create the icon. For MS-Windows it must be in bitmap format, with the name "Compile.bmp". For Unix XPM format is used, the file name is "Compile.xpm". The size must be 18 by 18 pixels. On MS-Windows other sizes can be used as well, but it will look ugly. Put the bitmap in the directory "bitmaps" in one of the directories from 'runtimepath'. E.g., for Unix "~/.vim/bitmaps/Compile.xpm". You can define tooltips for the items in the toolbar. A tooltip is a short text that explains what a toolbar item will do. For example "Open file". It appears when the mouse pointer is on the item, without moving for a moment. This is very useful if the meaning of the picture isn't that obvious. Example: > :tmenu ToolBar.Make Run make in the current directory < Note: Pay attention to the case used. "Toolbar" and "toolbar" are different from "ToolBar"! To remove a tooltip, use the |:tunmenu| command. The 'toolbar' option can be used to display text instead of a bitmap, or both text and a bitmap. Most people use just the bitmap, since the text takes quite a bit of space. POPUP MENU The popup menu pops up where the mouse pointer is. On MS-Windows you activate it by clicking the right mouse button. Then you can select an item with the left mouse button. On Unix the popup menu is used by pressing and holding the right mouse button. The popup menu only appears when the 'mousemodel' has been set to "popup" or "popup_setpos". The difference between the two is that "popup_setpos" moves the cursor to the mouse pointer position. When clicking inside a selection, the selection will be used unmodified. When there is a selection but you click outside of it, the selection is removed. There is a separate popup menu for each mode. Thus there are never grey items like in the normal menus. What is the meaning of life, the universe and everything? *42* Douglas Adams, the only person who knew what this question really was about is now dead, unfortunately. So now you might wonder what the meaning of death is...
*usr_43.txt* For Vim version 6.1. Last change: 2001 Sep 03 Using filetypes When you are editing a file of a certain type, for example a C program or a shell script, you often use the same option settings and mappings. You quickly get tired of manually setting these each time. This chapter explains how to do it automatically. |43.1| Plugins for a filetype |43.2| Adding a filetype
*43.1* Plugins for a filetype *filetype-plugin* How to start using filetype plugins has already been discussed here: |add-filetype-plugin|. But you probably are not satisfied with the default settings, because they have been kept minimal. Suppose that for C files you want to set the 'softtabstop' option to 4 and define a mapping to insert a three-line comment. You do this with only two steps: *your-runtime-dir* 1. Create your own runtime directory. On Unix this usually is "~/.vim". In this directory create the "ftplugin" directory: > mkdir ~/.vim mkdir ~/.vim/ftplugin < When you are not on Unix, check the value of the 'runtimepath' option to see where Vim will look for the "ftplugin" directory: > set runtimepath < You would normally use the first directory name (before the first comma). You might want to prepend a directory name to the 'runtimepath' option in your |vimrc| file if you don't like the default value. 2. Create the file "~/.vim/ftplugin/c.vim", with the contents: > setlocal softtabstop=4 noremap <buffer> <LocalLeader>c o/**************<CR><CR>/<Esc> Try editing a C file. You should notice that the 'softtabstop' option is set to 4. But when you edit another file it's reset to the default zero. That is because the ":setlocal" command was used. This sets the 'softtabstop' option only locally to the buffer. As soon as you edit another buffer, it will be set to the value set for that buffer. For a new buffer it will get the default value or the value from the last ":set" command. Likewise, the mapping for "\c" will disappear when editing another buffer. The ":map <buffer>" command creates a mapping that is local to the current buffer. This works with any mapping command: ":map!", ":vmap", etc. The |<LocalLeader>| in the mapping is replaced with the value of "maplocalleader". You can find examples for filetype plugins in this directory: > $VIMRUNTIME/ftplugin/ More details about writing a filetype plugin can be found here: |write-plugin|.
*43.2* Adding a filetype If you are using a type of file that is not recognized by Vim, this is how to get it recognized. You need a runtime directory of your own. See |your-runtime-dir| above. Create a file "filetype.vim" which contains an autocommand for your filetype. (Autocommands were explained in section |40.3|.) Example: > augroup filetypedetect au BufNewFile,BufRead *.xyz setf xyz augroup END This will recognize all files that end in ".xyz" as the "xyz" filetype. The ":augroup" commands put this autocommand in the "filetypedetect" group. This allows removing all autocommands for filetype detection when doing ":filetype off". The "setf" command will set the 'filetype' option to its argument, unless it was set already. This will make sure that 'filetype' isn't set twice. You can use many different patterns to match the name of your file. Directory names can also be included. See |autocmd-patterns|. For example, the files under "/usr/share/scripts/" are all "ruby" files, but don't have the expected file name extension. Adding this to the example above: > augroup filetypedetect au BufNewFile,BufRead *.xyz setf xyz au BufNewFile,BufRead /usr/share/scripts/* setf ruby augroup END However, if you now edit a file /usr/share/scripts/README.txt, this is not a ruby file. The danger of a pattern ending in "*" is that it quickly matches too many files. To avoid trouble with this, put the filetype.vim file in another directory, one that is at the end of 'runtimepath'. For Unix for example, you could use "~/.vim/after/filetype.vim". You now put the detection of text files in ~/.vim/filetype.vim: > augroup filetypedetect au BufNewFile,BufRead *.txt setf text augroup END That file is found in 'runtimepath' first. Then use this in ~/.vim/after/filetype.vim, which is found last: > augroup filetypedetect au BufNewFile,BufRead /usr/share/scripts/* setf ruby augroup END What will happen now is that Vim searches for "filetype.vim" files in each directory in 'runtimepath'. First ~/.vim/filetype.vim is found. The autocommand to catch *.txt files is defined there. Then Vim finds the filetype.vim file in $VIMRUNTIME, which is halfway 'runtimepath'. Finally ~/.vim/after/filetype.vim is found and the autocommand for detecting ruby files in /usr/share/scripts is added. When you now edit /usr/share/scripts/README.txt, the autocommands are checked in the order in which they were defined. The *.txt pattern matches, thus "setf text" is executed to set the filetype to "text". The pattern for ruby matches too, and the "setf ruby" is executed. But since 'filetype' was already set to "text", nothing happens here. When you edit the file /usr/share/scripts/foobar the same autocommands are checked. Only the one for ruby matches and "setf ruby" sets 'filetype' to ruby. RECOGNIZING BY CONTENTS If your file cannot be recognized by its file name, you might be able to recognize it by its contents. For example, many script files start with a line like: #!/bin/xyz ~ To recognize this script create a file "scripts.vim" in your runtime directory (same place where filetype.vim goes). It might look like this: > if did_filetype() finish endif if getline(1) =~ '^#!.*[/\\]xyz\>' setf xyz endif The first check with did_filetype() is to avoid that you will check the contents of files for which the filetype was already detected by the file name. That avoids wasting time on checking the file when the "setf" command won't do anything. The scripts.vim file is sourced by an autocommand in the default filetype.vim file. Therefore, the order of checks is: 1. filetype.vim files before $VIMRUNTIME in 'runtimepath' 2. first part of $VIMRUNTIME/filetype.vim 3. all script.vim files in 'runtimepath' 4. remainder of $VIMRUNTIME/filetype.vim 5. filetype.vim files after $VIMRUNTIME in 'runtimepath' If this is not sufficient for you, add an autocommand that matches all files and sources a script or executes a function to check the contents of the file.
*usr_44.txt* For Vim version 6.1. Last change: 2001 Dec 22 Your own syntax highlighted Vim comes with highlighting for a couple of hundred different file types. If the file you are editing isn't included, read this chapter to find out how to get this type of file highlighted. Also see |:syn-define| in the reference manual. |44.1| Basic syntax commands |44.2| Keywords |44.3| Matches |44.4| Regions |44.5| Nested items |44.6| Following groups |44.7| Other arguments |44.8| Clusters |44.9| Including another syntax file |44.10| Synchronizing |44.11| Installing a syntax file |44.12| Portable syntax file layout
*44.1* Basic syntax commands Using an existing syntax file to start with will save you a lot of time. Try finding a syntax file in $VIMRUNTIME/syntax for a language that is similar. These files will also show you the normal layout of a syntax file. To understand it, you need to read the following. Let's start with the basic arguments. Before we start defining any new syntax, we need to clear out any old definitions: > :syntax clear This isn't required in the final syntax file, but very useful when experimenting. There are more simplifications in this chapter. If you are writing a syntax file to be used by others, read all the way through the end to find out the details. LISTING DEFINED ITEMS To check which syntax items are currently defined, use this command: > :syntax You can use this to check which items have actually been defined. Quite useful when you are experimenting with a new syntax file. It also shows the colors used for each item, which helps to find out what is what. To list the items in a specific syntax group use: > :syntax list {group-name} This also can be used to list clusters (explained in |44.8|). Just include the @ in the name. MATCHING CASE Some languages are not case sensitive, such as Pascal. Others, such as C, are case sensitive. You need to tell which type you have with the following commands: > :syntax case match :syntax case ignore The "match" argument means that Vim will match the case of syntax elements. Therefore, "int" differs from "Int" and "INT". If the "ignore" argument is used, the following are equivalent: "Procedure", "PROCEDURE" and "procedure". The :syntax case commands can appear anywhere in a syntax file and affect the syntax definitions that follow. In most cases, you have only one :syntax case command in your syntax file; if you work with an unusual language that contains both case-sensitive and non-case-sensitive elements, however, you can scatter the :syntax case command throughout the file.
*44.2* Keywords The most basic syntax elements are keywords. To define a keyword, use the following form: > :syntax keyword {group} {keyword} ... The {group} is the name of a syntax group. With the ":highlight" command you can assign colors to a {group}. The {keyword} argument is an actual keyword. Here are a few examples: > :syntax keyword xType int long char :syntax keyword xStatement if then else endif This example uses the group names "xType" and "xStatement". By convention, each group name is prefixed by the filetype for the language being defined. This example defines syntax for the x language (eXample language without an interesting name). In a syntax file for "csh" scripts the name "cshType" would be used. Thus the prefix is equal to the value of 'filetype'. These commands cause the words "int", "long" and "char" to be highlighted one way and the words "if", "then", "else" and "endif" to be highlighted another way. Now you need to connect the x group names to standard Vim names. You do this with the following commands: > :highlight link xType Type :highlight link xStatement Statement This tells Vim to highlight "xType" like "Type" and "xStatement" like "Statement". See |group-name| for the standard names. UNUSUAL KEYWORDS The characters used in a keyword must be in the 'iskeyword' option. If you use another character, the word will never match. Vim doesn't give a warning message for this. The x language uses the '-' character in keywords. This is how it's done: > :setlocal iskeyword+=- :syntax keyword xStatement when-not The ":setlocal" command is used to change 'iskeyword' only for the current buffer. Still it does change the behavior of commands like "w" and "*". If that is not wanted, don't define a keyword but use a match (explained in the next section). The x language allows for abbreviations. For example, "next" can be abbreviated to "n", "ne" or "nex". You can define them by using this command: > :syntax keyword xStatement n[ext] This doesn't match "nextone", keywords always match whole words only.
*44.3* Matches Consider defining something a bit more complex. You want to match ordinary identifiers. To do this, you define a match syntax item. This one matches any word consisting of only lowercase letters: > :syntax match xIdentifier /\<\l\+\>/ < Note: Keywords overrule any other syntax item. Thus the keywords "if", "then", etc., will be keywords, as defined with the ":syntax keyword" commands above, even though they also match the pattern for xIdentifier. The part at the end is a pattern, like it's used for searching. The // is used to surround the pattern (like how it's done in a ":substitute" command). You can use any other character, like a plus or a quote. Now define a match for a comment. In the x language it is anything from # to the end of a line: > :syntax match xComment /#.*/ Since you can use any search pattern, you can highlight very complex things with a match item. See |pattern| for help on search patterns.
*44.4* Regions In the example x language, strings are enclosed in double quotation marks ("). To highlight strings you define a region. You need a region start (double quote) and a region end (double quote). The definition is as follows: > :syntax region xString start=/"/ end=/"/ The "start" and "end" directives define the patterns used to find the start and end of the region. But what about strings that look like this? "A string with a double quote (\") in it" ~ This creates a problem: The double quotation marks in the middle of the string will end the region. You need to tell Vim to skip over any escaped double quotes in the string. Do this with the skip keyword: > :syntax region xString start=/"/ skip=/\\"/ end=/"/ The double backslash matches a single backslash, since the backslash is a special character in search patterns. When to use a region instead of a match? The main difference is that a match item is a single pattern, which must match as a whole. A region starts as soon as the "start" pattern matches. Whether the "end" pattern is found or not doesn't matter. Thus when the item depends on the "end" pattern to match, you cannot use a region. Otherwise, regions are often simpler to define. And it is easier to use nested items, as is explained in the next section.
*44.5* Nested items Take a look at this comment: %Get input TODO: Skip white space ~ You want to highlight TODO in big yellow letters, even though it is in a comment that is highlighted blue. To let Vim know about this, you define the following syntax groups: > :syntax keyword xTodo TODO contained :syntax match xComment /%.*/ contains=xTodo In the first line, the "contained" argument tells Vim that this keyword can exist only inside another syntax item. The next line has "contains=xTodo". This indicates that the xTodo syntax element is inside it. The result is that the comment line as a whole is matched with "xComment" and made blue. The word TODO inside it is matched by xTodo and highlighted yellow (highlighting for xTodo was setup for this). RECURSIVE NESTING The x language defines code blocks in curly braces. And a code block may contain other code blocks. This can be defined this way: > :syntax region xBlock start=/{/ end=/}/ contains=xBlock Suppose you have this text: while i < b { ~ if a { ~ b = c; ~ } ~ } ~ First a xBlock starts at the { in the first line. In the second line another { is found. Since we are inside a xBlock item, and it contains itself, a nested xBlock item will start here. Thus the "b = c" line is inside the second level xBlock region. Then a } is found in the next line, which matches with the end pattern of the region. This ends the nested xBlock. Because the } is included in the nested region, it is hidden from the first xBlock region. Then at the last } the first xBlock region ends. KEEPING THE END Consider the following two syntax items: > :syntax region xComment start=/%/ end=/$/ contained :syntax region xPreProc start=/#/ end=/$/ contains=xComment You define a comment as anything from % to the end of the line. A preprocessor directive is anything from # to the end of the line. Because you can have a comment on a preprocessor line, the preprocessor definition includes a "contains=xComment" argument. Now look what happens with this text: #define X = Y % Comment text ~ int foo = 1; ~ What you see is that the second line is also highlighted as xPreProc. The preprocessor directive should end at the end of the line. That is why you have used "end=/$/". So what is going wrong? The problem is the contained comment. The comment starts with % and ends at the end of the line. After the comment ends, the preprocessor syntax continues. This is after the end of the line has been seen, so the next line is included as well. To avoid this problem and to avoid a contained syntax item eating a needed end of line, use the "keepend" argument. This takes care of the double end-of-line matching: > :syntax region xComment start=/%/ end=/$/ contained :syntax region xPreProc start=/#/ end=/$/ contains=xComment keepend CONTAINING MANY ITEMS You can use the contains argument to specify that everything can be contained. For example: > :syntax region xList start=/\[/ end=/\]/ contains=ALL All syntax items will be contained in this one. It also contains itself, but not at the same position (that would cause an endless loop). You can specify that some groups are not contained. Thus contain all groups but the ones that are listed: > :syntax region xList start=/\[/ end=/\]/ contains=ALLBUT,xString With the "TOP" item you can include all items that don't have a "contained" argument. "CONTAINED" is used to only include items with a "contained" argument. See |:syn-contains| for the details.
*44.6* Following groups The x language has statements in this form: if (condition) then ~ You want to highlight the three items differently. But "(condition)" and "then" might also appear in other places, where they get different highlighting. This is how you can do this: > :syntax match xIf /if/ nextgroup=xIfCondition skipwhite :syntax match xIfCondition /([^)]*)/ contained nextgroup=xThen skipwhite :syntax match xThen /then/ contained The "nextgroup" argument specifies which item can come next. This is not required. If none of the items that are specified are found, nothing happens. For example, in this text: if not (condition) then ~ The "if" is matched by xIf. "not" doesn't match the specified nextgroup xIfCondition, thus only the "if" is highlighted. The "skipwhite" argument tells Vim that white space (spaces and tabs) may appear in between the items. Similar arguments are "skipnl", which allows a line break in between the items, and "skipempty", which allows empty lines. Notice that "skipnl" doesn't skip an empty line, something must match after the line break.
*44.7* Other arguments MATCHGROUP When you define a region, the entire region is highlighted according to the group name specified. To highlight the text enclosed in parentheses () with the group xInside, for example, use the following command: > :syntax region xInside start=/(/ end=/)/ Suppose, that you want to highlight the parentheses differently. You can do this with a lot of convoluted region statements, or you can use the "matchgroup" argument. This tells Vim to highlight the start and end of a region with a different highlight group (in this case, the Xparen group): > :syntax region xInside matchgroup=xParen start=/(/ end=/)/ The "matchgroup" argument applies to the start or end match that comes after it. In the previous example both start and end are highlighted with xParen. To highlight the end with xParenEnd: > > :syntax region xInside matchgroup=xParen start=/(/ \ matchgroup=xParenEnd end=/)/ A side effect of using "matchgroup" is that contained items will not match in the start or end of the region. The example for "transparent" uses this. TRANSPARENT In a C language file you would like to highlight the () text after a "while" differently from the () text after a "for". In both of these there can be nested () items, which should be highlighted in the same way. You must make sure the () highlighting stops at the matching ). This is one way to do this: > :syntax region cWhile matchgroup=cWhile start=/while\s*(/ end=/)/ \ contains=cCondNest :syntax region cFor matchgroup=cFor start=/for\s*(/ end=/)/ \ contains=cCondNest :syntax region cCondNest start=/(/ end=/)/ contained transparent Now you can give cWhile and cFor different highlighting. The cCondNest item can appear in either of them, but take over the highlighting of the item it is contained in. The "transparent" argument causes this. Notice that the "matchgroup" argument has the same group as the item itself. Why define it then? Well, the side effect of using a matchgroup is that contained items are not found in the match with the start item then. This avoids that the cCondNest group matches the ( just after the "while" or "for". If this would happen, it would span the whole text until the matching ) and the region would continue after it. Now cCondNest only matches after the match with the start pattern, thus after the first (. OFFSETS Suppose you want to define a region for the text between ( and ) after an "if". But you don't want to include the "if" or the ( and ). You can do this by specifying offsets for the patterns. Example: > :syntax region xCond start=/if\s*(/ms=e+1 end=/)/me=s-1 The offset for the start pattern is "ms=e+1". "ms" stands for Match Start. This defines an offset for the start of the match. Normally the match starts where the pattern matches. "e+1" means that the match now starts at the end of the pattern match, and then one character further. The offset for the end pattern is "me=s-1". "me" stands for Match End. "s-1" means the start of the pattern match and then one character back. The result is that in this text: if (foo == bar) ~ Only the text "foo == bar" will be highlighted as xCond. More about offsets here: |:syn-pattern-offset|. ONELINE The "oneline" argument indicates that the region does not cross a line boundary. For example: > :syntax region xIfThen start=/if/ end=/then/ oneline This defines a region that starts at "if" and ends at "then". But if there is no "then" after the "if", the region doesn't match. Note: When using "oneline" the region doesn't start if the end pattern doesn't match in the same line. Without "oneline" Vim does _not_ check if there is a match for the end pattern. The region starts even when the end pattern doesn't match in the rest of the file. CONTINUATION LINES AND AVOIDING THEM Things now become a little more complex. Let's define a preprocessor line. This starts with a # in the first column and continues until the end of the line. A line that ends with \ makes the next line a continuation line. The way you handle this is to allow the syntax item to contain a continuation pattern: > :syntax region xPreProc start=/^#/ end=/$/ contains=xLineContinue :syntax match xLineContinue "\\$" contained In this case, although xPreProc normally matches a single line, the group contained in it (namely xLineContinue) lets it go on for more than one line. For example, it would match both of these lines: #define SPAM spam spam spam \ ~ bacon and spam ~ In this case, this is what you want. If it is not what you want, you can call for the region to be on a single line by adding "excludenl" to the contained pattern. For example, you want to highlight "end" in xPreProc, but only at the end of the line. To avoid making the xPreProc continue on the next line, like xLineContinue does, use "excludenl" like this: > :syntax region xPreProc start=/^#/ end=/$/ \ contains=xLineContinue,xPreProcEnd :syntax match xPreProcEnd excludenl /end$/ contained :syntax match xLineContinue "\\$" contained "excludenl" must be placed before the pattern. Since "xLineContinue" doesn't have "excludenl", a match with it will extend xPreProc to the next line as before.
*44.8* Clusters One of the things you will notice as you start to write a syntax file is that you wind up generating a lot of syntax groups. Vim enables you to define a collection of syntax groups called a cluster. Suppose you have a language that contains for loops, if statements, while loops, and functions. Each of them contains the same syntax elements: numbers and identifiers. You define them like this: > :syntax match xFor /^for.*/ contains=xNumber,xIdent :syntax match xIf /^if.*/ contains=xNumber,xIdent :syntax match xWhile /^while.*/ contains=xNumber,xIdent You have to repeat the same "contains=" every time. If you want to add another contained item, you have to add it three times. Syntax clusters simplify these definitions by enabling you to have one cluster stand for several syntax groups. To define a cluster for the two items that the three groups contain, use the following command: > :syntax cluster xState contains=xNumber,xIdent Clusters are used inside other :syntax items just like any syntax group. Their names start with @. Thus, you can define the three groups like this: > :syntax match xFor /^for.*/ contains=@xState :syntax match xIf /^if.*/ contains=@xState :syntax match xWhile /^while.*/ contains=@xState You can add new group names to this cluster with the add argument: > :syntax cluster xState add=xString You can remove syntax groups from this list as well: > :syntax cluster xState remove=xNumber
*44.9* Including another syntax file The C++ language syntax is a superset of the C language. Because you do not want to write two syntax files, you can have the C++ syntax file read in the one for C by using the following command: > :runtime! syntax/c.vim The ":runtime!" command searches 'runtimepath' for all "syntax/c.vim" files. This makes the C syntax be defined like for C files. If you have replaced the c.vim syntax file, or added items with an extra file, these will be loaded as well. After loading the C syntax items the specific C++ items can be defined. For example, add keywords that are not used in C: > :syntax keyword cppStatement new delete this friend using This works just like in any other syntax file. Now consider the Perl language. It consists of two distinct parts: a documentation section in POD format, and a program written in Perl itself. The POD section starts with "=head" and ends with "=cut". You want to define the POD syntax in one file, and use it from the Perl syntax file. The ":syntax include" command reads in a syntax file and stores the elements it defined in a syntax cluster. For Perl, the statements are as follows: > :syntax include @Pod <sfile>:p:h/pod.vim :syntax region perlPOD start=/^=head/ end=/^=cut/ contains=@Pod When "=head" is found in a Perl file, the perlPOD region starts. In this region the @Pod cluster is contained. All the items defined as top-level items in the pod.vim syntax files will match here. When "=cut" is found, the region ends and we go back to the items defined in the Perl file. The ":syntax include" file is clever enough to ignore a ":syntax clear" command in the included file. And an argument like "contains=ALL" will only contain items defined in the included file, not in the file that includes it. The "<sfile>:p:h/" part uses the name of the current file (<sfile>), expands it to a full path (:p) and then takes the head (:h). This results in the directory name of the file. This causes the pod.vim file in the same directory to be included.
*44.10* Synchronizing Compilers have it easy. They start at the beginning of a file and parse it straight through. Vim does not have it so easy. It must start in the middle, where the editing is being done. So how does it tell where it is? The secret is the ":syntax sync" command. This tells Vim how to figure out where it is. For example, the following command tells Vim to scan backward for the beginning or end of a C-style comment and begin syntax coloring from there: > :syntax sync ccomment You can tune this processing with some arguments. The "minlines" argument tells Vim the minimum number of lines to look backward, and "maxlines" tells the editor the maximum number of lines to scan. For example, the following command tells Vim to look at least 10 lines before the top of the screen: > :syntax sync ccomment minlines=10 maxlines=500 If it cannot figure out where it is in that space, it starts looking farther and farther back until it figures out what to do. But it looks no farther back than 500 lines. (A large "maxlines" slows down processing. A small one might cause synchronization to fail.) To make synchronizing go a bit faster, tell Vim which syntax items can be skipped. Every match and region that only needs to be used when actually displaying text can be given the "display" argument. By default, the comment to be found will be colored as part of the Comment syntax group. If you want to color things another way, you can specify a different syntax group: > :syntax sync ccomment xAltComment If your programming language does not have C-style comments in it, you can try another method of synchronization. The simplest way is to tell Vim to space back a number of lines and try to figure out things from there. The following command tells Vim to go back 150 lines and start parsing from there: > :syntax sync minlines=150 A large "minlines" value can make Vim slower, especially when scrolling backwards in the file. Finally, you can specify a syntax group to look for by using this command: > :syntax sync match {sync-group-name} \ grouphere {group-name} {pattern} This tells Vim that when it sees {pattern} the syntax group named {group-name} begins just after the pattern given. The {sync-group-name} is used to give a name to this synchronization specification. For example, the sh scripting language begins an if statement with "if" and ends it with "fi": if [ --f file.txt ] ; then ~ echo "File exists" ~ fi ~ To define a "grouphere" directive for this syntax, you use the following command: > :syntax sync match shIfSync grouphere shIf "\<if\>" The "groupthere" argument tells Vim that the pattern ends a group. For example, the end of the if/fi group is as follows: > :syntax sync match shIfSync groupthere NONE "\<fi\>" In this example, the NONE tells Vim that you are not in any special syntax region. In particular, you are not inside an if block. You also can define matches and regions that are with no "grouphere" or "groupthere" arguments. These groups are for syntax groups skipped during synchronization. For example, the following skips over anything inside {}, even if it would normally match another synchronization method: > :syntax sync match xSpecial /{.*}/ More about synchronizing in the reference manual: |:syn-sync|.
*44.11* Installing a syntax file When your new syntax file is ready to be used, drop it in a "syntax" directory in 'runtimepath'. For Unix that would be "~/.vim/syntax". The name of the syntax file must be equal to the file type, with ".vim" added. Thus for the x language, the full path of the file would be: ~/.vim/syntax/x.vim ~ You must also make the file type be recognized. See |43.2|. If your file works well, you migth want to make it available to other Vim users. First read the next section to make sure your file works well for others. Then e-mail it to the Vim maintainer<EMAIL_ADDRESS>Also explain how the filetype can be detected. With a bit of luck your file will be included in the next Vim version! ADDING TO AN EXISTING SYNTAX FILE We were assuming you were adding a completely new syntax file. When an existing syntax file works, but is missing some items, you can add items in a separate file. That avoids changing the distributed syntax file, which will be lost when installing a new version of Vim. Write syntax commands in your file, possibly using group names from the existing syntax. For example, to add new variable types to the C syntax file: > :syntax keyword cType off_t uint Write the file with the same name as the original syntax file. In this case "c.vim". Place it in a directory near the end of 'runtimepath'. This makes it loaded after the original syntax file. For Unix this would be: ~/.vim/after/syntax/c.vim ~
*44.12* Portable syntax file layout Wouldn't it be nice if all Vim users exchange syntax files? To make this possible, the syntax file must follow a few guidelines. Start with a header that explains what the syntax file is for, who maintains it and when it was last updated. Don't include too much information about changes history, not many people will read it. Example: > " Vim syntax file " Language: C " Maintainer: Bram Moolenaar<EMAIL_ADDRESS>" Last Change: 2001 Jun 18 " Remark: Included by the C++ syntax. Use the same layout as the other syntax files. Using an existing syntax file as an example will save you a lot of time. Choose a good, descriptive name for your syntax file. Use lowercase letters and digits. Don't make it too long, it is used in many places: The name of the syntax file "name.vim", 'filetype', b:current_syntax the start of each syntax group (nameType, nameStatement, nameString, etc). Start with a check for "b:current_syntax". If it is defined, some other syntax file, earlier in 'runtimepath' was already loaded. To be compatible with Vim 5.8 use: > if version < 600 syntax clear elseif exists("b:current_syntax") finish endif Set "b:current_syntax" to the name of the syntax at the end. Don't forget that included files do this too, you might have to reset "b:current_syntax" if you include two files. If you want your syntax file to work with Vim 5.x, add a check for v:version. See yacc.vim for an example. Do not include anything that is a user preference. Don't set 'tabstop', 'expandtab', etc. These belong in a filetype plugin. Do not include mappings or abbreviations. Only include setting 'iskeyword' if it is really necessary for recognizing keywords. Avoid using specific colors. Link to the standard highlight groups whenever possible. Don't forget that some people use a different background color, or have only eight colors available. For backwards compatibility with Vim 5.8 this construction is used: > if version >= 508 || !exists("did_c_syn_inits") if version < 508 let did_c_syn_inits = 1 command -nargs=+ HiLink hi link <args> else command -nargs=+ HiLink hi def link <args> endif HiLink nameString String HiLink nameNumber Number ... etc ... delcommand HiLink endif Add the "display" argument to items that are not used when syncing, to speed up scrolling backwards and CTRL-L.
*usr_45.txt* For Vim version 6.1. Last change: 2001 Sep 03 Select your language The messages in Vim can be given in several languages. This chapter explains how to change which one is used. Also, the different ways to work with files in various languages is explained. |45.1| Language for Messages |45.2| Language for Menus |45.3| Using another encoding |45.4| Editing files with a different encoding |45.5| Entering language text
*45.1* Language for Messages When you start Vim, it checks the environment to find out what language you are using. Mostly this should work fine, and you get the messages in your language (if they are available). To see what the current language is, use this command: > :language If it replies with "C", this means the default is being used, which is English. Note: Using different languages only works when Vim was compiled to handle it. To find out if it works, use the ":version" command and check the output for "+gettext" and "+multi_lang". If they are there, you are OK. If you see "-gettext" or "-multi_lang" you will have to find another Vim. What if you would like your messages in a different language? There are several ways. Which one you should use depends on the capabilities of your system. The first way is to set the environment to the desired language before starting Vim. Example for Unix: > env LANG=de_DE.ISO_8859-1 vim This only works if the language is available on your system. The advantage is that all the GUI messages and things in libraries will use the right language as well. A disadvantage is that you must do this before starting Vim. If you want to change language while Vim is running, you can use the second method: > :language fr_FR.ISO_8859-1 This way you can try out several names for your language. You will get an error message when it's not supported on your system. You don't get an error when translated messages are not available. Vim will silently fall back to using English. To find out which languages are supported on your system, find the directory where they are listed. On my system it is "/usr/share/locale". On some systems it's in "/usr/lib/locale". The manual page for "setlocale" should give you a hint where it is found on your system. Be careful to type the name exactly as it should be. Upper and lowercase matter, and the '-' and '_' characters are easily confused. You can also set the language separately for messages, edited text and the time format. See |:language|. DO-IT-YOURSELF MESSAGE TRANSLATION If translated messages are not available for your language, you could write them yourself. To do this, get the source code for Vim and the GNU gettext package. After unpacking the sources, instructions can be found in the directory src/po/README.txt. It's not too difficult to do the translation. You don't need to be a programmer. You must know both English and the language you are translating to, of course. When you are satisfied with the translation, consider making it available to others. Upload it at vim-online (http://vim.sf.net) or e-mail it to the Vim maintainer<EMAIL_ADDRESS>Or both.
*45.2* Language for Menus The default menus are in English. To be able to use your local language, they must be translated. Normally this is automatically done for you if the environment is set for your language, just like with messages. You don't need to do anything extra for this. But it only works if translations for the language are available. Suppose you are in Germany, with the language set to German, but prefer to use "File" instead of "Datei". You can switch back to using the English menus this way: > :set langmenu=none It is also possible to specify a language: > :set langmenu=nl_NL.ISO_8859-1 Like above, differences between "-" and "_" matter. However, upper/lowercase differences are ignored here. The 'langmenu' option must be set before the menus are loaded. Once the menus have been defined changing 'langmenu' has no direct effect. Therefore, put the command to set 'langmenu' in your vimrc file. If you really want to switch menu language while running Vim, you can do it this way: > :source $VIMRUNTIME/delmenu.vim :set langmenu=de_DE.ISO_8859-1 :source $VIMRUNTIME/menu.vim There is one drawback: All menus that you defined yourself will be gone. You will need to redefine them as well. DO-IT-YOURSELF MENU TRANSLATION To see which menu translations are available, look in this directory: $VIMRUNTIME/lang ~ The files are called menu_{language}.vim. If you don't see the language you want to use, you can do your own translations. The simplest way to do this is by copying one of the existing language files, and change it. First find out the name of your language with the ":language" command. Use this name, but with all letters made lowercase. Then copy the file to your own runtime directory, as found early in 'runtimepath'. For example, for Unix you would do: > :!cp $VIMRUNTIME/lang/menu_ko_kr.euckr.vim ~/.vim/lang/menu_nl_be.iso_8859-1.vim You will find hints for the translation in "$VIMRUNTIME/lang/README.txt".
*45.3* Using another encoding Vim guesses that the files you are going to edit are encoded for your language. For many European languages this is "latin1". Then each byte is one character. That means there are 256 different characters possible. For Asian languages this is not sufficient. These mostly use a double-byte encoding, providing for over ten thousand possible characters. This still isn't enough when a text is to contain several different languages. This is where Unicode comes in. It was designed to include all characters used in commonly used languages. This is the "Super encoding that replaces all others". But it isn't used that much yet. Fortunately, Vim supports these three kinds of encodings. And, with some restrictions, you can use them even when your environment uses another language than the text. Nevertheless, when you only edit files that are in the encoding of your language, the default should work fine and you don't need to do anything. The following is only relevant when you want to edit different languages. Note: Using different encodings only works when Vim was compiled to handle it. To find out if it works, use the ":version" command and check the output for "+multi_byte". If it's there, you are OK. If you see "-multi_byte" you will have to find another Vim. USING UNICODE IN THE GUI The nice thing about Unicode is that other encodings can be converted to it and back without losing information. When you make Vim use Unicode internally, you will be able to edit files in any encoding. Unfortunately, the number of systems supporting Unicode is still limited. Thus it's unlikely that your language uses it. You need to tell Vim you want to use Unicode, and how to handle interfacing with the rest of the system. Let's start with the GUI version of Vim, which is able to display Unicode characters. This should work: > :set encoding=utf-8 :set guifont=-misc-fixed-medium-r-normal--18-120-100-100-c-90-iso10646-1 The 'encoding' option tells Vim the encoding of the characters that you use. This applies to the text in buffers (files you are editing), registers, Vim script files, etc. You can regard 'encoding' as the setting for the internals of Vim. This example assumes you have this font on your system. The name in the example is for X-Windows. This font is in a package that is used to enhance xterm with Unicode support. If you don't have this font, you might find it here: http://www.cl.cam.ac.uk/~mgk25/download/ucs-fonts.tar.gz ~ For MS-Windows, some fonts have a limited number of Unicode characters. Try using the "Courier New" font. You can use the Edit/Select Font... menu to select and try out the fonts available. Only fixed-width fonts can be used though. Example: > :set guifont=courier_new:h12 If it doesn't work well, try getting a fontpack. If Microsoft didn't move it, you can find it here: http://www.microsoft.com/typography/fontpack/default.htm ~ Now you have told Vim to use Unicode internally and display text with a Unicode font. Typed characters still arrive in the encoding of your original language. This requires converting them to Unicode. Tell Vim the language from which to convert with the 'termencoding' option. You can do it like this: > :let &termencoding = &encoding :set encoding=utf-8 This assigns the old value of 'encoding' to 'termencoding' before setting 'encoding' to utf-8. You will have to try out if this really works for your setup. It should work especially well when using an input method for an Asian language, and you want to edit Unicode text. USING UNICODE IN A UNICODE TERMINAL There are terminals that support Unicode directly. The standard xterm that comes with XFree86 is one of them. Let's use that as an example. First of all, the xterm must have been compiled with Unicode support. See |UTF8-xterm| how to check that and how to compile it when needed. Start the xterm with the "-u8" argument. You might also need so specify a font. Example: > xterm -u8 -fn -misc-fixed-medium-r-normal--18-120-100-100-c-90-iso10646-1 Now you can run Vim inside this terminal. Set 'encoding' to "utf-8" as before. That's all. USING UNICODE IN AN ORDINARY TERMINAL Suppose you want to work with Unicode files, but don't have a terminal with Unicode support. You can do this with Vim, although characters that are not supported by the terminal will not be displayed. The layout of the text will be preserved. > :let &termencoding = &encoding :set encoding=utf-8 This is the same as what was used for the GUI. But it works differently: Vim will convert the displayed text before sending it to the terminal. That avoids that the display is messed up with strange characters. For this to work the conversion between 'termencoding' and 'encoding' must be possible. Vim will convert from latin1 to Unicode, thus that always works. For other conversions the |+iconv| feature is required. Try editing a file with Unicode characters in it. You will notice that Vim will put a question mark (or underscore or some other character) in places where a character should be that the terminal can't display. Move the cursor to a question mark and use this command: > ga Vim will display a line with the code of the character. This gives you a hint about what character it is. You can look it up in a Unicode table. You could actually view a file that way, if you have lots of time at hand. Note: Since 'encoding' is used for all text inside Vim, changing it makes all non-ASCII text invalid. You will notice this when using registers and the 'viminfo' file (e.g., a remembered search pattern). It's recommended to set 'encoding' in your vimrc file, and leave it alone.
*45.4* Editing files with a different encoding Suppose you have setup Vim to use Unicode, and you want to edit a file that is in 16-bit Unicode. Sounds simple, right? Well, Vim actually uses utf-8 encoding internally, thus the 16-bit encoding must be converted. Thus there is a difference between the character set (Unicode) and the encoding (utf-8 or 16-bit). Vim will try to detect what kind of file you are editing. It uses the encoding names in the 'fileencodings' option. When using Unicode, the default value is: "ucs-bom,utf-8,latin1". This means that Vim checks the file to see if it's one of these encodings: ucs-bom File must start with a Byte Order Mark (BOM). This allows detection of 16-bit, 32-bit and utf-8 Unicode encodings. utf-8 utf-8 Unicode. This is rejected when a sequence of bytes is illegal in utf-8. latin1 The good old 8-bit encoding. Always works. When you start editing that 16-bit Unicode file, and it has a BOM, Vim will detect this and convert the file to utf-8 when reading it. The 'fileencoding' option (without s at the end) is set to the detected value. In this case it is "ucs-2le". That means it's Unicode, two bytes and little-endian. This file format is common on MS-Windows (e.g., for registry files). When writing the file, Vim will compare 'fileencoding' with 'encoding'. If they are different, the text will be converted. An empty value for 'fileencoding' means that no conversion is to be done. Thus the text is assumed to be encoded with 'encoding'. If the default 'fileencodings' value is not good for you, set it to the encodings you want Vim to try. Only when a value is found to be invalid will the next one be used. Putting "latin1" first doesn't work, because it is never illegal. An example, to fall back to Japanese when the file doesn't have a BOM and isn't utf-8: > :set fileencodings=ucs-bom,utf-8,sjis See |encoding-values| for suggested values. Other values may work as well. This depends on the conversion available. FORCING AN ENCODING If the automatic detection doesn't work you must tell Vim what encoding the file is. Example: > :edit ++enc=koi8-r russian.txt The "++enc" part specifies the name of the encoding to be used for this file only. Vim will convert the file from the specified encoding, Russian in this example, to 'encoding'. 'fileencoding' will also be set to the specified encoding, so that the reverse conversion can be done when writing the file. The same argument can be used when writing the file. This way you can actually use Vim to convert a file. Example: > :write ++enc=utf-8 russian.txt < Note: Conversion may result in lost characters. Conversion from an encoding to Unicode and back is mostly free of this problem, unless there are illegal characters. Conversion from Unicode to other encodings often loses information when there was more than one language in the file.
*45.5* Entering language text Computer keyboards don't have much more than a hundred keys. Some languages have thousands of characters, Unicode has ten thousands. So how do you type these characters? First of all, when you don't use too many of the special characters, you can use digraphs. This was already explained in |24.9|. When you use a language that uses many more characters than keys on your keyboard, you will want to use an Input Method (IM). This requires learning the translation from typed keys to resulting character. When you need an IM you probably already have one on your system. It should work with Vim like with other programs. For details see |mbyte-XIM| for X-Windows and |mbyte-IME| for MS-Windows. KEYMAPS For some languages the character set is different from latin, but uses a similar number of characters. It's possible to map keys to characters. Vim uses keymaps for this. Suppose you want to type hebrew. You can load the keymap like this: > :set keymap=hebrew Vim will try to find a keymap file for you. This depends on the value of 'encoding'. If no matching file was found, you will get an error message. Now you can type Hebrew in Insert mode. In Normal mode, and when typing a ":" command, Vim automatically switches to English. You can use this command to switch between Hebrew and English: > CTRL-^ This only works in Insert mode and Command-line mode. In Normal mode it does something completely different (jumps to alternate file). The usage of the keymap is indicated in the mode message, if you have the 'showmode' option set. In the GUI Vim will indicate the usage of keymaps with a different cursor color. You can also change the usage of the keymap with the 'iminsert' and 'imsearch' options. To see the list of mappings, use this command: > :lmap To find out which keymap files are available, in the GUI you can use the Edit/Keymap menu. Otherwise you can use this command: > :echo globpath(&rtp, "keymap/*.vim") DO-IT-YOURSELF KEYMAPS You can create your own keymap file. It's not very difficult. Start with a keymap file that is similar to the language you want to use. Copy it to the "keymap" directory in your runtime directory. For example, for Unix, you would use the directory "~/.vim/keymap". The name of the keymap file must look like this: keymap/{name}.vim ~ or keymap/{name}_{encoding}.vim ~ {name} is the name of the keymap. Chose a name that is obvious, but different from existing keymaps (unless you want to replace an existing keymap file). The name cannot contain an underscore. Optionally, add the encoding used. Examples: keymap/hebrew.vim ~ keymap/hebrew_utf-8.vim ~ The contents of the file should be self-explanatory. Look at a few of the keymaps that are distributed with Vim. For the details, see |mbyte-keymap|. LAST RESORT If all other methods fail, you can enter any character with CTRL-V: encoding type range ~ 8-bit CTRL-V 123 decimal 0-255 8-bit CTRL-V x a1 hexadecimal 00-ff 16-bit CTRL-V u 013b hexadecimal 0000-ffff 31-bit CTRL-V U 001303a4 hexadecimal 00000000-7fffffff Don't type the spaces. See |i_CTRL-V_digit| for the details.
*usr_90.txt* For Vim version 6.1. Last change: 2001 Oct 23 Installing Vim *install* Before you can use Vim you have to install it. Depending on your system it's simple or easy. This chapter gives a few hints and also explains how upgrading to a new version is done. |90.1| Unix |90.2| MS-Windows |90.3| Upgrading |90.4| Common installation issues |90.5| Uninstalling Vim
*90.1* Unix First you have to decide if you are going to install Vim system-wide or for a single user. The installation is almost the same, but the directory where Vim is installed in differs. For a system-wide installation the base directory "/usr/local" is often used. But this may be different for your system. Try finding out where other packages are installed. When installing for a single user, you can use your home directory as the base. The files will be placed in subdirectories like "bin" and "shared/vim". FROM A PACKAGE You can get precompiled binaries for many different UNIX systems. There is a long list with links on this page: http://www.vim.org/binaries.html ~ Volunteers maintain the binaries, so they are often out of date. It is a good idea to compile your own UNIX version from the source. Also, creating the editor from the source allows you to control which features are compiled. This does require a compiler though. If you have a Linux distribution, the "vi" program is probably a minimal version of Vim. It doesn't do syntax highlighting, for example. Try finding another Vim package in your distribution, or search on the web site. FROM SOURCES To compile and install Vim, you will need the following: - A C compiler (GCC preferred) - The GZIP program (you can get it from www.gnu.org) - The Vim source and runtime archives To get the Vim archives, look in this file for a mirror near you, this should provide the fastest download: ftp://ftp.vim.org/pub/vim/MIRRORS ~ Or use the home site ftp.vim.org, if you think it's fast enough. Go to the "unix" directory and you'll find a list of files there. The version number is embedded in the file name. You will want to get the most recent version. You can get the files for Unix in two ways: One big archive that contains everything, or four smaller ones that each fit on a floppy disk. For version 6.0 the single big one is called: vim-6.0.tar.bz2 ~ You need the bzip2 program to uncompress it. If you don't have it, get the four smaller files, which can be uncompressed with gzip. For Vim 6.0 they are called: vim-6.0-src1.tar.gz ~ vim-6.0-src2.tar.gz ~ vim-6.0-rt1.tar.gz ~ vim-6.0-rt2.tar.gz ~ COMPILING First create a top directory to work in, for example: > mkdir ~/vim cd ~/vim Then unpack the archives there. If you have the one big archive, you unpack it like this: > bzip2 -d -c path/vim-6.0.tar.bz2 | tar xf - Change "path" to where you have downloaded the file. gzip -d path/vim-6.0-src1.tar.gz | tar xf - gzip -d path/vim-6.0-src2.tar.gz | tar xf - gzip -d path/vim-6.0-rt1.tar.gz | tar xf - gzip -d path/vim-6.0-rt2.tar.gz | tar xf - If you are satisfied with getting the default features, and your environment is setup properly, you should be able to compile Vim with just this: > cd vim60/src make The make program will run configure and compile everything. Further on we will explain how to compile with different features. If there are errors while compiling, carefully look at the error messages. There should be a hint about what went wrong. Hopefully you will be able to correct it. You might have to disable some features to make Vim compile. Look in the Makefile for specific hints for your system. TESTING Now you can check if compiling worked OK: > make test This will run a sequence of test scripts to verify that Vim works as expected. Vim will be started many times and all kinds of text and messages flash by. If it is alright you will finally see: test results: ~ ALL DONE ~ If there are one or two messages about failed tests, Vim might still work, but not perfectly. If you see a lot of error messages or Vim doesn't finish until the end, there must be something wrong. Either try to find out yourself, or find someone who can solve it. You could look in the |maillist-archive| for a solution. If everything else fails, you could ask in the vim |maillist| if someone can help you. INSTALLING *install-home* If you want to install in your home directory, edit the Makefile and search for a line: #prefix = $(HOME) ~ Remove the # at the start of the line. When installing for the whole system, Vim has most likely already selected a good installation directory for you. You can also specify one, see below. You need to become root for the following. To install Vim do: > make install That should move all the relevant files to the right place. Now you can try running vim to verify that it works. Use two simple tests to check if Vim can find its runtime files: > :help :syntax enable If this doesn't work, use this command to check where Vim is looking for the runtime files: > :echo $VIMRUNTIME You can also start Vim with the "-V" argument to see what happens during startup: > vim -V Don't forget that the user manual assumes you Vim in a certain way. After installing Vim, follow the instructions at |not-compatible| to make Vim work as assumed in this manual. SELECTING FEATURES Vim has many ways to select features. One of the simple ways is to edit the Makefile. There are many directions and examples. Often you can enable or disable a feature by uncommenting a line. An alternative is to run "configure" separately. This allows you to specify configuration options manually. The disadvantage is that you have to figure out what exactly to type. Some of the most interesting configure arguments follow. These can also be enabled from the Makefile. --prefix={directory} Top directory where to install Vim. --with-features=tiny Compile with many features disabled. --with-features=small Compile with some features disabled. --with-features=big Compile with more features enabled. --with-features=huge Compile with most features enabled. See |+feature-list| for which feature is enabled in which case. --enable-perlinterp Enable the Perl interface. There are similar arguments for ruby, python and tcl. --disable-gui Do not compile the GUI interface. --without-x Do not compile X-windows features. When both of these are used, Vim will not connect to the X server, which makes startup faster. To see the whole list use: > ./configure --help You can find a bit of explanation for each feature, and links for more information here: |feature-list|. For the adventurous, edit the file "feature.h". You can also change the source code yourself!
*90.2* MS-Windows There are two ways to install the Vim program for Microsoft Windows. You can uncompress several archives, or use a self-installing big archive. Most users with fairly recent computers will prefer the second method. For the first one, you will need: - An archive with binaries for Vim. - The Vim runtime archive. - A program to unpack the zip files. To get the Vim archives, look in this file for a mirror near you, this should provide the fastest download: ftp://ftp.vim.org/pub/vim/MIRRORS ~ Or use the home site ftp.vim.org, if you think it's fast enough. Go to the "pc" directory and you'll find a list of files there. The version number is embedded in the file name. You will want to get the most recent version. We will use "60" here, which is version 6.0. gvim60.exe The self-installing archive. This is all you need for the second method. Just launch the executable, and follow the prompts. For the first method you must chose one of the binary archives. These are available: gvim60.zip The normal MS-Windows GUI version. gvim60ole.zip The MS-Windows GUI version with OLE support. Uses more memory, supports interfacing with other OLE applications. vim60w32.zip 32 bit MS-Windows console version. For use in a Win NT/2000/XP console. Does not work well on Win 95/98. vim60d32.zip 32 bit MS-DOS version. For use in the Win 95/98 console window. vim60d16.zip 16 bit MS-DOS version. Only for old systems. Does not support long filenames. You only need one of them. Although you could install both a GUI and a console version. You always need to get the archive with runtime files. vim60rt.zip The runtime files. Use your un-zip program to unpack the files. For example, using the "unzip" program: > cd c:\ unzip path\gvim60.zip unzip path\vim60rt.zip This will unpack the files in the directory "c:\vim\vim60". If you already have a "vim" directory somewhere, you will want to move to the directory just above it. Now change to the "vim\vim60" directory and run the install program: > install Carefully look through the messages and select the options you want to use. If you finally select "do it" the install program will carry out the actions you selected. The install program doesn't move the runtime files. They remain where you unpacked them. In case you are not satisfied with the features included in the supplied binaries, you could try compiling Vim yourself. Get the source archive from the same location as where the binaries are. You need a compiler for which a makefile exists. Microsoft Visual C works, but is expensive. The Free Borland command-line compiler 5.5 can be used, as well as the free MingW and Cygwin compilers. Check the file src/INSTALLpc.txt for hints.
*90.3* Upgrading If you are running one version of Vim and want to install another, here is what to do. UNIX When you type "make install" the runtime files will be copied to a directory which is specific for this version. Thus they will not overwrite a previous version. This makes it possible to use two or more versions next to each other. The executable "vim" will overwrite an older version. If you don't care about keeping the old version, running "make install" will work fine. You can delete the old runtime files manually. Just delete the directory with the version number in it and all files below it. Example: > rm -rf /usr/local/share/vim/vim58 There are normally no changed files below this directory. If you did change the "filetype.vim" file, for example, you better merge the changes into the new version before deleting it. If you are careful and want to try out the new version for a while before switching to it, install the new version under another name. You need to specify a configure argument. For example: > ./configure --with-vim-name=vim6 Before running "make install", you could use "make -n install" to check that no valuable existing files are overwritten. When you finally decide to switch to the new version, all you need to do is to rename the binary to "vim". For example: > mv /usr/local/bin/vim6 /usr/local/bin/vim MS-WINDOWS Upgrading is mostly equal to installing a new version. Just unpack the files in the same place as the previous version. A new directory will be created, e.g., "vim61", for the files of the new version. Your runtime files, vimrc file, viminfo, etc. will be left alone. If you want to run the new version next to the old one, you will have to do some handwork. Don't run the install program, it will overwrite a few files of the old version. Execute the new binaries by specifying the full path. The program should be able to automatically find the runtime files for the right version. However, this won't work if you set the $VIMRUNTIME variable somewhere. If you are satisfied with the upgrade, you can delete the files of the previous version. See |90.5|.
*90.4* Common installation issues This section describes some of the common problems that occur when installing Vim and suggests some solutions. It also contains answers to many installation questions. Q: I Do Not Have Root Privileges. How Do I Install Vim? (Unix) Use the following configuration command to install Vim in a directory called $HOME/vim: > ./configure --prefix=$HOME This gives you a personal copy of Vim. You need to put $HOME/bin in your path to execute the editor. Also see |install-home|. Q: The Colors Are Not Right on My Screen. (Unix) Check your terminal settings by using the following command in a shell: > echo $TERM If the terminal type listed is not correct, fix it. For more hints, see |06.2|. Another solution is to always use the GUI version of Vim, called gvim. This avoids the need for a correct terminal setup. Q: My Backspace And Delete Keys Don't Work Right The definition of what key sends what code is very unclear for backspace <BS> and Delete <Del> keys. First of all, check your $TERM setting. If there is nothing wrong with it, try this: > :set t_kb=^V<BS> :set t_kD=^V<Del> In the first line you need to press CTRL-V and then hit the backspace key. In the second line you need to press CTRL-V and then hit the Delete key. You can put these lines in your vimrc file, see |05.1|. A disadvantage is that it won't work when you use another terminal some day. Look here for alternate solutions: |:fixdel|. Q: I Am Using RedHat Linux. Can I Use the Vim That Comes with the System? By default RedHat installs a minimal version of Vim. Check your RPM packages for something named "Vim-enhanced-version.rpm" and install that. Q: How Do I Turn Syntax Coloring On? How do I make plugins work? Use the example vimrc script. You can find an explanation on how to use it here: |not-compatible|. See chapter 6 for information about syntax highlighting: |usr_06.txt|. Q: What Is a Good vimrc File to Use? See the www.vim.org Web site for several good examples. Q: Where Do I Find a Good Vim Plugin? See the Vim-online site: http://vim.sf.net. Many users have uploaded useful Vim scripts and plugins there. Q: Where Do I Find More Tips? See the Vim-online site: http://vim.sf.net. There is an archive with hints from Vim users. You might also want to search in the |maillist-archive|.
*90.5* Uninstalling Vim In the unlikely event you want to uninstall Vim completely, this is how you do it. UNIX When you installed Vim as a package, check your package manager to find out how to remove the package again. If you installed Vim from sources you can use this command: > make uninstall However, if you have deleted the original files or you used an archive that someone supplied, you can't do this. Do delete the files manually, here is an example for when "/usr/local" was used as the root: > rm -rf /usr/local/share/vim/vim60 rm /usr/local/bin/eview rm /usr/local/bin/evim rm /usr/local/bin/ex rm /usr/local/bin/gview rm /usr/local/bin/gvim rm /usr/local/bin/gvim rm /usr/local/bin/gvimdiff rm /usr/local/bin/rgview rm /usr/local/bin/rgvim rm /usr/local/bin/rview rm /usr/local/bin/rvim rm /usr/local/bin/rvim rm /usr/local/bin/view rm /usr/local/bin/vim rm /usr/local/bin/vimdiff rm /usr/local/bin/vimtutor rm /usr/local/bin/xxd rm /usr/local/man/man1/eview.1 rm /usr/local/man/man1/evim.1 rm /usr/local/man/man1/ex.1 rm /usr/local/man/man1/gview.1 rm /usr/local/man/man1/gvim.1 rm /usr/local/man/man1/gvimdiff.1 rm /usr/local/man/man1/rgview.1 rm /usr/local/man/man1/rgvim.1 rm /usr/local/man/man1/rview.1 rm /usr/local/man/man1/rvim.1 rm /usr/local/man/man1/view.1 rm /usr/local/man/man1/vim.1 rm /usr/local/man/man1/vimdiff.1 rm /usr/local/man/man1/vimtutor.1 rm /usr/local/man/man1/xxd.1 MS-WINDOWS If you installed Vim with the self-installing archive you can run the "uninstall-gui" program located in the same directory as the other Vim programs, e.g. "c:\vim\vim60". You can also launch it from the Start menu if installed the Vim entries there. This will remove most of the files, menu entries and desktop shortcuts. Some files may remain however, as they need a Windows restart before being deleted. You will be given the option to remove the whole "vim" directory. It probably contains your vimrc file and other runtime files that you created, so be careful. Else, if you installed Vim with the zip archives, the preferred way is to use the "uninstal" program (note the missing l at the end). You can find it in the same directory as the "install" program, e.g., "c:\vim\vim60". This should also work from the usual "install/remove software" page. However, this only removes the registry entries for Vim. You have to delete the files yourself. Simply select the directory "vim\vim60" and delete it recursively. There should be no files there that you changed, but you might want to check that first. The "vim" directory probably contains your vimrc file and other runtime files that you created. You might want to keep that.
Copyright: see |manual-copyright|