Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim Syntax Highlighting: highlight `self` python keyword with regex

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?

like image 604
BiBi Avatar asked Oct 19 '25 12:10

BiBi


2 Answers

You need to use the lookaround:

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

or

:syn match pythonBoolean "\(\W\|^\)\@<=self\(\.\)\@="
like image 129
Meninx - メネンックス Avatar answered Oct 21 '25 02:10

Meninx - メネンックス


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)

like image 30
jorgeh Avatar answered Oct 21 '25 02:10

jorgeh