Better Folding (Part 1): Pause Folds while Searching

· Nano Tips for Vim

#folding #search

Disabling search in foldopen has the disadvantage of making search nearly unusable, since you cannot see the search match in a closed fold. Enabling search in foldopen has the disadvantage of constantly opening all your folds as soon as you search, discouraging the use of many manually opened or closed folds very.

This snippet fixes this by pausing folds while searching, but restoring them when you are done searching:

 1vim.opt.foldopen:remove { "search" } -- no auto-open when searching, since the following snippet does that better
 2
 3vim.keymap.set("n", "/", "zn/", { desc = "Search & Pause Folds" })
 4vim.on_key(function(char)
 5	local key = vim.fn.keytrans(char)
 6	local searchKeys = { "n", "N", "*", "#", "/", "?" }
 7	local searchConfirmed = (key == "<CR>" and vim.fn.getcmdtype():find("[/?]") ~= nil)
 8	if not (searchConfirmed or vim.fn.mode() == "n") then return end
 9	local searchKeyUsed = searchConfirmed or (vim.tbl_contains(searchKeys, key))
10
11	local pauseFold = vim.opt.foldenable:get() and searchKeyUsed
12	local unpauseFold = not (vim.opt.foldenable:get()) and not searchKeyUsed
13	if pauseFold then
14		vim.opt.foldenable = false
15	elseif unpauseFold then
16		vim.opt.foldenable = true
17		vim.cmd.normal("zv") -- after closing folds, keep the *current* fold open
18	end
19end, vim.api.nvim_create_namespace("auto_pause_folds"))

While this snippet ensures that our folds persist even when searching, they are by default only persistent until you end the session. To make folds persist across sessions as well, you have to use :mkview and :loadview.