I've found I can make some comments use a different face by customizing font-lock-syntactic-face-function.

To give some context, I'm setting some comments to use font-lock-doc-face, in situations the major mode isn't setting it.

Currently I'm swapping in a new function, while it works using setq seems clunky.

;; Just an example.
(defconst mycustom-comment-prefix "////")
(defvar mycustom-font-lock-syntactic-face-function-original nil)
(defun mycustom-font-lock-syntactic-face-function (state)
    ;; Check if this comment starts with `mycustom-comment-prefix'.
    ((and (nth 4 state)
       (let ((p (nth 8 state)))
           (buffer-substring-no-properties p (+ p (length mycustom-comment-prefix)))))
        ;; Default behavior.
        (funcall mycustom-font-lock-syntactic-face-function-original state))))

  ;; --- snip ---

  ;; When enabling...
  (setq mycustom-font-lock-syntactic-face-function-original

  ;; Restore when disabling...
  (setq font-lock-syntactic-face-function

Is there a better way to handle the function override?

  • 1
    I’m voting to close this question because questions about "the best way" or "is there a better way" are too broad and invite primarily opinion-based answers. As such they're off-topic here.
    – Drew
    Commented Jun 26, 2020 at 15:20
  • Seems reasonable, I wasn't sure how to phrase this question, I'm interested to customize font locking and not sure if I'm overriding this in the right way.
    – ideasman42
    Commented Jun 27, 2020 at 3:42
  • You may be able to find a more specific question, perhaps by looking closer at something you are doing which doesn't do what you expect, or by asking how to do some specific thing. Underneath a vague or broad request for ideas or advice there are often some specific problems or questions. I'm guessing that's the case here.
    – Drew
    Commented Jun 27, 2020 at 4:17

1 Answer 1


Some of the details of what is "this" is missing, as is the explanation of what you find clunky, but I'd recommend you use add-function and remove-function instead of setq:

(defun mycustom-font-lock-syntactic-face-function (orig-fun state)
  ;; Check if this comment starts with `mycustom-comment-prefix'.
  (if (and (nth 4 state)
             (goto-char (nth 8 state))
             (looking-at mycustom-comment-prefix)))
    ;; Default behavior.
    (funcall orig-fun state)))

  ;; --- snip ---

  ;; When enabling...
  (add-function :around (local 'font-lock-syntactic-face-function)

  ;; Restore when disabling...
  (remove-function (local 'font-lock-syntactic-face-function)
  • Thanks, this works perfectly, clarified this
    – ideasman42
    Commented Jun 29, 2020 at 0:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.