1" Vim plugin for showing matching parens 2" Maintainer: Bram Moolenaar <[email protected]> 3" Last Change: 2006 Mar 04 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 availble. 9if exists("g:loaded_matchparen") || &cp || !exists("##CursorMoved") 10 finish 11endif 12let g:loaded_matchparen = 1 13 14augroup matchparen 15 " Replace all matchparen autocommands 16 autocmd! CursorMoved,CursorMovedI * call s:Highlight_Matching_Pair() 17augroup END 18 19let s:paren_hl_on = 0 20 21" Skip the rest if it was already done. 22if exists("*s:Highlight_Matching_Pair") 23 finish 24endif 25 26" The function that is invoked (very often) to define a ":match" highlighting 27" for any matching paren. 28function! s:Highlight_Matching_Pair() 29 " Remove any previous match. 30 if s:paren_hl_on 31 3match none 32 let s:paren_hl_on = 0 33 endif 34 35 " Avoid that we remove the popup menu. 36 if pumvisible() 37 return 38 endif 39 40 " Get the character under the cursor and check if it's in 'matchpairs'. 41 let c_lnum = line('.') 42 let c_col = col('.') 43 let before = 0 44 45 let c = getline(c_lnum)[c_col - 1] 46 let plist = split(&matchpairs, ':\|,') 47 let i = index(plist, c) 48 if i < 0 49 " not found, in Insert mode try character before the cursor 50 if c_col > 1 && (mode() == 'i' || mode() == 'R') 51 let before = 1 52 let c = getline(c_lnum)[c_col - 2] 53 let i = index(plist, c) 54 endif 55 if i < 0 56 " not found, nothing to do 57 return 58 endif 59 endif 60 61 " Figure out the arguments for searchpairpos(). 62 " Restrict the search to visible lines with "stopline". 63 if i % 2 == 0 64 let s_flags = 'nW' 65 let c2 = plist[i + 1] 66 let stopline = line('w$') 67 else 68 let s_flags = 'nbW' 69 let c2 = c 70 let c = plist[i - 1] 71 let stopline = line('w0') 72 endif 73 if c == '[' 74 let c = '\[' 75 let c2 = '\]' 76 endif 77 78 " When not in a string or comment ignore matches inside them. 79 let s_skip ='synIDattr(synID(c_lnum, c_col - before, 0), "name") ' . 80 \ '=~? "string\\|comment"' 81 execute 'if' s_skip '| let s_skip = 0 | endif' 82 83 " Find the match. When it was just before the cursor move it there for a 84 " moment. 85 if before > 0 86 let save_cursor = getpos('.') 87 call cursor(c_lnum, c_col - before) 88 endif 89 let [m_lnum, m_col] = searchpairpos(c, '', c2, s_flags, s_skip, stopline) 90 if before > 0 91 call setpos('.', save_cursor) 92 endif 93 94 " If a match is found setup match highlighting. 95 if m_lnum > 0 && m_lnum >= line('w0') && m_lnum <= line('w$') 96 exe '3match MatchParen /\(\%' . c_lnum . 'l\%' . (c_col - before) . 97 \ 'c\)\|\(\%' . m_lnum . 'l\%' . m_col . 'c\)/' 98 let s:paren_hl_on = 1 99 endif 100endfunction 101 102" Define commands that will disable and enable the plugin. 103command! NoMatchParen 3match none | unlet! g:loaded_matchparen | au! matchparen 104command! DoMatchParen runtime plugin/matchparen.vim | doau CursorMoved 105