*eval.txt* For Vim version 6.4. Last change: 2005 Oct 12 VIM REFERENCE MANUAL by Bram Moolenaar Expression evaluation *expression* *expr* *E15* *eval* Using expressions is introduced in chapter 41 of the user manual |usr_41.txt|. Note: Expression evaluation can be disabled at compile time. If this has been done, the features in this document are not available. See |+eval| and the last chapter below. 1. Variables |variables| 2. Expression syntax |expression-syntax| 3. Internal variable |internal-variables| 4. Builtin Functions |functions| 5. Defining functions |user-functions| 6. Curly braces names |curly-braces-names| 7. Commands |expression-commands| 8. Exception handling |exception-handling| 9. Examples |eval-examples| 10. No +eval feature |no-eval-feature| 11. The sandbox |eval-sandbox| {Vi does not have any of these commands} ============================================================================== 1. Variables *variables* There are two types of variables: Number a 32 bit signed number. String a NUL terminated string of 8-bit unsigned characters. These are converted automatically, depending on how they are used. Conversion from a Number to a String is by making the ASCII representation of the Number. Examples: > Number 123 --> String "123" Number 0 --> String "0" Number -1 --> String "-1" Conversion from a String to a Number is done by converting the first digits to a number. Hexadecimal "0xf9" and Octal "017" numbers are recognized. If the String doesn't start with digits, the result is zero. Examples: > String "456" --> Number 456 String "6bar" --> Number 6 String "foo" --> Number 0 String "0xf1" --> Number 241 String "0100" --> Number 64 String "-8" --> Number -8 String "+8" --> Number 0 To force conversion from String to Number, add zero to it: > :echo "0100" + 0 For boolean operators Numbers are used. Zero is FALSE, non-zero is TRUE. Note that in the command > :if "foo" "foo" is converted to 0, which means FALSE. To test for a non-empty string, use strlen(): > :if strlen("foo") If you need to know the type of a variable or expression, use the |type()| function. When the '!' flag is included in the 'viminfo' option, global variables that start with an uppercase letter, and don't contain a lowercase letter, are stored in the viminfo file |viminfo-file|. When the 'sessionoptions' option contains "global", global variables that start with an uppercase letter and contain at least one lowercase letter are stored in the session file |session-file|. variable name can be stored where ~ my_var_6 not My_Var_6 session file MY_VAR_6 viminfo file It's possible to form a variable name with curly braces, see |curly-braces-names|. ============================================================================== 2. Expression syntax *expression-syntax* Expression syntax summary, from least to most significant: |expr1| expr2 ? expr1 : expr1 if-then-else |expr2| expr3 || expr3 .. logical OR |expr3| expr4 && expr4 .. logical AND |expr4| expr5 == expr5 equal expr5 != expr5 not equal expr5 > expr5 greater than expr5 >= expr5 greater than or equal expr5 < expr5 smaller than expr5 <= expr5 smaller than or equal expr5 =~ expr5 regexp matches expr5 !~ expr5 regexp doesn't match expr5 ==? expr5 equal, ignoring case expr5 ==# expr5 equal, match case etc. As above, append ? for ignoring case, # for matching case |expr5| expr6 + expr6 .. number addition expr6 - expr6 .. number subtraction expr6 . expr6 .. string concatenation |expr6| expr7 * expr7 .. number multiplication expr7 / expr7 .. number division expr7 % expr7 .. number modulo |expr7| ! expr7 logical NOT - expr7 unary minus + expr7 unary plus expr8 |expr8| expr9[expr1] index in String |expr9| number number constant "string" string constant 'string' literal string constant &option option value (expr1) nested expression variable internal variable va{ria}ble internal variable with curly braces $VAR environment variable @r contents of register 'r' function(expr1, ...) function call func{ti}on(expr1, ...) function call with curly braces ".." indicates that the operations in this level can be concatenated. Example: > &nu || &list && &shell == "csh" All expressions within one level are parsed from left to right. expr1 *expr1* *E109* ----- expr2 ? expr1 : expr1 The expression before the '?' is evaluated to a number. If it evaluates to non-zero, the result is the value of the expression between the '?' and ':', otherwise the result is the value of the expression after the ':'. Example: > :echo lnum == 1 ? "top" : lnum Since the first expression is an "expr2", it cannot contain another ?:. The other two expressions can, thus allow for recursive use of ?:. Example: > :echo lnum == 1 ? "top" : lnum == 1000 ? "last" : lnum To keep this readable, using |line-continuation| is suggested: > :echo lnum == 1 :\ ? "top" :\ : lnum == 1000 :\ ? "last" :\ : lnum expr2 and expr3 *expr2* *expr3* --------------- *expr-barbar* *expr-&&* The "||" and "&&" operators take one argument on each side. The arguments are (converted to) Numbers. The result is: input output ~ n1 n2 n1 || n2 n1 && n2 ~ zero zero zero zero zero non-zero non-zero zero non-zero zero non-zero zero non-zero non-zero non-zero non-zero The operators can be concatenated, for example: > &nu || &list && &shell == "csh" Note that "&&" takes precedence over "||", so this has the meaning of: > &nu || (&list && &shell == "csh") Once the result is known, the expression "short-circuits", that is, further arguments are not evaluated. This is like what happens in C. For example: > let a = 1 echo a || b This is valid even if there is no variable called "b" because "a" is non-zero, so the result must be non-zero. Similarly below: > echo exists("b") && b == "yes" This is valid whether "b" has been defined or not. The second clause will only be evaluated if "b" has been defined. expr4 *expr4* ----- expr5 {cmp} expr5 Compare two expr5 expressions, resulting in a 0 if it evaluates to false, or 1 if it evaluates to true. *expr-==* *expr-!=* *expr->* *expr->=* *expr-<* *expr-<=* *expr-=~* *expr-!~* *expr-==#* *expr-!=#* *expr->#* *expr->=#* *expr-<#* *expr-<=#* *expr-=~#* *expr-!~#* *expr-==?* *expr-!=?* *expr->?* *expr->=?* *expr- ># >? greater than or equal >= >=# >=? smaller than < <# :let c = getline(line("."))[col(".") - 1] If the length of the String is less than the index, the result is an empty String. *expr9* number ------ number number constant *expr-number* Decimal, Hexadecimal (starting with 0x or 0X), or Octal (starting with 0). string *expr-string* *E114* ------ "string" string constant *expr-quote* Note that double quotes are used. A string constant accepts these special characters: \... three-digit octal number (e.g., "\316") \.. two-digit octal number (must be followed by non-digit) \. one-digit octal number (must be followed by non-digit) \x.. byte specified with two hex numbers (e.g., "\x1f") \x. byte specified with one hex number (must be followed by non-hex char) \X.. same as \x.. \X. same as \x. \u.... character specified with up to 4 hex numbers, stored according to the current value of 'encoding' (e.g., "\u02a4") \U.... same as \u.... \b backspace \e escape \f formfeed \n newline \r return \t tab \\ backslash \" double quote \ Special key named "xxx". e.g. "\" for CTRL-W. Note that "\000" and "\x00" force the end of the string. literal-string *literal-string* *E115* --------------- 'string' literal string constant *expr-'* Note that single quotes are used. This string is taken literally. No backslashes are removed or have a special meaning. A literal-string cannot contain a single quote. Use a normal string for that. option *expr-option* *E112* *E113* ------ &option option value, local value if possible &g:option global option value &l:option local option value Examples: > echo "tabstop is " . &tabstop if &insertmode Any option name can be used here. See |options|. When using the local value and there is no buffer-local or window-local value, the global value is used anyway. register *expr-register* -------- @r contents of register 'r' The result is the contents of the named register, as a single string. Newlines are inserted where required. To get the contents of the unnamed register use @" or @@. The '=' register can not be used here. See |registers| for an explanation of the available registers. nesting *expr-nesting* *E110* ------- (expr1) nested expression environment variable *expr-env* -------------------- $VAR environment variable The String value of any environment variable. When it is not defined, the result is an empty string. *expr-env-expand* Note that there is a difference between using $VAR directly and using expand("$VAR"). Using it directly will only expand environment variables that are known inside the current Vim session. Using expand() will first try using the environment variables known inside the current Vim session. If that fails, a shell will be used to expand the variable. This can be slow, but it does expand all variables that the shell knows about. Example: > :echo $version :echo expand("$version") The first one probably doesn't echo anything, the second echoes the $version variable (if your shell supports it). internal variable *expr-variable* ----------------- variable internal variable See below |internal-variables|. function call *expr-function* *E116* *E117* *E118* *E119* *E120* ------------- function(expr1, ...) function call See below |functions|. ============================================================================== 3. Internal variable *internal-variables* *E121* *E461* An internal variable name can be made up of letters, digits and '_'. But it cannot start with a digit. It's also possible to use curly braces, see |curly-braces-names|. An internal variable is created with the ":let" command |:let|. An internal variable is destroyed with the ":unlet" command |:unlet|. Using a name that isn't an internal variable, or an internal variable that has been destroyed, results in an error. There are several name spaces for variables. Which one is to be used is specified by what is prepended: (nothing) In a function: local to a function; otherwise: global |buffer-variable| b: Local to the current buffer. |window-variable| w: Local to the current window. |global-variable| g: Global. |local-variable| l: Local to a function. |script-variable| s: Local to a |:source|'ed Vim script. |function-argument| a: Function argument (only inside a function). |vim-variable| v: Global, predefined by Vim. *buffer-variable* *b:var* A variable name that is preceded with "b:" is local to the current buffer. Thus you can have several "b:foo" variables, one for each buffer. This kind of variable is deleted when the buffer is wiped out or deleted with |:bdelete|. One local buffer variable is predefined: *b:changedtick-variable* *changetick* b:changedtick The total number of changes to the current buffer. It is incremented for each change. An undo command is also a change in this case. This can be used to perform an action only when the buffer has changed. Example: > :if my_changedtick != b:changedtick : let my_changedtick = b:changedtick : call My_Update() :endif < *window-variable* *w:var* A variable name that is preceded with "w:" is local to the current window. It is deleted when the window is closed. *global-variable* *g:var* Inside functions global variables are accessed with "g:". Omitting this will access a variable local to a function. But "g:" can also be used in any other place if you like. *local-variable* *l:var* Inside functions local variables are accessed without prepending anything. But you can also prepend "l:" if you like. *script-variable* *s:var* In a Vim script variables starting with "s:" can be used. They cannot be accessed from outside of the scripts, thus are local to the script. They can be used in: - commands executed while the script is sourced - functions defined in the script - autocommands defined in the script - functions and autocommands defined in functions and autocommands which were defined in the script (recursively) - user defined commands defined in the script Thus not in: - other scripts sourced from this one - mappings - etc. script variables can be used to avoid conflicts with global variable names. Take this example: let s:counter = 0 function MyCounter() let s:counter = s:counter + 1 echo s:counter endfunction command Tick call MyCounter() You can now invoke "Tick" from any script, and the "s:counter" variable in that script will not be changed, only the "s:counter" in the script where "Tick" was defined is used. Another example that does the same: > let s:counter = 0 command Tick let s:counter = s:counter + 1 | echo s:counter When calling a function and invoking a user-defined command, the context for script variables is set to the script where the function or command was defined. The script variables are also available when a function is defined inside a function that is defined in a script. Example: > let s:counter = 0 function StartCounting(incr) if a:incr function MyCounter() let s:counter = s:counter + 1 endfunction else function MyCounter() let s:counter = s:counter - 1 endfunction endif endfunction This defines the MyCounter() function either for counting up or counting down when calling StartCounting(). It doesn't matter from where StartCounting() is called, the s:counter variable will be accessible in MyCounter(). When the same script is sourced again it will use the same script variables. They will remain valid as long as Vim is running. This can be used to maintain a counter: > if !exists("s:counter") let s:counter = 1 echo "script executed for the first time" else let s:counter = s:counter + 1 echo "script executed " . s:counter . " times now" endif Note that this means that filetype plugins don't get a different set of script variables for each buffer. Use local buffer variables instead |b:var|. Predefined Vim variables: *vim-variable* *v:var* *v:charconvert_from* *charconvert_from-variable* v:charconvert_from The name of the character encoding of a file to be converted. Only valid while evaluating the 'charconvert' option. *v:charconvert_to* *charconvert_to-variable* v:charconvert_to The name of the character encoding of a file after conversion. Only valid while evaluating the 'charconvert' option. *v:cmdarg* *cmdarg-variable* v:cmdarg This variable is used for two purposes: 1. The extra arguments given to a file read/write command. Currently these are "++enc=" and "++ff=". This variable is set before an autocommand event for a file read/write command is triggered. There is a leading space to make it possible to append this variable directly after the read/write command. Note: The "+cmd" argument isn't included here, because it will be executed anyway. 2. When printing a PostScript file with ":hardcopy" this is the argument for the ":hardcopy" command. This can be used in 'printexpr'. *v:cmdbang* *cmdbang-variable* v:cmdbang Set like v:cmdarg for a file read/write command. When a "!" was used the value is 1, otherwise it is 0. Note that this can only be used in autocommands. For user commands || can be used. *v:count* *count-variable* v:count The count given for the last Normal mode command. Can be used to get the count before a mapping. Read-only. Example: > :map _x :echo "the count is " . v:count < Note: The is required to remove the line range that you get when typing ':' after a count. "count" also works, for backwards compatibility. *v:count1* *count1-variable* v:count1 Just like "v:count", but defaults to one when no count is used. *v:ctype* *ctype-variable* v:ctype The current locale setting for characters of the runtime environment. This allows Vim scripts to be aware of the current locale encoding. Technical: it's the value of LC_CTYPE. When not using a locale the value is "C". This variable can not be set directly, use the |:language| command. See |multi-lang|. *v:dying* *dying-variable* v:dying Normally zero. When a deadly signal is caught it's set to one. When multiple signals are caught the number increases. Can be used in an autocommand to check if Vim didn't terminate normally. {only works on Unix} Example: > :au VimLeave * if v:dying | echo "\nAAAAaaaarrrggghhhh!!!\n" | endif < *v:errmsg* *errmsg-variable* v:errmsg Last given error message. It's allowed to set this variable. Example: > :let v:errmsg = "" :silent! next :if v:errmsg != "" : ... handle error < "errmsg" also works, for backwards compatibility. *v:exception* *exception-variable* v:exception The value of the exception most recently caught and not finished. See also |v:throwpoint| and |throw-variables|. Example: > :try : throw "oops" :catch /.*/ : echo "caught" v:exception :endtry < Output: "caught oops". *v:fname_in* *fname_in-variable* v:fname_in The name of the input file. Only valid while evaluating: option used for ~ 'charconvert' file to be converted 'diffexpr' original file 'patchexpr' original file 'printexpr' file to be printed *v:fname_out* *fname_out-variable* v:fname_out The name of the output file. Only valid while evaluating: option used for ~ 'charconvert' resulting converted file (*) 'diffexpr' output of diff 'patchexpr' resulting patched file (*) When doing conversion for a write command (e.g., ":w file") it will be equal to v:fname_in. When doing conversion for a read command (e.g., ":e file") it will be a temporary file and different from v:fname_in. *v:fname_new* *fname_new-variable* v:fname_new The name of the new version of the file. Only valid while evaluating 'diffexpr'. *v:fname_diff* *fname_diff-variable* v:fname_diff The name of the diff (patch) file. Only valid while evaluating 'patchexpr'. *v:folddashes* *folddashes-variable* v:folddashes Used for 'foldtext': dashes representing foldlevel of a closed fold. Read-only. |fold-foldtext| *v:foldlevel* *foldlevel-variable* v:foldlevel Used for 'foldtext': foldlevel of closed fold. Read-only. |fold-foldtext| *v:foldend* *foldend-variable* v:foldend Used for 'foldtext': last line of closed fold. Read-only. |fold-foldtext| *v:foldstart* *foldstart-variable* v:foldstart Used for 'foldtext': first line of closed fold. Read-only. |fold-foldtext| *v:lang* *lang-variable* v:lang The current locale setting for messages of the runtime environment. This allows Vim scripts to be aware of the current language. Technical: it's the value of LC_MESSAGES. The value is system dependent. This variable can not be set directly, use the |:language| command. It can be different from |v:ctype| when messages are desired in a different language than what is used for character encoding. See |multi-lang|. *v:lc_time* *lc_time-variable* v:lc_time The current locale setting for time messages of the runtime environment. This allows Vim scripts to be aware of the current language. Technical: it's the value of LC_TIME. This variable can not be set directly, use the |:language| command. See |multi-lang|. *v:lnum* *lnum-variable* v:lnum Line number for the 'foldexpr' and 'indentexpr' expressions. Only valid while one of these expressions is being evaluated. Read-only. |fold-expr| 'indentexpr' *v:prevcount* *prevcount-variable* v:prevcount The count given for the last but one Normal mode command. This is the v:count value of the previous command. Useful if you want to cancel Visual mode and then use the count. > :vmap % :call MyFilter(v:prevcount) < Read-only. *v:progname* *progname-variable* v:progname Contains the name (with path removed) with which Vim was invoked. Allows you to do special initialisations for "view", "evim" etc., or any other name you might symlink to Vim. Read-only. *v:register* *register-variable* v:register The name of the register supplied to the last normal mode command. Empty if none were supplied. |getreg()| |setreg()| *v:servername* *servername-variable* v:servername The resulting registered |x11-clientserver| name if any. Read-only. *v:shell_error* *shell_error-variable* v:shell_error Result of the last shell command. When non-zero, the last shell command had an error. When zero, there was no problem. This only works when the shell returns the error code to Vim. The value -1 is often used when the command could not be executed. Read-only. Example: > :!mv foo bar :if v:shell_error : echo 'could not rename "foo" to "bar"!' :endif < "shell_error" also works, for backwards compatibility. *v:statusmsg* *statusmsg-variable* v:statusmsg Last given status message. It's allowed to set this variable. *v:termresponse* *termresponse-variable* v:termresponse The escape sequence returned by the terminal for the |t_RV| termcap entry. It is set when Vim receives an escape sequence that starts with ESC [ or CSI and ends in a 'c', with only digits, ';' and '.' in between. When this option is set, the TermResponse autocommand event is fired, so that you can react to the response from the terminal. The response from a new xterm is: "[ Pp ; Pv ; Pc c". Pp is the terminal type: 0 for vt100 and 1 for vt220. Pv is the patch level (since this was introduced in patch 95, it's always 95 or bigger). Pc is always zero. {only when compiled with |+termresponse| feature} *v:this_session* *this_session-variable* v:this_session Full filename of the last loaded or saved session file. See |:mksession|. It is allowed to set this variable. When no session file has been saved, this variable is empty. "this_session" also works, for backwards compatibility. *v:throwpoint* *throwpoint-variable* v:throwpoint The point where the exception most recently caught and not finished was thrown. Not set when commands are typed. See also |v:exception| and |throw-variables|. Example: > :try : throw "oops" :catch /.*/ : echo "Exception from" v:throwpoint :endtry < Output: "Exception from test.vim, line 2" *v:version* *version-variable* v:version Version number of Vim: Major version number times 100 plus minor version number. Version 5.0 is 500. Version 5.1 (5.01) is 501. Read-only. "version" also works, for backwards compatibility. Use |has()| to check if a certain patch was included, e.g.: > if has("patch123") < Note that patch numbers are specific to the version, thus both version 5.0 and 5.1 may have a patch 123, but these are completely different. *v:warningmsg* *warningmsg-variable* v:warningmsg Last given warning message. It's allowed to set this variable. ============================================================================== 4. Builtin Functions *functions* See |function-list| for a list grouped by what the function is used for. (Use CTRL-] on the function name to jump to the full explanation) USAGE RESULT DESCRIPTION ~ append( {lnum}, {string}) Number append {string} below line {lnum} argc() Number number of files in the argument list argidx() Number current index in the argument list argv( {nr}) String {nr} entry of the argument list browse( {save}, {title}, {initdir}, {default}) String put up a file requester bufexists( {expr}) Number TRUE if buffer {expr} exists buflisted( {expr}) Number TRUE if buffer {expr} is listed bufloaded( {expr}) Number TRUE if buffer {expr} is loaded bufname( {expr}) String Name of the buffer {expr} bufnr( {expr}) Number Number of the buffer {expr} bufwinnr( {expr}) Number window number of buffer {expr} byte2line( {byte}) Number line number at byte count {byte} char2nr( {expr}) Number ASCII value of first char in {expr} cindent( {lnum}) Number C indent for line {lnum} col( {expr}) Number column nr of cursor or mark confirm( {msg} [, {choices} [, {default} [, {type}]]]) Number number of choice picked by user cscope_connection( [{num} , {dbpath} [, {prepend}]]) Number checks existence of cscope connection cursor( {lnum}, {col}) Number position cursor at {lnum}, {col} delete( {fname}) Number delete file {fname} did_filetype() Number TRUE if FileType autocommand event used escape( {string}, {chars}) String escape {chars} in {string} with '\' eventhandler( ) Number TRUE if inside an event handler executable( {expr}) Number 1 if executable {expr} exists exists( {expr}) Number TRUE if {expr} exists expand( {expr}) String expand special keywords in {expr} filereadable( {file}) Number TRUE if {file} is a readable file filewritable( {file}) Number TRUE if {file} is a writable file fnamemodify( {fname}, {mods}) String modify file name foldclosed( {lnum}) Number first line of fold at {lnum} if closed foldclosedend( {lnum}) Number last line of fold at {lnum} if closed foldlevel( {lnum}) Number fold level at {lnum} foldtext( ) String line displayed for closed fold foreground( ) Number bring the Vim window to the foreground getchar( [expr]) Number get one character from the user getcharmod( ) Number modifiers for the last typed character getbufvar( {expr}, {varname}) variable {varname} in buffer {expr} getcmdline() String return the current command-line getcmdpos() Number return cursor position in command-line getcwd() String the current working directory getfsize( {fname}) Number size in bytes of file getftime( {fname}) Number last modification time of file getline( {lnum}) String line {lnum} from current buffer getreg( [{regname}]) String contents of register getregtype( [{regname}]) String type of register getwinposx() Number X coord in pixels of GUI Vim window getwinposy() Number Y coord in pixels of GUI Vim window getwinvar( {nr}, {varname}) variable {varname} in window {nr} glob( {expr}) String expand file wildcards in {expr} globpath( {path}, {expr}) String do glob({expr}) for all dirs in {path} has( {feature}) Number TRUE if feature {feature} supported hasmapto( {what} [, {mode}]) Number TRUE if mapping to {what} exists histadd( {history},{item}) String add an item to a history histdel( {history} [, {item}]) String remove an item from a history histget( {history} [, {index}]) String get the item {index} from a history histnr( {history}) Number highest index of a history hlexists( {name}) Number TRUE if highlight group {name} exists hlID( {name}) Number syntax ID of highlight group {name} hostname() String name of the machine Vim is running on iconv( {expr}, {from}, {to}) String convert encoding of {expr} indent( {lnum}) Number indent of line {lnum} input( {prompt} [, {text}]) String get input from the user inputdialog( {p} [, {t} [, {c}]]) String like input() but in a GUI dialog inputrestore() Number restore typeahead inputsave() Number save and clear typeahead inputsecret( {prompt} [, {text}]) String like input() but hiding the text isdirectory( {directory}) Number TRUE if {directory} is a directory libcall( {lib}, {func}, {arg}) String call {func} in library {lib} with {arg} libcallnr( {lib}, {func}, {arg}) Number idem, but return a Number line( {expr}) Number line nr of cursor, last line or mark line2byte( {lnum}) Number byte count of line {lnum} lispindent( {lnum}) Number Lisp indent for line {lnum} localtime() Number current time maparg( {name}[, {mode}]) String rhs of mapping {name} in mode {mode} mapcheck( {name}[, {mode}]) String check for mappings matching {name} match( {expr}, {pat}[, {start}]) Number position where {pat} matches in {expr} matchend( {expr}, {pat}[, {start}]) Number position where {pat} ends in {expr} matchstr( {expr}, {pat}[, {start}]) String match of {pat} in {expr} mode() String current editing mode nextnonblank( {lnum}) Number line nr of non-blank line >= {lnum} nr2char( {expr}) String single char with ASCII value {expr} prevnonblank( {lnum}) Number line nr of non-blank line <= {lnum} remote_expr( {server}, {string} [, {idvar}]) String send expression remote_foreground( {server}) Number bring Vim server to the foreground remote_peek( {serverid} [, {retvar}]) Number check for reply string remote_read( {serverid}) String read reply string remote_send( {server}, {string} [, {idvar}]) String send key sequence rename( {from}, {to}) Number rename (move) file from {from} to {to} resolve( {filename}) String get filename a shortcut points to search( {pattern} [, {flags}]) Number search for {pattern} searchpair( {start}, {middle}, {end} [, {flags} [, {skip}]]) Number search for other end of start/end pair server2client( {clientid}, {string}) Number send reply string serverlist() String get a list of available servers setbufvar( {expr}, {varname}, {val}) set {varname} in buffer {expr} to {val} setcmdpos( {pos}) Number set cursor position in command-line setline( {lnum}, {line}) Number set line {lnum} to {line} setreg( {n}, {v}[, {opt}]) Number set register to value and type setwinvar( {nr}, {varname}, {val}) set {varname} in window {nr} to {val} simplify( {filename}) String simplify filename as much as possible strftime( {format}[, {time}]) String time in specified format stridx( {haystack}, {needle}) Number first index of {needle} in {haystack} strlen( {expr}) Number length of the String {expr} strpart( {src}, {start}[, {len}]) String {len} characters of {src} at {start} strridx( {haystack}, {needle}) Number last index of {needle} in {haystack} strtrans( {expr}) String translate string to make it printable submatch( {nr}) String specific match in ":substitute" substitute( {expr}, {pat}, {sub}, {flags}) String all {pat} in {expr} replaced with {sub} synID( {line}, {col}, {trans}) Number syntax ID at {line} and {col} synIDattr( {synID}, {what} [, {mode}]) String attribute {what} of syntax ID {synID} synIDtrans( {synID}) Number translated syntax ID of {synID} system( {expr}) String output of shell command {expr} tempname() String name for a temporary file tolower( {expr}) String the String {expr} switched to lowercase toupper( {expr}) String the String {expr} switched to uppercase type( {name}) Number type of variable {name} virtcol( {expr}) Number screen column of cursor or mark visualmode( [expr]) String last visual mode used winbufnr( {nr}) Number buffer number of window {nr} wincol() Number window column of the cursor winheight( {nr}) Number height of window {nr} winline() Number window line of the cursor winnr() Number number of current window winrestcmd() String returns command to restore window sizes winwidth( {nr}) Number width of window {nr} append({lnum}, {string}) *append()* Append the text {string} after line {lnum} in the current buffer. {lnum} can be zero, to insert a line before the first one. Returns 1 for failure ({lnum} out of range) or 0 for success. *argc()* argc() The result is the number of files in the argument list of the current window. See |arglist|. *argidx()* argidx() The result is the current index in the argument list. 0 is the first file. argc() - 1 is the last one. See |arglist|. *argv()* argv({nr}) The result is the {nr}th file in the argument list of the current window. See |arglist|. "argv(0)" is the first one. Example: > :let i = 0 :while i < argc() : let f = escape(argv(i), '. ') : exe 'amenu Arg.' . f . ' :e ' . f . '' : let i = i + 1 :endwhile < *browse()* browse({save}, {title}, {initdir}, {default}) Put up a file requester. This only works when "has("browse")" returns non-zero (only in some GUI versions). The input fields are: {save} when non-zero, select file to write {title} title for the requester {initdir} directory to start browsing in {default} default file name When the "Cancel" button is hit, something went wrong, or browsing is not possible, an empty string is returned. bufexists({expr}) *bufexists()* The result is a Number, which is non-zero if a buffer called {expr} exists. If the {expr} argument is a string it must match a buffer name exactly. If the {expr} argument is a number buffer numbers are used. Unlisted buffers will be found. Note that help files are listed by their short name in the output of |:buffers|, but bufexists() requires using their long name to be able to find them. Use "bufexists(0)" to test for the existence of an alternate file name. *buffer_exists()* Obsolete name: buffer_exists(). buflisted({expr}) *buflisted()* The result is a Number, which is non-zero if a buffer called {expr} exists and is listed (has the 'buflisted' option set). The {expr} argument is used like with bufexists(). bufloaded({expr}) *bufloaded()* The result is a Number, which is non-zero if a buffer called {expr} exists and is loaded (shown in a window or hidden). The {expr} argument is used like with bufexists(). bufname({expr}) *bufname()* The result is the name of a buffer, as it is displayed by the ":ls" command. If {expr} is a Number, that buffer number's name is given. Number zero is the alternate buffer for the current window. If {expr} is a String, it is used as a |file-pattern| to match with the buffer names. This is always done like 'magic' is set and 'cpoptions' is empty. When there is more than one match an empty string is returned. "" or "%" can be used for the current buffer, "#" for the alternate buffer. A full match is preferred, otherwise a match at the start, end or middle of the buffer name is accepted. Listed buffers are found first. If there is a single match with a listed buffer, that one is returned. Next unlisted buffers are searched for. If the {expr} is a String, but you want to use it as a buffer number, force it to be a Number by adding zero to it: > :echo bufname("3" + 0) < If the buffer doesn't exist, or doesn't have a name, an empty string is returned. > bufname("#") alternate buffer name bufname(3) name of buffer 3 bufname("%") name of current buffer bufname("file2") name of buffer where "file2" matches. < *buffer_name()* Obsolete name: buffer_name(). *bufnr()* bufnr({expr}) The result is the number of a buffer, as it is displayed by the ":ls" command. For the use of {expr}, see |bufname()| above. If the buffer doesn't exist, -1 is returned. bufnr("$") is the last buffer: > :let last_buffer = bufnr("$") < The result is a Number, which is the highest buffer number of existing buffers. Note that not all buffers with a smaller number necessarily exist, because ":bwipeout" may have removed them. Use bufexists() to test for the existence of a buffer. *buffer_number()* Obsolete name: buffer_number(). *last_buffer_nr()* Obsolete name for bufnr("$"): last_buffer_nr(). bufwinnr({expr}) *bufwinnr()* The result is a Number, which is the number of the first window associated with buffer {expr}. For the use of {expr}, see |bufname()| above. If buffer {expr} doesn't exist or there is no such window, -1 is returned. Example: > echo "A window containing buffer 1 is " . (bufwinnr(1)) < The number can be used with |CTRL-W_w| and ":wincmd w" |:wincmd|. byte2line({byte}) *byte2line()* Return the line number that contains the character at byte count {byte} in the current buffer. This includes the end-of-line character, depending on the 'fileformat' option for the current buffer. The first character has byte count one. Also see |line2byte()|, |go| and |:goto|. {not available when compiled without the |+byte_offset| feature} char2nr({expr}) *char2nr()* Return number value of the first char in {expr}. Examples: > char2nr(" ") returns 32 char2nr("ABC") returns 65 < The current 'encoding' is used. Example for "utf-8": > char2nr("á") returns 225 char2nr("á"[0]) returns 195 cindent({lnum}) *cindent()* Get the amount of indent for line {lnum} according the C indenting rules, as with 'cindent'. The indent is counted in spaces, the value of 'tabstop' is relevant. {lnum} is used just like in |getline()|. When {lnum} is invalid or Vim was not compiled the |+cindent| feature, -1 is returned. *col()* col({expr}) The result is a Number, which is the byte index of the column position given with {expr}. The accepted positions are: . the cursor position $ the end of the cursor line (the result is the number of characters in the cursor line plus one) 'x position of mark x (if the mark is not set, 0 is returned) For the screen column position use |virtcol()|. Note that only marks in the current file can be used. Examples: > col(".") column of cursor col("$") length of cursor line plus one col("'t") column of mark t col("'" . markname) column of mark markname < The first column is 1. 0 is returned for an error. For the cursor position, when 'virtualedit' is active, the column is one higher if the cursor is after the end of the line. This can be used to obtain the column in Insert mode: > :imap :let save_ve = &ve \:set ve=all \:echo col(".") . "\n" \let &ve = save_ve < *confirm()* confirm({msg} [, {choices} [, {default} [, {type}]]]) Confirm() offers the user a dialog, from which a choice can be made. It returns the number of the choice. For the first choice this is 1. Note: confirm() is only supported when compiled with dialog support, see |+dialog_con| and |+dialog_gui|. {msg} is displayed in a |dialog| with {choices} as the alternatives. When {choices} is missing or empty, "&OK" is used (and translated). {msg} is a String, use '\n' to include a newline. Only on some systems the string is wrapped when it doesn't fit. {choices} is a String, with the individual choices separated by '\n', e.g. > confirm("Save changes?", "&Yes\n&No\n&Cancel") < The letter after the '&' is the shortcut key for that choice. Thus you can type 'c' to select "Cancel". The shortcut does not need to be the first letter: > confirm("file has been modified", "&Save\nSave &All") < For the console, the first letter of each choice is used as the default shortcut key. The optional {default} argument is the number of the choice that is made if the user hits . Use 1 to make the first choice the default one. Use 0 to not set a default. If {default} is omitted, 1 is used. The optional {type} argument gives the type of dialog. This is only used for the icon of the Win32 GUI. It can be one of these values: "Error", "Question", "Info", "Warning" or "Generic". Only the first character is relevant. When {type} is omitted, "Generic" is used. If the user aborts the dialog by pressing , CTRL-C, or another valid interrupt key, confirm() returns 0. An example: > :let choice = confirm("What do you want?", "&Apples\n&Oranges\n&Bananas", 2) :if choice == 0 : echo "make up your mind!" :elseif choice == 3 : echo "tasteful" :else : echo "I prefer bananas myself." :endif < In a GUI dialog, buttons are used. The layout of the buttons depends on the 'v' flag in 'guioptions'. If it is included, the buttons are always put vertically. Otherwise, confirm() tries to put the buttons in one horizontal line. If they don't fit, a vertical layout is used anyway. For some systems the horizontal layout is always used. *cscope_connection()* cscope_connection([{num} , {dbpath} [, {prepend}]]) Checks for the existence of a |cscope| connection. If no parameters are specified, then the function returns: 0, if cscope was not available (not compiled in), or if there are no cscope connections; 1, if there is at least one cscope connection. If parameters are specified, then the value of {num} determines how existence of a cscope connection is checked: {num} Description of existence check ----- ------------------------------ 0 Same as no parameters (e.g., "cscope_connection()"). 1 Ignore {prepend}, and use partial string matches for {dbpath}. 2 Ignore {prepend}, and use exact string matches for {dbpath}. 3 Use {prepend}, use partial string matches for both {dbpath} and {prepend}. 4 Use {prepend}, use exact string matches for both {dbpath} and {prepend}. Note: All string comparisons are case sensitive! Examples. Suppose we had the following (from ":cs show"): > # pid database name prepend path 0 27664 cscope.out /usr/local < Invocation Return Val ~ ---------- ---------- > cscope_connection() 1 cscope_connection(1, "out") 1 cscope_connection(2, "out") 0 cscope_connection(3, "out") 0 cscope_connection(3, "out", "local") 1 cscope_connection(4, "out") 0 cscope_connection(4, "out", "local") 0 cscope_connection(4, "cscope.out", "/usr/local") 1 < cursor({lnum}, {col}) *cursor()* Positions the cursor at the column {col} in the line {lnum}. Does not change the jumplist. If {lnum} is greater than the number of lines in the buffer, the cursor will be positioned at the last line in the buffer. If {lnum} is zero, the cursor will stay in the current line. If {col} is greater than the number of characters in the line, the cursor will be positioned at the last character in the line. If {col} is zero, the cursor will stay in the current column. *delete()* delete({fname}) Deletes the file by the name {fname}. The result is a Number, which is 0 if the file was deleted successfully, and non-zero when the deletion failed. *did_filetype()* did_filetype() Returns non-zero when autocommands are being executed and the FileType event has been triggered at least once. Can be used to avoid triggering the FileType event again in the scripts that detect the file type. |FileType| When editing another file, the counter is reset, thus this really checks if the FileType event has been triggered for the current buffer. This allows an autocommand that starts editing another buffer to set 'filetype' and load a syntax file. escape({string}, {chars}) *escape()* Escape the characters in {chars} that occur in {string} with a backslash. Example: > :echo escape('c:\program files\vim', ' \') < results in: > c:\\program\ files\\vim < eventhandler() *eventhandler()* Returns 1 when inside an event handler. That is that Vim got interrupted while waiting for the user to type a character, e.g., when dropping a file on Vim. This means interactive commands cannot be used. Otherwise zero is returned. executable({expr}) *executable()* This function checks if an executable with the name {expr} exists. {expr} must be the name of the program without any arguments. executable() uses the normal $PATH. The result is a Number: 1 exists 0 does not exist -1 not implemented on this system *exists()* exists({expr}) The result is a Number, which is non-zero if {expr} is defined, zero otherwise. The {expr} argument is a string, which contains one of these: &option-name Vim option (only checks if it exists, not if it really works) +option-name Vim option that works. $ENVNAME environment variable (could also be done by comparing with an empty string) *funcname built-in function (see |functions|) or user defined function (see |user-functions|). varname internal variable (see |internal-variables|). Does not work for |curly-braces-names|. :cmdname Ex command: built-in command, user command or command modifier |:command|. Returns: 1 for match with start of a command 2 full match with a command 3 matches several user commands To check for a supported command always check the return value to be 2. #event autocommand defined for this event #event#pattern autocommand defined for this event and pattern (the pattern is taken literally and compared to the autocommand patterns character by character) For checking for a supported feature use |has()|. Examples: > exists("&shortname") exists("$HOSTNAME") exists("*strftime") exists("*s:MyFunc") exists("bufcount") exists(":Make") exists("#CursorHold"); exists("#BufReadPre#*.gz") < There must be no space between the symbol (&/$/*/#) and the name. Note that the argument must be a string, not the name of the variable itself! For example: > exists(bufcount) < This doesn't check for existence of the "bufcount" variable, but gets the contents of "bufcount", and checks if that exists. expand({expr} [, {flag}]) *expand()* Expand wildcards and the following special keywords in {expr}. The result is a String. When there are several matches, they are separated by characters. [Note: in version 5.0 a space was used, which caused problems when a file name contains a space] If the expansion fails, the result is an empty string. A name for a non-existing file is not included. When {expr} starts with '%', '#' or '<', the expansion is done like for the |cmdline-special| variables with their associated modifiers. Here is a short overview: % current file name # alternate file name #n alternate file name n file name under the cursor autocmd file name autocmd buffer number (as a String!) autocmd matched name sourced script file name word under the cursor WORD under the cursor the {clientid} of the last received message |server2client()| Modifiers: :p expand to full path :h head (last path component removed) :t tail (last path component only) :r root (one extension removed) :e extension only Example: > :let &tags = expand("%:p:h") . "/tags" < Note that when expanding a string that starts with '%', '#' or '<', any following text is ignored. This does NOT work: > :let doesntwork = expand("%:h.bak") < Use this: > :let doeswork = expand("%:h") . ".bak" < Also note that expanding "" and others only returns the referenced file name without further expansion. If "" is "~/.cshrc", you need to do another expand() to have the "~/" expanded into the path of the home directory: > :echo expand(expand("")) < There cannot be white space between the variables and the following modifier. The |fnamemodify()| function can be used to modify normal file names. When using '%' or '#', and the current or alternate file name is not defined, an empty string is used. Using "%:p" in a buffer with no name, results in the current directory, with a '/' added. When {expr} does not start with '%', '#' or '<', it is expanded like a file name is expanded on the command line. 'suffixes' and 'wildignore' are used, unless the optional {flag} argument is given and it is non-zero. Names for non-existing files are included. Expand() can also be used to expand variables and environment variables that are only known in a shell. But this can be slow, because a shell must be started. See |expr-env-expand|. The expanded variable is still handled like a list of file names. When an environment variable cannot be expanded, it is left unchanged. Thus ":echo expand('$FOOBAR')" results in "$FOOBAR". See |glob()| for finding existing files. See |system()| for getting the raw output of an external command. filereadable({file}) *filereadable()* The result is a Number, which is TRUE when a file with the name {file} exists, and can be read. If {file} doesn't exist, or is a directory, the result is FALSE. {file} is any expression, which is used as a String. *file_readable()* Obsolete name: file_readable(). filewritable({file}) *filewritable()* The result is a Number, which is 1 when a file with the name {file} exists, and can be written. If {file} doesn't exist, or is not writable, the result is 0. If (file) is a directory, and we can write to it, the result is 2. fnamemodify({fname}, {mods}) *fnamemodify()* Modify file name {fname} according to {mods}. {mods} is a string of characters like it is used for file names on the command line. See |filename-modifiers|. Example: > :echo fnamemodify("main.c", ":p:h") < results in: > /home/mool/vim/vim/src < Note: Environment variables and "~" don't work in {fname}, use |expand()| first then. foldclosed({lnum}) *foldclosed()* The result is a Number. If the line {lnum} is in a closed fold, the result is the number of the first line in that fold. If the line {lnum} is not in a closed fold, -1 is returned. foldclosedend({lnum}) *foldclosedend()* The result is a Number. If the line {lnum} is in a closed fold, the result is the number of the last line in that fold. If the line {lnum} is not in a closed fold, -1 is returned. foldlevel({lnum}) *foldlevel()* The result is a Number, which is the foldlevel of line {lnum} in the current buffer. For nested folds the deepest level is returned. If there is no fold at line {lnum}, zero is returned. It doesn't matter if the folds are open or closed. When used while updating folds (from 'foldexpr') -1 is returned for lines where folds are still to be updated and the foldlevel is unknown. As a special case the level of the previous line is usually available. *foldtext()* foldtext() Returns a String, to be displayed for a closed fold. This is the default function used for the 'foldtext' option and should only be called from evaluating 'foldtext'. It uses the |v:foldstart|, |v:foldend| and |v:folddashes| variables. The returned string looks like this: > +-- 45 lines: abcdef < The number of dashes depends on the foldlevel. The "45" is the number of lines in the fold. "abcdef" is the text in the first non-blank line of the fold. Leading white space, "//" or "/*" and the text from the 'foldmarker' and 'commentstring' options is removed. {not available when compiled without the |+folding| feature} *foreground()* foreground() Move the Vim window to the foreground. Useful when sent from a client to a Vim server. |remote_send()| On Win32 systems this might not work, the OS does not always allow a window to bring itself to the foreground. Use |remote_foreground()| instead. {only in the Win32, Athena, Motif and GTK GUI versions and the Win32 console version} getchar([expr]) *getchar()* Get a single character from the user. If it is an 8-bit character, the result is a number. Otherwise a String is returned with the encoded character. For a special key it's a sequence of bytes starting with 0x80 (decimal: 128). If [expr] is omitted, wait until a character is available. If [expr] is 0, only get a character when one is available. If [expr] is 1, only check if a character is available, it is not consumed. If a normal character is available, it is returned, otherwise a non-zero value is returned. If a normal character available, it is returned as a Number. Use nr2char() to convert it to a String. The returned value is zero if no character is available. The returned value is a string of characters for special keys and when a modifier (shift, control, alt) was used. There is no prompt, you will somehow have to make clear to the user that a character has to be typed. There is no mapping for the character. Key codes are replaced, thus when the user presses the key you get the code for the key, not the raw character sequence. Examples: > getchar() == "\" getchar() == "\" < This example redefines "f" to ignore case: > :nmap f :call FindChar() :function FindChar() : let c = nr2char(getchar()) : while col('.') < col('$') - 1 : normal l : if getline('.')[col('.') - 1] ==? c : break : endif : endwhile :endfunction getcharmod() *getcharmod()* The result is a Number which is the state of the modifiers for the last obtained character with getchar() or in another way. These values are added together: 2 shift 4 control 8 alt (meta) 16 mouse double click 32 mouse triple click 64 mouse quadruple click 128 Macintosh only: command Only the modifiers that have not been included in the character itself are obtained. Thus Shift-a results in "A" with no modifier. getbufvar({expr}, {varname}) *getbufvar()* The result is the value of option or local buffer variable {varname} in buffer {expr}. Note that the name without "b:" must be used. This also works for a global or local window option, but it doesn't work for a global or local window variable. For the use of {expr}, see |bufname()| above. When the buffer or variable doesn't exist an empty string is returned, there is no error message. Examples: > :let bufmodified = getbufvar(1, "&mod") :echo "todo myvar = " . getbufvar("todo", "myvar") < getcmdline() *getcmdline()* Return the current command-line. Only works when the command line is being edited, thus requires use of |c_CTRL-\_e| or |c_CTRL-R_=|. Example: > :cmap eescape(getcmdline(), ' \') < Also see |getcmdpos()| and |setcmdpos()|. getcmdpos() *getcmdpos()* Return the position of the cursor in the command line as a byte count. The first column is 1. Only works when editing the command line, thus requires use of |c_CTRL-\_e| or |c_CTRL-R_=|. Returns 0 otherwise. Also see |setcmdpos()| and |getcmdline()|. *getcwd()* getcwd() The result is a String, which is the name of the current working directory. getfsize({fname}) *getfsize()* The result is a Number, which is the size in bytes of the given file {fname}. If {fname} is a directory, 0 is returned. If the file {fname} can't be found, -1 is returned. getftime({fname}) *getftime()* The result is a Number, which is the last modification time of the given file {fname}. The value is measured as seconds since 1st Jan 1970, and may be passed to strftime(). See also |localtime()| and |strftime()|. If the file {fname} can't be found -1 is returned. *getline()* getline({lnum}) The result is a String, which is line {lnum} from the current buffer. Example: > getline(1) < When {lnum} is a String that doesn't start with a digit, line() is called to translate the String into a Number. To get the line under the cursor: > getline(".") < When {lnum} is smaller than 1 or bigger than the number of lines in the buffer, an empty string is returned. getreg([{regname}]) *getreg()* The result is a String, which is the contents of register {regname}. Example: > :let cliptext = getreg('*') < getreg('=') returns the last evaluated value of the expression register. (For use in maps). If {regname} is not specified, |v:register| is used. getregtype([{regname}]) *getregtype()* The result is a String, which is type of register {regname}. The value will be one of: "v" for |characterwise| text "V" for |linewise| text "{width}" for |blockwise-visual| text 0 for an empty or unknown register is one character with value 0x16. If {regname} is not specified, |v:register| is used. *getwinposx()* getwinposx() The result is a Number, which is the X coordinate in pixels of the left hand side of the GUI Vim window. The result will be -1 if the information is not available. *getwinposy()* getwinposy() The result is a Number, which is the Y coordinate in pixels of the top of the GUI Vim window. The result will be -1 if the information is not available. getwinvar({nr}, {varname}) *getwinvar()* The result is the value of option or local window variable {varname} in window {nr}. This also works for a global or local buffer option, but it doesn't work for a global or local buffer variable. Note that the name without "w:" must be used. Examples: > :let list_is_on = getwinvar(2, '&list') :echo "myvar = " . getwinvar(1, 'myvar') < *glob()* glob({expr}) Expand the file wildcards in {expr}. The result is a String. When there are several matches, they are separated by characters. If the expansion fails, the result is an empty string. A name for a non-existing file is not included. For most systems backticks can be used to get files names from any external command. Example: > :let tagfiles = glob("`find . -name tags -print`") :let &tags = substitute(tagfiles, "\n", ",", "g") < The result of the program inside the backticks should be one item per line. Spaces inside an item are allowed. See |expand()| for expanding special Vim variables. See |system()| for getting the raw output of an external command. globpath({path}, {expr}) *globpath()* Perform glob() on all directories in {path} and concatenate the results. Example: > :echo globpath(&rtp, "syntax/c.vim") < {path} is a comma-separated list of directory names. Each directory name is prepended to {expr} and expanded like with glob(). A path separator is inserted when needed. To add a comma inside a directory name escape it with a backslash. Note that on MS-Windows a directory may have a trailing backslash, remove it if you put a comma after it. If the expansion fails for one of the directories, there is no error message. The 'wildignore' option applies: Names matching one of the patterns in 'wildignore' will be skipped. *has()* has({feature}) The result is a Number, which is 1 if the feature {feature} is supported, zero otherwise. The {feature} argument is a string. See |feature-list| below. Also see |exists()|. hasmapto({what} [, {mode}]) *hasmapto()* The result is a Number, which is 1 if there is a mapping that contains {what} in somewhere in the rhs (what it is mapped to) and this mapping exists in one of the modes indicated by {mode}. Both the global mappings and the mappings local to the current buffer are checked for a match. If no matching mapping is found 0 is returned. The following characters are recognized in {mode}: n Normal mode v Visual mode o Operator-pending mode i Insert mode l Language-Argument ("r", "f", "t", etc.) c Command-line mode When {mode} is omitted, "nvo" is used. This function is useful to check if a mapping already exists to a function in a Vim script. Example: > :if !hasmapto('\ABCdoit') : map d \ABCdoit :endif < This installs the mapping to "\ABCdoit" only if there isn't already a mapping to "\ABCdoit". histadd({history}, {item}) *histadd()* Add the String {item} to the history {history} which can be one of: *hist-names* "cmd" or ":" command line history "search" or "/" search pattern history "expr" or "=" typed expression history "input" or "@" input line history If {item} does already exist in the history, it will be shifted to become the newest entry. The result is a Number: 1 if the operation was successful, otherwise 0 is returned. Example: > :call histadd("input", strftime("%Y %b %d")) :let date=input("Enter date: ") < This function is not available in the |sandbox|. histdel({history} [, {item}]) *histdel()* Clear {history}, ie. delete all its entries. See |hist-names| for the possible values of {history}. If the parameter {item} is given as String, this is seen as regular expression. All entries matching that expression will be removed from the history (if there are any). Upper/lowercase must match, unless "\c" is used |/\c|. If {item} is a Number, it will be interpreted as index, see |:history-indexing|. The respective entry will be removed if it exists. The result is a Number: 1 for a successful operation, otherwise 0 is returned. Examples: Clear expression register history: > :call histdel("expr") < Remove all entries starting with "*" from the search history: > :call histdel("/", '^\*') < The following three are equivalent: > :call histdel("search", histnr("search")) :call histdel("search", -1) :call histdel("search", '^'.histget("search", -1).'$') < To delete the last search pattern and use the last-but-one for the "n" command and 'hlsearch': > :call histdel("search", -1) :let @/ = histget("search", -1) histget({history} [, {index}]) *histget()* The result is a String, the entry with Number {index} from {history}. See |hist-names| for the possible values of {history}, and |:history-indexing| for {index}. If there is no such entry, an empty String is returned. When {index} is omitted, the most recent item from the history is used. Examples: Redo the second last search from history. > :execute '/' . histget("search", -2) < Define an Ex command ":H {num}" that supports re-execution of the {num}th entry from the output of |:history|. > :command -nargs=1 H execute histget("cmd", 0+) < histnr({history}) *histnr()* The result is the Number of the current entry in {history}. See |hist-names| for the possible values of {history}. If an error occurred, -1 is returned. Example: > :let inp_index = histnr("expr") < hlexists({name}) *hlexists()* The result is a Number, which is non-zero if a highlight group called {name} exists. This is when the group has been defined in some way. Not necessarily when highlighting has been defined for it, it may also have been used for a syntax item. *highlight_exists()* Obsolete name: highlight_exists(). *hlID()* hlID({name}) The result is a Number, which is the ID of the highlight group with name {name}. When the highlight group doesn't exist, zero is returned. This can be used to retrieve information about the highlight group. For example, to get the background color of the "Comment" group: > :echo synIDattr(synIDtrans(hlID("Comment")), "bg") < *highlightID()* Obsolete name: highlightID(). hostname() *hostname()* The result is a String, which is the name of the machine on which Vim is currently running. Machine names greater than 256 characters long are truncated. iconv({expr}, {from}, {to}) *iconv()* The result is a String, which is the text {expr} converted from encoding {from} to encoding {to}. When the conversion fails an empty string is returned. The encoding names are whatever the iconv() library function can accept, see ":!man 3 iconv". Most conversions require Vim to be compiled with the |+iconv| feature. Otherwise only UTF-8 to latin1 conversion and back can be done. This can be used to display messages with special characters, no matter what 'encoding' is set to. Write the message in UTF-8 and use: > echo iconv(utf8_str, "utf-8", &enc) < Note that Vim uses UTF-8 for all Unicode encodings, conversion from/to UCS-2 is automatically changed to use UTF-8. You cannot use UCS-2 in a string anyway, because of the NUL bytes. {only available when compiled with the +multi_byte feature} *indent()* indent({lnum}) The result is a Number, which is indent of line {lnum} in the current buffer. The indent is counted in spaces, the value of 'tabstop' is relevant. {lnum} is used just like in |getline()|. When {lnum} is invalid -1 is returned. input({prompt} [, {text}]) *input()* The result is a String, which is whatever the user typed on the command-line. The parameter is either a prompt string, or a blank string (for no prompt). A '\n' can be used in the prompt to start a new line. The highlighting set with |:echohl| is used for the prompt. The input is entered just like a command-line, with the same editing commands and mappings. There is a separate history for lines typed for input(). If the optional {text} is present, this is used for the default reply, as if the user typed this. NOTE: This must not be used in a startup file, for the versions that only run in GUI mode (e.g., the Win32 GUI). Note: When input() is called from within a mapping it will consume remaining characters from that mapping, because a mapping is handled like the characters were typed. Use |inputsave()| before input() and |inputrestore()| after input() to avoid that. Another solution is to avoid that further characters follow in the mapping, e.g., by using |:execute| or |:normal|. Example: > :if input("Coffee or beer? ") == "beer" : echo "Cheers!" :endif < Example with default text: > :let color = input("Color? ", "white") < Example with a mapping: > :nmap \x :call GetFoo():exe "/" . Foo :function GetFoo() : call inputsave() : let g:Foo = input("enter search pattern: ") : call inputrestore() :endfunction inputdialog({prompt} [, {text} [, {cancelreturn}]]) *inputdialog()* Like input(), but when the GUI is running and text dialogs are supported, a dialog window pops up to input the text. Example: > :let n = inputdialog("value for shiftwidth", &sw) :if n != "" : let &sw = n :endif < When the dialog is cancelled {cancelreturn} is returned. When omitted an empty string is returned. Hitting works like pressing the OK button. Hitting works like pressing the Cancel button. inputrestore() *inputrestore()* Restore typeahead that was saved with a previous inputsave(). Should be called the same number of times inputsave() is called. Calling it more often is harmless though. Returns 1 when there is nothing to restore, 0 otherwise. inputsave() *inputsave()* Preserve typeahead (also from mappings) and clear it, so that a following prompt gets input from the user. Should be followed by a matching inputrestore() after the prompt. Can be used several times, in which case there must be just as many inputrestore() calls. Returns 1 when out of memory, 0 otherwise. inputsecret({prompt} [, {text}]) *inputsecret()* This function acts much like the |input()| function with but two exceptions: a) the user's response will be displayed as a sequence of asterisks ("*") thereby keeping the entry secret, and b) the user's response will not be recorded on the input |history| stack. The result is a String, which is whatever the user actually typed on the command-line in response to the issued prompt. isdirectory({directory}) *isdirectory()* The result is a Number, which is non-zero when a directory with the name {directory} exists. If {directory} doesn't exist, or isn't a directory, the result is FALSE. {directory} is any expression, which is used as a String. *libcall()* *E364* *E368* libcall({libname}, {funcname}, {argument}) Call function {funcname} in the run-time library {libname} with single argument {argument}. This is useful to call functions in a library that you especially made to be used with Vim. Since only one argument is possible, calling standard library functions is rather limited. The result is the String returned by the function. If the function returns NULL, this will appear as an empty string "" to Vim. If the function returns a number, use libcallnr()! If {argument} is a number, it is passed to the function as an int; if {argument} is a string, it is passed as a null-terminated string. This function will fail in |restricted-mode|. libcall() allows you to write your own 'plug-in' extensions to Vim without having to recompile the program. It is NOT a means to call system functions! If you try to do so Vim will very probably crash. For Win32, the functions you write must be placed in a DLL and use the normal C calling convention (NOT Pascal which is used in Windows System DLLs). The function must take exactly one parameter, either a character pointer or a long integer, and must return a character pointer or NULL. The character pointer returned must point to memory that will remain valid after the function has returned (e.g. in static data in the DLL). If it points to allocated memory, that memory will leak away. Using a static buffer in the function should work, it's then freed when the DLL is unloaded. WARNING: If the function returns a non-valid pointer, Vim may crash! This also happens if the function returns a number, because Vim thinks it's a pointer. For Win32 systems, {libname} should be the filename of the DLL without the ".DLL" suffix. A full path is only required if the DLL is not in the usual places. For Unix: When compiling your own plugins, remember that the object code must be compiled as position-independent ('PIC'). {only in Win32 on some Unix versions, when the |+libcall| feature is present} Examples: > :echo libcall("libc.so", "getenv", "HOME") :echo libcallnr("/usr/lib/libc.so", "getpid", "") < *libcallnr()* libcallnr({libname}, {funcname}, {argument}) Just like libcall(), but used for a function that returns an int instead of a string. {only in Win32 on some Unix versions, when the |+libcall| feature is present} Example (not very useful...): > :call libcallnr("libc.so", "printf", "Hello World!\n") :call libcallnr("libc.so", "sleep", 10) < *line()* line({expr}) The result is a Number, which is the line number of the file position given with {expr}. The accepted positions are: . the cursor position $ the last line in the current buffer 'x position of mark x (if the mark is not set, 0 is returned) Note that only marks in the current file can be used. Examples: > line(".") line number of the cursor line("'t") line number of mark t line("'" . marker) line number of mark marker < *last-position-jump* This autocommand jumps to the last known position in a file just after opening it, if the '" mark is set: > :au BufReadPost * if line("'\"") > 0 && line("'\"") <= line("$") | exe "normal g'\"" | endif line2byte({lnum}) *line2byte()* Return the byte count from the start of the buffer for line {lnum}. This includes the end-of-line character, depending on the 'fileformat' option for the current buffer. The first line returns 1. This can also be used to get the byte count for the line just below the last line: > line2byte(line("$") + 1) < This is the file size plus one. When {lnum} is invalid, or the |+byte_offset| feature has been disabled at compile time, -1 is returned. Also see |byte2line()|, |go| and |:goto|. lispindent({lnum}) *lispindent()* Get the amount of indent for line {lnum} according the lisp indenting rules, as with 'lisp'. The indent is counted in spaces, the value of 'tabstop' is relevant. {lnum} is used just like in |getline()|. When {lnum} is invalid or Vim was not compiled the |+lispindent| feature, -1 is returned. localtime() *localtime()* Return the current time, measured as seconds since 1st Jan 1970. See also |strftime()| and |getftime()|. maparg({name}[, {mode}]) *maparg()* Return the rhs of mapping {name} in mode {mode}. When there is no mapping for {name}, an empty String is returned. These characters can be used for {mode}: "n" Normal "v" Visual "o" Operator-pending "i" Insert "c" Cmd-line "l" langmap |language-mapping| "" Normal, Visual and Operator-pending When {mode} is omitted, the modes from "" are used. The {name} can have special key names, like in the ":map" command. The returned String has special characters translated like in the output of the ":map" command listing. The mappings local to the current buffer are checked first, then the global mappings. mapcheck({name}[, {mode}]) *mapcheck()* Check if there is a mapping that matches with {name} in mode {mode}. See |maparg()| for {mode} and special names in {name}. A match happens with a mapping that starts with {name} and with a mapping which is equal to the start of {name}. matches mapping "a" "ab" "abc" ~ mapcheck("a") yes yes yes mapcheck("abc") yes yes yes mapcheck("ax") yes no no mapcheck("b") no no no The difference with maparg() is that mapcheck() finds a mapping that matches with {name}, while maparg() only finds a mapping for {name} exactly. When there is no mapping that starts with {name}, an empty String is returned. If there is one, the rhs of that mapping is returned. If there are several mappings that start with {name}, the rhs of one of them is returned. The mappings local to the current buffer are checked first, then the global mappings. This function can be used to check if a mapping can be added without being ambiguous. Example: > :if mapcheck("_vv") == "" : map _vv :set guifont=7x13 :endif < This avoids adding the "_vv" mapping when there already is a mapping for "_v" or for "_vvv". match({expr}, {pat}[, {start}]) *match()* The result is a Number, which gives the index (byte offset) in {expr} where {pat} matches. A match at the first character returns zero. If there is no match -1 is returned. Example: > :echo match("testing", "ing") < results in "4". See |string-match| for how {pat} is used. If {start} is given, the search starts from index {start}. The result, however, is still the index counted from the first character. Example: > :echo match("testing", "ing", 2) < result is again "4". > :echo match("testing", "ing", 4) < result is again "4". > :echo match("testing", "t", 2) < result is "3". If {start} < 0, it will be set to 0. If {start} > strlen({expr}) -1 is returned. See |pattern| for the patterns that are accepted. The 'ignorecase' option is used to set the ignore-caseness of the pattern. 'smartcase' is NOT used. The matching is always done like 'magic' is set and 'cpoptions' is empty. matchend({expr}, {pat}[, {start}]) *matchend()* Same as match(), but return the index of first character after the match. Example: > :echo matchend("testing", "ing") < results in "7". The {start}, if given, has the same meaning as for match(). > :echo matchend("testing", "ing", 2) < results in "7". > :echo matchend("testing", "ing", 5) < result is "-1". matchstr({expr}, {pat}[, {start}]) *matchstr()* Same as match(), but return the matched string. Example: > :echo matchstr("testing", "ing") < results in "ing". When there is no match "" is returned. The {start}, if given, has the same meaning as for match(). > :echo matchstr("testing", "ing", 2) < results in "ing". > :echo matchstr("testing", "ing", 5) < result is "". *mode()* mode() Return a string that indicates the current mode: n Normal v Visual by character V Visual by line CTRL-V Visual blockwise s Select by character S Select by line CTRL-S Select blockwise i Insert R Replace c Command-line r Hit-enter prompt This is useful in the 'statusline' option. In most other places it always returns "c" or "n". nextnonblank({lnum}) *nextnonblank()* Return the line number of the first line at or below {lnum} that is not blank. Example: > if getline(nextnonblank(1)) =~ "Java" < When {lnum} is invalid or there is no non-blank line at or below it, zero is returned. See also |prevnonblank()|. nr2char({expr}) *nr2char()* Return a string with a single character, which has the number value {expr}. Examples: > nr2char(64) returns "@" nr2char(32) returns " " < The current 'encoding' is used. Example for "utf-8": > nr2char(300) returns I with bow character < Note that a NUL character in the file is specified with nr2char(10), because NULs are represented with newline characters. nr2char(0) is a real NUL and terminates the string, thus isn't very useful. prevnonblank({lnum}) *prevnonblank()* Return the line number of the first line at or above {lnum} that is not blank. Example: > let ind = indent(prevnonblank(v:lnum - 1)) < When {lnum} is invalid or there is no non-blank line at or above it, zero is returned. Also see |nextnonblank()|. *remote_expr()* *E449* remote_expr({server}, {string} [, {idvar}]) Send the {string} to {server}. The string is sent as an expression and the result is returned after evaluation. If {idvar} is present, it is taken as the name of a variable and a {serverid} for later use with remote_read() is stored there. See also |clientserver| |RemoteReply|. This function is not available in the |sandbox|. {only available when compiled with the |+clientserver| feature} Note: Any errors will cause a local error message to be issued and the result will be the empty string. Examples: > :echo remote_expr("gvim", "2+2") :echo remote_expr("gvim1", "b:current_syntax") < remote_foreground({server}) *remote_foreground()* Move the Vim server with the name {server} to the foreground. This works like: > remote_expr({server}, "foreground()") < Except that on Win32 systems the client does the work, to work around the problem that the OS doesn't always allow the server to bring itself to the foreground. This function is not available in the |sandbox|. {only in the Win32, Athena, Motif and GTK GUI versions and the Win32 console version} remote_peek({serverid} [, {retvar}]) *remote_peek()* Returns a positive number if there are available strings from {serverid}. Copies any reply string into the variable {retvar} if specified. {retvar} must be a string with the name of a variable. Returns zero if none are available. Returns -1 if something is wrong. See also |clientserver|. This function is not available in the |sandbox|. {only available when compiled with the |+clientserver| feature} Examples: > :let repl = "" :echo "PEEK: ".remote_peek(id, "repl").": ".repl remote_read({serverid}) *remote_read()* Return the oldest available reply from {serverid} and consume it. It blocks until a reply is available. See also |clientserver|. This function is not available in the |sandbox|. {only available when compiled with the |+clientserver| feature} Example: > :echo remote_read(id) < *remote_send()* *E241* remote_send({server}, {string} [, {idvar}]) Send the {string} to {server}. The string is sent as input keys and the function returns immediately. If {idvar} is present, it is taken as the name of a variable and a {serverid} for later use with remote_read() is stored there. See also |clientserver| |RemoteReply|. This function is not available in the |sandbox|. {only available when compiled with the |+clientserver| feature} Note: Any errors will be reported in the server and may mess up the display. Examples: > :echo remote_send("gvim", ":DropAndReply ".file, "serverid"). \ remote_read(serverid) :autocmd NONE RemoteReply * \ echo remote_read(expand("")) :echo remote_send("gvim", ":sleep 10 | echo ". \ 'server2client(expand(""), "HELLO")') rename({from}, {to}) *rename()* Rename the file by the name {from} to the name {to}. This should also work to move files across file systems. The result is a Number, which is 0 if the file was renamed successfully, and non-zero when the renaming failed. This function is not available in the |sandbox|. resolve({filename}) *resolve()* *E655* On MS-Windows, when {filename} is a shortcut (a .lnk file), returns the path the shortcut points to in a simplified form. On Unix, repeat resolving symbolic links in all path components of {filename} and return the simplified result. To cope with link cycles, resolving of symbolic links is stopped after 100 iterations. On other systems, return the simplified {filename}. The simplification step is done as by |simplify()|. resolve() keeps a leading path component specifying the current directory (provided the result is still a relative path name) and also keeps a trailing path separator. search({pattern} [, {flags}]) *search()* Search for regexp pattern {pattern}. The search starts at the cursor position. {flags} is a String, which can contain these character flags: 'b' search backward instead of forward 'w' wrap around the end of the file 'W' don't wrap around the end of the file If neither 'w' or 'W' is given, the 'wrapscan' option applies. When a match has been found its line number is returned, and the cursor will be positioned at the match. If there is no match a 0 is returned and the cursor doesn't move. No error message is given. Example (goes over all files in the argument list): > :let n = 1 :while n <= argc() " loop over all files in arglist : exe "argument " . n : " start at the last char in the file and wrap for the : " first search to find match at start of file : normal G$ : let flags = "w" : while search("foo", flags) > 0 : s/foo/bar/g : let flags = "W" : endwhile : update " write the file if modified : let n = n + 1 :endwhile < *searchpair()* searchpair({start}, {middle}, {end} [, {flags} [, {skip}]]) Search for the match of a nested start-end pair. This can be used to find the "endif" that matches an "if", while other if/endif pairs in between are ignored. The search starts at the cursor. If a match is found, the cursor is positioned at it and the line number is returned. If no match is found 0 or -1 is returned and the cursor doesn't move. No error message is given. {start}, {middle} and {end} are patterns, see |pattern|. They must not contain \( \) pairs. Use of \%( \) is allowed. When {middle} is not empty, it is found when searching from either direction, but only when not in a nested start-end pair. A typical use is: > searchpair('\', '\', '\') < By leaving {middle} empty the "else" is skipped. {flags} are used like with |search()|. Additionally: 'n' do Not move the cursor 'r' Repeat until no more matches found; will find the outer pair 'm' return number of Matches instead of line number with the match; will only be > 1 when 'r' is used. When a match for {start}, {middle} or {end} is found, the {skip} expression is evaluated with the cursor positioned on the start of the match. It should return non-zero if this match is to be skipped. E.g., because it is inside a comment or a string. When {skip} is omitted or empty, every match is accepted. When evaluating {skip} causes an error the search is aborted and -1 returned. The value of 'ignorecase' is used. 'magic' is ignored, the patterns are used like it's on. The search starts exactly at the cursor. A match with {start}, {middle} or {end} at the next character, in the direction of searching, is the first one found. Example: > if 1 if 2 endif 2 endif 1 < When starting at the "if 2", with the cursor on the "i", and searching forwards, the "endif 2" is found. When starting on the character just before the "if 2", the "endif 1" will be found. That's because the "if 2" will be found first, and then this is considered to be a nested if/endif from "if 2" to "endif 2". When searching backwards and {end} is more than one character, it may be useful to put "\zs" at the end of the pattern, so that when the cursor is inside a match with the end it finds the matching start. Example, to find the "endif" command in a Vim script: > :echo searchpair('\', '\', '\', 'W', \ 'getline(".") =~ "^\\s*\""') < The cursor must be at or after the "if" for which a match is to be found. Note that single-quote strings are used to avoid having to double the backslashes. The skip expression only catches comments at the start of a line, not after a command. Also, a word "en" or "if" halfway a line is considered a match. Another example, to search for the matching "{" of a "}": > :echo searchpair('{', '', '}', 'bW') < This works when the cursor is at or before the "}" for which a match is to be found. To reject matches that syntax highlighting recognized as strings: > :echo searchpair('{', '', '}', 'bW', \ 'synIDattr(synID(line("."), col("."), 0), "name") =~? "string"') < server2client( {clientid}, {string}) *server2client()* Send a reply string to {clientid}. The most recent {clientid} that sent a string can be retrieved with expand(""). {only available when compiled with the |+clientserver| feature} Note: This id has to be stored before the next command can be received. Ie. before returning from the received command and before calling any commands that waits for input. See also |clientserver|. Example: > :echo server2client(expand(""), "HELLO") < serverlist() *serverlist()* Return a list of available server names, one per line. When there are no servers or the information is not available an empty string is returned. See also |clientserver|. {only available when compiled with the |+clientserver| feature} Example: > :echo serverlist() < setbufvar({expr}, {varname}, {val}) *setbufvar()* Set option or local variable {varname} in buffer {expr} to {val}. This also works for a global or local window option, but it doesn't work for a global or local window variable. For a local window option the global value is unchanged. For the use of {expr}, see |bufname()| above. Note that the variable name without "b:" must be used. Examples: > :call setbufvar(1, "&mod", 1) :call setbufvar("todo", "myvar", "foobar") < This function is not available in the |sandbox|. setcmdpos({pos}) *setcmdpos()* Set the cursor position in the command line to byte position {pos}. The first position is 1. Use |getcmdpos()| to obtain the current position. Only works while editing the command line, thus you must use |c_CTRL-\_e| or |c_CTRL-R_=|. The position is set after the command line is set to the expression. When the number is too big the cursor is put at the end of the line. A number smaller than one has undefined results. Returns 0 when successful, 1 when not editing the command line. setline({lnum}, {line}) *setline()* Set line {lnum} of the current buffer to {line}. If this succeeds, 0 is returned. If this fails (most likely because {lnum} is invalid) 1 is returned. Example: > :call setline(5, strftime("%c")) < Note: The '[ and '] marks are not set. *setreg()* setreg({regname}, {value} [,{options}]) Set the register {regname} to {value}. If {options} contains "a" or {regname} is upper case, then the value is appended. {options} can also contains a register type specification: "c" or "v" |characterwise| mode "l" or "V" |linewise| mode "b" or "" |blockwise-visual| mode If a number immediately follows "b" or "" then this is used as the width of the selection - if it is not specified then the width of the block is set to the number of characters in the longest line (counting a as 1 character). If {options} contains no register settings, then the default is to use character mode unless {value} ends in a . Setting the '=' register is not possible. Returns zero for success, non-zero for failure. Examples: > :call setreg(v:register, @*) :call setreg('*', @%, 'ac') :call setreg('a', "1\n2\n3", 'b5') < This example shows using the functions to save and restore a register. > :let var_a = getreg('a') :let var_amode = getregtype('a') .... :call setreg('a', var_a, var_amode) < You can also change the type of a register by appending nothing: > :call setreg('a', '', 'al') setwinvar({nr}, {varname}, {val}) *setwinvar()* Set option or local variable {varname} in window {nr} to {val}. This also works for a global or local buffer option, but it doesn't work for a global or local buffer variable. For a local buffer option the global value is unchanged. Note that the variable name without "w:" must be used. Examples: > :call setwinvar(1, "&list", 0) :call setwinvar(2, "myvar", "foobar") < This function is not available in the |sandbox|. simplify({filename}) *simplify()* Simplify the file name as much as possible without changing the meaning. Shortcuts (on MS-Windows) or symbolic links (on Unix) are not resolved. If the first path component in {filename} designates the current directory, this will be valid for the result as well. A trailing path separator is not removed either. Example: > simplify("./dir/.././/file/") == "./file/" < Note: The combination "dir/.." is only removed if "dir" is a searchable directory or does not exist. On Unix, it is also removed when "dir" is a symbolic link within the same directory. In order to resolve all the involved symbolic links before simplifying the path name, use |resolve()|. strftime({format} [, {time}]) *strftime()* The result is a String, which is a formatted date and time, as specified by the {format} string. The given {time} is used, or the current time if no time is given. The accepted {format} depends on your system, thus this is not portable! See the manual page of the C function strftime() for the format. The maximum length of the result is 80 characters. See also |localtime()| and |getftime()|. The language can be changed with the |:language| command. Examples: > :echo strftime("%c") Sun Apr 27 11:49:23 1997 :echo strftime("%Y %b %d %X") 1997 Apr 27 11:53:25 :echo strftime("%y%m%d %T") 970427 11:53:55 :echo strftime("%H:%M") 11:55 :echo strftime("%c", getftime("file.c")) Show mod time of file.c. < stridx({haystack}, {needle}) *stridx()* The result is a Number, which gives the index in {haystack} of the first occurrence of the String {needle} in the String {haystack}. The search is done case-sensitive. For advanced searches use |match()|. If the {needle} does not occur in {haystack} it returns -1. See also |strridx()|. Examples: > :echo stridx("An Example", "Example") 3 :echo stridx("Starting point", "Start") 0 :echo stridx("Starting point", "start") -1 < *strlen()* strlen({expr}) The result is a Number, which is the length of the String {expr} in bytes. If you want to count the number of multi-byte characters use something like this: > :let len = strlen(substitute(str, ".", "x", "g")) < Composing characters are not counted. strpart({src}, {start}[, {len}]) *strpart()* The result is a String, which is part of {src}, starting from byte {start}, with the length {len}. When non-existing bytes are included, this doesn't result in an error, the bytes are simply omitted. If {len} is missing, the copy continues from {start} till the end of the {src}. > strpart("abcdefg", 3, 2) == "de" strpart("abcdefg", -2, 4) == "ab" strpart("abcdefg", 5, 4) == "fg" strpart("abcdefg", 3) == "defg" < Note: To get the first character, {start} must be 0. For example, to get three bytes under and after the cursor: > strpart(getline(line(".")), col(".") - 1, 3) < strridx({haystack}, {needle}) *strridx()* The result is a Number, which gives the index in {haystack} of the last occurrence of the String {needle} in the String {haystack}. The search is done case-sensitive. For advanced searches use |match()|. If the {needle} does not occur in {haystack} it returns -1. See also |stridx()|. Examples: > :echo strridx("an angry armadillo", "an") 3 < strtrans({expr}) *strtrans()* The result is a String, which is {expr} with all unprintable characters translated into printable characters |'isprint'|. Like they are shown in a window. Example: > echo strtrans(@a) < This displays a newline in register a as "^@" instead of starting a new line. submatch({nr}) *submatch()* Only for an expression in a |:substitute| command. Returns the {nr}'th submatch of the matched text. When {nr} is 0 the whole matched text is returned. Example: > :s/\d\+/\=submatch(0) + 1/ < This finds the first number in the line and adds one to it. A line break is included as a newline character. substitute({expr}, {pat}, {sub}, {flags}) *substitute()* The result is a String, which is a copy of {expr}, in which the first match of {pat} is replaced with {sub}. This works like the ":substitute" command (without any flags). But the matching with {pat} is always done like the 'magic' option is set and 'cpoptions' is empty (to make scripts portable). See |string-match| for how {pat} is used. And a "~" in {sub} is not replaced with the previous {sub}. Note that some codes in {sub} have a special meaning |sub-replace-special|. For example, to replace something with "\n" (two characters), use "\\\\n" or '\\n'. When {pat} does not match in {expr}, {expr} is returned unmodified. When {flags} is "g", all matches of {pat} in {expr} are replaced. Otherwise {flags} should be "". Example: > :let &path = substitute(&path, ",\\=[^,]*$", "", "") < This removes the last component of the 'path' option. > :echo substitute("testing", ".*", "\\U\\0", "") < results in "TESTING". synID({line}, {col}, {trans}) *synID()* The result is a Number, which is the syntax ID at the position {line} and {col} in the current window. The syntax ID can be used with |synIDattr()| and |synIDtrans()| to obtain syntax information about text. {col} is 1 for the leftmost column, {line} is 1 for the first line. When {trans} is non-zero, transparent items are reduced to the item that they reveal. This is useful when wanting to know the effective color. When {trans} is zero, the transparent item is returned. This is useful when wanting to know which syntax item is effective (e.g. inside parens). Warning: This function can be very slow. Best speed is obtained by going through the file in forward direction. Example (echoes the name of the syntax item under the cursor): > :echo synIDattr(synID(line("."), col("."), 1), "name") < synIDattr({synID}, {what} [, {mode}]) *synIDattr()* The result is a String, which is the {what} attribute of syntax ID {synID}. This can be used to obtain information about a syntax item. {mode} can be "gui", "cterm" or "term", to get the attributes for that mode. When {mode} is omitted, or an invalid value is used, the attributes for the currently active highlighting are used (GUI, cterm or term). Use synIDtrans() to follow linked highlight groups. {what} result "name" the name of the syntax item "fg" foreground color (GUI: color name used to set the color, cterm: color number as a string, term: empty string) "bg" background color (like "fg") "fg#" like "fg", but for the GUI and the GUI is running the name in "#RRGGBB" form "bg#" like "fg#" for "bg" "bold" "1" if bold "italic" "1" if italic "reverse" "1" if reverse "inverse" "1" if inverse (= reverse) "underline" "1" if underlined Example (echoes the color of the syntax item under the cursor): > :echo synIDattr(synIDtrans(synID(line("."), col("."), 1)), "fg") < synIDtrans({synID}) *synIDtrans()* The result is a Number, which is the translated syntax ID of {synID}. This is the syntax group ID of what is being used to highlight the character. Highlight links given with ":highlight link" are followed. *system()* system({expr}) Get the output of the shell command {expr}. Note: newlines in {expr} may cause the command to fail. The characters in 'shellquote' and 'shellxquote' may also cause trouble. This is not to be used for interactive commands. The result is a String. Example: > :let files = system("ls") < To make the result more system-independent, the shell output is filtered to replace with for Macintosh, and with for DOS-like systems. The command executed is constructed using several options: 'shell' 'shellcmdflag' 'shellxquote' {expr} 'shellredir' {tmp} 'shellxquote' ({tmp} is an automatically generated file name). For Unix and OS/2 braces are put around {expr} to allow for concatenated commands. The resulting error code can be found in |v:shell_error|. This function will fail in |restricted-mode|. Unlike ":!cmd" there is no automatic check for changed files. Use |:checktime| to force a check. tempname() *tempname()* *temp-file-name* The result is a String, which is the name of a file that doesn't exist. It can be used for a temporary file. The name is different for at least 26 consecutive calls. Example: > :let tmpfile = tempname() :exe "redir > " . tmpfile < For Unix, the file will be in a private directory (only accessible by the current user) to avoid security problems (e.g., a symlink attack or other people reading your file). When Vim exits the directory and all files in it are deleted. For MS-Windows forward slashes are used when the 'shellslash' option is set or when 'shellcmdflag' starts with '-'. tolower({expr}) *tolower()* The result is a copy of the String given, with all uppercase characters turned into lowercase (just like applying |gu| to the string). toupper({expr}) *toupper()* The result is a copy of the String given, with all lowercase characters turned into uppercase (just like applying |gU| to the string). type({expr}) *type()* The result is a Number: 0 if {expr} has the type Number 1 if {expr} has the type String virtcol({expr}) *virtcol()* The result is a Number, which is the screen column of the file position given with {expr}. That is, the last screen position occupied by the character at that position, when the screen would be of unlimited width. When there is a at the position, the returned Number will be the column at the end of the . For example, for a in column 1, with 'ts' set to 8, it returns 8. For the byte position use |col()|. When Virtual editing is active in the current mode, a position beyond the end of the line can be returned. |'virtualedit'| The accepted positions are: . the cursor position $ the end of the cursor line (the result is the number of displayed characters in the cursor line plus one) 'x position of mark x (if the mark is not set, 0 is returned) Note that only marks in the current file can be used. Examples: > virtcol(".") with text "foo^Lbar", with cursor on the "^L", returns 5 virtcol("$") with text "foo^Lbar", returns 9 virtcol("'t") with text " there", with 't at 'h', returns 6 < The first column is 1. 0 is returned for an error. visualmode([expr]) *visualmode()* The result is a String, which describes the last Visual mode used. Initially it returns an empty string, but once Visual mode has been used, it returns "v", "V", or "" (a single CTRL-V character) for character-wise, line-wise, or block-wise Visual mode respectively. Example: > :exe "normal " . visualmode() < This enters the same Visual mode as before. It is also useful in scripts if you wish to act differently depending on the Visual mode that was used. If an expression is supplied that results in a non-zero number or a non-empty string, then the Visual mode will be cleared and the old value is returned. Note that " " and "0" are also non-empty strings, thus cause the mode to be cleared. *winbufnr()* winbufnr({nr}) The result is a Number, which is the number of the buffer associated with window {nr}. When {nr} is zero, the number of the buffer in the current window is returned. When window {nr} doesn't exist, -1 is returned. Example: > :echo "The file in the current window is " . bufname(winbufnr(0)) < *wincol()* wincol() The result is a Number, which is the virtual column of the cursor in the window. This is counting screen cells from the left side of the window. The leftmost column is one. winheight({nr}) *winheight()* The result is a Number, which is the height of window {nr}. When {nr} is zero, the height of the current window is returned. When window {nr} doesn't exist, -1 is returned. An existing window always has a height of zero or more. Examples: > :echo "The current window has " . winheight(0) . " lines." < *winline()* winline() The result is a Number, which is the screen line of the cursor in the window. This is counting screen lines from the top of the window. The first line is one. *winnr()* winnr() The result is a Number, which is the number of the current window. The top window has number 1. The number can be used with |CTRL-W_w| and ":wincmd w" |:wincmd|. *winrestcmd()* winrestcmd() Returns a sequence of |:resize| commands that should restore the current window sizes. Only works properly when no windows are opened or closed and the current window is unchanged. Example: > :let cmd = winrestcmd() :call MessWithWindowSizes() :exe cmd winwidth({nr}) *winwidth()* The result is a Number, which is the width of window {nr}. When {nr} is zero, the width of the current window is returned. When window {nr} doesn't exist, -1 is returned. An existing window always has a width of zero or more. Examples: > :echo "The current window has " . winwidth(0) . " columns." :if winwidth(0) <= 50 : exe "normal 50\|" :endif < *feature-list* There are three types of features: 1. Features that are only supported when they have been enabled when Vim was compiled |+feature-list|. Example: > :if has("cindent") 2. Features that are only supported when certain conditions have been met. Example: > :if has("gui_running") < *has-patch* 3. Included patches. First check |v:version| for the version of Vim. Then the "patch123" feature means that patch 123 has been included for this version. Example (checking version 6.2.148 or later): > :if v:version > 602 || v:version == 602 && has("patch148") all_builtin_terms Compiled with all builtin terminals enabled. amiga Amiga version of Vim. arabic Compiled with Arabic support |Arabic|. arp Compiled with ARP support (Amiga). autocmd Compiled with autocommands support. balloon_eval Compiled with |balloon-eval| support. beos BeOS version of Vim. browse Compiled with |:browse| support, and browse() will work. builtin_terms Compiled with some builtin terminals. byte_offset Compiled with support for 'o' in 'statusline' cindent Compiled with 'cindent' support. clientserver Compiled with remote invocation support |clientserver|. clipboard Compiled with 'clipboard' support. cmdline_compl Compiled with |cmdline-completion| support. cmdline_hist Compiled with |cmdline-history| support. cmdline_info Compiled with 'showcmd' and 'ruler' support. comments Compiled with |'comments'| support. cryptv Compiled with encryption support |encryption|. cscope Compiled with |cscope| support. compatible Compiled to be very Vi compatible. debug Compiled with "DEBUG" defined. dialog_con Compiled with console dialog support. dialog_gui Compiled with GUI dialog support. diff Compiled with |vimdiff| and 'diff' support. digraphs Compiled with support for digraphs. dnd Compiled with support for the "~ register |quote_~|. dos32 32 bits DOS (DJGPP) version of Vim. dos16 16 bits DOS version of Vim. ebcdic Compiled on a machine with ebcdic character set. emacs_tags Compiled with support for Emacs tags. eval Compiled with expression evaluation support. Always true, of course! ex_extra Compiled with extra Ex commands |+ex_extra|. extra_search Compiled with support for |'incsearch'| and |'hlsearch'| farsi Compiled with Farsi support |farsi|. file_in_path Compiled with support for |gf| and || find_in_path Compiled with support for include file searches |+find_in_path|. fname_case Case in file names matters (for Amiga, MS-DOS, and Windows this is not present). folding Compiled with |folding| support. footer Compiled with GUI footer support. |gui-footer| fork Compiled to use fork()/exec() instead of system(). gettext Compiled with message translation |multi-lang| gui Compiled with GUI enabled. gui_athena Compiled with Athena GUI. gui_beos Compiled with BeOS GUI. gui_gtk Compiled with GTK+ GUI (any version). gui_gtk2 Compiled with GTK+ 2 GUI (gui_gtk is also defined). gui_mac Compiled with Macintosh GUI. gui_motif Compiled with Motif GUI. gui_photon Compiled with Photon GUI. gui_win32 Compiled with MS Windows Win32 GUI. gui_win32s idem, and Win32s system being used (Windows 3.1) gui_running Vim is running in the GUI, or it will start soon. hangul_input Compiled with Hangul input support. |hangul| iconv Can use iconv() for conversion. insert_expand Compiled with support for CTRL-X expansion commands in Insert mode. jumplist Compiled with |jumplist| support. keymap Compiled with 'keymap' support. langmap Compiled with 'langmap' support. libcall Compiled with |libcall()| support. linebreak Compiled with 'linebreak', 'breakat' and 'showbreak' support. lispindent Compiled with support for lisp indenting. listcmds Compiled with commands for the buffer list |:files| and the argument list |arglist|. localmap Compiled with local mappings and abbr. |:map-local| mac Macintosh version of Vim. macunix Macintosh version of Vim, using Unix files (OS-X). menu Compiled with support for |:menu|. mksession Compiled with support for |:mksession|. modify_fname Compiled with file name modifiers. |filename-modifiers| mouse Compiled with support mouse. mouseshape Compiled with support for 'mouseshape'. mouse_dec Compiled with support for Dec terminal mouse. mouse_gpm Compiled with support for gpm (Linux console mouse) mouse_netterm Compiled with support for netterm mouse. mouse_pterm Compiled with support for qnx pterm mouse. mouse_xterm Compiled with support for xterm mouse. multi_byte Compiled with support for editing Korean et al. multi_byte_ime Compiled with support for IME input method. multi_lang Compiled with support for multiple languages. netbeans_intg Compiled with support for |netbeans|. ole Compiled with OLE automation support for Win32. os2 OS/2 version of Vim. osfiletype Compiled with support for osfiletypes |+osfiletype| path_extra Compiled with up/downwards search in 'path' and 'tags' perl Compiled with Perl interface. postscript Compiled with PostScript file printing. printer Compiled with |:hardcopy| support. python Compiled with Python interface. qnx QNX version of Vim. quickfix Compiled with |quickfix| support. rightleft Compiled with 'rightleft' support. ruby Compiled with Ruby interface |ruby|. scrollbind Compiled with 'scrollbind' support. showcmd Compiled with 'showcmd' support. signs Compiled with |:sign| support. smartindent Compiled with 'smartindent' support. sniff Compiled with SNiFF interface support. statusline Compiled with support for 'statusline', 'rulerformat' and special formats of 'titlestring' and 'iconstring'. sun_workshop Compiled with support for Sun |workshop|. syntax Compiled with syntax highlighting support. syntax_items There are active syntax highlighting items for the current buffer. system Compiled to use system() instead of fork()/exec(). tag_binary Compiled with binary searching in tags files |tag-binary-search|. tag_old_static Compiled with support for old static tags |tag-old-static|. tag_any_white Compiled with support for any white characters in tags files |tag-any-white|. tcl Compiled with Tcl interface. terminfo Compiled with terminfo instead of termcap. termresponse Compiled with support for |t_RV| and |v:termresponse|. textobjects Compiled with support for |text-objects|. tgetent Compiled with tgetent support, able to use a termcap or terminfo file. title Compiled with window title support |'title'|. toolbar Compiled with support for |gui-toolbar|. unix Unix version of Vim. user_commands User-defined commands. viminfo Compiled with viminfo support. vim_starting True while initial source'ing takes place. vertsplit Compiled with vertically split windows |:vsplit|. virtualedit Compiled with 'virtualedit' option. visual Compiled with Visual mode. visualextra Compiled with extra Visual mode commands. |blockwise-operators|. vms VMS version of Vim. vreplace Compiled with |gR| and |gr| commands. wildignore Compiled with 'wildignore' option. wildmenu Compiled with 'wildmenu' option. windows Compiled with support for more than one window. winaltkeys Compiled with 'winaltkeys' option. win16 Win16 version of Vim (MS-Windows 3.1). win32 Win32 version of Vim (MS-Windows 95/98/ME/NT/2000/XP). win64 Win64 version of Vim (MS-Windows 64 bit). win32unix Win32 version of Vim, using Unix files (Cygwin) win95 Win32 version for MS-Windows 95/98/ME. writebackup Compiled with 'writebackup' default on. xfontset Compiled with X fontset support |xfontset|. xim Compiled with X input method support |xim|. xsmp Compiled with X session management support. xsmp_interact Compiled with interactive X session management support. xterm_clipboard Compiled with support for xterm clipboard. xterm_save Compiled with support for saving and restoring the xterm screen. x11 Compiled with X11 support. *string-match* Matching a pattern in a String A regexp pattern as explained at |pattern| is normally used to find a match in the buffer lines. When a pattern is used to find a match in a String, almost everything works in the same way. The difference is that a String is handled like it is one line. When it contains a "\n" character, this is not seen as a line break for the pattern. It can be matched with a "\n" in the pattern, or with ".". Example: > :let a = "aaaa\nxxxx" :echo matchstr(a, "..\n..") aa xx :echo matchstr(a, "a.x") a x Don't forget that "^" will only match at the first character of the String and "$" at the last character of the string. They don't match after or before a "\n". ============================================================================== 5. Defining functions *user-functions* New functions can be defined. These can be called just like builtin functions. The function executes a sequence of Ex commands. Normal mode commands can be executed with the |:normal| command. The function name must start with an uppercase letter, to avoid confusion with builtin functions. To prevent from using the same name in different scripts avoid obvious, short names. A good habit is to start the function name with the name of the script, e.g., "HTMLcolor()". It's also possible to use curly braces, see |curly-braces-names|. *local-function* A function local to a script must start with "s:". A local script function can only be called from within the script and from functions, user commands and autocommands defined in the script. It is also possible to call the function from a mappings defined in the script, but then || must be used instead of "s:" when the mapping is expanded outside of the script. *:fu* *:function* *E128* *E129* *E123* :fu[nction] List all functions and their arguments. :fu[nction] {name} List function {name}. *E124* *E125* :fu[nction][!] {name}([arguments]) [range] [abort] Define a new function by the name {name}. The name must be made of alphanumeric characters and '_', and must start with a capital or "s:" (see above). *function-argument* *a:var* An argument can be defined by giving its name. In the function this can then be used as "a:name" ("a:" for argument). Up to 20 arguments can be given, separated by commas. Finally, an argument "..." can be specified, which means that more arguments may be following. In the function they can be used as "a:1", "a:2", etc. "a:0" is set to the number of extra arguments (which can be 0). When not using "...", the number of arguments in a function call must be equal to the number of named arguments. When using "...", the number of arguments may be larger. It is also possible to define a function without any arguments. You must still supply the () then. The body of the function follows in the next lines, until the matching |:endfunction|. It is allowed to define another function inside a function body. *E127* *E122* When a function by this name already exists and [!] is not used an error message is given. When [!] is used, an existing function is silently replaced. Unless it is currently being executed, that is an error. *a:firstline* *a:lastline* When the [range] argument is added, the function is expected to take care of a range itself. The range is passed as "a:firstline" and "a:lastline". If [range] is excluded, ":{range}call" will call the function for each line in the range, with the cursor on the start of each line. See |function-range-example|. When the [abort] argument is added, the function will abort as soon as an error is detected. The last used search pattern and the redo command "." will not be changed by the function. *:endf* *:endfunction* *E126* *E193* :endf[unction] The end of a function definition. Must be on a line by its own, without other commands. *:delf* *:delfunction* *E130* *E131* :delf[unction] {name} Delete function {name}. *:retu* *:return* *E133* :retu[rn] [expr] Return from a function. When "[expr]" is given, it is evaluated and returned as the result of the function. If "[expr]" is not given, the number 0 is returned. When a function ends without an explicit ":return", the number 0 is returned. Note that there is no check for unreachable lines, thus there is no warning if commands follow ":return". If the ":return" is used after a |:try| but before the matching |:finally| (if present), the commands following the ":finally" up to the matching |:endtry| are executed first. This process applies to all nested ":try"s inside the function. The function returns at the outermost ":endtry". Inside a function variables can be used. These are local variables, which will disappear when the function returns. Global variables need to be accessed with "g:". Example: > :function Table(title, ...) : echohl Title : echo a:title : echohl None : let idx = 1 : while idx <= a:0 : echo a:{idx} . ' ' : let idx = idx + 1 : endwhile : return idx :endfunction This function can then be called with: > let lines = Table("Table", "line1", "line2") let lines = Table("Empty Table") To return more than one value, pass the name of a global variable: > :function Compute(n1, n2, divname) : if a:n2 == 0 : return "fail" : endif : let g:{a:divname} = a:n1 / a:n2 : return "ok" :endfunction This function can then be called with: > :let success = Compute(13, 1324, "div") :if success == "ok" : echo div :endif An alternative is to return a command that can be executed. This also works with local variables in a calling function. Example: > :function Foo() : execute Bar() : echo "line " . lnum . " column " . col :endfunction :function Bar() : return "let lnum = " . line(".") . " | let col = " . col(".") :endfunction The names "lnum" and "col" could also be passed as argument to Bar(), to allow the caller to set the names. *:cal* *:call* *E107* :[range]cal[l] {name}([arguments]) Call a function. The name of the function and its arguments are as specified with |:function|. Up to 20 arguments can be used. Without a range and for functions that accept a range, the function is called once. When a range is given the cursor is positioned at the start of the first line before executing the function. When a range is given and the function doesn't handle it itself, the function is executed for each line in the range, with the cursor in the first column of that line. The cursor is left at the last line (possibly moved by the last function call). The arguments are re-evaluated for each line. Thus this works: *function-range-example* > :function Mynumber(arg) : echo line(".") . " " . a:arg :endfunction :1,5call Mynumber(getline(".")) < The "a:firstline" and "a:lastline" are defined anyway, they can be used to do something different at the start or end of the range. Example of a function that handles the range itself: > :function Cont() range : execute (a:firstline + 1) . "," . a:lastline . 's/^/\t\\ ' :endfunction :4,8call Cont() < This function inserts the continuation character "\" in front of all the lines in the range, except the first one. *E132* The recursiveness of user functions is restricted with the |'maxfuncdepth'| option. *autoload-functions* When using many or large functions, it's possible to automatically define them only when they are used. Use the FuncUndefined autocommand event with a pattern that matches the function(s) to be defined. Example: > :au FuncUndefined BufNet* source ~/vim/bufnetfuncs.vim The file "~/vim/bufnetfuncs.vim" should then define functions that start with "BufNet". Also see |FuncUndefined|. ============================================================================== 6. Curly braces names *curly-braces-names* Wherever you can use a variable, you can use a "curly braces name" variable. This is a regular variable name with one or more expressions wrapped in braces {} like this: > my_{adjective}_variable When Vim encounters this, it evaluates the expression inside the braces, puts that in place of the expression, and re-interprets the whole as a variable name. So in the above example, if the variable "adjective" was set to "noisy", then the reference would be to "my_noisy_variable", whereas if "adjective" was set to "quiet", then it would be to "my_quiet_variable". One application for this is to create a set of variables governed by an option value. For example, the statement > echo my_{&background}_message would output the contents of "my_dark_message" or "my_light_message" depending on the current value of 'background'. You can use multiple brace pairs: > echo my_{adverb}_{adjective}_message ..or even nest them: > echo my_{ad{end_of_word}}_message where "end_of_word" is either "verb" or "jective". However, the expression inside the braces must evaluate to a valid single variable name. e.g. this is invalid: > :let foo='a + b' :echo c{foo}d .. since the result of expansion is "ca + bd", which is not a variable name. *curly-braces-function-names* You can call and define functions by an evaluated name in a similar way. Example: > :let func_end='whizz' :call my_func_{func_end}(parameter) This would call the function "my_func_whizz(parameter)". ============================================================================== 7. Commands *expression-commands* :let {var-name} = {expr1} *:let* *E18* Set internal variable {var-name} to the result of the expression {expr1}. The variable will get the type from the {expr}. If {var-name} didn't exist yet, it is created. :let ${env-name} = {expr1} *:let-environment* *:let-$* Set environment variable {env-name} to the result of the expression {expr1}. The type is always String. :let @{reg-name} = {expr1} *:let-register* *:let-@* Write the result of the expression {expr1} in register {reg-name}. {reg-name} must be a single letter, and must be the name of a writable register (see |registers|). "@@" can be used for the unnamed register, "@/" for the search pattern. If the result of {expr1} ends in a or , the register will be linewise, otherwise it will be set to characterwise. This can be used to clear the last search pattern: > :let @/ = "" < This is different from searching for an empty string, that would match everywhere. :let &{option-name} = {expr1} *:let-option* *:let-star* Set option {option-name} to the result of the expression {expr1}. The value is always converted to the type of the option. For an option local to a window or buffer the effect is just like using the |:set| command: both the local value and the global value are changed. :let &l:{option-name} = {expr1} Like above, but only set the local value of an option (if there is one). Works like |:setlocal|. :let &g:{option-name} = {expr1} Like above, but only set the global value of an option (if there is one). Works like |:setglobal|. *E106* :let {var-name} .. List the value of variable {var-name}. Several variable names may be given. :let List the values of all variables. *:unlet* *:unl* *E108* :unl[et][!] {var-name} ... Remove the internal variable {var-name}. Several variable names can be given, they are all removed. With [!] no error message is given for non-existing variables. :if {expr1} *:if* *:endif* *:en* *E171* *E579* *E580* :en[dif] Execute the commands until the next matching ":else" or ":endif" if {expr1} evaluates to non-zero. From Vim version 4.5 until 5.0, every Ex command in between the ":if" and ":endif" is ignored. These two commands were just to allow for future expansions in a backwards compatible way. Nesting was allowed. Note that any ":else" or ":elseif" was ignored, the "else" part was not executed either. You can use this to remain compatible with older versions: > :if version >= 500 : version-5-specific-commands :endif < The commands still need to be parsed to find the "endif". Sometimes an older Vim has a problem with a new command. For example, ":silent" is recognized as a ":substitute" command. In that case ":execute" can avoid problems: > :if version >= 600 : execute "silent 1,$delete" :endif < NOTE: The ":append" and ":insert" commands don't work properly in between ":if" and ":endif". *:else* *:el* *E581* *E583* :el[se] Execute the commands until the next matching ":else" or ":endif" if they previously were not being executed. *:elseif* *:elsei* *E582* *E584* :elsei[f] {expr1} Short for ":else" ":if", with the addition that there is no extra ":endif". :wh[ile] {expr1} *:while* *:endwhile* *:wh* *:endw* *E170* *E585* *E588* :endw[hile] Repeat the commands between ":while" and ":endwhile", as long as {expr1} evaluates to non-zero. When an error is detected from a command inside the loop, execution continues after the "endwhile". NOTE: The ":append" and ":insert" commands don't work properly inside a ":while" loop. *:continue* *:con* *E586* :con[tinue] When used inside a ":while", jumps back to the ":while". If it is used after a |:try| inside the ":while" but before the matching |:finally| (if present), the commands following the ":finally" up to the matching |:endtry| are executed first. This process applies to all nested ":try"s inside the ":while". The outermost ":endtry" then jumps back to the ":while". *:break* *:brea* *E587* :brea[k] When used inside a ":while", skips to the command after the matching ":endwhile". If it is used after a |:try| inside the ":while" but before the matching |:finally| (if present), the commands following the ":finally" up to the matching |:endtry| are executed first. This process applies to all nested ":try"s inside the ":while". The outermost ":endtry" then jumps to the command after the ":endwhile". :try *:try* *:endt* *:endtry* *E600* *E601* *E602* :endt[ry] Change the error handling for the commands between ":try" and ":endtry" including everything being executed across ":source" commands, function calls, or autocommand invocations. When an error or interrupt is detected and there is a |:finally| command following, execution continues after the ":finally". Otherwise, or when the ":endtry" is reached thereafter, the next (dynamically) surrounding ":try" is checked for a corresponding ":finally" etc. Then the script processing is terminated. (Whether a function definition has an "abort" argument does not matter.) Example: > :try | edit too much | finally | echo "cleanup" | endtry :echo "impossible" " not reached, script terminated above < Moreover, an error or interrupt (dynamically) inside ":try" and ":endtry" is converted to an exception. It can be caught as if it were thrown by a |:throw| command (see |:catch|). In this case, the script processing is not terminated. The value "Vim:Interrupt" is used for an interrupt exception. An error in a Vim command is converted to a value of the form "Vim({command}):{errmsg}", other errors are converted to a value of the form "Vim:{errmsg}". {command} is the full command name, and {errmsg} is the message that is displayed if the error exception is not caught, always beginning with the error number. Examples: > :try | sleep 100 | catch /^Vim:Interrupt$/ | endtry :try | edit | catch /^Vim(edit):E\d\+/ | echo "error" | endtry < *:cat* *:catch* *E603* *E604* *E605* :cat[ch] /{pattern}/ The following commands until the next ":catch", |:finally|, or |:endtry| that belongs to the same |:try| as the ":catch" are executed when an exception matching {pattern} is being thrown and has not yet been caught by a previous ":catch". Otherwise, these commands are skipped. When {pattern} is omitted all errors are caught. Examples: > :catch /^Vim:Interrupt$/ " catch interrupts (CTRL-C) :catch /^Vim\%((\a\+)\)\=:E/ " catch all Vim errors :catch /^Vim\%((\a\+)\)\=:/ " catch errors and interrupts :catch /^Vim(write):/ " catch all errors in :write :catch /^Vim\%((\a\+)\)\=:E123/ " catch error E123 :catch /my-exception/ " catch user exception :catch /.*/ " catch everything :catch " same as /.*/ < Another character can be used instead of / around the {pattern}, so long as it does not have a special meaning (e.g., '|' or '"') and doesn't occur inside {pattern}. NOTE: It is not reliable to ":catch" the TEXT of an error message because it may vary in different locales. *:fina* *:finally* *E606* *E607* :fina[lly] The following commands until the matching |:endtry| are executed whenever the part between the matching |:try| and the ":finally" is left: either by falling through to the ":finally" or by a |:continue|, |:break|, |:finish|, or |:return|, or by an error or interrupt or exception (see |:throw|). *:th* *:throw* *E608* :th[row] {expr1} The {expr1} is evaluated and thrown as an exception. If the ":throw" is used after a |:try| but before the first corresponding |:catch|, commands are skipped until the first ":catch" matching {expr1} is reached. If there is no such ":catch" or if the ":throw" is used after a ":catch" but before the |:finally|, the commands following the ":finally" (if present) up to the matching |:endtry| are executed. If the ":throw" is after the ":finally", commands up to the ":endtry" are skipped. At the ":endtry", this process applies again for the next dynamically surrounding ":try" (which may be found in a calling function or sourcing script), until a matching ":catch" has been found. If the exception is not caught, the command processing is terminated. Example: > :try | throw "oops" | catch /^oo/ | echo "caught" | endtry < *:ec* *:echo* :ec[ho] {expr1} .. Echoes each {expr1}, with a space in between. The first {expr1} starts on a new line. Also see |:comment|. Use "\n" to start a new line. Use "\r" to move the cursor to the first column. Uses the highlighting set by the |:echohl| command. Cannot be followed by a comment. Example: > :echo "the value of 'shell' is" &shell < A later redraw may make the message disappear again. To avoid that a command from before the ":echo" causes a redraw afterwards (redraws are often postponed until you type something), force a redraw with the |:redraw| command. Example: > :new | redraw | echo "there is a new window" < *:echon* :echon {expr1} .. Echoes each {expr1}, without anything added. Also see |:comment|. Uses the highlighting set by the |:echohl| command. Cannot be followed by a comment. Example: > :echon "the value of 'shell' is " &shell < Note the difference between using ":echo", which is a Vim command, and ":!echo", which is an external shell command: > :!echo % --> filename < The arguments of ":!" are expanded, see |:_%|. > :!echo "%" --> filename or "filename" < Like the previous example. Whether you see the double quotes or not depends on your 'shell'. > :echo % --> nothing < The '%' is an illegal character in an expression. > :echo "%" --> % < This just echoes the '%' character. > :echo expand("%") --> filename < This calls the expand() function to expand the '%'. *:echoh* *:echohl* :echoh[l] {name} Use the highlight group {name} for the following |:echo|, |:echon| and |:echomsg| commands. Also used for the |input()| prompt. Example: > :echohl WarningMsg | echo "Don't panic!" | echohl None < Don't forget to set the group back to "None", otherwise all following echo's will be highlighted. *:echom* *:echomsg* :echom[sg] {expr1} .. Echo the expression(s) as a true message, saving the message in the |message-history|. Spaces are placed between the arguments as with the |:echo| command. But unprintable characters are displayed, not interpreted. Uses the highlighting set by the |:echohl| command. Example: > :echomsg "It's a Zizzer Zazzer Zuzz, as you can plainly see." < *:echoe* *:echoerr* :echoe[rr] {expr1} .. Echo the expression(s) as an error message, saving the message in the |message-history|. When used in a script or function the line number will be added. Spaces are placed between the arguments as with the :echo command. When used inside a try conditional, the message is raised as an error exception instead (see |try-echoerr|). Example: > :echoerr "This script just failed!" < If you just want a highlighted message use |:echohl|. And to get a beep: > :exe "normal \" < *:exe* *:execute* :exe[cute] {expr1} .. Executes the string that results from the evaluation of {expr1} as an Ex command. Multiple arguments are concatenated, with a space in between. {expr1} is used as the processed command, command line editing keys are not recognized. Cannot be followed by a comment. Examples: > :execute "buffer " nextbuf :execute "normal " count . "w" < ":execute" can be used to append a command to commands that don't accept a '|'. Example: > :execute '!ls' | echo "theend" < ":execute" is also a nice way to avoid having to type control characters in a Vim script for a ":normal" command: > :execute "normal ixxx\" < This has an character, see |expr-string|. Note: The executed string may be any command-line, but you cannot start or end a "while" or "if" command. Thus this is illegal: > :execute 'while i > 5' :execute 'echo "test" | break' < It is allowed to have a "while" or "if" command completely in the executed string: > :execute 'while i < 5 | echo i | let i = i + 1 | endwhile' < *:comment* ":execute", ":echo" and ":echon" cannot be followed by a comment directly, because they see the '"' as the start of a string. But, you can use '|' followed by a comment. Example: > :echo "foo" | "this is a comment ============================================================================== 8. Exception handling *exception-handling* The Vim script language comprises an exception handling feature. This section explains how it can be used in a Vim script. Exceptions may be raised by Vim on an error or on interrupt, see |catch-errors| and |catch-interrupt|. You can also explicitly throw an exception by using the ":throw" command, see |throw-catch|. TRY CONDITIONALS *try-conditionals* Exceptions can be caught or can cause cleanup code to be executed. You can use a try conditional to specify catch clauses (that catch exceptions) and/or a finally clause (to be executed for cleanup). A try conditional begins with a |:try| command and ends at the matching |:endtry| command. In between, you can use a |:catch| command to start a catch clause, or a |:finally| command to start a finally clause. There may be none or multiple catch clauses, but there is at most one finally clause, which must not be followed by any catch clauses. The lines before the catch clauses and the finally clause is called a try block. > :try : ... : ... TRY BLOCK : ... :catch /{pattern}/ : ... : ... CATCH CLAUSE : ... :catch /{pattern}/ : ... : ... CATCH CLAUSE : ... :finally : ... : ... FINALLY CLAUSE : ... :endtry The try conditional allows to watch code for exceptions and to take the appropriate actions. Exceptions from the try block may be caught. Exceptions from the try block and also the catch clauses may cause cleanup actions. When no exception is thrown during execution of the try block, the control is transferred to the finally clause, if present. After its execution, the script continues with the line following the ":endtry". When an exception occurs during execution of the try block, the remaining lines in the try block are skipped. The exception is matched against the patterns specified as arguments to the ":catch" commands. The catch clause after the first matching ":catch" is taken, other catch clauses are not executed. The catch clause ends when the next ":catch", ":finally", or ":endtry" command is reached - whatever is first. Then, the finally clause (if present) is executed. When the ":endtry" is reached, the script execution continues in the following line as usual. When an exception that does not match any of the patterns specified by the ":catch" commands is thrown in the try block, the exception is not caught by that try conditional and none of the catch clauses is executed. Only the finally clause, if present, is taken. The exception pends during execution of the finally clause. It is resumed at the ":endtry", so that commands after the ":endtry" are not executed and the exception might be caught elsewhere, see |try-nesting|. When during execution of a catch clause another exception is thrown, the remaining lines in that catch clause are not executed. The new exception is not matched against the patterns in any of the ":catch" commands of the same try conditional and none of its catch clauses is taken. If there is, however, a finally clause, it is executed, and the exception pends during its execution. The commands following the ":endtry" are not executed. The new exception might, however, be caught elsewhere, see |try-nesting|. When during execution of the finally clause (if present) an exception is thrown, the remaining lines in the finally clause are skipped. If the finally clause has been taken because of an exception from the try block or one of the catch clauses, the original (pending) exception is discarded. The commands following the ":endtry" are not executed, and the exception from the finally clause is propagated and can be caught elsewhere, see |try-nesting|. The finally clause is also executed, when a ":break" or ":continue" for a ":while" loop enclosing the complete try conditional is executed from the try block or a catch clause. Or when a ":return" or ":finish" is executed from the try block or a catch clause of a try conditional in a function or sourced script, respectively. The ":break", ":continue", ":return", or ":finish" pends during execution of the finally clause and is resumed when the ":endtry" is reached. It is, however, discarded when an exception is thrown from the finally clause. When a ":break" or ":continue" for a ":while" loop enclosing the complete try conditional or when a ":return" or ":finish" is encountered in the finally clause, the rest of the finally clause is skipped, and the ":break", ":continue", ":return" or ":finish" is executed as usual. If the finally clause has been taken because of an exception or an earlier ":break", ":continue", ":return", or ":finish" from the try block or a catch clause, this pending exception or command is discarded. For examples see |throw-catch| and |try-finally|. NESTING OF TRY CONDITIONALS *try-nesting* Try conditionals can be nested arbitrarily. That is, a complete try conditional can be put into the try block, a catch clause, or the finally clause of another try conditional. If the inner try conditional does not catch an exception thrown in its try block or throws a new exception from one of its catch clauses or its finally clause, the outer try conditional is checked according to the rules above. If the inner try conditional is in the try block of the outer try conditional, its catch clauses are checked, but otherwise only the finally clause is executed. It does not matter for nesting, whether the inner try conditional is directly contained in the outer one, or whether the outer one sources a script or calls a function containing the inner try conditional. When none of the active try conditionals catches an exception, just their finally clauses are executed. Thereafter, the script processing terminates. An error message is displayed in case of an uncaught exception explicitly thrown by a ":throw" command. For uncaught error and interrupt exceptions implicitly raised by Vim, the error message(s) or interrupt message are shown as usual. For examples see |throw-catch|. EXAMINING EXCEPTION HANDLING CODE *except-examine* Exception handling code can get tricky. If you are in doubt what happens, set 'verbose' to 13 or use the ":13verbose" command modifier when sourcing your script file. Then you see when an exception is thrown, discarded, caught, or finished. When using a verbosity level of at least 14, things pending in a finally clause are also shown. This information is also given in debug mode (see |debug-scripts|). THROWING AND CATCHING EXCEPTIONS *throw-catch* You can throw any number or string as an exception. Use the |:throw| command and pass the value to be thrown as argument: > :throw 4711 :throw "string" < *throw-expression* You can also specify an expression argument. The expression is then evaluated first, and the result is thrown: > :throw 4705 + strlen("string") :throw strpart("strings", 0, 6) An exception might be thrown during evaluation of the argument of the ":throw" command. Unless it is caught there, the expression evaluation is abandoned. The ":throw" command then does not throw a new exception. Example: > :function! Foo(arg) : try : throw a:arg : catch /foo/ : endtry : return 1 :endfunction : :function! Bar() : echo "in Bar" : return 4710 :endfunction : :throw Foo("arrgh") + Bar() This throws "arrgh", and "in Bar" is not displayed since Bar() is not executed. > :throw Foo("foo") + Bar() however displays "in Bar" and throws 4711. Any other command that takes an expression as argument might also be abandoned by an (uncaught) exception during the expression evaluation. The exception is then propagated to the caller of the command. Example: > :if Foo("arrgh") : echo "then" :else : echo "else" :endif Here neither of "then" or "else" is displayed. *catch-order* Exceptions can be caught by a try conditional with one or more |:catch| commands, see |try-conditionals|. The values to be caught by each ":catch" command can be specified as a pattern argument. The subsequent catch clause gets executed when a matching exception is caught. Example: > :function! Foo(value) : try : throw a:value : catch /^\d\+$/ : echo "Number thrown" : catch /.*/ : echo "String thrown" : endtry :endfunction : :call Foo(0x1267) :call Foo('string') The first call to Foo() displays "Number thrown", the second "String thrown". An exception is matched against the ":catch" commands in the order they are specified. Only the first match counts. So you should place the more specific ":catch" first. The following order does not make sense: > : catch /.*/ : echo "String thrown" : catch /^\d\+$/ : echo "Number thrown" The first ":catch" here matches always, so that the second catch clause is never taken. *throw-variables* If you catch an exception by a general pattern, you may access the exact value in the variable |v:exception|: > : catch /^\d\+$/ : echo "Number thrown. Value is" v:exception You may also be interested where an exception was thrown. This is stored in |v:throwpoint|. Note that "v:exception" and "v:throwpoint" are valid for the exception most recently caught as long it is not finished. Example: > :function! Caught() : if v:exception != "" : echo 'Caught "' . v:exception . '" in ' . v:throwpoint : else : echo 'Nothing caught' : endif :endfunction : :function! Foo() : try : try : try : throw 4711 : finally : call Caught() : endtry : catch /.*/ : call Caught() : throw "oops" : endtry : catch /.*/ : call Caught() : finally : call Caught() : endtry :endfunction : :call Foo() This displays > Nothing caught Caught "4711" in function Foo, line 4 Caught "oops" in function Foo, line 10 Nothing caught A practical example: The following command ":LineNumber" displays the line number in the script or function where it has been used: > :function! LineNumber() : return substitute(v:throwpoint, '.*\D\(\d\+\).*', '\1', "") :endfunction :command! LineNumber try | throw "" | catch | echo LineNumber() | endtry < *try-nested* An exception that is not caught by a try conditional can be caught by a surrounding try conditional: > :try : try : throw "foo" : catch /foobar/ : echo "foobar" : finally : echo "inner finally" : endtry :catch /foo/ : echo "foo" :endtry The inner try conditional does not catch the exception, just its finally clause is executed. The exception is then caught by the outer try conditional. The example displays "inner finally" and then "foo". *throw-from-catch* You can catch an exception and throw a new one to be caught elsewhere from the catch clause: > :function! Foo() : throw "foo" :endfunction : :function! Bar() : try : call Foo() : catch /foo/ : echo "Caught foo, throw bar" : throw "bar" : endtry :endfunction : :try : call Bar() :catch /.*/ : echo "Caught" v:exception :endtry This displays "Caught foo, throw bar" and then "Caught bar". *rethrow* There is no real rethrow in the Vim script language, but you may throw "v:exception" instead: > :function! Bar() : try : call Foo() : catch /.*/ : echo "Rethrow" v:exception : throw v:exception : endtry :endfunction < *try-echoerr* Note that this method cannot be used to "rethrow" Vim error or interrupt exceptions, because it is not possible to fake Vim internal exceptions. Trying so causes an error exception. You should throw your own exception denoting the situation. If you want to cause a Vim error exception containing the original error exception value, you can use the |:echoerr| command: > :try : try : asdf : catch /.*/ : echoerr v:exception : endtry :catch /.*/ : echo v:exception :endtry This code displays Vim(echoerr):Vim:E492: Not an editor command: asdf ~ CLEANUP CODE *try-finally* Scripts often change global settings and restore them at their end. If the user however interrupts the script by pressing CTRL-C, the settings remain in an inconsistent state. The same may happen to you in the development phase of a script when an error occurs or you explicitly throw an exception without catching it. You can solve these problems by using a try conditional with a finally clause for restoring the settings. Its execution is guaranteed on normal control flow, on error, on an explicit ":throw", and on interrupt. (Note that errors and interrupts from inside the try conditional are converted to exceptions. When not caught, they terminate the script after the finally clause has been executed.) Example: > :try : let s:saved_ts = &ts : set ts=17 : : " Do the hard work here. : :finally : let &ts = s:saved_ts : unlet s:saved_ts :endtry This method should be used locally whenever a function or part of a script changes global settings which need to be restored on failure or normal exit of that function or script part. *break-finally* Cleanup code works also when the try block or a catch clause is left by a ":continue", ":break", ":return", or ":finish". Example: > :let first = 1 :while 1 : try : if first : echo "first" : let first = 0 : continue : else : throw "second" : endif : catch /.*/ : echo v:exception : break : finally : echo "cleanup" : endtry : echo "still in while" :endwhile :echo "end" This displays "first", "cleanup", "second", "cleanup", and "end". > :function! Foo() : try : return 4711 : finally : echo "cleanup\n" : endtry : echo "Foo still active" :endfunction : :echo Foo() "returned by Foo" This displays "cleanup" and "4711 returned by Foo". You don't need to add an extra ":return" in the finally clause. (Above all, this would override the return value.) *except-from-finally* Using either of ":continue", ":break", ":return", ":finish", or ":throw" in a finally clause is possible, but not recommended since it abandons the cleanup actions for the try conditional. But, of course, interrupt and error exceptions might get raised from a finally clause. Example where an error in the finally clause stops an interrupt from working correctly: > :try : try : echo "Press CTRL-C for interrupt" : while 1 : endwhile : finally : unlet novar : endtry :catch /novar/ :endtry :echo "Script still running" :sleep 1 If you need to put commands that could fail into a finally clause, you should think about catching or ignoring the errors in these commands, see |catch-errors| and |ignore-errors|. CATCHING ERRORS *catch-errors* If you want to catch specific errors, you just have to put the code to be watched in a try block and add a catch clause for the error message. The presence of the try conditional causes all errors to be converted to an exception. No message is displayed and |v:errmsg| is not set then. To find the right pattern for the ":catch" command, you have to know how the format of the error exception is. Error exceptions have the following format: > Vim({cmdname}):{errmsg} or > Vim:{errmsg} {cmdname} is the name of the command that failed; the second form is used when the command name is not known. {errmsg} is the error message usually produced when the error occurs outside try conditionals. It always begins with a capital "E", followed by a two or three-digit error number, a colon, and a space. Examples: The command > :unlet novar normally produces the error message > E108: No such variable: "novar" which is converted inside try conditionals to an exception > Vim(unlet):E108: No such variable: "novar" The command > :dwim normally produces the error message > E492: Not an editor command: dwim which is converted inside try conditionals to an exception > Vim:E492: Not an editor command: dwim You can catch all ":unlet" errors by a > :catch /^Vim(unlet):/ or all errors for misspelled command names by a > :catch /^Vim:E492:/ Some error messages may be produced by different commands: > :function nofunc and > :delfunction nofunc both produce the error message > E128: Function name must start with a capital: nofunc which is converted inside try conditionals to an exception > Vim(function):E128: Function name must start with a capital: nofunc or > Vim(delfunction):E128: Function name must start with a capital: nofunc respectively. You can catch the error by its number independently on the command that caused it if you use the following pattern: > :catch /^Vim(\a\+):E128:/ Some commands like > :let x = novar produce multiple error messages, here: > E121: Undefined variable: novar E15: Invalid expression: novar Only the first is used for the exception value, since it is the most specific one (see |except-several-errors|). So you can catch it by > :catch /^Vim(\a\+):E121:/ You can catch all errors related to the name "nofunc" by > :catch /\/ You can catch all Vim errors in the ":write" and ":read" commands by > :catch /^Vim(\(write\|read\)):E\d\+:/ You can catch all Vim errors by the pattern > :catch /^Vim\((\a\+)\)\=:E\d\+:/ < *catch-text* NOTE: You should never catch the error message text itself: > :catch /No such variable/ only works in the english locale, but not when the user has selected a different language by the |:language| command. It is however helpful to cite the message text in a comment: > :catch /^Vim(\a\+):E108:/ " No such variable IGNORING ERRORS *ignore-errors* You can ignore errors in a specific Vim command by catching them locally: > :try : write :catch :endtry But you are strongly recommended NOT to use this simple form, since it could catch more than you want. With the ":write" command, some autocommands could be executed and cause errors not related to writing, for instance: > :au BufWritePre * unlet novar There could even be such errors you are not responsible for as a script writer: a user of your script might have defined such autocommands. You would then hide the error from the user. It is much better to use > :try : write :catch /^Vim(write):/ :endtry which only catches real write errors. So catch only what you'd like to ignore intentionally. For a single command that does not cause execution of autocommands, you could even suppress the conversion of errors to exceptions by the ":silent!" command: > :silent! nunmap k This works also when a try conditional is active. CATCHING INTERRUPTS *catch-interrupt* When there are active try conditionals, an interrupt (CTRL-C) is converted to the exception "Vim:Interrupt". You can catch it like every exception. The script is not terminated, then. Example: > :function! TASK1() : sleep 10 :endfunction :function! TASK2() : sleep 20 :endfunction :while 1 : let command = input("Type a command: ") : try : if command == "" : continue : elseif command == "END" : break : elseif command == "TASK1" : call TASK1() : elseif command == "TASK2" : call TASK2() : else : echo "\nIllegal command:" command : continue : endif : catch /^Vim:Interrupt$/ : echo "\nCommand interrupted" : " Caught the interrupt. Continue with next prompt. : endtry :endwhile You can interrupt a task here by pressing CTRL-C; the script then asks for a new command. If you press CTRL-C at the prompt, the script is terminated. For testing what happens when CTRL-C would be pressed on a specific line in your script, use the debug mode and execute the |>quit| or |>interrupt| command on that line. See |debug-scripts|. CATCHING ALL *catch-all* The commands > :catch /.*/ :catch // :catch catch everything, error exceptions, interrupt exceptions and exceptions explicitly thrown by the |:throw| command. This is useful at the top level of a script in order to catch unexpected things. Example: > :try : : " do the hard work here : :catch /MyException/ : : " handle known problem : :catch /^Vim:Interrupt$/ : echo "Script interrupted" :catch /.*/ : echo "Internal error (" . v:exception . ")" : echo " - occurred at " . v:throwpoint :endtry :" end of script Note: Catching all might catch more things than you want. Thus, you are strongly encouraged to catch only for problems that you can really handle by specifying a pattern argument to the ":catch". Example: Catching all could make it nearly impossible to interrupt a script by pressing CTRL-C: > :while 1 : try : sleep 1 : catch : endtry :endwhile EXCEPTIONS AND AUTOCOMMANDS *except-autocmd* Exceptions may be used during execution of autocommands. Example: > :autocmd User x try :autocmd User x throw "Oops!" :autocmd User x catch :autocmd User x echo v:exception :autocmd User x endtry :autocmd User x throw "Arrgh!" :autocmd User x echo "Should not be displayed" : :try : doautocmd User x :catch : echo v:exception :endtry This displays "Oops!" and "Arrgh!". *except-autocmd-Pre* For some commands, autocommands get executed before the main action of the command takes place. If an exception is thrown and not caught in the sequence of autocommands, the sequence and the command that caused its execution are abandoned and the exception is propagated to the caller of the command. Example: > :autocmd BufWritePre * throw "FAIL" :autocmd BufWritePre * echo "Should not be displayed" : :try : write :catch : echo "Caught:" v:exception "from" v:throwpoint :endtry Here, the ":write" command does not write the file currently being edited (as you can see by checking 'modified'), since the exception from the BufWritePre autocommand abandons the ":write". The exception is then caught and the script displays: > Caught: FAIL from BufWrite Auto commands for "*" < *except-autocmd-Post* For some commands, autocommands get executed after the main action of the command has taken place. If this main action fails and the command is inside an active try conditional, the autocommands are skipped and an error exception is thrown that can be caught by the caller of the command. Example: > :autocmd BufWritePost * echo "File successfully written!" : :try : write /i/m/p/o/s/s/i/b/l/e :catch : echo v:exception :endtry This just displays: > Vim(write):E212: Can't open file for writing (/i/m/p/o/s/s/i/b/l/e) If you really need to execute the autocommands even when the main action fails, trigger the event from the catch clause. Example: > :autocmd BufWritePre * set noreadonly :autocmd BufWritePost * set readonly : :try : write /i/m/p/o/s/s/i/b/l/e :catch : doautocmd BufWritePost /i/m/p/o/s/s/i/b/l/e :endtry < You can also use ":silent!": > :let x = "ok" :let v:errmsg = "" :autocmd BufWritePost * if v:errmsg != "" :autocmd BufWritePost * let x = "after fail" :autocmd BufWritePost * endif :try : silent! write /i/m/p/o/s/s/i/b/l/e :catch :endtry :echo x This displays "after fail". If the main action of the command does not fail, exceptions from the autocommands will be catchable by the caller of the command: > :autocmd BufWritePost * throw ":-(" :autocmd BufWritePost * echo "Should not be displayed" : :try : write :catch : echo v:exception :endtry < *except-autocmd-Cmd* For some commands, the normal action can be replaced by a sequence of autocommands. Exceptions from that sequence will be catchable by the caller of the command. Example: For the ":write" command, the caller cannot know whether the file had actually been written when the exception occurred. You need to tell it in some way. > :if !exists("cnt") : let cnt = 0 : : autocmd BufWriteCmd * if &modified : autocmd BufWriteCmd * let cnt = cnt + 1 : autocmd BufWriteCmd * if cnt % 3 == 2 : autocmd BufWriteCmd * throw "BufWriteCmdError" : autocmd BufWriteCmd * endif : autocmd BufWriteCmd * write | set nomodified : autocmd BufWriteCmd * if cnt % 3 == 0 : autocmd BufWriteCmd * throw "BufWriteCmdError" : autocmd BufWriteCmd * endif : autocmd BufWriteCmd * echo "File successfully written!" : autocmd BufWriteCmd * endif :endif : :try : write :catch /^BufWriteCmdError$/ : if &modified : echo "Error on writing (file contents not changed)" : else : echo "Error after writing" : endif :catch /^Vim(write):/ : echo "Error on writing" :endtry When this script is sourced several times after making changes, it displays first > File successfully written! then > Error on writing (file contents not changed) then > Error after writing etc. *except-autocmd-ill* You cannot spread a try conditional over autocommands for different events. The following code is ill-formed: > :autocmd BufWritePre * try : :autocmd BufWritePost * catch :autocmd BufWritePost * echo v:exception :autocmd BufWritePost * endtry : :write EXCEPTION HIERARCHIES AND PARAMETERIZED EXCEPTIONS *except-hier-param* Some programming languages allow to use hierarchies of exception classes or to pass additional information with the object of an exception class. You can do similar things in Vim. In order to throw an exception from a hierarchy, just throw the complete class name with the components separated by a colon, for instance throw the string "EXCEPT:MATHERR:OVERFLOW" for an overflow in a mathematical library. When you want to pass additional information with your exception class, add it in parentheses, for instance throw the string "EXCEPT:IO:WRITEERR(myfile)" for an error when writing "myfile". With the appropriate patterns in the ":catch" command, you can catch for base classes or derived classes of your hierarchy. Additional information in parentheses can be cut out from |v:exception| with the ":substitute" command. Example: > :function! CheckRange(a, func) : if a:a < 0 : throw "EXCEPT:MATHERR:RANGE(" . a:func . ")" : endif :endfunction : :function! Add(a, b) : call CheckRange(a:a, "Add") : call CheckRange(a:b, "Add") : let c = a:a + a:b : if c < 0 : throw "EXCEPT:MATHERR:OVERFLOW" : endif : return c :endfunction : :function! Div(a, b) : call CheckRange(a:a, "Div") : call CheckRange(a:b, "Div") : if (a:b == 0) : throw "EXCEPT:MATHERR:ZERODIV" : endif : return a:a / a:b :endfunction : :function! Write(file) : try : execute "write" a:file : catch /^Vim(write):/ : throw "EXCEPT:IO(" . getcwd() . ", " . a:file . "):WRITEERR" : endtry :endfunction : :try : : " something with arithmetics and I/O : :catch /^EXCEPT:MATHERR:RANGE/ : let function = substitute(v:exception, '.*(\(\a\+\)).*', '\1', "") : echo "Range error in" function : :catch /^EXCEPT:MATHERR/ " catches OVERFLOW and ZERODIV : echo "Math error" : :catch /^EXCEPT:IO/ : let dir = substitute(v:exception, '.*(\(.\+\),\s*.\+).*', '\1', "") : let file = substitute(v:exception, '.*(.\+,\s*\(.\+\)).*', '\1', "") : if file !~ '^/' : let file = dir . "/" . file : endif : echo 'I/O error for "' . file . '"' : :catch /^EXCEPT/ : echo "Unspecified error" : :endtry The exceptions raised by Vim itself (on error or when pressing CTRL-C) use a flat hierarchy: they are all in the "Vim" class. You cannot throw yourself exceptions with the "Vim" prefix; they are reserved for Vim. Vim error exceptions are parameterized with the name of the command that failed, if known. See |catch-errors|. PECULIARITIES *except-compat* The exception handling concept requires that the command sequence causing the exception is aborted immediately and control is transferred to finally clauses and/or a catch clause. In the Vim script language there are cases where scripts and functions continue after an error: in functions without the "abort" flag or in a command after ":silent!", control flow goes to the following line, and outside functions, control flow goes to the line following the outermost ":endwhile" or ":endif". On the other hand, errors should be catchable as exceptions (thus, requiring the immediate abortion). This problem has been solved by converting errors to exceptions and using immediate abortion (if not suppressed by ":silent!") only when a try conditional is active. This is no restriction since an (error) exception can be caught only from an active try conditional. If you want an immediate termination without catching the error, just use a try conditional without catch clause. (You can cause cleanup code being executed before termination by specifying a finally clause.) When no try conditional is active, the usual abortion and continuation behavior is used instead of immediate abortion. This ensures compatibility of scripts written for Vim 6.1 and earlier. However, when sourcing an existing script that does not use exception handling commands (or when calling one of its functions) from inside an active try conditional of a new script, you might change the control flow of the existing script on error. You get the immediate abortion on error and can catch the error in the new script. If however the sourced script suppresses error messages by using the ":silent!" command (checking for errors by testing |v:errmsg| if appropriate), its execution path is not changed. The error is not converted to an exception. (See |:silent|.) So the only remaining cause where this happens is for scripts that don't care about errors and produce error messages. You probably won't want to use such code from your new scripts. *except-syntax-err* Syntax errors in the exception handling commands are never caught by any of the ":catch" commands of the try conditional they belong to. Its finally clauses, however, is executed. Example: > :try : try : throw 4711 : catch /\(/ : echo "in catch with syntax error" : catch : echo "inner catch-all" : finally : echo "inner finally" : endtry :catch : echo 'outer catch-all caught "' . v:exception . '"' : finally : echo "outer finally" :endtry This displays: > inner finally outer catch-all caught "Vim(catch):E54: Unmatched \(" outer finally The original exception is discarded and an error exception is raised, instead. *except-single-line* The ":try", ":catch", ":finally", and ":endtry" commands can be put on a single line, but then syntax errors may make it difficult to recognize the "catch" line, thus you better avoid this. Example: > :try | unlet! foo # | catch | endtry raises an error exception for the trailing characters after the ":unlet!" argument, but does not see the ":catch" and ":endtry" commands, so that the error exception is discarded and the "E488: Trailing characters" message gets displayed. *except-several-errors* When several errors appear in a single command, the first error message is usually the most specific one and therefor converted to the error exception. Example: > echo novar causes > E121: Undefined variable: novar E15: Invalid expression: novar The value of the error exception inside try conditionals is: > Vim(echo):E121: Undefined variable: novar < *except-syntax-error* But when a syntax error is detected after a normal error in the same command, the syntax error is used for the exception being thrown. Example: > unlet novar # causes > E108: No such variable: "novar" E488: Trailing characters The value of the error exception inside try conditionals is: > Vim(unlet):E488: Trailing characters This is done because the syntax error might change the execution path in a way not intended by the user. Example: > try try | unlet novar # | catch | echo v:exception | endtry catch /.*/ echo "outer catch:" v:exception endtry This displays "outer catch: Vim(unlet):E488: Trailing characters", and then a "E600: Missing :endtry" error message is given, see |except-single-line|. ============================================================================== 9. Examples *eval-examples* Printing in Hex ~ > :" The function Nr2Hex() returns the Hex string of a number. :func Nr2Hex(nr) : let n = a:nr : let r = "" : while n : let r = '0123456789ABCDEF'[n % 16] . r : let n = n / 16 : endwhile : return r :endfunc :" The function String2Hex() converts each character in a string to a two :" character Hex string. :func String2Hex(str) : let out = '' : let ix = 0 : while ix < strlen(a:str) : let out = out . Nr2Hex(char2nr(a:str[ix])) : let ix = ix + 1 : endwhile : return out :endfunc Example of its use: > :echo Nr2Hex(32) result: "20" > :echo String2Hex("32") result: "3332" Sorting lines (by Robert Webb) ~ Here is a Vim script to sort lines. Highlight the lines in Vim and type ":Sort". This doesn't call any external programs so it'll work on any platform. The function Sort() actually takes the name of a comparison function as its argument, like qsort() does in C. So you could supply it with different comparison functions in order to sort according to date etc. > :" Function for use with Sort(), to compare two strings. :func! Strcmp(str1, str2) : if (a:str1 < a:str2) : return -1 : elseif (a:str1 > a:str2) : return 1 : else : return 0 : endif :endfunction :" Sort lines. SortR() is called recursively. :func! SortR(start, end, cmp) : if (a:start >= a:end) : return : endif : let partition = a:start - 1 : let middle = partition : let partStr = getline((a:start + a:end) / 2) : let i = a:start : while (i <= a:end) : let str = getline(i) : exec "let result = " . a:cmp . "(str, partStr)" : if (result <= 0) : " Need to put it before the partition. Swap lines i and partition. : let partition = partition + 1 : if (result == 0) : let middle = partition : endif : if (i != partition) : let str2 = getline(partition) : call setline(i, str2) : call setline(partition, str) : endif : endif : let i = i + 1 : endwhile : " Now we have a pointer to the "middle" element, as far as partitioning : " goes, which could be anywhere before the partition. Make sure it is at : " the end of the partition. : if (middle != partition) : let str = getline(middle) : let str2 = getline(partition) : call setline(middle, str2) : call setline(partition, str) : endif : call SortR(a:start, partition - 1, a:cmp) : call SortR(partition + 1, a:end, a:cmp) :endfunc :" To Sort a range of lines, pass the range to Sort() along with the name of a :" function that will compare two lines. :func! Sort(cmp) range : call SortR(a:firstline, a:lastline, a:cmp) :endfunc :" :Sort takes a range of lines and sorts them. :command! -nargs=0 -range Sort ,call Sort("Strcmp") < *sscanf* There is no sscanf() function in Vim. If you need to extract parts from a line, you can use matchstr() and substitute() to do it. This example shows how to get the file name, line number and column number out of a line like "foobar.txt, 123, 45". > :" Set up the match bit :let mx='\(\f\+\),\s*\(\d\+\),\s*\(\d\+\)' :"get the part matching the whole expression :let l = matchstr(line, mx) :"get each item out of the match :let file = substitute(l, mx, '\1', '') :let lnum = substitute(l, mx, '\2', '') :let col = substitute(l, mx, '\3', '') The input is in the variable "line", the results in the variables "file", "lnum" and "col". (idea from Michael Geddes) ============================================================================== 10. No +eval feature *no-eval-feature* When the |+eval| feature was disabled at compile time, none of the expression evaluation commands are available. To prevent this from causing Vim scripts to generate all kinds of errors, the ":if" and ":endif" commands are still recognized, though the argument of the ":if" and everything between the ":if" and the matching ":endif" is ignored. Nesting of ":if" blocks is allowed, but only if the commands are at the start of the line. The ":else" command is not recognized. Example of how to avoid executing commands when the |+eval| feature is missing: > :if 1 : echo "Expression evaluation is compiled in" :else : echo "You will _never_ see this message" :endif ============================================================================== 11. The sandbox *eval-sandbox* *sandbox* *E48* The 'foldexpr', 'includeexpr', 'indentexpr', 'statusline' and 'foldtext' options are evaluated in a sandbox. This means that you are protected from these expressions having nasty side effects. This gives some safety for when these options are set from a modeline. It is also used when the command from a tags file is executed. This is not guaranteed 100% secure, but it should block most attacks. These items are not allowed in the sandbox: - changing the buffer text - defining or changing mapping, autocommands, functions, user commands - setting certain options (see |option-summary|) - executing a shell command - reading or writing a file - jumping to another buffer or editing a file vim:tw=78:ts=8:ft=help:norl: