iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🪟

Wait! ✋ Is that folding plugin really necessary? 🤔 (Replaceable with Tree-sitter)

に公開

TL;DR

As long as the parser corresponding to the file is installed, you can enable automatic fold detection by configuring it like this.

Introduction

There are many plugins available for Neovim, some of which replicate IDE-like folding.

Due to the existence of such plugins, some might mistakenly believe that automatic fold detection in Neovim requires dedicated plugins or complex configurations.
However, in reality, for most use cases, this objective can be achieved using only nvim-treesitter.

Example Configuration

Specifically, you can write it as follows:

vim.o.foldexpr = "v:lua.vim.treesitter.foldexpr()"
vim.o.foldlevel = 99
vim.o.foldmethod = "expr"
vim.o.foldtext = "" -- Optional; for those who dislike the default fold display

vim.treesitter.foldexpr()

This is a built-in function of Neovim itself, and the actual Lua module can be referenced here.
In other words, in theory, syntax-based automatic fold detection is possible even without installing nvim-treesitter.
One point to note is that this function returns a value as if no folds exist if the target parser is not installed. Therefore, in the end, it is effectively necessary.

Bonus

This technique is already incorporated into SnaxVim, which I introduced previously.
In a recent update, it now supports the main branch of nvim-treesitter (settings for the master branch are also kept just in case). If you are having trouble with the migration, please take this opportunity to check it out. Your feedback would be greatly appreciated!

🔗 Repository: https://github.com/SnaxVim/SnaxVim

Discussion