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