user3012908
user3012908

Reputation: 25

How do I not highlight (being highlighted using matchadd()) a pattern in comments in Vim

For example, I want any character except space before or after a : to get highlighted. And for that I use:

highlight OpSpace ctermbg=darkblue ctermfg=white guibg=#F59292

:au BufWinEnter *.v,*.sv let w:m1=matchadd('OpSpace', '[^ ][:]\|[:][^ ]', -1)

This will highlight following:

reg [3:0] var;

The problem with it is that it highlights the comments also. Example being:

// The Joker likes to:

The o: part gets highlighted which I do not want (it is in a commented line, commented using //).

Any suggestion is appreciated.

Thanks in advance.

Upvotes: 1

Views: 212

Answers (1)

Ingo Karkat
Ingo Karkat

Reputation: 172550

You have two options:

Use syntax highlighting with containment

Instead of using matchadd(), which is separate from the syntax highlighting mechanism, you could extend the default syntax rules for your filetype. In syntax highlighting, subordinate matches must be explictly contained in upper-level groups. To avoid matching in comments, just don't add a containment there. The downside here is that you're integrating with another syntax, and finding all the groups to add the containment may not be trivial.

Refine the regexp

If this is just about //-style comments, you can add a negative lookbehind (see :help /\@<!) to the pattern:

:au BufWinEnter *.v,*.sv let w:m1=matchadd('OpSpace', '\%(//.*\)\@<![^ ][:]\|[:][^ ]', -1)

This matches only when there's no preceding // in the line.

Upvotes: 2

Related Questions