Ending syntax region at the start of a given pattern

Issue

This is a follow-up from:

VIM: simple steps to create syntax highlight file – for logfiles

I am trying to use the ‘region-match’ facility to syntax-highlight stack-traces in some logfiles: these logfiles (log4j-based) look a bit like this:

YYYY-MM-DD HH:MM:ss,SSSS...INFO...Message
YYYY-MM-DD HH:MM:ss,SSSS...INFO...Message
YYYY-MM-DD HH:MM:ss,SSSS...ERROR...Message
...stack trace...
...stack trace...
...blah blah, more server-vomit...
...
YYYY-MM-DD HH:MM:ss,SSSS...INFO...Message

So far I have managed to almost do what I want with this:

:syntax region error matchgroup=string start=/^\d\{4}-\d\{2}-\d\{2} \d\{2}:\d\{2}:\d\{2},\d\{3}.* ERROR/    end=/^\d\{4}-\d\{2}-\d\{2} \d\{2}:\d\{2}:\d\{2},\d\{3}/

But the issue, is that match goes too far – it includes the next record (ie, the match includes the next YYYY-MM-DD….).

I believe from this example (an exampled about quoted text) in the VIM manual that I should be able to highlight in-between? (But I don’t seem to be able to map the syntax for my example)

http://vimdoc.sourceforge.net/htmldoc/syntax.html#:syn-excludenl

So to be clear: I need to match the first YYYY-MM-DD… line (which includes ‘ERROR’) and then all subsequent lines up to but NOT including the next YYYY-MM-DD line.

Solution

There are a lot of difficulties with overlapping regions in Vim’s syntax highlighting engine. The order in which matches and regions are defined makes a difference and it can be very hard to make it do what you want.

The main thing I’d suggest is to look at :help syn-pattern-offset. This provides a means to make the region end at the start of a pattern among other things. For example if your end pattern is:

end=/pattern/re=s-1

Then the region will end at the character before the p of pattern.

This takes a lot of playing around to make it work and I’m far from being an expert on these things, but to get you started, try this:

syntax match logDate /^\d\{4}-\d\{2}-\d\{2}/ containedin=logDateTimeTypeLine nextgroup=logTime skipwhite
syntax match logTime /\d\{2}:\d\{2}:\d\{2},\d\{3}/ containedin=logDateTimeTypeLine,logTrace
syntax match logDateTimeTypeLine /^\d\{4}-\d\{2}-\d\{2} \d\{2}:\d\{2}:\d\{2},\d\{3}.*/
syntax region logTrace matchgroup=logErrorStartLine start=/^\d\{4}-\d\{2}-\d\{2} \d\{2}:\d\{2}:\d\{2},\d\{3}.*ERROR.*/ms=s,rs=e+1 end=/^\d\{4}-\d\{2}-\d\{2} \d\{2}:\d\{2}:\d\{2},\d\{3}/me=s-1,he=s-1,re=s-1
hi link logTrace Error
hi link logDateTimeTypeLine Keyword
hi link logDate String
hi link logTime Comment
hi logErrorStartLine guifg=red

Answered By – DrAl

Answer Checked By – Mary Flores (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.