Zap Gremlins

When copying text into Vim from Microsoft applications, such as Outlook or Word, every line ending will often have a ^M character appended. These pesky characters are known as gremlins. They are annoying and mess up my otherwise beautiful text. What to do? Destroy them with a single command, of course.

The command in its full glory:

maHmb:%s/<C-V><CR>//ge<CR>'bzt'a

It looks a lot worse than it actually is. Let’s walk through it.

  1. mm creates a new mark at the cursor’s current position, saving it to register a.
  2. H moves the cursor to the top of the screen.
  3. mb creates a new mark at the cursor’s current position, saving it to register b. This is so that we can have a reference to the original scroll position.
  4. :%s/<C-V><CR>//ge<CR> is a global find-and-replace command, which deletes all ^M characters in the current buffer (to find the gremlins, we search for <C-V><CR>).
  5. 'b moves the cursor to mark b, the previous top of screen.
  6. zt forces a redraw, to restore the original scroll position.
  7. 'a moves the cursor back to mark a, the starting cursor position.

In my .vimrc file, this is the key binding I use:

" zap gremlins (the Windows ^M)
nnoremap <Leader>mm maHmb:%s/<C-V><CR>//ge<CR>'bzt'a

In my configuration, comma is bound to leader. Pressing ,mm while in normal mode runs the command to zap all gremlins in the current buffer.

Please note that the names of the mark registers I used (a and b) are completely arbitrary. You can use whatever letters you want.