Skip to content

Instantly share code, notes, and snippets.

@habamax
Last active February 26, 2022 22:56
Embed
What would you like to do?

Annoying vim search highlight "everyone" tries to get rid of

You have turned on hlsearch for some reason in your vim config (well obviously to highlight your searches) but it gets in your way, right?

Now you try to find a solution to this problem, like

  1. spam random searches /klsdf<CR>

  2. do :nohl command or

  3. map a key to do it — :nnoremap <C-l> :nohl<CR><C-l>

  4. etc

My take to this problem is …​ not to use hlsearch:

" highlight incremental searches
set incsearch
" to use with <tab> cnoremaps
set wildcharm=<C-z>
" tab to cycle search candidates
cnoremap <expr> <Tab>   getcmdtype() =~ "[/?]" ? "<C-g>" : "<C-z>"
cnoremap <expr> <S-Tab> getcmdtype() =~ "[/?]" ? "<C-t>" : "<S-Tab>"

Or use it only when in / or ? because it is still useful to highlight occurences while typing so you might also add following:

"" highlight all occurrences of a term being searched/replaced
augroup hlsearch | au!
    au CmdlineEnter /,\? :set hlsearch
    au CmdlineLeave /,\? :set nohlsearch
augroup end

And it looks like this:

110236822 06e5dd80 7f49 11eb 94cd bb18fd46f14a

@joeytwiddle
Copy link

Interesting approach!

It inspired me to try something similar, but different. This script will clear the highlight after a short pause, and temporarily re-enable it when pressing n or N or other search keys.

temphlsearch.vim

@romainl
Copy link

romainl commented Nov 24, 2021

@joeytwiddle your plugin looks a lot like the first iteration of mine before I figured out that mapping n, N and friends caused more troubles than it solved.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment