VIM syntax highlight matching

Viewed 706

I noticed that C++ functions were not getting any styles applied to them with my vim stylings, so I figured it'd be simple to add a quick regex match to find any word immediately followed by a (, and count that as a syntax.

In my .vim, I put:

syn match cppFun "\w+(?=\()"

This appears to work fine with other regex matchers, but vim complained about an unmatching \). However, checking :highlight, I did see the syntax cppFun was getting something set to it.

I figured that maybe the vim regex was backwards, and so I tried this out

syn match cppFun "\w+\(?=(\)"

And while it no longer complained about an unmatching paren, I was getting still not getting function highlights in my main.cpp.

What should the regex look like in order to get the syntax highlighting showing up?

This is what I was testing against with \w+(?=\():

int main(int argc, char** argv) {
    std::puts('Hello World');
    return 0;
}

Expecting to match main and puts

2 Answers

You can use

\v\w+(\()@=

Details

  • \v - enables the very magic mode when quantifiers and capturing/lookaround parentheses do not need backslash-escaping
  • \w+ - one or more word characters (letters, digits, underscores)
  • (\()@= - a positive lookahead ((...)@=) that requires its pattern (here, a ( char) to match immediately to the right of the current location.

To match a word followed by a ( without matching the (, use \w\+\ze(.

The \ze terminates the matching part of the regex. The + needs to be prepended with a \ to make it magic. (See :help magic).

Also positive lookahead in vim is done with \@=. Not with (?=...).

Related