Home Writing Reading

til / Spellcheck multiple languages in Neovim

By default, spellchecking is not enabled in Neovim. But, we can easily turn it on using :set spell spelllang=en. This enables spellchecking (spell=true) and sets the language to English.

Only English spellchecking works out-of-the-box, but what if you want multiple language? For example, Swedish. First, we need to have a dictionary, which can be found here. Download the sv.utf-8.spl and sv.utf-8.sug files and put them in ~/.config/nvim/spell (adjust path as needed to fit your setup).

It’s tedious to have to write the commands every time we open up Neovim, so let’s add them to our config.

vim.opt.spell = true -- Enable spellchecking
vim.opt.spelllang = { "en", "sv" } -- Set languages

Using ]s and [s we can go the next or previous spelling mistake.

Every word won’t exist in the dictionaries. This means words will be marked as incorrect, but if you know they are correct you can mark them as good by putting your cursor on the word and doing zg. This create a new file with your additions. To remove a word from the list do zug. To see all available commands, check the docs using :h spell.

These commands add/remove to the default language, but we have multiple. Let’s create a function that we can use to add the word to a specific language’s additions.

-- Add word in a specific language
local function add_word_to_lang(lang)
	-- Find word under cursor
	local word = vim.fn.expand("<cword>")
	if word == "" then
		print("No word under cursor.")
		return
	end

	-- Save original language and spellfile
	local original_lang = vim.opt.spelllang:get()
	local original_spellfile = vim.opt.spellfile

	-- Get the current language file
	local spellfile_path = vim.fn.expand(string.format("~/.dotfiles/nvim/spell/%s.utf-8.add", lang))

	-- Temporarily set spelllang to only the desired language
	vim.opt.spelllang = { lang }
	vim.opt.spellfile = spellfile_path

	-- Mark word as good and save spellfile
	vim.cmd("silent! spellgood " .. word)
	vim.cmd("silent! mkspell! " .. spellfile_path)

	-- Restore original settings
	vim.opt.spelllang = original_lang
	vim.opt.spellfile = original_spellfile

	print("Added '" .. word .. "' to " .. lang)
end

Following what we did to organize key mappings, we can add a new grouping to add a word to a specific language easily.

-- Spelling
{ "<leader>w", group = "Spelling" },
{
	"<leader>ws",
	function()
		add_word_to_lang("sv")
	end,
	desc = "Add word to Swedish",
},
{
	"<leader>we",
	function()
		add_word_to_lang("en")
	end,
	desc = "Add word to English",
},

  • Loading next post...
  • Loading previous post...