2

I can create code folding in marker based folding if there is only one starting marker and one ending marker. What if I have to fold a code which has two starting marker and only one ending marker?

For example in the following code I am able to fold either ifdef or ifndef but not both.

Vim commands:

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

Code:

ifdef
     /*
      * some code
      */
ifndef
     /*
      * some code
      */
endif
     /*
      * some code
      */
endif

2 Answers 2

2

I've done that for C & C++ in VimFold4C -- along with folding brackets, includes, comments... However, there is a pending bug regarding nested #ifdef.

The task is not that trivial. That's why I won't post code here.

If you're just interested in folding those, may be, the easier would be to hack the syntax file of your language and indicate that folding shall occur on those "markers" -- and then use the syntax folding method.

1
  • 2
    Thanks Luc..!! Anything like VimFold4C will be too much for me.. !! I will try with fold-by-syntax method. Commented Mar 11, 2016 at 14:37
1

Fortunately, your desired markers have a common prefix, so you could use:

set foldmarker=if,endif

Then it will catch both ifdef and ifndef. By default, vim's 'foldtext' displays the line excluding the marker (leaving just 5 lines: def) so you could define a custom one:

function! FoldlineText()
    return getline(v:foldstart)
endfun
set foldtext=FoldlineText()

That will look like this (set foldcolumn=3 so you can see the folding): showing question code partially folded

The downside is if you also have if logic with different delimiters (like C++'s if vs #if), then those get folded too.

For languages like C++ that have characters distinguishing the different kinds of ifs, we can resolve that ambiguity:

set foldmarker=#if,#endif

cpp code showing the if is not folded

From the 2 in the foldcolumn, you can see that the stink block is not folded.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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