Search code examples
vimsyntax-highlightingvim-syntax-highlighting

Vim syntax highlighting: overlapping regex


I try to add some syntax highlighting for javascript to vim, but I keep running into one problem: when characters are already highlighted, they seem to be completely ignored by all other regular expressions.

For example, I tried to add syntax highlighting for the argument list of a function. While creating the right rexex I disabled the syntax highlighting for the function keyword, such that it was easier to see what my regex did. I ended up with the following (working) regex:

syn match javaScriptArguments "[(=\:\s,]function.\{-}(\zs.\{-}\ze)"

However, as soon as I enabled the highlighting for the function keyword again, this line doesn't work anymore. It seems that vim simply excludes everything which is already highlighted, and thus it won't find any matches for the regex above, even though it won't result in characters being highlighted twice.

How can I solve/work around this problem?


Solution

  • Syntax definitions must be contained for them to match inside other syntax items. Find all the gruesome details at :help syn-contains.

    In your case, you're relying on a look-before of the "function" keyword via \zs. In my experience, that's bound to cause problems, but may turn out to be unneccessary once you use contained. In general, it is difficult to extend an existing syntax definition without modifying the original script (which I suppose is what you're intending to do). Have a look at :help :syn-containedin and :help :syn-nextgroup.