mirror of
https://github.com/opdavies/toggle-checkbox.nvim.git
synced 2025-03-13 05:26:56 +00:00
fix: cursor position is cached
Running the toggle command via a keymap multiple times within the same file was always returning the first toggled line rather than updating the cursor position and using the next line.
This commit is contained in:
parent
19bc23fc3e
commit
f1e335a96d
|
@ -3,39 +3,38 @@ local checked_character = "x"
|
|||
local checked_checkbox = "[" .. checked_character .. "]"
|
||||
local unchecked_checkbox = "%[ %]"
|
||||
|
||||
local bufnr = vim.api.nvim_buf_get_number(0)
|
||||
local cursor = vim.api.nvim_win_get_cursor(0)
|
||||
local current_line = vim.api.nvim_buf_get_lines(bufnr, cursor[1] - 1, cursor[1], false)[1] or ""
|
||||
|
||||
local line_contains_an_unchecked_checkbox = function(line)
|
||||
return string.find(line, unchecked_checkbox)
|
||||
end
|
||||
|
||||
local write_line = function(new_line)
|
||||
vim.api.nvim_buf_set_lines(bufnr, cursor[1] - 1, cursor[1], false, { new_line })
|
||||
vim.api.nvim_win_set_cursor(0, cursor)
|
||||
local checkbox = {}
|
||||
|
||||
checkbox.check = function(line)
|
||||
return line:gsub("%[ %]", checked_checkbox)
|
||||
end
|
||||
|
||||
checkbox.uncheck = function(line)
|
||||
return line:gsub("%[" .. checked_character .. "%]", unchecked_checkbox)
|
||||
end
|
||||
|
||||
local M = {}
|
||||
|
||||
M.check = function()
|
||||
local new_line = current_line:gsub("%[ %]", checked_checkbox)
|
||||
write_line(new_line)
|
||||
end
|
||||
|
||||
M.toggle = function()
|
||||
local bufnr = vim.api.nvim_buf_get_number(0)
|
||||
local cursor = vim.api.nvim_win_get_cursor(0)
|
||||
local current_line = vim.api.nvim_buf_get_lines(bufnr, cursor[1] - 1, cursor[1], false)[1] or ""
|
||||
|
||||
-- If the line contains a checked checkbox then uncheck it.
|
||||
-- Otherwise, if it contains an unchecked checkbox, check it.
|
||||
local new_line = ""
|
||||
if line_contains_an_unchecked_checkbox(current_line) then
|
||||
M.check()
|
||||
new_line = checkbox.check(current_line)
|
||||
else
|
||||
M.uncheck()
|
||||
new_line = checkbox.uncheck(current_line)
|
||||
end
|
||||
end
|
||||
|
||||
M.uncheck = function()
|
||||
local new_line = current_line:gsub("%[" .. checked_character .. "%]", unchecked_checkbox)
|
||||
write_line(new_line)
|
||||
vim.api.nvim_buf_set_lines(bufnr, cursor[1] - 1, cursor[1], false, { new_line })
|
||||
vim.api.nvim_win_set_cursor(0, cursor)
|
||||
end
|
||||
|
||||
return M
|
||||
|
|
Loading…
Reference in a new issue