refactor: generalize toggle_todo pattern for multiple markers

main
borja (aider) 2 months ago
parent ea13e19e55
commit c7252424d7

@ -191,29 +191,24 @@ local function setup_buffer_keymaps()
end end
end end
-- function that checks if the current line starts with the string "- [ ]" or "- [x]" and toggles the x -- Toggles the checkbox [ ] <-> [x] for lines starting with -, *, +, or #
-- (Will be updated in Step 2 to handle *, +)
local function toggle_todo() local function toggle_todo()
local openpattern = "%- %[[ ]%]"
local closedpattern = "%- %[[x]%]"
local titleopenpattern = "# %[[ ]%]" -- Keep title toggle for now? Or remove? Let's keep it.
local titleclosedpattern = "# %[[x]%]"
local line = vim.api.nvim_get_current_line() local line = vim.api.nvim_get_current_line()
-- Pattern captures:
if string.match(line, openpattern) then -- 1: Prefix (indentation, marker '-', '*', '+', or '#', and whitespace)
line = string.gsub(line, openpattern, "- [x]", 1) -- Replace only first instance -- 2: State (' ' or 'x')
vim.api.nvim_set_current_line(line) -- 3: Rest of the line (after ']')
elseif string.match(line, closedpattern) then local prefix, state, rest = string.match(line, "^([%s]*[%-#%*%+]%s*)%[([ x])%](.*)")
line = string.gsub(line, closedpattern, "- [ ]", 1) -- Replace only first instance
vim.api.nvim_set_current_line(line) if prefix then -- Check if the pattern matched (i.e., it's a toggleable line)
elseif string.match(line, titleopenpattern) then -- Determine the new state
line = string.gsub(line, titleopenpattern, "# [x]", 1) local new_state = (state == ' ') and 'x' or ' '
vim.api.nvim_set_current_line(line) -- Reconstruct the line with the new state
elseif string.match(line, titleclosedpattern) then local new_line = prefix .. "[" .. new_state .. "]" .. rest
line = string.gsub(line, titleclosedpattern, "# [ ]", 1) -- Update the current line
vim.api.nvim_set_current_line(line) vim.api.nvim_set_current_line(new_line)
end end
-- If the pattern didn't match, do nothing.
end end
-- Set up buffer-local keymaps -- Set up buffer-local keymaps

Loading…
Cancel
Save