Movatterモバイル変換


[0]ホーム

URL:


Quick links:help overview ·quick reference ·user manual toc ·reference manual toc·faq
Go to keyword (shortcut:k)
Site search (shortcut:s)
usr_41.txt  ForVim version 9.1.  Last change: 2025 Jul 05     VIM USER MANUAL- byBramMoolenaar      Writea VimscriptThe Vimscript languageis used for thestartupvimrc file,syntax files, andmany other things.  This chapter explains the items that can be used ina Vimscript.  There area lot of them, therefore thisisa long chapter.41.1  Introduction41.2  Variables41.3  Expressions41.4  Conditionals41.5  Executing anexpression41.6  Usingfunctions41.7  Defininga function41.8Lists andDictionaries41.9  Whitespace41.10  Line continuation41.11  Comments41.12  Fileformat     Next chapter:usr_42.txt  Add newmenus Previous chapter:usr_40.txt  Make new commandsTable of contents:usr_toc.txt==============================================================================41.1  Introductionvim-script-introscriptLet's start with some nomenclature.A Vimscriptis any file that Vim caninterpret and execute.  This includes files written in Vim's scripting languagelike for example .vim files or configuration files like.vimrc and .gvimrc.These scripts may define functions, commands and settings that Vim uses tocustomize and extend its behavior.vim-script-notationThe correctnotationis "Vimscript" (or "Vim9script" when refering to thenewVim9 languageVim9-script), so we will use "Vimscript" to refer to theVim scripting language throughout this documentation. This shorthand helps tostreamline explanations and discussions about scripting with Vim.A Vimpluginisa collection of one or more Vim scripts, along with additionalfiles likehelp documentation, configuration files, and other resources,designed to add specific features or functionalities to Vim.Aplugin canprovide new commands, enhance existing capabilities, and integrate externaltools or services into the Vim environment.Your first experience with Vim scriptsis thevimrc file.  Vim readsit whenit starts up and executes the commands.  You can setoptions to the values youprefer, define mappings, select plugins and much more.   You can use any coloncommand init (commands that start witha ":"; these are sometimes referred toasEx commands or command-line commands).Syntax files are also Vim scripts.  As are files that setoptions foraspecific file type.A complicatedmacro can be defined bya separate Vimscript file.  You can think of other uses yourself.Vimscript comes in two flavors: legacy andVim9.  Since thishelp fileisfor new users, we'll teach you the newer and more convenientVim9 syntax.While legacyscriptis particularly for Vim,Vim9script looks more likeother languages, suchas JavaScript and TypeScript.To try out Vimscript the best wayis to editascript file and source it.Basically::edit test.vim[insert the script lines you want]:w:source %Let's start witha simple example:vim9scriptvar i = 1while i < 5  echo "count is" i  i += 1endwhileThe output of the example code is:count is 1count is 2count is 3count is 4In the first line thevim9script command makes clear thisisa new,Vim9script file.  That matters for how the rest of the fileis used.  Itisrecommended toputit in the very first line, before any comments.vim9-declarationsThe `vari= 1` command declares the "i" variable and initializes it.  Thegeneric form is:var {name} = {expression}In thiscase the variable nameis "i" and theexpressionisa simple value,the number one.Thewhile command startsa loop.  The generic form is:while {condition}  {statements}endwhileThe statements until the matchingendwhile are executed foras longas theconditionis true.  The condition used hereis theexpression "i< 5".  Thisistrue when the variableiis smaller than five.Note:If you happen to writea while loop that keeps on running, you caninterruptit by pressingCTRL-C (CTRL-Break on MS-Windows).Theecho command prints its arguments.  In thiscase thestring "countis"and the value of the variable i.  Sinceiis one, this will print:count is 1Then thereis the `i += 1` command.  This does the same thingas "i=i+ 1",it adds one to the variablei and assigns the new value to the same variable.The example was given to explain the commands, but would you really want tomake sucha loop,it can be written much more compact:for i in range(1, 4)  echo $"count is {i}"endforWe won't explain howfor,range()and$"string" work until later.  Followthe links if you are impatient.TRYING OUT EXAMPLESYou can easily try out most examples in thesehelp files without saving thecommands toa file.  For example, to try out the "for" loop abovedo this:1. position the cursor on the "for"2. startVisual mode with "v"3. move down to the "endfor"4. press colon, then "so" and EnterAfter pressing colon you will see ":'<,'>", whichis the range of the Visuallyselected text.For some commandsit matters they are executedas inVim9 script.  But typedcommands normally use legacyscript syntax, suchas the example below thatcauses theE1004 error.  For that use this fourth step:4. press colon, then "vim9 so" and Enter"vim9"is short forvim9cmd, whichisa command modifier to execute thefollowing command inVim9 syntax.Note that this won't work for examples that requireascript context.FOUR KINDS OF NUMBERSNumbers can be decimal, hexadecimal,octal and binary.A hexadecimal number starts with "0x" or "0X".  For example "0x1f"is decimal31 and "0x1234"is decimal 4660.Anoctal number starts with "0o", "0O".  "0o17"is decimal 15.A binary number starts with "0b" or "0B".  For example "0b101"is decimal 5.A decimal numberis just digits.  Careful: In legacyscript don'tputa zerobeforea decimal number,it will be interpretedas anoctal number!  That'sone reason to useVim9 script.Theecho command evaluates its argument and whenitisa number alwaysprints the decimal form.  Example:echo 0x7f 0o36127 30A numberis made negative witha minus sign.  This also works for hexadecimal,octal and binary numbers:echo -0x7f-127A minus signis also used for subtraction.  This can sometimes lead toconfusion.  If weputa minus sign before both numbers we get an error:echo -0x7f -0o36E1004: White space required before and after '-' at "-0o36"Note: if you are not usingaVim9script to try out these commands but typethem directly, they will be executedas legacy script.  Then the echo commandsees the second minus signas subtraction.  To get the error, prefix thecommand withvim9cmd:vim9cmd echo -0x7f -0o36E1004: White space required before and after '-' at "-0o36"Whitespace in anexpressionis often required to make sureitiseasy to readand avoid errors.  Suchas thinking that the "-0o36" above makes the numbernegative, whileitis actually seenasa subtraction.To actually have the minus sign be used for negation, you canput the secondexpression in parentheses:echo -0x7f (-0o36)-127 -30==============================================================================41.2  VariablesA variable name consists of ASCII letters, digits and the underscore.  Itcannot start witha digit.  Valid variable names are:counter_aap3very_long_variable_name_with_underscoresCamelCaseNameLENGTHInvalid names are "foo.bar" and "6var".Somevariables are global.  To seealist of currently defined globalvariables type this command::letYou can use globalvariables everywhere.  However,itis tooeasy to use thesame name in two unrelated scripts.  Thereforevariables declared inascriptare local to that script.  For example, if you have this in "script1.vim":vim9scriptvar counter = 5echo counter5And you try to use the variable in "script2.vim":vim9scriptecho counterE121: Undefined variable: counterUsingascript-local variable means you can be sure thatitis only changed inthatscript and not elsewhere.If youdo want to sharevariables between scripts, use the "g:" prefix andassign the value directly,do not usevar.  And usea specific name to avoidmistakes.  Thus in "script1.vim":vim9scriptg:mash_counter = 5echo g:mash_counter5And then in "script2.vim":vim9scriptecho g:mash_counter5Globalvariables can also be accessed on the command line, E.g. typing this:echo g:mash_counterThat will not work forascript-local variable.More aboutscript-localvariables here:script-variable.There are more kinds of variables, seeinternal-variables.  The most oftenused ones are:b:namevariable local toa bufferw:namevariable local toawindowg:nameglobal variable (also ina function)v:namevariable predefined by VimDELETING VARIABLESVariables take up memory and show up in the output of thelet command.  Todeletea global variable use theunlet command.  Example:unlet g:counterThis deletes the global variable "g:counter" to free up the memoryit uses.If you are not sure if the variable exists, and don't want an error messagewhenit doesn't, append !:unlet! g:counterYou cannotunletscript-localvariables inVim9 script, only in legacyscript.Whenascript has been processed to the end, the localvariables declaredthere will not be deleted.  Functions defined in thescript can use them.Example:vim9scriptvar counter = 0def g:GetCount(): number  counter += 1  return counterenddefEvery time you call the functionit will return the next count::echo g:GetCount()1:echo g:GetCount()2If you are worriedascript-local variableis consuming too much memory, setit to an empty ornull value after you no longer need it.  Example:var lines = readfile(...)...lines = []Note: below we'll leave out thevim9script line from examples, so we canconcentrate on the relevant commands, but you'll still need toputitat thetop of yourscript file.STRING VARIABLES AND CONSTANTSSo far only numbers were used for the variable value.  Strings can be usedaswell.  Numbers and strings are the basic types ofvariables that Vim supports.Example:var name = "Peter"echo namePeterEvery variable hasa type.  Very often,as in this example, the typeisdefined by assigninga value.  Thisis called type inference.  If youdo notwant to give the variablea value yet, you need to specify the type:var name: stringvar age: numberif male   name = "Peter"   age = 42else   name = "Elisa"   age = 45endifIf you makea mistake and try to assign the wrong type of value you'll get anerror:age = "Peter"E1012: Type mismatch; expected number but got stringMore about types in41.8.To assignastring value toa variable, you can useastring constant.  Thereare two types of these.  First thestring in double quotes,as we usedalready.  If you want to includea doublequote inside the string,putabackslash in front of it:var name = "he is \"Peter\""echo namehe is "Peter"To avoid the need for backslashes, you can useastring in single quotes:var name = 'he is "Peter"'echo namehe is "Peter"Insidea single-quotestring all the characters areas they are.  Only thesinglequote itselfis special: you need to use two to get one.Abackslashis taken literally, thus you can't useit to change the meaning of thecharacter after it:var name = 'P\e''ter'''echo nameP\e'ter'In double-quote stringsitis possible to use special characters.  Here areafew useful ones:\t<Tab>\n<NL>, line break\r<CR>,<Enter>\e<Esc>\b<BS>,backspace\""\\\,backslash\<Esc><Esc>\<C-W>CTRL-WThe last two are just examples.  The  "\<name>" form can be used to includethe special key "name".Seeexpr-quote for the fulllist of special items ina string.==============================================================================41.3  ExpressionsVim hasa fairly standard way to handle expressions.  You can read thedefinition here:expression-syntax.  Here we will show the most commonitems.The numbers, strings andvariables mentioned above are expressions bythemselves.  Thus everywhere anexpressionis expected, you can usea number,string or variable.  Other basic items in anexpression are:$NAMEenvironment variable&nameoption value@rregister contentsExamples:echo "The value of 'tabstop' is" &tsecho "Your home directory is" $HOMEif @a == 'text'The &name form can also be used to set an option value,do something andrestore the old value.  Example:var save_ic = &icset noics/The Start/The Beginning/&ic = save_icThis makes sure the "The Start"patternis used with the'ignorecase' optionoff.  Still,it keeps the value that the user had set.  (Another way todothis would be to add "\C" to the pattern, see/\C.)MATHEMATICSIt becomes more interesting if we combine these basic items.  Let's start withmathematics on numbers:a+badda-bsubtracta *bmultiplya/bdividea%bmoduloThe usual precedenceis used.  Example:echo 10 + 5 * 220Groupingis done with parentheses.  No surprises here.  Example:echo (10 + 5) * 230OTHERSStrings can be concatenated with ".." (seeexpr6).  Example:echo "Name: " .. nameName: PeterWhen the "echo" command gets multiple arguments,it separates them withaspace.  In the example the argumentisa single expression, thus nospaceisinserted.If you don't like the concatenation you can use the$"string" form, whichaccepts anexpression in curly braces:echo $"Name: {name}"Seeinterpolated-string for more information.Borrowed from theC languageis the conditional expression:a ? b : cIf "a" evaluates totrue "b"is used, otherwise "c"is used.  Example:var nr = 4echo nr > 5 ? "nr is big" : "nr is small"nr is smallThe three parts of the constructs are always evaluated first, thus you couldseeit works as:(a) ? (b) : (c)Thereis also thefalsy operator:echo name ?? "No name given"See??.==============================================================================41.4  ConditionalsTheif commands executes the following statements, until the matchingendif, only whena conditionis met.  The generic form is:if{condition}{statements}endifOnly when theexpression{condition} evaluates totrue or one will the{statements} be executed.  If they are not executed theymust still be validcommands.  If they contain garbage, Vim won't be able to find the matchingendif.You can also useelse.  The generic form for this is:if{condition}{statements}else{statements}endifThe second{statements} blockis only executed if the first one isn't.Finally, thereiselseifif{condition}{statements}elseif{condition}{statements}endifThis works just like usingelse and thenif, but without the need for anextraendif.A useful example for yourvimrc fileis checking the'term' option and doingsomething depending upon its value:if &term == "xterm"  # Do stuff for xtermelseif &term == "vt100"  # Do stuff for a vt100 terminalelse  # Do something for other terminalsendifThis uses "#" to starta comment, more about that later.LOGIC OPERATIONSWe already used some of them in the examples.  These are the most often usedones:a==bequal toa !=bnot equal toa>bgreater thana >=bgreater than or equal toa<bless thana <=bless than or equal toThe resultistrue if the conditionis met andfalse otherwise.  An example:if v:version >= 800  echo "congratulations"else  echo "you are using an old version, upgrade!"endifHere "v:version"isa variable defined by Vim, which has the value of the Vimversion.  800is for version 8.0, version 8.1 has the value 801.  Thisisuseful to writeascript that works with multiple versions of Vim.Seev:version.  You can also check fora specific feature withhas() oraspecific patch, seehas-patch.The logic operators work both for numbers and strings.  When comparing twostrings, the mathematical differenceis used.  This compares byte values,which may not be right for some languages.If you try to compareastring witha number you will get an error.For strings there are two more useful items:str =~ patmatches withstr !~ patdoes not match withThe left item "str"is usedasa string.  The right item "pat"is usedasapattern, like what's used for searching.  Example:if str =~ " "  echo "str contains a space"endifif str !~ '\.$'  echo "str does not end in a full stop"endifNotice the use ofa single-quotestring for the pattern.  Thisis useful,because patterns tend to contain many backslashes and backslashes need to bedoubled ina double-quote string.The matchis not anchored, if you want to match the wholestring start with"^" andend with "$".The'ignorecase' optionis not used when comparing strings.  When youdo wantto ignorecase append "?".  Thus "==?" compares two strings to be equal whileignoring case.  For the full table seeexpr-==.MORE LOOPINGThewhile command was already mentioned.  Two more statements can be used inbetween thewhile and theendwhile:continueJump back to the start of the while loop; theloop continues.breakJump forward to theendwhile; the loopisdiscontinued.Example:var counter = 1while counter < 40  if skip_number(counter)    continue  endif  if last_number(counter)    break  endif  sleep 50m  ++counterendwhileThesleep command makes Vim takea nap.  The "50m"specifies fiftymilliseconds.  Another exampleis `sleep 4`, which sleeps for four seconds.continue andbreak can also be used in betweenfor andendfor.Even more looping can be done with thefor command, see below in41.8.==============================================================================41.5  Executing anexpressionSo far the commands in thescript were executed by Vim directly.  Theexecute command allows executing the result of an expression.  Thisisavery powerful way to build commands and execute them.An exampleis to jump toa tag, whichis contained ina variable:execute "tag " .. tag_nameThe ".."is used to concatenate thestring "tag " with the value of variable"tag_name".  Suppose "tag_name" has the value "get_cmd", then the command thatwill be executed is:tag get_cmdTheexecute command can only executeEx commands.  Thenormal commandexecutesNormal mode commands.  However, its argumentis not anexpression butthe literal command characters.  Example:normal gg=GThis jumps to the first line with "gg" and formats all lines with the "="operator and the "G" movement.To makenormal work with an expression, combineexecute with it.Example:execute "normal " .. count .. "j"This will move the cursor "count" lines down.Make sure that the argument fornormalisa complete command.  OtherwiseVim will run into theend of the argument and silently abort the command.  Forexample, if you start the delete operator, youmust give themovement commandalso.  This works:normal d$This does nothing:normal dIf you startInsert mode anddo notendit with Esc,it willend anyway.  Thisworks toinsert "new text":execute "normal inew text"If you want todo something afterinserting text youdo need toendInsertmode:execute "normal inew text\<Esc>b"This inserts "new text" and puts the cursor on the firstletter of "text".Notice the use of the special key "\<Esc>".  This avoids having to enterareal<Esc> character in your script.  Thatis whereexecute withadouble-quotestring comes in handy.If you don't want to executeastringasa command but evaluateit to get theresult of the expression, you can use theeval() function:var optname = "path"var optvalue = eval('&' .. optname)A "&" characteris prepended to "path", thus the argument toeval()is"&path".  The result will then be the value of the'path' option.==============================================================================41.6  UsingfunctionsVim defines manyfunctions and providesa large amount of functionality thatway.A few examples will be given in this section.  You can find the wholelist below:function-list.A functionis called with the parameters in between parentheses, separated bycommas.  Example:search("Date: ", "W")This calls thesearch() function, with arguments "Date: " and "W".  Thesearch() function uses its first argumentasa searchpattern and the secondoneas flags.  The "W" flag means the search doesn't wrap around theend ofthe file.Using thecall commandis optional inVim9 script.  Itis required inlegacyscript and on the command line:call search("Date: ", "W")A function can be called in an expression.  Example:var line = getline(".")var repl = substitute(line, '\a', "*", "g")setline(".", repl)Thegetline() function obtainsa line from the current buffer.  Its argumentisa specification of the line number.  In thiscase "."is used, which meansthe line where the cursor is.Thesubstitute() function does something similar to the:substitute command.The first argument "line"is thestring on which to perform the substitution.The second argument '\a'is the pattern, the third "*"is the replacementstring.  Finally, the last argument "g"is the flags.Thesetline() function sets the line, specified by the first argument, toanew string, the second argument.  In this example the line under the cursorisreplaced with the result of the substitute().  Thus the effect of the threestatementsis equal to::substitute/\a/*/gUsing thefunctions becomes interesting when youdo more work before andafter thesubstitute() call.FUNCTIONSfunction-listThere are many functions.  We will mention them here, grouped by what they areused for.  You can find an alphabeticallist here:builtin-function-list.UseCTRL-] on the function name to jump to detailedhelp on it.String manipulation:string-functionsnr2char()geta character by its number valuelist2str()geta characterstring fromalist of numberschar2nr()get number value ofa characterstr2list()getlist of numbers fromastringstr2nr()convertastring toaNumberstr2float()convertastring toaFloatprintf()formatastring according to% itemsescape()escape characters inastring witha '\'shellescape()escapeastring for use witha shell commandfnameescape()escapea file name for use witha Vim commandtr()translate characters from one set to anotherstrtrans()translateastring to makeit printablekeytrans()translate internalkeycodes toa form thatcan be used by:maptolower()turnastring tolowercasetoupper()turnastring touppercasecharclass()class ofa charactermatch()position whereapattern matches inastringmatchbufline()all the matches ofapattern ina buffermatchend()position whereapattern match ends inastringmatchfuzzy()fuzzy matchesastring inalist of stringsmatchfuzzypos()fuzzy matchesastring inalist of stringsmatchstr()match ofapattern inastringmatchstrlist()all the matches ofapattern inaList ofstringsmatchstrpos()match and positions ofapattern inastringmatchlist()likematchstr() and also return submatchesstridx()firstindex ofa shortstring ina longstringstrridx()lastindex ofa shortstring ina longstringstrlen()length ofastring in bytesstrcharlen()length ofastring in charactersstrchars()number of characters inastringstrutf16len()number of UTF-16 code units inastringstrwidth()size ofstring when displayedstrdisplaywidth()size ofstring when displayed, deals with tabssetcellwidths()set character cell width overridesgetcellwidths()get character cell width overridesgetcellpixels()get character cell pixel sizereverse()reverse the order of characters inastringsubstitute()substituteapattern match withastringsubmatch()geta specific match in ":s" andsubstitute()strpart()get part ofastring using byteindexstrcharpart()get part ofastring using charindexslice()takeaslice ofa string, using charindex inVim9scriptstrgetchar()get character fromastring using charindexexpand()expand special keywordsexpandcmd()expanda command like done for:editiconv()convert text from one encoding to anotherbyteidx()byteindex ofa character inastringbyteidxcomp()likebyteidx() butcount composing characterscharidx()characterindex ofa byte inastringutf16idx()UTF-16index ofa byte inastringrepeat()repeatastring multiple timeseval()evaluateastringexpressionexecute()execute anEx command and get the outputwin_execute()likeexecute() but ina specifiedwindowtrim()trim characters fromastringbindtextdomain()set message lookup translation base pathgettext()lookup message translationngettext()lookup single/plural message translationstr2blob()convertalist of strings intoablobblob2str()convertablob intoalist of stringsList manipulation:list-functionsget()get an item without error for wrongindexlen()number of items inaListempty()check ifListis emptyinsert()insert an item somewhere inaListadd()append an item toaListextend()appendaList toaListextendnew()makea newList and append itemsremove()remove one or more items fromaListcopy()makea shallow copy ofaListdeepcopy()makea full copy ofaListfilter()remove selected items fromaListmap()change eachList itemmapnew()makea newList with changed itemsforeach()apply function toList itemsreduce()reduceaList toa valueslice()takeaslice ofaListsort()sortaListreverse()reverse the order of items inaListuniq()remove copies of repeated adjacent itemssplit()splitaString intoaListjoin()joinList items intoaStringrange()returnaList witha sequence of numbersstring()String representation ofaListcall()calla function withListas argumentsindex()index ofa value inaList orBlobindexof()index inaList orBlob where anexpressionevaluates totruemax()maximum value inaListmin()minimum value inaListcount()count number of timesa value appears inaListrepeat()repeataList multiple timesflatten()flattenaListflattennew()flattena copy ofaListitems()getList ofList index-value pairsTuple manipulation:tuple-functionscopy()makea shallow copy ofaTuplecount()count number of timesa value appears inaTupledeepcopy()makea full copy ofaTupleempty()check ifTupleis emptyforeach()apply function toTuple itemsget()get an item without error for wrongindexindex()index ofa value inaTupleindexof()index inaTuple where anexpressionistrueitems()getList ofTuple index-value pairsjoin()joinTuple items intoaStringlen()number of items inaTuplelist2tuple()convertalist of items intoaTuplemax()maximum value inaTuplemin()minimum value inaTuplereduce()reduceaTuple toa valuerepeat()repeataTuple multiple timesreverse()reverse the order of items inaTupleslice()takeaslice ofaTuplestring()string representation ofaTupletuple2list()convertaTuple intoaListDictionary manipulation:dict-functionsget()get an entry without an error fora wrong keylen()number of entries inaDictionaryhas_key()check whethera key appears inaDictionaryempty()check ifDictionaryis emptyremove()remove an entry fromaDictionaryextend()add entries from oneDictionary to anotherextendnew()makea newDictionary and append itemsfilter()remove selected entries fromaDictionarymap()change eachDictionary entrymapnew()makea newDictionary with changed itemsforeach()apply function toDictionary itemskeys()getList ofDictionary keysvalues()getList ofDictionary valuesitems()getList ofDictionary key-value pairscopy()makea shallow copy ofaDictionarydeepcopy()makea full copy ofaDictionarystring()String representation ofaDictionarymax()maximum value inaDictionarymin()minimum value inaDictionarycount()count number of timesa value appearsFloating point computation:float-functionsfloat2nr()convertFloat toNumberabs()absolute value (also works for Number)round()round offceil()round upfloor()round downtrunc()remove value after decimal pointfmod()remainder of divisionexp()exponentiallog()natural logarithm (logarithm to base e)log10()logarithm to base 10pow()value ofx to the exponentysqrt()square rootsin()sinecos()cosinetan()tangentasin()arc sineacos()arc cosineatan()arc tangentatan2()arc tangentsinh()hyperbolic sinecosh()hyperbolic cosinetanh()hyperbolic tangentisinf()check for infinityisnan()check for nota numberBlob manipulation:blob-functionsblob2list()getalist of numbers fromabloblist2blob()getablob fromalist of numbersreverse()reverse the order of numbers inablobOther computation:bitwise-functionand()bitwise ANDinvert()bitwise invertor()bitwise ORxor()bitwise XORsha256()SHA-256 hashrand()geta pseudo-random numbersrand()initialize seed used byrand()Variables:var-functionsinstanceof()check ifa variableis an instance ofa givenclasstype()type ofa variableasa numbertypename()type ofa variableas textislocked()check ifa variableis lockedfuncref()getaFuncref fora functionreferencefunction()getaFuncref fora function namegetbufvar()geta variable value froma specific buffersetbufvar()seta variable ina specific buffergetwinvar()geta variable from specificwindowgettabvar()geta variable from specifictab pagegettabwinvar()geta variable from specificwindow&tab pagesetwinvar()seta variable ina specificwindowsettabvar()seta variable ina specifictab pagesettabwinvar()seta variable ina specificwindow&tab pagegarbagecollect()possibly free memoryCursor andmark position:cursor-functionsmark-functionscol()column number of the cursor oramarkvirtcol()screen column of the cursor oramarkline()line number of the cursor ormarkwincol()window column number of the cursorwinline()window line number of the cursorcursor()position the cursorata line/columnscreencol()get screen column of the cursorscreenrow()get screen row of the cursorscreenpos()screen row and col ofa text charactervirtcol2col()byteindex ofa text character on screengetcurpos()get position of the cursorgetpos()get position of cursor, mark, etc.setpos()set position of cursor, mark, etc.getmarklist()list of global/local marksbyte2line()get line numberata specific bytecountline2byte()bytecountata specific linediff_filler()get the number of filler lines abovea linescreenattr()get attributeata screen line/rowscreenchar()get character codeata screen line/rowscreenchars()get character codesata screen line/rowscreenstring()getstring of charactersata screen line/rowcharcol()character number of the cursor oramarkgetcharpos()get character position of cursor, mark, etc.setcharpos()set character position of cursor, mark, etc.getcursorcharpos()get character position of the cursorsetcursorcharpos()set character position of the cursorWorking with text in the current buffer:text-functionsgetline()geta line orlist of lines from the buffergetregion()geta region of text from the buffergetregionpos()getalist of positions fora regionsetline()replacea line in the bufferappend()append line orlist of lines in the bufferindent()indent ofa specific linecindent()indent according toC indentinglispindent()indent according to Lisp indentingnextnonblank()find next non-blank lineprevnonblank()find previous non-blank linesearch()finda match forapatternsearchpos()finda match forapatternsearchcount()get number of matches before/after the cursorsearchpair()find the otherend ofa start/skip/endsearchpairpos()find the otherend ofa start/skip/endsearchdecl()search for the declaration ofa namegetcharsearch()return character search informationsetcharsearch()set character search informationWorking with text in another buffer:getbufline()getalist of lines from the specified buffergetbufoneline()geta one line from the specified buffersetbufline()replacea line in the specified bufferappendbufline()appendalist of lines in the specified bufferdeletebufline()delete lines froma specified buffersystem-functionsfile-functionsSystemfunctions and manipulation of files:glob()expandwildcardsglobpath()expandwildcards ina number of directoriesglob2regpat()converta globpattern intoa searchpatternfindfile()finda file inalist of directoriesfinddir()finda directory inalist of directoriesresolve()find out wherea shortcut points tofnamemodify()modifya file namepathshorten()shorten directory names ina pathsimplify()simplifya path withoutchanging its meaningexecutable()check if an executable program existsexepath()full path of an executable programfilereadable()check ifa file can be readfilewritable()check ifa file can be written togetfperm()get the permissions ofa filesetfperm()set the permissions ofa filegetftype()get the kind ofa fileisabsolutepath()check ifa pathis absoluteisdirectory()check ifa directory existsgetfsize()get the size ofa filegetcwd()get the current working directoryhaslocaldir()check if currentwindow used:lcd or:tcdtempname()get the name ofa temporary filemkdir()createa new directorychdir()change current working directorydelete()deletea filerename()renamea filesystem()get the result ofa shell commandasastringsystemlist()get the result ofa shell commandasalistenviron()get all environmentvariablesgetenv()get one environment variablesetenv()set an environment variablehostname()name of the systemreadfile()reada file intoaList of linesreadblob()reada file intoaBlobreaddir()getaList of file names ina directoryreaddirex()getaList of file information ina directorywritefile()writeaList of lines orBlob intoa filefilecopy()copya file{from} to{to}Date and Time:date-functionstime-functionsgetftime()get last modification time ofa filelocaltime()get current time in secondsstrftime()convert time toastringstrptime()converta date/timestring to timereltime()get the current or elapsed time accuratelyreltimestr()convertreltime() result toastringreltimefloat()convertreltime() result toaFloatAutocmds:autocmd-functionsautocmd_add()addalist of autocmds and groupsautocmd_delete()deletealist of autocmds and groupsautocmd_get()returnalist of autocmdsbuffer-functionswindow-functionsarg-functionsBuffers,windows and the argument list:argc()number of entries in the argumentlistargidx()current position in the argumentlistarglistid()get id of the argumentlistargv()get one entry from the argumentlistbufadd()adda file to thelist ofbuffersbufexists()check ifa buffer existsbuflisted()check ifa buffer exists andis listedbufload()ensurea bufferis loadedbufloaded()check ifa buffer exists andis loadedbufname()get the name ofa specific bufferbufnr()get the buffer number ofa specific buffertabpagebuflist()returnList ofbuffers inatab pagetabpagenr()get the number ofatab pagetabpagewinnr()likewinnr() fora specifiedtab pagewinnr()get thewindow number for the currentwindowbufwinid()get thewindow ID ofa specific bufferbufwinnr()get thewindow number ofa specific bufferwinbufnr()get the buffer number ofa specificwindowlistener_add()adda callback to listen to changeslistener_flush()invoke listener callbackslistener_remove()removea listener callbackwin_findbuf()findwindows containinga bufferwin_getid()getwindow ID ofawindowwin_gettype()get type ofwindowwin_gotoid()go towindow with IDwin_id2tabwin()gettab andwindow nr fromwindow IDwin_id2win()getwindow nr fromwindow IDwin_move_separator()movewindow vertical separatorwin_move_statusline()movewindow status linewin_splitmove()movewindow toa split of anotherwindowgetbufinfo()getalist with buffer informationgettabinfo()getalist withtab page informationgetwininfo()getalist withwindow informationgetchangelist()getalist of changelist entriesgetjumplist()getalist of jumplist entriesswapfilelist()list of existing swap files in'directory'swapinfo()information abouta swap fileswapname()get the swap file path ofa bufferCommand line:command-line-functionsgetcmdcomplpat()get completionpattern of the current commandlinegetcmdcompltype()get the type of the current command linecompletiongetcmdline()get the current command line inputgetcmdprompt()get the current command line promptgetcmdpos()get position of the cursor in the command linegetcmdscreenpos()get screen position of the cursor in thecommand linesetcmdline()set the current command linesetcmdpos()set position of the cursor in the command linegetcmdtype()return the current command-line typegetcmdwintype()return the current command-linewindow typegetcompletion()list of command-line completion matchesgetcompletiontype()get the type of the command-line completionfor specifiedstringfullcommand()get full command namecmdcomplete_info()get command-line completion informationQuickfix and location lists:quickfix-functionsgetqflist()list ofquickfixerrorssetqflist()modifyaquickfixlistgetloclist()list of locationlist itemssetloclist()modifya locationlistInsert mode completion:completion-functionscomplete()set found matchescomplete_add()add to found matchescomplete_check()check if completion should be abortedcomplete_info()get current completion informationcomplete_match()getinsert completion start match col andtrigger textpumvisible()check if thepopup menuis displayedpum_getpos()position and size ofpopup menu if visibleFolding:folding-functionsfoldclosed()check fora closed foldata specific linefoldclosedend()likefoldclosed() but return the last linefoldlevel()check for the fold levelata specific linefoldtext()generate the line displayed fora closed foldfoldtextresult()get the text displayed fora closed foldSyntax and highlighting:syntax-functionshighlighting-functionsclearmatches()clear all matches defined bymatchadd() andthe:match commandsgetmatches()get all matches defined bymatchadd() andthe:match commandshlexists()check ifa highlight group existshlget()get highlight group attributeshlset()set highlight group attributeshlID()get ID ofa highlight groupsynID()getsyntax IData specific positionsynIDattr()geta specific attribute ofasyntax IDsynIDtrans()get translatedsyntax IDsynstack()getlist ofsyntax IDsata specific positionsynconcealed()get info about (syntax) concealingdiff_hlID()get highlight ID fordiff modeata positionmatchadd()defineapattern to highlight (a "match")matchaddpos()definealist of positions to highlightmatcharg()get info about:match argumentsmatchdelete()deletea match defined bymatchadd() ora:match commandsetmatches()restorealist of matches saved bygetmatches()Spelling:spell-functionsspellbadword()locate badly spelledwordat or after cursorspellsuggest()return suggested spelling correctionssoundfold()return the sound-a-like equivalent ofawordHistory:history-functionshistadd()add an item toahistoryhistdel()delete an item fromahistoryhistget()get an item fromahistoryhistnr()get highestindex ofahistorylistInteractive:interactive-functionsbrowse()put upa file requesterbrowsedir()put upa directory requesterconfirm()let the user makea choicegetchar()geta character from the usergetcharstr()geta character from the userasastringgetcharmod()get modifiers for the last typed charactergetmousepos()get last known mouse positiongetmouseshape()get name of the current mouse shapeechoraw()output characters as-isfeedkeys()put characters in the typeahead queueinput()geta line from the userinputlist()let the user pick an entry fromalistinputsecret()geta line from the user without showingitinputdialog()geta line from the user inadialoginputsave()save and clear typeaheadinputrestore()restore typeaheadGUI:gui-functionsgetfontname()get name of current font being usedgetwinpos()position of the Vimwindowgetwinposx()X position of the Vimwindowgetwinposy()Y position of the Vimwindowballoon_show()set the balloon contentballoon_split()splita message fora balloonballoon_gettext()get the text in the balloonVim server:server-functionsserverlist()return thelist of server namesremote_startserver()runa serverremote_send()send command characters toa Vim serverremote_expr()evaluate anexpression ina Vim serverserver2client()senda reply toa client ofa Vim serverremote_peek()check if thereisa reply froma Vim serverremote_read()reada reply froma Vim serverforeground()move the Vimwindow to the foregroundremote_foreground()move the Vim serverwindow to the foregroundWindow size and position:window-size-functionswinheight()get height ofa specificwindowwinwidth()get width ofa specificwindowwin_screenpos()get screen position ofawindowwinlayout()get layout ofwindows inatab pagewinrestcmd()return command to restorewindow sizeswinsaveview()getview of currentwindowwinrestview()restore savedview of currentwindowMappings and Menus:mapping-functionsdigraph_get()getdigraphdigraph_getlist()get alldigraphsdigraph_set()registerdigraphdigraph_setlist()register multipledigraphshasmapto()check ifamapping existsmapcheck()check ifa matchingmapping existsmaparg()get rhs ofamappingmaplist()getlist of all mappingsmapset()restoreamappingmenu_info()get information abouta menu itemwildmenumode()check if the wildmodeis activeTesting:test-functionsassert_equal()assert that two expressions values are equalassert_equalfile()assert that two file contents are equalassert_notequal()assert that two expressions values are not equalassert_inrange()assert that anexpressionis insidea rangeassert_match()assert thatapattern matches the valueassert_notmatch()assert thatapattern does not match the valueassert_false()assert that anexpressionisfalseassert_true()assert that anexpressionistrueassert_exception()assert thata command throws an exceptionassert_beeps()assert thata command beepsassert_nobeep()assert thata command does not causeabeepassert_fails()assert thata command failsassert_report()reporta test failuretest_alloc_fail()make memory allocation failtest_autochdir()enable'autochdir' duringstartuptest_override()test with Vim internal overridestest_garbagecollect_now()   free memory right nowtest_garbagecollect_soon()  seta flag to free memory soontest_getvalue()get value of an internal variabletest_gui_event()generateaGUI event fortestingtest_ignore_error()ignorea specific error messagetest_mswin_event()generate anMS-Windows eventtest_null_blob()returnanullBlobtest_null_channel()returnanullChanneltest_null_dict()returnanullDicttest_null_function()returnanullFuncreftest_null_job()returnanullJobtest_null_list()returnanullListtest_null_partial()returnanullPartial functiontest_null_string()returnanullStringtest_null_tuple()returnanullTupletest_settime()set the time Vim uses internallytest_setmouse()set the mouse positiontest_feedinput()add key sequence to input buffertest_option_not_set()reset flag indicating option was settest_refcount()return an expression'sreferencecounttest_srand_seed()set the seed value forsrand()test_unknown()returna value with unknown typetest_void()returna value with void typeInter-process communication:channel-functionsch_canread()check if thereis something to readch_open()openachannelch_close()closeachannelch_close_in()close the in part ofachannelch_read()reada message fromachannelch_readblob()readaBlob fromachannelch_readraw()reada raw message fromachannelch_sendexpr()senda JSON message overachannelch_sendraw()senda raw message overachannelch_evalexpr()evaluate anexpression overchannelch_evalraw()evaluatea rawstring overchannelch_status()get status ofachannelch_getbufnr()get the buffer number ofachannelch_getjob()get thejob associated withachannelch_info()getchannel informationch_log()writea message in thechannel log filech_logfile()set thechannel log filech_setoptions()set theoptions forachanneljson_encode()encode anexpression toa JSONstringjson_decode()decodea JSONstring to Vim typesjs_encode()encode anexpression toa JSONstringjs_decode()decodea JSONstring to Vim typesbase64_encode()encodeablob intoa base64stringbase64_decode()decodea base64string intoabloberr_teapot()give error 418 or 503Jobs:job-functionsjob_start()startajobjob_stop()stopajobjob_status()get the status ofajobjob_getchannel()get thechannel used byajobjob_info()get information aboutajobjob_setoptions()setoptions forajobSigns:sign-functionssign_define()define or updatea signsign_getdefined()getalist of definedsignssign_getplaced()getalist of placedsignssign_jump()jump toa signsign_place()placea signsign_placelist()placealist ofsignssign_undefine()undefinea signsign_unplace()unplacea signsign_unplacelist()unplacealist ofsignsTerminal window:terminal-functionsterm_start()openaterminalwindow and runajobterm_list()get thelist ofterminalbuffersterm_sendkeys()send keystrokes toaterminalterm_wait()wait for screen to be updatedterm_getjob()get thejob associated withaterminalterm_scrape()get row ofaterminal screenterm_getline()geta line of text fromaterminalterm_getattr()get the value of attribute{what}term_getcursor()get the cursor position ofaterminalterm_getscrolled()get the scrollcount ofaterminalterm_getaltscreen()get the alternate screen flagterm_getsize()get the size ofaterminalterm_getstatus()get the status ofaterminalterm_gettitle()get the title ofaterminalterm_gettty()get the tty name ofaterminalterm_setansicolors()set 16 ANSI colors, used forGUIterm_getansicolors()get 16 ANSI colors, used forGUIterm_dumpdiff()display difference between two screen dumpsterm_dumpload()loadaterminal screen dump inawindowterm_dumpwrite()dump contents ofaterminal screen toa fileterm_setkill()set signal to stopjob inaterminalterm_setrestore()set command to restoreaterminalterm_setsize()set the size ofaterminalterm_setapi()setterminal JSON API function name prefixPopup window:popup-window-functionspopup_create()createpopup centered in the screenpopup_atcursor()createpopup just above the cursor position,closes when the cursor moves awaypopup_beval()at the position indicated by v:beval_variables, closes when the mouse moves awaypopup_notification()showa notification for three secondspopup_dialog()createpopup centered with padding and borderpopup_menu()prompt for selecting an item fromalistpopup_hide()hideapopup temporarilypopup_show()showa previously hiddenpopuppopup_move()change the position and size ofapopuppopup_setoptions()overrideoptions ofapopuppopup_settext()replace thepopup buffer contentspopup_setbuf()set thepopup bufferpopup_close()close onepopuppopup_clear()close all popupspopup_filter_menu()select fromalist of itemspopup_filter_yesno()block until 'y' or 'n'is pressedpopup_getoptions()get currentoptions forapopuppopup_getpos()get actual position and size ofapopuppopup_findecho()getwindow ID forpopup used for:echowindowpopup_findinfo()getwindow ID forpopup infowindowpopup_findpreview()getwindow ID forpopup previewwindowpopup_list()getlist of allpopupwindow IDspopup_locate()getpopupwindow ID from its screen positionTimers:timer-functionstimer_start()createatimertimer_pause()pause or unpauseatimertimer_stop()stopatimertimer_stopall()stop alltimerstimer_info()get information abouttimersTags:tag-functionstaglist()getlist of matchingtagstagfiles()getalist oftags filesgettagstack()get thetag stack ofawindowsettagstack()modify thetag stack ofawindowPrompt Buffer:promptbuffer-functionsprompt_getprompt()get the effective prompt text fora bufferprompt_setcallback()set prompt callback fora bufferprompt_setinterrupt()set interrupt callback fora bufferprompt_setprompt()set the prompt text fora bufferRegisters:register-functionsgetreg()get contents ofaregistergetreginfo()get information aboutaregistergetregtype()get type ofaregistersetreg()set contents and type ofaregisterreg_executing()return the name of theregister being executedreg_recording()return the name of theregister being recordedText Properties:text-property-functionsprop_add()attacha propertyata positionprop_add_list()attacha propertyat multiple positionsprop_clear()remove all properties froma line or linesprop_find()search fora propertyprop_list()returnalist of all properties ina lineprop_remove()removea property froma lineprop_type_add()add/definea property typeprop_type_change()change properties ofa typeprop_type_delete()removea text property typeprop_type_get()return the properties ofa typeprop_type_list()returnalist of all property typesSound:sound-functionssound_clear()stop playing all soundssound_playevent()play an event's soundsound_playfile()playa sound filesound_stop()stop playinga soundVarious:various-functionsmode()get current editing modestate()get current busy statevisualmode()last visual mode usedexists()check ifa variable, function, etc. existsexists_compiled()likeexists() but checkat compile timehas()check ifa featureis supported in Vimchangenr()return number of most recent changecscope_connection()check ifacscope connection existsdid_filetype()check ifaFileTypeautocommand was useddiff()diff twoLists of stringseventhandler()check if invoked by an event handlergetcellpixels()getList of cell pixel sizegetpid()get process ID of Vimgetscriptinfo()getlist of sourced Vim scriptsgetstacktrace()get current stack trace of Vim scriptsgetimstatus()check ifIME statusis activeinterrupt()interruptscript executionwindowsversion()getMS-Windows versionterminalprops()properties of theterminallibcall()calla function in an external librarylibcallnr()idem, returninga numberundofile()get the name of theundo fileundotree()return the state of theundo tree fora buffershiftwidth()effective value of'shiftwidth'wordcount()get byte/word/charcount of bufferid()getuniquestring for item to useasa keyluaeval()evaluateLuaexpressionmzeval()evaluateMzSchemeexpressionperleval()evaluatePerlexpression(+perl)py3eval()evaluatePythonexpression(+python3)pyeval()evaluatePythonexpression(+python)pyxeval()evaluatepython_xexpressionrubyeval()evaluateRubyexpressiondebugbreak()interrupta program being debugged==============================================================================41.7  Defininga functionVim enables you to define your own functions.  The basic function declarationbeginsas follows:def {name}({var1}, {var2}, ...): return-type  {body}enddefNote:Function namesmust begin witha capital letter.Let's definea short function to return the smaller of two numbers.  It startswith this line:def Min(num1: number, num2: number): numberThis tells Vim that the functionis named "Min",it takes two arguments thatare numbers: "num1" and "num2" and returnsa number.The first thing you need todois to check to see which numberis smaller:if num1 < num2Let's assign the variable "smaller" the value of the smallest number:var smaller: numberif num1 < num2  smaller = num1else  smaller = num2endifThe variable "smaller"isa local variable.  Itis declared to bea number,that way Vim can warn you for any mistakes.  Variables used insidea functionare local unless prefixed by something like "g:", "w:", or "b:".Note:To accessa global variable from insidea function youmust prepend"g:" to it.  Thus "g:today" insidea functionis used for the globalvariable "today", and "today"is another variable, local to thefunction or the script.You now use thereturn statement to return the smallest number to the user.Finally, youend the function:  return smallerenddefThe complete function definitionisas follows:def Min(num1: number, num2: number): number  var smaller: number  if num1 < num2    smaller = num1  else    smaller = num2  endif  return smallerenddefObviously thisisaverbose example.  You can makeit shorter by using tworeturn commands:def Min(num1: number, num2: number): number  if num1 < num2    return num1  endif  return num2enddefAnd if you remember the conditional expression, you need only one line:def Min(num1: number, num2: number): number  return num1 < num2 ? num1 : num2enddefA user defined functionis called in exactly the same wayasa built-infunction.  Only the nameis different.  The Min function can be used likethis:echo Min(5, 8)Only now will the function be executed and the lines be parsed by Vim.If there are mistakes, like using an undefined variable or function, you willnow get an error message.  When defining the function theseerrors are notdetected.  To get theerrors sooner you can tell Vim to compile all thefunctions in the script:defcompileCompilingfunctions takesa little time, but does reporterrors early.  Youcould use:defcompileat theend of yourscript while working on it, andcommentit out when everythingis fine.Fora function that does not return anything simply leave out the return type:def SayIt(text: string)  echo textenddefIf you want to return any kind of value, you can use the "any" return type:def GetValue(): anyThis disables type checking for the return value, use only when needed.Itis also possible to definea legacy function withfunction andendfunction.  Thesedo not have types and are not compiled.  Therefore theyexecute much slower.USING A RANGEA line range can be used witha function call.  The function will be calledonce for every line in the range, with the cursor in that line.  Example:def Number()  echo "line " .. line(".") .. " contains: " .. getline(".")enddefIf you call this function with::10,15Number()The function will be called six times,starting on line 10 and ending on line15.LISTING FUNCTIONSThefunction command lists the names and arguments of all user-definedfunctions::functiondef <SNR>86_Show(start: string, ...items: list<string>)function GetVimIndent()function SetSyn(name)The "<SNR>" prefix means thata functionis script-local.Vim9functionswill start with "def" and include argument and return types.  Legacyfunctionsare listed with "function".To see whata function does, use its nameas an argument forfunction::function SetSyn1     if &syntax == ''2       let &syntax = a:name3     endif   endfunctionTo see the "Show" function you need to include thescript prefix, sincemultiple "Show"functions can be defined in different scripts.  To findthe exact name you can usefunction, but the result may bea very long list.To only get thefunctions matchingapattern you can use thefilter prefix::filter Show functiondef <SNR>86_Show(start: string, ...items: list<string>):function <SNR>86_Show1    echohl Title2    echo "start is " .. startetc.DEBUGGINGThe line numberis useful for when you get an error message or when debugging.Seedebug-scripts about debugging mode.You can also set the'verbose' option to 12 or higher to see all functioncalls.  Setit to 15 or higher to see every executed line.DELETING A FUNCTIONTo delete the SetSyn() function::delfunction SetSynDeleting only works for globalfunctions andfunctions in legacy script, notforfunctions defined inaVim9 script.You get an error when the function doesn't exist or cannot be deleted.FUNCTION REFERENCESSometimesit can be useful to havea variable point to one function oranother.  You candoit witha functionreference variable.  Often shortenedto "funcref".  Example:def Right(): string  return 'Right!'enddefdef Wrong(): string  return 'Wrong!'enddefvar Afunc = g:result == 1 ? Right : Wrongecho Afunc()Wrong!This assumes "g:result"is not one.  SeeFuncref for details.Note that the name ofa variable that holdsa functionreferencemust startwitha capital.  Otherwiseit could be confused with the name ofa builtinfunction.FURTHER READINGUsinga variable number of argumentsis introduced insection50.2.More information about defining your ownfunctions here:user-functions.==============================================================================41.8Lists andDictionariesSo far we have used the basic typesString and Number.  Vim also supportsthree composite types: List,Tuple and Dictionary.AListis an ordered sequence of items.  The items can be any kind of value,thus you can makeaList of numbers,aList ofLists and evenaList of mixeditems.  To createaList with three strings:var alist = ['aap', 'noot', 'mies']TheList items are enclosed in square brackets and separated by commas.  Tocreate an empty List:var alist = []You can add items toaList with theadd() function:var alist = []add(alist, 'foo')add(alist, 'bar')echo alist['foo', 'bar']List concatenationis done with +:var alist = ['foo', 'bar']alist = alist + ['and', 'more']echo alist['foo', 'bar', 'and', 'more']Or, if you want to extendaList witha function, useextend():var alist = ['one']extend(alist, ['two', 'three'])echo alist['one', 'two', 'three']Notice that usingadd() will havea different effect thanextend():var alist = ['one']add(alist, ['two', 'three'])echo alist['one', ['two', 'three']]The second argument ofadd()is addedas an item, now you havea nested list.FOR LOOPOne of the nice things you cando withaListis iterate over it:var alist = ['one', 'two', 'three']for n in alist  echo nendforonetwothreeThis will loop over each element inList "alist", assigning each value tovariable "n".  The generic form ofa for loop is:for {varname} in {list-expression}  {commands}endforTo loopa certain number of times you needaList ofa specific length.  Therange() function creates one for you:for a in range(3)  echo aendfor012Notice that the first item of theList thatrange() producesis zero, thus thelast itemis oneless than the length of the list.  Detail: Internallyrange()does not actually create the list, so thata large range used ina for loopworks efficiently.  When used elsewhere, the rangeis turned into an actuallist, which takes more time fora long list.You can also specify the maximum value, the stride and evengo backwards:for a in range(8, 4, -2)  echo aendfor864A more useful example, looping over all the lines in the buffer:for line in getline(1, 50)  if line =~ "Date: "    echo line  endifendforThis looks into lines 1 to 50 (inclusive) and echoes any date found in there.For further reading seeLists.TUPLEATupleis an immutable ordered sequence of items.  An item can be of anytype.  Items can be accessed by theirindex number.  To createaTuple withthree strings:var atuple = ('one', 'two', 'three')TheTuple items are enclosed in parenthesis and separated by commas.  Tocreate an empty Tuple:var atuple = ()The:for loop can be used to iterate over the items inaTuple similar toaList.For further reading seeTuples.DICTIONARIESADictionary stores key-value pairs.  You can quickly lookupa value if youknow the key.ADictionaryis created with curly braces:var uk2nl = {one: 'een', two: 'twee', three: 'drie'}Now you can lookup words by putting the key in square brackets:echo uk2nl['two']tweeIf the key does not have special characters, you can use the dot notation:echo uk2nl.twotweeThe generic form for definingaDictionary is:{<key> : <value>, ...}An emptyDictionaryis one without any keys:{}The possibilities withDictionaries are numerous.  There arevariousfunctionsfor themas well.  For example, you can obtainalist of the keys and loopover them:for key in keys(uk2nl)  echo keyendforthreeonetwoYou will notice the keys are not ordered.  You can sort thelist to getaspecific order:for key in sort(keys(uk2nl))  echo keyendforonethreetwoBut you can never get back the order in which items are defined.  For that youneed to usea List,it stores items in an ordered sequence.For further reading seeDictionaries.==============================================================================41.9  WhitespaceBlank lines are allowed inascript and ignored.Leadingwhitespace characters (blanks and TABs) are ignored, except when using:let-heredoc without "trim".Trailingwhitespaceis often ignored, but not always.  One command thatincludesitismap.  You have to watch out for that,it can cause hard tounderstand mistakes.A generic solutionis to never use trailing white space,unless you really need it.To includeawhitespace character in the value of an option,itmust beescaped bya "\" (backslash)as in the following example::set tags=my\ nice\ fileIfit would be written as::set tags=my nice fileThis will issue an error, becauseitis interpreted as::set tags=my:set nice:set fileVim9scriptis very picky whenit comes to white space.  This was doneintentionally to make sure scripts areeasy to read and to avoid mistakes.If you use whitespace sensiblyit will just work.  When not you will get anerror message telling you where whitespaceis missing or should be removed.==============================================================================41.10  Line continuationIn legacy Vimscript line continuationis done by precedinga continuationline witha backslash:let mylist = [\ 'one',\ 'two',\ ]This requires the'cpo' option to exclude the "C" flag.  Normally thisis doneby putting thisat the start of the script:let s:save_cpo = &cposet cpo&vimAnd restore the optionat theend of the script:let &cpo = s:save_cpounlet s:save_cpoA few more details can be found here:line-continuation.InVim9script thebackslash can still be used, but in most placesitis notneeded:var mylist = ['one','two',]Also, the'cpo' option does not need to be changed.  Seevim9-line-continuation for details.==============================================================================41.11  CommentsInVim9script the character# startsa comment.  That character andeverything afterit until the end-of-lineis considereda comment andis ignored, except for commands that don't consider comments,as shown inexamples below.A comment can start on any character position on the line,but not whenitis part of the command, e.g. insidea string.The character " (the doublequote mark) startsa comment in legacy script.This involves some cleverness to make sure double quoted strings are notrecognizedas comments (just one reason to preferVim9 script).Thereisa little "catch" with comments for some commands.  Examples:abbrev dev development# shorthandmap <F3> o#include# insert includeexecute cmd# do it!ls *.c# list C files- The abbreviation'dev' will be expanded to 'development# shorthand'.- Themapping of<F3> will actually be the whole line after the 'o# ....'  including the '#insert include'.- Theexecute command will give an error.- The! command will send everything afterit to the shell, most likely  causing an error.There can be no comment aftermap,abbreviate,execute and! commands(there area few more commands with this restriction).  For themap,abbreviate andexecute commands thereisa trick:abbrev dev development|# shorthandmap <F3> o#include|# insert includeexecute '!ls *.c'|# do itWith the'|' character the commandis separated from the next one.  And thatnext commandis onlya comment.  The last command, usingexecuteisageneral solution,it works for all commands thatdo not accepta comment ora'|' to separate the next command.Notice that thereis no whitespace before the'|' in the abbreviation andmapping.  For these commands, any character until the end-of-line or'|'isincluded.  Asa consequence of this behavior, you don't always see thattrailingwhitespaceis included:map <F4> o#includeHereitis intended, in other casesit might be accidental.  To spot theseproblems, you can highlight trailing spaces:match Search /\s\+$/ForUnix thereis one special way to commenta line, that allows makinga Vimscript executable, andit also works in legacy script:#!/usr/bin/env vim -Secho "this is a Vim script"quit==============================================================================41.12  FileformatThe end-of-line character depends on the system.  For Vim scriptsitisrecommended to always use theUnix fileformat.  Lines are then separated withthe Newline character.  This also works on any other system.  That way you cancopy your Vim scripts fromMS-Windows toUnix and they still work.  See:source_crnl.  To be sureitis set right,do this beforewriting the file::setlocal fileformat=unixWhen using "dos" fileformat, lines are separated with CR-NL, two characters.The CR character causesvarious problems, better avoid this.==============================================================================Advance information aboutwriting Vimscriptis inusr_50.txt.Next chapter:usr_42.txt  Add newmenusCopyright: seemanual-copyright  vim:tw=78:ts=8:noet:ft=help:norl:

Quick links:help overview ·quick reference ·user manual toc ·reference manual toc·faq


[8]ページ先頭

©2009-2025 Movatter.jp