2

I want the piece of text std::string to be highlighted in vim according to the style defined in 'Type'. I can do that with

:call matchadd('Type','std::string')

It works. However, std::string is also highlighted in comments. In my code, comments follow a double slash //. How can I avoid highlights in comments?

3

Unfortunately, the match() functions are not aware of the syntax regions. So you need to fallback to change your pattern and exclude the comment pattern. Luckily for your case this is "quite easy" (well more or less) using a negative lookbehind assertion.

You need to use the /\@<!, which is the negative lookbehind atom used by Vims regexp engine. That would make your pattern something like this:

^\s*\(\/\/.*\)\@<!std::string

which comes down to

^        - start of line
\s*      - any number of whitespace
\(       - start group
  \/\/   - Start of your Comment
  .*     - Anything
 \)      - End group
 \@<!    - negative lookbehind assertion
 std::string  - Finally the search string you actually want to have highlighted ;)
  • Why is std::string highlighted only when it is in the beginning of the line (excluding white spaces)? For example, sizeof(std::string) is not highlighted. According to your explanations, it should, right? – Godoy Jul 22 '18 at 4:58
  • 1
    most likely the anchoring at the start of line prevents the match. Try whithout it – Christian Brabandt Jul 22 '18 at 16:06
  • Yes, it was that. The pattern \s*\(\/\/.*\)\@<!std::string highlights std::string everywhere in non commented lines. – Godoy Jul 23 '18 at 0:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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