pattern.txt ForVim version 9.1. Last change: 2025 Jul 10VIM REFERENCE MANUAL by Bram MoolenaarPatterns and search commandspattern-searchesThe very basics can be found insection03.9 of the user manual.A few moreexplanations are in chapter 27usr_27.txt.1. Search commandssearch-commands2. The definition ofapatternsearch-pattern3. Magic/magic4. Overview ofpattern itemspattern-overview5. Multi itemspattern-multi-items6. Ordinary atomspattern-atoms7. Ignoringcase inapattern/ignorecase8. Composing characterspatterns-composing9. Compare withPerl patternsperl-patterns10. Highlighting matchesmatch-highlight11. Fuzzy matchingfuzzy-matching==============================================================================1. Search commandssearch-commands//{pattern}[/]<CR>Search forward for the[count]'th occurrence of{pattern}exclusive./{pattern}/{offset}<CR>Search forward for the[count]'th occurrence of{pattern} andgo{offset} lines up or down.linewise./<CR>/<CR>Search forward for the[count]'th occurrence of thelatest usedpatternlast-pattern with latest used{offset}.//{offset}<CR>Search forward for the[count]'th occurrence of thelatest usedpatternlast-pattern with new{offset}. If{offset}is empty no offsetis used.??{pattern}[?]<CR>Search backward for the[count]'th previousoccurrence of{pattern}exclusive.?{pattern}?{offset}<CR>Search backward for the[count]'th previousoccurrence of{pattern} andgo{offset} lines up ordownlinewise.?<CR>?<CR>Search backward for the[count]'th occurrence of thelatest usedpatternlast-pattern with latest used{offset}.??{offset}<CR>Search backward for the[count]'th occurrence of thelatest usedpatternlast-pattern with new{offset}. If{offset}is empty no offsetis used.nnRepeat the latest "/" or "?"[count] times.If the cursor doesn't move the searchis repeated withcount+ 1.last-patternNNRepeat the latest "/" or "?"[count] times inopposite direction.last-patternstarE348E349*Search forward for the[count]'th occurrence of theword nearest to the cursor. Theword used for thesearchis the first of:1. the keyword under the cursor'iskeyword'2. the first keyword after the cursor, in the current line3. the non-blankword under the cursor4. the first non-blankword after the cursor, in the current lineOnly whole keywords are searched for, like with thecommand "/\<keyword\>".exclusive'ignorecase'is used,'smartcase'is not.##Sameas "*", but search backward. The pound sign(character 163) also works. If the "#" key worksasbackspace, try using "stty erase<BS>" beforestartingVim (<BS>isCTRL-H ora real backspace).gstarg*Like "*", but don'tput "\<" and "\>" around the word.This makes the search also find matches that are notawhole word.g#g#Like "#", but don'tput "\<" and "\>" around the word.This makes the search also find matches that are notawhole word.gdgdGoto local Declaration. When the cursoris ona localvariable, this command will jump to its declaration.This was made to work forC code, in other languagesit may not work well.First Vim searches for the start of the currentfunction, just like "[[". Ifitis not found thesearch stops in line 1. Ifitis found, Vim goes backuntila blank lineis found. From this position Vimsearches for the keyword under the cursor, like with"*", but lines that look likea comment are ignored(see'comments' option).Note that thisis not guaranteed to work, Vim does notreally check the syntax,it only searches fora matchwith the keyword. If included files also need to besearched use the commands listed ininclude-search.After this commandn searches forward for the nextmatch (not backward).gDgDGoto global Declaration. When the cursoris onaglobal variable thatis defined in the file, thiscommand will jump to its declaration. This works justlike "gd", except that the search for the keywordalways starts in line 1.1gd1gdLike "gd", but ignore matches insidea{} block thatends before the cursor position.1gD1gDLike "gD", but ignore matches insidea{} block thatends before the cursor position.CTRL-CCTRL-CInterrupt current (search) command. UseCTRL-Break onMS-Windowsdos-CTRL-Break.InNormal mode, any pending commandis aborted.When Vim was started with output redirected and thereare no changedbuffersCTRL-C exits Vim. Thatis tohelp users who use "vim file |grepword" and don'tknow how to get out (blindly typing :qa<CR> wouldwork).Ifapopupis open, the activepopup will be closed.:noh:nohlsearch:noh[lsearch]Stop the highlighting for the'hlsearch' option. Itis automatically turned back on when usinga searchcommand, or setting the'hlsearch' option.This command doesn't work in an autocommand, becausethe highlighting stateis saved and restored whenexecutingautocommandsautocmd-searchpat.Same thing for when invokinga user function.While typing the searchpattern the current match will be shown if the'incsearch' optionis on. Remember that you still have to finish the searchcommand with<CR> to actually position the cursorat the displayed match. Oruse<Esc> toabandon the search.nohlsearch-autoAll matches for the last used searchpattern will be highlighted if you setthe'hlsearch' option. This can be suspended with the:nohlsearch commandor auto suspended with nohlsearch plugin. Seenohlsearch-install.When'shortmess' does not include the "S" flag, Vim will automatically show anindex, on which the cursor is. This can look like this: [1/5]Cursor is on first of 5 matches. [1/>99]Cursor is on first of more than 99 matches. [>99/>99]Cursor is after 99 match of more than 99 matches. [?/??]Unknown how many matches exists, generating thestatistics was aborted because of search timeout.Note: thecount does not take offset into account.When no matchis found you get the error:E486Pattern not foundNote that for the:global command, when used in legacy script, you getanormal message "Pattern not found", forVi compatibility.InVim9script you getE486 for "pattern not found" orE538 when thepatternmatches in every line with:vglobal.For the:s command the "e" flag can be used to avoid the error message:s_flags.search-optionsThe followingoptions affect howa searchis performed in Vim:'hlsearch'highlight matches'ignorecase'ignorecase when searching'imsearch'useIME when entering the searchpattern'incsearch'show matches incrementallyas thepatternis typed'maxsearchcount'maximum number for the searchcountshm-S'shortmess'suppressmessagesshm-s; show searchcountshm-S'smartcase'override'ignorecase' ifpattern containsuppercase'wrapscan'continue searching from the start of the filesearch-offset{offset}These commands search for the specified pattern. With "/" and "?" anadditional offset may be given. There are two types of offsets: line offsetsand character offsets.The offset gives the cursor position relative to the found match:[num][num] lines downwards, in column 1 +[num][num] lines downwards, in column 1 -[num][num] lines upwards, in column 1 e[+num][num] characters to the right of theend of the match e[-num][num] characters to the left of theend of the match s[+num][num] characters to the right of the start of the match s[-num][num] characters to the left of the start of the match b[+num][num] identical to s[+num] above (mnemonic: begin) b[-num][num] identical to s[-num] above (mnemonic: begin) ;{pattern} perform another search, see//;Ifa '-' or '+'is given but[num]is omitted,acount of one will be used.When including an offset with 'e', the search becomesinclusive (thecharacter the cursor lands onis included in operations).Examples:patterncursor position/test/+1one line below "test", in column 1/test/eon the lastt of "test"/test/s+2on the 's' of "test"/test/b-3three characters before "test"If one of these commandsis used after an operator, the characters betweenthe cursor position before and after the searchis affected. However, ifaline offsetis given, the whole lines between the two cursor positions areaffected.An example of how to search for matches withapattern and change the matchwith another word:/foo<CR>find "foo"c//e<CR>change until end of matchbar<Esc>type replacement//<CR>go to start of next matchc//e<CR>change until end of matchbeep<Esc>type another replacementetc.//;E386A very special offsetis ';' followed by another search command. For example: /test 1/;/test /test.*/+1;?ing?The first one first finds the next occurrence of "test 1", and then the firstoccurrence of "test" after that.Thisis like executing two search commands after each other, except that:- It can be usedasa single motion command after an operator.- The direction fora following "n" or "N" command comes from the first search command.- When an error occurs the cursoris not movedat all.last-patternThe last usedpattern and offset are remembered. They can be used to repeatthe search, possibly in another direction or with another count.Note thattwo patterns are remembered: One for "normal" search commands and one for thesubstitute command ":s". Each time an emptypatternis given, the previouslyusedpatternis used. However, if thereis no previous search command,aprevious substitutepatternis used, if possible.The'magic' option sticks with the last used pattern. If you change'magic',this will not change how the last usedpattern will be interpreted.The'ignorecase' option does notdo this. When'ignorecase'is changed,itwill result in thepattern to match other text.All matches for the last used searchpattern will be highlighted if you setthe'hlsearch' option.To clear the last used search pattern::let @/ = ""This will not set thepattern to an empty string, because that would matcheverywhere. Thepatternis really cleared, like whenstarting Vim.The search usually skips matches that don't move the cursor. Whether the nextmatchis foundat the next character or after the skipped match depends on the'c' flag in'cpoptions'. Seecpo-c. with 'c' flag: "/..." advances 1 to 3 characterswithout 'c' flag: "/..." advances 1 characterThe unpredictability with the 'c' flagis caused bystarting the search in thefirst column, skipping matches until oneis found past the cursor position.When searching backwards, searching startsat the start of the line, using the'c' flag in'cpoptions'as described above. Then the last match before thecursor positionis used.InVi the ":tag" command sets the last searchpattern when thetagis searchedfor. In Vim thisis not done, the previous searchpatternis still remembered,unless the 't' flagis present in'cpoptions'. The searchpatternis alwaysput in the search history.If the'wrapscan' optionis on (whichis the default), searches wrap aroundtheend of the buffer. If'wrapscan'is not set, the backward search stopsat the beginning and the forward search stopsat theend of the buffer. If'wrapscan'is set and thepattern was not found the error message "patternnot found"is given, and the cursor will not be moved. If'wrapscan'is notset the message becomes "search hit BOTTOM without match" when searchingforward, or "search hit TOP without match" when searching backward. Ifwrapscanis set and the search wraps around theend of the file the message"search hit TOP, continuingat BOTTOM" or "search hit BOTTOM, continuingatTOP"is given when searching backwards or forwards respectively. This can beswitched off by setting the 's' flag in the'shortmess' option. The highlightmethod 'w'is used for this message (default: standout).search-rangeYou can limit the search command "/" toa certain range of lines by including\%>l items. For example, to match theword "limit" below line 199 and aboveline 300:/\%>199l\%<300llimitAlso see/\%>l.Another wayis to use the ":substitute" command with the 'c' flag. Example: :.,300s/Pattern//gcThis command will search from the cursor position until line 300 for"Pattern". At the match, you will be asked to typea character. Type 'q' tostopat this match, type 'n' to find the next match.The "*", "#", "g*" and "g#" commands look foraword near the cursor in thisorder, the first one thatis foundis used:- The keyword currently under the cursor.- The first keyword to the right of the cursor, in the same line.- TheWORD currently under the cursor.- The firstWORD to the right of the cursor, in the same line.The keyword may only contain letters and characters in'iskeyword'.TheWORD may contain any non-blanks (<Tab>s and/or<Space>s).Note that if you type with ten fingers, the characters areeasy to remember:the "#"is under your left hand middle finger (search to the left and up) andthe "*"is under your right hand middle finger (search to the right and down).(this depends on your keyboard layout though).E956In very rare casesa regularexpressionis used recursively. This can happenwhen executingapattern takesa long time and when checking formessages onchannelsa callbackis invoked that also usesapattern or anautocommandistriggered. In most cases this should be fine, but ifapatternis in use whenit's used againit fails. Usually this means thereis something wrong withthe pattern.==============================================================================2. The definition ofapatternsearch-patternpattern[pattern]regular-expressionregexpPatternE383E476For starters, read chapter 27 of the user manualusr_27.txt./bar/\bar/pattern1.Apatternis one or more branches, separated by "\|". It matches anything that matches one of the branches. Example: "foo\|beep" matches "foo" and matches "beep". If more than one branch matches, the first oneis used.pattern ::= branchor branch \| branchor branch \| branch \| branchetc./branch/\&2.A branchis one or more concats, separated by "\&". It matches the last concat, but only if all the preceding concats also matchat the same position. Examples:"foobeep\&..." matches "foo" in "foobeep".".*Peter\&.*Bob" matches ina line containing both "Peter" and "Bob" branch ::= concator concat \& concator concat \& concat \& concatetc./concat3.A concatis one or more pieces, concatenated. It matchesa match for the first piece, followed bya match for the second piece, etc. Example: "f[0-9]b", first matches "f", thena digit and then "b". concat ::= pieceor piece pieceor piece piece pieceetc./piece4.A pieceis an atom, possibly followed bya multi, an indication of how many times the atom can be matched. Example: "a*" matches any sequence of "a" characters: "", "a", "aa", etc. See/multi. piece ::= atomor atom multi/atom5. An atom can be one ofa longlist of items. Many atoms match one character in the text. Itis often an ordinary character ora character class. Parentheses can be used to makeapattern into an atom. The "\z(\)" constructis only forsyntax highlighting. atom ::= ordinary-atom/ordinary-atomor \(pattern \)/\(or \%(pattern \)/\%(or \z(pattern \)/\z(/\%#=two-enginesNFAVim includes tworegexp engines:1. An old, backtracking engine that supports everything.2.A new,NFA engine that works much faster on some patterns, possibly slower on some patterns.E1281Vim will automatically select the right engine for you. However, if you runintoa problem or want to specifically select one engine or the other, you canprepend one of the following to the pattern:\%#=0Force automatic selection. Only has an effect when'regexpengine' has been set toa non-zero value.\%#=1Force using the old engine.\%#=2Force using theNFA engine.You can also use the'regexpengine' option to change the default.E864E868E874E875E876E877E878If selecting theNFA engine andit runs into something thatis not implementedthepattern will not match. Thisis only useful when debugging Vim.==============================================================================3. Magic/magicSome characters in the pattern, suchas letters, are taken literally. Theymatch exactly the same character in the text. When preceded withabackslashhowever, these characters may geta special meaning. For example, "a" matchestheletter "a", while "\a" matches any alphabetic character.Other characters havea special meaning withouta backslash. They need to bepreceded withabackslash to match literally. For example "." matches anycharacter while "\." matchesa dot.Ifa characteris taken literally or not depends on the'magic' option and theitems in thepattern mentioned next. The'magic' option should always be set,butit can be switched off forVi compatibility. We mention the effect of'nomagic' here for completeness, but we recommend against using that./\m/\MUse of "\m" makes thepattern afterit be interpretedas if'magic'is set,ignoring the actual value of the'magic' option.Use of "\M" makes thepattern afterit be interpretedas if'nomagic'is used./\v/\VUse of "\v" means that after it, all ASCII characters except '0'-'9', 'a'-'z','A'-'Z' and '_' have special meaning: "very magic"Use of "\V" means that after it, onlyabackslash and the terminatingcharacter (usually/ or ?) have special meaning: "very nomagic"Examples:after: \v \m \M \Vmatches'magic''nomagic'aaaaliteral 'a' \a \a \a \aany alphabetic character.. \. \.any character \. \...literal dot$$$ \$end-of-line * * \* \*any number of the previous atom~~ \~ \~latest substitutestring () \(\) \(\) \(\)groupas an atom | \| \| \|nothing: separates alternatives \\ \\ \\ \\literalbackslash \{{{{literal curly brace{only Vim supports \m, \M, \v and \V}If you want to you can makeapattern immune to the'magic' option being setor not by putting "\m" or "\M"at the start of the pattern.==============================================================================4. Overview ofpattern itemspattern-overviewE865E866E867E869Overview of multi items./multiE61E62More explanation and examples below, follow the links.E64E871 multi 'magic' 'nomagic'matches of the preceding atom/star *\*0 or moreas manyas possible/\+ \+\+1 or moreas manyas possible/\= \=\=0 or 1as manyas possible/\? \?\?0 or 1as manyas possible/\{ \{n,m}\{n,m}n tomas manyas possible\{n}\{n}nexactly\{n,}\{n,}at leastnas manyas possible\{,m}\{,m}0 tomas manyas possible\{}\{}0 or moreas manyas possible (sameas *)/\{- \{-n,m}\{-n,m}n tomas fewas possible\{-n}\{-n}nexactly\{-n,}\{-n,}at leastnas fewas possible\{-,m}\{-,m}0 tomas fewas possible\{-}\{-}0 or moreas fewas possibleE59/\@> \@>\@>1, like matchinga wholepattern/\@= \@=\@=nothing, requiresa match/zero-width/\@! \@!\@!nothing, requires NO match/zero-width/\@<= \@<=\@<=nothing, requiresa match behind/zero-width/\@<! \@<!\@<!nothing, requires NO match behind/zero-widthOverview of ordinary atoms./ordinary-atomMore explanation and examples below, follow the links. ordinary atom magic nomagicmatches/^^^start-of-line (at start of pattern)/zero-width/\^ \^\^literal '^'/\_^ \_^\_^start-of-line (used anywhere)/zero-width/$$$end-of-line (atend of pattern)/zero-width/\$ \$\$literal '$'/\_$ \_$\_$end-of-line (used anywhere)/zero-width/..\.any single character (not an end-of-line)/\_. \_.\_.any single character or end-of-line/\< \<\<beginning ofaword/zero-width/\> \>\>end ofaword/zero-width/\zs \zs\zsanything, sets start of match/\ze \ze\zeanything, setsend of match/\%^ \%^\%^beginning of file/zero-widthE71/\%$ \%$\%$end of file/zero-width/\%V \%V\%VinsideVisual area/zero-width/\%# \%#\%#cursor position/zero-width/\%'m \%'m\%'mmarkm position/zero-width/\%l \%23l\%23lin line 23/zero-width/\%c \%23c\%23cin column 23/zero-width/\%v \%23v\%23vin virtual column 23/zero-widthCharacter classes:/character-classes magic nomagicmatches/\i \i\iidentifier character (see'isident' option)/\I \I\Ilike "\i", but excluding digits/\k \k\kkeyword character (see'iskeyword' option)/\K \K\Klike "\k", but excluding digits/\f \f\ffile name character (see'isfname' option)/\F \F\Flike "\f", but excluding digits/\p \p\pprintable character (see'isprint' option)/\P \P\Plike "\p", but excluding digits/\s \s\swhitespace character:<Space> and<Tab>/\S \S\Snon-whitespace character; opposite of \s/\d \d\ddigit:[0-9]/\D \D\Dnon-digit:[^0-9]/\x \x\xhex digit:[0-9A-Fa-f]/\X \X\Xnon-hex digit:[^0-9A-Fa-f]/\o \o\ooctal digit:[0-7]/\O \O\Onon-octal digit:[^0-7]/\w \w\wword character:[0-9A-Za-z_]/\W \W\Wnon-word character:[^0-9A-Za-z_]/\h \h\hhead ofword character:[A-Za-z_]/\H \H\Hnon-head ofword character:[^A-Za-z_]/\a \a\aalphabetic character:[A-Za-z]/\A \A\Anon-alphabetic character:[^A-Za-z]/\l \l\llowercase character:[a-z]/\L \L\Lnon-lowercase character:[^a-z]/\u \u\uuppercase character:[A-Z]/\U \U\Unon-uppercase character[^A-Z]/\_ \_x\_xwherexis any of the characters above: characterclass with end-of-line included(end of character classes) magic nomagicmatches/\e \e\e<Esc>/\t \t\t<Tab>/\r \r\r<CR>/\b \b\b<BS>/\n \n\nend-of-line/~~\~last given substitutestring/\1 \1\1samestringas matched by first \(\)/\2 \2\2Like "\1", but uses second \(\).../\9 \9\9Like "\1", but uses ninth \(\)E68/\z1 \z1\z1only forsyntax highlighting, see:syn-ext-match.../\z1 \z9\z9only forsyntax highlighting, see:syn-ext-matchxxa character with no special meaning matches itself/[][]\[]any character specified inside the[]/\%[] \%[]\%[]a sequence of optionally matched atoms/\c \c\cignore case,do not use the'ignorecase' option/\C \C\Cmatch case,do not use the'ignorecase' option/\Z \Z\Zignore differences inUnicode "combining characters".Useful when searching voweled Hebrew orArabic text. magic nomagicmatches/\m \m\m'magic' on for the following chars in thepattern/\M \M\M'magic' off for the following chars in thepattern/\v \v\vthe following chars in thepattern are "very magic"/\V \V\Vthe following chars in thepattern are "very nomagic"/\%#= \%#=1 \%#=1 selectregexp engine/zero-width/\%d \%d\%dmatch specified decimal character (eg \%d123)/\%x \%x\%xmatch specified hex character (eg \%x2a)/\%o \%o\%omatch specifiedoctal character (eg \%o040)/\%u \%u\%umatch specifiedmultibyte character (eg \%u20ac)/\%U \%U\%Umatch specified largemultibyte character (eg\%U12345678)/\%C \%C\%Cmatch any composing charactersExamplematches\<\I\i*or\<\h\w*\<[a-zA-Z_][a-zA-Z0-9_]*An identifier (e.g., inaC program).\(\.$\|\. \)A period followed by<EOL> ora space.[.!?][])"']*\($\|[ ]\)A searchpattern that finds theend ofa sentence,with almost the same definitionas the ")" command.cat\ZBoth "cat" and "càt"("a" followed by 0x0300)Does not match "càt" (character 0x00e0), eventhoughit may look the same.==============================================================================5. Multi itemspattern-multi-itemsAn atom can be followed by an indication of how many times the atom can bematched and in what way. Thisis calleda multi. See/multi for anoverview./star/\star*(use \* when'magic'is not set)Matches0 or more of the preceding atom,as manyas possible.Example 'nomagic'matchesa* a\*"", "a", "aa", "aaa", etc..* \.\*anything, also an empty string, no end-of-line\_.* \_.\*everything up to theend of the buffer\_.*END \_.\*ENDeverything up to and including the last "END"in the bufferException: When "*"is usedat the start of thepattern or just after"^"it matches thestar character.Be aware thatrepeating "\_." can matcha lot of text and takea longtime. For example, "\_.*END" matches all text from the currentposition to the last occurrence of "END" in the file. Since the "*"will matchas manyas possible, this first skips over all lines untiltheend of the file and then tries matching "END", backing up onecharacterata time./\+\+Matches 1 or more of the preceding atom,as manyas possible.Examplematches^.\+$any non-empty line\s\+whitespace ofat least one character/\=\=Matches0 or 1 of the preceding atom,as manyas possible.Examplematchesfoo\="fo" and "foo"/\?\?Just like \=. Cannot be used when searching backwards with the "?"command./\{E60E554E870\{n,m}Matchesn tom of the preceding atom,as manyas possible\{n}Matchesn of the preceding atom\{n,}Matchesat leastn of the preceding atom,as manyas possible\{,m}Matches0 tom of the preceding atom,as manyas possible\{}Matches0 or more of the preceding atom,as manyas possible (like *)/\{-\{-n,m}matchesn tom of the preceding atom,as fewas possible\{-n}matchesn of the preceding atom\{-n,}matchesat leastn of the preceding atom,as fewas possible\{-,m}matches0 tom of the preceding atom,as fewas possible\{-}matches0 or more of the preceding atom,as fewas possiblen andm are positive decimal numbers or zeronon-greedyIfa "-" appears immediately after the "{", thena shortest matchfirst algorithmis used (see example below). In particular, "\{-}"isthe sameas "*" but uses the shortest match first algorithm. BUT:Amatch that starts earlieris preferred overa shorter match: "a\{-}b"matches "aaab" in "xaaab".Examplematchesab\{2,3}c"abbc" or "abbbc"a\{5}"aaaaa"ab\{2,}c"abbc", "abbbc", "abbbbc", etc.ab\{,3}c"ac", "abc", "abbc" or "abbbc"a[bc]\{3}d"abbbd", "abbcd", "acbcd", "acccd", etc.a\(bc\)\{1,2}d"abcd" or "abcbcd"a[bc]\{-}[cd]"abc" in "abcd"a[bc]*[cd]"abcd" in "abcd"The} may optionally be preceded witha backslash: \{n,m\}./\@=\@=Matches the preceding atom with zero width.Like "(?=pattern)" in Perl.Examplematchesfoo\(bar\)\@="foo" in "foobar"foo\(bar\)\@=foonothing/zero-widthWhen using "\@=" (or "^", "$", "\<", "\>") no characters are includedin the match. These items are only used to check ifa match can bemade. This can be tricky, becausea match with following items willbe done in the same position. The last example above will not match"foobarfoo", becauseit tries match "foo" in the same position where"bar" matched.Note that using "\&" works the sameas using "\@=": "foo\&.."is thesameas "\(foo\)\@=..". But using "\&"is easier, you don't need theparentheses./\@!\@!Matches with zero width if the preceding atom does NOT matchat thecurrent position./zero-widthLike "(?!pattern)" in Perl.Examplematchesfoo\(bar\)\@!any "foo" not followed by "bar"a.\{-}p\@!"a", "ap", "app", "appp", etc. not immediatelyfollowed bya "p"if \(\(then\)\@!.\)*$"if " not followed by "then"Using "\@!"is tricky, because there are many places whereapatterndoes not match. "a.*p\@!" will match from an "a" to theend of theline, because ".*" can match all characters in the line and the "p"doesn't matchat theend of the line. "a.\{-}p\@!" will match any"a", "ap", "app", etc. that isn't followed bya "p", because the "."can matcha "p" and "p\@!" doesn't match after that.You can't use "\@!" to look fora non-match before the matchingposition: "\(foo\)\@!bar" will match "bar" in "foobar", becauseat theposition where "bar" matches, "foo" does not match. To avoid matching"foobar" you could use "\(foo\)\@!...bar", but that doesn't matchabarat the start ofa line. Use "\(foo\)\@<!bar".Useful example: to find "foo" ina line that does not contain "bar":/^\%(.*bar\)\@!.*\zsfooThispattern first checks that thereis nota single position in theline where "bar" matches. If ".*bar" matches somewhere the \@! willreject the pattern. When thereis no match any "foo" will be found.The "\zs"is to have the match start just before "foo"./\@<=\@<=Matches with zero width if the preceding atom matches just before whatfollows./zero-widthLike "(?<=pattern)" in Perl, but Vim allows non-fixed-width patterns.Examplematches\(an\_s\+\)\@<=file"file" after "an" and whitespace or anend-of-lineFor speed it's often much better to avoid this multi. Try using "\zs"instead/\zs. To match the sameas the above example:an\_s\+\zsfileAt least seta limit for the look-behind, see below."\@<=" and "\@<!" check for matches just before what follows.Theoretically these matches could start anywhere before this position.But to limit the time needed, only the line where what follows matchesis searched, and one line before that (if thereis one). This shouldbe sufficient to match most things and not be too slow.In the oldregexp engine the part of thepattern after "\@<=" and"\@<!" are checked fora match first, thus things like "\1" don't worktoreference \(\) inside the preceding atom. It does work the otherway around:Bad examplematches\%#=1\1\@<=,\([a-z]\+\)",abc" in "abc,abc"However, the newregexp engine works differently,itis better to notrely on this behavior,do not use \@<= ifit can be avoided:Examplematches\([a-z]\+\)\zs,\1",abc" in "abc,abc"\@123<=Like "\@<=" but only look back 123 bytes. This avoids trying lotsof matches that are known to fail and make executing thepattern veryslow. Example, check if thereisa "<" just before "span":/<\@1<=spanThis will try matching "<" only one byte before "span", whichis theonly place that works anyway.After crossinga line boundary, the limitis relative to theend ofthe line. Thus the charactersat the start of the line with the matchare not counted (thisis just to keepit simple).The number zerois the sameas no limit./\@<!\@<!Matches with zero width if the preceding atom does NOT match justbefore what follows. Thus this matches if thereis no position in thecurrent or previous line where the atom matches such thatit ends justbefore what follows./zero-widthLike "(?<!pattern)" in Perl, but Vim allows non-fixed-width patterns.The match with the preceding atomis made toend just before the matchwith what follows, thus an atom that ends in ".*" will work.Warning: This can be slow (because many positions need to be checkedfora match). Usea limit if you can, see below.Examplematches\(foo\)\@<!barany "bar" that's not in "foobar"\(\/\/.*\)\@<!in"in" whichis not after "//"\@123<!Like "\@<!" but only look back 123 bytes. This avoids trying lots ofmatches that are known to fail and make executing thepattern veryslow./\@>\@>Matches the preceding atom like matchinga whole pattern.Like "(?>pattern)" in Perl.Examplematches\(a*\)\@>anothing (the "a*" takes all the "a"'s, there can't beanother one following)This matches the preceding atomas ifit wasapattern by itself. Ifit doesn't match, thereis no retry with shorter sub-matches oranything. Observe this difference: "a*b" and "a*ab" both match"aaab", but in the secondcase the "a*" matches only the first two"a"s. "\(a*\)\@>ab" will not match "aaab", because the "a*" matchesthe "aaa" (as many "a"sas possible), thus the "ab" can't match.==============================================================================6. Ordinary atomspattern-atomsAn ordinary atom can be:/^^At beginning ofpattern or after "\|", "\(", "\%(" or "\n": matchesstart-of-line;at other positions, matches literal '^'./zero-widthExamplematches^beep(the start of theC function "beep" (probably)./\^\^Matches literal '^'. Can be usedat any position in the pattern, butnot inside []./\_^\_^Matches start-of-line./zero-width Can be usedat any position inthe pattern, but not inside [].Examplematches\_s*\_^foowhitespace and blank lines and then "foo"atstart-of-line/$$Atend ofpattern or in front of "\|", "\)" or "\n" ('magic' on):matches end-of-line<EOL>;at other positions, matches literal '$'./zero-width/\$\$Matches literal '$'. Can be usedat any position in the pattern, butnot inside []./\_$\_$Matches end-of-line./zero-width Can be usedat any position in thepattern, but not inside [].Note that "a\_$b" never matches, since"b" cannot match an end-of-line. Use "a\nb" instead/\n.Examplematchesfoo\_$\_s*"foo"at end-of-line and following whitespace andblank lines.(with'nomagic': \.)/./\.Matches any single character, but not an end-of-line./\_.\_.Matches any single character or end-of-line.Careful: "\_.*" matches all text to theend of the buffer!/\<\<Matches the beginning ofa word: The next charis the first char ofaword. The'iskeyword' optionspecifies whatisaword character./zero-width/\>\>Matches theend ofa word: The previous charis the last char ofaword. The'iskeyword' optionspecifies whatisaword character./zero-width/\zs\zsMatchesat any position, but not inside [], and sets the start of thematch there: The next charis the first char of the whole match./zero-widthExample:/^\s*\zsifmatches an "if"at the start ofa line, ignoring white space.Can be used multiple times, the last one encountered ina matchingbranchis used. Example:/\(.\{-}\zsFab\)\{3}Finds the third occurrence of "Fab".This cannot be followed bya multi.E888{not available when compiled without the |+syntax| feature}/\ze\zeMatchesat any position, but not inside [], and sets theend of thematch there: The previous charis the last char of the whole match./zero-widthCan be used multiple times, the last one encountered ina matchingbranchis used.Example: "end\ze\(if\|for\)" matches the "end" in "endif" and"endfor".This cannot be followed bya multi.E888{not available when compiled without the |+syntax| feature}/\%^start-of-file\%^Matches start of the file. When matching witha string, matches thestart of the string.For example, to find the first "VIM" ina file:/\%^\_.\{-}\zsVIM/\%$end-of-file\%$Matchesend of the file. When matching witha string, matches theend of the string.Note that this does NOT find the last "VIM" ina file:/VIM\_.\{-}\%$It will find the next VIM, because the part afterit will alwaysmatch. This one will find the last "VIM" in the file:/VIM\ze\(\(VIM\)\@!\_.\)*\%$This uses/\@! to ascertain that "VIM" does NOT match in anyposition after the first "VIM".Searching from theend of the file backwardsis easier!/\%V\%VMatch inside theVisual area. WhenVisual mode has already beenstopped match in the area thatgv would reselect.Thisisa/zero-width match. To make sure the wholepatternisinside theVisual areaputitat the start and just before theend ofthe pattern, e.g.:/\%Vfoo.*ba\%VrThis also works if only "foobar" was Visually selected. This:/\%Vfoo.*bar\%Vwould match "foobar" if theVisual selection continues after the "r".Only works for the current buffer./\%#cursor-position\%#Matches with the cursor position. Only works when matching inabuffer displayed ina window.WARNING: When the cursoris moved after thepattern was used, theresult becomes invalid. Vim doesn't automatically update the matches.Thisis especially relevant forsyntax highlighting and'hlsearch'.In other words: When the cursor moves the display isn't updated forthis change. An updateis done for lines which are changed (the wholelineis updated) or when using theCTRL-L command (the whole screenis updated). Example, to highlight theword under the cursor:/\k*\%#\k*When'hlsearch'is set and you move the cursor around and make changesthis will clearly show when the matchis updated or not./\%'m/\%<'m/\%>'m\%'mMatches with the position ofmark m.\%<'mMatches before the position ofmark m.\%>'mMatches after the position ofmark m.Example, to highlight the text frommark 's to 'e:/.\%>'s.*\%<'e..Note that two dots are required to includemark 'e in the match. Thatis because "\%<'e" matchesat the character before the 'e mark, andsince it'sa/zero-width matchit doesn't include that character.WARNING: When themarkis moved after thepattern was used, the resultbecomes invalid. Vim doesn't automatically update the matches.Similar to moving the cursor for "\%#"/\%#./\%l/\%>l/\%<lE951E1204E1273\%23lMatches ina specific line.\%<23lMatches abovea specific line (lower line number).\%>23lMatches belowa specific line (higher line number).\%.lMatchesat the cursor line.\%<.lMatches above the cursor line.\%>.lMatches below the cursor line.These six can be used to match specific lines ina buffer. The "23"can be any line number. The first lineis 1.WARNING: Wheninserting ordeleting lines Vim does not automaticallyupdate the matches. This meansSyntax highlighting quickly becomeswrong. Also when referring to the cursor position(".") andthe cursor moves the display isn't updated for this change. An updateis done when using theCTRL-L command (the whole screenis updated).Example, to highlight the line where the cursor currently is::exe '/\%' . line(".") . 'l'Alternatively use:/\%.lWhen'hlsearch'is set and you move the cursor around and make changesthis will clearly show when the matchis updated or not./\%c/\%>c/\%<c\%23cMatches ina specific column.\%<23cMatches beforea specific column.\%>23cMatches aftera specific column.\%.cMatchesat the cursor column.\%<.cMatches before the cursor column.\%>.cMatches after the cursor column.These six can be used to match specific columns ina buffer or string.The "23" can be any column number. The first columnis 1. Actually,the columnis the byte number (thus it's not exactly right formultibyte characters).WARNING: Wheninserting ordeleting text Vim does not automaticallyupdate the matches. This meansSyntax highlighting quickly becomeswrong. Also when referring to the cursor position(".") andthe cursor moves the display isn't updated for this change. An updateis done when using theCTRL-L command (the whole screenis updated).Example, to highlight the column where the cursor currently is::exe '/\%' .. col(".") .. 'c'Alternatively use:/\%.cWhen'hlsearch'is set and you move the cursor around and make changesthis will clearly show when the matchis updated or not.Example for matchinga single byte in column 44:/\%>43c.\%<46cNote that "\%<46c" matches in column 45 when the "." matchesa byte incolumn 44./\%v/\%>v/\%<v\%23vMatches ina specific virtual column.\%<23vMatches beforea specific virtual column.\%>23vMatches aftera specific virtual column.\%.vMatchesat the current virtual column.\%<.vMatches before the current virtual column.\%>.vMatches after the current virtual column.These six can be used to match specific virtual columns ina buffer orstring. When not matching witha buffer ina window, the optionvalues of the currentwindow are used (e.g.,'tabstop').The "23" can be any column number. The first columnis 1.Note that some virtual column positions will never match, because theyare halfway throughatab or other character that occupies more thanone screen character.WARNING: Wheninserting ordeleting text Vim does not automaticallyupdate highlighted matches. This meansSyntax highlighting quicklybecomes wrong. Also when referring to the cursor position(".") andthe cursor moves the display isn't updated for this change. An updateis done when using theCTRL-L command (the whole screenis updated).Example, to highlight all the characters after virtual column 72:/\%>72v.*When'hlsearch'is set and you move the cursor around and make changesthis will clearly show when the matchis updated or not.To match the text up to column 17:/^.*\%17vTo match all characters after the current virtual column (where thecursor is):/\%>.v.*Column 17is not included, because thisisa/zero-width match. Toinclude the column use:/^.*\%17v.This command does the same thing, but also matches when thereis nocharacter in column 17:/^.*\%<18v.Note that without the "^" to anchor the match in the first column,this will also highlight column 17:/.*\%17vColumn 17is highlighted by'hlsearch' because thereis another matchwhere ".*" matches zero characters.Character classes:\iidentifier character (see'isident' option)/\i\Ilike "\i", but excluding digits/\I\kkeyword character (see'iskeyword' option)/\k\Klike "\k", but excluding digits/\K\ffile name character (see'isfname' option)/\f\Flike "\f", but excluding digits/\F\pprintable character (see'isprint' option)/\p\Plike "\p", but excluding digits/\PNOTE: the above also work formultibyte characters. The ones below onlymatch ASCII characters,as indicated by the range.whitespacewhite-space\swhitespace character:<Space> and<Tab>/\s\Snon-whitespace character; opposite of \s/\S\ddigit:[0-9]/\d\Dnon-digit:[^0-9]/\D\xhex digit:[0-9A-Fa-f]/\x\Xnon-hex digit:[^0-9A-Fa-f]/\X\ooctal digit:[0-7]/\o\Onon-octal digit:[^0-7]/\O\wword character:[0-9A-Za-z_]/\w\Wnon-word character:[^0-9A-Za-z_]/\W\hhead ofword character:[A-Za-z_]/\h\Hnon-head ofword character:[^A-Za-z_]/\H\aalphabetic character:[A-Za-z]/\a\Anon-alphabetic character:[^A-Za-z]/\A\llowercase character:[a-z]/\l\Lnon-lowercase character:[^a-z]/\L\uuppercase character:[A-Z]/\u\Unon-uppercase character:[^A-Z]/\UNOTE: Using the atomis faster than the[] form.NOTE:'ignorecase', "\c" and "\C" are not used by character classes./\_E63/\_i/\_I/\_k/\_K/\_f/\_F/\_p/\_P/\_s/\_S/\_d/\_D/\_x/\_X/\_o/\_O/\_w/\_W/\_h/\_H/\_a/\_A/\_l/\_L/\_u/\_U\_xWhere "x"is any of the characters above: The characterclass withend-of-line added(end of character classes)\ematches<Esc>/\e\tmatches<Tab>/\t\rmatches<CR>/\r\bmatches<BS>/\b\nmatches an end-of-line/\nWhen matching inastring instead of buffer texta literal newlinecharacteris matched.~matches the last given substitutestring/~/\~\(\)Apattern enclosed by escaped parentheses./\(/\(\)/\)E.g., "\(^a\)" matches 'a'at the start ofa line.There can only be nine of these. You can use "\%(" to add more, butnot countingitasa sub-expression.E51E54E55E872E873\1 Matches the samestring that was matched by/\1E65the first sub-expression in \( and \).Example: "\([a-z]\).\1" matches "ata", "ehe", "tot", etc.\2 Like "\1", but uses second sub-expression,/\2.../\3\9 Like "\1", but uses ninth sub-expression./\9Note: The numbering of groupsis done based on which "\(" comes firstin thepattern (going left to right), NOT based on whatis matchedfirst.\%(\)Apattern enclosed by escaped parentheses./\%(\)/\%(E53Just like \(\), but without countingitasa sub-expression. Thisallows using more groups and it'sa little bit faster.xA single character, with no special meaning, matches itself/\/\\\xAbackslash followed bya single character, with no special meaning,is reserved for future expansions[](with'nomagic': \[])/[]/\[]/\_[]/collectionE76\_[]A collection. Thisisa sequence of characters enclosed in squarebrackets. It matches any single character in the collection.Examplematches[xyz]any 'x', 'y' or 'z'[a-zA-Z]$any alphabetic characterat theend ofa line\c[a-z]$same[А-яЁё]Russian alphabet (withutf-8 and cp1251)/[\n]With "\_" prepended the collection also includes the end-of-line.The same can be done by including "\n" in the collection. Theend-of-lineis also matched when the collection starts with "^"! Thus"\_[^ab]" matches the end-of-line and any character but "a" and "b".This makesitVi compatible: Without the "\_" or "\n" the collectiondoes not match an end-of-line.E769When the ']'is not there Vim will not give an error message butassume no collectionis used. Useful to search for '['. However, youdo getE769 for internal searching. And be aware that ina:substitute command the whole command becomes the pattern. E.g.":s/[/x/" searches for "[/x" and replacesit with nothing. It doesnot search for "[" and replacesit with "x"!E944E945If the sequence begins with "^",it matches any single character NOTin the collection: "[^xyz]" matches anything but 'x', 'y' and 'z'.- If two characters in the sequence are separated by '-', thisis shorthand for the fulllist of ASCII characters between them. E.g., "[0-9]" matches any decimal digit. If thestarting character exceeds the ending character, e.g.[c-a],E944 occurs. Non-ASCII characters can be used, but the character valuesmust not be more than 256 apart in the oldregexp engine. For example, searching by [\u3000-\u4000] after setting re=1 emitsaE945 error. Prepending \%#=2 will fix it.-A characterclassexpressionis evaluated to the set of characters belonging to that character class. The following character classes are supported: Name FuncContents[:alnum:][:alnum:] isalnumASCII letters and digits[:alpha:][:alpha:] isalphaASCII letters[:blank:][:blank:]space andtab[:cntrl:][:cntrl:] iscntrlASCIIcontrol characters[:digit:][:digit:]decimal digits '0' to '9'[:graph:][:graph:] isgraphASCII printable characters excludingspace[:lower:][:lower:] (1)lowercase letters (all letters when'ignorecase'is used)[:print:][:print:] (2)printable characters includingspace[:punct:][:punct:] ispunctASCII punctuation characters[:space:][:space:]whitespace characters: space, tab, CR,NL, vertical tab, form feed[:upper:][:upper:] (3)uppercase letters (all letters when'ignorecase'is used)[:xdigit:][:xdigit:]hexadecimal digits: 0-9, a-f, A-F[:return:][:return:]the<CR> character[:tab:][:tab:]the<Tab> character[:escape:][:escape:]the<Esc> character[:backspace:][:backspace:]the<BS> character[:ident:][:ident:]identifier character (sameas "\i")[:keyword:][:keyword:]keyword character (sameas "\k")[:fname:][:fname:]file name character (sameas "\f") The square brackets in characterclass expressions are additional to the square brackets delimitinga collection. For example, the followingisa plausiblepattern fora UNIX filename: "[-./[:alnum:]_~]\+". That is,alist ofat least one character, each of whichis either '-', '.', '/', alphabetic, numeric, '_' or '~'. These items only work for 8-bit characters, except[:lower:] and[:upper:] also work formultibyte characters when using the newregexp engine. Seetwo-engines. In the future these items may work formultibyte characters. For now, to get all "alpha" characters you can use: [[:lower:][:upper:]]. The "Func" column shows what library functionis used. The implementation depends on the system. Otherwise: (1) Uses islower() for ASCII and Vim builtin rules for other characters. (2) Uses Vim builtin rules (3) As with (1) but using isupper()/[[=[==]- An equivalence class. This means that characters are matched that have almost the same meaning, e.g., when ignoring accents. This only works for Unicode, latin1 and latin9. The form is:[=a=]/[[.[..]-A collation element. This currently simply acceptsa single character in the form:[.a.]/\]- To includea literal ']', '^', '-' or '\' in the collection,putabackslash before it: "[xyz\]]", "[\^xyz]", "[xy\-z]" and "[xyz\\]". (Note: POSIX does not support the use ofabackslash this way). For ']' you can also makeit the first character (followinga possible "^"): "[]xyz]" or "[^]xyz]". For '-' you can also makeit the first or last character: "[-xyz]", "[^-xyz]" or "[xyz-]". For '\' you can also letit be followed by any character that's not in "^]-\bdertnoUux". "[\xyz]" matches '\', 'x', 'y' and 'z'. It's better to use "\\" though, future expansions may use other characters after '\'.- Omitting the trailing]is not considered an error. "[]" works like "[]]",it matches the ']' character.- The following translations are accepted when the 'l' flagis not included in'cpoptions':\e<Esc>\t<Tab>\r<CR>(NOT end-of-line!)\b<BS>\nline break, see above/[\n]\d123decimal number of character\o40octal number of character up to 0o377\x20hexadecimal number of character up to 0xff\u20AChex. number ofmultibyte character up to 0xffff\U1234hex. number ofmultibyte character up to 8 characters0xffffffffE1541NOTE: The otherbackslash codes mentioned abovedo not work inside []!- Matching witha collection can be slow, because each character in the text has to be compared with each character in the collection. Use one of the other atoms above when possible. Example: "\d"is much faster than "[0-9]" and matches the same characters. However, the newNFAregexp engine deals with this better than the old one./\%[]E69E70E369\%[]A sequence of optionally matched atoms. This always matches.It matchesas much of thelist of atomsit containsas possible. Thusit stopsat the first atom that doesn't match. For example:/r\%[ead]matches "r", "re", "rea" or "read". The longest that matchesis used.To match theEx command "function", where "fu"is required and"nction"is optional, this would work:/\<fu\%[nction]\>The end-of-word atom "\>"is used to avoid matching "fu" in "full".It gets more complicated when the atoms are not ordinary characters.You don't often have to use it, butitis possible. Example:/\<r\%[[eo]ad]\>Matches the words "r", "re", "ro", "rea", "roa", "read" and "road".There can be no \(\), \%(\) or \z(\) items inside the[] and \%[] doesnot nest.To includea "[" use "[[]" and for "]" use []]", e.g.,:/index\%[[[]0[]]]matches "index" "index[", "index[0" and "index[0]".{not available when compiled without the |+syntax| feature}/\%d/\%x/\%o/\%u/\%UE678\%d123Matches the character specified witha decimal number. Must befollowed bya non-digit.\%o40Matches the character specified with anoctal number up to 0o377.Numbers below 0o40must be followed bya non-octal digit oranon-digit.\%x2aMatches the character specified with up to two hexadecimal characters.\%u20ACMatches the character specified with up to four hexadecimalcharacters.\%U1234abcdMatches the character specified with up to eight hexadecimalcharacters, up to 0x7fffffff (the maximum allowed valueis INT_MAXE1541, but the maximum validUnicode codepointis U+10FFFF).==============================================================================7. Ignoringcase inapattern/ignorecaseIf the'ignorecase' optionis on, thecase of normal lettersis ignored.'smartcase' can be set to ignorecase when thepattern containslowercaseletters only./\c/\CWhen "\c" appears anywhere in the pattern, the wholepatternis handled like'ignorecase'is on. The actual value of'ignorecase' and'smartcase'isignored. "\C" does the opposite: Force matchingcase for the whole pattern.{only Vim supports \c and \C}Note that'ignorecase', "\c" and "\C" are not used for the character classes.Examples: pattern'ignorecase' 'smartcase'matchesfoo off-foofoo on-foo Foo FOOFoo onofffoo Foo FOOFoo onon Foo\cfoo--foo Foo FOOfoo\C--fooTechnical detail:NL-used-for-Nul<Nul> characters in the file are storedas<NL> in memory. In the displaythey are shownas "^@". The translationis done when reading andwritingfiles. To matcha<Nul> witha searchpattern you can just enterCTRL-@ or"CTRL-V 000". Thisis probably just what you expect. Internally thecharacteris replaced witha<NL> in the search pattern. Whatis unusualisthat typingCTRL-VCTRL-J also insertsa<NL>, thus also searches fora<Nul>in the file.CR-used-for-NLWhen'fileformat'is "mac",<NL> characters in the file are storedas<CR>characters internally. In the text they are shownas "^J". Otherwise thisworks similar to the usage of<NL> fora<Nul>.When working withexpression evaluation,a<NL> character in thepatternmatchesa<NL> in the string. The use of "\n" (backslash n) to matcha<NL>doesn't work there,it only works to match text in the buffer.pattern-multi-bytepattern-multibytePatterns will also work withmultibyte characters, mostlyas you wouldexpect. But invalid bytes may cause trouble,apattern with an invalid bytewill probably never match.==============================================================================8. Composing characterspatterns-composing/\ZWhen "\Z" appears anywhere in the pattern, all composing characters areignored. Thus only the base characters need to match, the composingcharacters may be different and the number of composing characters may differ.Only relevant when'encoding'is "utf-8".Exception: If thepattern starts with one or more composing characters, thesemust match./\%CUse "\%C" to skip any composing characters. For example, thepattern "a" doesnot match in "càt" (where thea has the composing character 0x0300), but"a\%C" does.Note that this does not match "cát" (where the áis character0xe1,it does not havea compositing character). It does match "cat" (wheretheais just an a).Whena composing character appearsat the start of thepattern or after anitem that doesn't include the composing character,a matchis foundat anycharacter that includes this composing character.When usinga dot anda composing character, this works the sameas thecomposing character by itself, except thatit doesn't matter what comes beforethis.The order of composing characters does not matter. Also, the text may havemore composing characters than the pattern,it still matches. But allcomposing characters in thepatternmust be found in the text.SupposeBisa base character andx andy are composing characters:patterntextmatchBxyBxyyes (perfect match)BxyByxyes (order ignored)BxyByno (x missing)BxyBxno (y missing)BxBxyes (perfect match)BxByno (x missing)BxBxyyes (extray ignored)BxByxyes (extray ignored)==============================================================================9. Compare withPerl patternsperl-patternsVim's regexes are most similar to Perl's, in terms of what you can do. Thedifference between themis mostly just notation; here'sa summary of wherethey differ:Capabilityin Vimspeakin Perlspeak----------------------------------------------------------------forcecase insensitivity\c(?i)forcecase sensitivity\C(?-i)backref-less grouping\%(atom\)(?:atom)conservative quantifiers\{-n,m}*?, +?, ??, {}?0-width matchatom\@=(?=atom)0-width non-matchatom\@!(?!atom)0-width preceding matchatom\@<=(?<=atom)0-width preceding non-matchatom\@<!(?<!atom)match without retryatom\@>(?>atom)Vim andPerl handle newline characters insideastringa bit differently:In Perl,^ and$ only matchat the very beginning andend of the text,by default, but you can set the 'm' flag, which lets them matchatembedded newlinesas well. You can also set the 's' flag, which causesa. to match newlinesas well. (Both these flags can be changed insideapattern using the samesyntax used for thei flag above, BTW.)On the other hand, Vim's^ and$ always matchat embedded newlines, andyou get two separate atoms, \%^ and \%$, which only matchat the verystart andend of the text, respectively. Vim solves the second problemby giving you the \_ "modifier":putit in front ofa. ora characterclass, and they will match newlinesas well.Finally, these constructs areunique to Perl:- execution of arbitrary code in the regex: (?{perl code})- conditional expressions: (?(condition)true-expr|false-expr)...and these areunique to Vim:-changing the magic-ness ofa pattern: \v \V \m \M (very useful for avoiding backslashitis)- sequence of optionally matching atoms: \%[atoms]- \& (whichis to \| what "and"is to "or";it forces several branches to matchat one spot)- matching lines/columns by number: \%5l \%5c \%5v- setting the start andend of the match: \zs \ze==============================================================================10. Highlighting matchesmatch-highlightsyntax-vs-matchNote that the match highlight mechanismis independentofsyntax-highlighting, whichis (usually)a buffer-localhighlighting, while matchingis window-local, both methodscan be freely mixed. Match highlightingfunctions give youa bit more flexibility in when and how to apply, but aretypically only used for temporary highlighting, without strictrules. Both methods can be used toconceal text.Thus the matchingfunctions likematchadd() won't considersyntax rules andfunctions likesynconcealed() and theother way around.:mat:match:mat[ch]{group} /{pattern}/Defineapattern to highlight in the current window. It willbe highlighted with{group}. Example::highlight MyGroup ctermbg=green guibg=green:match MyGroup /TODO/Instead of// any character can be used tomark the start andend of the{pattern}. Watch out for using special characters,suchas'"' and'|'.{group}must existat the moment this commandis executed.The{group} highlighting still applies whena characteristo be highlighted for'hlsearch',as the highlighting formatchesis given higher priority than that of'hlsearch'.Syntax highlighting (see'syntax')is also overruled bymatches.Note that highlighting the last used searchpattern with'hlsearch'is used in all windows, while thepattern definedwith ":match" only exists in the current window. Itis keptwhen switching to another buffer.'ignorecase' does not apply, use/\c in thepattern toignore case. Otherwisecaseis not ignored.'redrawtime' defines the maximum time searched forpatternmatches.When matching end-of-line and Vim redraws only part of thedisplay you may get unexpected results. Thatis because Vimlooks fora match in the line where redrawing starts.Also seematcharg() andgetmatches(). The former returnsthe highlight group andpattern ofa previous:matchcommand. The latter returnsalist with highlight groups andpatterns defined by bothmatchadd() and:match.Highlighting matches using:match are limited to threematches (aside from:match,:2match and:3match areavailable).matchadd() does not have this limitation and inaddition makesit possible to prioritize matches.Another example, which highlights all characters in virtualcolumn 72 and more::highlight rightMargin term=bold ctermfg=blue guifg=blue:match rightMargin /.\%>72v/To highlight all character that are in virtual column 7::highlight col8 ctermbg=grey guibg=grey:match col8 /\%<8v.\%>7v/Note the use of two items to also matcha character thatoccupies more than one virtual column, suchasa TAB.:mat[ch]:mat[ch] noneCleara previously defined match pattern.:2mat[ch]{group} /{pattern}/:2match:2mat[ch]:2mat[ch] none:3mat[ch]{group} /{pattern}/:3match:3mat[ch]:3mat[ch] noneJust like:match above, but seta separate match. Thusthere can be three matches activeat the same time. The matchwith the lowest number has priority if several matchat thesame position. It uses the match id 3.The ":3match" commandis used by (Vim< 9.0.2054)matchparenplugin. You are suggested to use ":match" for manual matchingand ":2match" for anotherplugin or even better make use ofthe more flexiblematchadd() (and similar)functions instead.==============================================================================11. Fuzzy matchingfuzzy-matchingFuzzy matching refers to matching strings usinga non-exact search string.Fuzzy matching will matcha string, if all the characters in the searchstringare present anywhere in thestring in the same order. Caseis ignored. Inamatched string, other characters can be present between two consecutivecharacters in the search string. If the searchstring has multiple words, theneachwordis matched separately. So the words in the searchstring can bepresent in any order ina string.Fuzzy matching assignsa score for each matchedstring based on the followingcriteria:- The number of sequentially matching characters.- The number of characters (distance) between two consecutive matching characters.- Matchesat the beginning ofaword- Matchesata camelcase character (e.g. Case in CamelCase)- Matches aftera path separator ora hyphen.- The number of unmatched characters ina string.-A full/exact matchis preferred.The matchingstring with the highest scoreis returned first.For example, when you search for the "get pat"string using fuzzy matching,itwill match the strings "GetPattern", "PatternGet", "getPattern", "patGetter","getSomePattern", "MatchpatternGet" etc.Thefunctionsmatchfuzzy() andmatchfuzzypos() can be used to fuzzy searchastring inaList of strings. Thematchfuzzy() function returnsaList ofmatching strings. Thematchfuzzypos()functions returns theList of matches,the matching positions and the fuzzy match scores.The "f" flag of:vimgrep enables fuzzy matching.To enable fuzzy matching forins-completion, add the "fuzzy" value to the'completeopt' option. vim:tw=78:ts=8:noet:ft=help:norl: