替换后如何防止vim突出显示匹配项?

Ben*_*kes 15 vim

set hlsearch在我的~/.vimrc. 这通常非常有用,但是:noh在我执行类似替换操作'<,'>s/$/',/(在我运行它后突出显示每一行的结尾)之后必须这样做很烦人。vim像这样替换后如何不突出显示?

我在 Ubuntu 9.04 和vim7.2 上。我在 OS X 10.6(也是vim7.2)上有同样的问题。对两者都有效的东西是可取的。

更新:我收到的所有答案都只是添加了一个要执行的键映射:noh(或等效项)。我真的试图避免我真正习惯的自定义键行为,但是如果没有它们(例如在朋友的计算机上等),我就会惨败。我想在做替换后vim自动做:noh。也就是说,我只需要hlsearch在使用/or 时*(也许是其他一些情况),而不是其他时候。

小智 9

我有两种不同的解决方案,都很好,每个都有细微的不同行为。我最喜欢的是选项 2:

  1. 我的 .vimrc 中有以下两行:

    autocmd cursorhold * set nohlsearch
    autocmd cursormoved * set hlsearch
    
    Run Code Online (Sandbox Code Playgroud)

    如果光标不移动并关闭 hlsearch,第一个等待超时(不可配置)。如果光标再次移动,第二个会将其重新打开。

    这不是一个完美的解决方案,但它对我有用(并且当超时可配置时将接近完美 - 现在,超时与 vim 的内置计时器相关联。)

  2. 或者您可以尝试以下几行:

    autocmd cursorhold * set nohlsearch
    noremap n :set hlsearch<cr>n
    noremap N :set hlsearch<cr>N
    noremap / :set hlsearch<cr>/
    noremap ? :set hlsearch<cr>?
    
    Run Code Online (Sandbox Code Playgroud)

这将在没有光标移动的短暂超时后关闭 hlsearch,并为标准搜索命令重新打开它。它没有涵盖重新打开 hlsearch 的所有可能性,但它足以作为概念证明的入门。


Dou*_*ris 7

如果您不想永久禁用,您可以绑定一个键来切换高亮显示,如此答案中对 stackoverflow 上的类似问题的建议。

map  <F12> :set hls!<CR>
imap <F12> <ESC>:set hls!<CR>a
vmap <F12> <ESC>:set hls!<CR>gv
Run Code Online (Sandbox Code Playgroud)

如果要永久禁用突出显示:

11.1. After I searched for a text with a pattern, all the matched text
      stays highlighted. How do I turn off the highlighting
      temporarily/permanently?

The 'hlsearch' option controls whether all the matches for the last
searched pattern are highlighted or not. By default, this option is not
enabled. If this option is set in a system-wide vimrc file, then you can
turn off the search highlighting by using the following command:

    :set nohlsearch
Run Code Online (Sandbox Code Playgroud)

(来自VIM 常见问题解答

  • 我知道这个选项。问题是我通常不会*搜索*我想要替换的内容,因此在大多数情况下突出显示我替换的内容毫无意义。但是,当我*正在*搜索某些东西时,它非常有用,因此我不希望它*完全*消失。 (2认同)
  • @jamessan:我知道这是一个*搜索*和替换。只是那时我不需要突出显示它。主要是烦恼比什么都重要。 (2认同)