How to syntax highlight only part of the string?

24 views
Skip to first unread message

Igor Forca

unread,
Jan 18, 2017, 9:24:28 AM1/18/17
to vim_use
Hi,
in $HOME\vimfiles\syntax\sql.vim I have written several rules to have syntax highlighting for SQL statements. Works perfectly. But now I would like to write error like rules to have syntax mark with red background for bad habits or syntax errors.

For example I have written the following rule to mark all of the spaces at the end of line. This is not syntax error, just dummy spaces at the end of line, that is bad habit to have them, because there are of any use.

" space at the end of a line
syntax match sqlerror "\s\{-}$"

Above works fine it marks with red background all of the spaces at the end of line.

But now I have the following problem. Having one space between "order" and "by" is OK. Having two or more spaces between this two words I would like to mark a bad habit with red background.

So far I have written the following:

" two or more spaces between order and by words
syntax match sqlerror "\<order \{2,}by\>"

But above syntax highlights both words "order" and "by" and spaces between them.

Is it possible to mark only spaces that are too many?

Example:
" OK not problem and no red background
order by

" there are two spaces between "order"
" and "by" words and only ONE
" space should get with red background
order by

" there are three spaces between "order"
" and "by" words and only TWO spaces
" should get with red background
order by

How to write such a syntax highlights rule to search for "order by" combination but only marks red background spaces between them if there are more then two spaces between the worlds and not red background marking the words "order" or "by" itself?
Regards

Ben Fritz

unread,
Jan 18, 2017, 9:40:56 AM1/18/17
to vim_use

Use '\zs' and '\ze' to mark the beginning and the end of the match. This also works for search patterns. This is probably the easiest way but specifically for syntax highlighting there are also ways to adjust the beginning and end of the match or highlighted area with offsets, see :help :syn-pattern-offset.

Igor Forca

unread,
Jan 19, 2017, 9:36:05 AM1/19/17
to vim_use
@Ben, thank you for your answer. Very helpful. Bellow code works perfectly:
syntax match sqlerror "\<order \zs \+\zeby\>"
Reply all
Reply to author
Forward
0 new messages