In all the examples of font-lock-add-keywords I've seen, the font face is static.

That is, there is a regex or a matcher function and a literal font face identifier.

Is it possible to set the face dynamically? So the font face used can be selected using code that interacts with the matches for example?

Otherwise I would have to register multiple matchers, one for each face used.

  • "font face" isn't a clear term, to me. I think you just mean face, or maybe just font (one face attribute). Please clarify what you mean for this. – Drew Mar 29 at 15:23

Yes, you can. See the Elisp manual, node Search-based Fontification.

font-lock-keywords (which you set using font-lock-keywords, e.g. font-lock-add-keywords) can use a FACESPEC expression, which is evaluated to provide the face to use.

FACESPEC is an expression whose value specifies the face to use for highlighting. In the simplest case, FACESPEC is a Lisp variable (a symbol) whose value is a face name.

;; Highlight occurrences of ‘fubar’,
;; using the face which is the value of ‘fubar-face’.
("fubar" . fubar-face)

However, FACESPEC can also evaluate to a list of this form:

(face FACE PROP1 VAL1 PROP2 VAL2...)

to specify the face FACE and various additional text properties to put on the text that matches. If you do this, be sure to add the other text property names that you set in this way to the value of font-lock-extra-managed-props so that the properties will also be cleared out when they are no longer appropriate. Alternatively, you can set the variable font-lock-unfontify-region-function to a function that clears these properties. *Note Other Font Lock Variables::.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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