ChatGPT解决这个技术问题 Extra ChatGPT

Vim clear last search highlighting

Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.

After doing a search in Vim, I get all the occurrences highlighted. How can I disable that? I now do another search for something gibberish that can't be found.

Is there a way to just temporarily disable the highlight and then re-enable it when needed again?

:set invhlsearch will disable the highlighting if its already highlighted and enable it if it isn't. You can map it to say Shift-H.
@StewartJohnson doing that in my .vimrc files seems to interfere/break with :set mouse=a. Any ideas why? This error only happens in iTerm2
I have typed so much gibberish over the years to clear that highlight (really inefficient for multi-GB text files). The gibberish search is essentially a second search which wastes compute time. Great question!
@StewartJohnson Be careful! Your top-rated comment with mapping cause errors and unexpected behaviour as described in the comments below to stackoverflow.com/a/1037182/1698467
The nnoremap <esc> :noh<return><esc> solution suggested by @StewartJohnson works nicely in GUI vim, but causes problems with arrow keys and other ESC-encoded keys when running vim in a terminal. Don't put it in your ~/.vimrc without wrapping it in if has('gui_running') ... end.

q
qwertzguy

To turn off highlighting until the next search:

:noh

Or turn off highlighting completely:

set nohlsearch

Or, to toggle it:

set hlsearch!

nnoremap <F3> :set hlsearch!<CR>

This is not clear from this answer and comments : note that set nohlsearch will disable the highlighting for next searches as well. The behaviour of :noh is very different : the highlighting will be automatically reenabled when you perform a new search or even when you do something related to the current search (e.g. when you type n to go to the next item).
I map it to <Ctrl-L> because that's my go-to keystroke for cleaning up the screen. Here is my mapping: nmap <silent> <C-L> <C-L>:nohlsearch<CR>:match<CR>:diffupdate<CR>
@Rainning, is this what you would put in .vimrc? If not, what can you put in .vimrc to permanently enable :noh after every search?
For reader in 2021: nnoremap <nowait><silent> <C-C> :noh<CR>.
@LiamClink: I've updated the command, should be nnoremap. And yes you should put it in your .vimrc. I don't understand your question, since the next time you hit / on your key board and enter a new keyword to search, to old ones are all replaced, so you only need to cleanup by <C-C> yourself after every search.
g
gcochard

From the VIM Documentation

To clear the last used search pattern:

:let @/ = ""

This will not set the pattern to an empty string, because that would match everywhere. The pattern is really cleared, like when starting Vim.


...which would be a better solution to his problem as I understand it.
This is what I was looking for! I voted it up, the question is slightly vague. This led me to think this is what he wanted: "I now do another search for something gibberish that can't be found". Because that is what I was doing to clear the search, but not disable it so the next search would highlight again.
This is what I thought the question was about... here is a command I made to quicken clearing of the search string (and therefore removing all highlights): :command C let @/="" Using this allows you to type :C to clear the search string... very quick and doesn't affect future searching or highlighting.
@jcreamer898, see vim help on "registers" (:he registers). Vim has several different built-in registers that hold text, sometimes for yanked data, sometimes for last search, etc. When you do a search, vim puts the pattern in the "/" register, which you reference using @/. You can also assign values to registers using @regname=value where regname is the is the name of the register. So, @/="" is simply setting register "/" to an empty string (except that for the "/" register vim will clear the last search if it contains an empty string).
Add this to your .vimrc to get Ctrl+/ to clear the last search: noremap <silent> <c-_> :let @/ = ""<CR>
R
Rory O'Kane

You can do

:noh

or :nohlsearch to temporarily disable search highlighting until the next search.


thanks, this was helpful ... any command for returning the highlight ?
:nohs just shuts off the current highlighting. If you have :set hlsearch then it will continue to highlight your searches.
I think this is what the OP was searching for (although Shaun's answer works too). I'm upvoting this for being shorter. I know he accepted the nohls answer, but setting it will disable all search highlighting, even if another search is tried afterwards.
This is probably what the OP wanted in the first place and is the shortest, best answer IMHO.
Perfection is attainable even in this mortal realm! I will use this more than :help, and don't want to pollute : nnoremap :noh
佚名

I found this answer years ago on vim.org:

Add the following to your .vimrc:

"This unsets the "last search pattern" register by hitting return
nnoremap <CR> :noh<CR><CR>

Thus, after your search, just hit return again in command mode, and the highlighting disappears.


I think this is a much better solution than the one that's actually been accepted -- either this one or the other one where it's mapped to instead.
This is a much better answer to "nnoremap :noh" because it doesn't cause strange behavior.
An important thing to note, make sure you don't put any comments on the right hand side of a remap. They will be interpreted as commands for the remap as opposed to comments.
The comment is wrong; the command does not unset the last search pattern but simply switches off the highlighting of the current results; you can hit n to find the next occurrence (which will be highlighted again). BTW, when scripting, I would avoid the abbreviated form, and instead write :nohlsearch.
Add to avoid the display flashing and leaving noh in the command line - :nnoremap :nohlsearch
C
Community

From http://twitter.com/jonbho/status/2194406821

" Clear highlighting on escape in normal mode
nnoremap <esc> :noh<return><esc>
nnoremap <esc>^[ <esc>^[

The second line is needed for mapping to the escape key since Vim internally uses escape to represent special keys.


Just to be clear, this lets you clear the search highlighting by pressing the Escape key
For some reason, this makes my terminal vim start up as if "c" was pressed. Any ideas?
This caused some very strange behavior when I tried it: on startup, regular vim movements (eg j, k) would cause lines to be removed. nnoremap :noh didn't cause these problems. I couldn't track down the root cause.
hmm, I had the same problem as those above. Don't use this as-is without testing unless you like deleting your text randomly...
using "nnoremap :noh" makes vim always starting in "REPLACEMENT" mode.
m
millerdev

My original solution (below) was dirty and wasteful. I now use :noh

Like many features in Vim, the right way is often not easily discoverable.

--

(DO NOT DO THIS)

Search for an unlikely character sequence (mash the keys on the home row):

/;alskdjf;

This works in vim and less, and it's easier to remember/type than @ShaunBouckaert's logically cleaner solution "to clear the last used search pattern":

:let @/ = ""

A potential downside is that it adds junk to your search history.


Not only is this a dirty solution (which I myself used until now, no offense), another downside is that it adds an ugly red banner saying "pattern not found" at the bottom of the window, which is almost as annoying as the highlighting itself and requires further action to be discarded (e.g. "search + backspace").
It can also take a few seconds, as it actually searches the entire rest of the file. That's really annoying if the file is large. Of course, you could mark your current position, jump to the beginning, and search backwards for a character, but that's similarly dirty.
This is the solution most will have used before learning about the :nohl command. Once I learned about the latter, I immediately stopped to do those searches.
This is not an answer; it's just recommending to do what OP already does: "I now do another search for something gibberish that can't be found."
If you want a foolproof and short pattern just use /$4. It's not just unlikely to match anything but actually completely IMPOSSIBLE. $ must always be followed by a newline or be the end of the file, and 4 is neither a new line nor the end of the file. (The reason for 4 specifically is just that it is on the same key, so it's really easy to type quickly)
A
Anthony Geoghegan

The answers proposing :noh or :nohlsearch (e.g., Matt McMinn’s) are correct for temporarily disabling search highlighting – as asked in the original question.

I thought I'd contribute a mapping that I find useful in Normal mode:

nnoremap <C-L> :nohlsearch<CR><C-L>

By default, CtrlL in Vim clears and redraws the screen. A number of command line programs (mostly those using the GNU Readline library, such as Bash) use the same key combination to clear the screen. This feature is useful in the situation where a process running in the background prints to the terminal, over-writing parts of the foreground process.

This Normal mode mapping also clears the highlighting of most recent search term before redrawing the screen. I find the two features complement each other and it’s convenient to use one CtrlL for both actions together rather than create a separate mapping for disabling search highlighting.

NB: noremap is used rather than map as otherwise, the mapping would be recursive.

Tip: I usually remap Caps Lock to Ctrl to make it easier to type such key combinations; the details for doing this depend on your choice of OS / windowing system (and are off-topic for this answer). Both the following tips include information on mapping Caps Lock to Ctrl as well as Esc:

Map caps lock to escape in XWindows

Map caps lock to escape in Windows


s
sjas
nnoremap silent <cr> :noh<cr><cr>

That way I get rid of :noh shown in the commandline, when hitting enter after the search.

: is like starting entering a new command, Backspace clears it and puts the focus back into the editor window.


Thank you. The ":noh" showing up in the bottom left was driving me crazy, damn OCD.
I was trying to map it to shifted cr by doing nnoremap :noh but it didn't work, do you know why it might not be working?
I suspect you cannot combine shift with return, but I honestly have no idea.
@CharlieParker IIRC you can only use shift on [a-z] and such characters.
Instead of doing :<Backspace>, you can just add <silent> after the nnoremap to tell Vim to not display any output in the command area: nnoremap <silent> <cr> :noh<CR><CR>.
a
avocade

Remapped to in my .vimrc.local file, quick and dirty but very functional:

" Clear last search highlighting
map <Space> :noh<cr>

S
Sheharyar

Disable search highlighting permanently

Matches won't be highlighted whenever you do a search using /

:set nohlsearch

Clear highlight until next search

:noh

or :nohlsearch (clears until n or N is pressed)

Clear highlight on pressing ESC

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

Clear highlight on pressing another key or custom map

Clear highlights on pressing \ (backslash) nnoremap \ :noh

Clear highlights on hitting ESC twice nnoremap :noh


The nnoremap <silent> <esc> :noh<return><esc> solution works nicely in GUI vim, but causes severe problems with arrow keys and other ESC-encoded keys when running vim in a terminal. Don't put it in your ~/.vimrc without wrapping it in if has('gui_running') ... end. Also consider adding the <silent> which avoids flashing the :noh command in the status bar.
t
the Tin Man

I generally map :noh to the backslash key. To reenable the highlighting, just hit n, and it will highlight again.


P
Pablo Olmos de Aguilera C.

This is what I use (extracted from a lot of different questions/answers):

nnoremap <silent> <Esc><Esc> :let @/=""<CR>

With "double" Esc you remove the highlighting, but as soon as you search again, the highlighting reappears.

Another alternative:

nnoremap <silent> <Esc><Esc> :noh<CR> :call clearmatches()<CR>

According to vim documentation:

clearmatches() Clears all matches previously defined by |matchadd()| and the |:match| commands.


I faced some bugs in top solutions, so to save your time trying all the answers. Use this solution! Edit your .vimrc and put the following entry in it:nnoremap <silent> <Esc><Esc> :let @/=""<CR>
But that's what it says O.o. Maybe you could upvote?
I'm supporting your solution... It is the best one IMO... And I have also upvoted it.. :)
Clearing the search register with @/="" has the side effect of making n not work to get your search back. I prefer :noh which keeps the previous search in the register for re-use.
a
arcseldon

To turn off highlighting until the next search

:noh

https://i.stack.imgur.com/Skzzj.gif


0
00prometheus

Turn off highlighting as soon as you move the cursor:

Install vim-cool. It was created to fix this specific problem. It turns off highlighting as soon as you move the cursor. Be warned though, it requires a recent vim version!


This easily solves the problem. Remapping is just too much for me
Finally, no more extra keys to press lol
Should be a default option!
d
dkiyatkin

There are two 'must have' plugins for this:

sensible - Ctrl-l for nohlsearch and redraw screen. unimpared - [oh, ]oh and coh to control hlsearch.


coh still works, although there is a message suggesting to use yoh if you use coh
D
Deqing

If you have incsearch.vim plugin installed, then there is a setting to automatically clear highlight after searching:

let g:incsearch#auto_nohlsearch = 1

https://i.stack.imgur.com/75EF2.gif


t
the Tin Man

Janus for VIM and GVIM has a number of baked-in things for newbs like me, including

<leader>hs - toggles highlight search

which is exactly what you need. Just type \hs in normal mode. (The leader key is mapped to \ by default.)

HTH.


L
Lindsay Haisley

My guess is that the original question concerned not disabling search highlighting but simply clearing the highlighting from the last search. The solution of searching for a gibberish string, which the original poster mentioned, is one I've been using for some time to clear highlighting from a previous search, but it's ugly and cumbersome.

Several suggestions I've found to add nnoremap ... to ~/.vimrc have the effect here of putting vim into replace mode at startup, which isn't at all what I want. The simplest solution I've found is to add the line

nmap <esc><esc> :noh<return>

to my ~/.vimrc. This hews to the KISS principle and doesn't interfere with the arrow keys, which using a single does. A double- is required in command mode (or a triple- from insert or replace mode) to clear highlighting from a previous search, but from a UI perspective this makes the operation about as simple as possible.


What do you mean by the single interfering with arrow keys?
@hansmosh See unix.stackexchange.com/questions/28713/… I use two lines in my .vimrc as follows nmap <esc><esc> :noh<return> - to turn off search highlighting and nmap <esc>` :set hlsearch<return> - to turn on search highlighting
M
Matthieu

I personnaly like to map esc to the command :noh as follow:

map <esc> :noh<cr>

I wrote a whole article recently about Vim search: how to search on vanilla Vim and the best plugin to enhance the search features.


Remapping <esc> can be problematic because a timeout is added automatically, making it slow to reenter normal mode. vi.stackexchange.com/questions/16148/…
t
the Tin Man

This will clear the search highlight after updatetime milliseconds of inactivity.

updatetime defaults to 4000ms or 4s but I set mine to 10s. It is important to note that updatetime does more than just this so read the docs before you change it.

function! SearchHlClear()
    let @/ = ''
endfunction
augroup searchhighlight
    autocmd!
    autocmd CursorHold,CursorHoldI * call SearchHlClear()
augroup END

A
Amaynut

If you want to be able to enable/disable highlighting quickly, you can map a key to

" Press F4 to toggle highlighting on/off, and show current value.
:noremap <F4> :set hlsearch! hlsearch?<CR>

Just put the above snippet in you .vimrc file.

That's the most convenient way for me to show and hide the search highlight with a sing key stroke

For more information check the documentation http://vim.wikia.com/wiki/Highlight_all_search_pattern_matches


S
Stryker

I just use the simple nohl below and no plugins are needed.

:nohl


s
skywinder

One more solution by combining 2 top answers:

"To clear the last used search pattern:
nnoremap <F3> :let @/ = ""<CR>

Clearing the search register with @/="" has the side effect of making n not work to get your search back. I prefer :noh which keeps the previous search in the register for re-use. You can bind <F3> to that with nnoremap <F3> :noh<CR>
c
caopeng

you can use :noremap to turn on/off for the search result,like this

:noremap <F3> :set hls! hls?<CR>


J
John Slavick

I use the following in my ~/.vimrc

nnoremap <Leader><space> :noh<Enter>

This makes it very easy and quick to clear the current highlighted search. My leader key is mapped to \ so this makes the action very easy to perform with my right pinky finger and thumb.


t
the Tin Man

I think mixing @ShaunBouckaert and Mar 19 '09 at 16:22 answers is a good compromise :

" Reset highlighted search
nnoremap <CR> :let @/=""<CR><CR>

Press Enter and the highlighted text is no longer highlighted, while search highlighting is still enabled.


d
dinigo

Based on @baruch-even answer, you can delete search term on ESC double press while in normal mode with:

nnoremap <esc> :let @/ = ""<return><esc>
nnoremap <esc>^[ <esc>^[

I think the second binding is OK, but the first is dangerous. Remapping <esc> works nicely in GUI vim, but causes severe problems with arrow keys and other ESC-encoded keys when running vim in a terminal. Don't put it in your ~/.vimrc without wrapping it in if has('gui_running') ... end. Also consider adding the <silent> which avoids flashing the :noh command in the status bar.
r
ricardo

I don't like it either. I found it tiresome to enter :nohl all the time ... so i put the following mapping in my .vimrc

noremap <C-_> :nohl<cr>:<backspace>

The first bit (:nohl<cr>) clears the highlighting; the second bit (:<backspace>) is a trick to clean the command line. The search is still there in the background, so if you simply hit n it'll re-highlight and take you to the next occurrence.


a
ardnew

Define mappings for both behaviors, because both are useful!

Completely clear the search buffer (e.g., pressing n for next match will not resume search)

Retain search buffer, and toggle highlighting the search results on/off/on/... (e.g., pressing n will resume search, but highlighting will be based on current state of toggle)

" use double-Esc to completely clear the search buffer
nnoremap <silent> <Esc><Esc> :let @/ = ""<CR>
" use space to retain the search buffer and toggle highlighting off/on
nnoremap <silent> <Space> :set hlsearch!<CR>

With this, if I press <Esc> followed by an arrow key, it messes the buffer content because the Esc at the beginning of the arrow key is combined with the first <Esc> I've pressed, and vim is then left with the rest of the arrow key sequence which is garbage. And no, I'm not ready to give up on arrow keys for hjkl :)
@Eric I cannot reproduce it with gVim 8.2.2824 . Could you elaborate a bit? Also, try preceed <silent> with <nowait>
Unfortunately remapping <esc> like this will usually cause an annoying delay when exiting insert mode. See vi.stackexchange.com/questions/16148/….
p
pixel 67

I added this to my vimrc file.

command! H let @/=""

After you do a search and want to clear the highlights from your search just do :H