nvim: Add custom spellcheck toggle with user events

Added a user command `SpellTogle` which toggles on or off spellchecking
in the current buffer. Can be invoked like that, or with one or multiple
language to spellcheck (e.g. `SpellToggle en_us en_gb`). Can also be
invoked with a bang to always enable instead of toggling.

Publishes a user event called `SpellEnable` or `SpellDisable` depending
on the aciton which autocommands can listen for.
This commit is contained in:
Marty Oehme 2024-06-27 17:18:34 +02:00
parent 7ff62840b7
commit 9ded34f73c
Signed by: Marty
GPG key ID: EDBF2ED917B2EF6A
2 changed files with 22 additions and 4 deletions

View file

@ -24,3 +24,20 @@ vim.api.nvim_create_autocmd({ "TermOpen" }, {
pattern = "*",
command = "setlocal nonumber norelativenumber",
})
-- Custom spell enable which fires an event that other things can
-- hook into.
-- Toggles off and on by default, only turns on if called with bang.
vim.api.nvim_create_user_command("SpellToggle", function(opt)
vim.opt.spell = opt.bang or not vim.opt.spell:get()
if vim.opt.spell:get() then
if next(opt.fargs) ~= nil then
vim.opt.spelllang = opt.fargs
end
vim.api.nvim_exec_autocmds("User", { pattern = "SpellEnable" })
vim.notify("Spellcheck enabled")
else
vim.api.nvim_exec_autocmds("User", { pattern = "SpellDisable" })
vim.notify("Spellcheck disabled")
end
end, { nargs = "*", bang = true })

View file

@ -127,10 +127,11 @@ map("n", "<localleader>Q", "vapJgqap", { silent = true, desc = "Unformat then fo
-- SPELL CHECKING
-- Move to the prev/next spelling error with [S ]S
-- Move to the prev/next spelling error or suggestion with [s ]s
map("n", "<localleader>ZZ", ":setlocal spell! spelllang=en_us,en_gb,de_de<cr>", { desc = "Toggle spellcheck" })
map("n", "<localleader>ZE", ":setlocal spell! spelllang=en_us<cr>", { desc = "Toggle EN_US spellcheck" })
map("n", "<localleader>ZB", ":setlocal spell! spelllang=en_gb<cr>", { desc = "Toggle EN_GB spellcheck" })
map("n", "<localleader>ZD", ":setlocal spell! spelllang=de_de<cr>", { desc = "Toggle DE_DE spellcheck" })
map("n", "<localleader>ZZ", "<cmd>SpellToggle en_us en_gb de_de<cr>", { desc = "Toggle spellcheck" })
map("n", "<localleader>ZA", "<cmd>SpellToggle! en_us en_gb de_de<cr>", { desc = "Enable spellcheck" })
map("n", "<localleader>ZE", "<cmd>SpellToggle en_us<cr>", { desc = "Toggle EN_US spellcheck" })
map("n", "<localleader>ZB", "<cmd>SpellToggle en_gb<cr>", { desc = "Toggle EN_GB spellcheck" })
map("n", "<localleader>ZD", "<cmd>SpellToggle de_de<cr>", { desc = "Toggle DE_DE spellcheck" })
-- undo last spelling mistake from insert and normal mode
map("i", "<c-z>", "<C-G>u<Esc>e[s1z=`]a<C-G>u")
map("n", "<localleader>z", "mse[s1z=`s", { desc = "Fix last spell error" })