1

Is it possible to 'fold at the proper indentation' ? For example, the point in the below is to see conditional flow:

enter image description here

However, with how the above is formatted, it's almost impossible to see visually that those 42 lines are part of the else statement. Is it possible to do something like this in vim, or not really?

1
  • 1
    The foldtext option controls how close folds are displayed, however I don't know if it can respect the indentation.
    – Biggybi
    Commented Jun 26, 2020 at 20:57

1 Answer 1

3

It's possible indeed!

As @Biggybi mentioned, you have to use foldtext to achieve that.

You assign a function to foldtext, and within this function, you can access the v:foldstart and v:foldend variables.

From there, you can access the indentation. Here's a simple example:

    function! NeatFoldText()
        let lines_count      = v:foldend - v:foldstart + 1
        return repeat(' ', indent(nextnonblank(v:foldstart))) . lines_count . ' lines '
    endfunction

    set foldtext=NeatFoldText()

If you want to have something a bit more advanced, here's what I have in my vimrc:

    function! NeatFoldText()
        let foldchar         = matchstr(&fillchars, 'fold:\zs.')
        let lines_count      = v:foldend - v:foldstart + 1
        let lines_count_text = printf("┈─ %1s lines ─┈", lines_count) . repeat(foldchar, 10)
        let foldtextstart    = repeat(' ', indent(nextnonblank(v:foldstart))) . " ••• " 
        let foldtextend      = lines_count_text . repeat(foldchar, 8)
        let foldtextlength   = strlen(substitute(foldtextstart . foldtextend, '.', 'x', 'g')) + &foldcolumn

        return foldtextstart . repeat(foldchar, winwidth(0) - foldtextlength) . foldtextend
    endfunction

Demo

3
  • 1
    that is really cool! It took me a bit of time to wrap my head around how vim does folding (TextMate, VS Code, etc. tend to found the top line (while...) and show that line with all the code folded under it, but here it basically requires you keep the top line but then do the folding on the level under that. Thanks!
    – David542
    Commented Jun 26, 2020 at 22:42
  • is there any way to do it like this? imgur.com/a/6PO6umi
    – David542
    Commented Jun 26, 2020 at 22:45
  • 1
    That's unfortunately not possible, you cannot keep the syntax coloring in a folded line. It is possible to do it but with no colors
    – Zorzi
    Commented Jun 26, 2020 at 23:14

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.