From ed3452a8c1b2f724b82dc6138a0fd71a8fc0683a Mon Sep 17 00:00:00 2001 From: jakewvincent Date: Fri, 14 Jun 2024 16:52:28 -0700 Subject: [PATCH] fix: Avoid re-folding; use existing folds This commit changes the way that the folding function works. Instead of always creating a new fold (which is what the function previously did), it now looks to see if the cursor is already in an open fold, and if so, it will simply close the fold. If there is no fold, one will be created following the usual logic. --- lua/mkdnflow/folds.lua | 34 ++++++++++++++++++++-------------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/lua/mkdnflow/folds.lua b/lua/mkdnflow/folds.lua index a90d2aa..af365c0 100644 --- a/lua/mkdnflow/folds.lua +++ b/lua/mkdnflow/folds.lua @@ -78,29 +78,35 @@ end M.foldSection = function() local row, line = vim.api.nvim_win_get_cursor(0)[1], vim.api.nvim_get_current_line() - local in_fenced_code_block = utils.cursorInCodeBlock(row) - if M.getHeadingLevel(line) < 99 and not in_fenced_code_block then - local range = get_section_range() - if range then - vim.cmd(tostring(range[1]) .. ',' .. tostring(range[2]) .. 'fold') - end - else - local start_row = get_nearest_heading() - if start_row then - local range = get_section_range(start_row) + -- See if the cursor is in an open fold. If so, and if it is not also on a heading, close the + -- open fold. + if vim.fn.foldlevel(row) > 0 and not (M.getHeadingLevel(line) < 99) then + vim.cmd.foldclose() + else -- Otherwise, create a fold + local in_fenced_code_block = utils.cursorInCodeBlock(row) + -- See if the cursor is on a heading + if M.getHeadingLevel(line) < 99 and not in_fenced_code_block then + local range = get_section_range() if range then vim.cmd(tostring(range[1]) .. ',' .. tostring(range[2]) .. 'fold') end + else -- The cursor isn't on a heading, so find what the range of the fold should be + local start_row = get_nearest_heading() + if start_row then + local range = get_section_range(start_row) + if range then + vim.cmd(tostring(range[1]) .. ',' .. tostring(range[2]) .. 'fold') + end + end end end end M.unfoldSection = function(row) row = row or vim.api.nvim_win_get_cursor(0)[1] - local foldstart = vim.fn.foldclosed(tostring(row)) - if foldstart > -1 then - local foldend = vim.fn.foldclosedend(tostring(row)) - vim.cmd(tostring(foldstart) .. ',' .. tostring(foldend) .. 'foldopen') + -- If the cursor is on a closed fold, open the fold. + if vim.fn.foldlevel(row) > 0 then + vim.cmd.foldopen() end end