C++ Syntax Highlighting In Vim

Vim has been my choice of editor for a very long time, especially when it comes to programming. And while I’ve never been much for a lot of syntax highlighting when I’m writing code, my recent usage of other editors has made me reconsider this.

What I’ve grown particularly fond of is the highlighting of functions and class namespaces. I’m also in favour of highlighting the STL containers, mainly because I see them as standard types these days, and it provides a nice separation from my own containers / types.

Unfortunately the default C++ syntax file that ships with Vim is somewhat lacking with regards to this, so I decided to extend it.

All syntax definitions are defined in $VIMRUNTIME/syntax/[language].vim. The C++ syntax is made up from c.vim and cpp.vim, where the latter includes and extends the former. Rather than changing these files directly, it’s better to make a local extension.

After Vim has loaded the syntax definitions, it will automatically look in $VIM/.vim/after/syntax/[language]/*.vim for any extensions to a particular language’s syntax definition; it doesn’t matter what the file is called.

Here’s what I’ve added to my $VIM/.vim/after/syntax/cpp/custom.vim:

I basically added the containers and std::string to be highlighted by the “Statement” group, added some matching code for picking out functions, and finally I added a match for the std:: namespace because I like that to stand out.

In order to easily be able to individually highlight these in my color theme, I simply introduced a few new highlight groups to do so – which are the last 3 lines.

The final bit, is of course to actually assign a color to the custom highlight groups, which I’ve done in my color theme like so:

Here’s a small screenshot showing what it can look like:
vimcppsyn

Feel free to check out the GitHub repository where I keep my latest configurations.

|   

One Response to “C++ Syntax Highlighting In Vim”

  1. Jim says:

    Thanks for sharing! This is just what I’ve been looking for :)