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:
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:
Use 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))