Highlight searches in Vim but not substitutions?

I know it's possible to stop Vim from highlighting on any search, but is there a way to make it highlight on regular searches but not, for instance, substitutions?

I will often highlight a block of text then do something like:

:s/^/#/

to comment out the whole block. But then I have an ugly yellow bar running up and down the left side of my screen and I have to :noh every time to clear it.

I want highlighting to remain on regular /searches. Is this possible?


This doesn't answer your question fully but for me having the same problem it helped: I added this command to easily deactivate the highlighting after a search or a search-and-replace

nnoremap <esc> :noh<return><esc>

(from Vim clear last search highlighting)


My solution: put this in your vimrc file

set nohlsearch

noremap * :set hlsearch<CR>:nohlsearch<CR>*
noremap / :set hlsearch<CR>:nohlsearch<CR>/
noremap ? :set hlsearch<CR>:nohlsearch<CR>?

nnoremap <F4> :set invhlsearch<CR>
inoremap <F4> <ESC>:set invhlsearch<CR>gi
nnoremap <CR> :set nohlsearch<CR>

What it does:

  • Searches always enable highlights.
  • Use Enter to turn off highlights until the next search, but not the next substitute. Pressing Enter again will not turn them back on though.
  • Use F4 to turn off highlights until the next search, but not next substitute. Pressing F4 again will toggle the highlights for the last search pattern --- search OR substitute --- if there was one.
  • Some notes on highlights that are never really explained well:
    When the 'hlsearch' option is on, all future searches/substitutes will turn on "highlight visibility" . The current "highlight visibility" is not really an option you can directly query or set independently, but you can independently turn OFF highlight visibility with the command :nohlsearch (this is not the same as :set nohlsearch , because the next search will enable visibility again).

    In addition, whenever you run the command :set hlsearch there are two effects: It sets the option AND it makes vim forget if you've ever typed :nohlsearch . In other words, changing 'hlsearch' (either on or off) will force the current "highlight visibility" to logically match.

    链接地址: http://www.djcxy.com/p/49382.html

    上一篇: 如何在vim中使用find指令后关闭高亮显示

    下一篇: 在Vim中强调搜索但不替换?