1

I want to spellcheck a bunch of files with vim, so I run:

for a in *.txt
do
  vim -c 'set spell' $a
done

Now, in each file, I use ]s to find the next unknown word, and fix the typo or add it to my dictionary; and when I'm done I close the current file with ZZ and the next one automatically opens.

That's fine, but for the vast majority of files, there are no typos to report, so I end up doing a lot of ZZ, ZZ, ZZ, etc. It would be better if I could somehow do the following: start vim, but if there are no words in the file that the spellchecker doesn't know about, exit immediately. That way I wouldn't have to close files where there are no changes to make.

Is there a way to run vim and immediately exit when the spellchecker has no complaint about the file?

  • 1
    A simple version might attempt ]s and, if the cursor doesn’t move, quit. – D. Ben Knoble Aug 31 '18 at 13:51
2

A simple script to look for a misspelled word and to quit Vim if it doesn't exist might look like:

fun! SpellNext()
    " Go to start of buffer and enable spell checking.
    normal! gg
    set spell

    " Record cursor position.
    let l:pos = getpos('.')

    " Special case: first word is misspelled.
    if spellbadword()[1] isnot# ''
        return
    endif

    " Try to find a misspelled word.
    normal! ]s

    " No more words left if the position is unchanged from last
    " time, so quit Vim.
    if getpos('.') == l:pos
        quit
    endif
endfun

As an extra bonus this will also put your cursor on the first misspelled word.

You can load this script when Vim starts with the -S commandline flag, and call the function with -c:

$ vim -S spell.vim  -c ":call SpellNext()" file

All of that being said; it is probably easier to load multiple files in one go:

vim -p *.txt

And then call this on every tab:

:tabdo :call SpellNext()

Which will close all the tabs without spelling errors.

You can probably also do the same with buffers; but I'm in the "use-tabs-as-buffers" crowd, so I don't know how to do that from the top of my head >_<

  • This works fine, thanks a lot! The only downside to the first solution is that the terminal blinks each time that vim is opened and closed, but I guess this can't be avoided. :) I'll consider the second solution (which avoids this issue). – a3nm Sep 4 '18 at 6:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.