matchit.vim 30 KB

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