matchit.txt (20260B)
1 *matchit.txt* Extended "%" matching Last change: 2026 Jun 01 2 3 VIM REFERENCE MANUAL by Benji Fisher et al 4 5 6 *matchit* *matchit.vim* 7 8 1. Extended matching with "%" |matchit-intro| 9 2. Activation |matchit-activate| 10 3. Configuration |matchit-configure| 11 4. Supporting a New Language |matchit-newlang| 12 5. Known Bugs and Limitations |matchit-bugs| 13 14 The functionality mentioned here is a plugin, see |add-plugin|. 15 This plugin is only available if 'compatible' is not set. 16 17 ============================================================================== 18 1. Extended matching with "%" *matchit-intro* 19 20 *matchit-%* 21 % Cycle forward through matching groups, such as "if", "else", "endif", 22 as specified by |b:match_words|. 23 24 *g%* *v_g%* *o_g%* 25 g% Cycle backwards through matching groups, as specified by 26 |b:match_words|. For example, go from "if" to "endif" to "else". 27 28 *[%* *v_[%* *o_[%* 29 [% Go to [count] previous unmatched group, as specified by 30 |b:match_words|. Similar to |[{|. 31 32 *]%* *v_]%* *o_]%* 33 ]% Go to [count] next unmatched group, as specified by 34 |b:match_words|. Similar to |]}|. 35 36 *v_a%* 37 a% In Visual mode, select the matching group, as specified by 38 |b:match_words|, containing the cursor. Similar to |v_a[|. 39 A [count] is ignored, and only the first character of the closing 40 pattern is selected. 41 42 In Vim, as in plain vi, the percent key, |%|, jumps the cursor from a brace, 43 bracket, or paren to its match. This can be configured with the 'matchpairs' 44 option. The matchit plugin extends this in several ways: 45 46 You can match whole words, such as "if" and "endif", not just 47 single characters. You can also specify a |regular-expression|. 48 You can define groups with more than two words, such as "if", 49 "else", "endif". Banging on the "%" key will cycle from the "if" to 50 the first "else", the next "else", ..., the closing "endif", and back 51 to the opening "if". Nested structures are skipped. Using |g%| goes 52 in the reverse direction. 53 By default, words inside comments and strings are ignored, unless 54 the cursor is inside a comment or string when you type "%". If the 55 only thing you want to do is modify the behavior of "%" so that it 56 behaves this way, you do not have to define |b:match_words|, since the 57 script uses the 'matchpairs' option as well as this variable. 58 59 See |matchit-details| for details on what the script does, and |b:match_words| 60 for how to specify matching patterns. 61 62 MODES: *matchit-modes* *matchit-v_%* *matchit-o_%* 63 64 Mostly, % and related motions (|g%| and |[%| and |]%|) should just work like built-in 65 |motion| commands in |Operator-pending| and |Visual| modes (as of 8.1.648) 66 67 LANGUAGES: *matchit-languages* 68 69 Currently, the following languages are supported: Ada, ASP with VBS, Csh, 70 DTD, Entity, Essbase, Fortran, HTML, JSP (same as HTML), LaTeX, Lua, Pascal, 71 SGML, Shell, Tcsh, Vim, XML. Other languages may already have support via 72 the default |filetype-plugin|s in the standard vim distribution. 73 74 To support a new language, see |matchit-newlang| below. 75 76 DETAILS: *matchit-details* *matchit-parse* 77 78 Here is an outline of what matchit.vim does each time you hit the "%" key. If 79 there are |backref|s in |b:match_words| then the first step is to produce a 80 version in which these back references have been eliminated; if there are no 81 |backref|s then this step is skipped. This step is called parsing. For 82 example, "\(foo\|bar\):end\1" is parsed to yield 83 "\(foo\|bar\):end\(foo\|bar\)". This can get tricky, especially if there are 84 nested groups. If debugging is turned on, the parsed version is saved as 85 |b:match_pat|. 86 87 *matchit-choose* 88 Next, the script looks for a word on the current line that matches the pattern 89 just constructed. It includes the patterns from the 'matchpairs' option. 90 The goal is to do what you expect, which turns out to be a little complicated. 91 The script follows these rules: 92 93 Insist on a match that ends on or after the cursor. 94 Prefer a match that includes the cursor position (that is, one that 95 starts on or before the cursor). 96 Prefer a match that starts as close to the cursor as possible. 97 If more than one pattern in |b:match_words| matches, choose the one 98 that is listed first. 99 100 Examples: 101 102 Suppose you > 103 :let b:match_words = '<:>,<tag>:</tag>' 104 < and hit "%" with the cursor on or before the "<" in "a <tag> is born". 105 The pattern '<' comes first, so it is preferred over '<tag>', which 106 also matches. If the cursor is on the "t", however, then '<tag>' is 107 preferred, because this matches a bit of text containing the cursor. 108 If the two groups of patterns were reversed then '<' would never be 109 preferred. 110 111 Suppose you > 112 :let b:match_words = 'if:end if' 113 < (Note the space!) and hit "%" with the cursor at the end of "end if". 114 Then "if" matches, which is probably not what you want, but if the 115 cursor starts on the "end " then "end if" is chosen. (You can avoid 116 this problem by using a more complicated pattern.) 117 118 If there is no match, the cursor does not move. (Before version 1.13 of the 119 script, it would fall back on the usual behavior of |%|). If debugging is 120 turned on, the matched bit of text is saved as |b:match_match| and the cursor 121 column of the start of the match is saved as |b:match_col|. 122 123 Next, the script looks through |b:match_words| (original and parsed versions) 124 for the group and pattern that match. If debugging is turned on, the group is 125 saved as |b:match_ini| (the first pattern) and |b:match_tail| (the rest). If 126 there are |backref|s then, in addition, the matching pattern is saved as 127 |b:match_word| and a table of translations is saved as |b:match_table|. If 128 there are |backref|s, these are determined from the matching pattern and 129 |b:match_match| and substituted into each pattern in the matching group. 130 131 The script decides whether to search forwards or backwards and chooses 132 arguments for the |searchpair()| function. Then, the cursor is moved to the 133 start of the match, and |searchpair()| is called. By default, matching 134 structures inside strings and comments are ignored. This can be changed by 135 setting |b:match_skip|. 136 137 ============================================================================== 138 2. Activation *matchit-activate* 139 140 To use the matchit plugin add this line to your |vimrc|: > 141 packadd! matchit 142 143 The script should start working the next time you start Vim. 144 145 To use the matchit plugin after Vim has started, execute this command: > 146 packadd matchit 147 148 (Earlier versions of the script did nothing unless a |buffer-variable| named 149 |b:match_words| was defined. Even earlier versions contained autocommands 150 that set this variable for various file types. Now, |b:match_words| is 151 defined in many of the default |filetype-plugin|s instead.) 152 153 For a new language, you can add autocommands to the script or to your vimrc 154 file, but the recommended method is to add a line such as > 155 let b:match_words = '\<foo\>:\<bar\>' 156 to the |filetype-plugin| for your language. See |b:match_words| below for how 157 this variable is interpreted. 158 159 TROUBLESHOOTING *matchit-troubleshoot* 160 161 The script should work in most installations of Vim. It may not work if Vim 162 was compiled with a minimal feature set, for example if the |+syntax| option 163 was not enabled. If your Vim has support for syntax compiled in, but you do 164 not have |syntax| highlighting turned on, matchit.vim should work, but it may 165 fail to skip matching groups in comments and strings. If the |filetype| 166 mechanism is turned off, the |b:match_words| variable will probably not be 167 defined automatically. 168 169 2.1 Temporarily disable the matchit plugin *matchit-disable* *:MatchDisable* 170 171 To temporarily disable the matchit plugin, after it has been loaded, 172 execute this command: > 173 :MatchDisable 174 175 This will delete all the defined key mappings to the Vim default. 176 Now the "%" command will work like before loading the plugin |%| 177 178 2.2 Re-enable the matchit plugin *:MatchEnable* 179 180 To re-enable the plugin, after it was disabled, use the following command: > 181 :MatchEnable 182 183 This will resetup the key mappings. 184 185 ============================================================================== 186 3. Configuration *matchit-configure* 187 188 There are several variables that govern the behavior of matchit.vim. Note 189 that these are variables local to the buffer, not options, so use |:let| to 190 define them, not |:set|. Some of these variables have values that matter; for 191 others, it only matters whether the variable has been defined. All of these 192 can be defined in the |filetype-plugin| or autocommand that defines 193 |b:match_words| or "on the fly." 194 195 The main variable is |b:match_words|. It is described in the section below on 196 supporting a new language. 197 198 *b:match_ignorecase* 199 If you > 200 :let b:match_ignorecase = 1 201 then matchit.vim acts as if 'ignorecase' is set: for example, "end" and "END" 202 are equivalent. If you > 203 :let b:match_ignorecase = 0 204 then matchit.vim treats "end" and "END" differently. (There will be no 205 b:match_infercase option unless someone requests it.) 206 207 *b:match_debug* 208 Define b:match_debug if you want debugging information to be saved. See 209 |matchit-debug|, below. 210 211 *b:match_skip* 212 If b:match_skip is defined, it is passed as the skip argument to 213 |searchpair()|. This controls when matching structures are skipped, or 214 ignored. By default, they are ignored inside comments and strings, as 215 determined by the |syntax| mechanism. (If syntax highlighting is turned off, 216 nothing is skipped.) You can set b:match_skip to a string, which evaluates to 217 a non-zero, numerical value if the match is to be skipped or zero if the match 218 should not be skipped. In addition, the following special values are 219 supported by matchit.vim: 220 s:foo becomes (current syntax item) =~ foo 221 S:foo becomes (current syntax item) !~ foo 222 r:foo becomes (line before cursor) =~ foo 223 R:foo becomes (line before cursor) !~ foo 224 (The "s" is meant to suggest "syntax", and the "r" is meant to suggest 225 "regular expression".) 226 227 Examples: 228 229 You can get the default behavior with > 230 :let b:match_skip = 's:comment\|string' 231 < 232 If you want to skip matching structures unless they are at the start 233 of the line (ignoring whitespace) then you can > 234 :let b:match_skip = 'R:^\s*' 235 < Do not do this if strings or comments can span several lines, since 236 the normal syntax checking will not be done if you set b:match_skip. 237 238 In LaTeX, since "%" is used as the comment character, you can > 239 :let b:match_skip = 'r:%' 240 < Unfortunately, this will skip anything after "\%", an escaped "%". To 241 allow for this, and also "\\%" (an escaped backslash followed by the 242 comment character) you can > 243 :let b:match_skip = 'r:\(^\|[^\\]\)\(\\\\\)*%' 244 < 245 See the $VIMRUNTIME/ftplugin/vim.vim for an example that uses both 246 syntax and a regular expression. 247 248 *b:match_function* 249 If b:match_function is defined, matchit.vim will first call this function to 250 perform matching. This is useful for languages with an indentation-based block 251 structure (such as Python) or other complex matching requirements that cannot 252 be expressed with regular expression patterns. 253 254 The function should accept one argument: 255 forward - 1 for forward search (% command) 256 0 for backward search (g% command) 257 258 The function should return a list with one of these values: 259 [line, col] - Match found at the specified position 260 [] - No match found; fall through to regular matching 261 (|b:match_words|, matchpairs, etc.) 262 263 The cursor position is not changed by the function; matchit handles cursor 264 movement based on the returned position. 265 266 If the function throws an error, matchit gives up and doesn't continue. 267 Enable |b:match_debug| to see error messages from custom match functions. 268 269 Python example (simplified): > 270 let s:keywords = {'if': 'elif\|else', 'elif': 'elif\|else'} 271 272 function! s:PythonMatch(forward) abort 273 let keyword = matchstr(getline('.'), '^\s*\zs\w\+') 274 let pattern = get(s:keywords, keyword, '') 275 if empty(pattern) | return [] | endif 276 277 " Forward-only. Backwards left as an exercise for the reader. 278 let [lnum, col] = searchpos('^\s*\%(' . pattern . '\)\>', 'nW' 0, 0, 279 \ 'indent(".") != ' . indent('.')) 280 return lnum > 0 ? [lnum, col] : [] 281 endfunction 282 283 let b:match_function = function('s:PythonMatch') 284 < 285 See |matchit-newlang| below for more details on supporting new languages. 286 287 ============================================================================== 288 4. Supporting a New Language *matchit-newlang* 289 *b:match_words* 290 In order for matchit.vim to support a new language, you must define a suitable 291 pattern for |b:match_words|. You may also want to set some of the 292 |matchit-configure| variables, as described above. If your language has a 293 complicated syntax, or many keywords, you will need to know something about 294 Vim's |regular-expression|s. 295 296 The format for |b:match_words| is similar to that of the 'matchpairs' option: 297 it is a comma (,)-separated list of groups; each group is a colon(:)-separated 298 list of patterns (regular expressions). Commas and colons that are part of a 299 pattern should be escaped with backslashes ('\:' and '\,'). It is OK to have 300 only one group; the effect is undefined if a group has only one pattern. 301 A simple example is > 302 :let b:match_words = '\<if\>:\<endif\>,' 303 \ . '\<while\>:\<continue\>:\<break\>:\<endwhile\>' 304 (In Vim regular expressions, |\<| and |\>| denote word boundaries. Thus "if" 305 matches the end of "endif" but "\<if\>" does not.) Then banging on the "%" 306 key will bounce the cursor between "if" and the matching "endif"; and from 307 "while" to any matching "continue" or "break", then to the matching "endwhile" 308 and back to the "while". It is almost always easier to use |literal-string|s 309 (single quotes) as above: '\<if\>' rather than "\\<if\\>" and so on. 310 311 Exception: If the ":" character does not appear in b:match_words, then it is 312 treated as an expression to be evaluated. For example, > 313 :let b:match_words = 'GetMatchWords()' 314 allows you to define a function. This can return a different string depending 315 on the current syntax, for example. 316 317 Once you have defined the appropriate value of |b:match_words|, you will 318 probably want to have this set automatically each time you edit the 319 appropriate file type. The recommended way to do this is by adding the 320 definition to a |filetype-plugin| file. 321 322 Tips: Be careful that your initial pattern does not match your final pattern. 323 See the example above for the use of word-boundary expressions. It is usually 324 better to use ".\{-}" (as many as necessary) instead of ".*" (as many as 325 possible). See |\{-|. For example, in the string "<tag>label</tag>", "<.*>" 326 matches the whole string whereas "<.\{-}>" and "<[^>]*>" match "<tag>" and 327 "</tag>". 328 329 *matchit-spaces* *matchit-s:notend* 330 If "if" is to be paired with "end if" (Note the space!) then word boundaries 331 are not enough. Instead, define a regular expression s:notend that will match 332 anything but "end" and use it as follows: > 333 :let s:notend = '\%(\<end\s\+\)\@<!' 334 :let b:match_words = s:notend . '\<if\>:\<end\s\+if\>' 335 < *matchit-s:sol* 336 This is a simplified version of what is done for Ada. The s:notend is a 337 |script-variable|. Similarly, you may want to define a start-of-line regular 338 expression > 339 :let s:sol = '\%(^\|;\)\s*' 340 if keywords are only recognized after the start of a line or after a 341 semicolon (;), with optional white space. 342 343 *matchit-backref* 344 In any group, the expressions |\1|, |\2|, ..., |\9| refer to parts of the 345 INITIAL pattern enclosed in |\(|escaped parentheses|\)|. These are referred 346 to as back references, or backrefs. For example, > 347 :let b:match_words = '\<b\(o\+\)\>:\(h\)\1\>' 348 means that "bo" pairs with "ho" and "boo" pairs with "hoo" and so on. Note 349 that "\1" does not refer to the "\(h\)" in this example. If you have 350 "\(nested \(parentheses\)\) then "\d" refers to the d-th "\(" and everything 351 up to and including the matching "\)": in "\(nested\(parentheses\)\)", "\1" 352 refers to everything and "\2" refers to "\(parentheses\)". If you use a 353 variable such as |s:notend| or |s:sol| in the previous paragraph then remember 354 to count any "\(" patterns in this variable. You do not have to count groups 355 defined by |\%(\)|. 356 357 It should be possible to resolve back references from any pattern in the 358 group. For example, > 359 :let b:match_words = '\(foo\)\(bar\):more\1:and\2:end\1\2' 360 would not work because "\2" cannot be determined from "morefoo" and "\1" 361 cannot be determined from "andbar". On the other hand, > 362 :let b:match_words = '\(\(foo\)\(bar\)\):\3\2:end\1' 363 should work (and have the same effect as "foobar:barfoo:endfoobar"), although 364 this has not been thoroughly tested. 365 366 You can use |zero-width| patterns such as |\@<=| and |\zs|. (The latter has 367 not been thoroughly tested in matchit.vim.) For example, if the keyword "if" 368 must occur at the start of the line, with optional white space, you might use 369 the pattern "\(^\s*\)\@<=if" so that the cursor will end on the "i" instead of 370 at the start of the line. For another example, if HTML had only one tag then 371 one could > 372 :let b:match_words = '<:>,<\@<=tag>:<\@<=/tag>' 373 so that "%" can bounce between matching "<" and ">" pairs or (starting on 374 "tag" or "/tag") between matching tags. Without the |\@<=|, the script would 375 bounce from "tag" to the "<" in "</tag>", and another "%" would not take you 376 back to where you started. 377 378 DEBUGGING *matchit-debug* *:MatchDebug* 379 380 If you are having trouble figuring out the appropriate definition of 381 |b:match_words| then you can take advantage of the same information I use when 382 debugging the script. This is especially true if you are not sure whether 383 your patterns or my script are at fault! To make this more convenient, I have 384 made the command :MatchDebug, which defines the variable |b:match_debug| and 385 creates a Matchit menu. This menu makes it convenient to check the values of 386 the variables described below. You will probably also want to read 387 |matchit-details| above. 388 389 Defining the variable |b:match_debug| causes the script to set the following 390 variables, each time you hit the "%" key. Several of these are only defined 391 if |b:match_words| includes |backref|s. 392 393 *b:match_pat* 394 The b:match_pat variable is set to |b:match_words| with |backref|s parsed. 395 *b:match_match* 396 The b:match_match variable is set to the bit of text that is recognized as a 397 match. 398 *b:match_col* 399 The b:match_col variable is set to the cursor column of the start of the 400 matching text. 401 *b:match_wholeBR* 402 The b:match_wholeBR variable is set to the comma-separated group of patterns 403 that matches, with |backref|s unparsed. 404 *b:match_iniBR* 405 The b:match_iniBR variable is set to the first pattern in |b:match_wholeBR|. 406 *b:match_ini* 407 The b:match_ini variable is set to the first pattern in |b:match_wholeBR|, 408 with |backref|s resolved from |b:match_match|. 409 *b:match_tail* 410 The b:match_tail variable is set to the remaining patterns in 411 |b:match_wholeBR|, with |backref|s resolved from |b:match_match|. 412 *b:match_word* 413 The b:match_word variable is set to the pattern from |b:match_wholeBR| that 414 matches |b:match_match|. 415 *b:match_table* 416 The back reference '\'.d refers to the same thing as '\'.b:match_table[d] in 417 |b:match_word|. 418 419 ============================================================================== 420 5. Known Bugs and Limitations *matchit-bugs* 421 422 Repository: https://github.com/chrisbra/matchit/ 423 Bugs can be reported at the repository and the latest development snapshot can 424 also be downloaded there. 425 426 Just because I know about a bug does not mean that it is on my todo list. I 427 try to respond to reports of bugs that cause real problems. If it does not 428 cause serious problems, or if there is a work-around, a bug may sit there for 429 a while. Moral: if a bug (known or not) bothers you, let me know. 430 431 It would be nice if "\0" were recognized as the entire pattern. That is, it 432 would be nice if "foo:\end\0" had the same effect as "\(foo\):\end\1". I may 433 try to implement this in a future version. (This is not so easy to arrange as 434 you might think!) 435 436 ============================================================================== 437 vim:tw=78:ts=8:fo=tcq2:ft=help: