Neovim for Beginners — Code Folding

Learn the basics of folding and how to configure treesitter and LSP-based code folding.

alpha2phi
4 min readJul 8, 2022

--

Neovim for Beginners — Code Folding

In this article, we will learn the basics of folding and how to configure treesitter and LSP-based code folding.

This article is part of the Neovim for Beginners series.

The Neovim configuration files can be found in this repository.

Getting Started

The fastest way to understand folding is to spend a few minutes going through the Vim manual (:h usr_28.txt). We will only go through the basics here.

usr_28.txt

Fold Method

The foldmethodoption (:h 'foldmethod’) defines the kind of folding used for the current window. Possible values for this option are

  • manual (:h fold-manual) — Folds are created manually.
  • indent (:h fold-indent) — Lines with equal indent form a fold.
  • expr (:h fold-expr) — foldexpr gives the fold level of a line.
  • marker (:h fold-marker) — Markers are used to specify folds.
  • syntax (:h fold-syntax) — Syntax highlighting items specify folds.
  • diff (:h fold-diff) — Fold text that is not changed.

E.g. in the screenshot below, we fold the lines based on the indentation.

Fold by Indentation

In the screenshot below, we fold the paragraphs separated by blank lines.

:set foldexpr=getline(v:lnum)=~'^\\s*$'&&getline(v:lnum+1)=~'\\S'?'<1':1
Fold by Expression

Fold Level

The foldlevel option (:h 'foldlevel') sets the fold level. Folds with a higher level will be closed. Setting this option to zero will close all folds…

--

--

alpha2phi

Software engineer, Data Science and ML practitioner.