4

I am using Vim 8.1 on Debian 11 Bullseye, but it does not work in the recent Vim 8.2 either.

I would like to syntax highlight a Python formatted string, which looks currently in vim so:

is

but should look like this:

should

(compare the curly braces and their content)

Does anyone know of a plugin that does this "properly", or can provide the syntax I need to insert in /usr/share/vim/vim81/syntax/python.vim to achieve this highlighting?

2
  • How about trying :syntax region pythonFString matchgroup=pythonString start="f'" end="'" skip="\\'" contains=ALL? It might need tweaks though. Commented Dec 7, 2021 at 18:51
  • Thanks, but it does not work and I do not have the expertise to apply any 'tweaks'. It colors everything within the formatted string, also the string parts outside the {} pairs (not a problem, but one had to construct four variants of your syntax, because a Python formatted string can be enclosed in (1) single quotes, (2) double quotes, (3) triple single quotes, and (4) triple double quotes). The example image in the OP is colored by the pip/pyperclip package, which does everything right. Also, I have seen several web highlighters doing it right, like stackoverflow. Commented Dec 8, 2021 at 10:08

2 Answers 2

7

There is an appropriate highlighter on github: https://github.com/vim-python/python-syntax

In .vimrc, you need to enable either everything with

let g:python_highlight_all = 1

or specifics, like I did:

let g:python_highlight_string_format = 1
let g:python_highlight_builtin_objs  = 1

A python formatted string now looks like:

enter image description here

(with my color definitions)

Sign up to request clarification or add additional context in comments.

1 Comment

Unfortunately, it looks broken for long github.com/vim-python/python-syntax/issues/98
0

The plugin vim-python/python-syntax has a broken syntax highlighting for f-strings, see https://github.com/vim-python/python-syntax/issues/98

But the fix (not complete yet) exists in vim repository: https://github.com/vim/vim/pull/14057

To try it now one can execute the following code:

mkdir -p "$HOME/.vim/syntax
curl -s https://raw.githubusercontent.com/vim/vim/21c6d8b5b6ef510c9c78b9dfb89a41146599505f/runtime/syntax/python.vim \
  > "$HOME/.vim/syntax/python.vim"

After that, the f-strings are highlighted as a regular code

enter image description here

1 Comment

Your answer makes it sound as if the PR to the Vim project would fix a bug on the python-syntax repo. The latter was apparently forked from Vim 6.1 (!) and last updated four years ago. It's probably best to let it rest in peace.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.