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.

1 Answer 1

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)))))))
10
  • In some cases I have to use {{ or }} to add curly brakets into the string (stackoverflow.com/questions/68253951/…). But the coloring get confused. Would it be possible to handle those cases as well? Example coloring in those cases: gist.github.com/avatar-lavventura/…
    – alper
    Commented Jul 19, 2021 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
    Commented Jul 19, 2021 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
    Commented Jul 19, 2021 at 11:35
  • Yay! Finally I am able to upgrade to emacs >.27.1
    – alper
    Commented Jul 19, 2021 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
    Commented Mar 10, 2022 at 10:08

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.