matchparen.vim 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. " Vim plugin for showing matching parens
  2. " Maintainer: The Vim Project <https://github.com/vim/vim>
  3. " Last Change: 2024 May 18
  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. if !exists("g:matchparen_disable_cursor_hl")
  19. let g:matchparen_disable_cursor_hl = 0
  20. endif
  21. let s:has_matchaddpos = exists('*matchaddpos')
  22. augroup matchparen
  23. " Replace all matchparen autocommands
  24. autocmd! CursorMoved,CursorMovedI,WinEnter,WinScrolled * call s:Highlight_Matching_Pair()
  25. autocmd! BufWinEnter * autocmd SafeState * ++once call s:Highlight_Matching_Pair()
  26. autocmd! WinLeave,BufLeave * call s:Remove_Matches()
  27. if exists('##TextChanged')
  28. autocmd! TextChanged,TextChangedI * call s:Highlight_Matching_Pair()
  29. autocmd! TextChangedP * call s:Remove_Matches()
  30. endif
  31. augroup END
  32. " Skip the rest if it was already done.
  33. if exists("*s:Highlight_Matching_Pair")
  34. finish
  35. endif
  36. let s:cpo_save = &cpo
  37. set cpo-=C
  38. " The function that is invoked (very often) to define a ":match" highlighting
  39. " for any matching paren.
  40. func s:Highlight_Matching_Pair()
  41. if !exists("w:matchparen_ids")
  42. let w:matchparen_ids = []
  43. endif
  44. " Remove any previous match.
  45. call s:Remove_Matches()
  46. " Avoid that we remove the popup menu.
  47. " Return when there are no colors (looks like the cursor jumps).
  48. if pumvisible() || (&t_Co < 8 && !has("gui_running"))
  49. return
  50. endif
  51. " Get the character under the cursor and check if it's in 'matchpairs'.
  52. let c_lnum = line('.')
  53. let c_col = col('.')
  54. let before = 0
  55. let text = getline(c_lnum)
  56. let c_before = text->strpart(0, c_col - 1)->slice(-1)
  57. let c = text->strpart(c_col - 1)->slice(0, 1)
  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. elseif exists("b:ts_highlight") && &syntax != 'on'
  100. let s_skip = "match(v:lua.vim.treesitter.get_captures_at_cursor(), '"
  101. \ .. 'string\|character\|singlequote\|escape\|symbol\|comment'
  102. \ .. "') != -1"
  103. else
  104. " Build an expression that detects whether the current cursor position is
  105. " in certain syntax types (string, comment, etc.), for use as
  106. " searchpairpos()'s skip argument.
  107. " We match "escape" for special items, such as lispEscapeSpecial, and
  108. " match "symbol" for lispBarSymbol.
  109. let s_skip = 'synstack(".", col("."))'
  110. \ . '->indexof({_, id -> synIDattr(id, "name") =~? '
  111. \ . '"string\\|character\\|singlequote\\|escape\\|symbol\\|comment"}) >= 0'
  112. " If executing the expression determines that the cursor is currently in
  113. " one of the syntax types, then we want searchpairpos() to find the pair
  114. " within those syntax types (i.e., not skip). Otherwise, the cursor is
  115. " outside of the syntax types and s_skip should keep its value so we skip
  116. " any matching pair inside the syntax types.
  117. " Catch if this throws E363: pattern uses more memory than 'maxmempattern'.
  118. try
  119. execute 'if ' . s_skip . ' | let s_skip = "0" | endif'
  120. catch /^Vim\%((\a\+)\)\=:E363/
  121. " We won't find anything, so skip searching, should keep Vim responsive.
  122. return
  123. endtry
  124. endif
  125. " Limit the search to lines visible in the window.
  126. let stoplinebottom = line('w$')
  127. let stoplinetop = line('w0')
  128. if i % 2 == 0
  129. let stopline = stoplinebottom
  130. else
  131. let stopline = stoplinetop
  132. endif
  133. " Limit the search time to 300 msec to avoid a hang on very long lines.
  134. " This fails when a timeout is not supported.
  135. if mode() == 'i' || mode() == 'R'
  136. let timeout = exists("b:matchparen_insert_timeout") ? b:matchparen_insert_timeout : g:matchparen_insert_timeout
  137. else
  138. let timeout = exists("b:matchparen_timeout") ? b:matchparen_timeout : g:matchparen_timeout
  139. endif
  140. try
  141. let [m_lnum, m_col] = searchpairpos(c, '', c2, s_flags, s_skip, stopline, timeout)
  142. catch /E118/
  143. " Can't use the timeout, restrict the stopline a bit more to avoid taking
  144. " a long time on closed folds and long lines.
  145. " The "viewable" variables give a range in which we can scroll while
  146. " keeping the cursor at the same position.
  147. " adjustedScrolloff accounts for very large numbers of scrolloff.
  148. let adjustedScrolloff = min([&scrolloff, (line('w$') - line('w0')) / 2])
  149. let bottom_viewable = min([line('$'), c_lnum + &lines - adjustedScrolloff - 2])
  150. let top_viewable = max([1, c_lnum-&lines+adjustedScrolloff + 2])
  151. " one of these stoplines will be adjusted below, but the current values are
  152. " minimal boundaries within the current window
  153. if i % 2 == 0
  154. if has("byte_offset") && has("syntax_items") && &smc > 0
  155. let stopbyte = min([line2byte("$"), line2byte(".") + col(".") + &smc * 2])
  156. let stopline = min([bottom_viewable, byte2line(stopbyte)])
  157. else
  158. let stopline = min([bottom_viewable, c_lnum + 100])
  159. endif
  160. let stoplinebottom = stopline
  161. else
  162. if has("byte_offset") && has("syntax_items") && &smc > 0
  163. let stopbyte = max([1, line2byte(".") + col(".") - &smc * 2])
  164. let stopline = max([top_viewable, byte2line(stopbyte)])
  165. else
  166. let stopline = max([top_viewable, c_lnum - 100])
  167. endif
  168. let stoplinetop = stopline
  169. endif
  170. let [m_lnum, m_col] = searchpairpos(c, '', c2, s_flags, s_skip, stopline)
  171. endtry
  172. if before > 0
  173. if has_getcurpos
  174. call setpos('.', save_cursor)
  175. else
  176. call winrestview(save_cursor)
  177. endif
  178. endif
  179. " If a match is found setup match highlighting.
  180. if m_lnum > 0 && m_lnum >= stoplinetop && m_lnum <= stoplinebottom
  181. if s:has_matchaddpos
  182. if !g:matchparen_disable_cursor_hl
  183. call add(w:matchparen_ids, matchaddpos('MatchParen', [[c_lnum, c_col - before], [m_lnum, m_col]], 10))
  184. else
  185. call add(w:matchparen_ids, matchaddpos('MatchParen', [[m_lnum, m_col]], 10))
  186. endif
  187. else
  188. if !g:matchparen_disable_cursor_hl
  189. exe '3match MatchParen /\(\%' . c_lnum . 'l\%' . (c_col - before) .
  190. \ 'c\)\|\(\%' . m_lnum . 'l\%' . m_col . 'c\)/'
  191. else
  192. exe '3match MatchParen /\(\%' . m_lnum . 'l\%' . m_col . 'c\)/'
  193. endif
  194. call add(w:matchparen_ids, 3)
  195. endif
  196. let w:paren_hl_on = 1
  197. endif
  198. endfunction
  199. func s:Remove_Matches()
  200. if exists('w:paren_hl_on') && w:paren_hl_on
  201. while !empty(w:matchparen_ids)
  202. silent! call remove(w:matchparen_ids, 0)->matchdelete()
  203. endwhile
  204. let w:paren_hl_on = 0
  205. endif
  206. endfunc
  207. " Define commands that will disable and enable the plugin.
  208. command DoMatchParen call s:DoMatchParen()
  209. command NoMatchParen call s:NoMatchParen()
  210. func s:NoMatchParen()
  211. let w = winnr()
  212. noau windo call s:Remove_Matches()
  213. unlet! g:loaded_matchparen
  214. exe "noau ". w . "wincmd w"
  215. au! matchparen
  216. endfunc
  217. func s:DoMatchParen()
  218. runtime plugin/matchparen.vim
  219. let w = winnr()
  220. silent windo doau CursorMoved
  221. exe "noau ". w . "wincmd w"
  222. endfunc
  223. let &cpo = s:cpo_save
  224. unlet s:cpo_save