The default syntax highlighting for bib files doesn't highlight comments inside entries, like this:

    % title = {This isn't highlighted as a comment},

That's because bibtex doesn't allow comments inside entries, but biblatex does and I never use bibtex, so I want to add the highlighting myself.

I tried adding this to ~/.vim/after/syntax/bib.vim:

syn match testComment "%.*$"
highlight link testComment Comment

But it doesn't work. Any ideas on how I can make stuff after a % count as a comment anywhere on the file?

PS: Ideally the % still wouldn't count as a comment if it's inside a field, like url = {http://whatever.com%20whatever}… but I think I can figure out a regex pattern to account for that if I can get the highlighting to work inside entries at all.


The reason it does not work is that the match is inside an bibEntry. Thus you have to redefine the bibEntry region so as to include (with the contains= option a comment group. In this case, you should use a new comment group, not the existing bibComment and bibComment2, because these are reserved for standard bibtex comments.

I think the following should work if you put it in .../after/syntax/bib.vim:

syn region bibEntryData contained
  \ start=/[{(]/ms=e+1
  \ end=/[})]/me=e-1
  \ contains=bibKey,bibField,bibComment3
syn match bibComment3 "^\s*%.*"
highlight link bibComment3 Comment

Note: This assumes that all comments are "full line"-comments.

| improve this answer | |
  • Thanks for your help! That works for a few random comments, but not for most. It doesn't work with my example, for instance (% title = {This isn't…). – dbmrq Sep 12 '16 at 7:20
  • Ah, I think the updated answer works. We needed to go one level deeper into the nested syntax definitions. – Karl Yngve Lervåg Sep 12 '16 at 19:29
  • 1
    Awesome, thank you! I don't know much about how the contains= thing works, but I just replaced the regex pattern with "%.*" and it seems to work perfectly even for end-of-line comments. I worried that would cause problems with url fields like I mentioned in the "PS", but the comments still aren't highlighted inside each field's brackets, so it works great! – dbmrq Sep 12 '16 at 20:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.