Since back-ticks are often used for literals, is there a way I can highlight these in code comments?
So this:
# This is a comment, this is a literal: `4 + 4`.
# let's make things interesting (`literal_a`,`literal_b`).
Can display like this:
Emacs Stack Exchange is a question and answer site for those using, extending or developing Emacs. It only takes a minute to sign up.
Sign up to join this communityUse font-lock-add-keywords
for to add extra fontification.
See the documentation of font-lock-keywords
. You especially need the OVERRIDE
flag to override the normal fontification of the comment.
Use a function as MATCHER
. That function should search for the next comment or make sure that you are in one. Afterwards it should search for your literals.
The following lisp code demonstrates the procedure. It defines a minor mode clit-mode
that highlights the literals more-or-less as you specified them. (Currently, it does not highlight `4 + 4`
. But I am confident that you can fiddle around with the code until it does exactly what you want.)
Note that this code assumes that the character syntax is used for delimiting comments. It works on the basis of syntax-ppss
.
(defcustom clit-regexp "`\\_<[^[:space:]]+\\_>`"
"Regular expression matching literals in comments."
:type 'regexp
:group 'comment)
(defcustom clit-face 'hi-red-b
"Face for matching literals in comments."
:type 'face
:group 'comment)
(defun clit-matcher (limit)
"Search for `literal` in comments up to LIMIT."
(let (found)
(while (and
(null found)
(or
(ppss-comment-depth (syntax-ppss))
(comment-search-forward limit 1)))
(unless (setq found
(re-search-forward clit-regexp
(min (line-end-position) limit)
t))
(forward-line)))
found))
(defvar clit-keywords
'((clit-matcher
(0 clit-face t)))
"Font lock keywords for `clit-mode'.")
(define-minor-mode clit-mode
"Minor mode for highlighting literals in comments."
:lighter " `"
(if clit-mode
(font-lock-add-keywords nil clit-keywords t)
(font-lock-remove-keywords nil clit-keywords))
(font-lock-flush)
(font-lock-ensure))
emacs-lisp-mode
has a nice built-in system and it is just a matter of adding a few lines of code here and there.cc-mode
can use a different approach -- see emacs.stackexchange.com/a/20132/2287 and emacs.stackexchange.com/a/20228/2287