diff --git a/lua/todoer/init.lua b/lua/todoer/init.lua index 674a06b..cdefb69 100644 --- a/lua/todoer/init.lua +++ b/lua/todoer/init.lua @@ -191,29 +191,24 @@ local function setup_buffer_keymaps() end end - -- function that checks if the current line starts with the string "- [ ]" or "- [x]" and toggles the x - -- (Will be updated in Step 2 to handle *, +) + -- Toggles the checkbox [ ] <-> [x] for lines starting with -, *, +, or # 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() - - if string.match(line, openpattern) then - line = string.gsub(line, openpattern, "- [x]", 1) -- Replace only first instance - vim.api.nvim_set_current_line(line) - elseif string.match(line, closedpattern) then - line = string.gsub(line, closedpattern, "- [ ]", 1) -- Replace only first instance - vim.api.nvim_set_current_line(line) - elseif string.match(line, titleopenpattern) then - line = string.gsub(line, titleopenpattern, "# [x]", 1) - vim.api.nvim_set_current_line(line) - elseif string.match(line, titleclosedpattern) then - line = string.gsub(line, titleclosedpattern, "# [ ]", 1) - vim.api.nvim_set_current_line(line) + -- Pattern captures: + -- 1: Prefix (indentation, marker '-', '*', '+', or '#', and whitespace) + -- 2: State (' ' or 'x') + -- 3: Rest of the line (after ']') + local prefix, state, rest = string.match(line, "^([%s]*[%-#%*%+]%s*)%[([ x])%](.*)") + + if prefix then -- Check if the pattern matched (i.e., it's a toggleable line) + -- Determine the new state + local new_state = (state == ' ') and 'x' or ' ' + -- Reconstruct the line with the new state + local new_line = prefix .. "[" .. new_state .. "]" .. rest + -- Update the current line + vim.api.nvim_set_current_line(new_line) end + -- If the pattern didn't match, do nothing. end -- Set up buffer-local keymaps