How to fold C++-style comments in Vim?

Tag: vim Author: goonesownway Date: 2009-07-29

Syntax folding in Vim makes it easy to create folds for regions, the start and end of which can be defined with regular expressions:

syn region myRegion start="#region" end="#endregion" transparent keepend extend fold

However, I am not sure how I can use syntax folding to define folds for C++-style comments, which are sets of lines beginning with "//".

Why do you need to fold comments starting with "//" ? Those are one-line comments and they should be minimalistic and short so they don't need to be folded. You should fold only comment blocks starting with "/*" and ending with "/" and that should be easy to implement. According to your post this should be valid: syn region CommentBlock start="/" end="*/" transparent keepend extend fold
Many coding standards use "//" for block comments. MSDN uses these throughout. Besides, there are other things one might want to fold that fall into the same pattern, such as "#include" and "using" statements.

Best Answer

I think I found a solution:

:syn match comment "\v(^\s*//.*\n)+" fold

This is a multiline match that folds consecutive lines beginning with whitespace and double slashes. The "\v" in the beginning labels the pattern "very magic" for brevity. Seems to work.


This seems to work. Nice.