Vim Documentation: eval


       For Vim version 5.0p.  Last modification: 1997 Oct 19


		  VIM REFERENCE MANUAL    by Bram Moolenaar


Expression evaluation					 

Note: Expression evaluation can be disabled at compile time.  If this has been
done, all the features in this document are not available.

1. Variables		|variables|
2. Expression syntax	|expression-syntax|
3. Internal variable	|internal-variables|
4. Function calls	|functions|
5. Commands		|expression-commands|

{Vi does not have any of these commands}


1. 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 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")
2. Expression syntax Expression syntax summary, from least to most significant: |expr1| expr2 || expr2 .. logical OR |expr2| expr3 && expr3 .. logical AND |expr3| expr4 == expr4 equal expr4 != expr4 not equal expr4 > expr4 greater than expr4 >= expr4 greater than or equal expr4 < expr4 smaller than expr4 <= expr4 smaller than or equal expr4 =~ expr4 regexp matches expr4 !~ expr4 regexp doesn't match |expr4| expr5 + expr5 .. number addition expr5 - expr5 .. number subtraction expr5 . expr5 .. string concatenation |expr5| expr6 * expr6 .. number multiplication expr6 / expr6 .. number division expr6 % expr6 .. number modulo |expr6| ! expr6 logical NOT - expr6 unary minus |expr7| expr8[expr1] index in String || number number constant "string" string constant 'string' literal string constant &option option value (expr1) nested expression variable internal variable $VAR environment variable @r contents of register 'r' function(expr1, expr1) function call ".." 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 and expr2
The "||" and "&&" operators take one argument on each side. The arguments are (converted to) Numbers. The result is: 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") All arguments are computed, there is no skipping if the value of an argument doesn't matter, because the result is already known. This is different from C, although it only matters for errors (unknown variables), since there are no side effects from an expression. expr3
expr4 == expr4 equal expr4 != expr4 not equal expr4 > expr4 greater than expr4 >= expr4 greater than or equal expr4 < expr4 smaller than expr4 <= expr4 smaller than or equal expr4 =~ expr4 regexp matches expr4 !~ expr4 regexp doesn't match When comparing a String with a Number, the String is converted to a Number, and the comparison is done on Numbers. When comparing two Strings, this is done with strcmp(). This results in the mathematical difference, not necessarily the alphabetical difference in the local language. The "=~" and "!~" operators match the lefthand argument with the righthand argument, which is used as a pattern. See |pattern| for what a pattern is. This matching is always done like 'magic' was set, no matter what the actual value of 'magic' is. This makes scripts portable. The value of 'ignorecase' does matter though. To avoid backslashes in the regexp pattern to be doubled, use a backtick-string, see |literal-string|. expr4 and expr5
expr5 + expr5 .. number addition expr5 - expr5 .. number subtraction expr5 . expr5 .. string concatenation expr6 * expr6 .. number multiplication expr6 / expr6 .. number division expr6 % expr6 .. number modulo For all, except ".", Strings are converted to Numbers. Note the difference between "+" and ".": "123" + "456" = 579 "123" . "456" = "123456" When the righthand side of '/' is zero, the result is 0xfffffff. When the righthand side of '%' is zero, the result is 0. expr6
! expr6 logical NOT - expr6 unary minus For '!' non-zero becomes zero, zero becomes one. For '-' the sign of the number is changed. A String will be converted to a Number first. These two can be repeated and mixed. Examples: !-1 == 0 !!8 == 1 --9 == 9 expr7
expr8[expr1] index in String This results in a String that contains the expr1'th single character from expr8. expr8 is used as a String, expr1 as a Number. Note that index zero gives the first character. This is like it works in C. Careful: column numbers start with one! Example, to get the character under the cursor: > c = getline(line("."))[col(".") - 1] If the length of the String is less than the index, the result is an empty String. number
number number constant Decimal, Hexadecimal (starting with 0x or 0X), or Octal (starting with 0). string
"string" string constant Note that double quotes are used. A string constant accepts these special characters: \xxx three-digit octal number \xx two-digit octal number (must be followed by non-digit) \x one-digit octal number (must be followed by non-digit) \b backspace <BS> \e escape <Esc> \f formfeed <FF> \n newline <NL> \r return <CR> \t tab <Tab> \\ backslash literal-string
'string' literal string constant Note that single quotes are used. This string is taken literal. No backslashes are removed or have a special meaning. A literal-string cannot contain a single quote. Use a normal string for that. option
&option option value Any option name can be used here. See |options|. 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 @@. The '=' register can not be used here. See |registers| for an explanation of the available registers. nesting
(expr1) nested expression environment variable
$VAR environment variable The String value of any environment variable. When it is not defined, the result is an empty string. internal variable
variable internal variable See below |internal-variables|. function call
function(expr1, expr1) function call See below |functions|.
3. Internal variable An internal variable name can be made up of letters, digits and '_'. But it cannot start with a digit. 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. A variable name that is preceded with "b:" is local to the current buffer. A variable name that is preceded with "w:" is local to the current window. Predefined variables: count The count given for the last Normal mode command. Can be used to get the count before a mapping. Example: > :map _x :<C-U>echo "the count is " . count<CR> Note: The <C-U> is required to remove the line range that you get when typing ':' after a count. read-only. errmsg Last given error message. It's allowed to set this variable. Example: > :let errmsg = "" > :next > :if (errmsg != "") > : ... version Version number of Vim times 100. Version 5.0 is 500. Version 4.5 is 405. Read-only.
4. Function calls USAGE RESULT DESCRIPTION buffer_exists({expr}) Number TRUE if a buffer {exp} exists col({expr}) Number column nr of cursor or mark exists({var}) Number TRUE if {var} exists expand({expr}) String expand file wildcards in {expr} file_readable({file}) String TRUE if {file} a a readable file getline({lnum}) String line {lnum} from current buffer has({feature}) Number TRUE if feature {feature} supported highlight_exists({name}) Number TRUE if highlight group {name} exists last_buffer_nr() Number buffer number of last buffer line({expr}) Number line nr of cursor, last line or mark match({expr}, {pat}) Number position where {pat} matches in {expr} matchend({expr}, {pat}) Number position where {pat} ends in {expr} strftime({expr}) String current time in specified format strlen({expr}) Number length of the String {expr} strpart({src}, {start}, {len}) String {len} characters of {src} at {start} substitute({expr}, {pat}, {sub}) String all {pat} in {expr} replaced with {sub} virtcol({expr}) Number screen column of cursor or mark buffer_exists({var}) The result is a Number, which is non-zero if a buffer called {var} exists. If the {var} argument is a string it must match a buffer name exactly. If the {var} argument is a number buffer numbers are used. Use "buffer_exists(0)" to test for the existence of an alternate file name. col({expr}) The result is a Number, which is the column of the file position given with {expr}. The accepted positions are: . the cursor position '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: > col(".") column of cursor > col("'t") column of mark t > col("'" . markname) column of mark markname The first column is 1. 0 is returned for an error. exists({expr}) The result is a Number, which is 1 if {var} is defined, zero otherwise. The {expr} argument is a string, which contains one of these: &option-name Vim option $ENVNAME environment variable (could also be done by comparing with an empty string) varname internal variable (see |internal-variables|). Examples: > exists("&shortname") > exists("$HOSTNAME") > exists("bufcount") Note that the argument must be a string, not the name itself! expand({expr}) Expand the file wildcards in {expr}. The result is a String. Example: > :let &tags = expand("`find . -name tags -print`") When the result of {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 <cfile> file name under the cursor <afile> autocmd file name <sfile> sourced script file name <cword> word under the cursor <cWORD> WORD under the cursor 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" There cannot be white space between the variables and the following modifier. 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. file_readable({file}) 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. 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. 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. highlight_exists({name}) 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. last_buffer_nr() 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 ":bdel" may have removed them. Use buffer_exists() to test for the existence of a buffer. 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 strftime({format}) The result is a String, which is the current date and time, as specified by the {format} string. See the manual page of the C function strftime() for the format. The maximum length of the result is 80 characters. Examples: > :echo strftime("%c") Sun Apr 27 11:49:23 1997 > :echo strftime("%Y %b %d %X") 1997 Apr 27 11:53:25 match({expr}, {pat}) The result is a Number, which gives the index in {expr} where {pat} matches. If there is no match -1 is returned. Example: > :echo match("testing", "ing") results in "4". See |pattern| for the patterns that are accepted. matchend({expr}, {pat}) Same as match(), but return the index of first character after the match. Example: > :echo matchend("testing", "ing") results in "7". strlen({expr}) The result is a Number, which is the length of the String {expr}. strpart({src}, {start}, {len}) The result is a String, which is part of {src}, starting from character {start}, with the length {len}. When non-existing characters are included, this doesn't result in an error, the characters are simply omitted. > strpart("abcdefg", 3, 2) == "de" > strpart("abcdefg", -2, 4) == "ab" > strpart("abcdefg", 5, 4) == "fg" substitute({expr}, {pat}, {sub}) 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). When {pat} does not match in {expr}, {expr} is returned unmodified. Example: > :let &path = substitute(&path, ",\\=[^,]*$", "") This removes the last component of the 'path' option. > :echo substitute("testing", ".*", "\\U\\0") results in "TESTING". virtcol({expr}) 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 <Tab> at the position, the returned Number will be the column at the end of the <Tab>. For example, for a <Tab> in column 1, with 'ts' set to 8, it returns 8; The accepted positions are: . the cursor position '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("'t") with text " there", with 't at 'h', returns 6 There are two types of features: 1. Features that are only supported when they have been enabled when Vim was compiled. Example: > :if has("cindent") 2. Features that are only supported when certain conditions have been met. Example: > :if has("gui_running") all_builtin_terms Vim was compiled with all builtin terminals enabled. amiga Amiga version of Vim. arp Vim was compiled with ARP support (Amiga). autocmd Vim was complied with autocommands support. builtin_terms Vim was compiled with some builtin terminals. cindent Vim was compiled with 'cindent' support. compatible Vim was compiled to be very Vi compatible. debug Vim was compiled with "DEBUG" defined. digraphs Vim was compiled with support for digraphs. dos32 32 bits DOS (DJGPP) version of Vim. dos16 16 bits DOS version of Vim. emacs_tags Vim was compiled with support for Emacs tags. fork Vim was compiled to use fork()/exec() instead of system(). gui Vim was compiled with GUI enabled. gui_athena Vim was compiled with Athena GUI. gui_motif Vim was compiled with Motif GUI. gui_win32 Vim was compiled with MS Windows Win32 GUI. gui_running Vim is running in the GUI, or it will start soon. insert_expand Vim was compiled with support for CTRL-X expansion commands in Insert mode. langmap Vim was compiled with 'langmap' support. lispindent Vim was compiled with support for lisp indenting. perl Vim was compiled with Perl interface. python Vim was compiled with Python interface. rightleft Vim was compiled with 'rightleft' support. smartindent Vim was compiled with 'smartindent' support. syntax Vim was compiled with syntax highlighting support. syntax_items There are active syntax highlighting items for the current buffer. system Vim was compiled to use system() instead of fork()/exec(). terminfo Vim was compiled with terminfo instead of termcap. tgetent Vim was compiled with tgetent support, able to use a termcap or terminfo file. unix Unix version of Vim. viminfo Vim was compiled with viminfo support. win32 Win32 version of Vim (Windows 95/NT) writebackup Vim was compiled with 'writebackup' default on. x11 Vim was compiled with X11 support.
5. Commands :let {var-name} = {expr1} 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} Set environment variable {env-name} to the result of the expression {expr1}. The type is always String. :let @{reg-name} = {expr1} 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. If the result of {expr1} ends in a newline, the register will be linewise, otherwise it will be set to characterwise. :let &{option-name} = {expr1} Set option {option-name} to the result of the expression {expr1}. The type of the option is always used. :unl[et] {var-name} Remove the internal variable {var-name}. :if {expr1} :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 :else Execute the commands until the next matching ":else" or ":endif" if they previously were not being executed. :elsei[f] {expr1} Short for ":else" ":if", with the addition that there is no extra ":endif". :wh[ile] {expr1} :endw[hile] Repeat the commands between ":while" and ":endwhile", as long as {expr1} evaluates to non-zero. NOTE: The ":append" and ":insert" commands don't work properly inside a ":while" loop. :con[tinue] When used inside a ":while", jumps back to the ":while". :brea[k] When used inside a ":while", skips to the command after the matching ":endwhile". :ec[ho] {expr1} .. Echoes each {expr1}, with a space in between and a terminating newline. Example: > :echo "the value of 'shell' is" &shell :echon {expr1} .. Echoes each {expr1}, without anything added. Example: > :echon "the value of 'shell' is " &shell :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. Examples: > :execute "buffer" nextbuf > :execute "normal" count . "w" Execute can be used to append a next command to commands that don't accept a '|'. Example: > :execute '!ls' | echo "theend" 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 || let i = i + 1 | endwhile'

Generated by vim2html on Mon Nov 3 03:34:24 EST 1997