Hello.
Suppose I have a few words I would like to highlight, so I want to change the color of those few words only to, say, green.
Is there an easy way to do this in emacs?
Thank you.
Hello.
Suppose I have a few words I would like to highlight, so I want to change the color of those few words only to, say, green.
Is there an easy way to do this in emacs?
Thank you.
This is what I've done, using font-lock-add-keywords
. I wanted to highlight the words TODO:
, HACK:
, and FIXME:
in my code.
(defface todo-face
'((t ()))
"Face for highlighting comments like TODO: and HACK:")
(set-face-background 'todo-face cyan-name)
;; Add keywords we want highlighted
(defun add-todo-to-current-mode ()
(font-lock-add-keywords nil
'(("\\(TODO\\|HACK\\|FIXME\\):" 1 'todo-face prepend))
t))
Use the function font-lock-add-keywords
to define a new matcher for the string in question, binding that matcher to some face you've defined that will display as green. For example:
(font-lock-add-keywords nil
'("\\<foo\\>" 0 my-green-face))
Note that you can specify a particular mode where I wrote nil
above, and the matching forms can take on any of six different styles. See the documentation for the variable font-lock-keywords
for the rules and a few examples.
If you want them highlighted only temporarily, I find M-x highlight-regexp
command very helpful, it is especially nice for looking through log files of sorts. For example you made yourself a logging class that outputs some tracing info like MyClass::function() >
when function is run and MyClass::function() <
when it exits (can be especially useful sometimes when debugging multithreading issues) then you just ask emacs to highlight some of them green and other red and then you can see how did the execution go.
I use what Dimitri suggested. In particular, I have the following two lines in my .emacs
(global-hi-lock-mode t)
(global-set-key (kbd "C-M-h") 'highlight-regexp)
Every-time I need to highlight a certain word (or regex) in a buffer, I hit "C-M-h", which then prompts me for the word (or regex) I want to be displayed differently and then for a face to display it in.
The highlight package has highlight-regex which does exactly what you want.