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.
mm
creates a new mark at the cursor’s current position, saving it to registera
.H
moves the cursor to the top of the screen.mb
creates a new mark at the cursor’s current position, saving it to registerb
. This is so that we can have a reference to the original scroll position.:%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>
).'b
moves the cursor to markb
, the previous top of screen.zt
forces a redraw, to restore the original scroll position.'a
moves the cursor back to marka
, 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.