Is it possible to enable hlsearch when running a search (/) but not on : commands? For example, sometimes when doing a replace (on a very narrow range of text) it get distracting when I have a bunch of other lines highlighted, for example:

enter image description here

Here is a ten-second video of what I've done for this: https://gyazo.com/590a1927dcc2eb75d950053601dab9a7. If the answer is 'no', is there a better alternative than pressing :noh (or whatever mapping to it) after every search that I'm 'done with' ?


You can use the following autocommands to enable hlsearch only when using the / and ? (search) commands:

" Enable highlighting all the matches in incsearch mode
" But don't enable hlsearch always
augroup vimrc-incsearch-highlight
  autocmd CmdlineEnter [/\?] :set hlsearch
  autocmd CmdlineLeave [/\?] :set nohlsearch
augroup END

I don't think there is a way out of the box. hlsearch works with the search register (:h "/), which is used for search, substitute and the :global command.

I personally have hlsearch off by default and only enable it when I need it.

I have the following mapping:

noremap  <F8>   :set invhlsearch hlsearch?<CR>

The invhlsearch toggles hlsearch and the hlsearch? then prints the state.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.