Vim syntax highlighting: Bisect code inside parentheses and target each side

Viewed 117

Vim scripting newbie here, trying to write a syntax file for an ML-like language.

What I'm trying to do is apply type syntax highlighting rules to type annotations that exist to the right of a colon and inside of parentheses.

let foo (arg1 : Int) (arg2 : Maybe b) (arg3 : a -> b)
                ^^^          ^^^^^^^          ^^^^^^

I'm aware this is less of a question and more of a "please help" (apologies!), but I've been banging my head against this for a while and I really have no idea how I'm supposed to be tackling it. Should I be doing some sort of recursion, or does it require some regex wizardry, or some other clever vim tricks I'm unaware of.

1 Answers

You can use a :syntax region command to match on the delimiters (: and )), that would be the simplest approach.

This is a somewhat naive attempt, it works but also puts the delimiters inside the syntax group:

syntax region Type start=":" end=")"

You can improve on it by using anchors in your delimiters to only start matching on the first character after the starting pattern and stop matching on the last character before the ending one. See :help :syn-pattern for details on the possible anchors.

syntax region Type start=":\s*"ms=e+1 end="\s*)"me=s-1

(This one also skips the whitespace between the type and the delimiters, which might matter if you're styling the Type group with a background color.)

This answer is, of course, somewhat simplistic, since in real syntax highlighting use cases you'll often will have much more complex situations where you're matching the same parts of the text multiple times and you'll have complex interactions between the the syntax matches, with some of them being contained in others, or setting a next group to match... But hopefully this will get you started!

Related