vim

Fork of vim, an acceptable text editor
git clone git://git.laack.co/vim.git
Log | Files | Refs | README | LICENSE

matchit.vim (30636B)


      1 "  matchit.vim: (global plugin) Extended "%" matching
      2 "  autload script of matchit plugin, see ../plugin/matchit.vim
      3 "  Last Change: June 01, 2026
      4 
      5 " Neovim does not support scriptversion
      6 if has("vimscript-4")
      7   scriptversion 4
      8 endif
      9 
     10 let s:last_mps = ""
     11 let s:last_words = ":"
     12 let s:patBR = ""
     13 
     14 let s:save_cpo = &cpo
     15 set cpo&vim
     16 
     17 " Auto-complete mappings:  (not yet "ready for prime time")
     18 " TODO Read :help write-plugin for the "right" way to let the user
     19 " specify a key binding.
     20 "   let g:match_auto = '<C-]>'
     21 "   let g:match_autoCR = '<C-CR>'
     22 " if exists("g:match_auto")
     23 "   execute "inoremap " . g:match_auto . ' x<Esc>"=<SID>Autocomplete()<CR>Pls'
     24 " endif
     25 " if exists("g:match_autoCR")
     26 "   execute "inoremap " . g:match_autoCR . ' <CR><C-R>=<SID>Autocomplete()<CR>'
     27 " endif
     28 " if exists("g:match_gthhoh")
     29 "   execute "inoremap " . g:match_gthhoh . ' <C-O>:call <SID>Gthhoh()<CR>'
     30 " endif " gthhoh = "Get the heck out of here!"
     31 
     32 let s:notslash = '\\\@1<!\%(\\\\\)*'
     33 
     34 function s:RestoreOptions()
     35   " In s:CleanUp(), :execute "set" restore_options .
     36   let restore_options = ""
     37   if get(b:, 'match_ignorecase', &ic) != &ic
     38     let restore_options ..= (&ic ? " " : " no") .. "ignorecase"
     39     let &ignorecase = b:match_ignorecase
     40   endif
     41   if &ve != ''
     42     let restore_options = " ve=" .. &ve .. restore_options
     43     set ve=
     44   endif
     45   if &smartcase
     46     let restore_options = " smartcase " .. restore_options
     47     set nosmartcase
     48   endif
     49   return restore_options
     50 endfunction
     51 
     52 function matchit#Match_wrapper(word, forward, mode) range
     53   let restore_options = s:RestoreOptions()
     54   " In s:CleanUp(), we may need to check whether the cursor moved forward.
     55   let startpos = [line("."), col(".")]
     56   " if a count has been applied, use the default [count]% mode (see :h N%)
     57   if v:count
     58     exe "normal! " .. v:count .. "%"
     59     return s:CleanUp(restore_options, a:mode, startpos)
     60   end
     61   if a:mode =~# "v" && mode(1) =~# 'ni'
     62     exe "norm! gv"
     63   elseif a:mode == "o" && mode(1) !~# '[vV]'
     64     exe "norm! v"
     65   " If this function was called from Visual mode, make sure that the cursor
     66   " is at the correct end of the Visual range:
     67   elseif a:mode == "v"
     68     execute "normal! gv\<Esc>"
     69     let startpos = [line("."), col(".")]
     70   endif
     71 
     72   " Check for custom match function hook
     73   if exists("b:match_function")
     74     try
     75       let result = call(b:match_function, [a:forward])
     76       if !empty(result)
     77         call cursor(result)
     78         return s:CleanUp(restore_options, a:mode, startpos)
     79       endif
     80     catch /.*/
     81       if exists("b:match_debug")
     82         echohl WarningMsg
     83         echom 'matchit: b:match_function error: ' .. v:exception
     84         echohl NONE
     85       endif
     86       return s:CleanUp(restore_options, a:mode, startpos)
     87     endtry
     88     " Empty result: fall through to regular matching
     89   endif
     90 
     91   " First step:  if not already done, set the script variables
     92   "   s:do_BR   flag for whether there are backrefs
     93   "   s:pat     parsed version of b:match_words
     94   "   s:all     regexp based on s:pat and the default groups
     95   if !exists("b:match_words") || b:match_words == ""
     96     let match_words = ""
     97   elseif b:match_words =~ ":"
     98     let match_words = b:match_words
     99   else
    100     " Allow b:match_words = "GetVimMatchWords()" .
    101     execute "let match_words =" b:match_words
    102   endif
    103 " Thanks to Preben "Peppe" Guldberg and Bram Moolenaar for this suggestion!
    104   if (match_words != s:last_words) || (&mps != s:last_mps)
    105       \ || exists("b:match_debug")
    106     let s:last_mps = &mps
    107     " quote the special chars in 'matchpairs', replace [,:] with \| and then
    108     " append the builtin pairs (/*, */, #if, #ifdef, #ifndef, #else, #elif,
    109     " #elifdef, #elifndef, #endif)
    110     let default = escape(&mps, '[$^.*~\\/?]') .. (strlen(&mps) ? "," : "") ..
    111       \ '\/\*:\*\/,#\s*if\%(n\=def\)\=:#\s*else\>:#\s*elif\%(n\=def\)\=\>:#\s*endif\>'
    112     " s:all = pattern with all the keywords
    113     let match_words = s:Append(match_words, default)
    114     let s:last_words = match_words
    115     if match_words !~ s:notslash .. '\\\d'
    116       let s:do_BR = 0
    117       let s:pat = match_words
    118     else
    119       let s:do_BR = 1
    120       let s:pat = s:ParseWords(match_words)
    121     endif
    122     let s:all = substitute(s:pat, s:notslash .. '\zs[,:]\+', '\\|', 'g')
    123     " un-escape \, and \: to , and :
    124     let s:all = substitute(s:all, s:notslash .. '\zs\\\(:\|,\)', '\1', 'g')
    125     " Just in case there are too many '\(...)' groups inside the pattern, make
    126     " sure to use \%(...) groups, so that error E872 can be avoided
    127     let s:all = substitute(s:all, s:notslash .. '\zs\\(', '\\%(', 'g')
    128     let s:all = '\%(' .. s:all .. '\)'
    129     if exists("b:match_debug")
    130       let b:match_pat = s:pat
    131     endif
    132     " Reconstruct the version with unresolved backrefs.
    133     let s:patBR = substitute(match_words .. ',',
    134       \ s:notslash .. '\zs[,:]*,[,:]*', ',', 'g')
    135     let s:patBR = substitute(s:patBR, s:notslash .. '\zs:\{2,}', ':', 'g')
    136     " un-escape \, to ,
    137     let s:patBR = substitute(s:patBR, '\\,', ',', 'g')
    138   endif
    139 
    140   " Second step:  set the following local variables:
    141   "     matchline = line on which the cursor started
    142   "     curcol    = number of characters before match
    143   "     prefix    = regexp for start of line to start of match
    144   "     suffix    = regexp for end of match to end of line
    145   " Require match to end on or after the cursor and prefer it to
    146   " start on or before the cursor.
    147   let matchline = getline(startpos[0])
    148   if a:word != ''
    149     " word given
    150     if a:word !~ s:all
    151       echohl WarningMsg|echo 'Missing rule for word:"'.a:word.'"'|echohl NONE
    152       return s:CleanUp(restore_options, a:mode, startpos)
    153     endif
    154     let matchline = a:word
    155     let curcol = 0
    156     let prefix = '^\%('
    157     let suffix = '\)$'
    158   " Now the case when "word" is not given
    159   else  " Find the match that ends on or after the cursor and set curcol.
    160     let regexp = s:Wholematch(matchline, s:all, startpos[1]-1)
    161     let curcol = match(matchline, regexp)
    162     " If there is no match, give up.
    163     if curcol == -1
    164       return s:CleanUp(restore_options, a:mode, startpos)
    165     endif
    166     let endcol = matchend(matchline, regexp)
    167     let suf = strlen(matchline) - endcol
    168     let prefix = (curcol ? '^.*\%' .. (curcol + 1) .. 'c\%(' : '^\%(')
    169     let suffix = (suf ? '\)\%' .. (endcol + 1) .. 'c.*$'  : '\)$')
    170   endif
    171   if exists("b:match_debug")
    172     let b:match_match = matchstr(matchline, regexp)
    173     let b:match_col = curcol+1
    174   endif
    175 
    176   " Third step:  Find the group and single word that match, and the original
    177   " (backref) versions of these.  Then, resolve the backrefs.
    178   " Set the following local variable:
    179   " group = colon-separated list of patterns, one of which matches
    180   "       = ini:mid:fin or ini:fin
    181   "
    182   " Now, set group and groupBR to the matching group: 'if:endif' or
    183   " 'while:endwhile' or whatever.  A bit of a kluge:  s:Choose() returns
    184   " group . "," . groupBR, and we pick it apart.
    185   let group = s:Choose(s:pat, matchline, ",", ":", prefix, suffix, s:patBR)
    186   let i = matchend(group, s:notslash .. ",")
    187   let groupBR = strpart(group, i)
    188   let group = strpart(group, 0, i-1)
    189   " Now, matchline =~ prefix . substitute(group,':','\|','g') . suffix
    190   if s:do_BR " Do the hard part:  resolve those backrefs!
    191     let group = s:InsertRefs(groupBR, prefix, group, suffix, matchline)
    192   endif
    193   if exists("b:match_debug")
    194     let b:match_wholeBR = groupBR
    195     let i = matchend(groupBR, s:notslash .. ":")
    196     let b:match_iniBR = strpart(groupBR, 0, i-1)
    197   endif
    198 
    199   " Fourth step:  Set the arguments for searchpair().
    200   let i = matchend(group, s:notslash .. ":")
    201   let j = matchend(group, '.*' .. s:notslash .. ":")
    202   let ini = strpart(group, 0, i-1)
    203   let mid = substitute(strpart(group, i,j-i-1), s:notslash .. '\zs:', '\\|', 'g')
    204   let fin = strpart(group, j)
    205   "Un-escape the remaining , and : characters.
    206   let ini = substitute(ini, s:notslash .. '\zs\\\(:\|,\)', '\1', 'g')
    207   let mid = substitute(mid, s:notslash .. '\zs\\\(:\|,\)', '\1', 'g')
    208   let fin = substitute(fin, s:notslash .. '\zs\\\(:\|,\)', '\1', 'g')
    209   " searchpair() requires that these patterns avoid \(\) groups.
    210   let ini = substitute(ini, s:notslash .. '\zs\\(', '\\%(', 'g')
    211   let mid = substitute(mid, s:notslash .. '\zs\\(', '\\%(', 'g')
    212   let fin = substitute(fin, s:notslash .. '\zs\\(', '\\%(', 'g')
    213   " Set mid.  This is optimized for readability, not micro-efficiency!
    214   if a:forward && matchline =~ prefix .. fin .. suffix
    215     \ || !a:forward && matchline =~ prefix .. ini .. suffix
    216     let mid = ""
    217   endif
    218   " Set flag.  This is optimized for readability, not micro-efficiency!
    219   if a:forward && matchline =~ prefix .. fin .. suffix
    220     \ || !a:forward && matchline !~ prefix .. ini .. suffix
    221     let flag = "bW"
    222   else
    223     let flag = "W"
    224   endif
    225   " Set skip.
    226   if exists("b:match_skip")
    227     let skip = b:match_skip
    228   elseif exists("b:match_comment") " backwards compatibility and testing!
    229     let skip = "r:" .. b:match_comment
    230   else
    231     let skip = 's:comment\|string'
    232   endif
    233   let skip = s:ParseSkip(skip)
    234   if exists("b:match_debug")
    235     let b:match_ini = ini
    236     let b:match_tail = (strlen(mid) ? mid .. '\|' : '') .. fin
    237   endif
    238 
    239   " Fifth step:  actually start moving the cursor and call searchpair().
    240   " Later, :execute restore_cursor to get to the original screen.
    241   let view = winsaveview()
    242   call cursor(0, curcol + 1)
    243   if skip =~ 'synID' && !(has("syntax") && exists("g:syntax_on"))
    244     let skip = "0"
    245   else
    246     execute "if " .. skip .. "| let skip = '0' | endif"
    247   endif
    248   let sp_return = searchpair(ini, mid, fin, flag, skip)
    249   if &selection isnot# 'inclusive' && a:mode == 'v'
    250     " move cursor one pos to the right, because selection is not inclusive
    251     " add virtualedit=onemore, to make it work even when the match ends the
    252     " line
    253     if !(col('.') < col('$')-1)
    254       let eolmark=1 " flag to set a mark on eol (since we cannot move there)
    255     endif
    256     norm! l
    257   endif
    258   let final_position = "call cursor(" .. line(".") .. "," .. col(".") .. ")"
    259   " Restore cursor position and original screen.
    260   call winrestview(view)
    261   normal! m'
    262   if sp_return > 0
    263     execute final_position
    264   endif
    265   if exists('eolmark') && eolmark
    266     call setpos("''", [0, line('.'), col('$'), 0]) " set mark on the eol
    267   endif
    268   return s:CleanUp(restore_options, a:mode, startpos, mid .. '\|' .. fin)
    269 endfun
    270 
    271 " Restore options and do some special handling for Operator-pending mode.
    272 " The optional argument is the tail of the matching group.
    273 fun! s:CleanUp(options, mode, startpos, ...)
    274   if strlen(a:options)
    275     execute "set" a:options
    276   endif
    277   " Open folds, if appropriate.
    278   if a:mode != "o"
    279     if &foldopen =~ "percent"
    280       normal! zv
    281     endif
    282     " In Operator-pending mode, we want to include the whole match
    283     " (for example, d%).
    284     " This is only a problem if we end up moving in the forward direction.
    285   elseif (a:startpos[0] < line(".")) ||
    286         \ (a:startpos[0] == line(".") && a:startpos[1] < col("."))
    287     if a:0
    288       " Check whether the match is a single character.  If not, move to the
    289       " end of the match.
    290       let matchline = getline(".")
    291       let currcol = col(".")
    292       let regexp = s:Wholematch(matchline, a:1, currcol-1)
    293       let endcol = matchend(matchline, regexp)
    294       if endcol > currcol  " This is NOT off by one!
    295         call cursor(0, endcol)
    296       endif
    297     endif " a:0
    298   endif " a:mode != "o" && etc.
    299   return 0
    300 endfun
    301 
    302 " Example (simplified HTML patterns):  if
    303 "   a:groupBR   = '<\(\k\+\)>:</\1>'
    304 "   a:prefix    = '^.\{3}\('
    305 "   a:group     = '<\(\k\+\)>:</\(\k\+\)>'
    306 "   a:suffix    = '\).\{2}$'
    307 "   a:matchline =  "123<tag>12" or "123</tag>12"
    308 " then extract "tag" from a:matchline and return "<tag>:</tag>" .
    309 fun! s:InsertRefs(groupBR, prefix, group, suffix, matchline)
    310   if a:matchline !~ a:prefix ..
    311     \ substitute(a:group, s:notslash .. '\zs:', '\\|', 'g') .. a:suffix
    312     return a:group
    313   endif
    314   let i = matchend(a:groupBR, s:notslash .. ':')
    315   let ini = strpart(a:groupBR, 0, i-1)
    316   let tailBR = strpart(a:groupBR, i)
    317   let word = s:Choose(a:group, a:matchline, ":", "", a:prefix, a:suffix,
    318     \ a:groupBR)
    319   let i = matchend(word, s:notslash .. ":")
    320   let wordBR = strpart(word, i)
    321   let word = strpart(word, 0, i-1)
    322   " Now, a:matchline =~ a:prefix . word . a:suffix
    323   if wordBR != ini
    324     let table = s:Resolve(ini, wordBR, "table")
    325   else
    326     let table = ""
    327     let d = 0
    328     while d < 10
    329       if tailBR =~ s:notslash .. '\\' .. d
    330         let table = table .. d
    331       else
    332         let table = table .. "-"
    333       endif
    334       let d = d + 1
    335     endwhile
    336   endif
    337   let d = 9
    338   while d
    339     if table[d] != "-"
    340       let backref = substitute(a:matchline, a:prefix .. word .. a:suffix,
    341         \ '\' .. table[d], "")
    342       " escape magic pattern metacharacters and matchit special characters [,:]
    343       let backref = escape(backref, '\.*[^$~,:')
    344       execute s:Ref(ini, d, "start", "len")
    345       let ini = strpart(ini, 0, start) .. backref .. strpart(ini, start+len)
    346       let tailBR = substitute(tailBR, s:notslash .. '\zs\\' .. d,
    347         \ escape(backref, '\\&'), 'g')
    348     endif
    349     let d = d-1
    350   endwhile
    351   if exists("b:match_debug")
    352     if s:do_BR
    353       let b:match_table = table
    354       let b:match_word = word
    355     else
    356       let b:match_table = ""
    357       let b:match_word = ""
    358     endif
    359   endif
    360   return ini .. ":" .. tailBR
    361 endfun
    362 
    363 " String append item2 to item and add ',' in between items
    364 fun! s:Append(item, item2)
    365   if a:item == ''
    366     return a:item2
    367   endif
    368   " there is already a trailing comma, don't add another one
    369   if a:item[-1:] == ','
    370     return a:item .. a:item2
    371   endif
    372   return a:item .. ',' .. a:item2
    373 endfun
    374 
    375 " Input a comma-separated list of groups with backrefs, such as
    376 "   a:groups = '\(foo\):end\1,\(bar\):end\1'
    377 " and return a comma-separated list of groups with backrefs replaced:
    378 "   return '\(foo\):end\(foo\),\(bar\):end\(bar\)'
    379 fun! s:ParseWords(groups)
    380   let groups = substitute(a:groups .. ",", s:notslash .. '\zs[,:]*,[,:]*', ',', 'g')
    381   let groups = substitute(groups, s:notslash .. '\zs:\{2,}', ':', 'g')
    382   let parsed = ""
    383   while groups =~ '[^,:]'
    384     let i = matchend(groups, s:notslash .. ':')
    385     let j = matchend(groups, s:notslash .. ',')
    386     let ini = strpart(groups, 0, i-1)
    387     let tail = strpart(groups, i, j-i-1) .. ":"
    388     let groups = strpart(groups, j)
    389     let parsed = parsed .. ini
    390     let i = matchend(tail, s:notslash .. ':')
    391     while i != -1
    392       " In 'if:else:endif', ini='if' and word='else' and then word='endif'.
    393       let word = strpart(tail, 0, i-1)
    394       let tail = strpart(tail, i)
    395       let i = matchend(tail, s:notslash .. ':')
    396       let parsed = parsed .. ":" .. s:Resolve(ini, word, "word")
    397     endwhile " Now, tail has been used up.
    398     let parsed = parsed .. ","
    399   endwhile " groups =~ '[^,:]'
    400   let parsed = substitute(parsed, ',$', '', '')
    401   return parsed
    402 endfun
    403 
    404 " TODO I think this can be simplified and/or made more efficient.
    405 " TODO What should I do if a:start is out of range?
    406 " Return a regexp that matches all of a:string, such that
    407 " matchstr(a:string, regexp) represents the match for a:pat that starts
    408 " as close to a:start as possible, before being preferred to after, and
    409 " ends after a:start .
    410 " Usage:
    411 " let regexp = s:Wholematch(getline("."), 'foo\|bar', col(".")-1)
    412 " let i      = match(getline("."), regexp)
    413 " let j      = matchend(getline("."), regexp)
    414 " let match  = matchstr(getline("."), regexp)
    415 fun! s:Wholematch(string, pat, start)
    416   let group = '\%(' .. a:pat .. '\)'
    417   let prefix = (a:start ? '\(^.*\%<' .. (a:start + 2) .. 'c\)\zs' : '^')
    418   let len = strlen(a:string)
    419   let suffix = (a:start+1 < len ? '\(\%>' .. (a:start+1) .. 'c.*$\)\@=' : '$')
    420   if a:string !~ prefix .. group .. suffix
    421     let prefix = ''
    422   endif
    423   return prefix .. group .. suffix
    424 endfun
    425 
    426 " No extra arguments:  s:Ref(string, d) will
    427 " find the d'th occurrence of '\(' and return it, along with everything up
    428 " to and including the matching '\)'.
    429 " One argument:  s:Ref(string, d, "start") returns the index of the start
    430 " of the d'th '\(' and any other argument returns the length of the group.
    431 " Two arguments:  s:Ref(string, d, "foo", "bar") returns a string to be
    432 " executed, having the effect of
    433 "   :let foo = s:Ref(string, d, "start")
    434 "   :let bar = s:Ref(string, d, "len")
    435 fun! s:Ref(string, d, ...)
    436   let len = strlen(a:string)
    437   if a:d == 0
    438     let start = 0
    439   else
    440     let cnt = a:d
    441     let match = a:string
    442     while cnt
    443       let cnt = cnt - 1
    444       let index = matchend(match, s:notslash .. '\\(')
    445       if index == -1
    446         return ""
    447       endif
    448       let match = strpart(match, index)
    449     endwhile
    450     let start = len - strlen(match)
    451     if a:0 == 1 && a:1 == "start"
    452       return start - 2
    453     endif
    454     let cnt = 1
    455     while cnt
    456       let index = matchend(match, s:notslash .. '\\(\|\\)') - 1
    457       if index == -2
    458         return ""
    459       endif
    460       " Increment if an open, decrement if a ')':
    461       let cnt = cnt + (match[index]=="(" ? 1 : -1)  " ')'
    462       let match = strpart(match, index+1)
    463     endwhile
    464     let start = start - 2
    465     let len = len - start - strlen(match)
    466   endif
    467   if a:0 == 1
    468     return len
    469   elseif a:0 == 2
    470     return "let " .. a:1 .. "=" .. start .. "| let " .. a:2 .. "=" .. len
    471   else
    472     return strpart(a:string, start, len)
    473   endif
    474 endfun
    475 
    476 " Count the number of disjoint copies of pattern in string.
    477 " If the pattern is a literal string and contains no '0' or '1' characters
    478 " then s:Count(string, pattern, '0', '1') should be faster than
    479 " s:Count(string, pattern).
    480 fun! s:Count(string, pattern, ...)
    481   let pat = escape(a:pattern, '\\')
    482   if a:0 > 1
    483     let foo = substitute(a:string, '[^' .. a:pattern .. ']', "a:1", "g")
    484     let foo = substitute(a:string, pat, a:2, "g")
    485     let foo = substitute(foo, '[^' .. a:2 .. ']', "", "g")
    486     return strlen(foo)
    487   endif
    488   let result = 0
    489   let foo = a:string
    490   let index = matchend(foo, pat)
    491   while index != -1
    492     let result = result + 1
    493     let foo = strpart(foo, index)
    494     let index = matchend(foo, pat)
    495   endwhile
    496   return result
    497 endfun
    498 
    499 " s:Resolve('\(a\)\(b\)', '\(c\)\2\1\1\2') should return table.word, where
    500 " word = '\(c\)\(b\)\(a\)\3\2' and table = '-32-------'.  That is, the first
    501 " '\1' in target is replaced by '\(a\)' in word, table[1] = 3, and this
    502 " indicates that all other instances of '\1' in target are to be replaced
    503 " by '\3'.  The hard part is dealing with nesting...
    504 " Note that ":" is an illegal character for source and target,
    505 " unless it is preceded by "\".
    506 fun! s:Resolve(source, target, output)
    507   let word = a:target
    508   let i = matchend(word, s:notslash .. '\\\d') - 1
    509   let table = "----------"
    510   while i != -2 " There are back references to be replaced.
    511     let d = word[i]
    512     let backref = s:Ref(a:source, d)
    513     " The idea is to replace '\d' with backref.  Before we do this,
    514     " replace any \(\) groups in backref with :1, :2, ... if they
    515     " correspond to the first, second, ... group already inserted
    516     " into backref.  Later, replace :1 with \1 and so on.  The group
    517     " number w+b within backref corresponds to the group number
    518     " s within a:source.
    519     " w = number of '\(' in word before the current one
    520     let w = s:Count(
    521     \ substitute(strpart(word, 0, i-1), '\\\\', '', 'g'), '\(', '1')
    522     let b = 1 " number of the current '\(' in backref
    523     let s = d " number of the current '\(' in a:source
    524     while b <= s:Count(substitute(backref, '\\\\', '', 'g'), '\(', '1')
    525     \ && s < 10
    526       if table[s] == "-"
    527         if w + b < 10
    528           " let table[s] = w + b
    529           let table = strpart(table, 0, s) .. (w+b) .. strpart(table, s+1)
    530         endif
    531         let b = b + 1
    532         let s = s + 1
    533       else
    534         execute s:Ref(backref, b, "start", "len")
    535         let ref = strpart(backref, start, len)
    536         let backref = strpart(backref, 0, start) .. ":" .. table[s]
    537         \ .. strpart(backref, start+len)
    538         let s = s + s:Count(substitute(ref, '\\\\', '', 'g'), '\(', '1')
    539       endif
    540     endwhile
    541     let word = strpart(word, 0, i-1) .. backref .. strpart(word, i+1)
    542     let i = matchend(word, s:notslash .. '\\\d') - 1
    543   endwhile
    544   let word = substitute(word, s:notslash .. '\zs:', '\\', 'g')
    545   if a:output == "table"
    546     return table
    547   elseif a:output == "word"
    548     return word
    549   else
    550     return table .. word
    551   endif
    552 endfun
    553 
    554 " Assume a:comma = ",".  Then the format for a:patterns and a:1 is
    555 "   a:patterns = "<pat1>,<pat2>,..."
    556 "   a:1 = "<alt1>,<alt2>,..."
    557 " If <patn> is the first pattern that matches a:string then return <patn>
    558 " if no optional arguments are given; return <patn>,<altn> if a:1 is given.
    559 fun! s:Choose(patterns, string, comma, branch, prefix, suffix, ...)
    560   let tail = (a:patterns =~ a:comma .. "$" ? a:patterns : a:patterns .. a:comma)
    561   let i = matchend(tail, s:notslash .. a:comma)
    562   if a:0
    563     let alttail = (a:1 =~ a:comma .. "$" ? a:1 : a:1 .. a:comma)
    564     let j = matchend(alttail, s:notslash .. a:comma)
    565   endif
    566   let current = strpart(tail, 0, i-1)
    567   if a:branch == ""
    568     let currpat = current
    569   else
    570     let currpat = substitute(current, s:notslash .. a:branch, '\\|', 'g')
    571   endif
    572   " un-escape \, and \: to , and :
    573   let currpat = substitute(currpat, s:notslash .. '\zs\\\(:\|,\)', '\1', 'g')
    574   while a:string !~ a:prefix .. currpat .. a:suffix
    575     let tail = strpart(tail, i)
    576     let i = matchend(tail, s:notslash .. a:comma)
    577     if i == -1
    578       return -1
    579     endif
    580     let current = strpart(tail, 0, i-1)
    581     if a:branch == ""
    582       let currpat = current
    583     else
    584       let currpat = substitute(current, s:notslash .. a:branch, '\\|', 'g')
    585     endif
    586     " un-escape \, and \: to , and :
    587     let currpat = substitute(currpat, s:notslash .. '\zs\\\(:\|,\)', '\1', 'g')
    588     if a:0
    589       let alttail = strpart(alttail, j)
    590       let j = matchend(alttail, s:notslash .. a:comma)
    591     endif
    592   endwhile
    593   if a:0
    594     let current = current .. a:comma .. strpart(alttail, 0, j-1)
    595   endif
    596   return current
    597 endfun
    598 
    599 fun! matchit#Match_debug()
    600   let b:match_debug = 1 " Save debugging information.
    601   " pat = all of b:match_words with backrefs parsed
    602   amenu &Matchit.&pat   :echo b:match_pat<CR>
    603   " match = bit of text that is recognized as a match
    604   amenu &Matchit.&match :echo b:match_match<CR>
    605   " curcol = cursor column of the start of the matching text
    606   amenu &Matchit.&curcol        :echo b:match_col<CR>
    607   " wholeBR = matching group, original version
    608   amenu &Matchit.wh&oleBR       :echo b:match_wholeBR<CR>
    609   " iniBR = 'if' piece, original version
    610   amenu &Matchit.ini&BR :echo b:match_iniBR<CR>
    611   " ini = 'if' piece, with all backrefs resolved from match
    612   amenu &Matchit.&ini   :echo b:match_ini<CR>
    613   " tail = 'else\|endif' piece, with all backrefs resolved from match
    614   amenu &Matchit.&tail  :echo b:match_tail<CR>
    615   " fin = 'endif' piece, with all backrefs resolved from match
    616   amenu &Matchit.&word  :echo b:match_word<CR>
    617   " '\'.d in ini refers to the same thing as '\'.table[d] in word.
    618   amenu &Matchit.t&able :echo '0:' .. b:match_table .. ':9'<CR>
    619 endfun
    620 
    621 " Jump to the nearest unmatched "(" or "if" or "<tag>" if a:spflag == "bW"
    622 " or the nearest unmatched "</tag>" or "endif" or ")" if a:spflag == "W".
    623 " Return a "mark" for the original position, so that
    624 "   let m = MultiMatch("bW", "n") ... call winrestview(m)
    625 " will return to the original position.  If there is a problem, do not
    626 " move the cursor and return {}, unless a count is given, in which case
    627 " go up or down as many levels as possible and again return {}.
    628 " TODO This relies on the same patterns as % matching.  It might be a good
    629 " idea to give it its own matching patterns.
    630 fun! matchit#MultiMatch(spflag, mode)
    631   let restore_options = s:RestoreOptions()
    632   let startpos = [line("."), col(".")]
    633   " save v:count1 variable, might be reset from the restore_cursor command
    634   let level = v:count1
    635   if a:mode == "o" && mode(1) !~# '[vV]'
    636     exe "norm! v"
    637   endif
    638 
    639   " First step:  if not already done, set the script variables
    640   "   s:do_BR   flag for whether there are backrefs
    641   "   s:pat     parsed version of b:match_words
    642   "   s:all     regexp based on s:pat and the default groups
    643   " This part is copied and slightly modified from matchit#Match_wrapper().
    644   if !exists("b:match_words") || b:match_words == ""
    645     let match_words = ""
    646     " Allow b:match_words = "GetVimMatchWords()" .
    647   elseif b:match_words =~ ":"
    648     let match_words = b:match_words
    649   else
    650     execute "let match_words =" b:match_words
    651   endif
    652   if (match_words != s:last_words) || (&mps != s:last_mps) ||
    653     \ exists("b:match_debug")
    654     let default = escape(&mps, '[$^.*~\\/?]') .. (strlen(&mps) ? "," : "") ..
    655       \ '\/\*:\*\/,#\s*if\%(n\=def\)\=:#\s*else\>:#\s*elif\>:#\s*endif\>'
    656     let s:last_mps = &mps
    657     let match_words = s:Append(match_words, default)
    658     let s:last_words = match_words
    659     if match_words !~ s:notslash .. '\\\d'
    660       let s:do_BR = 0
    661       let s:pat = match_words
    662     else
    663       let s:do_BR = 1
    664       let s:pat = s:ParseWords(match_words)
    665     endif
    666     let s:all = '\%(' .. substitute(s:pat, '[,:]\+', '\\|', 'g') .. '\)'
    667     if exists("b:match_debug")
    668       let b:match_pat = s:pat
    669     endif
    670     " Reconstruct the version with unresolved backrefs.
    671     let s:patBR = substitute(match_words .. ',',
    672       \ s:notslash .. '\zs[,:]*,[,:]*', ',', 'g')
    673     let s:patBR = substitute(s:patBR, s:notslash .. '\zs:\{2,}', ':', 'g')
    674   endif
    675 
    676   " Second step:  figure out the patterns for searchpair()
    677   " and save the screen, cursor position, and 'ignorecase'.
    678   " - TODO:  A lot of this is copied from matchit#Match_wrapper().
    679   " - maybe even more functionality should be split off
    680   " - into separate functions!
    681   let openlist = split(s:pat .. ',', s:notslash .. '\zs:.\{-}' .. s:notslash .. ',')
    682   let midclolist = split(',' .. s:pat, s:notslash .. '\zs,.\{-}' .. s:notslash .. ':')
    683   call map(midclolist, {-> split(v:val, s:notslash .. ':')})
    684   let closelist = []
    685   let middlelist = []
    686   call map(midclolist, {i,v -> [extend(closelist, v[-1 : -1]),
    687         \ extend(middlelist, v[0 : -2])]})
    688   call map(openlist,   {i,v -> v =~# s:notslash .. '\\|' ? '\%(' .. v .. '\)' : v})
    689   call map(middlelist, {i,v -> v =~# s:notslash .. '\\|' ? '\%(' .. v .. '\)' : v})
    690   call map(closelist,  {i,v -> v =~# s:notslash .. '\\|' ? '\%(' .. v .. '\)' : v})
    691   let open   = join(openlist, ',')
    692   let middle = join(middlelist, ',')
    693   let close  = join(closelist, ',')
    694   if exists("b:match_skip")
    695     let skip = b:match_skip
    696   elseif exists("b:match_comment") " backwards compatibility and testing!
    697     let skip = "r:" .. b:match_comment
    698   else
    699     let skip = 's:comment\|string'
    700   endif
    701   let skip = s:ParseSkip(skip)
    702   let view = winsaveview()
    703 
    704   " Third step: call searchpair().
    705   " Replace '\('--but not '\\('--with '\%(' and ',' with '\|'.
    706   let openpat = substitute(open, '\%(' .. s:notslash .. '\)\@<=\\(', '\\%(', 'g')
    707   let openpat = substitute(openpat, ',', '\\|', 'g')
    708   let closepat = substitute(close, '\%(' .. s:notslash .. '\)\@<=\\(', '\\%(', 'g')
    709   let closepat = substitute(closepat, ',', '\\|', 'g')
    710   let middlepat = substitute(middle, '\%(' .. s:notslash .. '\)\@<=\\(', '\\%(', 'g')
    711   let middlepat = substitute(middlepat, ',', '\\|', 'g')
    712 
    713   if skip =~ 'synID' && !(has("syntax") && exists("g:syntax_on"))
    714     let skip = '0'
    715   else
    716     try
    717       execute "if " .. skip .. "| let skip = '0' | endif"
    718     catch /^Vim\%((\a\+)\)\=:E363/
    719       " We won't find anything, so skip searching, should keep Vim responsive.
    720       return {}
    721     endtry
    722   endif
    723   mark '
    724   while level
    725     if searchpair(openpat, middlepat, closepat, a:spflag, skip) < 1
    726       call s:CleanUp(restore_options, a:mode, startpos)
    727       return {}
    728     endif
    729     let level = level - 1
    730   endwhile
    731 
    732   " Restore options and return a string to restore the original position.
    733   call s:CleanUp(restore_options, a:mode, startpos)
    734   return view
    735 endfun
    736 
    737 " Search backwards for "if" or "while" or "<tag>" or ...
    738 " and return "endif" or "endwhile" or "</tag>" or ... .
    739 " For now, this uses b:match_words and the same script variables
    740 " as matchit#Match_wrapper() .  Later, it may get its own patterns,
    741 " either from a buffer variable or passed as arguments.
    742 " fun! s:Autocomplete()
    743 "   echo "autocomplete not yet implemented :-("
    744 "   if !exists("b:match_words") || b:match_words == ""
    745 "     return ""
    746 "   end
    747 "   let startpos = matchit#MultiMatch("bW")
    748 "
    749 "   if startpos == ""
    750 "     return ""
    751 "   endif
    752 "   " - TODO:  figure out whether 'if' or '<tag>' matched, and construct
    753 "   " - the appropriate closing.
    754 "   let matchline = getline(".")
    755 "   let curcol = col(".") - 1
    756 "   " - TODO:  Change the s:all argument if there is a new set of match pats.
    757 "   let regexp = s:Wholematch(matchline, s:all, curcol)
    758 "   let suf = strlen(matchline) - matchend(matchline, regexp)
    759 "   let prefix = (curcol ? '^.\{'  . curcol . '}\%(' : '^\%(')
    760 "   let suffix = (suf ? '\).\{' . suf . '}$'  : '\)$')
    761 "   " Reconstruct the version with unresolved backrefs.
    762 "   let patBR = substitute(b:match_words.',', '[,:]*,[,:]*', ',', 'g')
    763 "   let patBR = substitute(patBR, ':\{2,}', ':', "g")
    764 "   " Now, set group and groupBR to the matching group: 'if:endif' or
    765 "   " 'while:endwhile' or whatever.
    766 "   let group = s:Choose(s:pat, matchline, ",", ":", prefix, suffix, patBR)
    767 "   let i = matchend(group, s:notslash . ",")
    768 "   let groupBR = strpart(group, i)
    769 "   let group = strpart(group, 0, i-1)
    770 "   " Now, matchline =~ prefix . substitute(group,':','\|','g') . suffix
    771 "   if s:do_BR
    772 "     let group = s:InsertRefs(groupBR, prefix, group, suffix, matchline)
    773 "   endif
    774 " " let g:group = group
    775 "
    776 "   " - TODO:  Construct the closing from group.
    777 "   let fake = "end" . expand("<cword>")
    778 "   execute startpos
    779 "   return fake
    780 " endfun
    781 
    782 " Close all open structures.  "Get the heck out of here!"
    783 " fun! s:Gthhoh()
    784 "   let close = s:Autocomplete()
    785 "   while strlen(close)
    786 "     put=close
    787 "     let close = s:Autocomplete()
    788 "   endwhile
    789 " endfun
    790 
    791 " Parse special strings as typical skip arguments for searchpair():
    792 "   s:foo becomes (current syntax item) =~ foo
    793 "   S:foo becomes (current syntax item) !~ foo
    794 "   r:foo becomes (line before cursor) =~ foo
    795 "   R:foo becomes (line before cursor) !~ foo
    796 fun! s:ParseSkip(str)
    797   let skip = a:str
    798   if skip[1] == ":"
    799     if skip[0] ==# "s"
    800       let skip = "synIDattr(synID(line('.'),col('.'),1),'name') =~? '" ..
    801         \ strpart(skip,2) .. "'"
    802     elseif skip[0] ==# "S"
    803       let skip = "synIDattr(synID(line('.'),col('.'),1),'name') !~? '" ..
    804         \ strpart(skip,2) .. "'"
    805     elseif skip[0] ==# "r"
    806       let skip = "strpart(getline('.'),0,col('.'))=~'" .. strpart(skip,2) .. "'"
    807     elseif skip[0] ==# "R"
    808       let skip = "strpart(getline('.'),0,col('.'))!~'" .. strpart(skip,2) .. "'"
    809     endif
    810   endif
    811   return skip
    812 endfun
    813 
    814 let &cpo = s:save_cpo
    815 unlet s:save_cpo
    816 
    817 " vim:sts=2:sw=2:et: