Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fold C Preprocessor in VIM

Tags:

vim

folding

Is it possible to fold C preprocessor in VIM. For example:

#if defined(DEBUG)
  //some block of code
  myfunction();
#endif

I want to fold it so that it becomes:

 +--  4 lines: #if defined(DEBUG)---
like image 969
Sunny Avatar asked Mar 09 '10 09:03

Sunny


1 Answers

This is non-trivial due to the limitations of Vim's highlighting engine: it cannot highlight overlapping regions very well. You have two options as I see it:

  1. Use syntax highlighting and much about with the contains= option until it works for you (will depend on some plugins probably):

    syn region cMyFold start="#if" end="#end" transparent fold contains=ALL
    " OR
    syn region cMyFold start="#if" end="#end" transparent fold contains=ALLBUT,cCppSkip
    " OR something else along those lines
    " Use syntax folding
    set foldmethod=syntax
    

    This will probably take a lot of messing around and you may never get it working satisfactorily. Put this in vimfiles/after/syntax/c.vim or ~/.vim/after/syntax/c.vim.

  2. Use fold markers. This will work, but you won't be able to fold on braces or anything else that you might like. Put this in ~/.vim/after/ftplugin/c.vim (or the equivalent vimfiles path on Windows):

    " This function customises what is displayed on the folded line:
    set foldtext=MyFoldText()
    function! MyFoldText()
        let line = getline(v:foldstart)
        let linecount = v:foldend + 1 - v:foldstart
        let plural = ""
        if linecount != 1
            let plural = "s"
        endif
        let foldtext = printf(" +%s %d line%s: %s", v:folddashes, linecount, plural, line)
        return foldtext
    endfunction
    " This is the line that works the magic
    set foldmarker=#if,#endif
    set foldmethod=marker
    
like image 150
DrAl Avatar answered Sep 25 '22 10:09

DrAl