这里记录如何在Neovim启用内置的拼写检查功能。

启用拼写

首先,添加拼写检查语言:

1
set spelllang=en,cjk

上面的配置,将拼写语言设置为encjkcjk选项用于防止将CJK字符被标记为拼写错误。

CJK: 中日韩统一表意文字(英语:CJK Unified Ideographs),也称统一汉字、统汉码(英语:Unihan),目的是要把分别来自中文、日文、韩文、越南文、壮文、琉球文中,起源相同、本义相同、形状一样或稍异的表意文字,在ISO 10646及Unicode标准赋予相同编码。 所谓“起源相同、本义相同”、主要是汉字,包括繁体字、简化字、日本汉字(漢字/かんじ)、韩国汉字(漢字/한자)、琉球汉字(漢字/ハンジ)、越南的喃字(𡨸喃/Chữ Nôm)与儒字(𡨸儒/Chữ Nho)、方块壮字(𭨡倱/sawgun)。

cjk配置项,也记录在 Nvim doc 文档中:

Chinese, Japanese and other East Asian characters are normally marked as errors, because spell checking of these characters is not supported. If ‘spelllang’ includes “cjk”, these characters are not marked as errors. This is useful when editing text with spell checking while some Asian words are present.

使Nvim启用拼写检查功能,需要运行命令:set spell。下面可以添加一个映射来切换拼写检查:

1
nnoremap <silent> <F11> :set spell!<cr>

或者

1
vim.api.nvim_set_keymap('n', '<F11>', [[<Cmd>set spell!<CR>]], { noremap = true, silent = true })

此时,可以按来切换拼写检查。

此外,也可以在init.lua中通过创建autocmd,根据文件类型(filetype),来自动切换拼写检查功能,如:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
local spell_group = vim.api.nvim_create_augroup("spell_group", { clear = true })
vim.api.nvim_create_autocmd("FileType", {
  pattern = { "lua", "python", "go" },
  command = "setlocal spell spelllang=en_us,cjk",
  group = spell_group,
})
vim.api.nvim_create_autocmd("FileType", {
  pattern = { "markdown" },
  command = "setlocal nospell",
  group = spell_group,
})
vim.api.nvim_create_autocmd("TermOpen", {
  pattern = "*", -- disable spellchecking in the embeded terminal
  command = "setlocal nospell",
  group = spell_group,
})

上面的配置,在luaptyhongo文件中启用拼写检查,并将拼写语言设置为en_us,cjk,在Markdown文件禁用拼写检查, 同时在内嵌终端(embeded terminal)中禁用拼写检查。

更正拼写错误

在插入模式时,当输入了NeoVim认为是拼写错误的单词时,会在其下方显示下划线。要更正错误,可以依次按下<C-x>s键,此时 会显示一个建议正确单词的菜单列表,可以选择其中一项来更正拼写。

normal模式,可以使用下面的快捷键来快速处理拼写错误问题:

  • [s: 跳转到上一处拼写错误
  • ]s: 跳转到下一处拼写错误
  • z=: 对光标下或之后的单词,显示建议正确的拼写单词
  • zg: 将光标下的单词作为正确拼写单词加入到‘spellfile’
  • zw: 和zg类似,只是zw是将这个单词标记为拼写错误的单词

驼峰拼写检查

spelloptions配置选项默认值是"",此时,注释中的驼峰拼写的单词,会被判定为拼写错误,如: camel case

可以通过配spelloptions启动驼峰单词拼写:

1
vim.opt.spelloptions = "camel"

判断规则:

When a word is CamelCased, assume “Cased” is a separate word: every upper-case character in a word that comes after a lower case character indicates the start of a new word.

引用