Search code examples
vimvim-syntax-highlighting

Vim custom syntax, excluding previous match highlighting in a region


I'm writing a vim syntax highlighting script for a file that uses * to denote the start of a comment, except when surrounded by {}. i.e.

* This is a comment, bellow is math
{ x_variable * y_variable + 10.0 } 

I would like to highlight only the brackets, and ignore the comment highlighting inside, while still maintaining highlighting for numbers.

So far I have:

syn match mathSym "[{}]"
syn region mathRegion start=+{+ send=+}+ contains=numberHi
syn match commentHi "\*.*$" display contains=@Spell

hi link commentHi Comment
hi link mathSym Statement
hi link mathRegion Normal

I'm not sure if this is the right way to do it. It seem to ignore the * as a comment, and provide number highlighting, but no highlighting for the brackets.

I tried

region mathRegion start=+{+ send=+}+ contains=numberHi, mathSym

but this ends up setting all highlighting in the file to Normal


Solution

  • Your question is missing the numberHi stuff, but this should do the trick:

    syn region mathRegion matchgroup=mathSym start=+{+ end=+}+ contains=numberHi,mathSym
    syn match commentHi "\*.*$" display contains=@Spell
    
    hi link commentHi Comment
    hi link mathSym Statement
    
    • Instead of a separate match for mathSym, you can use the matchgroup=mathSym to highlight the start and end.
    • Also, you don't need to link mathRegion to Normal; just use it for structure.
    • The x * y won't match inside mathRegion, because it isn't contained in here. I don't see any problem with it.

    PS: Do you know the SyntaxAttr.vim - Show syntax highlighting attributes of character under cursor plugin? It's a great help when writing syntaxes.