Date Category Vim Tags spell

Vim has great built-in spell checking. Even better, when editing source code files, it is smart enough to know not do spell checking in source code, which is quite neat. However, it will still do spell checking for string literals. Most of the times, this is not desired. This post shows how to tell VIM only do spell checking in comments when editing code files.

Vim figures out which region of the contents need spell checking by inferring the syntax files. For example, for C files, the syntax file is located at /usr/share/vim/vim74/syntax/c.vim. There, you will find several lines that defines the cString region. One example is the following line:

syn region  cString     start=+L\="+ skip=+\\\\\|\\"+ end=+"+ contains=cSpecial,@Spell extend

You'll notice that at the end, it says @Spell, which tells VIM that the string literals need spell check.

To override this behavior, and let VIM leave string literals alone when do spell checking, we can change the definition of cString in our own syntax files.

For instance, you can put these lines in ~/.vim/after/syntax/c.vim:

if exists("c_no_cformat")
  syn region    cString     start=+L\="+ skip=+\\\\\|\\"+ end=+"+ contains=cSpecial
else
  syn region    cString     start=+L\="+ skip=+\\\\\|\\"+ end=+"+ contains=cSpecial,cFormat
endif

if !exists("c_no_c11") " ISO C11
  if exists("c_no_cformat")
    syn region  cString     start=+\%(U\|u8\=\)"+ skip=+\\\\\|\\"+ end=+"+ contains=cSpecial
  else
    syn region  cString     start=+\%(U\|u8\=\)"+ skip=+\\\\\|\\"+ end=+"+ contains=cSpecial,cFormat
  endif
endif

They are almost identical to the default definition in /usr/share/vim/vim74/syntax/c.vim, just the trailing @Spells are removed.

This technique can also be applied to other languages, such as python or Java.