Search code examples
vimfoldbrackets

Vim - add one line above the fold to the folding


When I am coding in vim, I use set foldmethod=syntax which folds my code. It looks something like this then:

enter image description here

How can I add the line above the { to the fold? So that it would look something like this:

enter image description here

So the idea is that it (always) takes the line above the fold into the fold. How can I make this happen?


Solution

  • This needs a custom fold expression (h fold-expr) indenpendently from:

    1. foldtext <- you want to fold one more line
    2. foldignore <- you still want to fold { and } whatever the indent

    In your vimrc:

    " Callback: Fold level <- next line indent
    function! FoldMethod(lnum)
        let l:indent = max([indent(a:lnum+1), indent(a:lnum)])
        return l:indent / &shiftwidth
    endfunction
    
    set foldmethod=expr
    set foldexpr=FoldMethod(v:lnum)