Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofold #ifdef..#endif in vim via .vimrc

Tags:

vim

folding

I have seen partial solutions over the internet but none that really satisfied me: what do I have to put into my .vimrc (ideally I don't want to chance any syntax/*.vim file) such that in all .c/cpp/h files that I open, I get automatic folding of #ifdef ... #endif sections?

like image 727
dcn Avatar asked Jun 29 '11 14:06

dcn


People also ask

What is auto fold?

Autofold is part of the move tool and allows you to. manipulate surfaces and create automatic folding. edges in SketchUp.

What stroller Folds itself?

Welcome to the Fold! The Larktale autofold™ is the first full-featured stroller to automatically fold itself in seconds. Larktale's patent-pending technology offers a self-folding feature that activates with flick of the wrist, and no springs or motors.

How do you fold a stroller?

Squeeze up the levers: These are located at the base on either side of the handlebar frame. Push the handlebar: Forward, over the seat. Tug on the red handle: It should now be on top of the folded seat. Tug it and the stroller will collapse.


2 Answers

You know that you can navigate preprocessor conditional blocks with the % key?

Also, [# and ]# navigate up/down.

So you could go to the start of a conditional block (perhaps with /^#Enter), then

 zf%               -- fold to next conditional directive
 v2]#zf            -- fold to second next directive (e.g. #else... #endif)

zd to drop the fold.

Perhaps you can devise a little script around this concept. I'm not very sure whether there will be (adverse) interaction with the regular syntax folding, since I'm not in the habit of using that. I usually use indent folding with manual fold manipulation like this.

like image 190
sehe Avatar answered Oct 08 '22 08:10

sehe


If the only type of folding that you want is the #ifdef sections, the easiest way is to create a file ~/.vim/after/ftplugin/c.vim (you may also need to do this in cpp.vim, I'm not sure) with the following content:

set foldmarker=#ifdef,#endif
set foldmethod=marker

If you really want to put it in .vimrc rather than using the ~/.vim/after/ structure, you can do something like this:

autocmd FileType *.[ch]{,pp} call FoldPreprocessor()
function! FoldPreprocessor()
    set foldmarker=#ifdef,#endif
    set foldmethod=marker
endfunction

You might also want to consider using:

set foldmarker=#if,#endif

As that will catch #if defined(...), #ifdef, #ifndef, #if 0 etc as well as #ifdef.

Doing this with syntax folding is more challenging as you'll have to change the syntax specification as it doesn't support this as standard.

like image 26
DrAl Avatar answered Oct 08 '22 08:10

DrAl