matchparen.vim 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. " Vim plugin for showing matching parens
  2. " Maintainer: The Vim Project <https://github.com/vim/vim>
  3. " Last Change: 2023 Oct 20
  4. " Former Maintainer: Bram Moolenaar <Bram@vim.org>
  5. " Exit quickly when:
  6. " - this plugin was already loaded (or disabled)
  7. " - when 'compatible' is set
  8. if exists("g:loaded_matchparen") || &cp
  9. finish
  10. endif
  11. let g:loaded_matchparen = 1
  12. if !exists("g:matchparen_timeout")
  13. let g:matchparen_timeout = 300
  14. endif
  15. if !exists("g:matchparen_insert_timeout")
  16. let g:matchparen_insert_timeout = 60
  17. endif
  18. let s:has_matchaddpos = exists('*matchaddpos')
  19. augroup matchparen
  20. " Replace all matchparen autocommands
  21. autocmd! CursorMoved,CursorMovedI,WinEnter,BufWinEnter,WinScrolled * call s:Highlight_Matching_Pair()
  22. autocmd! WinLeave,BufLeave * call s:Remove_Matches()
  23. if exists('##TextChanged')
  24. autocmd! TextChanged,TextChangedI * call s:Highlight_Matching_Pair()
  25. autocmd! TextChangedP * call s:Remove_Matches()
  26. endif
  27. augroup END
  28. " Skip the rest if it was already done.
  29. if exists("*s:Highlight_Matching_Pair")
  30. finish
  31. endif
  32. let s:cpo_save = &cpo
  33. set cpo-=C
  34. " The function that is invoked (very often) to define a ":match" highlighting
  35. " for any matching paren.
  36. func s:Highlight_Matching_Pair()
  37. if !exists("w:matchparen_ids")
  38. let w:matchparen_ids = []
  39. endif
  40. " Remove any previous match.
  41. call s:Remove_Matches()
  42. " Avoid that we remove the popup menu.
  43. " Return when there are no colors (looks like the cursor jumps).
  44. if pumvisible() || (&t_Co < 8 && !has("gui_running"))
  45. return
  46. endif
  47. " Get the character under the cursor and check if it's in 'matchpairs'.
  48. let c_lnum = line('.')
  49. let c_col = col('.')
  50. let before = 0
  51. let text = getline(c_lnum)
  52. let matches = matchlist(text, '\(.\)\=\%'.c_col.'c\(.\=\)')
  53. if empty(matches)
  54. let [c_before, c] = ['', '']
  55. else
  56. let [c_before, c] = matches[1:2]
  57. endif
  58. let plist = split(&matchpairs, '.\zs[:,]')
  59. let i = index(plist, c)
  60. if i < 0
  61. " not found, in Insert mode try character before the cursor
  62. if c_col > 1 && (mode() == 'i' || mode() == 'R')
  63. let before = strlen(c_before)
  64. let c = c_before
  65. let i = index(plist, c)
  66. endif
  67. if i < 0
  68. " not found, nothing to do
  69. return
  70. endif
  71. endif
  72. " Figure out the arguments for searchpairpos().
  73. if i % 2 == 0
  74. let s_flags = 'nW'
  75. let c2 = plist[i + 1]
  76. else
  77. let s_flags = 'nbW'
  78. let c2 = c
  79. let c = plist[i - 1]
  80. endif
  81. if c == '['
  82. let c = '\['
  83. let c2 = '\]'
  84. endif
  85. " Find the match. When it was just before the cursor move it there for a
  86. " moment.
  87. if before > 0
  88. let has_getcurpos = exists("*getcurpos")
  89. if has_getcurpos
  90. " getcurpos() is more efficient but doesn't exist before 7.4.313.
  91. let save_cursor = getcurpos()
  92. else
  93. let save_cursor = winsaveview()
  94. endif
  95. call cursor(c_lnum, c_col - before)
  96. endif
  97. if !has("syntax") || !exists("g:syntax_on")
  98. let s_skip = "0"
  99. else
  100. " Build an expression that detects whether the current cursor position is
  101. " in certain syntax types (string, comment, etc.), for use as
  102. " searchpairpos()'s skip argument.
  103. " We match "escape" for special items, such as lispEscapeSpecial, and
  104. " match "symbol" for lispBarSymbol.
  105. let s_skip = 'synstack(".", col("."))'
  106. \ . '->indexof({_, id -> synIDattr(id, "name") =~? '
  107. \ . '"string\\|character\\|singlequote\\|escape\\|symbol\\|comment"}) >= 0'
  108. " If executing the expression determines that the cursor is currently in
  109. " one of the syntax types, then we want searchpairpos() to find the pair
  110. " within those syntax types (i.e., not skip). Otherwise, the cursor is
  111. " outside of the syntax types and s_skip should keep its value so we skip
  112. " any matching pair inside the syntax types.
  113. " Catch if this throws E363: pattern uses more memory than 'maxmempattern'.
  114. try
  115. execute 'if ' . s_skip . ' | let s_skip = "0" | endif'
  116. catch /^Vim\%((\a\+)\)\=:E363/
  117. " We won't find anything, so skip searching, should keep Vim responsive.
  118. return
  119. endtry
  120. endif
  121. " Limit the search to lines visible in the window.
  122. let stoplinebottom = line('w$')
  123. let stoplinetop = line('w0')
  124. if i % 2 == 0
  125. let stopline = stoplinebottom
  126. else
  127. let stopline = stoplinetop
  128. endif
  129. " Limit the search time to 300 msec to avoid a hang on very long lines.
  130. " This fails when a timeout is not supported.
  131. if mode() == 'i' || mode() == 'R'
  132. let timeout = exists("b:matchparen_insert_timeout") ? b:matchparen_insert_timeout : g:matchparen_insert_timeout
  133. else
  134. let timeout = exists("b:matchparen_timeout") ? b:matchparen_timeout : g:matchparen_timeout
  135. endif
  136. try
  137. let [m_lnum, m_col] = searchpairpos(c, '', c2, s_flags, s_skip, stopline, timeout)
  138. catch /E118/
  139. " Can't use the timeout, restrict the stopline a bit more to avoid taking
  140. " a long time on closed folds and long lines.
  141. " The "viewable" variables give a range in which we can scroll while
  142. " keeping the cursor at the same position.
  143. " adjustedScrolloff accounts for very large numbers of scrolloff.
  144. let adjustedScrolloff = min([&scrolloff, (line('w$') - line('w0')) / 2])
  145. let bottom_viewable = min([line('$'), c_lnum + &lines - adjustedScrolloff - 2])
  146. let top_viewable = max([1, c_lnum-&lines+adjustedScrolloff + 2])
  147. " one of these stoplines will be adjusted below, but the current values are
  148. " minimal boundaries within the current window
  149. if i % 2 == 0
  150. if has("byte_offset") && has("syntax_items") && &smc > 0
  151. let stopbyte = min([line2byte("$"), line2byte(".") + col(".") + &smc * 2])
  152. let stopline = min([bottom_viewable, byte2line(stopbyte)])
  153. else
  154. let stopline = min([bottom_viewable, c_lnum + 100])
  155. endif
  156. let stoplinebottom = stopline
  157. else
  158. if has("byte_offset") && has("syntax_items") && &smc > 0
  159. let stopbyte = max([1, line2byte(".") + col(".") - &smc * 2])
  160. let stopline = max([top_viewable, byte2line(stopbyte)])
  161. else
  162. let stopline = max([top_viewable, c_lnum - 100])
  163. endif
  164. let stoplinetop = stopline
  165. endif
  166. let [m_lnum, m_col] = searchpairpos(c, '', c2, s_flags, s_skip, stopline)
  167. endtry
  168. if before > 0
  169. if has_getcurpos
  170. call setpos('.', save_cursor)
  171. else
  172. call winrestview(save_cursor)
  173. endif
  174. endif
  175. " If a match is found setup match highlighting.
  176. if m_lnum > 0 && m_lnum >= stoplinetop && m_lnum <= stoplinebottom
  177. if s:has_matchaddpos
  178. call add(w:matchparen_ids, matchaddpos('MatchParen', [[c_lnum, c_col - before], [m_lnum, m_col]], 10))
  179. else
  180. exe '3match MatchParen /\(\%' . c_lnum . 'l\%' . (c_col - before) .
  181. \ 'c\)\|\(\%' . m_lnum . 'l\%' . m_col . 'c\)/'
  182. call add(w:matchparen_ids, 3)
  183. endif
  184. let w:paren_hl_on = 1
  185. endif
  186. endfunction
  187. func s:Remove_Matches()
  188. if exists('w:paren_hl_on') && w:paren_hl_on
  189. while !empty(w:matchparen_ids)
  190. silent! call remove(w:matchparen_ids, 0)->matchdelete()
  191. endwhile
  192. let w:paren_hl_on = 0
  193. endif
  194. endfunc
  195. " Define commands that will disable and enable the plugin.
  196. command DoMatchParen call s:DoMatchParen()
  197. command NoMatchParen call s:NoMatchParen()
  198. func s:NoMatchParen()
  199. let w = winnr()
  200. noau windo silent! call matchdelete(3)
  201. unlet! g:loaded_matchparen
  202. exe "noau ". w . "wincmd w"
  203. au! matchparen
  204. endfunc
  205. func s:DoMatchParen()
  206. runtime plugin/matchparen.vim
  207. let w = winnr()
  208. silent windo doau CursorMoved
  209. exe "noau ". w . "wincmd w"
  210. endfunc
  211. let &cpo = s:cpo_save
  212. unlet s:cpo_save