Eval
Eval
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
|no-eval-feature|.
This file is about the backwards compatible Vim script. For Vim9 script,
which executes much faster, supports type checking and much more, see
|vim9.txt|.
1. Variables |variables|
1.1 Variable types
1.2 Function references |Funcref|
1.3 Lists |Lists|
1.4 Dictionaries |Dictionaries|
1.5 Blobs |Blobs|
1.6 More about variables |more-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. Vim script version |vimscript-version|
11. No +eval feature |no-eval-feature|
12. The sandbox |eval-sandbox|
13. Textlock |textlock|
==============================================================================
1. Variables *variables*
*Number* *Integer*
Number A 32 or 64 bit signed number. |expr-number|
The number of bits is available in |v:numbersize|.
Examples: -123 0x10 0177 0b1011
*E928*
String A NUL terminated string of 8-bit unsigned characters (bytes).
|expr-string| Examples: "ab\txx\"--" 'x-z''a,c'
Blob Binary Large Object. Stores any sequence of bytes. See |Blob|
for details
Example: 0zFF00ED015DAF
0z is an empty Blob.
The Number and String types are converted automatically, depending on how they
are used.
*no-type-checking*
You will not get an error if you try to change the type of a variable.
:let Fn = function("MyFunc")
:echo Fn()
< *E704* *E705* *E707*
A Funcref variable must start with a capital, "s:", "w:", "t:" or "b:". You
can use "g:" but the following name must still start with a capital. You
cannot have both a Funcref variable and a function with the same name.
The key of the Dictionary can start with a lower case letter. The actual
function name is not used here. Also see |numbered-function|.
The name of the referenced function can be obtained with |string()|. >
:let func = string(Fn)
You can use |call()| to invoke a Funcref and use a list variable for the
arguments: >
:let r = call(Fn, mylist)
<
*Partial*
A Funcref optionally binds a Dictionary and/or arguments. This is also called
a Partial. This is created by passing the Dictionary and/or arguments to
function() or funcref(). When calling the function the Dictionary and/or
arguments will be passed to the function. Example: >
This is very useful when passing a function around, e.g. in the arguments of
|ch_open()|.
Note that binding a function to a Dictionary also happens when the function is
a member of the Dictionary: >
Here MyFunction() will get myDict passed as "self". This happens when the
"myFunction" member is accessed. When making assigning "myFunction" to
otherDict and calling it, it will be bound to otherDict: >
Now "self" will be "otherDict". But when the dictionary was bound explicitly
this won't happen: >
1.3 Lists ~
*list* *List* *Lists* *E686*
A List is an ordered sequence of items. An item can be of any type. Items
can be accessed by their index number. Items can be added and removed at any
position in the sequence.
List creation ~
*E696* *E697*
A List is created with a comma separated list of items in square brackets.
Examples: >
:let mylist = [1, two, 3, "four"]
:let emptylist = []
List index ~
*list-index* *E684*
An item in the List can be accessed by putting the index in square brackets
after the List. Indexes are zero-based, thus the first item has index zero. >
:let item = mylist[0] " get the first item: 1
:let item = mylist[2] " get the third item: 3
To avoid an error for an invalid index use the |get()| function. When an item
is not available it returns zero or the default value you specify: >
:echo get(mylist, idx)
:echo get(mylist, idx, "NONE")
List concatenation ~
To prepend or append an item turn the item into a list by putting [] around
it. To change a list in-place see |list-modification| below.
Sublist ~
*sublist*
A part of the List can be obtained by specifying the first and last index,
separated by a colon in square brackets: >
:let shortlist = mylist[2:-1] " get List [3, "four"]
Omitting the first index is similar to zero. Omitting the last index is
similar to -1. >
:let endlist = mylist[2:] " from item 2 to the end: [3, "four"]
:let shortlist = mylist[2:2] " List with one item: [3]
:let otherlist = mylist[:] " make a copy of the List
If the first index is beyond the last item of the List or the second item is
before the first item, the result is an empty list. There is no error
message.
If the second index is equal to or greater than the length of the list the
length minus one is used: >
:let mylist = [0, 1, 2, 3]
:echo mylist[2:8] " result: [2, 3]
NOTE: mylist[s:e] means using the variable "s:e" as index. Watch out for
using a single letter variable before the ":". Insert a space when needed:
mylist[s : e].
List identity ~
*list-identity*
When variable "aa" is a list and you assign it to another variable "bb", both
variables refer to the same list. Thus changing the list "aa" will also
change "bb": >
:let aa = [1, 2, 3]
:let bb = aa
:call add(aa, 4)
:echo bb
< [1, 2, 3, 4]
Making a copy of a list is done with the |copy()| function. Using [:] also
works, as explained above. This creates a shallow copy of the list: Changing
a list item in the list will also change the item in the copied list: >
:let aa = [[1, 'a'], 2, 3]
:let bb = copy(aa)
:call add(aa, 4)
:let aa[0][1] = 'aaa'
:echo aa
< [[1, aaa], 2, 3, 4] >
:echo bb
< [[1, aaa], 2, 3]
The operator "is" can be used to check if two variables refer to the same
List. "isnot" does the opposite. In contrast "==" compares if two lists have
the same value. >
:let alist = [1, 2, 3]
:let blist = [1, 2, 3]
:echo alist is blist
< 0 >
:echo alist == blist
< 1
Note about comparing lists: Two lists are considered equal if they have the
same length and all items compare equal, as with using "==". There is one
exception: When comparing a number with a string they are considered
different. There is no automatic type conversion, as with using "==" on
variables. Example: >
echo 4 == "4"
< 1 >
echo [4] == ["4"]
< 0
Thus comparing Lists is more strict than comparing numbers and strings. You
can compare simple values this way too by putting them in a list: >
:let a = 5
:let b = "5"
:echo a == b
< 1 >
:echo [a] == [b]
< 0
List unpack ~
When the number of variables does not match the number of items in the list
this produces an error. To handle any extra items from the list append ";"
and a variable name: >
:let [var1, var2; rest] = mylist
Except that there is no error if there are only two items. "rest" will be an
empty list then.
List modification ~
*list-modification*
To change a specific item of a list use |:let| this way: >
:let list[4] = "four"
:let listlist[0][3] = item
To change part of a list you can specify the first and last item to be
modified. The value must at least have the number of items in the range: >
:let list[3:5] = [3, 4, 5]
Adding and removing items from a list is done with functions. Here are a few
examples: >
:call insert(list, 'a') " prepend item 'a'
:call insert(list, 'a', 3) " insert item 'a' before list[3]
:call add(list, "new") " append String item
:call add(list, [1, 2]) " append a List as one new item
:call extend(list, [1, 2]) " extend the list with two more items
:let i = remove(list, 3) " remove item 3
:unlet list[3] " idem
:let l = remove(list, 3, -1) " remove items 3 to last item
:unlet list[3 : ] " idem
:call filter(list, 'v:val !~ "x"') " remove items with an 'x'
For loop ~
The |:for| loop executes commands for each item in a list. A variable is set
to each item in the list in sequence. Example: >
:for item in mylist
: call Doit(item)
:endfor
If all you want to do is modify each item in the list then the |map()|
function will be a simpler method than a for loop.
Just like the |:let| command, |:for| also accepts a list of variables. This
requires the argument to be a list of lists. >
:for [lnum, col] in [[1, 3], [2, 8], [3, 0]]
: call Doit(lnum, col)
:endfor
This works like a |:let| command is done for each list item. Again, the types
must remain the same to avoid an error.
List functions ~
*E714*
Functions that are useful with a List: >
:let r = call(funcname, list) " call a function with an argument list
:if empty(list) " check if list is empty
:let l = len(list) " number of items in list
:let big = max(list) " maximum value in list
:let small = min(list) " minimum value in list
:let xs = count(list, 'x') " count nr of times 'x' appears in list
:let i = index(list, 'x') " index of first 'x' in list
:let lines = getline(1, 10) " get ten text lines from buffer
:call append('$', lines) " append text lines in buffer
:let list = split("a b c") " create list from items in a string
:let string = join(list, ', ') " create string from list items
:let s = string(list) " String representation of list
:call map(list, '">> " . v:val') " prepend ">> " to each item
Don't forget that a combination of features can make things simple. For
example, to add up all the numbers in a list: >
:exe 'let sum = ' . join(nrlist, '+')
1.4 Dictionaries ~
*dict* *Dict* *Dictionaries* *Dictionary*
A Dictionary is an associative array: Each entry has a key and a value. The
entry can be located with the key. The entries are stored without a specific
ordering.
Dictionary creation ~
*E720* *E721* *E722* *E723*
A Dictionary is created with a comma separated list of entries in curly
braces. Each entry has a key and a value, separated by a colon. Each key can
only appear once. Examples: >
:let mydict = {1: 'one', 2: 'two', 3: 'three'}
:let emptydict = {}
< *E713* *E716* *E717*
A key is always a String. You can use a Number, it will be converted to a
String automatically. Thus the String '4' and the number 4 will find the same
entry. Note that the String '04' and the Number 04 are different, since the
Number will be converted to the String '4'. The empty string can also be used
as a key.
*literal-Dict* *#{}*
To avoid having to put quotes around every key the #{} form can be used. This
does require the key to consist only of ASCII letters, digits, '-' and '_'.
Example: >
:let mydict = #{zero: 0, one_key: 1, two-key: 2, 333: 3}
Note that 333 here is the string "333". Empty keys are not possible with #{}.
Accessing entries ~
The normal way to access an entry is by putting the key in square brackets: >
:let val = mydict["one"]
:let mydict["four"] = 4
You can add new entries to an existing Dictionary this way, unlike Lists.
For keys that consist entirely of letters, digits and underscore the following
form can be used |expr-entry|: >
:let val = mydict.one
:let mydict.four = 4
Since an entry can be any type, also a List and a Dictionary, the indexing and
key lookup can be repeated: >
:echo dict.key[idx].key
You may want to loop over the entries in a dictionary. For this you need to
turn the Dictionary into a List and pass it to |:for|.
Most often you want to loop over the keys, using the |keys()| function: >
:for key in keys(mydict)
: echo key . ': ' . mydict[key]
:endfor
The List of keys is unsorted. You may want to sort them first: >
:for key in sort(keys(mydict))
If you want both the key and the value use the |items()| function. It returns
a List in which each item is a List with two items, the key and the value: >
:for [key, value] in items(mydict)
: echo key . ': ' . value
:endfor
Dictionary identity ~
*dict-identity*
Just like Lists you need to use |copy()| and |deepcopy()| to make a copy of a
Dictionary. Otherwise, assignment results in referring to the same
Dictionary: >
:let onedict = {'a': 1, 'b': 2}
:let adict = onedict
:let adict['a'] = 11
:echo onedict['a']
11
Two Dictionaries compare equal if all the key-value pairs compare equal. For
more info see |list-identity|.
Dictionary modification ~
*dict-modification*
To change an already existing entry of a Dictionary, or to add a new entry,
use |:let| this way: >
:let dict[4] = "four"
:let dict['one'] = item
Weeding out entries from a Dictionary can be done with |filter()|: >
:call filter(dict, 'v:val =~ "x"')
This removes all entries from "dict" with a value not matching 'x'.
This can also be used to remove all entries: >
call filter(dict, 0)
Dictionary function ~
*Dictionary-function* *self* *E725* *E862*
When a function is defined with the "dict" attribute it can be used in a
special way with a dictionary. Example: >
:function Mylen() dict
: return len(self.data)
:endfunction
:let mydict = {'data': [0, 1, 2, 3], 'len': function("Mylen")}
:echo mydict.len()
*numbered-function* *anonymous-function*
To avoid the extra name for the function it can be defined and directly
assigned to a Dictionary in this way: >
:let mydict = {'data': [0, 1, 2, 3]}
:function mydict.len()
: return len(self.data)
:endfunction
:echo mydict.len()
The function will then get a number and the value of dict.len is a |Funcref|
that references this function. The function can only be used through a
|Funcref|. It will automatically be deleted when there is no |Funcref|
remaining that refers to it.
If you get an error for a numbered function, you can find out what it is with
a trick. Assuming the function is 42, the command is: >
:function {42}
1.5 Blobs ~
*blob* *Blob* *Blobs* *E978*
A Blob is a binary object. It can be used to read an image from a file and
send it over a channel, for example.
A Blob mostly behaves like a |List| of numbers, where each number has the
value of an 8-bit byte, from 0 to 255.
Blob creation ~
A blob can be read from a file with |readfile()| passing the {type} argument
set to "B", for example: >
:let b = readfile('image.png', 'B')
Blob index ~
*blob-index* *E979*
A byte in the Blob can be accessed by putting the index in square brackets
after the Blob. Indexes are zero-based, thus the first byte has index zero. >
:let myblob = 0z00112233
:let byte = myblob[0] " get the first byte: 0x00
:let byte = myblob[2] " get the third byte: 0x22
A negative index is counted from the end. Index -1 refers to the last byte in
the Blob, -2 to the last but one byte, etc. >
:let last = myblob[-1] " get the last byte: 0x33
To avoid an error for an invalid index use the |get()| function. When an item
is not available it returns -1 or the default value you specify: >
:echo get(myblob, idx)
:echo get(myblob, idx, 999)
Blob iteration ~
The |:for| loop executes commands for each byte of a Blob. The loop variable is
set to each byte in the Blob. Example: >
:for byte in 0z112233
: call Doit(byte)
:endfor
This calls Doit() with 0x11, 0x22 and 0x33.
Blob concatenation ~
Part of a blob ~
A part of the Blob can be obtained by specifying the first and last index,
separated by a colon in square brackets: >
:let myblob = 0z00112233
:let shortblob = myblob[1:2] " get 0z1122
:let shortblob = myblob[2:-1] " get 0z2233
Omitting the first index is similar to zero. Omitting the last index is
similar to -1. >
:let endblob = myblob[2:] " from item 2 to the end: 0z2233
:let shortblob = myblob[2:2] " Blob with one byte: 0z22
:let otherblob = myblob[:] " make a copy of the Blob
If the first index is beyond the last byte of the Blob or the second index is
before the first index, the result is an empty Blob. There is no error
message.
If the second index is equal to or greater than the length of the list the
length minus one is used: >
:echo myblob[2:8] " result: 0z2233
Blob modification ~
*blob-modification*
To change a specific byte of a blob use |:let| this way: >
:let blob[4] = 0x44
When the index is just one beyond the end of the Blob, it is appended. Any
higher index is an error.
To change part of a blob you can specify the first and last byte to be
modified. The value must have the same number of bytes in the range: >
:let blob[3:5] = 0z334455
You can also use the functions |add()|, |remove()| and |insert()|.
Blob identity ~
When making a copy using [:] or |copy()| the values are the same, but the
identity is different: >
:let blob = 0z112233
:let blob2 = blob
:echo blob == blob2
< 1 >
:echo blob is blob2
< 1 >
:let blob3 = blob[:]
:echo blob == blob3
< 1 >
:echo blob is blob3
< 0
Making a copy of a Blob is done with the |copy()| function. Using [:] also
works, as explained above.
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|.
==============================================================================
2. Expression syntax *expression-syntax*
|expr1| expr2
expr2 ? expr1 : expr1 if-then-else
|expr2| expr3
expr3 || expr3 ... logical OR
|expr3| expr4
expr4 && expr4 ... logical AND
|expr4| expr5
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| expr6
expr6 + expr6 ... number addition, list or blob concatenation
expr6 - expr6 ... number subtraction
expr6 . expr6 ... string concatenation
expr6 .. expr6 ... string concatenation
|expr6| expr7
expr7 * expr7 ... number multiplication
expr7 / expr7 ... number division
expr7 % expr7 ... number modulo
|expr7| expr8
! expr7 logical NOT
- expr7 unary minus
+ expr7 unary plus
|expr8| expr9
expr8[expr1] byte of a String or item of a |List|
expr8[expr1 : expr1] substring of a String or sublist of a |List|
expr8.name entry in a |Dictionary|
expr8(expr1, ...) function call with |Funcref| variable
expr8->name(expr1, ...) |method| call
All expressions within one level are parsed from left to right.
You should always put a space before the ':', otherwise it can be mistaken for
use in a variable such as "a:1".
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 ~
|FALSE| |FALSE| |FALSE| |FALSE|
|FALSE| |TRUE| |TRUE| |FALSE|
|TRUE| |FALSE| |TRUE| |FALSE|
|TRUE| |TRUE| |TRUE| |TRUE|
Note that "&&" takes precedence over "||", so this has the meaning of: >
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 |TRUE|,
so the result must be |TRUE|. Similarly below: >
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
Examples:
"abc" ==# "Abc" evaluates to 0
"abc" ==? "Abc" evaluates to 1
"abc" == "Abc" evaluates to 1 if 'ignorecase' is set, 0 otherwise
*E691* *E692*
A |List| can only be compared with a |List| and only "equal", "not equal",
"is" and "isnot" can be used. This compares the values of the list,
recursively. Ignoring case means case is ignored when comparing item values.
*E735* *E736*
A |Dictionary| can only be compared with a |Dictionary| and only "equal", "not
equal", "is" and "isnot" can be used. This compares the key/values of the
|Dictionary| recursively. Ignoring case means case is ignored when comparing
item values.
*E694*
A |Funcref| can only be compared with a |Funcref| and only "equal", "not
equal", "is" and "isnot" can be used. Case is never ignored. Whether
arguments or a Dictionary are bound (with a partial) matters. The
Dictionaries must also be equal (or the same, in case of "is") and the
arguments must be equal (or the same).
To compare Funcrefs to see if they refer to the same function, ignoring bound
Dictionary and arguments, use |get()| to get the function name: >
if get(Part1, 'name') == get(Part2, 'name')
" Part1 and Part2 refer to the same function
When comparing two Strings, this is done with strcmp() or stricmp(). This
results in the mathematical difference (comparing byte values), not
necessarily the alphabetical difference in the local language.
When using the operators with a trailing '#', or the short version and
'ignorecase' is off, the comparing is done with strcmp(): case matters.
When using the operators with a trailing '?', or the short version and
'ignorecase' is set, the comparing is done with stricmp(): case is ignored.
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 and 'cpoptions' is empty, no
matter what the actual value of 'magic' or 'cpoptions' is. This makes scripts
portable. To avoid backslashes in the regexp pattern to be doubled, use a
single-quote string, see |literal-string|.
Since a string is considered to be a single line, a multi-line pattern
(containing \n, backslash-n) will not match. However, a literal NL character
can be matched like an ordinary character. Examples:
"foo\nbar" =~ "\n" evaluates to 1
"foo\nbar" =~ "\\n" evaluates to 0
For |Lists| only "+" is possible and then both expr6 must be a list. The
result is a new list with the two lists Concatenated.
Since '.' has the same precedence as '+' and '-', you need to read: >
1 . 90 + 90.0
As: >
(1 . 90) + 90.0
That works, since the String "190" is automatically converted to the Number
190, which can be added to the Float 90.0. However: >
1 . 90 * 90.0
Should be read as: >
1 . (90 * 90.0)
Since '.' has lower precedence than '*'. This does NOT work, since this
attempts to concatenate a Float and a String.
expr7 *expr7*
-----
! expr7 logical NOT *expr-!*
- expr7 unary minus *expr-unary--*
+ expr7 unary plus *expr-unary-+*
expr8 *expr8*
-----
This expression is either |expr9| or a sequence of the alternatives below,
in any order. E.g., these are all possible:
expr8[expr1].name
expr8.name[expr1]
expr8(expr1, ...)[expr1].name
expr8->(expr1, ...)[expr1]
Evaluation is always from left to right.
Index zero gives the first byte. This is like it works in C. Careful:
text column numbers start with one! Example, to get the byte under the
cursor: >
:let c = getline(".")[col(".") - 1]
If the length of the String is less than the index, the result is an empty
String. A negative index always results in an empty string (reason: backward
compatibility). Use [-1:] to get the last byte.
If expr8 is a |List| then it results the item at index expr1. See |list-index|
for possible index values. If the index is out of range this results in an
error. Example: >
:let item = mylist[-1] " get last item
If expr8 is a Number or String this results in the substring with the bytes
from expr1a to and including expr1b. expr8 is used as a String, expr1a and
expr1b are used as a Number. This doesn't recognize multi-byte encodings, see
|byteidx()| for computing the indexes.
A negative number can be used to measure from the end of the string. -1 is
the last character, -2 the last but one, etc.
If an index goes out of range for the string characters are omitted. If
expr1b is smaller than expr1a the result is an empty string.
Examples: >
:let c = name[-1:] " last byte of a string
:let c = name[-2:-2] " last but one byte of a string
:let s = line(".")[4:] " from the fifth byte to the end
:let s = s[:-3] " remove last two bytes
<
*slice*
If expr8 is a |List| this results in a new |List| with the items indicated by
the indexes expr1a and expr1b. This works like with a String, as explained
just above. Also see |sublist| below. Examples: >
:let l = mylist[:3] " first four items
:let l = mylist[4:4] " List with one item
:let l = mylist[:] " shallow copy of a List
If expr8 is a |Blob| this results in a new |Blob| with the bytes in the
indexes expr1a and expr1b, inclusive. Examples: >
:let b = 0zDEADBEEF
:let bs = b[1:2] " 0zADBE
:let bs = b[:] " copy of 0zDEADBEEF
Watch out for confusion between a namespace and a variable followed by a colon
for a sublist: >
mylist[n:] " uses variable n
mylist[s:] " uses namespace s:, error!
The name must consist of alphanumeric characters, just like a variable name,
but it may start with a number. Curly braces cannot be used.
Examples: >
:let dict = {"one": 1, 2: "two"}
:echo dict.one " shows "1"
:echo dict.2 " shows "two"
:echo dict .2 " error because of space before the dot
Note that the dot is also used for String concatenation. To avoid confusion
always put spaces around the dot for String concatenation.
When expr8 is a |Funcref| type variable, invoke the function it refers to.
This allows for chaining, passing the value that one method returns to the
next method: >
mylist->filter(filterexpr)->map(mapexpr)->sort()->join()
<
Example of using a lambda: >
GetPercentage()->{x -> x * 100}()->printf('%d%%')
<
When using -> the |expr7| operators will be applied first, thus: >
-1.234->string()
Is equivalent to: >
(-1.234)->string()
And NOT: >
-(1.234->string())
<
*E274*
"->name(" must not contain white space. There can be white space before the
"->" and after the "(", thus you can split the lines like this: >
mylist
\ ->filter(filterexpr)
\ ->map(mapexpr)
\ ->sort()
\ ->join()
When using the lambda form there must be no white space between the } and the
(.
*expr9*
number
------
number number constant *expr-number*
*hex-number* *octal-number* *binary-number*
*floating-point-format*
Floating point numbers can be written in two forms:
[-+]{N}.{M}
[-+]{N}.{M}[eE][-+]{exp}
{N} and {M} are numbers. Both {N} and {M} must be present and can only
contain digits.
[-+] means there is an optional plus or minus sign.
{exp} is the exponent, power of 10.
Only a decimal point is accepted, not a comma. No matter what the current
locale is.
{only when compiled with the |+float| feature}
Examples:
123.456
+0.0001
55.0
-0.123
1.234e03
1.0E-6
-3.1416e+88
Rationale:
Before floating point was introduced, the text "123.456" was interpreted as
the two numbers "123" and "456", both converted to a string and concatenated,
resulting in the string "123456". Since this was considered pointless, and we
could not find it intentionally being used in Vim scripts, this backwards
incompatibility was accepted in favor of being able to use the normal notation
for floating point numbers.
*float-pi* *float-e*
A few useful values to copy&paste: >
:let pi = 3.14159265359
:let e = 2.71828182846
Or, if you don't want to write them in as floating-point literals, you can
also use functions, like the following: >
:let pi = acos(-1.0)
:let e = exp(1.0)
<
*floating-point-precision*
The precision and range of floating points numbers depends on what "double"
means in the library Vim was compiled with. There is no way to change this at
runtime.
The default for displaying a |Float| is to use 6 decimal places, like using
printf("%g", f). You can select something else when using the |printf()|
function. Example: >
:echo printf('%.15e', atan(1))
< 7.853981633974483e-01
Note that "\xff" is stored as the byte 255, which may be invalid in some
encodings. Use "\u00ff" to store character 255 according to the current value
of 'encoding'.
Note that "\000" and "\x00" force the end of the string.
Single quoted strings are useful for patterns, so that backslashes do not need
to be doubled. These two commands are equivalent: >
if a =~ "\\s*"
if a =~ '\s*'
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.
When using the '=' register you get the expression itself, not what it
evaluates to. Use |eval()| to evaluate it.
nesting *expr-nesting* *E110*
-------
(expr1) nested expression
The String value of any environment variable. When it is not defined, the
result is an empty string.
The functions `getenv()` and `setenv()` can also be used and work for
environment variables with non-alphanumeric names.
The function `environ()` can be used to get a Dict with all environment
variables.
*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 $shell
:echo expand("$shell")
The first one probably doesn't echo anything, the second echoes the $shell
variable (if your shell supports it).
A lambda expression creates a new unnamed function which returns the result of
evaluating |expr1|. Lambda expressions differ from |user-functions| in
the following ways:
1. The body of the lambda expression is an |expr1| and not a sequence of |Ex|
commands.
2. The prefix "a:" should not be used for arguments. E.g.: >
:let F = {arg1, arg2 -> arg1 - arg2}
:echo F(5, 2)
< 3
The arguments are optional. Example: >
:let F = {-> 'error function'}
:echo F()
< error function
*closure*
Lambda expressions can access outer scope variables and arguments. This is
often called a closure. Example where "i" and "a:arg" are used in a lambda
while they already exist in the function scope. They remain valid even after
the function returns: >
:function Foo(arg)
: let i = 3
: return {x -> x + i - a:arg}
:endfunction
:let Bar = Foo(4)
:echo Bar(6)
< 5
Note that the variables must exist in the outer scope before the lambda is
defined for this to work. See also |:func-closure|.
Examples for using a lambda expression with |sort()|, |map()| and |filter()|: >
:echo map([1, 2, 3], {idx, val -> val + 1})
< [2, 3, 4] >
:echo sort([3,7,2,1,4], {a, b -> a - b})
< [1, 2, 3, 4, 7]
The lambda expression is also useful for Channel, Job and timer: >
:let timer = timer_start(500,
\ {-> execute("echo 'Handler called'", "")},
\ {'repeat': 3})
< Handler called
Handler called
Handler called
Lambda expressions have internal names like '<lambda>42'. If you get an error
for a lambda expression, you can find what it is with the following command: >
:function {'<lambda>42'}
See also: |numbered-function|
==============================================================================
3. Internal variable *internal-variables* *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|.
There are several name spaces for variables. Which one is to be used is
specified by what is prepended:
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.
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|.
*v:argv* *argv-variable*
v:argv The command line arguments Vim was invoked with. This is a
list of strings. The first item is the Vim command.
*v:beval_col* *beval_col-variable*
v:beval_col The number of the column, over which the mouse pointer is.
This is the byte index in the |v:beval_lnum| line.
Only valid while evaluating the 'balloonexpr' option.
*v:beval_bufnr* *beval_bufnr-variable*
v:beval_bufnr The number of the buffer, over which the mouse pointer is. Only
valid while evaluating the 'balloonexpr' option.
*v:beval_lnum* *beval_lnum-variable*
v:beval_lnum The number of the line, over which the mouse pointer is. Only
valid while evaluating the 'balloonexpr' option.
*v:beval_text* *beval_text-variable*
v:beval_text The text under or after the mouse pointer. Usually a word as
it is useful for debugging a C program. 'iskeyword' applies,
but a dot and "->" before the position is included. When on a
']' the text before it is used, including the matching '[' and
word before it. When on a Visual area within one line the
highlighted text is used. Also see |<cexpr>|.
Only valid while evaluating the 'balloonexpr' option.
*v:beval_winnr* *beval_winnr-variable*
v:beval_winnr The number of the window, over which the mouse pointer is. Only
valid while evaluating the 'balloonexpr' option. The first
window has number zero (unlike most other places where a
window gets a number).
*v:beval_winid* *beval_winid-variable*
v:beval_winid The |window-ID| of the window, over which the mouse pointer
is. Otherwise like v:beval_winnr.
*v:char* *char-variable*
v:char Argument for evaluating 'formatexpr' and used for the typed
character when using <expr> in an abbreviation |:map-<expr>|.
It is also used by the |InsertCharPre| and |InsertEnter| events.
*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 |<bang>|
can be used.
*v:completed_item* *completed_item-variable*
v:completed_item
|Dictionary| containing the |complete-items| for the most
recently completed word after |CompleteDone|. The
|Dictionary| is empty if the completion failed.
*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 :<C-U>echo "the count is " . v:count<CR>
< Note: The <C-U> is required to remove the line range that you
get when typing ':' after a count.
When there are two counts, as in "3d2w", they are multiplied,
just like what happens in the command, "d6w" for the example.
Also used for evaluating the 'formatexpr' option.
"count" also works, for backwards compatibility, unless
|scriptversion| is 3 or higher.
*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
< Note: if another deadly signal is caught when v:dying is one,
VimLeave autocommands will not be executed.
*v:echospace* *echospace-variable*
v:echospace Number of screen cells that can be used for an `:echo` message
in the last screen line before causing the |hit-enter-prompt|.
Depends on 'showcmd', 'ruler' and 'columns'. You need to
check 'cmdheight' for whether there are full-width lines
available above the last line.
*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, unless
|scriptversion| is 3 or higher.
*v:event* *event-variable*
v:event Dictionary containing information about the current
|autocommand|. See the specific event for what it puts in
this dictionary.
The dictionary is emptied when the |autocommand| finishes,
please refer to |dict-identity| for how to get an independent
copy of it. Use |deepcopy()| if you want to keep the
information after the event triggers. Example: >
au TextYankPost * let g:foo = deepcopy(v:event)
<
*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:false* *false-variable*
v:false A Number with value zero. Used to put "false" in JSON. See
|json_encode()|.
When used as a string this evaluates to "v:false". >
echo v:false
< v:false ~
That is so that eval() can parse the string back to the same
value. Read-only.
*v:fcs_reason* *fcs_reason-variable*
v:fcs_reason The reason why the |FileChangedShell| event was triggered.
Can be used in an autocommand to decide what to do and/or what
to set v:fcs_choice to. Possible values:
deleted file no longer exists
conflict file contents, mode or timestamp was
changed and buffer is modified
changed file contents has changed
mode mode of file changed
time only file timestamp changed
*v:fcs_choice* *fcs_choice-variable*
v:fcs_choice What should happen after a |FileChangedShell| event was
triggered. Can be used in an autocommand to tell Vim what to
do with the affected buffer:
reload Reload the buffer (does not work if
the file was deleted).
ask Ask the user what to do, as if there
was no autocommand. Except that when
only the timestamp changed nothing
will happen.
<empty> Nothing, the autocommand should do
everything that needs to be done.
The default is empty. If another (invalid) value is used then
Vim behaves like it is empty, there is no warning message.
*v:fname_in* *fname_in-variable*
v:fname_in The name of the input file. Valid while evaluating:
option used for ~
'charconvert' file to be converted
'diffexpr' original file
'patchexpr' original file
'printexpr' file to be printed
And set to the swap file name for |SwapExists|.
*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 in the |sandbox|. |fold-foldtext|
*v:foldlevel* *foldlevel-variable*
v:foldlevel Used for 'foldtext': foldlevel of closed fold.
Read-only in the |sandbox|. |fold-foldtext|
*v:foldend* *foldend-variable*
v:foldend Used for 'foldtext': last line of closed fold.
Read-only in the |sandbox|. |fold-foldtext|
*v:foldstart* *foldstart-variable*
v:foldstart Used for 'foldtext': first line of closed fold.
Read-only in the |sandbox|. |fold-foldtext|
*v:hlsearch* *hlsearch-variable*
v:hlsearch Variable that indicates whether search highlighting is on.
Setting it makes sense only if 'hlsearch' is enabled which
requires |+extra_search|. Setting this variable to zero acts
like the |:nohlsearch| command, setting it to one acts like >
let &hlsearch = &hlsearch
< Note that the value is restored when returning from a
function. |function-search-undo|.
*v:insertmode* *insertmode-variable*
v:insertmode Used for the |InsertEnter| and |InsertChange| autocommand
events. Values:
i Insert mode
r Replace mode
v Virtual Replace mode
*v:key* *key-variable*
v:key Key of the current item of a |Dictionary|. Only valid while
evaluating the expression used with |map()| and |filter()|.
Read-only.
*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' |fold-expr|, 'formatexpr' and
'indentexpr' expressions, tab page number for 'guitablabel'
and 'guitabtooltip'. Only valid while one of these
expressions is being evaluated. Read-only when in the
|sandbox|.
*v:mouse_win* *mouse_win-variable*
v:mouse_win Window number for a mouse click obtained with |getchar()|.
First window has number 1, like with |winnr()|. The value is
zero when there was no mouse button click.
*v:mouse_winid* *mouse_winid-variable*
v:mouse_winid Window ID for a mouse click obtained with |getchar()|.
The value is zero when there was no mouse button click.
*v:mouse_lnum* *mouse_lnum-variable*
v:mouse_lnum Line number for a mouse click obtained with |getchar()|.
This is the text line number, not the screen line number. The
value is zero when there was no mouse button click.
*v:mouse_col* *mouse_col-variable*
v:mouse_col Column number for a mouse click obtained with |getchar()|.
This is the screen column number, like with |virtcol()|. The
value is zero when there was no mouse button click.
*v:null* *null-variable*
v:null An empty String. Used to put "null" in JSON. See
|json_encode()|.
When used as a number this evaluates to zero.
When used as a string this evaluates to "v:null". >
echo v:null
< v:null ~
That is so that eval() can parse the string back to the same
value. Read-only.
*v:numbersize* *numbersize-variable*
v:numbersize Number of bits in a Number. This is normally 64, but on some
systems it may be 32.
*v:oldfiles* *oldfiles-variable*
v:oldfiles List of file names that is loaded from the |viminfo| file on
startup. These are the files that Vim remembers marks for.
The length of the List is limited by the ' argument of the
'viminfo' option (default is 100).
When the |viminfo| file is not used the List is empty.
Also see |:oldfiles| and |c_#<|.
The List can be modified, but this has no effect on what is
stored in the |viminfo| file later. If you use values other
than String this will cause trouble.
{only when compiled with the |+viminfo| feature}
*v:option_new*
v:option_new New value of the option. Valid while executing an |OptionSet|
autocommand.
*v:option_old*
v:option_old Old value of the option. Valid while executing an |OptionSet|
autocommand. Depending on the command used for setting and the
kind of option this is either the local old value or the
global old value.
*v:option_oldlocal*
v:option_oldlocal
Old local value of the option. Valid while executing an
|OptionSet| autocommand.
*v:option_oldglobal*
v:option_oldglobal
Old global value of the option. Valid while executing an
|OptionSet| autocommand.
*v:option_type*
v:option_type Scope of the set command. Valid while executing an
|OptionSet| autocommand. Can be either "global" or "local"
*v:option_command*
v:option_command
Command used to set the option. Valid while executing an
|OptionSet| autocommand.
value option was set via ~
"setlocal" |:setlocal| or ":let l:xxx"
"setglobal" |:setglobal| or ":let g:xxx"
"set" |:set| or |:let|
"modeline" |modeline|
*v:operator* *operator-variable*
v:operator The last operator given in Normal mode. This is a single
character except for commands starting with <g> or <z>,
in which case it is two characters. Best used alongside
|v:prevcount| and |v:register|. Useful if you want to cancel
Operator-pending mode and then use the operator, e.g.: >
:omap O <Esc>:call MyMotion(v:operator)<CR>
< The value remains set until another operator is entered, thus
don't expect it to be empty.
v:operator is not set for |:delete|, |:yank| or other Ex
commands.
Read-only.
*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 or Operator-pending mode and then
use the count, e.g.: >
:vmap % <Esc>:call MyFilter(v:prevcount)<CR>
< Read-only.
*v:profiling* *profiling-variable*
v:profiling Normally zero. Set to one after using ":profile start".
See |profiling|.
*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:progpath* *progpath-variable*
v:progpath Contains the command with which Vim was invoked, in a form
that when passed to the shell will run the same Vim executable
as the current one (if $PATH remains unchanged).
Useful if you want to message a Vim server using a
|--remote-expr|.
To get the full path use: >
echo exepath(v:progpath)
< If the command has a relative path it will be expanded to the
full path, so that it still works after `:cd`. Thus starting
"./vim" results in "/home/user/path/to/vim/src/vim".
On Linux and other systems it will always be the full path.
On Mac it may just be "vim" and using exepath() as mentioned
above should be used to get the full path.
On MS-Windows the executable may be called "vim.exe", but the
".exe" is not added to v:progpath.
Read-only.
*v:register* *register-variable*
v:register The name of the register in effect for the current normal mode
command (regardless of whether that command actually used a
register). Or for the currently executing normal mode mapping
(use this in custom commands that take a register).
If none is supplied it is the default register '"', unless
'clipboard' contains "unnamed" or "unnamedplus", then it is
'*' or '+'.
Also see |getreg()| and |setreg()|
*v:scrollstart* *scrollstart-variable*
v:scrollstart String describing the script or function that caused the
screen to scroll up. It's only set when it is empty, thus the
first reason is remembered. It is set to "Unknown" for a
typed command.
This can be used to find out why your script causes the
hit-enter prompt.
*v:servername* *servername-variable*
v:servername The resulting registered |client-server-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, unless
|scriptversion| is 3 or higher.
*v:statusmsg* *statusmsg-variable*
v:statusmsg Last given status message. It's allowed to set this variable.
*v:swapname* *swapname-variable*
v:swapname Only valid when executing |SwapExists| autocommands: Name of
the swap file found. Read-only.
*v:swapchoice* *swapchoice-variable*
v:swapchoice |SwapExists| autocommands can set this to the selected choice
for handling an existing swap file:
'o' Open read-only
'e' Edit anyway
'r' Recover
'd' Delete swapfile
'q' Quit
'a' Abort
The value should be a single-character string. An empty value
results in the user being asked, as would happen when there is
no SwapExists autocommand. The default is empty.
*v:swapcommand* *swapcommand-variable*
v:swapcommand Normal mode command to be executed after a file has been
opened. Can be used for a |SwapExists| autocommand to have
another Vim open the file and jump to the right place. For
example, when jumping to a tag the value is ":tag tagname\r".
For ":edit +cmd file" the value is ":cmd\r".
*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, then '>' or '?' 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: "<Esc>[> 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:termblinkresp*
v:termblinkresp The escape sequence returned by the terminal for the |t_RC|
termcap entry. This is used to find out whether the terminal
cursor is blinking. This is used by |term_getcursor()|.
*v:termstyleresp*
v:termstyleresp The escape sequence returned by the terminal for the |t_RS|
termcap entry. This is used to find out what the shape of the
cursor is. This is used by |term_getcursor()|.
*v:termrbgresp*
v:termrbgresp The escape sequence returned by the terminal for the |t_RB|
termcap entry. This is used to find out what the terminal
background color is, see 'background'.
*v:termrfgresp*
v:termrfgresp The escape sequence returned by the terminal for the |t_RF|
termcap entry. This is used to find out what the terminal
foreground color is.
*v:termu7resp*
v:termu7resp The escape sequence returned by the terminal for the |t_u7|
termcap entry. This is used to find out what the terminal
does with ambiguous width characters, see 'ambiwidth'.
*v:testing* *testing-variable*
v:testing Must be set before using `test_garbagecollect_now()`.
Also, when set certain error messages won't be shown for 2
seconds. (e.g. "'dictionary' option is empty")
*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, unless
|scriptversion| is 3 or higher
*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:true* *true-variable*
v:true A Number with value one. Used to put "true" in JSON. See
|json_encode()|.
When used as a string this evaluates to "v:true". >
echo v:true
< v:true ~
That is so that eval() can parse the string back to the same
value. Read-only.
*v:val* *val-variable*
v:val Value of the current item of a |List| or |Dictionary|. Only
valid while evaluating the expression used with |map()| and
|filter()|. Read-only.
*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
is 501. Read-only. "version" also works, for backwards
compatibility, unless |scriptversion| is 3 or higher.
Use |has()| to check if a certain patch was included, e.g.: >
if has("patch-7.4.123")
< 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:versionlong* *versionlong-variable*
v:versionlong Like v:version, but also including the patchlevel in the last
four digits. Version 8.1 with patch 123 has value 8010123.
This can be used like this: >
if v:versionlong >= 8010123
< However, if there are gaps in the list of patches included
this will not work well. This can happen if a recent patch
was included into an older version, e.g. for a security fix.
Use the has() function to make sure the patch is actually
included.
*v:vim_did_enter* *vim_did_enter-variable*
v:vim_did_enter Zero until most of startup is done. It is set to one just
before |VimEnter| autocommands are triggered.
*v:warningmsg* *warningmsg-variable*
v:warningmsg Last given warning message. It's allowed to set this variable.
*v:windowid* *windowid-variable*
v:windowid When any X11 based GUI is running or when running in a
terminal and Vim connects to the X server (|-X|) this will be
set to the window ID.
When an MS-Windows GUI is running this will be set to the
window handle.
Otherwise the value is zero.
Note: for windows inside Vim use |winnr()| or |win_getid()|,
see |window-ID|.
==============================================================================
4. Builtin Functions *functions*
See |function-list| for a list grouped by what the function is used for.
abs({expr}) *abs()*
Return the absolute value of {expr}. When {expr} evaluates to
a |Float| abs() returns a |Float|. When {expr} can be
converted to a |Number| abs() returns a |Number|. Otherwise
abs() gives an error message and returns -1.
Examples: >
echo abs(1.456)
< 1.456 >
echo abs(-5.456)
< 5.456 >
echo abs(-4)
< 4
acos({expr}) *acos()*
Return the arc cosine of {expr} measured in radians, as a
|Float| in the range of [0, pi].
{expr} must evaluate to a |Float| or a |Number| in the range
[-1, 1].
Examples: >
:echo acos(0)
< 1.570796 >
:echo acos(-0.5)
< 2.094395
argc([{winid}]) *argc()*
The result is the number of files in the argument list. See
|arglist|.
If {winid} is not supplied, the argument list of the current
window is used.
If {winid} is -1, the global argument list is used.
Otherwise {winid} specifies the window of which the argument
list is used: either the window number or the window ID.
Returns -1 if the {winid} argument is invalid.
*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|.
*arglistid()*
arglistid([{winnr} [, {tabnr}]])
Return the argument list ID. This is a number which
identifies the argument list being used. Zero is used for the
global argument list. See |arglist|.
Returns -1 if the arguments are invalid.
*argv()*
argv([{nr} [, {winid}]])
The result is the {nr}th file in the argument list. See
|arglist|. "argv(0)" is the first one. Example: >
:let i = 0
:while i < argc()
: let f = escape(fnameescape(argv(i)), '.')
: exe 'amenu Arg.' . f . ' :e ' . f . '<CR>'
: let i = i + 1
:endwhile
< Without the {nr} argument, or when {nr} is -1, a |List| with
the whole |arglist| is returned.
asin({expr}) *asin()*
Return the arc sine of {expr} measured in radians, as a |Float|
in the range of [-pi/2, pi/2].
{expr} must evaluate to a |Float| or a |Number| in the range
[-1, 1].
Examples: >
:echo asin(0.8)
< 0.927295 >
:echo asin(-0.5)
< -0.523599
atan({expr}) *atan()*
Return the principal value of the arc tangent of {expr}, in
the range [-pi/2, +pi/2] radians, as a |Float|.
{expr} must evaluate to a |Float| or a |Number|.
Examples: >
:echo atan(100)
< 1.560797 >
:echo atan(-4.01)
< -1.326405
balloon_gettext() *balloon_gettext()*
Return the current text in the balloon. Only for the string,
not used for the List.
balloon_show({expr}) *balloon_show()*
Show {expr} inside the balloon. For the GUI {expr} is used as
a string. For a terminal {expr} can be a list, which contains
the lines of the balloon. If {expr} is not a list it will be
split with |balloon_split()|.
If {expr} is an empty string any existing balloon is removed.
Example: >
func GetBalloonContent()
" ... initiate getting the content
return ''
endfunc
set balloonexpr=GetBalloonContent()
func BalloonCallback(result)
call balloon_show(a:result)
endfunc
< Can also be used as a |method|: >
GetText()->balloon_show()
<
The intended use is that fetching the content of the balloon
is initiated from 'balloonexpr'. It will invoke an
asynchronous method, in which a callback invokes
balloon_show(). The 'balloonexpr' itself can return an
empty string or a placeholder.
balloon_split({msg}) *balloon_split()*
Split {msg} into lines to be displayed in a balloon. The
splits are made for the current window size and optimize to
show debugger output.
Returns a |List| with the split lines.
Can also be used as a |method|: >
GetText()->balloon_split()->balloon_show()
*browse()*
browse({save}, {title}, {initdir}, {default})
Put up a file requester. This only works when "has("browse")"
returns |TRUE| (only in some GUI versions).
The input fields are:
{save} when |TRUE|, select file to write
{title} title for the requester
{initdir} directory to start browsing in
{default} default file name
An empty string is returned when the "Cancel" button is hit,
something went wrong, or browsing is not possible.
*browsedir()*
browsedir({title}, {initdir})
Put up a directory requester. This only works when
"has("browse")" returns |TRUE| (only in some GUI versions).
On systems where a directory browser is not supported a file
browser is used. In that case: select a file in the directory
to be used.
The input fields are:
{title} title for the requester
{initdir} directory to start browsing in
When the "Cancel" button is hit, something went wrong, or
browsing is not possible, an empty string is returned.
bufadd({name}) *bufadd()*
Add a buffer to the buffer list with {name}.
If a buffer for file {name} already exists, return that buffer
number. Otherwise return the buffer number of the newly
created buffer. When {name} is an empty string then a new
buffer is always created.
The buffer will not have 'buflisted' set and not be loaded
yet. To add some text to the buffer use this: >
let bufnr = bufadd('someName')
call bufload(bufnr)
call setbufline(bufnr, 1, ['some', 'text'])
< Can also be used as a |method|: >
let bufnr = 'somename'->bufadd()
bufexists({expr}) *bufexists()*
The result is a Number, which is |TRUE| if a buffer called
{expr} exists.
If the {expr} argument is a number, buffer numbers are used.
Number zero is the alternate buffer for the current window.
bufload({expr}) *bufload()*
Ensure the buffer {expr} is loaded. When the buffer name
refers to an existing file then the file is read. Otherwise
the buffer will be empty. If the buffer was already loaded
then there is no change.
If there is an existing swap file for the file of the buffer,
there will be no dialog, the buffer will be loaded anyway.
The {expr} argument is used like with |bufexists()|.
bufloaded({expr}) *bufloaded()*
The result is a Number, which is |TRUE| 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 omitted the current buffer is used.
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. If you only want a
full match then put "^" at the start and "$" at the end of the
pattern.
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)
< Can also be used as a |method|: >
echo bufnr->bufname()
*bufnr()*
bufnr([{expr} [, {create}]])
The result is the number of a buffer, as it is displayed by
the ":ls" command. For the use of {expr}, see |bufname()|
above.
bufwinid({expr}) *bufwinid()*
The result is a Number, which is the |window-ID| 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: >
bufwinnr({expr}) *bufwinnr()*
Like |bufwinid()| but return the window number instead of the
|window-ID|.
If buffer {expr} doesn't exist or there is no such window, -1
is returned. Example: >
< 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|.
ceil({expr}) *ceil()*
Return the smallest integral value greater than or equal to
{expr} as a |Float| (round up).
{expr} must evaluate to a |Float| or a |Number|.
Examples: >
echo ceil(1.456)
< 2.0 >
echo ceil(-5.456)
< -5.0 >
echo ceil(4.0)
< 4.0
changenr() *changenr()*
Return the number of the most recent change. This is the same
number as what is displayed with |:undolist| and can be used
with the |:undo| command.
When a change was made it is the number of that change. After
redo it is the number of the redone change. After undo it is
one less than the number of the undone change.
chdir({dir}) *chdir()*
Change the current working directory to {dir}. The scope of
the directory change depends on the directory of the current
window:
- If the current window has a window-local directory
(|:lcd|), then changes the window local directory.
- Otherwise, if the current tabpage has a local
directory (|:tcd|) then changes the tabpage local
directory.
- Otherwise, changes the global directory.
{dir} must be a String.
If successful, returns the previous working directory. Pass
this to another chdir() to restore the directory.
On failure, returns an empty string.
Example: >
let save_dir = chdir(newdir)
if save_dir != ""
" ... do some work
call chdir(save_dir)
endif
clearmatches([{win}]) *clearmatches()*
Clears all matches previously defined for the current window
by |matchadd()| and the |:match| commands.
If {win} is specified, use the window with this number or
window ID instead of the current window.
func! ListMonths()
call complete(col('.'), ['January', 'February', 'March',
\ 'April', 'May', 'June', 'July', 'August', 'September',
\ 'October', 'November', 'December'])
return ''
endfunc
< This isn't very useful, but it shows how it works. Note that
an empty string is returned to avoid a zero being inserted.
complete_add({expr}) *complete_add()*
Add {expr} to the list of matches. Only to be used by the
function specified with the 'completefunc' option.
Returns 0 for failure (empty string or out of memory),
1 when the match was added, 2 when the match was already in
the list.
See |complete-functions| for an explanation of {expr}. It is
the same as one item in the list that 'omnifunc' would return.
complete_check() *complete_check()*
Check for a key typed while looking for completion matches.
This is to be used when looking for matches takes some time.
Returns |TRUE| when searching for matches is to be aborted,
zero otherwise.
Only to be used by the function specified with the
'completefunc' option.
*complete_info()*
complete_info([{what}])
Returns a Dictionary with information about Insert mode
completion. See |ins-completion|.
The items are:
mode Current completion mode name string.
See |complete_info_mode| for the values.
pum_visible |TRUE| if popup menu is visible.
See |pumvisible()|.
items List of completion matches. Each item is a
dictionary containing the entries "word",
"abbr", "menu", "kind", "info" and "user_data".
See |complete-items|.
selected Selected item index. First index is zero.
Index is -1 if no item is selected (showing
typed text only)
inserted Inserted string. [NOT IMPLEMENT YET]
*complete_info_mode*
mode values are:
"" Not in completion mode
"keyword" Keyword completion |i_CTRL-X_CTRL-N|
"ctrl_x" Just pressed CTRL-X |i_CTRL-X|
"whole_line" Whole lines |i_CTRL-X_CTRL-L|
"files" File names |i_CTRL-X_CTRL-F|
"tags" Tags |i_CTRL-X_CTRL-]|
"path_defines" Definition completion |i_CTRL-X_CTRL-D|
"path_patterns" Include completion |i_CTRL-X_CTRL-I|
"dictionary" Dictionary |i_CTRL-X_CTRL-K|
"thesaurus" Thesaurus |i_CTRL-X_CTRL-T|
"cmdline" Vim Command line |i_CTRL-X_CTRL-V|
"function" User defined completion |i_CTRL-X_CTRL-U|
"omni" Omni completion |i_CTRL-X_CTRL-O|
"spell" Spelling suggestions |i_CTRL-X_s|
"eval" |complete()| completion
"unknown" Other internal modes
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.
cos({expr}) *cos()*
Return the cosine of {expr}, measured in radians, as a |Float|.
{expr} must evaluate to a |Float| or a |Number|.
Examples: >
:echo cos(100)
< 0.862319 >
:echo cos(-4.01)
< -0.646043
cosh({expr}) *cosh()*
Return the hyperbolic cosine of {expr} as a |Float| in the range
[1, inf].
{expr} must evaluate to a |Float| or a |Number|.
Examples: >
:echo cosh(0.5)
< 1.127626 >
:echo cosh(-0.5)
< -1.127626
If {start} is given then start with the item with this index.
{start} can only be used with a |List|.
When {ic} is given and it's |TRUE| then case is ignored.
debugbreak({pid}) *debugbreak()*
Specifically used to interrupt a program being debugged. It
will cause process {pid} to get a SIGTRAP. Behavior for other
processes is undefined. See |terminal-debugger|.
{only available on MS-Windows}
{first} and {last} are used like with |getline()|. Note that
when using |line()| this refers to the current buffer. Use "$"
to refer to the last line in buffer {expr}.
diff_filler({lnum}) *diff_filler()*
Returns the number of filler lines above line {lnum}.
These are the lines that were inserted at this point in
another diff'ed window. These filler lines are shown in the
display but don't exist in the buffer.
{lnum} is used like with |getline()|. Thus "." is the current
line, "'m" mark m, etc.
Returns 0 if the current window is not in diff mode.
Can also be used as a |method|: >
GetLnum()->diff_filler()
echoraw({expr}) *echoraw()*
Output {expr} as-is, including unprintable characters. This
can be used to output a terminal code. For example, to disable
modifyOtherKeys: >
call echoraw(&t_TE)
< and to enable it again: >
call echoraw(&t_TI)
< Use with care, you can mess up the terminal this way.
empty({expr}) *empty()*
Return the Number 1 if {expr} is empty, zero otherwise.
- A |List| or |Dictionary| is empty when it does not have any
items.
- A |String| is empty when its length is zero.
- A |Number| and |Float| are empty when their value is zero.
- |v:false|, |v:none| and |v:null| are empty, |v:true| is not.
- A |Job| is empty when it failed to start.
- A |Channel| is empty when it is closed.
- A |Blob| is empty when its length is zero.
environ() *environ()*
Return all of environment variables as dictionary. You can
check if an environment variable exists like this: >
:echo has_key(environ(), 'HOME')
< Note that the variable name may be CamelCase; to ignore case
use this: >
:echo index(keys(environ()), 'HOME', 0, 1) != -1
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 value of $PATH and/or the normal
searchpath for programs. *PATHEXT*
On MS-Windows the ".exe", ".bat", etc. can optionally be
included. Then the extensions in $PATHEXT are tried. Thus if
"foo.exe" does not exist, "foo.exe.bat" can be found. If
$PATHEXT is not set then ".com;.exe;.bat;.cmd" is used. A dot
by itself can be used in $PATHEXT to try using the name
without an extension. When 'shell' looks like a Unix shell,
then the name is also tried without adding an extension.
On MS-Windows it only checks if the file exists and is not a
directory, not if it's really executable.
On MS-Windows an executable in the same directory as Vim is
always found. Since this directory is added to $PATH it
should also work to execute it |win32-PATH|.
The result is a Number:
1 exists
0 does not exist
-1 not implemented on this system
|exepath()| can be used to get the full path of an executable.
exepath({expr}) *exepath()*
If {expr} is an executable and is either an absolute path, a
relative path or found in $PATH, return the full path.
Note that the current directory is used when {expr} starts
with "./", which may be a problem for Vim: >
echo exepath(v:progpath)
< If {expr} cannot be found in $PATH or is not executable then
an empty string is returned.
Examples: >
exists("&shortname")
exists("$HOSTNAME")
exists("*strftime")
exists("*s:MyFunc")
exists("bufcount")
exists(":Make")
exists("#CursorHold")
exists("#BufReadPre#*.gz")
exists("#filetypeindent")
exists("#filetypeindent#FileType")
exists("#filetypeindent#FileType#*")
exists("##ColorScheme")
< There must be no space between the symbol (&/$/*/#) and the
name.
There must be no extra characters after the name, although in
a few cases this is ignored. That may become more strict in
the future, thus don't count on it!
Working example: >
exists(":make")
< NOT working example: >
exists(":make install")
< 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 value of "bufcount", and checks if that exists.
exp({expr}) *exp()*
Return the exponential of {expr} as a |Float| in the range
[0, inf].
{expr} must evaluate to a |Float| or a |Number|.
Examples: >
:echo exp(2)
< 7.389056 >
:echo exp(-1)
< 0.367879
When {expr} starts with '%', '#' or '<', the expansion is done
like for the |cmdline-special| variables with their associated
modifiers. Here is a short overview:
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 "<cfile>" and others only returns the
referenced file name without further expansion. If "<cfile>"
is "~/.cshrc", you need to do another expand() to have the
"~/" expanded into the path of the home directory: >
:echo expand(expand("<cfile>"))
<
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.
expandcmd({expr}) *expandcmd()*
Expand special items in {expr} like what is done for an Ex
command such as `:edit`. This expands special keywords, like
with |expand()|, and environment variables, anywhere in
{expr}. "~user" and "~/path" are only expanded at the start.
Returns the expanded string. Example: >
:echo expandcmd('make %<.o')
< Can also be used as a |method|: >
GetCommand()->expandcmd()
<
extend({expr1}, {expr2} [, {expr3}]) *extend()*
{expr1} and {expr2} must be both |Lists| or both
|Dictionaries|.
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.
If you don't care about the file being readable you can use
|glob()|.
{file} is used as-is, you may want to expand wildcards first: >
echo filereadable('~/.vimrc')
0
echo filereadable(expand('~/.vimrc'))
1
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.
float2nr({expr}) *float2nr()*
Convert {expr} to a Number by omitting the part after the
decimal point.
{expr} must evaluate to a |Float| or a Number.
When the value of {expr} is out of range for a |Number| the
result is truncated to 0x7fffffff or -0x7fffffff (or when
64-bit Number support is enabled, 0x7fffffffffffffff or
-0x7fffffffffffffff). NaN results in -0x80000000 (or when
64-bit Number support is enabled, -0x8000000000000000).
Examples: >
echo float2nr(3.95)
< 3 >
echo float2nr(-23.45)
< -23 >
echo float2nr(1.0e100)
< 2147483647 (or 9223372036854775807) >
echo float2nr(-1.0e150)
< -2147483647 (or -9223372036854775807) >
echo float2nr(1.0e-100)
< 0
floor({expr}) *floor()*
Return the largest integral value less than or equal to
{expr} as a |Float| (round down).
{expr} must evaluate to a |Float| or a |Number|.
Examples: >
echo floor(1.856)
< 1.0 >
echo floor(-5.456)
< -6.0 >
echo floor(4.0)
< 4.0
fnameescape({string}) *fnameescape()*
Escape {string} for use as file name command argument. All
characters that have a special meaning, such as '%' and '|'
are escaped with a backslash.
For most systems the characters escaped are
" \t\n*?[{`$\\%#'\"|!<". For systems where a backslash
appears in a filename, it depends on the value of 'isfname'.
A leading '+' and '>' is also escaped (special after |:edit|
and |:write|). And a "-" by itself (special after |:cd|).
Example: >
:let fname = '+some str%nge|name'
:exe "edit " . fnameescape(fname)
< results in executing: >
edit \+some\ str\%nge\|name
<
Can also be used as a |method|: >
GetName()->fnameescape()
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.
foldtextresult({lnum}) *foldtextresult()*
Returns the text that is displayed for the closed fold at line
{lnum}. Evaluates 'foldtext' in the appropriate context.
When there is no closed fold at {lnum} an empty string is
returned.
{lnum} is used like with |getline()|. Thus "." is the current
line, "'m" mark m, etc.
Useful when exporting folded text, e.g., to HTML.
{not available when compiled without the |+folding| feature}
*funcref()*
funcref({name} [, {arglist}] [, {dict}])
Just like |function()|, but the returned Funcref will lookup
the function by reference, not by name. This matters when the
function {name} is redefined later.
< The function() call can be nested to add more arguments to the
Funcref. The extra arguments are appended to the list of
arguments. Example: >
func Callback(arg1, arg2, name)
...
let Func = function('Callback', ['one'])
let Func2 = function(Func, ['two'])
...
call Func2('name')
< Invokes the function as with: >
call Callback('one', 'two', 'name')
< The argument list and the Dictionary can be combined: >
function Callback(arg1, count) dict
...
let context = {"name": "example"}
let Func = function('Callback', ['one'], context)
...
call Func(500)
< Invokes the function as with: >
call context.Callback('one', 500)
<
Can also be used as a |method|: >
GetFuncname()->function([arg])
garbagecollect([{atexit}]) *garbagecollect()*
Cleanup unused |Lists|, |Dictionaries|, |Channels| and |Jobs|
that have circular references.
*getbufinfo()*
getbufinfo([{expr}])
getbufinfo([{dict}])
Get information about buffers as a List of Dictionaries.
Examples: >
for buf in getbufinfo()
echo buf.name
endfor
for buf in getbufinfo({'buflisted':1})
if buf.changed
....
endif
endfor
<
To get buffer-local options use: >
getbufvar({bufnr}, '&option_name')
<
*getbufline()*
getbufline({expr}, {lnum} [, {end}])
Return a |List| with the lines starting from {lnum} to {end}
(inclusive) in the buffer {expr}. If {end} is omitted, a
|List| with only the line {lnum} is returned.
For {lnum} and {end} "$" can be used for the last line of the
buffer. Otherwise a number must be used.
Example: >
:let lines = getbufline(bufnr("myfile"), 1, "$")
The returned list contains two entries: a list with the change
locations and the current position in the list. Each
entry in the change list is a dictionary with the following
entries:
col column number
coladd column offset for 'virtualedit'
lnum line number
If buffer {expr} is the current buffer, then the current
position refers to the position in the list. For other
buffers, it is set to the length of the list.
getchar([expr]) *getchar()*
Get a single character from the user or input stream.
If [expr] is omitted, wait until a character is available.
If [expr] is 0, only get a character when one is available.
Return zero otherwise.
If [expr] is 1, only check if a character is available, it is
not consumed. Return zero if no character available.
Without [expr] and when [expr] is 0 a whole character or
special key is returned. If it is a single character, the
result is a number. Use nr2char() to convert it to a String.
Otherwise a String is returned with the encoded character.
For a special key it's a String with a sequence of bytes
starting with 0x80 (decimal: 128). This is the same value as
the String "\<Key>", e.g., "\<Left>". The returned value is
also a String when a modifier (shift, control, alt) was used
that is not included in the character.
When the user clicks a mouse button, the mouse event will be
returned. The position can then be found in |v:mouse_col|,
|v:mouse_lnum|, |v:mouse_winid| and |v:mouse_win|.
|getmousepos()| can also be used. This example positions the
mouse as it would normally happen: >
let c = getchar()
if c == "\<LeftMouse>" && v:mouse_win > 0
exe v:mouse_win . "wincmd w"
exe v:mouse_lnum
exe "normal " . v:mouse_col . "|"
endif
<
When using bracketed paste only the first character is
returned, the rest of the pasted text is dropped.
|xterm-bracketed-paste|.
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 meta (when it's different from ALT)
32 mouse double click
64 mouse triple click
96 mouse quadruple click (== 32 + 64)
128 command (Macintosh only)
Only the modifiers that have not been included in the
character itself are obtained. Thus Shift-a results in "A"
without a modifier.
getcharsearch() *getcharsearch()*
Return the current character search information as a {dict}
with the following entries:
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 <F7> <C-\>eescape(getcmdline(), ' \')<CR>
< Also see |getcmdtype()|, |getcmdpos()| and |setcmdpos()|.
Returns an empty string when entering a password or using
|inputsecret()|.
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_=| or an expression mapping.
Returns 0 otherwise.
Also see |getcmdtype()|, |setcmdpos()| and |getcmdline()|.
getcmdtype() *getcmdtype()*
Return the current command-line type. Possible return values
are:
: normal Ex command
> debug mode command |debug-mode|
/ forward search command
? backward search command
@ |input()| command
- |:insert| or |:append| command
= |i_CTRL-R_=|
Only works when editing the command line, thus requires use of
|c_CTRL-\_e| or |c_CTRL-R_=| or an expression mapping.
Returns an empty string otherwise.
Also see |getcmdpos()|, |setcmdpos()| and |getcmdline()|.
getcmdwintype() *getcmdwintype()*
Return the current |command-line-window| type. Possible return
values are the same as |getcmdtype()|. Returns an empty string
when not in the command-line window.
This can be used to save and restore the cursor position: >
let save_cursor = getcurpos()
MoveTheCursorAround
call setpos('.', save_cursor)
< Note that this only works within the window. See
|winrestview()| for restoring more state.
*getcwd()*
getcwd([{winnr} [, {tabnr}]])
The result is a String, which is the name of the current
working directory.
Examples: >
" Get the working directory of the current window
:echo getcwd()
:echo getcwd(0)
:echo getcwd(0, 0)
" Get the working directory of window 3 in tabpage 2
:echo getcwd(3, 2)
" Get the global working directory
:echo getcwd(-1)
" Get the working directory of tabpage 3
:echo getcwd(-1, 3)
" Get the working directory of current tabpage
:echo getcwd(-1, 0)
getfontname([{name}]) *getfontname()*
Without an argument returns the name of the normal font being
used. Like what is used for the Normal highlight group
|hl-Normal|.
With an argument a check is done whether {name} is a valid
font name. If not then an empty string is returned.
Otherwise the actual font name is returned, or {name} if the
GUI does not support obtaining the real name.
Only works when the GUI is running, thus not in your vimrc or
gvimrc file. Use the |GUIEnter| autocommand to use this
function just after the GUI has started.
Note that the GTK GUI accepts any font name, thus checking for
a valid name does not work.
getfperm({fname}) *getfperm()*
The result is a String, which is the read, write, and execute
permissions of the given file {fname}.
If {fname} does not exist or its directory cannot be read, an
empty string is returned.
The result is of the form "rwxrwxrwx", where each group of
"rwx" flags represent, in turn, the permissions of the owner
of the file, the group the file belongs to, and other users.
If a user does not have a given permission the flag for this
is replaced with the string "-". Examples: >
:echo getfperm("/etc/passwd")
:echo getfperm(expand("~/.vimrc"))
< This will hopefully (from a security point of view) display
the string "rw-r--r--" or even "rw-------".
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.
If the size of {fname} is too big to fit in a Number then -2
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.
getftype({fname}) *getftype()*
The result is a String, which is a description of the kind of
file of the given file {fname}.
If {fname} does not exist an empty string is returned.
Here is a table over different kinds of files and their
results:
Normal file "file"
Directory "dir"
Symbolic link "link"
Block device "bdev"
Character device "cdev"
Socket "socket"
FIFO "fifo"
All other "other"
Example: >
getftype("/home")
< Note that a type such as "link" will only be returned on
systems that support it. On some systems only "dir" and
"file" are returned. On MS-Windows a symbolic link to a
directory returns "dir" instead of "link".
getimstatus() *getimstatus()*
The result is a Number, which is |TRUE| when the IME status is
active.
See 'imstatusfunc'.
The returned list contains two entries: a list with the jump
locations and the last used jump position number in the list.
Each entry in the jump location list is a dictionary with
the following entries:
bufnr buffer number
col column number
coladd column offset for 'virtualedit'
filename filename if available
lnum line number
< *getline()*
getline({lnum} [, {end}])
Without {end} 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.
getmarklist([{expr}] *getmarklist()*
Without the {expr} argument returns a |List| with information
about all the global marks. |mark|
getmatches([{win}]) *getmatches()*
Returns a |List| with all matches previously defined for the
current window by |matchadd()| and the |:match| commands.
|getmatches()| is useful in combination with |setmatches()|,
as |setmatches()| can restore a list of matches saved by
|getmatches()|.
Example: >
:echo getmatches()
< [{'group': 'MyGroup1', 'pattern': 'TODO',
'priority': 10, 'id': 1}, {'group': 'MyGroup2',
'pattern': 'FIXME', 'priority': 10, 'id': 2}] >
:let m = getmatches()
:call clearmatches()
:echo getmatches()
< [] >
:call setmatches(m)
:echo getmatches()
< [{'group': 'MyGroup1', 'pattern': 'TODO',
'priority': 10, 'id': 1}, {'group': 'MyGroup2',
'pattern': 'FIXME', 'priority': 10, 'id': 2}] >
:unlet m
<
getmousepos() *getmousepos()*
Returns a Dictionary with the last known position of the
mouse. This can be used in a mapping for a mouse click or in
a filter of a popup window. The items are:
screenrow screen row
screencol screen column
winid Window ID of the click
winrow row inside "winid"
wincol column inside "winid"
line text line inside "winid"
column text column inside "winid"
All numbers are 1-based.
If not over a window, e.g. when in the command line, then only
"screenrow" and "screencol" are valid, the others are zero.
When on the status line below a window or the vertical
separater right of a window, the "line" and "column" values
are zero.
*getpid()*
getpid() Return a Number which is the process ID of the Vim process.
On Unix and MS-Windows this is a unique number, until Vim
exits.
*getpos()*
getpos({expr}) Get the position for {expr}. For possible values of {expr}
see |line()|. For getting the cursor position see
|getcurpos()|.
The result is a |List| with four numbers:
[bufnum, lnum, col, off]
"bufnum" is zero, unless a mark like '0 or 'A is used, then it
is the buffer number of the mark.
"lnum" and "col" are the position in the buffer. The first
column is 1.
The "off" number is zero, unless 'virtualedit' is used. Then
it is the offset in screen columns from the start of the
character. E.g., a position within a <Tab> or after the last
character.
Note that for '< and '> Visual mode matters: when it is "V"
(visual line mode) the column of '< is zero and the column of
'> is a large number.
This can be used to save and restore the position of a mark: >
let save_a_mark = getpos("'a")
...
call setpos("'a", save_a_mark)
< Also see |getcurpos()| and |setpos()|.
getqflist([{what}]) *getqflist()*
Returns a list with all the current quickfix errors. Each
list item is a dictionary with these entries:
bufnr number of buffer that has the file name, use
bufname() to get the name
module module name
lnum line number in the buffer (first line is 1)
col column number (first column is 1)
vcol |TRUE|: "col" is visual column
|FALSE|: "col" is byte index
nr error number
pattern search pattern used to locate the error
text description of the error
type type of the error, 'E', '1', etc.
valid |TRUE|: recognized error message
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
"<CTRL-V>{width}" for |blockwise-visual| text
"" for an empty or unknown register
<CTRL-V> is one character with value 0x16.
If {regname} is not specified, |v:register| is used.
getwininfo([{winid}]) *getwininfo()*
Returns information about windows as a List with Dictionaries.
getwinpos([{timeout}]) *getwinpos()*
The result is a List with two numbers, the result of
|getwinposx()| and |getwinposy()| combined:
[x-pos, y-pos]
{timeout} can be used to specify how long to wait in msec for
a response from the terminal. When omitted 100 msec is used.
Use a longer time for a remote terminal.
When using a value less than 10 and no response is received
within that time, a previously reported position is returned,
if available. This can be used to poll for the position and
do some work in the meantime: >
while 1
let res = getwinpos(1)
if res[0] >= 0
break
endif
" Do some work here
endwhile
<
*getwinposy()*
getwinposy() The result is a Number, which is the Y coordinate in pixels of
the top of the GUI Vim window. Also works for an xterm (uses
a timeout of 100 msec).
The result will be -1 if the information is not available.
The value can be used with `:winpos`.
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.
glob2regpat({expr}) *glob2regpat()*
Convert a file pattern, as used by glob(), into a search
pattern. The result can be used to match with a string that
is a file name. E.g. >
if filename =~ glob2regpat('Make*.mak')
< This is equivalent to: >
if filename =~ '^Make.*\.mak$'
< When {expr} is an empty string the result is "^$", match an
empty string.
Note that the result depends on the system. On MS-Windows
a backslash usually means a path separator.
Note that to skip code that has a syntax error when the
feature is not available, Vim may skip the rest of the line
and miss a following `endif`. Therefore put the `endif` on a
separate line: >
if has('feature')
let x = this->breaks->without->the->feature
endif
< If the `endif` would be moved to the second line as "| endif" it
would not be found.
Example: >
:call histadd("input", strftime("%Y %b %d"))
:let date=input("Enter date: ")
< This function is not available in the |sandbox|.
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)
<
Can also be used as a |method|: >
GetHistory()->histdel()
Examples:
Redo the second last search from history. >
:execute '/' . histget("search", -2)
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")
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.
inputlist({textlist}) *inputlist()*
{textlist} must be a |List| of strings. This |List| is
displayed, one string per line. The user will be prompted to
enter a number, which is returned.
The user can also select an item by clicking on it with the
mouse. For the first string 0 is returned. When clicking
above the first item a negative number is returned. When
clicking on the prompt one more than the length of {textlist}
is returned.
Make sure {textlist} has less than 'lines' entries, otherwise
it won't work. It's a good idea to put the entry number at
the start of the string. And put a prompt in the first item.
Example: >
let color = inputlist(['Select color:', '1. red',
\ '2. green', '3. blue'])
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.
interrupt() *interrupt()*
Interrupt script execution. It works more or less like the
user typing CTRL-C, most commands won't execute and control
returns to the user. This is useful to abort execution
from lower down, e.g. in an autocommand. Example: >
:function s:check_typoname(file)
: if fnamemodify(a:file, ':t') == '['
: echomsg 'Maybe typo'
: call interrupt()
: endif
:endfunction
:au BufWritePre * call s:check_typoname(expand('<amatch>'))
invert({expr}) *invert()*
Bitwise invert. The argument is converted to a number. A
List, Dict or Float argument causes an error. Example: >
:let bits = invert(bits)
< Can also be used as a |method|: >
:let bits = bits->invert()
isdirectory({directory}) *isdirectory()*
The result is a Number, which is |TRUE| 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.
isinf({expr}) *isinf()*
Return 1 if {expr} is a positive infinity, or -1 a negative
infinity, otherwise 0. >
:echo isinf(1.0 / 0.0)
< 1 >
:echo isinf(-1.0 / 0.0)
< -1
< When {expr} is a variable that does not exist you get an error
message. Use |exists()| to check for existence.
isnan({expr}) *isnan()*
Return |TRUE| if {expr} is a float with value NaN. >
echo isnan(0.0 / 0.0)
< 1
items({dict}) *items()*
Return a |List| with all the key-value pairs of {dict}. Each
|List| item is a list with two items: the key of a {dict}
entry and the value of this entry. The |List| is in arbitrary
order. Also see |keys()| and |values()|.
Example: >
for [key, value] in items(mydict)
echo key . ': ' . value
endfor
js_decode({string}) *js_decode()*
This is similar to |json_decode()| with these differences:
- Object key names do not have to be in quotes.
- Strings can be in single quotes.
- Empty items in an array (between two commas) are allowed and
result in v:none items.
js_encode({expr}) *js_encode()*
This is similar to |json_encode()| with these differences:
- Object key names are not in quotes.
- v:none items in an array result in an empty item between
commas.
For example, the Vim object:
[1,v:none,{"one":1},v:none] ~
Will be encoded as:
[1,,{one:1},,] ~
While json_encode() would produce:
[1,null,{"one":1},null] ~
This encoding is valid for JavaScript. It is more efficient
than JSON, especially when using an array with optional items.
json_decode({string}) *json_decode()*
This parses a JSON formatted string and returns the equivalent
in Vim values. See |json_encode()| for the relation between
JSON and Vim values.
The decoding is permissive:
- A trailing comma in an array and object is ignored, e.g.
"[1, 2, ]" is the same as "[1, 2]".
- Integer keys are accepted in objects, e.g. {1:2} is the
same as {"1":2}.
- More floating point numbers are recognized, e.g. "1." for
"1.0", or "001.2" for "1.2". Special floating point values
"Infinity", "-Infinity" and "NaN" (capitalization ignored)
are accepted.
- Leading zeroes in integer numbers are ignored, e.g. "012"
for "12" or "-012" for "-12".
- Capitalization is ignored in literal names null, true or
false, e.g. "NULL" for "null", "True" for "true".
- Control characters U+0000 through U+001F which are not
escaped in strings are accepted, e.g. " " (tab
character in string) for "\t".
- An empty JSON expression or made of only spaces is accepted
and results in v:none.
- Backslash in an invalid 2-character sequence escape is
ignored, e.g. "\a" is decoded as "a".
- A correct surrogate pair in JSON strings should normally be
a 12 character sequence such as "\uD834\uDD1E", but
json_decode() silently accepts truncated surrogate pairs
such as "\uD834" or "\uD834\u"
*E938*
A duplicate key in an object, valid in rfc7159, is not
accepted by json_decode() as the result must be a valid Vim
type, e.g. this fails: {"a":"b", "a":"c"}
json_encode({expr}) *json_encode()*
Encode {expr} as JSON and return this as a string.
The encoding is specified in:
https://tools.ietf.org/html/rfc7159.html
Vim values are converted as follows:
|Number| decimal number
|Float| floating point number
Float nan "NaN"
Float inf "Infinity"
Float -inf "-Infinity"
|String| in double quotes (possibly null)
|Funcref| not possible, error
|List| as an array (possibly null); when
used recursively: []
|Dict| as an object (possibly null); when
used recursively: {}
|Blob| as an array of the individual bytes
v:false "false"
v:true "true"
v:none "null"
v:null "null"
Note that NaN and Infinity are passed on as values. This is
missing in the JSON standard, but several implementations do
allow it. If not then you will get an error.
keys({dict}) *keys()*
Return a |List| with all the keys of {dict}. The |List| is in
arbitrary order. Also see |items()| and |values()|.
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. 'encoding' matters, 'fileencoding' is ignored.
This can also be used to get the byte count for the line just
below the last line: >
line2byte(line("$") + 1)
< This is the buffer size plus one. If 'fileencoding' is empty
it 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|.
Example: >
func Listener(bufnr, start, end, added, changes)
echo 'lines ' .. a:start .. ' until ' .. a:end .. ' changed'
endfunc
call listener_add('Listener', bufnr)
The entries are in the order the changes were made, thus the
most recent change is at the end. The line numbers are valid
when the callback is invoked, but later changes may make them
invalid, thus keeping a copy for later might not work.
listener_flush([{buf}]) *listener_flush()*
Invoke listener callbacks for buffer {buf}. If there are no
pending changes then no callbacks are invoked.
listener_remove({id}) *listener_remove()*
Remove a listener previously added with listener_add().
Returns zero when {id} could not be found, one when {id} was
removed.
localtime() *localtime()*
Return the current time, measured as seconds since 1st Jan
1970. See also |strftime()|, |strptime()| and |getftime()|.
log({expr}) *log()*
Return the natural logarithm (base e) of {expr} as a |Float|.
{expr} must evaluate to a |Float| or a |Number| in the range
(0, inf].
Examples: >
:echo log(10)
< 2.302585 >
:echo log(exp(5))
< 5.0
log10({expr}) *log10()*
Return the logarithm of Float {expr} to base 10 as a |Float|.
{expr} must evaluate to a |Float| or a |Number|.
Examples: >
:echo log10(1000)
< 3.0 >
:echo log10(0.01)
< -2.0
The {name} can have special key names, like in the ":map"
command.
Example: >
:highlight MyGroup ctermbg=green guibg=green
:let m = matchadd("MyGroup", "TODO")
< Deletion of the pattern: >
:call matchdelete(m)
Example: >
:highlight MyGroup ctermbg=green guibg=green
:let m = matchaddpos("MyGroup", [[23, 24], 34])
< Deletion of the pattern: >
:call matchdelete(m)
matcharg({nr}) *matcharg()*
Selects the {nr} match item, as set with a |:match|,
|:2match| or |:3match| command.
Return a |List| with two elements:
The name of the highlight group used
The pattern used.
When {nr} is not 1, 2 or 3 returns an empty |List|.
When there is no match item set returns ['', ''].
This is useful to save and restore a |:match|.
Highlighting matches using the |:match| commands are limited
to three matches. |matchadd()| does not have this limitation.
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".
When {expr} is a |List| the result is equal to |match()|.
*max()*
max({expr}) Return the maximum value of all items in {expr}.
{expr} can be a List or a Dictionary. For a Dictionary,
it returns the maximum of all values in the Dictionary.
If {expr} is neither a List nor a Dictionary, or one of the
items in {expr} cannot be used as a Number this results in
an error. An empty |List| or |Dictionary| results in zero.
Examples: >
:echo menu_info('Edit.Cut')
:echo menu_info('File.Save', 'n')
<
Can also be used as a |method|: >
GetMenuName()->menu_info('v')
< *min()*
min({expr}) Return the minimum value of all items in {expr}.
{expr} can be a List or a Dictionary. For a Dictionary,
it returns the minimum of all values in the Dictionary.
If {expr} is neither a List nor a Dictionary, or one of the
items in {expr} cannot be used as a Number this results in
an error. An empty |List| or |Dictionary| results in zero.
n Normal, Terminal-Normal
no Operator-pending
nov Operator-pending (forced characterwise |o_v|)
noV Operator-pending (forced linewise |o_V|)
noCTRL-V Operator-pending (forced blockwise |o_CTRL-V|);
CTRL-V is one character
niI Normal using |i_CTRL-O| in |Insert-mode|
niR Normal using |i_CTRL-O| in |Replace-mode|
niV Normal using |i_CTRL-O| in |Virtual-Replace-mode|
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
ic Insert mode completion |compl-generic|
ix Insert mode |i_CTRL-X| completion
R Replace |R|
Rc Replace mode completion |compl-generic|
Rv Virtual Replace |gR|
Rx Replace mode |i_CTRL-X| completion
c Command-line editing
cv Vim Ex mode |gQ|
ce Normal Ex mode |Q|
r Hit-enter prompt
rm The -- more -- prompt
r? A |:confirm| query of some sort
! Shell or external command is executing
t Terminal-Job mode: keys go to the job
This is useful in the 'statusline' option or when used
with |remote_expr()| In most other places it always returns
"c" or "n".
Note that in the future more modes and more specific modes may
be added. It's better not to compare the whole string but only
the leading character(s).
Also see |visualmode()|.
mzeval({expr}) *mzeval()*
Evaluate MzScheme expression {expr} and return its result
converted to Vim data structures.
Numbers and strings are returned as they are.
Pairs (including lists and improper lists) and vectors are
returned as Vim |Lists|.
Hash tables are represented as Vim |Dictionary| type with keys
converted to strings.
All other types are converted to string with display function.
Examples: >
:mz (define l (list 1 2 3))
:mz (define h (make-hash)) (hash-set! h "list" l)
:echo mzeval("l")
:echo mzeval("h")
<
Can also be used as a |method|: >
GetExpr()->mzeval()
<
{only available when compiled with the |+mzscheme| feature}
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()|.
pathshorten({expr}) *pathshorten()*
Shorten directory names in the path {expr} and return the
result. The tail, the file name, is kept as-is. The other
components in the path are reduced to single letters. Leading
'~' and '.' characters are kept. Example: >
:echo pathshorten('~/.vim/autoload/myfile.vim')
< ~/.v/a/myfile.vim ~
It doesn't matter if the path exists or not.
perleval({expr}) *perleval()*
Evaluate Perl expression {expr} in scalar context and return
its result converted to Vim data structures. If value can't be
converted, it is returned as a string Perl representation.
Note: If you want an array or hash, {expr} must return a
reference to it.
Example: >
:echo perleval('[1 .. 4]')
< [1, 2, 3, 4]
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()|.
flags
Zero or more of the following flags:
field-width
An optional decimal digit string specifying a minimum
field width. If the converted value has fewer bytes
than the field width, it will be padded with spaces on
the left (or right, if the left-adjustment flag has
been given) to fill out the field width.
.precision
An optional precision, in the form of a period '.'
followed by an optional digit string. If the digit
string is omitted, the precision is taken as zero.
This gives the minimum number of digits to appear for
d, o, x, and X conversions, or the maximum number of
bytes to be printed from a string for s conversions.
For floating point it is the number of digits after
the decimal point.
type
A character that specifies the type of conversion to
be applied, see below.
i alias for d
D alias for ld
U alias for lu
O alias for lo
*printf-c*
c The Number argument is converted to a byte, and the
resulting character is written.
*printf-s*
s The text of the String argument is used. If a
precision is specified, no more bytes than the number
specified are used.
If the argument is not a String type, it is
automatically converted to text with the same format
as ":echo".
*printf-S*
S The text of the String argument is used. If a
precision is specified, no more display cells than the
number specified are used.
*printf-f* *E807*
f F The Float argument is converted into a string of the
form 123.456. The precision specifies the number of
digits after the decimal point. When the precision is
zero the decimal point is omitted. When the precision
is not specified 6 is used. A really big number
(out of range or dividing by zero) results in "inf"
or "-inf" with %f (INF or -INF with %F).
"0.0 / 0.0" results in "nan" with %f (NAN with %F).
Example: >
echo printf("%.2f", 12.115)
< 12.12
Note that roundoff depends on the system libraries.
Use |round()| when in doubt.
*printf-e* *printf-E*
e E The Float argument is converted into a string of the
form 1.234e+03 or 1.234E+03 when using 'E'. The
precision specifies the number of digits after the
decimal point, like with 'f'.
*printf-g* *printf-G*
g G The Float argument is converted like with 'f' if the
value is between 0.001 (inclusive) and 10000000.0
(exclusive). Otherwise 'e' is used for 'g' and 'E'
for 'G'. When no precision is specified superfluous
zeroes and '+' signs are removed, except for the zero
immediately after the decimal point. Thus 10000000.0
results in 1.0e7.
*printf-%*
% A '%' is written. No argument is converted. The
complete conversion specification is "%%".
*E766* *E767*
The number of {exprN} arguments must exactly match the number
of "%" items. If there are not sufficient or too many
arguments an error is given. Up to 18 arguments can be used.
pum_getpos() *pum_getpos()*
If the popup menu (see |ins-completion-menu|) is not visible,
returns an empty |Dictionary|, otherwise, returns a
|Dictionary| with the following keys:
height nr of items visible
width screen cells
row top screen row (0 first row)
col leftmost screen column (0 first col)
size total nr of items
scrollbar |TRUE| if scrollbar is visible
pumvisible() *pumvisible()*
Returns non-zero when the popup menu is visible, zero
otherwise. See |ins-completion-menu|.
This can be used to avoid some things that would remove the
popup menu.
py3eval({expr}) *py3eval()*
Evaluate Python expression {expr} and return its result
converted to Vim data structures.
Numbers and strings are returned as they are (strings are
copied though, Unicode strings are additionally converted to
'encoding').
Lists are represented as Vim |List| type.
Dictionaries are represented as Vim |Dictionary| type with
keys converted to strings.
*E858* *E859*
pyeval({expr}) *pyeval()*
Evaluate Python expression {expr} and return its result
converted to Vim data structures.
Numbers and strings are returned as they are (strings are
copied though).
Lists are represented as Vim |List| type.
Dictionaries are represented as Vim |Dictionary| type,
non-string keys result in error.
Can also be used as a |method|: >
GetExpr()->pyeval()
pyxeval({expr}) *pyxeval()*
Evaluate Python expression {expr} and return its result
converted to Vim data structures.
Uses Python 2 or 3, see |python_x| and 'pyxversion'.
See also: |pyeval()|, |py3eval()|
*E726* *E727*
range({expr} [, {max} [, {stride}]]) *range()*
Returns a |List| with Numbers:
- If only {expr} is specified: [0, 1, ..., {expr} - 1]
- If {max} is specified: [{expr}, {expr} + 1, ..., {max}]
- If {stride} is specified: [{expr}, {expr} + {stride}, ...,
{max}] (increasing {expr} with {stride} each time, not
producing a value past {max}).
When the maximum is one before the start the result is an
empty list. When the maximum is more than one before the
start this is an error.
Examples: >
range(4) " [0, 1, 2, 3]
range(2, 4) " [2, 3, 4]
range(2, 9, 3) " [2, 5, 8]
range(2, -2, -1) " [2, 1, 0, -1, -2]
range(0) " []
range(2, 0) " error!
<
Can also be used as a |method|: >
GetExpr()->range()
<
Examples: >
:echo rand()
:let seed = srand()
:echo rand(seed)
:echo rand(seed) % 16 " random number 0 - 15
<
*readdir()*
readdir({directory} [, {expr}])
Return a list with file and directory names in {directory}.
You can also use |glob()| if you don't need to do complicated
things, such as limiting the number of matches.
When {expr} is omitted all entries are included.
When {expr} is given, it is evaluated to check what to do:
If {expr} results in -1 then no further entries will
be handled.
If {expr} results in 0 then this entry will not be
added to the list.
If {expr} results in 1 then this entry will be added
to the list.
Each time {expr} is evaluated |v:val| is set to the entry name.
When {expr} is a function the name is passed as the argument.
For example, to get a list of files ending in ".txt": >
readdir(dirname, {n -> n =~ '.txt$'})
< To skip hidden and backup files: >
readdir(dirname, {n -> n !~ '^\.\|\~$'})
reg_executing() *reg_executing()*
Returns the single letter name of the register being executed.
Returns an empty string when no register is being executed.
See |@|.
reg_recording() *reg_recording()*
Returns the single letter name of the register being recorded.
Returns an empty string when not recording. See |q|.
reltimefloat({time}) *reltimefloat()*
Return a Float that represents the time value of {time}.
Example: >
let start = reltime()
call MyFunction()
let seconds = reltimefloat(reltime(start))
< See the note of reltimestr() about overhead.
Also see |profiling|.
reltimestr({time}) *reltimestr()*
Return a String that represents the time value of {time}.
This is the number of seconds, a dot and the number of
microseconds. Example: >
let start = reltime()
call MyFunction()
echo reltimestr(reltime(start))
< Note that overhead for the commands will be added to the time.
The accuracy depends on the system.
Leading spaces are used to make the string align nicely. You
can use split() to remove it. >
echo split(reltimestr(reltime(start)))[0]
< Also see |profiling|.
Can also be used as a |method|: >
reltime(start)->reltimestr()
*remote_expr()* *E449*
remote_expr({server}, {string} [, {idvar} [, {timeout}]])
Send the {string} to {server}. The string is sent as an
expression and the result is returned after evaluation.
The result must be a String or a |List|. A |List| is turned
into a String by joining the items with a line break in
between (not at the end), like with join(expr, "\n").
If {idvar} is present and not empty, it is taken as the name
of a variable and a {serverid} for later use with
|remote_read()| is stored there.
If {timeout} is given the read times out after this many
seconds. Otherwise a timeout of 600 seconds is used.
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")
<
Can also be used as a |method|: >
ServerName()->remote_expr(expr)
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.
Note: This does not restore the window if it was minimized,
like foreground() does.
This function is not available in the |sandbox|.
< {only in the Win32, Athena, Motif and GTK GUI versions and the
Win32 console version}
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)
remove({dict}, {key})
Remove the entry from {dict} with key {key} and return it.
Example: >
:echo "removed " . remove(dict, "one")
< If there is no {key} in {dict} this is an error.
reverse({object}) *reverse()*
Reverse the order of items in {object} in-place.
{object} can be a |List| or a |Blob|.
Returns {object}.
If you want an object to remain unmodified make a copy first: >
:let revlist = reverse(copy(mylist))
< Can also be used as a |method|: >
mylist->reverse()
round({expr}) *round()*
Round off {expr} to the nearest integral value and return it
as a |Float|. If {expr} lies halfway between two integral
values, then use the larger one (away from zero).
{expr} must evaluate to a |Float| or a |Number|.
Examples: >
echo round(0.456)
< 0.0 >
echo round(4.5)
< 5.0 >
echo round(-4.5)
< -5.0
rubyeval({expr}) *rubyeval()*
Evaluate Ruby expression {expr} and return its result
converted to Vim data structures.
Numbers, floats and strings are returned as they are (strings
are copied though).
Arrays are represented as Vim |List| type.
Hashes are represented as Vim |Dictionary| type.
Other objects are represented as strings resulted from their
"Object#to_s" method.
screencol() *screencol()*
The result is a Number, which is the current screen column of
the cursor. The leftmost column has number 1.
This function is mainly used for testing.
screenrow() *screenrow()*
The result is a Number, which is the current screen row of the
cursor. The top line has number one.
This function is mainly used for testing.
Alternatively you can use |winline()|.
If the 's' flag is supplied, the ' mark is set, only if the
cursor is moved. The 's' flag cannot be combined with the 'n'
flag.
*search()-sub-match*
With the 'p' flag the returned value is one more than the
first sub-match in \(\). One if none of them matched but the
whole pattern did match.
To get the column number too use |searchpos()|.
{flags} 'b', 'c', 'n', 's', 'w' and 'W' are used like with
|search()|. Additionally:
'r' Repeat until no more matches found; will find the
outer pair. Implies the 'W' flag.
'm' Return number of matches instead of line number with
the match; will be > 1 when 'r' is used.
Note: it's nearly always a good idea to use the 'W' flag, to
avoid wrapping around the end of the file.
< 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 "}": >
< 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: >
< When the 'p' flag is given then there is an extra item with
the sub-pattern match number |search()-sub-match|. Example: >
:let [lnum, col, submatch] = searchpos('\(\l\)\|\(\u\)', 'np')
< In this example "submatch" is 2 when a lowercase letter is
found |/\l|, 3 when an uppercase letter is found |/\u|.
setcharsearch({dict}) *setcharsearch()*
Set the current character search information to {dict},
which contains one or more of the following entries:
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|, |c_CTRL-R_=| or |c_CTRL-R_CTRL-R| with '='. For
|c_CTRL-\_e| and |c_CTRL-R_CTRL-R| with '=' the position is
set after the command line is set to the expression. For
|c_CTRL-R_=| it is set after evaluating the expression but
before inserting the resulting text.
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.
Example: >
:call setline(5, strftime("%c"))
< When {text} is a |List| then line {lnum} and following lines
will be set to the items in the list. Example: >
:call setline(5, ['aaa', 'bbb', 'ccc'])
< This is equivalent to: >
:for [n, l] in [[5, 'aaa'], [6, 'bbb'], [7, 'ccc']]
: call setline(n, l)
:endfor
< Note: The '[ and '] marks are not set.
"lnum" and "col" are the position in the buffer. The first
column is 1. Use a zero "lnum" to delete a mark. If "col" is
smaller than 1 then 1 is used.
Note that for '< and '> changing the line number may result in
the marks to be effectively be swapped, so that '< is always
before '>.
'r' The items from the current quickfix list are replaced
with the items from {list}. This can also be used to
clear the list: >
:call setqflist([], 'r')
<
'f' All the quickfix lists in the quickfix stack are
freed.
*E883*
Note: you may not use |List| containing more than one item to
set search and expression registers. Lists containing no
items act like empty strings.
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', 1, 1)
:let var_amode = getregtype('a')
....
:call setreg('a', var_a, var_amode)
< Note: you may not reliably restore register value
without using the third argument to |getreg()| as without it
newlines are represented as newlines AND Nul bytes are
represented as newlines as well, see |NL-used-for-Nul|.
The current index is set to one after the length of the tag
stack after the modification.
sha256({string}) *sha256()*
Returns a String with 64 hex characters, which is the SHA256
checksum of {string}.
shiftwidth([{col}]) *shiftwidth()*
Returns the effective value of 'shiftwidth'. This is the
'shiftwidth' value unless it is zero, in which case it is the
'tabstop' value. This function was introduced with patch
7.3.694 in 2012, everybody should have it by now (however it
did not allow for the optional {col} argument until 8.1.542).
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()|.
sinh({expr}) *sinh()*
Return the hyperbolic sine of {expr} as a |Float| in the range
[-inf, inf].
{expr} must evaluate to a |Float| or a |Number|.
Examples: >
:echo sinh(0.5)
< 0.521095 >
:echo sinh(-0.9)
< -1.026517
< When {func} is omitted, is empty or zero, then sort() uses the
string representation of each item to sort on. Numbers sort
after Strings, |Lists| after Numbers. For sorting text in the
current buffer use |:sort|.
Example: >
func MyCompare(i1, i2)
return a:i1 == a:i2 ? 0 : a:i1 > a:i2 ? 1 : -1
endfunc
let sortedlist = sort(mylist, "MyCompare")
< A shorter compare version for this specific simple case, which
ignores overflow: >
func MyCompare(i1, i2)
return a:i1 - a:i2
endfunc
<
sound_clear() *sound_clear()*
Stop playing all sounds.
{only available when compiled with the |+sound| feature}
*sound_playevent()*
sound_playevent({name} [, {callback}])
Play a sound identified by {name}. Which event names are
supported depends on the system. Often the XDG sound names
are used. On Ubuntu they may be found in
/usr/share/sounds/freedesktop/stereo. Example: >
call sound_playevent('bell')
< On MS-Windows, {name} can be SystemAsterisk, SystemDefault,
SystemExclamation, SystemExit, SystemHand, SystemQuestion,
SystemStart, SystemWelcome, etc.
*sound_playfile()*
sound_playfile({path} [, {callback}])
Like `sound_playevent()` but play sound file {path}. {path}
must be a full path. On Ubuntu you may find files to play
with this command: >
:!find /usr/share/sounds -type f | grep -v index.theme
sound_stop({id}) *sound_stop()*
Stop playing sound {id}. {id} must be previously returned by
`sound_playevent()` or `sound_playfile()`.
*soundfold()*
soundfold({word})
Return the sound-folded equivalent of {word}. Uses the first
language in 'spelllang' for the current window that supports
soundfolding. 'spell' must be set. When no sound folding is
possible the {word} is returned unmodified.
This can be used for making spelling suggestions. Note that
the method can be quite slow.
sqrt({expr}) *sqrt()*
Return the non-negative square root of Float {expr} as a
|Float|.
{expr} must evaluate to a |Float| or a |Number|. When {expr}
is negative the result is NaN (Not a Number).
Examples: >
:echo sqrt(100)
< 10.0 >
:echo sqrt(-4.01)
< nan
"nan" may be different, it depends on system libraries.
srand([{expr}]) *srand()*
Initialize seed used by |rand()|:
- If {expr} is not given, seed values are initialized by
reading from /dev/urandom, if possible, or using time(NULL)
a.k.a. epoch time otherwise; this only has second accuracy.
- If {expr} is given it must be a Number. It is used to
initialize the seed values. This is useful for testing or
when a predictable sequence is intended.
Examples: >
:let seed = srand()
:let seed = srand(userinput)
:echo rand(seed)
state([{what}]) *state()*
Return a string which contains characters indicating the
current state. Mostly useful in callbacks that want to do
work that may not always be safe. Roughly this works like:
- callback uses state() to check if work is safe to do.
Yes: then do it right away.
No: add to work queue and add a |SafeState| and/or
|SafeStateAgain| autocommand (|SafeState| triggers at
toplevel, |SafeStateAgain| triggers after handling
messages and callbacks).
- When SafeState or SafeStateAgain is triggered and executes
your autocommand, check with `state()` if the work can be
done now, and if yes remove it from the queue and execute.
Remove the autocommand if the queue is now empty.
Also see |mode()|.
str2float({expr}) *str2float()*
Convert String {expr} to a Float. This mostly works the same
as when using a floating point number in an expression, see
|floating-point-format|. But it's a bit more permissive.
E.g., "1e40" is accepted, while in an expression you need to
write "1.0e40". The hexadecimal form "0x123" is also
accepted, but not others, like binary or octal.
Text after the number is silently ignored.
The decimal point is always '.', no matter what the locale is
set to. A comma ends the number: "12,345.67" is converted to
12.0. You can strip out thousands separators with
|substitute()|: >
let f = str2float(substitute(text, ',', '', 'g'))
<
Can also be used as a |method|: >
let f = text->substitute(',', '', 'g')->str2float()
<
{only available when compiled with the |+float| feature}
*strlen()*
strlen({expr}) The result is a Number, which is the length of the String
{expr} in bytes.
If the argument is a Number it is first converted to a String.
For other types an error is given.
If you want to count the number of multi-byte characters use
|strchars()|.
Also see |len()|, |strdisplaywidth()| and |strwidth()|.
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.
Examples: >
:s/\d\+/\=submatch(0) + 1/
:echo substitute(text, '\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.
Example: >
:let &path = substitute(&path, ",\\=[^,]*$", "", "")
< This removes the last component of the 'path' option. >
:echo substitute("testing", ".*", "\\U\\0", "")
< results in "TESTING".
swapinfo({fname}) *swapinfo()*
The result is a dictionary, which holds information about the
swapfile {fname}. The available fields are:
version Vim version
user user name
host host name
fname original file name
pid PID of the Vim process that created the swap
file
mtime last modification time in seconds
inode Optional: INODE number of the file
dirty 1 if file was modified, 0 if not
Note that "user" and "host" are truncated to at most 39 bytes.
In case of failure an "error" item is added with the reason:
Cannot open file: file not found or in accessible
Cannot read file: cannot read first block
Not a swap file: does not contain correct block ID
Magic number mismatch: Info in first block is invalid
swapname({expr}) *swapname()*
The result is the swap file path of the buffer {expr}.
For the use of {expr}, see |bufname()| above.
If buffer {expr} is the current buffer, the result is equal to
|:swapname| (unless no swap file).
If buffer {expr} has no swap file, returns an empty string.
Example (echoes the name of the syntax item under the cursor): >
:echo synIDattr(synID(line("."), col("."), 1), "name")
<
Note that any wrong value in the options mentioned above may
make the function fail. It has also been reported to fail
when using a security agent application.
Unlike ":!cmd" there is no automatic check for changed files.
Use |:checktime| to force a check.
tabpagebuflist([{arg}]) *tabpagebuflist()*
The result is a |List|, where each item is the number of the
buffer associated with each window in the current tab page.
{arg} specifies the number of the tab page to be used. When
omitted the current tab page is used.
When {arg} is invalid the number zero is returned.
To get a list of all buffers in all tabs use this: >
let buflist = []
for i in range(tabpagenr('$'))
call extend(buflist, tabpagebuflist(i + 1))
endfor
< Note that a buffer may appear in more than one window.
tabpagenr([{arg}]) *tabpagenr()*
The result is a Number, which is the number of the current
tab page. The first tab page has number 1.
When the optional argument is "$", the number of the last tab
page is returned (the tab page count).
The number can be used with the |:tab| command.
To get an exact tag match, the anchors '^' and '$' should be
used in {expr}. This also make the function work faster.
Refer to |tag-regexp| for more information about the tag
search regular expression pattern.
tan({expr}) *tan()*
Return the tangent of {expr}, measured in radians, as a |Float|
in the range [-inf, inf].
{expr} must evaluate to a |Float| or a |Number|.
Examples: >
:echo tan(10)
< 0.648361 >
:echo tan(-4.01)
< -1.181502
tanh({expr}) *tanh()*
Return the hyperbolic tangent of {expr} as a |Float| in the
range [-1, 1].
{expr} must evaluate to a |Float| or a |Number|.
Examples: >
:echo tanh(0.5)
< 0.462117 >
:echo tanh(-1)
< -0.761594
*timer_info()*
timer_info([{id}])
Return a list with information about timers.
When {id} is given only information about this timer is
returned. When timer {id} does not exist an empty list is
returned.
When {id} is omitted information about all timers is returned.
Example: >
func MyHandler(timer)
echo 'Handler called'
endfunc
let timer = timer_start(500, 'MyHandler',
\ {'repeat': 3})
< This will invoke MyHandler() three times at 500 msec
intervals.
timer_stopall() *timer_stopall()*
Stop all timers. The timer callbacks will no longer be
invoked. Useful if a timer is misbehaving. If there are no
timers there is no error.
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).
Examples: >
echo tr("hello there", "ht", "HT")
< returns "Hello THere" >
echo tr("<blob>", "<>", "{}")
< returns "{blob}"
Examples: >
echo trim(" some text ")
< returns "some text" >
echo trim(" \r\t\t\r RESERVE \t\n\x0B\xA0") . "_TAIL"
< returns "RESERVE_TAIL" >
echo trim("rm<Xrm<>X>rrm", "rm<>")
< returns "Xrm<>X" (characters in the middle are not removed) >
echo trim(" vim ", " ", 2)
< returns " vim"
trunc({expr}) *trunc()*
Return the largest integral value with magnitude less than or
equal to {expr} as a |Float| (truncate towards zero).
{expr} must evaluate to a |Float| or a |Number|.
Examples: >
echo trunc(1.456)
< 1.0 >
echo trunc(-5.456)
< -5.0 >
echo trunc(4.0)
< 4.0
*type()*
type({expr}) The result is a Number representing the type of {expr}.
Instead of using the number directly, it is better to use the
v:t_ variable that has the value:
Number: 0 |v:t_number|
String: 1 |v:t_string|
Funcref: 2 |v:t_func|
List: 3 |v:t_list|
Dictionary: 4 |v:t_dict|
Float: 5 |v:t_float|
Boolean: 6 |v:t_bool| (v:false and v:true)
None: 7 |v:t_none| (v:null and v:none)
Job: 8 |v:t_job|
Channel: 9 |v:t_channel|
Blob: 10 |v:t_blob|
For backward compatibility, this method can be used: >
:if type(myvar) == type(0)
:if type(myvar) == type("")
:if type(myvar) == type(function("tr"))
:if type(myvar) == type([])
:if type(myvar) == type({})
:if type(myvar) == type(0.0)
:if type(myvar) == type(v:false)
:if type(myvar) == type(v:none)
< To check if the v:t_ variables exist use this: >
:if exists('v:t_number')
undofile({name}) *undofile()*
Return the name of the undo file that would be used for a file
with name {name} when writing. This uses the 'undodir'
option, finding directories that exist. It does not check if
the undo file exists.
{name} is always expanded to the full path, since that is what
is used internally.
If {name} is empty undofile() returns an empty string, since a
buffer without a file name will not write an undo file.
Useful in combination with |:wundo| and |:rundo|.
When compiled without the |+persistent_undo| option this always
returns an empty string.
undotree() *undotree()*
Return the current state of the undo tree in a dictionary with
the following items:
"seq_last" The highest undo sequence number used.
"seq_cur" The sequence number of the current position in
the undo tree. This differs from "seq_last"
when some changes were undone.
"time_cur" Time last used for |:earlier| and related
commands. Use |strftime()| to convert to
something readable.
"save_last" Number of the last file write. Zero when no
write yet.
"save_cur" Number of the current position in the undo
tree.
"synced" Non-zero when the last undo block was synced.
This happens when waiting from input from the
user. See |undo-blocks|.
"entries" A list of dictionaries with information about
undo blocks.
The first item in the "entries" list is the oldest undo item.
Each List item is a Dictionary with these items:
"seq" Undo sequence number. Same as what appears in
|:undolist|.
"time" Timestamp when the change happened. Use
|strftime()| to convert to something readable.
"newhead" Only appears in the item that is the last one
that was added. This marks the last change
and where further changes will be added.
"curhead" Only appears in the item that is the last one
that was undone. This marks the current
position in the undo tree, the block that will
be used by a redo command. When nothing was
undone after the last change this item will
not appear anywhere.
"save" Only appears on the last block before a file
write. The number is the write count. The
first write has number 1, the last one the
"save_last" mentioned above.
"alt" Alternate entry. This is again a List of undo
blocks. Each item may again have an "alt"
item.
values({dict}) *values()*
Return a |List| with all the values of {dict}. The |List| is
in arbitrary order. Also see |items()| and |keys()|.
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 <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. |conceal| is ignored.
For the byte position use |col()|.
For the use of {expr} see |col()|.
When 'virtualedit' is used {expr} can be [lnum, col, off], where
"off" is the offset in screen columns from the start of the
character. E.g., a position within a <Tab> or after the last
character. When "off" is omitted zero is used.
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)
v In Visual mode: the start of the Visual area (the
cursor is the end). When not in Visual mode
returns the cursor position. Differs from |'<| in
that it's updated right away.
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.
A more advanced example that echoes the maximum length of
all lines: >
echo max(map(range(1, line('$')), "virtcol([v:val, '$'])"))
visualmode([{expr}]) *visualmode()*
The result is a String, which describes the last Visual mode
used in the current buffer. Initially it returns an empty
string, but once Visual mode has been used, it returns "v",
"V", or "<CTRL-V>" (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 Visual mode is active, use |mode()| to get the Visual mode
(e.g., in a |:vmap|).
If {expr} is supplied and it evaluates to a non-zero Number or
a non-empty String, then the Visual mode will be cleared and
the old value is returned. See |non-zero-arg|.
wildmenumode() *wildmenumode()*
Returns |TRUE| when the wildmenu is active and |FALSE|
otherwise. See 'wildmenu' and 'wildmode'.
This can be used in mappings to handle the 'wildcharm' option
gracefully. (Makes only sense with |mapmode-c| mappings).
For example to make <c-j> work like <down> in wildmode, use: >
:cnoremap <expr> <C-j> wildmenumode() ? "\<Down>\<Tab>" : "\<c-j>"
<
(Note, this needs the 'wildcharm' option set appropriately).
win_findbuf({bufnr}) *win_findbuf()*
Returns a list with |window-ID|s for windows that contain
buffer {bufnr}. When there is none the list is empty.
Can also be used as a |method|: >
GetBufnr()->win_findbuf()
win_gettype([{nr}]) *win_gettype()*
Return the type of the window:
"popup" popup window |popup|
"command" command-line window |cmdwin|
(empty) normal window
"unknown" window {nr} not found
win_gotoid({expr}) *win_gotoid()*
Go to window with ID {expr}. This may also change the current
tabpage.
Return 1 if successful, 0 if the window cannot be found.
win_id2tabwin({expr}) *win_id2tabwin()*
Return a list with the tab number and window number of window
with ID {expr}: [tabnr, winnr].
Return [0, 0] if the window cannot be found.
win_id2win({expr}) *win_id2win()*
Return the window number of window with ID {expr}.
Return 0 if the window cannot be found in the current tabpage.
win_screenpos({nr}) *win_screenpos()*
Return the screen position of window {nr} as a list with two
numbers: [row, col]. The first window always has position
[1, 1], unless there is a tabline, then it is [2, 1].
{nr} can be the window number or the |window-ID|.
Return [0, 0] if the window cannot be found in the current
tabpage.
*winbufnr()*
winbufnr({nr}) The result is a Number, which is the number of the buffer
associated with window {nr}. {nr} can be the window number or
the |window-ID|.
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))
<
Can also be used as a |method|: >
FindWindow()->winbufnr()->bufname()
<
*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.
*windowsversion()*
windowsversion()
The result is a String. For MS-Windows it indicates the OS
version. E.g, Windows 10 is "10.0", Windows 8 is "6.2",
Windows XP is "5.1". For non-MS-Windows systems the result is
an empty string.
winheight({nr}) *winheight()*
The result is a Number, which is the height of window {nr}.
{nr} can be the window number or the |window-ID|.
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.
This excludes any window toolbar line.
Examples: >
:echo "The current window has " . winheight(0) . " lines."
Example: >
" Only one window in the tab page
:echo winlayout()
['leaf', 1000]
" Two horizontally split windows
:echo winlayout()
['col', [['leaf', 1000], ['leaf', 1001]]]
" The second tab page, with three horizontally split
" windows, with two vertically split windows in the
" middle window
:echo winlayout(2)
['col', [['leaf', 1002], ['row', [['leaf', 1003],
['leaf', 1001]]], ['leaf', 1000]]]
<
Can also be used as a |method|: >
GetTabnr()->winlayout()
<
*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.
If the cursor was moved the view on the file will be updated
first, this may cause a scroll.
*winnr()*
winnr([{arg}]) The result is a Number, which is the number of the current
window. The top window has number 1.
Returns zero for a popup window.
winwidth({nr}) *winwidth()*
The result is a Number, which is the width of window {nr}.
{nr} can be the window number or the |window-ID|.
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
: 50 wincmd |
:endif
< For getting the terminal or screen size, see the 'columns'
option.
wordcount() *wordcount()*
The result is a dictionary of byte/chars/word statistics for
the current buffer. This is the same info as provided by
|g_CTRL-G|
The return value includes:
bytes Number of bytes in the buffer
chars Number of chars in the buffer
words Number of words in the buffer
cursor_bytes Number of bytes before cursor position
(not in Visual mode)
cursor_chars Number of chars before cursor position
(not in Visual mode)
cursor_words Number of words before cursor position
(not in Visual mode)
visual_bytes Number of bytes visually selected
(only in Visual mode)
visual_chars Number of chars visually selected
(only in Visual mode)
visual_words Number of words visually selected
(only in Visual mode)
*writefile()*
writefile({object}, {fname} [, {flags}])
When {object} is a |List| write it to file {fname}. Each list
item is separated with a NL. Each list item must be a String
or Number.
When {flags} contains "b" then binary mode is used: There will
not be a NL after the last list item. An empty item at the
end does cause the last line in the file to end in a NL.
When {flags} contains "a" then append mode is used, lines are
appended to the file: >
:call writefile(["foo"], "event.log", "a")
:call writefile(["bar"], "event.log", "a")
<
When {flags} contains "s" then fsync() is called after writing
the file. This flushes the file to disk, if possible. This
takes more time but avoids losing the file if the system
crashes.
When {flags} does not contain "S" or "s" then fsync() is
called if the 'fsync' option is set.
When {flags} contains "S" then fsync() is not called, even
when 'fsync' is set.
*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. Beyond a certain version or at a certain version and including a specific
patch. The "patch-7.4.248" feature means that the Vim version is 7.5 or
later, or it is version 7.4 and patch 248 was included. Example: >
:if has("patch-7.4.248")
< Note that it's possible for patch 248 to be omitted even though 249 is
included. Only happens when cherry-picking patches.
Note that this form only works for patch 7.4.237 and later, before that
you need to check for the patch and the v:version. Example (checking
version 6.2.148 or later): >
:if v:version > 602 || (v:version == 602 && has("patch148"))
*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.
This section is about the legacy functions. For the Vim9 functions, which
execute much faster, support type checking and more, see |vim9.txt|.
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|. And the
|autoload| facility is useful to define a function only when it's called.
*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 mapping defined in the script, but then |<SID>| must be used
instead of "s:" when the mapping is expanded outside of the script.
There are only script-local functions, no buffer-local or window-local
functions.
:let F = Foo()
:echo F()
< 1 >
:echo F()
< 2 >
:echo F()
< 3
*function-search-undo*
The last used search pattern and the redo command "."
will not be changed by the function. This also
implies that the effect of |:nohlsearch| is undone
when the function returns.
*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).
*a:0* *a:1* *a:000* *E740* *...*
Up to 20 arguments can be given, separated by commas. After the named
arguments an argument "..." can be specified, which means that more arguments
may optionally be following. In the function the extra arguments can be used
as "a:1", "a:2", etc. "a:0" is set to the number of extra arguments (which
can be 0). "a:000" is set to a |List| that contains these arguments. Note
that "a:1" is the same as "a:000[0]".
*E742*
The a: scope and the variables in it cannot be changed, they are fixed.
However, if a composite type is used, such as |List| or |Dictionary| , you can
change their contents. Thus you can pass a |List| to a function and have the
function add an item to it. If you want to make sure the function cannot
change a |List| or |Dictionary| use |:lockvar|.
*optional-function-argument*
You can provide default values for positional named arguments. This makes
them optional for function calls. When a positional argument is not
specified at a call, the default expression is used to initialize it.
This only works for functions declared with `:function` or `:def`, not for
lambda expressions |expr-lambda|.
Example: >
function Something(key, value = 10)
echo a:key .. ": " .. a:value
endfunction
call Something('empty') "empty: 10"
call Something('key', 20) "key: 20"
The argument default expressions are evaluated at the time of the function
call, not definition. Thus it is possible to use an expression which is
invalid the moment the function is defined. The expressions are also only
evaluated when arguments are not specified during a call.
You can pass |v:none| to use the default expression. Note that this means you
cannot pass v:none as an ordinary value when an argument has a default
expression.
Example: >
function Something(a = 10, b = 20, c = 30)
endfunction
call Something(1, v:none, 3) " b = 20
<
*E989*
Optional arguments with default expressions must occur after any mandatory
arguments. You can use "..." after all optional named arguments.
*local-variables*
Inside a function local variables can be used. These 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
: echo a:0 . " items:"
: for s in a:000
: echon ' ' . s
: endfor
:endfunction
*E132*
The recursiveness of user functions is restricted with the |'maxfuncdepth'|
option.
It is also possible to use `:eval`. It does not support a range, but does
allow for method chaining, e.g.: >
eval GetList()->Filter()->append('$')
Using an autocommand ~
The autocommand is useful if you have a plugin that is a long Vim script file.
You can define the autocommand and quickly quit the script with `:finish`.
That makes Vim startup faster. The autocommand should then load the same file
again, setting a variable to skip the `:finish` command.
Use the FuncUndefined autocommand event with a pattern that matches the
function(s) to be defined. Example: >
The file "~/vim/bufnetfuncs.vim" should then define functions that start with
"BufNet". Also see |FuncUndefined|.
:call filename#funcname()
When such a function is called, and it is not defined yet, Vim will search the
"autoload" directories in 'runtimepath' for a script file called
"filename.vim". For example "~/.vim/autoload/filename.vim". That file should
then define the function like this: >
function filename#funcname()
echo "Done!"
endfunction
The file name and the name used before the # in the function must match
exactly, and the defined function must have the name exactly as it will be
called.
:call foo#bar#func()
This also works when reading a variable that has not been set yet: >
:let l = foo#bar#lvar
However, when the autoload script was already loaded it won't be loaded again
for an unknown variable.
When assigning a value to such a variable nothing special happens. This can
be used to pass settings to the autoload script before it's loaded: >
:let foo#bar#toggle = 1
:call foo#bar#func()
Note that when you make a mistake and call a function that is supposed to be
defined in an autoload script, but the script doesn't actually define the
function, the script will be sourced every time you try to call the function.
And you will get an error message every time.
Also note that if you have two script files, and one calls a function in the
other and vice versa, before the used function is defined, it won't work.
Avoid using the autoload functionality at the toplevel.
Hint: If you distribute a bunch of scripts you can pack them together with the
|vimball| utility. Also read the user manual |distribute-script|.
==============================================================================
6. Curly braces names *curly-braces-names*
In most places where 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".
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)
==============================================================================
7. Commands *expression-commands*
*E711* *E719*
:let {var-name}[{idx1}:{idx2}] = {expr1} *E708* *E709* *E710*
Set a sequence of items in a |List| to the result of
the expression {expr1}, which must be a list with the
correct number of items.
{idx1} can be omitted, zero is used instead.
{idx2} can be omitted, meaning the end of the list.
When the selected range of items is partly past the
end of the list, items will be added.
*:let=<<* *:let-heredoc*
*E990* *E991* *E172* *E221*
:let {var-name} =<< [trim] {endmarker}
text...
text...
{endmarker}
Set internal variable {var-name} to a List containing
the lines of text bounded by the string {endmarker}.
{endmarker} must not contain white space.
{endmarker} cannot start with a lower case character.
The last line should end only with the {endmarker}
string without any other character. Watch out for
white space after {endmarker}!
*:cons* *:const*
:cons[t] {var-name} = {expr1}
:cons[t] [{name1}, {name2}, ...] = {expr1}
:cons[t] [{name}, ..., ; {lastname}] = {expr1}
:cons[t] {var-name} =<< [trim] {marker}
text...
text...
{marker}
Similar to |:let|, but additionally lock the variable
after setting the value. This is the same as locking
the variable with |:lockvar| just after |:let|, thus: >
:const x = 1
< is equivalent to: >
:let x = 1
:lockvar 1 x
< This is useful if you want to make sure the variable
is not modified.
*E995*
|:const| does not allow to for changing a variable: >
:let x = 1
:const x = 2 " Error!
< *E996*
Note that environment variables, option values and
register values cannot be used here, since they cannot
be locked.
:cons[t]
:cons[t] {var-name}
If no argument is given or only {var-name} is given,
the behavior is the same as |:let|.
*: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
< *:echo-redraw*
A later redraw may make the message disappear again.
And since Vim mostly postpones redrawing until it's
finished with a sequence of commands this happens
quite often. 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.
The parsing works slightly different from |:echo|,
more like |:execute|. All the expressions are first
evaluated and concatenated before echoing anything.
If expressions does not evaluate to a Number or
String, string() is used to turn it into a string.
Uses the highlighting set by the |:echohl| command.
Example: >
:echomsg "It's a Zizzer Zazzer Zuzz, as you can plainly see."
< See |:echo-redraw| to avoid the message disappearing
when the screen is redrawn.
*: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
|:echomsg| 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 \<Esc>"
<
*:eval*
:eval {expr} Evaluate {expr} and discard the result. Example: >
:eval Getlist()->Filter()->append('$')
*: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. To avoid the extra space use the "."
operator to concatenate strings into one argument.
{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"
*:exe-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 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|.
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.
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|).
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)
: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.
: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()
Nothing caught
Caught "4711" in function Foo, line 4
Caught "oops" in function Foo, line 10
Nothing caught
: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
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
*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"
: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|.
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:
You can catch all errors related to the name "nofunc" by >
:catch /\<nofunc\>/
You can catch all Vim errors in the ":write" and ":read" commands by >
:catch /^Vim(\(write\|read\)):E\d\+:/
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: >
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.
: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|.
:catch /.*/
:catch //
:catch
: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*
*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: >
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: >
If you really need to execute the autocommands even when the main action
fails, trigger the event from the catch clause.
Example: >
: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
If the main action of the command does not fail, exceptions from the
autocommands will be catchable by the caller of the command: >
: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: >
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.)
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
*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 Binary ~
>
:" The function Nr2Bin() returns the binary string representation of a number.
:func Nr2Bin(nr)
: let n = a:nr
: let r = ""
: while n
: let r = '01'[n % 2] . r
: let n = n / 2
: endwhile
: return r
:endfunc
Sorting lines ~
:func SortBuffer()
: let lines = getline(1, '$')
: call sort(lines, function("Strcmp"))
: call setline(1, lines)
:endfunction
As a one-liner: >
:call setline(1, sort(getline(1, '$'), function("Strcmp")))
scanf() replacement ~
*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)
" Split the output into lines and parse each line. Add an entry to the
" "scripts" dictionary.
let scripts = {}
for line in split(scriptnames_output, "\n")
" Only do non-blank lines.
if line =~ '\S'
" Get the first number in the line.
let nr = matchstr(line, '\d\+')
" Get the file name, remove the script number " 123: ".
let name = substitute(line, '.\+:\s*', '', '')
" Add an item to the Dictionary
let scripts[nr] = name
endif
endfor
unlet scriptnames_output
==============================================================================
10. Vim script versions *vimscript-version* *vimscript-versions*
*scriptversion*
Over time many features have been added to Vim script. This includes Ex
commands, functions, variable types, etc. Each individual feature can be
checked with the |has()| and |exists()| functions.
Sometimes old syntax of functionality gets in the way of making Vim better.
When support is taken away this will break older Vim scripts. To make this
explicit the |:scriptversion| command can be used. When a Vim script is not
compatible with older versions of Vim this will give an explicit error,
instead of failing in mysterious ways.
*scriptversion-1* >
:scriptversion 1
< This is the original Vim script, same as not using a |:scriptversion|
command. Can be used to go back to old syntax for a range of lines.
Test for support with: >
has('vimscript-1')
*scriptversion-3* >
:scriptversion 3
< All |vim-variable|s must be prefixed by "v:". E.g. "version" doesn't
work as |v:version| anymore, it can be used as a normal variable.
Same for some obvious names as "count" and others.
Test for support with: >
has('vimscript-3')
<
*scriptversion-4* >
:scriptversion 4
< Numbers with a leading zero are not recognized as octal. With the
previous version you get: >
echo 017 " displays 15
echo 018 " displays 18
< with script version 4: >
echo 017 " displays 17
echo 018 " displays 18
< Also, it is possible to use single quotes inside numbers to make them
easier to read: >
echo 1'000'000
< The quotes must be surrounded by digits.
==============================================================================
11. 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.
:if 1
: echo "Expression evaluation is compiled in"
:else
: echo "You will _never_ see this message"
:endif
To execute a command only when the |+eval| feature is disabled can be done in
two ways. The simplest is to exit the script (or Vim) prematurely: >
if 1
echo "commands executed with +eval"
finish
endif
args " command executed without +eval
If you do not want to abort loading the script you can use a trick, as this
example shows: >
silent! while 0
set history=111
silent! endwhile
When the |+eval| feature is available the command is skipped because of the
"while 0". Without the |+eval| feature the "while 0" is an error, which is
silently ignored, and the command is executed.
==============================================================================
12. The sandbox *eval-sandbox* *sandbox* *E48*
*:san* *:sandbox*
:san[dbox] {cmd} Execute {cmd} in the sandbox. Useful to evaluate an
option that may have been set from a modeline, e.g.
'foldexpr'.
*sandbox-option*
A few options contain an expression. When this expression is evaluated it may
have to be done in the sandbox to avoid a security risk. But the sandbox is
restrictive, thus this only happens when the option was set from an insecure
location. Insecure in this context are:
- sourcing a .vimrc or .exrc in the current directory
- while executing in the sandbox
- value coming from a modeline
- executing a function that was defined in the sandbox
Note that when in the sandbox and saving an option value and restoring it, the
option will still be marked as it was set in the sandbox.
==============================================================================
13. Textlock *textlock*
In a few situations it is not allowed to change the text in the buffer, jump
to another window and some other things that might confuse or break what Vim
is currently doing. This mostly applies to things that happen when Vim is
actually doing something else. For example, evaluating the 'balloonexpr' may
happen any moment the mouse cursor is resting at some position.
vim:tw=78:ts=8:noet:ft=help:norl: