Today, I want to share a small trick for Emacs. In vim, strings like TODO or XXX are highlighted to make them easier to find and notice. I find this quite practical, so I also wanted this in Emacs.

Trailing whitespace

My first trick is to use (setq-default show-trailing-whitespace t). This will highlight trailing whitespace on a line in red. It has two uses: it helps to avoid superfluous whitespace, but it can also be used to mark lines. So I add # TODO       at the end of a line or just append some whitespace to be able to find the line again. I use this quite often when moving around a file while editing. I think of it like a little temporary post-it note. I rarely check this into source control.

Vim-like highlighting

I would nevertheless also like to highlight the actual strings, but only in comments and docstrings. There is a simple version by James Cherti [edit: and more]. That version is a minor mode, which may be very nice if you want to switch it on and off. Unfortunately, it applies the highlighting also in normal code, string literals, etc.

I don’t care about switching it off, but I care very much about having it only in comments/docstrings. So I’ll provide some code for my needs, tested on Emacs ≥ 30.1. Making it into a minor mode is left as an exercise to the reader.

First, we need a helper function that matches a regular expression. The speciality is that we will check that the face of the matched text corresponds to a comment and/or docstring. (Note that I like to prefix my/ to functions and variables in my Emacs config to avoid namespace clashes.)

(defun my/font-lock/match-in-comment
    (regex limit &optional include-docstrings subexp)
  "Match REGEX up to LIMIT, but only if the face at
the start of the match is `font-lock-comment-face'.

If INCLUDE-DOCSTRINGS is given and non-nil, also allow
matches if face is `font-lock-doc-face'.

The optional argument SUBEXP (default 0) specifies
which group of the match should be treated as the
whole match.  This has two consequences.  First,
point is moved to the end of the subgroup match
instead of the whole match.  Second, check the face
at the beginning of the subgroup.  For
`font-lock-add-keywords', you still need to specify
the subgroup separately."
  (let ((match-faces
         (if include-docstrings
             '(font-lock-comment-face
               font-lock-doc-face)
           '(font-lock-comment-face)))
        (group (or subexp 0))
        case-fold-search) ; always case-sensitive!
    (catch 'found
      ;; Keep looking for the regex.
      ;; If found, check if we're in a comment.
      (while (re-search-forward regex limit t)
        ;; Move point to the end of the relevant
        ;; subgroup.
        (goto-char (match-end group))
        ;; Test if we are in a comment (or docstring)
        ;; by checking face.  The face returned by
        ;; `get-text-property' could be a list of
        ;; faces, so we just make sure it's always
        ;; a list.
        (let ((face
               (ensure-list
                (get-text-property (match-beginning group)
                                   'face))))
          (when (seq-intersection match-faces face)
            ;; Found one, return `t'.
            (throw 'found t))))
      ;; Default value: no match
      nil)))

Then we can create a regular expression that matches our keywords. One complication is that we can match on word boundaries, but Emacs considers _ and - to be word boundaries. This is normally fine, but for these keywords I don’t like it. Let’s build a regular expression with rx, which is more readable than a string. I hope it is obvious how to add/remove keywords. Here it is wrapped in a complete function:

(defun my/prog-mode/todo-in-comment-matcher (limit)
  "Match TODO-type keywords if the match's face is
`font-lock-comment-face' or `font-lock-doc-face'.

The matching is bound by LIMIT."
  (my/font-lock/match-in-comment
   (rx ;; Start of line or not preceded by _/-.
       (or line-start (not (any "_-")))
       ;; Word boundary.
       word-start
       ;; The actual keywords.
       (group-n 1 (or "BUG"
                      "FIXME"
                      "TODO"
                      "XXX"))
       ;; Word boundary.
       word-end
       ;; Start of line or not followed by _/-.
       (or line-end (not (any "_-"))))
   limit t 1))

Emacs Lisp’s regular expressions do not support lookahead. That means we are using a trick here. We match a string that is surrounded either by line start/end or a character that is neither _ nor -. Additionally, we require a word boundary (but that matches an empty string and does not “eat” any characters). We have to move point back to the end of group 1, which contains the actual keywords, otherwise TODO TODO would only match the first keyword. That’s what the subexp argument is for.

Now let’s define a nice face for our highlight. I like this one:

(defface my/highlight-todo-face
  '((t :foreground "firebrick4"
       :background "goldenrod1"
       :weight normal
       :slant normal))
  "Face for TODO-type keywords.")

I want this to apply to all major modes derived from prog-mode, so I’ll add it to that mode’s hook:

(add-hook 'prog-mode-hook
          (lambda ()
            (font-lock-add-keywords
             nil ; current buffer
             '((my/prog-mode/todo-in-comment-matcher
                1 ; use group 1 of regex
                'my/highlight-todo-face
                t)) ; override existing face
             ;; Append.
             t)))

It is important to append the matcher, because it relies on comments/docstrings having already been highlighted.

Bonus round

You can also use the matcher function for other things. In Emacs Lisp, symbols in comments are highlighted in a different colour. Of course, Emacs cannot tell a symbol from a word, so the convention is to use `various' different ‘kinds’ of 'quoting' styles. However, this only applies to single, symbol-like strings. Spaces or parentheses disable the colouring. This has good reasons, but I prefer to use quotes also for different things, e.g., key combinations. In that case, ‘C-j’ would highlight but ‘C-x C-e’ would not. I do not use pairs of straight quotes, since that complicates the opening/closing quote logic. Here’s the solution with the function we already saw above:

(defun my/elisp/quotes-in-comment-matcher (limit)
  (my/font-lock/match-in-comment
   (rx (or (: "`" ; ASCII approximation
              ;; do not allow nested quotes/newline
              (group-n 1 (1+ (not (any "\n`'"))))
              "'")
           (: "‘" ; Unicode curly quotes
              ;; do not allow nested quotes/newline
              (group-n 1 (1+ (not (any "\n‘’"))))
              "’")))
   limit))

;; Apply also to Lisp interaction mode.
(dolist (mode '(emacs-lisp-mode
                lisp-interaction-mode))
  (font-lock-add-keywords
   mode
   '((my/elisp/quotes-in-comment-matcher
      1 font-lock-constant-face t))
   t))

Update 2026-11-07

While searching for a way to highlight headings in comments (;;;, ;;;;) in Emacs Lisp, I found that there is more prior art apart from the James Cherti snippet and the oft-cited and heavyweight hl-todo.

The Emacs Wiki lists fic-mode.el by Trey Jackson. I am at least encouraged by the fact that the implementation idea is basically the same as mine, although Trey was 16 years earlier (credit where it’s due).

There is also comment-tags, which is equally lightweight but might have a more robust mechanism to check if we’re in a comment. Maybe something to look at.


All code on this page is dedicated to the public domain:

Written 2026 by Tobias Brink

To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.

You should have received a copy of the CC0 Public Domain Dedication along with this software. If not, see https://creativecommons.org/publicdomain/zero/1.0/.