0

In my code, something like

#include <whatever>

is highlighted: #include (which belongs to the group 'cInclude') in pink; and <whatever> (belonging to the group 'cIncluded') in red. (Edit: whatever is any word.)

Also, to highlight the word vector according to the 'Type' style (in green) I do the following:

:call matchadd('Type','\<vector\>',0)

Here, 0 sets the priority to a low value. With this, my intention is that in

#include <vector>

, <vector> is highlighted according to the group 'cIncluded', and not according to the group 'Type'.

Unexpectedly, I do not get that result. The highlight for <vector> in #include <vector> turns out to be:

< in red (as in the group 'cIncluded')

vector in green (as in the group 'Type')

> in red (as in the group 'cIncluded')

Why?

4
  • 1
    \< and \> actually mean start-of-word and end-of-word in Vims regexp Sep 18, 2018 at 8:00
  • Yes, I am aware of that. I only want to highlight the word 'vector' when it is alone, but I do not want to highlight it inside the word 'vectorize', for example.
    – Godoy
    Sep 18, 2018 at 8:10
  • 1
    But you most likely want to have the < and > also included in your match, if I understand the question correctly, right? Sep 18, 2018 at 8:27
  • I want vector to be highlighted in green everywhere in the code except in the excerpt #include <vector>, where it should be highlighted in red. And I do not want vectorize to be highlighted.
    – Godoy
    Sep 18, 2018 at 8:34

2 Answers 2

3

From help matchadd:

Syntax highlighting (see 'syntax') is a separate mechanism, and regardless of the chosen priority a match will always overrule syntax highlighting.

To match everywhere except certain contexts, you can use zero-width atoms:

:call matchadd('Type', '\(#include <\)\@<!\<vector\>')
:call matchadd('Type', '\<vector\>\(>\)\@!')

The first matches the complete word vector if not preceded by #include <, and the second matches when it's not followed by >. Together, these should cover all occurrences of the word other than inside #include <vector>.

2
  • Thank you for the workaround. However, my question is why the priority that I set does not work.
    – Godoy
    Sep 18, 2018 at 9:23
  • Edited to add the relevant excerpt from the docs
    – JigglyNaga
    Sep 18, 2018 at 9:32
4

I would consider using syntax matching instead of matchadd() for this:

:syntax match Type /\<vector\>/

Because you are not specifying containedin, this will not match inside the cIncluded group that already exists. See :help :syn-containedin.

1
  • This is the best way to get the highlighting that I was looking for.
    – Godoy
    Sep 18, 2018 at 17:24

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.