matchit.vim 29 KB

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