I am using python-mode which colors the parameters.

When I concatinate strings the variable color is represented as different:

On the other hand, if I use fstring, the variable is not represented as different color:


Please note that, if I enter non-existing variable, python-mode detects it:

enter image description here

[Q] Is there any way to give a color to variables inside a fstring under python-mode?


I think this will do it for Emacs versions < 27.1

(require 'python)

(setq python-font-lock-keywords
      (append python-font-lock-keywords
          '(;; this is the full string.
        ;; group 1 is the quote type and a closing quote is matched
        ;; group 2 is the string part
         ;; these are the {keywords}
          ;; Pre-match form
          (progn (goto-char (match-beginning 0)) (match-end 0))
          ;; Post-match form
          (goto-char (match-end 0))
          ;; face for this match
          (0 font-lock-variable-name-face t))))))

For later versions replace python-font-lock-keywords with python-font-lock-keywords-maximum-decoration.

I think this works on all strings now, including multiline ones (that seems to be a tricky one in general though). I left the {} in the highlight, they get replaced and that made sense to me.

Here is what it looks like for me: enter image description here

font lock is hard!

The two other posts I looked at related to this are:

  1. Repeated regex capture for font-lock

  2. Python mode - custom syntax highlighting.

  • 1
    I think with the new version you can get rid of the font-lock-keywords-only setting, then this works for everything but mulitline f-strings. see teh new picture above. – John Kitchin Jan 30 '20 at 12:39
  • 1
    That probably is invalid. You can't use the same kind of quotes for the dictionary key here. Try f'received {jobInfo["received"]}' instead. – John Kitchin Jan 31 '20 at 12:23
  • 1
    I asked it at emacs.stackexchange.com/questions/55586/… – John Kitchin Feb 17 '20 at 13:35
  • 1
    There are some interesting approaches and explanations in the answers to the new question. I have updated this answer so it works with \n in it, but there may be a more robust answer that leverages syntax described at emacs.stackexchange.com/questions/55586/…. It will take some work to make that also do what is done here though. – John Kitchin Feb 17 '20 at 22:04
  • 1
    In GNU Emacs 27.1 seems like it does not work :-( – alper Sep 22 '20 at 18:04

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.