hlsearch for Emacs

September 19, 2008

Vim has an option called “hlsearch” that highlights every instance of your most recent search term.  Like this:

Searching for "ground" in a text document using Vim.

Searching for "ground" in a document using Vim.

Emacs has the viper and vimpulse plugins that closely emulate vi/vim keyboard commands, but no hlsearch.  If you’re using viper and a version of Emacs later than 22.0, pasting the following into your .viper will give you this functionality.

(defun viper-flash-search-pattern ()
  (hi-lock-mode 0) (hi-lock-mode 1)
  (hi-lock-set-pattern
     (car viper-search-history) 'hi-green)
)

Unfortunately toggling hi-lock mode (line 2) is destructive if you’re using hi-lock mode for anything in addition to highlighting search terms.  In other words, there’s probably a better way to write this function. To solve the problem of clearing highlighting I’m no longer using, I use this (inefficient) snippet:

(viper-record-kbd-macro "//"
  'vi-state
  [(meta x) h i - l o c k - m o d e (control m)
   (meta x) h i - l o c k - m o d e (control m)]
't)

Tags: , ,

Leave a Reply