1" Vim plugin for showing matching parens
2" Maintainer:  Bram Moolenaar <[email protected]>
3" Last Change: 2014 Jul 19
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  if exists('##TextChanged')
25    autocmd! TextChanged,TextChangedI * call s:Highlight_Matching_Pair()
26  endif
27augroup END
28
29" Skip the rest if it was already done.
30if exists("*s:Highlight_Matching_Pair")
31  finish
32endif
33
34let s:cpo_save = &cpo
35set cpo-=C
36
37" The function that is invoked (very often) to define a ":match" highlighting
38" for any matching paren.
39function! s:Highlight_Matching_Pair()
40  " Remove any previous match.
41  if exists('w:paren_hl_on') && w:paren_hl_on
42    silent! call matchdelete(3)
43    let w:paren_hl_on = 0
44  endif
45
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
52  " Get the character under the cursor and check if it's in 'matchpairs'.
53  let c_lnum = line('.')
54  let c_col = col('.')
55  let before = 0
56
57  let text = getline(c_lnum)
58  let c = text[c_col - 1]
59  let plist = split(&matchpairs, '.\zs[:,]')
60  let i = index(plist, c)
61  if i < 0
62    " not found, in Insert mode try character before the cursor
63    if c_col > 1 && (mode() == 'i' || mode() == 'R')
64      let before = 1
65      let c = text[c_col - 2]
66      let i = index(plist, c)
67    endif
68    if i < 0
69      " not found, nothing to do
70      return
71    endif
72  endif
73
74  " Figure out the arguments for searchpairpos().
75  if i % 2 == 0
76    let s_flags = 'nW'
77    let c2 = plist[i + 1]
78  else
79    let s_flags = 'nbW'
80    let c2 = c
81    let c = plist[i - 1]
82  endif
83  if c == '['
84    let c = '\['
85    let c2 = '\]'
86  endif
87
88  " Find the match.  When it was just before the cursor move it there for a
89  " moment.
90  if before > 0
91    let has_getcurpos = exists("*getcurpos")
92    if has_getcurpos
93      " getcurpos() is more efficient but doesn't exist before 7.4.313.
94      let save_cursor = getcurpos()
95    else
96      let save_cursor = winsaveview()
97    endif
98    call cursor(c_lnum, c_col - before)
99  endif
100
101  " When not in a string or comment ignore matches inside them.
102  " We match "escape" for special items, such as lispEscapeSpecial.
103  let s_skip ='synIDattr(synID(line("."), col("."), 0), "name") ' .
104	\ '=~?  "string\\|character\\|singlequote\\|escape\\|comment"'
105  execute 'if' s_skip '| let s_skip = 0 | endif'
106
107  " Limit the search to lines visible in the window.
108  let stoplinebottom = line('w$')
109  let stoplinetop = line('w0')
110  if i % 2 == 0
111    let stopline = stoplinebottom
112  else
113    let stopline = stoplinetop
114  endif
115
116  " Limit the search time to 300 msec to avoid a hang on very long lines.
117  " This fails when a timeout is not supported.
118  if mode() == 'i' || mode() == 'R'
119    let timeout = exists("b:matchparen_insert_timeout") ? b:matchparen_insert_timeout : g:matchparen_insert_timeout
120  else
121    let timeout = exists("b:matchparen_timeout") ? b:matchparen_timeout : g:matchparen_timeout
122  endif
123  try
124    let [m_lnum, m_col] = searchpairpos(c, '', c2, s_flags, s_skip, stopline, timeout)
125  catch /E118/
126    " Can't use the timeout, restrict the stopline a bit more to avoid taking
127    " a long time on closed folds and long lines.
128    " The "viewable" variables give a range in which we can scroll while
129    " keeping the cursor at the same position.
130    " adjustedScrolloff accounts for very large numbers of scrolloff.
131    let adjustedScrolloff = min([&scrolloff, (line('w$') - line('w0')) / 2])
132    let bottom_viewable = min([line('$'), c_lnum + &lines - adjustedScrolloff - 2])
133    let top_viewable = max([1, c_lnum-&lines+adjustedScrolloff + 2])
134    " one of these stoplines will be adjusted below, but the current values are
135    " minimal boundaries within the current window
136    if i % 2 == 0
137      if has("byte_offset") && has("syntax_items") && &smc > 0
138	let stopbyte = min([line2byte("$"), line2byte(".") + col(".") + &smc * 2])
139	let stopline = min([bottom_viewable, byte2line(stopbyte)])
140      else
141	let stopline = min([bottom_viewable, c_lnum + 100])
142      endif
143      let stoplinebottom = stopline
144    else
145      if has("byte_offset") && has("syntax_items") && &smc > 0
146	let stopbyte = max([1, line2byte(".") + col(".") - &smc * 2])
147	let stopline = max([top_viewable, byte2line(stopbyte)])
148      else
149	let stopline = max([top_viewable, c_lnum - 100])
150      endif
151      let stoplinetop = stopline
152    endif
153    let [m_lnum, m_col] = searchpairpos(c, '', c2, s_flags, s_skip, stopline)
154  endtry
155
156  if before > 0
157    if has_getcurpos
158      call setpos('.', save_cursor)
159    else
160      call winrestview(save_cursor)
161    endif
162  endif
163
164  " If a match is found setup match highlighting.
165  if m_lnum > 0 && m_lnum >= stoplinetop && m_lnum <= stoplinebottom
166    if exists('*matchaddpos')
167      call matchaddpos('MatchParen', [[c_lnum, c_col - before], [m_lnum, m_col]], 10, 3)
168    else
169      exe '3match MatchParen /\(\%' . c_lnum . 'l\%' . (c_col - before) .
170	    \ 'c\)\|\(\%' . m_lnum . 'l\%' . m_col . 'c\)/'
171    endif
172    let w:paren_hl_on = 1
173  endif
174endfunction
175
176" Define commands that will disable and enable the plugin.
177command! NoMatchParen windo silent! call matchdelete(3) | unlet! g:loaded_matchparen |
178	  \ au! matchparen
179command! DoMatchParen runtime plugin/matchparen.vim | windo doau CursorMoved
180
181let &cpo = s:cpo_save
182unlet s:cpo_save
183