简体   繁体   中英

Highlighting find next in vim

I often use vim's / search capabilities and will use n to jump to the next match. However, when the cursor jumps to the next match and the screen redraws, it is often not at all obvious where the cursor is on the screen (and thus where the next match is). In the past, I have had to do a jk dance to make the cursor move so I can find it. My cursor does not blink by default (I find that annoying), but what I would like is this: when the cursor jumps to the next match, it should change color or blink briefly to draw attention to its placement on the screen, then switch back to the default cursor behavior. How can I create this behavior in my .vimrc file? My google-fu has failed me thus far.

Note: I am aware there is a setting for highlighting all search matches ( hlsearch ), but I prefer to keep my view clean. Temporarily highlighting the current match would be fine, but I want to only draw attention to the current match, not all matches.

I use this in my .vimrc, which will center the search term in the middle of your display. This not only makes it easy to find the search term, but also automatically provides me with enough context before and after that I usually don't need to scroll around after searching.

" Center the display line after searches. (This makes it *much* easier to see
" the matched line.)
"
" More info: http://www.vim.org/tips/tip.php?tip_id=528
"
nnoremap n nzz
nnoremap N Nzz
nnoremap * *zz
nnoremap # #zz
nnoremap g* g*zz
nnoremap g# g#zz

Steve Losh made something similar - when you jump to a next location (n key) the cursor blinks! Here's how it works screencast , and here is the code (see older commits for some variations on the theme).

I whipped up a couple of functions that seem to handle this alright. They may not be the best implementation but they seem to work.

function! s:NextMatch()
    let param = getreg('/')
    let pos = getpos('.')
    let next_match = matchadd('Search', '\%'.pos[1].'l\%'.pos[2].'v'.param)
    redraw
    sleep 250ms
    silent! call matchdelete(next_match)
endfunction

function! s:DoNextMatch()
    let cmd_type = getcmdtype()
    if cmd_type == '/' || cmd_type == '?'
        return "\<cr>:call " . s:SID() . "NextMatch()\<cr>"
    endif
    return "\<cr>"
endfunction

function s:SID()
  return matchstr(expand('<sfile>'), '<SNR>\d\+_\zeSID$')
endfun

nnoremap <silent> n n:call <sid>NextMatch()<cr>
nnoremap <silent> N N:call <sid>NextMatch()<cr>
cnoremap <silent> <expr> <cr> <sid>DoNextMatch()

Tested with: vim -u test.vim -N file.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM