From 19bc23fc3e98869570f2baa9814f27eaa57cc659 Mon Sep 17 00:00:00 2001
From: Oliver Davies <oliver@oliverdavies.uk>
Date: Mon, 8 Aug 2022 19:11:15 -0400
Subject: [PATCH] feat: allow for toggling checkboxes

---
 lua/toggle-checkbox.lua | 18 ++++++++++++++----
 1 file changed, 14 insertions(+), 4 deletions(-)

diff --git a/lua/toggle-checkbox.lua b/lua/toggle-checkbox.lua
index 4f8ef0e..79d859f 100644
--- a/lua/toggle-checkbox.lua
+++ b/lua/toggle-checkbox.lua
@@ -1,15 +1,15 @@
 local checked_character = "x"
 
 local checked_checkbox = "[" .. checked_character .. "]"
-local unchecked_checkbox = "[ ]"
+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_a_checked_checkbox = function(line)
--- 	return string.find(line, checked_checkbox)
--- end
+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 })
@@ -23,6 +23,16 @@ M.check = function()
 	write_line(new_line)
 end
 
+M.toggle = function()
+	-- If the line contains a checked checkbox then uncheck it.
+	-- Otherwise, if it contains an unchecked checkbox, check it.
+	if line_contains_an_unchecked_checkbox(current_line) then
+		M.check()
+	else
+		M.uncheck()
+	end
+end
+
 M.uncheck = function()
 	local new_line = current_line:gsub("%[" .. checked_character .. "%]", unchecked_checkbox)
 	write_line(new_line)