How can I write a vim foldexpr which is equivalent to foldmethod=indent?

2

As a result of this answer here, I'm trying to write a foldexpr for vim which is equivalent to foldmethod=indent (as a starting point to then enhancing it to recognise my custom markers, see the question for more details).

I've tried this:

set foldmethod=foldexpr
set foldexpr=indent(v:lnum)

However, this fails on this simple HTML example:

<div id="a">
    <div id="b">
        <div id="c">
            <div id="d">
            </div>
        </div>

        <div id="e">
        </div>
    </div>
</div>

If I place my key on the <div id="c"> line, and hit zc, the fold works as expected and folds only that div. If I re-open, then place my key on the <div id="b"> line, and hit zc, the fold fails as <div id="e"> is not folded.

If I switch to foldmethod=indent, this doesn't happen; the second fold is performed correctly. How can I fix my foldexpr to make it behave like foldmethod=indent?

Andrew Ferrier

Posted 2013-03-03T12:54:56.753

Reputation: 1 604

Have you managed to get multiple foldmethods (marker and indent) working together using this approach? – blueyed – 2013-12-17T19:06:26.787

@blueyed, I'm afraid not. I put this project on hold for the time being. Would be interested to hear if you have any success. – Andrew Ferrier – 2013-12-18T09:34:36.907

Answers

3

Empty lines should keep the fold level of the previous line. Try this:

:set foldmethod=expr
:set foldexpr=empty(getline(v:lnum))?'=':indent(v:lnum)/4

Ingo Karkat

Posted 2013-03-03T12:54:56.753

Reputation: 19 513