4

I am trying to customize the syntax highlighting for python in vim. I want to highlight the keyword self but only when it is followed by a .. Here is the code I came up with:

syn match   pythonBoolean     "\(\Wself\)\%(\.\)"

Unfortunately, the . is also highlighted though I use a non capturing group \%(\.\).

Any idea?

BiBi
  • 7,418
  • 5
  • 43
  • 69

4 Answers4

6

You need to use the lookaround:

:syn match pythonBoolean "\(\W\|^\)\zsself\ze\." 

or

:syn match pythonBoolean "\(\W\|^\)\@<=self\(\.\)\@="
2

Building on @Meninx's answer, I added this to my .vimrc:

augroup PythonCustomization
  " highlight python self, when followed by a comma, a period or a parenth
   :autocmd FileType python syn match pythonStatement "\(\W\|^\)\@<=self\([\.,)]\)\@="
augroup END

Note 1: that in addition to what the op asked, it will also highlight when self is followed by a comma or a closing parenthesis.

Note 2: instead of using pythonBoolean, this highlights self using pythonStatement (personal preference). You can use other highlight-groups (run :syn with a python file open to see what's available)

jorgeh
  • 1,727
  • 20
  • 32
1

How about using lookbehinds and lookaheads? A valid regex for an occurence of self preceded by any non-word character [^a-zA-Z0-9_] and followed by . in common regex syntax is: (?<=\W)(self)(?=\.)

For vim regex take a look at this answer, and, if you need more help, check this page out.

Community
  • 1
  • 1
Nee
  • 566
  • 2
  • 17
1

As an alternative to lookbehind and lookahead, which tend to slow down vim:

syn match pythonBoolean "\<self\ze\."

Or, in case you want to highlight all objects:

syn match pythonBoolean "\<\w\+\ze\."
Vitor
  • 1,936
  • 12
  • 20