Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to highlight words beginning with ‘@’ in Vim syntax?

Tags:

syntax

regex

vim

I have a very simple Vim syntax file for personal notes. I would like to highlight people's name and I chose a Twitter-like syntax @jonathan.

I tried:

syntax match notesPerson "\<@\S\+"

To mean: words beginning with @ and having at least one non-whitespace character. The problem is that @ seems to be a special character in Vim regular expressions.

I tried to escape \@ and enclose in brackets [@], the usual tricks, but that didn't work. I could try something like (^|\s) (beginning of line or whitespace) but that's exactly the problem that word-boundary tries to solve.

Highlighting works on simplified regular expressions, so this is more a question of finding the right regex than anything else. What am I missing?

like image 954
jpalardy Avatar asked Dec 18 '12 20:12

jpalardy


1 Answers

@ is a special character only if you have enabled the “very magic” mode by having \v somewhere in the pattern prior to that @.

You have another problem here: @ does not start a new word. \< is not just “word boundary” like perl/PCRE’s \b, but “left word boundary” (in help: “beginning of the word”) meaning that \< must be followed by some keyword character. As @ is not normally a keyword character, pattern \<@ will never match. (And even if it was like \b, it would match constructs like abc@def which is definitely not what you want for the aforementioned reasons.)

You should use \k\@<!@\k\S* instead: \k\@<! ensures that @ is not preceded by any keyword character, \k\S* makes sure that first character of the name is a keyword one (you could probably also use @\<\S\+).

There is another solution: include @ into 'iskeyword' option and leave the regex as is:

:setlocal iskeyword+=@-@

See :help 'isfname' for the explanation why @-@ is used here. (The 'iskeyword' option has exactly the same syntax and will, in fact, redirect you there for the explanation.)

like image 89
ZyX Avatar answered Sep 20 '22 13:09

ZyX