vimtricks.wiki Concise Vim tricks, one at a time.

How do I control how many fold levels are open when first opening a file?

Answer

set foldlevelstart=N

Explanation

When Vim opens a file with folds enabled, it uses the foldlevelstart option to decide how many fold levels to open automatically. By default (-1), Vim uses the last foldlevel value. Setting it to a specific number gives you consistent, predictable fold behavior every time you open a file.

How it works

  • set foldlevelstart=-1 — use the last value of foldlevel (default; no change on open)
  • set foldlevelstart=0 — all folds closed when opening a file
  • set foldlevelstart=1 — top-level folds open, deeper ones closed
  • set foldlevelstart=99 — all folds open (effectively no folding visible on open)

The value maps directly to foldlevel: only folds at a deeper nesting level than foldlevelstart will start closed.

Example

With set foldmethod=syntax in a Python file and set foldlevelstart=1:

▸ def calculate_total():    ← level-1 fold, open
    ▸ if items:             ← level-2 fold, closed
    ▸ for x in items:      ← level-2 fold, closed

With set foldlevelstart=99, the same file opens with every fold expanded.

Tips

  • Use zm / zr to decrease / increase fold level interactively after opening
  • zM closes all folds; zR opens all folds
  • The interactive foldlevel (:set foldlevel=N) changes the current view but does not persist to new files; foldlevelstart is the startup equivalent
  • Add to your ftplugin files for per-filetype fold depth: e.g., open Markdown at level 1, Python at level 2

Next

How do I programmatically read and write Vim register contents including their type from Vimscript?