[vim] 挿入モードで検索ハイライトを無効にする

概要

検索時のハイライトはありがたいけど、挿入する頃には鬱陶しいので消したい。
:nohを適当にマッピングしてもいいがそれも面倒くさい。

挿入モード遷移時に:nohを実行する

autocmdのInsertEnterを使えば、挿入モード遷移時に任意のコマンドを実行させられるので、ここでnohを叩かせる。

autocmd InsertEnter * :noh

が、ダメ。動作しない。

Why

ヘルプを叩いてみた。

:noh[lsearch]           Stop the highlighting for the 'hlsearch' option.  It
                        is automatically turned back on when using a search
                        command, or setting the 'hlsearch' option.
                        This command doesn't work in an autocommand, because
                        the highlighting state is saved and restored when
                        executing autocommands |autocmd-searchpat|.
                        Same thing for when invoking a user function.

autocommandでは機能しないってハッキリ書いてあった。

代替策

しかたないので、挿入モード移行時にはハイライト機能を無効にし、挿入モードを終了したら有効に戻すというアプローチを取る。

autocmd InsertEnter * set nohlsearch
autocmd InsertLeave * set hlsearch

いい感じに動いた。

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です