neovim

Neovim text editor
git clone https://git.dasho.dev/neovim.git
Log | Files | Refs | README

matchparen.vim (7966B)


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