2

Is there any way to do this ? I'm using vim 8.2 with this python plugin. The inside of f strings for example is correctly highlighted but not the "f"

3

Syntax highlighting is a relatively deep subject and extending an existing highlighting scheme may get complicated depending on certain factors. I recommend you find a good reference and read up on things. One highly regarded source of information is Learn Vimscript the Hard Way which has three chapters (45-47) devoted to the topic

With that being said, I suspect this particular case can be handled fairly easily since a standalone "f", "b", "r" or "u" is pretty unique (i.e. unlikely to occur elsewhere in Python source code).

Here's a "quick and dirty" solution that works for me...

First, since you are just supplementing the existing configuration, create an "after" file to contain the new config: ~/.vim/after/syntax/python.vim. Edit this file and add these two lines...

syntax match pythonStrFormatTag /\<[brfu]\>/
highlight link pythonStrFormatTag Special

The first line defines a regex pattern to match the letters of interest. The surrounding \< and \> prevent a match when those letters are part of a word. If you want to use a slightly more refined pattern you could try \<[brfu]\>\ze['"] which will require a single or double quote after the letter but, thanks to the \ze, will not include it in the text to color.

Replace Special with any existing highlight group that has a color scheme that you like. Run :hi while editing a Python file to see what's available.

That's it. I just did a quick sanity test and it works but let me know if there are any issues. (The pattern might need a bit of refinement if there's a conflicting match that I didn't consider.)

13
  • I would use a lookahead to avoid consuming the quote, and then use ['"] because python, but otherwise looks great
    – D. Ben Knoble
    Sep 24 at 13:40
  • \zs and \ze actually don’t play well in syntax (or at least they didnt; maybe thats changed). They consume the parts of the match and discard them, so other syntax never has a chance to match those pieces. The perl-style operators (odd syntax, hard to remember for me) don’t consume (or do and put it back, same difference?), so they don’t interfere that way
    – D. Ben Knoble
    Sep 24 at 14:40
  • 1
    grep 'syn match.*\\z[se]' /usr/share/vim/vim82/syntax/*.vim returns over 500 matches...so I feel better about it now. :)
    – B Layer
    Sep 24 at 15:04
  • 1
    @D.BenKnoble (just read those links) Yes, interesting. What you said is true (as is what I guessed about relative performance)...or was true. My brief investigation suggests "was" but my confidence in that is low now. I'll have to look closer...if I can only find the time. :P
    – B Layer
    Sep 26 at 5:51

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.