Search code examples
vimvim-syntax-highlighting

vim regex & highlight syntax: find a match and ignore sub-match in it


I am trying to write a syntax highlighter in VIM. How do you highlight a match within another match?

To find each match, I created two syn match lines, which work where the matches are separate.

syn match celString "^xpath=.\{-};"      -> matches "xpath=.........;"
syn match celComment "\${.\{-}}"         -> matches "${LIB_METADATA};"

highlight syntax results - first line has separated matches, while second line has overlapping matches

  • The first line is pink for the xpath string and blue for the ${..} string.

  • The second line is pink for the xpath string, but the ${..} contained inside that string is ignored.

I've tried to change the order of the syn match lines, but that doesn't have any effect.

I'd appreciate your ideas.


Solution

  • By default, Vim only applies the syntax groups to text that hasn't yet been assigned a syntax. To specify that one group can contain other groups, use the contains=... attribute:

    :syn match celString "^xpath=.\{-};" contains=celComment
    

    The order of definition shouldn't matter here. See :help :syn-contains for more information.