2

I use the following in my .vimrc to match capitalised strings and highlight them:

match Macro /\v<[A-Z|_]{2,}>/

However, I don't want to match comments (ie. where a // preceeds the text in the same line or where the text is surrounded by a /* and */).

How do I modify the above to achieve this?

quant
  • 21,507
  • 32
  • 115
  • 211
  • 1
    I don't think you do, but it would be really interesting to add zero-width assertions to vim's regexes for e.g. "the current position is/isn't inside a syntax region named X" – hobbs Jun 01 '14 at 23:32
  • I haven't tried this, but maybe write a conflicting syntax rule that is only active within comments? – merlin2011 Jun 01 '14 at 23:44

1 Answers1

3

I'm assuming that the | in your regex was supposed to mean "or." It doesn't: within brackets, no "or" is required. Your | refers to the actual character |.

This regular expression should do the trick about 98% of the time, maybe more:

\v(\/\/[^\n]*|\/\*(\_[^*]|\*\_[^/])*)@<!<[A-Z_]{2,}>

It uses positive lookbehind to make sure that there is no // preceding the string in the same line and no /* preceding it that is not followed by a */. It fails in the following case:

if (string == "/*") { // Looks like the start of a block comment
    return CONSTANT; // Won't be highlighted
}

If you want better results than this (that is, if you're worried that you'll obsess over the bug whenever you run into it) you could make this more sophisticated. How sophisticated depends on your language. In JavaScript, for example, you will need to worry about regex literals as well as strings:

// Looks like a comment after the "//" in the regex:
if (/\//.test(string)) return CONSTANT; // Won't be highlighted

If you want an idea of how complicated a regex to match a regex is, look at my answer here.

Community
  • 1
  • 1
Brian McCutchon
  • 8,354
  • 3
  • 33
  • 45