I have the following code inside my vimrc
hi CurrentWordUL cterm=underline gui=underline
hi Search cterm=underline ctermfg=124 gui=underline guifg=#af0000
augroup MyHighlighter
autocmd!
" autocmd User IncSearchEnter MatchHighlighter 0
" autocmd User IncSearchExecute MatchHighlighter 1
set updatetime=700
autocmd CursorHold * if (get(g:, 'matchhl', 1) && (&ft !~ join(g:ft_blacklist, '\|')))
\ | silent! exe printf('match CurrentWordUL /\<%s\>/', expand('<cword>'))
\ | endif
autocmd CursorMoved * if (get(g:, 'matchhl', 1) && (&ft !~ join(g:ft_blacklist, '\|')))
\ | silent! exe printf('match none')
\ | endif
augroup END
nnoremap <silent> <f4> :MatchHighlighter<CR>
command! -nargs=? MatchHighlighter
\ call ToggleSetMatchHL(
\ empty(<q-args>) ? !get(g:, 'matchhl', 1) : expand(<q-args>))
function! ToggleSetMatchHL(arg) abort
match none | diffupdate | syntax sync fromstart
let g:matchhl = a:arg
endfunction
The purpose of this is to highlight (underline) matching word under the cursor.
The issue I have is when I'm searching with /, ?, *, # etc. The matching highlight overwrite the search highlight.
Is there anyway I can know "end of search" (I don't know the definition of "end of search" but maybe someone can suggest something) or "nohlsearch" was called?
Thanks in advance.
:match
to :call matchadd(...)
, you can specify a {priority}
. A negative one will put the highlighting below the search highlighting (which has prio 0
; default is 10
)./
, ?
, *
, etc); that would detect a start of search. For /
and ?
, you could define a cmap <CR>
with a check of getcmdtype() =~# '[/?]'
to detect the conclusion of a search. I wouldn't recommend this approach; the mappings may interfere with other plugins.:match
(which is window-local, so the highlighting also behaves differently than the built-in search highlighting), you could automatically adapt the current search pattern (register /
) instead. My SearchHighlighting plugin chooses this approach with its :SearchAutoHighlighting
command. (The plugin page has links to many alternative plugins you may want to check out; I would prefer a well-maintained plugin over a custom code snippet in my ~/.vimrc
.)