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