Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I highlight member variables in Python?

I'm trying to set up a certain type of syntax highlighting for Python.

I want self and cls to be highlighted like comments. I want member variables to be highlighted like functions.

For example, if normal text is (white), comments are (gray), and functions are (red):

self._member

should be self(gray).(white)_member(red)

self._member.other.method()

should be self(gray).(white)_member(red).other.method()(white)

self._method()

should be self(gray)._method()(white)

I tried copying and modifying the syntax for decorators since they seemed similar, but no luck. I also took a look at the docs, but they were pretty intense. Any idea on how I could do this?

Edit:

I almost got it:

syn keyword pythonThis   cls self
syn match   pythonMember "\(cls\.\|self\.\)\@<=[A-Za-z_]\+\(\.\| \)"

hi link pythonThis    Comment
hi link pythonMember  Function

The only problem with this is that a dot following a member variable is red instead of white (self._member.other.method() isn't highlighted exactly as specified above). Not a big deal, but it would be nice to know how to ignore multiple groups in a single match (It doesn't seem that you can use \@<= multiple times).

like image 391
Dean Avatar asked Aug 03 '26 22:08

Dean


1 Answers

syn keyword pythonThis cls self

syn match pythonChain '\v(^|\W)(cls|self)\zs(\s*\.\s*\h\w*)+' contains=pythonMember
syn match pythonMember '\h\w*' contained

hi link pythonThis Comment
hi link pythonMember Function
like image 109
esneider Avatar answered Aug 06 '26 23:08

esneider



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!