1

Every time a Python file is loaded, no folds are automatically applied based on the fold options that have been set (see below). Instead, I have to manually press zx to force the folds to be applied.

This problem is limited to Python files and the use of the Treesitter-based expression folding method. Initial and automatic folding works fine when the "indent" method is used, or another file type is loaded (e.g. Lua).

How can I resolve this issue?

I have checked that:

  • The Python Treesitter parser has been installed and is functioning correctly (i.e. the output of :checkhealth nvim-treesitter is fine).
  • No Python-specific autocommands have been interfering with the code folding settings (i.e. both :autocmd FileType python and :autocmd BufRead,BufEnter *.py do not show any autocommands).
  • No other Python-specific Neovim plugins have been installed.

Fold Options

vim.opt.foldcolumn = "1"    -- Show fold indication in column
vim.opt.foldlevel = 1       -- The default fold level (higher means more folds open by default)
vim.opt.foldtext = ""       -- Do not show fold information (just show existing text on folded line)
vim.opt.foldmethod = "expr" -- Use custom expression for folding
vim.opt.foldexpr = "nvim_treesitter#foldexpr()" -- Set expression for folding to treesitter

1 Answer 1

1

The issue stems from the delays in the initialisation of the Treesitter parser and the generation of the syntax tree.

The nvim_treesitter#foldexpr() function relies on this syntax tree to fold the code---its absence prevents folding.

The solution is to set up an auto-command that applies the folding after the Treesitter parser has had time to build the syntax tree. vim.schedule is used as it waits for Neovim's event loop to be idle before executing the scheduled function (i.e. after initial buffer processing and plug-in initialisation). This can be done by adding the following to your config:

-- Create group to assign commands
-- "clear = true" must be set to prevent loading an auto-command repeatedly every time a file is resourced
local autocmd_group = vim.api.nvim_create_augroup("Custom auto-commands", { clear = true })

vim.api.nvim_create_autocmd("BufReadPost", {
    pattern = "*.py",
    desc = "Apply code folds after reading Python file into buffer (uses vim.schedule)",
    callback = function()
        vim.schedule(function()
            vim.cmd("normal! zx")
        end)
    end,
    group = autocmd_group,
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.