0

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:

str

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 in python-mode for Emacs version >27.1?


Related answer for Emacs <27.1: https://emacs.stackexchange.com/a/55186/18414 When I apply it, it messes up all the original coloring in Python-mode. Everything becomes white except strings.

Drew
  • 75,699
  • 9
  • 109
  • 225
alper
  • 1,238
  • 11
  • 30

1 Answers1

1

I am using this:

(if (version< "27.0" emacs-version)
    (setq python-font-lock-keywords-maximum-decoration
        (append python-font-lock-keywords-maximum-decoration
            '(("f\\(['\"]\\{1,3\\}\\)\\(.+?\\)\\1"
               ("{[^}]*?}"
            (progn (goto-char (match-beginning 0)) (match-end 0))
            (goto-char (match-end 0))
            (0 font-lock-variable-name-face t)))))))
djangoliv
  • 3,169
  • 16
  • 31
  • In some cases I have to use `{{` or `}}` to add curly brakets into the string (https://stackoverflow.com/questions/68253951/how-do-i-add-curly-brackets-to-f-strings-in-python-3/68254078#68254078). But the coloring get confused. Would it be possible to handle those cases as well? Example coloring in those cases: https://gist.github.com/avatar-lavventura/27bcfb5df8b9d243fa8bf4b7928d2254#gistcomment-3817024 – alper Jul 19 '21 at 10:07
  • Also can we add a condition to apply your function only for emacs `>27.1`? because it does not work for `<27.1` :-( // Even it works with `<27.1` that will be golden – alper Jul 19 '21 at 10:08
  • You can add a test for emacs version (I edited my answer). For the "{{" case, I don't have solution yet. – djangoliv Jul 19 '21 at 11:35
  • Yay! Finally I am able to upgrade to emacs `>.27.1` – alper Jul 19 '21 at 12:14
  • Sorry for pretty late comment, when I try `f"{variable}"` it shows `variable` as white white, it is same on your end or does it apply different color? – alper Mar 10 '22 at 10:08
  • LightGoldenrod (yellow) for me (Face: font-lock-variable-name-face) – djangoliv Mar 10 '22 at 16:49
  • Could this be applied only for the string color in between `{}` and does not apply for the other variable colors? – alper Mar 10 '22 at 18:02
  • you can use any face (even a specially created one) by replacing `font-lock-variable-name-face` with the face you want in the proposed code. – djangoliv Mar 11 '22 at 07:53
  • I was not able to figure out related face name only for the `{}`, I can try to ask it in different quation – alper Mar 11 '22 at 13:30
  • Yes, I think you should ask another question. – djangoliv Mar 11 '22 at 14:55