0

Suppose I would like to highlight text after // as comments, but shall stop after a }, for example:

Some Text **//Some Comments**

Some Text **//Some Comments}** More Text

What I prepared in my syntax file is

syn match                           MyComment  "\v\/\/.*(\}|$){-}"
hi def link                         MyComment  GruvboxGray

, where I used {-} try to match the shortest content, but it does not work, still, everything after // are matched as comments, not interrupted by a }.

Is there a way to define the shortest match?

5
  • Your .* will gobble up everything. Try something like (untested): [^}]{-}
    – Friedrich
    Commented Jul 30 at 13:27
  • @Friedrich seems it's not working.... also, it shall be \} than } right?
    – athos
    Commented Jul 30 at 14:30
  • I don't think (even in \v mode) that you need to escape } here
    – D. Ben Knoble
    Commented Jul 30 at 20:10
  • @D.BenKnoble mmm.. the \v "very magic" mode is a bit mysterious. I think in "very magic" mode, all ASCII characters except '0'-'9', 'a'-'z', 'A'-'Z' and '_' have a special meaning. However Friedrich's answer works without escaping }. But, if in syntax file I define syn match MyTest "\vxx\}" and syn match MyTest "\vyy}" , then hi def link MyTest GruvboxRed, then in vi only xx} will be red, yy} won't. I'm confused.
    – athos
    Commented Jul 30 at 21:18
  • AFAIK, only opening curlies need to be escaped depending on magicness and whether they start a multi or are a literal "{". Closing curlies can be escaped but the regex engine should be able to tell from the context.
    – Friedrich
    Commented Jul 31 at 5:33

1 Answer 1

2

Your pattern is almost right, there's really just a little bit of confusion with multi and escapes.

In your pattern, you want to match two slashes followed by anything and terminated by a closing curly brace or a newline. You want the anything part to be non-greedy so you need to apply the non-greedy multi to it. The middle part of your pattern should be .{-}.

The OR statement to either match a closing curly brace or end of line is simply (}|$)

As a finishing note, you already cleverly use " to delimit your pattern and need not escape the slashes in it. See :help :syn-pattern.

Applying all this, your :syntax command becomes:

syn match MyComment "\v//.{-}(}|$)"

The same pattern without the very magic flag would have the same length. I'd favor this one because it's closer to the defaults:

syn match MyComment "//.\{-}(}\|$)"
1
  • Thank you so much. it's nice to see a neat solution to a tricky issue.
    – athos
    Commented Jul 30 at 21:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.