Skip to content

Commit ed3452a

Browse files
committed
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.
1 parent f10310d commit ed3452a

File tree

1 file changed

+20
-14
lines changed

1 file changed

+20
-14
lines changed

lua/mkdnflow/folds.lua

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -78,29 +78,35 @@ end
7878

7979
M.foldSection = function()
8080
local row, line = vim.api.nvim_win_get_cursor(0)[1], vim.api.nvim_get_current_line()
81-
local in_fenced_code_block = utils.cursorInCodeBlock(row)
82-
if M.getHeadingLevel(line) < 99 and not in_fenced_code_block then
83-
local range = get_section_range()
84-
if range then
85-
vim.cmd(tostring(range[1]) .. ',' .. tostring(range[2]) .. 'fold')
86-
end
87-
else
88-
local start_row = get_nearest_heading()
89-
if start_row then
90-
local range = get_section_range(start_row)
81+
-- See if the cursor is in an open fold. If so, and if it is not also on a heading, close the
82+
-- open fold.
83+
if vim.fn.foldlevel(row) > 0 and not (M.getHeadingLevel(line) < 99) then
84+
vim.cmd.foldclose()
85+
else -- Otherwise, create a fold
86+
local in_fenced_code_block = utils.cursorInCodeBlock(row)
87+
-- See if the cursor is on a heading
88+
if M.getHeadingLevel(line) < 99 and not in_fenced_code_block then
89+
local range = get_section_range()
9190
if range then
9291
vim.cmd(tostring(range[1]) .. ',' .. tostring(range[2]) .. 'fold')
9392
end
93+
else -- The cursor isn't on a heading, so find what the range of the fold should be
94+
local start_row = get_nearest_heading()
95+
if start_row then
96+
local range = get_section_range(start_row)
97+
if range then
98+
vim.cmd(tostring(range[1]) .. ',' .. tostring(range[2]) .. 'fold')
99+
end
100+
end
94101
end
95102
end
96103
end
97104

98105
M.unfoldSection = function(row)
99106
row = row or vim.api.nvim_win_get_cursor(0)[1]
100-
local foldstart = vim.fn.foldclosed(tostring(row))
101-
if foldstart > -1 then
102-
local foldend = vim.fn.foldclosedend(tostring(row))
103-
vim.cmd(tostring(foldstart) .. ',' .. tostring(foldend) .. 'foldopen')
107+
-- If the cursor is on a closed fold, open the fold.
108+
if vim.fn.foldlevel(row) > 0 then
109+
vim.cmd.foldopen()
104110
end
105111
end
106112

0 commit comments

Comments
 (0)