Jeff Terrell

Jeff Terrell
Ph.D. Candidate
Department of Computer Science
University of North Carolina at Chapel Hill

jsterrel AT cs.unc.edu
(919) 962-1791 (office)

C preprocessor folding in Vim

Setup

Vim is version 7.0.

Background

I want to use folding in Vim so that all C preprocessor conditionals are folded by default. For example:

...
#ifdef FAST_IPSEC
#include <netipsec/ipsec.h>
#include <netipsec/xform.h>
#include <netipsec/key.h>
#endif /*FAST_IPSEC*/
...

Should become:

...
+--  5 lines: #ifdef FAST_IPSEC------------------------
...

Furthermore, nested preprocessor conditionals should be folded in a nested fashion. For example (with the left column displayed with :foldcolumn=4):

-   #ifdef IPSEC
|   #include 
|   #include 
|-  #ifdef IPSEC_DEBUG
||  #include 
||  #else
||  #define KEYDEBUG(lev,arg)
||  #endif
|   #endif /*IPSEC*/

Lastly, I want to disable all other folding in C files, so that these are the only folds.

Resolution

Part 1: disable other folds

In $VIMRUNTIME/syntax/c.vim ($VIMRUNTIME is /usr/local/share/vim/vim70/ on my machine), change the line defining a cBlock region to:

if exists("c_no_block_fold")
  syntax region cBlock start="{" end="}" transparent
else
  syntax region cBlock start="{" end="}" transparent fold
endif

Next, add these lines to your ~/.vimrc file:

let c_no_comment_fold=1
let c_no_if0_fold=1
let c_no_block_fold=1

Part 2: enable folding for C preprocessor conditionals

Add this line to the bottom of $VIMRUNTIME/syntax/c.vim:

syn region cMyFold start="#if" end="#end" transparent fold contains=ALL

And if you want this folding to happen automatically when opening *.c files, add this to your ~/.vimrc file:

autocmd BufNewFile,BufRead *.c set foldenable foldmethod=syntax

Remarks

This is a suboptimal solution. For one thing, it would be better to add these commands to a personal C syntax file, instead of changing the global one in $VIMRUNTIME. But, frankly, I've already spent far too long figuring this out (instead of getting actual work done), and I'm tired of messing with this.

References

Thanks to Lev ??? for showing me how to enable syntax highlighting within the folded region.

articles/vim-c-preproc-fold.php: Last Modified: 12/03/07@18:02:20 | Size: 3202 bytes | View Source