I've turned on spellcheck with :set spell spelllang=en_us. Now there's a bunch of words highlighted in red, and I just want to correct them all to their closest matches.

How can I correct all misspelled words in the entire file?

up vote 11 down vote accepted

Here's something I didn't know until a little while ago: Macros can be recursive! That is, you can call a macro from within the same macro.

So, here's the command:

ggqq]s1z=@qq@q

That is,

gg  Move to the beginning of the file
qq  Start recording the "q" macro
]s  Find the next misspelled word
1z= Correct its spelling
@q  Call the "q" macro (we're still recording!)
q   Finish recording
@q  Call the macro for the first time

Since there's a @q at the end of the macro, it repeatedly calls itself until it reaches EOF. Therefore, it'll correct all the misspelled words in the entire document.

Make sure the q macro is empty before running this, though (if not, you can clear it with qqq).

  • Is there also a way to easily see which words Vim corrected? I ran this on a file, and it generated a lot of gobbledygook ... – Martin Tournoij Feb 6 '15 at 0:18
  • How terrifying. So this calls the macro while it is still recording that same macro? – Lyndon White Feb 6 '15 at 4:28
  • @Carpetsmoker You could save the file as a new file, and run a diff on them. But this isn't going to produce anywhere near reasonable results for source code and the like, of course. – Doorknob Feb 6 '15 at 12:46
  • @Oxinabox Yes, and as long as the macro is empty before this, the finished macro will repeatedly call itself until reaching EOF. – Doorknob Feb 6 '15 at 12:47

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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