matchparen.vim 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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. 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. if !g:matchparen_disable_cursor_hl
  179. call add(w:matchparen_ids, matchaddpos('MatchParen', [[c_lnum, c_col - before], [m_lnum, m_col]], 10))
  180. else
  181. call add(w:matchparen_ids, matchaddpos('MatchParen', [[m_lnum, m_col]], 10))
  182. endif
  183. else
  184. if !g:matchparen_disable_cursor_hl
  185. exe '3match MatchParen /\(\%' . c_lnum . 'l\%' . (c_col - before) .
  186. \ 'c\)\|\(\%' . m_lnum . 'l\%' . m_col . 'c\)/'
  187. else
  188. exe '3match MatchParen /\(\%' . m_lnum . 'l\%' . m_col . 'c\)/'
  189. endif
  190. call add(w:matchparen_ids, 3)
  191. endif
  192. let w:paren_hl_on = 1
  193. endif
  194. endfunction
  195. func s:Remove_Matches()
  196. if exists('w:paren_hl_on') && w:paren_hl_on
  197. while !empty(w:matchparen_ids)
  198. silent! call remove(w:matchparen_ids, 0)->matchdelete()
  199. endwhile
  200. let w:paren_hl_on = 0
  201. endif
  202. endfunc
  203. " Define commands that will disable and enable the plugin.
  204. command DoMatchParen call s:DoMatchParen()
  205. command NoMatchParen call s:NoMatchParen()
  206. func s:NoMatchParen()
  207. let w = winnr()
  208. noau windo call s:Remove_Matches()
  209. unlet! g:loaded_matchparen
  210. exe "noau ". w . "wincmd w"
  211. au! matchparen
  212. endfunc
  213. func s:DoMatchParen()
  214. runtime plugin/matchparen.vim
  215. let w = winnr()
  216. silent windo doau CursorMoved
  217. exe "noau ". w . "wincmd w"
  218. endfunc
  219. let &cpo = s:cpo_save
  220. unlet s:cpo_save