Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I fold GNU C style functions in Vim correctly?

Tags:

vim

folding

When writing C code, I use a mixture of GNU and K&R style. This means that the return value, each parameter and the opening body curly brace of a function is on its own line. I would also like to use Vim's folding feature but with foldmethod=syntax, the folding looks like this:

bad-folding

Is it possible to see the function name in the fold summary without any special fold markers or foldexprs?

like image 906
matthias Avatar asked Oct 29 '12 11:10

matthias


2 Answers

Something which might be a good compromise - if you use the indent fold - is to set the foldminlines parameter to a higher number.

:set foldmethod=indent
:set foldminlines=5

If most of your functions are long, it will affect only your list of parameters. The downside obviously is, that it will automatically unfold also small functions which are smaller then 5 lines long.

like image 180
romanofski Avatar answered Nov 03 '22 19:11

romanofski


Try this as a starting point (I have it in my vimrc but I found it online):

" Folding {
function! CssFoldText()
    let line = getline(v:foldstart)
    let nnum = nextnonblank(v:foldstart + 1)
    while nnum < v:foldend+1
        let line = line . " " . substitute(getline(nnum), "^ *", "", "g")
        let nnum = nnum + 1 
    endwhile
    return line
endfunction

setlocal foldtext=CssFoldText()
setlocal foldmethod=marker
setlocal foldmarker={,}
setlocal fillchars=fold:/
setlocal foldlevel=-1
"   highlight Folded term=underline cterm=bold gui=bold guifg=Blue guibg=Black
"   highlight FoldColumn term=underline cterm=bold gui=bold guifg=Blue guibg=Black
"}
like image 42
DavidGamba Avatar answered Nov 03 '22 18:11

DavidGamba