Better Folding (part 3): Remember your folds across sessions

· Nano Tips for Vim


When you manually fold a lot of lines, one annoying thing you may have noticed is that these folds to not persist across sessions. However, we can save and load folding with vim's builtin :mkview and :loadview. Create autocommands for the two commands, and we are got folds persisting across sessions (or technically, leaving/entering a buffer).

 1local function remember(mode)
 2	-- avoid complications with some special filetypes
 3	local ignoredFts = { "TelescopePrompt", "DressingSelect", "DressingInput", "toggleterm", "gitcommit", "replacer", "harpoon", "help", "qf" }
 4	if vim.tbl_contains(ignoredFts, or ~= "" or not then return end
 6	if mode == "save" then
 7		cmd.mkview(1)
 8	else
 9		pcall(function() cmd.loadview(1) end) -- pcall, since new files have no view yet
10	end
12vim.api.nvim_create_autocmd("BufWinLeave", {
13	pattern = "?*",
14	callback = function() remember("save") end,
16vim.api.nvim_create_autocmd("BufWinEnter", {
17	pattern = "?*",
18	callback = function() remember("load") end,

However, one thing you might have noticed is that folds are still lost when you search in a file. Luckily, that, too, can be fixed.