Movatterモバイル変換


[0]ホーム

URL:


Vimfn

Nvim:help pages,generated fromsource using thetree-sitter-vimdoc parser.


Vimscript functionsbuiltin.txt
For functions grouped by what they are used for seefunction-list.

1. Detailsvimscript-functions-details

abs({expr})abs()
Return the absolute value of{expr}. When{expr} evaluates toaFloat abs() returns aFloat. When{expr} can beconverted to aNumber abs() returns aNumber. Otherwiseabs() gives an error message and returns -1.Examples:
echo abs(1.456)
1.456
echo abs(-5.456)
5.456
echo abs(-4)
4
Parameters:
{expr} (number)
Return:
(number)
acos({expr})acos()
Return the arc cosine of{expr} measured in radians, as aFloat in the range of [0, pi].{expr} must evaluate to aFloat or aNumber in the range[-1, 1].Returns NaN if{expr} is outside the range [-1, 1]. Returns0.0 if{expr} is not aFloat or aNumber.Examples:
echo acos(0)
1.570796
echo acos(-0.5)
2.094395
Parameters:
{expr} (number)
Return:
(number)
add({object},{expr})add()
Append the item{expr} toList orBlob{object}. Returnsthe resultingList orBlob. Examples:
let alist = add([1, 2, 3], item)call add(mylist, "woodstock")
Note that when{expr} is aList it is appended as a singleitem. Useextend() to concatenateLists.When{object} is aBlob then{expr} must be a number.Useinsert() to add an item at another position.Returns 1 if{object} is not aList or aBlob.
Parameters:
{object} (any)
{expr} (any)
Return:
(any) ResultingList orBlob, or 1 if{object} is not aList or aBlob.
and({expr},{expr})and()
Bitwise AND on the two arguments. The arguments are convertedto a number. A List, Dict or Float argument causes an error.Also seeor() andxor().Example:
let flag = and(bits, 0x80)
Parameters:
{expr} (number)
{expr1} (number)
Return:
(integer)
api_info()api_info()
Returns Dictionary ofapi-metadata.
View it in a nice human-readable format:
lua vim.print(vim.fn.api_info())
Return:
(table)
append({lnum},{text})append()
When{text} is aList: Append each item of theList as atext line below line{lnum} in the current buffer.Otherwise append{text} as one text line below line{lnum} inthe current buffer.Any type of item is accepted and converted to a String.{lnum} can be zero to insert a line before the first one.{lnum} is used like withgetline().Returns 1 for failure ({lnum} out of range or out of memory),0 for success. When{text} is an empty list zero is returned,no matter the value of{lnum}. Example:
let failed = append(line('$'), "# THE END")let failed = append(0, ["Chapter 1", "the beginning"])
Parameters:
{lnum} (integer|string)
{text} (string|string[])
Return:
(0|1)
appendbufline({buf},{lnum},{text})appendbufline()
Likeappend() but append the text in buffer{expr}.
This function works only for loaded buffers. First callbufload() if needed.
For the use of{buf}, seebufname().
{lnum} is the line number to append below. Note that usingline() would use the current buffer, not the one appendingto. Use "$" to append at the end of the buffer. Other stringvalues are not supported.
On success 0 is returned, on failure 1 is returned.
If{buf} is not a valid buffer or{lnum} is not valid, anerror message is given. Example:
let failed = appendbufline(13, 0, "# THE START")
However, when{text} is an empty list then no error is givenfor an invalid{lnum}, since{lnum} isn't actually used.
Parameters:
{buf} (integer|string)
{lnum} (integer)
{text} (string)
Return:
(0|1)
argc([{winid}])argc()
The result is the number of files in the argument list. Seearglist.If{winid} is not supplied, the argument list of the currentwindow is used.If{winid} is -1, the global argument list is used.Otherwise{winid} specifies the window of which the argumentlist is used: either the window number or the window ID.Returns -1 if the{winid} argument is invalid.
Parameters:
{winid} (integer?)
Return:
(integer)
argidx()argidx()
The result is the current index in the argument list. 0 isthe first file. argc() - 1 is the last one. Seearglist.
Return:
(integer)
arglistid([{winnr} [,{tabnr}]])arglistid()
Return the argument list ID. This is a number whichidentifies the argument list being used. Zero is used for theglobal argument list. Seearglist.Returns -1 if the arguments are invalid.
Without arguments use the current window.With{winnr} only use this window in the current tab page.With{winnr} and{tabnr} use the window in the specified tabpage.{winnr} can be the window number or thewindow-ID.
Parameters:
{winnr} (integer?)
{tabnr} (integer?)
Return:
(integer)
argv([{nr} [,{winid}]])argv()
The result is the{nr}th file in the argument list. Seearglist. "argv(0)" is the first one. Example:
let i = 0while i < argc()  let f = escape(fnameescape(argv(i)), '.')  exe 'amenu Arg.' .. f .. ' :e ' .. f .. '<CR>'  let i = i + 1endwhile
Without the{nr} argument, or when{nr} is -1, aList withthe wholearglist is returned.
The{winid} argument specifies the window ID, seeargc().For the Vim command line arguments seev:argv.
Returns an empty string if{nr}th argument is not present inthe argument list. Returns an empty List if the{winid}argument is invalid.
Parameters:
{nr} (integer?)
{winid} (integer?)
Return:
(string|string[])
asin({expr})asin()
Return the arc sine of{expr} measured in radians, as aFloatin the range of [-pi/2, pi/2].{expr} must evaluate to aFloat or aNumber in the range[-1, 1].Returns NaN if{expr} is outside the range [-1, 1]. Returns0.0 if{expr} is not aFloat or aNumber.Examples:
echo asin(0.8)
0.927295
echo asin(-0.5)
-0.523599
Parameters:
{expr} (any)
Return:
(number)
assert_beeps({cmd})assert_beeps()
Run{cmd} and add an error message tov:errors if it doesNOT produce a beep or visual bell.Also seeassert_fails(),assert_nobeep() andassert-return.
Parameters:
{cmd} (string)
Return:
(0|1)
assert_equal({expected},{actual} [,{msg}])assert_equal()
When{expected} and{actual} are not equal an error message isadded tov:errors and 1 is returned. Otherwise zero isreturned.assert-returnThe error is in the form "Expected{expected} but got{actual}". When{msg} is present it is prefixed to that,along with the location of the assert when run from a script.
There is no automatic conversion, the String "4" is differentfrom the Number 4. And the number 4 is different from theFloat 4.0. The value of'ignorecase' is not used here, casealways matters.Example:
call assert_equal('foo', 'bar', 'baz')
Will add the following tov:errors:
test.vim line 12: baz: Expected 'foo' but got 'bar'
Parameters:
{expected} (any)
{actual} (any)
{msg} (any?)
Return:
(0|1)
assert_equalfile({fname_one},{fname_two})assert_equalfile()
When the files{fname_one} and{fname_two} do not containexactly the same text an error message is added tov:errors.Also seeassert-return.When{fname_one} or{fname_two} does not exist the error willmention that.
Parameters:
{fname_one} (string)
{fname_two} (string)
Return:
(0|1)
assert_exception({error} [,{msg}])assert_exception()
When v:exception does not contain the string{error} an errormessage is added tov:errors. Also seeassert-return.This can be used to assert that a command throws an exception.Using the error number, followed by a colon, avoids problemswith translations:
try  commandthatfails  call assert_false(1, 'command should have failed')catch  call assert_exception('E492:')endtry
Parameters:
{error} (any)
{msg} (any?)
Return:
(0|1)
assert_fails()
assert_fails({cmd} [,{error} [,{msg} [,{lnum} [,{context}]]]])Run{cmd} and add an error message tov:errors if it doesNOT produce an error or when{error} is not found in theerror message. Also seeassert-return.
When{error} is a string it must be found literally in thefirst reported error. Most often this will be the error code,including the colon, e.g. "E123:".
call assert_fails('bad cmd', 'E987:')
When{error} is aList with one or two strings, these areused as patterns. The first pattern is matched against thefirst reported error:
call assert_fails('cmd', ['E987:.*expected bool'])
The second pattern, if present, is matched against the lastreported error. To only match the last error use an emptystring for the first error:
call assert_fails('cmd', ['', 'E987:'])
If{msg} is empty then it is not used. Do this to get thedefault message when passing the{lnum} argument.E1115
When{lnum} is present and not negative, and the{error}argument is present and matches, then this is compared withthe line number at which the error was reported. That can bethe line number in a function or in a script.E1116
When{context} is present it is used as a pattern and matchedagainst the context (script name or function name) where{lnum} is located in.
Note that beeping is not considered an error, and some failingcommands only beep. Useassert_beeps() for those.
Parameters:
{cmd} (string)
{error} (any?)
{msg} (any?)
{lnum} (integer?)
{context} (any?)
Return:
(0|1)
assert_false({actual} [,{msg}])assert_false()
When{actual} is not false an error message is added tov:errors, like withassert_equal().The error is in the form "Expected False but got{actual}".When{msg} is present it is prefixed to that, along with thelocation of the assert when run from a script.Also seeassert-return.
A value is false when it is zero. When{actual} is not anumber the assert fails.
Parameters:
{actual} (any)
{msg} (any?)
Return:
(0|1)
assert_inrange({lower},{upper},{actual} [,{msg}])assert_inrange()
This asserts number andFloat values. When{actual} is lowerthan{lower} or higher than{upper} an error message is addedtov:errors. Also seeassert-return.The error is in the form "Expected range{lower} -{upper},but got{actual}". When{msg} is present it is prefixed tothat.
Parameters:
{lower} (number)
{upper} (number)
{actual} (number)
{msg} (string?)
Return:
(0|1)
assert_match({pattern},{actual} [,{msg}])assert_match()
When{pattern} does not match{actual} an error message isadded tov:errors. Also seeassert-return.The error is in the form "Pattern{pattern} does not match{actual}". When{msg} is present it is prefixed to that,along with the location of the assert when run from a script.
{pattern} is used as withexpr-=~: The matching is always donelike'magic' was set and'cpoptions' is empty, no matter whatthe actual value of'magic' or'cpoptions' is.
{actual} is used as a string, automatic conversion applies.Use "^" and "$" to match with the start and end of the text.Use both to match the whole text.
Example:
call assert_match('^f.*o$', 'foobar')
Will result in a string to be added tov:errors:
test.vim line 12: Pattern '^f.*o$' does not match 'foobar'
Parameters:
{pattern} (string)
{actual} (string)
{msg} (string?)
Return:
(0|1)
assert_nobeep({cmd})assert_nobeep()
Run{cmd} and add an error message tov:errors if itproduces a beep or visual bell.Also seeassert_beeps().
Parameters:
{cmd} (string)
Return:
(0|1)
assert_notequal({expected},{actual} [,{msg}])assert_notequal()
The opposite ofassert_equal(): add an error message tov:errors when{expected} and{actual} are equal.Also seeassert-return.
Parameters:
{expected} (any)
{actual} (any)
{msg} (any?)
Return:
(0|1)
assert_notmatch({pattern},{actual} [,{msg}])assert_notmatch()
The opposite ofassert_match(): add an error message tov:errors when{pattern} matches{actual}.Also seeassert-return.
Parameters:
{pattern} (string)
{actual} (string)
{msg} (string?)
Return:
(0|1)
assert_report({msg})assert_report()
Report a test failure directly, using String{msg}.Always returns one.
Parameters:
{msg} (string)
Return:
(0|1)
assert_true({actual} [,{msg}])assert_true()
When{actual} is not true an error message is added tov:errors, like withassert_equal().Also seeassert-return.A value isTRUE when it is a non-zero number orv:true.When{actual} is not a number orv:true the assert fails.When{msg} is given it is prefixed to the default message,along with the location of the assert when run from a script.
Parameters:
{actual} (any)
{msg} (string?)
Return:
(0|1)
atan({expr})atan()
Return the principal value of the arc tangent of{expr}, inthe range [-pi/2, +pi/2] radians, as aFloat.{expr} must evaluate to aFloat or aNumber.Returns 0.0 if{expr} is not aFloat or aNumber.Examples:
echo atan(100)
1.560797
echo atan(-4.01)
-1.326405
Parameters:
{expr} (number)
Return:
(number)
atan2({expr1},{expr2})atan2()
Return the arc tangent of{expr1} /{expr2}, measured inradians, as aFloat in the range [-pi, pi].{expr1} and{expr2} must evaluate to aFloat or aNumber.Returns 0.0 if{expr1} or{expr2} is not aFloat or aNumber.Examples:
echo atan2(-1, 1)
-0.785398
echo atan2(1, -1)
2.356194
Parameters:
{expr1} (number)
{expr2} (number)
Return:
(number)
blob2list({blob})blob2list()
Return a List containing the number value of each byte in Blob{blob}. Examples:
blob2list(0z0102.0304)" returns [1, 2, 3, 4]blob2list(0z)" returns []
Returns an empty List on error.list2blob() does theopposite.
Parameters:
{blob} (any)
Return:
(any[])
browse({save},{title},{initdir},{default})browse()
Put up a file requester. This only works when "has("browse")"returnsTRUE (only in some GUI versions).The input fields are:{save}whenTRUE, select file to write{title}title for the requester{initdir}directory to start browsing in{default}default file nameAn empty string is returned when the "Cancel" button is hit,something went wrong, or browsing is not possible.
Parameters:
{save} (any)
{title} (string)
{initdir} (string)
{default} (string)
Return:
(0|1)
browsedir({title},{initdir})browsedir()
Put up a directory requester. This only works when"has("browse")" returnsTRUE (only in some GUI versions).On systems where a directory browser is not supported a filebrowser is used. In that case: select a file in the directoryto be used.The input fields are:{title}title for the requester{initdir}directory to start browsing inWhen the "Cancel" button is hit, something went wrong, orbrowsing is not possible, an empty string is returned.
Parameters:
{title} (string)
{initdir} (string)
Return:
(0|1)
bufadd({name})bufadd()
Add a buffer to the buffer list with name{name} (must be aString).If a buffer for file{name} already exists, return that buffernumber. Otherwise return the buffer number of the newlycreated buffer. When{name} is an empty string then a newbuffer is always created.The buffer will not have'buflisted' set and not be loadedyet. To add some text to the buffer use this:
let bufnr = bufadd('someName')call bufload(bufnr)call setbufline(bufnr, 1, ['some', 'text'])
Returns 0 on error.
Parameters:
{name} (string)
Return:
(integer)
bufexists({buf})bufexists()
The result is a Number, which isTRUE if a buffer called{buf} exists.If the{buf} argument is a number, buffer numbers are used.Number zero is the alternate buffer for the current window.
If the{buf} argument is a string it must match a buffer nameexactly. The name can be:
Relative to the current directory.
A full path.
The name of a buffer with'buftype' set to "nofile".
A URL name.Unlisted buffers will be found.Note that help files are listed by their short name in theoutput of:buffers, but bufexists() requires using theirlong name to be able to find them.bufexists() may report a buffer exists, but to use the namewith a:buffer command you may need to useexpand(). Espfor MS-Windows 8.3 names in the form "c:\DOCUME~1"Use "bufexists(0)" to test for the existence of an alternatefile name.
Parameters:
{buf} (any)
Return:
(0|1)
buflisted({buf})buflisted()
The result is a Number, which isTRUE if a buffer called{buf} exists and is listed (has the'buflisted' option set).The{buf} argument is used like withbufexists().
Parameters:
{buf} (any)
Return:
(0|1)
bufload({buf})bufload()
Ensure the buffer{buf} is loaded. When the buffer namerefers to an existing file then the file is read. Otherwisethe buffer will be empty. If the buffer was already loadedthen there is no change. If the buffer is not related to afile then no file is read (e.g., when'buftype' is "nofile").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{buf} argument is used like withbufexists().
Parameters:
{buf} (any)
bufloaded({buf})bufloaded()
The result is a Number, which isTRUE if a buffer called{buf} exists and is loaded (shown in a window or hidden).The{buf} argument is used like withbufexists().
Parameters:
{buf} (any)
Return:
(0|1)
bufname([{buf}])bufname()
The result is the name of a buffer. Mostly as it is displayedby the:ls command, but not using special names such as"[No Name]".If{buf} is omitted the current buffer is used.If{buf} is a Number, that buffer number's name is given.Number zero is the alternate buffer for the current window.If{buf} is a String, it is used as afile-pattern to matchwith the buffer names. This is always done like'magic' isset and'cpoptions' is empty. When there is more than onematch an empty string is returned."" or "%" can be used for the current buffer, "#" for thealternate buffer.A full match is preferred, otherwise a match at the start, endor middle of the buffer name is accepted. If you only want afull match then put "^" at the start and "$" at the end of thepattern.Listed buffers are found first. If there is a single matchwith a listed buffer, that one is returned. Next unlistedbuffers are searched for.If the{buf} is a String, but you want to use it as a buffernumber, force it to be a Number by adding zero to it:
echo bufname("3" + 0)
If the buffer doesn't exist, or doesn't have a name, an emptystring is returned.
echo bufname("#")" alternate buffer nameecho bufname(3)" name of buffer 3echo bufname("%")" name of current bufferecho bufname("file2")" name of buffer where "file2" matches.
Parameters:
{buf} (integer|string?)
Return:
(string)
bufnr([{buf} [,{create}]])bufnr()
The result is the number of a buffer, as it is displayed bythe:ls command. For the use of{buf}, seebufname()above.If the buffer doesn't exist, -1 is returned. Or, if the{create} argument is present and TRUE, a new, unlisted,buffer is created and its number is returned.bufnr("$") is the last buffer:
let last_buffer = bufnr("$")
The result is a Number, which is the highest buffer numberof existing buffers. Note that not all buffers with a smallernumber necessarily exist, because ":bwipeout" may have removedthem. Use bufexists() to test for the existence of a buffer.
Parameters:
{buf} (integer|string?)
{create} (any?)
Return:
(integer)
bufwinid({buf})bufwinid()
The result is a Number, which is thewindow-ID of the firstwindow associated with buffer{buf}. For the use of{buf},seebufname() above. If buffer{buf} doesn't exist orthere is no such window, -1 is returned. Example:
echo "A window containing buffer 1 is " .. (bufwinid(1))
Only deals with the current tab page. Seewin_findbuf() forfinding more.
Parameters:
{buf} (any)
Return:
(integer)
bufwinnr({buf})bufwinnr()
Likebufwinid() but return the window number instead of thewindow-ID.If buffer{buf} doesn't exist or there is no such window, -1is returned. Example:
echo "A window containing buffer 1 is " .. (bufwinnr(1))
The number can be used withCTRL-W_w and ":wincmd w":wincmd.
Parameters:
{buf} (any)
Return:
(integer)
byte2line({byte})byte2line()
Return the line number that contains the character at bytecount{byte} in the current buffer. This includes theend-of-line character, depending on the'fileformat' optionfor the current buffer. The first character has byte countone.Also seeline2byte(),go and:goto.
Returns -1 if the{byte} value is invalid.
Parameters:
{byte} (any)
Return:
(integer)
byteidx({expr},{nr} [,{utf16}])byteidx()
Return byte index of the{nr}th character in the String{expr}. Use zero for the first character, it then returnszero.If there are no multibyte characters the returned value isequal to{nr}.Composing characters are not counted separately, their bytelength is added to the preceding base character. Seebyteidxcomp() below for counting composing charactersseparately.When{utf16} is present and TRUE,{nr} is used as the UTF-16index in the String{expr} instead of as the character index.The UTF-16 index is the index in the string when it is encodedwith 16-bit words. If the specified UTF-16 index is in themiddle of a character (e.g. in a 4-byte character), then thebyte index of the first byte in the character is returned.Refer tostring-offset-encoding for more information.Example :
echo matchstr(str, ".", byteidx(str, 3))
will display the fourth character. Another way to do thesame:
let s = strpart(str, byteidx(str, 3))echo strpart(s, 0, byteidx(s, 1))
Also seestrgetchar() andstrcharpart().
If there are less than{nr} characters -1 is returned.If there are exactly{nr} characters the length of the stringin bytes is returned.Seecharidx() andutf16idx() for getting the character andUTF-16 index respectively from the byte index.Examples:
echo byteidx('a😊😊', 2)" returns 5echo byteidx('a😊😊', 2, 1)" returns 1echo byteidx('a😊😊', 3, 1)" returns 5
Parameters:
{expr} (any)
{nr} (integer)
{utf16} (any?)
Return:
(integer)
byteidxcomp({expr},{nr} [,{utf16}])byteidxcomp()
Like byteidx(), except that a composing character is countedas a separate character. Example:
let s = 'e' .. nr2char(0x301)echo byteidx(s, 1)echo byteidxcomp(s, 1)echo byteidxcomp(s, 2)
The first and third echo result in 3 ('e' plus composingcharacter is 3 bytes), the second echo results in 1 ('e' isone byte).
Parameters:
{expr} (any)
{nr} (integer)
{utf16} (any?)
Return:
(integer)
call({func},{arglist} [,{dict}])call()E699Call function{func} with the items inList{arglist} asarguments.{func} can either be aFuncref or the name of a function.a:firstline and a:lastline are set to the cursor line.Returns the return value of the called function.{dict} is for functions with the "dict" attribute. It will beused to set the local variable "self".Dictionary-function
Parameters:
{func} (any)
{arglist} (any)
{dict} (any?)
Return:
(any)
ceil({expr})ceil()
Return the smallest integral value greater than or equal to{expr} as aFloat (round up).{expr} must evaluate to aFloat or aNumber.Examples:
echo ceil(1.456)
2.0
echo ceil(-5.456)
-5.0
echo ceil(4.0)
4.0
Returns 0.0 if{expr} is not aFloat or aNumber.
Parameters:
{expr} (number)
Return:
(number)
chanclose({id} [,{stream}])chanclose()
Close a channel or a specific stream associated with it.For a job,{stream} can be one of "stdin", "stdout","stderr" or "rpc" (closes stdin/stdout for a job startedwith"rpc":v:true) If{stream} is omitted, all streamsare closed. If the channel is a pty, this will then close thepty master, sending SIGHUP to the job process.For a socket, there is only one stream, and{stream} should beomitted.
Parameters:
{id} (integer)
{stream} (string?)
Return:
(0|1)
changenr()changenr()
Return the number of the most recent change. This is the samenumber as what is displayed with:undolist and can be usedwith the:undo command.When a change was made it is the number of that change. Afterredo it is the number of the redone change. After undo it isone less than the number of the undone change.Returns 0 if the undo list is empty.
Return:
(integer)
chansend({id},{data})chansend()
Send data to channel{id}. For a job, it writes it to thestdin of the process. For the stdio channelchannel-stdio,it writes to Nvim's stdout. Returns the number of byteswritten if the write succeeded, 0 otherwise.Seechannel-bytes for more information.
{data} may be a string, string convertible,Blob, or a list.If{data} is a list, the items will be joined by newlines; anynewlines in an item will be sent as NUL. To send a finalnewline, include a final empty string. Example:
call chansend(id, ["abc", "123\n456", ""])
will send "abc<NL>123<NUL>456<NL>".
chansend() writes raw data, not RPC messages. If the channelwas created with"rpc":v:true then the channel expects RPCmessages, userpcnotify() andrpcrequest() instead.
Parameters:
{id} (number)
{data} (string|string[])
Return:
(0|1)
char2nr({string} [,{utf8}])char2nr()
Return Number value of the first char in{string}.Examples:
echo char2nr(" ")" returns 32echo char2nr("ABC")" returns 65echo char2nr("á")" returns 225echo char2nr("á"[0])" returns 195echo char2nr("\<M-x>")" returns 128
Non-ASCII characters are always treated as UTF-8 characters.{utf8} is ignored, it exists only for backwards-compatibility.A combining character is a separate character.nr2char() does the opposite.
Returns 0 if{string} is not aString.
Parameters:
{string} (string)
{utf8} (any?)
Return:
(0|1)
charclass({string})charclass()
Return the character class of the first character in{string}.The character class is one of:0blank1punctuation2word character (depends on'iskeyword')3emojiotherspecific Unicode classThe class is used in patterns and word motions.Returns 0 if{string} is not aString.
Parameters:
{string} (string)
Return:
(0|1|2|3|'other')
charcol({expr} [,{winid}])charcol()
Same ascol() but returns the character index of the columnposition given with{expr} instead of the byte position.
Example:With the cursor on '세' in line 5 with text "여보세요":
echo charcol('.')" returns 3echo col('.')" returns 7
Parameters:
{expr} (string|any[])
{winid} (integer?)
Return:
(integer)
charidx({string},{idx} [,{countcc} [,{utf16}]])charidx()
Return the character index of the byte at{idx} in{string}.The index of the first character is zero.If there are no multibyte characters the returned value isequal to{idx}.
When{countcc} is omitted orFALSE, then composing charactersare not counted separately, their byte length is added to thepreceding base character.When{countcc} isTRUE, then composing characters arecounted as separate characters.
When{utf16} is present and TRUE,{idx} is used as the UTF-16index in the String{expr} instead of as the byte index.
Returns -1 if the arguments are invalid or if there are lessthan{idx} bytes. If there are exactly{idx} bytes the lengthof the string in characters is returned.
An error is given and -1 is returned if the first argument isnot a string, the second argument is not a number or when thethird argument is present and is not zero or one.
Seebyteidx() andbyteidxcomp() for getting the byte indexfrom the character index andutf16idx() for getting theUTF-16 index from the character index.Refer tostring-offset-encoding for more information.Examples:
echo charidx('áb́ć', 3)" returns 1echo charidx('áb́ć', 6, 1)" returns 4echo charidx('áb́ć', 16)" returns -1echo charidx('a😊😊', 4, 0, 1)" returns 2
Parameters:
{string} (string)
{idx} (integer)
{countcc} (boolean?)
{utf16} (boolean?)
Return:
(integer)
chdir({dir} [,{scope}])chdir()
Changes the current working directory to{dir}. The scope ofthe change is determined as follows:If{scope} is not present, the current working directory ischanged to the scope of the current directory:
If the window local directory (:lcd) is set, it changes the current working directory for that scope.
Otherwise, if the tab page local directory (:tcd) is set, it changes the current directory for that scope.
Otherwise, changes the global directory for that scope.
If{scope} is present, changes the current working directoryfor the specified scope: "window"Changes the window local directory.:lcd "tabpage"Changes the tab page local directory.:tcd "global"Changes the global directory.:cd
{dir} must be a String.If successful, returns the previous working directory. Passthis 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
Parameters:
{dir} (string)
{scope} (string?)
Return:
(string)
cindent({lnum})cindent()
Get the amount of indent for line{lnum} according theC-indenting rules, as with'cindent'.The indent is counted in spaces, the value of'tabstop' isrelevant.{lnum} is used just like ingetline().When{lnum} is invalid -1 is returned.
To get or set indent of lines in a string, seevim.text.indent().
Parameters:
{lnum} (integer|string)
Return:
(integer)
clearmatches([{win}])clearmatches()
Clears all matches previously defined for the current windowbymatchadd() and the:match commands.If{win} is specified, use the window with this number orwindow ID instead of the current window.
Parameters:
{win} (integer?)
cmdcomplete_info()cmdcomplete_info()
Returns aDictionary with information about cmdlinecompletion. Seecmdline-completion.The items are: cmdline_origThe original command-line string beforecompletion began. pum_visibleTRUE if popup menu is visible.Seepumvisible(). matchesList of all completion candidates. Each itemis a string. selectedSelected item index. First index is zero.Index is -1 if no item is selected (showingtyped text only, or the last completion afterno item is selected when using the<Up> or<Down> keys)
Returns an emptyDictionary if no completion was attempted,if there was only one candidate and it was fully completed, orif an error occurred.
Return:
(table<string,any>)
col({expr} [,{winid}])col()
The result is a Number, which is the byte index of the columnposition given with{expr}.For accepted positions seegetpos().When{expr} is "$", it means the end of the cursor line, sothe result is the number of bytes in the cursor line plus one.Additionally{expr} can be [lnum, col]: aList with the lineand column number. Most useful when the column is "$", to getthe last column of a specific line. When "lnum" or "col" isout of range then col() returns zero.
With the optional{winid} argument the values are obtained forthat window instead of the current window.
To get the line number useline(). To get both usegetpos().
For the screen column position usevirtcol(). For thecharacter position usecharcol().
Note that only marks in the current file can be used.
Examples:
echo col(".")" column of cursorecho col("$")" length of cursor line plus oneecho col("'t")" column of mark techo col("'" .. markname)" column of mark markname
The first column is 1. Returns 0 if{expr} is invalid or whenthe window with ID{winid} is not found.For an uppercase mark the column may actually be in anotherbuffer.For the cursor position, when'virtualedit' is active, thecolumn is one higher if the cursor is after the end of theline. Also, when using a<Cmd> mapping the cursor isn'tmoved, this can be used to obtain the column in Insert mode:
imap <F2> <Cmd>echo col(".").."\n"<CR>
Parameters:
{expr} (string|any[])
{winid} (integer?)
Return:
(integer)
complete({startcol},{matches})complete()E785Set the matches for Insert mode completion.Can only be used in Insert mode. You need to use a mappingwithCTRL-R = (seei_CTRL-R). It does not work afterCTRL-Oor with an expression mapping.{startcol} is the byte offset in the line where the completedtext start. The text up to the cursor is the original textthat will be replaced by the matches. Use col('.') for anempty string. "col('.') - 1" will replace one character by amatch.{matches} must be aList. EachList item is one match.Seecomplete-items for the kind of items that are possible."longest" in'completeopt' is ignored.Note that the after calling this function you need to avoidinserting anything that would cause completion to stop.The match can be selected withCTRL-N andCTRL-P as usual withInsert mode completion. The popup menu will appear ifspecified, seeins-completion-menu.Example:
inoremap <F5> <C-R>=ListMonths()<CR>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 thatan empty string is returned to avoid a zero being inserted.
Parameters:
{startcol} (integer)
{matches} (any[])
complete_add({expr})complete_add()
Add{expr} to the list of matches. Only to be used by thefunction 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 inthe list.Seecomplete-functions for an explanation of{expr}. It isthe same as one item in the list that'omnifunc' would return.
Parameters:
{expr} (any)
Return:
(0|1|2)
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.ReturnsTRUE when searching for matches is to be aborted,zero otherwise.Only to be used by the function specified with the'completefunc' option.
Return:
(0|1)
complete_info([{what}])complete_info()
Returns aDictionary with information about Insert modecompletion. Seeins-completion.The items are: modeCurrent completion mode name string.Seecomplete_info_mode for the values. pum_visibleTRUE if popup menu is visible.Seepumvisible(). itemsList of all completion candidates. Each itemis a dictionary containing the entries "word","abbr", "menu", "kind", "info" and "user_data".Seecomplete-items. matchesSame as "items", but only returns items thatare matching current query. If both "matches"and "items" are in "what", the returned listwill still be named "items", but each itemwill have an additional "match" field. selectedSelected item index. First index is zero.Index is -1 if no item is selected (showingtyped text only, or the last completion afterno item is selected when using the<Up> or<Down> keys) completedReturn a dictionary containing the entries ofthe currently selected index item. preview_winid Info floating preview window id. preview_bufnr Info floating preview buffer id.
complete_info_mode
mode values are: "" Not in completion mode "keyword" Keyword completioni_CTRL-X_CTRL-N "ctrl_x" Just pressedCTRL-Xi_CTRL-X "scroll" Scrolling withi_CTRL-X_CTRL-E ori_CTRL-X_CTRL-Y "whole_line" Whole linesi_CTRL-X_CTRL-L "files" File namesi_CTRL-X_CTRL-F "tags" Tagsi_CTRL-X_CTRL-] "path_defines" Definition completioni_CTRL-X_CTRL-D "path_patterns" Include completioni_CTRL-X_CTRL-I "dictionary" Dictionaryi_CTRL-X_CTRL-K "thesaurus" Thesaurusi_CTRL-X_CTRL-T "cmdline" Vim Command linei_CTRL-X_CTRL-V "function" User defined completioni_CTRL-X_CTRL-U "omni" Omni completioni_CTRL-X_CTRL-O "spell" Spelling suggestionsi_CTRL-X_s "eval"complete() completion "register" Words from registersi_CTRL-X_CTRL-R "unknown" Other internal modes
If the optional{what} list argument is supplied, then onlythe items listed in{what} are returned. Unsupported items in{what} are silently ignored.
To get the position and size of the popup menu, seepum_getpos(). It's also available inv:event during theCompleteChanged event.
Returns an emptyDictionary on error.
Examples:
" Get all itemscall complete_info()" Get only 'mode'call complete_info(['mode'])" Get only 'mode' and 'pum_visible'call complete_info(['mode', 'pum_visible'])
Parameters:
{what} (any[]?)
Return:
(table)
complete_match([{lnum},{col}])complete_match()
Searches backward from the given position and returns a Listof matches according to the'isexpand' option. When noarguments are provided, uses the current cursor position.
Each match is represented as a List containing[startcol, trigger_text] where:
startcol: column position where completion should start, or -1 if no trigger position is found. For multi-character triggers, returns the column of the first character.
trigger_text: the matching trigger string from'isexpand', or empty string if no match was found or when using the default'iskeyword' pattern.
When'isexpand' is empty, uses the'iskeyword' pattern "\k\+$"to find the start of the current keyword.
Examples:
set isexpand=.,->,/,/*,abcfunc CustomComplete()  let res = complete_match()  if res->len() == 0 | return | endif  let [col, trigger] = res[0]  let items = []  if trigger == '/*'    let items = ['/** */']  elseif trigger == '/'    let items = ['/*! */', '// TODO:', '// fixme:']  elseif trigger == '.'    let items = ['length()']  elseif trigger =~ '^\->'    let items = ['map()', 'reduce()']  elseif trigger =~ '^\abc'    let items = ['def', 'ghk']  endif  if items->len() > 0    let startcol = trigger =~ '^/' ? col : col + len(trigger)    call complete(startcol, items)  endifendfuncinoremap <Tab> <Cmd>call CustomComplete()<CR>
Parameters:
{lnum} (integer?)
{col} (integer?)
Return:
(table)
confirm({msg} [,{choices} [,{default} [,{type}]]])confirm()
confirm() offers the user a dialog, from which a choice can bemade. It returns the number of the choice. For the firstchoice this is 1.
{msg} is displayed in a dialog with{choices} as thealternatives. When{choices} is missing or empty, "&OK" isused (and translated).{msg} is a String, use '\n' to include a newline. Only onsome systems the string is wrapped when it doesn't fit.
{choices} is a String, with the individual choices separatedby '\n', e.g.
confirm("Save changes?", "&Yes\n&No\n&Cancel")
The letter after the '&' is the shortcut key for that choice.Thus you can type 'c' to select "Cancel". The shortcut doesnot need to be the first letter:
confirm("file has been modified", "&Save\nSave &All")
For the console, the first letter of each choice is used asthe default shortcut key. Case is ignored.
The optional{type} String argument gives the type of dialog.It can be one of these values: "Error", "Question", "Info","Warning" or "Generic". Only the first character is relevant.When{type} is omitted, "Generic" is used.
The optional{type} argument gives the type of dialog. Thisis only used for the icon of the Win32 GUI. It can be one ofthese values: "Error", "Question", "Info", "Warning" or"Generic". Only the first character is relevant.When{type} is omitted, "Generic" is used.
If the user aborts the dialog by pressing<Esc>,CTRL-C,or another valid interrupt key, confirm() returns 0.
An example:
let choice = confirm("What do you want?",                     \ "&Apples\n&Oranges\n&Bananas", 2)if choice == 0     echo "make up your mind!"elseif choice == 3     echo "tasteful"else     echo "I prefer bananas myself."endif
In a GUI dialog, buttons are used. The layout of the buttonsdepends 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 theydon't fit, a vertical layout is used anyway. For some systemsthe horizontal layout is always used.
Parameters:
{msg} (string)
{choices} (string?)
{default} (integer?)
{type} (string?)
Return:
(integer)
copy({expr})copy()
Make a copy of{expr}. For Numbers and Strings this isn'tdifferent from using{expr} directly.When{expr} is aList a shallow copy is created. This meansthat the originalList can be changed without changing thecopy, and vice versa. But the items are identical, thuschanging an item changes the contents of bothLists.ADictionary is copied in a similar way as aList.Also seedeepcopy().
Parameters:
{expr} (T)
Return:
(T)
cos({expr})cos()
Return the cosine of{expr}, measured in radians, as aFloat.{expr} must evaluate to aFloat or aNumber.Returns 0.0 if{expr} is not aFloat or aNumber.Examples:
echo cos(100)
0.862319
echo cos(-4.01)
-0.646043
Parameters:
{expr} (number)
Return:
(number)
cosh({expr})cosh()
Return the hyperbolic cosine of{expr} as aFloat in the range[1, inf].{expr} must evaluate to aFloat or aNumber.Returns 0.0 if{expr} is not aFloat or aNumber.Examples:
echo cosh(0.5)
1.127626
echo cosh(-0.5)
-1.127626
Parameters:
{expr} (number)
Return:
(number)
count({comp},{expr} [,{ic} [,{start}]])count()E706Return the number of times an item with value{expr} appearsinString,List orDictionary{comp}.
If{start} is given then start with the item with this index.{start} can only be used with aList.
When{ic} is given and it'sTRUE then case is ignored.
When{comp} is a string then the number of not overlappingoccurrences of{expr} is returned. Zero is returned when{expr} is an empty string.
Parameters:
{comp} (string|table|any[])
{expr} (any)
{ic} (boolean?)
{start} (integer?)
Return:
(integer)
ctxget([{index}])ctxget()
Returns aDictionary representing thecontext at{index}from the top of thecontext-stack (seecontext-dict).If{index} is not given, it is assumed to be 0 (i.e.: top).
Parameters:
{index} (integer?)
Return:
(table)
ctxpop()ctxpop()
Pops and restores thecontext at the top of thecontext-stack.
Return:
(any)
ctxpush([{types}])ctxpush()
Pushes the current editor state (context) on thecontext-stack.If{types} is given and is aList ofStrings, it specifieswhichcontext-types to include in the pushed context.Otherwise, all context types are included.
Parameters:
{types} (string[]?)
Return:
(any)
ctxset({context} [,{index}])ctxset()
Sets thecontext at{index} from the top of thecontext-stack to that represented by{context}.{context} is a Dictionary with context data (context-dict).If{index} is not given, it is assumed to be 0 (i.e.: top).
Parameters:
{context} (table)
{index} (integer?)
Return:
(integer)
ctxsize()ctxsize()
Returns the size of thecontext-stack.
Return:
(any)
cursor({lnum},{col} [,{off}])cursor()
cursor({list})Positions the cursor at the column (byte count){col} in theline{lnum}. The first column is one.
When there is one argument{list} this is used as aListwith two, three or four item:[{lnum},{col}][{lnum},{col},{off}][{lnum},{col},{off},{curswant}]This is like the return value ofgetpos() orgetcurpos(),but without the first item.
To position the cursor using{col} as the character count, usesetcursorcharpos().
Does not change the jumplist.{lnum} is used like withgetline(), except that if{lnum} iszero, the cursor will stay in the current line.If{lnum} is greater than the number of lines in the buffer,the cursor will be positioned at the last line in the buffer.If{col} is greater than the number of bytes in the line,the cursor will be positioned at the last character in theline.If{col} is zero, the cursor will stay in the current column.If{curswant} is given it is used to set the preferred columnfor vertical movement. Otherwise{col} is used.
When'virtualedit' is used{off} specifies the offset inscreen columns from the start of the character. E.g., aposition within a<Tab> or after the last character.Returns 0 when the position could be set, -1 otherwise.
Parameters:
{list} (integer[])
Return:
(any)
debugbreak({pid})debugbreak()
Specifically used to interrupt a program being debugged. Itwill cause process{pid} to get a SIGTRAP. Behavior for otherprocesses is undefined. Seeterminal-debug.(Sends a SIGINT to a process{pid} other than MS-Windows)
ReturnsTRUE if successfully interrupted the program.Otherwise returnsFALSE.
Parameters:
{pid} (integer)
Return:
(any)
deepcopy({expr} [,{noref}])deepcopy()E698Make a copy of{expr}. For Numbers and Strings this isn'tdifferent from using{expr} directly.When{expr} is aList a full copy is created. This meansthat the originalList can be changed without changing thecopy, and vice versa. When an item is aList, a copy for itis made, recursively. Thus changing an item in the copy doesnot change the contents of the originalList.
When{noref} is omitted or zero a containedList orDictionary is only copied once. All references point tothis single copy. With{noref} set to 1 every occurrence of aList orDictionary results in a new copy. This also meansthat a cyclic reference causes deepcopy() to fail.E724
Nesting is possible up to 100 levels. When there is an itemthat refers back to a higher level making a deep copy with{noref} set to 1 will fail.Also seecopy().
Parameters:
{expr} (T)
{noref} (boolean?)
Return:
(T)
delete({fname} [,{flags}])delete()
Without{flags} or with{flags} empty: Deletes the file by thename{fname}.
This also works when{fname} is a symbolic link. The symboliclink itself is deleted, not what it points to.
When{flags} is "d": Deletes the directory by the name{fname}. This fails when directory{fname} is not empty.
When{flags} is "rf": Deletes the directory by the name{fname} and everything in it, recursively. BE CAREFUL!Note: on MS-Windows it is not possible to delete a directorythat is being used.
The result is a Number, which is 0/false if the deleteoperation was successful and -1/true when the deletion failedor partly failed.
Parameters:
{fname} (string)
{flags} (string?)
Return:
(integer)
deletebufline({buf},{first} [,{last}])deletebufline()
Delete lines{first} to{last} (inclusive) from buffer{buf}.If{last} is omitted then delete line{first} only.On success 0 is returned, on failure 1 is returned.
This function works only for loaded buffers. First callbufload() if needed.
For the use of{buf}, seebufname() above.
{first} and{last} are used like withgetline(). Note thatwhen usingline() this refers to the current buffer. Use "$"to refer to the last line in buffer{buf}.
Parameters:
{buf} (integer|string)
{first} (integer|string)
{last} (integer|string?)
Return:
(any)
dictwatcheradd({dict},{pattern},{callback})dictwatcheradd()
Adds a watcher to a dictionary. A dictionary watcher isidentified by three components:
A dictionary({dict});
A key pattern({pattern}).
A function({callback}).
After this is called, every change on{dict} and on keysmatching{pattern} will result in{callback} being invoked.
For example, to watch all global variables:
silent! call dictwatcherdel(g:, '*', 'OnDictChanged')function! OnDictChanged(d,k,z)  echomsg string(a:k) string(a:z)endfunctioncall dictwatcheradd(g:, '*', 'OnDictChanged')
For now{pattern} only accepts very simple patterns that cancontain a "*" at the end of the string, in which case it willmatch every key that begins with the substring before the "*".That means if "*" is not the last character of{pattern}, onlykeys that are exactly equal as{pattern} will be matched.
The{callback} receives three arguments:
The dictionary being watched.
The key which changed.
A dictionary containing the new and old values for the key.
The type of change can be determined by examining the keyspresent on the third argument:
If contains bothold andnew, the key was updated.
If it contains onlynew, the key was added.
If it contains onlyold, the key was deleted.
This function can be used by plugins to implement options withvalidation and parsing logic.
Parameters:
{dict} (table)
{pattern} (string)
{callback} (function)
Return:
(any)
dictwatcherdel({dict},{pattern},{callback})dictwatcherdel()
Removes a watcher added withdictwatcheradd(). All threearguments must match the ones passed todictwatcheradd() inorder for the watcher to be successfully deleted.
Parameters:
{dict} (any)
{pattern} (string)
{callback} (function)
Return:
(any)
did_filetype()did_filetype()
ReturnsTRUE when autocommands are being executed and theFileType event has been triggered at least once. Can be usedto avoid triggering the FileType event again in the scriptsthat detect the file type.FileTypeReturnsFALSE when:setf FALLBACK was used.When editing another file, the counter is reset, thus thisreally checks if the FileType event has been triggered for thecurrent buffer. This allows an autocommand that startsediting another buffer to set'filetype' and load a syntaxfile.
Return:
(integer)
diff_filler({lnum})diff_filler()
Returns the number of filler lines above line{lnum}.These are the lines that were inserted at this point inanother diff'ed window. These filler lines are shown in thedisplay but don't exist in the buffer.{lnum} is used like withgetline(). Thus "." is the currentline, "'m" mark m, etc.Returns 0 if the current window is not in diff mode.
Parameters:
{lnum} (integer|string)
Return:
(integer)
diff_hlID({lnum},{col})diff_hlID()
Returns the highlight ID for diff mode at line{lnum} column{col} (byte index). When the current line does not have adiff change zero is returned.{lnum} is used like withgetline(). Thus "." is the currentline, "'m" mark m, etc.{col} is 1 for the leftmost column,{lnum} is 1 for the firstline.The highlight ID can be used withsynIDattr() to obtainsyntax information about the highlighting.
Parameters:
{lnum} (integer|string)
{col} (integer)
Return:
(any)
digraph_get({chars})digraph_get()E1214Return the digraph of{chars}. This should be a string withexactly two characters. If{chars} are not just twocharacters, or the digraph of{chars} does not exist, an erroris given and an empty string is returned.
Also seedigraph_getlist().
Examples:
" Get a built-in digraphecho digraph_get('00')" Returns '∞'" Get a user-defined digraphcall digraph_set('aa', 'あ')echo digraph_get('aa')" Returns 'あ'
Parameters:
{chars} (string)
Return:
(string)
digraph_getlist([{listall}])digraph_getlist()
Return a list of digraphs. If the{listall} argument is givenand it is TRUE, return all digraphs, including the defaultdigraphs. Otherwise, return only user-defined digraphs.
Also seedigraph_get().
Examples:
" Get user-defined digraphsecho digraph_getlist()" Get all the digraphs, including default digraphsecho digraph_getlist(1)
Parameters:
{listall} (boolean?)
Return:
(string[][])
digraph_set({chars},{digraph})digraph_set()
Add digraph{chars} to the list.{chars} must be a stringwith two characters.{digraph} is a string with one UTF-8encoded character.E1215Be careful, composing characters are NOT ignored. Thisfunction is similar to:digraphs command, but useful to adddigraphs start with a white space.
The function result is v:true ifdigraph is registered. Ifthis fails an error message is given and v:false is returned.
If you want to define multiple digraphs at once, you can usedigraph_setlist().
Example:
call digraph_set('  ', 'あ')
Parameters:
{chars} (string)
{digraph} (string)
Return:
(any)
digraph_setlist({digraphlist})digraph_setlist()
Similar todigraph_set() but this function can add multipledigraphs at once.{digraphlist} is a list composed of lists,where each list contains two strings with{chars} and{digraph} as indigraph_set().E1216Example:
call digraph_setlist([['aa', 'あ'], ['ii', 'い']])
It is similar to the following:
for [chars, digraph] in [['aa', 'あ'], ['ii', 'い']]      call digraph_set(chars, digraph)endfor
Except that the function returns after the first error,following digraphs will not be added.
Parameters:
{digraphlist} (table<integer,string[]>)
Return:
(any)
empty({expr})empty()
Return the Number 1 if{expr} is empty, zero otherwise.
AList orDictionary is empty when it does not have any items.
AString is empty when its length is zero.
ANumber andFloat are empty when their value is zero.
v:false andv:null are empty,v:true is not.
ABlob is empty when its length is zero.
Parameters:
{expr} (any)
Return:
(integer)
environ()environ()
Return all of environment variables as dictionary. You cancheck if an environment variable exists like this:
echo has_key(environ(), 'HOME')
Note that the variable name may be CamelCase; to ignore caseuse this:
echo index(keys(environ()), 'HOME', 0, 1) != -1
Return:
(any)
escape({string},{chars})escape()
Escape the characters in{chars} that occur in{string} with abackslash. Example:
echo escape('c:\program files\vim', ' \')
results in:
c:\\program\ files\\vim
Also seeshellescape() andfnameescape().
Parameters:
{string} (string)
{chars} (string)
Return:
(string)
eval({string})eval()
Evaluate{string} and return the result. Especially useful toturn the result ofstring() back into the original value.This works for Numbers, Floats, Strings, Blobs and compositesof them. Also works forFuncrefs that refer to existingfunctions.
Parameters:
{string} (string)
Return:
(any)
eventhandler()eventhandler()
Returns 1 when inside an event handler. That is that Vim gotinterrupted while waiting for the user to type a character,e.g., when dropping a file on Vim. This means interactivecommands cannot be used. Otherwise zero is returned.
Return:
(any)
executable({expr})executable()
This function checks if an executable with the name{expr}exists.{expr} must be the name of the program without anyarguments.
executable() uses the value of $PATH and/or the normalsearchpath for programs.PATHEXT
On MS-Windows the ".exe", ".bat", etc. can optionally beincluded. 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 dotby itself can be used in $PATHEXT to try using the namewithout 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 adirectory, not if it's really executable.On MS-Windows an executable in the same directory as the Vimexecutable is always found (it's added to $PATH atstartup).NoDefaultCurrentDirectoryInExePath
On MS-Windows an executable in Vim's current working directoryis also normally found, but this can be disabled by settingthe $NoDefaultCurrentDirectoryInExePath environment variable.
The result is a Number:1exists0does not existexepath() can be used to get the full path of an executable.
Parameters:
{expr} (string)
Return:
(0|1)
execute({command} [,{silent}])execute()
Execute{command} and capture its output.If{command} is aString, returns{command} output.If{command} is aList, returns concatenated outputs.Line continuations in{command} are not recognized.Examples:
echo execute('echon "foo"')
foo
echo execute(['echon "foo"', 'echon "bar"'])
foobar
The optional{silent} argument can have these values:""no:silent used"silent":silent used"silent!":silent! usedThe default is "silent". Note that with "silent!", unlike:redir, error messages are dropped.
To get a list of lines usesplit() on the result:
execute('args')->split("\n")
This function is not available in thesandbox.Note: If nested, an outer execute() will not observe output ofthe inner calls.Note: Text attributes (highlights) are not captured.To execute a command in another window than the current oneusewin_execute().
Parameters:
{command} (string|string[])
{silent} (''|'silent'|'silent!'?)
Return:
(string)
exepath({expr})exepath()
Returns the full path of{expr} if it is an executable andgiven as a (partial or full) path or is found in $PATH.Returns empty string otherwise.If{expr} starts with "./" thecurrent-directory is used.
Parameters:
{expr} (string)
Return:
(string)
exists({expr})exists()
The result is a Number, which isTRUE if{expr} isdefined, zero otherwise.
For checking for a supported feature usehas().For checking if a file exists usefilereadable().
The{expr} argument is a string, which contains one of these:varnameinternal variable (seedict.keyinternal-variables). Also workslist[i]forcurly-braces-names,Dictionaryentries,List items, etc.Beware that evaluating an index maycause an error message for an invalidexpression. E.g.:
let l = [1, 2, 3]echo exists("l[5]")
0
echo exists("l[xx]")
E121: Undefined variable: xx 0&option-nameVim option (only checks if it exists,not if it really works)+option-nameVim option that works.$ENVNAMEenvironment variable (could also bedone by comparing with an emptystring)*funcname built-in function (seefunctions)or user defined function (seeuser-function). Also works for avariable that is a Funcref.:cmdnameEx command: built-in command, usercommand or command modifier:command.Returns:1 for match with start of a command2 full match with a command3 matches several user commandsTo check for a supported commandalways check the return value to be 2.:2matchThe:2match command.:3matchThe:3match command (but youprobably should not use it, it isreserved for internal usage)#eventautocommand defined for this event#event#patternautocommand defined for this event andpattern (the pattern is takenliterally and compared to theautocommand patterns character bycharacter)#groupautocommand group exists#group#eventautocommand defined for this group andevent.#group#event#patternautocommand defined for this group,event and pattern.##eventautocommand for this event issupported.
Examples:
echo exists("&mouse")echo exists("$HOSTNAME")echo exists("*strftime")echo exists("*s:MyFunc")echo exists("*MyFunc")echo exists("*v:lua.Func")echo exists("bufcount")echo exists(":Make")echo exists("#CursorHold")echo exists("#BufReadPre#*.gz")echo exists("#filetypeindent")echo exists("#filetypeindent#FileType")echo exists("#filetypeindent#FileType#*")echo exists("##ColorScheme")
There must be no space between the symbol (&/$/*/#) and thename.There must be no extra characters after the name, although ina few cases this is ignored. That may become stricter in thefuture, thus don't count on it!Working example:
echo exists(":make")
NOT working example:
echo exists(":make install")
Note that the argument must be a string, not the name of thevariable itself. For example:
echo exists(bufcount)
This doesn't check for existence of the "bufcount" variable,but gets the value of "bufcount", and checks if that exists.
Parameters:
{expr} (string)
Return:
(0|1)
exp({expr})exp()
Return the exponential of{expr} as aFloat in the range[0, inf].{expr} must evaluate to aFloat or aNumber.Returns 0.0 if{expr} is not aFloat or aNumber.Examples:
echo exp(2)
7.389056
echo exp(-1)
0.367879
Parameters:
{expr} (number)
Return:
(any)
expand({string} [,{nosuf} [,{list}]])expand()
Expand wildcards and the following special keywords in{string}.'wildignorecase' applies.
If{list} is given and it isTRUE, a List will be returned.Otherwise the result is a String and when there are severalmatches, they are separated by<NL> characters.
If the expansion fails, the result is an empty string. A namefor a non-existing file is not included, unless{string} doesnot start with '%', '#' or '<', see below.
When{string} starts with '%', '#' or '<', the expansion isdone like for thecmdline-special variables with theirassociated modifiers. Here is a short overview:
%Current file name#Alternate file name#nAlternate file name n<cfile>File name under the cursor<afile>Autocmd file name<abuf>Autocmd buffer number (as a String!)<amatch>Autocmd matched name<cexpr>C expression under the cursor<sfile>Deprecated, use<script> or<stack><slnum>Sourced script line number or functionline number<sflnum>Script file line number, also when ina function<SID>"<SNR>123_" where "123" is thecurrent script ID<SID><script>Sourced script file, or script filewhere the current function was defined.For Lua seelua-script-location.<stack>Call stack<cword>Word under the cursor<cWORD>WORD under the cursor<client>The{clientid} of the last receivedmessageModifiers::pExpand to full path:hHead (last path component removed):tTail (last path component only):rRoot (one extension removed):eExtension only
More modifiers are supported, for the full list seefilename-modifiers.
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 thereferenced 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 thefollowing modifier. Thefnamemodify() function can be usedto modify normal file names.
When using '%' or '#', and the current or alternate file nameis not defined, an empty string is used. Using "%:p" in abuffer with no name, results in the current directory, with a'/' added.When'verbose' is set then expanding '%', '#' and <> itemswill result in an error message if the argument cannot beexpanded.
When{string} does not start with '%', '#' or '<', it isexpanded like a file name is expanded on the command line.'suffixes' and'wildignore' are used, unless the optional{nosuf} argument is given and it isTRUE.Names for non-existing files are included. The "**" item canbe used to search in a directory tree. For example, to findall "README" files in the current directory and below:
echo expand("**/README")
expand() can also be used to expand variables and environmentvariables that are only known in a shell. But this can beslow, because a shell may be used to do the expansion. Seeexpr-env-expand.The expanded variable is still handled like a list of filenames. When an environment variable cannot be expanded, it isleft unchanged. Thus ":echo expand('$FOOBAR')" results in"$FOOBAR".
Seeglob() for finding existing files. Seesystem() forgetting the raw output of an external command.
Parameters:
{string} (string)
{nosuf} (boolean?)
{list} (nil|false?)
Return:
(string)
expandcmd({string} [,{options}])expandcmd()
Expand special items in String{string} like what is done foran Ex command such as:edit. This expands special keywords,like withexpand(), and environment variables, anywhere in{string}. "~user" and "~/path" are only expanded at thestart.
The following items are supported in the{options} Dictargument: errmsgIf set to TRUE, error messages are displayedif an error is encountered during expansion.By default, error messages are not displayed.
Returns the expanded string. If an error is encounteredduring expansion, the unmodified{string} is returned.
Example:
echo expandcmd('make %<.o')
make /path/runtime/doc/builtin.o
echo expandcmd('make %<.o', {'errmsg': v:true})
Parameters:
{string} (string)
{options} (table?)
Return:
(any)
extend({expr1},{expr2} [,{expr3}])extend()
{expr1} and{expr2} must be bothLists or bothDictionaries.
If they areLists: Append{expr2} to{expr1}.If{expr3} is given insert the items of{expr2} before theitem with index{expr3} in{expr1}. When{expr3} is zeroinsert before the first item. When{expr3} is equal tolen({expr1}) then{expr2} is appended.Examples:
echo sort(extend(mylist, [7, 5]))call extend(mylist, [2, 3], 1)
When{expr1} is the same List as{expr2} then the number ofitems copied is equal to the original length of the List.E.g., when{expr3} is 1 you get N new copies of the first item(where N is the original length of the List).Useadd() to concatenate one item to a list. To concatenatetwo lists into a new list use the + operator:
let newlist = [1, 2, 3] + [4, 5]
If they areDictionaries:Add all entries from{expr2} to{expr1}.If a key exists in both{expr1} and{expr2} then{expr3} isused to decide what to do:{expr3} = "keep": keep the value of{expr1}{expr3} = "force": use the value of{expr2}{expr3} = "error": give an error messageE737
When{expr3} is omitted then "force" is assumed.
{expr1} is changed when{expr2} is not empty. If necessarymake a copy of{expr1} first or useextendnew() to return anew List/Dictionary.{expr2} remains unchanged.When{expr1} is locked and{expr2} is not empty the operationfails.Returns{expr1}. Returns 0 on error.
Parameters:
{expr1} (table)
{expr2} (table)
{expr3} (table?)
Return:
(any)
extendnew({expr1},{expr2} [,{expr3}])extendnew()
Likeextend() but instead of adding items to{expr1} a newList or Dictionary is created and returned.{expr1} remainsunchanged.
Parameters:
{expr1} (table)
{expr2} (table)
{expr3} (table?)
Return:
(any)
feedkeys({string} [,{mode}])feedkeys()
Characters in{string} are queued for processing as if theycome from a mapping or were typed by the user.
By default the string is added to the end of the typeaheadbuffer, thus if a mapping is still being executed thecharacters come after them. Use the 'i' flag to insert beforeother characters, they will be executed next, before anycharacters from a mapping.
The function does not wait for processing of keys contained in{string}.
To include special keys into{string}, use double-quotesand "\..." notationexpr-quote. For example,feedkeys("\<CR>") simulates pressing of the<Enter> key. Butfeedkeys('\<CR>') pushes 5 characters.The<Ignore> keycode may be used to exit thewait-for-character without doing anything.
{mode} is a String, which can contain these character flags:'m'Remap keys. This is default. If{mode} is absent,keys are remapped.'n'Do not remap keys.'t'Handle keys as if typed; otherwise they are handled asif coming from a mapping. This matters for undo,opening folds, etc.'L'Lowlevel input. Other flags are not used.'i'Insert the string instead of appending (see above).'x'Execute commands until typeahead is empty. This issimilar to using ":normal!". You can call feedkeys()several times without 'x' and then one time with 'x'(possibly with an empty{string}) to execute all thetypeahead. Note that when Vim ends in Insert mode itwill behave as if<Esc> is typed, to avoid gettingstuck, waiting for a character to be typed before thescript continues.Note that if you manage to call feedkeys() whileexecuting commands, thus calling it recursively, thenall typeahead will be consumed by the last call.'!'When used with 'x' will not end Insert mode. Can beused in a test when a timer is set to exit Insert modea little later. Useful for testing CursorHoldI.
Return value is always 0.
Parameters:
{string} (string)
{mode} (string?)
Return:
(any)
filecopy({from},{to})filecopy()
Copy the file pointed to by the name{from} to{to}. Theresult is a Number, which isTRUE if the file was copiedsuccessfully, andFALSE when it failed.If a file with name{to} already exists, it will fail.Note that it does not handle directories (yet).
This function is not available in thesandbox.
Parameters:
{from} (string)
{to} (string)
Return:
(0|1)
filereadable({file})filereadable()
The result is a Number, which isTRUE when a file with thename{file} exists, and can be read. If{file} doesn't exist,or is a directory, the result isFALSE.{file} is anyexpression, which is used as a String.If you don't care about the file being readable you can useglob().{file} is used as-is, you may want to expand wildcards first:
echo filereadable('~/.vimrc')
0
echo filereadable(expand('~/.vimrc'))
1
Parameters:
{file} (string)
Return:
(0|1)
filewritable({file})filewritable()
The result is a Number, which is 1 when a file with thename{file} exists, and can be written. If{file} doesn'texist, or is not writable, the result is 0. If{file} is adirectory, and we can write to it, the result is 2.
Parameters:
{file} (string)
Return:
(0|1)
filter({expr1},{expr2})filter()
{expr1} must be aList,String,Blob orDictionary.For each item in{expr1} evaluate{expr2} and when the resultis zero or false remove the item from theList orDictionary. Similarly for each byte in aBlob and eachcharacter in aString.
{expr2} must be astring orFuncref.
If{expr2} is astring, inside{expr2}v:val has the valueof the current item. For aDictionaryv:key has the keyof the current item and for aListv:key has the index ofthe current item. For aBlobv:key has the index of thecurrent byte. For aStringv:key has the index of thecurrent character.Examples:
call filter(mylist, 'v:val !~ "OLD"')
Removes the items where "OLD" appears.
call filter(mydict, 'v:key >= 8')
Removes the items with a key below 8.
call filter(var, 0)
Removes all the items, thus clears theList orDictionary.
Note that{expr2} is the result of expression and is thenused as an expression again. Often it is good to use aliteral-string to avoid having to double backslashes.
If{expr2} is aFuncref it must take two arguments:1. the key or the index of the current item.2. the value of the current item.The function must returnTRUE if the item should be kept.Example that keeps the odd items of a list:
func Odd(idx, val)  return a:idx % 2 == 1endfunccall filter(mylist, function('Odd'))
It is shorter when using alambda:
call filter(myList, {idx, val -> idx * val <= 42})
If you do not use "val" you can leave it out:
call filter(myList, {idx -> idx % 2 == 1})
For aList and aDictionary the operation is donein-place. If you want it to remain unmodified make a copyfirst:
let l = filter(copy(mylist), 'v:val =~ "KEEP"')
Returns{expr1}, theList orDictionary that was filtered,or a newBlob orString.When an error is encountered while evaluating{expr2} nofurther items in{expr1} are processed.When{expr2} is a Funcref errors inside a function are ignored,unless it was defined with the "abort" flag.
Parameters:
{expr1} (string|table)
{expr2} (string|function)
Return:
(any)
finddir({name} [,{path} [,{count}]])finddir()
Find directory{name} in{path}. Supports both downwards andupwards recursive directory searches. Seefile-searchingfor the syntax of{path}.
Returns the path of the first found match. When the founddirectory is below the current directory a relative path isreturned. Otherwise a full path is returned.If{path} is omitted or empty then'path' is used.
If the optional{count} is given, find{count}'s occurrence of{name} in{path} instead of the first one.When{count} is negative return all the matches in aList.
Returns an empty string if the directory is not found.
This is quite similar to the ex-command:find.
Parameters:
{name} (string)
{path} (string?)
{count} (integer?)
Return:
(string|string[])
findfile({name} [,{path} [,{count}]])findfile()
Just likefinddir(), but find a file instead of a directory.Uses'suffixesadd'.Example:
echo findfile("tags.vim", ".;")
Searches from the directory of the current file upwards untilit finds the file "tags.vim".
Parameters:
{name} (string)
{path} (string?)
{count} (integer?)
Return:
(string|string[])
flatten({list} [,{maxdepth}])flatten()
Flatten{list} up to{maxdepth} levels. Without{maxdepth}the result is aList without nesting, as if{maxdepth} isa very large number.The{list} is changed in place, useflattennew() if you donot want that.E900
{maxdepth} means how deep in nested lists changes are made.{list} is not modified when{maxdepth} is 0.{maxdepth} must be positive number.
If there is an error the number zero is returned.
Example:
echo flatten([1, [2, [3, 4]], 5])
[1, 2, 3, 4, 5]
echo flatten([1, [2, [3, 4]], 5], 1)
[1, 2, [3, 4], 5]
Parameters:
{list} (any[])
{maxdepth} (integer?)
Return:
(any[]|0)
flattennew({list} [,{maxdepth}])flattennew()
Likeflatten() but first make a copy of{list}.
Parameters:
{list} (any[])
{maxdepth} (integer?)
Return:
(any[]|0)
float2nr({expr})float2nr()
Convert{expr} to a Number by omitting the part after thedecimal point.{expr} must evaluate to aFloat or aNumber.Returns 0 if{expr} is not aFloat or aNumber.When the value of{expr} is out of range for aNumber theresult is truncated to 0x7fffffff or -0x7fffffff (or when64-bit Number support is enabled, 0x7fffffffffffffff or-0x7fffffffffffffff). NaN results in -0x80000000 (or when64-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
Parameters:
{expr} (number)
Return:
(any)
floor({expr})floor()
Return the largest integral value less than or equal to{expr} as aFloat (round down).{expr} must evaluate to aFloat or aNumber.Returns 0.0 if{expr} is not aFloat or aNumber.Examples:
echo floor(1.856)
1.0
echo floor(-5.456)
-6.0
echo floor(4.0)
4.0
Parameters:
{expr} (number)
Return:
(any)
fmod({expr1},{expr2})fmod()
Return the remainder of{expr1} /{expr2}, even if thedivision is not representable. Returns{expr1} - i *{expr2}for some integer i such that if{expr2} is non-zero, theresult has the same sign as{expr1} and magnitude less thanthe magnitude of{expr2}. If{expr2} is zero, the valuereturned is zero. The value returned is aFloat.{expr1} and{expr2} must evaluate to aFloat or aNumber.Returns 0.0 if{expr1} or{expr2} is not aFloat or aNumber.Examples:
echo fmod(12.33, 1.22)
0.13
echo fmod(-12.33, 1.22)
-0.13
Parameters:
{expr1} (number)
{expr2} (number)
Return:
(any)
fnameescape({string})fnameescape()
Escape{string} for use as file name command argument. Allcharacters 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 backslashappears in a filename, it depends on the value of'isfname'.A leading '+' and '>' is also escaped (special after:editand:write). And a "-" by itself (special after:cd).Returns an empty string on error.Example:
let fname = '+some str%nge|name'exe "edit " .. fnameescape(fname)
results in executing:
edit \+some\ str\%nge\|name
Parameters:
{string} (string)
Return:
(string)
fnamemodify({fname},{mods})fnamemodify()
Modify file name{fname} according to{mods}.{mods} is astring of characters like it is used for file names on thecommand line. Seefilename-modifiers.Example:
echo fnamemodify("main.c", ":p:h")
results in:
/home/user/vim/vim/src
If{mods} is empty or an unsupported modifier is used then{fname} is returned.When{fname} is empty then with{mods} ":h" returns ".", sothat:cd can be used with it. This is different fromexpand('%:h') without a buffer name, which returns an emptystring.Note: Environment variables don't work in{fname}, useexpand() first then.
Parameters:
{fname} (string)
{mods} (string)
Return:
(string)
foldclosed({lnum})foldclosed()
The result is a Number. If the line{lnum} is in a closedfold, 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.{lnum} is used like withgetline(). Thus "." is the currentline, "'m" mark m, etc.
Parameters:
{lnum} (integer|string)
Return:
(integer)
foldclosedend({lnum})foldclosedend()
The result is a Number. If the line{lnum} is in a closedfold, 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.{lnum} is used like withgetline(). Thus "." is the currentline, "'m" mark m, etc.
Parameters:
{lnum} (integer|string)
Return:
(integer)
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 isreturned. If there is no fold at line{lnum}, zero isreturned. It doesn't matter if the folds are open or closed.When used while updating folds (from'foldexpr') -1 isreturned for lines where folds are still to be updated and thefoldlevel is unknown. As a special case the level of theprevious line is usually available.{lnum} is used like withgetline(). Thus "." is the currentline, "'m" mark m, etc.
Parameters:
{lnum} (integer|string)
Return:
(integer)
foldtext()foldtext()
Returns a String, to be displayed for a closed fold. This isthe default function used for the'foldtext' option and shouldonly be called from evaluating'foldtext'. It uses thev:foldstart,v:foldend andv:folddashes variables.The returned string looks like this:
+-- 45 lines: abcdef
The number of leading dashes depends on the foldlevel. The"45" is the number of lines in the fold. "abcdef" is the textin the first non-blank line of the fold. Leading white space,"//" or "/*" and the text from the'foldmarker' and'commentstring' options is removed.When used to draw the actual foldtext, the rest of the linewill be filled with the fold char from the'fillchars'setting.Returns an empty string when there is no fold.
Return:
(string)
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 isreturned.{lnum} is used like withgetline(). Thus "." is the currentline, "'m" mark m, etc.Useful when exporting folded text, e.g., to HTML.
Parameters:
{lnum} (integer|string)
Return:
(string)
foreach({expr1},{expr2})foreach()
{expr1} must be aList,String,Blob orDictionary.For each item in{expr1} execute{expr2}.{expr1} is notmodified; its values may be, as with:lockvar 1.E741Seemap() andfilter() to modify{expr1}.
{expr2} must be astring orFuncref.
If{expr2} is astring, inside{expr2}v:val has the valueof the current item. For aDictionaryv:key has the keyof the current item and for aListv:key has the index ofthe current item. For aBlobv:key has the index of thecurrent byte. For aStringv:key has the index of thecurrent character.Examples:
call foreach(mylist, 'let used[v:val] = v:true')
This records the items that are in the{expr1} list.
Note that{expr2} is the result of expression and is then usedas a command. Often it is good to use aliteral-string toavoid having to double backslashes.
If{expr2} is aFuncref it must take two arguments:1. the key or the index of the current item.2. the value of the current item.With a lambda you don't get an error if it only accepts oneargument.If the function returns a value, it is ignored.
Returns{expr1} in all cases.When an error is encountered while executing{expr2} nofurther items in{expr1} are processed.When{expr2} is a Funcref errors inside a function are ignored,unless it was defined with the "abort" flag.
Parameters:
{expr1} (string|table)
{expr2} (string|function)
Return:
(string|table)
fullcommand({name})fullcommand()
Get the full command name from a short abbreviated commandname; see20.2 for details on command abbreviations.
The string argument{name} may start with a: and caninclude a [range], these are skipped and not returned.Returns an empty string if a command doesn't exist or if it'sambiguous (for user-defined commands).
For examplefullcommand('s'),fullcommand('sub'),fullcommand(':%substitute') all return "substitute".
Parameters:
{name} (string)
Return:
(string)
funcref({name} [,{arglist}] [,{dict}])funcref()
Just likefunction(), but the returned Funcref will lookupthe function by reference, not by name. This matters when thefunction{name} is redefined later.
Unlikefunction(),{name} must be an existing user function.It only works for an autoloaded function if it has alreadybeen loaded (to avoid mistakenly loading the autoload scriptwhen only intending to use the function name, usefunction()instead).{name} cannot be a builtin function.Returns 0 on error.
Parameters:
{name} (string)
{arglist} (any?)
{dict} (any?)
Return:
(any)
function({name} [,{arglist}] [,{dict}])function()partialE700E923Return aFuncref variable that refers to function{name}.{name} can be the name of a user defined function or aninternal function.
{name} can also be a Funcref or a partial. When it is apartial the dict stored in it will be used and the{dict}argument is not allowed. E.g.:
let FuncWithArg = function(dict.Func, [arg])let Broken = function(dict.Func, [arg], dict)
When using the Funcref the function will be found by{name},also when it was redefined later. Usefuncref() to keep thesame function.
When{arglist} or{dict} is present this creates a partial.That means the argument list and/or the dictionary is stored inthe Funcref and will be used when the Funcref is called.
The arguments are passed to the function in front of otherarguments, but after any argument frommethod. Example:
func Callback(arg1, arg2, name)"...endfunclet Partial = function('Callback', ['one', 'two'])"...call Partial('name')
Invokes the function as with:
call Callback('one', 'two', 'name')
With amethod:
func Callback(one, two, three)"...endfunclet Partial = function('Callback', ['two'])"...eval 'one'->Partial('three')
Invokes the function as with:
call Callback('one', 'two', 'three')
The function() call can be nested to add more arguments to theFuncref. The extra arguments are appended to the list ofarguments. Example:
func Callback(arg1, arg2, name)"...endfunclet Func = function('Callback', ['one'])let Func2 = function(Func, ['two'])"...call Func2('name')
Invokes the function as with:
call Callback('one', 'two', 'name')
The Dictionary is only useful when calling a "dict" function.In that case the{dict} is passed in as "self". Example:
function Callback() dict   echo "called for " .. self.nameendfunction"...let context = {"name": "example"}let Func = function('Callback', context)"...call Func()" will echo: called for example
The use of function() is not needed when there are no extraarguments, these two are equivalent, if Callback() is definedas context.Callback():
let Func = function('Callback', context)let Func = context.Callback
The argument list and the Dictionary can be combined:
function Callback(arg1, count) dict"...endfunctionlet context = {"name": "example"}let Func = function('Callback', ['one'], context)"...call Func(500)
Invokes the function as with:
call context.Callback('one', 500)
Returns 0 on error.
Parameters:
{name} (string)
{arglist} (any?)
{dict} (any?)
Return:
(any)
garbagecollect([{atexit}])garbagecollect()
Cleanup unusedLists andDictionaries that have circularreferences.
There is hardly ever a need to invoke this function, as it isautomatically done when Vim runs out of memory or is waitingfor the user to press a key after'updatetime'. Items withoutcircular references are always freed when they become unused.This is useful if you have deleted a very bigList and/orDictionary with circular references in a script that runsfor a long time.
When the optional{atexit} argument is one, garbagecollection will also be done when exiting Vim, if it wasn'tdone before. This is useful when checking for memory leaks.
The garbage collection is not done immediately but only whenit's safe to perform. This is when waiting for the user totype a character.
Parameters:
{atexit} (boolean?)
Return:
(any)
get({list},{idx} [,{default}])get()get()-listGet item{idx} fromList{list}. When this item is notavailable return{default}. Return zero when{default} isomitted.
Parameters:
{list} (any[])
{idx} (integer)
{default} (any?)
Return:
(any)
get({blob},{idx} [,{default}])get()-blob
Get byte{idx} fromBlob{blob}. When this byte is notavailable return{default}. Return -1 when{default} isomitted.
Parameters:
{blob} (string)
{idx} (integer)
{default} (any?)
Return:
(any)
get({dict},{key} [,{default}])get()-dict
Get item with key{key} fromDictionary{dict}. When thisitem is not available return{default}. Return zero when{default} is omitted. Useful example:
let val = get(g:, 'var_name', 'default')
This gets the value of g:var_name if it exists, and uses"default" when it does not exist.
Parameters:
{dict} (table<string,any>)
{key} (string)
{default} (any?)
Return:
(any)
get({func},{what})get()-func
Get item{what} fromFuncref{func}. Possible values for{what} are: "name" The function name "func" The function "dict" The dictionary "args" The list with arguments "arity" A dictionary with information about the number of arguments accepted by the function (minus the{arglist}) with the following fields:required the number of positional argumentsoptional the number of optional arguments, in addition to the required onesvarargsTRUE if the function accepts a variable number of arguments...
Note: There is no error, if the{arglist} ofthe Funcref contains more arguments than theFuncref expects, it's not validated.
Returns zero on error.
Parameters:
{func} (function)
{what} (string)
Return:
(any)
getbufinfo([{buf}])getbufinfo()
getbufinfo([{dict}])Get information about buffers as a List of Dictionaries.
Without an argument information about all the buffers isreturned.
When the argument is aDictionary only the buffers matchingthe specified criteria are returned. The following keys canbe specified in{dict}:buflistedinclude only listed buffers.bufloadedinclude only loaded buffers.bufmodifiedinclude only modified buffers.
Otherwise,{buf} specifies a particular buffer to returninformation for. For the use of{buf}, seebufname()above. If the buffer is found the returned List has one item.Otherwise the result is an empty list.
Each returned List item is a dictionary with the followingentries:bufnrBuffer number.changedTRUE if the buffer is modified.changedtickNumber of changes made to the buffer.commandTRUE if the buffer belongs to thecommand-line windowcmdwin.hiddenTRUE if the buffer is hidden.lastusedTimestamp in seconds, likelocaltime(), when the buffer waslast used.listedTRUE if the buffer is listed.lnumLine number used for the buffer whenopened in the current window.Only valid if the buffer has beendisplayed in the window in the past.If you want the line number of thelast known cursor position in a givenwindow, useline():
echo line('.', {winid})
linecountNumber of lines in the buffer (onlyvalid when loaded)loadedTRUE if the buffer is loaded.nameFull path to the file in the buffer.signsList of signs placed in the buffer.Each list item is a dictionary withthe following fields: id sign identifier lnum line number name sign namevariablesA reference to the dictionary withbuffer-local variables.windowsList ofwindow-IDs that display thisbuffer
Examples:
for buf in getbufinfo()    echo buf.nameendforfor buf in getbufinfo({'buflisted':1})    if buf.changed        " ....    endifendfor
To get buffer-local options use:
getbufvar({bufnr}, '&option_name')
Parameters:
{dict} (vim.fn.getbufinfo.dict?)
Return:
(vim.fn.getbufinfo.ret.item[])
getbufline({buf},{lnum} [,{end}])getbufline()
Return aList with the lines starting from{lnum} to{end}(inclusive) in the buffer{buf}. If{end} is omitted, aList with only the line{lnum} is returned. Seegetbufoneline() for only getting the line.
For the use of{buf}, seebufname() above.
For{lnum} and{end} "$" can be used for the last line of thebuffer. Otherwise a number must be used.
When{lnum} is smaller than 1 or bigger than the number oflines in the buffer, an emptyList is returned.
When{end} is greater than the number of lines in the buffer,it is treated as{end} is set to the number of lines in thebuffer. When{end} is before{lnum} an emptyList isreturned.
This function works only for loaded buffers. For unloaded andnon-existing buffers, an emptyList is returned.
Example:
let lines = getbufline(bufnr("myfile"), 1, "$")
Parameters:
{buf} (integer|string)
{lnum} (integer)
{end} (integer?)
Return:
(string[])
getbufoneline({buf},{lnum})getbufoneline()
Just likegetbufline() but only get one line and return itas a string.
Parameters:
{buf} (integer|string)
{lnum} (integer)
Return:
(string)
getbufvar({buf},{varname} [,{def}])getbufvar()
The result is the value of option or local buffer variable{varname} in buffer{buf}. Note that the name without "b:"must be used.The{varname} argument is a string.When{varname} is empty returns aDictionary with all thebuffer-local variables.When{varname} is equal to "&" returns aDictionary with allthe buffer-local options.Otherwise, when{varname} starts with "&" returns the value ofa buffer-local option.This also works for a global or buffer-local option, but itdoesn't work for a global variable, window-local variable orwindow-local option.For the use of{buf}, seebufname() above.When the buffer or variable doesn't exist{def} or an emptystring is returned, there is no error message.Examples:
let bufmodified = getbufvar(1, "&mod")echo "todo myvar = " .. getbufvar("todo", "myvar")
Parameters:
{buf} (integer|string)
{varname} (string)
{def} (any?)
Return:
(any)
getcellwidths()getcellwidths()
Returns aList of cell widths of character ranges overriddenbysetcellwidths(). The format is equal to the argument ofsetcellwidths(). If no character ranges have their cellwidths overridden, an empty List is returned.
Return:
(any)
getchangelist([{buf}])getchangelist()
Returns thechangelist for the buffer{buf}. For the useof{buf}, seebufname() above. If buffer{buf} doesn'texist, an empty list is returned.
The returned list contains two entries: a list with the changelocations and the current position in the list. Eachentry in the change list is a dictionary with the followingentries:colcolumn numbercoladdcolumn offset for'virtualedit'lnumline numberIf buffer{buf} is the current buffer, then the currentposition refers to the position in the list. For otherbuffers, it is set to the length of the list.
Parameters:
{buf} (integer|string?)
Return:
(table[])
getchar([{expr} [,{opts}]])getchar()
Get a single character from the user or input stream.If{expr} is omitted or is -1, wait until a character isavailable.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 isnot consumed. Return zero if no character available.To always get a string, specify "number" asFALSE in{opts}.
Without{expr} and when{expr} is 0 a whole character orspecial key is returned. If it is a single character, theresult is a Number. Usenr2char() 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 bytesstarting with 0x80 (decimal: 128). This is the same value asthe String "\<Key>", e.g., "\<Left>". The returned value isalso a String when a modifier (shift, control, alt) was usedthat is not included in the character.keytrans() can alsobe used to convert a returned String into a readable form.
When{expr} is 0 and Esc is typed, there will be a short delaywhile Vim waits to see if this is the start of an escapesequence.
When{expr} is 1 only the first byte is returned. For aone-byte character it is the character itself as a number.Use nr2char() to convert it to a String.
Use getcharmod() to obtain any additional modifiers.
The optional argument{opts} is a Dict and supports thefollowing items:
cursorA String specifying cursor behaviorwhen waiting for a character."hide": hide the cursor."keep": keep current cursor unchanged."msg": move cursor to message area.(default: automagically decidebetween "keep" and "msg")
numberIfTRUE, return a Number when gettinga single character.IfFALSE, the return value is alwaysconverted to a String, and an emptyString (instead of 0) is returned whenno character is available.(default:TRUE)
simplifyIfTRUE, include modifiers in thecharacter if possible. E.g., returnthe same value forCTRL-I and<Tab>.IfFALSE, don't include modifiers inthe character.(default:TRUE)
When the user clicks a mouse button, the mouse event will bereturned. The position can then be found inv:mouse_col,v:mouse_lnum,v:mouse_winid andv:mouse_win.getmousepos() can also be used. Mouse move events will beignored.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
There is no prompt, you will somehow have to make clear to theuser that a character has to be typed. The screen is notredrawn, e.g. when resizing the window.
There is no mapping for the character.Key codes are replaced, thus when the user presses the<Del>key you get the code for the<Del> key, not the raw charactersequence. Examples:
getchar() == "\<Del>"getchar() == "\<S-Left>"
This example redefines "f" to ignore case:
nmap f :call FindChar()<CR>function FindChar()  let c = nr2char(getchar())  while col('.') < col('$') - 1    normal l    if getline('.')[col('.') - 1] ==? c      break    endif  endwhileendfunction
Parameters:
{expr} (-1|0|1?)
{opts} (table?)
Return:
(integer|string)
getcharmod()getcharmod()
The result is a Number which is the state of the modifiers forthe last obtained character with getchar() or in another way.These values are added together:2shift4control8alt (meta)16meta (when it's different from ALT)32mouse double click64mouse triple click96mouse quadruple click (== 32 + 64)128command (Mac) or superOnly the modifiers that have not been included in thecharacter itself are obtained. Thus Shift-a results in "A"without a modifier. Returns 0 if no modifiers are used.
Return:
(integer)
getcharpos({expr})getcharpos()
Get the position for String{expr}. Same asgetpos() but thecolumn number in the returned List is a character indexinstead of a byte index.Ifgetpos() returns a very large column number, equal tov:maxcol, then getcharpos() will return the character indexof the last character.
Example:With the cursor on '세' in line 5 with text "여보세요":
getcharpos('.')returns [0, 5, 3, 0]getpos('.')returns [0, 5, 7, 0]
Parameters:
{expr} (string)
Return:
(integer[])
getcharsearch()getcharsearch()
Return the current character search information as a{dict}with the following entries:
charcharacter previously used for a charactersearch (t,f,T, orF); empty stringif no character search has been performed forwarddirection of character search; 1 for forward,0 for backward untiltype of character search; 1 for at orTcharacter search, 0 for anf orFcharacter search
This can be useful to always have; and, searchforward/backward regardless of the direction of the previouscharacter search:
nnoremap <expr> ; getcharsearch().forward ? ';' : ','nnoremap <expr> , getcharsearch().forward ? ',' : ';'
Also seesetcharsearch().
Return:
(table)
getcharstr([{expr} [,{opts}]])getcharstr()
The same asgetchar(), except that this always returns aString, and "number" isn't allowed in{opts}.
Parameters:
{expr} (-1|0|1?)
{opts} (table?)
Return:
(string)
getcmdcomplpat()getcmdcomplpat()
Return completion pattern of the current command-line.Only works when the command line is being edited, thusrequires use ofc_CTRL-\_e orc_CTRL-R_=.Also seegetcmdtype(),setcmdpos(),getcmdline(),getcmdprompt(),getcmdcompltype() andsetcmdline().Returns an empty string when completion is not defined.
Return:
(string)
getcmdcompltype()getcmdcompltype()
Return the type of the current command-line completion.Only works when the command line is being edited, thusrequires use ofc_CTRL-\_e orc_CTRL-R_=.See:command-completion for the return string.Also seegetcmdtype(),setcmdpos(),getcmdline(),getcmdprompt(),getcmdcomplpat() andsetcmdline().Returns an empty string when completion is not defined.
To get the type of the command-line completion for a specifiedstring, usegetcompletiontype().
Return:
(string)
getcmdline()getcmdline()
Return the current command-line input. Only works when thecommand line is being edited, thus requires use ofc_CTRL-\_e orc_CTRL-R_=.Example:
cmap <F7> <C-\>eescape(getcmdline(), ' \')<CR>
Also seegetcmdtype(),getcmdpos(),setcmdpos(),getcmdprompt() andsetcmdline().Returns an empty string when entering a password or usinginputsecret().
Return:
(string)
getcmdpos()getcmdpos()
Return the position of the cursor in the command line as abyte count. The first column is 1.Only works when editing the command line, thus requires use ofc_CTRL-\_e orc_CTRL-R_= or an expression mapping.Returns 0 otherwise.Also seegetcmdtype(),setcmdpos(),getcmdline(),getcmdprompt() andsetcmdline().
Return:
(integer)
getcmdprompt()getcmdprompt()
Return the current command-line prompt when using functionslikeinput() orconfirm().Only works when the command line is being edited, thusrequires use ofc_CTRL-\_e orc_CTRL-R_=.Also seegetcmdtype(),getcmdline(),getcmdpos(),setcmdpos() andsetcmdline().
Return:
(string)
getcmdscreenpos()getcmdscreenpos()
Return the screen position of the cursor in the command lineas a byte count. The first column is 1.Instead ofgetcmdpos(), it adds the prompt position.Only works when editing the command line, thus requires use ofc_CTRL-\_e orc_CTRL-R_= or an expression mapping.Returns 0 otherwise.Also seegetcmdpos(),setcmdpos(),getcmdline() andsetcmdline().
Return:
(integer)
getcmdtype()getcmdtype()
Return the current command-line type. Possible return valuesare: :normal Ex command >debug mode commanddebug-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 ofc_CTRL-\_e orc_CTRL-R_= or an expression mapping.Returns an empty string otherwise.Also seegetcmdpos(),setcmdpos() andgetcmdline().
Return:
(':'|'>'|'/'|'?'|'@'|'-'|'='|'')
getcmdwintype()getcmdwintype()
Return the currentcommand-line-window type. Possible returnvalues are the same asgetcmdtype(). Returns an empty stringwhen not in the command-line window.
Return:
(':'|'>'|'/'|'?'|'@'|'-'|'='|'')
getcompletion({pat},{type} [,{filtered}])getcompletion()
Return a list of command-line completion matches. The String{type} argument specifies what for. The following completiontypes are supported:
arglistfile names in argument listaugroupautocmd groupsbufferbuffer namesbreakpoint:breakadd and:breakdel suboptionscmdlinecmdline-completion resultcolorcolor schemescommandEx commandcompilercompilerscustom,{func}custom completion, defined via{func}customlist,{func} custom completion, defined via{func}diff_buffer:diffget and:diffput completiondirdirectory namesdir_in_pathdirectory names in'cdpath'environmentenvironment variable nameseventautocommand eventsexpressionVim expressionfilefile and directory namesfile_in_pathfile and directory names in'path'filetypefiletype names'filetype'filetypecmd:filetype suboptionsfunctionfunction namehelphelp subjectshighlighthighlight groupshistory:history suboptionskeymapkeyboard mappingslocalelocale names (as output of locale -a)mapclearbuffer argumentmappingmapping namemenumenusmessages:messages suboptionsoptionoptionspackaddoptional packagepack-add namesretab:retab suboptionsruntime:runtime completionscriptnamessourced script names:scriptnamesshellcmdShell commandshellcmdlineShell command line with filename argumentssign:sign suboptionssyntaxsyntax file names'syntax'syntime:syntime suboptionstagtagstag_listfilestags, file namesuseruser namesvaruser variables
If{pat} is an empty string, then all the matches arereturned. Otherwise only items matching{pat} are returned.Seewildcards for the use of special characters in{pat}.
If the optional{filtered} flag is set to 1, then'wildignore'is applied to filter the results. Otherwise all the matchesare returned. The'wildignorecase' option always applies.
If the'wildoptions' option contains "fuzzy", then fuzzymatching is used to get the completion matches. Otherwiseregular expression matching is used. Thus this functionfollows the user preference, what happens on the command line.If you do not want this you can make'wildoptions' emptybefore calling getcompletion() and restore it afterwards.
If{type} is "cmdline", then thecmdline-completion result isreturned. For example, to complete the possible values aftera ":call" command:
echo getcompletion('call ', 'cmdline')
If there are no matches, an empty list is returned. Aninvalid value for{type} produces an error.
Parameters:
{pat} (string)
{type} (string)
{filtered} (boolean?)
Return:
(string[])
getcompletiontype({pat})getcompletiontype()
Return the type of the command-line completion using{pat}.When no corresponding completion type is found, an emptystring is returned.To get the current command-line completion type, usegetcmdcompltype().
Parameters:
{pat} (string)
Return:
(string)
getcurpos([{winid}])getcurpos()
Get the position of the cursor. This is like getpos('.'), butincludes an extra "curswant" item in the list:
[0, lnum, col, off, curswant]
The "curswant" number is the preferred column when moving thecursor vertically. After$ command it will be a very largenumber equal tov:maxcol. Also seegetcursorcharpos() andgetpos().The first "bufnum" item is always zero. The byte position ofthe cursor is returned in "col". To get the characterposition, usegetcursorcharpos().
The optional{winid} argument can specify the window. It canbe the window number or thewindow-ID. The last knowncursor position is returned, this may be invalid for thecurrent value of the buffer if it is not the current window.If{winid} is invalid a list with zeroes is returned.
This can be used to save and restore the cursor position:
let save_cursor = getcurpos()MoveTheCursorAroundcall setpos('.', save_cursor)
Note that this only works within the window. Seewinrestview() for restoring more state.
Parameters:
{winid} (integer?)
Return:
([integer, integer, integer, integer, integer])
getcursorcharpos([{winid}])getcursorcharpos()
Same asgetcurpos() but the column number in the returnedList is a character index instead of a byte index.
Example:With the cursor on '보' in line 3 with text "여보세요":
getcursorcharpos()" returns [0, 3, 2, 0, 3]getcurpos()" returns [0, 3, 4, 0, 3]
Parameters:
{winid} (integer?)
Return:
(any)
getcwd([{winnr} [,{tabnr}]])getcwd()
With no arguments, returns the name of the effectivecurrent-directory. With{winnr} or{tabnr} the workingdirectory of that scope is returned, and'autochdir' isignored.Tabs and windows are identified by their respective numbers,0 means current tab or window. Missing tab number implies 0.Thus the following are equivalent:
getcwd(0)getcwd(0, 0)
If{winnr} is -1 it is ignored, only the tab is resolved.{winnr} can be the window number or thewindow-ID.If both{winnr} and{tabnr} are -1 the global workingdirectory is returned.Throw error if the arguments are invalid.E5000E5001E5002
Parameters:
{winnr} (integer?)
{tabnr} (integer?)
Return:
(string)
getenv({name})getenv()
Return the value of environment variable{name}. The{name}argument is a string, without a leading '$'. Example:
myHome = getenv('HOME')
When the variable does not existv:null is returned. Thatis different from a variable set to an empty string.See alsoexpr-env.
Parameters:
{name} (string)
Return:
(string)
getfontname([{name}])getfontname()
Without an argument returns the name of the normal font beingused. Like what is used for the Normal highlight grouphl-Normal.With an argument a check is done whether String{name} is avalid font name. If not then an empty string is returned.Otherwise the actual font name is returned, or{name} if theGUI does not support obtaining the real name.Only works when the GUI is running, thus not in your vimrc orgvimrc file. Use theGUIEnter autocommand to use thisfunction just after the GUI has started.
Parameters:
{name} (string?)
Return:
(string)
getfperm({fname})getfperm()
The result is a String, which is the read, write, and executepermissions of the given file{fname}.If{fname} does not exist or its directory cannot be read, anempty string is returned.The result is of the form "rwxrwxrwx", where each group of"rwx" flags represent, in turn, the permissions of the ownerof the file, the group the file belongs to, and other users.If a user does not have a given permission the flag for thisis replaced with the string "-". Examples:
echo getfperm("/etc/passwd")echo getfperm(expand("~/.config/nvim/init.vim"))
This will hopefully (from a security point of view) displaythe string "rw-r--r--" or even "rw-------".
For setting permissions usesetfperm().
Parameters:
{fname} (string)
Return:
(string)
getfsize({fname})getfsize()
The result is a Number, which is the size in bytes of thegiven 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 -2is returned.
Parameters:
{fname} (string)
Return:
(integer)
getftime({fname})getftime()
The result is a Number, which is the last modification time ofthe given file{fname}. The value is measured as secondssince 1st Jan 1970, and may be passed to strftime(). See alsolocaltime() andstrftime().If the file{fname} can't be found -1 is returned.
Parameters:
{fname} (string)
Return:
(integer)
getftype({fname})getftype()
The result is a String, which is a description of the kind offile 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 theirresults: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 onsystems that support it. On some systems only "dir" and"file" are returned.
Parameters:
{fname} (string)
Return:
('file'|'dir'|'link'|'bdev'|'cdev'|'socket'|'fifo'|'other')
getjumplist([{winnr} [,{tabnr}]])getjumplist()
Returns thejumplist for the specified window.
Without arguments use the current window.With{winnr} only use this window in the current tab page.{winnr} can also be awindow-ID.With{winnr} and{tabnr} use the window in the specified tabpage. If{winnr} or{tabnr} is invalid, an empty list isreturned.
The returned list contains two entries: a list with the jumplocations and the last used jump position number in the list.Each entry in the jump location list is a dictionary withthe following entries:bufnrbuffer numbercolcolumn numbercoladdcolumn offset for'virtualedit'filenamefilename if availablelnumline number
Parameters:
{winnr} (integer?)
{tabnr} (integer?)
Return:
(vim.fn.getjumplist.ret)
getline({lnum} [,{end}])getline()
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 adigit,line() is called to translate the String into a Number.To get the line under the cursor:
getline(".")
When{lnum} is a number smaller than 1 or bigger than thenumber of lines in the buffer, an empty string is returned.
When{end} is given the result is aList where each item isa line from the current buffer in the range{lnum} to{end},including line{end}.{end} is used in the same way as{lnum}.Non-existing lines are silently omitted.When{end} is before{lnum} an emptyList is returned.Example:
let start = line('.')let end = search("^$") - 1let lines = getline(start, end)
To get lines from another buffer seegetbufline() andgetbufoneline()
Parameters:
{lnum} (integer|string)
{end} (nil|false?)
Return:
(string)
getloclist({nr} [,{what}])getloclist()
Returns aList with all the entries in the location list forwindow{nr}.{nr} can be the window number or thewindow-ID.When{nr} is zero the current window is used.
For a location list window, the displayed location list isreturned. For an invalid window number{nr}, an empty list isreturned. Otherwise, same asgetqflist().
If the optional{what} dictionary argument is supplied, thenreturns the items listed in{what} as a dictionary. Refer togetqflist() for the supported items in{what}.
In addition to the items supported bygetqflist() in{what},the following item is supported bygetloclist():
filewinidid of the window used to display filesfrom the location list. This field isapplicable only when called from alocation list window. Seelocation-list-file-window for moredetails.
Returns aDictionary with default values if there is nolocation list for the window{nr}.Returns an empty Dictionary if window{nr} does not exist.
Examples (See alsogetqflist-examples):
echo getloclist(3, {'all': 0})echo getloclist(5, {'filewinid': 0})
Parameters:
{nr} (integer)
{what} (table?)
Return:
(any)
getmarklist([{buf}])getmarklist()
Without the{buf} argument returns aList with informationabout all the global marks.mark
If the optional{buf} argument is specified, returns thelocal marks defined in buffer{buf}. For the use of{buf},seebufname(). If{buf} is invalid, an empty list isreturned.
Each item in the returned List is aDict with the following: mark name of the mark prefixed by "'" pos aList with the position of the mark:[bufnum, lnum, col, off] Refer togetpos() for more information. file file name
Refer togetpos() for getting information about a specificmark.
Parameters:
{buf} (integer??)
Return:
(vim.fn.getmarklist.ret.item[])
getmatches([{win}])getmatches()
Returns aList with all matches previously defined for thecurrent window bymatchadd() and the:match commands.getmatches() is useful in combination withsetmatches(),assetmatches() can restore a list of matches saved bygetmatches().If{win} is specified, use the window with this number orwindow ID instead of the current window. If{win} is invalid,an empty list is returned.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
Parameters:
{win} (integer?)
Return:
(vim.fn.getmatches.ret.item[])
getmousepos()getmousepos()
Returns aDictionary with the last known position of themouse. This can be used in a mapping for a mouse click. Theitems are:screenrowscreen rowscreencolscreen columnwinidWindow ID of the clickwinrowrow inside "winid"wincolcolumn inside "winid"linetext line inside "winid"columntext column inside "winid"coladdoffset (in screen columns) from thestart of the clicked charAll 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 verticalseparator right of a window, the "line" and "column" valuesare zero.
When the position is after the text then "column" is thelength of the text in bytes plus one.
If the mouse is over a focusable floating window then thatwindow is used.
When usinggetchar() the Vim variablesv:mouse_lnum,v:mouse_col andv:mouse_winid also provide these values.
Return:
(vim.fn.getmousepos.ret)
getpid()getpid()
Return a Number which is the process ID of the Vim process.This is a unique number, until Vim exits.
Return:
(integer)
getpos({expr})getpos()
Get the position for String{expr}.The accepted values for{expr} are: . The cursor position. $ The last line in the current buffer. 'x Position of mark x (if the mark is not set, 0 is returned for all values). w0 First line visible in current window (one if the display isn't updated, e.g. in silent Ex mode). w$ Last line visible in current window (this is one less than "w0" if no lines are visible). v When not in Visual mode, returns the cursor position. In Visual mode, returns the other end of the Visual area. A good way to think about this is that in Visual mode "v" and "." complement each other. While "." refers to the cursor position, "v" refers to wherev_o would move the cursor. As a result, you can use "v" and "." together to work on all of a selection in characterwise Visual mode. If the cursor is at the end of a characterwise Visual area, "v" refers to the start of the same Visual area. And if the cursor is at the start of a characterwise Visual area, "v" refers to the end of the same Visual area. "v" differs from'< and'> in that it's updated right away.Note that a mark in another file can be used. The line numberthen applies to another buffer.
The result is aList with four numbers: [bufnum, lnum, col, off]"bufnum" is zero, unless a mark like '0 or 'A is used, then itis the buffer number of the mark."lnum" and "col" are the position in the buffer. The firstcolumn is 1.The "off" number is zero, unless'virtualedit' is used. Thenit is the offset in screen columns from the start of thecharacter. E.g., a position within a<Tab> or after the lastcharacter.
For getting the cursor position seegetcurpos().The column number in the returned List is the byte positionwithin the line. To get the character position in the line,usegetcharpos().
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 equal tov:maxcol.A very large column number equal tov:maxcol can be returned,in which case it means "after the end of the line".If{expr} is invalid, returns a list with all zeros.
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 seegetcharpos(),getcurpos() andsetpos().
Parameters:
{expr} (string)
Return:
([integer, integer, integer, integer])
getqflist([{what}])getqflist()
Returns aList with all the current quickfix errors. Eachlist item is a dictionary with these entries:bufnrnumber of buffer that has the file name, usebufname() to get the namemodulemodule namelnumline number in the buffer (first line is 1)end_lnumend of line number if the item is multilinecolcolumn number (first column is 1)end_colend of column number if the item has rangevcolTRUE: "col" is visual columnFALSE: "col" is byte indexnrerror numberpatternsearch pattern used to locate the errortextdescription of the errortypetype of the error, 'E', '1', etc.validTRUE: recognized error messageuser_datacustom data associated with the item, can beany type.
When there is no error list or it's empty, an empty list isreturned. Quickfix list entries with a non-existing buffernumber are returned with "bufnr" set to zero (Note: somefunctions accept buffer number zero for the alternate buffer,you may need to explicitly check for zero).
Useful application: Find pattern matches in multiple files anddo something with them:
vimgrep /theword/jg *.cfor d in getqflist()   echo bufname(d.bufnr) ':' d.lnum '=' d.textendfor
If the optional{what} dictionary argument is supplied, thenreturns only the items listed in{what} as a dictionary. Thefollowing string items are supported in{what}:changedtickget the total number of changes madeto the listquickfix-changedtickcontextget thequickfix-contextefmerrorformat to use when parsing "lines". Ifnot present, then the'errorformat' optionvalue is used.idget information for the quickfix list withquickfix-ID; zero means the id for thecurrent list or the list specified by "nr"idxget information for the quickfix entry at thisindex in the list specified by "id" or "nr".If set to zero, then uses the current entry.Seequickfix-indexitemsquickfix list entrieslinesparse a list of lines using'efm' and returnthe resulting entries. Only aList type isaccepted. The current quickfix list is notmodified. Seequickfix-parse.nrget information for this quickfix list; zeromeans the current quickfix list and "$" meansthe last quickfix listqfbufnr number of the buffer displayed in the quickfixwindow. Returns 0 if the quickfix buffer isnot present. Seequickfix-buffer.sizenumber of entries in the quickfix listtitleget the list titlequickfix-titlewinidget the quickfixwindow-IDallall of the above quickfix propertiesNon-string items in{what} are ignored. To get the value of aparticular item, set it to zero.If "nr" is not present then the current quickfix list is used.If both "nr" and a non-zero "id" are specified, then the listspecified by "id" is used.To get the number of lists in the quickfix stack, set "nr" to"$" in{what}. The "nr" value in the returned dictionarycontains the quickfix stack size.When "lines" is specified, all the other items except "efm"are ignored. The returned dictionary contains the entry"items" with the list of entries.
The returned dictionary contains the following entries:changedticktotal number of changes made to thelistquickfix-changedtickcontextquickfix list context. Seequickfix-contextIf not present, set to "".idquickfix list IDquickfix-ID. If notpresent, set to 0.idxindex of the quickfix entry in the list. If notpresent, set to 0.itemsquickfix list entries. If not present, set toan empty list.nrquickfix list number. If not present, set to 0qfbufnrnumber of the buffer displayed in the quickfixwindow. If not present, set to 0.sizenumber of entries in the quickfix list. If notpresent, set to 0.titlequickfix list title text. If not present, setto "".winidquickfixwindow-ID. If not present, set to 0
Examples (See alsogetqflist-examples):
echo getqflist({'all': 1})echo getqflist({'nr': 2, 'title': 1})echo getqflist({'lines' : ["F1:10:L10"]})
Parameters:
{what} (table?)
Return:
(any)
getreg([{regname} [, 1 [,{list}]]])getreg()
The result is a String, which is the contents of register{regname}. Example:
let cliptext = getreg('*')
When register{regname} was not set the result is an emptystring.The{regname} argument must be a string.
getreg('=') returns the last evaluated value of the expressionregister. (For use in maps.)getreg('=', 1) returns the expression itself, so that it canbe restored withsetreg(). For other registers the extraargument is ignored, thus you can always give it.
If{list} is present andTRUE, the result type is changedtoList. Each list item is one text line. Use it if you careabout zero bytes possibly present inside register: withoutthird argument both NLs and zero bytes are represented as NLs(seeNL-used-for-Nul).When the register was not set an empty list is returned.
If{regname} is not specified,v:register is used.
Parameters:
{regname} (string?)
{expr} (any?)
{list} (nil|false?)
Return:
(string)
getreginfo([{regname}])getreginfo()
Returns detailed information about register{regname} as aDictionary with the following entries:regcontentsList of lines contained in register{regname}, likegetreg({regname}, 1, 1).regtypethe type of register{regname}, as ingetregtype().isunnamedBoolean flag, v:true if this registeris currently pointed to by the unnamedregister.points_tofor the unnamed register, gives thesingle letter name of the registercurrently pointed to (seequotequote).For example, after deleting a linewithdd, this field will be "1",which is the register that got thedeleted text.
The{regname} argument is a string. If{regname} is invalidor not set, an empty Dictionary will be returned.If{regname} is not specified,v:register is used.The returned Dictionary can be passed tosetreg().
Parameters:
{regname} (string?)
Return:
(table)
getregion({pos1},{pos2} [,{opts}])getregion()
Returns the list of strings from{pos1} to{pos2} from abuffer.
{pos1} and{pos2} must both beLists with four numbers.Seegetpos() for the format of the list. It's possibleto specify positions from a different buffer, but pleasenote the limitations atgetregion-notes.
The optional argument{opts} is a Dict and supports thefollowing items:
typeSpecify the region's selection type.Seegetregtype() for possible values,except that the width can be omittedand an empty string cannot be used.(default: "v")
exclusiveIfTRUE, use exclusive selectionfor the end position.(default: follow'selection')
You can get the last selection type byvisualmode().If Visual mode is active, usemode() to get the Visual mode(e.g., in a:vmap).This function is useful to get text starting and ending indifferent columns, such as acharwise-visual selection.
getregion-notes
Note that:
Order of{pos1} and{pos2} doesn't matter, it will always return content from the upper left position to the lower right position.
If'virtualedit' is enabled and the region is past the end of the lines, resulting lines are padded with spaces.
If the region is blockwise and it starts or ends in the middle of a multi-cell character, it is not included but its selected part is substituted with spaces.
If{pos1} and{pos2} are not in the same buffer, an empty list is returned.
{pos1} and{pos2} must belong to abufloaded() buffer.
It is evaluated in current window context, which makes a difference if the buffer is displayed in a window with different'virtualedit' or'list' values.
When specifying an exclusive selection and{pos1} and{pos2} are equal, the returned list contains a single character as if selection is inclusive, to match the behavior of an empty exclusive selection in Visual mode.
Examples:
xnoremap <CR>\ <Cmd>echom getregion(\ getpos('v'), getpos('.'), #{ type: mode() })<CR>
Parameters:
{pos1} ([integer, integer, integer, integer])
{pos2} ([integer, integer, integer, integer])
{opts} ({type?:string, exclusive?:boolean}?)
Return:
(string[])
getregionpos({pos1},{pos2} [,{opts}])getregionpos()
Same asgetregion(), but returns a list of positionsdescribing the buffer text segments bound by{pos1} and{pos2}.The segments are a pair of positions for every line:
[[{start_pos}, {end_pos}], ...]
The position is aList with four numbers: [bufnum, lnum, col, off]"bufnum" is the buffer number."lnum" and "col" are the position in the buffer. The firstcolumn is 1.If the "off" number of a starting position is non-zero, it isthe offset in screen columns from the start of the character.E.g., a position within a<Tab> or after the last character.If the "off" number of an ending position is non-zero, it isthe offset of the character's first cell not included in theselection, otherwise all its cells are included.
Apart from the options supported bygetregion(),{opts} alsosupports the following:
eolIfTRUE, indicate positions beyondthe end of a line with "col" valuesone more than the length of the line.IfFALSE, positions are limitedwithin their lines, and if a line isempty or the selection is entirelybeyond the end of a line, a "col"value of 0 is used for both positions.(default:FALSE)
Parameters:
{pos1} ([integer, integer, integer, integer])
{pos2} ([integer, integer, integer, integer])
{opts} ({type?:string, exclusive?:boolean, eol?:boolean}?)
Return:
([ [integer, integer, integer, integer], [integer, integer, integer, integer] ][])
getregtype([{regname}])getregtype()
The result is a String, which is type of register{regname}.The value will be one of: "v"forcharwise text "V"forlinewise text "<CTRL-V>{width}"forblockwise-visual text ""for an empty or unknown register<CTRL-V> is one character with value 0x16.The{regname} argument is a string. If{regname} is notspecified,v:register is used.
Parameters:
{regname} (string?)
Return:
(string)
getscriptinfo([{opts}])getscriptinfo()
Returns aList with information about all the sourced Vimscripts in the order they were sourced, like what:scriptnames shows.
The optional Dict argument{opts} supports the followingoptional items: nameScript name match pattern. If specified,and "sid" is not specified, information aboutscripts with a name that match the pattern"name" are returned. sidScript ID<SID>. If specified, onlyinformation about the script with ID "sid" isreturned and "name" is ignored.
Each item in the returned List is aDict with the followingitems: autoloadAlways set to FALSE. functions List of script-local function names defined inthe script. Present only when a particularscript is specified using the "sid" item in{opts}. nameVim script file name. sidScript ID<SID>. variables A dictionary with the script-local variables.Present only when a particular script isspecified using the "sid" item in{opts}.Note that this is a copy, the value ofscript-local variables cannot be changed usingthis dictionary. versionVim script version, always 1
Examples:
echo getscriptinfo({'name': 'myscript'})echo getscriptinfo({'sid': 15})[0].variables
Parameters:
{opts} (table?)
Return:
(vim.fn.getscriptinfo.ret[])
getstacktrace()getstacktrace()
Returns the current stack trace of Vim scripts.Stack trace is aList, of which each item is aDictionarywith the following items: funcrefThe funcref if the stack is at a function,otherwise this item is omitted. eventThe string of the event description if thestack is at an autocmd event, otherwise thisitem is omitted. lnumThe line number in the script on the stack. filepathThe file path of the script on the stack.
Return:
(table[])
gettabinfo([{tabnr}])gettabinfo()
If{tabnr} is not specified, then information about all thetab pages is returned as aList. Each List item is aDictionary. Otherwise,{tabnr} specifies the tab pagenumber and information about that one is returned. If the tabpage does not exist an empty List is returned.
Each List item is aDictionary with the following entries:tabnrtab page number.variablesa reference to the dictionary withtabpage-local variableswindowsList ofwindow-IDs in the tab page.
Parameters:
{tabnr} (integer?)
Return:
(any)
gettabvar({tabnr},{varname} [,{def}])gettabvar()
Get the value of a tab-local variable{varname} in tab page{tabnr}.t:varTabs are numbered starting with one.The{varname} argument is a string. When{varname} is empty adictionary with all tab-local variables is returned.Note that the name without "t:" must be used.When the tab or variable doesn't exist{def} or an emptystring is returned, there is no error message.
Parameters:
{tabnr} (integer)
{varname} (string)
{def} (any?)
Return:
(any)
gettabwinvar({tabnr},{winnr},{varname} [,{def}])gettabwinvar()
Get the value of window-local variable{varname} in window{winnr} in tab page{tabnr}.The{varname} argument is a string. When{varname} is empty adictionary with all window-local variables is returned.When{varname} is equal to "&" get the values of allwindow-local options in aDictionary.Otherwise, when{varname} starts with "&" get the value of awindow-local option.Note that{varname} must be the name without "w:".Tabs are numbered starting with one. For the current tabpageusegetwinvar().{winnr} can be the window number or thewindow-ID.When{winnr} is zero the current window is used.This also works for a global option, buffer-local option andwindow-local option, but it doesn't work for a global variableor buffer-local variable.When the tab, window or variable doesn't exist{def} or anempty string is returned, there is no error message.Examples:
let list_is_on = gettabwinvar(1, 2, '&list')echo "myvar = " .. gettabwinvar(3, 1, 'myvar')
To obtain all window-local variables use:
gettabwinvar({tabnr}, {winnr}, '&')
Parameters:
{tabnr} (integer)
{winnr} (integer)
{varname} (string)
{def} (any?)
Return:
(any)
gettagstack([{winnr}])gettagstack()
The result is a Dict, which is the tag stack of window{winnr}.{winnr} can be the window number or thewindow-ID.When{winnr} is not specified, the current window is used.When window{winnr} doesn't exist, an empty Dict is returned.
The returned dictionary contains the following entries:curidxCurrent index in the stack. When attop of the stack, set to (length + 1).Index of bottom of the stack is 1.itemsList of items in the stack. Each itemis a dictionary containing theentries described below.lengthNumber of entries in the stack.
Each item in the stack is a dictionary with the followingentries:bufnrbuffer number of the current jumpfromcursor position before the tag jump.Seegetpos() for the format of thereturned list.matchnrcurrent matching tag number. Used whenmultiple matching tags are found for aname.tagnamename of the tag
Seetagstack for more information about the tag stack.
Parameters:
{winnr} (integer?)
Return:
(any)
gettext({text})gettext()
Translate String{text} if possible.This is mainly for use in the distributed Vim scripts. Whengenerating message translations the{text} is extracted byxgettext, the translator can add the translated message in the.po file and Vim will lookup the translation when gettext() iscalled.For{text} double quoted strings are preferred, becausexgettext does not understand escaping in single quotedstrings.
Parameters:
{text} (string)
Return:
(string)
getwininfo([{winid}])getwininfo()
Returns information about windows as aList with Dictionaries.
If{winid} is given Information about the window with that IDis returned, as aList with one item. If the window does notexist the result is an empty list.
Without{winid} information about all the windows in all thetab pages is returned.
Each List item is aDictionary with the following entries:botlinelast complete displayed buffer linebufnrnumber of buffer in the windowheightwindow height (excluding winbar)leftcolfirst column displayed; only used when'wrap' is offloclist1 if showing a location listquickfix1 if quickfix or location list windowterminal1 if a terminal windowtabnrtab page numbertoplinefirst displayed buffer linevariablesa reference to the dictionary withwindow-local variableswidthwindow widthwinbar1 if the window has a toolbar, 0otherwisewincolleftmost screen column of the window;"col" fromwin_screenpos()textoffnumber of columns occupied by any'foldcolumn','signcolumn' and linenumber in front of the textwinidwindow-ID winnrwindow numberwinrowtopmost screen line of the window;"row" fromwin_screenpos()
Parameters:
{winid} (integer?)
Return:
(vim.fn.getwininfo.ret.item[])
getwinpos([{timeout}])getwinpos()
The result is aList with two numbers, the result ofgetwinposx() andgetwinposy() combined:[x-pos, y-pos]{timeout} can be used to specify how long to wait in msec fora 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 receivedwithin that time, a previously reported position is returned,if available. This can be used to poll for the position anddo some work in the meantime:
while 1  let res = getwinpos(1)  if res[0] >= 0    break  endif  " Do some work hereendwhile
Parameters:
{timeout} (integer?)
Return:
(any)
getwinposx()getwinposx()
The result is a Number, which is the X coordinate in pixels ofthe left hand side of the GUI Vim window. The result will be-1 if the information is not available.The value can be used with:winpos.
Return:
(integer)
getwinposy()getwinposy()
The result is a Number, which is the Y coordinate in pixels ofthe top of the GUI Vim window. The result will be -1 if theinformation is not available.The value can be used with:winpos.
Return:
(integer)
getwinvar({winnr},{varname} [,{def}])getwinvar()
Likegettabwinvar() for the current tabpage.Examples:
let list_is_on = getwinvar(2, '&list')echo "myvar = " .. getwinvar(1, 'myvar')
Parameters:
{winnr} (integer)
{varname} (string)
{def} (any?)
Return:
(any)
glob({expr} [,{nosuf} [,{list} [,{alllinks}]]])glob()
Expand the file wildcards in{expr}. Seewildcards for theuse of special characters.
Unless the optional{nosuf} argument is given and isTRUE,the'suffixes' and'wildignore' options apply: Names matchingone of the patterns in'wildignore' will be skipped and'suffixes' affect the ordering of matches.'wildignorecase' always applies.
When{list} is present and it isTRUE the result is aListwith all matching files. The advantage of using a List is,you also get filenames containing newlines correctly.Otherwise the result is a String and when there are severalmatches, they are separated by<NL> characters.
If the expansion fails, the result is an empty String or List.
You can also usereaddir() if you need to do complicatedthings, such as limiting the number of matches.
A name for a non-existing file is not included. A symboliclink is only included if it points to an existing file.However, when the{alllinks} argument is present and it isTRUE then all symbolic links are included.
For most systems backticks can be used to get files names fromany 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 oneitem per line. Spaces inside an item are allowed.
Seeexpand() for expanding special Vim variables. Seesystem() for getting the raw output of an external command.
Parameters:
{expr} (string)
{nosuf} (boolean?)
{list} (boolean?)
{alllinks} (boolean?)
Return:
(any)
glob2regpat({string})glob2regpat()
Convert a file pattern, as used by glob(), into a searchpattern. The result can be used to match with a string thatis a file name. E.g.
if filename =~ glob2regpat('Make*.mak')  " ...endif
This is equivalent to:
if filename =~ '^Make.*\.mak$'  " ...endif
When{string} is an empty string the result is "^$", match anempty string.Note that the result depends on the system. On MS-Windowsa backslash usually means a path separator.
Parameters:
{string} (string)
Return:
(string)
globpath({path},{expr} [,{nosuf} [,{list} [,{allinks}]]])globpath()Perform glob() for String{expr} on all directories in{path}and concatenate the results. Example:
echo globpath(&rtp, "syntax/c.vim")
{path} is a comma-separated list of directory names. Eachdirectory name is prepended to{expr} and expanded like withglob(). A path separator is inserted when needed.To add a comma inside a directory name escape it with abackslash. Note that on MS-Windows a directory may have atrailing backslash, remove it if you put a comma after it.If the expansion fails for one of the directories, there is noerror message.
Unless the optional{nosuf} argument is given and isTRUE,the'suffixes' and'wildignore' options apply: Names matchingone of the patterns in'wildignore' will be skipped and'suffixes' affect the ordering of matches.
When{list} is present and it isTRUE the result is aListwith all matching files. The advantage of using a List is, youalso get filenames containing newlines correctly. Otherwisethe result is a String and when there are several matches,they are separated by<NL> characters. Example:
echo globpath(&rtp, "syntax/c.vim", 0, 1)
{allinks} is used as withglob().
The "**" item can be used to search in a directory tree.For example, to find all "README.txt" files in the directoriesin'runtimepath' and below:
echo globpath(&rtp, "**/README.txt")
Upwards search and limiting the depth of "**" is notsupported, thus using'path' will not always work properly.
Parameters:
{path} (string)
{expr} (string)
{nosuf} (boolean?)
{list} (boolean?)
{allinks} (boolean?)
Return:
(any)
has({feature})has()
Returns 1 if{feature} is supported, 0 otherwise. The{feature} argument is a feature name like "nvim-0.2.1" or"win32", see below. See alsoexists().
To get the system name usevim.uv.os_uname() in Lua:
print(vim.uv.os_uname().sysname)
If the code has a syntax error then Vimscript may skip therest of the line. Put:if and:endif on separate lines toavoid the syntax error:
if has('feature')  let x = this_breaks_without_the_feature()endif
Vim's compile-time feature-names (prefixed with "+") are notrecognized because Nvim is always compiled with all possiblefeatures.feature-compile
Feature names can be:1. Nvim version. For example the "nvim-0.2.1" feature means that Nvim is version 0.2.1 or later:
if has("nvim-0.2.1")  " ...endif
2. Runtime condition or other pseudo-feature. For example the "win32" feature checks if the current system is Windows:
if has("win32")  " ...endif
feature-list
List of supported pseudo-feature names:aclACL support.bsdBSD system (not macOS, use "mac" for that).clipboardclipboard provider is available.fname_caseCase in file names matters (for Darwin and MS-Windowsthis is not present).gui_runningNvim has a GUI.hurdGNU/Hurd system.iconvCan useiconv() for conversion.linuxLinux system.macMacOS system.nvimThis is Nvim.python3Legacy Vimpython3 interface.has-pythonpythonxLegacy Vimpython_x interface.has-pythonxsunSunOS system.ttyininput is a terminal (tty).ttyoutoutput is a terminal (tty).unixUnix system.vim_starting True duringstartup.win32Windows system (32 or 64 bit).win64Windows system (64 bit).wslWSL (Windows Subsystem for Linux) system.
has-patch
3. Vim patch. For example the "patch123" feature means that Vim patch 123 at the currentv:version was included:
if v:version > 602 || v:version == 602 && has("patch148")  " ...endif
4. Vim version. For example the "patch-7.4.237" feature means that Nvim is Vim-compatible to version 7.4.237 or later.
if has("patch-7.4.237")  " ...endif
Parameters:
{feature} (string)
Return:
(0|1)
has_key({dict},{key})has_key()
The result is a Number, which is TRUE ifDictionary{dict}has an entry with key{key}. FALSE otherwise. The{key}argument is a string.
Parameters:
{dict} (table)
{key} (string)
Return:
(0|1)
haslocaldir([{winnr} [,{tabnr}]])haslocaldir()
The result is a Number, which is 1 when the window has set alocal path via:lcd or when{winnr} is -1 and the tabpagehas set a local path via:tcd, otherwise 0.
Tabs and windows are identified by their respective numbers,0 means current tab or window. Missing argument implies 0.Thus the following are equivalent:
echo haslocaldir()echo haslocaldir(0)echo haslocaldir(0, 0)
With{winnr} use that window in the current tabpage.With{winnr} and{tabnr} use the window in that tabpage.{winnr} can be the window number or thewindow-ID.If{winnr} is -1 it is ignored, only the tab is resolved.Throw error if the arguments are invalid.E5000E5001E5002
Parameters:
{winnr} (integer?)
{tabnr} (integer?)
Return:
(0|1)
hasmapto({what} [,{mode} [,{abbr}]])hasmapto()
The result is a Number, which is TRUE if there is a mappingthat contains{what} in somewhere in the rhs (what it ismapped to) and this mapping exists in one of the modesindicated by{mode}.The arguments{what} and{mode} are strings.When{abbr} is there and it isTRUE use abbreviationsinstead of mappings. Don't forget to specify Insert and/orCommand-line mode.Both the global mappings and the mappings local to the currentbuffer are checked for a match.If no matching mapping is found FALSE is returned.The following characters are recognized in{mode}:nNormal modevVisual and Select modexVisual modesSelect modeoOperator-pending modeiInsert modelLanguage-Argument ("r", "f", "t", etc.)cCommand-line modeWhen{mode} is omitted, "nvo" is used.
This function is useful to check if a mapping already existsto a function in a Vim script. Example:
if !hasmapto('\ABCdoit')   map <Leader>d \ABCdoitendif
This installs the mapping to "\ABCdoit" only if there isn'talready a mapping to "\ABCdoit".
Parameters:
{what} (any)
{mode} (string?)
{abbr} (boolean?)
Return:
(0|1)
histadd({history},{item})histadd()
Add the String{item} to the history{history} which can beone of:hist-names
"cmd" or ":" command line history"search" or "/" search pattern history"expr" or "=" typed expression history"input" or "@" input line history"debug" or ">" debug command historyempty the current or last used historyThe{history} string does not need to be the whole name, onecharacter is sufficient.If{item} does already exist in the history, it will beshifted to become the newest entry.The result is a Number: TRUE if the operation was successful,otherwise FALSE is returned.
Example:
call histadd("input", strftime("%Y %b %d"))let date=input("Enter date: ")
This function is not available in thesandbox.
Parameters:
{history} (string)
{item} (any)
Return:
(0|1)
histdel({history} [,{item}])histdel()
Clear{history}, i.e. delete all its entries. Seehist-namesfor the possible values of{history}.
If the parameter{item} evaluates to a String, it is used as aregular expression. All entries matching that expression willbe removed from the history (if there are any).Upper/lowercase must match, unless "\c" is used/\c.If{item} evaluates to a Number, it will be interpreted asan index, see:history-indexing. The respective entry willbe removed if it exists.
The result is TRUE for a successful operation, otherwise FALSEis returned.
Examples:Clear expression register history:
call histdel("expr")
Remove all entries starting with "*" from the search history:
call histdel("/", '^\*')
The following three are equivalent:
call histdel("search", histnr("search"))call histdel("search", -1)call histdel("search", '^' .. histget("search", -1) .. '$')
To delete the last search pattern and use the last-but-one forthe "n" command and'hlsearch':
call histdel("search", -1)let @/ = histget("search", -1)
Parameters:
{history} (string)
{item} (any?)
Return:
(0|1)
histget({history} [,{index}])histget()
The result is a String, the entry with Number{index} from{history}. Seehist-names for the possible values of{history}, and:history-indexing for{index}. If there isno such entry, an empty String is returned. When{index} isomitted, the most recent item from the history is used.
Examples:Redo the second last search from history.
execute '/' .. histget("search", -2)
Define an Ex command ":H{num}" that supports re-execution ofthe{num}th entry from the output of:history.
command -nargs=1 H execute histget("cmd", 0+<args>)
Parameters:
{history} (string)
{index} (integer|string?)
Return:
(string)
histnr({history})histnr()
The result is the Number of the current entry in{history}.Seehist-names for the possible values of{history}.If an error occurred, -1 is returned.
Example:
let inp_index = histnr("expr")
Parameters:
{history} (string)
Return:
(integer)
hlID({name})hlID()
The result is a Number, which is the ID of the highlight groupwith name{name}. When the highlight group doesn't exist,zero is returned.This can be used to retrieve information about the highlightgroup. For example, to get the background color of the"Comment" group:
echo synIDattr(synIDtrans(hlID("Comment")), "bg")
Parameters:
{name} (string)
Return:
(integer)
hlexists({name})hlexists()
The result is a Number, which is TRUE if a highlight groupcalled{name} exists. This is when the group has beendefined in some way. Not necessarily when highlighting hasbeen defined for it, it may also have been used for a syntaxitem.
Parameters:
{name} (string)
Return:
(0|1)
hostname()hostname()
The result is a String, which is the name of the machine onwhich Vim is currently running. Machine names greater than256 characters long are truncated.
Return:
(string)
iconv({string},{from},{to})iconv()
The result is a String, which is the text{string} convertedfrom encoding{from} to encoding{to}.When the conversion completely fails an empty string isreturned. When some characters could not be converted theyare replaced with "?".The encoding names are whatever the iconv() library functioncan accept, see ":!man 3 iconv".Note that Vim uses UTF-8 for all Unicode encodings, conversionfrom/to UCS-2 is automatically changed to use UTF-8. Youcannot use UCS-2 in a string anyway, because of the NUL bytes.
Parameters:
{string} (string)
{from} (string)
{to} (string)
Return:
(string)
id({expr})id()
Returns aString which is a unique identifier of thecontainer type (List,Dict,Blob andPartial). It isguaranteed that for the mentioned typesid(v1) ==# id(v2)returns true ifftype(v1) == type(v2) && v1 is v2.Note thatv:_null_string,v:_null_list,v:_null_dict andv:_null_blob have the sameid() with different typesbecause they are internally represented as NULL pointers.id() returns a hexadecimal representation of the pointers tothe containers (i.e. like0x994a40), same asprintf("%p",{expr})`, but it is advised against counting on the exactformat of the return value.
It is not guaranteed thatid(no_longer_existing_container)will not be equal to some otherid(): new containers mayreuse identifiers of the garbage-collected ones.
Parameters:
{expr} (any)
Return:
(string)
indent({lnum})indent()
The result is a Number, which is indent of line{lnum} in thecurrent buffer. The indent is counted in spaces, the valueof'tabstop' is relevant.{lnum} is used just like ingetline().When{lnum} is invalid -1 is returned.
To get or set indent of lines in a string, seevim.text.indent().
Parameters:
{lnum} (integer|string)
Return:
(integer)
index({object},{expr} [,{start} [,{ic}]])index()
Find{expr} in{object} and return its index. Seeindexof() for using a lambda to select the item.
If{object} is aList return the lowest index where the itemhas a value equal to{expr}. There is no automaticconversion, so the String "4" is different from the Number 4.And the Number 4 is different from the Float 4.0. The valueof'ignorecase' is not used here, case matters as indicated bythe{ic} argument.
If{object} is aBlob return the lowest index where the bytevalue is equal to{expr}.
If{start} is given then start looking at the item with index{start} (may be negative for an item relative to the end).
When{ic} is given and it isTRUE, ignore case. Otherwisecase must match.
-1 is returned when{expr} is not found in{object}.Example:
let idx = index(words, "the")if index(numbers, 123) >= 0  " ...endif
Parameters:
{object} (any)
{expr} (any)
{start} (integer?)
{ic} (boolean?)
Return:
(integer)
indexof({object},{expr} [,{opts}])indexof()
Returns the index of an item in{object} where{expr} isv:true.{object} must be aList or aBlob.
If{object} is aList, evaluate{expr} for each item in theList until the expression is v:true and return the index ofthis item.
If{object} is aBlob evaluate{expr} for each byte in theBlob until the expression is v:true and return the index ofthis byte.
{expr} must be astring orFuncref.
If{expr} is astring: If{object} is aList, inside{expr}v:key has the index of the current List item andv:val has the value of the item. If{object} is aBlob,inside{expr}v:key has the index of the current byte andv:val has the byte value.
If{expr} is aFuncref it must take two arguments:1. the key or the index of the current item.2. the value of the current item.The function must returnTRUE if the item is found and thesearch should stop.
The optional argument{opts} is a Dict and supports thefollowing items: startidxstart evaluating{expr} at the item with thisindex; may be negative for an item relative tothe endReturns -1 when{expr} evaluates to v:false for all the items.Example:
let l = [#{n: 10}, #{n: 20}, #{n: 30}]echo indexof(l, "v:val.n == 20")echo indexof(l, {i, v -> v.n == 30})echo indexof(l, "v:val.n == 20", #{startidx: 1})
Parameters:
{object} (any)
{expr} (any)
{opts} (table?)
Return:
(integer)
input({prompt} [,{text} [,{completion}]])input()
Parameters:
{prompt} (string)
{text} (string?)
{completion} (string?)
Return:
(string)
input({opts})The result is a String, which is whatever the user typed onthe command-line. The{prompt} argument is either a promptstring, or a blank string (for no prompt). A '\n' can be usedin the prompt to start a new line.
In the second form it accepts a single dictionary with thefollowing keys, any of which may be omitted:
Key Default Description
prompt "" Same as{prompt} in the first form.default "" Same as{text} in the first form.completion nothing Same as{completion} in the first form.cancelreturn "" The value returned when the dialog is cancelled.highlight nothing Highlight handler:Funcref.
The highlighting set with:echohl is used for the prompt.The input is entered just like a command-line, with the sameediting commands and mappings. There is a separate historyfor lines typed for input().Example:
if input("Coffee or beer? ") == "beer"  echo "Cheers!"endif
If the optional{text} argument is present and not empty, thisis used for the default reply, as if the user typed this.Example:
let color = input("Color? ", "white")
The optional{completion} argument specifies the type ofcompletion supported for the input. Without it completion isnot performed. The supported completion types are the same asthat can be supplied to a user-defined command using the"-complete=" argument. Refer to:command-completion formore information. Example:
let fname = input("File: ", "", "file")
input()-highlightE5400E5402The optionalhighlight key allows specifying function whichwill be used for highlighting user input. This functionreceives user input as its only argument and must returna list of 3-tuples [hl_start_col, hl_end_col + 1, hl_group]wherehl_start_col is the first highlighted column,hl_end_col is the last highlighted column (+ 1!),hl_group is:hi group used for highlighting.E5403E5404E5405E5406Both hl_start_col and hl_end_col + 1 must point to the startof the multibyte character (highlighting must not breakmultibyte characters), hl_end_col + 1 may be equal to theinput length. Start column must be in range [0, len(input)),end column must be in range (hl_start_col, len(input)],sections must be ordered so that next hl_start_col is greaterthen or equal to previous hl_end_col.
Example (try some input with parentheses):
highlight RBP1 guibg=Red ctermbg=redhighlight RBP2 guibg=Yellow ctermbg=yellowhighlight RBP3 guibg=Green ctermbg=greenhighlight RBP4 guibg=Blue ctermbg=bluelet g:rainbow_levels = 4function! RainbowParens(cmdline)  let ret = []  let i = 0  let lvl = 0  while i < len(a:cmdline)    if a:cmdline[i] is# '('      call add(ret, [i, i + 1, 'RBP' .. ((lvl % g:rainbow_levels) + 1)])      let lvl += 1    elseif a:cmdline[i] is# ')'      let lvl -= 1      call add(ret, [i, i + 1, 'RBP' .. ((lvl % g:rainbow_levels) + 1)])    endif    let i += 1  endwhile  return retendfunctioncall input({'prompt':'>','highlight':'RainbowParens'})
Highlight function is called at least once for each newdisplayed input string, before command-line is redrawn. It isexpected that function is pure for the duration of one input()call, i.e. it produces the same output for the same input, sooutput may be memoized. Function is run like under:silentmodifier. If the function causes any errors, it will beskipped for the duration of the current input() call.
Highlighting is disabled if command-line contains arabiccharacters.
NOTE: This function must not be used in a startup file, forthe versions that only run in GUI mode (e.g., the Win32 GUI).Note: When input() is called from within a mapping it willconsume remaining characters from that mapping, because amapping is handled like the characters were typed.Useinputsave() before input() andinputrestore()after input() to avoid that. Another solution is to avoidthat further characters follow in the mapping, e.g., by using:execute or:normal.
Example with a mapping:
nmap \x :call GetFoo()<CR>:exe "/" .. Foo<CR>function GetFoo()  call inputsave()  let g:Foo = input("enter search pattern: ")  call inputrestore()endfunction
Parameters:
{opts} (table)
Return:
(string)
inputlist({textlist})inputlist()
{textlist} must be aList of strings. ThisList isdisplayed, one string per line. The user will be prompted toenter a number, which is returned.The user can also select an item by clicking on it with themouse, if the mouse is enabled in the command line ('mouse' is"a" or includes "c"). For the first string 0 is returned.When clicking above the first item a negative number isreturned. When clicking on the prompt one more than thelength of{textlist} is returned.Make sure{textlist} has less than'lines' entries, otherwiseit won't work. It's a good idea to put the entry number atthe start of the string. And put a prompt in the first item.Example:
let color = inputlist(['Select color:', '1. red',        \ '2. green', '3. blue'])
Parameters:
{textlist} (string[])
Return:
(any)
inputrestore()inputrestore()
Restore typeahead that was saved with a previousinputsave().Should be called the same number of times inputsave() iscalled. Calling it more often is harmless though.Returns TRUE when there is nothing to restore, FALSE otherwise.
Return:
(integer)
inputsave()inputsave()
Preserve typeahead (also from mappings) and clear it, so thata following prompt gets input from the user. Should befollowed by a matching inputrestore() after the prompt. Canbe used several times, in which case there must be just asmany inputrestore() calls.Returns TRUE when out of memory, FALSE otherwise.
Return:
(integer)
inputsecret({prompt} [,{text}])inputsecret()
This function acts much like theinput() function with buttwo exceptions:a) the user's response will be displayed as a sequence ofasterisks ("*") thereby keeping the entry secret, andb) the user's response will not be recorded on the inputhistory stack.The result is a String, which is whatever the user actuallytyped on the command-line in response to the issued prompt.NOTE: Command-line completion is not supported.
Parameters:
{prompt} (string)
{text} (string?)
Return:
(string)
insert({object},{item} [,{idx}])insert()
When{object} is aList or aBlob insert{item} at the startof it.
If{idx} is specified insert{item} before the item with index{idx}. If{idx} is zero it goes before the first item, justlike omitting{idx}. A negative{idx} is also possible, seelist-index. -1 inserts just before the last item.
Returns the resultingList orBlob. Examples:
let mylist = insert([2, 3, 5], 1)call insert(mylist, 4, -1)call insert(mylist, 6, len(mylist))
The last example can be done simpler withadd().Note that when{item} is aList it is inserted as a singleitem. Useextend() to concatenateLists.
Parameters:
{object} (any)
{item} (any)
{idx} (integer?)
Return:
(any)
interrupt()interrupt()
Interrupt script execution. It works more or less like theuser typingCTRL-C, most commands won't execute and controlreturns to the user. This is useful to abort executionfrom lower down, e.g. in an autocommand. Example:
function s:check_typoname(file)   if fnamemodify(a:file, ':t') == '['       echomsg 'Maybe typo'       call interrupt()   endifendfunctionau BufWritePre * call s:check_typoname(expand('<amatch>'))
Return:
(any)
invert({expr})invert()
Bitwise invert. The argument is converted to a number. AList, Dict or Float argument causes an error. Example:
let bits = invert(bits)
Parameters:
{expr} (integer)
Return:
(integer)
isabsolutepath({path})isabsolutepath()
The result is a Number, which isTRUE when{path} is anabsolute path.On Unix, a path is considered absolute when it starts with '/'.On MS-Windows, it is considered absolute when it starts with anoptional drive prefix and is followed by a '\' or '/'. UNC pathsare always absolute.Example:
echo isabsolutepath('/usr/share/')" 1echo isabsolutepath('./foobar')" 0echo isabsolutepath('C:\Windows')" 1echo isabsolutepath('foobar')" 0echo isabsolutepath('\\remote\file')" 1
Parameters:
{path} (string)
Return:
(0|1)
isdirectory({directory})isdirectory()
The result is a Number, which isTRUE when a directorywith the name{directory} exists. If{directory} doesn'texist, or isn't a directory, the result isFALSE.{directory}is any expression, which is used as a String.
Parameters:
{directory} (string)
Return:
(0|1)
isinf({expr})isinf()
Return 1 if{expr} is a positive infinity, or -1 a negativeinfinity, otherwise 0.
echo isinf(1.0 / 0.0)
1
echo isinf(-1.0 / 0.0)
-1
Parameters:
{expr} (number)
Return:
(1|0|-1)
islocked({expr})islocked()E786The result is a Number, which isTRUE when{expr} is thename of a locked variable.The string argument{expr} must be the name of a variable,List item orDictionary entry, not the variable itself!Example:
let alist = [0, ['a', 'b'], 2, 3]lockvar 1 alistecho islocked('alist')" 1echo islocked('alist[1]')" 0
When{expr} is a variable that does not exist you get an errormessage. Useexists() to check for existence.
Parameters:
{expr} (any)
Return:
(0|1)
isnan({expr})isnan()
ReturnTRUE if{expr} is a float with value NaN.
echo isnan(0.0 / 0.0)
1
Parameters:
{expr} (number)
Return:
(0|1)
items({expr})items()
Return aList with all key/index and value pairs of{expr}.EachList item is a list with two items:
for aDict: the key and the value
for aList orString: the index and the valueThe returnedList is in arbitrary order for aDict,otherwise it's in ascending order of the index.
Also seekeys() andvalues().
Example:
let mydict = #{a: 'red', b: 'blue'}for [key, value] in items(mydict)   echo $"{key} = {value}"endforecho items([1, 2, 3])echo items("foobar")
Parameters:
{expr} (table|string)
Return:
(any)
jobpid({job})jobpid()
Return the PID (process id) ofjob-id{job}.
Parameters:
{job} (integer)
Return:
(integer)
jobresize({job},{width},{height})jobresize()
Resize the pseudo terminal window ofjob-id{job} to{width}columns and{height} rows.Fails if the job was not started with"pty":v:true.
Parameters:
{job} (integer)
{width} (integer)
{height} (integer)
Return:
(any)
jobstart({cmd} [,{opts}])jobstart()
Note: Prefervim.system() in Lua (unless usingrpc,pty, orterm).
Spawns{cmd} as a job.If{cmd} is a List it runs directly (no'shell').If{cmd} is a String it runs in the'shell', like this:
call jobstart(split(&shell) + split(&shellcmdflag) + ['{cmd}'])
(Seeshell-unquoting for details.)
Example: start a job and handle its output:
call jobstart(['nvim', '-h'], {'on_stdout':{j,d,e->append(line('.'),d)}})
Example: start a job in aterminal connected to the current buffer:
call jobstart(['nvim', '-h'], {'term':v:true})
Returnsjob-id on success, 0 on invalid arguments (or jobtable is full), -1 if{cmd}[0] or'shell' is not executable.The returned job-id is a validchannel-id representing thejob's stdio streams. Usechansend() (orrpcnotify() andrpcrequest() if "rpc" was enabled) to send data to stdin andchanclose() to close the streams without stopping the job.
Seejob-control andRPC.
NOTE: on Windows if{cmd} is a List:
cmd[0] must be an executable (not a "built-in"). If it is in $PATH it can be called by name, without an extension:
call jobstart(['ping', 'neovim.io'])
If it is a full or partial path, extension is required:
call jobstart(['System32\ping.exe', 'neovim.io'])
{cmd} is collapsed to a string of quoted args as expected by CommandLineToArgvWhttps://msdn.microsoft.com/bb776391 unless cmd[0] is some form of "cmd.exe".
jobstart-env
The job environment is initialized as follows: $NVIM is set tov:servername of the parent Nvim $NVIM_LISTEN_ADDRESS is unset $NVIM_LOG_FILE is unset $VIM is unset $VIMRUNTIME is unsetYou can set these with theenv option.
jobstart-options
{opts} is a dictionary with these keys: clear_env: (boolean)env defines the job environment exactly, instead of merging current environment. cwd: (string, default=|current-directory|) Working directory of the job. detach: (boolean) Detach the job process: it will not be killed when Nvim exits. If the process exits before Nvim,on_exit will be invoked. env: (dict) Map of environment variable name:value pairs extending (or replace with "clear_env") the current environment.jobstart-env height: (number) Height of thepty terminal.on_exit: (function) Callback invoked when the job exits.on_stdout: (function) Callback invoked when the job emits stdout data.on_stderr: (function) Callback invoked when the job emits stderr data. overlapped: (boolean) Sets FILE_FLAG_OVERLAPPED for the stdio passed to the child process. Only on MS-Windows; ignored on other platforms. pty: (boolean) Connect the job to a new pseudo terminal, and its streams to the master file descriptor.on_stdout receives all output,on_stderr is ignored.terminal-start rpc: (boolean) Usemsgpack-rpc to communicate with the job over stdio. Thenon_stdout is ignored, buton_stderr can still be used. stderr_buffered: (boolean) Collect data until EOF (stream closed) before invokingon_stderr.channel-buffered stdout_buffered: (boolean) Collect data until EOF (stream closed) before invokingon_stdout.channel-buffered stdin: (string) Either "pipe" (default) to connect the job's stdin to a channel or "null" to disconnect stdin. term: (boolean) Spawns{cmd} in a new pseudo-terminal session connected to the current (unmodified) buffer. Implies "pty". Default "height" and "width" are set to the current window dimensions.jobstart(). Defaults $TERM to "xterm-256color". width: (number) Width of thepty terminal.
{opts} is passed asself dictionary to the callback; thecaller may set other keys to pass application-specific data.
Returns:
channel-id on success
0 on invalid arguments
-1 if{cmd}[0] is not executable.See alsojob-control,channel,msgpack-rpc.
Parameters:
{cmd} (string|string[])
{opts} (table?)
Return:
(integer)
jobstop({id})jobstop()
Stopjob-id{id} by sending SIGTERM to the job process. Ifthe process does not terminate after a timeout then SIGKILLwill be sent. When the job terminates itson_exit handler(if any) will be invoked.Seejob-control.
Returns 1 for valid job id, 0 for invalid id, including jobs haveexited or stopped.
Parameters:
{id} (integer)
Return:
(integer)
jobwait({jobs} [,{timeout}])jobwait()
Waits for jobs and theiron_exit handlers to complete.
{jobs} is a List ofjob-ids to wait for.{timeout} is the maximum waiting time in milliseconds. Ifomitted or -1, wait forever.
Timeout of 0 can be used to check the status of a job:
let running = jobwait([{job-id}], 0)[0] == -1
During jobwait() callbacks for jobs not in the{jobs} list maybe invoked. The screen will not redraw unless:redraw isinvoked by a callback.
Returns a list of len({jobs}) integers, where each integer isthe status of the corresponding job:Exit-code, if the job exited-1 if the timeout was exceeded-2 if the job was interrupted (byCTRL-C)-3 if the job-id is invalid
Parameters:
{jobs} (integer[])
{timeout} (integer?)
Return:
(integer[])
join({list} [,{sep}])join()
Join the items in{list} together into one String.When{sep} is specified it is put in between the items. If{sep} is omitted a single space is used.Note that{sep} is not added at the end. You might want toadd it there too:
let lines = join(mylist, "\n") .. "\n"
String items are used as-is.Lists andDictionaries areconverted into a string like withstring().The opposite function issplit().
Parameters:
{list} (any[])
{sep} (string?)
Return:
(string)
json_decode({expr})json_decode()
Convert{expr} from JSON object. Acceptsreadfile()-stylelist as the input, as well as regular string. May output anyVim value. In the following cases it will outputmsgpack-special-dict:1. Dictionary contains duplicate key.2. String contains NUL byte. Two special dictionaries: for dictionary and for string will be emitted in case string with NUL byte was a dictionary key.
Note: function treats its input as UTF-8 always. The JSONstandard allows only a few encodings, of which UTF-8 isrecommended and the only one required to be supported.Non-UTF-8 characters are an error.
Parameters:
{expr} (any)
Return:
(any)
json_encode({expr})json_encode()
Convert{expr} into a JSON string. Acceptsmsgpack-special-dict as the input. Will not convertFuncrefs, mappings with non-string keys (can be created asmsgpack-special-dict), values with self-referencingcontainers, strings which contain non-UTF-8 characters,pseudo-UTF-8 strings which contain codepoints reserved forsurrogate pairs (such strings are not valid UTF-8 strings).Non-printable characters are converted into "\u1234" escapesor special escapes like "\t", other are dumped as-is.Blobs are converted to arrays of the individual bytes.
Parameters:
{expr} (any)
Return:
(string)
keys({dict})keys()
Return aList with all the keys of{dict}. TheList is inarbitrary order. Also seeitems() andvalues().
Parameters:
{dict} (table)
Return:
(string[])
keytrans({string})keytrans()
Turn the internal byte representation of keys into a form thatcan be used for:map. E.g.
let xx = "\<C-Home>"echo keytrans(xx)
<C-Home>
Parameters:
{string} (string)
Return:
(string)
len({expr})len()E701The result is a Number, which is the length of the argument.When{expr} is a String or a Number the length in bytes isused, as withstrlen().When{expr} is aList the number of items in theList isreturned.When{expr} is aBlob the number of bytes is returned.When{expr} is aDictionary the number of entries in theDictionary is returned.Otherwise an error is given and returns zero.
Parameters:
{expr} (any[])
Return:
(integer)
libcall({libname},{funcname},{argument})libcall()E364E368Call function{funcname} in the run-time library{libname}with single argument{argument}.This is useful to call functions in a library that youespecially made to be used with Vim. Since only one argumentis possible, calling standard library functions is ratherlimited.The result is the String returned by the function. If thefunction returns NULL, this will appear as an empty string ""to Vim.If the function returns a number, use libcallnr()!If{argument} is a number, it is passed to the function as anint; if{argument} is a string, it is passed as anull-terminated string.
libcall() allows you to write your own 'plug-in' extensions toVim without having to recompile the program. It is NOT ameans to call system functions! If you try to do so Vim willvery probably crash.
For Win32, the functions you write must be placed in a DLLand use the normal C calling convention (NOT Pascal which isused in Windows System DLLs). The function must take exactlyone parameter, either a character pointer or a long integer,and must return a character pointer or NULL. The characterpointer returned must point to memory that will remain validafter the function has returned (e.g. in static data in theDLL). If it points to allocated memory, that memory willleak away. Using a static buffer in the function should work,it's then freed when the DLL is unloaded.
WARNING: If the function returns a non-valid pointer, Vim maycrash!This also happens if the function returns a number,because Vim thinks it's a pointer.For Win32 systems,{libname} should be the filename of the DLLwithout the ".DLL" suffix. A full path is only required ifthe DLL is not in the usual places.For Unix: When compiling your own plugins, remember that theobject code must be compiled as position-independent ('PIC').Examples:
echo libcall("libc.so", "getenv", "HOME")
Parameters:
{libname} (string)
{funcname} (string)
{argument} (any)
Return:
(any)
libcallnr({libname},{funcname},{argument})libcallnr()
Just likelibcall(), but used for a function that returns anint instead of a string.Examples:
echo libcallnr("/usr/lib/libc.so", "getpid", "")call libcallnr("libc.so", "printf", "Hello World!\n")call libcallnr("libc.so", "sleep", 10)
Parameters:
{libname} (string)
{funcname} (string)
{argument} (any)
Return:
(any)
line({expr} [,{winid}])line()
Seegetpos() for accepted positions.
To get the column number usecol(). To get both usegetpos().
With the optional{winid} argument the values are obtained forthat window instead of the current window.
Returns 0 for invalid values of{expr} and{winid}.
Examples:
echo line(".")" line number of the cursorecho line(".", winid)" idem, in window "winid"echo line("'t")" line number of mark techo line("'" .. marker)" line number of mark marker
To jump to the last known position when opening a file seelast-position-jump.
Parameters:
{expr} (string|integer[])
{winid} (integer?)
Return:
(integer)
line2byte({lnum})line2byte()
Return the byte count from the start of the buffer for line{lnum}. This includes the end-of-line character, depending onthe'fileformat' option for the current buffer. The firstline returns 1. UTF-8 encoding is used,'fileencoding' isignored. This can also be used to get the byte count for theline just below the last line:
echo line2byte(line("$") + 1)
This is the buffer size plus one. If'fileencoding' is emptyit is the file size plus one.{lnum} is used like withgetline(). When{lnum} is invalid -1 is returned.Also seebyte2line(),go and:goto.
Parameters:
{lnum} (integer|string)
Return:
(integer)
lispindent({lnum})lispindent()
Get the amount of indent for line{lnum} according the lispindenting rules, as with'lisp'.The indent is counted in spaces, the value of'tabstop' isrelevant.{lnum} is used just like ingetline().When{lnum} is invalid, -1 is returned.
Parameters:
{lnum} (integer|string)
Return:
(integer)
list2blob({list})list2blob()
Return a Blob concatenating all the number values in{list}.Examples:
echo list2blob([1, 2, 3, 4])" returns 0z01020304echo list2blob([])" returns 0z
Returns an empty Blob on error. If one of the numbers isnegative or more than 255 errorE1239 is given.
blob2list() does the opposite.
Parameters:
{list} (any[])
Return:
(string)
list2str({list} [,{utf8}])list2str()
Convert each number in{list} to a character string canconcatenate them all. Examples:
echo list2str([32])" returns " "echo list2str([65, 66, 67])" returns "ABC"
The same can be done (slowly) with:
echo join(map(list, {nr, val -> nr2char(val)}), '')
str2list() does the opposite.
UTF-8 encoding is always used,{utf8} option has no effect,and exists only for backwards-compatibility.With UTF-8 composing characters work as expected:
echo list2str([97, 769])" returns "á"
Returns an empty string on error.
Parameters:
{list} (any[])
{utf8} (boolean?)
Return:
(string)
localtime()localtime()
Return the current time, measured as seconds since 1st Jan1970. See alsostrftime(),strptime() andgetftime().
Return:
(integer)
log({expr})log()
Return the natural logarithm (base e) of{expr} as aFloat.{expr} must evaluate to aFloat or aNumber in the range(0, inf].Returns 0.0 if{expr} is not aFloat or aNumber.Examples:
echo log(10)
2.302585
echo log(exp(5))
5.0
Parameters:
{expr} (number)
Return:
(number)
log10({expr})log10()
Return the logarithm of Float{expr} to base 10 as aFloat.{expr} must evaluate to aFloat or aNumber.Returns 0.0 if{expr} is not aFloat or aNumber.Examples:
echo log10(1000)
3.0
echo log10(0.01)
-2.0
Parameters:
{expr} (number)
Return:
(number)
luaeval({expr} [,{expr}])luaeval()
Evaluate Lua expression{expr} and return its result convertedto Vim data structures. Seelua-eval for details.
See alsov:lua-call.
Parameters:
{expr} (string)
{expr1} (any[]?)
Return:
(any)
map({expr1},{expr2})map()
{expr1} must be aList,String,Blob orDictionary.When{expr1} is aList orDictionary, replace eachitem in{expr1} with the result of evaluating{expr2}.For aBlob each byte is replaced.For aString, each character, including composingcharacters, is replaced.If the item type changes you may want to usemapnew() tocreate a new List or Dictionary.
{expr2} must be aString orFuncref.
If{expr2} is aString, inside{expr2}v:val has the valueof the current item. For aDictionaryv:key has the keyof the current item and for aListv:key has the index ofthe current item. For aBlobv:key has the index of thecurrent byte. For aStringv:key has the index of thecurrent character.Example:
call map(mylist, '"> " .. v:val .. " <"')
This puts "> " before and " <" after each item in "mylist".
Note that{expr2} is the result of an expression and is thenused as an expression again. Often it is good to use aliteral-string to avoid having to double backslashes. Youstill have to double ' quotes
If{expr2} is aFuncref it is called with two arguments:1. The key or the index of the current item.2. the value of the current item.The function must return the new value of the item. Examplethat changes each value by "key-value":
func KeyValue(key, val)  return a:key .. '-' .. a:valendfunccall map(myDict, function('KeyValue'))
It is shorter when using alambda:
call map(myDict, {key, val -> key .. '-' .. val})
If you do not use "val" you can leave it out:
call map(myDict, {key -> 'item: ' .. key})
If you do not use "key" you can use a short name:
call map(myDict, {_, val -> 'item: ' .. val})
The operation is done in-place for aList andDictionary.If you want it to remain unmodified make a copy first:
let tlist = map(copy(mylist), ' v:val .. "\t"')
Returns{expr1}, theList orDictionary that was filtered,or a newBlob orString.When an error is encountered while evaluating{expr2} nofurther items in{expr1} are processed.When{expr2} is a Funcref errors inside a function are ignored,unless it was defined with the "abort" flag.
Parameters:
{expr1} (string|table|any[])
{expr2} (string|function)
Return:
(any)
maparg({name} [,{mode} [,{abbr} [,{dict}]]])maparg()
When{dict} is omitted or zero: Return the rhs of mapping{name} in mode{mode}. The returned String has specialcharacters translated like in the output of the ":map" commandlisting. When{dict} is TRUE a dictionary is returned, seebelow. To get a list of all mappings seemaplist().
When there is no mapping for{name}, an empty String isreturned if{dict} is FALSE, otherwise returns an empty Dict.When the mapping for{name} is empty, then "<Nop>" isreturned.
The{name} can have special key names, like in the ":map"command.
{mode} can be one of these strings:"n"Normal"v"Visual (including Select)"o"Operator-pending"i"Insert"c"Cmd-line"s"Select"x"Visual"l"langmaplanguage-mapping"t"Terminal""Normal, Visual and Operator-pendingWhen{mode} is omitted, the modes for "" are used.
When{abbr} is there and it isTRUE use abbreviationsinstead of mappings.
When{dict} isTRUE, return a dictionary describing themapping, with these items:mapping-dict
"lhs" The{lhs} of the mapping as it would be typed "lhsraw" The{lhs} of the mapping as raw bytes "lhsrawalt" The{lhs} of the mapping as raw bytes, alternate form, only present when it differs from "lhsraw" "rhs" The{rhs} of the mapping as typed. "callback" Lua function, if RHS was defined as such. "silent" 1 for a:map-silent mapping, else 0. "noremap" 1 if the{rhs} of the mapping is not remappable. "script" 1 if mapping was defined with<script>. "expr" 1 for an expression mapping (:map-<expr>). "buffer" 1 for a buffer local mapping (:map-local). "mode" Modes for which the mapping is defined. In addition to the modes mentioned above, these characters will be used: " " Normal, Visual and Operator-pending "!" Insert and Commandline mode (mapmode-ic) "sid" The script local ID, used for<sid> mappings (<SID>). Negative for special contexts. "scriptversion" The version of the script, always 1. "lnum" The line number in "sid", zero if unknown. "nowait" Do not wait for other, longer mappings. (:map-<nowait>). "abbr" True if this is anabbreviation. "mode_bits" Nvim's internal binary representation of "mode".mapset() ignores this; only "mode" is used. Seemaplist() for usage examples. The values are from src/nvim/state_defs.h and may change in the future.
The dictionary can be used to restore a mapping withmapset().
The mappings local to the current buffer are checked first,then the global mappings.This function can be used to map a key even when it's alreadymapped, and have it do the original mapping too. Sketch:
exe 'nnoremap <Tab> ==' .. maparg('<Tab>', 'n')
Parameters:
{name} (string)
{mode} (string?)
{abbr} (boolean?)
{dict} (false?)
Return:
(string)
mapcheck({name} [,{mode} [,{abbr}]])mapcheck()
Check if there is a mapping that matches with{name} in mode{mode}. Seemaparg() for{mode} and special names in{name}.When{abbr} is there and it is non-zero use abbreviationsinstead of mappings.A match happens with a mapping that starts with{name} andwith a mapping which is equal to the start of{name}.
matches mapping "a""ab""abc"
mapcheck("a")yesyes yes mapcheck("abc")yesyes yes mapcheck("ax")yesno no mapcheck("b")nono no
The difference with maparg() is that mapcheck() finds amapping that matches with{name}, while maparg() only finds amapping for{name} exactly.When there is no mapping that starts with{name}, an emptyString is returned. If there is one, the RHS of that mappingis returned. If there are several mappings that start with{name}, the RHS of one of them is returned. This will be"<Nop>" if the RHS is empty.The mappings local to the current buffer are checked first,then the global mappings.This function can be used to check if a mapping can be addedwithout being ambiguous. Example:
if mapcheck("_vv") == ""   map _vv :set guifont=7x13<CR>endif
This avoids adding the "_vv" mapping when there already is amapping for "_v" or for "_vvv".
Parameters:
{name} (string)
{mode} (string?)
{abbr} (boolean?)
Return:
(any)
maplist([{abbr}])maplist()
Returns aList of all mappings. Each List item is aDict,the same as what is returned bymaparg(), seemapping-dict. When{abbr} is there and it isTRUE useabbreviations instead of mappings.
Example to show all mappings with "MultiMatch" in rhs:
echo maplist()->filter({_, m ->        \ match(get(m, 'rhs', ''), 'MultiMatch') >= 0        \ })
It can be tricky to find mappings for particular:map-modes.mapping-dict's "mode_bits" can simplify this. For example,the mode_bits for Normal, Insert or Command-line modes are0x19. To find all the mappings available in those modes youcan do:
let saved_maps = []for m in maplist()    if and(m.mode_bits, 0x19) != 0        eval saved_maps->add(m)    endifendforecho saved_maps->mapnew({_, m -> m.lhs})
The values of the mode_bits are defined in Nvim'ssrc/nvim/state_defs.h file and they can be discovered atruntime using:map-commands and "maplist()". Example:
omap xyzzy <Nop>let op_bit = maplist()->filter(    \ {_, m -> m.lhs == 'xyzzy'})[0].mode_bitsounmap xyzzyecho printf("Operator-pending mode bit: 0x%x", op_bit)
Parameters:
{abbr} (0|1?)
Return:
(table[])
mapnew({expr1},{expr2})mapnew()
Likemap() but instead of replacing items in{expr1} a newList or Dictionary is created and returned.{expr1} remainsunchanged. Items can still be changed by{expr2}, if youdon't want that usedeepcopy() first.
Parameters:
{expr1} (any)
{expr2} (any)
Return:
(any)
mapset({mode},{abbr},{dict})mapset()
mapset({dict})Restore a mapping from a dictionary, possibly returned bymaparg() ormaplist(). A buffer mapping, when dict.bufferis true, is set on the current buffer; it is up to the callerto ensure that the intended buffer is the current buffer. Thisfeature allows copying mappings from one buffer to another.The dict.mode value may restore a single mapping that coversmore than one mode, like with mode values of '!', ' ', "nox",or 'v'.E1276
In the first form,{mode} and{abbr} should be the same asfor the call tomaparg().E460{mode} is used to define the mode in which the mapping is set,not the "mode" entry in{dict}.Example for saving and restoring a mapping:
let save_map = maparg('K', 'n', 0, 1)nnoremap K somethingelse" ...call mapset('n', 0, save_map)
Note that if you are going to replace a map in several modes,e.g. with:map!, you need to save/restore the mapping forall of them, when they might differ.
In the second form, with{dict} as the only argument, modeand abbr are taken from the dict.Example:
let save_maps = maplist()->filter(                        \ {_, m -> m.lhs == 'K'})nnoremap K somethingelsecnoremap K somethingelse2" ...unmap Kfor d in save_maps    call mapset(d)endfor
Parameters:
{dict} (table<string,any>)
Return:
(any)
match({expr},{pat} [,{start} [,{count}]])match()
When{expr} is aList then this returns the index of thefirst item where{pat} matches. Each item is used as aString,Lists andDictionaries are used as echoed.
Otherwise,{expr} is used as a String. The result is aNumber, which gives the index (byte offset) in{expr} where{pat} matches.
A match at the first character orList item returns zero.If there is no match -1 is returned.
For getting submatches seematchlist().Example:
echo match("testing", "ing")" results in 4echo match([1, 'x'], '\a')" results in 1
Seestring-match for how{pat} is used.strpbrk()
Vim doesn't have a strpbrk() function. But you can do:
let sepidx = match(line, '[.,;: \t]')
strcasestr()
Vim doesn't have a strcasestr() function. But you can add"\c" to the pattern to ignore case:
let idx = match(haystack, '\cneedle')
If{start} is given, the search starts from byte index{start} in a String or item{start} in aList.The result, however, is still the index counted from thefirst character/item. Example:
echo match("testing", "ing", 2)
result is again "4".
echo match("testing", "ing", 4)
result is again "4".
echo match("testing", "t", 2)
result is "3".For a String, if{start} > 0 then it is like the string starts{start} bytes later, thus "^" will match at{start}. Exceptwhen{count} is given, then it's like matches before the{start} byte are ignored (this is a bit complicated to keep itbackwards compatible).For a String, if{start} < 0, it will be set to 0. For a listthe index is counted from the end.If{start} is out of range ({start} > strlen({expr}) for aString or{start} > len({expr}) for aList) -1 is returned.
When{count} is given use the{count}th match. When a matchis found in a String the search for the next one starts onecharacter further. Thus this example results in 1:
echo match("testing", "..", 0, 2)
In aList the search continues in the next item.Note that when{count} is added the way{start} works changes,see above.
match-pattern
Seepattern for the patterns that are accepted.The'ignorecase' option is used to set the ignore-caseness ofthe pattern.'smartcase' is NOT used. The matching is alwaysdone like'magic' is set and'cpoptions' is empty.Note that a match at the start is preferred, thus when thepattern is using "*" (any number of matches) it tends to findzero matches at the start instead of a number of matchesfurther down in the text.
Parameters:
{expr} (string|any[])
{pat} (string)
{start} (integer?)
{count} (integer?)
Return:
(integer)
matchadd()E798E799E801E957matchadd({group},{pattern} [,{priority} [,{id} [,{dict}]]])Defines a pattern to be highlighted in the current window (a"match"). It will be highlighted with{group}. Returns anidentification number (ID), which can be used to delete thematch usingmatchdelete(). The ID is bound to the window.Matching is case sensitive and magic, unless case sensitivityor magicness are explicitly overridden in{pattern}. The'magic','smartcase' and'ignorecase' options are not used.The "Conceal" value is special, it causes the match to beconcealed.
The optional{priority} argument assigns a priority to thematch. A match with a high priority will have itshighlighting overrule that of a match with a lower priority.A priority is specified as an integer (negative numbers are noexception). If the{priority} argument is not specified, thedefault priority is 10. The priority of'hlsearch' is zero,hence all matches with a priority greater than zero willoverrule it. Syntax highlighting (see'syntax') is a separatemechanism, and regardless of the chosen priority a match willalways overrule syntax highlighting.
The optional{id} argument allows the request for a specificmatch ID. If a specified ID is already taken, an errormessage will appear and the match will not be added. An IDis specified as a positive integer (zero excluded). IDs 1, 2and 3 are reserved for:match,:2match and:3match,respectively. 3 is reserved for use by thematchparenplugin.If the{id} argument is not specified or -1,matchadd()automatically chooses a free ID, which is at least 1000.
The optional{dict} argument allows for further customvalues. Currently this is used to specify a match specificconceal character that will be shown forhl-Concealhighlighted matches. The dict can have the following members:
conceal Special character to show instead of the match (only forhl-Conceal highlighted matches, see:syn-cchar)window Instead of the current window use the window with this number or window ID.
The number of matches is not limited, as it is the case withthe:match commands.
Returns -1 on error.
Example:
highlight MyGroup ctermbg=green guibg=greenlet m = matchadd("MyGroup", "TODO")
Deletion of the pattern:
call matchdelete(m)
A list of matches defined bymatchadd() and:match areavailable fromgetmatches(). All matches can be deleted inone operation byclearmatches().
Parameters:
{group} (integer|string)
{pattern} (string)
{priority} (integer?)
{id} (integer?)
{dict} (table?)
Return:
(integer)
matchaddpos({group},{pos} [,{priority} [,{id} [,{dict}]]])matchaddpos()Same asmatchadd(), but requires a list of positions{pos}instead of a pattern. This command is faster thanmatchadd()because it does not handle regular expressions and it setsbuffer line boundaries to redraw screen. It is supposed to beused when fast match additions and deletions are required, forexample to highlight matching parentheses.E5030E5031{pos} is a list of positions. Each position can be one ofthese:
A number. This whole line will be highlighted. The first line has number 1.
A list with one number, e.g., [23]. The whole line with this number will be highlighted.
A list with two numbers, e.g., [23, 11]. The first number is the line number, the second one is the column number (first column is 1, the value must correspond to the byte index ascol() would return). The character at this position will be highlighted.
A list with three numbers, e.g., [23, 11, 3]. As above, but the third number gives the length of the highlight in bytes.
Entries with zero and negative line numbers are silentlyignored, as well as entries with negative column numbers andlengths.
Returns -1 on error.
Example:
highlight MyGroup ctermbg=green guibg=greenlet m = matchaddpos("MyGroup", [[23, 24], 34])
Deletion of the pattern:
call matchdelete(m)
Matches added bymatchaddpos() are returned bygetmatches().
Parameters:
{group} (integer|string)
{pos} (any[])
{priority} (integer?)
{id} (integer?)
{dict} (table?)
Return:
(integer|table)
matcharg({nr})matcharg()
Selects the{nr} match item, as set with a:match,:2match or:3match command.Return aList with two elements:The name of the highlight group usedThe pattern used.When{nr} is not 1, 2 or 3 returns an emptyList.When there is no match item set returns ['', ''].This is useful to save and restore a:match.Highlighting matches using the:match commands are limitedto three matches.matchadd() does not have this limitation.
Parameters:
{nr} (integer)
Return:
(string[])
matchbufline({buf},{pat},{lnum},{end}, [,{dict}])matchbufline()
Returns theList of matches in lines from{lnum} to{end} inbuffer{buf} where{pat} matches.
{lnum} and{end} can either be a line number or the string "$"to refer to the last line in{buf}.
The{dict} argument supports following items: submatchesinclude submatch information (/\()
For each match, aDict with the following items is returned: byteidxstarting byte index of the match lnumline number where there is a match textmatched stringNote that there can be multiple matches in a single line.
This function works only for loaded buffers. First callbufload() if needed.
Seematch-pattern for information about the effect of someoption settings on the pattern.
When{buf} is not a valid buffer, the buffer is not loaded or{lnum} or{end} is not valid then an error is given and anemptyList is returned.
Examples:
" Assuming line 3 in buffer 5 contains "a"echo matchbufline(5, '\<\k\+\>', 3, 3)
[{'lnum': 3, 'byteidx': 0, 'text': 'a'}]
" Assuming line 4 in buffer 10 contains "tik tok"echo matchbufline(10, '\<\k\+\>', 1, 4)
[{'lnum': 4, 'byteidx': 0, 'text': 'tik'}, {'lnum': 4, 'byteidx': 4, 'text': 'tok'}]
If{submatch} is present and is v:true, then submatches like"\1", "\2", etc. are also returned. Example:
" Assuming line 2 in buffer 2 contains "acd"echo matchbufline(2, '\(a\)\?\(b\)\?\(c\)\?\(.*\)', 2, 2                            \ {'submatches': v:true})
[{'lnum': 2, 'byteidx': 0, 'text': 'acd', 'submatches': ['a', '', 'c', 'd', '', '', '', '', '']}] The "submatches" List always contains 9 items. If a submatchis not found, then an empty string is returned for thatsubmatch.
Parameters:
{buf} (string|integer)
{pat} (string)
{lnum} (string|integer)
{end} (string|integer)
{dict} (table?)
Return:
(string[])
matchdelete({id} [,{win}])matchdelete()E802E803Deletes a match with ID{id} previously defined bymatchadd()or one of the:match commands. Returns 0 if successful,otherwise -1. See example formatchadd(). All matches canbe deleted in one operation byclearmatches().If{win} is specified, use the window with this number orwindow ID instead of the current window.
Parameters:
{id} (integer)
{win} (integer?)
Return:
(any)
matchend({expr},{pat} [,{start} [,{count}]])matchend()
Same asmatch(), but return the index of first characterafter the match. Example:
echo matchend("testing", "ing")
results in "7".strspn()strcspn()Vim doesn't have a strspn() or strcspn() function, but you cando it with matchend():
let span = matchend(line, '[a-zA-Z]')let span = matchend(line, '[^a-zA-Z]')
Except that -1 is returned when there are no matches.
The{start}, if given, has the same meaning as formatch().
echo matchend("testing", "ing", 2)
results in "7".
echo matchend("testing", "ing", 5)
result is "-1".When{expr} is aList the result is equal tomatch().
Parameters:
{expr} (any)
{pat} (string)
{start} (integer?)
{count} (integer?)
Return:
(integer)
matchfuzzy({list},{str} [,{dict}])matchfuzzy()
If{list} is a list of strings, then returns aList with allthe strings in{list} that fuzzy match{str}. The strings inthe returned list are sorted based on the matching score.
The optional{dict} argument always supports the followingitems: matchseqWhen this item is present return only matchesthat contain the characters in{str} in thegiven sequence. limitMaximum number of matches in{list} to bereturned. Zero means no limit.
If{list} is a list of dictionaries, then the optional{dict}argument supports the following additional items: keyKey of the item which is fuzzy matched against{str}. The value of this item should be astring. text_cbFuncref that will be called for every itemin{list} to get the text for fuzzy matching.This should accept a dictionary item as theargument and return the text for that item touse for fuzzy matching.
{str} is treated as a literal string and regular expressionmatching is NOT supported. The maximum supported{str} lengthis 256.
When{str} has multiple words each separated by white space,then the list of strings that have all the words is returned.
If there are no matching strings or there is an error, then anempty list is returned. If length of{str} is greater than256, then returns an empty list.
When{limit} is given, matchfuzzy() will find up to thisnumber of matches in{list} and return them in sorted order.
Refer tofuzzy-matching for more information about fuzzymatching strings.
Example:
echo matchfuzzy(["clay", "crow"], "cay")
results in ["clay"].
echo getbufinfo()->map({_, v -> v.name})->matchfuzzy("ndl")
results in a list of buffer names fuzzy matching "ndl".
echo getbufinfo()->matchfuzzy("ndl", {'key' : 'name'})
results in a list of buffer information dicts with buffernames fuzzy matching "ndl".
echo getbufinfo()->matchfuzzy("spl",                             \ {'text_cb' : {v -> v.name}})
results in a list of buffer information dicts with buffernames fuzzy matching "spl".
echo v:oldfiles->matchfuzzy("test")
results in a list of file names fuzzy matching "test".
let l = readfile("buffer.c")->matchfuzzy("str")
results in a list of lines in "buffer.c" fuzzy matching "str".
echo ['one two', 'two one']->matchfuzzy('two one')
results in['two one', 'one two'] .
echo ['one two', 'two one']->matchfuzzy('two one',                             \ {'matchseq': 1})
results in['two one'].
Parameters:
{list} (any[])
{str} (string)
{dict} (table?)
Return:
(table)
matchfuzzypos({list},{str} [,{dict}])matchfuzzypos()
Same asmatchfuzzy(), but returns the list of matchedstrings, the list of character positions where charactersin{str} matches and a list of matching scores. You canusebyteidx() to convert a character position to a byteposition.
If{str} matches multiple times in a string, then only thepositions for the best match is returned.
If there are no matching strings or there is an error, then alist with three empty list items is returned.
Example:
echo matchfuzzypos(['testing'], 'tsg')
results in [["testing"], [[0, 2, 6]], [99]]
echo matchfuzzypos(['clay', 'lacy'], 'la')
results in [["lacy", "clay"], [[0, 1], [1, 2]], [153, 133]]
echo [{'text': 'hello', 'id' : 10}]        \ ->matchfuzzypos('ll', {'key' : 'text'})
results in[[{"id": 10, "text": "hello"}], [[2, 3]], [127]]
Parameters:
{list} (any[])
{str} (string)
{dict} (table?)
Return:
(table)
matchlist({expr},{pat} [,{start} [,{count}]])matchlist()
Same asmatch(), but return aList. The first item in thelist is the matched string, same as what matchstr() wouldreturn. Following items are submatches, like "\1", "\2", etc.in:substitute. When an optional submatch didn't match anempty string is used. Example:
echo matchlist('acd', '\(a\)\?\(b\)\?\(c\)\?\(.*\)')
Results in: ['acd', 'a', '', 'c', 'd', '', '', '', '', '']When there is no match an empty list is returned.
You can pass in a List, but that is not very useful.
Parameters:
{expr} (any)
{pat} (string)
{start} (integer?)
{count} (integer?)
Return:
(string[])
matchstr({expr},{pat} [,{start} [,{count}]])matchstr()
Same asmatch(), but return the matched string. Example:
echo matchstr("testing", "ing")
results in "ing".When there is no match "" is returned.The{start}, if given, has the same meaning as formatch().
echo matchstr("testing", "ing", 2)
results in "ing".
echo matchstr("testing", "ing", 5)
result is "".When{expr} is aList then the matching item is returned.The type isn't changed, it's not necessarily a String.
Parameters:
{expr} (any)
{pat} (string)
{start} (integer?)
{count} (integer?)
Return:
(string)
matchstrlist({list},{pat} [,{dict}])matchstrlist()
Returns theList of matches in{list} where{pat} matches.{list} is aList of strings.{pat} is matched against eachstring in{list}.
The{dict} argument supports following items: submatchesinclude submatch information (/\()
For each match, aDict with the following items is returned: byteidxstarting byte index of the match. idxindex in{list} of the match. textmatched string submatchesa List of submatches. Present only if"submatches" is set to v:true in{dict}.
Seematch-pattern for information about the effect of someoption settings on the pattern.
Example:
echo matchstrlist(['tik tok'], '\<\k\+\>')
[{'idx': 0, 'byteidx': 0, 'text': 'tik'}, {'idx': 0, 'byteidx': 4, 'text': 'tok'}]
echo matchstrlist(['a', 'b'], '\<\k\+\>')
[{'idx': 0, 'byteidx': 0, 'text': 'a'}, {'idx': 1, 'byteidx': 0, 'text': 'b'}]
If "submatches" is present and is v:true, then submatches like"\1", "\2", etc. are also returned. Example:
echo matchstrlist(['acd'], '\(a\)\?\(b\)\?\(c\)\?\(.*\)',                            \ #{submatches: v:true})
[{'idx': 0, 'byteidx': 0, 'text': 'acd', 'submatches': ['a', '', 'c', 'd', '', '', '', '', '']}] The "submatches" List always contains 9 items. If a submatchis not found, then an empty string is returned for thatsubmatch.
Parameters:
{list} (string[])
{pat} (string)
{dict} (table?)
Return:
(string[])
matchstrpos({expr},{pat} [,{start} [,{count}]])matchstrpos()
Same asmatchstr(), but return the matched string, the startposition and the end position of the match. Example:
echo matchstrpos("testing", "ing")
results in ["ing", 4, 7].When there is no match ["", -1, -1] is returned.The{start}, if given, has the same meaning as formatch().
echo matchstrpos("testing", "ing", 2)
results in ["ing", 4, 7].
echo matchstrpos("testing", "ing", 5)
result is ["", -1, -1].When{expr} is aList then the matching item, the indexof first item where{pat} matches, the start position and theend position of the match are returned.
echo matchstrpos([1, '__x'], '\a')
result is ["x", 1, 2, 3].The type isn't changed, it's not necessarily a String.
Parameters:
{expr} (any)
{pat} (string)
{start} (integer?)
{count} (integer?)
Return:
(table)
max({expr})max()
Return the maximum value of all items in{expr}. Example:
echo max([apples, pears, oranges])
{expr} can be aList or aDictionary. 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 theitems in{expr} cannot be used as a Number this results inan error. An emptyList orDictionary results in zero.
Parameters:
{expr} (any)
Return:
(number)
menu_get({path} [,{modes}])menu_get()
Returns aList ofDictionaries describingmenus (definedby:menu,:amenu, …), includinghidden-menus.
{path} matches a menu by name, or all menus if{path} is anempty string. Example:
echo menu_get('File','')echo menu_get('')
{modes} is a string of zero or more modes (seemaparg() orcreating-menus for the list of modes). "a" means "all".
Example:
nnoremenu &Test.Test inormalinoremenu Test.Test insertvnoremenu Test.Test xecho menu_get("")
returns something like this:
[ {  "hidden": 0,  "name": "Test",  "priority": 500,  "shortcut": 84,  "submenus": [ {    "hidden": 0,    "mappings": {      i": {        "enabled": 1,        "noremap": 1,        "rhs": "insert",        "sid": 1,        "silent": 0      },      n": { ... },      s": { ... },      v": { ... }    },    "name": "Test",    "priority": 500,    "shortcut": 0  } ]} ]
Parameters:
{path} (string)
{modes} (string?)
Return:
(any)
menu_info({name} [,{mode}])menu_info()
Return information about the specified menu{name} inmode{mode}. The menu name should be specified without theshortcut character ('&'). If{name} is "", then the top-levelmenu names are returned.
{mode} can be one of these strings:"n"Normal"v"Visual (including Select)"o"Operator-pending"i"Insert"c"Cmd-line"s"Select"x"Visual"t"Terminal-Job""Normal, Visual and Operator-pending"!"Insert and Cmd-lineWhen{mode} is omitted, the modes for "" are used.
Returns aDictionary containing the following items: accelmenu item accelerator textmenu-text displaydisplay name (name without '&') enabledv:true if this menu item is enabledRefer to:menu-enable iconname of the icon file (for toolbar)toolbar-icon iconidxindex of a built-in icon modesmodes for which the menu is defined. Inaddition to the modes mentioned above, thesecharacters will be used:" "Normal, Visual and Operator-pending namemenu item name. noremenuv:true if the{rhs} of the menu item is notremappable else v:false. prioritymenu order prioritymenu-priority rhsright-hand-side of the menu item. The returnedstring has special characters translated likein the output of the ":menu" command listing.When the{rhs} of a menu item is empty, then"<Nop>" is returned. scriptv:true if script-local remapping of{rhs} isallowed else v:false. See:menu-script. shortcutshortcut key (character after '&' inthe menu name)menu-shortcut silentv:true if the menu item is createdwith<silent> argument:menu-silent submenusList containing the names ofall the submenus. Present only if the menuitem has submenus.
Returns an empty dictionary if the menu item is not found.
Examples:
echo menu_info('Edit.Cut')echo menu_info('File.Save', 'n')" Display the entire menu hierarchy in a bufferfunc ShowMenu(name, pfx)  let m = menu_info(a:name)  call append(line('$'), a:pfx .. m.display)  for child in m->get('submenus', [])    call ShowMenu(a:name .. '.' .. escape(child, '.'),                                \ a:pfx .. '    ')  endforendfuncnewfor topmenu in menu_info('').submenus  call ShowMenu(topmenu, '')endfor
Parameters:
{name} (string)
{mode} (string?)
Return:
(any)
min({expr})min()
Return the minimum value of all items in{expr}. Example:
echo min([apples, pears, oranges])
{expr} can be aList or aDictionary. 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 theitems in{expr} cannot be used as a Number this results inan error. An emptyList orDictionary results in zero.
Parameters:
{expr} (any)
Return:
(number)
mkdir({name} [,{flags} [,{prot}]])mkdir()E739Create directory{name}.
When{flags} is present it must be a string. An empty stringhas no effect.
{flags} can contain these character flags: "p"intermediate directories will be created as necessary "D"{name} will be deleted at the end of the currentfunction, but not recursively:defer "R"{name} will be deleted recursively at the end of thecurrent function:defer
Note that when{name} has more than one part and "p" is usedsome directories may already exist. Only the first one thatis created and what it contains is scheduled to be deleted.E.g. when using:
call mkdir('subdir/tmp/autoload', 'pR')
and "subdir" already exists then "subdir/tmp" will bescheduled for deletion, like with:
defer delete('subdir/tmp', 'rf')
If{prot} is given it is used to set the protection bits ofthe new directory. The default is 0o755 (rwxr-xr-x: r/w forthe user, readable for others). Use 0o700 to make itunreadable for others. This is used for the newly createddirectories. Note: umask is applied to{prot} (on Unix).Example:
call mkdir($HOME .. "/tmp/foo/bar", "p", 0o700)
This function is not available in thesandbox.
If you try to create an existing directory with{flags} set to"p" mkdir() will silently exit.
The function result is a Number, which is TRUE if the call wassuccessful or FALSE if the directory creation failed or partlyfailed.
Parameters:
{name} (string)
{flags} (string?)
{prot} (string?)
Return:
(integer)
mode([{expr}])mode()
Return a string that indicates the current mode.If{expr} is supplied and it evaluates to a non-zero Number ora non-empty String (non-zero-arg), then the full mode isreturned, otherwise only the first letter is returned.Also seestate().
n Normal no Operator-pending nov Operator-pending (forced charwiseo_v) noV Operator-pending (forced linewiseo_V) noCTRL-V Operator-pending (forced blockwiseo_CTRL-V)CTRL-V is one character niI Normal usingi_CTRL-O inInsert-mode niR Normal usingi_CTRL-O inReplace-mode niV Normal usingi_CTRL-O inVirtual-Replace-mode nt Normal interminal-emulator (insert goes toTerminal mode) ntT Normal usingt_CTRL-\_CTRL-O inTerminal-mode v Visual by character vs Visual by character usingv_CTRL-O in Select mode V Visual by line Vs Visual by line usingv_CTRL-O in Select modeCTRL-V Visual blockwiseCTRL-Vs Visual blockwise usingv_CTRL-O in Select mode s Select by character S Select by lineCTRL-S Select blockwise i Insert ic Insert mode completioncompl-generic ix Insert modei_CTRL-X completion R ReplaceR Rc Replace mode completioncompl-generic Rx Replace modei_CTRL-X completion Rv Virtual ReplacegR Rvc Virtual Replace mode completioncompl-generic Rvx Virtual Replace modei_CTRL-X completion c Command-line editing cr Command-line editing overstrike modec_<Insert> cv Vim Ex modegQ cvr Vim Ex mode while in overstrike modec_<Insert> r Hit-enter prompt rm The -- more -- prompt r? A:confirm query of some sort ! Shell or external command is executing t Terminal mode: keys go to the job
This is useful in the'statusline' option or RPC calls. Inmost other places it always returns "c" or "n".Note that in the future more modes and more specific modes maybe added. It's better not to compare the whole string but onlythe leading character(s).Also seevisualmode().
Parameters:
{expr} (any?)
Return:
(any)
msgpackdump({list} [,{type}])msgpackdump()
Convert a list of Vimscript objects to msgpack. Returned value is areadfile()-style list. When{type} contains "B", aBlob isreturned instead. Example:
call writefile(msgpackdump([{}]), 'fname.mpack', 'b')
or, using aBlob:
call writefile(msgpackdump([{}], 'B'), 'fname.mpack')
This will write the single 0x80 byte to afname.mpack file(dictionary with zero items is represented by 0x80 byte inmessagepack).
Limitations:E5004E50051.Funcrefs cannot be dumped.2. Containers that reference themselves cannot be dumped.3. Dictionary keys are always dumped as STR strings.4. Other strings andBlobs are always dumped as BIN strings.5. Points 3. and 4. do not apply tomsgpack-special-dicts.
Parameters:
{list} (any)
{type} (any?)
Return:
(any)
msgpackparse({data})msgpackparse()
Convert areadfile()-style list or aBlob to a list ofVimscript objects.Example:
let fname = expand('~/.config/nvim/shada/main.shada')let mpack = readfile(fname, 'b')let shada_objects = msgpackparse(mpack)
This will read ~/.config/nvim/shada/main.shada file toshada_objects list.
Limitations:1. Mapping ordering is not preserved unless messagepack mapping is dumped using generic mapping (msgpack-special-map).2. Since the parser aims to preserve all data untouched (except for 1.) some strings are parsed tomsgpack-special-dict format which is not convenient to use.msgpack-special-dict
Some messagepack strings may be parsed to specialdictionaries. Special dictionaries are dictionaries which
1. Contain exactly two keys:_TYPE and_VAL.2._TYPE key is one of the types found inv:msgpack_types variable.3. Value for_VAL has the following format (Key column contains name of the key fromv:msgpack_types):
KeyValue
nilZero, ignored when dumping. Not returned bymsgpackparse() sincev:null was introduced.booleanOne or zero. When dumping it is only checked thatvalue is aNumber. Not returned bymsgpackparse()sincev:true andv:false were introduced.integerList with four numbers: sign (-1 or 1), highest twobits, number with bits from 62nd to 31st, lowest 31bits. I.e. to get actual number one will need to usecode like
_VAL[0] * ((_VAL[1] << 62)           & (_VAL[2] << 31)           & _VAL[3])
Special dictionary with this type will appear inmsgpackparse() output under one of the followingcircumstances:1.Number is 32-bit and value is either above INT32_MAX or below INT32_MIN.2.Number is 64-bit and value is above INT64_MAX. It cannot possibly be below INT64_MIN because msgpack C parser does not support such values.floatFloat. This value cannot possibly appear inmsgpackparse() output.stringString, orBlob if binary string contains zerobyte. This value cannot appear inmsgpackparse()output since blobs were introduced.arrayList. This value cannot appear inmsgpackparse()output.msgpack-special-map
mapList ofLists with two items (key and value) each.This value will appear inmsgpackparse() output ifparsed mapping contains one of the following keys:1. Any key that is not a string (including keys which are binary strings).2. String with NUL byte inside.3. Duplicate key.extList with two values: first is a signed integerrepresenting extension type. Second isreadfile()-style list of strings.
Parameters:
{data} (any)
Return:
(any)
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" | endif
When{lnum} is invalid or there is no non-blank line at orbelow it, zero is returned.{lnum} is used like withgetline().See alsoprevnonblank().
Parameters:
{lnum} (integer|string)
Return:
(integer)
nr2char({expr} [,{utf8}])nr2char()
Return a string with a single character, which has the numbervalue{expr}. Examples:
echo nr2char(64)" returns '@'echo nr2char(32)" returns ' '
Example for "utf-8":
echo nr2char(300)" returns I with bow character
UTF-8 encoding is always used,{utf8} option has no effect,and exists only for backwards-compatibility.Note that a NUL character in the file is specified withnr2char(10), because NULs are represented with newlinecharacters. nr2char(0) is a real NUL and terminates thestring, thus results in an empty string.
Parameters:
{expr} (integer)
{utf8} (boolean?)
Return:
(string)
nvim_...({...})nvim_...()E5555eval-apiCall nvimapi functions. The type checking of arguments willbe stricter than for most other builtins. For instance,if Integer is expected, aNumber must be passed in, aString will not be autoconverted.Buffer numbers, as returned bybufnr() could be used asfirst argument to nvim_buf_... functions. All functionsexpecting an object (buffer, window or tabpage) canalso take the numerical value 0 to indicate the current(focused) object.
Parameters:
{...} (any)
Return:
(any)
or({expr},{expr})or()
Bitwise OR on the two arguments. The arguments are convertedto a number. A List, Dict or Float argument causes an error.Also seeand() andxor().Example:
let bits = or(bits, 0x80)
Rationale: The reason this is a function and not using the "|"character like many languages, is that Vi has always used "|"to separate commands. In many places it would not be clear if"|" is an operator or a command separator.
Parameters:
{expr} (number)
{expr1} (number)
Return:
(any)
pathshorten({path} [,{len}])pathshorten()
Shorten directory names in the path{path} and return theresult. The tail, the file name, is kept as-is. The othercomponents in the path are reduced to{len} letters in length.If{len} is omitted or smaller than 1 then 1 is used (singleletters). Leading '~' and '.' characters are kept. Examples:
echo pathshorten('~/.config/nvim/autoload/file1.vim')
~/.c/n/a/file1.vim
echo pathshorten('~/.config/nvim/autoload/file2.vim', 2)
~/.co/nv/au/file2.vim
It doesn't matter if the path exists or not.Returns an empty string on error.
Parameters:
{path} (string)
{len} (integer?)
Return:
(string)
perleval({expr})perleval()
Evaluateperl expression{expr} and return its resultconverted to Vim data structures.Numbers and strings are returned as they are (strings arecopied though).Lists are represented as VimList type.Dictionaries are represented as VimDictionary type,non-string keys result in error.
Note: If you want an array or hash,{expr} must return areference to it.Example:
echo perleval('[1 .. 4]')
[1, 2, 3, 4]
Parameters:
{expr} (any)
Return:
(any)
pow({x},{y})pow()
Return the power of{x} to the exponent{y} as aFloat.{x} and{y} must evaluate to aFloat or aNumber.Returns 0.0 if{x} or{y} is not aFloat or aNumber.Examples:
echo pow(3, 3)
27.0
echo pow(2, 16)
65536.0
echo pow(32, 0.20)
2.0
Parameters:
{x} (number)
{y} (number)
Return:
(number)
preinserted()preinserted()
Returns non-zero if text has been inserted after the cursorbecause "preinsert" is present in'completeopt', or because"longest" is present in'completeopt' while'autocomplete'is active. Otherwise returns zero.
Return:
(number)
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 orabove it, zero is returned.{lnum} is used like withgetline().Also seenextnonblank().
Parameters:
{lnum} (integer|string)
Return:
(integer)
printf({fmt},{expr1} ...)printf()
Return a String with{fmt}, where "%" items are replaced bythe formatted form of their respective arguments. Example:
echo printf("%4d: E%d %.30s", lnum, errno, msg)
May result in:
" 99: E42 asdfasdfasdfasdfasdfasdfasdfas"
When used as amethod the base is passed as the secondargument:
Compute()->printf("result: %d")
You can usecall() to pass the items as a list.
Often used items are: %sstring %6Sstring right-aligned in 6 display cells %6sstring right-aligned in 6 bytes %.9sstring truncated to 9 bytes %csingle byte %ddecimal number %5ddecimal number padded with spaces to 5 characters %bbinary number %08bbinary number padded with zeros to at least 8 characters %Bbinary number using upper case letters %xhex number %04xhex number padded with zeros to at least 4 characters %Xhex number using upper case letters %ooctal number %ffloating point number as 12.23, inf, -inf or nan %Ffloating point number as 12.23, INF, -INF or NAN %efloating point number as 1.23e3, inf, -inf or nan %Efloating point number as 1.23E3, INF, -INF or NAN %gfloating point number, as %f or %e depending on value %Gfloating point number, as %F or %E depending on value %%the % character itself %prepresentation of the pointer to the container
Conversion specifications start with '%' and end with theconversion type. All other characters are copied unchanged tothe result.
The "%" starts a conversion specification. The followingarguments appear in sequence:
% [pos-argument] [flags] [field-width] [.precision] type
pos-argumentAt most one positional argument specifier. Thesetake the form{n$}, where n is >= 1.
flagsZero or more of the following flags:
# The value should be converted to an "alternate form". For c, d, and s conversions, this option has no effect. For o conversions, the precision of the number is increased to force the first character of the output string to a zero (except if a zero value is printed with an explicit precision of zero). For x and X conversions, a non-zero result has the string "0x" (or "0X" for X conversions) prepended to it.
0 (zero) Zero padding. For all conversions the converted value is padded on the left with zeros rather than blanks. If a precision is given with a numeric conversion (d, o, x, and X), the 0 flag is ignored.
- A negative field width flag; the converted value is to be left adjusted on the field boundary. The converted value is padded on the right with blanks, rather than on the left with blanks or zeros. A - overrides a 0 if both are given.
' ' (space) A blank should be left before a positive number produced by a signed conversion (d).
+ A sign must always be placed before a number produced by a signed conversion. A + overrides a space if both are used.
field-widthAn optional decimal digit string specifying a minimumfield width. If the converted value has fewer bytesthan the field width, it will be padded with spaces onthe left (or right, if the left-adjustment flag hasbeen given) to fill out the field width. For the Sconversion the count is in cells.
.precisionAn optional precision, in the form of a period '.'followed by an optional digit string. If the digitstring is omitted, the precision is taken as zero.This gives the minimum number of digits to appear ford, o, x, and X conversions, the maximum number ofbytes to be printed from a string for s conversions,or the maximum number of cells to be printed from astring for S conversions.For floating point it is the number of digits afterthe decimal point.
typeA character that specifies the type of conversion tobe applied, see below.
A field width or precision, or both, may be indicated by anasterisk "*" instead of a digit string. In this case, aNumber argument supplies the field width or precision. Anegative field width is treated as a left adjustment flagfollowed by a positive field width; a negative precision istreated as though it were missing. Example:
echo printf("%d: %.*s", nr, width, line)
This limits the length of the text used from "line" to"width" bytes.
If the argument to be formatted is specified using apositional argument specifier, and a '*' is used to indicatethat a number argument is to be used to specify the width orprecision, the argument(s) to be used must also be specifiedusing a{n$} positional argument specifier. Seeprintf-$.
The conversion specifiers and their meanings are:
printf-dprintf-bprintf-Bprintf-oprintf-xprintf-XdbBoxXThe Number argument is converted to signed decimal (d),unsigned binary (b and B), unsigned octal (o), orunsigned hexadecimal (x and X) notation. The letters"abcdef" are used for x conversions; the letters"ABCDEF" are used for X conversions. The precision, ifany, gives the minimum number of digits that mustappear; if the converted value requires fewer digits, itis padded on the left with zeros. In no case does anon-existent or small field width cause truncation of anumeric field; if the result of a conversion is widerthan the field width, the field is expanded to containthe conversion result.The 'h' modifier indicates the argument is 16 bits.The 'l' modifier indicates the argument is a longinteger. The size will be 32 bits or 64 bitsdepending on your platform.The "ll" modifier indicates the argument is 64 bits.The b and B conversion specifiers never take a widthmodifier and always assume their argument is a 64 bitinteger.Generally, these modifiers are not useful. They areignored when type is known from the argument.
ialias for dDalias for ldUalias for luOalias for lo
printf-c
cThe Number argument is converted to a byte, and theresulting character is written.
printf-s
sThe text of the String argument is used. If aprecision is specified, no more bytes than the numberspecified are used.If the argument is not a String type, it isautomatically converted to text with the same formatas ":echo".printf-S
SThe text of the String argument is used. If aprecision is specified, no more display cells than thenumber specified are used.
printf-fE807f FThe Float argument is converted into a string of theform 123.456. The precision specifies the number ofdigits after the decimal point. When the precision iszero the decimal point is omitted. When the precisionis 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.12Note that roundoff depends on the system libraries.Useround() when in doubt.
printf-eprintf-Ee EThe Float argument is converted into a string of theform 1.234e+03 or 1.234E+03 when using 'E'. Theprecision specifies the number of digits after thedecimal point, like with 'f'.
printf-gprintf-Gg GThe Float argument is converted like with 'f' if thevalue is between 0.001 (inclusive) and 10000000.0(exclusive). Otherwise 'e' is used for 'g' and 'E'for 'G'. When no precision is specified superfluouszeroes and '+' signs are removed, except for the zeroimmediately after the decimal point. Thus 10000000.0results in 1.0e7.
printf-%
%A '%' is written. No argument is converted. Thecomplete conversion specification is "%%".
When a Number argument is expected a String argument is alsoaccepted and automatically converted.When a Float or String argument is expected a Number argumentis also accepted and automatically converted.Any other argument type results in an error message.
E766E767The number of{exprN} arguments must exactly match the numberof "%" items. If there are not sufficient or too manyarguments an error is given. Up to 18 arguments can be used.
printf-$
In certain languages, error and informative messages aremore readable when the order of words is different from thecorresponding message in English. To accommodate translationshaving a different word order, positional arguments may beused to indicate this. For instance:
#, c-formatmsgid "%s returning %s"msgstr "waarde %2$s komt terug van %1$s"
In this example, the sentence has its 2 string argumentsreversed in the output.
echo printf(    "In The Netherlands, vim's creator's name is: %1$s %2$s",    "Bram", "Moolenaar")
In The Netherlands, vim's creator's name is: Bram Moolenaar
echo printf(    "In Belgium, vim's creator's name is: %2$s %1$s",    "Bram", "Moolenaar")
In Belgium, vim's creator's name is: Moolenaar Bram
Width (and precision) can be specified using the '*' specifier.In this case, you must specify the field width position in theargument list.
echo printf("%1$*2$.*3$d", 1, 2, 3)
001
echo printf("%2$*3$.*1$d", 1, 2, 3)
2
echo printf("%3$*1$.*2$d", 1, 2, 3)
03
echo printf("%1$*2$.*3$g", 1.4142, 2, 3)
1.414
You can mix specifying the width and/or precision directlyand via positional arguments:
echo printf("%1$4.*2$f", 1.4142135, 6)
1.414214
echo printf("%1$*2$.4f", 1.4142135, 6)
1.4142
echo printf("%1$*2$.*3$f", 1.4142135, 6, 2)
1.41
You will get an overflow errorE1510, when the field-widthor precision will result in a string longer than 1 MB(1024*1024 = 1048576) chars.
E1500
You cannot mix positional and non-positional arguments:
echo printf("%s%1$s", "One", "Two")
E1500: Cannot mix positional and non-positional arguments: %s%1$s
E1501
You cannot skip a positional argument in a format string:
echo printf("%3$s%1$s", "One", "Two", "Three")
E1501: format argument 2 unused in $-style format: %3$s%1$s
E1502
You can re-use a [field-width] (or [precision]) argument:
echo printf("%1$d at width %2$d is: %01$*2$d", 1, 2)
1 at width 2 is: 01
However, you can't use it as a different type:
echo printf("%1$d at width %2$ld is: %01$*2$d", 1, 2)
E1502: Positional argument 2 used as field width reused as different type: long int/int
E1503
When a positional argument is used, but not the correct numberor arguments is given, an error is raised:
echo printf("%1$d at width %2$d is: %01$*2$.*3$d", 1, 2)
E1503: Positional argument 3 out of bounds: %1$d at width %2$d is: %01$*2$.*3$d
Only the first error is reported:
echo printf("%01$*2$.*3$d %4$d", 1, 2)
E1503: Positional argument 3 out of bounds: %01$*2$.*3$d %4$d
E1504
A positional argument can be used more than once:
echo printf("%1$s %2$s %1$s", "One", "Two")
One Two One
However, you can't use a different type the second time:
echo printf("%1$s %2$s %1$d", "One", "Two")
E1504: Positional argument 1 type used inconsistently: int/string
E1505
Various other errors that lead to a format string beingwrongly formatted lead to:
echo printf("%1$d at width %2$d is: %01$*2$.3$d", 1, 2)
E1505: Invalid format specifier: %1$d at width %2$d is: %01$*2$.3$d
E1507
This internal error indicates that the logic to parse apositional format argument ran into a problem that couldn't beotherwise reported. Please file a bug against Vim if you runinto this, copying the exact format string and parameters thatwere used.
Parameters:
{fmt} (string)
{expr1} (any?)
Return:
(string)
prompt_getinput({buf})prompt_getinput()
Gets the current user-input inprompt-buffer{buf} without invokingprompt_callback.{buf} can be a buffer name or number.
If the buffer doesn't exist or isn't a prompt buffer, an emptystring is returned.
Parameters:
{buf} (integer|string)
Return:
(any)
prompt_getprompt({buf})prompt_getprompt()
Returns the effective prompt text for buffer{buf}.{buf} canbe a buffer name or number. Seeprompt-buffer.
If the buffer doesn't exist or isn't a prompt buffer, an emptystring is returned.
Parameters:
{buf} (integer|string)
Return:
(any)
prompt_setcallback({buf},{expr})prompt_setcallback()
Set prompt callback for buffer{buf} to{expr}. When{expr}is an empty string the callback is removed. This has onlyeffect if{buf} has'buftype' set to "prompt".
The callback is invoked when pressing Enter. The currentbuffer will always be the prompt buffer. A new line for aprompt is added before invoking the callback, thus the promptfor which the callback was invoked will be in the last but oneline.If the callback wants to add text to the buffer, it mustinsert it above the last line, since that is where the currentprompt is. This can also be done asynchronously.The callback is invoked with one argument, which is the textthat was entered at the prompt. This can be an empty stringif the user only typed Enter.Example:
func s:TextEntered(text)  if a:text == 'exit' || a:text == 'quit'    stopinsert    " Reset 'modified' to allow the buffer to be closed.    " We assume there is nothing useful to be saved.    set nomodified    close  else    " Do something useful with "a:text".  In this example    " we just repeat it.    call append(line('$') - 1, 'Entered: "' .. a:text .. '"')  endifendfunccall prompt_setcallback(bufnr(), function('s:TextEntered'))
Parameters:
{buf} (integer|string)
{expr} (string|function)
Return:
(any)
prompt_setinterrupt({buf},{expr})prompt_setinterrupt()
Set a callback for buffer{buf} to{expr}. When{expr} is anempty string the callback is removed. This has only effect if{buf} has'buftype' set to "prompt".
This callback will be invoked when pressingCTRL-C in Insertmode. Without setting a callback Vim will exit Insert mode,as in any buffer.
Parameters:
{buf} (integer|string)
{expr} (string|function)
Return:
(any)
prompt_setprompt({buf},{text})prompt_setprompt()
Set prompt for buffer{buf} to{text}. You most likely want{text} to end in a space.The result is only visible if{buf} has'buftype' set to"prompt". Example:
call prompt_setprompt(bufnr(''), 'command: ')
Parameters:
{buf} (integer|string)
{text} (string)
Return:
(any)
pum_getpos()pum_getpos()
If the popup menu (seeins-completion-menu) is not visible,returns an emptyDictionary, otherwise, returns aDictionary with the following keys:heightnr of items visiblewidthscreen cellsrowtop screen row (0 first row)colleftmost screen column (0 first col)sizetotal nr of itemsscrollbarTRUE if scrollbar is visible
The values are the same as inv:event duringCompleteChanged.
Return:
(any)
pumvisible()pumvisible()
Returns non-zero when the popup menu is visible, zerootherwise. Seeins-completion-menu.This can be used to avoid some things that would remove thepopup menu.
Return:
(any)
py3eval({expr})py3eval()
Evaluate Python expression{expr} and return its resultconverted to Vim data structures.Numbers and strings are returned as they are (strings arecopied though, Unicode strings are additionally converted toUTF-8).Lists are represented as VimList type.Dictionaries are represented as VimDictionary type withkeys converted to strings.
Parameters:
{expr} (any)
Return:
(any)
pyeval({expr})pyeval()E858E859Evaluate Python expression{expr} and return its resultconverted to Vim data structures.Numbers and strings are returned as they are (strings arecopied though).Lists are represented as VimList type.Dictionaries are represented as VimDictionary type,non-string keys result in error.
Parameters:
{expr} (any)
Return:
(any)
pyxeval({expr})pyxeval()
Evaluate Python expression{expr} and return its resultconverted to Vim data structures.Uses Python 2 or 3, seepython_x and'pyxversion'.See also:pyeval(),py3eval()
Parameters:
{expr} (any)
Return:
(any)
rand([{expr}])rand()
Return a pseudo-random Number generated with an xoshiro128**algorithm using seed{expr}. The returned number is 32 bits,also on 64 bits systems, for consistency.{expr} can be initialized bysrand() and will be updated byrand(). If{expr} is omitted, an internal seed value is usedand updated.Returns -1 if{expr} is invalid.
Examples:
echo rand()let seed = srand()echo rand(seed)echo rand(seed) % 16  " random number 0 - 15
Parameters:
{expr} (number?)
Return:
(any)
range({expr} [,{max} [,{stride}]])range()E726E727Returns aList 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 anempty list. When the maximum is more than one before thestart this is an error.Examples:
echo range(4)" [0, 1, 2, 3]echo range(2, 4)" [2, 3, 4]echo range(2, 9, 3)" [2, 5, 8]echo range(2, -2, -1)" [2, 1, 0, -1, -2]echo range(0)" []echo range(2, 0)" error!
Parameters:
{expr} (any)
{max} (integer?)
{stride} (integer?)
Return:
(any)
readblob({fname} [,{offset} [,{size}]])readblob()
Read file{fname} in binary mode and return aBlob.If{offset} is specified, read the file from the specifiedoffset. If it is a negative value, it is used as an offsetfrom the end of the file. E.g., to read the last 12 bytes:
echo readblob('file.bin', -12)
If{size} is specified, only the specified size will be read.E.g. to read the first 100 bytes of a file:
echo readblob('file.bin', 0, 100)
If{size} is -1 or omitted, the whole data starting from{offset} will be read.This can be also used to read the data from a character deviceon Unix when{size} is explicitly set. Only if the devicesupports seeking{offset} can be used. Otherwise it should bezero. E.g. to read 10 bytes from a serial console:
echo readblob('/dev/ttyS0', 0, 10)
When the file can't be opened an error message is given andthe result is an emptyBlob.When the offset is beyond the end of the file the result is anempty blob.When trying to read more bytes than are available the resultis truncated.Also seereadfile() andwritefile().
Parameters:
{fname} (string)
{offset} (integer?)
{size} (integer?)
Return:
(any)
readdir({directory} [,{expr}])readdir()
Return a list with file and directory names in{directory}.You can also useglob() if you don't need to do complicatedthings, 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 willbe handled.If{expr} results in 0 then this entry will not beadded to the list.If{expr} results in 1 then this entry will be addedto the list.Each time{expr} is evaluatedv: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":
echo readdir(dirname, {n -> n =~ '.txt$'})
To skip hidden and backup files:
echo readdir(dirname, {n -> n !~ '^\.\|\~$'})
If you want to get a directory tree:
function! s:tree(dir)    return {a:dir : map(readdir(a:dir),    \ {_, x -> isdirectory(x) ?    \          {x : s:tree(a:dir .. '/' .. x)} : x})}endfunctionecho s:tree(".")
Returns an empty List on error.
Parameters:
{directory} (string)
{expr} (integer?)
Return:
(any)
readfile({fname} [,{type} [,{max}]])readfile()
Read file{fname} and return aList, each line of the fileas an item. Lines are broken at NL characters. Macintoshfiles separated with CR will result in a single long line(unless a NL appears somewhere).All NUL characters are replaced with a NL character.When{type} contains "b" binary mode is used:
When the last line ends in a NL an extra empty list item is added.
No CR characters are removed.Otherwise:
CR characters that appear before a NL are removed.
Whether the last line ends in a NL or not does not matter.
Any UTF-8 byte order mark is removed from the text.When{max} is given this specifies the maximum number of linesto be read. Useful if you only want to check the first tenlines of a file:
for line in readfile(fname, '', 10)  if line =~ 'Date' | echo line | endifendfor
When{max} is negative -{max} lines from the end of the fileare returned, or as many as there are.When{max} is zero the result is an empty list.Note that without{max} the whole file is read into memory.Also note that there is no recognition of encoding. Read afile into a buffer if you need to.Deprecated (usereadblob() instead): When{type} contains"B" aBlob is returned with the binary data of the fileunmodified.When the file can't be opened an error message is given andthe result is an empty list.Also seewritefile().
Parameters:
{fname} (string)
{type} (string?)
{max} (integer?)
Return:
(string[])
reduce({object},{func} [,{initial}])reduce()E998{func} is called for every item in{object}, which can be aString,List or aBlob.{func} is called with twoarguments: the result so far and current item. Afterprocessing all items the result is returned.
{initial} is the initial result. When omitted, the first itemin{object} is used and{func} is first called for the seconditem. If{initial} is not given and{object} is empty noresult can be computed, an E998 error is given.
Examples:
echo reduce([1, 3, 5], { acc, val -> acc + val })echo reduce(['x', 'y'], { acc, val -> acc .. val }, 'a')echo reduce(0z1122, { acc, val -> 2 * acc + val })echo reduce('xyz', { acc, val -> acc .. ',' .. val })
Parameters:
{object} (any)
{func} (fun(accumulator: T, current: any): any)
{initial} (any?)
Return:
(T)
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@.
Return:
(any)
reg_recorded()reg_recorded()
Returns the single letter name of the last recorded register.Returns an empty string when nothing was recorded yet.Seeq andQ.
Return:
(any)
reg_recording()reg_recording()
Returns the single letter name of the register being recorded.Returns an empty string when not recording. Seeq.
Return:
(any)
reltime()reltime()
reltime({start})reltime({start},{end})Return an item that represents a time value. The item is alist with items that depend on the system.The item can be passed toreltimestr() to convert it to astring orreltimefloat() to convert to a Float.
Without an argument it returns the current "relative time", animplementation-defined value meaningful only when used as anargument toreltime(),reltimestr() andreltimefloat().
With one argument it returns the time passed since the timespecified in the argument.With two arguments it returns the time passed between{start}and{end}.
The{start} and{end} arguments must be values returned byreltime(). Returns zero on error.
Note:localtime() returns the current (non-relative) time.
Parameters:
{start} (any?)
{end} (any?)
Return:
(any)
reltimefloat({time})reltimefloat()
Return a Float that represents the time value of{time}.Unit of time is seconds.Example:let start = reltime()call MyFunction()let seconds = reltimefloat(reltime(start))See the note of reltimestr() about overhead.Also seeprofiling.If there is an error an empty string is returned
Parameters:
{time} (any)
Return:
(any)
reltimestr({time})reltimestr()
Return a String that represents the time value of{time}.This is the number of seconds, a dot and the number ofmicroseconds. Example:
let start = reltime()call MyFunction()echo reltimestr(reltime(start))
Note that overhead for the commands will be added to the time.Leading spaces are used to make the string align nicely. Youcan use split() to remove it.
echo split(reltimestr(reltime(start)))[0]
Also seeprofiling.If there is an error an empty string is returned
Parameters:
{time} (any)
Return:
(any)
remove({list},{idx})remove()
remove({list},{idx},{end})Without{end}: Remove the item at{idx} fromList{list} andreturn the item.With{end}: Remove items from{idx} to{end} (inclusive) andreturn aList with these items. When{idx} points to the sameitem as{end} a list with one item is returned. When{end}points to an item before{idx} this is an error.Seelist-index for possible values of{idx} and{end}.Returns zero on error.Example:
echo "last item: " .. remove(mylist, -1)call remove(mylist, 0, 9)
Usedelete() to remove a file.
Parameters:
{list} (any[])
{idx} (integer)
{end} (integer?)
Return:
(any)
remove({blob},{idx})remove({blob},{idx},{end})Without{end}: Remove the byte at{idx} fromBlob{blob} andreturn the byte.With{end}: Remove bytes from{idx} to{end} (inclusive) andreturn aBlob with these bytes. When{idx} points to the samebyte as{end} aBlob with one byte is returned. When{end}points to a byte before{idx} this is an error.Returns zero on error.Example:
echo "last byte: " .. remove(myblob, -1)call remove(mylist, 0, 9)
Parameters:
{blob} (any)
{idx} (integer)
{end} (integer?)
Return:
(any)
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.Returns zero on error.
Parameters:
{dict} (any)
{key} (string)
Return:
(any)
rename({from},{to})rename()
Rename the file by the name{from} to the name{to}. Thisshould also work to move files across file systems. Theresult is a Number, which is 0 if the file was renamedsuccessfully, and non-zero when the renaming failed.NOTE: If{to} exists it is overwritten without warning.This function is not available in thesandbox.
Parameters:
{from} (string)
{to} (string)
Return:
(integer)
repeat({expr},{count})repeat()
Repeat{expr}{count} times and return the concatenatedresult. Example:
let separator = repeat('-', 80)
When{count} is zero or negative the result is empty.When{expr} is aList or aBlob the result is{expr}concatenated{count} times. Example:
let longlist = repeat(['a', 'b'], 3)
Results in ['a', 'b', 'a', 'b', 'a', 'b'].
Parameters:
{expr} (any)
{count} (integer)
Return:
(any)
resolve({filename})resolve()E655On MS-Windows, when{filename} is a shortcut (a .lnk file),returns the path the shortcut points to in a simplified form.On Unix, repeat resolving symbolic links in all pathcomponents of{filename} and return the simplified result.To cope with link cycles, resolving of symbolic links isstopped after 100 iterations.On other systems, return the simplified{filename}.The simplification step is done as bysimplify().resolve() keeps a leading path component specifying thecurrent directory (provided the result is still a relativepath name) and also keeps a trailing path separator.
Parameters:
{filename} (string)
Return:
(string)
reverse({object})reverse()
Reverse the order of items in{object}.{object} can be aList, aBlob or aString. For a List and a Blob theitems are reversed in-place and{object} is returned.For a String a new String is returned.Returns zero if{object} is not a List, Blob or a String.If you want a List or Blob to remain unmodified make a copyfirst:
let revlist = reverse(copy(mylist))
Parameters:
{object} (T[])
Return:
(T[])
round({expr})round()
Round off{expr} to the nearest integral value and return itas aFloat. If{expr} lies halfway between two integralvalues, then use the larger one (away from zero).{expr} must evaluate to aFloat or aNumber.Returns 0.0 if{expr} is not aFloat or aNumber.Examples:
echo round(0.456)
0.0
echo round(4.5)
5.0
echo round(-4.5)
-5.0
Parameters:
{expr} (number)
Return:
(number)
rpcnotify({channel},{event} [,{args}...])rpcnotify()
Sends{event} to{channel} viaRPC and returns immediately.If{channel} is 0, the event is broadcast to all channels.Example:
au VimLeave call rpcnotify(0, "leaving")
Parameters:
{channel} (integer)
{event} (string)
{...} (any)
Return:
(integer)
rpcrequest({channel},{method} [,{args}...])rpcrequest()
Sends a request to{channel} to invoke{method} viaRPC and blocks until a response is received.Example:
let result = rpcrequest(rpc_chan, "func", 1, 2, 3)
Parameters:
{channel} (integer)
{method} (string)
{...} (any)
Return:
(any)
rubyeval({expr})rubyeval()
Evaluate Ruby expression{expr} and return its resultconverted to Vim data structures.Numbers, floats and strings are returned as they are (stringsare copied though).Arrays are represented as VimList type.Hashes are represented as VimDictionary type.Other objects are represented as strings resulted from their"Object#to_s" method.
Parameters:
{expr} (any)
Return:
(any)
screenattr({row},{col})screenattr()
Likescreenchar(), but return the attribute. This is a ratherarbitrary number that can only be used to compare to theattribute at other positions.Returns -1 when row or col is out of range.
Parameters:
{row} (integer)
{col} (integer)
Return:
(integer)
screenchar({row},{col})screenchar()
The result is a Number, which is the character at position[row, col] on the screen. This works for every possiblescreen position, also status lines, window separators and thecommand line. The top left position is row one, column oneThe character excludes composing characters. For double-byteencodings it may only be the first byte.This is mainly to be used for testing.Returns -1 when row or col is out of range.
Parameters:
{row} (integer)
{col} (integer)
Return:
(integer)
screenchars({row},{col})screenchars()
The result is aList of Numbers. The first number is the sameas whatscreenchar() returns. Further numbers arecomposing characters on top of the base character.This is mainly to be used for testing.Returns an empty List when row or col is out of range.
Parameters:
{row} (integer)
{col} (integer)
Return:
(integer[])
screencol()screencol()
The result is a Number, which is the current screen column ofthe cursor. The leftmost column has number 1.This function is mainly used for testing.
Note: Always returns the current screen column, thus if usedin a command (e.g. ":echo screencol()") it will return thecolumn inside the command line, which is 1 when the command isexecuted. To get the cursor position in the file use one ofthe following mappings:
nnoremap <expr> GG ":echom " .. screencol() .. "\n"nnoremap <silent> GG :echom screencol()<CR>noremap GG <Cmd>echom screencol()<CR>
Return:
(integer[])
screenpos({winid},{lnum},{col})screenpos()
The result is a Dict with the screen position of the textcharacter in window{winid} at buffer line{lnum} and column{col}.{col} is a one-based byte index.The Dict has these members:rowscreen rowcolfirst screen columnendcollast screen columncurscolcursor screen columnIf the specified position is not visible, all values are zero.The "endcol" value differs from "col" when the characteroccupies more than one screen cell. E.g. for a Tab "col" canbe 1 and "endcol" can be 8.The "curscol" value is where the cursor would be placed. Fora Tab it would be the same as "endcol", while for a doublewidth character it would be the same as "col".Theconceal feature is ignored here, the column numbers areas if'conceallevel' is zero. You can set the cursor to theright position and usescreencol() to get the value withconceal taken into account.If the position is in a closed fold the screen position of thefirst character is returned,{col} is not used.Returns an empty Dict if{winid} is invalid.
Parameters:
{winid} (integer)
{lnum} (integer)
{col} (integer)
Return:
(any)
screenrow()screenrow()
The result is a Number, which is the current screen row of thecursor. The top line has number one.This function is mainly used for testing.Alternatively you can usewinline().
Note: Same restrictions as withscreencol().
Return:
(integer)
screenstring({row},{col})screenstring()
The result is a String that contains the base character andany composing characters at position [row, col] on the screen.This is likescreenchars() but returning a String with thecharacters.This is mainly to be used for testing.Returns an empty String when row or col is out of range.
Parameters:
{row} (integer)
{col} (integer)
Return:
(string)
search({pattern} [,{flags} [,{stopline} [,{timeout} [,{skip}]]]])search()Search for regexp pattern{pattern}. The search starts at thecursor position (you can usecursor() to set it).
When a match has been found its line number is returned.If there is no match a 0 is returned and the cursor doesn'tmove. No error message is given.To get the matched string, usematchbufline().
{flags} is a String, which can contain these character flags:'b'search Backward instead of forward'c'accept a match at the Cursor position'e'move to the End of the match'n'do Not move the cursor'p'return number of matching sub-Pattern (see below)'s'Set the ' mark at the previous location of the cursor'w'Wrap around the end of the file'W'don't Wrap around the end of the file'z'start searching at the cursor column instead of ZeroIf neither 'w' or 'W' is given, the'wrapscan' option applies.
If the 's' flag is supplied, the ' mark is set, only if thecursor is moved. The 's' flag cannot be combined with the 'n'flag.
'ignorecase','smartcase' and'magic' are used.
When the 'z' flag is not given, forward searching alwaysstarts in column zero and then matches before the cursor areskipped. When the 'c' flag is present in'cpo' the nextsearch starts after the match. Without the 'c' flag the nextsearch starts one column after the start of the match. Thismatters for overlapping matches. Seecpo-c. You can alsoinsert "\ze" to change where the match ends, see/\ze.
When searching backwards and the 'z' flag is given then thesearch starts in column zero, thus no match in the currentline will be found (unless wrapping around the end of thefile).
When the{stopline} argument is given then the search stopsafter searching this line. This is useful to restrict thesearch to a range of lines. Examples:
let match = search('(', 'b', line("w0"))let end = search('END', '', line("w$"))
When{stopline} is used and it is not zero this also impliesthat the search does not wrap around the end of the file.A zero value is equal to not giving the argument.
When the{timeout} argument is given the search stops whenmore than this many milliseconds have passed. Thus when{timeout} is 500 the search stops after half a second.The value must not be negative. A zero value is like notgiving the argument.
Note: the timeout is only considered when searching, notwhile evaluating the{skip} expression.
If the{skip} expression is given it is evaluated with thecursor positioned on the start of a match. If it evaluates tonon-zero this match is skipped. This can be used, forexample, to skip a match in a comment or a string.{skip} can be a string, which is evaluated as an expression, afunction reference or a lambda.When{skip} is omitted or empty, every match is accepted.When evaluating{skip} causes an error the search is abortedand -1 returned.search()-sub-match
With the 'p' flag the returned value is one more than thefirst sub-match in \(\). One if none of them matched but thewhole pattern did match.To get the column number too usesearchpos().
The cursor will be positioned at the match, unless the 'n'flag is used.
Example (goes over all files in the argument list):
let n = 1while n <= argc()    " loop over all files in arglist  exe "argument " .. n  " start at the last char in the file and wrap for the  " first search to find match at start of file  normal G$  let flags = "w"  while search("foo", flags) > 0    s/foo/bar/g    let flags = "W"  endwhile  update    " write the file if modified  let n = n + 1endwhile
Example for using some flags:
echo search('\<if\|\(else\)\|\(endif\)', 'ncpe')
This will search for the keywords "if", "else", and "endif"under or after the cursor. Because of the 'p' flag, itreturns 1, 2, or 3 depending on which keyword is found, or 0if the search fails. With the cursor on the first word of theline:
if (foo == 0) | let foo = foo + 1 | endif
the function returns 1. Without the 'c' flag, the functionfinds the "endif" and returns 3. The same thing happenswithout the 'e' flag if the cursor is on the "f" of "if".The 'n' flag tells the function not to move the cursor.
Parameters:
{pattern} (string)
{flags} (string?)
{stopline} (integer?)
{timeout} (integer?)
{skip} (string|function?)
Return:
(integer)
searchcount([{options}])searchcount()
Get or update the last search count, like what is displayedwithout the "S" flag in'shortmess'. This works even if'shortmess' does contain the "S" flag.
This returns aDictionary. The dictionary is empty if theprevious pattern was not set and "pattern" was not specified.
keytypemeaning
currentNumber current position of match;0 if the cursor position isbefore the first match exact_matchBoolean 1 if "current" is matched on"pos", otherwise 0 totalNumber total count of matches found incompleteNumber 0: search was fully completed1: recomputing was timed out2: max count exceeded
For{options} see further down.
To get the last search count whenn orN was pressed, callthis function withrecompute: 0 . This sometimes returnswrong information because of'maxsearchcount'.If the count exceeded'maxsearchcount', the result must be'maxsearchcount' + 1. If you want to get correct information,specifyrecompute: 1:
" result == 'maxsearchcount' + 1 when many matcheslet result = searchcount(#{recompute: 0})" Below returns correct result (recompute defaults" to 1)let result = searchcount()
The function is useful to add the count to'statusline':
function! LastSearchCount() abort  let result = searchcount(#{recompute: 0})  if empty(result)    return ''  endif  if result.incomplete ==# 1     " timed out    return printf(' /%s [?/??]', @/)  elseif result.incomplete ==# 2 " max count exceeded    if result.total > result.maxcount &&    \  result.current > result.maxcount      return printf(' /%s [>%d/>%d]', @/,      \             result.current, result.total)    elseif result.total > result.maxcount      return printf(' /%s [%d/>%d]', @/,      \             result.current, result.total)    endif  endif  return printf(' /%s [%d/%d]', @/,  \             result.current, result.total)endfunctionlet &statusline ..= '%{LastSearchCount()}'" Or if you want to show the count only when" 'hlsearch' was on" let &statusline ..=" \   '%{v:hlsearch ? LastSearchCount() : ""}'
You can also update the search count, which can be useful in aCursorMoved orCursorMovedI autocommand:
autocmd CursorMoved,CursorMovedI *  \ let s:searchcount_timer = timer_start(  \   200, function('s:update_searchcount'))function! s:update_searchcount(timer) abort  if a:timer ==# s:searchcount_timer    call searchcount(#{    \ recompute: 1, maxcount: 0, timeout: 100})    redrawstatus  endifendfunction
This can also be used to count matched texts with specifiedpattern in the current buffer using "pattern":
" Count '\<foo\>' in this buffer" (Note that it also updates search count)let result = searchcount(#{pattern: '\<foo\>'})" To restore old search count by old pattern," search againcall searchcount()
{options} must be aDictionary. It can contain:
keytypemeaning
recomputeBoolean ifTRUE, recompute the countliken orN was executed.otherwise returns the lastcomputed result (whenn orN was used when "S" is notin'shortmess', or thisfunction was called).(default:TRUE) patternString recompute if this was givenand different with@/.this works as same as thebelow command is executedbefore calling this function
let @/ = pattern
(default:@/) timeoutNumber 0 or negative number is notimeout. timeout millisecondsfor recomputing the result(default: 0) maxcountNumber 0 or negative number is nolimit. max count of matchedtext while recomputing theresult. if search exceededtotal count, "total" valuebecomesmaxcount + 1(default:'maxsearchcount') posList[lnum, col, off] valuewhen recomputing the result.this changes "current" resultvalue. seecursor(),getpos()(default: cursor's position)
Parameters:
{options} (table?)
Return:
(any)
searchdecl({name} [,{global} [,{thisblock}]])searchdecl()
Search for the declaration of{name}.
With a non-zero{global} argument it works likegD, findfirst match in the file. Otherwise it works likegd, findfirst match in the function.
With a non-zero{thisblock} argument matches in a {} blockthat ends before the cursor position are ignored. Avoidsfinding variable declarations only valid in another scope.
Moves the cursor to the found match.Returns zero for success, non-zero for failure.Example:
if searchdecl('myvar') == 0   echo getline('.')endif
Parameters:
{name} (string)
{global} (boolean?)
{thisblock} (boolean?)
Return:
(any)
searchpair()
searchpair({start},{middle},{end} [,{flags} [,{skip} [,{stopline} [,{timeout}]]]])Search for the match of a nested start-end pair. This can beused to find the "endif" that matches an "if", while otherif/endif pairs in between are ignored.The search starts at the cursor. The default is to searchforward, include 'b' in{flags} to search backward.If a match is found, the cursor is positioned at it and theline number is returned. If no match is found 0 or -1 isreturned and the cursor doesn't move. No error message isgiven.
{start},{middle} and{end} are patterns, seepattern. Theymust not contain \( \) pairs. Use of \%( \) is allowed. When{middle} is not empty, it is found when searching from eitherdirection, but only when not in a nested start-end pair. Atypical use is:
echo searchpair('\<if\>', '\<else\>', '\<endif\>')
By leaving{middle} empty the "else" is skipped.
{flags} 'b', 'c', 'n', 's', 'w' and 'W' are used like withsearch(). Additionally:'r'Repeat until no more matches found; will find theouter pair. Implies the 'W' flag.'m'Return number of matches instead of line number withthe match; will be > 1 when 'r' is used.Note: it's nearly always a good idea to use the 'W' flag, toavoid wrapping around the end of the file.
When a match for{start},{middle} or{end} is found, the{skip} expression is evaluated with the cursor positioned onthe start of the match. It should return non-zero if thismatch is to be skipped. E.g., because it is inside a commentor a string.When{skip} is omitted or empty, every match is accepted.When evaluating{skip} causes an error the search is abortedand -1 returned.{skip} can be a string, a lambda, a funcref or a partial.Anything else makes the function fail.
For{stopline} and{timeout} seesearch().
The value of'ignorecase' is used.'magic' is ignored, thepatterns are used like it's on.
The search starts exactly at the cursor. A match with{start},{middle} or{end} at the next character, in thedirection of searching, is the first one found. Example:
if 1  if 2  endif 2endif 1
When starting at the "if 2", with the cursor on the "i", andsearching forwards, the "endif 2" is found. When starting onthe character just before the "if 2", the "endif 1" will befound. That's because the "if 2" will be found first, andthen this is considered to be a nested if/endif from "if 2" to"endif 2".When searching backwards and{end} is more than one character,it may be useful to put "\zs" at the end of the pattern, sothat when the cursor is inside a match with the end it findsthe matching start.
Example, to find the "endif" command in a Vim script:
echo searchpair('\<if\>', '\<el\%[seif]\>', '\<en\%[dif]\>', 'W',\ 'getline(".") =~ "^\\s*\""')
The cursor must be at or after the "if" for which a match isto be found. Note that single-quote strings are used to avoidhaving to double the backslashes. The skip expression onlycatches comments at the start of a line, not after a command.Also, a word "en" or "if" halfway through a line is considereda match.Another example, to search for the matching "{" of a "}":
echo searchpair('{', '', '}', 'bW')
This works when the cursor is at or before the "}" for which amatch is to be found. To reject matches that syntaxhighlighting recognized as strings:
echo searchpair('{', '', '}', 'bW',     \ 'synIDattr(synID(line("."), col("."), 0), "name") =~? "string"')
Parameters:
{start} (string)
{middle} (string)
{end} (string)
{flags} (string?)
{skip} (string|function?)
{stopline} (integer?)
{timeout} (integer?)
Return:
(integer)
searchpairpos()
searchpairpos({start},{middle},{end} [,{flags} [,{skip} [,{stopline} [,{timeout}]]]])Same assearchpair(), but returns aList with the line andcolumn position of the match. The first element of theListis the line number and the second element is the byte index ofthe column position of the match. If no match is found,returns [0, 0].
let [lnum,col] = searchpairpos('{', '', '}', 'n')
Seematch-parens for a bigger and more useful example.
Parameters:
{start} (string)
{middle} (string)
{end} (string)
{flags} (string?)
{skip} (string|function?)
{stopline} (integer?)
{timeout} (integer?)
Return:
([integer, integer])
searchpos()
searchpos({pattern} [,{flags} [,{stopline} [,{timeout} [,{skip}]]]])Same assearch(), but returns aList with the line andcolumn position of the match. The first element of theListis the line number and the second element is the byte index ofthe column position of the match. If no match is found,returns [0, 0].Example:
let [lnum, col] = searchpos('mypattern', 'n')
When the 'p' flag is given then there is an extra item withthe sub-pattern match numbersearch()-sub-match. Example:
let [lnum, col, submatch] = searchpos('\(\l\)\|\(\u\)', 'np')
In this example "submatch" is 2 when a lowercase letter isfound/\l, 3 when an uppercase letter is found/\u.
Parameters:
{pattern} (string)
{flags} (string?)
{stopline} (integer?)
{timeout} (integer?)
{skip} (string|function?)
Return:
(any)
serverlist([{opts}])serverlist()
Returns a list of server addresses, or empty if all serverswere stopped.serverstart()serverstop()
The optional argument{opts} is a Dict and supports the following items:
peer : IfTRUE, servers not started byserverstart() will also be returned. (default:FALSE) Not supported on Windows yet.
Example:
echo serverlist()
Parameters:
{opts} (table?)
Return:
(string[])
serverstart([{address}])serverstart()
Opens a socket or named pipe at{address} and listens forRPC messages. Clients can sendAPI commands to thereturned address to control Nvim.
Returns the address string (which may differ from the{address} argument, see below).
If{address} has a colon (":") it is a TCP/IPv4/IPv6 address where the last ":" separates host and port (empty or zero assigns a random port).
Else{address} is the path to a named pipe (except on Windows).
If{address} has no slashes ("/") it is treated as the "name" part of a generated path in this format:
stdpath("run").."/{name}.{pid}.{counter}"
If{address} is omitted the name is "nvim".
echo serverstart()
=> /tmp/nvim.bram/oknANW/nvim.15430.5
Example bash command to list all Nvim servers:
ls ${XDG_RUNTIME_DIR:-${TMPDIR}nvim.${USER}}/*/nvim.*.0
Example named pipe:
if has('win32')  echo serverstart('\\.\pipe\nvim-pipe-1234')else  echo serverstart('nvim.sock')endif
Example TCP/IP address:
echo serverstart('::1:12345')
Parameters:
{address} (string?)
Return:
(string)
serverstop({address})serverstop()
Closes the pipe or socket at{address}.Returns TRUE if{address} is valid, else FALSE.Ifv:servername is stopped it is set to the next availableaddress inserverlist().
Parameters:
{address} (string)
Return:
(integer)
setbufline({buf},{lnum},{text})setbufline()
Set line{lnum} to{text} in buffer{buf}. This works likesetline() for the specified buffer.
This function works only for loaded buffers. First callbufload() if needed.
To insert lines useappendbufline().
{text} can be a string to set one line, or a List of stringsto set multiple lines. If the List extends below the lastline then those lines are added. If the List is empty thennothing is changed and zero is returned.
For the use of{buf}, seebufname() above.
{lnum} is used like withsetline().Use "$" to refer to the last line in buffer{buf}.When{lnum} is just below the last line the{text} will beadded below the last line.On success 0 is returned, on failure 1 is returned.
If{buf} is not a valid buffer or{lnum} is not valid, anerror message is given.
Parameters:
{buf} (integer|string)
{lnum} (integer)
{text} (string|string[])
Return:
(integer)
setbufvar({buf},{varname},{val})setbufvar()
Set option or local variable{varname} in buffer{buf} to{val}.This also works for a global or local window option, but itdoesn't work for a global or local window variable.For a local window option the global value is unchanged.For the use of{buf}, seebufname() above.The{varname} argument is a string.Note that the variable name without "b:" must be used.Examples:
call setbufvar(1, "&mod", 1)call setbufvar("todo", "myvar", "foobar")
This function is not available in thesandbox.
Parameters:
{buf} (integer|string)
{varname} (string)
{val} (any)
Return:
(any)
setcellwidths({list})setcellwidths()
Specify overrides for cell widths of character ranges. Thistells Vim how wide characters are when displayed in theterminal, counted in screen cells. The values override'ambiwidth'. Example:
call setcellwidths([             \ [0x111, 0x111, 1],             \ [0x2194, 0x2199, 2],             \ ])
The{list} argument is a List of Lists with each threenumbers: [{low},{high},{width}].E1109E1110{low} and{high} can be the same, in which case this refers toone character. Otherwise it is the range of characters from{low} to{high} (inclusive).E1111E1114Only characters with value 0x80 and higher can be used.
{width} must be either 1 or 2, indicating the character widthin screen cells.E1112
An error is given if the argument is invalid, also when arange overlaps with another.E1113
If the new value causes'fillchars' or'listchars' to becomeinvalid it is rejected and an error is given.
To clear the overrides pass an empty{list}:
call setcellwidths([])
You can use the script $VIMRUNTIME/scripts/emoji_list.lua to seethe effect for known emoji characters. Move the cursorthrough the text to check if the cell widths of your terminalmatch with what Vim knows about each emoji. If it doesn'tlook right you need to adjust the{list} argument.
Parameters:
{list} (any[])
Return:
(any)
setcharpos({expr},{list})setcharpos()
Same assetpos() but uses the specified column number as thecharacter index instead of the byte index in the line.
Example:With the text "여보세요" in line 8:
call setcharpos('.', [0, 8, 4, 0])
positions the cursor on the fourth character '요'.
call setpos('.', [0, 8, 4, 0])
positions the cursor on the second character '보'.
Parameters:
{expr} (string)
{list} (integer[])
Return:
(any)
setcharsearch({dict})setcharsearch()
Set the current character search information to{dict},which contains one or more of the following entries:
charcharacter which will be used for a subsequent, or; command; an empty string clears thecharacter search forwarddirection of character search; 1 for forward,0 for backward untiltype of character search; 1 for at orTcharacter search, 0 for anf orFcharacter search
This can be useful to save/restore a user's character searchfrom a script:
let prevsearch = getcharsearch()" Perform a command which clobbers user's searchcall setcharsearch(prevsearch)
Also seegetcharsearch().
Parameters:
{dict} (string)
Return:
(any)
setcmdline({str} [,{pos}])setcmdline()
Set the command line to{str} and set the cursor position to{pos}.If{pos} is omitted, the cursor is positioned after the text.Returns 0 when successful, 1 when not editing the commandline.
Parameters:
{str} (string)
{pos} (integer?)
Return:
(integer)
setcmdpos({pos})setcmdpos()
Set the cursor position in the command line to byte position{pos}. The first position is 1.Usegetcmdpos() to obtain the current position.Only works while editing the command line, thus you must usec_CTRL-\_e,c_CTRL-R_= orc_CTRL-R_CTRL-R with '='. Forc_CTRL-\_e andc_CTRL-R_CTRL-R with '=' the position isset after the command line is set to the expression. Forc_CTRL-R_= it is set after evaluating the expression butbefore inserting the resulting text.When the number is too big the cursor is put at the end of theline. A number smaller than one has undefined results.Returns 0 when successful, 1 when not editing the commandline.
Parameters:
{pos} (integer)
Return:
(any)
setcursorcharpos({lnum},{col} [,{off}])setcursorcharpos()
setcursorcharpos({list})Same ascursor() but uses the specified column number as thecharacter index instead of the byte index in the line.
Example:With the text "여보세요" in line 4:
call setcursorcharpos(4, 3)
positions the cursor on the third character '세'.
call cursor(4, 3)
positions the cursor on the first character '여'.
Returns 0 when the position could be set, -1 otherwise.
Parameters:
{list} (integer[])
Return:
(any)
setenv({name},{val})setenv()
Set environment variable{name} to{val}. Example:
call setenv('HOME', '/home/myhome')
When{val} isv:null the environment variable is deleted.See alsoexpr-env.
Parameters:
{name} (string)
{val} (string)
Return:
(any)
setfperm({fname},{mode})setfperm()chmodSet the file permissions for{fname} to{mode}.{mode} must be a string with 9 characters. It is of the form"rwxrwxrwx", where each group of "rwx" flags represent, inturn, the permissions of the owner of the file, the group thefile belongs to, and other users. A '-' character means thepermission is off, any other character means on. Multi-bytecharacters are not supported.
For example "rw-r-----" means read-write for the user,readable by the group, not accessible by others. "xx-x-----"would do the same thing.
Returns non-zero for success, zero for failure.
To read permissions seegetfperm().
Parameters:
{fname} (string)
{mode} (string)
Return:
(any)
setline({lnum},{text})setline()
Set line{lnum} of the current buffer to{text}. To insertlines useappend(). To set lines in another buffer usesetbufline().
{lnum} is used like withgetline().When{lnum} is just below the last line the{text} will beadded below the last line.{text} can be any type or a List of any type, each item isconverted to a String. When{text} is an empty List thennothing is changed and FALSE is returned.
If this succeeds, FALSE is returned. If this fails (most likelybecause{lnum} is invalid) TRUE is returned.
Example:
call setline(5, strftime("%c"))
When{text} is aList then line{lnum} and following lineswill 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.
Parameters:
{lnum} (integer|string)
{text} (any)
Return:
(any)
setloclist({nr},{list} [,{action} [,{what}]])setloclist()
Create or replace or add to the location list for window{nr}.{nr} can be the window number or thewindow-ID.When{nr} is zero the current window is used.
For a location list window, the displayed location list ismodified. For an invalid window number{nr}, -1 is returned.Otherwise, same assetqflist().Also seelocation-list.
For{action} seesetqflist-action.
If the optional{what} dictionary argument is supplied, thenonly the items listed in{what} are set. Refer tosetqflist()for the list of supported keys in{what}.
Parameters:
{nr} (integer)
{list} (any)
{action} (string?)
{what} (table?)
Return:
(any)
setmatches({list} [,{win}])setmatches()
Restores a list of matches saved bygetmatches() for thecurrent window. Returns 0 if successful, otherwise -1. Allcurrent matches are cleared before the list is restored. Seeexample forgetmatches().If{win} is specified, use the window with this number orwindow ID instead of the current window.
Parameters:
{list} (vim.fn.getmatches.ret.item[])
{win} (integer?)
Return:
(any)
setpos({expr},{list})setpos()
Set the position for String{expr}. Possible values:.the cursor'xmark x
{list} must be aList with four or five numbers: [bufnum, lnum, col, off] [bufnum, lnum, col, off, curswant]
"bufnum" is the buffer number.Zero can be used for thecurrent buffer. When setting an uppercase mark "bufnum" isused for the mark position. For other marks it specifies thebuffer to set the mark in. You can use thebufnr() functionto turn a file name into a buffer number.For setting the cursor and the ' mark "bufnum" is ignored,since these are associated with a window, not a buffer.Does not change the jumplist.
"lnum" and "col" are the position in the buffer. The firstcolumn is 1. Use a zero "lnum" to delete a mark. If "col" issmaller than 1 then 1 is used. To use the character countinstead of the byte count, usesetcharpos().
The "off" number is only used when'virtualedit' is set. Thenit is the offset in screen columns from the start of thecharacter. E.g., a position within a<Tab> or after the lastcharacter.
The "curswant" number is only used when setting the cursorposition. It sets the preferred column for when moving thecursor vertically. When the "curswant" number is missing thepreferred column is not set. When it is present and setting amark position it is not used.
Note that for '< and '> changing the line number may result inthe marks to be effectively be swapped, so that '< is alwaysbefore '>.
Returns 0 when the position could be set, -1 otherwise.An error message is given if{expr} is invalid.
Also seesetcharpos(),getpos() andgetcurpos().
This does not restore the preferred column for movingvertically; if you set the cursor position with this,j andk motions will jump to previous columns! Usecursor() toalso set the preferred column. Also see the "curswant" key inwinrestview().
Parameters:
{expr} (string)
{list} (integer[])
Return:
(any)
setqflist({list} [,{action} [,{what}]])setqflist()
Create or replace or add to the quickfix list.
If the optional{what} dictionary argument is supplied, thenonly the items listed in{what} are set. The first{list}argument is ignored. See below for the supported items in{what}.setqflist-what
When{what} is not present, the items in{list} are used. Eachitem must be a dictionary. Non-dictionary items in{list} areignored. Each dictionary item can contain the followingentries:
bufnrbuffer number; must be the number of a validbuffer filenamename of a file; only used when "bufnr" is notpresent or it is invalid. modulename of a module; if given it will be used inquickfix error window instead of the filename. lnumline number in the file end_lnumend of lines, if the item spans multiple lines patternsearch pattern used to locate the error colcolumn number vcolwhen non-zero: "col" is visual columnwhen zero: "col" is byte index end_colend column, if the item spans multiple columns nrerror number textdescription of the error typesingle-character error type, 'E', 'W', etc. validrecognized error message user_datacustom data associated with the item, can beany type.
The "col", "vcol", "nr", "type" and "text" entries areoptional. Either "lnum" or "pattern" entry can be used tolocate a matching error line.If the "filename" and "bufnr" entries are not present orneither the "lnum" or "pattern" entries are present, then theitem will not be handled as an error line.If both "pattern" and "lnum" are present then "pattern" willbe used.If the "valid" entry is not supplied, then the valid flag isset when "bufnr" is a valid buffer or "filename" exists.If you supply an empty{list}, the quickfix list will becleared.Note that the list is not exactly the same as whatgetqflist() returns.
{action} values:setqflist-actionE927'a'The items from{list} are added to the existingquickfix list. If there is no existing list, then anew list is created.
'r'The items from the current quickfix list are replacedwith the items from{list}. This can also be used toclear the list:
call setqflist([], 'r')
'u'Like 'r', but tries to preserve the current selectionin the quickfix list.'f'All the quickfix lists in the quickfix stack arefreed.
If{action} is not present or is set to ' ', then a new listis created. The new quickfix list is added after the currentquickfix list in the stack and all the following lists arefreed. To add a new quickfix list at the end of the stack,set "nr" in{what} to "$".
The following items can be specified in dictionary{what}: contextquickfix list context. Seequickfix-context efmerrorformat to use when parsing text from"lines". If this is not present, then the'errorformat' option value is used.Seequickfix-parse idquickfix list identifierquickfix-ID idxindex of the current entry in the quickfixlist specified by "id" or "nr". If set to '$',then the last entry in the list is set as thecurrent entry. Seequickfix-index itemslist of quickfix entries. Same as the{list}argument. linesuse'errorformat' to parse a list of lines andadd the resulting entries to the quickfix list{nr} or{id}. Only aList value is supported.Seequickfix-parse nrlist number in the quickfix stack; zeromeans the current quickfix list and "$" meansthe last quickfix list. quickfixtextfuncfunction to get the text to display in thequickfix window. The value can be the name ofa function or a funcref or a lambda. Refer toquickfix-window-function for an explanationof how to write the function and an example. titlequickfix list title text. Seequickfix-titleUnsupported keys in{what} are ignored.If the "nr" item is not present, then the current quickfix listis modified. When creating a new quickfix list, "nr" can beset to a value one greater than the quickfix stack size.When modifying a quickfix list, to guarantee that the correctlist is modified, "id" should be used instead of "nr" tospecify the list.
Examples (See alsosetqflist-examples):
call setqflist([], 'r', {'title': 'My search'})call setqflist([], 'r', {'nr': 2, 'title': 'Errors'})call setqflist([], 'a', {'id':qfid, 'lines':["F1:10:L10"]})
Returns zero for success, -1 for failure.
This function can be used to create a quickfix listindependent of the'errorformat' setting. Use a command like:cc 1 to jump to the first position.
Parameters:
{list} (vim.quickfix.entry[])
{action} (string?)
{what} (vim.fn.setqflist.what?)
Return:
(integer)
setreg({regname},{value} [,{options}])setreg()
Set the register{regname} to{value}.If{regname} is "" or "@", the unnamed register '"' is used.The{regname} argument is a string.
{value} may be any value returned bygetreg() orgetreginfo(), including aList orDict.If{options} contains "a" or{regname} is upper case,then the value is appended.
{options} can also contain a register type specification: "c" or "v"charwise mode "l" or "V"linewise mode "b" or "<CTRL-V>"blockwise-visual modeIf a number immediately follows "b" or "<CTRL-V>" then this isused as the width of the selection - if it is not specifiedthen the width of the block is set to the number of charactersin the longest line (counting a<Tab> as 1 character).If{options} contains "u" or '"', then the unnamed register isset to point to register{regname}.
If{options} contains no register settings, then the defaultis to use character mode unless{value} ends in a<NL> forstring{value} and linewise mode for list{value}. Blockwisemode is never selected automatically.Returns zero for success, non-zero for failure.
E883
Note: you may not useList 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')call setreg('"', { 'points_to': 'a'})
This example shows using the functions to save and restore aregister:
let var_a = getreginfo()call setreg('a', var_a)
or:
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 valuewithout using the third argument togetreg() as without itnewlines are represented as newlines AND Nul bytes arerepresented as newlines as well, seeNL-used-for-Nul.
You can also change the type of a register by appendingnothing:
call setreg('a', '', 'al')
Parameters:
{regname} (string)
{value} (any)
{options} (string?)
Return:
(any)
settabvar({tabnr},{varname},{val})settabvar()
Set tab-local variable{varname} to{val} in tab page{tabnr}.t:var The{varname} argument is a string.Note that the variable name without "t:" must be used.Tabs are numbered starting with one.This function is not available in thesandbox.
Parameters:
{tabnr} (integer)
{varname} (string)
{val} (any)
Return:
(any)
settabwinvar({tabnr},{winnr},{varname},{val})settabwinvar()
Set option or local variable{varname} in window{winnr} to{val}.Tabs are numbered starting with one. For the current tabpageusesetwinvar().{winnr} can be the window number or thewindow-ID.When{winnr} is zero the current window is used.This also works for a global or local buffer option, but itdoesn't work for a global or local buffer variable.For a local buffer option the global value is unchanged.Note that the variable name without "w:" must be used.Examples:
call settabwinvar(1, 1, "&list", 0)call settabwinvar(3, 2, "myvar", "foobar")
This function is not available in thesandbox.
Parameters:
{tabnr} (integer)
{winnr} (integer)
{varname} (string)
{val} (any)
Return:
(any)
settagstack({nr},{dict} [,{action}])settagstack()
Modify the tag stack of the window{nr} using{dict}.{nr} can be the window number or thewindow-ID.
For a list of supported items in{dict}, refer togettagstack(). "curidx" takes effect before changing the tagstack.E962
How the tag stack is modified depends on the{action}argument:
If{action} is not present or is set to 'r', then the tag stack is replaced.
If{action} is set to 'a', then new entries from{dict} are pushed (added) onto the tag stack.
If{action} is set to 't', then all the entries from the current entry in the tag stack or "curidx" in{dict} are removed and then new entries are pushed to the stack.
The current index is set to one after the length of the tagstack after the modification.
Returns zero for success, -1 for failure.
Examples (for more examples seetagstack-examples): Empty the tag stack of window 3:
call settagstack(3, {'items' : []})
Save and restore the tag stack:
let stack = gettagstack(1003)" do something elsecall settagstack(1003, stack)unlet stack
Parameters:
{nr} (integer)
{dict} (any)
{action} (string?)
Return:
(any)
setwinvar({nr},{varname},{val})setwinvar()
Likesettabwinvar() for the current tab page.Examples:
call setwinvar(1, "&list", 0)call setwinvar(2, "myvar", "foobar")
Parameters:
{nr} (integer)
{varname} (string)
{val} (any)
Return:
(any)
sha256({expr})sha256()
Returns a String with 64 hex characters, which is the SHA256checksum of{expr}.{expr} is a String or a Blob.
Parameters:
{expr} (string)
Return:
(string)
shellescape({string} [,{special}])shellescape()
Escape{string} for use as a shell command argument.
On Windows when'shellslash' is not set, encloses{string} indouble-quotes and doubles all double-quotes within{string}.Otherwise encloses{string} in single-quotes and replaces all"'" with "'\''".
The{special} argument adds additional escaping of keywordsused in Vim commands. If it is anon-zero-arg:
Special items such as "!", "%", "#" and "<cword>" (as listed inexpand()) will be preceded by a backslash. The backslash will be removed again by the:! command.
The<NL> character is escaped.
If'shell' contains "csh" in the tail:
The "!" character will be escaped. This is because csh and tcsh use "!" for history replacement even in single-quotes.
The<NL> character is escaped (twice if{special} is anon-zero-arg).
If'shell' contains "fish" in the tail, the "\" character willbe escaped because in fish it is used as an escape characterinside single quotes.
Example of use with a:! command:
exe '!dir ' .. shellescape(expand('<cfile>'), 1)
This results in a directory listing for the file under thecursor. Example of use withsystem():
call system("chmod +w -- " .. shellescape(expand("%")))
See also::S.
Parameters:
{string} (string)
{special} (boolean?)
Return:
(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. To be backwards compatible in indentplugins, use this:
if exists('*shiftwidth')  func s:sw()    return shiftwidth()  endfuncelse  func s:sw()    return &sw  endfuncendif
And then use s:sw() instead of &sw.
When there is one argument{col} this is used as column numberfor which to return the'shiftwidth' value. This matters for the'vartabstop' feature. If no{col} argument is given, column 1will be assumed.
Parameters:
{col} (integer?)
Return:
(integer)
sign_define({name} [,{dict}])sign_define()
sign_define({list})Define a new sign named{name} or modify the attributes of anexisting sign. This is similar to the:sign-define command.
Prefix{name} with a unique text to avoid name collisions.There is no{group} like with placing signs.
The{name} can be a String or a Number. The optional{dict}argument specifies the sign attributes. The following valuesare supported: iconfull path to the bitmap file for the sign. linehlhighlight group used for the whole line thesign is placed in. prioritydefault priority value of the sign numhlhighlight group used for the line number wherethe sign is placed. texttext that is displayed when there is no iconor the GUI is not being used. texthlhighlight group used for the text item culhlhighlight group used for the text item whenthe cursor is on the same line as the sign and'cursorline' is enabled.
If the sign named{name} already exists, then the attributesof the sign are updated.
The one argument{list} can be used to define a list of signs.Each list item is a dictionary with the above items in{dict}and a "name" item for the sign name.
Returns 0 on success and -1 on failure. When the one argument{list} is used, then returns a List of values one for eachdefined sign.
Examples:
call sign_define("mySign", {        \ "text" : "=>",        \ "texthl" : "Error",        \ "linehl" : "Search"})call sign_define([        \ {'name' : 'sign1',        \  'text' : '=>'},        \ {'name' : 'sign2',        \  'text' : '!!'}        \ ])
Parameters:
{list} (vim.fn.sign_define.dict[])
Return:
((0|-1)[])
sign_getdefined([{name}])sign_getdefined()
Get a list of defined signs and their attributes.This is similar to the:sign-list command.
If the{name} is not supplied, then a list of all the definedsigns is returned. Otherwise the attribute of the specifiedsign is returned.
Each list item in the returned value is a dictionary with thefollowing entries: iconfull path to the bitmap file of the sign linehlhighlight group used for the whole line thesign is placed in; not present if not set. namename of the sign prioritydefault priority value of the sign numhlhighlight group used for the line number wherethe sign is placed; not present if not set. texttext that is displayed when there is no iconor the GUI is not being used. texthlhighlight group used for the text item; notpresent if not set. culhlhighlight group used for the text item whenthe cursor is on the same line as the sign and'cursorline' is enabled; not present if notset.
Returns an empty List if there are no signs and when{name} isnot found.
Examples:
" Get a list of all the defined signsecho sign_getdefined()" Get the attribute of the sign named mySignecho sign_getdefined("mySign")
Parameters:
{name} (string?)
Return:
(vim.fn.sign_getdefined.ret.item[])
sign_getplaced([{buf} [,{dict}]])sign_getplaced()
Return a list of signs placed in a buffer or all the buffers.This is similar to the:sign-place-list command.
If the optional buffer name{buf} is specified, then only thelist of signs placed in that buffer is returned. For the useof{buf}, seebufname(). The optional{dict} can containthe following entries: groupselect only signs in this group idselect sign with this identifier lnumselect signs placed in this line. For the useof{lnum}, seeline().If{group} is "*", then signs in all the groups including theglobal group are returned. If{group} is not supplied or is anempty string, then only signs in the global group arereturned. If no arguments are supplied, then signs in theglobal group placed in all the buffers are returned.Seesign-group.
Each list item in the returned value is a dictionary with thefollowing entries:bufnrnumber of the buffer with the signsignslist of signs placed in{bufnr}. Each listitem is a dictionary with the below listedentries
The dictionary for each sign contains the following entries:group sign group. Set to '' for the global group.id identifier of the signlnum line number where the sign is placedname name of the defined signpriority sign priority
The returned signs in a buffer are ordered by their linenumber and priority.
Returns an empty list on failure or if there are no placedsigns.
Examples:
" Get a List of signs placed in eval.c in the" global groupecho sign_getplaced("eval.c")" Get a List of signs in group 'g1' placed in eval.cecho sign_getplaced("eval.c", {'group' : 'g1'})" Get a List of signs placed at line 10 in eval.cecho sign_getplaced("eval.c", {'lnum' : 10})" Get sign with identifier 10 placed in a.pyecho sign_getplaced("a.py", {'id' : 10})" Get sign with id 20 in group 'g1' placed in a.pyecho sign_getplaced("a.py", {'group' : 'g1',                                \  'id' : 20})" Get a List of all the placed signsecho sign_getplaced()
Parameters:
{buf} (integer|string?)
{dict} (vim.fn.sign_getplaced.dict?)
Return:
(vim.fn.sign_getplaced.ret.item[])
sign_jump({id},{group},{buf})sign_jump()
Open the buffer{buf} or jump to the window that contains{buf} and position the cursor at sign{id} in group{group}.This is similar to the:sign-jump command.
If{group} is an empty string, then the global group is used.For the use of{buf}, seebufname().
Returns the line number of the sign. Returns -1 if thearguments are invalid.
Example:
" Jump to sign 10 in the current buffercall sign_jump(10, '', '')
Parameters:
{id} (integer)
{group} (string)
{buf} (integer|string)
Return:
(integer)
sign_place({id},{group},{name},{buf} [,{dict}])sign_place()
Place the sign defined as{name} at line{lnum} in file orbuffer{buf} and assign{id} and{group} to sign. This issimilar to the:sign-place command.
If the sign identifier{id} is zero, then a new identifier isallocated. Otherwise the specified number is used.{group} isthe sign group name. To use the global sign group, use anempty string.{group} functions as a namespace for{id}, thustwo groups can use the same IDs. Refer tosign-identifierandsign-group for more information.
{name} refers to a defined sign.{buf} refers to a buffer name or number. For the acceptedvalues, seebufname().
The optional{dict} argument supports the following entries:lnumline number in the file or buffer{buf} where the sign is to be placed.For the accepted values, seeline().prioritypriority of the sign. Seesign-priority for more information.
If the optional{dict} is not specified, then it modifies theplaced sign{id} in group{group} to use the defined sign{name}.
Returns the sign identifier on success and -1 on failure.
Examples:
" Place a sign named sign1 with id 5 at line 20 in" buffer json.ccall sign_place(5, '', 'sign1', 'json.c',                                \ {'lnum' : 20})" Updates sign 5 in buffer json.c to use sign2call sign_place(5, '', 'sign2', 'json.c')" Place a sign named sign3 at line 30 in" buffer json.c with a new identifierlet id = sign_place(0, '', 'sign3', 'json.c',                                \ {'lnum' : 30})" Place a sign named sign4 with id 10 in group 'g3'" at line 40 in buffer json.c with priority 90call sign_place(10, 'g3', 'sign4', 'json.c',                \ {'lnum' : 40, 'priority' : 90})
Parameters:
{id} (integer)
{group} (string)
{name} (string)
{buf} (integer|string)
{dict} (vim.fn.sign_place.dict?)
Return:
(integer)
sign_placelist({list})sign_placelist()
Place one or more signs. This is similar to thesign_place() function. The{list} argument specifies theList of signs to place. Each list item is a dict with thefollowing sign attributes: bufferBuffer name or number. For the acceptedvalues, seebufname(). groupSign group.{group} functions as a namespacefor{id}, thus two groups can use the sameIDs. If not specified or set to an emptystring, then the global group is used. Seesign-group for more information. idSign identifier. If not specified or zero,then a new unique identifier is allocated.Otherwise the specified number is used. Seesign-identifier for more information. lnumLine number in the buffer where the sign is tobe placed. For the accepted values, seeline(). nameName of the sign to place. Seesign_define()for more information. priorityPriority of the sign. When multiple signs areplaced on a line, the sign with the highestpriority is used. If not specified, thedefault value of 10 is used, unless specifiedotherwise by the sign definition. Seesign-priority for more information.
If{id} refers to an existing sign, then the existing sign ismodified to use the specified{name} and/or{priority}.
Returns a List of sign identifiers. If failed to place asign, the corresponding list item is set to -1.
Examples:
" Place sign s1 with id 5 at line 20 and id 10 at line" 30 in buffer a.clet [n1, n2] = sign_placelist([        \ {'id' : 5,        \  'name' : 's1',        \  'buffer' : 'a.c',        \  'lnum' : 20},        \ {'id' : 10,        \  'name' : 's1',        \  'buffer' : 'a.c',        \  'lnum' : 30}        \ ])" Place sign s1 in buffer a.c at line 40 and 50" with auto-generated identifierslet [n1, n2] = sign_placelist([        \ {'name' : 's1',        \  'buffer' : 'a.c',        \  'lnum' : 40},        \ {'name' : 's1',        \  'buffer' : 'a.c',        \  'lnum' : 50}        \ ])
Parameters:
{list} (vim.fn.sign_placelist.list.item[])
Return:
(integer[])
sign_undefine([{name}])sign_undefine()
sign_undefine({list})Deletes a previously defined sign{name}. This is similar tothe:sign-undefine command. If{name} is not supplied, thendeletes all the defined signs.
The one argument{list} can be used to undefine a list ofsigns. Each list item is the name of a sign.
Returns 0 on success and -1 on failure. For the one argument{list} call, returns a list of values one for each undefinedsign.
Examples:
" Delete a sign named mySigncall sign_undefine("mySign")" Delete signs 'sign1' and 'sign2'call sign_undefine(["sign1", "sign2"])" Delete all the signscall sign_undefine()
Parameters:
{list} (string[]?)
Return:
(integer[])
sign_unplace({group} [,{dict}])sign_unplace()
Remove a previously placed sign in one or more buffers. Thisis similar to the:sign-unplace command.
{group} is the sign group name. To use the global sign group,use an empty string. If{group} is set to "*", then all thegroups including the global group are used.The signs in{group} are selected based on the entries in{dict}. The following optional entries in{dict} aresupported:bufferbuffer name or number. Seebufname().idsign identifierIf{dict} is not supplied, then all the signs in{group} areremoved.
Returns 0 on success and -1 on failure.
Examples:
" Remove sign 10 from buffer a.vimcall sign_unplace('', {'buffer' : "a.vim", 'id' : 10})" Remove sign 20 in group 'g1' from buffer 3call sign_unplace('g1', {'buffer' : 3, 'id' : 20})" Remove all the signs in group 'g2' from buffer 10call sign_unplace('g2', {'buffer' : 10})" Remove sign 30 in group 'g3' from all the bufferscall sign_unplace('g3', {'id' : 30})" Remove all the signs placed in buffer 5call sign_unplace('*', {'buffer' : 5})" Remove the signs in group 'g4' from all the bufferscall sign_unplace('g4')" Remove sign 40 from all the bufferscall sign_unplace('*', {'id' : 40})" Remove all the placed signs from all the bufferscall sign_unplace('*')
Parameters:
{group} (string)
{dict} (vim.fn.sign_unplace.dict?)
Return:
(0|-1)
sign_unplacelist({list})sign_unplacelist()
Remove previously placed signs from one or more buffers. Thisis similar to thesign_unplace() function.
The{list} argument specifies the List of signs to remove.Each list item is a dict with the following sign attributes: bufferbuffer name or number. For the acceptedvalues, seebufname(). If not specified,then the specified sign is removed from allthe buffers. groupsign group name. If not specified or set to anempty string, then the global sign group isused. If set to "*", then all the groupsincluding the global group are used. idsign identifier. If not specified, then allthe signs in the specified group are removed.
Returns a List where an entry is set to 0 if the correspondingsign was successfully removed or -1 on failure.
Example:
" Remove sign with id 10 from buffer a.vim and sign" with id 20 from buffer b.vimcall sign_unplacelist([        \ {'id' : 10, 'buffer' : "a.vim"},        \ {'id' : 20, 'buffer' : 'b.vim'},        \ ])
Parameters:
{list} (vim.fn.sign_unplacelist.list.item)
Return:
((0|-1)[])
simplify({filename})simplify()
Simplify the file name as much as possible without changingthe meaning. Shortcuts (on MS-Windows) or symbolic links (onUnix) are not resolved. If the first path component in{filename} designates the current directory, this will bevalid for the result as well. A trailing path separator isnot removed either. On Unix "//path" is unchanged, but"///path" is simplified to "/path" (this follows the Posixstandard).Example:
simplify("./dir/.././/file/") == "./file/"
Note: The combination "dir/.." is only removed if "dir" isa searchable directory or does not exist. On Unix, it is alsoremoved when "dir" is a symbolic link within the samedirectory. In order to resolve all the involved symboliclinks before simplifying the path name, useresolve().
Parameters:
{filename} (string)
Return:
(string)
sin({expr})sin()
Return the sine of{expr}, measured in radians, as aFloat.{expr} must evaluate to aFloat or aNumber.Returns 0.0 if{expr} is not aFloat or aNumber.Examples:
echo sin(100)
-0.506366
echo sin(-4.01)
0.763301
Parameters:
{expr} (number)
Return:
(number)
sinh({expr})sinh()
Return the hyperbolic sine of{expr} as aFloat in the range[-inf, inf].{expr} must evaluate to aFloat or aNumber.Returns 0.0 if{expr} is not aFloat or aNumber.Examples:
echo sinh(0.5)
0.521095
echo sinh(-0.9)
-1.026517
Parameters:
{expr} (number)
Return:
(any)
slice({expr},{start} [,{end}])slice()
Similar to using aslice "expr[start : end]", but "end" isused exclusive. And for a string the indexes are used ascharacter indexes instead of byte indexes.Also, composing characters are treated as a part of thepreceding base character.When{end} is omitted the slice continues to the last item.When{end} is -1 the last item is omitted.Returns an empty value if{start} or{end} are invalid.
Parameters:
{expr} (any)
{start} (integer)
{end} (integer?)
Return:
(any)
sockconnect({mode},{address} [,{opts}])sockconnect()
Connect a socket to an address. If{mode} is "pipe" then{address} should be the path of a local domain socket (onunix) or named pipe (on Windows). If{mode} is "tcp" then{address} should be of the form "host:port" where the hostshould be an ip address or host name, and port the portnumber.
For "pipe" mode, seeluv-pipe-handle. For "tcp" mode, seeluv-tcp-handle.
Returns achannel ID. Close the socket withchanclose().Usechansend() to send data over a bytes socket, andrpcrequest() andrpcnotify() to communicate with a RPCsocket.
{opts} is an optional dictionary with these keys:on_data : callback invoked when data was read from socket data_buffered : read socket data inchannel-buffered mode. rpc : If set,msgpack-rpc will be used to communicate over the socket.Returns:
The channel ID on success (greater than zero)
0 on invalid arguments or connection failure.
Parameters:
{mode} (string)
{address} (string)
{opts} (table?)
Return:
(any)
sort({list} [,{how} [,{dict}]])sort()E702Sort the items in{list} in-place. Returns{list}.
If you want a list to remain unmodified make a copy first:
let sortedlist = sort(copy(mylist))
When{how} is omitted or is a string, then sort() uses thestring representation of each item to sort on. Numbers sortafter Strings,Lists after Numbers. For sorting text in thecurrent buffer use:sort.
When{how} is given and it is 'i' then case is ignored.For backwards compatibility, the value one can be used toignore case. Zero means to not ignore case.
When{how} is given and it is 'l' then the current collationlocale is used for ordering. Implementation details: strcoll()is used to compare strings. See:language check or set thecollation locale.v:collate can also be used to check thecurrent locale. Sorting using the locale typically ignorescase. Example:
" ö is sorted similarly to o with English locale.language collate en_US.UTF8echo sort(['n', 'o', 'O', 'ö', 'p', 'z'], 'l')
['n', 'o', 'O', 'ö', 'p', 'z']
" ö is sorted after z with Swedish locale.language collate sv_SE.UTF8echo sort(['n', 'o', 'O', 'ö', 'p', 'z'], 'l')
['n', 'o', 'O', 'p', 'z', 'ö']
This does not work properly on Mac.
When{how} is given and it is 'n' then all items will besorted numerical (Implementation detail: this uses thestrtod() function to parse numbers, Strings, Lists, Dicts andFuncrefs will be considered as being 0).
When{how} is given and it is 'N' then all items will besorted numerical. This is like 'n' but a string containingdigits will be used as the number they represent.
When{how} is given and it is 'f' then all items will besorted numerical. All values must be a Number or a Float.
When{how} is aFuncref or a function name, this functionis called to compare items. The function is invoked with twoitems as argument and must return zero if they are equal, 1 orbigger if the first one sorts after the second one, -1 orsmaller if the first one sorts before the second one.
{dict} is for functions with the "dict" attribute. It will beused to set the local variable "self".Dictionary-function
The sort is stable, items which compare equal (as number or asstring) will keep their relative position. E.g., when sortingon numbers, text strings will sort next to each other, in thesame order as they were originally.
Example:
func MyCompare(i1, i2)   return a:i1 == a:i2 ? 0 : a:i1 > a:i2 ? 1 : -1endfunceval mylist->sort("MyCompare")
A shorter compare version for this specific simple case, whichignores overflow:
func MyCompare(i1, i2)   return a:i1 - a:i2endfunc
For a simple expression you can use a lambda:
eval mylist->sort({i1, i2 -> i1 - i2})
Parameters:
{list} (T[])
{how} (string|function?)
{dict} (any?)
Return:
(T[])
soundfold({word})soundfold()
Return the sound-folded equivalent of{word}. Uses the firstlanguage in'spelllang' for the current window that supportssoundfolding.'spell' must be set. When no sound folding ispossible the{word} is returned unmodified.This can be used for making spelling suggestions. Note thatthe method can be quite slow.
Parameters:
{word} (string)
Return:
(string)
spellbadword([{sentence}])spellbadword()
Without argument: The result is the badly spelled word underor after the cursor. The cursor is moved to the start of thebad word. When no bad word is found in the cursor line theresult is an empty string and the cursor doesn't move.
With argument: The result is the first word in{sentence} thatis badly spelled. If there are no spelling mistakes theresult is an empty string.
The return value is a list with two items:
The badly spelled word or an empty string.
The type of the spelling error:"bad"spelling mistake"rare"rare word"local"word only valid in another region"caps"word should start with CapitalExample:
echo spellbadword("the quik brown fox")
['quik', 'bad']
The spelling information for the current window and the valueof'spelllang' are used.
Parameters:
{sentence} (string?)
Return:
(any)
spellsuggest({word} [,{max} [,{capital}]])spellsuggest()
Return aList with spelling suggestions to replace{word}.When{max} is given up to this number of suggestions arereturned. Otherwise up to 25 suggestions are returned.
When the{capital} argument is given and it's non-zero onlysuggestions with a leading capital will be given. Use thisafter a match with'spellcapcheck'.
{word} can be a badly spelled word followed by other text.This allows for joining two words that were split. Thesuggestions also include the following text, thus you canreplace a line.
{word} may also be a good word. Similar words will then bereturned.{word} itself is not included in the suggestions,although it may appear capitalized.
The spelling information for the current window is used. Thevalues of'spelllang' and'spellsuggest' are used.
Parameters:
{word} (string)
{max} (integer?)
{capital} (boolean?)
Return:
(string[])
split({string} [,{pattern} [,{keepempty}]])split()
Make aList out of{string}. When{pattern} is omitted orempty each white space separated sequence of charactersbecomes an item.Otherwise the string is split where{pattern} matches,removing the matched characters.'ignorecase' is not usedhere, add \c to ignore case./\cWhen the first or last item is empty it is omitted, unless the{keepempty} argument is given and it's non-zero.Other empty items are kept when{pattern} matches at least onecharacter or when{keepempty} is non-zero.Example:
let words = split(getline('.'), '\W\+')
To split a string in individual characters:
for c in split(mystring, '\zs') | endfor
If you want to keep the separator you can also use '\zs' atthe end of the pattern:
echo split('abc:def:ghi', ':\zs')
['abc:', 'def:', 'ghi']
Splitting a table where the first element can be empty:
let items = split(line, ':', 1)
The opposite function isjoin().
Parameters:
{string} (string)
{pattern} (string?)
{keepempty} (boolean?)
Return:
(string[])
sqrt({expr})sqrt()
Return the non-negative square root of Float{expr} as aFloat.{expr} must evaluate to aFloat or aNumber. When{expr}is negative the result is NaN (Not a Number). Returns 0.0 if{expr} is not aFloat or aNumber.Examples:
echo sqrt(100)
10.0
echo sqrt(-4.01)
str2float("nan")NaN may be different, it depends on system libraries.
Parameters:
{expr} (number)
Return:
(any)
srand([{expr}])srand()
Initialize seed used byrand():
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)
Parameters:
{expr} (number?)
Return:
(any)
state([{what}])state()
Return a string which contains characters indicating thecurrent state. Mostly useful in callbacks that want to dowork 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 aSafeState autocommand.
When SafeState is triggered and executes your autocommand, check withstate() 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 seemode().
When{what} is given only characters in this string will beadded. E.g, this checks if the screen has scrolled:
if state('s') == ''   " screen has not scrolled
These characters indicate the state, generally indicating thatsomething is busy: mhalfway a mapping, :normal command, feedkeys() orstuffed command ooperator pending, e.g. afterd aInsert mode autocomplete active xexecuting an autocommand Snot triggering SafeState, e.g. afterf or a count ccallback invoked, including timer (repeats forrecursiveness up to "ccc") sscreen has scrolled for messages
Parameters:
{what} (string?)
Return:
(any)
stdioopen({opts})stdioopen()
With--headless this opens stdin and stdout as achannel.May be called only once. Seechannel-stdio. stderr is nothandled by this function, seev:stderr.
Close the stdio handles withchanclose(). Usechansend()to send data to stdout, andrpcrequest() andrpcnotify()to communicate over RPC.
{opts} is a dictionary with these keys:on_stdin : callback invoked when stdin is written to. on_print : callback invoked when Nvim needs to print a message, with the message (whose type is string) as sole argument. stdin_buffered : read stdin inchannel-buffered mode. rpc : If set,msgpack-rpc will be used to communicate over stdioReturns:
channel-id on success (value is always 1)
0 on invalid arguments
Parameters:
{opts} (table)
Return:
(any)
stdpath({what})stdpath()E6100Returnsstandard-path locations of various default files anddirectories. The locations are driven bybase-directorieswhich you can configure via$NVIM_APPNAME or the$XDG_…environment variables.
{what} Type Description
cache String Cache directory: arbitrary temporary storage for plugins, etc.config String User configuration directory.init.vim is stored here.config_dirs List Other configuration directories.data String User data directory.data_dirs List Other data directories.log String Logs directory (for use by plugins too).run String Run directory: temporary, local storage for sockets, named pipes, etc.state String Session state: storage for backupdir, file drafts,shada, swap, undo,'viewdir'.
Example:
echo stdpath("config")
Parameters:
{what} ('cache'|'config'|'config_dirs'|'data'|'data_dirs'|'log'|'run'|'state')
Return:
(string|string[])
str2float({string} [,{quoted}])str2float()
Convert String{string} to a Float. This mostly works thesame as when using a floating point number in an expression,seefloating-point-format. But it's a bit more permissive.E.g., "1e40" is accepted, while in an expression you need towrite "1.0e40". The hexadecimal form "0x123" is alsoaccepted, but not others, like binary or octal.When{quoted} is present and non-zero then embedded singlequotes before the dot are ignored, thus "1'000.0" is athousand.Text after the number is silently ignored.The decimal point is always '.', no matter what the locale isset to. A comma ends the number: "12,345.67" is converted to12.0. You can strip out thousands separators withsubstitute():
let f = str2float(substitute(text, ',', '', 'g'))
Returns 0.0 if the conversion fails.
Parameters:
{string} (string)
{quoted} (boolean?)
Return:
(any)
str2list({string} [,{utf8}])str2list()
Return a list containing the number values which representeach character in String{string}. Examples:
echo str2list(" ")" returns [32]echo str2list("ABC")" returns [65, 66, 67]
list2str() does the opposite.
UTF-8 encoding is always used,{utf8} option has no effect,and exists only for backwards-compatibility.With UTF-8 composing characters are handled properly:
echo str2list("á")" returns [97, 769]
Parameters:
{string} (string)
{utf8} (boolean?)
Return:
(any)
str2nr({string} [,{base}])str2nr()
Convert string{string} to a number.{base} is the conversion base, it can be 2, 8, 10 or 16.When{quoted} is present and non-zero then embedded singlequotes are ignored, thus "1'000'000" is a million.
When{base} is omitted base 10 is used. This also means thata leading zero doesn't cause octal conversion to be used, aswith the default String to Number conversion. Example:
let nr = str2nr('0123')
When{base} is 16 a leading "0x" or "0X" is ignored. With adifferent base the result will be zero. Similarly, when{base} is 8 a leading "0", "0o" or "0O" is ignored, and when{base} is 2 a leading "0b" or "0B" is ignored.Text after the number is silently ignored.
Returns 0 if{string} is empty or on error.
Parameters:
{string} (string)
{base} (integer?)
Return:
(any)
strcharlen({string})strcharlen()
The result is a Number, which is the number of charactersin String{string}. Composing characters are ignored.strchars() can count the number of characters, countingcomposing characters separately.
Returns 0 if{string} is empty or on error.
Also seestrlen(),strdisplaywidth() andstrwidth().
Parameters:
{string} (string)
Return:
(any)
strcharpart({src},{start} [,{len} [,{skipcc}]])strcharpart()
Likestrpart() but using character index and length insteadof byte index and length.When{skipcc} is omitted or zero, composing characters arecounted separately.When{skipcc} set to 1, composing characters are treated as apart of the preceding base character, similar toslice().When a character index is used where a character does notexist it is omitted and counted as one character. Forexample:
echo strcharpart('abc', -1, 2)
results in 'a'.
Returns an empty string on error.
Parameters:
{src} (string)
{start} (integer)
{len} (integer?)
{skipcc} (boolean?)
Return:
(any)
strchars({string} [,{skipcc}])strchars()
The result is a Number, which is the number of charactersin String{string}.When{skipcc} is omitted or zero, composing characters arecounted separately.When{skipcc} set to 1, composing characters are ignored.strcharlen() always does this.
Returns zero on error.
Also seestrlen(),strdisplaywidth() andstrwidth().
{skipcc} is only available after 7.4.755. For backwardcompatibility, you can define a wrapper function:
if has("patch-7.4.755")  function s:strchars(str, skipcc)    return strchars(a:str, a:skipcc)  endfunctionelse  function s:strchars(str, skipcc)    if a:skipcc      return strlen(substitute(a:str, ".", "x", "g"))    else      return strchars(a:str)    endif  endfunctionendif
Parameters:
{string} (string)
{skipcc} (boolean?)
Return:
(integer)
strdisplaywidth({string} [,{col}])strdisplaywidth()
The result is a Number, which is the number of display cellsString{string} occupies on the screen when it starts at{col}(first column is zero). When{col} is omitted zero is used.Otherwise it is the screen column where to start. Thismatters for Tab characters.The option settings of the current window are used. Thismatters for anything that's displayed differently, such as'tabstop' and'display'.When{string} contains characters with East Asian Width ClassAmbiguous, this function's return value depends on'ambiwidth'.Returns zero on error.Also seestrlen(),strwidth() andstrchars().
Parameters:
{string} (string)
{col} (integer?)
Return:
(integer)
strftime({format} [,{time}])strftime()
The result is a String, which is a formatted date and time, asspecified by the{format} string. The given{time} is used,or the current time if no time is given. The accepted{format} depends on your system, thus this is not portable!See the manual page of the C function strftime() for theformat. The maximum length of the result is 80 characters.See alsolocaltime(),getftime() andstrptime().The language can be changed with the:language command.Examples:
echo strftime("%c")   " Sun Apr 27 11:49:23 1997echo strftime("%Y %b %d %X")   " 1997 Apr 27 11:53:25echo strftime("%y%m%d %T")   " 970427 11:53:55echo strftime("%H:%M")   " 11:55echo strftime("%c", getftime("file.c"))                                 " Show mod time of file.c.
Parameters:
{format} (string)
{time} (number?)
Return:
(string)
strgetchar({str},{index})strgetchar()
Get a Number corresponding to the character at{index} in{str}. This uses a zero-based character index, not a byteindex. Composing characters are considered separatecharacters here. Usenr2char() to convert the Number to aString.Returns -1 if{index} is invalid.Also seestrcharpart() andstrchars().
Parameters:
{str} (string)
{index} (integer)
Return:
(integer)
stridx({haystack},{needle} [,{start}])stridx()
The result is a Number, which gives the byte index in{haystack} of the first occurrence of the String{needle}.If{start} is specified, the search starts at index{start}.This can be used to find a second match:
let colon1 = stridx(line, ":")let colon2 = stridx(line, ":", colon1 + 1)
The search is done case-sensitive.For pattern searches usematch().-1 is returned if the{needle} does not occur in{haystack}.See alsostrridx().Examples:
echo stridx("An Example", "Example")     " 3echo stridx("Starting point", "Start")   " 0echo stridx("Starting point", "start")   " -1
strstr()strchr()stridx() works similar to the C function strstr(). When usedwith a single character it works similar to strchr().
Parameters:
{haystack} (string)
{needle} (string)
{start} (integer?)
Return:
(integer)
string({expr})string()
Return{expr} converted to a String. If{expr} is a Number,Float, String, Blob or a composition of them, then the resultcan be parsed back witheval().
{expr} typeresult
String'string'Number123Float123.123456 or 1.123456e8 orstr2float('inf') Funcreffunction('name') Blob0z00112233.44556677.8899List[item, item]Dictionary{key: value, key: value} Note that in String values the ' character is doubled.Also seestrtrans().Note 2: Output format is mostly compatible with YAML, exceptfor infinite and NaN floating-point values representationswhich usestr2float(). Strings are also dumped literally,only single quote is escaped, which does not allow using YAMLfor parsing back binary strings.eval() should always workfor strings and floats though, and this is the only officialmethod. Usemsgpackdump() orjson_encode() if you need toshare data with other applications.
Parameters:
{expr} (any)
Return:
(string)
strlen({string})strlen()
The result is a Number, which is the length of the String{string} in bytes.If the argument is a Number it is first converted to a String.For other types an error is given and zero is returned.If you want to count the number of multibyte characters usestrchars().Also seelen(),strdisplaywidth() andstrwidth().
Parameters:
{string} (string)
Return:
(integer)
strpart({src},{start} [,{len} [,{chars}]])strpart()
The result is a String, which is part of{src}, starting frombyte{start}, with the byte length{len}.When{chars} is present and TRUE then{len} is the number ofcharacters positions (composing characters are not countedseparately, thus "1" means one base character and anyfollowing composing characters).To count{start} as characters instead of bytes usestrcharpart().
When bytes are selected which do not exist, this doesn'tresult in an error, the bytes are simply omitted.If{len} is missing, the copy continues from{start} till theend of the{src}.
echo strpart("abcdefg", 3, 2)    " returns 'de'echo strpart("abcdefg", -2, 4)   " returns 'ab'echo strpart("abcdefg", 5, 4)    " returns 'fg'echo strpart("abcdefg", 3) " returns 'defg'
Note: To get the first character,{start} must be 0. Forexample, to get the character under the cursor:
strpart(getline("."), col(".") - 1, 1, v:true)
Returns an empty string on error.
Parameters:
{src} (string)
{start} (integer)
{len} (integer?)
{chars} (0|1?)
Return:
(string)
strptime({format},{timestring})strptime()
The result is a Number, which is a unix timestamp representingthe date and time in{timestring}, which is expected to matchthe format specified in{format}.
The accepted{format} depends on your system, thus this is notportable! See the manual page of the C function strptime()for the format. Especially avoid "%c". The value of $TZ alsomatters.
If the{timestring} cannot be parsed with{format} zero isreturned. If you do not know the format of{timestring} youcan try different{format} values until you get a non-zeroresult.
See alsostrftime().Examples:
echo strptime("%Y %b %d %X", "1997 Apr 27 11:49:23")
862156163
echo strftime("%c", strptime("%y%m%d %T", "970427 11:53:55"))
Sun Apr 27 11:53:55 1997
echo strftime("%c", strptime("%Y%m%d%H%M%S", "19970427115355") + 3600)
Sun Apr 27 12:53:55 1997
Parameters:
{format} (string)
{timestring} (string)
Return:
(integer)
strridx({haystack},{needle} [,{start}])strridx()
The result is a Number, which gives the byte index in{haystack} of the last occurrence of the String{needle}.When{start} is specified, matches beyond this index areignored. This can be used to find a match before a previousmatch:
let lastcomma = strridx(line, ",")let comma2 = strridx(line, ",", lastcomma - 1)
The search is done case-sensitive.For pattern searches usematch().-1 is returned if the{needle} does not occur in{haystack}.If the{needle} is empty the length of{haystack} is returned.See alsostridx(). Examples:
echo strridx("an angry armadillo", "an")     3
strrchr()
When used with a single character it works similar to the Cfunction strrchr().
Parameters:
{haystack} (string)
{needle} (string)
{start} (integer?)
Return:
(integer)
strtrans({string})strtrans()
The result is a String, which is{string} with all unprintablecharacters 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 ofstarting a new line.
Returns an empty string on error.
Parameters:
{string} (string)
Return:
(string)
strutf16len({string} [,{countcc}])strutf16len()
The result is a Number, which is the number of UTF-16 codeunits in String{string} (after converting it to UTF-16).
When{countcc} is TRUE, composing characters are countedseparately.When{countcc} is omitted or FALSE, composing characters areignored.
Returns zero on error.
Also seestrlen() andstrcharlen().Examples:
echo strutf16len('a')" returns 1echo strutf16len('©')" returns 1echo strutf16len('😊')" returns 2echo strutf16len('ą́')" returns 1echo strutf16len('ą́', v:true)" returns 3
Parameters:
{string} (string)
{countcc} (0|1?)
Return:
(integer)
strwidth({string})strwidth()
The result is a Number, which is the number of display cellsString{string} occupies. A Tab character is counted as onecell, alternatively usestrdisplaywidth().When{string} contains characters with East Asian Width ClassAmbiguous, this function's return value depends on'ambiwidth'.Returns zero on error.Also seestrlen(),strdisplaywidth() andstrchars().
Parameters:
{string} (string)
Return:
(integer)
submatch({nr} [,{list}])submatch()E935Only for an expression in a:substitute command orsubstitute() function.Returns the{nr}th submatch of the matched text. When{nr}is 0 the whole matched text is returned.Note that a NL in the string can stand for a line break of amulti-line match or a NUL character in the text.Also seesub-replace-expression.
If{list} is present and non-zero then submatch() returnsa list of strings, similar togetline() with two arguments.NL characters in the text represent NUL characters in thetext.Only returns more than one item for:substitute, insidesubstitute() this list will always contain one or zeroitems, since there are no real line breaks.
When substitute() is used recursively only the submatches inthe current (deepest) call can be obtained.
Returns an empty string or list on error.
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.
Parameters:
{nr} (integer)
{list} (nil?)
Return:
(string)
substitute({string},{pat},{sub},{flags})substitute()
The result is a String, which is a copy of{string}, in whichthe first match of{pat} is replaced with{sub}.When{flags} is "g", all matches of{pat} in{string} arereplaced. Otherwise{flags} should be "".
This works like the ":substitute" command (without any flags).But the matching with{pat} is always done like the'magic'option is set and'cpoptions' is empty (to make scriptsportable).'ignorecase' is still relevant, use/\c or/\Cif you want to ignore or match case and ignore'ignorecase'.'smartcase' is not used. Seestring-match for how{pat} isused.
A "~" in{sub} is not replaced with the previous{sub}.Note that some codes in{sub} have a special meaningsub-replace-special. For example, to replace something with"\n" (two characters), use "\\\\n" or '\\n'.
When{pat} does not match in{string},{string} is returnedunmodified.
Example:
let &path = substitute(&path, ",\\=[^,]*$", "", "")
This removes the last component of the'path' option.
echo substitute("testing", ".*", "\\U\\0", "")
results in "TESTING".
When{sub} starts with "\=", the remainder is interpreted asan expression. Seesub-replace-expression. Example:
echo substitute(s, '%\(\x\x\)',   \ '\=nr2char("0x" .. submatch(1))', 'g')
When{sub} is a Funcref that function is called, with oneoptional argument. Example:
echo substitute(s, '%\(\x\x\)', SubNr, 'g')
The optional argument is a list which contains the wholematched string and up to nine submatches, like whatsubmatch() returns. Example:
echo substitute(s, '%\(\x\x\)', {m -> '0x' .. m[1]}, 'g')
Returns an empty string on error.
Parameters:
{string} (string)
{pat} (string)
{sub} (string)
{flags} (string)
Return:
(string)
swapfilelist()swapfilelist()
Returns a list of swap file names, like what "vim -r" shows.See the-r command argument. The'directory' option is usedfor the directories to inspect. If you only want to get alist of swap files in the current directory then temporarilyset'directory' to a dot:
let save_dir = &directorylet &directory = '.'let swapfiles = swapfilelist()let &directory = save_dir
Return:
(string[])
swapinfo({fname})swapinfo()
The result is a dictionary, which holds information about theswapfile{fname}. The available fields are:version Vim versionuseruser namehosthost namefnameoriginal file namepidPID of the Nvim process that created the swapfile, or zero if not running.mtimelast modification time in secondsinodeOptional: INODE number of the filedirty1 if file was modified, 0 if notIn case of failure an "error" item is added with the reason:Cannot open file: file not found or in accessibleCannot read file: cannot read first blockNot a swap file: does not contain correct block IDMagic number mismatch: Info in first block is invalid
Parameters:
{fname} (string)
Return:
(any)
swapname({buf})swapname()
The result is the swap file path of the buffer{buf}.For the use of{buf}, seebufname() above.If buffer{buf} is the current buffer, the result is equal to:swapname (unless there is no swap file).If buffer{buf} has no swap file, returns an empty string.
Parameters:
{buf} (integer|string)
Return:
(string)
synID({lnum},{col},{trans})synID()
The result is a Number, which is the syntax ID at the position{lnum} and{col} in the current window.The syntax ID can be used withsynIDattr() andsynIDtrans() to obtain syntax information about text.
{col} is 1 for the leftmost column,{lnum} is 1 for the firstline.'synmaxcol' applies, in a longer line zero is returned.Note that when the position is after the last character,that's where the cursor can be in Insert mode, synID() returnszero.{lnum} is used like withgetline().
When{trans} isTRUE, transparent items are reduced to theitem that they reveal. This is useful when wanting to knowthe effective color. When{trans} isFALSE, the transparentitem is returned. This is useful when wanting to know whichsyntax item is effective (e.g. inside parens).Warning: This function can be very slow. Best speed isobtained by going through the file in forward direction.
Returns zero on error.
Example (echoes the name of the syntax item under the cursor):
echo synIDattr(synID(line("."), col("."), 1), "name")
Parameters:
{lnum} (integer|string)
{col} (integer)
{trans} (0|1)
Return:
(integer)
synIDattr({synID},{what} [,{mode}])synIDattr()
The result is a String, which is the{what} attribute ofsyntax ID{synID}. This can be used to obtain informationabout a syntax item.{mode} can be "gui" or "cterm", to get the attributesfor that mode. When{mode} is omitted, or an invalid value isused, the attributes for the currently active highlighting areused (GUI or cterm).Use synIDtrans() to follow linked highlight groups.{what}result"name"the name of the syntax item"fg"foreground color (GUI: color name used to setthe color, cterm: color number as a string,term: empty string)"bg"background color (as with "fg")"font"font name (only available in the GUI)highlight-font "sp"special color (as with "fg")guisp"fg#"like "fg", but for the GUI and the GUI isrunning the name in "#RRGGBB" form"bg#"like "fg#" for "bg""sp#"like "fg#" for "sp""bold""1" if bold"italic""1" if italic"reverse""1" if reverse"inverse""1" if inverse (= reverse)"standout""1" if standout"underline""1" if underlined"undercurl""1" if undercurled"underdouble""1" if double underlined"underdotted""1" if dotted underlined"underdashed""1" if dashed underlined"strikethrough""1" if struckthrough"altfont""1" if alternative font"nocombine""1" if nocombine
Returns an empty string on error.
Example (echoes the color of the syntax item under thecursor):
echo synIDattr(synIDtrans(synID(line("."), col("."), 1)), "fg")
Can also be used as amethod:
echo synID(line("."), col("."), 1)->synIDtrans()->synIDattr("fg")
Parameters:
{synID} (integer)
{what} (string)
{mode} (string?)
Return:
(string)
synIDtrans({synID})synIDtrans()
The result is a Number, which is the translated syntax ID of{synID}. This is the syntax group ID of what is being used tohighlight the character. Highlight links given with":highlight link" are followed.
Returns zero on error.
Parameters:
{synID} (integer)
Return:
(integer)
synconcealed({lnum},{col})synconcealed()
The result is aList with currently three items:1. The first item in the list is 0 if the character at the position{lnum} and{col} is not part of a concealable region, 1 if it is.{lnum} is used like withgetline().2. The second item in the list is a string. If the first item is 1, the second item contains the text which will be displayed in place of the concealed text, depending on the current setting of'conceallevel' and'listchars'.3. The third and final item in the list is a number representing the specific syntax region matched in the line. When the character is not concealed the value is zero. This allows detection of the beginning of a new concealable region if there are two consecutive regions with the same replacement character. For an example, if the text is "123456" and both "23" and "45" are concealed and replaced by the character "X", then:
callreturns
synconcealed(lnum, 1) [0, '', 0]synconcealed(lnum, 2) [1, 'X', 1]synconcealed(lnum, 3) [1, 'X', 1]synconcealed(lnum, 4) [1, 'X', 2]synconcealed(lnum, 5) [1, 'X', 2]synconcealed(lnum, 6) [0, '', 0]
Note: Doesn't considermatchadd() highlighting items,since syntax and matching highlighting are two differentmechanismssyntax-vs-match.
Parameters:
{lnum} (integer|string)
{col} (integer)
Return:
([integer, string, integer])
synstack({lnum},{col})synstack()
Return aList, which is the stack of syntax items at theposition{lnum} and{col} in the current window.{lnum} isused like withgetline(). Each item in the List is an IDlike whatsynID() returns.The first item in the List is the outer region, following areitems contained in that one. The last one is whatsynID()returns, unless not the whole item is highlighted or it is atransparent item.This function is useful for debugging a syntax file.Example that shows the syntax stack under the cursor:
for id in synstack(line("."), col("."))   echo synIDattr(id, "name")endfor
When the position specified with{lnum} and{col} is invalidan empty list is returned. The position just after the lastcharacter in a line and the first column in an empty line arevalid positions.
Parameters:
{lnum} (integer|string)
{col} (integer)
Return:
(integer[])
system({cmd} [,{input}])system()E677Note: Prefervim.system() in Lua.
Gets the output of{cmd} as astring (systemlist() returnsaList) and setsv:shell_error to the error code.{cmd} is treated as injobstart():If{cmd} is a List it runs directly (no'shell').If{cmd} is a String it runs in the'shell', like this:
call jobstart(split(&shell) + split(&shellcmdflag) + ['{cmd}'])
Not to be used for interactive commands.
Result is a String, filtered to avoid platform-specific quirks:
<CR><NL> is replaced with<NL>
NUL characters are replaced with SOH (0x01)
Example:
echo system(['ls', expand('%:h')])
If{input} is a string it is written to a pipe and passed asstdin to the command. The string is written as-is, lineseparators are not changed.If{input} is aList it is written to the pipe aswritefile() does with{binary} set to "b" (i.e. witha newline between each list item, and newlines inside listitems converted to NULs).When{input} is given and is a valid buffer id, the content ofthe buffer is written to the file line by line, each lineterminated by NL (and NUL where the text has NL).E5677
Note: system() cannot write to or read from backgrounded ("&")shell commands, e.g.:
echo system("cat - &", "foo")
which is equivalent to:
$ echo foo | bash -c 'cat - &'
The pipes are disconnected (unless overridden by shellredirection syntax) before input can reach it. Usejobstart() instead.
Note: Useshellescape() or::S withexpand() orfnamemodify() to escape special characters in a commandargument.'shellquote' and'shellxquote' must be properlyconfigured. Example:
echo system('ls '..shellescape(expand('%:h')))echo system('ls '..expand('%:h:S'))
Unlike ":!cmd" there is no automatic check for changed files.Use:checktime to force a check.
Parameters:
{cmd} (string|string[])
{input} (string|string[]|integer?)
Return:
(string)
systemlist({cmd} [,{input} [,{keepempty}]])systemlist()
Same assystem(), but returns aList with lines (parts ofoutput separated by NL) with NULs transformed into NLs. Outputis the same asreadfile() will output with{binary} argumentset to "b", except that a final newline is not preserved,unless{keepempty} is non-zero.Note that on MS-Windows you may get trailing CR characters.
To see the difference between "echo hello" and "echo -n hello"usesystem() andsplit():
echo split(system('echo hello'), '\n', 1)
Returns an empty string on error.
Parameters:
{cmd} (string|string[])
{input} (string|string[]|integer?)
{keepempty} (integer?)
Return:
(string[])
tabpagebuflist([{arg}])tabpagebuflist()
The result is aList, where each item is the number of thebuffer associated with each window in the current tab page.{arg} specifies the number of the tab page to be used. Whenomitted 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.
Parameters:
{arg} (integer?)
Return:
(any)
tabpagenr([{arg}])tabpagenr()
The result is a Number, which is the number of the currenttab page. The first tab page has number 1.
The optional argument{arg} supports the following values:$the number of the last tab page (the tab pagecount).#the number of the last accessed tab page(whereg<Tab> goes to). If there is noprevious tab page, 0 is returned.The number can be used with the:tab command.
Returns zero on error.
Parameters:
{arg} ('$'|'#'?)
Return:
(integer)
tabpagewinnr({tabarg} [,{arg}])tabpagewinnr()
Likewinnr() but for tab page{tabarg}.{tabarg} specifies the number of tab page to be used.{arg} is used like withwinnr():
When omitted the current window number is returned. This is the window which will be used when going to this tab page.
When "$" the number of windows is returned.
When "#" the previous window nr is returned.Useful examples:
tabpagewinnr(1)    " current window of tab page 1tabpagewinnr(4, '$')    " number of windows in tab page 4
When{tabarg} is invalid zero is returned.
Parameters:
{tabarg} (integer)
{arg} ('$'|'#'?)
Return:
(integer)
tagfiles()tagfiles()
Returns aList with the file names used to search for tagsfor the current buffer. This is the'tags' option expanded.
Return:
(string[])
taglist({expr} [,{filename}])taglist()
Returns aList of tags matching the regular expression{expr}.
If{filename} is passed it is used to prioritize the resultsin the same way that:tselect does. Seetag-priority.{filename} should be the full path of the file.
Each list item is a dictionary with at least the followingentries:nameName of the tag.filenameName of the file where the tag isdefined. It is either relative to thecurrent directory or a full path.cmdEx command used to locate the tag inthe file.kindType of the tag. The value for thisentry depends on the language specifickind values. Only available whenusing a tags file generated byUniversal/Exuberant ctags or hdrtag.staticA file specific tag. Refer tostatic-tag for more information.More entries may be present, depending on the content of thetags file: access, implementation, inherits and signature.Refer to the ctags documentation for information about thesefields. For C code the fields "struct", "class" and "enum"may appear, they give the name of the entity the tag iscontained in.
The ex-command "cmd" can be either an ex search pattern, aline number or a line number followed by a byte number.
If there are no matching tags, then an empty list is returned.
To get an exact tag match, the anchors '^' and '$' should beused in{expr}. This also make the function work faster.Refer totag-regexp for more information about the tagsearch regular expression pattern.
Refer to'tags' for information about how the tags file islocated by Vim. Refer totags-file-format for the format ofthe tags file generated by the different ctags tools.
Parameters:
{expr} (any)
{filename} (string?)
Return:
(any)
tan({expr})tan()
Return the tangent of{expr}, measured in radians, as aFloatin the range [-inf, inf].{expr} must evaluate to aFloat or aNumber.Returns 0.0 if{expr} is not aFloat or aNumber.Examples:
echo tan(10)
0.648361
echo tan(-4.01)
-1.181502
Parameters:
{expr} (number)
Return:
(number)
tanh({expr})tanh()
Return the hyperbolic tangent of{expr} as aFloat in therange [-1, 1].{expr} must evaluate to aFloat or aNumber.Returns 0.0 if{expr} is not aFloat or aNumber.Examples:
echo tanh(0.5)
0.462117
echo tanh(-1)
-0.761594
Parameters:
{expr} (number)
Return:
(number)
tempname()tempname()
Generates a (non-existent) filename located in the Nvim roottempdir. Scripts can use the filename as a temporary file.Example:
let tmpfile = tempname()exe "redir > " .. tmpfile
Return:
(string)
test_garbagecollect_now()test_garbagecollect_now()
Likegarbagecollect(), but executed right away. This mustonly be called directly to avoid any structure to existinternally, andv:testing must have been set before callingany function.E1142
Return:
(any)
timer_info([{id}])timer_info()
Return a list with information about timers.When{id} is given only information about this timer isreturned. When timer{id} does not exist an empty list isreturned.When{id} is omitted information about all timers is returned.
For each timer the information is stored in aDictionary withthese items: "id" the timer ID "time" time the timer was started with "repeat" number of times the timer will still fire; -1 means forever "callback" the callback
Parameters:
{id} (integer?)
Return:
(any)
timer_pause({timer},{paused})timer_pause()
Pause or unpause a timer. A paused timer does not invoke itscallback when its time expires. Unpausing a timer may causethe callback to be invoked almost immediately if enough timehas passed.
Pausing a timer is useful to avoid the callback to be calledfor a short time.
If{paused} evaluates to a non-zero Number or a non-emptyString, then the timer is paused, otherwise it is unpaused.Seenon-zero-arg.
Parameters:
{timer} (integer)
{paused} (boolean)
Return:
(any)
timer_start({time},{callback} [,{options}])timer_start()timerCreate a timer and return the timer ID.
{time} is the waiting time in milliseconds. This is theminimum time before invoking the callback. When the system isbusy or Vim is not waiting for input the time will be longer.Zero can be used to execute the callback when Vim is back inthe main loop.
{callback} is the function to call. It can be the name of afunction or aFuncref. It is called with one argument, whichis the timer ID. The callback is only invoked when Vim iswaiting for input.
{options} is a dictionary. Supported entries: "repeat"Number of times to repeat the callback.-1 means forever. Default is 1.If the timer causes an error three times in arow the repeat is cancelled.
Returns -1 on error.
Example:
func MyHandler(timer)  echo 'Handler called'endfunclet timer = timer_start(500, 'MyHandler',        \ {'repeat': 3})
This invokes MyHandler() three times at 500 msec intervals.
Parameters:
{time} (number)
{callback} (string|function)
{options} (table?)
Return:
(any)
timer_stop({timer})timer_stop()
Stop a timer. The timer callback will no longer be invoked.{timer} is an ID returned by timer_start(), thus it must be aNumber. If{timer} does not exist there is no error.
Parameters:
{timer} (integer)
Return:
(any)
timer_stopall()timer_stopall()
Stop all timers. The timer callbacks will no longer beinvoked. Useful if some timers is misbehaving. If there areno timers there is no error.
Return:
(any)
tolower({expr})tolower()
The result is a copy of the String given, with all uppercasecharacters turned into lowercase (just like applyinggu tothe string). Returns an empty string on error.
Parameters:
{expr} (string)
Return:
(string)
toupper({expr})toupper()
The result is a copy of the String given, with all lowercasecharacters turned into uppercase (just like applyinggU tothe string). Returns an empty string on error.
Parameters:
{expr} (string)
Return:
(string)
tr({src},{fromstr},{tostr})tr()
The result is a copy of the{src} string with all characterswhich appear in{fromstr} replaced by the character in thatposition in the{tostr} string. Thus the first character in{fromstr} is translated into the first character in{tostr}and so on. Exactly like the unix "tr" command.This code also deals with multibyte characters properly.
Returns an empty string on error.
Examples:
echo tr("hello there", "ht", "HT")
returns "Hello THere"
echo tr("<blob>", "<>", "{}")
returns "{blob}"
Parameters:
{src} (string)
{fromstr} (string)
{tostr} (string)
Return:
(string)
trim({text} [,{mask} [,{dir}]])trim()
Return{text} as a String where any character in{mask} isremoved from the beginning and/or end of{text}.
If{mask} is not given, or is an empty string,{mask} is allcharacters up to 0x20, which includes Tab, space, NL and CR,plus the non-breaking space character 0xa0.
The optional{dir} argument specifies where to remove thecharacters:0remove from the beginning and end of{text}1remove only at the beginning of{text}2remove only at the end of{text}When omitted both ends are trimmed.
This function deals with multibyte characters properly.Returns an empty string on error.
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"
Parameters:
{text} (string)
{mask} (string?)
{dir} (0|1|2?)
Return:
(string)
trunc({expr})trunc()
Return the largest integral value with magnitude less than orequal to{expr} as aFloat (truncate towards zero).{expr} must evaluate to aFloat or aNumber.Returns 0.0 if{expr} is not aFloat or aNumber.Examples:
echo trunc(1.456)
1.0
echo trunc(-5.456)
-5.0
echo trunc(4.0)
4.0
Parameters:
{expr} (number)
Return:
(integer)
type({expr})type()
The result is a Number representing the type of{expr}.Instead of using the number directly, it is better to use thev:t_ variable that has the value:Number: 0v:t_numberString: 1v:t_stringFuncref: 2v:t_funcList: 3v:t_listDictionary: 4v:t_dictFloat: 5v:t_floatBoolean: 6v:t_bool (v:false andv:true)Null: 7 (v:null)Blob: 10v:t_blobFor backward compatibility, this method can be used:
if type(myvar) == type(0) | endifif type(myvar) == type("") | endifif type(myvar) == type(function("tr")) | endifif type(myvar) == type([]) | endifif type(myvar) == type({}) | endifif type(myvar) == type(0.0) | endifif type(myvar) == type(v:true) | endif
In place of checking forv:null type it is better to checkforv:null directly as it is the only value of this type:
if myvar is v:null | endif
To check if the v:t_ variables exist use this:
if exists('v:t_number') | endif
Parameters:
{expr} (any)
Return:
(integer)
undofile({name})undofile()
Return the name of the undo file that would be used for a filewith name{name} when writing. This uses the'undodir'option, finding directories that exist. It does not check ifthe undo file exists.{name} is always expanded to the full path, since that is whatis used internally.If{name} is empty undofile() returns an empty string, since abuffer without a file name will not write an undo file.Useful in combination with:wundo and:rundo.
Parameters:
{name} (string)
Return:
(string)
undotree([{buf}])undotree()
Return the current state of the undo tree for the currentbuffer, or for a specific buffer if{buf} is given. Theresult is a dictionary with the following items: "seq_last"The highest undo sequence number used. "seq_cur"The sequence number of the current position inthe undo tree. This differs from "seq_last"when some changes were undone. "time_cur"Time last used for:earlier and relatedcommands. Usestrftime() to convert tosomething readable. "save_last"Number of the last file write. Zero when nowrite yet. "save_cur"Number of the current position in the undotree. "synced"Non-zero when the last undo block was synced.This happens when waiting from input from theuser. Seeundo-blocks. "entries"A list of dictionaries with information aboutundo blocks.
The first item in the "entries" list is the oldest undo item.Each List item is aDictionary with these items: "seq"Undo sequence number. Same as what appears in:undolist. "time"Timestamp when the change happened. Usestrftime() to convert to something readable. "newhead"Only appears in the item that is the last onethat was added. This marks the last changeand where further changes will be added. "curhead"Only appears in the item that is the last onethat was undone. This marks the currentposition in the undo tree, the block that willbe used by a redo command. When nothing wasundone after the last change this item willnot appear anywhere. "save"Only appears on the last block before a filewrite. The number is the write count. Thefirst write has number 1, the last one the"save_last" mentioned above. "alt"Alternate entry. This is again a List of undoblocks. Each item may again have an "alt"item.
Parameters:
{buf} (integer|string?)
Return:
(vim.fn.undotree.ret)
uniq({list} [,{func} [,{dict}]])uniq()E882Note: Prefervim.list.unique() in Lua.
Remove second and succeeding copies of repeated adjacent{list} items in-place. Returns{list}. If you want a listto remain unmodified make a copy first:
let newlist = uniq(copy(mylist))
The default compare function uses the string representation ofeach item. For the use of{func} and{dict} seesort().For deduplicating text in the current buffer see:uniq.
Returns zero if{list} is not aList.
Parameters:
{list} (any)
{func} (any?)
{dict} (any?)
Return:
(any[]|0)
utf16idx({string},{idx} [,{countcc} [,{charidx}]])utf16idx()
Same ascharidx() but returns the UTF-16 code unit index ofthe byte at{idx} in{string} (after converting it to UTF-16).
When{charidx} is present and TRUE,{idx} is used as thecharacter index in the String{string} instead of as the byteindex.An{idx} in the middle of a UTF-8 sequence is roundeddownwards to the beginning of that sequence.
Returns -1 if the arguments are invalid or if there are lessthan{idx} bytes in{string}. If there are exactly{idx} bytesthe length of the string in UTF-16 code units is returned.
Seebyteidx() andbyteidxcomp() for getting the byte indexfrom the UTF-16 index andcharidx() for getting thecharacter index from the UTF-16 index.Refer tostring-offset-encoding for more information.Examples:
echo utf16idx('a😊😊', 3)" returns 2echo utf16idx('a😊😊', 7)" returns 4echo utf16idx('a😊😊', 1, 0, 1)" returns 2echo utf16idx('a😊😊', 2, 0, 1)" returns 4echo utf16idx('aą́c', 6)" returns 2echo utf16idx('aą́c', 6, 1)" returns 4echo utf16idx('a😊😊', 9)" returns -1
Parameters:
{string} (string)
{idx} (integer)
{countcc} (boolean?)
{charidx} (boolean?)
Return:
(integer)
values({dict})values()
Return aList with all the values of{dict}. TheList isin arbitrary order. Also seeitems() andkeys().Returns zero if{dict} is not aDict.
Parameters:
{dict} (any)
Return:
(any)
virtcol({expr} [,{list} [,{winid}]])virtcol()
The result is a Number, which is the screen column of the fileposition given with{expr}. That is, the total number ofscreen cells occupied by the part of the line until the end ofthe character at that position. When there is a<Tab> at theposition, the returned Number will be the column at the end ofthe<Tab>. For example, for a<Tab> in column 1, with'ts'set to 8, it returns 8.conceal is ignored.For the byte position usecol().
For the use of{expr} seegetpos() andcol().When{expr} is "$", it means the end of the cursor line, sothe result is the number of cells in the cursor line plus one.
When'virtualedit' is used{expr} can be [lnum, col, off],where "off" is the offset in screen columns from the start ofthe character. E.g., a position within a<Tab> or after thelast character. When "off" is omitted zero is used. WhenVirtual editing is active in the current mode, a positionbeyond the end of the line can be returned. Also see'virtualedit'
If{list} is present and non-zero then virtcol() returns aList with the first and last screen position occupied by thecharacter.
With the optional{winid} argument the values are obtained forthat window instead of the current window.
Note that only marks in the current file can be used.Examples:
" With text "foo^Lbar" and cursor on the "^L":echo virtcol(".")" returns 5echo virtcol(".", 1)" returns [4, 5]echo virtcol("$")" returns 9" With text "  there", with 't at 'h':echo virtcol("'t")" returns 6
The first column is 1. 0 or [0, 0] is returned for an error.
A more advanced example that echoes the maximum length ofall lines:
echo max(map(range(1, line('$')), "virtcol([v:val, '$'])"))
Parameters:
{expr} (string|any[])
{list} (boolean?)
{winid} (integer?)
Return:
(integer|[integer, integer])
virtcol2col({winid},{lnum},{col})virtcol2col()
The result is a Number, which is the byte index of thecharacter in window{winid} at buffer line{lnum} and virtualcolumn{col}.
If buffer line{lnum} is an empty line, 0 is returned.
If{col} is greater than the last virtual column in line{lnum}, then the byte index of the character at the lastvirtual column is returned.
For a multi-byte character, the column number of the firstbyte in the character is returned.
The{winid} argument can be the window number or thewindow-ID. If this is zero, then the current window is used.
Returns -1 if the window{winid} doesn't exist or the bufferline{lnum} or virtual column{col} is invalid.
See alsoscreenpos(),virtcol() andcol().
Parameters:
{winid} (integer)
{lnum} (integer)
{col} (integer)
Return:
(integer)
visualmode([{expr}])visualmode()
The result is a String, which describes the last Visual modeused in the current buffer. Initially it returns an emptystring, but once Visual mode has been used, it returns "v","V", or "<CTRL-V>" (a singleCTRL-V character) forcharacter-wise, line-wise, or block-wise Visual moderespectively.Example:
exe "normal " .. visualmode()
This enters the same Visual mode as before. It is also usefulin scripts if you wish to act differently depending on theVisual mode that was used.If Visual mode is active, usemode() to get the Visual mode(e.g., in a:vmap).If{expr} is supplied and it evaluates to a non-zero Number ora non-empty String, then the Visual mode will be cleared andthe old value is returned. Seenon-zero-arg.
Parameters:
{expr} (boolean?)
Return:
(string)
wait({timeout},{condition} [,{interval}])wait()
Waits until{condition} evaluates toTRUE, where{condition}is aFuncref orstring containing an expression.
{timeout} is the maximum waiting time in milliseconds, -1means forever.
Condition is evaluated on user events, internal events, andevery{interval} milliseconds (default: 200).
Returns a status integer:0 if the condition was satisfied before timeout-1 if the timeout was exceeded-2 if the function was interrupted (byCTRL-C)-3 if an error occurred
Parameters:
{timeout} (integer)
{condition} (any)
{interval} (number?)
Return:
(any)
wildmenumode()wildmenumode()
ReturnsTRUE when the wildmenu is active andFALSEotherwise. See'wildmenu' and'wildmode'.This can be used in mappings to handle the'wildcharm' optiongracefully. (Makes only sense withmapmode-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).
Return:
(any)
wildtrigger()wildtrigger()
Start wildcard expansion in the command-line, using thebehavior defined by the'wildmode' and'wildoptions' settings.
This function also enables completion in search patterns suchas/,?,:s,:g,:v and:vimgrep.
Unlike pressing'wildchar' manually, this function does notproduce a beep when no matches are found and generallyoperates more quietly. This makes it suitable for triggeringcompletion automatically.
Note: After navigating command-line history, the first call towildtrigger() is a no-op; a second call is needed to startexpansion. This is to support history navigation incommand-line autocompletion.
Seecmdline-autocompletion.
Return value is always 0.
Return:
(number)
win_execute({id},{command} [,{silent}])win_execute()
Likeexecute() but in the context of window{id}.The window will temporarily be made the current window,without triggering autocommands or changing directory. Whenexecuting{command} autocommands will be triggered, this mayhave unexpected side effects. Use:noautocmd if needed.Example:
call win_execute(winid, 'syntax enable')
Doing the same withsetwinvar() would not triggerautocommands and not actually show syntax highlighting.
When window{id} does not exist then no error is given andan empty string is returned.
Parameters:
{id} (integer)
{command} (string)
{silent} (boolean?)
Return:
(any)
win_findbuf({bufnr})win_findbuf()
Returns aList withwindow-IDs for windows that containbuffer{bufnr}. When there is none the list is empty.
Parameters:
{bufnr} (integer)
Return:
(integer[])
win_getid([{win} [,{tab}]])win_getid()
Get thewindow-ID for the specified window.When{win} is missing use the current window.With{win} this is the window number. The top window hasnumber 1.Without{tab} use the current tab, otherwise the tab withnumber{tab}. The first tab has number one.Return zero if the window cannot be found.
Parameters:
{win} (integer?)
{tab} (integer?)
Return:
(integer)
win_gettype([{nr}])win_gettype()
Return the type of the window:"autocmd"autocommand window. Temporary windowused to execute autocommands."command"command-line windowcmdwin(empty)normal window"loclist"location-list-window "popup"floating windowapi-floatwin"preview"preview windowpreview-window"quickfix"quickfix-window "unknown"window{nr} not found
When{nr} is omitted return the type of the current window.When{nr} is given return the type of this window by number orwindow-ID.
Also see the'buftype' option.
Parameters:
{nr} (integer?)
Return:
('autocmd'|'command'|''|'loclist'|'popup'|'preview'|'quickfix'|'unknown')
win_gotoid({expr})win_gotoid()
Go to window with ID{expr}. This may also change the currenttabpage.Return TRUE if successful, FALSE if the window cannot be found.
Parameters:
{expr} (integer)
Return:
(0|1)
win_id2tabwin({expr})win_id2tabwin()
Return a list with the tab number and window number of windowwith ID{expr}: [tabnr, winnr].Return [0, 0] if the window cannot be found.
Parameters:
{expr} (integer)
Return:
(any)
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.
Parameters:
{expr} (integer)
Return:
(integer)
win_move_separator({nr},{offset})win_move_separator()
Move window{nr}'s vertical separator (i.e., the right border)by{offset} columns, as if being dragged by the mouse.{nr}can be a window number orwindow-ID. A positive{offset}moves right and a negative{offset} moves left. Moving awindow's vertical separator will change the width of thewindow and the width of other windows adjacent to the verticalseparator. The magnitude of movement may be smaller thanspecified (e.g., as a consequence of maintaining'winminwidth'). Returns TRUE if the window can be found andFALSE otherwise.This will fail for the rightmost window and a full-widthwindow, since it has no separator on the right.Only works for the current tab page.E1308
Parameters:
{nr} (integer)
{offset} (integer)
Return:
(any)
win_move_statusline({nr},{offset})win_move_statusline()
Move window{nr}'s status line (i.e., the bottom border) by{offset} rows, as if being dragged by the mouse.{nr} can be awindow number orwindow-ID. A positive{offset} moves downand a negative{offset} moves up. Moving a window's statusline will change the height of the window and the height ofother windows adjacent to the status line. The magnitude ofmovement may be smaller than specified (e.g., as a consequenceof maintaining'winminheight'). Returns TRUE if the window canbe found and FALSE otherwise.Only works for the current tab page.
Parameters:
{nr} (integer)
{offset} (integer)
Return:
(any)
win_screenpos({nr})win_screenpos()
Return the screen position of window{nr} as a list with twonumbers: [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 thewindow-ID. Use zerofor the current window.Returns [0, 0] if the window cannot be found.
Parameters:
{nr} (integer)
Return:
(any)
win_splitmove({nr},{target} [,{options}])win_splitmove()
Temporarily switch to window{target}, then move window{nr}to a new split adjacent to{target}.Unlike commands such as:split, no new windows are created(thewindow-ID of window{nr} is unchanged after the move).
Both{nr} and{target} can be window numbers orwindow-IDs.Both must be in the current tab page.
Returns zero for success, non-zero for failure.
{options} is aDictionary with the following optional entries: "vertical"When TRUE, the split is created vertically,like with:vsplit. "rightbelow"When TRUE, the split is made below or to theright (if vertical). When FALSE, it is doneabove or to the left (if vertical). When notpresent, the values of'splitbelow' and'splitright' are used.
Parameters:
{nr} (integer)
{target} (integer)
{options} (table?)
Return:
(any)
winbufnr({nr})winbufnr()
The result is a Number, which is the number of the bufferassociated with window{nr}.{nr} can be the window number orthewindow-ID.When{nr} is zero, the number of the buffer in the currentwindow is returned.When window{nr} doesn't exist, -1 is returned.Example:
echo "The file in the current window is " .. bufname(winbufnr(0))
Parameters:
{nr} (integer)
Return:
(integer)
wincol()wincol()
The result is a Number, which is the virtual column of thecursor in the window. This is counting screen cells from theleft side of the window. The leftmost column is one.
Return:
(integer)
windowsversion()windowsversion()
The result is a String. For MS-Windows it indicates the OSversion. E.g, Windows 10 is "10.0", Windows 8 is "6.2",Windows XP is "5.1". For non-MS-Windows systems the result isan empty string.
Return:
(string)
winheight({nr})winheight()
Gets the height ofwindow-ID{nr} (zero for "currentwindow"), excluding any'winbar' and'statusline'. Returns -1if window{nr} doesn't exist. An existing window always hasa height of zero or more.
Examples:
echo "Current window has " .. winheight(0) .. " lines."
Parameters:
{nr} (integer)
Return:
(integer)
winlayout([{tabnr}])winlayout()
The result is a nested List containing the layout of windowsin a tabpage.
Without{tabnr} use the current tabpage, otherwise the tabpagewith number{tabnr}. If the tabpage{tabnr} is not found,returns an empty list.
For a leaf window, it returns:
["leaf", {winid}]
For horizontally split windows, which form a column, itreturns:
["col", [{nested list of windows}]]
For vertically split windows, which form a row, it returns:
["row", [{nested list of windows}]]
Example:
" Only one window in the tab pageecho winlayout()
['leaf', 1000]
" Two horizontally split windowsecho winlayout()
['col', [['leaf', 1000], ['leaf', 1001]]]
" The second tab page, with three horizontally split" windows, with two vertically split windows in the" middle windowecho winlayout(2)
['col', [['leaf', 1002], ['row', [['leaf', 1003],                    ['leaf', 1001]]], ['leaf', 1000]]]
Parameters:
{tabnr} (integer?)
Return:
(vim.fn.winlayout.ret)
winline()winline()
The result is a Number, which is the screen line of the cursorin the window. This is counting screen lines from the top ofthe window. The first line is one.If the cursor was moved the view on the file will be updatedfirst, this may cause a scroll.
Return:
(integer)
winnr([{arg}])winnr()
The result is a Number, which is the number of the currentwindow. The top window has number 1.Returns zero for a hidden or nonfocusable window, unlessit is the current window.
The optional argument{arg} supports the following values:$the number of the last window (the windowcount).#the number of the last accessed window (whereCTRL-W_p goes to). If there is no previouswindow or it is in another tab page 0 isreturned. May refer to the current window insome cases (e.g. when evaluating'statusline'expressions).{N}jthe number of the Nth window below thecurrent window (whereCTRL-W_j goes to).{N}kthe number of the Nth window above the currentwindow (whereCTRL-W_k goes to).{N}hthe number of the Nth window left of thecurrent window (whereCTRL-W_h goes to).{N}lthe number of the Nth window right of thecurrent window (whereCTRL-W_l goes to).The number can be used withCTRL-W_w and ":wincmd w":wincmd.When{arg} is invalid an error is given and zero is returned.Also seetabpagewinnr() andwin_getid().Examples:
let window_count = winnr('$')let prev_window = winnr('#')let wnum = winnr('3k')
Parameters:
{arg} (string|integer?)
Return:
(integer)
winrestcmd()winrestcmd()
Returns a sequence of:resize commands that should restorethe current window sizes. Only works properly when no windowsare opened or closed and the current window and tab page isunchanged.Example:
let cmd = winrestcmd()call MessWithWindowSizes()exe cmd
Return:
(string)
winrestview({dict})winrestview()
Uses theDictionary returned bywinsaveview() to restorethe view of the current window.Note: The{dict} does not have to contain all values, that arereturned bywinsaveview(). If values are missing, thosesettings won't be restored. So you can use:
call winrestview({'curswant': 4})
This will only set the curswant value (the column the cursorwants to move on vertical movements) of the cursor to column 5(yes, that is 5), while all other settings will remain thesame. This is useful, if you set the cursor position manually.
If you have changed the values the result is unpredictable.If the window size changed the result won't be the same.
Parameters:
{dict} (vim.fn.winrestview.dict)
Return:
(any)
winsaveview()winsaveview()
Returns aDictionary that contains information to restorethe view of the current window. Usewinrestview() torestore the view.This is useful if you have a mapping that jumps around in thebuffer and you want to go back to the original view.This does not save fold information. Use the'foldenable'option to temporarily switch off folding, so that folds arenot opened when moving around. This may have side effects.The return value includes:lnumcursor line numbercolcursor column (Note: the first columnzero, as opposed to whatgetcurpos()returns)coladdcursor column offset for'virtualedit'curswantcolumn for vertical movement (Note:the first column is zero, as opposedto whatgetcurpos() returns). After$ command it will be a very largenumber equal tov:maxcol.toplinefirst line in the windowtopfillfiller lines, only in diff modeleftcolfirst column displayed; only used when'wrap' is offskipcolcolumns skippedNote that no option values are saved.
Return:
(vim.fn.winsaveview.ret)
winwidth({nr})winwidth()
Gets the width ofwindow-ID{nr} (zero for "currentwindow"), including columns (sign-column,'statuscolumn',etc.). Returns -1 if window{nr} doesn't exist. An existingwindow always has a width of zero or more.
Example:
echo "Current window has " .. winwidth(0) .. " columns."if winwidth(0) <= 50  50 wincmd |endif
To get the buffer "viewport", usegetwininfo():
:echo getwininfo(win_getid())[0].width - getwininfo(win_getid())[0].textoff
To get the Nvim screen size, see the'columns' option.
Parameters:
{nr} (integer)
Return:
(integer)
wordcount()wordcount()
The result is a dictionary of byte/chars/word statistics forthe current buffer. This is the same info as provided byg_CTRL-G The return value includes:bytesNumber of bytes in the buffercharsNumber of chars in the bufferwordsNumber of words in the buffercursor_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)
Return:
(any)
writefile({object},{fname} [,{flags}])writefile()
When{object} is aList write it to file{fname}. Each listitem is separated with a NL. Each list item must be a Stringor Number.All NL characters are replaced with a NUL character.Inserting CR characters needs to be done before passing{list}to writefile().
When{object} is aBlob write the bytes to file{fname}unmodified, also when binary mode is not specified.
{flags} must be a String. These characters are recognized:
'b' 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.
'a' Append mode is used, lines are appended to the file:
call writefile(["foo"], "event.log", "a")call writefile(["bar"], "event.log", "a")
'D' Delete the file when the current function ends. This works like:
defer delete({fname})
Fails when not in a function. Also see:defer.
's' 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.
'S' fsync() is not called, even when'fsync' is set.
When{flags} does not contain "S" or "s" then fsync() is called if the'fsync' option is set.
An existing file is overwritten, if possible.
When the write fails -1 is returned, otherwise 0. There is anerror message if the file can't be created or when writingfails.
Also seereadfile().To copy a file byte for byte:
let fl = readfile("foo", "b")call writefile(fl, "foocopy", "b")
Parameters:
{object} (any)
{fname} (string)
{flags} (string?)
Return:
(any)
xor({expr},{expr})xor()
Bitwise XOR on the two arguments. The arguments are convertedto a number. A List, Dict or Float argument causes an error.Also seeand() andor().Example:
let bits = xor(bits, 0x80)
Parameters:
{expr} (integer)
{expr1} (integer)
Return:
(integer)

2. Matching a pattern in a Stringstring-match

This is common between several functions. A regexp pattern as explained atpattern is normally used to find a match in the buffer lines. When apattern is used to find a match in a String, almost everything works in thesame 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 thepattern. It can be matched with a "\n" in the pattern, or with ".". Example:
let a = "aaaa\nxxxx"echo matchstr(a, "..\n..")" aa" xxecho 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".
Main
Commands index
Quick reference

1. Details
2. Matching a pattern in a String

[8]ページ先頭

©2009-2025 Movatter.jp