I have read the documentation on foldexpr, and I have read through Possible to set `foldexpr` using a function reference?.

I have tried this:

vim.o.foldexpr = function()
  return "1"

which clearly does not work, giving the following error:

Error detected while processing ftplugin/markdown.lua:
E5113: Error while calling lua chunk: ftplugin/markdown.lua:13: Invalid 'foldexpr': expected Integer/Boolean/String, got Function
stack traceback:
        [C]: in function '__newindex'
        ftplugin/markdown.lua:13: in main chunk

I see this: https://www.jmaguire.tech/posts/treesitter_folding/ which tells me to do

vim.opt.foldexpr = "nvim_treesitter#foldexpr()"

using the opt dict instead of the o one, and setting it to the function via a string - however, this will only work when the function is defined in vimscript not in lua. Do I need to have a shim and define my function in vim (even if the vim function is just one :lua command defining a function??) or can I use a pure lua reference.

1 Answer 1


Cross-posted with https://www.reddit.com/r/neovim/comments/193n9fx/how_to_reference_local_function_for_foldexpr/

(1) Export the function to the global namespace (_G):

_G.get_my_foldlevel = function() ... end

vim.o.foldexpr = 'v:lua.get_my_foldlevel()`

(2) or write in a lua module, and require:

--- e.g. config/folding.lua
local M = {}
function M.get_my_foldlevel() ... end
return M
vim.o.foldexpr = 'v:lua.require("config.folding").get_my_foldlevel()'

Personally I don't prefer global variables, so I chose an approach similar to (2) in my config.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.