Highlighting by Word, Line and Regexp
With Emacs’s Hi-Lock mode you can highlight by word, line or regular expression with ease. The highlighter functionality in Emacs is particularly helpful when if you are trying to do complex code refactoring or if you are fixing data or text by hand.
The Emacs Hi-Lock facility is obviously – and this should come as no surprise to you if you have used Emacs for a while – very complex with lots of whiz-bang features. I’ll concern myself with the most common use-cases for Hi-Lock and leave the more advanced concepts for another time.
Global Hi-Lock Key bindings
As luck would have it, the highlighter commands are bound to easy-to-reach key bindings.
M-s h lor
Highlights all lines matching a regular expression
M-s h por
Highlights everything matching a phrase
M-s h ror
Highlights everything matching a regular expression
M-s h uor
Deletes the highlighter under point
M-s h wor
Inserts a list of Hi-Lock patterns into the buffer
M-s h for
Searches for Hi-Lock patterns in the buffer to use.
NOTE:All of the highlight-xxxx commands are actually just aliases for the hi-lock-xxxx commands.
If you don’t like the Hi-Lock colors they can be customized easily with
M-x customize-group RET hi-lock-faces. You can of course alter the variable
hi-lock-face-defaults and add your own faces.
There is a mechanism for storing and restoring the Hi-Locks you’ve created. If you create highlights interactively you can tell Emacs to insert those patterns into the active buffer by running
M-s h w. Emacs will wrap the elisp patterns in the comment format used by the buffer (if one is defined) or ask if you no comment format is defined.
The patterns should be added to the top of the file, as Emacs will only search the first 10,000 characters (customize
hi-lock-file-patterns-range to change that amount) for the patterns before giving up.
Emacs will not highlight patterns found in a file automatically. You must explicitly tell it to do so by manually invoking
M-x hi-lock-mode or globally with
You can also add it to your .emacs file:
Emacs may ask you if you want to load the patterns if it finds any. If you find that as annoying as I do, you can add this to have Emacs always highlight any Hi-Lock patterns it finds in the file:
(setq hi-lock-file-patterns-policy #'(lambda (dummy) t))