Custom Folding in python makes nvim slow

Hello everyone,

I want to make a custom folding method for python scripts. I want to fold everything that starts with “# %%”. I wrote the following function:

" Custom Folding for python
function! BlockFolds()
 let thisline = getline(v:lnum)
 if match(thisline, '# %%') >= 0
    return ">1"
 else
    return "="
 endif
endfunction

autocmd BufEnter *.py set foldmethod=expr
autocmd BufEnter *.py set foldexpr=BlockFolds()

It works but then neovim becomes extremely slow for files with 1000+ lines. I have neovim 0.5 nightly.

Is there a better way to do it? Is there any plugin that I can use? Can I write the same function in lua?

Thank you in advance for your help.

You could try if thisline =~# '^# %%', that might speed things up a bit.

When you say Neovim becomes slow, can you be more specific, what slows down.

It becomes very laggy when I scroll, change lines or start to type something.

The problem is that the function has to be evaluated for every single line in the code, and if you have many lines, it becomes an issue (?). And probably this happens continuously to check for new folds etc.

I tried your suggestion, same behaviour. (Thanks anyway).

Can you use the tree-sitter based folding for python?

you mean to enable this:

set foldmethod=expr
set foldexpr=nvim_treesitter#foldexpr()

Then the folding is done using the nvim-treesitter/queries/python/folds.scm right? So I have to add my expression to the folds.scm?

would be nice if you run/create some benchmark and compare vim/nvim 0.4/master.

The only benchmark I can think of is making a screen capture video, if you have a better idea happy to apply it.