builtin.txt ForVim version 9.1. Last change: 2025 Jul 03VIM REFERENCE MANUAL by Bram MoolenaarBuiltinfunctionsbuiltin-functionsNote: Expression evaluation can be disabledat compile time, the builtinfunctions are not available then. See+eval andno-eval-feature.Forfunctions grouped by what they are used for seefunction-list.1. Overviewbuiltin-function-list2. Detailsbuiltin-function-details3. Featurelistfeature-list4. Matchingapattern inaStringstring-match==============================================================================1. Overviewbuiltin-function-listUseCTRL-] on the function name to jump to the full explanation.USAGERESULTDESCRIPTIONabs({expr})Float orNumber absolute value of{expr}acos({expr})Floatarc cosine of{expr}add({object},{item})List/Blob append{item} to{object}and({expr},{expr})Numberbitwise ANDappend({lnum},{text})Numberappend{text} below line{lnum}appendbufline({buf},{lnum},{text})Numberappend{text} below line{lnum}in buffer{buf}argc([{winid}])Numbernumber of files in the argumentlistargidx()Numbercurrentindex in the argumentlistarglistid([{winnr} [,{tabnr}]])Numberargumentlist idargv({nr} [,{winid}])String{nr} entry of the argumentlistargv([-1,{winid}])Listthe argumentlistasin({expr})Floatarc sine of{expr}assert_beeps({cmd})Numberassert{cmd} causesabeepassert_equal({exp},{act} [,{msg}])Numberassert{exp}is equal to{act}assert_equalfile({fname-one},{fname-two} [,{msg}])Numberassert file contents are equalassert_exception({error} [,{msg}])Numberassert{error}is inv:exceptionassert_fails({cmd} [,{error} [,{msg} [,{lnum} [,{context}]]]])Numberassert{cmd} failsassert_false({actual} [,{msg}])Numberassert{actual}isfalseassert_inrange({lower},{upper},{actual} [,{msg}])Numberassert{actual}is inside the rangeassert_match({pat},{text} [,{msg}])Numberassert{pat} matches{text}assert_nobeep({cmd})Numberassert{cmd} does not causeabeepassert_notequal({exp},{act} [,{msg}])Numberassert{exp}is not equal{act}assert_notmatch({pat},{text} [,{msg}])Numberassert{pat} not matches{text}assert_report({msg})Numberreporta test failureassert_true({actual} [,{msg}])Numberassert{actual}istrueatan({expr})Floatarc tangent of{expr}atan2({expr1},{expr2})Floatarc tangent of{expr1}/{expr2}autocmd_add({acmds})Booladdalist of autocmds and groupsautocmd_delete({acmds})Booldeletealist of autocmds and groupsautocmd_get([{opts}])Listreturnalist of autocmdsballoon_gettext()Stringcurrent text in the balloonballoon_show({expr})noneshow{expr} inside the balloonballoon_split({msg})Listsplit{msg}as used fora balloonbase64_decode({string})Blobbase64 decode{string} charactersbase64_encode({blob})Stringbase64 encode the bytes in{blob}bindtextdomain({package},{path})Boolbind text domain to specified pathblob2list({blob})Listconvert{blob} intoalist of numbersblob2str({blob} [,{options}])Listconvert{blob} intoalist of stringsbrowse({save},{title},{initdir},{default})Stringput upa file requesterbrowsedir({title},{initdir})Stringput upa directory requesterbufadd({name})Numberadda buffer to the bufferlistbufexists({buf})NumberTRUE if buffer{buf} existsbuflisted({buf})NumberTRUE if buffer{buf}is listedbufload({buf})Numberload buffer{buf} if not loaded yetbufloaded({buf})NumberTRUE if buffer{buf}is loadedbufname([{buf}])StringName of the buffer{buf}bufnr([{buf} [,{create}]])NumberNumber of the buffer{buf}bufwinid({buf})Numberwindow ID of buffer{buf}bufwinnr({buf})Numberwindow number of buffer{buf}byte2line({byte})Numberline numberat bytecount{byte}byteidx({expr},{nr} [,{utf16}])Numberbyteindex of{nr}'th char in{expr}byteidxcomp({expr},{nr} [,{utf16}])Numberbyteindex of{nr}'th char in{expr}call({func},{arglist} [,{dict}])anycall{func} with arguments{arglist}ceil({expr})Floatround{expr} upch_canread({handle})Numbercheck if thereis something to readch_close({handle})noneclose{handle}ch_close_in({handle})noneclose in part of{handle}ch_evalexpr({handle},{expr} [,{options}])anyevaluate{expr} on JSON{handle}ch_evalraw({handle},{string} [,{options}])anyevaluate{string} on raw{handle}ch_getbufnr({handle},{what})Numberget buffer number for{handle}/{what}ch_getjob({channel})Jobget theJob of{channel}ch_info({handle})Stringinfo aboutchannel{handle}ch_log({msg} [,{handle}])nonewrite{msg} in thechannel log filech_logfile({fname} [,{mode}])nonestart loggingchannel activitych_open({address} [,{options}])Channelopenachannel to{address}ch_read({handle} [,{options}])Stringread from{handle}ch_readblob({handle} [,{options}])BlobreadBlob from{handle}ch_readraw({handle} [,{options}])Stringread raw from{handle}ch_sendexpr({handle},{expr} [,{options}])anysend{expr} over JSON{handle}ch_sendraw({handle},{expr} [,{options}])anysend{expr} over raw{handle}ch_setoptions({handle},{options})nonesetoptions for{handle}ch_status({handle} [,{options}])Stringstatus ofchannel{handle}changenr()Numbercurrent change numberchar2nr({expr} [,{utf8}])NumberASCII/UTF-8 value of first char in{expr}charclass({string})Numbercharacterclass of{string}charcol({expr} [,{winid}])Numbercolumn number of cursor ormarkcharidx({string},{idx} [,{countcc} [,{utf16}]])Numbercharindex of byte{idx} in{string}chdir({dir})Stringchange current working directorycindent({lnum})NumberC indent for line{lnum}clearmatches([{win}])noneclear all matchescmdcomplete_info()Dictget current cmdline completioninformationcol({expr} [,{winid}])Numbercolumn byteindex of cursor ormarkcomplete({startcol},{matches}) nonesetInsert mode completioncomplete_add({expr})Numberadd completion matchcomplete_check()Numbercheck for key typed during completioncomplete_info([{what}])Dictget current completion informationcomplete_match([{lnum},{col}])Listget completion column and trigger textconfirm({msg} [,{choices} [,{default} [,{type}]]])Numbernumber of choice picked by usercopy({expr})anymakea shallow copy of{expr}cos({expr})Floatcosine of{expr}cosh({expr})Floathyperbolic cosine of{expr}count({comp},{expr} [,{ic} [,{start}]])Numbercount how many{expr} are in{comp}cscope_connection([{num},{dbpath} [,{prepend}]])Numberchecks existence ofcscope connectioncursor({lnum},{col} [,{off}])Numbermove cursor to{lnum},{col},{off}cursor({list})Numbermove cursor to position in{list}debugbreak({pid})Numberinterrupt process being debuggeddeepcopy({expr} [,{noref}])anymakea full copy of{expr}delete({fname} [,{flags}])Numberdelete the file or directory{fname}deletebufline({buf},{first} [,{last}])Numberdelete lines from buffer{buf}did_filetype()NumberTRUE ifFileType autocmd event useddiff({fromlist},{tolist} [,{options}])Listdiff twoLists of stringsdiff_filler({lnum})Numberdiff filler lines about{lnum}diff_hlID({lnum},{col})Numberdiff highlightingat{lnum}/{col}digraph_get({chars})Stringget thedigraph of{chars}digraph_getlist([{listall}])Listget alldigraphsdigraph_set({chars},{digraph})Boolregisterdigraphdigraph_setlist({digraphlist})Boolregister multipledigraphsechoraw({expr})noneoutput{expr} as-isempty({expr})NumberTRUE if{expr}is emptyenviron()Dictreturn environmentvariableserr_teapot([{expr}])nonegive E418, orE503 if{expr}isTRUEescape({string},{chars})Stringescape{chars} in{string} with '\'eval({string})anyevaluate{string} into its valueeventhandler()NumberTRUE if inside an event handlerexecutable({expr})Number1 if executable{expr} existsexecute({command})Stringexecute{command} and get the outputexepath({expr})Stringfull path of the command{expr}exists({expr})NumberTRUE if{expr} existsexists_compiled({expr})NumberTRUE if{expr} existsat compile timeexp({expr})Floatexponential of{expr}expand({expr} [,{nosuf} [,{list}]])anyexpand special keywords in{expr}expandcmd({string} [,{options}])Stringexpand{string} like with:editextend({expr1},{expr2} [,{expr3}])List/Dictinsert items of{expr2} into{expr1}extendnew({expr1},{expr2} [,{expr3}])List/Dict likeextend() but createsa newList orDictionaryfeedkeys({string} [,{mode}])Numberadd key sequence to typeahead bufferfilecopy({from},{to})NumberTRUE ifcopying file{from} to{to}workedfilereadable({file})NumberTRUE if{file}isa readable filefilewritable({file})NumberTRUE if{file}isa writable filefilter({expr1},{expr2})List/Dict/Blob/Stringremove items from{expr1} where{expr2}is0finddir({name} [,{path} [,{count}]])findfile({name} [,{path} [,{count}]])String/List find dir/file{name} in{path}flatten({list} [,{maxdepth}])Listflatten{list} up to{maxdepth} levelsflattennew({list} [,{maxdepth}])Listflattena copy of{list}float2nr({expr})NumberconvertFloat{expr} toaNumberfloor({expr})Floatround{expr} downfmod({expr1},{expr2})Floatremainder of{expr1}/{expr2}fnameescape({fname})Stringescape special characters in{fname}fnamemodify({fname},{mods})Stringmodify file namefoldclosed({lnum})Numberfirst line of foldat{lnum} if closedfoldclosedend({lnum})Numberlast line of foldat{lnum} if closedfoldlevel({lnum})Numberfold levelat{lnum}foldtext()Stringline displayed for closed foldfoldtextresult({lnum})Stringtext for closed foldat{lnum}foreach({expr1},{expr2})List/Tuple/Dict/Blob/Stringfor each item in{expr1} call{expr2}foreground()Numberbring the Vimwindow to the foregroundfullcommand({name} [,{vim9}])Stringget full command from{name}funcref({name} [,{arglist}] [,{dict}])Funcrefreference to function{name}function({name} [,{arglist}] [,{dict}])Funcrefnamedreference to function{name}garbagecollect([{atexit}])nonefree memory, breaking cyclic referencesget({list},{idx} [,{def}])anyget item{idx} from{list} or{def}get({dict},{key} [,{def}])anyget item{key} from{dict} or{def}get({func},{what})anyget property of funcref/partial{func}getbufinfo([{buf}])Listinformation aboutbuffersgetbufline({buf},{lnum} [,{end}])Listlines{lnum} to{end} of buffer{buf}getbufoneline({buf},{lnum})Stringline{lnum} of buffer{buf}getbufvar({buf},{varname} [,{def}])anyvariable{varname} in buffer{buf}getcellpixels()Listget character cell pixel sizegetcellwidths()Listget character cell width overridesgetchangelist([{buf}])Listlist of changelist itemsgetchar([{expr} [,{opts}]])Number orStringget one character from the usergetcharmod()Numbermodifiers for the last typed charactergetcharpos({expr})Listposition of cursor, mark, etc.getcharsearch()Dictlast character searchgetcharstr([{expr} [,{opts}]])Stringget one character from the usergetcmdcomplpat()Stringreturn the completionpattern of thecurrent command-line completiongetcmdcompltype({pat})Stringreturn the type of command-linecompletiongetcmdline()Stringreturn the current command-line inputgetcmdpos()Numberreturn cursor position in command-linegetcmdprompt()Stringreturn the current command-line promptgetcmdscreenpos()Numberreturn cursor screen position incommand-linegetcmdtype()Stringreturn current command-line typegetcmdwintype()Stringreturn current command-linewindow typegetcompletion({pat},{type} [,{filtered}])Listlist of cmdline completion matchesgetcurpos([{winnr}])Listposition of the cursorgetcursorcharpos([{winnr}])Listcharacter position of the cursorgetcwd([{winnr} [,{tabnr}]])Stringget the current working directorygetenv({name})Stringreturn environment variablegetfontname([{name}])Stringname of font being usedgetfperm({fname})Stringfile permissions of file{fname}getfsize({fname})Numbersize in bytes of file{fname}getftime({fname})Numberlast modification time of filegetftype({fname})Stringdescription of type of file{fname}getimstatus()NumberTRUE if theIME statusis activegetjumplist([{winnr} [,{tabnr}]])Listlist of jumplist itemsgetline({lnum})Stringline{lnum} of current buffergetline({lnum},{end})Listlines{lnum} to{end} of current buffergetloclist({nr})Listlist of locationlist itemsgetloclist({nr},{what})Dictget specific locationlist propertiesgetmarklist([{buf}])Listlist of global/local marksgetmatches([{win}])Listlist of current matchesgetmousepos()Dictlast known mouse positiongetmouseshape()Stringcurrent mouse shape namegetpid()Numberprocess ID of Vimgetpos({expr})Listposition of cursor, mark, etc.getqflist()Listlist ofquickfix itemsgetqflist({what})Dictget specificquickfixlist propertiesgetreg([{regname} [, 1 [,{list}]]])String orList contents ofaregistergetreginfo([{regname}])Dictinformation aboutaregistergetregion({pos1},{pos2} [,{opts}])Listget the text from{pos1} to{pos2}getregionpos({pos1},{pos2} [,{opts}])Listgetalist of positions fora regiongetregtype([{regname}])Stringtype ofaregistergetscriptinfo([{opts}])Listlist of sourced scriptsgetstacktrace()Listget current stack trace of Vim scriptsgettabinfo([{expr}])Listlist oftab pagesgettabvar({nr},{varname} [,{def}])anyvariable{varname} intab{nr} or{def}gettabwinvar({tabnr},{winnr},{name} [,{def}])any{name} in{winnr} intab page{tabnr}gettagstack([{nr}])Dictget thetag stack ofwindow{nr}gettext({text} [,{package}])Stringlookup translation of{text}getwininfo([{winid}])Listlist of info about eachwindowgetwinpos([{timeout}])ListX andY coord in pixels of Vimwindowgetwinposx()NumberX coord in pixels of the Vimwindowgetwinposy()NumberY coord in pixels of the Vimwindowgetwinvar({nr},{varname} [,{def}])anyvariable{varname} inwindow{nr}glob({expr} [,{nosuf} [,{list} [,{alllinks}]]])anyexpand filewildcards in{expr}glob2regpat({expr})Stringconverta glob pat intoa search patglobpath({path},{expr} [,{nosuf} [,{list} [,{alllinks}]]])Stringdo glob({expr}) for all dirs in{path}has({feature} [,{check}])NumberTRUE if feature{feature} supportedhas_key({dict},{key})NumberTRUE if{dict} has entry{key}haslocaldir([{winnr} [,{tabnr}]])NumberTRUE if thewindow executed:lcdor:tcdhasmapto({what} [,{mode} [,{abbr}]])NumberTRUE ifmapping to{what} existshistadd({history},{item})Numberadd an item toahistoryhistdel({history} [,{item}])Numberremove an item fromahistoryhistget({history} [,{index}])Stringget the item{index} fromahistoryhistnr({history})Numberhighestindex ofahistoryhlID({name})Numbersyntax ID of highlight group{name}hlexists({name})NumberTRUE if highlight group{name} existshlget([{name} [,{resolve}]])Listget highlight group attributeshlset({list})Numberset highlight group attributeshostname()Stringname of the machine Vimis running oniconv({expr},{from},{to})Stringconvert encoding of{expr}id({item})Stringgetunique identitystring of itemindent({lnum})Numberindent of line{lnum}index({object},{expr} [,{start} [,{ic}]])Numberindex in{object} where{expr} appearsindexof({object},{expr} [,{opts}]])Numberindex in{object} where{expr}istrueinput({prompt} [,{text} [,{completion}]])Stringget input from the userinputdialog({prompt} [,{text} [,{cancelreturn}]])Stringlikeinput() but inaGUIdialoginputlist({textlist})Numberlet the user pick froma choicelistinputrestore()Numberrestore typeaheadinputsave()Numbersave and clear typeaheadinputsecret({prompt} [,{text}])Stringlikeinput() but hiding the textinsert({object},{item} [,{idx}])Listinsert{item} in{object} [before{idx}]instanceof({object},{class})NumberTRUE if{object}is an instance of{class}interrupt()noneinterruptscript executioninvert({expr})Numberbitwise invertisabsolutepath({path})NumberTRUE if{path}is an absolute pathisdirectory({directory})NumberTRUE if{directory}isa directoryisinf({expr})Numberdetermine if{expr}is infinity value(positive or negative)islocked({expr})NumberTRUE if{expr}is lockedisnan({expr})NumberTRUE if{expr}is NaNitems({dict})Listkey-value pairs in{dict}job_getchannel({job})Channelget thechannel handle for{job}job_info([{job}])Dictget information about{job}job_setoptions({job},{options}) nonesetoptions for{job}job_start({command} [,{options}])Jobstartajobjob_status({job})Stringget the status of{job}job_stop({job} [,{how}])Numberstop{job}join({expr} [,{sep}])Stringjoin items in{expr} into oneStringjs_decode({string})anydecode JS style JSONjs_encode({expr})Stringencode JS style JSONjson_decode({string})anydecode JSONjson_encode({expr})Stringencode JSONkeys({dict})Listkeys in{dict}keytrans({string})Stringtranslate internalkeycodes toa formthat can be used by:maplen({expr})Numberthe length of{expr}libcall({lib},{func},{arg})Stringcall{func} in library{lib} with{arg}libcallnr({lib},{func},{arg})Numberidem, but returnaNumberline({expr} [,{winid}])Numberline nr of cursor, last line ormarkline2byte({lnum})Numberbytecount of line{lnum}lispindent({lnum})NumberLisp indent for line{lnum}list2blob({list})Blobturn{list} of numbers intoaBloblist2str({list} [,{utf8}])Stringturn{list} of numbers intoaStringlist2tuple({list})Tupleturn{list} of items intoatuplelistener_add({callback} [,{buf}])Numberadda callback to listen to changeslistener_flush([{buf}])noneinvoke listener callbackslistener_remove({id})noneremovea listener callbacklocaltime()Numbercurrent timelog({expr})Floatnatural logarithm (base e) of{expr}log10({expr})Floatlogarithm ofFloat{expr} to base 10luaeval({expr} [,{expr}])anyevaluateLuaexpressionmap({expr1},{expr2})List/Dict/Blob/Stringchange each item in{expr1} to{expr2}maparg({name} [,{mode} [,{abbr} [,{dict}]]])String orDictrhs ofmapping{name} in mode{mode}mapcheck({name} [,{mode} [,{abbr}]])Stringcheck for mappings matching{name}maplist([{abbr}])Listlist of all mappings,adict for eachmapnew({expr1},{expr2})List/Dict/Blob/Stringlikemap() but createsa newList orDictionarymapset({mode},{abbr},{dict})nonerestoremapping frommaparg() resultmatch({expr},{pat} [,{start} [,{count}]])Numberposition where{pat} matches in{expr}matchadd({group},{pattern} [,{priority} [,{id} [,{dict}]]])Numberhighlight{pattern} with{group}matchaddpos({group},{pos} [,{priority} [,{id} [,{dict}]]])Numberhighlight positions with{group}matcharg({nr})Listarguments of:matchmatchbufline({buf},{pat},{lnum},{end}, [,{dict})Listall the{pat} matches in buffer{buf}matchdelete({id} [,{win}])Numberdelete match identified by{id}matchend({expr},{pat} [,{start} [,{count}]])Numberposition where{pat} ends in{expr}matchfuzzy({list},{str} [,{dict}])Listfuzzy match{str} in{list}matchfuzzypos({list},{str} [,{dict}])Listfuzzy match{str} in{list}matchlist({expr},{pat} [,{start} [,{count}]])Listmatch and submatches of{pat} in{expr}matchstr({expr},{pat} [,{start} [,{count}]])String{count}'th match of{pat} in{expr}matchstrlist({list},{pat} [,{dict})Listall the{pat} matches in{list}matchstrpos({expr},{pat} [,{start} [,{count}]])List{count}'th match of{pat} in{expr}max({expr})Numbermaximum value of items in{expr}menu_info({name} [,{mode}])Dictget menu item informationmin({expr})Numberminimum value of items in{expr}mkdir({name} [,{flags} [,{prot}]])Numbercreate directory{name}mode([{expr}])Stringcurrent editing modemzeval({expr})anyevaluateMzSchemeexpressionnextnonblank({lnum})Numberline nr of non-blank line >={lnum}ngettext({single},{plural},{number}[,{domain}])Stringtranslate text based on{number}nr2char({expr} [,{utf8}])Stringsingle char with ASCII/UTF-8 value{expr}or({expr},{expr})Numberbitwise ORpathshorten({expr} [,{len}])Stringshorten directory names ina pathperleval({expr})anyevaluatePerlexpressionpopup_atcursor({what},{options})Number createpopupwindow near the cursorpopup_beval({what},{options})Numbercreatepopupwindow for'ballooneval'popup_clear()noneclose allpopupwindowspopup_close({id} [,{result}])noneclosepopupwindow{id}popup_create({what},{options})Numbercreateapopupwindowpopup_dialog({what},{options})Numbercreateapopupwindow usedasadialogpopup_filter_menu({id},{key})Numberfilter fora menupopupwindowpopup_filter_yesno({id},{key})Numberfilter foradialogpopupwindowpopup_findecho()Numbergetwindow ID ofpopup for:echowinpopup_findinfo()Numbergetwindow ID of infopopupwindowpopup_findpreview()Numbergetwindow ID of previewpopupwindowpopup_getoptions({id})Dictgetoptions ofpopupwindow{id}popup_getpos({id})Dictget position ofpopupwindow{id}popup_hide({id})nonehidepopup menu{id}popup_list()Listgetalist ofwindow IDs of all popupspopup_locate({row},{col})Numbergetwindow ID ofpopupat positionpopup_menu({what},{options})Numbercreateapopupwindow usedasa menupopup_move({id},{options})noneset position ofpopupwindow{id}popup_notification({what},{options})Numbercreatea notificationpopupwindowpopup_setbuf({id},{buf})Boolset the buffer for thepopupwindow{id}popup_setoptions({id},{options})nonesetoptions forpopupwindow{id}popup_settext({id},{text})noneset the text ofpopupwindow{id}popup_show({id})noneunhidepopupwindow{id}pow({x},{y})Float{x} to the power of{y}prevnonblank({lnum})Numberline nr of non-blank line <={lnum}printf({fmt},{expr1}...)Stringformat textprompt_getprompt({buf})Stringget prompt textprompt_setcallback({buf},{expr}) noneset prompt callback functionprompt_setinterrupt({buf},{text}) noneset prompt interrupt functionprompt_setprompt({buf},{text}) noneset prompt textprop_add({lnum},{col},{props}) noneadd one text propertyprop_add_list({props}, [[{lnum},{col},{end-lnum},{end-col}], ...])noneadd multiple text propertiesprop_clear({lnum} [,{lnum-end} [,{props}]])noneremove all text propertiesprop_find({props} [,{direction}])Dictsearch fora text propertyprop_list({lnum} [,{props}])Listtext properties in{lnum}prop_remove({props} [,{lnum} [,{lnum-end}]])Numberremovea text propertyprop_type_add({name},{props})nonedefinea new property typeprop_type_change({name},{props})nonechange an existing property typeprop_type_delete({name} [,{props}])nonedeletea property typeprop_type_get({name} [,{props}])Dictget property type valuesprop_type_list([{props}])Listgetlist of property typespum_getpos()Dictposition and size of pum if visiblepumvisible()Numberwhetherpopup menuis visiblepy3eval({expr} [,{locals}])anyevaluatepython3expressionpyeval({expr} [,{locals}])anyevaluatePythonexpressionpyxeval({expr} [,{locals}])anyevaluatepython_xexpressionrand([{expr}])Numberget pseudo-random numberrange({expr} [,{max} [,{stride}]])Listitems from{expr} to{max}readblob({fname} [,{offset} [,{size}]])BlobreadaBlob from{fname}readdir({dir} [,{expr} [,{dict}]])Listfile names in{dir} selected by{expr}readdirex({dir} [,{expr} [,{dict}]])Listfile info in{dir} selected by{expr}readfile({fname} [,{type} [,{max}]])Listgetlist of lines from file{fname}reduce({object},{func} [,{initial}])anyreduce{object} using{func}reg_executing()Stringget the executingregister namereg_recording()Stringget therecordingregister namereltime([{start} [,{end}]])Listget time valuereltimefloat({time})Floatturn the time value intoaFloatreltimestr({time})Stringturn time value intoaStringremote_expr({server},{string} [,{idvar} [,{timeout}]])Stringsendexpressionremote_foreground({server})Numberbring Vim server to the foregroundremote_peek({serverid} [,{retvar}])Numbercheck for replystringremote_read({serverid} [,{timeout}])Stringread replystringremote_send({server},{string} [,{idvar}])Stringsend key sequenceremote_startserver({name})nonebecome server{name}remove({list},{idx} [,{end}])any/Listremove items{idx}-{end} from{list}remove({blob},{idx} [,{end}])Number/Blobremove bytes{idx}-{end} from{blob}remove({dict},{key})anyremove entry{key} from{dict}rename({from},{to})Numberrename (move) file from{from} to{to}repeat({expr},{count})List/Tuple/Blob/Stringrepeat{expr}{count} timesresolve({filename})Stringget filenamea shortcut points toreverse({obj})List/Tuple/Blob/Stringreverse{obj}round({expr})Floatround off{expr}rubyeval({expr})anyevaluateRubyexpressionscreenattr({row},{col})Numberattributeat screen positionscreenchar({row},{col})Numbercharacterat screen positionscreenchars({row},{col})ListList of charactersat screen positionscreencol()Numbercurrent cursor columnscreenpos({winid},{lnum},{col})Dictscreen row and col ofa text characterscreenrow()Numbercurrent cursor rowscreenstring({row},{col})Stringcharactersat screen positionsearch({pattern} [,{flags} [,{stopline} [,{timeout} [,{skip}]]]])Numbersearch for{pattern}searchcount([{options}])Dictget or update search statssearchdecl({name} [,{global} [,{thisblock}]])Numbersearch for variable declarationsearchpair({start},{middle},{end} [,{flags} [,{skip} [...]]])Numbersearch for otherend of start/end pairsearchpairpos({start},{middle},{end} [,{flags} [,{skip} [...]]])Listsearch for otherend of start/end pairsearchpos({pattern} [,{flags} [,{stopline} [,{timeout} [,{skip}]]]])Listsearch for{pattern}server2client({clientid},{string})Numbersend replystringserverlist()Stringgetalist of available serverssetbufline({buf},{lnum},{text})Numberset line{lnum} to{text} in buffer{buf}setbufvar({buf},{varname},{val})noneset{varname} in buffer{buf} to{val}setcellwidths({list})noneset character cell width overridessetcharpos({expr},{list})Numberset the{expr} position to{list}setcharsearch({dict})Dictset character search from{dict}setcmdline({str} [,{pos}])Numberset command-linesetcmdpos({pos})Numberset cursor position in command-linesetcursorcharpos({list})Numbermove cursor to position in{list}setenv({name},{val})noneset environment variablesetfperm({fname},{mode})Numberset{fname} file permissions to{mode}setline({lnum},{line})Numberset line{lnum} to{line}setloclist({nr},{list} [,{action}])Numbermodify locationlist using{list}setloclist({nr},{list},{action},{what})Numbermodify specific locationlist propssetmatches({list} [,{win}])Numberrestorealist of matchessetpos({expr},{list})Numberset the{expr} position to{list}setqflist({list} [,{action}])Numbermodifyquickfixlist using{list}setqflist({list},{action},{what})Numbermodify specificquickfixlist propssetreg({n},{v} [,{opt}])Numbersetregister to value and typesettabvar({nr},{varname},{val}) noneset{varname} intab page{nr} to{val}settabwinvar({tabnr},{winnr},{varname},{val})noneset{varname} inwindow{winnr} intabpage{tabnr} to{val}settagstack({nr},{dict} [,{action}])Numbermodifytag stack using{dict}setwinvar({nr},{varname},{val}) noneset{varname} inwindow{nr} to{val}sha256({string})StringSHA256 checksum of{string}shellescape({string} [,{special}])Stringescape{string} for useas shellcommand argumentshiftwidth([{col}])Numbereffective value of'shiftwidth'sign_define({name} [,{dict}])Numberdefine or updatea signsign_define({list})Listdefine or updatealist ofsignssign_getdefined([{name}])Listgetalist of definedsignssign_getplaced([{buf} [,{dict}]])Listgetalist of placedsignssign_jump({id},{group},{buf})Numberjump toa signsign_place({id},{group},{name},{buf} [,{dict}])Numberplacea signsign_placelist({list})Listplacealist ofsignssign_undefine([{name}])Numberundefinea signsign_undefine({list})Listundefinealist ofsignssign_unplace({group} [,{dict}])Numberunplacea signsign_unplacelist({list})Listunplacealist ofsignssimplify({filename})Stringsimplify filenameas muchas possiblesin({expr})Floatsine of{expr}sinh({expr})Floathyperbolic sine of{expr}slice({expr},{start} [,{end}]) String,List orBlobslice ofa String,List orBlobsort({list} [,{how} [,{dict}]])Listsort{list}, compare with{how}sound_clear()nonestop playing all soundssound_playevent({name} [,{callback}])Numberplay an event soundsound_playfile({path} [,{callback}])Numberplay sound file{path}sound_stop({id})nonestop playing sound{id}soundfold({word})Stringsound-fold{word}spellbadword()Stringbadly spelledwordat cursorspellsuggest({word} [,{max} [,{capital}]])Listspelling suggestionssplit({expr} [,{pat} [,{keepempty}]])ListmakeList from{pat} separated{expr}sqrt({expr})Floatsquare root of{expr}srand([{expr}])Listget seed forrand()state([{what}])Stringcurrent state of Vimstr2blob({list} [,{options}])Blobconvertlist of strings intoaBlobstr2float({expr} [,{quoted}])FloatconvertString toFloatstr2list({expr} [,{utf8}])Listconvert each character of{expr} toASCII/UTF-8 valuestr2nr({expr} [,{base} [,{quoted}]])NumberconvertString toNumberstrcharlen({expr})Numbercharacter length of theString{expr}strcharpart({str},{start} [,{len} [,{skipcc}]])String{len} characters of{str}atcharacter{start}strchars({expr} [,{skipcc}])Numbercharactercount of theString{expr}strdisplaywidth({expr} [,{col}])Number display length of theString{expr}strftime({format} [,{time}])Stringformat time witha specified formatstrgetchar({str},{index})Numberget char{index} from{str}stridx({haystack},{needle} [,{start}])Numberindex of{needle} in{haystack}string({expr})StringString representation of{expr} valuestrlen({expr})Numberlength of theString{expr}strpart({str},{start} [,{len} [,{chars}]])String{len} bytes/chars of{str}atbyte{start}strptime({format},{timestring})NumberConvert{timestring} tounixtimestampstrridx({haystack},{needle} [,{start}])Numberlastindex of{needle} in{haystack}strtrans({expr})Stringtranslatestring to makeit printablestrutf16len({string} [,{countcc}])Numbernumber of UTF-16 code units in{string}strwidth({expr})Numberdisplay cell length of theString{expr}submatch({nr} [,{list}])String orListspecific match in ":s" orsubstitute()substitute({expr},{pat},{sub},{flags})Stringall{pat} in{expr} replaced with{sub}swapfilelist()Listswap files found in'directory'swapinfo({fname})Dictinformation about swap file{fname}swapname({buf})Stringswap file of buffer{buf}synID({lnum},{col},{trans})Numbersyntax IDat{lnum} and{col}synIDattr({synID},{what} [,{mode}])Stringattribute{what} ofsyntax ID{synID}synIDtrans({synID})Numbertranslatedsyntax ID of{synID}synconcealed({lnum},{col})Listinfo about concealingsynstack({lnum},{col})Liststack ofsyntax IDsat{lnum} and{col}system({expr} [,{input}])Stringoutput of shell command/filter{expr}systemlist({expr} [,{input}])Listoutput of shell command/filter{expr}tabpagebuflist([{arg}])Listlist of buffer numbers intab pagetabpagenr([{arg}])Numbernumber of current or lasttab pagetabpagewinnr({tabarg} [,{arg}])Numbernumber of currentwindow intab pagetagfiles()Listtags files usedtaglist({expr} [,{filename}])Listlist oftags matching{expr}tan({expr})Floattangent of{expr}tanh({expr})Floathyperbolic tangent of{expr}tempname()Stringname fora temporary fileterm_dumpdiff({filename},{filename} [,{options}])Number display difference between two dumpsterm_dumpload({filename} [,{options}])Numberdisplayinga screen dumpterm_dumpwrite({buf},{filename} [,{options}])nonedumpterminalwindow contentsterm_getaltscreen({buf})Numberget the alternate screen flagterm_getansicolors({buf})Listget ANSI palette inGUI color modeterm_getattr({attr},{what})Numberget the value of attribute{what}term_getcursor({buf})Listget the cursor position ofaterminalterm_getjob({buf})Jobget thejob associated withaterminalterm_getline({buf},{row})Stringgeta line of text fromaterminalterm_getscrolled({buf})Numberget the scrollcount ofaterminalterm_getsize({buf})Listget the size ofaterminalterm_getstatus({buf})Stringget the status ofaterminalterm_gettitle({buf})Stringget the title ofaterminalterm_gettty({buf}, [{input}])Stringget the tty name ofaterminalterm_list()Listget thelist ofterminalbuffersterm_scrape({buf},{row})Listget row ofaterminal screenterm_sendkeys({buf},{keys})nonesend keystrokes toaterminalterm_setansicolors({buf},{colors})noneset ANSI palette inGUI color modeterm_setapi({buf},{expr})nonesetterminal-api function name prefixterm_setkill({buf},{how})noneset signal to stopjob interminalterm_setrestore({buf},{command}) noneset command to restoreterminalterm_setsize({buf},{rows},{cols})noneset the size ofaterminalterm_start({cmd} [,{options}])Numberopenaterminalwindow and runajobterm_wait({buf} [,{time}])Number wait for screen to be updatedterminalprops()Dictproperties of theterminaltest_alloc_fail({id},{countdown},{repeat})nonemake memory allocation failtest_autochdir()noneenable'autochdir' duringstartuptest_feedinput({string})noneadd key sequence to input buffertest_garbagecollect_now()nonefree memory right now fortestingtest_garbagecollect_soon()nonefree memory soon fortestingtest_getvalue({string})anyget value of an internal variabletest_gui_event({event},{args})boolgenerateaGUI event fortestingtest_ignore_error({expr})noneignorea specific errortest_mswin_event({event},{args})boolgenerateMS-Windows event fortestingtest_null_blob()Blobnull value fortestingtest_null_channel()Channelnull value fortestingtest_null_dict()Dictnull value fortestingtest_null_function()Funcrefnull value fortestingtest_null_job()Jobnull value fortestingtest_null_list()Listnull value fortestingtest_null_partial()Funcrefnull value fortestingtest_null_string()Stringnull value fortestingtest_null_tuple()Tuplenull value fortestingtest_option_not_set({name})nonereset flag indicating option was settest_override({expr},{val})nonetest with Vim internal overridestest_refcount({expr})Numberget thereferencecount of{expr}test_setmouse({row},{col})noneset the mouse position fortestingtest_settime({expr})noneset current time fortestingtest_srand_seed([{seed}])noneset seed fortestingsrand()test_unknown()anyunknown value fortestingtest_void()anyvoid value fortestingtimer_info([{id}])Listinformation abouttimerstimer_pause({id},{pause})nonepause or unpauseatimertimer_start({time},{callback} [,{options}])Numbercreateatimertimer_stop({timer})nonestopatimertimer_stopall()nonestop alltimerstolower({expr})StringtheString{expr} switched tolowercasetoupper({expr})StringtheString{expr} switched touppercasetr({src},{fromstr},{tostr})Stringtranslate chars of{src} in{fromstr}to chars in{tostr}trim({text} [,{mask} [,{dir}]])Stringtrim characters in{mask} from{text}trunc({expr})FloattruncateFloat{expr}tuple2list({tuple})Listturn{tuple} of items intoalisttype({expr})Numbertype of value{expr}typename({expr})Stringrepresentation of the type of{expr}undofile({name})Stringundo file name for{name}undotree([{buf}])Listundo file tree for buffer{buf}uniq({list} [,{func} [,{dict}]])Listremove adjacent duplicates fromalistutf16idx({string},{idx} [,{countcc} [,{charidx}]])NumberUTF-16index of byte{idx} in{string}values({dict})Listvalues in{dict}virtcol({expr} [,{list} [,{winid}])Number orListscreen column of cursor ormarkvirtcol2col({winid},{lnum},{col})Number byteindex ofa character on screenvisualmode([{expr}])Stringlast visual mode usedwildmenumode()Numberwhether'wildmenu' modeis activewin_execute({id},{command} [,{silent}])Stringexecute{command} inwindow{id}win_findbuf({bufnr})Listfindwindows containing{bufnr}win_getid([{win} [,{tab}]])Numbergetwindow ID for{win} in{tab}win_gettype([{nr}])Stringtype ofwindow{nr}win_gotoid({expr})Numbergo towindow with ID{expr}win_id2tabwin({expr})Listgettab andwindow nr fromwindow IDwin_id2win({expr})Numbergetwindow nr fromwindow IDwin_move_separator({nr})Numbermovewindow vertical separatorwin_move_statusline({nr})Numbermovewindow status linewin_screenpos({nr})Listget screen position ofwindow{nr}win_splitmove({nr},{target} [,{options}])Numbermovewindow{nr} to split of{target}winbufnr({nr})Numberbuffer number ofwindow{nr}wincol()Numberwindow column of the cursorwindowsversion()StringMS-Windows OS versionwinheight({nr})Numberheight ofwindow{nr}winlayout([{tabnr}])Listlayout ofwindows intab{tabnr}winline()Numberwindow line of the cursorwinnr([{expr}])Numbernumber of currentwindowwinrestcmd()Stringreturns command to restorewindow sizeswinrestview({dict})nonerestoreview of currentwindowwinsaveview()Dictsaveview of currentwindowwinwidth({nr})Numberwidth ofwindow{nr}wordcount()Dictget byte/char/word statisticswritefile({object},{fname} [,{flags}])NumberwriteBlob orList of lines to filexor({expr},{expr})Numberbitwise XOR==============================================================================2. Detailsbuiltin-function-detailsNot allfunctions are here, some have been moved toahelp file covering thespecific functionality.Return typespecifies the type forVim9-script, seevim9-typesabs({expr})abs()Return the absolute value of{expr}. When{expr} evaluates toaFloatabs() returnsaFloat. When{expr} can beconverted toaNumberabs() returnsaNumber. Otherwiseabs() gives an error message and returns -1.Examples:echo abs(1.456)1.456echo abs(-5.456)5.456echo abs(-4)4Can also be usedasamethod:Compute()->abs()Return type:Number orFloat depending on{expr}acos({expr})acos()Return the arc cosine of{expr} measured in radians,asaFloat in the range of [0, pi].{expr}must evaluate toaFloat oraNumber in the range[-1, 1]. Otherwiseacos() returns "nan".Examples::echo acos(0)1.570796:echo acos(-0.5)2.094395Can also be usedasamethod:Compute()->acos()Return type:Floatadd({object},{expr})add()Append the item{expr} toList orBlob{object}. Returnsthe resultingList orBlob. Examples::let alist = add([1, 2, 3], item):call add(mylist, "woodstock")Note that when{expr}isaListitis appendedasa singleitem. Useextend() to concatenateLists.When{object}isaBlob then{expr}must bea number.Useinsert() to add an itemat another position.Returns 1 if{object}is notaList oraBlob.Can also be usedasamethod:mylist->add(val1)->add(val2)Return type: list<{type}> (depending on the givenList) orBloband({expr},{expr})and()Bitwise AND on the two arguments. The arguments are convertedtoa number.A List,Dict orFloat argument causes an error.Also seeor() andxor().Example::let flag = and(bits, 0x80)Can also be usedasamethod::let flag = bits->and(0x80)Return type:Numberappend({lnum},{text})append()When{text}isaList: Append each item of theListasatext line below line{lnum} in the current buffer.Otherwise append{text}as one text line below line{lnum} inthe current buffer.Any type of itemis accepted and converted toa String.{lnum} can be zero toinserta 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 emptylist zerois returned,no matter the value of{lnum}.InVim9script an invalid argument or negative numberresults in an error. Example::let failed = append(line('$'), "# THE END"):let failed = append(0, ["Chapter 1", "the beginning"])Can also be usedasamethod aftera List, the baseispassedas the second argument:mylist->append(lnum)Return type:Numberappendbufline({buf},{lnum},{text})appendbufline()Likeappend() but append the text in buffer{buf}.This function works only for loaded buffers. First callbufload() if needed.For the use of{buf}, seebufname().{lnum}is the line number to append below.Note that usingline() would use the current buffer, not the one appendingto. Use "$" to appendat theend of the buffer. Otherstringvalues are not supported.On success0is returned, on failure 1is returned.InVim9script an erroris given for an invalid{lnum}.If{buf}is nota valid buffer or{lnum}is not valid, anerror messageis given. Example::let failed = appendbufline(13, 0, "# THE START")However, when{text}is an emptylist then no erroris givenfor an invalid{lnum}, since{lnum} isn't actually used.Can also be usedasamethod aftera List, the baseispassedas the second argument:mylist->appendbufline(buf, lnum)Return type:Numberargc([{winid}])argc()The resultis the number of files in the argument list. Seearglist.If{winid}is not supplied, the argumentlist of the currentwindowis used.If{winid}is -1, the global argumentlistis used.Otherwise{winid}specifies thewindow of which the argumentlistis used: either thewindow number or thewindow ID.Returns -1 if the{winid} argumentis invalid.Return type:Numberargidx()argidx()The resultis the currentindex in the argument list.0isthe first file.argc()- 1is the last one. Seearglist.Return type:Numberarglistid()arglistid([{winnr} [,{tabnr}]])Return the argumentlist ID. Thisisa number whichidentifies the argumentlist being used. Zerois used for theglobal argument list. Seearglist.Returns -1 if the arguments are invalid.Without arguments use the current window.With{winnr} only use thiswindow in the currenttab page.With{winnr} and{tabnr} use thewindow in the specifiedtabpage.{winnr} can be thewindow number or thewindow-ID.Return type:Numberargv()argv([{nr} [,{winid}]])The resultis the{nr}th file in the argument list. Seearglist. "argv(0)"is the first one. Example::let i = 0:while i < argc(): let f = escape(fnameescape(argv(i)), '.'): exe 'amenu Arg.' .. f .. ' :e ' .. f .. '<CR>': let i = i + 1:endwhileWithout the{nr} argument, or when{nr}is -1,aList withthe wholearglistis returned.The{winid} argumentspecifies thewindow ID, seeargc().For the Vim command line arguments seev:argv.Returns an emptystring if{nr}th argumentis not present inthe argument list. Returns an emptyList if the{winid}argumentis invalid.Return type:Stringasin({expr})asin()Return the arc sine of{expr} measured in radians,asaFloatin the range of [-pi/2, pi/2].{expr}must evaluate toaFloat oraNumber in the range[-1, 1].Returns "nan" if{expr}is outside the range [-1, 1]. Returns0.0 if{expr}is notaFloat oraNumber.Examples::echo asin(0.8)0.927295:echo asin(-0.5)-0.523599Can also be usedasamethod:Compute()->asin()Return type:Floatassert_functions are documented here:assert-functions-detailsatan({expr})atan()Return the principal value of the arc tangent of{expr}, inthe range [-pi/2, +pi/2] radians,asaFloat.{expr}must evaluate toaFloat oraNumber.Returns 0.0 if{expr}is notaFloat oraNumber.Examples::echo atan(100)1.560797:echo atan(-4.01)-1.326405Can also be usedasamethod:Compute()->atan()Return type:Floatatan2({expr1},{expr2})atan2()Return the arc tangent of{expr1}/{expr2}, measured inradians,asaFloat in the range [-pi, pi].{expr1} and{expr2}must evaluate toaFloat oraNumber.Returns 0.0 if{expr1} or{expr2}is notaFloat oraNumber.Examples::echo atan2(-1, 1)-0.785398:echo atan2(1, -1)2.356194Can also be usedasamethod:Compute()->atan2(1)Return type:Floatautocmd_add({acmds})autocmd_add()AddsaList of autocmds and autocmd groups.The{acmds} argumentisaList where each itemisaDict withthe following optional items: bufnrbuffer number to adda buffer-local autocmd.If this itemis specified, then the "pattern"itemis ignored. cmdEx command to execute for this autocmd event eventautocmd event name. Refer toautocmd-events.This can be eitheraString witha singleevent name oraList of event names. groupautocmd group name. Refer toautocmd-groups.If this group doesn't exist thenitiscreated. If not specified or empty, then thedefault groupis used. nestedboolean flag, set tov:true to adda nestedautocmd. Refer toautocmd-nested. onceboolean flag, set tov:true to add an autocmdwhich executes only once. Refer toautocmd-once.patternautocmdpattern string. Refer toautocmd-patterns. If "bufnr" itemispresent, then this itemis ignored. This canbeaString witha singlepattern oraList ofpatterns. replaceboolean flag, set tov:true to remove all thecommands associated with the specified autocmdevent and group and add the{cmd}. Thisisuseful to avoid adding the same commandmultiple times for an autocmd event ina group.Returnsv:true on success andv:false on failure.Examples:" Create a buffer-local autocmd for buffer 5let acmd = {}let acmd.group = 'MyGroup'let acmd.event = 'BufEnter'let acmd.bufnr = 5let acmd.cmd = 'call BufEnterFunc()'call autocmd_add([acmd])Can also be usedasamethod:GetAutocmdList()->autocmd_add()Return type:vim9-booleanautocmd_delete({acmds})autocmd_delete()DeletesaList of autocmds and autocmd groups.The{acmds} argumentisaList where each itemisaDict withthe following optional items: bufnrbuffer number to deletea buffer-local autocmd.If this itemis specified, then the "pattern"itemis ignored. cmdEx command for this autocmd event eventautocmd event name. Refer toautocmd-events.If'*' then all the autocmd events in thisgroup are deleted. groupautocmd group name. Refer toautocmd-groups.If not specified or empty, then the defaultgroupis used. nestedset tov:true fora nested autocmd.Refer toautocmd-nested. onceset tov:true for an autocmd which executesonly once. Refer toautocmd-once.patternautocmdpattern string. Refer toautocmd-patterns. If "bufnr" itemispresent, then this itemis ignored.If only{group}is specified ina{acmds} entry and{event},{pattern} and{cmd} are not specified, then that autocmd groupis deleted.Returnsv:true on success andv:false on failure.Examples:" :autocmd! BufLeave *.vimlet acmd = #{event: 'BufLeave', pattern: '*.vim'}call autocmd_delete([acmd]})" :autocmd! MyGroup1 BufLeavelet acmd = #{group: 'MyGroup1', event: 'BufLeave'}call autocmd_delete([acmd])" :autocmd! MyGroup2 BufEnter *.clet acmd = #{group: 'MyGroup2', event: 'BufEnter',\ pattern: '*.c'}" :autocmd! MyGroup2 * *.clet acmd = #{group: 'MyGroup2', event: '*',\ pattern: '*.c'}call autocmd_delete([acmd])" :autocmd! MyGroup3let acmd = #{group: 'MyGroup3'}call autocmd_delete([acmd])Can also be usedasamethod:GetAutocmdList()->autocmd_delete()Return type:vim9-booleanautocmd_get([{opts}])autocmd_get()ReturnsaList of autocmds. If{opts}is not supplied, thenreturns the autocmds for all the events in all the groups.The optional{opts}Dict argument supports the followingitems: groupAutocmd group name. If specified, returns onlythe autocmds defined in this group. If thespecified group doesn't exist, results in anerror message. If set to an empty string,then the default autocmd groupis used. eventAutocmd event name. If specified, returns onlythe autocmds defined for this event. If setto "*", then returns autocmds for all theevents. If the specified event doesn't exist,results in an error message.patternAutocmd pattern. If specified, returns onlythe autocmds defined for this pattern.A combination of the above three times can be supplied in{opts}.EachDict in the returnedList contains the following items: bufnrFor buffer-local autocmds, buffer number wherethe autocmdis defined. cmdCommand executed for this autocmd. eventAutocmd event name. groupAutocmd group name. nestedBoolean flag, set tov:true fora nestedautocmd. Seeautocmd-nested. onceBoolean flag, set to v:true, if the autocmdwill be executed only once. Seeautocmd-once.patternAutocmd pattern. Fora buffer-localautocmd, this will be of the form "<buffer=n>".If there are multiple commands for an autocmd event inagroup, then separate items are returned for each command.Returns an emptyList if an autocmd with the specified groupor event orpatternis not found.Examples:" :autocmd MyGroupecho autocmd_get(#{group: 'Mygroup'})" :autocmd G BufUnloadecho autocmd_get(#{group: 'G', event: 'BufUnload'})" :autocmd G * *.tslet acmd = #{group: 'G', event: '*', pattern: '*.ts'}echo autocmd_get(acmd)" :autocmd Syntaxecho autocmd_get(#{event: 'Syntax'})" :autocmd G BufEnter *.tslet acmd = #{group: 'G', event: 'BufEnter',\ pattern: '*.ts'}echo autocmd_get(acmd)Can also be usedasamethod:Getopts()->autocmd_get()Return type: list<dict<any>>balloon_gettext()balloon_gettext()Return the current text in the balloon. Only for the string,not used for the List. Returns an emptystring if balloonis not present.Return type:Stringballoon_show({expr})balloon_show()Show{expr} inside the balloon. For theGUI{expr}is usedasa string. Foraterminal{expr} can bea list, which containsthe lines of the balloon. If{expr}is notalistit will besplit withballoon_split().If{expr}is an emptystring any existing balloonis removed.Example:func GetBalloonContent() " ... initiate getting the content return ''endfuncset balloonexpr=GetBalloonContent()func BalloonCallback(result) call balloon_show(a:result)endfuncCan also be usedasamethod:GetText()->balloon_show()The intended useis that fetching the content of the balloonis initiated from'balloonexpr'. It will invoke anasynchronous method, in whicha callback invokesballoon_show(). The'balloonexpr' itself can return anemptystring ora placeholder, e.g. "loading...".When showinga balloonis not possible then nothing happens,no error messageis given.{only available when compiled with the+balloon_eval or+balloon_eval_term feature}Return type:Numberballoon_split({msg})balloon_split()SplitString{msg} into lines to be displayed ina balloon.The splits are made for the currentwindow size and optimizeto show debugger output.ReturnsaList with the split lines. Returns an emptyListon error.Can also be usedasamethod:GetText()->balloon_split()->balloon_show(){only available when compiled with the+balloon_eval_termfeature}Return type: list<any> or list<string>base64_decode({string})base64_decode()ReturnaBlob containing the bytes decoded from the base64encoded characters in{string}.The{string} argument should contain only base64-encodedcharacters and should havea length thatisa multiple of 4.Returns an emptyblob on error.Examples: " Write the decoded contents to a binary file call writefile(base64_decode(s), 'tools.bmp') " Decode a base64-encoded string echo blob2str(base64_decode(encodedstr))Can also be usedasamethod:GetEncodedString()->base64_decode()Return type:Blobbase64_encode({blob})base64_encode()Returna base64-encodedString representing the bytes in{blob}. The base64 alphabet defined in RFC 4648is used.Examples: " Encode the contents of a binary file echo base64_encode(readblob('somefile.bin')) " Encode a string echo base64_encode(str2blob([somestr]))Can also be usedasamethod:GetBinaryData()->base64_encode()Return type:Stringbindtextdomain({package},{path})bindtextdomain()Binda specific{package} toa{path} so that thegettext() function can be used to get language-specifictranslations fora package.{path}is the directory namefor the translations. Seepackage-translation.Returnsv:true on success andv:false on failure (out ofmemory).Return type:vim9-booleanblob2list({blob})blob2list()ReturnaList containing the number value of each byte inBlob{blob}. Examples:blob2list(0z0102.0304)returns [1, 2, 3, 4]blob2list(0z)returns []Returns an emptyList on error.list2blob() does theopposite.Can also be usedasamethod:GetBlob()->blob2list()Return type: list<any> or list<number>blob2str({blob} [,{options}])blob2str()ReturnaList of Strings in the current'encoding' byconverting the bytes in{blob} into characters.Each<NL> byte in theblobis interpretedas theend ofastring anda newlist itemis added. Each<NUL> byte in theblobis converted intoa<NL> character.If{options}is not supplied, the current'encoding' valueisused to decode the bytes in{blob}.The argument{options}isaDict and supports the followingitems: encodingDecode the bytes in{blob} using thisencoding. The valueisaString. Seeencoding-names for the supported values(plus the special value "none").E1515E1516When current'encoding'is "utf-8", an erroris given and anemptyListis returned if an invalid byte sequenceisencountered in{blob}. To suppress this validation and getpotentially invalid string, set "encoding" in{options} to"none".Returns an emptyList ifblobis empty.See alsostr2blob()Examples: blob2str(0z6162)returns ['ab'] blob2str(0zC2ABC2BB)returns ['«»'] blob2str(0z610A62)returns ['a', 'b'] blob2str(0z610062)returns ['a\nb'] blob2str(0zABBB, {'encoding': 'latin1'}) returns ['«»']Can also be usedasamethod:GetBlob()->blob2str()Return type: list<string>browse()browse({save},{title},{initdir},{default})Put upa file requester. This only works when "has("browse")"returnsTRUE (only in someGUI versions).The input fields are:{save}whenTRUE, select file to write{title}title for the requester{initdir}directory to start browsing in{default}default file nameAn emptystringis returned when the "Cancel" buttonis hit,something went wrong, or browsingis not possible.Return type:Stringbrowsedir({title},{initdir})browsedir()Put upa directory requester. This only works when"has("browse")" returnsTRUE (only in someGUI versions).On systems wherea directory browseris not supporteda filebrowseris used. In that case: selecta file in the directoryto be used.The input fields are:{title}title for the requester{initdir}directory to start browsing inWhen the "Cancel" buttonis hit, something went wrong, orbrowsingis not possible, an emptystringis returned.Return type:Stringbufadd({name})bufadd()Adda buffer to the bufferlist with name{name} (must beaString).Ifa buffer for file{name} already exists, return that buffernumber. Otherwise return the buffer number of the newlycreated buffer. When{name}is an emptystring thena newbufferis 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'])Returns0 on error.Can also be usedasamethod:let bufnr = 'somename'->bufadd()Return type:Numberbufexists({buf})bufexists()The resultisa Number, whichisTRUE ifa buffer called{buf} exists.If the{buf} argumentisa number, buffer numbers are used.Number zerois the alternate buffer for the current window.If the{buf} argumentisastringitmust matcha buffer nameexactly. The name can be:- Relative to the current directory.-A full path.- The name ofa buffer with'buftype' set to "nofile".-A URL name.Unlistedbuffers will be found.Note thathelp files are listed by their short name in theoutput of:buffers, butbufexists() requires using theirlong name to be able to find them.bufexists() may reporta buffer exists, but to use the namewitha:buffer command you may need to useexpand(). EspforMS-Windows 8.3 names in the form "c:\DOCUME~1"Use "bufexists(0)" to test for the existence of an alternatefile name.Can also be usedasamethod:let exists = 'somename'->bufexists()Return type:NumberObsolete name: buffer_exists().buffer_exists()buflisted({buf})buflisted()The resultisa Number, whichisTRUE ifa buffer called{buf} exists andis listed (has the'buflisted' option set).The{buf} argumentis used like withbufexists().Can also be usedasamethod:let listed = 'somename'->buflisted()Return type:Numberbufload({buf})bufload()Ensure the buffer{buf}is loaded. When the buffer namerefers to an existing file then the fileis read. Otherwisethe buffer will be empty. If the buffer was already loadedthen thereis no change. If the bufferis not related toafile then no fileis read (e.g., when'buftype'is "nofile").If thereis an existing swap file for the file of the buffer,there will be no dialog, the buffer will be loaded anyway.The{buf} argumentis used like withbufexists().Can also be usedasamethod:eval 'somename'->bufload()Return type:Numberbufloaded({buf})bufloaded()The resultisa Number, whichisTRUE ifa buffer called{buf} exists andis loaded (shown inawindow or hidden).The{buf} argumentis used like withbufexists().Can also be usedasamethod:let loaded = 'somename'->bufloaded()Return type:Numberbufname([{buf}])bufname()The resultis the name ofa buffer. Mostlyasitis displayedby the:ls command, but not using special names suchas"[No Name]".If{buf}is omitted the current bufferis used.If{buf}isa Number, that buffer number's nameis given.Number zerois the alternate buffer for the current window.If{buf}isa String,itis usedasafile-pattern to matchwith the buffer names. Thisis always done like'magic'isset and'cpoptions'is empty. When thereis more than onematch an emptystringis returned."" or "%" can be used for the current buffer, "#" for thealternate buffer.A full matchis preferred, otherwisea matchat the start,endor middle of the buffer nameis accepted. If you only wantafull match thenput "^"at the start and "$"at theend of thepattern.Listedbuffers are found first. If thereisa single matchwitha listed buffer, that oneis returned. Next unlistedbuffers are searched for.If the{buf}isa String, but you want to useitasa buffernumber, forceit to beaNumber by adding zero to it::echo bufname("3" + 0)Can also be usedasamethod:echo bufnr->bufname()If the buffer doesn't exist, or doesn't havea name, an emptystringis returned.bufname("#")alternate buffer namebufname(3)name of buffer 3bufname("%")name of current bufferbufname("file2")name of buffer where "file2" matches.Return type:Stringbuffer_name()Obsolete name: buffer_name().bufnr([{buf} [,{create}]])bufnr()The resultis the number ofa buffer,asitis displayed bythe:ls command. For the use of{buf}, seebufname()above.If the buffer doesn't exist, -1is returned. Or, if the{create} argumentis present and TRUE,a new, unlisted,bufferis created and its numberis returned. Example:let newbuf = bufnr('Scratch001', 1)Using an empty name uses the current buffer. To createa newbuffer with an empty name usebufadd().bufnr("$")is the last buffer::let last_buffer = bufnr("$")The resultisa Number, whichis the highest buffer numberof existing buffers.Note that not allbuffers witha smallernumber necessarily exist, because ":bwipeout" may have removedthem. Usebufexists() to test for the existence ofa buffer.Can also be usedasamethod:echo bufref->bufnr()Return type:NumberObsolete name: buffer_number().buffer_number()last_buffer_nr()Obsolete name for bufnr("$"): last_buffer_nr().bufwinid({buf})bufwinid()The resultisa Number, whichis thewindow-ID of the firstwindow associated with buffer{buf}. For the use of{buf},seebufname() above. If buffer{buf} doesn't exist orthereis no such window, -1is returned. Example:echo "A window containing buffer 1 is " .. (bufwinid(1))Only deals with the currenttab page. Seewin_findbuf() forfinding more.Can also be usedasamethod:FindBuffer()->bufwinid()Return type:Numberbufwinnr({buf})bufwinnr()Likebufwinid() but return thewindow number instead of thewindow-ID.If buffer{buf} doesn't exist or thereis no such window, -1is returned. Example:echo "A window containing buffer 1 is " .. (bufwinnr(1))The number can be used withCTRL-W_w and ":wincmdw":wincmd.Can also be usedasamethod:FindBuffer()->bufwinnr()Return type:Numberbyte2line({byte})byte2line()Return the line number that contains the characterat bytecount{byte} in the current buffer. This includes theend-of-line character, depending on the'fileformat' optionfor the current buffer. The first character has bytecountone.Also seeline2byte(),go and:goto.Returns -1 if the{byte} valueis invalid.Can also be usedasamethod:GetOffset()->byte2line()Return type:Number{not available when compiled without the+byte_offsetfeature}byteidx({expr},{nr} [,{utf16}])byteidx()Return byteindex of the{nr}'th character in theString{expr}. Use zero for the first character,it then returnszero.If there are nomultibyte characters the returned valueisequal to{nr}.Composing characters are not counted separately, their bytelengthis added to the preceding base character. Seebyteidxcomp() below for counting composing charactersseparately.When{utf16}is present and TRUE,{nr}is usedas the UTF-16index in theString{expr} instead ofas the character index.The UTF-16indexis theindex in thestring whenitis encodedwith 16-bit words. If the specified UTF-16indexis in themiddle ofa character (e.g. ina 4-byte character), then thebyteindex of the first byte in the characteris returned.Refer tostring-offset-encoding for more information.Example:echo matchstr(str, ".", byteidx(str, 3))will display the fourth character. Another way todo thesame:let s = strpart(str, byteidx(str, 3))echo strpart(s, 0, byteidx(s, 1))Also seestrgetchar() andstrcharpart().If there areless than{nr} characters -1is returned.If there are exactly{nr} characters the length of thestringin bytesis returned.Seecharidx() andutf16idx() for getting the character andUTF-16index respectively from the byte index.Examples:echo byteidx('a😊😊', 2)returns 5echo byteidx('a😊😊', 2, 1)returns 1echo byteidx('a😊😊', 3, 1)returns 5Can also be usedasamethod:GetName()->byteidx(idx)Return type:Numberbyteidxcomp({expr},{nr} [,{utf16}])byteidxcomp()Like byteidx(), except thata composing characteris countedasa separate character. Example:let s = 'e' .. nr2char(0x301)echo byteidx(s, 1)echo byteidxcomp(s, 1)echo byteidxcomp(s, 2)The first and third echo result in 3 ('e' plus composingcharacteris 3 bytes), the second echo results in 1 ('e'isone byte).Only works differently frombyteidx() when'encoding'is settoaUnicode encoding.Can also be usedasamethod:GetName()->byteidxcomp(idx)Return type:Numbercall({func},{arglist} [,{dict}])call()E699Call function{func} with the items inList{arglist}asarguments.{func} can either beaFuncref or the name ofa function.a:firstline anda:lastline are set to the cursor line.Returns the return value of the called function.{dict}is forfunctions with the "dict" attribute. It will beused to set the local variable "self".Dictionary-functionCan also be usedasamethod:GetFunc()->call([arg, arg], dict)Return type: any, depending on{func}ceil({expr})ceil()Return the smallest integral value greater than or equal to{expr}asaFloat (round up).{expr}must evaluate toaFloat oraNumber.Examples:echo ceil(1.456)2.0echo ceil(-5.456)-5.0echo ceil(4.0)4.0Returns 0.0 if{expr}is notaFloat oraNumber.Can also be usedasamethod:Compute()->ceil()Return type:Floatch_functions are documented here:channel-functions-detailschangenr()changenr()Return the number of the most recent change. Thisis the samenumberas whatis displayed with:undolist and can be usedwith the:undo command.Whena change was madeitis the number of that change. Afterredoitis the number of the redone change. Afterundoitisoneless than the number of the undone change.Returns0 if theundolistis empty.Return type:Numberchar2nr({string} [,{utf8}])char2nr()ReturnNumber value of the first char in{string}.Examples:char2nr(" ")returns 32char2nr("ABC")returns 65When{utf8}is omitted or zero, the current'encoding'is used.Example for "utf-8":char2nr("á")returns 225char2nr("á"[0])returns 195When{utf8}is TRUE, always treatasUTF-8 characters.A combining characterisa separate character.nr2char() does the opposite.To turnastring intoalist of character numbers: let str = "ABC" let list = map(split(str, '\zs'), {_, val -> char2nr(val)})Result: [65, 66, 67]Returns0 if{string}is notaString.Can also be usedasamethod:GetChar()->char2nr()Return type:Numbercharclass({string})charclass()Return the characterclass of the first character in{string}.The characterclassis one of:0blank1punctuation2word character (depends on'iskeyword')3emojiotherspecificUnicodeclassTheclassis used in patterns andword motions.Returns0 if{string}is notaString.Return type:Numbercharcol({expr} [,{winid}])charcol()Sameascol() but returns the characterindex of the columnposition given with{expr} instead of the byte position.Example:With the cursor on'세' in line 5 with text "여보세요":charcol('.')returns 3col('.')returns 7Can also be usedasamethod:GetPos()->col()Return type:Numbercharidx()charidx({string},{idx} [,{countcc} [,{utf16}]])Return the characterindex of the byteat{idx} in{string}.Theindex of the first characteris zero.If there are nomultibyte characters the returned valueisequal to{idx}.When{countcc}is omitted orFALSE, then composing charactersare not counted separately, their byte lengthis added to thepreceding base character.When{countcc}isTRUE, then composing characters arecountedas separate characters.When{utf16}is present and TRUE,{idx}is usedas the UTF-16index in theString{expr} instead ofas the byte index.Returns -1 if the arguments are invalid or if there arelessthan{idx} bytes. If there are exactly{idx} bytes the lengthof thestring in charactersis returned.An erroris given and -1is returned if the first argumentisnota string, the second argumentis nota number or when thethird argumentis present andis not zero or one.Seebyteidx() andbyteidxcomp() for getting the byteindexfrom the characterindex andutf16idx() for getting theUTF-16index from the character index.Refer tostring-offset-encoding for more information.Examples:echo charidx('áb́ć', 3)returns 1echo charidx('áb́ć', 6, 1)returns 4echo charidx('áb́ć', 16)returns -1echo charidx('a😊😊', 4, 0, 1)returns 2Can also be usedasamethod:GetName()->charidx(idx)Return type:Numberchdir({dir})chdir()Change the current working directory to{dir}. The scope ofthe directory change depends on the directory of the currentwindow:- If the currentwindow hasa window-local directory(:lcd), then changes thewindow local directory.- Otherwise, if the currenttabpage hasa local directory(:tcd) then changes thetabpage local directory.- Otherwise, changes the global directory.{dir}must bea String.If successful, returns the previous working directory. Passthis to anotherchdir() to restore the directory.On failure, returns an empty string.Example:let save_dir = chdir(newdir)if save_dir != "" " ... do some work call chdir(save_dir)endifCan also be usedasamethod:GetDir()->chdir()Return type:Stringcindent({lnum})cindent()Get the amount of indent for line{lnum} according theCindenting rules,as with'cindent'.The indentis counted in spaces, the value of'tabstop'isrelevant.{lnum}is used just like ingetline().When{lnum}is invalid -1is returned.SeeC-indenting.Can also be usedasamethod:GetLnum()->cindent()Return type:Numberclearmatches([{win}])clearmatches()Clears all matches previously defined for the currentwindowbymatchadd() and the:match commands.If{win}is specified, use thewindow with this number orwindow ID instead of the current window.Can also be usedasamethod:GetWin()->clearmatches()Return type:Numbercmdcomplete_info()cmdcomplete_info()ReturnsaDictionary with information about cmdlinecompletion. Seecmdline-completion.The items are: cmdline_origThe original command-linestring beforecompletion began. pum_visibleTRUE ifpopup menuis visible.Seepumvisible(). matchesList of all completion candidates. Each itemisa string. selectedSelected item index. Firstindexis zero.Indexis -1 if no itemis selected (showingtyped text only, or the last completion afterno itemis selected when using the<Up> or<Down> keys)Returns an emptyDictionary if no completion was attempted,if there was only one candidate andit was fully completed, orif an error occurred.Return type: dict<any>col({expr} [,{winid}])col()The resultisa Number, whichis the byteindex of the columnposition given with{expr}.For accepted positions seegetpos().When{expr}is "$",it means theend of the cursor line, sothe resultis 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 columnis "$", to getthe last column ofa specific line. When "lnum" or "col"isout of range thencol() returns zero.With the optional{winid} argument the values are obtained forthatwindow instead of the current window.To get the line number useline(). To get both usegetpos().For the screen column position usevirtcol(). For thecharacter position usecharcol().Note that only marks in the current file can be used.Examples:col(".")column of cursorcol("$")length of cursor line plus onecol("'t")column of mark tcol("'" .. markname)column of mark marknameThe first columnis 1. Returns0 if{expr}is invalid or whenthewindow with ID{winid}is not found.For anuppercasemark the column may actually be in anotherbuffer.For the cursor position, when'virtualedit'is active, thecolumnis one higher if the cursoris after theend of theline. Also, when usinga<Cmd>mapping the cursor isn'tmoved, this can be used to obtain the column inInsert mode::imap <F2> <Cmd>echowin col(".")<CR>Can also be usedasamethod:GetPos()->col()Return type:Numbercomplete({startcol},{matches})complete()E785Set the matches forInsert mode completion.Can only be used inInsert mode. You need to useamappingwithCTRL-R= (seei_CTRL-R). It does not work afterCTRL-Oor with anexpression mapping.{startcol}is the byte offset in the line where the completedtext start. The text up to the cursoris the original textthat will be replaced by the matches. Use col('.') for anempty string. "col('.')- 1" will replace one character byamatch.{matches}must beaList. EachList itemis 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-Pas usual withInsert mode completion. Thepopup 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 ''endfuncThis isn't very useful, butit shows howit works.Note thatan emptystringis returned to avoida zero being inserted.Can also be usedasamethod, the baseis passedas thesecond argument:GetMatches()->complete(col('.'))Return type:Numbercomplete_add({expr})complete_add()Add{expr} to thelist of matches. Only to be used by thefunction specified with the'completefunc' option.Returns0 for failure (emptystring 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}. Itisthe sameas one item in thelist that'omnifunc' would return.Can also be usedasamethod:GetMoreMatches()->complete_add()Return type:Numbercomplete_check()complete_check()Check fora key typed while looking for completion matches.Thisis to be used when looking for matches takes some time.ReturnsTRUE when searching for matchesis to be aborted,zero otherwise.Only to be used by the function specified with the'completefunc' option.Return type:Numbercomplete_info([{what}])complete_info()ReturnsaDictionary with information aboutInsert modecompletion. Seeins-completion.The items are: modeCurrent completion mode name string.Seecomplete_info_mode for the values. pum_visibleTRUE ifpopup menuis visible.Seepumvisible(). itemsList of all completion candidates. Each itemisa dictionary containing the entries "word","abbr", "menu", "kind", "info" and "user_data".Seecomplete-items. matchesSameas "items", but only returns items thatare matching current query. If both "matches"and "items" are in "what", the returnedlistwill still be named "items", but each itemwill have an additional "match" field. selectedSelected item index. Firstindexis zero.Indexis -1 if no itemis selected (showingtyped text only, or the last completion afterno itemis selected when using the<Up> or<Down> keys) completedReturna dictionary containing the entries ofthe currently selectedindex item.complete_info_modemode values are: "" Not in completion mode "keyword" Keyword completioni_CTRL-X_CTRL-N "ctrl_x" Just pressedCTRL-Xi_CTRL-X "scroll" Scrolling withi_CTRL-X_CTRL-E ori_CTRL-X_CTRL-Y "whole_line" Whole linesi_CTRL-X_CTRL-L "files" File namesi_CTRL-X_CTRL-F "tags" Tagsi_CTRL-X_CTRL-] "path_defines" Definition completioni_CTRL-X_CTRL-D "path_patterns" Include completioni_CTRL-X_CTRL-I "dictionary"Dictionaryi_CTRL-X_CTRL-K "thesaurus" Thesaurusi_CTRL-X_CTRL-T "cmdline" Vim Command linei_CTRL-X_CTRL-V "function"User defined completioni_CTRL-X_CTRL-U "omni" Omni completioni_CTRL-X_CTRL-O "spell" Spelling suggestionsi_CTRL-X_s "eval"complete() completion "register" Words fromregistersi_CTRL-X_CTRL-R "unknown" Other internal modesIf the optional{what}list argumentis supplied, then onlythe items listed in{what} are returned. Unsupported items in{what} are silently ignored.To get the position and size of thepopup menu, seepum_getpos(). It's also available inv:event during theCompleteChanged event.Returns an emptyDictionary on error.Examples:" Get all itemscall complete_info()" Get only 'mode'call complete_info(['mode'])" Get only 'mode' and 'pum_visible'call complete_info(['mode', 'pum_visible'])Can also be usedasamethod:GetItems()->complete_info()Return type: dict<any>complete_match([{lnum},{col}])complete_match()Searches backward from the given position and returnsaListof matches according to the'isexpand' option. When noarguments are provided, uses the current cursor position.Each matchis representedasaList containing[startcol, trigger_text] where:- startcol: column position where completion should start, or -1 if no trigger positionis found. For multi-character triggers, returns the column of the first character.- trigger_text: the matching triggerstring from'isexpand', or emptystring if no match was found or when using the default'iskeyword' pattern.When'isexpand'is empty, uses the'iskeyword'pattern "\k\+$"to find the start of the current keyword.Examples:set isexpand=.,->,/,/*,abcfunc CustomComplete() let res = complete_match() if res->len() == 0 | return | endif let [col, trigger] = res[0] let items = [] if trigger == '/*' let items = ['/** */'] elseif trigger == '/' let items = ['/*! */', '// TODO:', '// fixme:'] elseif trigger == '.' let items = ['length()'] elseif trigger =~ '^\->' let items = ['map()', 'reduce()'] elseif trigger =~ '^\abc' let items = ['def', 'ghk'] endif if items->len() > 0 let startcol = trigger =~ '^/' ? col : col + len(trigger) call complete(startcol, items) endifendfuncinoremap <Tab> <Cmd>call CustomComplete()<CR>Return type: list<list<any>>confirm()confirm({msg} [,{choices} [,{default} [,{type}]]])confirm() offers the usera dialog, from whicha choice can bemade. It returns the number of the choice. For the firstchoice thisis 1.Note:confirm()is only supported when compiled withdialogsupport, see+dialog_con+dialog_con_gui and+dialog_gui.{msg}is displayed inadialog with{choices}as thealternatives. When{choices}is missing or empty, "&OK"isused (and translated).{msg}isa String, use '\n' to includea newline. Only onsome systems thestringis wrapped whenit doesn't fit.{choices}isa String, with the individual choices separatedby '\n', e.g.confirm("Save changes?", "&Yes\n&No\n&Cancel")Theletter after the '&'is the shortcut key for that choice.Thus you can type 'c' to select "Cancel". The shortcut doesnot need to be the first letter:confirm("file has been modified", "&Save\nSave &All")For the console, the firstletter of each choiceis usedasthe default shortcut key. Caseis ignored.The optional{default} argumentis the number of the choicethatis made if the user hits<CR>. Use 1 to make the firstchoice the default one. Use0 to not seta default. If{default}is omitted, 1is used.The optional{type}String argument gives the type of dialog.Thisis only used for the icon of the GTK, Mac,Motif andWin32 GUI. It can be one of these values: "Error","Question", "Info", "Warning" or "Generic". Only the firstcharacteris relevant. When{type}is omitted, "Generic"isused.If the user aborts thedialog by pressing<Esc>,CTRL-C,or another valid interrupt key,confirm() returns 0.An example: let choice = confirm("What do you want?",\ "&Apples\n&Oranges\n&Bananas", 2) if choice == 0echo "make up your mind!" elseif choice == 3echo "tasteful" elseecho "I prefer bananas myself." endifInaGUI dialog, buttons are used. The layout of the buttonsdepends on the 'v' flag in'guioptions'. Ifitis included,the buttons are alwaysput vertically. Otherwise,confirm()tries toput the buttons in one horizontal line. If theydon't fit,a vertical layoutis used anyway. For some systemsthe horizontal layoutis always used.Can also be usedasamethodin:BuildMessage()->confirm("&Yes\n&No")Return type:Numbercopy({expr})copy()Makea copy of{expr}. For Numbers and Strings this isn'tdifferent from using{expr} directly.When{expr}isaLista shallow copyis created. This meansthat the originalList can be changed withoutchanging thecopy, and vice versa. But the items are identical, thuschanging an item changes the contents of bothLists.ATuple orDictionaryis copied ina similar wayasaList.Also seedeepcopy().Can also be usedasamethod:mylist->copy()Return type: any, depending on{expr}cos({expr})cos()Return the cosine of{expr}, measured in radians,asaFloat.{expr}must evaluate toaFloat oraNumber.Returns 0.0 if{expr}is notaFloat oraNumber.Examples::echo cos(100)0.862319:echo cos(-4.01)-0.646043Can also be usedasamethod:Compute()->cos()Return type:Floatcosh({expr})cosh()Return the hyperbolic cosine of{expr}asaFloat in the range[1, inf].{expr}must evaluate toaFloat oraNumber.Returns 0.0 if{expr}is notaFloat oraNumber.Examples::echo cosh(0.5)1.127626:echo cosh(-0.5)-1.127626Can also be usedasamethod:Compute()->cosh()Return type:Floatcount({comp},{expr} [,{ic} [,{start}]])count()E706Return the number of times an item with value{expr} appearsinString,List,Tuple orDictionary{comp}.If{start}is given then start with the item with this index.{start} can only be used withaList oraTuple.When{ic}is given and it'sTRUE thencaseis ignored.When{comp}isastring then the number of not overlappingoccurrences of{expr}is returned. Zerois returned when{expr}is an empty string.Can also be usedasamethod:mylist->count(val)Return type:Numbercscope_connection()cscope_connection([{num},{dbpath} [,{prepend}]])Checks for the existence ofacscope connection. If noparameters are specified, then the function returns:0, ifcscope was not available (not compiled in), or if there are nocscope connections;1, if thereisat least onecscope connection.If parameters are specified, then the value of{num}determines how existence ofacscope connectionis checked:{num}Description of existence check-----------------------------------0Sameas no parameters (e.g., "cscope_connection()").1Ignore{prepend}, and usepartialstring matches for{dbpath}.2Ignore{prepend}, and use exactstring matches for{dbpath}.3Use{prepend}, usepartialstring matches for both{dbpath} and{prepend}.4Use{prepend}, use exactstring matches for both{dbpath} and{prepend}.Note: Allstring comparisons arecase sensitive!Examples. Suppose we had the following (from ":cs show"): # pid database nameprepend path 0 27664 cscope.out/usr/localInvocationReturn Val--------------------cscope_connection()1cscope_connection(1, "out")1cscope_connection(2, "out")0cscope_connection(3, "out")0cscope_connection(3, "out", "local")1cscope_connection(4, "out")0cscope_connection(4, "out", "local")0cscope_connection(4, "cscope.out", "/usr/local")1Return type:Numbercursor({lnum},{col} [,{off}])cursor()cursor({list})Positions the cursorat the column (byte count){col} in theline{lnum}. The first columnis one.When thereis one argument{list} thisis usedasaListwith two, three or four item:[{lnum},{col}][{lnum},{col},{off}][{lnum},{col},{off},{curswant}]Thisis like the return value ofgetpos() orgetcurpos(),but without the first item.To position the cursor using{col}as the character count, usesetcursorcharpos().Does not change the jumplist.{lnum}is used like withgetline(), except that if{lnum}iszero, the cursor will stay in the current line.If{lnum}is greater than the number of lines in the buffer,the cursor will be positionedat the last line in the buffer.If{col}is greater than the number of bytes in the line,the cursor will be positionedat the last character in theline.If{col}is zero, the cursor will stay in the current column.If{curswant}is givenitis used to set the preferred columnfor vertical movement. Otherwise{col}is used.When'virtualedit'is used{off}specifies the offset inscreen columns from the start of the character. E.g.,aposition withina<Tab> or after the last character.Returns0 when the position could be set, -1 otherwise.Can also be usedasamethod:GetCursorPos()->cursor()Return type:Numberdebugbreak({pid})debugbreak()Specifically used to interrupta program being debugged. Itwill cause process{pid} to geta SIGTRAP. Behavior for otherprocessesis undefined. Seeterminal-debugger.{only available on MS-Windows}ReturnsTRUE if successfully interrupted the program.Otherwise returnsFALSE.Can also be usedasamethod:GetPid()->debugbreak()Return type:Numberdeepcopy({expr} [,{noref}])deepcopy()E698Makea copy of{expr}. For Numbers and Strings this isn'tdifferent from using{expr} directly.When{expr}isaLista full copyis created. This meansthat the originalList can be changed withoutchanging thecopy, and vice versa. When an itemisaList orDictionary,a copy foritis made, recursively. Thuschanging an item in the copy does not change the contents ofthe originalList.ATuple orDictionaryis copied ina similar wayasaList.When{noref}is omitted or zeroa containedList orDictionaryis only copied once. All references point tothis single copy. With{noref} set to 1 every occurrence ofaList orDictionary results ina new copy. This also meansthata cyclicreference causesdeepcopy() to fail.E724Nestingis possible up to 100 levels. When thereis an itemthat refers back toa higher level makinga deep copy with{noref} set to 1 will fail.Also seecopy().Can also be usedasamethod:GetObject()->deepcopy()Return type: any, depending on{expr}delete({fname} [,{flags}])delete()Without{flags} or with{flags} empty: Deletes the file by thename{fname}.This also works when{fname}isa symbolic link. The symboliclink itselfis deleted, not whatit points to.When{flags}is "d": Deletes the directory by the name{fname}. This fails when directory{fname}is not empty.When{flags}is "rf": Deletes the directory by the name{fname} and everything in it, recursively. BE CAREFUL!Note: onMS-Windowsitis not possible to deletea directorythatis being used.The resultisa Number, whichis 0/false if the deleteoperation was successful and -1/true when the deletion failedor partly failed.Useremove() to delete an item fromaList.To deletea line from the buffer use:delete ordeletebufline().Can also be usedasamethod:GetName()->delete()Return type:Numberdeletebufline({buf},{first} [,{last}])deletebufline()Delete lines{first} to{last} (inclusive) from buffer{buf}.If{last}is omitted then delete line{first} only.On success0is returned, on failure 1is returned.This function works only for loaded buffers. First callbufload() if needed.For the use of{buf}, seebufname() above.{first} and{last} are used like withgetline().Note thatwhen usingline() this refers to the current buffer. Use "$"to refer to the last line in buffer{buf}.Can also be usedasamethod:GetBuffer()->deletebufline(1)Return type:Numberdid_filetype()did_filetype()ReturnsTRUE whenautocommands are being executed and theFileType event has been triggeredat least once. Can be usedto avoid triggering theFileType event again in the scriptsthat detect the file type.FileTypeReturnsFALSE when `:setf FALLBACK` was used.When editing another file, the counteris reset, thus thisreally checks if theFileType event has been triggered for thecurrent buffer. This allows anautocommand that startsediting another buffer to set'filetype' and loadasyntaxfile.Return type:Numberdiff({fromlist},{tolist} [,{options}])diff()ReturnsaString oraList containing thediff between thestrings in{fromlist} and{tolist}. Uses the Vim internaldiff library to compute the diff.E106The optional "output" item in{options}specifies the returneddiff format. The following values are supported: indicesReturnaList of thestarting and endingindices andacount of the strings in eachdiff hunk. unifiedReturn the unifieddiff outputasa String.Thisis the default.If the "output" item in{options}is "indices", thenaListisreturned. EachList item containsaDict with the followingitems for eachdiff hunk: from_idxstartindex in{fromlist} for thisdiff hunk. from_countnumber of strings in{fromlist} that areadded/removed/modified in thisdiff hunk. to_idxstartindex in{tolist} for thisdiff hunk. to_countnumber of strings in{tolist} that areadded/removed/modified in thisdiff hunk.The{options}Dict argument alsospecifiesdiffoptions(similar to'diffopt') and supports the following items: algorithmDict specifying thediff algorithm touse. Supportedboolean items are"myers", "minimal", "patience" and"histogram". contextdiff context length. Defaultis 0. iblankignore changes where lines are allblank. icaseignore changes incase of text. indent-heuristicuse the indent heuristic for theinternaldiff library. iwhiteignore changes in amount of whitespace. iwhiteallignore all whitespace changes. iwhiteeolignore whitespace changesatend ofline.For more information about these options, refer to'diffopt'.To compute the unified diff, all the items in{fromlist} areconcatenated intoastring usinga newline separator and thesame for{tolist}. The unifieddiff output uses line numbers.Returns an emptyList orString if{fromlist} and{tolist} areidentical.Examples: :echo diff(['abc'], ['xxx']) @@ -1 +1 @@ -abc +xxx :echo diff(['abc'], ['xxx'], {'output': 'indices'}) [{'from_idx': 0, 'from_count': 1, 'to_idx': 0, 'to_count': 1}] :echo diff(readfile('oldfile'), readfile('newfile')) :echo diff(getbufline(5, 1, '$'), getbufline(6, 1, '$'))For more examples, refer todiff-func-examplesCan also be usedasamethod:GetFromList->diff(to_list)Return type:String or list<dict<number>> or list<any>depending on{options}diff_filler({lnum})diff_filler()Returns the number of filler lines above line{lnum}.These are the lines that were insertedat 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.Returns0 if the currentwindowis not indiff mode.Can also be usedasamethod:GetLnum()->diff_filler()Return type:Numberdiff_hlID({lnum},{col})diff_hlID()Returns the highlight ID fordiff modeat line{lnum} column{col} (byte index). When the current line does not haveadiff change zerois 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.Can also be usedasamethod:GetLnum()->diff_hlID(col)Return type:Numberdigraph_get({chars})digraph_get()E1214Return thedigraph of{chars}. This should beastring withexactly two characters. If{chars} are not just twocharacters, or thedigraph of{chars} does not exist, an erroris given and an emptystringis returned.The character will be converted fromUnicode to'encoding'when needed. This does require the conversion to beavailable,it might fail.Also seedigraph_getlist().Examples:" Get a built-in digraph:echo digraph_get('00')" Returns '∞'" Get a user-defined digraph:call digraph_set('aa', 'あ'):echo digraph_get('aa')" Returns 'あ'Can also be usedasamethod:GetChars()->digraph_get()Return type:StringThis function works only when compiled with the+digraphsfeature. If this featureis disabled, this function willdisplay an error message.digraph_getlist([{listall}])digraph_getlist()Returnalist of digraphs. If the{listall} argumentis givenanditis TRUE, return all digraphs, including the defaultdigraphs. Otherwise, return only user-defined digraphs.The characters will be converted fromUnicode to'encoding'when needed. This does require the conservation to beavailable,it might fail.Also seedigraph_get().Examples:" Get user-defined digraphs:echo digraph_getlist()" Get all the digraphs, including default digraphs:echo digraph_getlist(1)Can also be usedasamethod:GetNumber()->digraph_getlist()Return type: list<list<string>>This function works only when compiled with the+digraphsfeature. If this featureis disabled, this function willdisplay an error message.digraph_set({chars},{digraph})digraph_set()Adddigraph{chars} to the list.{chars}must beastringwith two characters.{digraph}isastring with oneUTF-8encoded character.E1215Be careful, composing characters are NOT ignored. Thisfunctionis similar to:digraphs command, but useful to adddigraphs start witha white space.The function returnsv:true ifdigraphis registered. Ifthis fails an error messageis given andv:falseis returned.If you want to define multipledigraphsat once, you can usedigraph_setlist().Example:call digraph_set(' ', 'あ')Can be usedasamethod:GetString()->digraph_set('あ')Return type:vim9-booleanThis function works only when compiled with the+digraphsfeature. If this featureis disabled, this function willdisplay an error message.digraph_setlist({digraphlist})digraph_setlist()Similar todigraph_set() but this function can add multipledigraphsat once.{digraphlist}isalist composed of lists,where eachlist contains two strings with{chars} and{digraph}as indigraph_set().E1216Example: call digraph_setlist([['aa', 'あ'], ['ii', 'い']])Itis similar to the following: for [chars, digraph] in [['aa', 'あ'], ['ii', 'い']] call digraph_set(chars, digraph) endforExcept that the function returns after the first error,followingdigraphs will not be added.Can be usedasamethod: GetList()->digraph_setlist()Return type:vim9-booleanThis function works only when compiled with the+digraphsfeature. If this featureis disabled, this function willdisplay an error message.echoraw({string})echoraw()Output{string} as-is, including unprintable characters.This can be used to outputaterminal code. For example, todisable modifyOtherKeys:call echoraw(&t_TE)and to enableit again:call echoraw(&t_TI)Use with care, you can mess up theterminal this way.Return type:Numberempty({expr})empty()Return theNumber 1 if{expr}is empty, zero otherwise.-AList,Tuple orDictionaryis empty whenit does not have any items.-AStringis empty when its lengthis zero.-ANumber andFloat are empty when their valueis zero.-v:false,v:none andv:null are empty,v:trueis not.-AJobis empty whenit failed to start.-AChannelis empty whenitis closed.-ABlobis empty when its lengthis zero.- AnObjectis empty, when theempty()method in theobject (if present) returns true.object-empty()Fora longList thisis much faster than comparing thelength with zero.Can also be usedasamethod:mylist->empty()Return type:Numberenviron()environ()Return all of environmentvariablesas dictionary. You cancheck if an environment variable exists like this::echo has_key(environ(), 'HOME')Note that the variable name may be CamelCase; to ignorecaseuse this::echo index(keys(environ()), 'HOME', 0, 1) != -1Return type: dict<string>err_teapot([{expr}])err_teapot()Produce an error with number 418, needed for implementation ofRFC 2324.If{expr}is present anditisTRUE error 503is given,indicating that coffeeis temporarily not available.If{expr}is presentitmust bea String.Return type:Numberescape({string},{chars})escape()Escape the characters in{chars} that occur in{string} withabackslash. Example::echo escape('c:\program files\vim', ' \')results in:c:\\program\ files\\vimAlso seeshellescape() andfnameescape().Can also be usedasamethod:GetText()->escape(' \')Return type:Stringeval()eval({string})Evaluate{string} and return the result. Especially useful toturn the result ofstring() back into the original value.This works for Numbers, Floats, Strings,Blobs and compositesof them. Also works forFuncrefs that refer to existingfunctions. InVim9 script,it can be used to obtainenumvalues from their fully qualified names.Can also be usedasamethod:argv->join()->eval()Return type: any, depending on{string}eventhandler()eventhandler()Returns 1 when inside an event handler. Thatis that Vim gotinterrupted while waiting for the user to typea character,e.g., when droppinga file on Vim. This means interactivecommands cannot be used. Otherwise zerois returned.Return type:Numberexecutable({expr})executable()This function checks if an executable with the name{expr}exists.{expr}must be the name of the program without anyarguments.executable() uses the value of $PATH and/or the normalsearchpath for programs.PATHEXTOnMS-Windows the ".exe", ".bat", etc. can optionally beincluded. Then the extensions in $PATHEXT are tried. Thus if"foo.exe" does not exist, "foo.exe.bat" can be found. If$PATHEXTis not set then ".com;.exe;.bat;.cmd"is used.A dotby itself can be used in $PATHEXT to try using the namewithout an extension. When'shell' looks likeaUnix shell,then the nameis also tried without adding an extension.OnMS-Windowsit only checks if the file exists andis notadirectory, not if it's really executable.OnMS-Windows an executable in the same directoryas the Vimexecutableis always found. Since this directoryis added to$PATHit should also work to executeitwin32-PATH.NoDefaultCurrentDirectoryInExePathOnMS-Windows an executable in Vim's current working directoryis also normally found, but this can be disabled by settingthe $NoDefaultCurrentDirectoryInExePath environment variable.The resultisa Number:1exists0does not exist-1not implemented on this systemexepath() can be used to get the full path of an executable.Can also be usedasamethod:GetCommand()->executable()Return type:Numberexecute({command} [,{silent}])execute()Execute anEx command or commands and return the outputasastring.{command} can beastring ora List. Incase ofaList thelines are executed one by one.Thisis more orless equivalent to:redir => var{command}redir ENDExcept that line continuation in{command}is not recognized.The optional{silent} argument can have these values:""no:silent used"silent":silent used"silent!":silent! usedThe defaultis "silent".Note that with "silent!", unlike:redir, errormessages are dropped. When using an externalcommand the screen may be messed up, usesystem() instead.E930Itis not possible to use:redir anywhere in{command}.To getalist of lines usesplit() on the result:execute('args')->split("\n")To executea command in anotherwindow than the current oneusewin_execute().When used recursively the output of the recursive callis notincluded in the output of the higher level call.Can also be usedasamethod:GetCommand()->execute()Return type:Stringexepath({expr})exepath()If{expr}is an executable andis either an absolute path,arelative path or found in $PATH, return the full path.Note that the current directoryis used when{expr} startswith "./", which may bea problem for Vim:echo exepath(v:progpath)If{expr} cannot be found in $PATH oris not executable thenan emptystringis returned.Can also be usedasamethod:GetCommand()->exepath()Return type:Stringexists({expr})exists()The resultisa Number, whichisTRUE if{expr}is defined,zero otherwise.Note: Ina compiled:def function the evaluationis doneatruntime. Useexists_compiled() to evaluate theexpressionat compile time.For checking fora supported feature usehas().For checking ifa file exists usefilereadable().The{expr} argumentisa string, which contains one of these:varnameinternal variable (seedict.keyinternal-variables). Also workslist[i]forcurly-braces-names,Dictionaryimport.Funcentries,List items,class andclass.Funcobject methods, imported items, etc.object.FuncDoes not work for localvariables inaclass.varnamecompiled:def function.object.varnameAlso works fora function inVim9script, sinceit can be usedasafunction reference.Beware that evaluating anindex maycause an error message for an invalidexpression. E.g.: :let l = [1, 2, 3] :echo exists("l[5]")0 :echo exists("l[xx]") E121: Undefined variable: xx0&option-nameVim option (only checks ifit exists,not ifit really works)+option-nameVim option that works.$ENVNAMEenvironment variable (could also bedone by comparing with an emptystring)*funcnamebuilt-in function (seefunctions)or user defined function (seeuser-functions) thatis implemented.Also works fora variable thatisaFuncref.?funcnamebuilt-in function that could beimplemented; to be used to check if"funcname"is valid:cmdnameEx command: built-in command, usercommand or command modifier:command.Returns:1 for match with start ofa command2 full match witha command3 matches several user commandsTo check fora supported commandalways check the return value to be 2.:2matchThe:2match command.:3matchThe:3match command (but youprobably should not use it,itisreserved for internal usage)#eventautocommand defined for this event#event#patternautocommand defined for this event andpattern (thepatternis 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 eventissupported.Examples:exists("&shortname")exists("$HOSTNAME")exists("*strftime")exists("*s:MyFunc")" only for legacy scriptexists("*MyFunc")exists("bufcount")exists(":Make")exists("#CursorHold")exists("#BufReadPre#*.gz")exists("#filetypeindent")exists("#filetypeindent#FileType")exists("#filetypeindent#FileType#*")exists("##ColorScheme")Theremust be nospace between the symbol (&/$/*/#) and thename.Theremust be no extra characters after the name, although ina few cases thisis ignored. That may become stricter in thefuture, thus don'tcount on it!Working example:exists(":make")NOT working example:exists(":make install")Note that the argumentmust bea string, not the name of thevariable itself. For example:exists(bufcount)This doesn't check for existence of the "bufcount" variable,but gets the value of "bufcount", and checks if that exists.Can also be usedasamethod:Varname()->exists()Return type:Stringexists_compiled({expr})exists_compiled()Likeexists() but evaluatedat compile time. Thisis usefulto skipa block wherea functionis used that would otherwisegive an error:if exists_compiled('*ThatFunction') ThatFunction('works')endifIfexists() were used thena compilation error would begiven if ThatFunction()is not defined.{expr}must bea literal string.E1232Can only be used ina:def function.E1233This does not work to check for arguments or local variables.Return type:Stringexp({expr})exp()Return the exponential of{expr}asaFloat in the range[0, inf].{expr}must evaluate toaFloat oraNumber.Returns 0.0 if{expr}is notaFloat oraNumber.Examples::echo exp(2)7.389056:echo exp(-1)0.367879Can also be usedasamethod:Compute()->exp()Return type:Floatexpand({string} [,{nosuf} [,{list}]])expand()Expandwildcards and the following special keywords in{string}.'wildignorecase' applies.If{list}is given anditisTRUE,aList will be returned.Otherwise the resultisaString and when there are severalmatches, they are separated by<NL> characters. [Note: inversion 5.0aspace was used, which caused problems whenafile name containsa space]If the expansion fails, the resultis an empty string.A namefora non-existing fileis not included, unless{string} doesnot start with '%', '#' or '<', see below.Fora:terminalwindow '%' expands toa '!' followed bythe command or shell thatis run.terminal-bufnameWhen{string} starts with '%', '#' or '<', the expansionisdone like for thecmdline-specialvariables with theirassociated modifiers. Hereisa short overview:%current file name#alternate file name#nalternate file namen<cfile>file name under the cursor<afile>autocmd file name<abuf>autocmd buffer number (asa String!)<amatch>autocmd matched name<cexpr>Cexpression under the cursor<sfile>sourcedscript file or function name<slnum>sourcedscript line number or functionline number<sflnum>script file line number, also when ina function<SID>"<SNR>123_" where "123"is thecurrentscript ID<SID><script>sourcedscript file, orscript filewhere the current function was defined<stack>call stack<cword>word under the cursor<cWORD>WORD under the cursor<client>the{clientid} of the last receivedmessageserver2client()Modifiers::pexpand to full path:hhead (last path component removed):ttail (last path component only):rroot (one extension removed):eextension onlyExample::let &tags = expand("%:p:h") .. "/tags"Note that when expandingastring that starts with '%', '#' or'<', any following textis ignored. This does NOT work::let doesntwork = expand("%:h.bak")Use this::let doeswork = expand("%:h") .. ".bak"Alsonote that expanding "<cfile>" and others only returns thereferenced file name without further expansion. If "<cfile>"is "~/.cshrc", you need todo anotherexpand() to have the"~/" expanded into the path of thehome directory::echo expand(expand("<cfile>"))There cannot be whitespace between thevariables and thefollowing modifier. Thefnamemodify() function can be usedto modify normal file names.When using '%' or '#', and the current or alternate file nameis not defined, an emptystringis used. Using "%:p" inabuffer with no name, results in the current directory, witha'/' added.When'verbose'is set then expanding '%', '#' and<> itemswill result in an error message if the argument cannot beexpanded.When{string} does not start with '%', '#' or '<',itisexpanded likea file nameis expanded on the command line.'suffixes' and'wildignore' are used, unless the optional{nosuf} argumentis given anditisTRUE.Names for non-existing files are included. The "**" item canbe used to search ina directory tree. For example, to findall "README" files in the current directory and below::echo expand("**/README")expand() can also be used to expandvariables and environmentvariables that are only known ina shell. But this can beslow, becausea shell may be used todo the expansion. Seeexpr-env-expand.The expanded variableis still handled likealist of filenames. When an environment variable cannot be expanded,itisleft unchanged. Thus ":echo expand('$FOOBAR')" results in"$FOOBAR".Seeglob() for finding existing files. Seesystem() forgetting the raw output of an external command.Can also be usedasamethod:Getpattern()->expand()Return type:String or list<string> depending on{list}expandcmd({string} [,{options}])expandcmd()Expand special items inString{string} like whatis done foranEx command suchas:edit. This expands special keywords,like withexpand(), and environment variables, anywhere in{string}. "~user" and "~/path" are only expandedat thestart.The following items are supported in the{options}Dictargument: errmsgIf set to TRUE, errormessages are displayedif an erroris encountered during expansion.By default, errormessages are not displayed.Returns the expanded string. If an erroris encounteredduring expansion, the unmodified{string}is returned.Example::echo expandcmd('make %<.o')make /path/runtime/doc/builtin.o:echo expandcmd('make %<.o', {'errmsg': v:true})Can also be usedasamethod:GetCommand()->expandcmd()Return type:String or list<string> depending on{list}extend({expr1},{expr2} [,{expr3}])extend(){expr1} and{expr2}must be bothLists or bothDictionaries.If they areLists: Append{expr2} to{expr1}.If{expr3}is giveninsert the items of{expr2} before theitem withindex{expr3} in{expr1}. When{expr3}is zeroinsert before the first item. When{expr3}is equal tolen({expr1}) then{expr2}is appended.Examples::echo sort(extend(mylist, [7, 5])):call extend(mylist, [2, 3], 1)When{expr1}is the sameListas{expr2} then the number ofitems copiedis equal to the original length of the List.E.g., when{expr3}is 1 you getN new copies of the first item(whereNis the original length of the List).Useadd() to concatenate one item toa list. To concatenatetwo lists intoa newlist use the+ operator::let newlist = [1, 2, 3] + [4, 5]If they areDictionaries:Add all entries from{expr2} to{expr1}.Ifa 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 messageE737When{expr3}is omitted then "force"is assumed.{expr1}is changed when{expr2}is not empty. If necessarymakea copy of{expr1} first or useextendnew() to returnanew List/Dictionary.{expr2} remains unchanged.When{expr1}is locked and{expr2}is not empty the operationfails.Returns{expr1}. Returns0 on error.Can also be usedasamethod:mylist->extend(otherlist)Return type: list<{type}> or dict<{type}> depending on{expr1}and{expr2}, incase of error:Numberextendnew({expr1},{expr2} [,{expr3}])extendnew()Likeextend() but instead of adding items to{expr1}a newList orDictionaryis created and returned.{expr1} remainsunchanged.Return type: list<{type}> or dict<{type}> depending on{expr1}and{expr2}, incase of error:Numberfeedkeys({string} [,{mode}])feedkeys()Characters in{string} are queued for processingas if theycome fromamapping or were typed by the user.By default thestringis added to theend of the typeaheadbuffer, thus ifamappingis still being executed thecharacters come after them. Use the 'i' flag toinsert beforeother characters, they will be executed next, before anycharacters froma mapping.The function does not wait for processing of keys contained in{string}.To include special keys into{string}, use double-quotesand "\..."notationexpr-quote. For example,feedkeys("\<CR>") simulates pressing of the<Enter> key. Butfeedkeys('\<CR>') pushes 5 characters.A special code that might be usefulis<Ignore>,it exits thewait fora character without doing anything.<Ignore>{mode}isa String, which can contain these character flags:'m'Remap keys. Thisis default. If{mode}is absent,keys are remapped.'n'Do not remap keys.'t'Handle keysas if typed; otherwise they are handledasif coming froma mapping. This matters for undo,opening folds, etc.'L'Lowlevel input. Only works forUnix or when using theGUI. Keys are usedas if they were coming from theterminal. Other flags are not used.E980WhenaCTRL-C interrupts and 't'is includedit setsthe internal "got_int" flag.'i'Insert thestring instead of appending (see above).'x'Execute commands until typeaheadis empty. Thisissimilar to using ":normal!". You can callfeedkeys()several times without 'x' and then one time with 'x'(possibly with an empty{string}) to execute all thetypeahead.Note that when Vim ends inInsert modeitwill behaveas if<Esc>is typed, to avoid gettingstuck, waiting fora character to be typed before thescript continues.Note that if you manage to callfeedkeys() whileexecuting commands, thus callingit recursively, thenall typeahead will be consumed by the last call.'c'Remove anyscript context when executing, so thatlegacyscriptsyntax applies, "s:var" does not work,etc.Note that if thestring being fed setsascriptcontext this still applies.'!'When used with 'x' will notendInsert mode. Can beused ina test whenatimeris set to exitInsert modea little later. Useful fortesting CursorHoldI.Return valueis always 0.Can also be usedasamethod:GetInput()->feedkeys()Return type:Numberfilecopy({from},{to})filecopy()Copy the file pointed to by the name{from} to{to}. Theresultisa Number, whichisTRUE if the file was copiedsuccessfully, andFALSE whenit failed.Ifa file with name{to} already exists,it will fail.Note thatit does not handle directories (yet).This functionis not available in thesandbox.Can also be usedasamethod:GetOldName()->filecopy(newname)Return type:Numberfilereadable({file})filereadable()The resultisa Number, whichisTRUE whena file with thename{file} exists, and can be read. If{file} doesn't exist,orisa directory, the resultisFALSE.{file}is anyexpression, whichis usedasa String.If you don't care about the file being readable you can useglob().{file}is used as-is, you may want to expandwildcards first:echo filereadable('~/.vimrc')0echo filereadable(expand('~/.vimrc'))1Can also be usedasamethod:GetName()->filereadable()Return type:Numberfile_readable()Obsolete name: file_readable().filewritable({file})filewritable()The resultisa Number, whichis 1 whena file with thename{file} exists, and can be written. If{file} doesn'texist, oris not writable, the resultis 0. If{file}isadirectory, and we can write to it, the resultis 2.Can also be usedasamethod:GetName()->filewritable()Return type:Numberfilter({expr1},{expr2})filter(){expr1}must beaList,String,Blob orDictionary.For each item in{expr1} evaluate{expr2} and when the resultis zero orfalse remove the item from theList orDictionary. Similarly for each byte inaBlob and eachcharacter inaString.{expr2}must beastring orFuncref.If{expr2}isastring, inside{expr2}v:val has the valueof the current item. ForaDictionaryv:key has the keyof the current item and foraListv:key has theindex ofthe current item. ForaBlobv:key has theindex of thecurrent byte. ForaStringv:key has theindex of thecurrent character.Examples:call filter(mylist, 'v:val !~ "OLD"')Removes the items where "OLD" appears.call filter(mydict, 'v:key >= 8')Removes the items witha key below 8.call filter(var, 0)Removes all the items, thus clears theList orDictionary.Note that{expr2}is the result ofexpression andis thenusedas anexpression again. Oftenitis good to usealiteral-string to avoid having to double backslashes.If{expr2}isaFuncrefitmust take two arguments:1. the key or theindex of the current item.2. the value of the current item.The functionmust returnTRUE if the item should be kept.Example that keeps the odd items ofa list:func Odd(idx, val) return a:idx % 2 == 1endfunccall filter(mylist, function('Odd'))Itis shorter when usingalambda. InVim9 syntax:call filter(myList, (idx, val) => idx * val <= 42)In legacyscript syntax:call filter(myList, {idx, val -> idx * val <= 42})If youdo not use "val" you can leaveit out:call filter(myList, {idx -> idx % 2 == 1})InVim9script the resultmust be true, false, zero or one.Other values will result ina type error.ForaList andaDictionary the operationis donein-place. If you wantit to remain unmodified makea copyfirst::let l = filter(copy(mylist), 'v:val =~ "KEEP"')Returns{expr1}, theList orDictionary that was filtered,ora newBlob orString.When an erroris encountered while evaluating{expr2} nofurther items in{expr1} are processed.When{expr2}isaFuncreferrors insidea function are ignored,unlessit was defined with the "abort" flag.Can also be usedasamethod:mylist->filter(expr2)Return type:String,Blob, list<{type}> or dict<{type}>depending on{expr1}finddir({name} [,{path} [,{count}]])finddir()Find directory{name} in{path}. Supports both downwards andupwards recursive directory searches. Seefile-searchingfor thesyntax of{path}.Returns the path of the first found match. When the founddirectoryis below the current directorya relative pathisreturned. Otherwisea full pathis returned.If{path}is omitted or empty then'path'is used.If the optional{count}is given, find{count}'s occurrence of{name} in{path} instead of the first one.When{count}is negative return all the matches inaList.Returns an emptystring if the directoryis not found.Thisis quite similar to the ex-command:find.Can also be usedasamethod:GetName()->finddir()Return type: list<string> if{count}is negative,Stringotherwisefindfile({name} [,{path} [,{count}]])findfile()Just likefinddir(), but finda file instead ofa directory.Uses'suffixesadd'.Example::echo findfile("tags.vim", ".;")Searches from the directory of the current file upwards untilit finds the file "tags.vim".Can also be usedasamethod:GetName()->findfile()Return type: list<string> if{count}is negative,Stringotherwiseflatten({list} [,{maxdepth}])flatten()Flatten{list} up to{maxdepth} levels. Without{maxdepth}the resultisaList without nesting,as if{maxdepth}isa very large number.The{list}is changed in place, useflattennew() if youdonot want that.InVim9scriptflatten() cannot be used, youmust always useflattennew().E900{maxdepth} means how deep in nested lists changes are made.{list}is not modified when{maxdepth}is 0.{maxdepth}must be positive number.If thereis an error the number zerois returned.Example::echo flatten([1, [2, [3, 4]], 5])[1, 2, 3, 4, 5]:echo flatten([1, [2, [3, 4]], 5], 1)[1, 2, [3, 4], 5]Can also be usedasamethod:mylist->flatten()Return type: list<{type}>flattennew({list} [,{maxdepth}])flattennew()Likeflatten() but first makea copy of{list}.Return type: list<{type}>float2nr({expr})float2nr()Convert{expr} toaNumber by omitting the part after thedecimal point.{expr}must evaluate toaFloat oraNumber.Returns0 if{expr}is notaFloat oraNumber.When the value of{expr}is out of range foraNumber theresultis truncated to 0x7fffffff or -0x7fffffff (or when64-bitNumber supportis enabled, 0x7fffffffffffffff or-0x7fffffffffffffff). NaN results in -0x80000000 (or when64-bitNumber supportis enabled, -0x8000000000000000).Examples:echo float2nr(3.95)3echo float2nr(-23.45)-23echo float2nr(1.0e100)2147483647 (or 9223372036854775807)echo float2nr(-1.0e150)-2147483647 (or -9223372036854775807)echo float2nr(1.0e-100)0Can also be usedasamethod:Compute()->float2nr()Return type:Numberfloor({expr})floor()Return the largest integral valueless than or equal to{expr}asaFloat (round down).{expr}must evaluate toaFloat oraNumber.Returns 0.0 if{expr}is notaFloat oraNumber.Examples:echo floor(1.856)1.0echo floor(-5.456)-6.0echo floor(4.0)4.0Can also be usedasamethod:Compute()->floor()Return type:Floatfmod({expr1},{expr2})fmod()Return the remainder of{expr1}/{expr2}, even if thedivisionis not representable. Returns{expr1}-i *{expr2}for some integeri such that if{expr2}is non-zero, theresult has the same signas{expr1} and magnitudeless thanthe magnitude of{expr2}. If{expr2}is zero, the valuereturnedis zero. The value returnedisaFloat.{expr1} and{expr2}must evaluate toaFloat oraNumber.Returns 0.0 if{expr1} or{expr2}is notaFloat oraNumber.Examples::echo fmod(12.33, 1.22)0.13:echo fmod(-12.33, 1.22)-0.13Can also be usedasamethod:Compute()->fmod(1.22)Return type:Floatfnameescape({string})fnameescape()Escape{string} for useas file name command argument. Allcharacters that havea special meaning, suchas '%' and'|'are escaped witha backslash.For most systems the characters escaped are" \t\n*?[{`$\\%#'\"|!<". For systems whereabackslashappears ina filename,it depends on the value of'isfname'.A leading '+' and '>'is also escaped (special after:editand:write). Anda "-" by itself (special after:cd).Returns an emptystring on error.Example::let fname = '+some str%nge|name':exe "edit " .. fnameescape(fname)results in executing:edit \+some\ str\%nge\|nameCan also be usedasamethod:GetName()->fnameescape()Return type:Stringfnamemodify({fname},{mods})fnamemodify()Modify file name{fname} according to{mods}.{mods}isastring of characters likeitis used for file names on thecommand line. Seefilename-modifiers.Example::echo fnamemodify("main.c", ":p:h")results in:/home/user/vim/vim/srcIf{mods}is empty or an unsupported modifieris used then{fname}is returned.When{fname}is empty then with{mods} ":h" returns ".", sothat:cd can be used with it. Thisis different fromexpand('%:h') withouta buffer name, which returns an emptystring.Note: Environmentvariables don't work in{fname}, useexpand() first then.Can also be usedasamethod:GetName()->fnamemodify(':p:h')Return type:Stringfoldclosed({lnum})foldclosed()The resultisa Number. If the line{lnum}is ina closedfold, the resultis the number of the first line in that fold.If the line{lnum}is not ina closed fold, -1is returned.{lnum}is used like withgetline(). Thus "."is the currentline, "'m"mark m, etc.Can also be usedasamethod:GetLnum()->foldclosed()Return type:Numberfoldclosedend({lnum})foldclosedend()The resultisa Number. If the line{lnum}is ina closedfold, the resultis the number of the last line in that fold.If the line{lnum}is not ina closed fold, -1is returned.{lnum}is used like withgetline(). Thus "."is the currentline, "'m"mark m, etc.Can also be usedasamethod:GetLnum()->foldclosedend()Return type:Numberfoldlevel({lnum})foldlevel()The resultisa Number, whichis the foldlevel of line{lnum}in the current buffer. For nestedfolds the deepest levelisreturned. If thereis no foldat line{lnum}, zeroisreturned. It doesn't matter if thefolds are open or closed.When used while updatingfolds (from'foldexpr') -1isreturned for lines wherefolds are still to be updated and thefoldlevelis unknown. Asa specialcase the level of theprevious lineis usually available.{lnum}is used like withgetline(). Thus "."is the currentline, "'m"mark m, etc.Can also be usedasamethod:GetLnum()->foldlevel()Return type:Numberfoldtext()foldtext()Returnsa String, to be displayed fora closed fold. Thisisthe default function used for the'foldtext' option and shouldonly be called from evaluating'foldtext'. It uses thev:foldstart,v:foldend andv:folddashes variables.The returnedstring looks like this:+-- 45 lines: abcdefThe number of leading dashes depends on the foldlevel. The"45"is the number of lines in the fold. "abcdef"is the textin the first non-blank line of the fold. Leading white space,"//" or "/*" and the text from the'foldmarker' and'commentstring'optionsis removed.When used to draw the actual foldtext, the rest of the linewill be filled with the fold char from the'fillchars'setting.Returns an emptystring when thereis no fold.Return type:String{not available when compiled without the |+folding| feature}foldtextresult({lnum})foldtextresult()Returns the text thatis displayed for the closed foldat line{lnum}. Evaluates'foldtext' in the appropriate context.When thereis no closed foldat{lnum} an emptystringisreturned.{lnum}is used like withgetline(). Thus "."is the currentline, "'m"mark m, etc.Useful when exporting folded text, e.g., to HTML.{not available when compiled without the |+folding| feature}Can also be usedasamethod:GetLnum()->foldtextresult()Return type:Stringforeach({expr1},{expr2})foreach()E1525{expr1}must beaList,Tuple,String,Blob orDictionary.For each item in{expr1} execute{expr2}.{expr1}is notmodified; its values may be,as with:lockvar 1.E741Seemap() andfilter() to modify{expr1}.{expr2}must beastring orFuncref.If{expr2}isastring, inside{expr2}v:val has the valueof the current item. ForaDictionaryv:key has the keyof the current item and foraList oraTuplev:key hastheindex of the current item. ForaBlobv:key has theindex of the current byte. ForaStringv:key has theindex of the current character.Examples:call foreach(mylist, 'used[v:val] = true')This records the items that are in the{expr1} list.Note that{expr2}is the result ofexpression andis then usedasa command. Oftenitis good to usealiteral-string toavoid having to double backslashes.If{expr2}isaFuncrefitmust take two arguments:1. the key or theindex of the current item.2. the value of the current item.Witha legacyscriptlambda you don't get an error ifit onlyaccepts one argument, but withaVim9lambda you get "E1106:One argument too many", the number of argumentsmust match.If the function returnsa value,itis ignored.Returns{expr1} in all cases.When an erroris encountered while executing{expr2} nofurther items in{expr1} are processed.When{expr2}isaFuncreferrors insidea function are ignored,unlessit was defined with the "abort" flag.Can also be usedasamethod:mylist->foreach(expr2)Return type:String,Blob, list<{type}>, tuple<{type}> ordict<{type}> depending on{expr1}foreground()foreground()Move the Vimwindow to the foreground. Useful when sent froma client toa Vim server.remote_send()OnWin32 systems this might not work, the OS does not alwaysallowawindow to bring itself to the foreground. Useremote_foreground() instead.Return type:Number{only in the Win32,Motif andGTKGUI versions and theWin32 console version}fullcommand({name} [,{vim9}])fullcommand()Get the full command name froma short abbreviated commandname; see20.2 for details on command abbreviations.Thestring argument{name} may start witha: and canincludea[range], these are skipped and not returned.Returns an emptystring ifa command doesn't exist, if it'sambiguous (for user-defined commands) or cannot be shortenedthis way.vim9-no-shortenWithout the{vim9} argument uses the currentscript version.If{vim9}is present andFALSE then legacyscript rules areused. When{vim9}is present andTRUE thenVim9 rules areused, e.g. "en"is nota short form of "endif".For examplefullcommand('s'),fullcommand('sub'),fullcommand(':%substitute') all return "substitute".Can also be usedasamethod:GetName()->fullcommand()Return type:Stringfuncref({name} [,{arglist}] [,{dict}])funcref()Just likefunction(), but the returnedFuncref will lookupthe function by reference, not by name. This matters when thefunction{name}is redefined later.Unlikefunction(),{name}must be an existing user function.It only works for an autoloaded function ifit has alreadybeen loaded (to avoid mistakenly loading theautoloadscriptwhen only intending to use the function name, usefunction()instead).{name} cannot bea builtin function.Returns0 on error.Can also be usedasamethod:GetFuncname()->funcref([arg])Return type: func(...): any orNumber on errorfunction()partialE700E923function({name} [,{arglist}] [,{dict}])ReturnaFuncref variable that refers to function{name}.{name} can be the name ofa user defined function or aninternal function.{name} can also beaFuncref ora partial. Whenitisapartial thedict stored init will be used and the{dict}argumentis not allowed. E.g.:let FuncWithArg = function(dict.Func, [arg])let Broken = function(dict.Func, [arg], dict)When using theFuncref the function will be found by{name},also whenit was redefined later. Usefuncref() to keep thesame function.When{arglist} or{dict}is present this createsa partial.That means the argumentlist and/or the dictionaryis stored intheFuncref and will be used when theFuncrefis called.The arguments are passed to the function in front of otherarguments, but after any argument frommethod. Example:func Callback(arg1, arg2, name)...let Partial = function('Callback', ['one', 'two'])...call Partial('name')Invokes the functionas with:call Callback('one', 'two', 'name')Withamethod:func Callback(one, two, three)...let Partial = function('Callback', ['two'])...eval 'one'->Partial('three')Invokes the functionas with:call Callback('one', 'two', 'three')Thefunction() call can be nested to add more arguments to theFuncref. The extra arguments are appended to thelist ofarguments. Example:func Callback(arg1, arg2, name)"...let Func = function('Callback', ['one'])let Func2 = function(Func, ['two'])"...call Func2('name')Invokes the functionas with:call Callback('one', 'two', 'name')TheDictionaryis only useful when callinga "dict" function.In thatcase the{dict}is passed inas "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 exampleThe use offunction()is not needed when there are no extraarguments, these two are equivalent, if Callback()is definedas context.Callback():let Func = function('Callback', context)let Func = context.CallbackThe argumentlist and theDictionary can be combined:function Callback(arg1, count) dict"...let context = {"name": "example"}let Func = function('Callback', ['one'], context)"...call Func(500)Invokes the functionas with:call context.Callback('one', 500)Returns0 on error.Can also be usedasamethod:GetFuncname()->function([arg])Return type: func(...): any orNumber on errorgarbagecollect([{atexit}])garbagecollect()Cleanup unusedLists,Dictionaries,Channels andJobsthat have circular references.Thereis hardly evera need to invoke this function,asitisautomatically done when Vim runs out of memory oris waitingfor the user to pressa key after'updatetime'. Items withoutcircular references are always freed when they become unused.Thisis useful if you have deleteda very bigList and/orDictionary with circular references inascript that runsfora long time.When the optional{atexit} argumentis one, garbagecollection will also be done whenexiting Vim, ifit wasn'tdone before. Thisis useful when checking for memory leaks.The garbage collectionis not done immediately but only whenit's safe to perform. Thisis when waiting for the user totypea character. To force garbage collection immediately usetest_garbagecollect_now().Return type:Stringget({list},{idx} [,{default}])get()get()-listGet item{idx} fromList{list}. When this itemis notavailable return{default}. Return zero when{default}isomitted.Preferably usedasamethod:mylist->get(idx)Return type: any, depending on{list}get({tuple},{idx} [,{default}])get()-tupleGet item{idx} fromTuple{tuple}. When this itemis notavailable return{default}. Return zero when{default}isomitted.Preferably usedasamethod:mytuple->get(idx)Return type: any, depending on{tuple}get({blob},{idx} [,{default}])get()-blobGet byte{idx} fromBlob{blob}. When this byteis notavailable return{default}. Return -1 when{default}isomitted.Preferably usedasamethod:myblob->get(idx)Return type:Numberget({dict},{key} [,{default}])get()-dictGet item with key{key} fromDictionary{dict}. When thisitemis not available return{default}. Return zero when{default}is omitted. Useful example:let val = get(g:, 'var_name', 'default')This gets the value of g:var_name ifit exists, and uses'default' whenit does not exist.Preferably usedasamethod:mydict->get(key)Return type: any, depending on{dict}get({func},{what})get()-funcGet item{what} fromFuncref{func}. Possible values for{what} are: "name" The function name "func" The function "dict" The dictionary "args" Thelist 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 acceptsa variable number of arguments...Note: Thereis no error, if the{arglist} oftheFuncref contains more arguments than theFuncref expects, it's not validated.Returns zero on error.Preferably usedasamethod:myfunc->get(what)Return type: any, depending on{func} and{what}getbufinfo()getbufinfo([{buf}])getbufinfo([{dict}])Get information aboutbuffersasaList of Dictionaries.Without an argument information about all thebuffersisreturned.When the argumentisaDictionary only thebuffers matchingthe specified criteria are returned. The following keys canbe specified in{dict}:buflistedinclude only listed buffers.bufloadedinclude only loaded buffers.bufmodifiedinclude only modified buffers.Otherwise,{buf}specifiesa particular buffer to returninformation for. For the use of{buf}, seebufname()above. If the bufferis found the returnedList has one item.Otherwise the resultis an empty list.Each returnedList itemisa dictionary with the followingentries:bufnrBuffer number.changedTRUE if the bufferis modified.changedtickNumber of changes made to the buffer.commandTRUE if the buffer belongs to thecommand-linewindowcmdwin.hiddenTRUE if the bufferis hidden.lastusedTimestamp in seconds, likelocaltime(), when the buffer waslast used.{only with the |+viminfo| feature}listedTRUE if the bufferis listed.lnumLine number used for the buffer whenopened in the current window.Only valid if the buffer has beendisplayed in thewindow in the past.If you want the line number of thelast known cursor position ina givenwindow, useline()::echo line('.', {winid})linecountNumber of lines in the buffer (onlyvalid when loaded)loadedTRUE if the bufferis loaded.nameFull path to the file in the buffer.signsList ofsigns placed in the buffer.Eachlist itemisa dictionary withthe following fields: id sign identifier lnum line number name sign namevariablesAreference to the dictionary withbuffer-local variables.windowsList ofwindow-IDs that display thisbufferpopupsList ofpopupwindow-IDs thatdisplay this bufferExamples:for buf in getbufinfo() echo buf.nameendforfor buf in getbufinfo({'buflisted':1}) if buf.changed.... endifendforTo get buffer-localoptions use:getbufvar({bufnr}, '&option_name')Can also be usedasamethod:GetBufnr()->getbufinfo()Return type: list<dict<any>>getbufline()getbufline({buf},{lnum} [,{end}])ReturnaList with the linesstarting from{lnum} to{end}(inclusive) in the buffer{buf}. If{end}is omitted,aList with only the line{lnum}is returned. Seegetbufoneline() for only getting the line.For the use of{buf}, seebufname() above.For{lnum} and{end} "$" can be used for the last line of thebuffer. Otherwisea numbermust be used.When{lnum}is smaller than 1 or bigger than the number oflines in the buffer, an emptyListis returned.When{end}is greater than the number of lines in the buffer,itis treatedas{end}is set to the number of lines in thebuffer. When{end}is before{lnum} an emptyListisreturned.This function works only for loaded buffers. For unloaded andnon-existing buffers, an emptyListis returned.Example::let lines = getbufline(bufnr("myfile"), 1, "$")Can also be usedasamethod:GetBufnr()->getbufline(lnum)Return type: list<string>getbufoneline()getbufoneline({buf},{lnum})Just likegetbufline() but only get one line and returnitasa string.Return type:Stringgetbufvar({buf},{varname} [,{def}])getbufvar()The resultis the value of option or local buffer variable{varname} in buffer{buf}.Note that the name without "b:"must be used.The{varname} argumentisa string.When{varname}is empty returnsaDictionary with all thebuffer-local variables.When{varname}is equal to "&" returnsaDictionary with allthe buffer-local options.Otherwise, when{varname} starts with "&" returns the value ofa buffer-local option.This also works fora global or buffer-local option, butitdoesn't work fora 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 emptystringis returned, thereis no error message.Examples::let bufmodified = getbufvar(1, "&mod"):echo "todo myvar = " .. getbufvar("todo", "myvar")Can also be usedasamethod:GetBufnr()->getbufvar(varname)Return type: any, depending on{varname}getcellpixels()getcellpixels()ReturnsaList ofterminal cell pixel size.List formatis [xpixel, ypixel].Only works onUnix (terminal and gVim) and Windows (gVim only).Returns[] on other systems or on failure.Note that there could be variations across different terminals.On macOS, system Terminal.app returns sizes in points (beforeRetina scaling), whereas third-party terminals return raw pixelsizes (post Retina scaling).Return type: list<any>getcellwidths()getcellwidths()ReturnsaList of cell widths of character ranges overriddenbysetcellwidths(). The formatis equal to the argument ofsetcellwidths(). If no character ranges have their cellwidths overridden, an emptyListis returned.Return type: list<any>getchangelist([{buf}])getchangelist()Returns thechangelist for the buffer{buf}. For the useof{buf}, seebufname() above. If buffer{buf} doesn'texist, an emptylistis returned.The returnedlist contains two entries:alist with the changelocations and the current position in the list. Eachentry in the changelistisa dictionary with the followingentries:colcolumn numbercoladdcolumn offset for'virtualedit'lnumline numberIf buffer{buf}is the current buffer, then the currentposition refers to the position in the list. For otherbuffers,itis set to the length of the list.Can also be usedasamethod:GetBufnr()->getchangelist()Return type: list<any>getchar([{expr} [,{opts}]])getchar()Geta single character from the user or input stream.If{expr}is omitted oris -1, wait untila characterisavailable.If{expr}is 0, only geta character when oneis available.Return zero otherwise.If{expr}is 1, only check ifa characteris available,itisnot consumed. Return zero if no character available.If you prefer always gettingastring usegetcharstr(), orspecifyFALSEas "number" in{opts}.Without{expr} and when{expr}is0a whole character orspecial keyis returned. Ifitisa single character, theresultisa Number. Usenr2char() to convertit toa String.OtherwiseaStringis returned with the encoded character.Fora special key it'saString witha sequence of bytesstarting with 0x80 (decimal: 128). Thisis the same valueastheString "\<Key>", e.g., "\<Left>". The returned valueisalsoaString whena modifier (shift, control, alt) was usedthatis not included in the character.keytrans() can alsobe used to converta returnedString intoa readable form.When{expr}is0 and Escis typed, there will bea short delaywhile Vim waits to see if thisis the start of anescapesequence.When{expr}is 1 only the first byteis returned. Foraone-byte characteritis the character itselfasa number.Usenr2char() to convertit toa String.Usegetcharmod() to obtain any additional modifiers.The optional argument{opts}isaDict and supports thefollowing items:cursorAString specifying cursor behaviorwhen waiting fora character."hide": hide the cursor."keep": keep current cursor unchanged."msg": move cursor to message area.(default: "msg")numberIfTRUE, returnaNumber when gettinga single character.IfFALSE, the return valueis alwaysconverted toa String, and an emptyString (instead of 0)is returned whenno characteris available.(default:TRUE)simplifyIfTRUE, include modifiers in thecharacter if possible. E.g., returnthe same value forCTRL-I and<Tab>.IfFALSE, don't include modifiers inthe character.(default:TRUE)When the user clicksa mouse button, the mouse event will bereturned. The position can then be found inv:mouse_col,v:mouse_lnum,v:mouse_winid andv:mouse_win.getmousepos() can also be used. Mouse move events will beignored.This example positions the mouseasit would normally happen:let c = getchar()if c == "\<LeftMouse>" && v:mouse_win > 0 exe v:mouse_win .. "wincmd w" exe v:mouse_lnum exe "normal " .. v:mouse_col .. "|"endifWhen using bracketed paste only the first characterisreturned, the rest of the pasted textis dropped.xterm-bracketed-paste.Thereis no prompt, you will somehow have to make clear to theuser thata character has to be typed. The screenis notredrawn, e.g. when resizing the window. When usingapopupwindowit should work better withapopup-filter.Thereis nomapping for the character.Key codes are replaced, thus when the user presses the<Del>key you get the code for the<Del> key, not the raw charactersequence. Examples:getchar() == "\<Del>"getchar() == "\<S-Left>"This example redefines "f" to ignore case::nmap f :call FindChar()<CR>:function FindChar(): let c = nr2char(getchar()): while col('.') < col('$') - 1: normal l: if getline('.')[col('.') - 1] ==? c: break: endif: endwhile:endfunctionYou may also receive synthetic characters, suchas<CursorHold>. Often you will want to ignore this and getanother character::function GetKey(): let c = getchar(): while c == "\<CursorHold>": let c = getchar(): endwhile: return c:endfunctionReturn type:Number orStringgetcharmod()getcharmod()The resultisaNumber whichis the state of the modifiers forthe last obtained character withgetchar() or in another way.These values are added together:2shift4control8alt (meta)16meta (when it's different from ALT)32mouse double click64mouse triple click96mouse quadruple click (== 32+ 64)128command (Mac) or super (GTK)Only the modifiers that have not been included in thecharacter itself are obtained. Thus Shift-a results in "A"withouta modifier. Returns0 if no modifiers are used.Return type:Numbergetcharpos({expr})getcharpos()Get the position forString{expr}. Sameasgetpos() but thecolumn number in the returnedListisa characterindexinstead ofa byte index.Ifgetpos() returnsa very large column number, equal tov:maxcol, thengetcharpos() will return the characterindexof the last character.Example:With the cursor on'세' in line 5 with text "여보세요":getcharpos('.')returns [0, 5, 3, 0]getpos('.')returns [0, 5, 7, 0]Can also be usedasamethod:GetMark()->getcharpos()Return type: list<number>getcharsearch()getcharsearch()Return the current character search informationasa{dict}with the following entries: charcharacter previously used fora charactersearch(t,f,T, orF); emptystringif no character search has been performed forwarddirection of character search; 1 for forward,0 for backward untiltype of character search; 1 forat orTcharacter search,0 for anf orFcharacter searchThis can be useful to always have; and, searchforward/backward regardless of the direction of the previouscharacter search::nnoremap <expr> ; getcharsearch().forward ? ';' : ',':nnoremap <expr> , getcharsearch().forward ? ',' : ';'Also seesetcharsearch().Return type: dict<any>getcharstr([{expr} [,{opts}]])getcharstr()The sameasgetchar(), except that this always returnsaString, and "number" isn't allowed in{opts}.Return type:Stringgetcmdcomplpat()getcmdcomplpat()Return completionpattern of the current command-line.Only works when the command lineis being edited, thusrequires use ofc_CTRL-\_e orc_CTRL-R_=.Also seegetcmdtype(),setcmdpos(),getcmdline(),getcmdprompt(),getcmdcompltype() andsetcmdline().Returns an emptystring when completionis not defined.Return type:Stringgetcmdcompltype([{pat}])getcmdcompltype()Return the type of command-line completion using{pat}.If{pat}is omited, only works when the command lineis beingedited, thus requires use ofc_CTRL-\_e orc_CTRL-R_=.See:command-completion for the return string.Also seegetcmdtype(),setcmdpos(),getcmdline(),getcmdprompt(),getcmdcomplpat() andsetcmdline().Returns an emptystring when completionis not defined.Return type:Stringgetcmdline()getcmdline()Return the current command-line input. Only works when thecommand lineis being edited, thus requires use ofc_CTRL-\_e orc_CTRL-R_=.Example::cmap <F7> <C-\>eescape(getcmdline(), ' \')<CR>Also seegetcmdtype(),getcmdpos(),setcmdpos(),getcmdprompt() andsetcmdline().Returns an emptystring when enteringa password or usinginputsecret().Return type:Stringgetcmdpos()getcmdpos()Return the position of the cursor in the command lineasabyte count. The first columnis 1.Only works when editing the command line, thus requires use ofc_CTRL-\_e orc_CTRL-R_= or anexpression mapping.Returns0 otherwise.Also seegetcmdtype(),setcmdpos(),getcmdline(),getcmdprompt() andsetcmdline().Return type:Numbergetcmdprompt()getcmdprompt()Return the current command-line prompt when usingfunctionslikeinput() orconfirm().Only works when the command lineis being edited, thusrequires use ofc_CTRL-\_e orc_CTRL-R_=.Also seegetcmdtype(),getcmdline(),getcmdpos(),setcmdpos() andsetcmdline().Return type:Stringgetcmdscreenpos()getcmdscreenpos()Return the screen position of the cursor in the command lineasa byte count. The first columnis 1.Instead ofgetcmdpos(),it adds the prompt position.Only works when editing the command line, thus requires use ofc_CTRL-\_e orc_CTRL-R_= or anexpression mapping.Returns0 otherwise.Also seegetcmdpos(),setcmdpos(),getcmdline() andsetcmdline().Return type:Numbergetcmdtype()getcmdtype()Return the current command-line type. Possible return valuesare::normalEx command>debug mode commanddebug-mode/forward search command?backward search command@input() command-:insert or:append command=i_CTRL-R_=Only works when editing the command line, thus requires use ofc_CTRL-\_e orc_CTRL-R_= or anexpression mapping.Returns an emptystring otherwise.Also seegetcmdpos(),setcmdpos() andgetcmdline().Return type:Stringgetcmdwintype()getcmdwintype()Return the currentcommand-line-window type. Possible returnvalues are the sameasgetcmdtype(). Returns an emptystringwhen not in the command-line window.Return type:Stringgetcompletion({pat},{type} [,{filtered}])getcompletion()Returnalist of command-line completion matches. TheString{type} argumentspecifies what for. The following completiontypes are supported:arglistfile names in argumentlistaugroupautocmd groupsbufferbuffer namesbehave:behave suboptionsbreakpoint:breakadd and:breakdel suboptionscolorcolor schemescommandEx commandcmdlinecmdline-completion resultcompilercompilerscscope:cscope suboptionscustom,{func}custom completion, defined via{func}customlist,{func} custom completion, defined via{func}diff_buffer:diffget and:diffput completiondirdirectory namesdir_in_pathdirectory names in'cdpath'environmentenvironment variable nameseventautocommand eventsexpressionVimexpressionfilefile 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 oflocale -a)mapclearbuffer argumentmappingmapping namemenumenusmessages:messages suboptionsoptionoptionspackaddoptional packagepack-add namesruntime:runtime completionscriptnamessourcedscript names:scriptnamesshellcmdShell commandshellcmdlineShell command line with filename argumentssign:sign suboptionssyntaxsyntax file names'syntax'syntime:syntime suboptionstagtagstag_listfilestags, file namesuseruser namesvaruservariablesIf{pat}is an empty string, then all the matches arereturned. Otherwise only items matching{pat} are returned.Seewildcards for the use of special characters in{pat}.If the optional{filtered} flagis set to 1, then'wildignore'is applied tofilter the results. Otherwise all the matchesare returned. The'wildignorecase' option always applies.If the'wildoptions' option contains'fuzzy', then fuzzymatchingis used to get the completion matches. Otherwiseregularexpression matchingis used. Thus this functionfollows the user preference, what happens on the command line.If youdo not want this you can make'wildoptions' emptybefore callinggetcompletion() and restoreit afterwards.If{type}is "cmdline", then thecmdline-completion resultisreturned. For example, to complete the possible values aftera ":call" command:echo getcompletion('call ', 'cmdline')If there are no matches, an emptylistis returned. Aninvalid value for{type} produces an error.Can also be usedasamethod:GetPattern()->getcompletion('color')Return type: list<string>getcurpos()getcurpos([{winid}])Get the position of the cursor. Thisis like getpos('.'), butincludes an extra "curswant" item in the list: [0, lnum, col, off, curswant]The "curswant" numberis the preferred column when moving thecursor vertically. After$ commandit will bea very largenumber equal tov:maxcol. Also seegetcursorcharpos() andgetpos().The first "bufnum" itemis always zero. The byte position ofthe cursoris returned in'col'. To get the characterposition, usegetcursorcharpos().The optional{winid} argument can specify the window. It canbe thewindow number or thewindow-ID. The last knowncursor positionis returned, this may be invalid for thecurrent value of the buffer ifitis not the current window.If{winid}is invalidalist with zeroesis returned.This can be used to save and restore the cursor position:let save_cursor = getcurpos()MoveTheCursorAroundcall setpos('.', save_cursor)Note that this only works within the window. Seewinrestview() for restoring more state.Can also be usedasamethod:GetWinid()->getcurpos()Return type: list<number>getcursorcharpos([{winid}])getcursorcharpos()Sameasgetcurpos() but the column number in the returnedListisa characterindex instead ofa byte index.Example:With the cursor on'보' in line 3 with text "여보세요":getcursorcharpos()returns [0, 3, 2, 0, 3]getcurpos()returns [0, 3, 4, 0, 3]Can also be usedasamethod:GetWinid()->getcursorcharpos()Return type: list<number>getcwd([{winnr} [,{tabnr}]])getcwd()The resultisa String, whichis the name of the currentworking directory.'autochdir'is ignored.With{winnr} return the local current directory of thiswindowin the currenttab page.{winnr} can be thewindow number orthewindow-ID.If{winnr}is -1 return the name of the global workingdirectory. See alsohaslocaldir().With{winnr} and{tabnr} return the local current directory ofthewindow in the specifiedtab page. If{winnr}is -1 returnthe working directory of the tabpage.If{winnr}is zero use the current window, if{tabnr}is zerouse the current tabpage.Without any arguments, return the actual working directory ofthe current window.Return an emptystring if the arguments are invalid.Examples:" Get the working directory of the current window:echo getcwd():echo getcwd(0):echo getcwd(0, 0)" Get the working directory of window 3 in tabpage 2:echo getcwd(3, 2)" Get the global working directory:echo getcwd(-1)" Get the working directory of tabpage 3:echo getcwd(-1, 3)" Get the working directory of current tabpage:echo getcwd(-1, 0)Can also be usedasamethod:GetWinnr()->getcwd()Return type:Stringgetenv({name})getenv()Return the value of environment variable{name}. The{name}argumentisa string, withouta leading '$'. Example:myHome = getenv('HOME')When the variable does not existv:nullis returned. Thatis different froma variable set to an empty string, althoughsome systems interpret the empty valueas the variable beingdeleted. See alsoexpr-env.Can also be usedasamethod:GetVarname()->getenv()Return type:String orNumbergetfontname([{name}])getfontname()Without an argument returns the name of the normal font beingused. Like whatis used for theNormal highlight grouphl-Normal.With an argumenta checkis done whetherString{name}isavalid font name. If not then an emptystringis returned.Otherwise the actual font nameis returned, or{name} if theGUI does not support obtaining the real name.Only works when theGUIis running, thus not in yourvimrc orgvimrc file. Use theGUIEnterautocommand to use thisfunction just after theGUI has started.Note that theGTKGUI accepts any font name, thus checking fora valid name does not work.Return type:Stringgetfperm({fname})getfperm()The resultisa String, whichis the read, write, and executepermissions of the given file{fname}.If{fname} does not exist or its directory cannot be read, anemptystringis returned.The resultis 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.Ifa user does not havea given permission the flag for thisis replaced with thestring "-". Examples::echo getfperm("/etc/passwd"):echo getfperm(expand("~/.vimrc"))This will hopefully (froma security point of view) displaythestring "rw-r--r--" or even "rw-------".Can also be usedasamethod:GetFilename()->getfperm()Return type:StringFor setting permissions usesetfperm().getfsize({fname})getfsize()The resultisa Number, whichis the size in bytes of thegiven file{fname}.If{fname}isa directory,0is returned.If the file{fname} can't be found, -1is returned.If the size of{fname}is too big to fit inaNumber then -2is returned.Can also be usedasamethod:GetFilename()->getfsize()Return type:Numbergetftime({fname})getftime()The resultisa Number, whichis the last modification time ofthe given file{fname}. The valueis measuredas secondssince 1st Jan 1970, and may be passed to strftime(). See alsolocaltime() andstrftime().If the file{fname} can't be found -1is returned.Can also be usedasamethod:GetFilename()->getftime()Return type:Numbergetftype({fname})getftype()The resultisa String, whichisa description of the kind offile of the given file{fname}.If{fname} does not exist an emptystringis returned.Hereisa table over different kinds of files and theirresults:Normal file"file"Directory"dir"Symbolic link"link"Block device"bdev"Character device"cdev"Socket"socket"FIFO"fifo"All other"other"Example:getftype("/home")Note thata type suchas "link" will only be returned onsystems that support it. On some systems only "dir" and"file" are returned. OnMS-Windowsa symbolic link toadirectory returns "dir" instead of "link".Can also be usedasamethod:GetFilename()->getftype()Return type:Stringgetimstatus()getimstatus()The resultisa Number, whichisTRUE when theIME statusisactive andFALSE otherwise.See'imstatusfunc'.Return type:Numbergetjumplist([{winnr} [,{tabnr}]])getjumplist()Returns thejumplist for the specified window.Without arguments use the current window.With{winnr} only use thiswindow in the currenttab page.{winnr} can also beawindow-ID.With{winnr} and{tabnr} use thewindow in the specifiedtabpage. If{winnr} or{tabnr}is invalid, an emptylistisreturned.The returnedlist contains two entries:alist with the jumplocations and the last used jump position number in the list.Each entry in the jump locationlistisa dictionary withthe following entries:bufnrbuffer numbercolcolumn numbercoladdcolumn offset for'virtualedit'filenamefilename if availablelnumline numberCan also be usedasamethod:GetWinnr()->getjumplist()Return type: list<any>getline()getline({lnum} [,{end}])Without{end} the resultisa String, whichis line{lnum}from the current buffer. Example:getline(1)When{lnum}isaString that doesn't start withadigit,line()is called to translate theString intoa Number.To get the line under the cursor:getline(".")When{lnum}isa number smaller than 1 or bigger than thenumber of lines in the buffer, an emptystringis returned.When{end}is given the resultisaList where each itemisa line from the current buffer in the range{lnum} to{end},including line{end}.{end}is used in the same wayas{lnum}.Non-existing lines are silently omitted.When{end}is before{lnum} an emptyListis returned.Example::let start = line('.'):let end = search("^$") - 1:let lines = getline(start, end)Can also be usedasamethod:ComputeLnum()->getline()Return type: list<string> orString depending on{end}To get lines from another buffer seegetbufline() andgetbufoneline()getloclist({nr} [,{what}])getloclist()ReturnsaList with all the entries in the locationlist forwindow{nr}.{nr} can be thewindow number or thewindow-ID.When{nr}is zero the currentwindowis used.Fora locationlist window, the displayed locationlistisreturned. For an invalidwindow number{nr}, an emptylistisreturned. Otherwise, sameasgetqflist().If the optional{what} dictionary argumentis supplied, thenreturns the items listed in{what}asa dictionary. Refer togetqflist() for the supported items in{what}.In addition to the items supported bygetqflist() in{what},the following itemis supported bygetloclist():filewinidid of thewindow used to display filesfrom the location list. This fieldisapplicable only when called fromalocationlist window. Seelocation-list-file-window for moredetails.ReturnsaDictionary with default values if thereis nolocationlist for thewindow{nr}.Returns an emptyDictionary ifwindow{nr} does not exist.Examples (See alsogetqflist-examples)::echo getloclist(3, {'all': 0}):echo getloclist(5, {'filewinid': 0})Return type: list<dict<any>> or list<any>getmarklist([{buf}])getmarklist()Without the{buf} argument returnsaList with informationabout all the global marks.markIf the optional{buf} argumentis specified, returns thelocal marks defined in buffer{buf}. For the use of{buf},seebufname(). If{buf}is invalid, an emptylistisreturned.Each item in the returnedListisaDict with the following:mark name of themark prefixed by "'" posaList with the position of the mark:[bufnum, lnum, col, off] Refer togetpos() for more information. file file nameRefer togetpos() for getting information abouta specificmark.Can also be usedasamethod:GetBufnr()->getmarklist()Return type: list<dict<any>> or list<any>getmatches([{win}])getmatches()ReturnsaList with all matches previously defined for thecurrentwindow bymatchadd() and the:match commands.getmatches()is useful in combination withsetmatches(),assetmatches() can restorealist of matches saved bygetmatches().If{win}is specified, use thewindow with this number orwindow ID instead of the current window. If{win}is invalid,an emptylistis 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 mReturn type: list<dict<any>> or list<any>getmousepos()getmousepos()ReturnsaDictionary with the last known position of themouse. This can be used inamapping fora mouse click or inafilter ofapopup window. The items are:screenrowscreen rowscreencolscreen columnwinidWindow ID of the clickwinrowrow inside "winid"wincolcolumn inside "winid"linetext line inside "winid"columntext column inside "winid"coladdoffset (in screen columns) from thestart of the clicked charAll numbers are 1-based.If not overa window, e.g. when in the command line or withintabpanel, then only "screenrow" and "screencol" are valid,the others are zero.When on the status line belowawindow or the verticalseparator right ofa window, the "line" and "column" valuesare zero.When the positionis after the text then "column"is thelength of the text in bytes plus one.If the mouseis overapopupwindow then thatwindowis used.When usinggetchar() the Vimvariablesv:mouse_lnum,v:mouse_col andv:mouse_winid also provide these values.Return type: dict<number>getmouseshape()getmouseshape()Returns the name of the currently showing mouse pointer.When the+mouseshape featureis not supported or the shapeis unknown an emptystringis returned.This functionis mainly intended for testing.Return type:Stringgetpid()getpid()ReturnaNumber whichis the process ID of the Vim process.OnUnix andMS-Windows thisisaunique number, until Vimexits.Return type:Numbergetpos({expr})getpos()Get the position forString{expr}.The accepted values for{expr} are:E1209. The cursor position.$ The last line in the current buffer. 'x Position ofmarkx (if themarkis not set,0is returned for all values). w0 First line visible in currentwindow (one if the display isn't updated, e.g. in silentEx mode). w$ Last line visible in currentwindow (thisis oneless than "w0" if no lines are visible).v When not inVisual mode, returns the cursor position. InVisual mode, returns the otherend of theVisual area.A good way to think about thisis that inVisual mode "v" and "." complement each other. While "." refers to the cursor position, "v" refers to wherev_o would move the cursor. Asa result, you can use "v" and "." together to work on all ofa selection incharacterwiseVisual mode. If the cursorisat theend ofacharacterwiseVisual area, "v" refers to the start of the sameVisual area. And if the cursorisat the start ofacharacterwiseVisual area, "v" refers to theend of the sameVisual area. "v" differs from'< and'> in that it's updated right away.Note thatamark in another file can be used. The line numberthen applies to another buffer.The resultisaList with four numbers: [bufnum, lnum, col, off]"bufnum"is zero, unlessamark like'0 or'Ais used, thenitis the buffer number of the mark."lnum" and "col" are the position in the buffer. The firstcolumnis 1.The "off" numberis zero, unless'virtualedit'is used. Thenitis the offset in screen columns from the start of thecharacter. E.g.,a position withina<Tab> or after the lastcharacter.For getting the cursor position seegetcurpos().The column number in the returnedListis the byte positionwithin the line. To get the character position in the line,usegetcharpos().Note that for'< and'>Visual mode matters: whenitis "V"(visual line mode) the column of'<is zero and the column of'>isa large number equal tov:maxcol.A very large column number equal tov:maxcol can be returned,in whichcaseit means "after theend of the line".If{expr}is invalid, returnsalist with all zeros.This can be used to save and restore the position ofa mark:let save_a_mark = getpos("'a")...call setpos("'a", save_a_mark)Also seegetcharpos(),getcurpos() andsetpos().Can also be usedasamethod:GetMark()->getpos()Return type: list<number>getqflist([{what}])getqflist()ReturnsaList with all the currentquickfix errors. Eachlist itemisa dictionary with these entries:bufnrnumber of buffer that has the file name, usebufname() to get the namemodulemodule namelnumline number in the buffer (first lineis 1)end_lnumend of line number if the itemis multilinecolcolumn number (first columnis 1)end_colend of column number if the item has rangevcolTRUE: "col"is visual columnFALSE: "col"is byteindexnrerror numberpatternsearchpattern used to locate the errortextdescription of the errortypetype of the error, 'E', '1', etc.validTRUE: recognized error messageuser_datacustom data associated with the item, can beany type.When thereis no errorlist or it's empty, an emptylistisreturned.Quickfixlist entries witha non-existing buffernumber are returned with "bufnr" set to zero (Note: somefunctions accept buffer number zero for the alternate buffer,you may need to explicitly check for zero).Useful application: Findpattern matches in multiple files anddo something with them::vimgrep /theword/jg *.c:for d in getqflist(): echo bufname(d.bufnr) ':' d.lnum '=' d.text:endforIf the optional{what} dictionary argumentis supplied, thenreturns only the items listed in{what}asa dictionary. Thefollowingstring items are supported in{what}:changedtickget the total number of changes madeto thelistquickfix-changedtickcontextget thequickfix-contextefmerrorformat to use when parsing "lines". Ifnot present, then the'errorformat' optionvalueis used.idget information for thequickfixlist withquickfix-ID; zero means the id for thecurrentlist or thelist specified by "nr"idxget information for thequickfix entryat thisindex in thelist specified by'id' or'nr'.If set to zero, then uses the current entry.Seequickfix-indexitemsquickfixlist entrieslinesparsealist of lines using'efm' and returnthe resulting entries. OnlyaList typeisaccepted. The currentquickfixlistis notmodified. Seequickfix-parse.nrget information for thisquickfix list; zeromeans the currentquickfixlist and "$" meansthe lastquickfixlistqfbufnr number of the buffer displayed in thequickfixwindow. Returns0 if thequickfix bufferisnot present. Seequickfix-buffer.sizenumber of entries in thequickfixlisttitleget thelist titlequickfix-titlewinidget thequickfixwindow-IDallall of the abovequickfix propertiesNon-string items in{what} are ignored. To get the value ofaparticular item, setit to zero.If "nr"is not present then the currentquickfixlistis used.If both "nr" anda non-zero "id" are specified, then thelistspecified by "id"is used.To get the number of lists in thequickfix stack, set "nr" to"$" in{what}. The "nr" value in the returned dictionarycontains thequickfix stack size.When "lines"is specified, all the other items except "efm"are ignored. The returned dictionary contains the entry"items" with thelist of entries.The returned dictionary contains the following entries:changedticktotal number of changes made to thelistquickfix-changedtickcontextquickfixlist context. Seequickfix-contextIf not present, set to "".idquickfixlist IDquickfix-ID. If notpresent, set to 0.idxindex of thequickfix entry in the list. If notpresent, set to 0.itemsquickfixlist entries. If not present, set toan empty list.nrquickfixlist number. If not present, set to0qfbufnrnumber of the buffer displayed in thequickfixwindow. If not present, set to 0.sizenumber of entries in thequickfix list. If notpresent, set to 0.titlequickfixlist title text. If not present, setto "".winidquickfixwindow-ID. If not present, set to0Examples (See alsogetqflist-examples)::echo getqflist({'all': 1}):echo getqflist({'nr': 2, 'title': 1}):echo getqflist({'lines' : ["F1:10:L10"]})Return type: list<dict<any>> or list<any>getreg([{regname} [, 1 [,{list}]]])getreg()The resultisa String, whichis the contents ofregister{regname}. Example::let cliptext = getreg('*')Whenregister{regname} was not set the resultis an emptystring.The{regname} argumentmust bea string.E1162getreg('=') returns the last evaluated value of theexpressionregister. (For use in maps.)getreg('=', 1) returns theexpression itself, so thatit canbe restored withsetreg(). For otherregisters the extraargumentis ignored, thus you can always give it.If{list}is present andTRUE, the result typeis changedtoList. Eachlist itemis one text line. Useit if you careabout zero bytes possibly present inside register: withoutthird argument both NLs and zero bytes are representedas NLs(seeNL-used-for-Nul).When theregister was not set an emptylistis returned.If{regname}is "", the unnamedregister'"'is used.If{regname}is not specified,v:registeris used.InVim9-script{regname}must be one character.Can also be usedasamethod:GetRegname()->getreg()Return type:String or list<string> depending on{list}getreginfo([{regname}])getreginfo()Returns detailed information aboutregister{regname}asaDictionary with the following entries:regcontentsList of lines contained inregister{regname}, likegetreg({regname}, 1, 1).regtypethe type ofregister{regname},as ingetregtype().isunnamedBoolean flag,v:true if thisregisteris currently pointed to by the unnamedregister.points_tofor the unnamed register, gives thesingleletter name of theregistercurrently pointed to (seequotequote).For example, afterdeletinga linewithdd, this field will be "1",whichis theregister that got thedeleted text.The{regname} argumentisa string. If{regname}is invalidor not set, an emptyDictionary will be returned.If{regname}is "" or "@", the unnamedregister'"'is used.If{regname}is not specified,v:registeris used.The returnedDictionary can be passed tosetreg().InVim9-script{regname}must be one character.Can also be usedasamethod:GetRegname()->getreginfo()Return type: dict<any>getregion({pos1},{pos2} [,{opts}])getregion()Returns thelist of strings from{pos1} to{pos2} fromabuffer.{pos1} and{pos2}must both beLists with four numbers.Seegetpos() for the format of the list. It's possibleto specify positions froma different buffer, but pleasenote the limitationsatgetregion-notes.The optional argument{opts}isaDict and supports thefollowing items:typeSpecify the region's selection type.Seegetregtype() for possible values,except that the width can be omittedand an emptystring cannot be used.(default: "v")exclusiveIfTRUE, useexclusive selectionfor theend position.(default: follow'selection')You can get the last selection type byvisualmode().IfVisual modeis active, usemode() to get theVisual mode(e.g., ina:vmap).This functionis useful to get textstarting and ending indifferent columns, suchasacharacterwise-visual selection.getregion-notesNote that:- Order of{pos1} and{pos2} doesn't matter,it will always return content from the upper left position to the lower right position.- If'virtualedit'is enabled and the regionis past theend of the lines, resulting lines are padded with spaces.- If the regionis blockwise andit starts or ends in the middle ofa multi-cell character,itis not included but its selected partis substituted with spaces.- If{pos1} and{pos2} are not in the same buffer, an emptylistis returned.-{pos1} and{pos2}must belong toabufloaded() buffer.- Itis evaluated in currentwindow context, which makesa difference if the bufferis displayed inawindow with different'virtualedit' or'list' values.- When specifying anexclusive selection and{pos1} and{pos2} are equal, the returnedlist containsa single characteras if selectionis inclusive, to match the behavior of an emptyexclusive selection inVisual mode.Examples::xnoremap <CR>\ <Cmd>echow getregion(\ getpos('v'), getpos('.'), #{ type: mode() })<CR>Can also be usedasamethod:getpos('.')->getregion(getpos("'a"))Return type: list<string>getregionpos({pos1},{pos2} [,{opts}])getregionpos()Sameasgetregion(), but returnsalist of positionsdescribing the buffer text segments bound by{pos1} and{pos2}.The segments area pair of positions for every line:[[{start_pos}, {end_pos}], ...]The positionisaList with four numbers: [bufnum, lnum, col, off]"bufnum"is the buffer number."lnum" and "col" are the position in the buffer. The firstcolumnis 1.If the "off" number ofastarting positionis non-zero,itisthe offset in screen columns from the start of the character.E.g.,a position withina<Tab> or after the last character.If the "off" number of an ending positionis non-zero,itisthe offset of the character's first cell not included in theselection, otherwise all its cells are included.Apart from theoptions supported bygetregion(),{opts} alsosupports the following:eolIfTRUE, indicate positions beyondtheend ofa line with "col" valuesone more than the length of the line.IfFALSE, positions are limitedwithin their lines, and ifa lineisempty or the selectionis entirelybeyond theend ofa line,a "col"value of0is used for both positions.(default:FALSE)Can also be usedasamethod:getpos('.')->getregionpos(getpos("'a"))For an example, see the highlight-yankplugin52.6Return type: list<list<list<number>>>getregtype([{regname}])getregtype()The resultisa String, whichis type ofregister{regname}.The value will be one of: "v"forcharacterwise text "V"forlinewise text "<CTRL-V>{width}"forblockwise-visual text ""for an empty or unknownregister<CTRL-V>is one character with value 0x16.The{regname} argumentisa string. If{regname}is "", theunnamedregister'"'is used. If{regname}is not specified,v:registeris used.InVim9-script{regname}must be one character.Can also be usedasamethod:GetRegname()->getregtype()Return type:Stringgetscriptinfo([{opts}])getscriptinfo()ReturnsaList with information about all the sourced Vimscripts in the order they were sourced, like what:scriptnames shows.The optionalDict argument{opts} supports the followingoptional items: nameScript name match pattern. If specified,and "sid"is not specified, information aboutscripts witha name that match thepattern"name" are returned. sidScript ID<SID>. If specified, onlyinformation about thescript with ID "sid"isreturned and "name"is ignored.Each item in the returnedListisaDict with the followingitems:autoloadSet toTRUE forascript that was used with`import autoload` but was not actually sourcedyet (seeimport-autoload).functionsList ofscript-local function names defined inthe script. Present only whena particularscriptis specified using the "sid" item in{opts}. nameVimscript file name. sidScript ID<SID>. sourcedScript ID of the actually sourcedscript thatthisscript name links to, if any, otherwisezerovariablesA dictionary with thescript-local variables.Present only whena particularscriptisspecified using the "sid" item in{opts}.Note that thisisa copy, the value ofscript-localvariables cannot be changed usingthis dictionary. versionVimscript version(scriptversion)Examples::echo getscriptinfo({'name': 'myscript'}):echo getscriptinfo({'sid': 15})[0].variablesReturn type: list<dict<any>>getstacktrace()getstacktrace()Returns the current stack trace of Vim scripts.Stack traceisaList, of which each itemisaDictionarywith the following items: funcrefThe funcref if the stackisata function,otherwise this itemis omitted. eventThestring of the event description if thestackisat an autocmd event, otherwise thisitemis omitted. lnumThe line number in thescript on the stack. filepathThe file path of thescript on the stack.Return type: list<dict<any>>gettabinfo([{tabnr}])gettabinfo()If{tabnr}is not specified, then information about all thetab pagesis returnedasaList. EachList itemisaDictionary. Otherwise,{tabnr}specifies thetab pagenumber and information about that oneis returned. If thetabpage does not exist an emptyListis returned.EachList itemisaDictionary with the following entries:tabnrtab page number.variablesareference to the dictionary withtabpage-localvariableswindowsList ofwindow-IDs in thetab page.Can also be usedasamethod:GetTabnr()->gettabinfo()Return type: list<dict<any>>gettabvar({tabnr},{varname} [,{def}])gettabvar()Get the value ofa tab-local variable{varname} intab page{tabnr}.t:varTabs are numberedstarting with one.The{varname} argumentisa string. When{varname}is emptyadictionary with all tab-localvariablesis returned.Note that the name without "t:"must be used.When thetab or variable doesn't exist{def} or an emptystringis returned, thereis no error message.Can also be usedasamethod:GetTabnr()->gettabvar(varname)Return type: any, depending on{varname}gettabwinvar({tabnr},{winnr},{varname} [,{def}])gettabwinvar()Get the value of window-local variable{varname} inwindow{winnr} intab page{tabnr}.The{varname} argumentisa string. When{varname}is emptyadictionary with all window-localvariablesis returned.When{varname}is equal to "&" get the values of allwindow-localoptions inaDictionary.Otherwise, when{varname} starts with "&" get the value ofawindow-local option.Note that{varname}must be the name without "w:".Tabs are numberedstarting with one. For the currenttabpageusegetwinvar().{winnr} can be thewindow number or thewindow-ID.When{winnr}is zero the currentwindowis used.This also works fora global option, buffer-local option andwindow-local option, butit doesn't work fora global variableor buffer-local variable.When the tab,window or variable doesn't exist{def} or anemptystringis returned, thereis no error message.Examples::let list_is_on = gettabwinvar(1, 2, '&list'):echo "myvar = " .. gettabwinvar(3, 1, 'myvar')To obtain all window-localvariables use:gettabwinvar({tabnr}, {winnr}, '&')Can also be usedasamethod:GetTabnr()->gettabwinvar(winnr, varname)Return type: any, depending on{varname}gettagstack([{winnr}])gettagstack()The resultisa Dict, whichis thetag stack ofwindow{winnr}.{winnr} can be thewindow number or thewindow-ID.When{winnr}is not specified, the currentwindowis used.Whenwindow{winnr} doesn't exist, an emptyDictis returned.The returned dictionary contains the following entries:curidxCurrentindex in the stack. Whenattop of the stack, set to (length+ 1).Index of bottom of the stackis 1.itemsList of items in the stack. Each itemisa dictionary containing theentries described below.lengthNumber of entries in the stack.Each item in the stackisa dictionary with the followingentries:bufnrbuffer number of the current jumpfromcursor position before thetag jump.Seegetpos() for the format of thereturned list.matchnrcurrent matchingtag number. Used whenmultiple matchingtags are found foraname.tagnamename of thetagSeetagstack for more information about thetag stack.Can also be usedasamethod:GetWinnr()->gettagstack()Return type: dict<any>gettext({text} [,{package}])gettext()TranslateString{text} if possible.Thisis intended for use in Vim scripts. When generatingmessage translations the{text}is extracted byxgettext,the translator can add translatedmessages into the .po fileand Vim will lookup the translation whengettext()is called.For{text} double quoted strings are preferred, becausexgettext does not support single quoted escaped text.When the{package}is specified, the translationis looked upfor that specific package. Thisis mainly required forthird-party Vim scripts. You need to specifya path to thetranslations with thebindtextdomain() function beforeusing thegettext() function.Return type:Stringgetwininfo([{winid}])getwininfo()Returns information aboutwindowsasaList with Dictionaries.If{winid}is given Information about thewindow with that IDis returned,asaList with one item. If thewindow does notexist the resultis an empty list.Without{winid} information about all thewindows in all thetab pagesis returned.EachList itemisaDictionary with the following entries:botlinelast complete displayed buffer linebufnrnumber of buffer in thewindowheightwindow height (excluding winbar)leftcolfirst column displayed; only used when'wrap'is offloclist1 if showinga locationlist{only with the +quickfix feature}quickfix1 ifquickfix or locationlistwindow{only with the +quickfix feature}terminal1 ifaterminalwindow{only with the +terminal feature}tabnrtab page numbertoplinefirst displayed buffer linevariablesareference to the dictionary withwindow-localvariableswidthwindow widthwinbar1 if thewindow hasa toolbar,0otherwisewincolleftmost screen column of the window;"col" fromwin_screenpos()textoffnumber of columns occupied by any'foldcolumn','signcolumn' and linenumber in front of the textwinidwindow-IDwinnrwindow numberwinrowtopmost screen line of the window;"row" fromwin_screenpos()Can also be usedasamethod:GetWinnr()->getwininfo()Return type: list<dict<any>>getwinpos([{timeout}])getwinpos()The resultisaList with two numbers, the result ofgetwinposx() andgetwinposy() combined:[x-pos, y-pos]{timeout} can be used to specify how long to wait in msec fora response from the terminal. When omitted 100 msecis used.Usea longer time fora remote terminal.When usinga valueless than 10 and no responseis receivedwithin that time,a previously reported positionis returned,if available. This can be used to poll for the position anddo some work in the meantime:while 1 let res = getwinpos(1) if res[0] >= 0 break endif " Do some work hereendwhileCan also be usedasamethod:GetTimeout()->getwinpos()Return type: list<number>getwinposx()getwinposx()The resultisa Number, whichis theX coordinate in pixels ofthe left hand side of theGUI Vim window. Also works for anxterm (usesa timeout of 100 msec).The result will be -1 if the informationis not available(e.g. on the Wayland backend).The value can be used with:winpos.Return type:Numbergetwinposy()getwinposy()The resultisa Number, whichis theY coordinate in pixels ofthe top of theGUI Vim window. Also works for an xterm (usesa timeout of 100 msec).The result will be -1 if the informationis not available(e.g. on the Wayland backend).The value can be used with:winpos.Return type:Numbergetwinvar({winnr},{varname} [,{def}])getwinvar()Likegettabwinvar() for the current tabpage.Examples::let list_is_on = getwinvar(2, '&list'):echo "myvar = " .. getwinvar(1, 'myvar')Can also be usedasamethod:GetWinnr()->getwinvar(varname)Return type: any, depending on{varname}glob({expr} [,{nosuf} [,{list} [,{alllinks}]]])glob()Expand the filewildcards in{expr}. Seewildcards for theuse of special characters.Unless the optional{nosuf} argumentis given andisTRUE,the'suffixes' and'wildignore'options apply: Names matchingone of the patterns in'wildignore' will be skipped and'suffixes' affect the ordering of matches.'wildignorecase' always applies.When{list}is present anditisTRUE the resultisaListwith all matching files. The advantage of usingaList is,you also get filenames containing newlines correctly.Otherwise the resultisaString and when there are severalmatches, they are separated by<NL> characters.If the expansion fails, the resultis an emptyString or List.You can also usereaddir() if you need todo complicatedthings, suchas limiting the number of matches.A name fora non-existing fileis not included.A symboliclinkis only included ifit points to an existing file.However, when the{alllinks} argumentis present anditisTRUE then all symbolic links are included.For most systems backticks can be used to get files names fromany external command. Example::let tagfiles = glob("`find . -name tags -print`"):let &tags = substitute(tagfiles, "\n", ",", "g")The result of the program inside the backticks should be oneitem per line. Spaces inside an item are allowed.Seeexpand() for expanding special Vim variables. Seesystem() for getting the raw output of an external command.Can also be usedasamethod:GetExpr()->glob()Return type:String or list<string> or list<any> dependingon{list}glob2regpat({string})glob2regpat()Converta file pattern,as used by glob(), intoa searchpattern. The result can be used to match withastring thatisa file name. E.g.if filename =~ glob2regpat('Make*.mak')Thisis equivalent to:if filename =~ '^Make.*\.mak$'When{string}is an emptystring the resultis "^$", match anempty string.Note that the result depends on the system. OnMS-Windowsabackslash usually meansa path separator.Can also be usedasamethod:GetExpr()->glob2regpat()Return type:Stringglobpath()globpath({path},{expr} [,{nosuf} [,{list} [,{alllinks}]]])Performglob() forString{expr} on all directories in{path}and concatenate the results. Example::echo globpath(&rtp, "syntax/c.vim"){path}isa comma-separatedlist of directory names. Eachdirectory nameis prepended to{expr} and expanded like withglob().A path separatoris inserted when needed.To adda comma insidea directory nameescapeit withabackslash.Note that onMS-Windowsa directory may haveatrailing backslash, removeit if youputa comma after it.If the expansion fails for one of the directories, thereis noerror message.Unless the optional{nosuf} argumentis given andisTRUE,the'suffixes' and'wildignore'options apply: Names matchingone of the patterns in'wildignore' will be skipped and'suffixes' affect the ordering of matches.When{list}is present anditisTRUE the resultisaListwith all matching files. The advantage of usingaList is, youalso get filenames containing newlines correctly. Otherwisethe resultisaString and when there are several matches,they are separated by<NL> characters. Example::echo globpath(&rtp, "syntax/c.vim", 0, 1){alllinks}is usedas withglob().The "**" item can be used to search ina directory tree.For example, to find all "README.txt" files in the directoriesin'runtimepath' and below::echo globpath(&rtp, "**/README.txt")Upwards search and limiting the depth of "**"is notsupported, thus using'path' will not always work properly.Can also be usedasamethod, the baseis passedas thesecond argument:GetExpr()->globpath(&rtp)Return type:String or list<string> or list<any> dependingon{list}has({feature} [,{check}])has()When{check}is omitted oris zero: The resultisa Number,whichis 1 if the feature{feature}is supported, zerootherwise. The{feature} argumentisa string,caseisignored. Seefeature-list below.When{check}is present and not zero: The resultisa Number,whichis 1 if the feature{feature} could ever be supported,zero otherwise. Thisis useful to check fora typo in{feature} and to detect dead code. Keep in mind that an olderVim version will not know abouta feature added later andfeatures that have been abandoned will not be known by thecurrent Vim version.Also seeexists() andexists_compiled().Note that to skip code that hasasyntax error when thefeatureis not available, Vim may skip the rest of the lineand missa followingendif. Thereforeput theendif onaseparate line:if has('feature') let x = this->breaks->without->the->featureendifIf theendif would be moved to the second lineas "| endif"itwould not be found.Return type:Numberhas_key({dict},{key})has_key()The resultisa Number, whichisTRUE ifDictionary{dict}has an entry with key{key}.FALSE otherwise.The{key} argumentisa string. InVim9scripta numberisalso accepted (and converted toa string) but no other types.In legacyscript the usual automatic conversion tostringisdone.Can also be usedasamethod:mydict->has_key(key)Return type:Numberhaslocaldir([{winnr} [,{tabnr}]])haslocaldir()The resultisa Number: 1 when thewindow has seta local directory via:lcd 2 when thetab-page has seta local directory via:tcd0 otherwise.Without arguments use the current window.With{winnr} use thiswindow in the currenttab page.With{winnr} and{tabnr} use thewindow in the specifiedtabpage.{winnr} can be thewindow number or thewindow-ID.If{winnr}is -1itis ignored and only thetabpageis used.Return0 if the arguments are invalid.Examples:if haslocaldir() == 1 " window local directory caseelseif haslocaldir() == 2 " tab-local directory caseelse " global directory caseendif" current window:echo haslocaldir():echo haslocaldir(0):echo haslocaldir(0, 0)" window n in current tab page:echo haslocaldir(n):echo haslocaldir(n, 0)" window n in tab page m:echo haslocaldir(n, m)" tab page m:echo haslocaldir(-1, m)Can also be usedasamethod:GetWinnr()->haslocaldir()Return type:Numberhasmapto({what} [,{mode} [,{abbr}]])hasmapto()The resultisa Number, whichisTRUE if thereisamappingthat contains{what} in somewhere in the rhs (whatitismapped to) and thismapping exists in one of the modesindicated by{mode}.The arguments{what} and{mode} are strings.When{abbr}is there anditisTRUE useabbreviationsinstead of mappings. Don't forget to specifyInsert and/orCommand-line mode.Both the global mappings and the mappings local to the currentbuffer are checked fora match.If no matchingmappingis foundFALSEis returned.The following characters are recognized in{mode}:nNormal modevVisual andSelect modexVisual modesSelect modeoOperator-pending modeiInsert modelLanguage-Argument("r", "f", "t", etc.)cCommand-line modeWhen{mode}is omitted, "nvo"is used.This functionis useful to check ifamapping already existstoa function ina Vim script. Example::if !hasmapto('\ABCdoit'): map <Leader>d \ABCdoit:endifThis installs themapping to "\ABCdoit" only if there isn'talreadyamapping to "\ABCdoit".Can also be usedasamethod:GetRHS()->hasmapto()Return type:Numberhistadd({history},{item})histadd()Add theString{item} to thehistory{history} which can beone of:hist-names"cmd" or ":" command linehistory"search" or "/" searchpatternhistory"expr" or "=" typedexpressionhistory"input" or "@" input linehistory"debug" or ">" debug commandhistoryempty the current or last usedhistoryThe{history}string does not need to be the whole name, onecharacteris sufficient.If{item} does already exist in the history,it will beshifted to become the newest entry.The resultisa Number:TRUE if the operation was successful,otherwiseFALSEis returned.Example::call histadd("input", strftime("%Y %b %d")):let date=input("Enter date: ")This functionis not available in thesandbox.Can also be usedasamethod, the baseis passedas thesecond argument:GetHistory()->histadd('search')Return type:Numberhistdel({history} [,{item}])histdel()Clear{history}, i.e. delete all its entries. Seehist-namesfor the possible values of{history}.If the parameter{item} evaluates toa String,itis usedasaregular expression. All entries matching thatexpression willbe removed from thehistory (if there are any).Upper/lowercasemust match, unless "\c"is used/\c.If{item} evaluates toa Number,it will be interpretedasan index, see:history-indexing. The respective entry willbe removed ifit exists.The resultisTRUE fora successful operation, otherwiseFALSEis returned.Examples:Clearexpressionregister history::call histdel("expr")Remove all entriesstarting with "*" from the search history::call histdel("/", '^\*')The following three are equivalent::call histdel("search", histnr("search")):call histdel("search", -1):call histdel("search", '^' .. histget("search", -1) .. '$')To delete the last searchpattern and use the last-but-one forthe "n" command and'hlsearch'::call histdel("search", -1):let @/ = histget("search", -1)Can also be usedasamethod:GetHistory()->histdel()Return type:Numberhistget({history} [,{index}])histget()The resultisa String, the entry withNumber{index} from{history}. Seehist-names for the possible values of{history}, and:history-indexing for{index}. If thereisno such entry, an emptyStringis returned. When{index}isomitted, the most recent item from thehistoryis used.Examples:Redo the second last search from history.:execute '/' .. histget("search", -2)Define anEx command ":H{num}" that supports re-execution ofthe{num}th entry from the output of:history.:command -nargs=1 H execute histget("cmd", 0+<args>)Can also be usedasamethod:GetHistory()->histget()Return type:Stringhistnr({history})histnr()The resultis theNumber of the current entry in{history}.Seehist-names for the possible values of{history}.If an error occurred, -1is returned.Example::let inp_index = histnr("expr")Can also be usedasamethod:GetHistory()->histnr()Return type:Numberhlexists({name})hlexists()The resultisa Number, whichisTRUE ifa highlight groupcalled{name} exists. Thisis when the group has beendefined in some way. Not necessarily when highlighting hasbeen defined for it,it may also have been used forasyntaxitem.highlight_exists()Obsolete name: highlight_exists().Can also be usedasamethod:GetName()->hlexists()Return type:Numberhlget([{name} [,{resolve}]])hlget()ReturnsaList of all the highlight group attributes. If theoptional{name}is specified, then returnsaList with onlythe attributes of the specified highlight group. Returns anemptyList if the highlight group{name}is not present.If the optional{resolve} argumentis set tov:true and thehighlight group{name}is linked to another group, then thelinkis resolved recursively and the attributes of theresolved highlight group are returned.Each entry in the returnedListisaDictionary with thefollowing items:clearedboolean flag, set tov:true if the highlightgroup attributes are cleared or not yetspecified. Seehighlight-clear.ctermcterm attributes. Seehighlight-cterm.ctermbgcterm background color.Seehighlight-ctermbg.ctermfgcterm foreground color.Seehighlight-ctermfg.ctermulctermunderline color. Seehighlight-ctermul.defaultboolean flag, set tov:true if the highlightgroup linkisa default link. Seehighlight-default.fonthighlight group font. Seehighlight-font.guigui attributes. Seehighlight-gui.guibggui background color. Seehighlight-guibg.guifggui foreground color. Seehighlight-guifg.guispgui special color. Seehighlight-guisp.idhighlight group ID.linkstolinked highlight group name.See:highlight-link.namehighlight group name. Seegroup-name.startstartterminal keycode. Seehighlight-start.stopstopterminal keycode. Seehighlight-stop.termterm attributes. Seehighlight-term.The'term','cterm' and'gui' items in the aboveDictionaryhavea dictionary value with the following optionalbooleanitems:'bold','standout','underline','undercurl','italic','reverse','inverse' and'strikethrough'.Example(s)::echo hlget():echo hlget('ModeMsg'):echo hlget('Number', v:true)Can also be usedasamethod:GetName()->hlget()Return type: list<dict<any>>hlset({list})hlset()Creates or modifies the attributes ofaList of highlightgroups. Each item in{list}isa dictionary containing theattributes ofa highlight group. Seehlget() for thelist ofsupported items in this dictionary.In addition to the items described inhlget(), the followingadditional items are supported in the dictionary:forceboolean flag to force the creation ofa link for an existing highlight groupwith attributes.The highlight groupis identified using the'name' item andthe'id' item (if supplied)is ignored. Ifa highlight groupwitha specified name doesn't exist, thenitis created.Otherwise the attributes of an existing highlight group aremodified.If an empty dictionary valueis used for the'term' or'cterm'or'gui' entries, then the corresponding attributes arecleared. If the'cleared' itemis set to v:true, then all theattributes of the highlight group are cleared.The'linksto' item can be used to linka highlight group toanother highlight group. See:highlight-link.Returns zero for success, -1 for failure.Example(s):" add bold attribute to the Visual highlight group:call hlset([#{name: 'Visual',\ term: #{reverse: 1 , bold: 1}}]):call hlset([#{name: 'Type', guifg: 'DarkGreen'}]):let l = hlget():call hlset(l)" clear the Search highlight group:call hlset([#{name: 'Search', cleared: v:true}])" clear the 'term' attributes for a highlight group:call hlset([#{name: 'Title', term: {}}])" create the MyHlg group linking it to DiffAdd:call hlset([#{name: 'MyHlg', linksto: 'DiffAdd'}])" remove the MyHlg group link:call hlset([#{name: 'MyHlg', linksto: 'NONE'}])" clear the attributes and a link:call hlset([#{name: 'MyHlg', cleared: v:true,\ linksto: 'NONE'}])Can also be usedasamethod:GetAttrList()->hlset()Return type:NumberhlID({name})hlID()The resultisa Number, whichis the ID of the highlight groupwith name{name}. When the highlight group doesn't exist,zerois 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")highlightID()Obsolete name: highlightID().Can also be usedasamethod:GetName()->hlID()Return type:Numberhostname()hostname()The resultisa String, whichis the name of the machine onwhich Vimis currently running. Machine names greater than256 characters long are truncated.Return type:Stringiconv({string},{from},{to})iconv()The resultisa String, whichis the text{string} convertedfrom encoding{from} to encoding{to}.When the conversion completely fails an emptystringisreturned. When some characters could not be converted theyare replaced with "?".The encoding names are whatever theiconv() library functioncan accept, see ":!man 3 iconv".Most conversions require Vim to be compiled with the+iconvfeature. Otherwise onlyUTF-8 to latin1 conversion and backcan be done.This can be used to displaymessages with special characters,no matter what'encoding'is set to. Write the message inUTF-8 and use:echo iconv(utf8_str, "utf-8", &enc)Note that Vim usesUTF-8 for allUnicode encodings, conversionfrom/to UCS-2is automatically changed to use UTF-8. Youcannot use UCS-2 inastring anyway, because of the NUL bytes.Can also be usedasamethod:GetText()->iconv('latin1', 'utf-8')Return type:Stringid({item})id()The resultisauniqueString associated with the{item} andnot with the{item}'s contents. Itis only valid while the{item} exists andis referenced. Itis valid only in theinstance of vim that produces the result. The whole ideaisthatid({item}) does not change if the contents of{item}changes. Thisis usefulasakey for creating an identitydictionary, rather than one based on equals.This operation does notreference{item} and thereis nofunction to convert theid to the{item}. It may be useful tohavea map ofid to{item}. The following var referenceMap: dict<any> var id = item->id() referenceMap[id] = itemprevents{item} from being garbage collected and providesaway to get the{item} from theid.{item} may bea List, Tuple, Dictionary, Object, Job,Channelor Blob. If the itemis nota permitted type, oritisanullvalue, then an emptyStringis returned.Can also be usedasamethod:GetItem()->id()Return type:Stringindent({lnum})indent()The resultisa Number, whichis indent of line{lnum} in thecurrent buffer. The indentis counted in spaces, the valueof'tabstop'is relevant.{lnum}is used just like ingetline().When{lnum}is invalid -1is returned. InVim9script anerroris given.Can also be usedasamethod:GetLnum()->indent()Return type:Numberindex({object},{expr} [,{start} [,{ic}]])index()Find{expr} in{object} and return its index. Seeindexof() for usingalambda to select the item.If{object}isaList oraTuple return the lowestindexwhere the item hasa value equal to{expr}. Thereis noautomatic conversion, so theString "4"is different from theNumber 4. And the number 4is different from theFloat 4.0.The value of'ignorecase'is not used here,case mattersasindicated by the{ic} argument.If{object}isBlob return the lowestindex where the bytevalueis equal to{expr}.If{start}is given then start lookingat the item withindex{start} (may be negative for an item relative to the end).When{ic}is given anditisTRUE, ignore case. Otherwisecasemust match.-1is returned when{expr}is not found in{object}.Example::let idx = index(words, "the"):if index(numbers, 123) >= 0Can also be usedasamethod:GetObject()->index(what)Return type:Numberindexof({object},{expr} [,{opts}])indexof()Returns theindex of an item in{object} where{expr}isv:true.{object}must beaList,aTuple oraBlob.If{object}isaList oraTuple, evaluate{expr} for eachitem in theList orTuple until theexpressionisv:trueand return theindex of this item.If{object}isaBlob evaluate{expr} for each byte in theBlob until theexpressionisv:true and return theindex ofthis byte.{expr}must beastring orFuncref.If{expr}isastring: If{object}isaList oraTuple,inside{expr}v:key has theindex of the currentList orTuple item andv:val has the value of the item. If{object}isaBlob, inside{expr}v:key has theindex of thecurrent byte andv:val has the byte value.If{expr}isaFuncrefitmust take two arguments:1. the key or theindex of the current item.2. the value of the current item.The functionmust returnTRUE if the itemis found and thesearch should stop.The optional argument{opts}isaDict and supports thefollowing items: startidxstart evaluating{expr}at the item with thisindex; may be negative for an item relative totheendReturns -1 when{expr} evaluates tov: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})Can also be usedasamethod:mylist->indexof(expr)Return type:Numberinput({prompt} [,{text} [,{completion}]])input()The resultisa String, whichis whatever the user typed onthe command-line. The{prompt} argumentis eithera promptstring, ora blankstring (for no prompt).A '\n' can be usedin the prompt to starta new line.The highlighting set with:echohlis used for the prompt.The inputis entered just likea command-line, with the sameediting commands and mappings. Thereisa separatehistoryfor lines typed for input().Example::if input("Coffee or beer? ") == "beer": echo "Cheers!":endifIf the optional{text} argumentis present and not empty, thisis used for the default reply,as if the user typed this.Example::let color = input("Color? ", "white")The optional{completion} argumentspecifies the type ofcompletion supported for the input. Withoutit completionisnot performed. The supported completion types are the sameasthat can be supplied toa user-defined command using the"-complete=" argument. Refer to:command-completion formore information. Example:let fname = input("File: ", "", "file")NOTE: This functionmust not be used inastartup file, forthe versions that only run inGUI mode (e.g., theWin32 GUI).Note: Wheninput()is called from withinamappingit willconsume remaining characters from that mapping, becauseamappingis handled like the characters were typed.Useinputsave() beforeinput() andinputrestore()afterinput() to avoid that. Another solutionis to avoidthat further characters follow in the mapping, e.g., by using:execute or:normal.Example witha mapping::nmap \x :call GetFoo()<CR>:exe "/" .. Foo<CR>:function GetFoo(): call inputsave(): let g:Foo = input("enter search pattern: "): call inputrestore():endfunctionCan also be usedasamethod:GetPrompt()->input()Return type:Stringinputdialog({prompt} [,{text} [,{cancelreturn}]])inputdialog()Likeinput(), but when theGUIis running and text dialogsare supported,adialogwindow pops up to input the text.Example: :let n = inputdialog("value for shiftwidth", shiftwidth()) :if n != "" : let &sw = n :endifWhen thedialogis cancelled{cancelreturn}is returned. Whenomitted an emptystringis returned.Hitting<Enter> works like pressing the OK button. Hitting<Esc> works like pressing the Cancel button.NOTE:Command-line completionis not supported.Can also be usedasamethod:GetPrompt()->inputdialog()Return type:Stringinputlist({textlist})inputlist(){textlist}must beaList of strings. ThisListisdisplayed, onestring per line. The user will be prompted toentera number, whichis returned.The user can also select an item by clicking onit with themouse, if the mouseis enabled in the command line ('mouse'is"a" or includes "c"). For the firststring0is returned.When clicking above the first itema negative numberisreturned. When clicking on the prompt one more than thelength of{textlist}is returned.Make sure{textlist} hasless than'lines' entries, otherwiseit won't work. It'sa good idea toput the entry numberatthe start of the string. Andputa prompt in the first item.Example:let color = inputlist(['Select color:', '1. red',\ '2. green', '3. blue'])Can also be usedasamethod:GetChoices()->inputlist()Return type:Numberinputrestore()inputrestore()Restore typeahead that was saved witha previousinputsave().Should be called the same number of timesinputsave()iscalled. Callingit more oftenis harmless though.ReturnsTRUE when thereis nothing to restore,FALSE otherwise.Return type:Numberinputsave()inputsave()Preserve typeahead (also from mappings) and clear it, so thata following prompt gets input from the user. Should befollowed bya matchinginputrestore() after the prompt. Canbe used several times, in whichcase theremust be justasmanyinputrestore() calls.ReturnsTRUE when out of memory,FALSE otherwise.Return type:Numberinputsecret({prompt} [,{text}])inputsecret()This function acts much like theinput() function with buttwo exceptions:a) the user's response will be displayedasa sequence ofasterisks("*") thereby keeping the entry secret, andb) the user's response will not be recorded on the inputhistory stack.The resultisa String, whichis whatever the user actuallytyped on the command-line in response to the issued prompt.NOTE:Command-line completionis not supported.Can also be usedasamethod:GetPrompt()->inputsecret()Return type:Stringinsert({object},{item} [,{idx}])insert()When{object}isaList oraBlobinsert{item}at the startof it.If{idx}is specifiedinsert{item} before the item withindex{idx}. If{idx}is zeroit goes before the first item, justlike omitting{idx}.A negative{idx}is also possible, seelist-index. -1 inserts just before the last item.Returns the resultingList orBlob. Examples::let mylist = insert([2, 3, 5], 1):call insert(mylist, 4, -1):call insert(mylist, 6, len(mylist))The last example can be done simpler withadd().Note that when{item}isaListitis insertedasa singleitem. Useextend() to concatenateLists.Can also be usedasamethod:mylist->insert(item)Return type:Numberinstanceof()E614E616E693instanceof({object},{class})The resultisa Number, whichisTRUE when the{object}argumentisa direct or indirect instance ofaClass,Interface, orclass:type alias specified by{class}.If{class}is varargs, the function returnsTRUE when{object}is an instance of any of the specified classes.Example:instanceof(animal, Dog, Cat)Can also be usedasamethod:myobj->instanceof(mytype)Return type:Numberinterrupt()interrupt()Interruptscript execution. It works more orless like theuser typingCTRL-C, most commands won't execute andcontrolreturns to the user. Thisis 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(): endif:endfunction:au BufWritePre * call s:check_typoname(expand('<amatch>'))Return type: voidinvert({expr})invert()Bitwise invert. The argumentis converted toa number.AList,Dict orFloat argument causes an error. Example::let bits = invert(bits)Can also be usedasamethod::let bits = bits->invert()Return type:Numberisabsolutepath({path})isabsolutepath()The resultisa Number, whichisTRUE when{path}is anabsolute path.On Unix,a pathis considered absolute whenit starts with '/'.On MS-Windows,itis considered absolute whenit starts with anoptional drive prefix andis followed bya '\' or '/'. UNC pathsare always absolute.Example:echo isabsolutepath('/usr/share/')" 1echo isabsolutepath('./foobar')" 0echo isabsolutepath('C:\Windows')" 1echo isabsolutepath('foobar')" 0echo isabsolutepath('\\remote\file')" 1Can also be usedasamethod:GetName()->isabsolutepath()Return type:Numberisdirectory({directory})isdirectory()The resultisa Number, whichisTRUE whena directorywith the name{directory} exists. If{directory} doesn'texist, or isn'ta directory, the resultisFALSE.{directory}is any expression, whichis usedasa String.Can also be usedasamethod:GetName()->isdirectory()Return type:Numberisinf({expr})isinf()Return 1 if{expr}isa positive infinity, or -1a negativeinfinity, otherwise 0.:echo isinf(1.0 / 0.0)1:echo isinf(-1.0 / 0.0)-1Can also be usedasamethod:Compute()->isinf()Return type:Numberislocked({expr})islocked()E786The resultisa Number, whichisTRUE when{expr}is thename ofa locked variable.Thestring argument{expr}must be the name ofa variable,List item orDictionary entry, not the variable itself!Example::let alist = [0, ['a', 'b'], 2, 3]:lockvar 1 alist:echo islocked('alist')" 1:echo islocked('alist[1]')" 0When{expr}isa variable that does not exist -1is returned.If{expr} usesa range,list ordictindex thatis out ofrange or does not exist you get an error message. Useexists() to check for existence.InVim9scriptit does not work for local function variables.Can also be usedasamethod:GetName()->islocked()Return type:Numberisnan({expr})isnan()ReturnTRUE if{expr}isa float with value NaN.echo isnan(0.0 / 0.0)1Can also be usedasamethod:Compute()->isnan()Return type:Numberitems({dict})items()ReturnaList with all the key-value pairs of{dict}. EachList itemisalist with two items: the key ofa{dict}entry and the value of this entry. TheListis in arbitraryorder. Also seekeys() andvalues().Example:for [key, value] in items(mydict) echo key .. ': ' .. valueendforAList,aTuple oraString argumentis also supported.In these cases,items() returnsaList with theindex and thevalueat the index.Can also be usedasamethod:mydict->items()Return type: list<list<any>> or list<any>job_functions are documented here:job-functions-detailsjoin({expr} [,{sep}])join()Join the items in{expr} together into one String.{expr} canbeaList oraTuple.When{sep}is specifieditisput in between the items. If{sep}is omitteda singlespaceis used.Note that{sep}is not addedat the end. You might want toaddit there too:let lines = join(mylist, "\n") .. "\n"String items are used as-is.Lists,Tuples andDictionaries are converted intoastring like withstring(). The opposite functionissplit().Can also be usedasamethod:mylist->join()Return type:Stringjs_decode({string})js_decode()Thisis similar tojson_decode() with these differences:-Object key namesdo not have to be in quotes.- Strings can be in single quotes.- Empty items in an array (between two commas) are allowed and result inv:none items.Can also be usedasamethod:ReadObject()->js_decode()Return type: any, depending on{varname}js_encode({expr})js_encode()Thisis similar tojson_encode() with these differences:-Object key names are not in quotes.-v:none items in an array result in an empty item between commas.For example, the Vim object:[1,v:none,{"one":1},v:none]Will be encoded as:[1,,{one:1},,]Whilejson_encode() would produce:[1,null,{"one":1},null]This encodingis valid for JavaScript. Itis more efficientthan JSON, especially when using an array with optional items.Can also be usedasamethod:GetObject()->js_encode()Return type:Stringjson_decode({string})json_decode()E491This parsesa JSON formattedstring and returns the equivalentin Vim values. Seejson_encode() for the relation betweenJSON and Vim values.The decodingis permissive:-A trailing comma in an array andobjectis ignored, e.g. "[1, 2,]"is the sameas "[1, 2]".-Integer keys are accepted in objects, e.g.{1:2}is the sameas{"1":2}.- More floating point numbers are recognized, e.g. "1." for "1.0", or "001.2" for "1.2".Special floating point values "Infinity", "-Infinity" and "NaN" (capitalization ignored) are accepted.- Leading zeroes in integer numbers are ignored, e.g. "012" for "12" or "-012" for "-12".- Capitalizationis ignored in literal names null,true or false, e.g. "NULL" for "null", "True" for "true".- Control characters U+0000 through U+001F which are not escaped in strings are accepted, e.g. "" (tab character in string) for "\t".- An empty JSONexpression or made of only spacesis accepted and results in v:none.- Backslash in an invalid 2-character sequenceescapeis ignored, e.g. "\a"is decodedas "a".-A correct surrogate pair in JSON strings should normally bea 12 character sequence suchas "\uD834\uDD1E", butjson_decode() silently accepts truncated surrogate pairs suchas "\uD834" or "\uD834\u"E938A duplicate key in an object, valid in rfc7159,is notaccepted byjson_decode()as the resultmust bea valid Vimtype, e.g. this fails:{"a":"b", "a":"c"}Can also be usedasamethod:ReadObject()->json_decode()Return type: any, depending on{varname}json_encode({expr})json_encode()Encode{expr}as JSON and return thisasa string.The encodingis specified in:https://tools.ietf.org/html/rfc7159.htmlVim values are convertedas follows:E1161Number decimal numberFloat floating point numberFloat nan"NaN"Float inf"Infinity"Float -inf"-Infinity"String in doublequotes (possibly null)Funcref not possible, errorListas an array (possibly null); whenused recursively:[]Tupleas an array (possibly null); whenused recursively:[]Dictas anobject (possibly null); whenused recursively:{}Blobas an array of the individual bytesv:false"false"v:true"true"v:none"null"v:null"null"Note that NaN and Infinity are passed onas values. Thisismissing in the JSON standard, but several implementationsdoallow it. If not then you will get an error.Ifastring contains an illegal character then the replacementcharacter 0xfffdis used.Can also be usedasamethod:GetObject()->json_encode()Return type:Stringkeys({dict})keys()ReturnaList with all the keys of{dict}. TheListis inarbitrary order. Also seeitems() andvalues().Can also be usedasamethod:mydict->keys()Return type: list<string>keytrans({string})keytrans()Turn the internal byte representation of keys intoa form thatcan be used for:map. E.g.:let xx = "\<C-Home>":echo keytrans(xx)<C-Home>Can also be usedasamethod:"\<C-Home>"->keytrans()Return type:Stringlen({expr})len()E701The resultisa Number, whichis the length of the argument.When{expr}isaString oraNumber the length in bytesisused,as withstrlen().When{expr}isaList the number of items in theListisreturned.When{expr}isaTuple the number of items in theTupleisreturned.When{expr}isaBlob the number of bytesis returned.When{expr}isaDictionary the number of entries in theDictionaryis returned.When{expr}is anObject, invokes thelen()method in theobject (if present) to get the length(object-len()).Otherwise returns zero.Can also be usedasamethod:mylist->len()Return type:Numberlibcall()E364E368libcall({libname},{funcname},{argument})Call function{funcname} in the run-time library{libname}with single argument{argument}.Thisis useful to callfunctions ina library that youespecially made to be used with Vim. Since only one argumentis possible, calling standard libraryfunctionsis ratherlimited.The resultis theString returned by the function. If thefunction returns NULL, this will appearas an emptystring ""to Vim.If the function returnsa number, use libcallnr()!If{argument}isa number,itis passed to the functionas anint; if{argument}isa string,itis passedasanull-terminated string.This function will fail inrestricted-mode.libcall() allows you to write your own 'plug-in' extensions toVim without having to recompile the program. Itis NOTameans to call system functions! If you try todo so Vim willvery probably crash.For Win32, thefunctions you writemust be placed ina DLLand use the normalC calling convention (NOT Pascal whichisused in Windows System DLLs). The functionmust take exactlyone parameter, eithera character pointer ora long integer,andmust returna character pointer or NULL. The characterpointer returnedmust point to memory that will remain validafter the function has returned (e.g. in static data in theDLL). Ifit points to allocated memory, that memory willleak away. Usinga static buffer in the function should work,it's then freed when the DLLis unloaded.WARNING: If the function returnsa non-valid pointer, Vim maycrash!This also happens if the function returnsa number,because Vim thinks it'sa pointer.ForWin32 systems,{libname} should be the filename of the DLLwithout the ".DLL" suffix.A full pathis only required ifthe DLLis not in the usual places.For Unix: When compiling your own plugins, remember that theobject codemust be compiledas position-independent ('PIC').{only inWin32 and someUnix versions, when the+libcallfeatureis present}Examples::echo libcall("libc.so", "getenv", "HOME")Can also be usedasamethod, the baseis passedas thethird argument:GetValue()->libcall("libc.so", "getenv")libcallnr()libcallnr({libname},{funcname},{argument})Just likelibcall(), but used fora function that returns anint instead ofa string.{only inWin32 on someUnix versions, when the+libcallfeatureis present}Examples::echo libcallnr("/usr/lib/libc.so", "getpid", ""):call libcallnr("libc.so", "printf", "Hello World!\n"):call libcallnr("libc.so", "sleep", 10)Can also be usedasamethod, the baseis passedas thethird argument:GetValue()->libcallnr("libc.so", "printf")Return type:Stringline({expr} [,{winid}])line()The resultisa Number, whichis the line number of the fileposition given with{expr}. The{expr} argumentisa string.Seegetpos() for accepted positions.To get the column number usecol(). To get both usegetpos().With the optional{winid} argument the values are obtained forthatwindow instead of the current window.Returns0 for invalid values of{expr} and{winid}.Examples:line(".")line number of the cursorline(".", winid)idem, in window "winid"line("'t")line number of mark tline("'" .. marker)line number of mark markerTo jump to the last known position when openinga file seelast-position-jump.Can also be usedasamethod:GetValue()->line()Return type:Numberline2byte({lnum})line2byte()Return the bytecount from the start of the buffer for line{lnum}. This includes the end-of-line character, depending onthe'fileformat' option for the current buffer. The firstline returns 1.'encoding' matters,'fileencoding'is ignored.This can also be used to get the bytecount for the line justbelow the last line:line2byte(line("$") + 1)Thisis the buffer size plus one. If'fileencoding'is emptyitis the file size plus one.{lnum}is used like withgetline(). When{lnum}is invalid, or the+byte_offsetfeature has been disabledat compile time, -1is returned.Also seebyte2line(),go and:goto.Can also be usedasamethod:GetLnum()->line2byte()Return type:Numberlispindent({lnum})lispindent()Get the amount of indent for line{lnum} according the lispindenting rules,as with'lisp'.The indentis counted in spaces, the value of'tabstop'isrelevant.{lnum}is used just like ingetline().When{lnum}is invalid -1is returned. InVim9script anerroris given.Can also be usedasamethod:GetLnum()->lispindent()Return type:Numberlist2blob({list})list2blob()ReturnaBlob concatenating all the number values in{list}.Examples:list2blob([1, 2, 3, 4])returns 0z01020304list2blob([])returns 0zReturns an emptyBlob on error. If one of the numbersisnegative or more than 255 errorE1239is given.blob2list() does the opposite.Can also be usedasamethod:GetList()->list2blob()Return type:Bloblist2str({list} [,{utf8}])list2str()Convert each number in{list} toa characterstring andconcatenates them all. Examples:list2str([32])returns " "list2str([65, 66, 67])returns "ABC"The same can be done (slowly) with:join(map(list, {nr, val -> nr2char(val)}), '')str2list() does the opposite.When{utf8}is omitted or zero, the current'encoding'is used.When{utf8}is TRUE, always returnUTF-8 characters.WithUTF-8 composing characters workas expected:list2str([97, 769])returns "á"Returns an emptystring on error.Can also be usedasamethod:GetList()->list2str()Return type:Stringlist2tuple({list})list2tuple()CreateaTuple froma shallow copy of thelist items.Examples:list2tuple([1, 2, 3])returns (1, 2, 3)tuple2list() does the opposite.This function doesn't recursively convert all theList itemsin{list} toa Tuple.Note that the items are identicalbetween thelist and the tuple,changing an item changes thecontents of both thetuple and the list.Returns an emptytuple on error.Can also be usedasamethod:GetList()->list2tuple()Return type: tuple<{type}> (depending on the givenList)listener_add({callback} [,{buf}])listener_add()Adda callback function that will be invoked when changes havebeen made to buffer{buf}.{buf} refers toa buffer name or number. For the acceptedvalues, seebufname(). When{buf}is omitted the currentbufferis used.Returnsaunique ID that can be passed tolistener_remove().The{callback}is invoked with five arguments: bufnrthe buffer that was changed startfirst changed line numberendfirst line number below the change addednumber of lines added, negative if lines weredeleted changesaList of items with details about the changesExample: func Listener(bufnr, start, end, added, changes) echo 'lines ' .. a:start .. ' until ' .. a:end .. ' changed' endfunc call listener_add('Listener', bufnr)TheList cannot be changed. Each item in "changes"isadictionary with these entries: lnumthe first line number of the changeendthe first line below the change addednumber of lines added; negative if lines weredeleted colfirst column in "lnum" that was affected bythe change; one if unknown or the whole linewas affected; thisisa byte index, firstcharacter hasa value of one.When lines are inserted (not whena lineis split, e.g. bytyping CR inInsert mode) the values are: lnumline above which the new lineis addedendequal to "lnum" addednumber of lines inserted col1When lines are deleted the values are: lnumthe first deleted lineendthe line below the first deleted line, beforethe deletion was done addednegative, number of lines deleted col1When lines are changed: lnumthe first changed lineendthe line below the last changed line added0 colfirst column witha change or 1The entries are in the order the changes were made, thus themost recent changeisat the end. The line numbers are validwhen the callbackis invoked, but later changes may make theminvalid, thus keepinga copy for later might not work.The{callback}is invoked just before the screenis updated,whenlistener_flush()is called or whena changeis beingmade that changes the linecount ina wayit causesa linenumber in thelist of changes to become invalid.The{callback}is invoked with the text locked, seetextlock. If youdo need to make changes to the buffer, useatimer todo this latertimer_start().The{callback}is not invoked when the bufferis first loaded.Use theBufReadPost autocmd event to handle the initial textofa buffer.The{callback}is also not invoked when the bufferisunloaded, use theBufUnload autocmd event for that.Returns zero if{callback} or{buf}is invalid.Can also be usedasamethod, the baseis passedas thesecond argument:GetBuffer()->listener_add(callback)Return type:Numberlistener_flush([{buf}])listener_flush()Invoke listener callbacks for buffer{buf}. If there are nopending changes then no callbacks are invoked.{buf} refers toa buffer name or number. For the acceptedvalues, seebufname(). When{buf}is omitted the currentbufferis used.Can also be usedasamethod:GetBuffer()->listener_flush()Return type:Numberlistener_remove({id})listener_remove()Removea listener previously added with listener_add().ReturnsFALSE when{id} could not be found,TRUE when{id} wasremoved.Can also be usedasamethod:GetListenerId()->listener_remove()Return type:Numberlocaltime()localtime()Return the current time, measuredas seconds since 1st Jan1970. See alsostrftime(),strptime() andgetftime().Return type:Numberlog({expr})log()Return the natural logarithm (base e) of{expr}asaFloat.{expr}must evaluate toaFloat oraNumber in the range(0, inf].Returns 0.0 if{expr}is notaFloat oraNumber.Examples::echo log(10)2.302585:echo log(exp(5))5.0Can also be usedasamethod:Compute()->log()Return type:Floatlog10({expr})log10()Return the logarithm ofFloat{expr} to base 10asaFloat.{expr}must evaluate toaFloat oraNumber.Returns 0.0 if{expr}is notaFloat oraNumber.Examples::echo log10(1000)3.0:echo log10(0.01)-2.0Can also be usedasamethod:Compute()->log10()Return type:Floatluaeval({expr} [,{expr}])luaeval()EvaluateLuaexpression{expr} and return its result convertedto Vim data structures. Second{expr} may hold additionalargument accessibleas _A inside first{expr}.Strings are returnedas they are.Booleanobjects are converted to numbers.Numbers are converted toFloat values.Dictionaries and lists obtained by vim.eval() are returnedas-is.Otherobjects are returnedas zero without any errors.Seelua-luaeval for more details.Note that ina:def function localvariables are not visibleto{expr}.Can also be usedasamethod:GetExpr()->luaeval()Return type: any, depending on{expr}{only available when compiled with the |+lua| feature}map({expr1},{expr2})map(){expr1}must beaList,String,Blob orDictionary.When{expr1}isaList orDictionary, replace eachitem in{expr1} with the result of evaluating{expr2}.ForaBlob each byteis replaced.ForaString, each character, including composingcharacters,is replaced.If the item type changes you may want to usemapnew() tocreatea newList or Dictionary. Thisis required when usingVim9 script.{expr2}must beaString orFuncref.If{expr2}isaString, inside{expr2}v:val has the valueof the current item. ForaDictionaryv:key has the keyof the current item and foraListv:key has theindex ofthe current item. ForaBlobv:key has theindex of thecurrent byte. ForaStringv:key has theindex of thecurrent character.Example::call map(mylist, '"> " .. v:val .. " <"')This puts "> " before and "<" after each item in "mylist".Note that{expr2}is the result of anexpression andis thenusedas anexpression again. Oftenitis good to usealiteral-string to avoid having to double backslashes. Youstill have to double'quotesIf{expr2}isaFuncrefitis called with two arguments:1. The key or theindex of the current item.2. the value of the current item.Witha legacyscriptlambda you don't get an error ifit onlyaccepts one argument, but withaVim9lambda you get "E1106:One argument too many", the number of argumentsmust match.The functionmust 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'))Itis shorter when usingalambda:call map(myDict, {key, val -> key .. '-' .. val})If youdo not use "val" you can leaveit out:call map(myDict, {key -> 'item: ' .. key})If youdo not use "key" you can usea short name:call map(myDict, {_, val -> 'item: ' .. val})The operationis done in-place foraList andDictionary.If you wantit to remain unmodified makea copy first::let tlist = map(copy(mylist), ' v:val .. "\t"')Returns{expr1}, theList orDictionary that was filtered,ora newBlob orString.When an erroris encountered while evaluating{expr2} nofurther items in{expr1} are processed.When{expr2}isaFuncreferrors insidea function are ignored,unlessit was defined with the "abort" flag.Can also be usedasamethod:mylist->map(expr2)Return type:String,Blob, list<{type}> or dict<{type}>depending on{expr1}maparg({name} [,{mode} [,{abbr} [,{dict}]]])maparg()When{dict}is omitted or zero: Return the rhs ofmapping{name} in mode{mode}. The returnedString has specialcharacters translated like in the output of the ":map" commandlisting. When{dict}isTRUEa dictionaryis returned, seebelow. To getalist of all mappings seemaplist().When thereis nomapping for{name}, an emptyStringisreturned if{dict}is FALSE, otherwise returns an empty Dict.When themapping for{name}is empty, then "<Nop>"isreturned.The{name} can have special key names, like in the ":map"command.{mode} can be one of these strings:"n"Normal"v"Visual (including Select)"o"Operator-pending"i"Insert"c"Cmd-line"s"Select"x"Visual"l"langmaplanguage-mapping"t"Terminal-Job""Normal,Visual andOperator-pendingWhen{mode}is omitted, the modes for "" are used.When{abbr}is there anditisTRUE useabbreviationsinstead of mappings.When{dict}is there anditisTRUE returna dictionarycontaining all the information of themapping with thefollowing items:mapping-dict "lhs" The{lhs} of themappingasit would be typed "lhsraw" The{lhs} of themappingas raw bytes "lhsrawalt" The{lhs} of themappingas raw bytes, alternate form, only present whenit differs from "lhsraw" "rhs" The{rhs} of themappingas typed. "silent" 1 fora:map-silent mapping, else 0. "noremap" 1 if the{rhs} of themappingis not remappable. "script" 1 ifmapping was defined with<script>. "expr" 1 for anexpressionmapping(:map-<expr>). "buffer" 1 fora buffer localmapping(:map-local). "mode" Modes for which themappingis defined. In addition to the modes mentioned above, these characters will be used: " " Normal,Visual andOperator-pending "!"Insert and Commandline mode(mapmode-ic) "sid" Thescript local ID, used for<sid> mappings(<SID>). Negative for special contexts. "scriptversion" The version of the script. 999999 forVim9 script. "lnum" The line number in "sid", zero if unknown. "nowait" Do not wait for other, longer mappings.(:map-<nowait>). "abbr" True if thisis an abbreviationabbreviations. "mode_bits" Vim's internal binary representation of "mode".mapset() ignores this; only "mode"is used. Seemaplist() for usage examples. The values are from src/vim.h and may change in the future.The dictionary can be used to restoreamapping withmapset().The mappings local to the current buffer are checked first,then the global mappings.This function can be used to mapa key even when it's alreadymapped, and haveitdo the originalmapping too. Sketch:exe 'nnoremap <Tab> ==' .. maparg('<Tab>', 'n')Can also be usedasamethod:GetKey()->maparg('n')Return type:String or dict<any> depending on{dict}mapcheck({name} [,{mode} [,{abbr}]])mapcheck()Check if thereisamapping that matches with{name} in mode{mode}. Seemaparg() for{mode} and special names in{name}.When{abbr}is there anditisTRUE useabbreviationsinstead of mappings.A match happens withamapping that starts with{name} andwithamapping whichis equal to the start of{name}.matches mapping "a""ab""abc" mapcheck("a")yesyes yes mapcheck("abc")yesyes yes mapcheck("ax")yesno no mapcheck("b")nono noThe difference withmaparg()is thatmapcheck() findsamapping that matches with{name}, whilemaparg() only findsamapping for{name} exactly.When thereis nomapping that starts with{name}, an emptyStringis returned. If thereis one, the RHS of thatmappingis returned. If there are several mappings that start with{name}, the RHS of one of themis returned. This will be"<Nop>" if the RHSis empty.The mappings local to the current buffer are checked first,then the global mappings.This function can be used to check ifamapping can be addedwithout being ambiguous. Example::if mapcheck("_vv") == "": map _vv :set guifont=7x13<CR>:endifThis avoids adding the "_vv"mapping when there alreadyisamapping for "_v" or for "_vvv".Can also be usedasamethod:GetKey()->mapcheck('n')Return type:Stringmaplist([{abbr}])maplist()ReturnsaList of all mappings. EachList itemisaDict,the sameas whatis returned bymaparg(), seemapping-dict. When{abbr}is there anditisTRUE useabbreviations instead of mappings.Example to show all mappings with 'MultiMatch' in rhs:vim9scriptecho maplist()->filter((_, m) => match(m.rhs, 'MultiMatch') >= 0)It can be tricky to find mappings for particular:map-modes.mapping-dict's "mode_bits" can simplify this. For example,the mode_bits for Normal,Insert orCommand-line modes are0x19. To find all the mappings available in those modes youcan do:vim9scriptvar saved_maps = []for m in maplist() if and(m.mode_bits, 0x19) != 0saved_maps->add(m) endifendforecho saved_maps->mapnew((_, m) => m.lhs)The values of the mode_bits are defined in Vim's src/vim.hfile and they can be discoveredat runtime using:map-commands and "maplist()". Example:vim9scriptomap xyzzy <Nop>var op_bit = maplist()->filter( (_, m) => m.lhs == 'xyzzy')[0].mode_bitsounmap xyzzyecho printf("Operator-pending mode bit: 0x%x", op_bit)Return type: list<dict<any>>mapnew({expr1},{expr2})mapnew()Likemap() but instead ofreplacing items in{expr1}a newList orDictionaryis created and returned.{expr1} remainsunchanged. Items can still be changed by{expr2}, if youdon't want that usedeepcopy() first.Return type:String,Blob, list<{type}> or dict<{type}>depending on{expr1}mapset({mode},{abbr},{dict})mapset()mapset({dict})Restoreamapping froma dictionary, possibly returned bymaparg() ormaplist().A buffer mapping, when dict.bufferis true,is set on the current buffer;itis up to the callerto ensure that the intended bufferis the current buffer. Thisfeature allowscopying mappings from one buffer to another.The dict.mode value may restorea singlemapping that coversmore than one mode, like with mode values of '!',' ','nox',or 'v'.E1276In the first form,{mode} and{abbr} should be the sameasfor the call tomaparg().E460{mode}is used to define the mode in which themappingis set,not the "mode" entry in{dict}.Example for saving and restoringa mapping:let save_map = maparg('K', 'n', 0, 1)nnoremap K somethingelse...call mapset('n', 0, save_map)Note that if you are going to replacea map in several modes,e.g. with:map!, you need to save/restore themapping forall of them, when they might differ.In the second form, with{dict}as the only argument, modeand abbr are taken from the dict.Example:vim9scriptvar save_maps = maplist()->filter((_, m) => m.lhs == 'K')nnoremap K somethingelsecnoremap K somethingelse2# ...unmap Kfor d in save_maps mapset(d)endforReturn type:Numbermatch({expr},{pat} [,{start} [,{count}]])match()When{expr}isaList then this returns theindex of thefirst item where{pat} matches. Each itemis usedasaString,Lists andDictionaries are usedas echoed.Otherwise,{expr}is usedasa String. The resultisaNumber, which gives theindex (byte offset) in{expr} where{pat} matches.A matchat the first character orList item returns zero.If thereis no match -1is returned.For getting submatches seematchlist().Example::echo match("testing", "ing")" results in 4:echo match([1, 'x'], '\a')" results in 1Seestring-match for how{pat}is used.strpbrk()Vim doesn't haveastrpbrk() function. But you can do::let sepidx = match(line, '[.,;: \t]')strcasestr()Vim doesn't haveastrcasestr() function. But you can add"\c" to thepattern to ignore case::let idx = match(haystack, '\cneedle')If{start}is given, the search starts from byteindex{start} inaString or item{start} inaList.The result, however,is still theindex counted from thefirst character/item. Example::echo match("testing", "ing", 2)resultis again "4".:echo match("testing", "ing", 4)resultis again "4".:echo match("testing", "t", 2)resultis "3".Fora String, if{start}>0 thenitis like thestring starts{start} bytes later, thus "^" will matchat{start}. Exceptwhen{count}is given, then it's like matches before the{start} byte are ignored (thisisa bit complicated to keepitbackwards compatible).Fora String, if{start}< 0,it will be set to 0. Foralisttheindexis counted from the end.If{start}is out of range ({start}> strlen({expr}) foraString or{start}> len({expr}) foraList) -1is returned.When{count}is given use the{count}'th match. Whena matchis found inaString the search for the next one starts onecharacter further. Thus this example results in 1:echo match("testing", "..", 0, 2)InaList the search continues in the next item.Note that when{count}is added the way{start} works changes,see above.match-patternSeepattern for the patterns that are accepted.The'ignorecase' optionis used to set the ignore-caseness ofthe pattern.'smartcase'is NOT used. The matchingis alwaysdone like'magic'is set and'cpoptions'is empty.Note thata matchat the startis preferred, thus when thepatternis using "*" (any number of matches)it tends to findzero matchesat the start instead ofa number of matchesfurther down in the text.Can also be usedasamethod:GetText()->match('word')GetList()->match('word')Return type:Numbermatchadd()E290E798E799E801E957matchadd({group},{pattern} [,{priority} [,{id} [,{dict}]]])Definesapattern to be highlighted in the currentwindow (a"match"). It will be highlighted with{group}. Returns anidentification number (ID), which can be used to delete thematch usingmatchdelete(). The IDis bound to the window.Matchingiscase sensitive and magic, unlesscase sensitivityor magicness are explicitly overridden in{pattern}. The'magic','smartcase' and'ignorecase'options are not used.The "Conceal" valueis special,it causes the match to beconcealed.The optional{priority} argument assignsa priority to thematch.A match witha high priority will have itshighlighting overrule that ofa match witha lower priority.A priorityis specifiedas an integer (negative numbers are noexception). If the{priority} argumentis not specified, thedefault priorityis 10. The priority of'hlsearch'is zero,hence all matches witha priority greater than zero willoverrule it.Syntax highlighting (see'syntax')isa separatemechanism, and regardless of the chosen prioritya match willalways overrulesyntax highlighting.The optional{id} argument allows the request fora specificmatch ID. Ifa specified IDis already taken, an errormessage will appear and the match will not be added. An IDis specifiedasa positive integer (zero excluded). IDs 1, 2and 3 are reserved for:match,:2match and:3match,respectively. 3is reserved for use by thematchparenplugin.If the{id} argumentis not specified or -1,matchadd()automatically choosesa free ID, whichisat least 1000.The optional{dict} argument allows for further customvalues. Currently thisis used to specifya match specificconceal character that will be shown forhl-Concealhighlighted matches. Thedict can have the following members:concealSpecial character to show instead of the match (only forhl-Conceal highlighted matches, see:syn-cchar)window Instead of the currentwindow use thewindow with this number orwindow ID.The number of matchesis not limited,asitis thecase withthe:match commands.Returns -1 on error.Example::highlight MyGroup ctermbg=green guibg=green:let m = matchadd("MyGroup", "TODO")Deletion of the pattern::call matchdelete(m)Alist of matches defined bymatchadd() and:match areavailable fromgetmatches(). All matches can be deleted inone operation byclearmatches().Can also be usedasamethod:GetGroup()->matchadd('TODO')Return type:Numbermatchaddpos()matchaddpos({group},{pos} [,{priority} [,{id} [,{dict}]]])Sameasmatchadd(), but requiresalist of positions{pos}instead ofa pattern. This commandis faster thanmatchadd()becauseit does not handle regular expressions andit setsbuffer line boundaries to redraw screen. Itis supposed to beused when fast match additions and deletions are required, forexample to highlight matching parentheses.{pos}isalist of positions. Each position can be one ofthese:-A number. This whole line will be highlighted. The first line has number 1.-Alist with one number, e.g.,[23]. The whole line with this number will be highlighted.-Alist with two numbers, e.g., [23, 11]. The first numberis the line number, the second oneis the column number (first columnis 1, the valuemust correspond to the byteindexascol() would return). The characterat this position will be highlighted.-Alist with three numbers, e.g., [23, 11, 3]. As above, but the third number gives the length of the highlight in bytes.Returns -1 on error.Example::highlight MyGroup ctermbg=green guibg=green:let m = matchaddpos("MyGroup", [[23, 24], 34])Deletion of the pattern::call matchdelete(m)Matches added bymatchaddpos() are returned bygetmatches().Can also be usedasamethod:GetGroup()->matchaddpos([23, 11])Return type:Numbermatcharg({nr})matcharg()Selects the{nr} match item,as set witha:match,:2match or:3match command.ReturnaList with two elements:The name of the highlight group usedThepattern used.When{nr}is not 1, 2 or 3 returns an emptyList.When thereis no match item set returns ['', ''].Thisis useful to save and restorea:match.Highlighting matches using the:match commands are limitedto three matches.matchadd() does not have this limitation.Can also be usedasamethod:GetMatch()->matcharg()Return type: list<string>matchbufline()matchbufline({buf},{pat},{lnum},{end}, [,{dict}])Returns theList of matches in lines from{lnum} to{end} inbuffer{buf} where{pat} matches.{lnum} and{end} can either bea line number or thestring "$"to refer to the last line in{buf}.The{dict} argument supports following items: submatchesinclude submatch information(/\()For each match,aDict with the following itemsis returned: byteidxstarting byteindex of the match lnumline number where thereisa match textmatchedstringNote that there can be multiple matches ina single line.This function works only for loaded buffers. First callbufload() if needed.Seematch-pattern for information about the effect of someoption settings on the pattern.When{buf}is nota valid buffer, the bufferis not loaded or{lnum} or{end}is not valid then an erroris given and anemptyListis returned.Examples: " Assuming line 3 in buffer 5 contains "a" :echo matchbufline(5, '\<\k\+\>', 3, 3) [{'lnum': 3, 'byteidx': 0, 'text': 'a'}] " Assuming line 4 in buffer 10 contains "tik tok" :echo matchbufline(10, '\<\k\+\>', 1, 4) [{'lnum': 4, 'byteidx': 0, 'text': 'tik'}, {'lnum': 4, 'byteidx': 4, 'text': 'tok'}]If{submatch}is present andis 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. Ifa submatchis not found, then an emptystringis returned for thatsubmatch.Can also be usedasamethod:GetBuffer()->matchbufline('mypat', 1, '$')Return type: list<dict<any>> or list<any>matchdelete({id} [,{win})matchdelete()E802E803Deletesa match with ID{id} previously defined bymatchadd()or one of the:match commands. Returns0 if successful,otherwise -1. See example formatchadd(). All matches canbe deleted in one operation byclearmatches().If{win}is specified, use thewindow with this number orwindow ID instead of the current window.Can also be usedasamethod:GetMatch()->matchdelete()Return type:Numbermatchend({expr},{pat} [,{start} [,{count}]])matchend()Sameasmatch(), but return theindex of first characterafter the match. Example::echo matchend("testing", "ing")results in "7".strspn()strcspn()Vim doesn't haveastrspn() orstrcspn() function, but you candoit with matchend()::let span = matchend(line, '[a-zA-Z]'):let span = matchend(line, '[^a-zA-Z]')Except that -1is returned when there are no matches.The{start}, if given, has the same meaningas formatch().:echo matchend("testing", "ing", 2)results in "7".:echo matchend("testing", "ing", 5)resultis "-1".When{expr}isaList the resultis equal tomatch().Can also be usedasamethod:GetText()->matchend('word')Return type:Numbermatchfuzzy({list},{str} [,{dict}])matchfuzzy()If{list}isalist of strings, then returnsaList with allthe strings in{list} that fuzzy match{str}. The strings inthe returnedlist are sorted based on the matching score.The optional{dict} argument always supports the followingitems: matchseqWhen this itemis present return only matchesthat contain the characters in{str} in thegiven sequence. limitMaximum number of matches in{list} to bereturned. Zero means no limit. camelcaseUse enhanced camelcase scoring making resultsbetter suited for completion related toprogramming languages. Defaults to v:true.If{list}isalist of dictionaries, then the optional{dict}argument supports the following additional items: keyKey of the item whichis fuzzy matched against{str}. The value of this item should beastring. text_cbFuncref that will be called for every itemin{list} to get the text for fuzzy matching.This should accepta dictionary itemas theargument and return the text for that item touse for fuzzy matching.{str}is treatedasa literalstring and regularexpressionmatchingis NOT supported. The maximum supported{str} lengthis 256.When{str} has multiple words each separated by white space,then thelist of strings that have all the wordsis returned.If there are no matching strings or thereis an error, then anemptylistis returned. If length of{str}is greater than256, then returns an empty list.When{limit}is given,matchfuzzy() will find up to thisnumber of matches in{list} and return them in sorted order.Refer tofuzzy-matching for more information about fuzzymatching strings.Example: :echo matchfuzzy(["clay", "crow"], "cay")results in["clay"]. :echo getbufinfo()->map({_, v -> v.name})->matchfuzzy("ndl")results inalist of buffer names fuzzy matching "ndl". :echo getbufinfo()->matchfuzzy("ndl", {'key' : 'name'})results inalist of buffer information dicts with buffernames fuzzy matching "ndl". :echo getbufinfo()->matchfuzzy("spl",\ {'text_cb' : {v -> v.name}})results inalist of buffer information dicts with buffernames fuzzy matching "spl". :echo v:oldfiles->matchfuzzy("test")results inalist of file names fuzzy matching "test". :let l = readfile("buffer.c")->matchfuzzy("str")results inalist of lines in "buffer.c" fuzzy matching "str". :echo ['one two', 'two one']->matchfuzzy('two one')results in ['two one', 'one two']. :echo ['one two', 'two one']->matchfuzzy('two one',\ {'matchseq': 1})results in ['two one'].Return type: list<string> or list<any>matchfuzzypos({list},{str} [,{dict}])matchfuzzypos()Sameasmatchfuzzy(), but returns thelist of matchedstrings, thelist of character positions where charactersin{str} matches andalist of matching scores. You canusebyteidx() to converta character position toa byteposition.If{str} matches multiple times ina string, then only thepositions for the best matchis returned.If there are no matching strings or thereis an error, thenalist with three emptylist itemsis returned.Example::echo matchfuzzypos(['testing'], 'tsg')results in [['testing'], [[0, 2, 6]],[99]]:echo matchfuzzypos(['clay', 'lacy'], 'la')results in [['lacy','clay'], [[0, 1], [1, 2]], [153, 133]]:echo [{'text': 'hello', 'id' : 10}]->matchfuzzypos('ll', {'key' : 'text'})results in [[{'id': 10,'text':'hello'}], [[2, 3]],[127]]Return type: list<list<any>>matchlist({expr},{pat} [,{start} [,{count}]])matchlist()Sameasmatch(), but returnaList. The first item in thelistis the matched string, sameas whatmatchstr() wouldreturn. Following items are submatches, like "\1", "\2", etc.in:substitute. When an optional submatch didn't match anemptystringis used. Example:echo matchlist('acd', '\(a\)\?\(b\)\?\(c\)\?\(.*\)')Results in: ['acd', 'a', '', 'c', 'd', '', '', '', '', '']When thereis no match an emptylistis returned.You can pass ina List, but thatis not very useful.Can also be usedasamethod:GetText()->matchlist('word')Return type: list<string> or list<any>matchstrlist()matchstrlist({list},{pat} [,{dict}])Returns theList of matches in{list} where{pat} matches.{list}isaList of strings.{pat}is matched against eachstring in{list}.The{dict} argument supports following items: submatchesinclude submatch information(/\()For each match,aDict with the following itemsis returned: byteidxstarting byteindex of the match. idxindex in{list} of the match. textmatchedstring submatchesaList of submatches. Present only if"submatches"is set tov:true in{dict}.Seematch-pattern for information about the effect of someoption settings on the pattern.Example: :echo matchstrlist(['tik tok'], '\<\k\+\>') [{'idx': 0, 'byteidx': 0, 'text': 'tik'}, {'idx': 0, 'byteidx': 4, 'text': 'tok'}] :echo matchstrlist(['a', 'b'], '\<\k\+\>') [{'idx': 0, 'byteidx': 0, 'text': 'a'}, {'idx': 1, 'byteidx': 0, 'text': 'b'}]If "submatches"is present andis v:true, then submatches like"\1", "\2", etc. are also returned. Example: :echo matchstrlist(['acd'], '\(a\)\?\(b\)\?\(c\)\?\(.*\)',\ #{submatches: v:true}) [{'idx': 0, 'byteidx': 0, 'text': 'acd', 'submatches': ['a', '', 'c', 'd', '', '', '', '', '']}]The "submatches"List always contains 9 items. Ifa submatchis not found, then an emptystringis returned for thatsubmatch.Can also be usedasamethod:GetListOfStrings()->matchstrlist('mypat')Return type: list<dict<any>> or list<any>matchstr({expr},{pat} [,{start} [,{count}]])matchstr()Sameasmatch(), but return the matched string. Example::echo matchstr("testing", "ing")results in "ing".When thereis no match ""is returned.The{start}, if given, has the same meaningas formatch().:echo matchstr("testing", "ing", 2)results in "ing".:echo matchstr("testing", "ing", 5)resultis "".When{expr}isaList then the matching itemis returned.The type isn't changed, it's not necessarilya String.Can also be usedasamethod:GetText()->matchstr('word')Return type:Stringmatchstrpos({expr},{pat} [,{start} [,{count}]])matchstrpos()Sameasmatchstr(), but return the matched string, the startposition and theend position of the match. Example::echo matchstrpos("testing", "ing")results in["ing", 4, 7].When thereis no match["", -1, -1]is returned.The{start}, if given, has the same meaningas formatch().:echo matchstrpos("testing", "ing", 2)results in["ing", 4, 7].:echo matchstrpos("testing", "ing", 5)resultis["", -1, -1].When{expr}isaList then the matching item, theindexof first item where{pat} matches, the start position and theend position of the match are returned.:echo matchstrpos([1, '__x'], '\a')resultis["x", 1, 2, 3].The type isn't changed, it's not necessarilya String.Can also be usedasamethod:GetText()->matchstrpos('word')Return type: list<any>max({expr})max()Return the maximum value of all items in{expr}. Example:echo max([apples, pears, oranges]){expr} can beaList,aTuple oraDictionary. ForaDictionary,it returns the maximum of all values in theDictionary. If{expr}is neitheraList noraTuple noraDictionary, or one of the items in{expr} cannot be usedasaNumber this results in an error. An emptyList,TupleorDictionary results in zero.Can also be usedasamethod:mylist->max()Return type:Numbermenu_info({name} [,{mode}])menu_info()Return information about the specified menu{name} inmode{mode}. The menu name should be specified without theshortcut character ('&'). If{name}is "", then the top-levelmenu names are returned.{mode} can be one of these strings:"n"Normal"v"Visual (including Select)"o"Operator-pending"i"Insert"c"Cmd-line"s"Select"x"Visual"t"Terminal-Job""Normal,Visual andOperator-pending"!"Insert and Cmd-lineWhen{mode}is omitted, the modes for "" are used.ReturnsaDictionary containing the following items: accelmenu item accelerator textmenu-text displaydisplay name (name without '&') enabledv:true if this menu itemis enabledRefer to:menu-enable iconname of the icon file (for toolbar)toolbar-icon iconidxindex ofa built-in icon modesmodes for which the menuis defined. Inaddition to the modes mentioned above, thesecharacters will be used:" "Normal,Visual andOperator-pending namemenu item name. noremenuv:true if the{rhs} of the menu itemis 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} ofa menu itemis empty, then"<Nop>"is returned.scriptv:true ifscript-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 itemis createdwith<silent> argument:menu-silent submenusList containing the names ofall the submenus. Present only if the menuitem has submenus.Returns an empty dictionary if the menu itemis not found.Examples::echo menu_info('Edit.Cut'):echo menu_info('File.Save', 'n')" Display the entire menu hierarchy in a bufferfunc ShowMenu(name, pfx) let m = menu_info(a:name) call append(line('$'), a:pfx .. m.display) for child in m->get('submenus', []) call ShowMenu(a:name .. '.' .. escape(child, '.'),\ a:pfx .. ' ') endforendfuncnewfor topmenu in menu_info('').submenus call ShowMenu(topmenu, '')endforCan also be usedasamethod:GetMenuName()->menu_info('v')Return type: dict<any>min({expr})min()Return the minimum value of all items in{expr}. Example:echo min([apples, pears, oranges]){expr} can beaList,aTuple oraDictionary. ForaDictionary,it returns the minimum of all values in theDictionary. If{expr}is neitheraList noraTuple noraDictionary, or one of the items in{expr} cannot be usedasaNumber this results in an error. An emptyList,Tuple orDictionary results in zero.Can also be usedasamethod:mylist->min()Return type:Numbermkdir({name} [,{flags} [,{prot}]])mkdir()E739Create directory{name}.When{flags}is presentitmust bea string. An emptystringhas no effect.{flags} can contain these character flags: "p"intermediate directories will be createdas necessary "D"{name} will be deletedat theend of the currentfunction, but not recursively:defer "R"{name} will be deleted recursivelyat theend of thecurrent function:deferNote that when{name} has more than one part and "p"is usedsome directories may already exist. Only the first one thatis created and whatit containsis scheduled to be deleted.E.g. when using:call mkdir('subdir/tmp/autoload', 'pR')and "subdir" already exists then "subdir/tmp" will bescheduled for deletion, like with:defer delete('subdir/tmp', 'rf')Note that if scheduling the defer fails the directoryis notdeleted. This should only happen when out of memory.If{prot}is givenitis used to set the protection bits ofthe new directory. The defaultis 0o755 (rwxr-xr-x: r/w forthe user, readable for others). Use 0o700 to makeitunreadable for others. Thisis used for the newly createddirectories.Note: umaskis applied to{prot} (on Unix).Example::call mkdir($HOME .. "/tmp/foo/bar", "p", 0o700)This functionis not available in thesandbox.Thereis no error if the directory already exists and the "p"flagis passed (since patch 8.0.1708). However, without the"p" option the call will fail.The function resultisa Number, whichisTRUE if the call wassuccessful orFALSE if the directory creation failed or partlyfailed.Not available on all systems. To check use::if exists("*mkdir")Can also be usedasamethod:GetName()->mkdir()Return type:Numbermode([{expr}])mode()Returnastring that indicates the current mode.If{expr}is supplied andit evaluates toa non-zeroNumber ora non-emptyString(non-zero-arg), then the full modeisreturned, otherwise only the firstletteris returned.Also seestate().nNormal noOperator-pending novOperator-pending (forcedcharacterwiseo_v) noVOperator-pending (forcedlinewiseo_V) noCTRL-VOperator-pending (forced blockwiseo_CTRL-V);CTRL-Vis one character niINormal usingi_CTRL-O inInsert-mode niRNormal usingi_CTRL-O inReplace-mode niVNormal usingi_CTRL-O inVirtual-Replace-mode ntTerminal-Normal (insert goes toTerminal-Job mode)vVisual by character vsVisual by character usingv_CTRL-O inSelect modeVVisual by line VsVisual by line usingv_CTRL-O inSelect modeCTRL-VVisual blockwiseCTRL-VsVisual blockwise usingv_CTRL-O inSelect modesSelect by characterSSelect by lineCTRL-SSelect blockwiseiInsert icInsert mode completioncompl-generic ixInsert modei_CTRL-X completionRReplaceR RcReplace mode completioncompl-generic RxReplace modei_CTRL-X completion Rv VirtualReplacegR Rvc VirtualReplace mode completioncompl-generic Rvx VirtualReplace modei_CTRL-X completioncCommand-line editing ctCommand-line editing viaTerminal-Job mode crCommand-line editing overstrike modec_<Insert> cv VimEx modegQ cvr VimEx mode while in overstrike modec_<Insert> ceNormalEx modeQr Hit-enter prompt rm The-- more-- prompt r?A:confirm query of some sort! Shell or external commandis executingtTerminal-Job mode: keysgo to thejobThisis useful in the'statusline' option or when usedwithremote_expr() In most other placesit always returns"c" or "n".Note that in the future more modes and more specific modes maybe added. It's better not to compare the wholestring but onlythe leading character(s).Also seevisualmode().Can also be usedasamethod:DoFull()->mode()Return type:Stringmzeval({expr})mzeval()EvaluateMzSchemeexpression{expr} and return its resultconverted to Vim data structures.Numbers and strings are returnedas they are.Pairs (including lists and improper lists) and vectors arereturnedas VimLists.Hash tables are representedas VimDictionary type with keysconverted to strings.All other types are converted tostring with display function.Examples: :mz (define l (list 1 2 3)) :mz (define h (make-hash)) (hash-set! h "list" l) :echo mzeval("l") :echo mzeval("h")Note that ina:def function localvariables are not visibleto{expr}.Can also be usedasamethod:GetExpr()->mzeval()Return type: any, depending on{expr}{only available when compiled with the |+mzscheme| feature}nextnonblank({lnum})nextnonblank()Return the line number of the first lineat or below{lnum}thatis not blank. Example:if getline(nextnonblank(1)) =~ "Java"When{lnum}is invalid or thereis no non-blank lineat orbelow it, zerois returned.{lnum}is used like withgetline().See alsoprevnonblank().Can also be usedasamethod:GetLnum()->nextnonblank()Return type:Numberngettext({single},{plural},{number}[,{domain})ngettext()Returnastring that contains the correct value foramessage based on the rules for plural form(s) ina language. Examples:ngettext("File", "Files", 2) # returns "Files"Can be usedasamethod:1->ngettext("File", "Files") # returns "File"Seegettext() for information on the domain parameter.Return type:Stringnr2char({expr} [,{utf8}])nr2char()Returnastring witha single character, which has the numbervalue{expr}. Examples:nr2char(64)returns "@"nr2char(32)returns " "When{utf8}is omitted or zero, the current'encoding'is used.Example for "utf-8":nr2char(300)returns I with bow characterWhen{utf8}is TRUE, always returnUTF-8 characters.Note thata NUL character in the fileis specified withnr2char(10), because NULs are represented with newlinecharacters. nr2char(0)isa real NUL and terminates thestring, thus results in an empty string.To turnalist of character numbers intoa string: let list = [65, 66, 67] let str = join(map(list, {_, val -> nr2char(val)}), '')Result: "ABC"Can also be usedasamethod:GetNumber()->nr2char()Return type:Stringor({expr},{expr})or()Bitwise OR on the two arguments. The arguments are convertedtoa number.A List,Dict orFloat argument causes an error.Also seeand() andxor().Example::let bits = or(bits, 0x80)Can also be usedasamethod::let bits = bits->or(0x80)Rationale: The reason thisisa function and not using the "|"character like many languages,is thatVi has always used "|"to separate commands. In many placesit would not be clear if"|"is anoperator ora command separator.Return type:Numberpathshorten({path} [,{len}])pathshorten()Shorten directory names in the path{path} and return theresult. The tail, the file name,is kept as-is. The othercomponents in the path are reduced to{len} letters in length.If{len}is omitted or smaller than 1 then 1is used (singleletters). Leading '~' and '.' characters are kept. Examples::echo pathshorten('~/.vim/autoload/myfile.vim')~/.v/a/myfile.vim:echo pathshorten('~/.vim/autoload/myfile.vim', 2)~/.vi/au/myfile.vimIt doesn't matter if the path exists or not.Returns an emptystring on error.Can also be usedasamethod:GetDirectories()->pathshorten()Return type:Stringperleval({expr})perleval()EvaluatePerlexpression{expr} in scalar context and returnits result converted to Vim data structures. If value can't beconverted,itis returnedasastringPerl representation.Note: If you want an array or hash,{expr}must returnareference to it.Example::echo perleval('[1 .. 4]')[1, 2, 3, 4]Note that ina:def function localvariables are not visibleto{expr}.Can also be usedasamethod:GetExpr()->perleval()Return type: any, depending on{expr}{only available when compiled with the |+perl| feature}popup_functions are documented here:popup-functionspow({x},{y})pow()Return the power of{x} to the exponent{y}asaFloat.{x} and{y}must evaluate toaFloat oraNumber.Returns 0.0 if{x} or{y}is notaFloat oraNumber.Examples::echo pow(3, 3)27.0:echo pow(2, 16)65536.0:echo pow(32, 0.20)2.0Can also be usedasamethod:Compute()->pow(3)Return type:Numberprevnonblank({lnum})prevnonblank()Return the line number of the first lineat or above{lnum}thatis not blank. Example:let ind = indent(prevnonblank(v:lnum - 1))When{lnum}is invalid or thereis no non-blank lineat orabove it, zerois returned.{lnum}is used like withgetline().Also seenextnonblank().Can also be usedasamethod:GetLnum()->prevnonblank()Return type:Numberprintf({fmt},{expr1} ...)printf()ReturnaString with{fmt}, where "%" items are replaced bythe formatted form of their respective arguments. Example:printf("%4d: E%d %.30s", lnum, errno, msg)May result in:" 99: E42 asdfasdfasdfasdfasdfasdfasdfas"When usedasamethod the baseis passedas the secondargument:Compute()->printf("result: %d")You can usecall() to pass the itemsasa list.Often used items are: %sstring %6Sstring right-aligned in 6 display cells %6sstring right-aligned in 6 bytes %.9sstring truncated to 9 bytes %csingle byte %ddecimal number %5ddecimal number padded with spaces to 5 characters %xhex number %04xhex number padded with zeros toat least 4 characters %Xhex number using uppercase letters %ooctal number %08bbinary number padded with zeros toat least 8 chars %ffloating point numberas 12.23, inf, -inf or nan %Ffloating point numberas 12.23, INF, -INF or NAN %efloating point numberas 1.23e3, inf, -inf or nan %Efloating point numberas 1.23E3, INF, -INF or NAN %gfloating point number,as %f or %e depending on value %Gfloating point number,as %F or %E depending on value %%the% character itselfConversion specifications start with '%' andend with theconversion type. All other characters are copied unchanged tothe result.The "%" startsa conversion specification. The followingarguments appear in sequence:%[pos-argument][flags][field-width] [.precision] typepos-argumentAt most one positional argument specifier. Thesetake the form{n$}, wherenis >= 1.flagsZero or more of the following flags:# The value should be converted to an "alternate form". For c, d, ands conversions, this option has no effect. Foro conversions, the precision of the numberis increased to force the first character of the outputstring toa zero (except ifa zero valueis printed with an explicit precision of zero). Forb andB conversions,a non-zero result has thestring "0b" (or "0B" forB conversions) prepended to it. Forx andX conversions,a non-zero result has thestring "0x" (or "0X" forX conversions) prepended to it.0 (zero) Zero padding. For all conversions the converted valueis padded on the left with zeros rather than blanks. Ifa precisionis given witha numeric conversion (d, b, B, o, x, and X), the0 flagis ignored.-A negative field width flag; the converted valueis to be left adjusted on the field boundary. The converted valueis padded on the right with blanks, rather than on the left with blanks or zeros.A- overridesa0 if both are given.'' (space)A blank should be left beforea positive number produced bya signed conversion (d).+A signmust always be placed beforea number produced bya signed conversion.A+ overridesaspace if both are used.field-widthAn optional decimal digitstring specifyinga minimumfield width. If the converted value has fewer bytesthan the field width,it will be padded with spaces onthe left (or right, if the left-adjustment flag hasbeen given) to fill out the field width. For theSconversion thecountis in cells..precisionAn optional precision, in the form ofa period '.'followed by an optional digit string. If the digitstringis omitted, the precisionis takenas zero.This gives the minimum number of digits to appear ford, o, x, andX conversions, the maximum number ofbytes to be printed fromastring fors conversions,or the maximum number of cells to be printed fromastring forS conversions.For floating pointitis the number of digits afterthe decimal point.typeA character thatspecifies the type of conversion tobe applied, see below.A field width or precision, or both, may be indicated by anasterisk'*' instead ofa digit string. In this case,aNumber argument supplies the field width or precision.Anegative field widthis treatedasa left adjustment flagfollowed bya positive field width;a negative precisionistreatedas thoughit were missing. Example::echo printf("%d: %.*s", nr, width, line)Thislimits the length of the text used from "line" to"width" bytes.If the argument to be formattedis specified usingapositional argument specifier, anda'*'is used to indicatethata number argumentis to be used to specify the width orprecision, the argument(s) to be usedmust also be specifiedusinga{n$} positional argument specifier. Seeprintf-$.The conversion specifiers and their meanings are:printf-dprintf-bprintf-Bprintf-oprintf-xprintf-XdbBoxXTheNumber argumentis converted to signed decimal(d), unsigned binary (b and B), unsignedoctal (o), orunsigned hexadecimal (x and X) notation. The letters"abcdef" are used forx conversions; the letters"ABCDEF" are used forX conversions.The precision, if any, gives the minimum number ofdigits thatmust appear; if the converted valuerequires fewer digits,itis padded on the left withzeros.In nocase doesa non-existent or small field widthcause truncation ofa numeric field; if the result ofa conversionis wider than the field width, the fieldis expanded to contain the conversion result.The 'h' modifier indicates the argumentis 16 bits.The 'l' modifier indicates the argumentisa longinteger. The size will be 32 bits or 64 bitsdepending on your platform.The "ll" modifier indicates the argumentis 64 bits.Theb andB conversion specifiers never takea widthmodifier and always assume their argumentisa 64 bitinteger.Generally, these modifiers are not useful. They areignored when typeis known from the argument.ialias fordDalias for ldUalias for luOalias for loprintf-ccTheNumber argumentis converted toa byte, and theresulting characteris written.printf-ssThe text of theString argumentis used. Ifaprecisionis specified, no more bytes than the numberspecified are used.If the argumentis notaString type,itisautomatically converted to text with the same formatas ":echo".printf-SSThe text of theString argumentis used. Ifaprecisionis specified, no more display cells than thenumber specified are used.printf-fE807fFTheFloat argumentis converted intoastring of theform 123.456. The precisionspecifies the number ofdigits after the decimal point. When the precisioniszero the decimal pointis omitted. When the precisionis not specified 6is used.A really big number(out of range or dividing by zero) results in "inf"or "-inf" with %f (INF or -INF with %F)."0.0/ 0.0" results in "nan" with %f (NAN with %F).Example:echo printf("%.2f", 12.115)12.12Note that roundoff depends on the system libraries.Useround() when in doubt.printf-eprintf-EeETheFloat argumentis converted intoastring of theform 1.234e+03 or 1.234E+03 when using 'E'. Theprecisionspecifies the number of digits after thedecimal point, like with 'f'.printf-gprintf-GgGTheFloat argumentis converted like with 'f' if thevalueis between 0.001 (inclusive) and 10000000.0(exclusive). Otherwise 'e'is used for 'g' and 'E'for 'G'. When no precisionis specified superfluouszeroes and '+'signs are removed, except for the zeroimmediately after the decimal point. Thus 10000000.0results in 1.0e7.printf-%%A '%'is written. No argumentis converted. Thecomplete conversion specificationis "%%".WhenaNumber argumentis expectedaString argumentis alsoaccepted and automatically converted.WhenaFloat orString argumentis expectedaNumber argumentis also accepted and automatically converted.Any other argument type results in an error message.E766E767The number of{exprN} argumentsmust exactly match the numberof "%" items. If there are not sufficient or too manyarguments an erroris given. Up to 18 arguments can be used.printf-$In certain languages, error and informativemessages aremore readable when the order of wordsis different from thecorresponding message in English. To accommodate translationshavinga differentword order, positional arguments may beused to indicate this. For instance: #, c-format msgid "%s returning %s" msgstr "waarde %2$s komt terug van %1$s"In this example, thesentence has its 2string argumentsreversed in the output. echo printf("In The Netherlands, vim's creator's name is: %1$s %2$s","Bram", "Moolenaar") In The Netherlands, vim's creator's name is:BramMoolenaar echo printf("In Belgium, vim's creator's name is: %2$s %1$s","Bram", "Moolenaar") In Belgium, vim's creator's name is:MoolenaarBramWidth (and precision) can be specified using the'*' specifier.In this case, youmust specify the field width position in theargument list. echo printf("%1$*2$.*3$d", 1, 2, 3) 001 echo printf("%2$*3$.*1$d", 1, 2, 3) 2 echo printf("%3$*1$.*2$d", 1, 2, 3) 03 echo printf("%1$*2$.*3$g", 1.4142, 2, 3) 1.414You can mix specifying the width and/or precision directlyand via positional arguments: echo printf("%1$4.*2$f", 1.4142135, 6) 1.414214 echo printf("%1$*2$.4f", 1.4142135, 6) 1.4142 echo printf("%1$*2$.*3$f", 1.4142135, 6, 2) 1.41You will get an overflow errorE1510, when the field-widthor precision will result inastring longer than 1 MiB(1024*1024= 1048576) chars.E1500You cannot mix positional and non-positional arguments: echo printf("%s%1$s", "One", "Two") E1500: Cannot mix positional and non-positional arguments: %s%1$sE1501You cannot skipa positional argument ina format string: echo printf("%3$s%1$s", "One", "Two", "Three") E1501: format argument 2 unused in $-style format: %3$s%1$sE1502You can re-usea[field-width] (or[precision]) argument: echo printf("%1$d at width %2$d is: %01$*2$d", 1, 2) 1at width 2 is: 01However, you can't useitasa different type: echo printf("%1$d at width %2$ld is: %01$*2$d", 1, 2) E1502: Positional argument 2 usedas field width reusedas different type: long int/intE1503Whena positional argumentis used, but not the correct numberor argumentsis given, an erroris raised: echo printf("%1$d at width %2$d is: %01$*2$.*3$d", 1, 2) E1503: Positional argument 3 out of bounds: %1$dat width %2$d is: %01$*2$.*3$dOnly the first erroris reported: echo printf("%01$*2$.*3$d %4$d", 1, 2) E1503: Positional argument 3 out of bounds: %01$*2$.*3$d %4$dE1504A positional argument can be used more than once: echo printf("%1$s %2$s %1$s", "One", "Two") One Two OneHowever, you can't usea different type the second time: echo printf("%1$s %2$s %1$d", "One", "Two") E1504: Positional argument 1 type used inconsistently: int/stringE1505Various othererrors that lead toa formatstring beingwrongly formatted lead to: echo printf("%1$d at width %2$d is: %01$*2$.3$d", 1, 2) E1505: Invalid format specifier: %1$dat width %2$d is: %01$*2$.3$dE1507This internal error indicates that the logic to parseapositional format argument ran intoa problem that couldn't beotherwise reported. Please filea bug against Vim if you runinto this,copying the exact formatstring and parameters thatwere used.Return type:Stringprompt_getprompt({buf})prompt_getprompt()Returns the effective prompt text for buffer{buf}.{buf} canbea buffer name or number. Seeprompt-buffer.If the buffer doesn't exist or isn'ta prompt buffer, an emptystringis returned.Can also be usedasamethod:GetBuffer()->prompt_getprompt()Return type:String{only available when compiled with the |+channel| feature}prompt_setcallback({buf},{expr})prompt_setcallback()Set prompt callback for buffer{buf} to{expr}. When{expr}is an emptystring the callbackis removed. This has onlyeffect if{buf} has'buftype' set to "prompt".The callbackis invoked when pressing Enter. The currentbuffer will always be the prompt buffer.A new line forapromptis added before invoking the callback, thus the promptfor which the callback was invoked will be in the last but oneline.If the callback wants to add text to the buffer,itmustinsertit above the last line, since thatis where the currentprompt is. This can also be done asynchronously.The callbackis invoked with one argument, whichis the textthat was enteredat the prompt. This can be an emptystringif the user only typed Enter.Example: func s:TextEntered(text) if a:text == 'exit' || a:text == 'quit' stopinsert " Reset 'modified' to allow the buffer to be closed. " We assume there is nothing useful to be saved. set nomodified close else " Do something useful with "a:text". In this example " we just repeat it. call append(line('$') - 1, 'Entered: "' .. a:text .. '"') endif endfunc call prompt_setcallback(bufnr(), function('s:TextEntered'))Can also be usedasamethod:GetBuffer()->prompt_setcallback(callback){only available when compiled with the |+channel| feature}prompt_setinterrupt({buf},{expr})prompt_setinterrupt()Seta callback for buffer{buf} to{expr}. When{expr}is anemptystring the callbackis removed. This has only effect if{buf} has'buftype' set to "prompt".This callback will be invoked when pressingCTRL-C inInsertmode. Without settinga callback Vim will exitInsert mode,as in any buffer.Can also be usedasamethod:GetBuffer()->prompt_setinterrupt(callback)Return type:Number{only available when compiled with the |+channel| feature}prompt_setprompt({buf},{text})prompt_setprompt()Set prompt for buffer{buf} to{text}. You most likely want{text} toend ina space.The resultis only visible if{buf} has'buftype' set to"prompt". Example:call prompt_setprompt(bufnr(), 'command: ')Can also be usedasamethod:GetBuffer()->prompt_setprompt('command: ')Return type:Number{only available when compiled with the |+channel| feature}prop_functions are documented here:text-prop-functionspum_getpos()pum_getpos()If thepopup menu (seeins-completion-menu)is not visible,returns an emptyDictionary, otherwise, returnsaDictionary with the following keys:heightnr of items visiblewidthscreen cellsrowtop screen row (0 first row)colleftmost screen column (0 first col)sizetotal nr of itemsscrollbarTRUE if scrollbaris visibleThe values are the sameas inv:event duringCompleteChanged.Return type: dict<any>pumvisible()pumvisible()Returns non-zero when thepopup menuis visible, zerootherwise. Seeins-completion-menu.This can be used to avoid some things that would remove thepopup menu.Return type:Numberpy3eval({expr} [,{locals}])py3eval()EvaluatePythonexpression{expr} and return its resultconverted to Vim data structures.Ifa{locals}Dictionaryis given,it defines set of localvariables available in the expression. The keys are variablenames and the values are the variable values.Dictionary,List andTuple values are referenced, and may be updatedby theexpression (as ifpython-bindeval was used).Numbers and strings are returnedas they are (strings arecopied though,Unicode strings are additionally converted to'encoding').Lists are representedas VimList type.Tuples are representedas VimTuple type.Dictionaries are representedas VimDictionary type withkeys converted to strings.Note that ina:def function localvariables are not visibleto{expr}.Can also be usedasamethod:GetExpr()->py3eval()'b",".join(l)'->py3eval({'l': ['a', 'b', 'c']})Return type: any, depending on{expr}{only available when compiled with the |+python3| feature}E858E859pyeval({expr} [,{locals}])pyeval()EvaluatePythonexpression{expr} and return its resultconverted to Vim data structures.For{locals} seepy3eval().Numbers and strings are returnedas they are (strings arecopied though).Lists are representedas VimList type.Tuples are representedas VimTuple type.Dictionaries are representedas VimDictionary type,non-string keys result in error.Note that ina:def function localvariables are not visibleto{expr}.Can also be usedasamethod:GetExpr()->pyeval()Return type: any, depending on{expr}{only available when compiled with the |+python| feature}pyxeval({expr} [,{locals}])pyxeval()EvaluatePythonexpression{expr} and return its resultconverted to Vim data structures.For{locals} seepy3eval().UsesPython 2 or 3, seepython_x and'pyxversion'.See also:pyeval(),py3eval()Can also be usedasamethod:GetExpr()->pyxeval()Return type: any, depending on{expr}{only available when compiled with the+python or the+python3 feature}rand([{expr}])rand()randomReturna pseudo-randomNumber generated with an xoshiro128**algorithm using seed{expr}. The returned numberis 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 valueis usedand updated.Returns -1 if{expr}is invalid.Examples::echo rand():let seed = srand():echo rand(seed):echo rand(seed) % 16 " random number 0 - 15Return type:NumberE726E727range({expr} [,{max} [,{stride}]])range()ReturnsaList with Numbers:- If only{expr}is specified: [0, 1, ...,{expr}- 1]- If{max}is specified: [{expr},{expr}+ 1, ...,{max}]- If{stride}is specified: [{expr},{expr}+{stride}, ...,{max}] (increasing{expr} with{stride} each time, not producinga value past{max}).When the maximumis one before the start the resultis anempty list. When the maximumis more than one before thestart thisis an error.Examples:range(4)" [0, 1, 2, 3]range(2, 4)" [2, 3, 4]range(2, 9, 3)" [2, 5, 8]range(2, -2, -1)" [2, 1, 0, -1, -2]range(0)" []range(2, 0)" error!Can also be usedasamethod:GetExpr()->range()Return type: list<number>readblob({fname} [,{offset} [,{size}]])readblob()Read file{fname} in binary mode and returnaBlob.If{offset}is specified, read the file from the specifiedoffset. Ifitisa negative value,itis usedas an offsetfrom theend of the file. E.g., to read the last 12 bytes:readblob('file.bin', -12)If{size}is specified, only the specified size will be read.E.g. to read the first 100 bytes ofa file:readblob('file.bin', 0, 100)If{size}is -1 or omitted, the whole datastarting from{offset} will be read.This can be also used to read the data froma character deviceonUnix when{size}is explicitly set. Only if the devicesupports seeking{offset} can be used. Otherwiseit should bezero. E.g. to read 10 bytes froma serial console:readblob('/dev/ttyS0', 0, 10)When the file can't be opened an error messageis given andthe resultis an emptyBlob.When the offsetis beyond theend of the file the resultis anempty blob.When trying to read more bytes than are available the resultis truncated.Also seereadfile() andwritefile().Return type:Blobreaddir({directory} [,{expr} [,{dict}]])readdir()Returnalist with file and directory names in{directory}.You can also useglob() if you don't need todo complicatedthings, suchas limiting the number of matches.Thelist will be sorted (case sensitive), see the{dict}argument below forchanging the sort order.When{expr}is omitted all entries are included.When{expr}is given,itis evaluated to check what to do:If{expr} results in -1 then no further entries willbe handled.If{expr} results in0 then this entry will not beadded to the list.If{expr} results in 1 then this entry will be addedto the list.The entries "." and ".." are always excluded.Each time{expr}is evaluatedv:valis set to the entry name.When{expr}isa function the nameis passedas the argument.For example, to getalist of files ending in ".txt": readdir(dirname, {n -> n =~ '.txt$'})To skip hidden andbackup files: readdir(dirname, {n -> n !~ '^\.\|\~$'})E857The optional{dict} argument allows for further customvalues. Currently thisis used to specify if and howsortingshould be performed. Thedict can have the following members: sort How to sort the result returned from the system. Valid values are:"none"do not sort (fastest method)"case" sortcase sensitive (byte value of each character, technically, using strcmp()) (default)"icase" sortcase insensitive (technically using strcasecmp())"collate" sort using the collation order of the "POSIX" or "C"locale (technically using strcoll()) Other values are silently ignored.For example, to getalist of all files in the currentdirectory withoutsorting the individual entries: readdir('.', '1', #{sort: 'none'})If you want to geta directory tree: function! s:tree(dir) return {a:dir : map(readdir(a:dir), \ {_, x -> isdirectory(x) ? \ {x : s:tree(a:dir .. '/' .. x)} : x})} endfunction echo s:tree(".")Returns an emptyList on error.Can also be usedasamethod:GetDirName()->readdir()Return type: list<string> or list<any>readdirex({directory} [,{expr} [,{dict}]])readdirex()Extended version ofreaddir().Returnalist ofDictionaries with file and directoryinformation in{directory}.Thisis useful if you want to get the attributes of file anddirectoryat the same timeas gettingalist ofa directory.Thisis much faster than callingreaddir() then callinggetfperm(),getfsize(),getftime() andgetftype() foreach file and directory especially on MS-Windows.Thelist will by default be sorted by name (case sensitive),thesorting can be changed by using the optional{dict}argument, seereaddir().TheDictionary for file and directory information has thefollowing items:groupGroup name of the entry. (Only on Unix)nameName of the entry.permPermissions of the entry. Seegetfperm().sizeSize of the entry. Seegetfsize().timeTimestamp of the entry. Seegetftime().typeType of the entry.On Unix, almost sameasgetftype() except: Symlink toa dir"linkd" Other symlink"link"On MS-Windows:Normal file"file" Directory"dir" Junction"junction" Symlink toa dir"linkd" Other symlink"link" Other reparse point"reparse"userUser name of the entry's owner. (Only on Unix)On Unix, if the entryisa symlink, theDictionary includesthe information of the target (except the "type" item).On MS-Windows,it includes the information of the symlinkitself because of performance reasons.When{expr}is omitted all entries are included.When{expr}is given,itis evaluated to check what to do:If{expr} results in -1 then no further entries willbe handled.If{expr} results in0 then this entry will not beadded to the list.If{expr} results in 1 then this entry will be addedto the list.The entries "." and ".." are always excluded.Each time{expr}is evaluatedv:valis set toaDictionaryof the entry.When{expr}isa function the entryis passedas the argument.For example, to getalist of files ending in ".txt": readdirex(dirname, {e -> e.name =~ '.txt$'})For example, to getalist of all files in the currentdirectory withoutsorting the individual entries: readdirex(dirname, '1', #{sort: 'none'})Can also be usedasamethod:GetDirName()->readdirex()Return type: list<dict<any>> or list<any>readfile()readfile({fname} [,{type} [,{max}]])Read file{fname} and returnaList, each line of the fileas an item. Lines are brokenat NL characters.Macintoshfiles separated with CR will result ina single long line(unlessa NL appears somewhere).All NUL characters are replaced witha NL character.When{type} contains "b" binary modeis used:- When the last line ends ina NL an extra emptylist itemis added.- No CR characters are removed.Otherwise:- CR characters that appear beforea NL are removed.- Whether the last line ends ina NL or not does not matter.- When'encoding'isUnicode anyUTF-8 byte ordermarkis removed from the text.When{max}is given thisspecifies the maximum number of linesto be read. Useful if you only want to check the first tenlines ofa file::for line in readfile(fname, '', 10): if line =~ 'Date' | echo line | endif:endforWhen{max}is negative -{max} lines from theend of the fileare returned, oras manyas there are.When{max}is zero the resultis an empty list.Note that without{max} the whole fileis read into memory.Alsonote that thereis no recognition of encoding. Readafile intoa buffer if you need to.Deprecated (usereadblob() instead): When{type} contains"B"aBlobis returned with the binary data of the fileunmodified.When the file can't be opened an error messageis given andthe resultis an empty list.Also seewritefile().Can also be usedasamethod:GetFileName()->readfile()Return type: list<string> or list<any>reduce({object},{func} [,{initial}])reduce()E998{func}is called for every item in{object}, which can beaString,List,Tuple oraBlob.{func}is called withtwo arguments: the result so far and current item. Afterprocessing all items the resultis returned.E1132{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, anE998 erroris given.Examples:echo reduce([1, 3, 5], { acc, val -> acc + val })echo reduce(['x', 'y'], { acc, val -> acc .. val }, 'a')echo reduce(0z1122, { acc, val -> 2 * acc + val })echo reduce('xyz', { acc, val -> acc .. ',' .. val })Can also be usedasamethod:echo mylist->reduce({ acc, val -> acc + val }, 0)Return type:String,Blob, list<{type}> or dict<{type}>depending on{object} and{func}reg_executing()reg_executing()Returns the singleletter name of theregister being executed.Returns an emptystring when noregisteris being executed.See@.Return type:Stringreg_recording()reg_recording()Returns the singleletter name of theregister being recorded.Returns an emptystring when not recording. Seeq.Return type:Stringreltime()reltime()reltime({start})reltime({start},{end})Return an item that representsa time value. The itemisalist with items that depend on the system. In Vim 9scriptthe type list<any> can be used.The item can be passed toreltimestr() to convertit toastring orreltimefloat() to convert toa Float. Forexample, to see the time spent in function Work():var startTime = reltime()Work()echo startTime->reltime()->reltimestr()Without an argumentreltime() returns the current time (therepresentationis system-dependent,it cannot be usedas thewall-clock time, seelocaltime() for that).With one argumentit returns the time passed since the timespecified in the argument.With two argumentsit returns the time passed between{start}and{end}.The{start} and{end} argumentsmust be values returned byreltime(). If thereis an error an emptyListis returned inlegacy script, inVim9script an erroris given.Can also be usedasamethod:GetStart()->reltime()Return type: list<number>{only available when compiled with the |+reltime| feature}reltimefloat({time})reltimefloat()ReturnaFloat that represents the time value of{time}.Example:let start = reltime()call MyFunction()let seconds = reltimefloat(reltime(start))See thenote ofreltimestr() about overhead.Also seeprofiling.If thereis an error 0.0is returned in legacy script, inVim9script an erroris given.Can also be usedasamethod:reltime(start)->reltimefloat()Return type:Float{only available when compiled with the |+reltime| feature}reltimestr({time})reltimestr()ReturnaString that represents the time value of{time}.Thisis the number of seconds,a dot and the number ofmicroseconds. Example:let start = reltime()call MyFunction()echo reltimestr(reltime(start))Note that overhead for the commands will be added to the time.The accuracy depends on the system. Usereltimefloat() for thegreatest accuracy whichis nanoseconds on some systems.Leading spaces are used to make thestring align nicely. Youcan usesplit() to remove it.echo split(reltimestr(reltime(start)))[0]Also seeprofiling.If thereis an error an emptystringis returned in legacyscript, inVim9script an erroris given.Can also be usedasamethod:reltime(start)->reltimestr()Return type:String{only available when compiled with the |+reltime| feature}remote_expr()E449remote_expr({server},{string} [,{idvar} [,{timeout}]])Send the{string} to{server}. The{server} argumentisastring, also see{server}.Thestringis sentas anexpression and the resultis returnedafter evaluation. The resultmust beaString oraListother types will be converted to String.AListis turnedintoaString by joining the items witha line break inbetween (notat the end), like with join(expr, "\n").If{idvar}is present and not empty,itis takenas the nameofa variable anda{serverid} for later use withremote_read()is stored there.If{timeout}is given the read times out after this manyseconds. Otherwisea timeout of 600 secondsis used.See alsoclientserverRemoteReply.This functionis not available in thesandbox.{only available when compiled with the |+clientserver| feature}Note: Anyerrors will causea local error message to be issuedand the result will be the empty string.Variables will be evaluated in the global namespace,independent ofa function currently being active. Exceptwhen in debug mode, then local functionvariables andarguments can be evaluated.Examples::echo remote_expr("gvim", "2+2"):echo remote_expr("gvim1", "b:current_syntax")Can also be usedasamethod:ServerName()->remote_expr(expr)Return type:String or list<{type}>remote_foreground({server})remote_foreground()Move the Vim server with the name{server} to the foreground.The{server} argumentisa string, also see{server}.This works like:remote_expr({server}, "foreground()")Except that onWin32 systems the client does the work, to workaround the problem that the OS doesn't always allow the serverto bring itself to the foreground.Note: This does not restore thewindow ifit was minimized,likeforeground() does.This functionis not available in thesandbox.Can also be usedasamethod:ServerName()->remote_foreground()Return type:Number{only in the Win32,Motif andGTKGUI versions and theWin32 console version}remote_peek({serverid} [,{retvar}])remote_peek()Returnsa positive number if there are available stringsfrom{serverid}. Copies any replystring into the variable{retvar} if specified.{retvar}must beastring with thename ofa variable.Returns zero if none are available.Returns -1 if somethingis wrong.See alsoclientserver.This functionis not available in thesandbox.{only available when compiled with the |+clientserver| feature}Examples: :let repl = "" :echo "PEEK: " .. remote_peek(id, "repl") .. ": " .. replCan also be usedasamethod:ServerId()->remote_peek()Return type:Numberremote_read({serverid}, [{timeout}])remote_read()Return the oldest available reply from{serverid} and consumeit. Unlessa{timeout} in secondsis given,it blocks untilareplyis available. Returns an empty string, ifa replyisnot available or on error.See alsoclientserver.This functionis not available in thesandbox.{only available when compiled with the |+clientserver| feature}Example::echo remote_read(id)Can also be usedasamethod:ServerId()->remote_read()Return type:Stringremote_send({server},{string} [,{idvar}])remote_send()E241Send the{string} to{server}. The{server} argumentisastring, also see{server}.Thestringis sentas input keys and the function returnsimmediately. At the Vim server the keys are not mapped:map.If{idvar}is present,itis takenas the name ofa variableanda{serverid} for later use withremote_read()is storedthere.See alsoclientserverRemoteReply.This functionis not available in thesandbox.{only available when compiled with the |+clientserver| feature}Note: Anyerrors will be reported in the server and may messup the display.Examples::echo remote_send("gvim", ":DropAndReply " .. file, "serverid") .. \ remote_read(serverid):autocmd NONE RemoteReply * \ echo remote_read(expand("<amatch>")):echo remote_send("gvim", ":sleep 10 | echo " .. \ 'server2client(expand("<client>"), "HELLO")<CR>')Can also be usedasamethod:ServerName()->remote_send(keys)Return type:Stringremote_startserver({name})remote_startserver()E941E942Become the server{name}.{name}must bea non-empty string.This fails if already runningasa server, whenv:servernameis not empty.Can also be usedasamethod:ServerName()->remote_startserver()Return type:Number{only available when compiled with the |+clientserver| feature}remove({list},{idx})remove()remove({list},{idx},{end})Without{end}: Remove the itemat{idx} fromList{list} andreturn the item.With{end}: Remove items from{idx} to{end} (inclusive) andreturnaList with these items. When{idx} points to the sameitemas{end}alist with one itemis returned. When{end}points to an item before{idx} thisis an error.Seelist-index for possible values of{idx} and{end}.Returns zero on error.Example::echo "last item: " .. remove(mylist, -1):call remove(mylist, 0, 9)Usedelete() to removea file.Can also be usedasamethod:mylist->remove(idx)Return type: any, depending on{list}remove({blob},{idx})remove({blob},{idx},{end})Without{end}: Remove the byteat{idx} fromBlob{blob} andreturn the byte.With{end}: Remove bytes from{idx} to{end} (inclusive) andreturnaBlob with these bytes. When{idx} points to the samebyteas{end}aBlob with one byteis returned. When{end}points toa byte before{idx} thisis an error.Returns zero on error.Example::echo "last byte: " .. remove(myblob, -1):call remove(mylist, 0, 9)Return type:Numberremove({dict},{key})Remove the entry from{dict} with key{key} and return it.Example::echo "removed " .. remove(dict, "one")If thereis no{key} in{dict} thisis an error.Returns zero on error.Return type: any, depending on{dict}rename({from},{to})rename()Rename the file by the name{from} to the name{to}. Thisshould also work to move files across file systems. Theresultisa Number, whichis0 if the file was renamedsuccessfully, and non-zero when the renaming failed.NOTE: If{to} existsitis overwritten without warning.This functionis not available in thesandbox.Can also be usedasamethod:GetOldName()->rename(newname)Return type:Numberrepeat({expr},{count})repeat()Repeat{expr}{count} times and return the concatenatedresult. Example::let separator = repeat('-', 80)When{count}is zero or negative the resultis empty.When{expr}isaList,aTuple oraBlob the resultis{expr} concatenated{count} times. Example::let longlist = repeat(['a', 'b'], 3)Results in ['a', 'b', 'a', 'b', 'a', 'b'].Can also be usedasamethod:mylist->repeat(count)Return type:String,Blob, list<{type}> or tuple<{type}>depending on{expr}resolve({filename})resolve()E655On MS-Windows, when{filename}isa shortcut (a .lnk file),returns the path the shortcut points to ina simplified form.When{filename}isa symbolic link or junction point, returnthe full path to the target. If the target of junctionisremoved, return{filename}.On Unix, repeat resolving symbolic links in all pathcomponents of{filename} and return the simplified result.To cope with link cycles, resolving of symbolic linksisstopped after 100 iterations.On other systems, return the simplified{filename}.The simplification stepis doneas bysimplify().resolve() keepsa leading path component specifying thecurrent directory (provided the resultis stilla relativepath name) and also keepsa trailing path separator.Can also be usedasamethod:GetName()->resolve()Return type:Stringreverse({object})reverse()Reverse the order of items in{object}.{object} can beaList,aTuple,aBlob oraString. ForaList andaBlob the items are reversed in-place and{object}is returned.Fora Tuple,a newTupleis returned.ForaStringa newStringis returned.Returns zero if{object}is nota List, Tuple,Blob oraString. If you wantaList orBlob to remain unmodified makea copy first::let revlist = reverse(copy(mylist))Can also be usedasamethod:mylist->reverse()Return type:String,Blob, list<{type}> or tuple<{type}>depending on{object}round({expr})round()Round off{expr} to the nearest integral value and returnitasaFloat. If{expr} lies halfway between two integralvalues, then use the larger one (away from zero).{expr}must evaluate toaFloat oraNumber.Returns 0.0 if{expr}is notaFloat oraNumber.Examples:echo round(0.456)0.0echo round(4.5)5.0echo round(-4.5)-5.0Can also be usedasamethod:Compute()->round()Return type:Floatrubyeval({expr})rubyeval()EvaluateRubyexpression{expr} and return its resultconverted to Vim data structures.Numbers, floats and strings are returnedas they are (stringsare copied though).Arrays are representedas VimList type.Hashes are representedas VimDictionary type.Otherobjects are representedas strings resulted from their"Object#to_s" method.Note that ina:def function localvariables are not visibleto{expr}.Can also be usedasamethod:GetRubyExpr()->rubyeval()Return type: any, depending on{expr}{only available when compiled with the |+ruby| feature}screenattr({row},{col})screenattr()Likescreenchar(), but return the attribute. Thisisa ratherarbitrary number that can only be used to compare to theattributeat other positions.Returns -1 when row or colis out of range.Can also be usedasamethod:GetRow()->screenattr(col)Return type:Numberscreenchar({row},{col})screenchar()The resultisa Number, whichis the characterat position[row, col] on the screen. This works for every possiblescreen position, also status lines,window separators and thecommand line. The top left positionis row one, column oneThe character excludes composing characters. For double-byteencodingsit may only be the first byte.Thisis mainly to be used for testing.Returns -1 when row or colis out of range.Can also be usedasamethod:GetRow()->screenchar(col)Return type:Numberscreenchars({row},{col})screenchars()The resultisaList of Numbers. The first numberis the sameas whatscreenchar() returns. Further numbers arecomposing characters on top of the base character.Thisis mainly to be used for testing.Returns an emptyList when row or colis out of range.Can also be usedasamethod:GetRow()->screenchars(col)Return type: list<number> or list<any>screencol()screencol()The resultisa Number, whichis the current screen column ofthe cursor. The leftmost column has number 1.This functionis mainly used for testing.Note: Always returns the current screen column, thus if usedina command (e.g. ":echoscreencol()")it will return thecolumn inside the command line, whichis 1 when the commandisexecuted. To get the cursor position in the file use one ofthe following mappings:nnoremap <expr> GG ":echom " .. screencol() .. "\n"nnoremap <silent> GG :echom screencol()<CR>nnoremap GG <Cmd>echom screencol()<CR>Return type:Numberscreenpos({winid},{lnum},{col})screenpos()The resultisaDict with the screen position of the textcharacter inwindow{winid}at buffer line{lnum} and column{col}.{col}isa one-based byte index.TheDict has these members:rowscreen rowcolfirst screen columnendcollast screen columncurscolcursor screen columnIf the specified positionis not visible, all values are zero.The "endcol" value differs from "col" when the characteroccupies more than one screen cell. E.g. foraTab "col" canbe 1 and "endcol" can be 8.The "curscol" valueis where the cursor would be placed. ForaTabit would be the sameas "endcol", while fora doublewidth characterit would be the sameas "col".Theconceal featureis 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 positionis ina closed fold the screen position of thefirst characteris returned,{col}is not used.Returns an emptyDict if{winid}is invalid.Can also be usedasamethod:GetWinid()->screenpos(lnum, col)Return type: dict<number> or dict<any>screenrow()screenrow()The resultisa Number, whichis the current screen row of thecursor. The top line has number one.This functionis mainly used for testing.Alternatively you can usewinline().Note: Same restrictionsas withscreencol().Return type:Numberscreenstring({row},{col})screenstring()The resultisaString that contains the base character andany composing charactersat position [row, col] on the screen.Thisis likescreenchars() but returningaString with thecharacters.Thisis mainly to be used for testing.Returns an emptyString when row or colis out of range.Can also be usedasamethod:GetRow()->screenstring(col)Return type:Stringsearch()search({pattern} [,{flags} [,{stopline} [,{timeout} [,{skip}]]]])Search forregexppattern{pattern}. The search startsat thecursor position (you can usecursor() to set it).Whena match has been found its line numberis returned.If thereis no matcha0is returned and the cursor doesn'tmove. No error messageis given.To get the matched string, usematchbufline().{flags}isa String, which can contain these character flags:'b'search Backward instead of forward'c'accepta matchat 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'markat the previous location of the cursor'w'Wrap around theend of the file'W'don't Wrap around theend of the file'z'start searchingat the cursor column instead of ZeroIf neither 'w' or 'W'is given, the'wrapscan' option applies.If the 's' flagis supplied, the'markis set, only if thecursoris moved. The 's' flag cannot be combined with the 'n'flag.'ignorecase','smartcase' and'magic' are used.When the 'z' flagis not given, forward searching alwaysstarts in column zero and then matches before the cursor areskipped. When the 'c' flagis present in'cpo' the nextsearch starts after the match. Without the 'c' flag the nextsearch starts one column after the start of the match. Thismatters for overlapping matches. Seecpo-c. You can alsoinsert "\ze" to change where the match ends, see/\ze.When searching backwards and the 'z' flagis given then thesearch starts in column zero, thus no match in the currentline will be found (unless wrapping around theend of thefile).When the{stopline} argumentis given then the search stopsafter searching this line. Thisis useful to restrict thesearch toa range of lines. Examples:let match = search('(', 'b', line("w0"))let end = search('END', '', line("w$"))When{stopline}is used anditis not zero this also impliesthat the search does not wrap around theend of the file.A zero valueis equal to not giving the argument.E1285E1286E1287E1288E1289When the{timeout} argumentis given the search stops whenmore than this many milliseconds have passed. Thus when{timeout}is 500 the search stops after halfa second.The valuemust not be negative.A zero valueis like notgiving the argument.Note: the timeoutis only considered when searching, notwhile evaluating the{skip} expression.{only available when compiled with the |+reltime| feature}If the{skip}expressionis givenitis evaluated with thecursor positioned on the start ofa match. Ifit evaluates tonon-zero this matchis skipped. This can be used, forexample, to skipa match ina comment ora string.{skip} can bea string, whichis evaluatedas an expression,afunctionreference ora lambda.When{skip}is omitted or empty, every matchis accepted.When evaluating{skip} causes an error the searchis abortedand -1 returned.search()-sub-matchWith the 'p' flag the returned valueis one more than thefirst sub-match in \(\). One if none of them matched but thewholepattern did match.To get the column number too usesearchpos().The cursor will be positionedat the match, unless the 'n'flagis used.Example (goes over all files in the argument list): :let n = 1 :while 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 + 1 :endwhileExample for using some flags: :echo search('\<if\|\(else\)\|\(endif\)', 'ncpe')This will search for the keywords "if", "else", and "endif"under or after the cursor. Because of the 'p' flag,itreturns 1, 2, or 3 depending on which keywordis found, or0if the search fails. With the cursor on the firstword of theline: if (foo == 0) | let foo = foo + 1 | endifthe function returns 1. Without the 'c' flag, the functionfinds the "endif" and returns 3. The same thing happenswithout the 'e' flag if the cursoris on the "f" of "if".The 'n' flag tells the function not to move the cursor.Can also be usedasamethod:GetPattern()->search()Return type:Numbersearchcount([{options}])searchcount()Get or update the last search count, like whatis displayedwithout the "S" flag in'shortmess'. This works even if'shortmess' does contain the "S" flag.This returnsaDictionary. The dictionaryis empty if thepreviouspattern was not set and "pattern" was not specified. keytypemeaning currentNumber current position of match;0 if the cursor positionisbefore the first match exact_matchBoolean 1 if "current"is matched on"pos", otherwise0 totalNumber totalcount of matches found incompleteNumber 0: search was fully completed1: recomputing was timed out2: maxcount exceededFor{options} see further down.To get the last searchcount whenn orN was pressed, callthis function with `recompute: 0`. This sometimes returnswrong information becausen andN's maximumcountis 99.Ifit exceeded 99 the resultmust be maxcount+ 1 (100). Ifyou want to get correct information, specify `recompute: 1`:" result == maxcount + 1 (100) when many matcheslet result = searchcount(#{recompute: 0})" Below returns correct result (recompute defaults" to 1)let result = searchcount()The functionis useful to add thecount to'statusline':function! LastSearchCount() abort let result = searchcount(#{recompute: 0}) if empty(result) return '' endif if result.incomplete ==# 1 " timed out return printf(' /%s [?/??]', @/) elseif result.incomplete ==# 2 " max count exceeded if result.total > result.maxcount && \ result.current > result.maxcount return printf(' /%s [>%d/>%d]', @/, \ result.current, result.total) elseif result.total > result.maxcount return printf(' /%s [%d/>%d]', @/, \ result.current, result.total) endif endif return printf(' /%s [%d/%d]', @/, \result.current, result.total)endfunctionlet &statusline ..= '%{LastSearchCount()}'" Or if you want to show the count only when" 'hlsearch' was on" let &statusline ..=" \ '%{v:hlsearch ? LastSearchCount() : ""}'You can also update the search count, which can be useful inaCursorMoved orCursorMovedI autocommand:autocmd CursorMoved,CursorMovedI * \ let s:searchcount_timer = timer_start( \ 200, function('s:update_searchcount'))function! s:update_searchcount(timer) abort if a:timer ==# s:searchcount_timer call searchcount(#{ \ recompute: 1, maxcount: 0, timeout: 100}) redrawstatus endifendfunctionThis can also be used tocount matched texts with specifiedpattern in the current buffer using "pattern":" Count '\<foo\>' in this buffer" (Note that it also updates search count)let result = searchcount(#{pattern: '\<foo\>'})" To restore old search count by old pattern," search againcall searchcount(){options}must beaDictionary. It can contain: keytypemeaning recomputeBoolean ifTRUE, recompute thecountliken orN was executed.otherwise returns the lastcomputed result (whenn orN was used when "S"is notin'shortmess', or thisfunction was called).(default:TRUE)patternString recompute if this was givenand different with@/.this worksas sameas thebelow commandis executedbefore calling this function let @/ = pattern(default:@/) timeoutNumber0 or negative numberis notimeout. timeout millisecondsfor recomputing the result(default: 0) maxcountNumber0 or negative numberis nolimit. maxcount of matchedtext while recomputing theresult. if search exceededtotal count, "total" valuebecomes `maxcount+ 1`(default: 99) posList `[lnum, col, off]` valuewhen recomputing the result.this changes "current" resultvalue. seecursor(),getpos()(default: cursor's position)Can also be usedasamethod:GetSearchOpts()->searchcount()Return type: dict<number>searchdecl({name} [,{global} [,{thisblock}]])searchdecl()Search for the declaration of{name}.Witha non-zero{global} argumentit works likegD, findfirst match in the file. Otherwiseit works likegd, findfirst match in the function.Witha non-zero{thisblock} argument matches ina{} blockthat ends before the cursor position are ignored. Avoidsfinding variable declarations only valid in another scope.Moves the cursor to the found match.Returns zero for success, non-zero for failure.Example:if searchdecl('myvar') == 0 echo getline('.')endifCan also be usedasamethod:GetName()->searchdecl()Return type:Numbersearchpair()searchpair({start},{middle},{end} [,{flags} [,{skip}[,{stopline} [,{timeout}]]]])Search for the match ofa 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 startsat the cursor. The defaultis to searchforward, include 'b' in{flags} to search backward.Ifa matchis found, the cursoris positionedatit and theline numberis returned. If no matchis found0 or -1isreturned and the cursor doesn't move. No error messageisgiven.{start},{middle} and{end} are patterns, seepattern. Theymust not contain \( \) pairs. Use of \%( \)is allowed. When{middle}is not empty,itis found when searching from eitherdirection, but only when not ina nested start-end pair.Atypical use is:searchpair('\<if\>', '\<else\>', '\<endif\>')By leaving{middle} empty the "else"is skipped.{flags} 'b', 'c', 'n', 's', 'w' and 'W' are used like withsearch(). Additionally:'r'Repeat until no more matches found; will find theouter pair. Implies the 'W' flag.'m'Return number of matches instead of line number withthe match; will be> 1 when 'r'is used.Note: it's nearly alwaysa good idea to use the 'W' flag, toavoid wrapping around theend of the file.Whena match for{start},{middle} or{end}is found, the{skip}expressionis evaluated with the cursor positioned onthe start of the match. It should return non-zero if thismatchis to be skipped. E.g., becauseitis insidea commentora string.When{skip}is omitted or empty, every matchis accepted.When evaluating{skip} causes an error the searchis abortedand -1 returned.{skip} can bea string,a lambda,a funcref ora partial.Anything else makes the function fail.Ina:def function when the{skip} argumentisastringconstantitis compiled into instructions.For{stopline} and{timeout} seesearch().The value of'ignorecase'is used.'magic'is ignored, thepatterns are used like it's on.The search starts exactlyat the cursor.A match with{start},{middle} or{end}at the next character, in thedirection of searching,is the first one found. Example:if 1 if 2 endif 2endif 1Whenstartingat the "if 2", with the cursor on the "i", andsearching forwards, the "endif 2"is found. Whenstarting onthe character just before the "if 2", the "endif 1" will befound. That's because the "if 2" will be found first, andthen thisis considered to bea nested if/endif from "if 2" to"endif 2".When searching backwards and{end}is more than one character,it may be useful toput "\zs"at theend of the pattern, sothat when the cursoris insidea match with theendit findsthe matching start.Example, to find the "endif" command ina Vim script::echo searchpair('\<if\>', '\<el\%[seif]\>', '\<en\%[dif]\>', 'W',\ 'getline(".") =~ "^\\s*\""')The cursormust beat or after the "if" for whicha matchisto be found.Note that single-quote strings are used to avoidhaving to double the backslashes. The skipexpression onlycatches commentsat the start ofa line, not aftera command.Also,aword "en" or "if" halfwaya lineis consideredamatch.Another example, to search for the matching "{" of a "}"::echo searchpair('{', '', '}', 'bW')This works when the cursorisat or before the "}" for whichamatchis to be found. To reject matches thatsyntaxhighlighting recognizedas strings::echo searchpair('{', '', '}', 'bW', \ 'synIDattr(synID(line("."), col("."), 0), "name") =~? "string"')Return type:Numbersearchpairpos()searchpairpos({start},{middle},{end} [,{flags} [,{skip}[,{stopline} [,{timeout}]]]])Sameassearchpair(), but returnsaList with the line andcolumn position of the match. The first element of theListis the line number and the second elementis the byteindex ofthe column position of the match. If no matchis found,returns [0, 0].:let [lnum,col] = searchpairpos('{', '', '}', 'n')Seematch-parens fora bigger and more useful example.Return type: list<number>searchpos()searchpos({pattern} [,{flags} [,{stopline} [,{timeout} [,{skip}]]]])Sameassearch(), but returnsaList with the line andcolumn position of the match. The first element of theListis the line number and the second elementis the byteindex ofthe column position of the match. If no matchis found,returns [0, 0].Example::let [lnum, col] = searchpos('mypattern', 'n')When the 'p' flagis given then thereis an extra item withthe sub-pattern match numbersearch()-sub-match. Example::let [lnum, col, submatch] = searchpos('\(\l\)\|\(\u\)', 'np')In this example "submatch"is 2 whenalowercaseletterisfound/\l, 3 when anuppercaseletteris found/\u.Can also be usedasamethod:GetPattern()->searchpos()Return type: list<number>server2client({clientid},{string})server2client()Senda replystring to{clientid}. The most recent{clientid}that sentastring can be retrieved with expand("<client>").{only available when compiled with the |+clientserver| feature}Returns zero for success, -1 for failure.Note:This id has to be stored before the next command can bereceived. I.e. before returning from the received command andbefore calling any commands that waits for input.See alsoclientserver.Example::echo server2client(expand("<client>"), "HELLO")Can also be usedasamethod:GetClientId()->server2client(string)Return type:Numberserverlist()serverlist()Returnalist of available server names, one per line.When there are no servers or the informationis not availablean emptystringis returned. See alsoclientserver.{only available when compiled with the |+clientserver| feature}Example::echo serverlist()Return type:Stringsetbufline({buf},{lnum},{text})setbufline()Set line{lnum} to{text} in buffer{buf}. This works likesetline() for the specified buffer.This function works only for loaded buffers. First callbufload() if needed.Toinsert lines useappendbufline().Any text properties in{lnum} are cleared.{text} can beastring to set one line, oraList of stringsto set multiple lines. If theListextends below the lastline then those lines are added. If theListis empty thennothingis changed and zerois returned.For the use of{buf}, seebufname() above.{lnum}is used like withsetline().Use "$" to refer to the last line in buffer{buf}.When{lnum}is just below the last line the{text} will beadded below the last line.When{buf}is nota valid buffer, the bufferis not loaded or{lnum}is not valid then 1is returned. InVim9script anerroris given.On success0is returned.Can also be usedasamethod, the baseis passedas thethird argument:GetText()->setbufline(buf, lnum)Return type:Numbersetbufvar({buf},{varname},{val})setbufvar()Set option or local variable{varname} in buffer{buf} to{val}.This also works fora global or localwindow option, butitdoesn't work fora global or localwindow variable.Fora localwindow option the global valueis unchanged.For the use of{buf}, seebufname() above.The{varname} argumentisa string.Note that the variable name without "b:"must be used.Examples::call setbufvar(1, "&mod", 1):call setbufvar("todo", "myvar", "foobar")This functionis not available in thesandbox.Can also be usedasamethod, the baseis passedas thethird argument:GetValue()->setbufvar(buf, varname)Return type:Numbersetcellwidths({list})setcellwidths()Specify overrides for cell widths of character ranges. Thistells Vim how wide characters are when displayed in theterminal, counted in screen cells. The values override'ambiwidth'. Example: call setcellwidths([\ [0x111, 0x111, 1],\ [0x2194, 0x2199, 2],\ ])The{list} argumentisaList ofLists with each threenumbers: [{low},{high},{width}].E1109E1110{low} and{high} can be the same, in whichcase this refers toone character. Otherwiseitis 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.E1112An erroris given if the argumentis invalid, also whenarange overlaps with another.E1113If the new value causes'fillchars' or'listchars' to becomeinvaliditis rejected and an erroris given.To clear the overrides pass an empty{list}: setcellwidths([]);You can use thescript $VIMRUNTIME/tools/emoji_list.vim to seethe effect for known emoji characters. Move the cursorthrough the text to check if the cell widths of yourterminalmatch with what Vim knows about each emoji. Ifit doesn'tlook right you need to adjust the{list} argument.Return type:Numbersetcharpos({expr},{list})setcharpos()Sameassetpos() but uses the specified column numberas thecharacterindex instead of the byteindex in the line.Example:With the text "여보세요" in line 8:call setcharpos('.', [0, 8, 4, 0])positions the cursor on the fourth character'요'.call setpos('.', [0, 8, 4, 0])positions the cursor on the second character'보'.Can also be usedasamethod:GetPosition()->setcharpos('.')Return type:Numbersetcharsearch({dict})setcharsearch()Set the current character search information to{dict},which contains one or more of the following entries: charcharacter which will be used fora subsequent, or; command; an emptystring clears thecharacter search forwarddirection of character search; 1 for forward,0 for backward untiltype of character search; 1 forat orTcharacter search,0 for anf orFcharacter searchThis can be useful to save/restorea user's character searchfroma script::let prevsearch = getcharsearch():" Perform a command which clobbers user's search:call setcharsearch(prevsearch)Also seegetcharsearch().Can also be usedasamethod:SavedSearch()->setcharsearch()Return type: dict<any>setcmdline({str} [,{pos}])setcmdline()Set the command line to{str} and set the cursor position to{pos}.If{pos}is omitted, the cursoris positioned after the text.Returns0 when successful, 1 when not editing the commandline.Can also be usedasamethod:GetText()->setcmdline()Return type:Numbersetcmdpos({pos})setcmdpos()Set the cursor position in the command line to byte position{pos}. The first positionis 1.Usegetcmdpos() to obtain the current position.Only works while editing the command line, thus youmust usec_CTRL-\_e,c_CTRL-R_= orc_CTRL-R_CTRL-R with '='. Forc_CTRL-\_e andc_CTRL-R_CTRL-R with '=' the positionisset after the command lineis set to the expression. Forc_CTRL-R_=itis set after evaluating theexpression butbeforeinserting the resulting text.When the numberis too big the cursorisputat theend of theline.A number smaller than one has undefined results.Returns0 when successful, 1 when not editing the commandline.Can also be usedasamethod:GetPos()->setcmdpos()Return type:Numbersetcursorcharpos({lnum},{col} [,{off}])setcursorcharpos()setcursorcharpos({list})Sameascursor() but uses the specified column numberas thecharacterindex instead of the byteindex in the line.Example:With the text "여보세요" in line 4:call setcursorcharpos(4, 3)positions the cursor on the third character'세'.call cursor(4, 3)positions the cursor on the first character'여'.Can also be usedasamethod:GetCursorPos()->setcursorcharpos()Returns0 when the position could be set, -1 otherwise.Return type:Numbersetenv({name},{val})setenv()Set environment variable{name} to{val}. Example:call setenv('HOME', '/home/myhome')When{val}isv:null the environment variableis deleted.See alsoexpr-env.Can also be usedasamethod, the baseis passedas thesecond argument:GetPath()->setenv('PATH')Return type:Numbersetfperm({fname},{mode})setfperm()chmodSet the file permissions for{fname} to{mode}.{mode}must beastring with 9 characters. Itis 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 thepermissionis off, any other character means on. Multi-bytecharacters are not supported.For example "rw-r-----" means read-write for the user,readable by the group, not accessible by others. "xx-x-----"woulddo the same thing.Returns non-zero for success, zero for failure.Can also be usedasamethod:GetFilename()->setfperm(mode)To read permissions seegetfperm().Return type:Numbersetline({lnum},{text})setline()Set line{lnum} of the current buffer to{text}. Toinsertlines useappend(). To set lines in another buffer usesetbufline().Any text properties in{lnum} are cleared. Seetext-prop-cleared{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 oraList of any type, each itemisconverted toa String. When{text}is an emptyList thennothingis changed andFALSEis returned.If this succeeds,FALSEis returned. If this fails (most likelybecause{lnum}is invalid)TRUEis returned.InVim9script an erroris given if{lnum}is invalid.Example::call setline(5, strftime("%c"))When{text}isaList then line{lnum} and following lineswill be set to the items in the list. Example::call setline(5, ['aaa', 'bbb', 'ccc'])Thisis equivalent to::for [n, l] in [[5, 'aaa'], [6, 'bbb'], [7, 'ccc']]: call setline(n, l):endforNote: The'[ and'] marks are not set.Can also be usedasamethod, the baseis passedas thesecond argument:GetText()->setline(lnum)Return type:Numbersetloclist({nr},{list} [,{action} [,{what}]])setloclist()Create or replace or add to the locationlist forwindow{nr}.{nr} can be thewindow number or thewindow-ID.When{nr}is zero the currentwindowis used.Fora locationlist window, the displayed locationlistismodified. For an invalidwindow number{nr}, -1is returned.Otherwise, sameassetqflist().Also seelocation-list.For{action} seesetqflist-action.If the optional{what} dictionary argumentis supplied, thenonly the items listed in{what} are set. Refer tosetqflist()for thelist of supported keys in{what}.Can also be usedasamethod, the baseis passedas thesecond argument:GetLoclist()->setloclist(winnr)Return type:Numbersetmatches({list} [,{win}])setmatches()Restoresalist of matches saved bygetmatches() for thecurrent window. Returns0 if successful, otherwise -1. Allcurrent matches are cleared before thelistis restored. Seeexample forgetmatches().If{win}is specified, use thewindow with this number orwindow ID instead of the current window.Can also be usedasamethod:GetMatches()->setmatches()Return type:Numbersetpos({expr},{list})setpos()Set the position forString{expr}. Possible values:.the cursor'xmarkx{list}must beaList with four or five numbers: [bufnum, lnum, col, off] [bufnum, lnum, col, off, curswant]"bufnum"is the buffer number. Zero can be used for thecurrent buffer. When setting anuppercasemark "bufnum"isused for themark position. For other marksitspecifies thebuffer to set themark in. You can use thebufnr() functionto turna file name intoa buffer number.For setting the cursor and the'mark "bufnum"is ignored,since these are associated witha window, nota buffer.Does not change the jumplist."lnum" and "col" are the position in the buffer. The firstcolumnis 1. Usea zero "lnum" to deletea mark. If "col"issmaller than 1 then 1is used. To use the charactercountinstead of the byte count, usesetcharpos().The "off" numberis only used when'virtualedit'is set. Thenitis the offset in screen columns from the start of thecharacter. E.g.,a position withina<Tab> or after the lastcharacter.The "curswant" numberis only used when setting the cursorposition. It sets the preferred column for when moving thecursor vertically. When the "curswant" numberis missing thepreferred columnis not set. Whenitis present and settingamark positionitis not used.Note that for'< and'>changing the line number may result inthe marks to be effectively be swapped, so that'<is alwaysbefore '>.Returns0 when the position could be set, -1 otherwise.An error messageis given if{expr}is invalid.Also seesetcharpos(),getpos() andgetcurpos().This does not restore the preferred column for movingvertically; if you set the cursor position with this,j andk motions will jump to previous columns! Usecursor() toalso set the preferred column. Also see the "curswant" key inwinrestview().Can also be usedasamethod:GetPosition()->setpos('.')Return type:Numbersetqflist({list} [,{action} [,{what}]])setqflist()Create or replace or add to thequickfix list.If the optional{what} dictionary argumentis supplied, thenonly the items listed in{what} are set. The first{list}argumentis ignored. See below for the supported items in{what}.setqflist-whatWhen{what}is not present, the items in{list} are used. Eachitemmust bea dictionary. Non-dictionary items in{list} areignored. Each dictionary item can contain the followingentries: bufnrbuffer number;must be the number ofa validbuffer filenamename ofa file; only used when "bufnr"is notpresent oritis invalid. modulename ofa module; if givenit will be used inquickfix errorwindow instead of the filename. lnumline number in the file end_lnumend of lines, if the item spans multiple linespatternsearchpattern used to locate the error colcolumn number vcolwhen non-zero: "col"is visual columnwhen zero: "col"is byteindex end_colend column, if the item spans multiple columns nrerror number textdescription of the error typesingle-character error type, 'E', 'W', etc. validrecognized error message user_data custom data associated with the item, can beany type.The "col", "vcol", "nr", "type" and "text" entries areoptional. Either "lnum" or "pattern" entry can be used tolocatea matching error line.If the "filename" and "bufnr" entries are not present orneither the "lnum" or "pattern" entries are present, then theitem will not be handledas an error line.If both "pattern" and "lnum" are present then "pattern" willbe used.If the "valid" entryis not supplied, then the valid flagisset when "bufnr"isa valid buffer or "filename" exists.If you supply an empty{list}, thequickfixlist will becleared.Note that thelistis not exactly the sameas whatgetqflist() returns.{action} values:setqflist-actionE927'a'The items from{list} are added to the existingquickfix list. If thereis no existing list, thenanewlistis created.'r'The items from the currentquickfixlist are replacedwith the items from{list}. This can also be used toclear the list::call setqflist([], 'r')'u'Like 'r', but tries to preserve the current selectionin thequickfix list.'f'All thequickfix lists in thequickfix stack arefreed.If{action}is not present oris set to' ', thena newlistis created. The newquickfixlistis added after the currentquickfixlist in the stack and all the following lists arefreed. To adda newquickfixlistat theend of the stack,set "nr" in{what} to "$".The following items can be specified in dictionary{what}: contextquickfixlist context. Seequickfix-context efmerrorformat to use when parsing text from"lines". If thisis not present, then the'errorformat' option valueis used.Seequickfix-parse idquickfixlist identifierquickfix-ID idxindex of the current entry in thequickfixlist specified by'id' or'nr'. If set to '$',then the last entry in thelistis setas thecurrent entry. Seequickfix-index itemslist ofquickfix entries. Sameas the{list}argument. linesuse'errorformat' to parsealist of lines andadd the resulting entries to thequickfixlist{nr} or{id}. OnlyaList valueis supported.Seequickfix-parse nrlist number in thequickfix stack; zeromeans the currentquickfixlist and "$" meansthe lastquickfix list. quickfixtextfuncfunction to get the text to display in thequickfix window. The value can be the name ofa function ora funcref ora lambda. Refer toquickfix-window-function for an explanationof how to write the function and an example. titlequickfixlist title text. Seequickfix-titleUnsupported keys in{what} are ignored.If the "nr" itemis not present, then the currentquickfixlistis modified. When creatinga newquickfix list, "nr" can beset toa value one greater than thequickfix stack size.When modifyingaquickfix list, to guarantee that the correctlistis modified, "id" should be used instead of "nr" tospecify the list.Examples (See alsosetqflist-examples): :call setqflist([], 'r', {'title': 'My search'}) :call setqflist([], 'r', {'nr': 2, 'title': 'Errors'}) :call setqflist([], 'a', {'id':qfid, 'lines':["F1:10:L10"]})Returns zero for success, -1 for failure.This function can be used to createaquickfixlistindependent of the'errorformat' setting. Usea command like`:cc 1` to jump to the first position.Can also be usedasamethod, the baseis passedas thesecond argument:GetErrorlist()->setqflist()Return type:Numbersetreg({regname},{value} [,{options}])setreg()Set theregister{regname} to{value}.If{regname}is "" or "@", the unnamedregister'"'is used.The{regname} argumentisa string. InVim9-script{regname}must be one character.{value} may be any value returned bygetreg() orgetreginfo(), includingaList orDict.If{options} contains "a" or{regname}is upper case,then the valueis appended.{options} can also containaregister type specification: "c" or "v"characterwise mode "l" or "V"linewise mode "b" or "<CTRL-V>"blockwise-visual modeIfa number immediately follows "b" or "<CTRL-V>" then thisisusedas the width of the selection- ifitis not specifiedthen the width of the blockis set to the number of charactersin the longest line (countinga<Tab>as 1 character).If{options} contains noregister settings, then the defaultis to use character mode unless{value} ends ina<NL> forstring{value} andlinewise mode forlist{value}. Blockwisemodeis never selected automatically.Returns zero for success, non-zero for failure.E883Note: you may not useList containing more than one item to set search andexpression registers.Lists containing no items act like empty strings.Examples::call setreg(v:register, @*):call setreg('*', @%, 'ac'):call setreg('a', "1\n2\n3", 'b5'):call setreg('"', { 'points_to': 'a'})This example shows using thefunctions to save and restorearegister::let var_a = getreginfo():call setreg('a', var_a)or::let var_a = getreg('a', 1, 1):let var_amode = getregtype('a') ....:call setreg('a', var_a, var_amode)Note: you may not reliably restoreregister valuewithout using the third argument togetreg()as withoutitnewlines are representedas newlines AND Nul bytes arerepresentedas newlinesas well, seeNL-used-for-Nul.You can also change the type ofaregister by appendingnothing::call setreg('a', '', 'al')Can also be usedasamethod, the baseis passedas thesecond argument:GetText()->setreg('a')Return type:Numbersettabvar({tabnr},{varname},{val})settabvar()Set tab-local variable{varname} to{val} intab page{tabnr}.t:varThe{varname} argumentisa string.Note thatautocommands are blocked, side effects may not betriggered, e.g. when setting'filetype'.Note that the variable name without "t:"must be used.Tabs are numberedstarting with one.This functionis not available in thesandbox.Can also be usedasamethod, the baseis passedas thethird argument:GetValue()->settabvar(tab, name)Return type:Numbersettabwinvar({tabnr},{winnr},{varname},{val})settabwinvar()Set option or local variable{varname} inwindow{winnr} to{val}.Tabs are numberedstarting with one. For the currenttabpageusesetwinvar().{winnr} can be thewindow number or thewindow-ID.When{winnr}is zero the currentwindowis used.Note thatautocommands are blocked, side effects may not betriggered, e.g. when setting'filetype' or'syntax'.This also works fora global or local buffer option, butitdoesn't work fora global or local buffer variable.Fora local buffer option the global valueis unchanged.Note that the variable name without "w:"must be used.Examples::call settabwinvar(1, 1, "&list", 0):call settabwinvar(3, 2, "myvar", "foobar")This functionis not available in thesandbox.Can also be usedasamethod, the baseis passedas thefourth argument:GetValue()->settabwinvar(tab, winnr, name)Return type:Numbersettagstack({nr},{dict} [,{action}])settagstack()Modify thetag stack of thewindow{nr} using{dict}.{nr} can be thewindow number or thewindow-ID.Foralist of supported items in{dict}, refer togettagstack(). "curidx" takes effect beforechanging thetagstack.E962How thetag stackis modified depends on the{action}argument:- If{action}is not present oris set to 'r', then thetag stackis replaced.- If{action}is set to 'a', then new entries from{dict} are pushed (added) onto thetag stack.- If{action}is set to 't', then all the entries from the current entry in thetag stack or "curidx" in{dict} are removed and then new entries are pushed to the stack.The currentindexis set to one after the length of thetagstack after the modification.Returns zero for success, -1 for failure.Examples (for more examples seetagstack-examples): Empty thetag stack ofwindow 3:call settagstack(3, {'items' : []}) Save and restore thetag stack:let stack = gettagstack(1003)" do something elsecall settagstack(1003, stack)unlet stackCan also be usedasamethod, the baseis passedas thesecond argument:GetStack()->settagstack(winnr)Return type:Numbersetwinvar({winnr},{varname},{val})setwinvar()Likesettabwinvar() for the currenttab page.Examples::call setwinvar(1, "&list", 0):call setwinvar(2, "myvar", "foobar")Can also be usedasamethod, the baseis passedas thethird argument:GetValue()->setwinvar(winnr, name)Return type:Numbersha256({string})sha256()ReturnsaString with 64 hex characters, whichis the SHA256checksum of{string}.Can also be usedasamethod:GetText()->sha256()Return type:String{only available when compiled with the |+cryptv| feature}shellescape({string} [,{special}])shellescape()Escape{string} for useasa shell command argument.When the'shell' contains powershell (MS-Windows) or pwsh(MS-Windows, Linux, and macOS) thenit will enclose{string}in singlequotes and will double up all internal singlequotes.On MS-Windows, when'shellslash'is not set,it will enclose{string} in doublequotes and double all doublequotes within{string}.Otherwiseit will enclose{string} in singlequotes andreplace all "'" with "'\''".The{special} argument adds additional escaping of keywordsused in Vim commands. Whenitis not omitted anda non-zeronumber ora non-emptyString(non-zero-arg), then specialitems suchas "!", "%", "#" and "<cword>" (as listed inexpand()) will be preceded bya backslash.Thisbackslash will be removed again by the:! command.The "!" character will be escaped (again withanon-zero-arg{special}) when'shell' contains "csh" in the tail. Thatisbecause for csh and tcsh "!"is used forhistory replacementeven when inside single quotes.Withanon-zero-arg{special} the<NL> characteris alsoescaped. When'shell' containing "csh" in the tail it'sescapeda second time.The "\" character will be escaped when'shell' contains "fish"in the tail. Thatis because for fish "\"is usedas anescapecharacter inside single quotes.Example of use witha:! command: :exe '!dir ' .. shellescape(expand('<cfile>'), 1)This results ina directory listing for the file under thecursor. Example of use withsystem(): :call system("chmod +w -- " .. shellescape(expand("%")))See also::S.Can also be usedasamethod:GetCommand()->shellescape()Return type:Stringshiftwidth([{col}])shiftwidth()Returns the effective value of'shiftwidth'. Thisis the'shiftwidth' value unlessitis zero, in whichcaseitis the'tabstop' value. This function was introduced with patch7.3.694 in 2012, everybody should haveit by now (howeveritdid not allow for the optional{col} argument until 8.1.542).When thereis one argument{col} thisis usedas column numberfor which to return the'shiftwidth' value. This matters for the'vartabstop' feature. If the'vartabstop' settingis enabled andno{col} argumentis given, column 1 will be assumed.Can also be usedasamethod:GetColumn()->shiftwidth()Return type:Numbersign_functions are documented here:sign-functions-detailssimplify({filename})simplify()Simplify the file nameas muchas possible withoutchangingthe meaning. Shortcuts (on MS-Windows) or symbolic links (onUnix) are not resolved. If the first path component in{filename} designates the current directory, this will bevalid for the resultas well.A trailing path separatorisnot removed either. OnUnix "//path"is unchanged, but"///path"is simplified to "/path" (this follows thePosixstandard).Example:simplify("./dir/.././/file/") == "./file/"Note: The combination "dir/.."is only removed if "dir"isa searchable directory or does not exist. On Unix,itis alsoremoved when "dir"isa symbolic link within the samedirectory. In order to resolve all the involved symboliclinks before simplifying the path name, useresolve().Can also be usedasamethod:GetName()->simplify()Return type:Stringsin({expr})sin()Return the sine of{expr}, measured in radians,asaFloat.{expr}must evaluate toaFloat oraNumber.Returns 0.0 if{expr}is notaFloat oraNumber.Examples::echo sin(100)-0.506366:echo sin(-4.01)0.763301Can also be usedasamethod:Compute()->sin()Return type:Floatsinh({expr})sinh()Return the hyperbolic sine of{expr}asaFloat in the range[-inf, inf].{expr}must evaluate toaFloat oraNumber.Returns 0.0 if{expr}is notaFloat oraNumber.Examples::echo sinh(0.5)0.521095:echo sinh(-0.9)-1.026517Can also be usedasamethod:Compute()->sinh()Return type:Floatslice({expr},{start} [,{end}])slice()Similar to usingaslice "expr[start: end]", but "end"isused exclusive. And forastring the indexes are usedascharacter indexes instead of byte indexes, like invim9script. Also, composing characters are treatedasapart of the preceding base character.When{end}is omitted theslice continues to the last item.When{end}is -1 the last itemis omitted.Returns an empty value if{start} or{end} are invalid.Can also be usedasamethod:GetList()->slice(offset)Return type: list<{type}> or tuple<{type}>sort({list} [,{how} [,{dict}]])sort()E702Sort the items in{list} in-place. Returns{list}.If you wantalist to remain unmodified makea copy first::let sortedlist = sort(copy(mylist))When{how}is omitted orisa string, thensort() uses thestring representation of each item to sort on. Numbers sortafter Strings,Lists after Numbers. Forsorting text in thecurrent buffer use:sort.When{how}is given anditis 'i' thencaseis ignored.In legacy script, for backwards compatibility, the value onecan be used to ignore case. Zero means to not ignore case.When{how}is given anditis 'l' then the current collationlocaleis 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 thelocale typically ignorescase. Example:" ö is sorted similarly to o with English locale.:language collate en_US.UTF8:echo sort(['n', 'o', 'O', 'ö', 'p', 'z'], 'l')['n', 'o', 'O', 'ö', 'p', 'z']" ö is sorted after z with Swedish locale.:language collate sv_SE.UTF8:echo sort(['n', 'o', 'O', 'ö', 'p', 'z'], 'l')['n', 'o', 'O', 'p', 'z', 'ö']This does not work properly on Mac.When{how}is given anditis 'n' then all items will besorted numerical (Implementation detail: this uses thestrtod() function to parse numbers. Strings, Lists, Dicts andFuncrefs will be consideredas being 0).Note that this won'tsortalist of strings with numbers!When{how}is given anditis 'N' then all items will besorted numerical. Thisis like 'n' butastring containingdigits will be usedas the number they represent.When{how}is given anditis 'f' then all items will besorted numerical. All valuesmust beaNumber ora Float.When{how}isaFuncref ora function name, this functionis called to compare items. The functionis invoked with twoitemsas argument andmust 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 forfunctions with the "dict" attribute. It will beused to set the local variable "self".Dictionary-functionThe sortis stable, items which compare equal (as number orasstring) will keep their relative position. E.g., whensortingon numbers, text strings will sort next to each other, in thesame orderas they were originally.Can also be usedasamethod:mylist->sort()Also seeuniq().Example:func MyCompare(i1, i2) return a:i1 == a:i2 ? 0 : a:i1 > a:i2 ? 1 : -1endfunceval mylist->sort("MyCompare")A shorter compare version for this specific simple case, whichignores overflow:func MyCompare(i1, i2) return a:i1 - a:i2endfuncFora simpleexpression you can usea lambda:eval mylist->sort({i1, i2 -> i1 - i2})Return type: list<{type}>sound_clear()sound_clear()Stop playing all sounds.On some Linux systems you may need the libcanberra-pulsepackage, otherwise sound may not stop.Return type:Number{only available when compiled with the |+sound| feature}sound_playevent()sound_playevent({name} [,{callback}])Playa sound identified by{name}. Which event names aresupported depends on the system. Often the XDG sound namesare used. On Ubuntu they may be found in/usr/share/sounds/freedesktop/stereo. Example:call sound_playevent('bell')On MS-Windows,{name} can be SystemAsterisk, SystemDefault,SystemExclamation, SystemExit, SystemHand, SystemQuestion,SystemStart, SystemWelcome, etc.On macOS,{name} refers to files located in/System/Library/Sounds (e.g. "Tink"). It will also work forcustom installed sounds in folders like ~/Library/Sounds.When{callback}is specifieditis invoked when the soundisfinished. The first argumentis the sound ID, the secondargumentis the status:0sound was played to theend1sound was interrupted2error occurred after sound startedExample: func Callback(id, status) echomsg "sound " .. a:id .. " finished with " .. a:status endfunc call sound_playevent('bell', 'Callback')MS-Windows:{callback} doesn't work for this function.Returns the sound ID, which can be passed tosound_stop().Returns zero if the sound could not be played.Can also be usedasamethod:GetSoundName()->sound_playevent()Return type:Number{only available when compiled with the |+sound| feature}sound_playfile()sound_playfile({path} [,{callback}])Likesound_playevent() but play sound file{path}.{path}must bea full path. On Ubuntu you may find files to playwith this command: :!find /usr/share/sounds -type f | grep -v index.themeCan also be usedasamethod:GetSoundPath()->sound_playfile()Return type:Number{only available when compiled with the |+sound| feature}sound_stop({id})sound_stop()Stop playing sound{id}.{id}must be previously returned bysound_playevent() orsound_playfile().On some Linux systems you may need the libcanberra-pulsepackage, otherwise sound may not stop.On MS-Windows, this does not work for event sound started bysound_playevent(). To stop event sounds, usesound_clear().Can also be usedasamethod:soundid->sound_stop()Return type:Number{only available when compiled with the |+sound| feature}soundfold()soundfold({word})Return the sound-folded equivalent of{word}. Uses the firstlanguage in'spelllang' for the currentwindow that supportssoundfolding.'spell'must be set. When no soundfoldingispossible the{word}is returned unmodified.This can be used for making spelling suggestions.Note thatthemethod can be quite slow.Can also be usedasamethod:GetWord()->soundfold()Return type:Stringspellbadword([{sentence}])spellbadword()Without argument: The resultis the badly spelledword underor after the cursor. The cursoris moved to the start of thebad word. When no badwordis found in the cursor line theresultis an emptystring and the cursor doesn't move.With argument: The resultis the firstword in{sentence} thatis badly spelled. If there are no spelling mistakes theresultis an empty string.The return valueisalist with two items:- The badly spelledword or an empty string.- The type of the spelling error:"bad"spelling mistake"rare"rareword"local"word only valid in another region"caps"word should start with CapitalExample:echo spellbadword("the quik brown fox")['quik', 'bad']The spelling information for the currentwindow and the valueof'spelllang' are used.Can also be usedasamethod:GetText()->spellbadword()Return type: list<string>spellsuggest({word} [,{max} [,{capital}]])spellsuggest()ReturnaList with spelling suggestions to replace{word}.When{max}is given up to this number of suggestions arereturned. Otherwise up to 25 suggestions are returned.When the{capital} argumentis given and it's non-zero onlysuggestions witha leading capital will be given. Use thisaftera match with'spellcapcheck'.{word} can bea badly spelledword followed by other text.This allows for joining two words that were split. Thesuggestions also include the following text, thus you canreplacea line.{word} may also bea good word. Similar words will then bereturned.{word} itselfis not included in the suggestions,althoughit may appear capitalized.The spelling information for the currentwindowis used. Thevalues of'spelllang' and'spellsuggest' are used.Can also be usedasamethod:GetWord()->spellsuggest()Return type: list<string> or list<any>split({string} [,{pattern} [,{keepempty}]])split()MakeaList out of{string}. When{pattern}is omitted orempty each whitespace separated sequence of charactersbecomes an item.Otherwise thestringis split where{pattern} matches,removing the matched characters.'ignorecase'is not usedhere, add \c to ignore case./\cWhen the first or last itemis emptyitis omitted, unless the{keepempty} argumentis given and it's non-zero.Other empty items are kept when{pattern} matchesat least onecharacter or when{keepempty}is non-zero.Example::let words = split(getline('.'), '\W\+')To splitastring in individual characters::for c in split(mystring, '\zs')If you want to keep the separator you can also use '\zs'attheend of the pattern::echo split('abc:def:ghi', ':\zs')['abc:', 'def:', 'ghi']Splittinga table where the first element can be empty::let items = split(line, ':', 1)The opposite functionisjoin().Can also be usedasamethod:GetString()->split()Return type: list<string>sqrt({expr})sqrt()Return the non-negative square root ofFloat{expr}asaFloat.{expr}must evaluate toaFloat oraNumber. When{expr}is negative the resultis NaN (Nota Number). Returns 0.0 if{expr}is notaFloat oraNumber.Examples::echo sqrt(100)10.0:echo sqrt(-4.01)nan"nan" may be different,it depends on system libraries.Can also be usedasamethod:Compute()->sqrt()Return type:Floatsrand([{expr}])srand()Initialize seed used byrand():- If{expr}is not given, seed values are initialized by reading from /dev/urandom, if possible, or using time(NULL) a.k.a. epoch time otherwise; this only has second accuracy.- If{expr}is givenitmust bea Number. Itis used to initialize the seed values. Thisis useful fortesting or whena predictable sequenceis intended.Examples::let seed = srand():let seed = srand(userinput):echo rand(seed)Return type: list<number>state([{what}])state()Returnastring which contains characters indicating thecurrent state. Mostly useful in callbacks that want todowork that may not always be safe. Roughly this works like:- callback usesstate() to check if workis safe to do. Yes: thendoit right away. No: add to work queue and addaSafeState and/orSafeStateAgainautocommand(SafeState triggersat toplevel,SafeStateAgain triggers after handlingmessages and callbacks).- WhenSafeState orSafeStateAgainis triggered and executes your autocommand, check withstate() if the work can be done now, and if yes removeit from the queue and execute. Remove theautocommand if the queueis now empty.Also seemode().When{what}is given only characters in thisstring will beadded. E.g, this checks if the screen has scrolled:if state('s') == '' " screen has not scrolledThese characters indicate the state, generally indicating thatsomethingis busy:mhalfwaya mapping,:normal command,feedkeys() orstuffed commandooperator pending, e.g. afterdaInsert mode autocomplete activexexecuting anautocommandwblocked on waiting, e.g. ch_evalexpr(),ch_read() andch_readraw() when reading jsonSnot triggeringSafeState or SafeStateAgain, e.g. afterf oracountccallback invoked, includingtimer (repeats forrecursiveness up to "ccc")sscreen has scrolled formessagesReturn type:Stringstr2blob({list} [,{options}])str2blob()ReturnaBlob by converting the characters in theList ofstrings in{list} into bytes.A<NL> byteis added to theblob after eachlist item.Anewline character in thestringis translated intoa<NUL>byte in the blob.If{options}is not supplied, the current'encoding' valueisused to convert the characters into bytes.The argument{options}isaDict and supports the followingitems: encodingConvert the characters using this encodingbefore making the Blob.The valueisaString. Seeencoding-namesfor the supported values.An erroris given and an emptyblobis returned if thecharacter encoding fails.Returns an emptyBlob if{list}is empty.See alsoblob2str()Examples: str2blob(["ab"])returns 0z6162 str2blob(["«»"])returns 0zC2ABC2BB str2blob(["a\nb"])returns 0z610062 str2blob(["a","b"])returns 0z610A62 str2blob(["«»"], {'encoding': 'latin1'}) returns 0zABBB str2blob(readfile('myfile.txt'))Can also be usedasamethod:GetListOfStrings()->str2blob()Return type:Blobstr2float({string} [,{quoted}])str2float()ConvertString{string} toa Float. This mostly works thesameas when usinga floating point number in an expression,seefloating-point-format. But it'sa bit more permissive.E.g., "1e40"is accepted, while in anexpression 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"isathousand.Text after the numberis silently ignored.The decimal pointis always '.', no matter what thelocaleisset to.A comma ends the number: "12,345.67"is converted to12.0. You can strip out thousands separators withsubstitute():let f = str2float(substitute(text, ',', '', 'g'))Returns 0.0 if the conversion fails.Can also be usedasamethod:let f = text->substitute(',', '', 'g')->str2float()Return type:Floatstr2list({string} [,{utf8}])str2list()Returnalist containing the number values which representeach character inString{string}. Examples:str2list(" ")returns [32]str2list("ABC")returns [65, 66, 67]list2str() does the opposite.When{utf8}is omitted or zero, the current'encoding'is used.When{utf8}is TRUE, always treat theStringasUTF-8characters. WithUTF-8 composing characters are handledproperly:str2list("á")returns [97, 769]Can also be usedasamethod:GetString()->str2list()Return type: list<number>str2nr({string} [,{base} [,{quoted}]])str2nr()Convertstring{string} toa 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"isa million.When{base}is omitted base 10is used. This also means thata leading zero doesn't causeoctal conversion to be used,aswith the defaultString toNumber conversion. Example:let nr = str2nr('0123')When{base}is 16a leading "0x" or "0X"is ignored. Withadifferent base the result will be zero. Similarly, when{base}is 8a leading "0", "0o" or "0O"is ignored, and when{base}is 2a leading "0b" or "0B"is ignored.Text after the numberis silently ignored.Returns0 if{string}is empty or on error.Can also be usedasamethod:GetText()->str2nr()Return type:Numberstrcharlen({string})strcharlen()The resultisa Number, whichis the number of charactersinString{string}. Composing characters are ignored.strchars() cancount the number of characters, countingcomposing characters separately.Returns0 if{string}is empty or on error.Also seestrlen(),strdisplaywidth() andstrwidth().Can also be usedasamethod:GetText()->strcharlen()Return type:Numberstrcharpart({src},{start} [,{len} [,{skipcc}]])strcharpart()Likestrpart() but using characterindex and length insteadof byteindex and length.When{skipcc}is omitted or zero, composing characters arecounted separately.When{skipcc} set to 1, composing characters are treatedasapart of the preceding base character, similar toslice().Whena characterindexis used wherea character does notexistitis omitted and countedas one character. Forexample:strcharpart('abc', -1, 2)results in 'a'.Returns an emptystring on error.Can also be usedasamethod:GetText()->strcharpart(5)Return type:Stringstrchars({string} [,{skipcc}])strchars()The resultisa Number, whichis the number of charactersinString{string}.When{skipcc}is omitted or zero, composing characters arecounted separately.When{skipcc} set to 1, composing characters are ignored.strcharlen() always does this.Returns zero on error.Also seestrlen(),strdisplaywidth() andstrwidth().{skipcc}is only available after 7.4.755. For backwardcompatibility, you can definea wrapper function: if has("patch-7.4.755") function s:strchars(str, skipcc)return strchars(a:str, a:skipcc) endfunction else function s:strchars(str, skipcc)if a:skipcc return strlen(substitute(a:str, ".", "x", "g"))else return strchars(a:str)endif endfunction endifCan also be usedasamethod:GetText()->strchars()Return type:Numberstrdisplaywidth({string} [,{col}])strdisplaywidth()The resultisa Number, whichis the number of display cellsString{string} occupies on the screen whenit startsat{col}(first columnis zero). When{col}is omitted zerois used.Otherwiseitis the screen column where to start. Thismatters forTab characters.The option settings of the currentwindow are used. Thismatters for anything that's displayed differently, suchas'tabstop' and'display'.When{string} contains characters with East Asian WidthClassAmbiguous, this function's return value depends on'ambiwidth'.Returns zero on error.Also seestrlen(),strwidth() andstrchars().Can also be usedasamethod:GetText()->strdisplaywidth()Return type:Numberstrftime({format} [,{time}])strftime()The resultisa String, whichisa formatted date and time,asspecified by the{format} string. The given{time}is used,or the current time if no timeis given. The accepted{format} depends on your system, thus thisis not portable!See the manual page of theC functionstrftime() for theformat. The maximum length of the resultis 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 1997 :echo strftime("%Y %b %d %X") 1997 Apr 27 11:53:25 :echo strftime("%y%m%d %T") 970427 11:53:55 :echo strftime("%H:%M") 11:55 :echo strftime("%c", getftime("file.c")) Show mod time of file.c.Not available on all systems. To check use::if exists("*strftime")Can also be usedasamethod:GetFormat()->strftime()Return type:Stringstrgetchar({str},{index})strgetchar()GetaNumber corresponding to the characterat{index} in{str}. This usesa zero-based character index, nota byteindex. Composing characters are considered separatecharacters here. Usenr2char() to convert theNumber toaString.Returns -1 if{index}is invalid.Also seestrcharpart() andstrchars().Can also be usedasamethod:GetText()->strgetchar(5)Return type:Numberstridx({haystack},{needle} [,{start}])stridx()The resultisa Number, which gives the byteindex in{haystack} of the first occurrence of theString{needle}.If{start}is specified, the search startsatindex{start}.This can be used to finda second match::let colon1 = stridx(line, ":"):let colon2 = stridx(line, ":", colon1 + 1)The searchis done case-sensitive.Forpattern searches usematch().-1is returned if the{needle} does not occur in{haystack}.See alsostrridx().Examples: :echo stridx("An Example", "Example") 3 :echo stridx("Starting point", "Start") 0 :echo stridx("Starting point", "start") -1strstr()strchr()stridx() works similar to theC function strstr(). When usedwitha single characterit works similar to strchr().Can also be usedasamethod:GetHaystack()->stridx(needle)Return type:Numberstring({expr})string()Return{expr} converted toa String. If{expr}isa Number,Float, String,Blob ora composition of them, then the resultcan be parsed back witheval().{expr} typeresultString'string' (singlequotes are doubled)Number123Float123.123456 or 1.123456e8Funcreffunction('name')Blob0z00112233.44556677.8899List[item, item]Tuple(item, item)Dictionary{key: value, key: value}Classclass SomeNameObjectobject of SomeName{lnum: 1, col: 3}Enumenum EnumNameEnumValueenum name.value{name: str, ordinal: nr}WhenaList,Tuple orDictionary hasa recursivereferenceitis replaced by "[...]" or "(...)" or "{...}".Usingeval() on the result will then fail.For an object, invokes thestring()method to geta textualrepresentation of the object. If themethodis not present,then the default representationis used.object-string()Can also be usedasamethod:mylist->string()Also seestrtrans().Return type:Stringstrlen({string})strlen()The resultisa Number, whichis the length of theString{string} in bytes.If the argumentisaNumberitis first converted toa String.For other types an erroris given and zerois returned.If you want tocount the number ofmultibyte characters usestrchars().Also seelen(),strdisplaywidth() andstrwidth().Can also be usedasamethod:GetString()->strlen()Return type:Numberstrpart({src},{start} [,{len} [,{chars}]])strpart()The resultisa String, whichis part of{src},starting frombyte{start}, with the byte length{len}.When{chars}is present andTRUE then{len}is the number ofcharacters positions (composing characters are not countedseparately, thus "1" means one base character and anyfollowing composing characters).Tocount{start}as characters instead of bytes usestrcharpart().When bytes are selected whichdo not exist, this doesn'tresult in an error, the bytes are simply omitted.If{len}is missing, the copy continues from{start} till theend of the{src}.strpart("abcdefg", 3, 2) == "de"strpart("abcdefg", -2, 4) == "ab"strpart("abcdefg", 5, 4) == "fg"strpart("abcdefg", 3) == "defg"Note: To get the first character,{start}must be 0. Forexample, to get the character under the cursor:strpart(getline("."), col(".") - 1, 1, v:true)Returns an emptystring on error.Can also be usedasamethod:GetText()->strpart(5)Return type:Stringstrptime({format},{timestring})strptime()The resultisa Number, whichisaunixtimestamp representingthe date and time in{timestring}, whichis expected to matchthe format specified in{format}.The accepted{format} depends on your system, thus thisis notportable! See the manual page of theC functionstrptime()for the format. Especially avoid "%c". The value of $TZ alsomatters.If the{timestring} cannot be parsed with{format} zeroisreturned. If youdo not know the format of{timestring} youcan try different{format} values until you geta non-zeroresult.See alsostrftime().Examples: :echo strptime("%Y %b %d %X", "1997 Apr 27 11:49:23") 862156163 :echo strftime("%c", strptime("%y%m%d %T", "970427 11:53:55")) Sun Apr 27 11:53:55 1997 :echo strftime("%c", strptime("%Y%m%d%H%M%S", "19970427115355") + 3600) Sun Apr 27 12:53:55 1997Can also be usedasamethod:GetFormat()->strptime(timestring)Not available on all systems. To check use::if exists("*strptime")Return type:Numberstrridx({haystack},{needle} [,{start}])strridx()The resultisa Number, which gives the byteindex in{haystack} of the last occurrence of theString{needle}.When{start}is specified, matches beyond thisindex areignored. This can be used to finda match beforea previousmatch::let lastcomma = strridx(line, ","):let comma2 = strridx(line, ",", lastcomma - 1)The searchis done case-sensitive.Forpattern searches usematch().-1is returned if the{needle} does not occur in{haystack}.If the{needle}is empty the length of{haystack}is returned.See alsostridx(). Examples: :echo strridx("an angry armadillo", "an") 3strrchr()When used witha single characterit works similar to theCfunction strrchr().Can also be usedasamethod:GetHaystack()->strridx(needle)Return type:Numberstrtrans({string})strtrans()The resultisa String, whichis{string} with all unprintablecharacters translated into printable characters'isprint'.Like they are shown ina window. Example:echo strtrans(@a)This displaysa newline inregisteraas "^@" instead ofstartinga new line.Returns an emptystring on error.Can also be usedasamethod:GetString()->strtrans()Return type:Stringstrutf16len({string} [,{countcc}])strutf16len()The resultisa Number, whichis the number of UTF-16 codeunits inString{string} (after convertingit to UTF-16).When{countcc}is TRUE, composing characters are countedseparately.When{countcc}is omitted or FALSE, composing characters areignored.Returns zero on error.Also seestrlen() andstrcharlen().Examples: echo strutf16len('a')returns 1 echo strutf16len('©')returns 1 echo strutf16len('😊')returns 2 echo strutf16len('ą́')returns 1 echo strutf16len('ą́', v:true)returns 3Can also be usedasamethod:GetText()->strutf16len()Return type:Numberstrwidth({string})strwidth()The resultisa Number, whichis the number of display cellsString{string} occupies.ATab characteris countedas onecell, alternatively usestrdisplaywidth().When{string} contains characters with East Asian WidthClassAmbiguous, this function's return value depends on'ambiwidth'.Returns zero on error.Also seestrlen(),strdisplaywidth() andstrchars().Can also be usedasamethod:GetString()->strwidth()Return type:Numbersubmatch({nr} [,{list}])submatch()E935Only for anexpression ina:substitute command orsubstitute() function.Returns the{nr}'th submatch of the matched text. When{nr}is0 the whole matched textis returned.Note thata NL in thestring can stand fora line break ofamulti-line match ora NUL character in the text.Also seesub-replace-expression.If{list}is present and non-zero thensubmatch() returnsalist 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() thislist will always contain one or zeroitems, since there are no real line breaks.Whensubstitute()is used recursively only the submatches inthe current (deepest) call can be obtained.Returns an emptystring orlist on error.Examples::s/\d\+/\=submatch(0) + 1/:echo substitute(text, '\d\+', '\=submatch(0) + 1', '')This finds the first number in the line and adds one to it.A line breakis includedasa newline character.Can also be usedasamethod:GetNr()->submatch()Return type:String or list<string> depending on{list}substitute({string},{pat},{sub},{flags})substitute()The resultisa String, whichisa copy of{string}, in whichthe first match of{pat}is replaced with{sub}.When{flags}is "g", all matches of{pat} in{string} arereplaced. Otherwise{flags} should be "".This works like the ":substitute" command (without any flags).But the matching with{pat}is always done like the'magic'optionis set and'cpoptions'is empty (to make scriptsportable).'ignorecase'is still relevant, use/\c or/\Cif you want to ignore or matchcase and ignore'ignorecase'.'smartcase'is not used. Seestring-match for how{pat}isused.A "~" in{sub}is not replaced with the previous{sub}.Note that some codes in{sub} havea special meaningsub-replace-special. For example, to replace something with"\n" (two characters), use "\\\\n" or '\\n'.When{pat} does not match in{string},{string}is returnedunmodified.Example: :let &path = substitute(&path, ",\\=[^,]*$", "", "")This removes the last component of the'path' option. :echo substitute("testing", ".*", "\\U\\0", "")results in "TESTING".When{sub} starts with "\=", the remainderis interpretedasan expression. Seesub-replace-expression. Example: :echo substitute(s, '%\(\x\x\)', \ '\=nr2char("0x" .. submatch(1))', 'g')When{sub}isaFuncref that functionis called, with oneoptional argument. Example: :echo substitute(s, '%\(\x\x\)', SubNr, 'g')The optional argumentisalist which contains the wholematchedstring and up to nine submatches, like whatsubmatch() returns. Example: :echo substitute(s, '%\(\x\x\)', {m -> '0x' .. m[1]}, 'g')Returns an emptystring on error.Can also be usedasamethod:GetString()->substitute(pat, sub, flags)Return type:Stringswapfilelist()swapfilelist()Returnsalist of swap file names, like what "vim-r" shows.See the-r command argument. The'directory' optionis usedfor the directories to inspect. If you only want to getalist of swap files in the current directory then temporarilyset'directory' toa dot:let save_dir = &directorylet &directory = '.'let swapfiles = swapfilelist()let &directory = save_dirReturn type: list<string>swapinfo({fname})swapinfo()The resultisa dictionary, which holds information about theswapfile{fname}. The available fields are:version Vim versionuseruser namehosthost namefnameoriginal file namepidPID of the Vim process that created the swapfilemtimelast modification time in secondsinodeOptional: INODE number of the filedirty1 if file was modified,0 if notNote that "user" and "host" are truncated toat most 39 bytes.Incase of failure an "error" itemis added with the reason:Cannot open file: file not found or in accessibleCannot read file: cannot read first blockNota swap file: does not contain correct block IDMagic number mismatch: Info in first blockis invalidCan also be usedasamethod:GetFilename()->swapinfo()Return type: dict<any> or dict<string>swapname({buf})swapname()The resultis the swap file path of the buffer{expr}.For the use of{buf}, seebufname() above.If buffer{buf}is the current buffer, the resultis equal to:swapname (unless thereis no swap file).If buffer{buf} has no swap file, returns an empty string.Can also be usedasamethod:GetBufname()->swapname()Return type:StringsynID({lnum},{col},{trans})synID()The resultisa Number, whichis thesyntax IDat the position{lnum} and{col} in the current window.Thesyntax ID can be used withsynIDattr() andsynIDtrans() to obtainsyntax information about text.{col}is 1 for the leftmost column,{lnum}is 1 for the firstline.'synmaxcol' applies, ina longer line zerois returned.Note that when the positionis after the last character,that's where the cursor can be inInsert mode,synID() returnszero.{lnum}is used like withgetline().When{trans}isTRUE, transparent items are reduced to theitem that they reveal. Thisis useful when wanting to knowthe effective color. When{trans}isFALSE, the transparentitemis returned. Thisis useful when wanting to know whichsyntax itemis effective (e.g. inside parens).Warning: This function can be very slow. Best speedisobtained by going through the file in forward direction.Returns zero on error.Example (echoes the name of thesyntax item under the cursor)::echo synIDattr(synID(line("."), col("."), 1), "name")Return type:NumbersynIDattr({synID},{what} [,{mode}])synIDattr()The resultisa String, whichis the{what} attribute ofsyntax ID{synID}. This can be used to obtain informationaboutasyntax item.{mode} can be "gui", "cterm" or "term", to get the attributesfor that mode. When{mode}is omitted, or an invalid valueisused, the attributes for the currently active highlighting areused (GUI, cterm or term).UsesynIDtrans() to follow linked highlight groups.{what}result"name"the name of thesyntax item"fg"foreground color (GUI: color name used to setthe color, cterm: color numberasa string,term: empty string)"bg"background color (as with "fg")"font"font name (only available in the GUI)highlight-font"sp"special color for theGUI (as with "fg")highlight-guisp"ul"underline color for cterm: numberasastring"fg#"like "fg", but for theGUI and theGUIisrunning the name in "#RRGGBB" form"bg#"like "fg#" for "bg""sp#"like "fg#" for "sp""bold""1" ifbold"italic""1" ifitalic"reverse""1" if reverse"inverse""1" ifinverse (= reverse)"standout""1" ifstandout"underline""1" if underlined"undercurl""1" if undercurled"strike""1" ifstrikethrough"nocombine""1" ifnocombineReturns an emptystring on error.Example (echoes the color of thesyntax item under thecursor)::echo synIDattr(synIDtrans(synID(line("."), col("."), 1)), "fg")Can also be usedasamethod::echo synID(line("."), col("."), 1)->synIDtrans()->synIDattr("fg")Return type:StringsynIDtrans({synID})synIDtrans()The resultisa Number, whichis the translatedsyntax ID of{synID}. Thisis thesyntax group ID of whatis being used tohighlight the character. Highlight links given with":highlight link" are followed.Returns zero on error.Can also be usedasamethod::echo synID(line("."), col("."), 1)->synIDtrans()->synIDattr("fg")Return type:Numbersynconcealed({lnum},{col})synconcealed()The resultisaList with currently three items:1. The first item in thelistis0 if the characterat the position{lnum} and{col}is not part ofa concealable region, 1 ifit is.{lnum}is used like withgetline().2. The second item in thelistisa string. If the first itemis 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 thelistisa number representing the specificsyntax region matched in the line. When the characteris not concealed the valueis zero. This allows detection of the beginning ofa new concealable region if there are two consecutive regions with the same replacement character. For an example, if the textis "123456" and both "23" and "45" are concealed and replaced by the character "X", then:callreturnssynconcealed(lnum, 1) [0, '', 0]synconcealed(lnum, 2) [1, 'X', 1]synconcealed(lnum, 3) [1, 'X', 1]synconcealed(lnum, 4) [1, 'X', 2]synconcealed(lnum, 5) [1, 'X', 2]synconcealed(lnum, 6) [0, '', 0]Note: Doesn't considermatchadd() highlighting items,sincesyntax and matching highlighting are two differentmechanismssyntax-vs-match.Return type: list<any>synstack({lnum},{col})synstack()ReturnaList, whichis the stack ofsyntax itemsat theposition{lnum} and{col} in the current window.{lnum}isused like withgetline(). Each item in theListis an IDlike whatsynID() returns.The first item in theListis the outer region, following areitems contained in that one. The last oneis whatsynID()returns, unless not the whole itemis highlighted oritisatransparent item.This functionis useful for debuggingasyntax file.Example that shows thesyntax stack under the cursor:for id in synstack(line("."), col(".")) echo synIDattr(id, "name")endforWhen the position specified with{lnum} and{col}is invalidan emptyListis returned. The position just after the lastcharacter ina line and the first column in an empty line arevalid positions.Return type: list<number> or list<any>system({expr} [,{input}])system()E677Get the output of the shell command{expr}asaString. Seesystemlist() to get the outputasaList.When{input}is given andisaString thisstringis writtentoa file and passedas stdin to the command. Thestringiswritten as-is, you need to take care of using the correct lineseparators yourself.If{input}is given andisaListitis written to the fileina waywritefile() does with{binary} set to "b" (i.e.witha newline between eachlist item with newlines insidelist items converted to NULs).When{input}is given andisa number thatisa valid id foran existing buffer then the content of the bufferis writtento the file line by line, each line terminated bya NL andNULs characters where the text hasa NL.Pipes are not used, the'shelltemp' optionis not used.When prepended by:silent theterminal will not be set tocooked mode. Thisis meant to be used for commands thatdonot need the user to type. It avoids stray characters showingup on the screen which requireCTRL-L to remove.:silent let f = system('ls *.vim')Note: Useshellescape() or::S withexpand() orfnamemodify() toescape special characters ina commandargument. Newlines in{expr} may cause the command to fail.The characters in'shellquote' and'shellxquote' may alsocause trouble.Thisis not to be used for interactive commands.The resultisa String. Example: :let files = system('ls ' .. shellescape(expand('%:h'))) :let files = system('ls ' .. expand('%:h:S'))To make the result more system-independent, the shell outputis filtered to replace<CR> with<NL> for Macintosh, and<CR><NL> with<NL> for DOS-like systems.To avoid thestring being truncatedata NUL, all NULcharacters are replaced with SOH (0x01).The command executedis constructed using several options:'shell''shellcmdflag''shellxquote'{expr}'shellredir'{tmp}'shellxquote'({tmp}is an automatically generated file name).For Unix, braces areput around{expr} to allow forconcatenated commands.The command will be executed in "cooked" mode, so thataCTRL-C will interrupt the command (onUnixat least).The resulting error code can be found inv:shell_error.This function will fail inrestricted-mode.Note that any wrong value in theoptions mentioned above maymake the function fail. It has also been reported to failwhen usinga security agent application.Unlike ":!cmd" thereis no automatic check for changed files.Use:checktime to forcea check.Can also be usedasamethod::echo GetCmd()->system()Return type:Stringsystemlist({expr} [,{input}])systemlist()Sameassystem(), but returnsaList with lines (parts ofoutput separated by NL) with NULs transformed into NLs. Outputis the sameasreadfile() will output with{binary} argumentset to "b", except that thereis no extra empty item when theresult ends ina NL.Note that onMS-Windows you may get trailing CR characters.To see the difference between "echo hello" and "echo-n hello"usesystem() andsplit():echo system('echo hello')->split('\n', 1)Returns an emptystring on error.Can also be usedasamethod::echo GetCmd()->systemlist()Return type: list<string>tabpagebuflist([{arg}])tabpagebuflist()The resultisaList, where each itemis the number of thebuffer associated with eachwindow in the currenttab page.{arg}specifies the number of thetab page to be used. Whenomitted the currenttab pageis used.When{arg}is invalid the number zerois returned.To getalist of allbuffers in all tabs use this:let buflist = []for i in range(tabpagenr('$')) call extend(buflist, tabpagebuflist(i + 1))endforNote thata buffer may appear in more than one window.Can also be usedasamethod:GetTabpage()->tabpagebuflist()Return type: list<number>tabpagenr([{arg}])tabpagenr()The resultisa Number, whichis the number of the currenttab page. The firsttab page has number 1.The optional argument{arg} supports the following values:$the number of the lasttab page (thetab pagecount).#the number of the last accessedtab page(whereg<Tab> goes to). if thereis noprevioustab page0is returned.The number can be used with the:tab command.Returns zero on error.Return type:Numbertabpagewinnr({tabarg} [,{arg}])tabpagewinnr()Likewinnr() but fortab page{tabarg}.{tabarg}specifies the number oftab page to be used.{arg}is used like withwinnr():- When omitted the currentwindow numberis returned. Thisis thewindow which will be used when going to thistab page.- When "$" the number ofwindowsis returned.- When "#" the previouswindow nris returned.Useful examples: tabpagewinnr(1) " current window of tab page 1 tabpagewinnr(4, '$') " number of windows in tab page 4When{tabarg}is invalid zerois returned.Can also be usedasamethod:GetTabpage()->tabpagewinnr()Return type:Numbertagfiles()tagfiles()ReturnsaList with the file names used to search fortagsfor the current buffer. Thisis the'tags' option expanded.Return type: list<string> or list<any>taglist({expr} [,{filename}])taglist()ReturnsaList oftags matching the regularexpression{expr}.If{filename}is passeditis used to prioritize the resultsin the same way that:tselect does. Seetag-priority.{filename} should be the full path of the file.Eachlist itemisa dictionary withat least the followingentries:nameName of the tag.filenameName of the file where thetagisdefined. Itis either relative to thecurrent directory ora full path.cmdEx command used to locate thetag inthe file.kindType of the tag. The value for thisentry depends on the language specifickind values. Only available whenusingatags file generated byUniversal/Exuberantctags or hdrtag.staticA file specific tag. Refer tostatic-tag for more information.More entries may be present, depending on the content of thetags file: access, implementation, inherits and signature.Refer to thectags documentation for information about thesefields. ForC code the fields "struct", "class" and "enum"may appear, they give the name of the entity thetagiscontained in.The ex-command "cmd" can be either anex search pattern,aline number ora line number followed bya byte number.If there are no matching tags, then an emptylistis returned.To get an exacttag match, the anchors '^' and '$' should beused in{expr}. This also make the function work faster.Refer totag-regexp for more information about thetagsearch regularexpression pattern.Refer to'tags' for information about how thetags fileislocated by Vim. Refer totags-file-format for the format ofthetags file generated by the differentctags tools.Can also be usedasamethod:GetTagpattern()->taglist()Return type: list<dict<any>> or list<any>tan({expr})tan()Return the tangent of{expr}, measured in radians,asaFloatin the range [-inf, inf].{expr}must evaluate toaFloat oraNumber.Returns 0.0 if{expr}is notaFloat oraNumber.Examples::echo tan(10)0.648361:echo tan(-4.01)-1.181502Can also be usedasamethod:Compute()->tan()Return type:Floattanh({expr})tanh()Return the hyperbolic tangent of{expr}asaFloat in therange [-1, 1].{expr}must evaluate toaFloat oraNumber.Returns 0.0 if{expr}is notaFloat oraNumber.Examples::echo tanh(0.5)0.462117:echo tanh(-1)-0.761594Can also be usedasamethod:Compute()->tanh()Return type:Floattempname()tempname()temp-file-nameThe resultisa String, whichis the name ofa file thatdoesn't exist. It can be used fora temporary file. The nameis different forat least 26 consecutive calls. Example::let tmpfile = tempname():exe "redir > " .. tmpfileFor Unix, the file will be ina private directorytempfilethatis recursively deleted when Vim exits, on other systemstemporary files are not cleaned up automatically on exit.ForMS-Windows forward slashes are used when the'shellslash'optionis set, or when'shellcmdflag' starts with '-' and'shell' does not contain powershell or pwsh.Return type:Stringterm_functions are documented here:terminal-function-detailsterminalprops()terminalprops()ReturnsaDictionary with properties of theterminal that Vimdetected from the response tot_RV request. Seev:termresponse for the response itself. Ifv:termresponseis empty most values here will be 'u' for unknown. cursor_stylewhether sendingt_RS works ** cursor_blink_modewhether sendingt_RC works ** underline_rgbwhethert_8u works ** mousemouse type supported kittywhether Kittyterminal was detected** value 'u' for unknown, 'y' for yes, 'n' for noIf the+termresponse featureis missing then the resultisan empty dictionary.If "cursor_style"is 'y' thent_RS will be sent to request thecurrent cursor style.If "cursor_blink_mode"is 'y' thent_RC will be sent torequest the cursor blink status."cursor_style" and "cursor_blink_mode" are also set ift_u7is not empty, Vim will detect the working of sendingt_RSandt_RC on startup.When "underline_rgb"is not 'y', thent_8u will be made empty.This avoids sendingit to xterm, which would clear the colors.For "mouse" the value 'u'is unknownAlso see:-'ambiwidth'- detected by usingt_u7.-v:termstyleresp andv:termblinkresp for the response tot_RS andt_RC.Return type: dict<string>test_functions are documented here:test-functions-detailstimer_info()timer_info([{id}])Returnalist with information about timers.When{id}is given only information about thistimerisreturned. Whentimer{id} does not exist an emptylistisreturned.When{id}is omitted information about alltimersis returned.For eachtimer the informationis stored inaDictionary withthese items: "id" thetimer ID "time" time thetimer was started with "remaining" time until thetimer fires "repeat" number of times thetimer will still fire; -1 means forever "callback" the callback "paused" 1 if thetimeris paused,0 otherwiseCan also be usedasamethod:GetTimer()->timer_info()Return type: list<dict<any>> or list<any>{only available when compiled with the |+timers| feature}timer_pause({timer},{paused})timer_pause()Pause or unpausea timer.A pausedtimer does not invoke itscallback when its time expires. Unpausingatimer may causethe callback to be invoked almost immediately if enough timehas passed.Pausingatimeris useful to avoid the callback to be calledfora short time.If{paused} evaluates toa non-zeroNumber ora non-emptyString, then thetimeris paused, otherwiseitis unpaused.Seenon-zero-arg.Can also be usedasamethod:GetTimer()->timer_pause(1)Return type:Number{only available when compiled with the |+timers| feature}timer_start()timertimerstimer_start({time},{callback} [,{options}])Createatimer and return thetimer ID.{time}is the waiting time in milliseconds. Thisis theminimum time before invoking the callback. When the systemisbusy or Vimis not waiting for input the time will be longer.Zero can be used to execute the callback when Vimis back inthe main loop.{callback}is the function to call. It can be the name ofafunction oraFuncref. Itis called with one argument, whichis thetimer ID. The callbackis only invoked when Vimiswaiting for input.If you want to showa message lookatpopup_notification()to avoid interfering with what the useris doing.{options}isa dictionary. Supported entries: "repeat"Number of times to repeat calling thecallback. -1 means forever. When not presentthe callback will be called once.If thetimer causes an error three times inarow the repeatis cancelled. This avoids thatVim becomes unusable because of all the errormessages.Returns -1 on error.Example:func MyHandler(timer) echo 'Handler called'endfunclet timer = timer_start(500, 'MyHandler',\ {'repeat': 3})This will invoke MyHandler() three timesat 500 msecintervals.Can also be usedasamethod:GetMsec()->timer_start(callback)Not available in thesandbox.Return type:Number{only available when compiled with the |+timers| feature}timer_stop({timer})timer_stop()Stopa timer. Thetimer callback will no longer be invoked.{timer}is an ID returned by timer_start(), thusitmust beaNumber. If{timer} does not exist thereis no error.Can also be usedasamethod:GetTimer()->timer_stop()Return type:Number{only available when compiled with the |+timers| feature}timer_stopall()timer_stopall()Stop all timers. Thetimer callbacks will no longer beinvoked. Useful ifatimeris misbehaving. If there are notimers thereis no error.Return type:Number{only available when compiled with the |+timers| feature}tolower({expr})tolower()The resultisa copy of theString given, with alluppercasecharacters turned intolowercase (just like applyinggu tothe string). Returns an emptystring on error.Can also be usedasamethod:GetText()->tolower()Return type:Stringtoupper({expr})toupper()The resultisa copy of theString given, with alllowercasecharacters turned intouppercase (just like applyinggU tothe string). Returns an emptystring on error.Can also be usedasamethod:GetText()->toupper()Return type:Stringtr({src},{fromstr},{tostr})tr()The resultisa copy of the{src}string with all characterswhich appear in{fromstr} replaced by the character in thatposition in the{tostr} string. Thus the first character in{fromstr}is translated into the first character in{tostr}and so on. Exactly like theunix "tr" command.This code also deals withmultibyte characters properly.Returns an emptystring on error.Examples:echo tr("hello there", "ht", "HT")returns "Hello THere"echo tr("<blob>", "<>", "{}")returns "{blob}"Can also be usedasamethod:GetText()->tr(from, to)Return type:Stringtrim({text} [,{mask} [,{dir}]])trim()Return{text}asaString where any character in{mask}isremoved from the beginning and/orend of{text}.If{mask}is not given, oris an empty string,{mask}is allcharacters up to 0x20, which includes Tab, space, NL and CR,plus the non-breakingspace character 0xa0.The optional{dir} argumentspecifies where to remove thecharacters:0remove from the beginning andend of{text}1remove onlyat the beginning of{text}2remove onlyat theend of{text}When omitted both ends are trimmed.This function deals withmultibyte characters properly.Returns an emptystring on error.Examples:echo trim(" some text ")returns "some text"echo trim(" \r\t\t\r RESERVE \t\n\x0B\xA0") .. "_TAIL"returns "RESERVE_TAIL"echo trim("rm<Xrm<>X>rrm", "rm<>")returns "Xrm<>X" (characters in the middle are not removed)echo trim(" vim ", " ", 2)returns " vim"Can also be usedasamethod:GetText()->trim()Return type:Stringtrunc({expr})trunc()Return the largest integral value with magnitudeless than orequal to{expr}asaFloat (truncate towards zero).{expr}must evaluate toaFloat oraNumber.Returns 0.0 if{expr}is notaFloat oraNumber.Examples:echo trunc(1.456)1.0echo trunc(-5.456)-5.0echo trunc(4.0)4.0Can also be usedasamethod:Compute()->trunc()Return type:Floattuple2list({tuple})tuple2list()CreateaList froma shallow copy of thetuple items.Examples:tuple2list((1, 2, 3))returns [1, 2, 3]list2tuple() does the opposite.This function doesn't recursively convert all theTuple itemsin{tuple} toa List.Note that the items are identicalbetween thelist and the tuple,changing an item changes thecontents of both thetuple and the list.Returns an emptylist on error.Can also be usedasamethod:GetTuple()->tuple2list()Return type: list<{type}> (depending on the givenTuple)type()type({expr})The resultisaNumber representing the type of{expr}.Instead of using the number directly,itis 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 and v:true)None: 7v:t_none (v:null and v:none)Job: 8v:t_jobChannel: 9v:t_channelBlob: 10v:t_blobClass: 12v:t_classObject: 13v:t_objectTypealias: 14v:t_typealiasEnum: 15v:t_enumEnumValue: 16v:t_enumvalueTuple: 17v:t_tupleFor backward compatibility, thismethod can be used::if type(myvar) == type(0):if type(myvar) == type(""):if type(myvar) == type(function("tr")):if type(myvar) == type([]):if type(myvar) == type({}):if type(myvar) == type(0.0):if type(myvar) == type(v:false):if type(myvar) == type(v:none)To check if the v:t_variables exist use this::if exists('v:t_number')Can also be usedasamethod:mylist->type()Return type:Numbertypename({expr})typename()Returnastring representation of the type of{expr}.Example:echo typename([1, 2, 3])list<number>Return type:Stringundofile({name})undofile()Return the name of theundo file that would be used fora filewith name{name} when writing. This uses the'undodir'option, finding directories that exist. It does not check iftheundo file exists.{name}is always expanded to the full path, since thatis whatis used internally.If{name}is emptyundofile() returns an empty string, sinceabuffer withouta file name will not write anundo file.Useful in combination with:wundo and:rundo.When compiled without the+persistent_undo option this alwaysreturns an empty string.Can also be usedasamethod:GetFilename()->undofile()Return type:Stringundotree([{buf}])undotree()Return the current state of theundo tree for the currentbuffer, or fora specific buffer if{buf}is given. Theresultisa dictionary with the following items: "seq_last"The highestundo sequence number used. "seq_cur"The sequence number of the current position intheundo 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 theundotree. "synced"Non-zero when the lastundo block was synced.This happens when waiting from input from theuser. Seeundo-blocks. "entries"Alist of dictionaries with information aboutundo blocks.The first item in the "entries"listis the oldestundo item.EachList itemisaDictionary with these items: "seq"Undo sequence number. Sameas what appears in:undolist. "time"Timestamp when the change happened. Usestrftime() to convert to something readable. "newhead"Only appears in the item thatis the last onethat was added. This marks the last changeand where further changes will be added. "curhead"Only appears in the item thatis the last onethat was undone. This marks the currentposition in theundo tree, the block that willbe used byaredo command. When nothing wasundone after the last change this item willnot appear anywhere. "save"Only appears on the last block beforea filewrite. The numberis the write count. Thefirst write has number 1, the last one the"save_last" mentioned above. "alt"Alternate entry. Thisis againaList ofundoblocks. Each item may again have an "alt"item.Return type: dict<any>uniq({list} [,{func} [,{dict}]])uniq()E882Remove second and succeeding copies of repeated adjacent{list} items in-place. Returns{list}. If you wantalistto remain unmodified makea copy first::let newlist = uniq(copy(mylist))The default compare function uses thestring representation ofeach item. For the use of{func} and{dict} seesort().Fordeduplicating text in the current buffer see:uniq.Returns zero if{list}is notaList.Can also be usedasamethod:mylist->uniq()Return type: list<{type}>utf16idx()utf16idx({string},{idx} [,{countcc} [,{charidx}]])Sameascharidx() but returns the UTF-16 code unitindex ofthe byteat{idx} in{string} (after convertingit to UTF-16).When{charidx}is present and TRUE,{idx}is usedas thecharacterindex in theString{string} instead ofas the byteindex.An{idx} in the middle ofaUTF-8 sequenceis roundeddownwards to the beginning of that sequence.Returns -1 if the arguments are invalid or if there arelessthan{idx} bytes in{string}. If there are exactly{idx} bytesthe length of thestring in UTF-16 code unitsis returned.Seebyteidx() andbyteidxcomp() for getting the byteindexfrom the UTF-16index andcharidx() for getting thecharacterindex from the UTF-16 index.Refer tostring-offset-encoding for more information.Examples:echo utf16idx('a😊😊', 3)returns 2echo utf16idx('a😊😊', 7)returns 4echo utf16idx('a😊😊', 1, 0, 1)returns 2echo utf16idx('a😊😊', 2, 0, 1)returns 4echo utf16idx('aą́c', 6)returns 2echo utf16idx('aą́c', 6, 1)returns 4echo utf16idx('a😊😊', 9)returns -1Can also be usedasamethod:GetName()->utf16idx(idx)Return type:Numbervalues({dict})values()ReturnaList with all the values of{dict}. TheListisin arbitrary order. Also seeitems() andkeys().Returns zero if{dict}is notaDict.Can also be usedasamethod:mydict->values()Return type: list<any>virtcol({expr} [,{list} [,{winid}]])virtcol()The resultisa Number, whichis the screen column of the fileposition given with{expr}. That is, the last screen positionoccupied by the characterat that position, when the screenwould be of unlimited width. When thereisa<Tab>at theposition, the returnedNumber will be the columnat theend ofthe<Tab>. For example, fora<Tab> in column 1, with'ts'set to 8,it returns 8.concealis ignored.For the byte position usecol().For the use of{expr} seegetpos() andcol().When{expr}is "$",it means theend of the cursor line, sothe resultis the number of cells in the cursor line plus one.When'virtualedit'is used{expr} can be [lnum, col, off],where "off"is the offset in screen columns from the start ofthe character. E.g.,a position withina<Tab> or after thelast character. When "off"is omitted zerois used. WhenVirtual editingis active in the current mode,a positionbeyond theend of the line can be returned. Also see'virtualedit'If{list}is present and non-zero thenvirtcol() returnsaList with the first and last screen position occupied by thecharacter.With the optional{winid} argument the values are obtained forthatwindow instead of the current window.Note that only marks in the current file can be used.Examples:" With text "foo^Lbar" and cursor on the "^L":virtcol(".")" returns 5virtcol(".", 1)" returns [4, 5]virtcol("$")" returns 9" With text " there", with 't at 'h':virtcol("'t")" returns 6The first columnis 1.0 or [0, 0]is returned for an error.A more advanced example that echoes the maximum length ofall lines: echo max(map(range(1, line('$')), "virtcol([v:val, '$'])"))Can also be usedasamethod:GetPos()->virtcol()Return type:Numbervirtcol2col({winid},{lnum},{col})virtcol2col()The resultisa Number, whichis the byteindex of thecharacter inwindow{winid}at buffer line{lnum} and virtualcolumn{col}.If buffer line{lnum}is an empty line,0is returned.If{col}is greater than the last virtual column in line{lnum}, then the byteindex of the characterat the lastvirtual columnis returned.Foramulti-byte character, the column number of the firstbyte in the characteris returned.The{winid} argument can be thewindow number or thewindow-ID. If thisis zero, then the currentwindowis used.Returns -1 if thewindow{winid} doesn't exist or the bufferline{lnum} or virtual column{col}is invalid.See alsoscreenpos(),virtcol() andcol().Can also be usedasamethod:GetWinid()->virtcol2col(lnum, col)Return type:Numbervisualmode([{expr}])visualmode()The resultisa String, which describes the lastVisual modeused in the current buffer. Initiallyit returns an emptystring, but onceVisual mode has been used,it returns "v","V", or "<CTRL-V>" (a singleCTRL-V character) forcharacter-wise, line-wise, or block-wiseVisual moderespectively.Example::exe "normal " .. visualmode()This enters the sameVisual modeas before. Itis also usefulin scripts if you wish to act differently depending on theVisual mode that was used.IfVisual modeis active, usemode() to get theVisual mode(e.g., ina:vmap).If{expr}is supplied andit evaluates toa non-zeroNumber ora non-empty String, then theVisual mode will be cleared andthe old valueis returned. Seenon-zero-arg.Return type:Stringwildmenumode()wildmenumode()ReturnsTRUE when the wildmenuis active andFALSEotherwise. See'wildmenu' and'wildmode'.This can be used in mappings to handle the'wildcharm' optiongracefully. (Makes only sense withmapmode-c mappings).For example to make<c-j> work like<down> in wildmode, use: :cnoremap <expr> <C-j> wildmenumode() ? "\<Down>\<Tab>" : "\<c-j>"(Note: this needs the'wildcharm' option set appropriately).Return type:Numberwin_execute({id},{command} [,{silent}])win_execute()Likeexecute() but in the context ofwindow{id}.Thewindow will temporarily be made the current window,without triggeringautocommands orchanging directory. Whenexecuting{command}autocommands will be triggered, this mayhave unexpected side effects. Use:noautocmd if needed.Example:call win_execute(winid, 'set syntax=python')Doing the same withsetwinvar() would not triggerautocommands and not actually showsyntax highlighting.E994Not all commands are allowed inpopup windows.Whenwindow{id} does not exist then no erroris given andan emptystringis returned.Can also be usedasamethod, the baseis passedas thesecond argument:GetCommand()->win_execute(winid)Return type:Stringwin_findbuf({bufnr})win_findbuf()ReturnsaList withwindow-IDs forwindows that containbuffer{bufnr}. When thereis none thelistis empty.Can also be usedasamethod:GetBufnr()->win_findbuf()Return type: list<number> or list<any>win_getid([{win} [,{tab}]])win_getid()Get thewindow-ID for the specified window.When{win}is missing use the current window.With{win} thisis thewindow number. The topwindow hasnumber 1.Without{tab} use the current tab, otherwise thetab withnumber{tab}. The firsttab has number one.Return zero if thewindow cannot be found.Can also be usedasamethod:GetWinnr()->win_getid()Return type:Numberwin_gettype([{nr}])win_gettype()Return the type of the window:"autocmd"autocommand window. Temporarywindowused to execute autocommands."command"command-linewindowcmdwin(empty)normalwindow"loclist"location-list-window"popup"popupwindowpopup"preview"previewwindowpreview-window"quickfix"quickfix-window"unknown"window{nr} not foundWhen{nr}is omitted return the type of the current window.When{nr}is given return the type of thiswindow by number orwindow-ID.Also see the'buftype' option. When runningaterminal inapopupwindow then'buftype'is "terminal" andwin_gettype()returns "popup".Can also be usedasamethod:GetWinid()->win_gettype()Return type:Stringwin_gotoid({expr})win_gotoid()Go towindow with ID{expr}. This may also change the currenttabpage.ReturnTRUE if successful,FALSE if thewindow cannot be found.Can also be usedasamethod:GetWinid()->win_gotoid()Return type:Numberwin_id2tabwin({expr})win_id2tabwin()Returnalist with thetab number andwindow number ofwindowwith ID{expr}: [tabnr, winnr].Return [0, 0] if thewindow cannot be found.Can also be usedasamethod:GetWinid()->win_id2tabwin()Return type: list<number>win_id2win({expr})win_id2win()Return thewindow number ofwindow with ID{expr}.Return0 if thewindow cannot be found in the current tabpage.Can also be usedasamethod:GetWinid()->win_id2win()Return type:Numberwin_move_separator({nr},{offset})win_move_separator()Movewindow{nr}'s vertical separator (i.e., the right border)by{offset} columns,as if being dragged by the mouse.{nr}can beawindow number orwindow-ID.A positive{offset}moves right anda negative{offset} moves left. Movingawindow's vertical separator will change the width of thewindow and the width of otherwindows adjacent to the verticalseparator. The magnitude ofmovement may be smaller thanspecified (e.g.,asa consequence of maintaining'winminwidth'). ReturnsTRUE if thewindow can be found andFALSE otherwise.This will fail for the rightmostwindow anda full-widthwindow, sinceit has no separator on the right.Only works for the currenttab page.E1308Can also be usedasamethod:GetWinnr()->win_move_separator(offset)Return type:Numberwin_move_statusline({nr},{offset})win_move_statusline()Movewindow{nr}'s status line (i.e., the bottom border) by{offset} rows,as if being dragged by the mouse.{nr} can beawindow number orwindow-ID.A positive{offset} moves downanda negative{offset} moves up. Movinga window's statusline will change the height of thewindow and the height ofotherwindows adjacent to the status line. The magnitude ofmovement may be smaller than specified (e.g.,asa consequenceof maintaining'winminheight'). ReturnsTRUE if thewindow canbe found andFALSE otherwise.Only works for the currenttab page.Can also be usedasamethod:GetWinnr()->win_move_statusline(offset)Return type:Numberwin_screenpos({nr})win_screenpos()Return the screen position ofwindow{nr}asalist with twonumbers: [row, col]. The firstwindow always has position[1, 1], unless thereisa tabline, thenitis [2, 1].{nr} can be thewindow number or thewindow-ID. Use zerofor the current window.Returns [0, 0] if thewindow cannot be found.Can also be usedasamethod:GetWinid()->win_screenpos()Return type: list<number>win_splitmove({nr},{target} [,{options}])win_splitmove()Temporarily switch towindow{target}, then movewindow{nr}toa new split adjacent to{target}.Unlike commands suchas:split, no newwindows are created(thewindow-ID ofwindow{nr}is unchanged after the move).Both{nr} and{target} can bewindow numbers orwindow-IDs.Bothmust be in the currenttab page.Returns zero for success, non-zero for failure.{options}isaDictionary with the following optional entries: "vertical"When TRUE, the splitis created vertically,like with:vsplit. "rightbelow"When TRUE, the splitis made below or to theright (if vertical). When FALSE,itis doneabove or to the left (if vertical). When notpresent, the values of'splitbelow' and'splitright' are used.Can also be usedasamethod:GetWinid()->win_splitmove(target)Return type:Numberwinbufnr()winbufnr({nr})The resultisa Number, whichis the number of the bufferassociated withwindow{nr}.{nr} can be thewindow number orthewindow-ID.When{nr}is zero, the number of the buffer in the currentwindowis returned.Whenwindow{nr} doesn't exist, -1is returned.Example: :echo "The file in the current window is " . bufname(winbufnr(0))Can also be usedasamethod:FindWindow()->winbufnr()->bufname()Return type:Numberwincol()wincol()The resultisa Number, whichis the virtual column of thecursor in the window. Thisis counting screen cells from theleft side of the window. The leftmost columnis one.Return type:Numberwindowsversion()windowsversion()The resultisa String. ForMS-Windowsit indicates the OSversion. E.g, Windows 10is "10.0", Windows 8is "6.2",Windows XPis "5.1". For non-MS-Windows systems the resultisan empty string.Return type:Stringwinheight({nr})winheight()The resultisa Number, whichis the height ofwindow{nr}.{nr} can be thewindow number or thewindow-ID.When{nr}is zero, the height of the currentwindowisreturned. Whenwindow{nr} doesn't exist, -1is returned.An existingwindow always hasa height of zero or more.This excludes anywindow toolbar line.Examples: :echo "The current window has " .. winheight(0) .. " lines."Can also be usedasamethod:GetWinid()->winheight()Return type:Numberwinlayout([{tabnr}])winlayout()The resultisa nestedList containing the layout ofwindowsina tabpage.Without{tabnr} use the current tabpage, otherwise thetabpagewith number{tabnr}. If thetabpage{tabnr}is not found,returns an empty list.Fora leaf window,it returns:['leaf',{winid}]For horizontally split windows, which forma column,itreturns:['col', [{nestedlist of windows}]]For vertically split windows, which forma row,it returns:['row', [{nestedlist of windows}]]Example:" Only one window in the tab page:echo winlayout()['leaf', 1000]" Two horizontally split windows:echo winlayout()['col', [['leaf', 1000], ['leaf', 1001]]]" The second tab page, with three horizontally split" windows, with two vertically split windows in the" middle window:echo winlayout(2)['col', [['leaf', 1002], ['row', [['leaf', 1003], ['leaf', 1001]]], ['leaf', 1000]]]Can also be usedasamethod:GetTabnr()->winlayout()Return type: list<any>winline()winline()The resultisa Number, whichis the screen line of the cursorin the window. Thisis counting screen lines from the top ofthe window. The first lineis one.If the cursor was moved theview on the file will be updatedfirst, this may causea scroll.Return type:Numberwinnr([{arg}])winnr()The resultisa Number, whichis the number of the currentwindow. The topwindow has number 1.Returns zero forapopup window.The optional argument{arg} supports the following values:$the number of the lastwindow (thewindowcount).#the number of the last accessedwindow (whereCTRL-W_p goes to). If thereis no previouswindow oritis in anothertab page0isreturned. May refer to the currentwindow insome cases (e.g. when evaluating'statusline'expressions).{N}jthe number of the Nthwindow below thecurrentwindow (whereCTRL-W_j goes to).{N}kthe number of the Nthwindow above the currentwindow (whereCTRL-W_k goes to).{N}hthe number of the Nthwindow left of thecurrentwindow (whereCTRL-W_h goes to).{N}lthe number of the Nthwindow right of thecurrentwindow (whereCTRL-W_l goes to).The number can be used withCTRL-W_w and ":wincmdw":wincmd.When{arg}is invalid an erroris given and zerois returned.Also seetabpagewinnr() andwin_getid().Examples:let window_count = winnr('$')let prev_window = winnr('#')let wnum = winnr('3k')Can also be usedasamethod:GetWinval()->winnr()Return type:Numberwinrestcmd()winrestcmd()Returnsa sequence of:resize commands that should restorethe currentwindow sizes. Only works properly when nowindowsare opened or closed and the currentwindow andtab pageisunchanged.Example::let cmd = winrestcmd():call MessWithWindowSizes():exe cmdReturn type:Stringwinrestview({dict})winrestview()Uses theDictionary returned bywinsaveview() to restoretheview of the current window.Note: The{dict} does not have to contain all values, that arereturned bywinsaveview(). If values are missing, thosesettings won't be restored. So you can use: :call winrestview({'curswant': 4})This will only set the curswant value (the column the cursorwants to move on vertical movements) of the cursor to column 5(yes, thatis 5), while all other settings will remain thesame. Thisis useful, if you set the cursor position manually.If you have changed the values the resultis unpredictable.If thewindow size changed the result won't be the same.Can also be usedasamethod:GetView()->winrestview()Return type:Numberwinsaveview()winsaveview()ReturnsaDictionary that contains information to restoretheview of the current window. Usewinrestview() torestore the view.Thisis useful if you haveamapping that jumps around in thebuffer and you want togo back to the original view.This does not save fold information. Use the'foldenable'option to temporarily switch off folding, so thatfolds arenot opened when moving around. This may have side effects.The return value includes:lnumcursor line numbercolcursor column (Note: the first columnzero,as opposed to whatgetcurpos()returns)coladdcursor column offset for'virtualedit'curswantcolumn for verticalmovement (Note:the first columnis zero,as opposedto whatgetcurpos() returns). After$ commandit will bea very largenumber equal tov:maxcol.toplinefirst line in thewindowtopfillfiller lines, only indiff modeleftcolfirst column displayed; only used when'wrap'is offskipcolcolumns skippedNote that no option values are saved.Return type: dict<number>winwidth({nr})winwidth()The resultisa Number, whichis the width ofwindow{nr}.{nr} can be thewindow number or thewindow-ID.When{nr}is zero, the width of the currentwindowisreturned. Whenwindow{nr} doesn't exist, -1is returned.An existingwindow always hasa width of zero or more.Examples: :echo "The current window has " .. winwidth(0) .. " columns." :if winwidth(0) <= 50 : 50 wincmd | :endifFor getting theterminal or screen size, see the'columns'option.Can also be usedasamethod:GetWinid()->winwidth()Return type:Numberwordcount()wordcount()The resultisa dictionary of byte/chars/word statistics forthe current buffer. Thisis the same infoas provided byg_CTRL-GThe return value includes:bytesNumber of bytes in the buffercharsNumber of chars in the bufferwordsNumber of words in the buffercursor_bytesNumber of bytes before cursor position(not inVisual mode)cursor_charsNumber of chars before cursor position(not inVisual mode)cursor_wordsNumber of words before cursor position(not inVisual mode)visual_bytesNumber of bytes visually selected(only inVisual mode)visual_charsNumber of chars visually selected(only inVisual mode)visual_wordsNumber of words visually selected(only inVisual mode)Return type: dict<number>writefile({object},{fname} [,{flags}])writefile()When{object}isaList writeit to file{fname}. Eachlistitemis separated witha NL. Eachlist itemmust beaStringor Number.All NL characters are replaced witha NUL character.Inserting CR characters needs to be done before passing{list}to writefile().When{object}isaBlob write the bytes to file{fname}unmodified, also when binary modeis not specified.{flags}must bea String. These characters are recognized:'b' Binary modeis used: There will not bea NL after the lastlist item. An empty itemat theend does cause the last line in the file toend ina NL.'a' Append modeis used, lines are appended to the file::call writefile(["foo"], "event.log", "a"):call writefile(["bar"], "event.log", "a")'D' Delete the file when the current function ends. This works like::defer delete({fname}) Fails when not ina function. Also see:defer.'s' fsync()is called afterwriting the file. This flushes the file to disk, if possible. This takes more time but avoids losing the file if the system crashes.'S' fsync()is not called, even when'fsync'is set. When{flags} does not contain "S" or "s" then fsync()is called if the'fsync' optionis set.An existing fileis overwritten, if possible.When the write fails -1is returned, otherwise 0. Thereis anerror message if the file can't be created or whenwritingfails.Also seereadfile().To copya file byte for byte::let fl = readfile("foo", "b"):call writefile(fl, "foocopy", "b")Can also be usedasamethod:GetText()->writefile("thefile")Return type:Numberxor({expr},{expr})xor()Bitwise XOR on the two arguments. The arguments are convertedtoa number.A List,Dict orFloat argument causes an error.Also seeand() andor().Example::let bits = xor(bits, 0x80)Can also be usedasamethod::let bits = bits->xor(0x80)Return type:Number==============================================================================3. Featurelistfeature-listThere are three types of features:1. Features that are only supported when they have been enabled when Vim was compiled+feature-list. Example::if has("cindent")gui_running2. Features that are only supported when certain conditions have been met. Example::if has("gui_running")has-patch3. Beyonda certain version orata certain version and includinga specific patch. The "patch-7.4.248" feature means that theVim version is 7.5 or later, oritis version 7.4 and patch 248 was included. Example::if has("patch-7.4.248")Note that it's possible for patch 248 to be omitted even though 249is included. Only happens when cherry-picking patches.Note that this form only works for patch 7.4.237 and later, before that you need to check for the patch and the v:version. Example (checking version 6.2.148 or later)::if v:version > 602 || (v:version == 602 && has("patch148"))Hint: To find out if Vim supports backslashes ina file name (MS-Windows),use: `if exists('+shellslash')`aclCompiled withACL support.all_builtin_termsCompiled with all builtin terminals enabled. (alwaystrue)amigaAmiga version of Vim.arabicCompiled withArabic supportArabic.arpCompiled with ARP support (Amiga).autocmdCompiled withautocommand support. (always true)autochdirCompiled with support for'autochdir'autoservernameAutomatically enableclientserverballoon_evalCompiled withballoon-eval support.balloon_multilineGUI supports multiline balloons.beosBeOS version of Vim.browseCompiled with:browse support, andbrowse() willwork.browsefilterCompiled with support forbrowsefilter.bsdCompiled on an OS in the BSD family (excluding macOS).builtin_termsCompiled with some builtin terminals. (always true)byte_offsetCompiled with support for 'o' in'statusline'channelCompiled with support forchannel andjobcindentCompiled with'cindent' support. (always true)clientserverCompiled with remote invocation supportclientserver.clipboardCompiled with'clipboard' support.clipboard_workingCompiled with'clipboard' support andit can be used.cmdline_complCompiled withcmdline-completion support.cmdline_histCompiled withcmdline-history support.cmdline_infoCompiled with'showcmd' and'ruler' support.commentsCompiled with'comments' support.compatibleCompiled to be veryVi compatible.conptyPlatform whereConPTY can be used.cryptvCompiled withencryption supportencryption.cscopeCompiled withcscope support.cursorbindCompiled with'cursorbind' (always true)debugCompiled with "DEBUG" defined.dialog_conCompiled with consoledialog support.dialog_con_guiCompiled with console andGUIdialog support.dialog_guiCompiled withGUIdialog support.diffCompiled withvimdiff and'diff' support.digraphsCompiled with support for digraphs.directxCompiled with support for DirectX and'renderoptions'.dndCompiled with support for the "~registerquote_~.drop_fileCompiled withdrop_file support.ebcdicCompiled ona machine with ebcdic character set.emacs_tagsCompiled with support for Emacs tags.evalCompiled withexpression evaluation support. Alwaystrue, of course!ex_extra+ex_extra (always true)extra_searchCompiled with support for'incsearch' and'hlsearch'farsiSupport forFarsi was removedfarsi.file_in_pathCompiled with support forgf and<cfile> (alwaystrue)filterpipeWhen'shelltemp'is off pipes are used for shellread/write/filter commandsfind_in_pathCompiled with support for include file searches+find_in_path.floatCompiled with support forFloat.fname_caseCase in file names matters (forAmiga andMS-Windowsthisis not present).foldingCompiled withfolding support.footerCompiled withGUI footer support.gui-footerforkCompiled to use fork()/exec() instead of system().gettextCompiled with message translationmulti-langguiCompiled withGUI enabled.gui_athenaCompiled with AthenaGUI (always false).gui_gnomeCompiled withGnome support (gui_gtkis also defined).gui_gtkCompiled withGTK+GUI (any version).gui_gtk2Compiled withGTK+ 2GUI (gui_gtkis also defined).gui_gtk3Compiled withGTK+ 3GUI (gui_gtkis also defined).gui_haikuCompiled withHaiku GUI.gui_macCompiled withMacintosh GUI.gui_motifCompiled withMotif GUI.gui_photonCompiled with Photon GUI.gui_runningVimis running in the GUI, orit will start soon.gui_win32Compiled withMS-WindowsWin32 GUI.gui_win32sidem, and Win32s system being used (Windows 3.1)haikuHaiku version of Vim.hangul_inputCompiled with Hangul input support.hangulhpuxHP-UX version of Vim.hurdGNU/Hurd version of VimiconvCan useiconv() for conversion.insert_expandCompiled with support forCTRL-X expansion commands inInsert mode. (always true)jobCompiled with support forchannel andjobipv6Compiled with support for IPv6 networking inchannel.jumplistCompiled withjumplist support. (always true)keymapCompiled with'keymap' support.lambdaCompiled withlambda support.langmapCompiled with'langmap' support.libcallCompiled withlibcall() support.linebreakCompiled with'linebreak','breakat','showbreak' and'breakindent' support.linuxLinux version of Vim.lispindentCompiled with support for lisp indenting.(always true)listcmdsCompiled with commands for the bufferlist:filesand the argumentlistarglist.localmapCompiled with local mappings and abbr.:map-localluaCompiled withLua interfaceLua.macAnyMacintosh version of Vim cf. osxmacunixSynonym for osxdarwinmenuCompiled with support for:menu.mksessionCompiled with support for:mksession.modify_fnameCompiled with file name modifiers.filename-modifiers(always true)mouseCompiled with support for mouse.mouse_decCompiled with support for Decterminal mouse.mouse_gpmCompiled with support for gpm (Linux console mouse)mouse_gpm_enabledGPM mouseis workingmouse_nettermCompiled with support for netterm mouse.mouse_ptermCompiled with support forqnx pterm mouse.mouse_sysmouseCompiled with support forsysmouse(*BSD console mouse)mouse_sgrCompiled with support for sgr mouse.mouse_urxvtCompiled with support for urxvt mouse.mouse_xtermCompiled with support for xterm mouse.mouseshapeCompiled with support for'mouseshape'.multi_byteCompiled with support for'encoding' (always true)multi_byte_encoding'encoding'is set toamultibyte encoding.multi_byte_imeCompiled with support forIME input method.multi_langCompiled with support for multiple languages.mzschemeCompiled withMzScheme interfacemzscheme.nanotimeCompiled with sub-second time stamp checks.netbeans_enabledCompiled with support fornetbeans and connected.netbeans_intgCompiled with support fornetbeans.num64Compiled with 64-bitNumber support. (always true)oleCompiled with OLE automation support for Win32.osxCompiled for macOS cf.macosxdarwinCompiled for macOS, withmac-darwin-featurepackagesCompiled withpackages support.path_extraCompiled with up/downwards search in'path' and'tags'perlCompiled withPerl interface.persistent_undoCompiled with support for persistentundo history.postscriptCompiled with PostScript file printing.printerCompiled with:hardcopy support.profileCompiled with:profile support.prof_nsecProfile results are in nanoseconds.pythonPython 2.x interface available.has-pythonpython_compiledCompiled withPython 2.x interface.has-pythonpython_dynamicPython 2.x interfaceis dynamically loaded.has-pythonpython3Python 3.x interface available.has-pythonpython3_compiledCompiled withPython 3.x interface.has-pythonpython3_dynamicPython 3.x interfaceis dynamically loaded.has-pythonpython3_stablePython 3.x interfaceis usingPython Stable ABI.has-pythonpythonxPython 2.x and/or 3.x interface available.python_xqnxQNX version of Vim.quickfixCompiled withquickfix support.reltimeCompiled withreltime() support.rightleftCompiled with'rightleft' support.rubyCompiled withRuby interfaceruby.scrollbindCompiled with'scrollbind' support. (always true)showcmdCompiled with'showcmd' support.signsCompiled with:sign support.smartindentCompiled with'smartindent' support. (always true)sodiumCompiled with libsodium for better crypt supportsoundCompiled with sound support, e.g.sound_playevent()spellCompiled withspell checking supportspell.startuptimeCompiled with--startuptime support.statuslineCompiled with support for'statusline','rulerformat'and special formats of'titlestring' and'iconstring'.sunSunOS version of Vim.sun_workshopSupport for Sunworkshop has been removed.syntaxCompiled withsyntax highlighting supportsyntax.syntax_itemsThere are activesyntax highlighting items for thecurrent buffer.systemCompiled to usesystem() instead of fork()/exec().tag_binaryCompiled with binary searching intags filestag-binary-search. (always true)tag_old_staticSupport for old statictags was removed, seetag-old-static.tclCompiled withTcl interface.termguicolorsCompiled withtrue color interminal support.terminalCompiled withterminal support.terminfoCompiled withterminfo instead of termcap.termresponseCompiled with support fort_RV andv:termresponse.textobjectsCompiled with support fortext-objects.textpropCompiled with support fortext-properties.tgetentCompiled with tgetent support, able to useatermcaporterminfo file.timersCompiled withtimer_start() support.titleCompiled withwindow title support'title'.(always true)toolbarCompiled with support forgui-toolbar.ttyininputisaterminal (tty)ttyoutoutputisaterminal (tty)unixUnix version of Vim.+unixunnamedplusCompiled with support for "unnamedplus" in'clipboard'user_commandsUser-defined commands. (always true)vartabsCompiled with variable tabstop support'vartabstop'.vconWin32: Virtual console supportis working, can use'termguicolors'. Also see+vtp.vertsplitCompiled with vertically splitwindows:vsplit.(always true)vim_startingTrue while initial source'ing takes place.startupvim_startingvim9scriptCompiled withVim9script supportviminfoCompiled withviminfo support.vimscript-1Compiled Vimscript version 1 supportvimscript-2Compiled Vimscript version 2 supportvimscript-3Compiled Vimscript version 3 supportvimscript-4Compiled Vimscript version 4 supportvirtualeditCompiled with'virtualedit' option. (always true)visualCompiled withVisual mode. (always true)visualextraCompiled with extraVisual mode commands. (alwaystrue)blockwise-operators.vmsVMS version of Vim.vreplaceCompiled withgR andgr commands. (always true)vtpCompiled for vcon support+vtp (check vcon to findout ifit works in the current console).waylandCompiled with Wayland protocol support.wayland_clipboardCompiled with support for Wayland selections/clipboardwildignoreCompiled with'wildignore' option.wildmenuCompiled with'wildmenu' option.win16old version forMS-Windows 3.1 (always false)win32Win32 version of Vim (MS-Windows 95 and later, 32 or64 bits)win32unixWin32 version of Vim, usingUnix files (Cygwin)win64Win64 version of Vim (MS-Windows 64 bit).win95Win32 version forMS-Windows 95/98/ME (always false)winaltkeysCompiled with'winaltkeys' option.windowsCompiled with support for more than one window.(always true)writebackupCompiled with'writebackup' default on.xattrCompiled with extended attributes supportxattr(currently only supported on Linux).xfontsetCompiled withXfontset supportxfontset.ximCompiled withX inputmethod supportxim.xpmCompiled with pixmap support.xpm_w32Compiled with pixmap support for Win32. (Only forbackward compatibility. Use "xpm" instead.)xsmpCompiled withX session management support.xsmp_interactCompiled with interactiveX session management support.xterm_clipboardCompiled with support for xterm clipboard.xterm_saveCompiled with support for saving and restoring thexterm screen.x11Compiled withX11 support.==============================================================================4. Matchingapattern inaStringstring-matchThisis common between several functions.Aregexppatternas explainedatpatternis normally used to finda match in the buffer lines. Whenapatternis used to finda match ina String, almost everything works in thesame way. The differenceis thataStringis handled likeitis one line.Whenit containsa "\n" character, thisis not seenasa line break for thepattern. It can be matched witha "\n" in the pattern, or with ".". Example::let a = "aaaa\nxxxx":echo matchstr(a, "..\n..")aaxx:echo matchstr(a, "a.x")axDon't forget that "^" will only matchat the first character of theString and"$"at the last character of the string. They don't match after or beforea"\n". vim:tw=78:ts=8:noet:ft=help:norl: