LaTeX section highlighting in vim

Issue

In LaTeX, a section looks like:

\section{Section Title}

I would like to highlight such sections, or section titles. I tried to put the following in ~/.vim/bundle/latexrc/after/syntax/tex.vim:

syn match texSectioning "\\section\>" skipwhite nextgroup=texSectioningTitle
syn region texSectioningTitle       contained matchgroup=Delimiter start='{'    end='}' contains=@texSectioningGroup
syn cluster texSectioningGroup      contains=texMatcher,texComment,texDelimiter

(Note that this kind of syntax is not handled by the default tex.vim syntax file. It only defines “section zones”, which are pretty much worthless for me.)

I then define the following in my color scheme:

hi texSectioning gui=bold guifg=red

And nothing happens; that is, section titles do not appear in red in my LaTeX code (even after I reloaded the file completely).

I am totally confused as to how vim’s syntax work, and how to debug it.

Edit
Some more information: it sometimes works and sometimes not. Completely unpredictable. What could be the problem? Pathogen? Something else? I’m completely puzzled.

Solution

Here is the answer: the tex.vim divides the text in zones, in which the syntax must be explicitly allowed. The key element is that command:

syn cluster texChapterGroup contains=@texSectioningGroup

This says to vim that inside a texChapterGroup, the syntax cluster texSectioningGroup is allowed. The next thing to do is simply to define that cluster as usual.

Another detail is that the region texSectioningTitle must be contained, otherwise it will match arbitrary pairs of {} in LaTeX.

So a complete solution goes like this:

syn match texSectioningCommand '\\section\>' skipwhite     nextgroup=texSectioningTitle contains=@texSectioningGroup
syn region texSectioningTitle        start='{'  end='}' contained
syn cluster texSectioningGroup contains=texSectioningCommand
syn cluster texChapterGroup contains=@texSectioningGroup

Edit Here is why the behaviour was apparently unpredictable: vim does not read the entire file to figure out the syntax. So in a big enough chapter, my section syntax would work because vim did not go far enough to see it was in a chapter zone.

Answered By – Olivier Verdier

Answer Checked By – Dawn Plyler (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.