Set foldlevel in part of file in vim

379 Views Asked by At

Setting foldlevel when folding is active displays all folds up to that level and closes the rest.* I would like to do something similar for only part of the file, perhaps all material below the current fold or all material in a range.

Consider this file:

Tippy Top
    chapter
        section
            subsection
    chapter 2
        section 2.1
            sub 2.1.1

where the leading white space is tabs and :setlocal foldmethod=indent is in effect.

I would like to go to Tippy Top and do something like :expandToLevel 1 and see only the 2 chapter headings.

I can use zC to close everything, but zo simply restores the previous view, with lower level headings like subsection expanded if they were expanded earlier.

I've tried using :foldclose, repetition counts, highlighting a visual region, za, foldnestmax, but none achieve the behavior I want.

So far, to get expansion to a certain level only, I use one of 2 methods:

  1. Use :set foldlevel to get what I want in my current area, thereby wiping out whatever custom folds I've done elsewhere.
  2. Manually close the folds I want closed, e.g., zc on chapter and chapter 2.

The first loses what I've done in the rest of the document and the second is slow and tedious when there are more then a few entries.

I notice that the C function foldUpdateIEMS() and related functions take a range of lines. I'm not sure what the function does, but something like that doesn't seem to be exposed to vim scripts.

Apr 25 update: got vim running in a debugger and put a breakpoint on foldUpdateIEMS(). It fired when loading the file, but not when I :set foldlevel=2. So it does not seem to be directly involved in opening and closing folds. It does seem to define the folds.

My interest in these functions comes from vimoutliner, which uses foldmethod=expr. But I simplified to a plain text file with tab indentation to focus on the essential issues.

*As a side issue, when I set foldlevel=1 with the test file above I only see chapter, not chapter 2. I don't know why.

1

There are 1 best solutions below

2
On

I would like to go to Tippy Top and do something like :expandToLevel 1 and see only the 2 chapter headings.

:set foldlevel=1

does just that:

fold

or you could do 2zm (you may need :set folminlines=0). I don't like to count so I would simply do something like zM to close everything, and then zr to open one level.