1 *eval.txt* For Vim version 5.8. Last change: 2001 May 29
4 VIM REFERENCE MANUAL by Bram Moolenaar
7 Expression evaluation *expression* *expr*
9 Note: Expression evaluation can be disabled at compile time. If this has been
10 done, the features in this document are not available. See |+eval| and the
13 1. Variables |variables|
14 2. Expression syntax |expression-syntax|
15 3. Internal variable |internal-variables|
16 4. Builtin Functions |functions|
17 5. Defining functions |user-functions|
18 6. Commands |expression-commands|
19 7. Examples |eval-examples|
20 8. No +eval feature |no-eval-feature|
22 {Vi does not have any of these commands}
24 ==============================================================================
25 1. Variables *variables*
27 There are two types of variables:
29 Number a 32 bit signed number.
30 String a NUL terminated string of 8-bit unsigned characters.
32 These are converted automatically, depending on how they are used.
34 Conversion from a Number to a String is by making the ASCII representation of
36 > Number 123 --> String "123"
37 > Number 0 --> String "0"
38 > Number -1 --> String "-1"
40 Conversion from a String to a Number is done by converting the first digits
41 to a number. Hexadecimal "0xf9" and Octal "017" numbers are recognized. If
42 the String doesn't start with digits, the result is zero. Examples:
43 > String "456" --> Number 456
44 > String "6bar" --> Number 6
45 > String "foo" --> Number 0
46 > String "0xf1" --> Number 241
47 > String "0100" --> Number 64
49 To force conversion from String to Number, add zero to it:
52 For boolean operators Numbers are used. Zero is FALSE, non-zero is TRUE.
54 Note that in the command
56 "foo" is converted to 0, which means FALSE. To test for a non-empty string,
60 When the '!' flag is included in the 'viminfo' option, global variables that
61 start with an uppercase letter, and don't contain a lowercase letter, are
62 stored in the viminfo file |viminfo-file|.
64 When the 'sessionoptions' option contains "global", global variables that
65 start with an uppercase letter and contain at least one lowercase letter are
66 stored in the session file |session-file|.
68 variable name can be stored where ~
73 ==============================================================================
74 2. Expression syntax *expression-syntax*
76 Expression syntax summary, from least to most significant:
78 |expr1| expr2 || expr2 .. logical OR
80 |expr2| expr3 && expr3 .. logical AND
82 |expr3| expr4 == expr4 equal
83 expr4 != expr4 not equal
84 expr4 > expr4 greater than
85 expr4 >= expr4 greater than or equal
86 expr4 < expr4 smaller than
87 expr4 <= expr4 smaller than or equal
88 expr4 =~ expr4 regexp matches
89 expr4 !~ expr4 regexp doesn't match
90 expr4 ==? expr4 equal, ignoring case
91 expr4 ==# expr4 equal, match case
92 etc. As above, append ? for ignoring case, # for matching case
94 |expr4| expr5 + expr5 .. number addition
95 expr5 - expr5 .. number subtraction
96 expr5 . expr5 .. string concatenation
98 |expr5| expr6 * expr6 .. number multiplication
99 expr6 / expr6 .. number division
100 expr6 % expr6 .. number modulo
102 |expr6| ! expr6 logical NOT
106 |expr7| expr8[expr1] index in String
108 |expr8| number number constant
109 "string" string constant
110 'string' literal string constant
112 (expr1) nested expression
113 variable internal variable
114 $VAR environment variable
115 @r contents of register 'r'
116 function(expr1, ...) function call
118 ".." indicates that the operations in this level can be concatenated.
120 > &nu || &list && &shell == "csh"
122 All expressions within one level are parsed from left to right.
125 expr1 and expr2 *expr1* *expr2*
128 *expr-barbar* *expr-&&*
129 The "||" and "&&" operators take one argument on each side. The arguments
130 are (converted to) Numbers. The result is:
133 n1 n2 n1 || n2 n1 && n2 ~
135 zero non-zero non-zero zero
136 non-zero zero non-zero zero
137 non-zero non-zero non-zero non-zero
139 The operators can be concatenated, for example:
141 > &nu || &list && &shell == "csh"
143 Note that "&&" takes precedence over "||", so this has the meaning of:
145 > &nu || (&list && &shell == "csh")
147 Once the result is known, the expression "short-circuits", that is, further
148 arguments are not evaluated. This is like what happens in C. For example:
153 This is valid even if there is no variable called "b" because "a" is non-zero,
154 so the result must be non-zero. Similarly below:
156 > echo exists("b") && b == "yes"
158 This is valid whether "b" has been defined or not. The second clause will
159 only be evaluated if "b" has been defined.
167 Compare two expr4 expressions, resulting in a 0 if it evaluates to false, or 1
168 if it evaluates to true.
170 *expr-==* *expr-!=* *expr->* *expr->=*
171 *expr-<* *expr-<=* *expr-=~* *expr-!~*
172 *expr-==#* *expr-!=#* *expr->#* *expr->=#*
173 *expr-<#* *expr-<=#* *expr-=~#* *expr-!~#*
174 *expr-==?* *expr-!=?* *expr->?* *expr->=?*
175 *expr-<?* *expr-<=?* *expr-=~?* *expr-!~?*
176 use 'ignorecase' match case ignore case ~
180 greater than or equal >= >=# >=?
182 smaller than or equal <= <=# <=?
183 regexp matches =~ =~# =~?
184 regexp doesn't match !~ !~# !~?
187 "abc" ==# "Abc" evaluates to 0
188 "abc" ==? "Abc" evaluates to 1
189 "abc" == "Abc" evaluates to 1 if 'ignorecase' is set, 0 otherwise
191 When comparing a String with a Number, the String is converted to a Number,
192 and the comparison is done on Numbers.
194 When comparing two Strings, this is done with strcmp() or stricmp(). This
195 results in the mathematical difference (comparing byte values), not
196 necessarily the alphabetical difference in the local language.
198 When using the operators with a trailing '#", or the short version and
199 'ignorecase' is off, the comparing is done with strcmp().
201 When using the operators with a trailing '?', or the short version and
202 'ignorecase' is set, the comparing is done with stricmp().
204 The "=~" and "!~" operators match the lefthand argument with the righthand
205 argument, which is used as a pattern. See |pattern| for what a pattern is.
206 This matching is always done like 'magic' was set and 'cpoptions' is empty, no
207 matter what the actual value of 'magic' or 'cpoptions' is. This makes scripts
208 portable. To avoid backslashes in the regexp pattern to be doubled, use a
209 single-quote string, see |literal-string|.
212 expr4 and expr5 *expr4* *expr5*
214 expr5 + expr5 .. number addition *expr-+*
215 expr5 - expr5 .. number subtraction *expr--*
216 expr5 . expr5 .. string concatenation *expr-.*
218 expr6 * expr6 .. number multiplication *expr-star*
219 expr6 / expr6 .. number division *expr-/*
220 expr6 % expr6 .. number modulo *expr-%*
222 For all, except ".", Strings are converted to Numbers.
224 Note the difference between "+" and ".":
226 "123" . "456" = "123456"
228 When the righthand side of '/' is zero, the result is 0xfffffff.
229 When the righthand side of '%' is zero, the result is 0.
234 ! expr6 logical NOT *expr-!*
235 - expr6 unary minus *expr-unary--*
237 For '!' non-zero becomes zero, zero becomes one.
238 For '-' the sign of the number is changed.
240 A String will be converted to a Number first.
242 These two can be repeated and mixed. Examples:
250 expr8[expr1] index in String *expr-[]*
252 This results in a String that contains the expr1'th single character from
253 expr8. expr8 is used as a String, expr1 as a Number.
255 Note that index zero gives the first character. This is like it works in C.
256 Careful: column numbers start with one! Example, to get the character under
258 > c = getline(line("."))[col(".") - 1]
260 If the length of the String is less than the index, the result is an empty
266 number number constant *expr-number*
268 Decimal, Hexadecimal (starting with 0x or 0X), or Octal (starting with 0).
273 "string" string constant *expr-quote*
275 Note that double quotes are used.
277 A string constant accepts these special characters:
278 \... three-digit octal number (e.g., "\316")
279 \.. two-digit octal number (must be followed by non-digit)
280 \. one-digit octal number (must be followed by non-digit)
281 \x.. two-character hex number (e.g., "\x1f")
282 \x. one-character hex number (must be followed by non-hex)
293 \<xxx> Special key named "xxx". e.g. "\<C-W>" for CTRL-W.
295 Note that "\000" and "\x00" force the end of the string.
298 literal-string *literal-string*
300 'string' literal string constant *expr-'*
302 Note that single quotes are used.
304 This string is taken literally. No backslashes are removed or have a special
305 meaning. A literal-string cannot contain a single quote. Use a normal string
313 Any option name can be used here. See |options|.
316 register *expr-register*
318 @r contents of register 'r'
320 The result is the contents of the named register, as a single string.
321 Newlines are inserted where required. To get the contents of the unnamed
322 register use @@. The '=' register can not be used here. See |registers| for
323 an explanation of the available registers.
326 nesting *expr-nesting*
328 (expr1) nested expression
331 environment variable *expr-env*
333 $VAR environment variable
335 The String value of any environment variable. When it is not defined, the
336 result is an empty string.
338 Note that there is a difference between using $VAR directly and using
339 expand("$VAR"). Using it directly will only expand environment variables that
340 are known inside the current Vim session. Using expand() will first try using
341 the environment variables known inside the current Vim session. If that
342 fails, a shell will be used to expand the variable. This can be slow, but it
343 does expand all variables that the shell knows about. Example:
345 > echo expand("$version")
346 The first one probably doesn't echo anything, the second echoes the $version
347 variable (if your shell supports it).
350 internal variable *expr-variable*
352 variable internal variable
353 See below |internal-variables|.
356 function call *expr-function*
358 function(expr1, ...) function call
359 See below |functions|.
362 ==============================================================================
363 3. Internal variable *internal-variables*
365 An internal variable name can be made up of letters, digits and '_'. But it
366 cannot start with a digit.
368 An internal variable is created with the ":let" command |:let|.
369 An internal variable is destroyed with the ":unlet" command |:unlet|.
370 Using a name that isn't an internal variable, or an internal variable that has
371 been destroyed, results in an error.
373 A variable name that is preceded with "b:" is local to the current buffer.
374 Thus you can have several "b:foo" variables, one for each buffer.
375 This kind of variable is deleted when the buffer is unloaded. If you want to
376 keep it, avoid that the buffer is unloaded by setting the 'hidden' option.
378 A variable name that is preceded with "w:" is local to the current window. It
379 is deleted when the window is closed.
381 Inside functions global variables are accessed with "g:".
383 Predefined Vim variables:
384 *v:count* *count-variable*
385 v:count The count given for the last Normal mode command. Can be used
386 to get the count before a mapping. Read-only. Example:
387 > :map _x :<C-U>echo "the count is " . count<CR>
388 Note: The <C-U> is required to remove the line range that you
389 get when typing ':' after a count.
390 "count" also works, for backwards compatibility.
392 *v:count1* *count1-variable*
393 v:count1 Just like "v:count", but defaults to one when no count is
396 *v:errmsg* *errmsg-variable*
397 v:errmsg Last given error message. It's allowed to set this variable.
403 "errmsg" also works, for backwards compatibility.
405 *v:warningmsg* *warningmsg-variable*
406 v:warningmsg Last given warning message. It's allowed to set this variable.
408 *v:statusmsg* *statusmsg-variable*
409 v:statusmsg Last given status message. It's allowed to set this variable.
411 *v:shell_error* *shell_error-variable*
412 v:shell_error Result of the last shell command. When non-zero, the last
413 shell command had an error. When zero, there was no problem.
414 This only works when the shell returns the error code to Vim.
415 The value -1 is often used when the command could not be
420 > : echo 'could not rename "foo" to "bar"!'
422 "shell_error" also works, for backwards compatibility.
424 *v:this_session* *this_session-variable*
425 v:this_session Full filename of the last loaded or saved session file. See
426 |:mksession|. It is allowed to set this variable. When no
427 session file has been saved, this variable is empty.
428 "this_session" also works, for backwards compatibility.
430 *v:version* *version-variable*
431 v:version Version number of Vim: Major version number times 100 plus
432 minor version number. Version 5.0 is 500. Version 5.1 (5.01)
433 is 501. Read-only. "version" also works, for backwards
436 ==============================================================================
437 4. Builtin Functions *functions*
439 (Use CTRL-] on the function name to jump to the full explanation)
441 USAGE RESULT DESCRIPTION ~
443 append( {lnum}, {string}) Number append {string} below line {lnum}
444 argc() Number number of files in the argument list
445 argv( {nr}) String {nr} entry of the argument list
446 browse( {save}, {title}, {initdir}, {default})
447 String put up a file requester
448 bufexists( {expr}) Number TRUE if buffer {expr} exists
449 bufloaded( {expr}) Number TRUE if buffer {expr} is loaded
450 bufname( {expr}) String Name of the buffer {expr}
451 bufnr( {expr}) Number Number of the buffer {expr}
452 bufwinnr( {nr}) Number window number of buffer {nr}
453 byte2line( {byte}) Number line number at byte count {byte}
454 char2nr( {expr}) Number ASCII value of first char in {expr}
455 col( {expr}) Number column nr of cursor or mark
456 confirm( {msg}, {choices} [, {default} [, {type}]])
457 Number number of choice picked by user
458 delete( {fname}) Number delete file {fname}
459 did_filetype() Number TRUE if FileType autocommand event used
460 escape( {string}, {chars}) String escape {chars} in {string} with '\'
461 exists( {var}) Number TRUE if {var} exists
462 expand( {expr}) String expand special keywords in {expr}
463 filereadable( {file}) Number TRUE if {file} is a readable file
464 fnamemodify( {fname}, {mods}) String modify file name
465 getcwd() String the current working directory
466 getftime( {fname}) Number last modification time of file
467 getline( {lnum}) String line {lnum} from current buffer
468 getwinposx() Number X coord in pixels of GUI vim window
469 getwinposy() Number Y coord in pixels of GUI vim window
470 glob( {expr} [, {flag}]) String expand file wildcards in {expr}
471 has( {feature}) Number TRUE if feature {feature} supported
472 histadd( {history},{item}) String add an item to a history
473 histdel( {history} [, {item}]) String remove an item from a history
474 histget( {history} [, {index}]) String get the item {index} from a history
475 histnr( {history}) Number highest index of a history
476 hlexists( {name}) Number TRUE if highlight group {name} exists
477 hlID( {name}) Number syntax ID of highlight group {name}
478 hostname() String name of the machine vim is running on
479 input( {prompt}) String get input from the user
480 isdirectory( {directory}) Number TRUE if {directory} is a directory
481 libcall( {lib}, {func}, {arg} String call {func} in library {lib}
482 line( {expr}) Number line nr of cursor, last line or mark
483 line2byte( {lnum}) Number byte count of line {lnum}
484 localtime() Number current time
485 maparg( {name}[, {mode}]) String rhs of mapping {name} in mode {mode}
486 mapcheck( {name}[, {mode}]) String check for mappings matching {name}
487 match( {expr}, {pat}) Number position where {pat} matches in {expr}
488 matchend( {expr}, {pat}) Number position where {pat} ends in {expr}
489 matchstr( {expr}, {pat}) String match of {pat} in {expr}
490 nr2char( {expr}) String single char with ASCII value {expr}
491 rename({from}, {to}) Number rename (move) file from {from} to {to}
492 setline( {lnum}, {line}) Number set line {lnum} to {line}
493 strftime( {format}[, {time}]) String time in specified format
494 strlen( {expr}) Number length of the String {expr}
495 strpart( {src}, {start}, {len}) String {len} characters of {src} at {start}
496 strtrans( {expr}) String translate sting to make it printable
497 substitute( {expr}, {pat}, {sub}, {flags})
498 String all {pat} in {expr} replaced with {sub}
499 synID( {line}, {col}, {trans}) Number syntax ID at {line} and {col}
500 synIDattr( {synID}, {what} [, {mode}])
501 String attribute {what} of syntax ID {synID}
502 synIDtrans( {synID}) Number translated syntax ID of {synID}
503 system( {expr}) String output of shell command {expr}
504 tempname() String name for a temporary file
505 virtcol( {expr}) Number screen column of cursor or mark
506 visualmode() String last visual mode used
507 winbufnr( {nr}) Number buffer number of window {nr}
508 winheight( {nr}) Number height of window {nr}
509 winnr() Number number of current window
511 append({lnum}, {string} *append()*
512 Append the text {string} after line {lnum} in the current
513 buffer. {lnum} can be zero, to insert a line before the first
514 one. Returns 1 for failure ({lnum} out of range) or 0 for
518 argc() The result is the number of files in the argument list. See
522 argv({nr}) The result is the {nr}th file in the argument list. See
523 |arglist|. "argv(0)" is the first one. Example:
526 > let f = substitute(argv(i), '\([. ]\)', '\\&', 'g')
527 > exe 'amenu Arg.' . f . ' :e ' . f . '<CR>'
532 browse({save}, {title}, {initdir}, {default})
533 Put up a file requester. This only works when "has("browse")"
534 returns non-zero (only in some GUI versions).
535 The input fields are:
536 {save} when non-zero, select file to write
537 {title} title for the requester
538 {initdir} directory to start browsing in
539 {default} default file name
540 When the "Cancel" button is hit, something went wrong, or
541 browsing is not possible, an empty string is returned.
545 The result is a Number, which is non-zero if a buffer called
546 {expr} exists. If the {expr} argument is a string it must
547 match a buffer name exactly. If the {expr} argument is a
548 number buffer numbers are used. Use "bufexists(0)" to test
549 for the existence of an alternate file name.
551 Obsolete name: buffer_exists().
555 The result is a Number, which is non-zero if a buffer called
556 {expr} exists and is loaded (shown in a window or hidden).
557 The {expr} argument is used like with bufexists().
561 The result is the name of a buffer, as it is displayed by the
563 If {expr} is a Number, that buffer number's name is given.
564 Number zero is the alternate buffer for the current window.
565 If {expr} is a String, it is used as a regexp pattern to match
566 with the buffer names. This is always done like 'magic' is
567 set and 'cpoptions' is empty. When there is more than one
568 match an empty string is returned. "" or "%" can be used for
569 the current buffer, "#" for the alternate buffer.
570 If the {expr} is a String, but you want to use it as a buffer
571 number, force it to be a Number by adding zero to it:
572 > echo bufname("3" + 0)
573 If the buffer doesn't exist, or doesn't have a name, an empty
575 > bufname("#") alternate buffer name
576 > bufname(3) name of buffer 3
577 > bufname("%") name of current buffer
578 > bufname("file2") name of buffer where "file2" matches.
580 Obsolete name: buffer_name().
583 bufnr({expr}) The result is the number of a buffer, as it is displayed by
584 the ":ls" command. For the use of {expr}, see bufname()
585 above. If the buffer doesn't exist, -1 is returned.
586 bufnr("$") is the last buffer:
587 > :let last_buffer = bufnr("$")
588 The result is a Number, which is the highest buffer number
589 of existing buffers. Note that not all buffers with a smaller
590 number necessarily exist, because ":bdel" may have removed
591 them. Use bufexists() to test for the existence of a buffer.
593 Obsolete name: buffer_number().
595 Obsolete name for bufnr("$"): last_buffer_nr().
599 The result is a Number, which is the number of the first
600 window associated with buffer {expr}. For the use of {expr},
601 see bufname() above. If buffer {expr} doesn't exist or there
602 is no such window, -1 is returned. Example:
603 > echo "A window containing buffer 1 is " . (bufwinnr(1))
607 Return the line number that contains the character at byte
608 count {byte} in the current buffer. This includes the
609 end-of-line character, depending on the 'fileformat' option
610 for the current buffer. The first character has byte count
612 Also see |line2byte()|, |go| and |:goto|.
613 {not available when compiled without the |+byte_offset|
618 Return ASCII value of the first char in {expr}. Examples:
619 > char2nr(" ") returns 32
620 > char2nr("ABC") returns 65
623 col({expr}) The result is a Number, which is the column of the file
624 position given with {expr}. The accepted positions are:
625 . the cursor position
626 'x position of mark x (if the mark is not set, 0 is
628 Note that only marks in the current file can be used.
630 > col(".") column of cursor
631 > col("'t") column of mark t
632 > col("'" . markname) column of mark markname
633 The first column is 1. 0 is returned for an error.
636 confirm({msg}, {choices} [, {default} [, {type}]])
637 Confirm() offers the user a dialog, from which a choice can be
638 made. It returns the number of the choice. For the first
640 Note: confirm() is only supported when compiled with dialog
641 support, see |+dialog_con| and |+dialog_gui|.
642 {msg} is displayed in a |dialog| with {choices} as the
644 {msg} is a String, use '\n' to include a newline. Only on
645 some systems the string is wrapped when it doesn't fit.
646 {choices} is a String, with the individual choices separated
648 > confirm("Save changes?", "&Yes\n&No\n&Cancel")
649 The letter after the '&' is the shortcut key for that choice.
650 Thus you can type 'c' to select "Cancel". The shorcut does
651 not need to be the first letter:
652 > confirm("file has been modified", "&Save\nSave &All")
653 For the console, the first letter of each choice is used as
654 the default shortcut key.
655 The optional {default} argument is the number of the choice
656 that is made if the user hits <CR>. Use 1 to make the first
657 choice the default one. Use 0 to not set a default. If
658 {default} is omitted, 0 is used.
659 The optional {type} argument gives the type of dialog. This
660 is only used for the icon of the Win32 GUI. It can be one of
661 these values: "Error", "Question", "Info", "Warning" or
662 "Generic". Only the first character is relevant. When {type}
663 is omitted, "Generic" is used.
664 If the user aborts the dialog by pressing <Esc>, CTRL-C,
665 or another valid interrupt key, confirm() returns 0.
668 > :let choice = confirm("What do you want?", "&Apples\n&Oranges\n&Bananas", 2)
670 > : echo "make up your mind!"
671 > :elseif choice == 3
674 > : echo "I prefer bananas myself."
676 In a GUI dialog, buttons are used. The layout of the buttons
677 depends on the 'v' flag in 'guioptions'. If it is included,
678 the buttons are always put vertically. Otherwise, confirm()
679 tries to put the buttons in one horizontal line. If they
680 don't fit, a vertical layout is used anyway. For some systems
681 the horizontal layout is always used.
684 delete({fname}) Deletes the file by the name {fname}. The result is a Number,
685 which is 0 if the file was deleted successfully, and non-zero
686 when the deletion failed.
689 did_filetype() Returns non-zero when autocommands are being executed and the
690 FileType event has been triggered at least once. Can be used
691 to avoid triggering the FileType event again in the scripts
692 that detect the file type. |FileType|
694 escape({string}, {chars}) *escape()*
695 Escape the characters in {chars} that occur in {string} with a
697 > :echo escape('c:\program files\vim', ' \')
699 > c:\\program\ files\\vim
702 exists({expr}) The result is a Number, which is 1 if {var} is defined, zero
703 otherwise. The {expr} argument is a string, which contains
705 &option-name Vim option
706 $ENVNAME environment variable (could also be
707 done by comparing with an empty
709 *funcname built-in function (see |functions|)
710 or user defined function (see
712 varname internal variable (see
713 |internal-variables|).
716 > exists("&shortname")
717 > exists("$HOSTNAME")
718 > exists("*strftime")
720 There must be no space between the symbol &/$/* and the name.
721 Note that the argument must be a string, not the name of the
722 variable itself! This example doesn't check for existence of
723 the "bufcount" variable, but gets the contents of "bufcount",
724 and checks if that exists:
728 expand({expr} [, {flag}])
729 Expand wildcards and the following special keywords in {expr}.
730 The result is a String.
732 When there are several matches, they are separated by <NL>
733 characters. [Note: in version 5.0 a space was used, which
734 caused problems when a file name contains a space]
736 If the expansion fails, the result is an empty string. A name
737 for a non-existing file is not included.
739 When {expr} starts with '%', '#' or '<', the expansion is done
740 like for the |cmdline-special| variables with their associated
741 modifiers. Here is a short overview:
744 # alternate file name
745 #n alternate file name n
746 <cfile> file name under the cursor
747 <afile> autocmd file name
748 <abuf> autocmd buffer number
749 <sfile> sourced script file name
750 <cword> word under the cursor
751 <cWORD> WORD under the cursor
753 :p expand to full path
754 :h head (last path component removed)
755 :t tail (last path component only)
756 :r root (one extension removed)
760 > :let &tags = expand("%:p:h") . "/tags"
761 Note that when expanding a string that starts with '%', '#' or
762 '<', any following text is ignored. This does NOT work:
763 > :let doesntwork = expand("%:h.bak")
765 > :let doeswork = expand("%:h") . ".bak"
766 Also note that expanding "<cfile>" and others only returns the
767 referenced file name without further expansion. If "<cfile>"
768 is "~/.cshrc", you need to do another expand() to have the
769 "~/" expanded into the path of the home directory:
770 > :echo expand(expand("<cfile>"))
772 There cannot be white space between the variables and the
773 following modifier. The |fnamemodify()| function can be used
774 to modify normal file names.
776 When using '%' or '#', and the current or alternate file name
777 is not defined, an empty string is used. Using "%:p" in a
778 buffer with no name, results in the current directory, with a
781 When {expr} does not start with '%', '#' or '<', it is
782 expanded like a file name is expanded on the command line.
783 'suffixes' and 'wildignore' are used, unless the optional
784 {flag} argument is given and it is non-zero.
786 Expand() can also be used to expand variables and environment
787 variables that are only known in a shell. But this can be
788 slow, because a shell must be started. See |expr-env-expand|.
790 See |glob()| for finding existing files. See |system()| for
791 getting the raw output of an external command.
795 The result is a Number, which is TRUE when a file with the
796 name {file} exists, and can be read. If {file} doesn't exist,
797 or is a directory, the result is FALSE. {file} is any
798 expression, which is used as a String.
800 Obsolete name: file_readable().
803 fnamemodify({fname}, {mods})
804 Modify file name {fname} according to {mods}. {mods} is a
805 string of characters like it is used for file names on the
806 command line. See |filename-modifiers|.
808 > :echo fnamemodify("main.c", ":p:h")
810 > /home/mool/vim/vim/src/
813 getcwd() The result is a String, which is the name of the current
818 The result is a Number, which is the last modification time of
819 the given file {fname}. The value is measured as seconds
820 since 1st Jan 1970, and may be passed to strftime(). See also
821 |localtime()| and |strftime()|.
822 If the file {fname} can't be found -1 is returned.
825 getline({lnum}) The result is a String, which is line {lnum} from the current
828 When {lnum} is a String that doesn't start with a
829 digit, line() is called to translate the String into a Number.
830 To get the line under the cursor:
832 When {lnum} is smaller than 1 or bigger than the number of
833 lines in the buffer, an empty string is returned.
836 getwinposx() The result is a Number, which is the X coordinate in pixels of
837 the left hand side of the GUI vim window. The result will be
838 -1 if the information is not available.
841 getwinposy() The result is a Number, which is the Y coordinate in pixels of
842 the top of the GUI vim window. The result will be -1 if the
843 information is not available.
846 glob({expr}) Expand the file wildcards in {expr}. The result is a String.
847 When there are several matches, they are separated by <NL>
849 If the expansion fails, the result is an empty string.
850 A name for a non-existing file is not included.
852 For most systems backticks can be used to get files names from
853 any external command. Example:
854 > :let tagfiles = glob("`find . -name tags -print`")
855 > :let &tags = substitute(tagfiles, "\n", ",", "g")
856 The result of the program inside the backticks should be one
857 item per line. Spaces inside an item are allowed.
859 See |expand()| for expanding special Vim variables. See
860 |system()| for getting the raw output of an external command.
863 has({feature}) The result is a Number, which is 1 if the feature {feature} is
864 supported, zero otherwise. The {feature} argument is a
865 string. See |feature-list| below.
868 histadd({history}, {item})
869 Add the String {item} to the history {history} which can be
871 "cmd" or ":" command line history
872 "search" or "/" search pattern history
873 "expr" or "=" typed expression history
874 "input" or "@" input line history
875 If {item} does already exist in the history, it will be
876 shifted to become the newest entry.
877 The result is a Number: 1 if the operation was successful,
878 otherwise 0 is returned.
881 > :call histadd("input", strftime("%Y %b %d"))
882 > :let date=input("Enter date: ")
885 histdel({history} [, {item}])
886 Clear {history}, ie. delete all its entries. See |hist-names|
887 for the possible values of {history}.
889 If the parameter {item} is given as String, this is seen
890 as regular expression. All entries matching that expression
891 will be removed from the history (if there are any).
892 If {item} is a Number, it will be interpreted as index, see
893 |:history-indexing|. The respective entry will be removed
896 The result is a Number: 1 for a successful operation,
897 otherwise 0 is returned.
900 Clear expression register history:
901 > :call histdel("expr")
903 Remove all entries starting with "*" from the search history:
904 > :call histdel("/", '^\*')
906 The following three are equivalent:
907 > :call histdel("search", histnr("search"))
908 > :call histdel("search", -1)
909 > :call histdel("search", '^'.histget("search", -1).'$')
911 To delete the last search pattern and use the last-but-one for
912 the "n" command and 'hlsearch':
913 > :call histdel("search", -1)
914 > :let @/ = histget("search", -1)
918 histget({history} [, {index}])
919 The result is a String, the entry with Number {index} from
920 {history}. See |hist-names| for the possible values of
921 {history}, and |:history-indexing| for {index}. If there is
922 no such entry, an empty String is returned. When {index} is
923 omitted, the most recent item from the history is used.
926 Redo the second last search from history.
927 > :execute '/' . histget("search", -2)
929 Define an Ex command ":H {num}" that supports
930 re-execution of the {num}th entry from the output
932 > :command -nargs=1 H execute histget("cmd",0+<args>)
936 The result is the Number of the current entry in {history}.
937 See |hist-names| for the possible values of {history}.
938 If an error occurred, -1 is returned.
941 > :let inp_index = histnr("expr")
945 The result is a Number, which is non-zero if a highlight group
946 called {name} exists. This is when the group has been
947 defined in some way. Not necessarily when highlighting has
948 been defined for it, it may also have been used for a syntax
951 Obsolete name: highlight_exists().
954 hlID({name}) The result is a Number, which is the ID of the highlight group
955 with name {name}. When the highlight group doesn't exist,
957 This can be used to retrieve information about the highlight
958 group. For example, to get the background color of the
960 > :echo synIDattr(synIDtrans(hlID("Comment")), "bg")
962 Obsolete name: highlightID().
966 The result is a String, which is the name of the machine on
967 which Vim is currently running. Machine names greater than
968 256 characters long are truncated.
970 input({prompt}) *input()*
971 The result is a String, which is whatever the user typed on
972 the command-line. The parameter is either a prompt string, or
973 a blank string (for no prompt). A '\n' can be used in the
974 prompt to start a new line. The highlighting set with
975 |:echohl| is used for the prompt. The input is entered just
976 like a command-line, with the same editing commands and
977 mappings. There is a separate history for lines typed for
979 NOTE: This must not be used in a startup file, for the
980 versions that only run in GUI mode (e.g., the Win32 GUI).
983 > :if input("Coffee or beer? ") == "beer"
987 isdirectory({directory})
988 The result is a Number, which is TRUE when a directory with
989 the name {directory} exists. If {directory} doesn't exist, or
990 isn't a directory, the result is FALSE. {directory} is any
991 expression, which is used as a String.
994 libcall({libname}, {funcname}, {argument})
995 Call function {funcname} in the run-time library {libname}
996 with argument {argument}. The result is the String returned.
997 If {argument} is a number, it is passed to the function as an
998 int; if {param} is a string, it is passed as a null-terminated
999 string. If the function returns NULL, this will appear as an
1000 empty string "" to Vim.
1002 libcall() allows you to write your own 'plug-in' extensions to
1003 Vim without having to recompile the program. It is NOT a
1004 means to call system functions! If you try to do so Vim will
1005 very probably crash.
1007 For Win32, the functions you write must be placed in a DLL
1008 and use the normal C calling convention (NOT Pascal which is
1009 used in Windows System DLLs). The function must take exactly
1010 one parameter, either a character pointer or a long integer,
1011 and must return a character pointer or NULL. The character
1012 pointer returned must point to memory that will remain valid
1013 after the function has returned (e.g. in static data in the
1014 DLL). If it points to allocated memory, that memory will
1015 leak away. Using a static buffer in the function should work,
1016 it's then freed when the DLL is unloaded.
1018 WARNING: If the function returns a non-valid pointer, Vim will
1019 crash! This also happens if the function returns a number,
1020 because Vim thinks it's a pointer.
1021 For Win32 systems, {libname} should be the filename of the DLL
1022 without the ".DLL" suffix. A full path is only required if
1023 the DLL is not in the usual places.
1024 {only in Win32 versions}
1027 line({expr}) The result is a Number, which is the line number of the file
1028 position given with {expr}. The accepted positions are:
1029 . the cursor position
1030 $ the last line in the current buffer
1031 'x position of mark x (if the mark is not set, 0 is
1033 Note that only marks in the current file can be used.
1035 > line(".") line number of the cursor
1036 > line("'t") line number of mark t
1037 > line("'" . marker) line number of mark marker
1038 *last-position-jump*
1039 This autocommand jumps to the last known position in a file
1040 just after opening it, if the '" mark is set:
1041 > :au BufReadPost * if line("'\"") | exe "normal '\"" | endif
1045 Return the byte count from the start of the buffer for line
1046 {lnum}. This includes the end-of-line character, depending on
1047 the 'fileformat' option for the current buffer. The first
1049 This can also be used to get the byte count for the line just
1050 below the last line:
1051 > line2byte(line("$") + 1)
1052 This is the file size plus one.
1053 When {lnum} is invalid, or the |+byte_offset| feature has been
1054 disabled at compile time, -1 is returned.
1055 Also see |byte2line()|, |go| and |:goto|.
1059 Return the current time, measured as seconds since 1st Jan
1060 1970. See also |strftime()| and |getftime()|.
1063 maparg({name}[, {mode}])
1064 Return the rhs of mapping {name} in mode {mode}. When there
1065 is no mapping for {name}, an empty String is returned.
1066 These characters can be used for {mode}:
1069 "o" Operator-pending
1072 "" Normal, Visual and Operator-pending
1073 When {mode} is omitted, the modes from "" are used.
1074 The {name} can have special key names, like in the ":map"
1075 command. The returned String has special characters
1076 translated like in the output of the ":map" command listing.
1079 mapcheck({name}[, {mode}])
1080 Check if there is a mapping that matches with {name} in mode
1081 {mode}. See |maparg()| for {mode} and special names in
1083 When there is no mapping that matches with {name}, and empty
1084 String is returned. If there is one, the rhs of that mapping
1085 is returned. If there are several matches, the rhs of one of
1087 This function can be used to check if a mapping can be added
1088 without being ambiguous. Example:
1089 > if mapcheck("_vv") == ""
1090 > map _vv :set guifont=7x13<CR>
1092 The "_vv" mapping may conflict with a mapping for "_v" or for
1096 match({expr}, {pat})
1097 The result is a Number, which gives the index in {expr} where
1098 {pat} matches. A match at the first character returns zero.
1099 If there is no match -1 is returned. Example:
1100 > :echo match("testing", "ing")
1102 See |pattern| for the patterns that are accepted.
1103 The 'ignorecase' option is used to set the ignore-caseness of
1104 the pattern. 'smartcase' is NOT used. The matching is always
1105 done like 'magic' is set and 'cpoptions' is empty.
1108 matchend({expr}, {pat})
1109 Same as match(), but return the index of first character after
1111 > :echo matchend("testing", "ing")
1115 matchstr({expr}, {pat})
1116 Same as match(), but return the matched string. Example:
1117 > :echo matchstr("testing", "ing")
1119 When there is no match "" is returned.
1123 Return a string with a single chararacter, which has the ASCII
1124 value {expr}. Examples:
1125 > nr2char(64) returns "@"
1126 > nr2char(32) returns " "
1128 rename({from}, {to}) *rename()*
1129 Rename the file by the name {from} to the name {to}. This
1130 should also work to move files across file systems. The
1131 result is a Number, which is 0 if the file was renamed
1132 successfully, and non-zero when the renaming failed.
1135 setline({lnum}, {line})
1136 Set line {lnum} of the current buffer to {line}. If this
1137 succeeds, 0 is returned. If this fails (most likely because
1138 {lnum} is invalid) 1 is returned. Example:
1139 > :call setline(5, strftime("%c"))
1142 strftime({format} [, {time}])
1143 The result is a String, which is a formatted date and time, as
1144 specified by the {format} string. The given {time} is used,
1145 or the current time if no time is given. The accepted
1146 {format} depends on your system, thus this is not portable!
1147 See the manual page of the C function strftime() for the
1148 format. The maximum length of the result is 80 characters.
1149 See also |localtime()| and |getftime()|. Examples:
1150 > :echo strftime("%c") Sun Apr 27 11:49:23 1997
1151 > :echo strftime("%Y %b %d %X") 1997 Apr 27 11:53:25
1152 > :echo strftime("%y%m%d %T") 970427 11:53:55
1153 > :echo strftime("%H:%M") 11:55
1154 > :echo strftime("%c", getftime("file.c"))
1155 > Show mod time of file.c.
1158 strlen({expr}) The result is a Number, which is the length of the String
1162 strpart({src}, {start}, {len})
1163 The result is a String, which is part of {src},
1164 starting from character {start}, with the length {len}.
1165 When non-existing characters are included, this doesn't result
1166 in an error, the characters are simply omitted.
1167 > strpart("abcdefg", 3, 2) == "de"
1168 > strpart("abcdefg", -2, 4) == "ab"
1169 > strpart("abcdefg", 5, 4) == "fg"
1170 Note: To get the first character, {start} must be 0. For
1171 example, to get three characters under and after the cursor:
1172 > strpart(getline(line(".")), col(".") - 1, 3)
1176 The result is a String, which is {expr} with all unprintable
1177 characters translated into printable characters |'isprint'|.
1178 Like they are shown in a window. Example:
1180 This displays a newline in register a as "^@" instead of
1181 starting a new line.
1184 substitute({expr}, {pat}, {sub}, {flags})
1185 The result is a String, which is a copy of {expr}, in which
1186 the first match of {pat} is replaced with {sub}. This works
1187 like the ":substitute" command (without any flags). But the
1188 matching with {pat} is always done like the 'magic' option is
1189 set and 'cpoptions' is empty (to make scripts portable).
1190 And a "~" in {sub} is not replaced with the previous {sub}.
1191 Note that some codes in {sub} have a special meaning
1192 |sub-replace-special|. For example, to replace something with
1193 a literal "\n", use "\\\\n" or '\\n'.
1194 When {pat} does not match in {expr}, {expr} is returned
1196 When {flags} is "g", all matches of {pat} in {expr} are
1197 replaced. Otherwise {flags} should be "".
1199 > :let &path = substitute(&path, ",\\=[^,]*$", "", "")
1200 This removes the last component of the 'path' option.
1201 > :echo substitute("testing", ".*", "\\U\\0", "")
1202 results in "TESTING".
1205 synID({line}, {col}, {trans})
1206 The result is a Number, which is the syntax ID at the position
1207 {line} and {col} in the current window.
1208 The syntax ID can be used with |synIDattr()| and
1209 |synIDtrans()| to obtain syntax information about text.
1210 {col} is 1 for the leftmost column, {line} is 1 for the first
1212 When {trans} is non-zero, transparent items are reduced to the
1213 item that they reveal. This is useful when wanting to know
1214 the effective color. When {trans} is zero, the transparent
1215 item is returned. This is useful when wanting to know which
1216 syntax item is effective (e.g. inside parens).
1217 Warning: This function can be very slow. Best speed is
1218 obtained by going through the file in forward direction.
1220 Example (echos the name of the syntax item under the cursor):
1221 > :echo synIDattr(synID(line("."), col("."), 1), "name")
1224 synIDattr({synID}, {what} [, {mode}])
1225 The result is a String, which is the {what} attribute of
1226 syntax ID {synID}. This can be used to obtain information
1227 about a syntax item.
1228 {mode} can be "gui", "cterm" or "term", to get the attributes
1229 for that mode. When {mode} is omitted, or an invalid value is
1230 used, the attributes for the currently active highlighting are
1231 used (GUI, cterm or term).
1232 Use synIDtrans() to follow linked highlight groups.
1234 "name" the name of the syntax item
1235 "fg" foreground color (GUI: color name, cterm:
1236 color number as a string, term: empty string)
1237 "bg" background color (like "fg")
1238 "fg#" like "fg", but name in "#RRGGBB" form
1239 "bg#" like "bg", but name in "#RRGGBB" form
1241 "italic" "1" if italic
1242 "reverse" "1" if reverse
1243 "inverse" "1" if inverse (= reverse)
1244 "underline" "1" if underlined
1246 When the GUI is not running or the cterm mode is asked for,
1247 "fg#" is equal to "fg" and "bg#" is equal to "bg".
1249 Example (echos the color of the syntax item under the cursor):
1250 > :echo synIDattr(synIDtrans(synID(line("."), col("."), 1)), "fg")
1254 The result is a Number, which is the translated syntax ID of
1255 {synID}. This is the syntax group ID of what is being used to
1256 highlight the character. Highlight links given with
1257 ":highlight link" are followed.
1260 system({expr}) Get the output of the shell command {expr}. Note: newlines
1261 in {expr} may cause the command to fail. This is not to be
1262 used for interactive commands.
1263 The result is a String. To make the result more
1264 system-independent, the shell output is filtered to replace
1265 <CR> with <NL> for Macintosh, and <CR><NL> with <NL> for
1267 'shellredir' is used to capture the output of the command.
1268 Depending on 'shell', you might be able to capture stdout with
1269 ">" and stdout plus stderr with ">&" (csh) or use "2>" to
1270 capture stderr (sh).
1271 The resulting error code can be found in |v:shell_error|.
1272 This function will fail in |restricted-mode|.
1274 *tempname()* *temp-file-name*
1276 The result is a String, which is the name of a file that
1277 doesn't exist. It can be used for a temporary file. The name
1278 is different for at least 26 consecutive calls. Example:
1279 > let tmpfile = tempname()
1280 > exe "redir > " . tmpfile
1284 The result is a String, which describes the last Visual mode
1285 used. Initially it returns an empty string, but once Visual
1286 mode has been used, it returns "v", "V", or "<CTRL-V>" (a
1287 single CTRL-V character) for character-wise, line-wise, or
1288 block-wise Visual mode respecively.
1290 > exe "normal " . visualmode()
1291 This enters the same Visual mode as before. It is also useful
1292 in scripts if you wish to act differently depending on the
1293 Visual mode that was used.
1297 The result is a Number, which is the screen column of the file
1298 position given with {expr}. That is, the last screen position
1299 occupied by the character at that position, when the screen
1300 would be of unlimited width. When there is a <Tab> at the
1301 position, the returned Number will be the column at the end of
1302 the <Tab>. For example, for a <Tab> in column 1, with 'ts'
1303 set to 8, it returns 8;
1304 The accepted positions are:
1305 . the cursor position
1306 'x position of mark x (if the mark is not set, 0 is
1308 Note that only marks in the current file can be used.
1310 > virtcol(".") with text "foo^Lbar", with cursor on the "^L", returns 5
1311 > virtcol("'t") with text " there", with 't at 'h', returns 6
1312 The first column is 1. 0 is returned for an error.
1315 winbufnr({nr}) The result is a Number, which is the number of the buffer
1316 associated with window {nr}. When {nr} is zero, the number of
1317 the buffer in the current window is returned. When window
1318 {nr} doesn't exist, -1 is returned.
1320 > echo "The file in the current window is " . bufname(winbufnr(0))
1324 The result is a Number, which is the height of window {nr}.
1325 When {nr} is zero, the height of the current window is
1326 returned. When window {nr} doesn't exist, -1 is returned.
1327 An existing window always has a height of zero or more.
1329 > echo "The current window has " . winheight(0) . " lines."
1332 winnr() The result is a Number, which is the number of the current
1333 window. The top window has number 1.
1336 There are two types of features:
1337 1. Features that are only supported when they have been enabled when Vim
1338 was compiled |+feature-list|. Example:
1339 > :if has("cindent")
1340 2. Features that are only supported when certain conditions have been met.
1342 > :if has("gui_running")
1344 all_builtin_terms Compiled with all builtin terminals enabled.
1345 amiga Amiga version of Vim.
1346 arp Compiled with ARP support (Amiga).
1347 autocmd Compiled with autocommands support.
1348 beos BeOS version of Vim.
1349 browse Compiled with |:browse| support, and browse() will
1351 builtin_terms Compiled with some builtin terminals.
1352 byte_offset Compiled with support for 'o' in 'statusline'
1353 cindent Compiled with 'cindent' support.
1354 clipboard Compiled with 'clipboard' support.
1355 cmdline_compl Compiled with |cmdline-completion| support.
1356 cmdline_info Compiled with 'showcmd' and 'ruler' support.
1357 comments Compiled with |'comments'| support.
1358 cryptv Compiled with encryption support |encryption|.
1359 cscope Compiled with |cscope| support.
1360 compatible Compiled to be very Vi compatible.
1361 debug Compiled with "DEBUG" defined.
1362 dialog_con Compiled with console dialog support.
1363 dialog_gui Compiled with GUI dialog support.
1364 digraphs Compiled with support for digraphs.
1365 dos32 32 bits DOS (DJGPP) version of Vim.
1366 dos16 16 bits DOS version of Vim.
1367 emacs_tags Compiled with support for Emacs tags.
1368 eval Compiled with expression evaluation support. Always
1370 ex_extra Compiled with extra Ex commands |+ex_extra|.
1371 extra_search Compiled with support for |'incsearch'| and
1373 farsi Compiled with Farsi support |farsi|.
1374 file_in_path Compiled with support for |gf| and |<cfile>|
1375 find_in_path Compiled with support for include file searches
1377 fname_case Case in file names matters (for Amiga, MS-DOS, and
1378 Windows this is not present).
1379 fork Compiled to use fork()/exec() instead of system().
1380 gui Compiled with GUI enabled.
1381 gui_athena Compiled with Athena GUI.
1382 gui_beos Compiled with BeOs GUI.
1383 gui_gtk Compiled with GTK+ GUI.
1384 gui_mac Compiled with Macintosh GUI.
1385 gui_motif Compiled with Motif GUI.
1386 gui_win32 Compiled with MS Windows Win32 GUI.
1387 gui_win32s idem, and Win32s system being used (Windows 3.1)
1388 gui_running Vim is running in the GUI, or it will start soon.
1389 hangul_input Compiled with Hangul input support. |hangul|
1390 insert_expand Compiled with support for CTRL-X expansion commands in
1392 langmap Compiled with 'langmap' support.
1393 linebreak Compiled with 'linebreak', 'breakat' and 'showbreak'
1395 lispindent Compiled with support for lisp indenting.
1396 mac Macintosh version of Vim.
1397 menu Compiled with support for |:menu|.
1398 mksession Compiled with support for |:mksession|.
1399 modify_fname Compiled with file name modifiers. |filename-modifiers|
1400 mouse Compiled with support mouse.
1401 mouse_dec Compiled with support for Dec terminal mouse.
1402 mouse_gpm Compiled with support for gpm (Linux console mouse)
1403 mouse_netterm Compiled with support for netterm mouse.
1404 mouse_xterm Compiled with support for xterm mouse.
1405 multi_byte Compiled with support for Korean et al.
1406 multi_byte_ime Compiled with support for IME input method
1407 ole Compiled with OLE automation support for Win32.
1408 os2 OS/2 version of Vim.
1409 osfiletype Compiled with support for osfiletypes |+osfiletype|
1410 perl Compiled with Perl interface.
1411 python Compiled with Python interface.
1412 quickfix Compiled with |quickfix| support.
1413 rightleft Compiled with 'rightleft' support.
1414 scrollbind Compiled with 'scrollbind' support.
1415 showcmd Compiled with 'showcmd' support.
1416 smartindent Compiled with 'smartindent' support.
1417 sniff Compiled with SniFF interface support.
1418 statusline Compiled with support for 'statusline', 'rulerformat'
1419 and special formats of 'titlestring' and 'iconstring'.
1420 syntax Compiled with syntax highlighting support.
1421 syntax_items There are active syntax highlighting items for the
1423 system Compiled to use system() instead of fork()/exec().
1424 tag_binary Compiled with binary searching in tags files
1425 |tag-binary-search|.
1426 tag_old_static Compiled with support for old static tags
1428 tag_any_white Compiled with support for any white characters in tags
1429 files |tag-any-white|.
1430 tcl Compiled with Tcl interface.
1431 terminfo Compiled with terminfo instead of termcap.
1432 textobjects Compiled with support for |text-objects|.
1433 tgetent Compiled with tgetent support, able to use a termcap
1435 title Compiled with window title support |'title'|.
1436 unix Unix version of Vim.
1437 user_commands User-defined commands.
1438 viminfo Compiled with viminfo support.
1439 vim_starting True while initial source'ing takes place.
1440 visualextra Compiled with extra Visual mode commands
1441 |blockwise-operators|.
1442 vms VMS version of Vim.
1443 wildmenu Compiled with 'wildmenu' option.
1444 wildignore Compiled with 'wildignore' option.
1445 winaltkeys Compiled with 'winaltkeys' option.
1446 win16 Win16 version of Vim (Windows 3.1).
1447 win32 Win32 version of Vim (Windows 95/NT).
1448 writebackup Compiled with 'writebackup' default on.
1449 xim Compiled with X input method support |xim|.
1450 xfontset Compiled with X fontset support |xfontset|.
1451 xterm_clipboard Compiled with support for xterm clipboard.
1452 xterm_save Compiled with support for saving and restoring the
1454 x11 Compiled with X11 support.
1456 ==============================================================================
1457 5. Defining functions *user-functions*
1459 New functions can be defined. These can be called just like builtin
1462 The function name must start with an uppercase letter, to avoid confusion with
1463 builtin functions. To prevent from using the same name in different scripts
1464 avoid obvious, short names. A good habit is to start the function name with
1465 the name of the script, e.g., "HTMLcolor()".
1468 :fu[nction] List all functions and their arguments.
1470 :fu[nction] {name} List function {name}.
1472 :fu[nction][!] {name}([arguments]) [range] [abort]
1473 Define a new function by the name {name}. The name
1474 must be made of alphanumeric characters and '_', and
1475 must start with a capital.
1476 An argument can be defined by giving its name. In the
1477 function this can then be used as "a:name" ("a:" for
1479 Up to 20 arguments can be given, separated by commas.
1480 Finally, an argument "..." can be specified, which
1481 means that more arguments may be following. In the
1482 function they can be used as "a:1", "a:2", etc. "a:0"
1483 is set to the number of extra arguments (which can be
1485 When not using "...", the number of arguments in a
1486 function call must be equal the number of named
1487 arguments. When using "...", the number of arguments
1489 It is also possible to define a function without any
1490 arguments. You must still supply the () then.
1491 The body of the function follows in the next lines,
1492 until the matching |:endfunction|. It is allowed to
1493 define another function inside a function body.
1494 When a function by this name already exists and [!] is
1495 not used an error message is given. When [!] is used,
1496 an existing function is silently replaced.
1497 When the [range] argument is added, the function is
1498 expected to take care of a range itself. The range is
1499 passed as "a:firstline" and "a:lastline". If [range]
1500 is excluded, ":{range}call" will call the function for
1501 each line in the range, with the cursor on the start
1502 of each line. See |function-range-example|.
1503 When the [abort] argument is added, the function will
1504 abort as soon as an error is detected.
1505 The last used search pattern and the redo command "."
1506 will not be changed by the function.
1508 *:endf* *:endfunction*
1509 :endf[unction] The end of a function definition.
1511 *:delf* *:delfunction*
1512 :delf[unction] {name} Delete function {name}.
1515 :retu[rn] [expr] Return from a function. When "[expr]" is given, it is
1516 evaluated and returned as the result of the function.
1517 If "[expr]" is not given, the number 0 is returned.
1518 When a function ends without an explicit ":return",
1519 the number 0 is returned.
1520 Note that there is no check for unreachable lines,
1521 thus there is no warning if commands follow ":return".
1523 Inside a function variables can be used. These are local variables, which
1524 will disappear when the function returns. Global variables need to be
1528 > :function Table(title, ...)
1533 > : while idx <= a:0
1534 > : exe "echo a:" . idx
1535 > : let idx = idx + 1
1540 This function can then be called with:
1541 > let lines = Table("Table", "line1", "line2")
1542 > let lines = Table("Empty Table")
1544 To return more than one value, pass the name of a global variable:
1545 > :function Compute(n1, n2, divname)
1549 > : exe "let g:" . a:divname . " = ". a:n1 / a:n2
1553 This function can then be called with:
1554 > :let success = Compute(13, 1324, "div")
1555 > :if success == "ok"
1559 An alternative is to return a command that can be executed. This also works
1560 with local variables in a calling function. Example:
1563 > : echo "line " . lnum . " column " . col
1567 > : return "let lnum = " . line(".") . " | let col = " . col(".")
1570 The names "lnum" and "col" could also be passed as argument to Bar(), to allow
1571 the caller to set the names.
1574 :[range]cal[l] {name}([arguments])
1575 Call a function. The name of the function and its arguments
1576 are as specified with |:function|. Up to 20 arguments can be
1578 Without a range and for functions that accept a range, the
1579 function is called once, with the cursor at the current
1581 When a range is given and the function doesn't handle it
1582 itself, the function is executed for each line in the range,
1583 with the cursor in the first column of that line. The cursor
1584 is left at the last line (possibly moved by the last function
1585 call). The arguments are re-evaluated for each line. Thus
1587 *function-range-example*
1588 > :function Mynumber(arg)
1589 > : echo line(".") . " " . a:arg
1591 > :1,5call Mynumber(getline("."))
1593 The "a:firstline" and "a:lastline" are defined anyway, they
1594 can be used to do something different at the start or end of
1597 Example of a function that handles the range itself:
1599 > :function Cont() range
1600 > : execute (a:firstline + 1) . "," . a:lastline . 's/^/\t\\ '
1604 This function inserts the continuation character "\" in front
1605 of all the lines in the range, except the first one.
1608 The recursiveness of user functions is restricted with the |'maxfuncdepth'|
1611 ==============================================================================
1612 6. Commands *expression-commands*
1614 :let {var-name} = {expr1} *:let*
1615 Set internal variable {var-name} to the result of the
1616 expression {expr1}. The variable will get the type
1617 from the {expr}. if {var-name} didn't exist yet, it
1620 :let ${env-name} = {expr1} *:let-environment* *:let-$*
1621 Set environment variable {env-name} to the result of
1622 the expression {expr1}. The type is always String.
1624 :let @{reg-name} = {expr1} *:let-register* *:let-@*
1625 Write the result of the expression {expr1} in register
1626 {reg-name}. {reg-name} must be a single letter, and
1627 must be the name of a writable register (see
1628 |registers|). "@@" can be used for the unnamed
1629 register, "@/" for the search pattern.
1630 If the result of {expr1} ends in a <CR> or <NL>, the
1631 register will be linewise, otherwise it will be set to
1634 :let &{option-name} = {expr1} *:let-option* *:let-star*
1635 Set option {option-name} to the result of the
1636 expression {expr1}. The type of the option is always
1640 :unl[et][!] {var-name} ...
1641 Remove the internal variable {var-name}. Several
1642 variable names can be given, they are all removed.
1643 With [!] no error message is given for non-existing
1646 :if {expr1} *:if* *:endif* *:en*
1647 :en[dif] Execute the commands until the next matching ":else"
1648 or ":endif" if {expr1} evaluates to non-zero.
1650 From Vim version 4.5 until 5.0, every Ex command in
1651 between the ":if" and ":endif" is ignored. These two
1652 commands were just to allow for future expansions in a
1653 backwards compatible way. Nesting was allowed. Note
1654 that any ":else" or ":elseif" was ignored, the "else"
1655 part was not executed either.
1657 You can use this to remain compatible with older
1659 > :if version >= 500
1660 > : version-5-specific-commands
1664 :el[se] Execute the commands until the next matching ":else"
1665 or ":endif" if they previously were not being
1669 :elsei[f] {expr1} Short for ":else" ":if", with the addition that there
1670 is no extra ":endif".
1672 :wh[ile] {expr1} *:while* *:endwhile* *:wh* *:endw*
1673 :endw[hile] Repeat the commands between ":while" and ":endwhile",
1674 as long as {expr1} evaluates to non-zero.
1675 When an error is detected from a command inside the
1676 loop, execution continues after the "endwhile".
1678 NOTE: The ":append" and ":insert" commands don't work properly
1679 inside a ":while" loop.
1682 :con[tinue] When used inside a ":while", jumps back to the
1686 :brea[k] When used inside a ":while", skips to the command
1687 after the matching ":endwhile".
1690 :ec[ho] {expr1} .. Echoes each {expr1}, with a space in between and a
1691 terminating <EOL>. Also see |:comment|.
1692 Use "\n" to start a new line. Use "\r" to move the
1693 cursor to the first column.
1694 Cannot be followed by a comment.
1696 > :echo "the value of 'shell' is" &shell
1699 :echon {expr1} .. Echoes each {expr1}, without anything added. Also see
1701 Cannot be followed by a comment.
1703 > :echon "the value of 'shell' is " &shell
1705 Note the difference between using ":echo", which is a
1706 Vim command, and ":!echo", which is an external shell
1708 > :!echo % --> filename
1709 The arguments of ":!" are expanded, see |:_%|.
1710 > :!echo "%" --> filename or "filename"
1711 Like the previous example. Whether you see the double
1712 quotes or not depends on your 'shell'.
1713 > :echo % --> nothing
1714 The '%' is an illegal character in an expression.
1716 This just echoes the '%' character.
1717 > :echo expand("%") --> filename
1718 This calls the expand() function to expand the '%'.
1721 :echoh[l] {name} Use the highlight group {name} for the following
1722 ":echo[n]" commands. Example:
1723 > :echohl WarningMsg | echo "Don't panic!" | echohl None
1724 Don't forget to set the group back to "None",
1725 otherwise all following echo's will be highlighted.
1728 :exe[cute] {expr1} .. Executes the string that results from the evaluation
1729 of {expr1} as an Ex command. Multiple arguments are
1730 concatenated, with a space in between.
1731 Cannot be followed by a comment.
1733 > :execute "buffer " nextbuf
1734 > :execute "normal " count . "w"
1736 Execute can be used to append a next command to
1737 commands that don't accept a '|'. Example:
1738 > :execute '!ls' | echo "theend"
1740 Note: The executed string may be any command-line, but
1741 you cannot start or end a "while" or "if" command.
1742 Thus this is illegal:
1743 > :execute 'while i > 5'
1744 > :execute 'echo "test" | break'
1746 It is allowed to have a "while" or "if" command
1747 completely in the executed string:
1748 > :execute 'while i < 5 | echo i | let i = i + 1 | endwhile'
1752 ":execute", ":echo" and ":echon" cannot be followed by
1753 a comment directly, because they see the '"' as the
1754 start of a string. But, you can use '|' followed by a
1756 > :echo "foo" | "this is a comment
1758 ==============================================================================
1759 7. Examples *eval-examples*
1763 > " The function Nr2Hex() returns the Hex string of a number.
1768 > let r = '0123456789ABCDEF'[n % 16] . r
1774 > " The function String2Hex() converts each character in a string to a two
1775 > " character Hex string.
1776 > func String2Hex(str)
1779 > while ix < strlen(a:str)
1780 > let out = out . Nr2Hex(char2nr(a:str[ix]))
1789 > echo String2Hex("32")
1793 Sorting lines (by Robert Webb) ~
1795 Here is a vim script to sort lines. Highlight the lines in vim and type
1796 ":Sort". This doesn't call any external programs so it'll work on any
1797 platform. The function Sort() actually takes the name of a comparison
1798 function as its argument, like qsort() does in C. So you could supply it
1799 with different comparison functions in order to sort according to date etc.
1801 > " Function for use with Sort(), to compare two strings.
1802 > func! Strcmp(str1, str2)
1803 > if (a:str1 < a:str2)
1805 > elseif (a:str1 > a:str2)
1812 > " Sort lines. SortR() is called recursively.
1813 > func! SortR(start, end, cmp)
1814 > if (a:start >= a:end)
1817 > let partition = a:start - 1
1818 > let middle = partition
1819 > let partStr = getline((a:start + a:end) / 2)
1821 > while (i <= a:end)
1822 > let str = getline(i)
1823 > exec "let result = " . a:cmp . "(str, partStr)"
1825 > " Need to put it before the partition. Swap lines i and partition.
1826 > let partition = partition + 1
1828 > let middle = partition
1830 > if (i != partition)
1831 > let str2 = getline(partition)
1832 > call setline(i, str2)
1833 > call setline(partition, str)
1839 > " Now we have a pointer to the "middle" element, as far as partitioning
1840 > " goes, which could be anywhere before the partition. Make sure it is at
1841 > " the end of the partition.
1842 > if (middle != partition)
1843 > let str = getline(middle)
1844 > let str2 = getline(partition)
1845 > call setline(middle, str2)
1846 > call setline(partition, str)
1848 > call SortR(a:start, partition - 1, a:cmp)
1849 > call SortR(partition + 1, a:end, a:cmp)
1852 > " To Sort a range of lines, pass the range to Sort() along with the name of a
1853 > " function that will compare two lines.
1854 > func! Sort(cmp) range
1855 > call SortR(a:firstline, a:lastline, a:cmp)
1858 > " :Sort takes a range of lines and sorts them.
1859 > command! -nargs=0 -range Sort <line1>,<line2>call Sort("Strcmp")
1862 There is no sscanf() function in Vim. If you need to extract parts from a
1863 line, you can use matchstr() and substitute() to do it This example shows
1864 how to get the file name, line number and column number out of a line like
1865 "foobar.txt, 123, 45".
1866 > " Set up the match bit
1867 > let mx='\(\f\+\),\s*\(\d\+\),\s*\(\d\+\)'
1868 > "get the part matching the whole expression
1869 > let l = matchstr(line, mx)
1870 > "get each item out of the match
1871 > let file = substitute(l, mx, '\1', '')
1872 > let lnum = substitute(l, mx, '\2', '')
1873 > let col = substitute(l, mx, '\3', '')
1875 The input is in the variable "line", the results in the variables "file",
1876 "lnum" and "col". (idea from Michael Geddes)
1878 ==============================================================================
1879 8. No +eval feature *no-eval-feature*
1881 When the |+eval| feature was disabled at compile time, all the expression
1882 evaluation commands are not available. To avoid that a Vim script generates
1883 all kinds of errors, the ":if" and ":endif" commands are recognized.
1884 Everything between the ":if" and the matching ":endif" is ignored. It does
1885 not matter what argument is used after the ":if". Nesting of these commands
1886 is recognized, but only if the commands are at the start of the line. The
1887 ":else" command is not recognized.
1889 Example of how to avoid commands to be executed when the |+eval| feature is
1892 > echo "Expression evaluation is compiled in"
1895 vim:tw=78:ts=8:sw=8: