Nvim:help
pages,generated fromsource using thetree-sitter-vimdoc parser.
{expr}
)abs(){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)
echo abs(-5.456)
echo abs(-4)
{expr}
(number
)number
){expr}
)acos(){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)
echo acos(-0.5)
{expr}
(number
)number
){object}
,{expr}
)add(){expr}
toList orBlob{object}
. Returnsthe resultingList orBlob. Examples:let alist = add([1, 2, 3], item)call add(mylist, "woodstock")
{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.{object}
(any
){expr}
(any
){expr}
,{expr}
)and()or()
andxor()
.Example:let flag = and(bits, 0x80)
{expr}
(number
){expr1}
(number
)integer
)lua vim.print(vim.fn.api_info())
table
){lnum}
,{text}
)append(){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"])
{lnum}
(integer|string
){text}
(string|string[]
)0|1
){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.{buf}
is not a valid buffer or{lnum}
is not valid, anerror message is given. Example:let failed = appendbufline(13, 0, "# THE START")
{text}
is an empty list then no error is givenfor an invalid{lnum}
, since{lnum}
isn't actually used.{buf}
(integer|string
){lnum}
(integer
){text}
(string
)0|1
){winid}
])argc(){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.{winid}
(integer?
)integer
)integer
){winnr}
[,{tabnr}
]])arglistid(){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.{winnr}
(integer?
){tabnr}
(integer?
)integer
){nr}
[,{winid}
]])argv(){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
{winid}
argument specifies the window ID, seeargc().For the Vim command line arguments seev:argv.{nr}
th argument is not present inthe argument list. Returns an empty List if the{winid}
argument is invalid.{nr}
(integer?
){winid}
(integer?
)string|string[]
){expr}
)asin(){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)
echo asin(-0.5)
{expr}
(any
)number
){cmd}
)assert_beeps(){cmd}
and add an error message tov:errors if it doesNOT produce a beep or visual bell.Also seeassert_fails(),assert_nobeep() andassert-return.{cmd}
(string
)0|1
){expected}
,{actual}
[,{msg}
])assert_equal(){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.call assert_equal('foo', 'bar', 'baz')
{expected}
(any
){actual}
(any
){msg}
(any?
)0|1
){fname_one}
,{fname_two}
)assert_equalfile(){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.{fname_one}
(string
){fname_two}
(string
)0|1
){error}
[,{msg}
])assert_exception(){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
{error}
(any
){msg}
(any?
)0|1
){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.{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:')
{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'])
call assert_fails('cmd', ['', 'E987:'])
{msg}
is empty then it is not used. Do this to get thedefault message when passing the{lnum}
argument.E1115{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{context}
is present it is used as a pattern and matchedagainst the context (script name or function name) where{lnum}
is located in.{cmd}
(string
){error}
(any?
){msg}
(any?
){lnum}
(integer?
){context}
(any?
)0|1
){actual}
[,{msg}
])assert_false(){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.{actual}
is not anumber the assert fails.{actual}
(any
){msg}
(any?
)0|1
){lower}
,{upper}
,{actual}
[,{msg}
])assert_inrange(){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.{lower}
(number
){upper}
(number
){actual}
(number
){msg}
(string?
)0|1
){pattern}
,{actual}
[,{msg}
])assert_match(){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.call assert_match('^f.*o$', 'foobar')
{pattern}
(string
){actual}
(string
){msg}
(string?
)0|1
){cmd}
)assert_nobeep(){cmd}
and add an error message tov:errors if itproduces a beep or visual bell.Also seeassert_beeps().{cmd}
(string
)0|1
){expected}
,{actual}
[,{msg}
])assert_notequal()assert_equal()
: add an error message tov:errors when{expected}
and{actual}
are equal.Also seeassert-return.{expected}
(any
){actual}
(any
){msg}
(any?
)0|1
){pattern}
,{actual}
[,{msg}
])assert_notmatch()assert_match()
: add an error message tov:errors when{pattern}
matches{actual}
.Also seeassert-return.{pattern}
(string
){actual}
(string
){msg}
(string?
)0|1
){msg}
)assert_report(){msg}
.Always returns one.{msg}
(string
)0|1
){actual}
[,{msg}
])assert_true(){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.{actual}
(any
){msg}
(string?
)0|1
){expr}
)atan(){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)
echo atan(-4.01)
{expr}
(number
)number
){expr1}
,{expr2}
)atan2(){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)
echo atan2(1, -1)
{expr1}
(number
){expr2}
(number
)number
){blob}
)blob2list(){blob}
. Examples:blob2list(0z0102.0304)" returns [1, 2, 3, 4]blob2list(0z)" returns []
{blob}
(any
)any[]
){save}
,{title}
,{initdir}
,{default}
)browse(){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.{save}
(any
){title}
(string
){initdir}
(string
){default}
(string
)0|1
){title}
,{initdir}
)browsedir(){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.{title}
(string
){initdir}
(string
)0|1
){name}
)bufadd(){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'])
{name}
(string
)integer
){buf}
)bufexists(){buf}
exists.If the{buf}
argument is a number, buffer numbers are used.Number zero is the alternate buffer for the current window.{buf}
argument is a string it must match a buffer nameexactly. The name can be:{buf}
(any
)0|1
){buf}
)buflisted(){buf}
exists and is listed (has the'buflisted' option set).The{buf}
argument is used like withbufexists().{buf}
(any
)0|1
){buf}
)bufload(){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().{buf}
(any
){buf}
)bufloaded(){buf}
exists and is loaded (shown in a window or hidden).The{buf}
argument is used like withbufexists().{buf}
(any
)0|1
){buf}
])bufname():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)
echo bufname("#")" alternate buffer nameecho bufname(3)" name of buffer 3echo bufname("%")" name of current bufferecho bufname("file2")" name of buffer where "file2" matches.
{buf}
(integer|string?
)string
){buf}
[,{create}
]])bufnr():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("$")
{buf}
(integer|string?
){create}
(any?
)integer
){buf}
)bufwinid(){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))
{buf}
(any
)integer
){buf}
)bufwinnr(){buf}
doesn't exist or there is no such window, -1is returned. Example:echo "A window containing buffer 1 is " .. (bufwinnr(1))
{buf}
(any
)integer
){byte}
)byte2line(){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.{byte}
value is invalid.{byte}
(any
)integer
){expr}
,{nr}
[,{utf16}
])byteidx(){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))
let s = strpart(str, byteidx(str, 3))echo strpart(s, 0, byteidx(s, 1))
{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
{expr}
(any
){nr}
(integer
){utf16}
(any?
)integer
){expr}
,{nr}
[,{utf16}
])byteidxcomp()let s = 'e' .. nr2char(0x301)echo byteidx(s, 1)echo byteidxcomp(s, 1)echo byteidxcomp(s, 2)
{expr}
(any
){nr}
(integer
){utf16}
(any?
)integer
){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{func}
(any
){arglist}
(any
){dict}
(any?
)any
){expr}
)ceil(){expr}
as aFloat (round up).{expr}
must evaluate to aFloat or aNumber.Examples:echo ceil(1.456)
echo ceil(-5.456)
echo ceil(4.0)
{expr}
(number
)number
){id}
[,{stream}
])chanclose(){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.{id}
(integer
){stream}
(string?
)0|1
)integer
){id}
,{data}
)chansend(){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", ""])
"rpc":v:true
then the channel expects RPCmessages, userpcnotify() andrpcrequest() instead.{id}
(number
){data}
(string|string[]
)0|1
){string}
[,{utf8}
])char2nr(){string}
.Examples:echo char2nr(" ")" returns 32echo char2nr("ABC")" returns 65echo char2nr("á")" returns 225echo char2nr("á"[0])" returns 195echo char2nr("\<M-x>")" returns 128
{utf8}
is ignored, it exists only for backwards-compatibility.A combining character is a separate character.nr2char() does the opposite.{string}
is not aString.{string}
(string
){utf8}
(any?
)0|1
){string}
)charclass(){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.{string}
(string
)0|1|2|3|'other'
){expr}
[,{winid}
])charcol(){expr}
instead of the byte position.echo charcol('.')" returns 3echo col('.')" returns 7
{expr}
(string|any[]
){winid}
(integer?
)integer
){string}
,{idx}
[,{countcc}
[,{utf16}
]])charidx(){idx}
in{string}
.The index of the first character is zero.If there are no multibyte characters the returned value isequal to{idx}
.{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.{utf16}
is present and TRUE,{idx}
is used as the UTF-16index in the String{expr}
instead of as the byte index.{idx}
bytes. If there are exactly{idx}
bytes the lengthof the string in characters is returned.echo charidx('áb́ć', 3)" returns 1echo charidx('áb́ć', 6, 1)" returns 4echo charidx('áb́ć', 16)" returns -1echo charidx('a😊😊', 4, 0, 1)" returns 2
{string}
(string
){idx}
(integer
){countcc}
(boolean?
){utf16}
(boolean?
)integer
){dir}
[,{scope}
])chdir(){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:{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.let save_dir = chdir(newdir)if save_dir != "" " ... do some work call chdir(save_dir)endif
{dir}
(string
){scope}
(string?
)string
){lnum}
)cindent(){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.{lnum}
(integer|string
)integer
){win}
])clearmatches(){win}
is specified, use the window with this number orwindow ID instead of the current window.{win}
(integer?
)<Up>
or<Down>
keys)table<string,any>
){expr}
[,{winid}
])col(){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.{winid}
argument the values are obtained forthat window instead of the current window.echo col(".")" column of cursorecho col("$")" length of cursor line plus oneecho col("'t")" column of mark techo col("'" .. markname)" column of mark markname
{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>
{expr}
(string|any[]
){winid}
(integer?
)integer
){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-O
or 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
{startcol}
(integer
){matches}
(any[]
){expr}
)complete_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.{expr}
(any
)0|1|2
)0|1
){what}
])complete_info()<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.CTRL-X
i_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{what}
list argument is supplied, then onlythe items listed in{what}
are returned. Unsupported items in{what}
are silently ignored." Get all itemscall complete_info()" Get only 'mode'call complete_info(['mode'])" Get only 'mode' and 'pum_visible'call complete_info(['mode', 'pum_visible'])
{what}
(any[]?
)table
){lnum}
,{col}
])complete_match()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>
{lnum}
(integer?
){col}
(integer?
)table
){msg}
[,{choices}
[,{default}
[,{type}
]]])confirm(){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")
confirm("file has been modified", "&Save\nSave &All")
{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.{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.<Esc>
,CTRL-C
,or another valid interrupt key, confirm() returns 0.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
{msg}
(string
){choices}
(string?
){default}
(integer?
){type}
(string?
)integer
){expr}
)copy(){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().{expr}
(T
)T
){expr}
)cos(){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)
echo cos(-4.01)
{expr}
(number
)number
){expr}
)cosh(){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)
echo cosh(-0.5)
{expr}
(number
)number
){comp}
,{expr}
[,{ic}
[,{start}
]])count()E706Return the number of times an item with value{expr}
appearsinString,List orDictionary{comp}
.{ic}
is given and it'sTRUE then case is ignored.{comp}
is a string then the number of not overlappingoccurrences of{expr}
is returned. Zero is returned when{expr}
is an empty string.{comp}
(string|table|any[]
){expr}
(any
){ic}
(boolean?
){start}
(integer?
)integer
){index}
])ctxget(){index}
from the top of thecontext-stack (seecontext-dict).If{index}
is not given, it is assumed to be 0 (i.e.: top).{index}
(integer?
)table
)any
){types}
])ctxpush(){types}
is given and is aList ofStrings, it specifieswhichcontext-types to include in the pushed context.Otherwise, all context types are included.{types}
(string[]?
)any
){context}
[,{index}
])ctxset(){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).{context}
(table
){index}
(integer?
)integer
)any
){lnum}
,{col}
[,{off}
])cursor(){list}
)Positions the cursor at the column (byte count){col}
in theline{lnum}
. The first column is one.{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.{col}
as the character count, usesetcursorcharpos().{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.{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.{list}
(integer[]
)any
){pid}
)debugbreak(){pid}
to get a SIGTRAP. Behavior for otherprocesses is undefined. Seeterminal-debug.(Sends a SIGINT to a process{pid}
other than MS-Windows){pid}
(integer
)any
){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.{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{noref}
set to 1 will fail.Also seecopy().{expr}
(T
){noref}
(boolean?
)T
){fname}
[,{flags}
])delete(){flags}
or with{flags}
empty: Deletes the file by thename{fname}
.{fname}
is a symbolic link. The symboliclink itself is deleted, not what it points to.{flags}
is "d": Deletes the directory by the name{fname}
. This fails when directory{fname}
is not empty.{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.{fname}
(string
){flags}
(string?
)integer
){buf}
,{first}
[,{last}
])deletebufline(){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.{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}
.{buf}
(integer|string
){first}
(integer|string
){last}
(integer|string?
)any
){dict}
,{pattern}
,{callback}
)dictwatcheradd(){dict}
);{pattern}
).{callback}
).{dict}
and on keysmatching{pattern}
will result in{callback}
being invoked.silent! call dictwatcherdel(g:, '*', 'OnDictChanged')function! OnDictChanged(d,k,z) echomsg string(a:k) string(a:z)endfunctioncall dictwatcheradd(g:, '*', 'OnDictChanged')
{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.{callback}
receives three arguments:old
andnew
, the key was updated.new
, the key was added.old
, the key was deleted.{dict}
(table
){pattern}
(string
){callback}
(function
)any
){dict}
,{pattern}
,{callback}
)dictwatcherdel(){dict}
(any
){pattern}
(string
){callback}
(function
)any
):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.integer
){lnum}
)diff_filler(){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.{lnum}
(integer|string
)integer
){lnum}
,{col}
)diff_hlID(){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.{lnum}
(integer|string
){col}
(integer
)any
){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." Get a built-in digraphecho digraph_get('00')" Returns '∞'" Get a user-defined digraphcall digraph_set('aa', 'あ')echo digraph_get('aa')" Returns 'あ'
{chars}
(string
)string
){listall}
])digraph_getlist(){listall}
argument is givenand it is TRUE, return all digraphs, including the defaultdigraphs. Otherwise, return only user-defined digraphs." Get user-defined digraphsecho digraph_getlist()" Get all the digraphs, including default digraphsecho digraph_getlist(1)
{listall}
(boolean?
)string[][]
){chars}
,{digraph}
)digraph_set(){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.call digraph_set(' ', 'あ')
{chars}
(string
){digraph}
(string
)any
){digraphlist}
)digraph_setlist(){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', 'い']])
for [chars, digraph] in [['aa', 'あ'], ['ii', 'い']] call digraph_set(chars, digraph)endfor
{digraphlist}
(table<integer,string[]>
)any
){expr}
)empty(){expr}
is empty, zero otherwise.{expr}
(any
)integer
)echo has_key(environ(), 'HOME')
echo index(keys(environ()), 'HOME', 0, 1) != -1
any
){string}
,{chars}
)escape(){chars}
that occur in{string}
with abackslash. Example:echo escape('c:\program files\vim', ' \')
c:\\program\ files\\vim
{string}
(string
){chars}
(string
)string
){string}
)eval(){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.{string}
(string
)any
)any
){expr}
)executable(){expr}
exists.{expr}
must be the name of the program without anyarguments.{expr}
(string
)0|1
){command}
[,{silent}
])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"')
echo execute(['echon "foo"', 'echon "bar"'])
{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.split()
on the result:execute('args')->split("\n")
win_execute()
.{command}
(string|string[]
){silent}
(''|'silent'|'silent!'?
)string
){expr}
)exepath(){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.{expr}
(string
)string
){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]")
echo exists("l[xx]")
*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.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")
echo exists(":make")
echo exists(":make install")
echo exists(bufcount)
{expr}
(string
)0|1
){expr}
)exp(){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)
echo exp(-1)
{expr}
(number
)any
){string}
[,{nosuf}
[,{list}
]])expand(){string}
.'wildignorecase' applies.{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.{string}
doesnot start with '%', '#' or '<', see below.{string}
starts with '%', '#' or '<', the expansion isdone like for thecmdline-special variables with theirassociated modifiers. Here is a short overview:<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 onlylet &tags = expand("%:p:h") .. "/tags"
let doesntwork = expand("%:h.bak")
let doeswork = expand("%:h") .. ".bak"
echo expand(expand("<cfile>"))
{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")
{string}
(string
){nosuf}
(boolean?
){list}
(nil|false?
)string
){string}
[,{options}
])expandcmd(){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.{options}
Dictargument: errmsgIf set to TRUE, error messages are displayedif an error is encountered during expansion.By default, error messages are not displayed.{string}
is returned.echo expandcmd('make %<.o')
make /path/runtime/doc/builtin.o
echo expandcmd('make %<.o', {'errmsg': v:true})
{string}
(string
){options}
(table?
)any
){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)
{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]
{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{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.{expr1}
(table
){expr2}
(table
){expr3}
(table?
)any
){expr1}
,{expr2}
[,{expr3}
])extendnew(){expr1}
a newList or Dictionary is created and returned.{expr1}
remainsunchanged.{expr1}
(table
){expr2}
(table
){expr3}
(table?
)any
){string}
[,{mode}
])feedkeys(){string}
are queued for processing as if theycome from a mapping or were typed by the user.{string}
.{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.{string}
(string
){mode}
(string?
)any
){from}
,{to}
)filecopy(){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).{from}
(string
){to}
(string
)0|1
){file}
)filereadable(){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
{file}
(string
)0|1
){file}
)filewritable(){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.{file}
(string
)0|1
){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}
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"')
call filter(mydict, 'v:key >= 8')
call filter(var, 0)
{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.{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'))
call filter(myList, {idx, val -> idx * val <= 42})
call filter(myList, {idx -> idx % 2 == 1})
let l = filter(copy(mylist), 'v:val =~ "KEEP"')
{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.{expr1}
(string|table
){expr2}
(string|function
)any
){name}
[,{path}
[,{count}
]])finddir(){name}
in{path}
. Supports both downwards andupwards recursive directory searches. Seefile-searchingfor the syntax of{path}
.{path}
is omitted or empty then'path' is used.{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.:find
.{name}
(string
){path}
(string?
){count}
(integer?
)string|string[]
){name}
[,{path}
[,{count}
]])findfile()echo findfile("tags.vim", ".;")
{name}
(string
){path}
(string?
){count}
(integer?
)string|string[]
){list}
[,{maxdepth}
])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.echo flatten([1, [2, [3, 4]], 5])
echo flatten([1, [2, [3, 4]], 5], 1)
{list}
(any[]
){maxdepth}
(integer?
)any[]|0
){list}
(any[]
){maxdepth}
(integer?
)any[]|0
){expr}
)float2nr(){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)
echo float2nr(-23.45)
echo float2nr(1.0e100)
echo float2nr(-1.0e150)
echo float2nr(1.0e-100)
{expr}
(number
)any
){expr}
)floor(){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)
echo floor(-5.456)
echo floor(4.0)
{expr}
(number
)any
){expr1}
,{expr2}
)fmod(){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)
echo fmod(-12.33, 1.22)
{expr1}
(number
){expr2}
(number
)any
){string}
)fnameescape(){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)
edit \+some\ str\%nge\|name
{string}
(string
)string
){fname}
,{mods}
)fnamemodify(){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")
/home/user/vim/vim/src
{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.{fname}
(string
){mods}
(string
)string
){lnum}
)foldclosed(){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.{lnum}
(integer|string
)integer
){lnum}
)foldclosedend(){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.{lnum}
(integer|string
)integer
){lnum}
)foldlevel(){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.{lnum}
(integer|string
)integer
)+-- 45 lines: abcdef
string
){lnum}
)foldtextresult(){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.{lnum}
(integer|string
)string
){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}
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')
{expr1}
list.{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.{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.{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.{expr1}
(string|table
){expr2}
(string|function
)string|table
){name}
)fullcommand(){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).fullcommand('s')
,fullcommand('sub')
,fullcommand(':%substitute')
all return "substitute".{name}
(string
)string
){name}
[,{arglist}
] [,{dict}
])funcref(){name}
is redefined later.{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.{name}
(string
){arglist}
(any?
){dict}
(any?
)any
){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)
{name}
,also when it was redefined later. Usefuncref() to keep thesame function.{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.func Callback(arg1, arg2, name)"...endfunclet Partial = function('Callback', ['one', 'two'])"...call Partial('name')
call Callback('one', 'two', 'name')
func Callback(one, two, three)"...endfunclet Partial = function('Callback', ['two'])"...eval 'one'->Partial('three')
call Callback('one', 'two', 'three')
func Callback(arg1, arg2, name)"...endfunclet Func = function('Callback', ['one'])let Func2 = function(Func, ['two'])"...call Func2('name')
call Callback('one', 'two', 'name')
{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
let Func = function('Callback', context)let Func = context.Callback
function Callback(arg1, count) dict"...endfunctionlet context = {"name": "example"}let Func = function('Callback', ['one'], context)"...call Func(500)
call context.Callback('one', 500)
{name}
(string
){arglist}
(any?
){dict}
(any?
)any
){atexit}
])garbagecollect(){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.{atexit}
(boolean?
)any
){list}
,{idx}
[,{default}
])get()get()-listGet item{idx}
fromList{list}
. When this item is notavailable return{default}
. Return zero when{default}
isomitted.{list}
(any[]
){idx}
(integer
){default}
(any?
)any
){blob}
,{idx}
[,{default}
])get()-blob{idx}
fromBlob{blob}
. When this byte is notavailable return{default}
. Return -1 when{default}
isomitted.{blob}
(string
){idx}
(integer
){default}
(any?
)any
){dict}
,{key}
[,{default}
])get()-dict{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')
{dict}
(table<string,any>
){key}
(string
){default}
(any?
)any
){func}
,{what}
)get()-func{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...{arglist}
ofthe Funcref contains more arguments than theFuncref expects, it's not validated.{func}
(function
){what}
(string
)any
){buf}
])getbufinfo(){dict}
])Get information about buffers as a List of Dictionaries.{dict}
:buflistedinclude only listed buffers.bufloadedinclude only loaded buffers.bufmodifiedinclude only modified buffers.{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.echo line('.', {winid})
for buf in getbufinfo() echo buf.nameendforfor buf in getbufinfo({'buflisted':1}) if buf.changed " .... endifendfor
getbufvar({bufnr}, '&option_name')
{dict}
(vim.fn.getbufinfo.dict?
)vim.fn.getbufinfo.ret.item[]
){buf}
,{lnum}
[,{end}
])getbufline(){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.{buf}
, seebufname() above.{lnum}
and{end}
"$" can be used for the last line of thebuffer. Otherwise a number must be used.{lnum}
is smaller than 1 or bigger than the number oflines in the buffer, an emptyList is returned.{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.let lines = getbufline(bufnr("myfile"), 1, "$")
{buf}
(integer|string
){lnum}
(integer
){end}
(integer?
)string[]
){buf}
,{lnum}
)getbufoneline()getbufline()
but only get one line and return itas a string.{buf}
(integer|string
){lnum}
(integer
)string
){buf}
,{varname}
[,{def}
])getbufvar(){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")
{buf}
(integer|string
){varname}
(string
){def}
(any?
)any
)any
){buf}
])getchangelist(){buf}
. For the useof{buf}
, seebufname() above. If buffer{buf}
doesn'texist, an empty list is returned.{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.{buf}
(integer|string?
)table[]
){expr}
[,{opts}
]])getchar(){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}
.{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.{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.{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.{opts}
is a Dict and supports thefollowing items:CTRL-I
and<Tab>
.IfFALSE, don't include modifiers inthe character.(default:TRUE)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
<Del>
key you get the code for the<Del>
key, not the raw charactersequence. Examples:getchar() == "\<Del>"getchar() == "\<S-Left>"
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
{expr}
(-1|0|1?
){opts}
(table?
)integer|string
)integer
){expr}
)getcharpos(){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.getcharpos('.')returns [0, 5, 3, 0]getpos('.')returns [0, 5, 7, 0]
{expr}
(string
)integer[]
){dict}
with the following entries:nnoremap <expr> ; getcharsearch().forward ? ';' : ','nnoremap <expr> , getcharsearch().forward ? ',' : ';'
table
){expr}
[,{opts}
]])getcharstr(){opts}
.{expr}
(-1|0|1?
){opts}
(table?
)string
)string
)string
)cmap <F7> <C-\>eescape(getcmdline(), ' \')<CR>
string
)integer
)string
)integer
)-
: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().':'|'>'|'/'|'?'|'@'|'-'|'='|''
)':'|'>'|'/'|'?'|'@'|'-'|'='|''
){pat}
,{type}
[,{filtered}
])getcompletion(){type}
argument specifies what for. The following completiontypes are supported:{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{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}
.{filtered}
flag is set to 1, then'wildignore'is applied to filter the results. Otherwise all the matchesare returned. The'wildignorecase' option always applies.{type}
is "cmdline", then thecmdline-completion result isreturned. For example, to complete the possible values aftera ":call" command:echo getcompletion('call ', 'cmdline')
{type}
produces an error.{pat}
(string
){type}
(string
){filtered}
(boolean?
)string[]
){pat}
)getcompletiontype(){pat}
.When no corresponding completion type is found, an emptystring is returned.To get the current command-line completion type, usegetcmdcompltype().{pat}
(string
)string
){winid}
])getcurpos(){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.let save_cursor = getcurpos()MoveTheCursorAroundcall setpos('.', save_cursor)
{winid}
(integer?
)[integer, integer, integer, integer, integer]
){winid}
])getcursorcharpos()getcursorcharpos()" returns [0, 3, 2, 0, 3]getcurpos()" returns [0, 3, 4, 0, 3]
{winid}
(integer?
)any
){winnr}
[,{tabnr}
]])getcwd(){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)
{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{winnr}
(integer?
){tabnr}
(integer?
)string
){name}
)getenv(){name}
. The{name}
argument is a string, without a leading '$'. Example:myHome = getenv('HOME')
{name}
(string
)string
){name}
])getfontname(){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.{name}
(string?
)string
){fname}
)getfperm(){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"))
{fname}
(string
)string
){fname}
)getfsize(){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.{fname}
(string
)integer
){fname}
)getftime(){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.{fname}
(string
)integer
){fname}
)getftype(){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")
{fname}
(string
)'file'|'dir'|'link'|'bdev'|'cdev'|'socket'|'fifo'|'other'
){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.{winnr}
(integer?
){tabnr}
(integer?
)vim.fn.getjumplist.ret
){lnum}
[,{end}
])getline(){end}
the result is a String, which is line{lnum}
from the current buffer. Example:getline(1)
{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(".")
{lnum}
is a number smaller than 1 or bigger than thenumber of lines in the buffer, an empty string is returned.{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)
{lnum}
(integer|string
){end}
(nil|false?
)string
){nr}
[,{what}
])getloclist(){nr}
.{nr}
can be the window number or thewindow-ID.When{nr}
is zero the current window is used.{nr}
, an empty list isreturned. Otherwise, same asgetqflist().{what}
dictionary argument is supplied, thenreturns the items listed in{what}
as a dictionary. Refer togetqflist() for the supported items in{what}
.{what}
,the following item is supported bygetloclist():{nr}
.Returns an empty Dictionary if window{nr}
does not exist.echo getloclist(3, {'all': 0})echo getloclist(5, {'filewinid': 0})
{nr}
(integer
){what}
(table?
)any
){buf}
])getmarklist(){buf}
argument returns aList with informationabout all the global marks.mark{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.{buf}
(integer??
)vim.fn.getmarklist.ret.item[]
){win}
])getmatches(){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
{win}
(integer?
)vim.fn.getmatches.ret.item[]
)vim.fn.getmousepos.ret
)integer
){expr}
)getpos(){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.<Tab>
or after the lastcharacter.{expr}
is invalid, returns a list with all zeros.let save_a_mark = getpos("'a")" ...call setpos("'a", save_a_mark)
{expr}
(string
)[integer, integer, integer, integer]
){what}
])getqflist()vimgrep /theword/jg *.cfor d in getqflist() echo bufname(d.bufnr) ':' d.lnum '=' d.textendfor
{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.echo getqflist({'all': 1})echo getqflist({'nr': 2, 'title': 1})echo getqflist({'lines' : ["F1:10:L10"]})
{what}
(table?
)any
){regname}
[, 1 [,{list}
]]])getreg(){regname}
. Example:let cliptext = getreg('*')
{regname}
was not set the result is an emptystring.The{regname}
argument must be a string.{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.{regname}
is not specified,v:register is used.{regname}
(string?
){expr}
(any?
){list}
(nil|false?
)string
){regname}
])getreginfo(){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.{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().{regname}
(string?
)table
){pos1}
,{pos2}
[,{opts}
])getregion(){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.{opts}
is a Dict and supports thefollowing items:{pos1}
and{pos2}
doesn't matter, it will always return content from the upper left position to the lower right position.{pos1}
and{pos2}
are not in the same buffer, an empty list is returned.{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.xnoremap <CR>\ <Cmd>echom getregion(\ getpos('v'), getpos('.'), #{ type: mode() })<CR>
{pos1}
([integer, integer, integer, integer]
){pos2}
([integer, integer, integer, integer]
){opts}
({type?:string, exclusive?:boolean}?
)string[]
){pos1}
,{pos2}
[,{opts}
])getregionpos(){pos1}
and{pos2}
.The segments are a pair of positions for every line:[[{start_pos}, {end_pos}], ...]
<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.{opts}
alsosupports the following:{pos1}
([integer, integer, integer, integer]
){pos2}
([integer, integer, integer, integer]
){opts}
({type?:string, exclusive?:boolean, eol?:boolean}?
)[ [integer, integer, integer, integer], [integer, integer, integer, integer] ][]
){regname}
])getregtype(){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.{regname}
(string?
)string
){opts}
])getscriptinfo():scriptnames
shows.{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.{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 1echo getscriptinfo({'name': 'myscript'})echo getscriptinfo({'sid': 15})[0].variables
{opts}
(table?
)vim.fn.getscriptinfo.ret[]
)table[]
){tabnr}
])gettabinfo(){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.{tabnr}
(integer?
)any
){tabnr}
,{varname}
[,{def}
])gettabvar(){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.{tabnr}
(integer
){varname}
(string
){def}
(any?
)any
){tabnr}
,{winnr}
,{varname}
[,{def}
])gettabwinvar(){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')
gettabwinvar({tabnr}, {winnr}, '&')
{tabnr}
(integer
){winnr}
(integer
){varname}
(string
){def}
(any?
)any
){winnr}
])gettagstack(){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.{winnr}
(integer?
)any
){text}
)gettext(){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.{text}
(string
)string
){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.{winid}
information about all the windows in all thetab pages is returned.{winid}
(integer?
)vim.fn.getwininfo.ret.item[]
){timeout}
])getwinpos(){timeout}
can be used to specify how long to wait in msec fora response from the terminal. When omitted 100 msec is used.while 1 let res = getwinpos(1) if res[0] >= 0 break endif " Do some work hereendwhile
{timeout}
(integer?
)any
):winpos
.integer
):winpos
.integer
){winnr}
,{varname}
[,{def}
])getwinvar()let list_is_on = getwinvar(2, '&list')echo "myvar = " .. getwinvar(1, 'myvar')
{winnr}
(integer
){varname}
(string
){def}
(any?
)any
){expr}
[,{nosuf}
[,{list}
[,{alllinks}
]]])glob(){expr}
. Seewildcards for theuse of special characters.{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.{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.{alllinks}
argument is present and it isTRUE then all symbolic links are included.let tagfiles = glob("`find . -name tags -print`")let &tags = substitute(tagfiles, "\n", ",", "g")
{expr}
(string
){nosuf}
(boolean?
){list}
(boolean?
){alllinks}
(boolean?
)any
){string}
)glob2regpat()if filename =~ glob2regpat('Make*.mak') " ...endif
if filename =~ '^Make.*\.mak$' " ...endif
{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.{string}
(string
)string
){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.{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.{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().echo globpath(&rtp, "**/README.txt")
{path}
(string
){expr}
(string
){nosuf}
(boolean?
){list}
(boolean?
){allinks}
(boolean?
)any
){feature}
)has(){feature}
is supported, 0 otherwise. The{feature}
argument is a feature name like "nvim-0.2.1" or"win32", see below. See alsoexists().print(vim.uv.os_uname().sysname)
if has('feature') let x = this_breaks_without_the_feature()endif
if has("nvim-0.2.1") " ...endif
if has("win32") " ...endif
if v:version > 602 || v:version == 602 && has("patch148") " ...endif
if has("patch-7.4.237") " ...endif
{feature}
(string
)0|1
){dict}
,{key}
)has_key(){dict}
has an entry with key{key}
. FALSE otherwise. The{key}
argument is a string.{dict}
(table
){key}
(string
)0|1
){winnr}
[,{tabnr}
]])haslocaldir(){winnr}
is -1 and the tabpagehas set a local path via:tcd, otherwise 0.echo haslocaldir()echo haslocaldir(0)echo haslocaldir(0, 0)
{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{winnr}
(integer?
){tabnr}
(integer?
)0|1
){what}
[,{mode}
[,{abbr}
]])hasmapto(){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.if !hasmapto('\ABCdoit') map <Leader>d \ABCdoitendif
{what}
(any
){mode}
(string?
){abbr}
(boolean?
)0|1
){history}
,{item}
)histadd(){item}
to the history{history}
which can beone of:hist-names{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.call histadd("input", strftime("%Y %b %d"))let date=input("Enter date: ")
{history}
(string
){item}
(any
)0|1
){history}
[,{item}
])histdel(){history}
, i.e. delete all its entries. Seehist-namesfor the possible values of{history}
.{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.call histdel("expr")
call histdel("/", '^\*')
call histdel("search", histnr("search"))call histdel("search", -1)call histdel("search", '^' .. histget("search", -1) .. '$')
call histdel("search", -1)let @/ = histget("search", -1)
{history}
(string
){item}
(any?
)0|1
){history}
[,{index}
])histget(){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.execute '/' .. histget("search", -2)
{num}
" that supports re-execution ofthe{num}
th entry from the output of:history.command -nargs=1 H execute histget("cmd", 0+<args>)
{history}
(string
){index}
(integer|string?
)string
){history}
)histnr(){history}
.Seehist-names for the possible values of{history}
.If an error occurred, -1 is returned.let inp_index = histnr("expr")
{history}
(string
)integer
){name}
)hlID(){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")
{name}
(string
)integer
){name}
)hlexists(){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.{name}
(string
)0|1
)string
){string}
,{from}
,{to}
)iconv(){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.{string}
(string
){from}
(string
){to}
(string
)string
){expr}
)id()id(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.id(no_longer_existing_container)
will not be equal to some otherid()
: new containers mayreuse identifiers of the garbage-collected ones.{expr}
(any
)string
){lnum}
)indent(){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.{lnum}
(integer|string
)integer
){object}
,{expr}
[,{start}
[,{ic}
]])index(){expr}
in{object}
and return its index. Seeindexof() for using a lambda to select the item.{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.{start}
is given then start looking at the item with index{start}
(may be negative for an item relative to the end).{ic}
is given and it isTRUE, ignore case. Otherwisecase must match.{expr}
is not found in{object}
.Example:let idx = index(words, "the")if index(numbers, 123) >= 0 " ...endif
{object}
(any
){expr}
(any
){start}
(integer?
){ic}
(boolean?
)integer
){object}
,{expr}
[,{opts}
])indexof(){object}
where{expr}
isv:true.{object}
must be aList or aBlob.{object}
is aList, evaluate{expr}
for each item in theList until the expression is v:true and return the index ofthis item.{object}
is aBlob evaluate{expr}
for each byte in theBlob until the expression is v:true and return the index ofthis byte.{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.{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.{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})
{object}
(any
){expr}
(any
){opts}
(table?
)integer
){prompt}
(string
){text}
(string?
){completion}
(string?
)string
){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.{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.if input("Coffee or beer? ") == "beer" echo "Cheers!"endif
{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")
{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")
highlight
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.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'})
nmap \x :call GetFoo()<CR>:exe "/" .. Foo<CR>function GetFoo() call inputsave() let g:Foo = input("enter search pattern: ") call inputrestore()endfunction
{opts}
(table
)string
){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'])
{textlist}
(string[]
)any
)integer
)integer
){prompt}
[,{text}
])inputsecret(){prompt}
(string
){text}
(string?
)string
){object}
,{item}
[,{idx}
])insert(){object}
is aList or aBlob insert{item}
at the startof it.{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.let mylist = insert([2, 3, 5], 1)call insert(mylist, 4, -1)call insert(mylist, 6, len(mylist))
{item}
is aList it is inserted as a singleitem. Useextend() to concatenateLists.{object}
(any
){item}
(any
){idx}
(integer?
)any
)CTRL-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>'))
any
){expr}
)invert()let bits = invert(bits)
{expr}
(integer
)integer
){path}
)isabsolutepath(){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
{path}
(string
)0|1
){directory}
)isdirectory(){directory}
exists. If{directory}
doesn'texist, or isn't a directory, the result isFALSE.{directory}
is any expression, which is used as a String.{directory}
(string
)0|1
){expr}
)isinf(){expr}
is a positive infinity, or -1 a negativeinfinity, otherwise 0.echo isinf(1.0 / 0.0)
echo isinf(-1.0 / 0.0)
{expr}
(number
)1|0|-1
){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
{expr}
is a variable that does not exist you get an errormessage. Useexists() to check for existence.{expr}
(any
)0|1
){expr}
(number
)0|1
){expr}
)items(){expr}
.EachList item is a list with two items:let mydict = #{a: 'red', b: 'blue'}for [key, value] in items(mydict) echo $"{key} = {value}"endforecho items([1, 2, 3])echo items("foobar")
{expr}
(table|string
)any
){job}
(integer
)integer
){job}
,{width}
,{height}
)jobresize(){job}
to{width}
columns and{height}
rows.Fails if the job was not started with"pty":v:true
.{job}
(integer
){width}
(integer
){height}
(integer
)any
){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}'])
call jobstart(['nvim', '-h'], {'on_stdout':{j,d,e->append(line('.'),d)}})
call jobstart(['nvim', '-h'], {'term':v:true})
{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.{cmd}
is a List:call jobstart(['ping', 'neovim.io'])
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".env
option.{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.{cmd}
(string|string[]
){opts}
(table?
)integer
){id}
)jobstop(){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.{id}
(integer
)integer
){jobs}
is a List ofjob-ids to wait for.{timeout}
is the maximum waiting time in milliseconds. Ifomitted or -1, wait forever.let running = jobwait([{job-id}], 0)[0] == -1
{jobs}
list maybe invoked. The screen will not redraw unless:redraw isinvoked by a callback.{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{jobs}
(integer[]
){timeout}
(integer?
)integer[]
){list}
[,{sep}
])join(){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"
{list}
(any[]
){sep}
(string?
)string
){expr}
)json_decode(){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.{expr}
(any
)any
){expr}
)json_encode(){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.{expr}
(any
)string
){dict}
)keys(){dict}
. TheList is inarbitrary order. Also seeitems() andvalues().{dict}
(table
)string[]
){string}
)keytrans()let xx = "\<C-Home>"echo keytrans(xx)
<C-Home>
{string}
(string
)string
){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.{expr}
(any[]
)integer
){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.{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")
{libname}
(string
){funcname}
(string
){argument}
(any
)any
){libname}
,{funcname}
,{argument}
)libcallnr()echo libcallnr("/usr/lib/libc.so", "getpid", "")call libcallnr("libc.so", "printf", "Hello World!\n")call libcallnr("libc.so", "sleep", 10)
{libname}
(string
){funcname}
(string
){argument}
(any
)any
){winid}
argument the values are obtained forthat window instead of the current window.{expr}
and{winid}
.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
{expr}
(string|integer[]
){winid}
(integer?
)integer
){lnum}
)line2byte(){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)
{lnum}
is used like withgetline(). When{lnum}
is invalid -1 is returned.Also seebyte2line(),go and:goto.{lnum}
(integer|string
)integer
){lnum}
)lispindent(){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.{lnum}
(integer|string
)integer
){list}
)list2blob(){list}
.Examples:echo list2blob([1, 2, 3, 4])" returns 0z01020304echo list2blob([])" returns 0z
{list}
(any[]
)string
){list}
[,{utf8}
])list2str(){list}
to a character string canconcatenate them all. Examples:echo list2str([32])" returns " "echo list2str([65, 66, 67])" returns "ABC"
echo join(map(list, {nr, val -> nr2char(val)}), '')
{utf8}
option has no effect,and exists only for backwards-compatibility.With UTF-8 composing characters work as expected:echo list2str([97, 769])" returns "á"
{list}
(any[]
){utf8}
(boolean?
)string
)integer
){expr}
)log(){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)
echo log(exp(5))
{expr}
(number
)number
){expr}
)log10(){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)
echo log10(0.01)
{expr}
(number
)number
){expr}
[,{expr}
])luaeval(){expr}
and return its result convertedto Vim data structures. Seelua-eval for details.{expr}
(string
){expr1}
(any[]?
)any
){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}
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 .. " <"')
{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{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'))
call map(myDict, {key, val -> key .. '-' .. val})
call map(myDict, {key -> 'item: ' .. key})
call map(myDict, {_, val -> 'item: ' .. val})
let tlist = map(copy(mylist), ' v:val .. "\t"')
{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.{expr1}
(string|table|any[]
){expr2}
(string|function
)any
){name}
[,{mode}
[,{abbr}
[,{dict}
]]])maparg(){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().{name}
, an empty String isreturned if{dict}
is FALSE, otherwise returns an empty Dict.When the mapping for{name}
is empty, then "<Nop>" isreturned.{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.{abbr}
is there and it isTRUE use abbreviationsinstead of mappings.{dict}
isTRUE, return a dictionary describing themapping, with these items:mapping-dict{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.exe 'nnoremap <Tab> ==' .. maparg('<Tab>', 'n')
{name}
(string
){mode}
(string?
){abbr}
(boolean?
){dict}
(false?
)string
){name}
[,{mode}
[,{abbr}
]])mapcheck(){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}
.{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
{name}
(string
){mode}
(string?
){abbr}
(boolean?
)any
){abbr}
])maplist(){abbr}
is there and it isTRUE useabbreviations instead of mappings.echo maplist()->filter({_, m -> \ match(get(m, 'rhs', ''), 'MultiMatch') >= 0 \ })
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})
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)
{abbr}
(0|1?
)table[]
){expr1}
,{expr2}
)mapnew(){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.{expr1}
(any
){expr2}
(any
)any
){mode}
,{abbr}
,{dict}
)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{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)
:map!
, you need to save/restore the mapping forall of them, when they might differ.{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
{dict}
(table<string,any>
)any
){expr}
,{pat}
[,{start}
[,{count}
]])match(){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.{expr}
is used as a String. The result is aNumber, which gives the index (byte offset) in{expr}
where{pat}
matches.echo match("testing", "ing")" results in 4echo match([1, 'x'], '\a')" results in 1
{pat}
is used.strpbrk()let sepidx = match(line, '[.,;: \t]')
let idx = match(haystack, '\cneedle')
{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)
echo match("testing", "ing", 4)
echo match("testing", "t", 2)
{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.{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)
{count}
is added the way{start}
works changes,see above.{expr}
(string|any[]
){pat}
(string
){start}
(integer?
){count}
(integer?
)integer
){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.{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.{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.{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:highlight MyGroup ctermbg=green guibg=greenlet m = matchadd("MyGroup", "TODO")
call matchdelete(m)
{group}
(integer|string
){pattern}
(string
){priority}
(integer?
){id}
(integer?
){dict}
(table?
)integer
){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:highlight MyGroup ctermbg=green guibg=greenlet m = matchaddpos("MyGroup", [[23, 24], 34])
call matchdelete(m)
{group}
(integer|string
){pos}
(any[]
){priority}
(integer?
){id}
(integer?
){dict}
(table?
)integer|table
){nr}
)matcharg(){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.{nr}
(integer
)string[]
){buf}
,{pat}
,{lnum}
,{end}
, [,{dict}
])matchbufline(){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}
.{dict}
argument supports following items: submatchesinclude submatch information (/\(){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." 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'}]
{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.{buf}
(string|integer
){pat}
(string
){lnum}
(string|integer
){end}
(string|integer
){dict}
(table?
)string[]
){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.{id}
(integer
){win}
(integer?
)any
){expr}
,{pat}
[,{start}
[,{count}
]])matchend()echo matchend("testing", "ing")
let span = matchend(line, '[a-zA-Z]')let span = matchend(line, '[^a-zA-Z]')
echo matchend("testing", "ing", 5)
{expr}
(any
){pat}
(string
){start}
(integer?
){count}
(integer?
)integer
){list}
,{str}
[,{dict}
])matchfuzzy(){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.{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.{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.{str}
has multiple words each separated by white space,then the list of strings that have all the words is returned.{str}
is greater than256, then returns an empty list.{limit}
is given, matchfuzzy() will find up to thisnumber of matches in{list}
and return them in sorted order.echo matchfuzzy(["clay", "crow"], "cay")
echo getbufinfo()->map({_, v -> v.name})->matchfuzzy("ndl")
echo getbufinfo()->matchfuzzy("ndl", {'key' : 'name'})
echo getbufinfo()->matchfuzzy("spl", \ {'text_cb' : {v -> v.name}})
echo v:oldfiles->matchfuzzy("test")
let l = readfile("buffer.c")->matchfuzzy("str")
echo ['one two', 'two one']->matchfuzzy('two one')
['two one', 'one two']
.echo ['one two', 'two one']->matchfuzzy('two one', \ {'matchseq': 1})
['two one']
.{list}
(any[]
){str}
(string
){dict}
(table?
)table
){list}
,{str}
[,{dict}
])matchfuzzypos(){str}
matches and a list of matching scores. You canusebyteidx() to convert a character position to a byteposition.{str}
matches multiple times in a string, then only thepositions for the best match is returned.echo matchfuzzypos(['testing'], 'tsg')
echo matchfuzzypos(['clay', 'lacy'], 'la')
echo [{'text': 'hello', 'id' : 10}] \ ->matchfuzzypos('ll', {'key' : 'text'})
[[{"id": 10, "text": "hello"}], [[2, 3]], [127]]
{list}
(any[]
){str}
(string
){dict}
(table?
)table
){expr}
,{pat}
[,{start}
[,{count}
]])matchlist()echo matchlist('acd', '\(a\)\?\(b\)\?\(c\)\?\(.*\)')
{expr}
(any
){pat}
(string
){start}
(integer?
){count}
(integer?
)string[]
){expr}
,{pat}
[,{start}
[,{count}
]])matchstr()echo matchstr("testing", "ing")
{start}
, if given, has the same meaning as formatch().echo matchstr("testing", "ing", 2)
echo matchstr("testing", "ing", 5)
{expr}
is aList then the matching item is returned.The type isn't changed, it's not necessarily a String.{expr}
(any
){pat}
(string
){start}
(integer?
){count}
(integer?
)string
){list}
,{pat}
[,{dict}
])matchstrlist(){list}
where{pat}
matches.{list}
is aList of strings.{pat}
is matched against eachstring in{list}
.{dict}
argument supports following items: submatchesinclude submatch information (/\(){list}
of the match. textmatched string submatchesa List of submatches. Present only if"submatches" is set to v:true in{dict}
.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'}]
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.{list}
(string[]
){pat}
(string
){dict}
(table?
)string[]
){expr}
,{pat}
[,{start}
[,{count}
]])matchstrpos()echo matchstrpos("testing", "ing")
{start}
, if given, has the same meaning as formatch().echo matchstrpos("testing", "ing", 2)
echo matchstrpos("testing", "ing", 5)
{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')
{expr}
(any
){pat}
(string
){start}
(integer?
){count}
(integer?
)table
){expr}
)max(){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.{expr}
(any
)number
){path}
[,{modes}
])menu_get(){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".nnoremenu &Test.Test inormalinoremenu Test.Test insertvnoremenu Test.Test xecho menu_get("")
[ { "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 } ]} ]
{path}
(string
){modes}
(string?
)any
){name}
[,{mode}
])menu_info(){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.{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.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
{name}
(string
){mode}
(string?
)any
){expr}
)min(){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.{expr}
(any
)number
){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{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')
defer delete('subdir/tmp', 'rf')
{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)
{flags}
set to"p" mkdir() will silently exit.{name}
(string
){flags}
(string?
){prot}
(string?
)integer
){expr}
])mode(){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().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-V
s 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{expr}
(any?
)any
){list}
[,{type}
])msgpackdump(){type}
contains "B", aBlob isreturned instead. Example:call writefile(msgpackdump([{}]), 'fname.mpack', 'b')
call writefile(msgpackdump([{}], 'B'), 'fname.mpack')
fname.mpack
file(dictionary with zero items is represented by 0x80 byte inmessagepack).{list}
(any
){type}
(any?
)any
){data}
)msgpackparse()let fname = expand('~/.config/nvim/shada/main.shada')let mpack = readfile(fname, 'b')let shada_objects = msgpackparse(mpack)
shada_objects
list._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):_VAL[0] * ((_VAL[1] << 62) & (_VAL[2] << 31) & _VAL[3])
{data}
(any
)any
){lnum}
)nextnonblank(){lnum}
that is not blank. Example:if getline(nextnonblank(1)) =~ "Java" | endif
{lnum}
is invalid or there is no non-blank line at orbelow it, zero is returned.{lnum}
is used like withgetline().See alsoprevnonblank().{lnum}
(integer|string
)integer
){expr}
[,{utf8}
])nr2char(){expr}
. Examples:echo nr2char(64)" returns '@'echo nr2char(32)" returns ' '
echo nr2char(300)" returns I with bow character
{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.{expr}
(integer
){utf8}
(boolean?
)string
){...}
)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.{...}
(any
)any
){expr}
,{expr}
)or()and()
andxor()
.Example:let bits = or(bits, 0x80)
{expr}
(number
){expr1}
(number
)any
){path}
[,{len}
])pathshorten(){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')
echo pathshorten('~/.config/nvim/autoload/file2.vim', 2)
{path}
(string
){len}
(integer?
)string
){expr}
)perleval(){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.{expr}
must return areference to it.Example:echo perleval('[1 .. 4]')
{expr}
(any
)any
){x}
,{y}
)pow(){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)
echo pow(2, 16)
echo pow(32, 0.20)
{x}
(number
){y}
(number
)number
)number
){lnum}
)prevnonblank(){lnum}
that is not blank. Example:let ind = indent(prevnonblank(v:lnum - 1))
{lnum}
is invalid or there is no non-blank line at orabove it, zero is returned.{lnum}
is used like withgetline().Also seenextnonblank().{lnum}
(integer|string
)integer
){fmt}
,{expr1}
...)printf(){fmt}
, where "%" items are replaced bythe formatted form of their respective arguments. Example:echo printf("%4d: E%d %.30s", lnum, errno, msg)
Compute()->printf("result: %d")
call()
to pass the items as a list.{n$}
, where n is >= 1.echo printf("%d: %.*s", nr, width, line)
{n$}
positional argument specifier. Seeprintf-$.echo printf("%.2f", 12.115)
{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.#, c-formatmsgid "%s returning %s"msgstr "waarde %2$s komt terug van %1$s"
echo printf( "In The Netherlands, vim's creator's name is: %1$s %2$s", "Bram", "Moolenaar")
echo printf( "In Belgium, vim's creator's name is: %2$s %1$s", "Bram", "Moolenaar")
echo printf("%1$*2$.*3$d", 1, 2, 3)
echo printf("%2$*3$.*1$d", 1, 2, 3)
echo printf("%3$*1$.*2$d", 1, 2, 3)
echo printf("%1$*2$.*3$g", 1.4142, 2, 3)
echo printf("%1$4.*2$f", 1.4142135, 6)
echo printf("%1$*2$.4f", 1.4142135, 6)
echo printf("%1$*2$.*3$f", 1.4142135, 6, 2)
echo printf("%3$s%1$s", "One", "Two", "Three")
echo printf("%1$d at width %2$d is: %01$*2$d", 1, 2)
echo printf("%1$d at width %2$ld is: %01$*2$d", 1, 2)
echo printf("%1$d at width %2$d is: %01$*2$.*3$d", 1, 2)
echo printf("%01$*2$.*3$d %4$d", 1, 2)
echo printf("%1$s %2$s %1$d", "One", "Two")
echo printf("%1$d at width %2$d is: %01$*2$.3$d", 1, 2)
{fmt}
(string
){expr1}
(any?
)string
){buf}
)prompt_getinput(){buf}
without invokingprompt_callback.{buf}
can be a buffer name or number.{buf}
(integer|string
)any
){buf}
)prompt_getprompt(){buf}
.{buf}
canbe a buffer name or number. Seeprompt-buffer.{buf}
(integer|string
)any
){buf}
,{expr}
)prompt_setcallback(){buf}
to{expr}
. When{expr}
is an empty string the callback is removed. This has onlyeffect if{buf}
has'buftype' set to "prompt".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'))
{buf}
(integer|string
){expr}
(string|function
)any
){buf}
,{expr}
)prompt_setinterrupt(){buf}
to{expr}
. When{expr}
is anempty string the callback is removed. This has only effect if{buf}
has'buftype' set to "prompt".CTRL-C
in Insertmode. Without setting a callback Vim will exit Insert mode,as in any buffer.{buf}
(integer|string
){expr}
(string|function
)any
){buf}
,{text}
)prompt_setprompt(){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: ')
{buf}
(integer|string
){text}
(string
)any
)any
)any
){expr}
)py3eval(){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.{expr}
(any
)any
){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.{expr}
(any
)any
){expr}
)pyxeval(){expr}
and return its resultconverted to Vim data structures.Uses Python 2 or 3, seepython_x and'pyxversion'.See also:pyeval(),py3eval(){expr}
(any
)any
){expr}
])rand(){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.echo rand()let seed = srand()echo rand(seed)echo rand(seed) % 16 " random number 0 - 15
{expr}
(number?
)any
){expr}
[,{max}
[,{stride}
]])range()E726E727Returns aList with Numbers:{expr}
is specified: [0, 1, ...,{expr}
- 1]{max}
is specified: [{expr}
,{expr}
+ 1, ...,{max}
]{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!
{expr}
(any
){max}
(integer?
){stride}
(integer?
)any
){fname}
[,{offset}
[,{size}
]])readblob(){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)
{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)
{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)
{fname}
(string
){offset}
(integer?
){size}
(integer?
)any
){directory}
[,{expr}
])readdir(){directory}
.You can also useglob() if you don't need to do complicatedthings, such as limiting the number of matches.{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$'})
echo readdir(dirname, {n -> n !~ '^\.\|\~$'})
function! s:tree(dir) return {a:dir : map(readdir(a:dir), \ {_, x -> isdirectory(x) ? \ {x : s:tree(a:dir .. '/' .. x)} : x})}endfunctionecho s:tree(".")
{directory}
(string
){expr}
(integer?
)any
){fname}
[,{type}
[,{max}
]])readfile(){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:{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
{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().{fname}
(string
){type}
(string?
){max}
(integer?
)string[]
){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.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 })
{object}
(any
){func}
(fun(accumulator: T, current: any): any
){initial}
(any?
)T
)any
)any
)any
){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.{start}
and{end}
.{start}
and{end}
arguments must be values returned byreltime(). Returns zero on error.{start}
(any?
){end}
(any?
)any
){time}
)reltimefloat(){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{time}
(any
)any
){time}
)reltimestr(){time}
.This is the number of seconds, a dot and the number ofmicroseconds. Example:let start = reltime()call MyFunction()echo reltimestr(reltime(start))
echo split(reltimestr(reltime(start)))[0]
{time}
(any
)any
){list}
,{idx}
)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)
{list}
(any[]
){idx}
(integer
){end}
(integer?
)any
){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)
{blob}
(any
){idx}
(integer
){end}
(integer?
)any
){dict}
,{key}
)Remove the entry from{dict}
with key{key}
and return it.Example:echo "removed " .. remove(dict, "one")
{key}
in{dict}
this is an error.Returns zero on error.{dict}
(any
){key}
(string
)any
){from}
,{to}
)rename(){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.{from}
(string
){to}
(string
)integer
){expr}
,{count}
)repeat(){expr}
{count}
times and return the concatenatedresult. Example:let separator = repeat('-', 80)
{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)
{expr}
(any
){count}
(integer
)any
){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.{filename}
(string
)string
){object}
)reverse(){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))
{object}
(T[]
)T[]
){expr}
)round(){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)
echo round(4.5)
echo round(-4.5)
{expr}
(number
)number
){channel}
,{event}
[,{args}
...])rpcnotify(){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")
{channel}
(integer
){event}
(string
){...}
(any
)integer
){channel}
,{method}
[,{args}
...])rpcrequest(){channel}
to invoke{method}
viaRPC and blocks until a response is received.Example:let result = rpcrequest(rpc_chan, "func", 1, 2, 3)
{channel}
(integer
){method}
(string
){...}
(any
)any
){expr}
)rubyeval(){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.{expr}
(any
)any
){row}
,{col}
)screenattr(){row}
(integer
){col}
(integer
)integer
){row}
,{col}
)screenchar(){row}
(integer
){col}
(integer
)integer
){row}
,{col}
)screenchars(){row}
(integer
){col}
(integer
)integer[]
)nnoremap <expr> GG ":echom " .. screencol() .. "\n"nnoremap <silent> GG :echom screencol()<CR>noremap GG <Cmd>echom screencol()<CR>
integer[]
){winid}
,{lnum}
,{col}
)screenpos(){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.{winid}
(integer
){lnum}
(integer
){col}
(integer
)any
)integer
){row}
,{col}
)screenstring(){row}
(integer
){col}
(integer
)string
){pattern}
[,{flags}
[,{stopline}
[,{timeout}
[,{skip}
]]]])search()Search for regexp pattern{pattern}
. The search starts at thecursor position (you can usecursor() to set it).{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.{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$"))
{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.{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.{skip}
expression.{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-matchlet 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
echo search('\<if\|\(else\)\|\(endif\)', 'ncpe')
{pattern}
(string
){flags}
(string?
){stopline}
(integer?
){timeout}
(integer?
){skip}
(string|function?
)integer
){options}
])searchcount(){options}
see further down.recompute: 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()
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() : ""}'
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
" 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:let @/ = pattern
maxcount + 1
(default:'maxsearchcount') posList[lnum, col, off]
valuewhen recomputing the result.this changes "current" resultvalue. seecursor(),getpos()(default: cursor's position){options}
(table?
)any
){global}
argument it works likegD, findfirst match in the file. Otherwise it works likegd, findfirst match in the function.{thisblock}
argument matches in a {} blockthat ends before the cursor position are ignored. Avoidsfinding variable declarations only valid in another scope.if searchdecl('myvar') == 0 echo getline('.')endif
{name}
(string
){global}
(boolean?
){thisblock}
(boolean?
)any
){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\>')
{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.{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.{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
{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.echo searchpair('\<if\>', '\<el\%[seif]\>', '\<en\%[dif]\>', 'W',\ 'getline(".") =~ "^\\s*\""')
echo searchpair('{', '', '}', 'bW')
echo searchpair('{', '', '}', 'bW', \ 'synIDattr(synID(line("."), col("."), 0), "name") =~? "string"')
{start}
(string
){middle}
(string
){end}
(string
){flags}
(string?
){skip}
(string|function?
){stopline}
(integer?
){timeout}
(integer?
)integer
){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')
{start}
(string
){middle}
(string
){end}
(string
){flags}
(string?
){skip}
(string|function?
){stopline}
(integer?
){timeout}
(integer?
)[integer, integer]
){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')
let [lnum, col, submatch] = searchpos('\(\l\)\|\(\u\)', 'np')
{pattern}
(string
){flags}
(string?
){stopline}
(integer?
){timeout}
(integer?
){skip}
(string|function?
)any
){opts}
])serverlist(){opts}
is a Dict and supports the following items:echo serverlist()
{opts}
(table?
)string[]
){address}
])serverstart(){address}
and listens forRPC messages. Clients can sendAPI commands to thereturned address to control Nvim.{address}
argument, see below).{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).{address}
is the path to a named pipe (except on Windows).{address}
has no slashes ("/") it is treated as the "name" part of a generated path in this format:stdpath("run").."/{name}.{pid}.{counter}"
{address}
is omitted the name is "nvim".echo serverstart()
=> /tmp/nvim.bram/oknANW/nvim.15430.5
ls ${XDG_RUNTIME_DIR:-${TMPDIR}nvim.${USER}}/*/nvim.*.0
if has('win32') echo serverstart('\\.\pipe\nvim-pipe-1234')else echo serverstart('nvim.sock')endif
echo serverstart('::1:12345')
{address}
(string?
)string
){address}
)serverstop(){address}
.Returns TRUE if{address}
is valid, else FALSE.Ifv:servername is stopped it is set to the next availableaddress inserverlist().{address}
(string
)integer
){buf}
,{lnum}
,{text}
)setbufline(){lnum}
to{text}
in buffer{buf}
. This works likesetline() for the specified buffer.{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.{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.{buf}
is not a valid buffer or{lnum}
is not valid, anerror message is given.{buf}
(integer|string
){lnum}
(integer
){text}
(string|string[]
)integer
){buf}
,{varname}
,{val}
)setbufvar(){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")
{buf}
(integer|string
){varname}
(string
){val}
(any
)any
){list}
)setcellwidths()call setcellwidths([ \ [0x111, 0x111, 1], \ [0x2194, 0x2199, 2], \ ])
{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{list}
:call setcellwidths([])
{list}
argument.{list}
(any[]
)any
){expr}
,{list}
)setcharpos()call setcharpos('.', [0, 8, 4, 0])
call setpos('.', [0, 8, 4, 0])
{expr}
(string
){list}
(integer[]
)any
){dict}
)setcharsearch(){dict}
,which contains one or more of the following entries:let prevsearch = getcharsearch()" Perform a command which clobbers user's searchcall setcharsearch(prevsearch)
{dict}
(string
)any
){str}
[,{pos}
])setcmdline(){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.{str}
(string
){pos}
(integer?
)integer
){pos}
)setcmdpos(){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.{pos}
(integer
)any
){lnum}
,{col}
[,{off}
])setcursorcharpos(){list}
)Same ascursor() but uses the specified column number as thecharacter index instead of the byte index in the line.call setcursorcharpos(4, 3)
call cursor(4, 3)
{list}
(integer[]
)any
){name}
,{val}
)setenv(){name}
to{val}
. Example:call setenv('HOME', '/home/myhome')
{name}
(string
){val}
(string
)any
){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.{fname}
(string
){mode}
(string
)any
){lnum}
,{text}
)setline(){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.{lnum}
is invalid) TRUE is returned.call setline(5, strftime("%c"))
{text}
is aList then line{lnum}
and following lineswill be set to the items in the list. Example:call setline(5, ['aaa', 'bbb', 'ccc'])
for [n, l] in [[5, 'aaa'], [6, 'bbb'], [7, 'ccc']] call setline(n, l)endfor
{lnum}
(integer|string
){text}
(any
)any
){nr}
,{list}
[,{action}
[,{what}
]])setloclist(){nr}
.{nr}
can be the window number or thewindow-ID.When{nr}
is zero the current window is used.{nr}
, -1 is returned.Otherwise, same assetqflist().Also seelocation-list.{action}
seesetqflist-action.{what}
dictionary argument is supplied, thenonly the items listed in{what}
are set. Refer tosetqflist()for the list of supported keys in{what}
.{nr}
(integer
){list}
(any
){action}
(string?
){what}
(table?
)any
){list}
[,{win}
])setmatches(){win}
is specified, use the window with this number orwindow ID instead of the current window.{list}
(vim.fn.getmatches.ret.item[]
){win}
(integer?
)any
){list}
must be aList with four or five numbers: [bufnum, lnum, col, off] [bufnum, lnum, col, off, curswant]<Tab>
or after the lastcharacter.{expr}
is invalid.{expr}
(string
){list}
(integer[]
)any
){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{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:{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.{list}
. This can also be used toclear the list:call setqflist([], 'r')
{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 "$".{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.call setqflist([], 'r', {'title': 'My search'})call setqflist([], 'r', {'nr': 2, 'title': 'Errors'})call setqflist([], 'a', {'id':qfid, 'lines':["F1:10:L10"]})
:cc 1
to jump to the first position.{list}
(vim.quickfix.entry[]
){action}
(string?
){what}
(vim.fn.setqflist.what?
)integer
){regname}
,{value}
[,{options}
])setreg(){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}
.{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.call setreg(v:register, @*)call setreg('*', @%, 'ac')call setreg('a', "1\n2\n3", 'b5')call setreg('"', { 'points_to': 'a'})
let var_a = getreginfo()call setreg('a', var_a)
let var_a = getreg('a', 1, 1)let var_amode = getregtype('a')" ....call setreg('a', var_a, var_amode)
call setreg('a', '', 'al')
{regname}
(string
){value}
(any
){options}
(string?
)any
){tabnr}
,{varname}
,{val}
)settabvar(){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.{tabnr}
(integer
){varname}
(string
){val}
(any
)any
){tabnr}
,{winnr}
,{varname}
,{val}
)settabwinvar(){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")
{tabnr}
(integer
){winnr}
(integer
){varname}
(string
){val}
(any
)any
){nr}
,{dict}
[,{action}
])settagstack(){nr}
using{dict}
.{nr}
can be the window number or thewindow-ID.{dict}
, refer togettagstack(). "curidx" takes effect before changing the tagstack.E962{action}
argument:{action}
is not present or is set to 'r', then the tag stack is replaced.{action}
is set to 'a', then new entries from{dict}
are pushed (added) onto the tag stack.{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.call settagstack(3, {'items' : []})
let stack = gettagstack(1003)" do something elsecall settagstack(1003, stack)unlet stack
{nr}
(integer
){dict}
(any
){action}
(string?
)any
){nr}
,{varname}
,{val}
)setwinvar()call setwinvar(1, "&list", 0)call setwinvar(2, "myvar", "foobar")
{nr}
(integer
){varname}
(string
){val}
(any
)any
){expr}
)sha256(){expr}
.{expr}
is a String or a Blob.{expr}
(string
)string
){string}
indouble-quotes and doubles all double-quotes within{string}
.Otherwise encloses{string}
in single-quotes and replaces all"'" with "'\''".{special}
argument adds additional escaping of keywordsused in Vim commands. If it is anon-zero-arg:<NL>
character is escaped.exe '!dir ' .. shellescape(expand('<cfile>'), 1)
call system("chmod +w -- " .. shellescape(expand("%")))
{string}
(string
){special}
(boolean?
)string
){col}
])shiftwidth()if exists('*shiftwidth') func s:sw() return shiftwidth() endfuncelse func s:sw() return &sw endfuncendif
{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.{col}
(integer?
)integer
){name}
[,{dict}
])sign_define(){list}
)Define a new sign named{name}
or modify the attributes of anexisting sign. This is similar to the:sign-define command.{name}
with a unique text to avoid name collisions.There is no{group}
like with placing signs.{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.{name}
already exists, then the attributesof the sign are updated.{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.{list}
is used, then returns a List of values one for eachdefined sign.call sign_define("mySign", { \ "text" : "=>", \ "texthl" : "Error", \ "linehl" : "Search"})call sign_define([ \ {'name' : 'sign1', \ 'text' : '=>'}, \ {'name' : 'sign2', \ 'text' : '!!'} \ ])
{list}
(vim.fn.sign_define.dict[]
)(0|-1)[]
){name}
])sign_getdefined(){name}
is not supplied, then a list of all the definedsigns is returned. Otherwise the attribute of the specifiedsign is returned.{name}
isnot found." Get a list of all the defined signsecho sign_getdefined()" Get the attribute of the sign named mySignecho sign_getdefined("mySign")
{name}
(string?
)vim.fn.sign_getdefined.ret.item[]
){buf}
[,{dict}
]])sign_getplaced(){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.{bufnr}
. Each listitem is a dictionary with the below listedentries" 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()
{buf}
(integer|string?
){dict}
(vim.fn.sign_getplaced.dict?
)vim.fn.sign_getplaced.ret.item[]
){id}
,{group}
,{buf}
)sign_jump(){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." Jump to sign 10 in the current buffercall sign_jump(10, '', '')
{id}
(integer
){group}
(string
){buf}
(integer|string
)integer
){id}
,{group}
,{name}
,{buf}
[,{dict}
])sign_place(){name}
at line{lnum}
in file orbuffer{buf}
and assign{id}
and{group}
to sign. This issimilar to the:sign-place command.{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().{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.{dict}
is not specified, then it modifies theplaced sign{id}
in group{group}
to use the defined sign{name}
." 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})
{id}
(integer
){group}
(string
){name}
(string
){buf}
(integer|string
){dict}
(vim.fn.sign_place.dict?
)integer
){list}
)sign_placelist(){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.{id}
refers to an existing sign, then the existing sign ismodified to use the specified{name}
and/or{priority}
." 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} \ ])
{list}
(vim.fn.sign_placelist.list.item[]
)integer[]
){name}
])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.{list}
can be used to undefine a list ofsigns. Each list item is the name of a sign.{list}
call, returns a list of values one for each undefinedsign." Delete a sign named mySigncall sign_undefine("mySign")" Delete signs 'sign1' and 'sign2'call sign_undefine(["sign1", "sign2"])" Delete all the signscall sign_undefine()
{list}
(string[]?
)integer[]
){group}
[,{dict}
])sign_unplace(){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." 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('*')
{group}
(string
){dict}
(vim.fn.sign_unplace.dict?
)0|-1
){list}
)sign_unplacelist(){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." 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'}, \ ])
{list}
(vim.fn.sign_unplacelist.list.item
)(0|-1)[]
){filename}
)simplify(){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/"
{filename}
(string
)string
){expr}
)sin(){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)
echo sin(-4.01)
{expr}
(number
)number
){expr}
)sinh(){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)
echo sinh(-0.9)
{expr}
(number
)any
){expr}
,{start}
[,{end}
])slice(){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.{expr}
(any
){start}
(integer
){end}
(integer?
)any
){mode}
,{address}
[,{opts}
])sockconnect(){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.{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:{mode}
(string
){address}
(string
){opts}
(table?
)any
)let sortedlist = sort(copy(mylist))
{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.{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.{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')
" ö is sorted after z with Swedish locale.language collate sv_SE.UTF8echo sort(['n', 'o', 'O', 'ö', 'p', 'z'], 'l')
{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).{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.{how}
is given and it is 'f' then all items will besorted numerical. All values must be a Number or a Float.{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-functionfunc MyCompare(i1, i2) return a:i1 == a:i2 ? 0 : a:i1 > a:i2 ? 1 : -1endfunceval mylist->sort("MyCompare")
func MyCompare(i1, i2) return a:i1 - a:i2endfunc
eval mylist->sort({i1, i2 -> i1 - i2})
{list}
(T[]
){how}
(string|function?
){dict}
(any?
)T[]
){word}
)soundfold(){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.{word}
(string
)string
){sentence}
])spellbadword(){sentence}
thatis badly spelled. If there are no spelling mistakes theresult is an empty string.echo spellbadword("the quik brown fox")
{sentence}
(string?
)any
){word}
[,{max}
[,{capital}
]])spellsuggest(){word}
.When{max}
is given up to this number of suggestions arereturned. Otherwise up to 25 suggestions are returned.{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.{word}
(string
){max}
(integer?
){capital}
(boolean?
)string[]
){string}
[,{pattern}
[,{keepempty}
]])split(){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\+')
for c in split(mystring, '\zs') | endfor
echo split('abc:def:ghi', ':\zs')
['abc:', 'def:', 'ghi']
let items = split(line, ':', 1)
{string}
(string
){pattern}
(string?
){keepempty}
(boolean?
)string[]
){expr}
)sqrt(){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)
echo sqrt(-4.01)
{expr}
(number
)any
){expr}
])srand(){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.{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.let seed = srand()let seed = srand(userinput)echo rand(seed)
{expr}
(number?
)any
){what}
])state()state()
if the work can be done now, and if yes remove it from the queue and execute. Remove the autocommand if the queue is now empty.Also seemode().{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
{what}
(string?
)any
){opts}
)stdioopen(){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:{opts}
(table
)any
){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 Descriptionecho stdpath("config")
{what}
('cache'|'config'|'config_dirs'|'data'|'data_dirs'|'log'|'run'|'state'
)string|string[]
){string}
[,{quoted}
])str2float(){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'))
{string}
(string
){quoted}
(boolean?
)any
){string}
[,{utf8}
])str2list(){string}
. Examples:echo str2list(" ")" returns [32]echo str2list("ABC")" returns [65, 66, 67]
{utf8}
option has no effect,and exists only for backwards-compatibility.With UTF-8 composing characters are handled properly:echo str2list("á")" returns [97, 769]
{string}
(string
){utf8}
(boolean?
)any
){string}
[,{base}
])str2nr(){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.{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')
{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.{string}
is empty or on error.{string}
(string
){base}
(integer?
)any
){string}
)strcharlen(){string}
. Composing characters are ignored.strchars() can count the number of characters, countingcomposing characters separately.{string}
is empty or on error.{string}
(string
)any
){src}
,{start}
[,{len}
[,{skipcc}
]])strcharpart(){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)
{src}
(string
){start}
(integer
){len}
(integer?
){skipcc}
(boolean?
)any
){string}
[,{skipcc}
])strchars(){string}
.When{skipcc}
is omitted or zero, composing characters arecounted separately.When{skipcc}
set to 1, composing characters are ignored.strcharlen() always does this.{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
{string}
(string
){skipcc}
(boolean?
)integer
){string}
[,{col}
])strdisplaywidth(){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().{string}
(string
){col}
(integer?
)integer
){format}
[,{time}
])strftime(){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.
{format}
(string
){time}
(number?
)string
){str}
,{index}
)strgetchar(){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().{str}
(string
){index}
(integer
)integer
){haystack}
,{needle}
[,{start}
])stridx(){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)
{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
{haystack}
(string
){needle}
(string
){start}
(integer?
)integer
){expr}
)string(){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}
typeresultstr2float('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.{expr}
(any
)string
){string}
)strlen(){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().{string}
(string
)integer
){src}
,{start}
[,{len}
[,{chars}
]])strpart(){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().{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'
{start}
must be 0. Forexample, to get the character under the cursor:strpart(getline("."), col(".") - 1, 1, v:true)
{src}
(string
){start}
(integer
){len}
(integer?
){chars}
(0|1?
)string
){format}
,{timestring}
)strptime(){timestring}
, which is expected to matchthe format specified in{format}
.{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.{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.echo strptime("%Y %b %d %X", "1997 Apr 27 11:49:23")
echo strftime("%c", strptime("%y%m%d %T", "970427 11:53:55"))
echo strftime("%c", strptime("%Y%m%d%H%M%S", "19970427115355") + 3600)
{format}
(string
){timestring}
(string
)integer
){haystack}
,{needle}
[,{start}
])strridx(){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)
{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
{haystack}
(string
){needle}
(string
){start}
(integer?
)integer
){string}
)strtrans(){string}
with all unprintablecharacters translated into printable characters'isprint'.Like they are shown in a window. Example:echo strtrans(@a)
{string}
(string
)string
){string}
[,{countcc}
])strutf16len(){string}
(after converting it to UTF-16).{countcc}
is TRUE, composing characters are countedseparately.When{countcc}
is omitted or FALSE, composing characters areignored.echo strutf16len('a')" returns 1echo strutf16len('©')" returns 1echo strutf16len('😊')" returns 2echo strutf16len('ą́')" returns 1echo strutf16len('ą́', v:true)" returns 3
{string}
(string
){countcc}
(0|1?
)integer
){string}
)strwidth(){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().{string}
(string
)integer
){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.{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.s/\d\+/\=submatch(0) + 1/echo substitute(text, '\d\+', '\=submatch(0) + 1', '')
{nr}
(integer
){list}
(nil?
)string
){string}
,{pat}
,{sub}
,{flags}
)substitute(){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 "".{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.{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'.{pat}
does not match in{string}
,{string}
is returnedunmodified.let &path = substitute(&path, ",\\=[^,]*$", "", "")
echo substitute("testing", ".*", "\\U\\0", "")
{sub}
starts with "\=", the remainder is interpreted asan expression. Seesub-replace-expression. Example:echo substitute(s, '%\(\x\x\)', \ '\=nr2char("0x" .. submatch(1))', 'g')
{sub}
is a Funcref that function is called, with oneoptional argument. Example:echo substitute(s, '%\(\x\x\)', SubNr, 'g')
echo substitute(s, '%\(\x\x\)', {m -> '0x' .. m[1]}, 'g')
{string}
(string
){pat}
(string
){sub}
(string
){flags}
(string
)string
)let save_dir = &directorylet &directory = '.'let swapfiles = swapfilelist()let &directory = save_dir
string[]
){fname}
)swapinfo(){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{fname}
(string
)any
){buf}
)swapname(){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.{buf}
(integer|string
)string
){lnum}
,{col}
,{trans}
)synID(){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().{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.echo synIDattr(synID(line("."), col("."), 1), "name")
{lnum}
(integer|string
){col}
(integer
){trans}
(0|1
)integer
){synID}
,{what}
[,{mode}
])synIDattr(){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 nocombineecho synIDattr(synIDtrans(synID(line("."), col("."), 1)), "fg")
echo synID(line("."), col("."), 1)->synIDtrans()->synIDattr("fg")
{synID}
(integer
){what}
(string
){mode}
(string?
)string
){synID}
)synIDtrans(){synID}
. This is the syntax group ID of what is being used tohighlight the character. Highlight links given with":highlight link" are followed.{synID}
(integer
)integer
){lnum}
,{col}
)synconcealed(){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:{lnum}
(integer|string
){col}
(integer
)[integer, string, integer]
){lnum}
,{col}
)synstack(){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
{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.{lnum}
(integer|string
){col}
(integer
)integer[]
){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}'])
<CR>
<NL>
is replaced with<NL>
echo system(['ls', expand('%:h')])
{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).E5677echo system("cat - &", "foo")
$ echo foo | bash -c 'cat - &'
echo system('ls '..shellescape(expand('%:h')))echo system('ls '..expand('%:h:S'))
{cmd}
(string|string[]
){input}
(string|string[]|integer?
)string
){cmd}
[,{input}
[,{keepempty}
]])systemlist(){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.echo split(system('echo hello'), '\n', 1)
{cmd}
(string|string[]
){input}
(string|string[]|integer?
){keepempty}
(integer?
)string[]
){arg}
])tabpagebuflist(){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
{arg}
(integer?
)any
){arg}
])tabpagenr(){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.{arg}
('$'|'#'?
)integer
){tabarg}
[,{arg}
])tabpagewinnr(){tabarg}
.{tabarg}
specifies the number of tab page to be used.{arg}
is used like withwinnr():tabpagewinnr(1) " current window of tab page 1tabpagewinnr(4, '$') " number of windows in tab page 4
{tabarg}
is invalid zero is returned.{tabarg}
(integer
){arg}
('$'|'#'?
)integer
)string[]
){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.{expr}
. This also make the function work faster.Refer totag-regexp for more information about the tagsearch regular expression pattern.{expr}
(any
){filename}
(string?
)any
){expr}
)tan(){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)
echo tan(-4.01)
{expr}
(number
)number
){expr}
)tanh(){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)
echo tanh(-1)
{expr}
(number
)number
)let tmpfile = tempname()exe "redir > " .. tmpfile
string
)any
){id}
])timer_info(){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.{id}
(integer?
)any
){timer}
,{paused}
)timer_pause(){paused}
evaluates to a non-zero Number or a non-emptyString, then the timer is paused, otherwise it is unpaused.Seenon-zero-arg.{timer}
(integer
){paused}
(boolean
)any
){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.func MyHandler(timer) echo 'Handler called'endfunclet timer = timer_start(500, 'MyHandler', \ {'repeat': 3})
{time}
(number
){callback}
(string|function
){options}
(table?
)any
){timer}
)timer_stop(){timer}
is an ID returned by timer_start(), thus it must be aNumber. If{timer}
does not exist there is no error.{timer}
(integer
)any
)any
){expr}
)tolower(){expr}
(string
)string
){expr}
)toupper(){expr}
(string
)string
){src}
,{fromstr}
,{tostr}
)tr(){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.echo tr("hello there", "ht", "HT")
echo tr("<blob>", "<>", "{}")
{src}
(string
){fromstr}
(string
){tostr}
(string
)string
){text}
[,{mask}
[,{dir}
]])trim(){text}
as a String where any character in{mask}
isremoved from the beginning and/or end of{text}
.{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.{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.echo trim(" some text ")
echo trim(" \r\t\t\r RESERVE \t\n\x0B\xA0") .. "_TAIL"
echo trim("rm<Xrm<>X>rrm", "rm<>")
echo trim(" vim ", " ", 2)
{text}
(string
){mask}
(string?
){dir}
(0|1|2?
)string
){expr}
)trunc(){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)
echo trunc(-5.456)
echo trunc(4.0)
{expr}
(number
)integer
){expr}
)type(){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
if myvar is v:null | endif
if exists('v:t_number') | endif
{expr}
(any
)integer
){name}
)undofile(){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.{name}
(string
)string
){buf}
])undotree(){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.{buf}
(integer|string?
)vim.fn.undotree.ret
){list}
items in-place. Returns{list}
. If you want a listto remain unmodified make a copy first:let newlist = uniq(copy(mylist))
{func}
and{dict}
seesort().For deduplicating text in the current buffer see:uniq.{list}
is not aList.{list}
(any
){func}
(any?
){dict}
(any?
)any[]|0
){string}
,{idx}
[,{countcc}
[,{charidx}
]])utf16idx(){idx}
in{string}
(after converting it to UTF-16).{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.{idx}
bytes in{string}
. If there are exactly{idx}
bytesthe length of the string in UTF-16 code units is returned.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
{string}
(string
){idx}
(integer
){countcc}
(boolean?
){charidx}
(boolean?
)integer
){dict}
)values(){dict}
. TheList isin arbitrary order. Also seeitems() andkeys().Returns zero if{dict}
is not aDict.{dict}
(any
)any
){expr}
[,{list}
[,{winid}
]])virtcol(){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().{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.{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'{list}
is present and non-zero then virtcol() returns aList with the first and last screen position occupied by thecharacter.{winid}
argument the values are obtained forthat window instead of the current window." 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
echo max(map(range(1, line('$')), "virtcol([v:val, '$'])"))
{expr}
(string|any[]
){list}
(boolean?
){winid}
(integer?
)integer|[integer, integer]
){winid}
,{lnum}
,{col}
)virtcol2col(){winid}
at buffer line{lnum}
and virtualcolumn{col}
.{lnum}
is an empty line, 0 is returned.{col}
is greater than the last virtual column in line{lnum}
, then the byte index of the character at the lastvirtual column is returned.{winid}
argument can be the window number or thewindow-ID. If this is zero, then the current window is used.{winid}
doesn't exist or the bufferline{lnum}
or virtual column{col}
is invalid.{winid}
(integer
){lnum}
(integer
){col}
(integer
)integer
){expr}
])visualmode()CTRL-V
character) forcharacter-wise, line-wise, or block-wise Visual moderespectively.Example:exe "normal " .. visualmode()
{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.{expr}
(boolean?
)string
){timeout}
,{condition}
[,{interval}
])wait(){condition}
evaluates toTRUE, where{condition}
is aFuncref orstring containing an expression.{timeout}
is the maximum waiting time in milliseconds, -1means forever.{interval}
milliseconds (default: 200).{timeout}
(integer
){condition}
(any
){interval}
(number?
)any
)<c-j>
work like<down>
in wildmode, use:cnoremap <expr> <C-j> wildmenumode() ? "\<Down>\<Tab>" : "\<c-j>"
any
)number
){id}
,{command}
[,{silent}
])win_execute()execute()
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')
setwinvar()
would not triggerautocommands and not actually show syntax highlighting.{id}
does not exist then no error is given andan empty string is returned.{id}
(integer
){command}
(string
){silent}
(boolean?
)any
){bufnr}
)win_findbuf(){bufnr}
. When there is none the list is empty.{bufnr}
(integer
)integer[]
){win}
[,{tab}
]])win_getid(){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.{win}
(integer?
){tab}
(integer?
)integer
){nr}
])win_gettype(){nr}
not found{nr}
is omitted return the type of the current window.When{nr}
is given return the type of this window by number orwindow-ID.{nr}
(integer?
)'autocmd'|'command'|''|'loclist'|'popup'|'preview'|'quickfix'|'unknown'
){expr}
)win_gotoid(){expr}
. This may also change the currenttabpage.Return TRUE if successful, FALSE if the window cannot be found.{expr}
(integer
)0|1
){expr}
)win_id2tabwin(){expr}
: [tabnr, winnr].Return [0, 0] if the window cannot be found.{expr}
(integer
)any
){expr}
)win_id2win(){expr}
.Return 0 if the window cannot be found in the current tabpage.{expr}
(integer
)integer
){nr}
,{offset}
)win_move_separator(){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{nr}
(integer
){offset}
(integer
)any
){nr}
,{offset}
)win_move_statusline(){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.{nr}
(integer
){offset}
(integer
)any
){nr}
)win_screenpos(){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.{nr}
(integer
)any
){nr}
,{target}
[,{options}
])win_splitmove(){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).{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.{nr}
(integer
){target}
(integer
){options}
(table?
)any
){nr}
)winbufnr(){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))
{nr}
(integer
)integer
)integer
)string
){nr}
)winheight(){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.echo "Current window has " .. winheight(0) .. " lines."
{nr}
(integer
)integer
){tabnr}
])winlayout(){tabnr}
use the current tabpage, otherwise the tabpagewith number{tabnr}
. If the tabpage{tabnr}
is not found,returns an empty list.["leaf", {winid}]
["col", [{nested list of windows}]]
["row", [{nested list of windows}]]
" 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]]]
{tabnr}
(integer?
)vim.fn.winlayout.ret
)integer
){arg}
])winnr(){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')
{arg}
(string|integer?
)integer
)let cmd = winrestcmd()call MessWithWindowSizes()exe cmd
string
){dict}
)winrestview(){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})
{dict}
(vim.fn.winrestview.dict
)any
)vim.fn.winsaveview.ret
){nr}
)winwidth(){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.echo "Current window has " .. winwidth(0) .. " columns."if winwidth(0) <= 50 50 wincmd |endif
:echo getwininfo(win_getid())[0].width - getwininfo(win_getid())[0].textoff
{nr}
(integer
)integer
)any
){object}
,{fname}
[,{flags}
])writefile(){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().{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:call writefile(["foo"], "event.log", "a")call writefile(["bar"], "event.log", "a")
defer delete({fname})
{flags}
does not contain "S" or "s" then fsync() is called if the'fsync' option is set.let fl = readfile("foo", "b")call writefile(fl, "foocopy", "b")
{object}
(any
){fname}
(string
){flags}
(string?
)any
){expr}
,{expr}
)xor()and()
andor()
.Example:let bits = xor(bits, 0x80)
{expr}
(integer
){expr1}
(integer
)integer
)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".