TransWikia.com

Why does creating a new fold sometimes cause the entire file to be folded?

Vi and Vim Asked on February 6, 2021

Sometimes when I create a new fold in vim, it folds the entire file. Why?
(foldmethod=manual)

e.g.,

  1. zi (all folds are now open)
  2. zi (all folds are now closed)
  3. lines 1-309 are folded closed, and lines 617-662 are folded closed (file has 662 lines)
  4. my cursor is on line 377
  5. I do zfG to fold all lines from line 377 to end-of-file
    Expected: lines 377 thru end-of-file are closed, and lines 310-366 are visible
    Actual: all lines in file are closed

Workaround:

  1. zD (delete all folds)
  2. :1,309fold (fold 1-309)
  3. :377,$fold (fold 377-eof)

My fold* settings:

  foldclose=
  foldcolumn=0
  foldenable
  foldexpr=0
  foldignore=#
  foldlevel=0
  foldlevelstart=-1
  foldmarker={{{,}}}
  foldmethod=manual
  foldminlines=1
  foldnestmax=20
  foldopen=block,hor,mark,percent,quickfix,tag,undo
  foldtext=foldtext()

One Answer

This behavior will happen if line 377 is part of a fold that starts at the top of the file, and that fold that is currently open.

In that case, the new fold Vim will create will actually start at line 1 (not at line 377) and Vim will close the new fold, effectively folding the whole file.

You can reproduce this behavior with:

  1. zE (delete all folds.)
  2. :1,309fold (fold 1-309, first initial fold you described.)
  3. :617,$fold (fold 617-eof, second initial fold you described.)
  4. :1,400fold (a fold starting at the top and including line 377.)
  5. zo (open this last fold!)
  6. 377G (go to line 377.)
  7. zfG (fold to the end, but this actually folds 1-eof!)

It's possible you're not opening that fold explicitly, but through one of the actions in 'foldopen', such as following a tag or going to a mark. Even a horizontal movement (such as 377G0) will trigger that fold to open.

If you'd like to see the folds visually, you can use this command to add the fold level to the beginning of each line:

:%s/^/=foldlevel('.')."t"/

(Note that this will modify your buffer, but it should be easy to revert it with another :%s command. This will also get out-of-sync as you create or delete folds, you should also be able to update the per-line fold level after such operation with a similar :%s command.)

You also mentioned that the zi command would close all folds (when enabling fold), but that's not really accurate... Vim will keep track of the folds manually closed and opened and preserve those choices when you toggle 'foldenable' with zi.

The command that will close all folds is actually zM.

Answered by filbranden on February 6, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP