cmdline.txt ForVim version 9.1. Last change: 2025 Jun 28VIM REFERENCE MANUAL by Bram MoolenaarCmdline-modeCommand-line-modeCommand-line modeCmdlineCommand-linemode-cmdline:Command-line modeis used to enterEx commands(":"), search patterns("/" and "?"), andfilter commands("!").Basic command line editingis explained in chapter 20 of the user manualusr_20.txt.1.Command-line editingcmdline-editing2.Command-line completioncmdline-completion3.Ex command-linescmdline-lines4.Ex command-line rangescmdline-ranges5.Ex command-line flagsex-flags6.Ex special characterscmdline-special7.Command-linewindowcmdline-window==============================================================================1.Command-line editingcmdline-editingNormally characters are inserted in front of the cursor position. You canmove around in the command-line with the left and right cursor keys. With the<Insert> key, you cantoggle betweeninserting and overstriking characters.Note that if your keyboard does not have working cursor keys or any of theother special keys, you can use ":cnoremap" to define another key for them.For example, to define tcsh style editing keys:tcsh-style:cnoremap <C-A> <Home>:cnoremap <C-F> <Right>:cnoremap <C-B> <Left>:cnoremap <Esc>b <S-Left>:cnoremap <Esc>f <S-Right>(<>notation<>; type all this literally)cmdline-too-longWhen the command lineis getting longer than what fits on the screen, only thepart that fits will be shown. The cursor can only move in this visible part,thus you cannot edit beyond that.cmdline-historyhistoryThe command-lines that you enter are remembered inahistory table. You canrecall them with the up and down cursor keys. There are actually fivehistory tables:- one for ':' commands- one for search strings- one for expressions- one for input lines, typed for theinput() function.- one for debug mode commandsThese are completely separate. Eachhistory can only be accessed whenentering the same type of line.Use the'history' option to set the number of lines that are remembered(default: 50).Notes:- When you entera command-line thatis exactly the sameas an older one, the old oneis removed (to avoid repeated commands moving older commands out of the history).- Only commands that are typed are remembered. Ones that completely come from mappings are notput in the history.- All searches areput in the search history, including the ones that come from commands like "*" and "#". But fora mapping, only the last searchis remembered (to avoid that long mappings trash the history).{not available when compiled without the |+cmdline_hist| feature}Thereis an automatic completion of names on the command-line; seecmdline-completion.c_CTRL-VCTRL-VInsert next non-digit literally. Up to three digits form thedecimal value ofa single byte. The non-digit and the threedigits are not considered for mapping. This works the samewayas inInsert mode (see above,i_CTRL-V).Note: UnderMS-WindowsCTRL-Vis often mapped to paste text.UseCTRL-Q instead then.WhenmodifyOtherKeysis enabled then special Escape sequenceis converted back to whatit was withoutmodifyOtherKeys,unless the Shift keyis also pressed.c_CTRL-QCTRL-QSameasCTRL-V. But with some terminalsitis used forcontrol flow,it doesn't work then.CTRL-SHIFT-Vc_CTRL-SHIFT-Vc_CTRL-SHIFT-QCTRL-SHIFT-QWorks just likeCTRL-V, unlessmodifyOtherKeysis active,thenit inserts the Escape sequence fora key with modifiers.In theGUI thekey-notationis inserted without simplifying.Note: WhenCTRL-SHIFT-Vis intercepted by your system (e.g.,to paste text) you can often useCTRL-SHIFT-Q instead.However, in some terminals (e.g.GNOME Terminal),CTRL-SHIFT-Qquits theterminal without confirmation.c_<Left>c_Left<Left>cursor left. See'wildmenu' for behavior during wildmenucompletion mode.c_<Right>c_Right<Right>cursor right. See'wildmenu' for behavior during wildmenucompletion mode.c_<S-Left><S-Left> or<C-Left>c_<C-Left>cursor oneWORD leftc_<S-Right><S-Right> or<C-Right>c_<C-Right>cursor oneWORD rightCTRL-B or<Home>c_CTRL-Bc_<Home>c_Homecursor to beginning of command-lineCTRL-E or<End>c_CTRL-Ec_<End>c_Endcursor toend of command-line. See'wildmenu' for behaviorduring wildmenu completion mode.c_<LeftMouse><LeftMouse>Move the cursor to the position of the mouse click.c_<MiddleMouse><MiddleMouse>Paste the contents of theclipboard (forX11 the primaryselection). Thisis similar to usingCTRL-R *, but no CRcharacters are inserted between lines.CTRL-Hc_<BS>c_CTRL-Hc_BS<BS>Delete the character in front of the cursor (see:fixdel ifyour<BS> key does notdo what you want).c_<Del>c_Del<Del>Delete the character under the cursor (atend of line:character before the cursor) (see:fixdel if your<Del>key does notdo what you want).c_CTRL-WCTRL-WDelete theword before the cursor. This depends on the'iskeyword' option.c_CTRL-UCTRL-URemove all characters between the cursor position andthe beginning of the line. Previous versions of vimdeleted all characters on the line. If thatis thepreferred behavior, add the following to your .vimrc::cnoremap <C-U> <C-E><C-U>c_<Insert>c_Insert<Insert>Toggle betweeninsert and overstrike.{char1}<BS>{char2}orc_digraphCTRL-K{char1}{char2}c_CTRL-Kenterdigraph (seedigraphs). When{char1}isa specialkey, the code for that keyis inserted in<> form.CTRL-R{register}c_CTRL-Rc_<C-R>Insert the contents ofa numbered or named register. BetweentypingCTRL-R and the second character'"' will be displayedto indicate that you are expected to enter the name ofaregister.The textis insertedas if you typed it, but mappings andabbreviations are not used.Command-line completion through'wildchar'is not triggered though. And characters thatendthe command line are inserted literally (<Esc>,<CR>,<NL>,<C-C>).A<BS> orCTRL-W could stillend the command linethough, and remaining characters will then be interpreted inanother mode, which might not be what you intended.Special registers:'"'the unnamed register, containing the text ofthe last delete oryank'%'the current file name'#'the alternate file name'*'theclipboard contents (X11: primary selection)'+'theclipboard contents'/'the last searchpattern':'the last command-line'-'the last small (less thana line) delete'.'the last inserted textc_CTRL-R_='='theexpression register: you are prompted toenter anexpression (seeexpression)(doesn't workat theexpression prompt; somethings suchaschanging the buffer or currentwindow are not allowed to avoid side effects)When the resultisaList the items are usedas lines. They can have line breaks insidetoo.When the resultisaFloat it's automaticallyconverted toa String.Note that when you only want to move thecursor and notinsert anything, youmust makesure theexpression evaluates to an emptystring. E.g.:<C-R><C-R>=setcmdpos(2)[-1]<CR>Seeregisters about registers.Implementation detail: When using theexpressionregisterand invoking setcmdpos(), this sets the position beforeinserting the resulting string. UseCTRL-RCTRL-R to set theposition afterwards.CTRL-RCTRL-Fc_CTRL-R_CTRL-Fc_<C-R>_<C-F>CTRL-RCTRL-Pc_CTRL-R_CTRL-Pc_<C-R>_<C-P>CTRL-RCTRL-Wc_CTRL-R_CTRL-Wc_<C-R>_<C-W>CTRL-RCTRL-Ac_CTRL-R_CTRL-Ac_<C-R>_<C-A>CTRL-RCTRL-Lc_CTRL-R_CTRL-Lc_<C-R>_<C-L>Insert theobject under the cursor:CTRL-Fthe Filename under the cursorCTRL-Pthe Filename under the cursor, expanded with'path'as ingfCTRL-Wthe Word under the cursorCTRL-AtheWORD under the cursor; seeWORDCTRL-Lthe line under the cursorWhen'incsearch'is set the cursor positionat theend of thecurrently displayed matchis used. WithCTRL-W the part oftheword that was already typedis not inserted again.c_CTRL-R_CTRL-Rc_<C-R>_<C-R>c_CTRL-R_CTRL-Oc_<C-R>_<C-O>CTRL-RCTRL-R{register CTRL-F CTRL-P CTRL-W CTRL-A CTRL-L}CTRL-RCTRL-O{register CTRL-F CTRL-P CTRL-W CTRL-A CTRL-L}Insertregister orobject under the cursor. Works likec_CTRL-R but inserts the text literally. For example, ifregistera contains "xy^Hz" (where ^Hisa backspace),"CTRL-Ra" willinsert "xz" while "CTRL-RCTRL-Ra" willinsert "xy^Hz".CTRL-\e{expr}c_CTRL-\_eEvaluate{expr} and replace the whole command line with theresult. You will be prompted for the expression, type<Enter>to finish it. It's most useful in mappings though. Seeexpression.Seec_CTRL-R_= forinserting the result of an expression.Usefulfunctions aregetcmdtype(),getcmdline() andgetcmdpos().The cursor positionis unchanged, except when the cursor wasat theend of the line, thenit staysat the end.setcmdpos() can be used to set the cursor position.Thesandboxis used for evaluating theexpression to avoidnasty side effects.Example::cmap <F7> <C-\>eAppendSome()<CR>:func AppendSome() :let cmd = getcmdline() .. " Some()" :" place the cursor on the ) :call setcmdpos(strlen(cmd)) :return cmd:endfuncThis doesn't work recursively, thus not when already editingan expression. Butitis possible to use ina mapping.c_CTRL-YCTRL-YWhen thereisa modeless selection, copy the selection intothe clipboard.modeless-selectionIf thereis no selectionCTRL-Yis insertedasa character.See'wildmenu' for behavior during wildmenu completion mode.CTRL-M orCTRL-Jc_CTRL-Mc_CTRL-Jc_<NL>c_<CR>c_CR<CR> or<NL>start entered commandCTRL-[c_CTRL-[c_<Esc>c_Esc<Esc>When typed and 'x' not present in'cpoptions', quitCommand-line mode without executing. In macros or when 'x'present in'cpoptions', start entered command.Note: If your<Esc> keyis hard to hit on your keyboard, trainyourself to useCTRL-[.c_CTRL-CCTRL-Cquit command-line without executingc_<Up>c_Up<Up>recall older command-line from history, whose beginningmatches the current command-line (see below). See'wildmenu'for behavior during wildmenu completion mode.{not available when compiled without the+cmdline_histfeature}c_<Down>c_Down<Down>recall more recent command-line from history, whose beginningmatches the current command-line (see below). See'wildmenu'for behavior during wildmenu completion mode.{not available when compiled without the+cmdline_histfeature}c_<S-Up>c_<PageUp><S-Up> or<PageUp>recall older command-line fromhistory{not available when compiled without the+cmdline_histfeature}c_<S-Down>c_<PageDown><S-Down> or<PageDown>recall more recent command-line fromhistory{not available when compiled without the+cmdline_histfeature}CTRL-Dcommand-line completion (seecmdline-completion)'wildchar' optioncommand-line completion (seecmdline-completion)CTRL-Ncommand-line completion (seecmdline-completion)CTRL-Pcommand-line completion (seecmdline-completion)CTRL-Acommand-line completion (seecmdline-completion)CTRL-Lcommand-line completion (seecmdline-completion)c_CTRL-_CTRL-_a- switch between Hebrew and English keyboard mode, whichisprivate to the command-line and not related to hkmap.Thisis useful when Hebrew text entryis required in thecommand-line, searches, abbreviations, etc. Applies only ifVimis compiled with the+rightleft feature and the'allowrevins' optionis set.Seerileft.txt.b- switch betweenFarsi and English keyboard mode, whichisprivate to the command-line and not related to fkmap. InFarsi keyboard mode the characters are inserted in reverseinsert manner. Thisis useful whenFarsi text entryisrequired in the command-line, searches, abbreviations, etc.Applies only if Vimis compiled with the+farsi feature.Seefarsi.txt.c_CTRL-^CTRL-^Toggle the use of language:lmap mappings and/or InputMethod.When typingapattern fora search command and'imsearch'isnot -1, VALis the value of'imsearch', otherwise VALis thevalue of'iminsert'.When language mappings are defined:- If VALis 1 (langmap mappings used)it becomes0 (no langmap mappings used).- If VAL was not 1it becomes 1, thus langmap mappings are enabled.When no language mappings are defined:- If VALis 2 (Input Methodis used)it becomes0 (no inputmethod used)- If VAL has another valueit becomes 2, thus the Input Methodis enabled.These language mappings are normally used to type charactersthat are different from what the keyboard produces. The'keymap' option can be used toinstalla whole number of them.When enteringa command line, langmap mappings are switchedoff, since you are expected to typea command. Afterswitchingit on withCTRL-^, the new stateis not used againfor the next command or Search pattern.c_CTRL-]CTRL-]Trigger abbreviation, withoutinsertinga character.For Emacs-style editing on the command-line seeemacs-keys.The<Up> and<Down> keys take the current command-lineasa search string.The beginning of the next/previous command-lines are compared with thisstring. The first line that matchesis the new command-line. When typingthese two keys repeatedly, the samestringis used again. For example, thiscan be used to find the previous substitute command: Type ":s" and then<Up>.The same could be done by typing<S-Up>a number of times until the desiredcommand-lineis shown. (Note: the shifted arrow keysdo not work on allterminals):his:history:his[tory]Print thehistory of last entered commands.{not available when compiled without the+cmdline_histfeature}:his[tory] [{name}] [{first}][, [{last}]]List the contents ofhistory{name} which can be:c[md] or:command-linehistorys[earch] or/ or?searchstringhistorye[xpr] or=expressionregisterhistoryi[nput] or@input linehistoryd[ebug] or>debug commandhistorya[ll]all of the aboveIf the numbers{first} and/or{last} are given, the respectiverange of entries fromahistoryis listed. These numbers canbe specified in the following form::history-indexingA positive number represents the absoluteindex of an entryasitis given in the first column ofa:history listing.This number remains fixed even if other entries are deleted.(seeE1510)A negative number means the relative position of an entry,counted from the newest entry (which hasindex -1) backwards.Examples:List entries 6 to 12 from the search history::history / 6,12List the penultimate entry from all histories::history all -2List the most recent two entries from all histories::history all -2,:keepp[atterns]{command}:keepp:keeppatternsExecute{command}, without adding anything to the searchhistory and, incase of:s or:&, without modifying thelast substitutepattern or substitute string.==============================================================================2.Command-line completioncmdline-completionWhen editing the command-line,a few commands can be used to complete theword before the cursor. Thisis available for:- Command names: At the start of the command-line.-++opt values.- Tags: Only after the ":tag" command.- File names: Only aftera command that acceptsa file name ora setting for an option that can be set toa file name. Thisis called file name completion.- Shell command names: After ":!cmd", ":r !cmd" and ":w !cmd". $PATHis used.- Options: Only after the ":set" command.- Mappings: Only aftera ":map" or similar command.- Variable and function names: Only aftera ":if", ":call" or similar command.The number ofhelp item matchesis limited (currently to 300) to avoida longdelay when there are very many matches.These are the commands that can be used:c_CTRL-DCTRL-DList names that match thepattern in front of the cursor.When showing file names, directories are highlighted (see'highlight' option). Names where'suffixes' matches are movedto the end.The'wildoptions' option can be set to "tagfile" tolist thefile of matching tags.c_CTRL-Ic_wildcharc_<Tab>/_<Tab>'wildchar' optionA matchis done on thepattern in front of the cursor. Thematch (if there are several, the first match)is insertedin place of the pattern. (Note: does not work insideamacro, because<Tab> or<Esc> are mostly usedas'wildchar',and these havea special meaning in some macros.) When typedagain and there were multiple matches, the nextmatchis inserted. After the last match, the firstis usedagain (wrap around).In search context use<CTRL-V><Tab> or "\t" to search foraliteral<Tab> instead of triggering completion.The behavior can be changed with the'wildmode' option.c_<S-Tab><S-Tab>Like'wildchar' or<Tab>, but begin with the last match andthengo to the previous match.<S-Tab> does not work everywhere.c_CTRL-NCTRL-NAfter using'wildchar' which got multiple matches,go to nextmatch. Otherwise recall more recent command-line from history.c_CTRL-PCTRL-PAfter using'wildchar' which got multiple matches,go toprevious match. Otherwise recall older command-line fromhistory.c_CTRL-ACTRL-AAll names that match thepattern in front of the cursor areinserted.c_CTRL-LCTRL-LA matchis done on thepattern in front of the cursor. Ifthereis one match,itis inserted in place of the pattern.If there are multiple matches the longest common partisinserted in place of the pattern. If the resultis shorterthan the pattern, no completionis done./_CTRL-LWhen'incsearch'is set, enteringa searchpattern for "/" or"?" and the current matchis displayed thenCTRL-L will addone character from theend of the current match. If'ignorecase' and'smartcase' are set and the command line hasnouppercase characters, the added characteris converted tolowercase.c_CTRL-G/_CTRL-GCTRL-GWhen'incsearch'is set, enteringa searchpattern for "/" or"?" and the current matchis displayed thenCTRL-G will moveto the next match (does not takesearch-offset into account)UseCTRL-T to move to the previous match. Hint: ona regularkeyboardGis below T.c_CTRL-T/_CTRL-TCTRL-TWhen'incsearch'is set, enteringa searchpattern for "/" or"?" and the current matchis displayed thenCTRL-T will moveto the previous match (does not takesearch-offset intoaccount).UseCTRL-G to move to the next match. Hint: ona regularkeyboardTis above G.The'wildchar' option defaults to<Tab> (CTRL-E when inVi compatible mode; ina previous version<Esc> was used). In thepattern standardwildcards areaccepted when matching file names.Whenrepeating'wildchar' orCTRL-N you cycle through the matches, eventuallyending up back to what was typed. If the first matchis not what you wanted,you can use<S-Tab> orCTRL-P togo straight back to what you typed.The'wildmenu' option can be set to show the matches just above the commandline.The'wildoptions' option provides additional configuration to useapopup menufor'wildmenu', and to use fuzzy matching.The'wildignorecase' option can be set to ignorecase in filenames. Forcompleting other texts (e.g. command names), the'ignorecase' optionis usedinstead (fuzzy matching always ignores case, however).If you like tcsh's autolist completion, you can use this mapping::cnoremap X <C-L><C-D>(WhereXis the command key to use,<C-L>isCTRL-L and<C-D>isCTRL-D)This will find the longest match and thenlist all matching files.If you like tcsh's autolist completion, you can use the'wildmode' option toemulate it. For example, this mimics autolist=ambiguous::set wildmode=longest,listThis will find the longest match with the first'wildchar', thenlist allmatching files with the next.complete-script-local-functionsWhen completing user function names, prepend "s:" to findscript-localfunctions.suffixesFor file name completion you can use the'suffixes' option to seta prioritybetween files with almost the same name. If there are multiple matches,those files with an extension thatis in the'suffixes' option are ignored.The defaultis ".bak,~,.o,.h,.info,.swp,.obj", which means that files endingin ".bak", "~", ".o", ".h", ".info", ".swp" and ".obj" are sometimes ignored.An empty entry, two consecutive commas, matcha file name that does notcontaina ".", thus has no suffix. Thisis useful to ignore "prog" and prefer"prog.c".Examples: pattern:files:match: test*test.c test.h test.otest.c test*test.h test.otest.h and test.o test*test.i test.h test.ctest.i and test.cItis impossible to ignoresuffixes with two dots.If thereis more than one matching file (after ignoring the ones matchingthe'suffixes' option) the first file nameis inserted. You can see thatthereis only one match when you type'wildchar' twice and the completedmatch stays the same. You can get to the other matches by entering'wildchar',CTRL-N orCTRL-P. All files are included, also the ones withextensions matching the'suffixes' option.To completely ignore files with some extension use'wildignore'.To match only files thatendat theend of the typed text appenda "$". Forexample, to match only files thatend in ".c"::e *.c$This will not matcha file ending in ".cpp". Without the "$"it does match.If you would like using<S-Tab> forCTRL-P in an xterm,put this command inyour .cshrc:xmodmap -e "keysym Tab = Tab Find"And this in your .vimrc::cmap <Esc>[1~ <C-P>complete-set-optionWhen setting an option using:set=, the old value of an option can beobtained by hitting'wildchar' just after the '='. For example, typing'wildchar' after ":set dir=" willinsert the current value of'dir'. Thisoverrules file name completion for theoptions that takea file name.When using:set=,:set+=, or:set^=,stringoptions that havepre-defined names orsyntax (e.g.'diffopt','listchars') or arealist ofsingle-character flags (e.g.'shortmess') will also presentalist of possiblevalues for completion when using'wildchar'.When using:set-=, comma-separatedoptions like'diffopt' or'backupdir'will show each item separately. Flaglistoptions like'shortmess' will showboth the entire old value and the individual flags. Otherwise completion willjust fill in with the entire old value.==============================================================================3.Ex command-linescmdline-linesTheEx commands havea few specialties::quote:comment'"'at the start ofa line causes the whole line to be ignored.'"'aftera command causes the rest of the line to be ignored. This can be usedto add comments. Example::set ai"set 'autoindent' optionItis not possible to adda comment toa shell command ":!cmd" or to the":map" command anda few others (mainly commands that expect expressions)that see the'"'as part of their argument::argdo:autocmd:bufdo:cexpr (and the like):cdo (and the like):command:cscope (and the like):debug:display:echo (and the like):elseif:execute:folddoopen:folddoclosed:for:grep (and the like):help (and the like):if:let:make:map (and the like including :abbrev commands):menu (and the like):mkspell:normal:ownsyntax:popup:promptfind (and the like):registers:return:sort:syntax:tabdo:tearoff:vimgrep (and the like):while:windo:bar:\bar'|' can be used to separate commands, so you can give multiple commands in oneline. If you want to use'|' in an argument, precedeit with '\'.These commands see the'|'as their argument, and can therefore not befollowed by another Vim command::argdo:autocmd:bufdo:cdo:cfdo:command:cscope:debug:eval:folddoopen:folddoclosed:function:global:help:helpfind:helpgrep:lcscope:ldo:lfdo:lhelpgrep:make:normal:perl:perldo:promptfind:promptrepl:pyfile:python:registers:read!:scscope:sign:tabdo:tcl:tcldo:tclfile:terminal:vglobal:windo:write! :[range]!a user defined command without the "-bar" argument:command and the followingVim9-script keywords::abstract:class:enum:interfaceNote that thisis confusing (inherited from Vi): With ":g" the'|'is includedin the command, with ":s"itis not.To be able to use another command anyway, use the ":execute" command.Example (append the output of "ls" and jump to the first line)::execute 'r !ls' | '[Thereis one exception: When the 'b' flagis present in'cpoptions', with the":map" and ":abbr" commands and friendsCTRL-V needs to be used instead of'\'. You can also use "<Bar>" instead. See alsomap_bar.Examples::!ls | wcview the output of two commands:r !ls | wcinsert the same output in the text:%g/foo/p|>moves all matching lines one shiftwidth:%s/foo/bar/|>moves one line one shiftwidth:map q 10^V|map "q" to "10|":map q 10\| map \ lmap "q" to "10\" and map "\" to "l"(when 'b' is present in 'cpoptions')You can also use<NL> to separate commands in the same wayas with'|'. Toinserta<NL> useCTRL-VCTRL-J. "^@" will be shown. Using'|'is thepreferred method. But for external commandsa<NL>must be used, becausea'|'is included in the external command. To avoid the special meaning of<NL>itmust be preceded witha backslash. Example::r !date<NL>-joinThis reads the current date into the file and joinsit with the previous line.Note that when the command before the'|' generates an error, the followingcommands will not be executed.Because ofVi compatibility the following strange commands are supported::|print current line (like ":p"):3|print line 3 (like ":3p"):3goto line 3A colonis allowed between the range and the command name. Itis ignored(thisisVi compatible). For example::1,$:s/pat/stringWhen the character '%' or '#'is used wherea file nameis expected, they areexpanded to the current and alternate file name (see the chapter "editingfiles":_%:_#).Embedded spaces in file names are allowed on theAmiga if one file nameisexpectedas argument. Trailing spaces will be ignored, unless escaped withabackslash orCTRL-V.Note that the ":next" command uses spaces to separatefile names. Escape the spaces to include them ina file name. Example::next foo\ bar goes\ to school\starts editing the three files "foobar", "goes to" and "school ".When you want to use the special characters'"' or'|' ina command, or wantto use '%' or '#' ina file name, precede them witha backslash. Thebackslashis not required ina range and in the ":substitute" command.See also`=.:_!The '!' (bang) character after anEx command makes the command behave inadifferent way. The '!' should be placed immediately after the command, withoutany blanks in between. If youinsert blanks the '!' will be seenas anargument for the command, which hasa different meaning. For example::w! namewrite the current buffer to file "name", overwritingany existing file:w !namesend the current bufferas standard input to command"name"==============================================================================4.Ex command-line rangescmdline-ranges[range]E16SomeEx commands accepta line range in front of them. Thisis notedas[range]. It consists of one or more line specifiers, separated with ',' or';'.The basics are explained insection10.3 of the user manual.InVim9scripta range needs to be prefixed witha colon to avoid ambiguitywith continuation lines. For example, "+" can be used fora range butis alsoa continuation of an expression:var result = start+ printIf the "+"isa range thenitmust be prefixed witha colon:var result = start:+ print:,:;When separated with ';' the cursor position will be set to that linebefore interpreting the next line specifier. This doesn't happen for ','.Examples: 4,/this line/from line 4 till match with "this line" after the cursor line. 5;/that line/from line 5 till match with "that line" after line 5.The default line specifier for most commandsis the cursor position, but thecommands ":write" and ":global" have the whole file (1,$)as default.If more line specifiers are given than required for the command, the firstone(s) will be ignored.Line numbers may be specified with::range{address}{number}an absolute line numberE1247.the current line:.$the last line in the file:$%equal to 1,$ (the entire file):%'tposition ofmarkt (lowercase):''Tposition ofmarkT (uppercase); when themarkis inanother fileit cannot be used ina range/{pattern}[/]the next line where{pattern} matches:/also see:range-pattern below?{pattern}[?]the previous line where{pattern} matches:?also see:range-pattern below\/the next line where the previously used searchpattern matches\?the previous line where the previously used searchpattern matches\&the next line where the previously used substitutepattern matches:range-offsetEach may be followed (several times) by '+' or '-' and an optional number.This numberis added or subtracted from the preceding line number. If thenumberis omitted, 1is used. If thereis nothing before the '+' or '-' thenthe current lineis used.:range-closed-foldWhena line number after the commais ina closed folditis adjusted to thelast line of the fold, thus the whole foldis included.Whena numberis added thisis done after the adjustment to the last line ofthe fold. This means these lines are additionally included in the range. Forexample: :3,4+2printOn this text:1 one2 two3 three4 four FOLDED5 five FOLDED6 six7 seven8 eightWhere lines four and five area closed fold, ends upprinting lines 3 to 7.The 7 comes from the "4" in the range, whichis adjusted to theend of theclosed fold, whichis 5, and then the offset 2is added.An example for subtracting (which isn't very useful): :2,4-1printOn this text:1 one2 two3 three FOLDED4 four FOLDED5 five FOLDED6 six FOLDED7 seven8 eightWhere lines three to six area closed fold, ends upprinting lines 2 to 6.The 6 comes from the "4" in the range, whichis adjusted to theend of theclosed fold, whichis 6, and then 1is subtracted, then thisis still in theclosed fold and the last line of that foldis used, whichis 6.:range-patternThe "/" and "?" after{pattern} are required to separate thepattern fromanything that follows.The "/" and "?" may be preceded with another address. The search starts fromthere. The difference from using ';'is that the cursor isn't moved.Examples:/pat1//pat2/Find line containing "pat2" after line containing"pat1", without moving the cursor.7;/pat2/Find line containing "pat2", after line 7, leavingthe cursor in line 7.The{number}must be between0 and the number of lines in the file. Whenusinga0 (zero) thisis interpretedasa 1 by most commands. Commands thatuseitasacountdo useitasa zero(:tag,:pop, etc). Some commandsinterpret the zeroas "before the first line"(:read, search pattern, etc).Examples:.+3three lines below the cursor/that/+1the line below the next line containing "that".,$from current line until end of file0;/thatthe first line containing "that", also matches in thefirst line.1;/thatthe first line after line 1 containing "that"Some commands allow foracount after the command. Thiscountis usedas thenumber of lines to be used,starting with the line given in the last linespecifier (the defaultis the cursor line). The commands that acceptacountare the ones that usea range butdo not havea file name argument (becausea file name can also bea number). Thecount cannot be negative.Examples::s/x/X/g 5substitute 'x' by 'X' in the current line and fourfollowing lines:23d 4delete lines 23, 24, 25 and 26Folds and RangeWhenfolds are active the line numbers are rounded off to include the wholeclosed fold. Seefold-behavior.Reverse RangeE493A range should have the lower line number first. If thisis not the case, Vimwill ask you ifit should swap the line numbers.Backwards range given, OK to swapThisis not done within the global command ":g".You can use ":silent" beforea command to avoid the question, the range willalways be swapped then.Count and RangeN:When givingacount before entering ":", thisis translated into::.,.+(count - 1)In words: The "count" linesat and after the cursor. Example: To deletethree lines:3:d<CR>is translated into: .,.+2d<CR>Visual Mode and Rangev_:{Visual}:Startsa command-line with theVisual selected linesasarange. The code:'<,'>is used for this range, which makesit possible to selecta similar line from the command-linehistory forrepeatinga command on different Visually selectedlines.:*:star:star-visual-rangeWhenVisual mode was already ended,a short way to use theVisual area fora rangeis:*. This requires that "*" doesnot appear in'cpo', seecpo-star. Otherwise you will haveto type:'<,'>For when "*"is in'cpo' see:star-compatible.==============================================================================5.Ex command-line flagsex-flagsThese flags are supported bya selection ofEx commands. They print the linethat the cursor ends up after executing the command:loutput like for:list#add line numberpoutput like for:printThe flags can be combined, thus "l#" uses botha line number and:list styleoutput.==============================================================================6.Ex special characterscmdline-specialNote: These are special characters in the executed command line. If you wanttoinsert special things while typing you can use theCTRL-R command. Forexample, "%" stands for the current file name, whileCTRL-R% inserts thecurrent file name right away. Seec_CTRL-R.Note: If you want to avoid the effects of special characters ina Vimscriptyou may want to usefnameescape(). Also see`=.InEx commands,at places wherea file name can be used, the followingcharacters havea special meaning. These can also be used in theexpressionfunctionexpand().%Is replaced with the current file name.:_%c_%#Is replaced with the alternate file name.:_#c_#Thisis remembered for every window.#n(wherenisa number)is replaced with:_#0:_#nthe file name of buffer n. "#0"is the sameas "#".c_#n##Is replaced with all names in the argumentlist:_##c_##concatenated, separated by spaces. Eachspace ina nameis preceded witha backslash.#<n(wherenisa number> 0)is replaced with old:_#<c_#<file name n. See:oldfiles orv:oldfiles to get thenumber.E809{only when compiled with the |+eval| and |+viminfo| features}InVim9-script#is used to starta comment, use %% for the alternate filename:%Is replaced with the current file name.%%Is replaced with the alternate file name.:_%%c_%%%%n(wherenisa number)is replaced with:_%%0:_%%nthe file name of buffer n. "%%0"is the sameas "%%".c_%%n%%%Is replaced with all names in the argument:_%%%c_%%%#list concatenated, separated by spaces.%%<n(wherenisa number> 0)is replaced with old:_%%<c_%%<file name n.Note that these, except "#<n", give the file nameasit was typed. If anabsolute pathis needed (when using the file name froma different directory),you need to add ":p". Seefilename-modifiers.The "#<n" item returns an absolute path, butit will start with "~/" for filesbelow yourhome directory.Note that backslashes are inserted before spaces, so that the command willcorrectly interpret the file name. But this doesn't happen for shellcommands. For those you probably have to usequotes (this fails for filesthat containaquote and wildcards)::!ls "%":r !spell "%"To avoid the special meaning of '%' and '#'insertabackslash before it.Detail: The special meaningis always escaped when thereisabackslash beforeit, no matter how many backslashes.you type:result#alternate.file \## \\#\#Also see`=.E499E500Note: these are typed literally, they are not special keys!:<cword><cword><cword>is replaced with theword under the cursor (likestar):<cWORD><cWORD><cWORD>is replaced with theWORD under the cursor (seeWORD):<cexpr><cexpr><cexpr>is replaced with theword under the cursor, including more to formaC expression. E.g., when the cursoris on "arg" of "ptr->arg" then the resultis "ptr->arg"; when the cursoris on "]" of "list[idx]" then the resultis "list[idx]". Thisis used forv:beval_text.:<cfile><cfile><cfile>is replaced with the path name under the cursor (like whatgf uses):<afile><afile><afile> When executing autocommands,is replaced with the file name of the buffer being manipulated, or the file fora read or write.E495:<abuf><abuf><abuf> When executing autocommands,is replaced with the currently effective buffer number. Itis not set for all events, also seebufnr(). For ":r file" and ":so file"itis the current buffer, the file being read/sourcedis not ina buffer.E496:<amatch><amatch><amatch> When executing autocommands,is replaced with the match for which thisautocommand was executed.E497 It differs from<afile> when the file name isn't used to match with (for FileType,Syntax andSpellFileMissing events). When the matchis witha file name,itis expanded to the full path.:<sfile><sfile><sfile> When executinga:source command,is replaced with the file name of the sourced file.E498 When executinga legacy function,is replaced with the call stack,as with<stack> (thisis for backwards compatibility, using<stack> or<script>is preferred). InVim9script using<sfile> ina function gives errorE1245.Note thatfilename-modifiers are useless when<sfile>is not used insidea script.:<stack><stack><stack>is replaced with the call stack, using "function{function-name}[{lnum}]" fora function line and "script{file-name}[{lnum}]" forascript line, and ".." in between items. E.g.: "function{function-name1}[{lnum}]..{function-name2}[{lnum}]" If thereis no call stack you get errorE489.:<script><script><script> When executinga:source command,is replaced with the file name of the sourced file. When executinga function,is replaced with the file name of thescript whereitis defined. If the file name cannot be determined you get errorE1274.:<slnum><slnum><slnum> When executinga:source command,is replaced with the line number.E842 When executinga function it's the line number relative to the start of the function.:<sflnum><sflnum><sflnum> When executinga script,is replaced with the line number. It differs from<slnum> in that<sflnum>is replaced with thescript line number in any situation.E961:<client><client><client>is replaced with the{clinetid} of the last received message inserver2client()filename-modifiers:_%:::8::p::.::~::h::t::r::e::s::gs::S%:8%:p%:.%:~%:h%:t%:r%:e%:s%:gs%:SThe file name modifiers can be used after "%", "#", "#n", "<cfile>", "<sfile>","<afile>" or "<abuf>". They are also used with thefnamemodify() function.These modifiers can be given, in this order::pMake file namea full path. Must be the first modifier. Alsochanges "~/" (and "~user/" forUnix and VMS) to the path forthehome directory. If the nameisa directorya pathseparatoris addedat the end. Fora file name that does notexist and does not have an absolute path the resultisunpredictable. OnMS-Windows an 8.3 filenameis expanded tothe long name.:8Converts the path to 8.3 short format (currently only onMS-Windows). Will act onas much ofa path thatis anexisting path.:~Reduce file name to be relative to thehome directory, ifpossible. File nameis unmodified ifitis not below thehomedirectory.:.Reduce file name to be relative to current directory, ifpossible. File nameis unmodified ifitis not below thecurrent directory.For maximum shortness, use ":~:.".:hHead of the file name (the last component and any separatorsremoved). Cannot be used with :e,:r or :t.Can be repeated to remove several componentsat the end.When the file name ends ina path separator, only the pathseparatoris removed. Thus ":p:h" ona directory name resultson the directory name itself (without trailing slash).When the file nameis an absolute path (starts with "/" forUnix; "x:\" for Win32; "drive:" for Amiga), that partis notremoved. When thereis no head (pathis relative to currentdirectory) the resultis empty.:tTail of the file name (last component of the name). Mustprecede any:r or :e.:rRoot of the file name (the last extension removed). Whenthereis only an extension (file name that starts with '.',e.g., ".vimrc"),itis not removed. Can be repeated to removeseveral extensions (last one first).:eExtension of the file name. Only makes sense when used alone.When thereis no extension the resultis empty.When thereis only an extension (file name that starts with'.'), the resultis empty. Can be repeated to include moreextensions. If there are not enough extensions (butat leastone)as muchas possible are included.:s?pat?sub?Substitute the first occurrence of "pat" with "sub". Thisworks like the:s command. "pat"isa regular expression.Any character can be used for '?', butitmust not occur in"pat" or "sub".After this, the previous modifiers can be used again. Forexample ":p", to makea full path after the substitution.:gs?pat?sub?Substitute all occurrences of "pat" with "sub". Otherwisethis works like ":s".:SEscape special characters for use witha shell command (seeshellescape()). Must be the last one. Examples: :!dir <cfile>:S :call system('chmod +w -- ' . expand('%:S'))Examples, when the file nameis "src/version.c", current dir"/home/mool/vim": :p/home/mool/vim/src/version.c :p:. src/version.c :p:~ ~/vim/src/version.c :h src :p:h/home/mool/vim/src :p:h:h/home/mool/vim :t version.c :p:t version.c :r src/version :p:r/home/mool/vim/src/version :t:r version :e c :s?version?main? src/main.c :s?version?main?:p/home/mool/vim/src/main.c :p:gs?/?\\?\home\mool\vim\src\version.cExamples, when the file nameis "src/version.c.gz": :p/home/mool/vim/src/version.c.gz :e gz :e:e c.gz :e:e:e c.gz :e:e:r c :r src/version.c :r:e c :r:r src/version :r:r:r src/versionextension-removal:_%<Ifa "<"is appended to "%", "#", "#n" or "CTRL-Vp" the extension of the filenameis removed (everything after and including the last '.' in the filename). Thisis included for backwards compatibility with version 3.0, the":r" formis preferred. Examples:%current file name%<current file name without extension#alternate file name for current window#<idem, without extension#31alternate file number 31#31<idem, without extension<cword>word under the cursor<cWORD>WORD under the cursor (see |WORD|)<cfile>path name under the cursor<cfile><idem, without extensionNote: Wherea file nameis expectedwildcards expansionis done. OnUnix theshellis used for this, unlessit can be done internally (for speed).Unless inrestricted-mode, backticks work also, like in:n `echo *.c`But expansionis only done if there are anywildcards before expanding the'%', '#', etc.. This avoids expandingwildcards insidea file name. If youwant to expand the result of<cfile>, addawildcard character to it.Examples: (alternate file nameis "?readme?")commandexpands to:e#:e ?readme?:e `ls #`:e{files matching "?readme?"}:e #.*:e{files matching "?readme?.*"}:cd<cfile>:cd{file name under cursor}:cd<cfile>*:cd{file name under cursor plus "*" and then expanded}Also see`=.When the expanded argument containsa "!" anditis used fora shell command(":!cmd", ":r !cmd" or ":w !cmd"), the "!"is escaped withabackslash toavoidit being expanded intoa previously used command. When the'shell'option contains "sh", thisis done twice, to avoid the shell trying to expandthe "!".filename-backslashFor filesystems that useabackslashas directory separator (MS-Windows), it'sa bit difficult to recognizeabackslash thatis used toescape the specialmeaning of the next character. The general rule is: If thebackslashisfollowed bya normal file name character,it does not havea special meaning.Therefore "\file\foo"isa valid file name, you don't have to type thebackslash twice.An exceptionis the '$' sign. Itisa valid character ina file name. Butto avoida file name like "$home" to be interpretedas an environment variable,it needs to be preceded bya backslash. Therefore you need to use "/\$home"for the file "$home" in the root directory.A few examples:FILE NAMEINTERPRETED AS$homeexpanded to value of environment var $home\$homefile "$home" in current directory/\$homefile "$home" in root directory\\$homefile "\\", followed by expanded $homeAlso see`=.==============================================================================7.Command-linewindowcmdline-windowcmdwincommand-line-windowIn the command-linewindow the command line can be edited just like editingtext in any window. Itisa special kind of window, because you cannot leaveit ina normal way.OPENc_CTRL-Fq:q/q?There are two ways to open the command-line window:1. FromCommand-line mode, use the key specified with the'cedit' option. The defaultisCTRL-F when'compatible'is not set.2. FromNormal mode, use the "q:", "q/" or "q?" command. This starts editing anEx command-line("q:") or searchstring("q/" or "q?").Note that thisis not possible whilerecordingis in progress (the "q" stopsrecording then).When thewindow opensitis filled with the command-line history. The lastline contains the commandas typed so far. The left column will showacharacter that indicates the type of command-line being edited, seecmdwin-char.Vim will be inNormal mode when the editoris opened, except when'insertmode'is set.E1292Oncea command-linewindowis openitis not possible to open another one.The height of thewindowis specified with'cmdwinheight' (or smaller if thereis no room). Thewindowis always full width andis positioned just above thecommand-line.EDITYou can now use commands to move around and edit the text in the window. BothinNormal mode andInsert mode.Itis possible to use ":", "/" and other commands that use the command-line,but it's not possible to open another command-linewindow then. Thereis nonesting.E11E1188The command-linewindowis nota normal window. Itis not possible to move toanotherwindow or edit another buffer. All commands that woulddo this aredisabled in the command-line window. Of courseit _is_ possible to executeany command that you entered in the command-line window. Other text edits arediscarded when closing the window.CLOSEE199There are several ways to leave the command-line window:<CR>Execute the command-line under the cursor. Works both inInsert and inNormal mode.CTRL-CContinue inCommand-line mode. The command-line under thecursoris usedas the command-line. Works both inInsert andinNormal mode. Thereis no redraw, thus thewindow willremain visible.:quitDiscard the command line andgo back toNormal mode.":close",CTRL-W c, ":exit", ":xit" andCTRL-\CTRL-N alsowork.:qallQuit Vim, unless there are changes in some buffer.:qall!Quit Vim, discarding changes to any buffer.Once the command-linewindowis closed the oldwindow sizes are restored. Theexecuted command applies to thewindow and buffer where the command-line wasstarted from. This worksas if the command-linewindow was not there, exceptthat there will be an extra screen redraw.The buffer used for the command-linewindowis deleted. Any changes to linesother than the one thatis executed with<CR> are lost.If you would like to execute the command under the cursor and then have thecommand-linewindow open again, you may find thismapping useful::autocmd CmdwinEnter * map <buffer> <F5> <CR>q:VARIOUSThe command-linewindow cannot be used:- when there alreadyisa command-linewindow (no nesting)- for entering anencryption key or when usinginputsecret()Someoptions are set when the command-linewindowis opened:'filetype'"vim", when editing anEx command-line; this starts Vimsyntaxhighlighting ifit was enabled'rightleft'off'modifiable'on'buftype'"nofile"'swapfile'offItis allowed to write the buffer contents toa file. Thisis aneasy way tosave the command-linehistory and readit back later.If the'wildchar' optionis set to<Tab>, and the command-linewindowis usedfor anEx command, then two mappings will be added to use<Tab> for completionin the command-line window, like this::inoremap <buffer> <Tab> <C-X><C-V>:nnoremap <buffer> <Tab> a<C-X><C-V>Note that hitting<Tab> inNormal mode willdo completion on the nextcharacter. That wayit worksat theend of the line.If you don't want these mappings, disable them with:au CmdwinEnter [:>] iunmap <Tab>au CmdwinEnter [:>] nunmap <Tab>You couldput these lines in yourvimrc file.While in the command-linewindow you cannot use the mouse toput the cursor inanother window, or drag statuslines of other windows. You can drag thestatusline of the command-linewindow itself and the statusline above it.Thus you can resize the command-line window, but not others.Thegetcmdwintype() function returns the type of the command-line beingeditedas described incmdwin-char.AUTOCOMMANDSTwoautocommand events are used:CmdwinEnter andCmdwinLeave. You can usethe Cmdwin events todo settings specifically for the command-line window.Be careful not to cause side effects!Example::au CmdwinEnter : let b:cpt_save = &cpt | set cpt=.:au CmdwinLeave : let &cpt = b:cpt_saveThis sets'complete' to use completion in the currentwindow fori_CTRL-N.Another example::au CmdwinEnter [/?] startinsertThis will make Vim start inInsert mode in the command-line window.cmdwin-charThe character used for thepattern indicates the type of command-line::normalEx command>debug mode commanddebug-mode/forward searchstring?backward searchstring=expression for "=expr-register@string forinput()-text for:insert or:append vim:tw=78:ts=8:noet:ft=help:norl: