6

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?

Doorknob
  • 15,237
  • 3
  • 48
  • 70

1 Answers1

11

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).

Doorknob
  • 15,237
  • 3
  • 48
  • 70
  • 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 06 '15 at 00:18
  • How terrifying. So this calls the macro while it is still recording that same macro? – Frames Catherine White Feb 06 '15 at 04: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 06 '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 06 '15 at 12:47