Vim uses two different highlight groups for matching patterns while searching in the command-line with / or :substitute for example.

  • The incsearch group for the match under the cursor
  • The search group for the others

When the command-line is left, the match under the cursor is set back to the search group. I would like it to remain as it is while in command-line.

I actually wrote a function which changes the group of the match under the cursor. I mapped it to n and N. It also applies a different highlight for the first and last match.

" highlight current search and first/last search differently
function! HLCurrent() abort
    if exists("currmatch")
        call matchdelete(currmatch)
    " only on cursor
    let patt = '\c\%#'.@/
    " check prev and next match
    let prevmatch = search(@/, 'bWn')
    let nextmatch = search(@/, 'Wn')
    " if on first or last match
    if prevmatch == 0 || nextmatch == 0
        let currmatch = matchadd('EdgeSearch', patt, 101)
        let currmatch = matchadd('IncSearch', patt, 101)
nnoremap <silent> n n:call HLCurrent()<cr>
nnoremap <silent> N N:call HLCurrent()<cr>

It works well, but I still have the problem of the group being changed when leaving the command-line window.

Using my function, I expected this autocmd to do the trick, but it does not work as expected:

augroup HLCurrentRightNow
    au CmdlineLeave,CmdwinLeave * call clearmatches() | call HLCurrent()
augroup end

So, what would be a way to apply my function when exiting the command-line?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.