Skip to content

Commit

Permalink
fix: Avoid re-folding; use existing folds
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
jakewvincent committed Jun 14, 2024
1 parent f10310d commit ed3452a
Showing 1 changed file with 20 additions and 14 deletions.
34 changes: 20 additions & 14 deletions lua/mkdnflow/folds.lua
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down

0 comments on commit ed3452a

Please sign in to comment.