robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

zeertzjqvim-patch:e9f8e0f: runtime(matchit): Update matchit plugin (#40085)dcf36e613b

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