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:
It looks a lot worse than it actually is. Let’s walk through it.
mmcreates a new mark at the cursor’s current position, saving it to register
Hmoves the cursor to the top of the screen.
mbcreates 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.
:%s/<C-V><CR>//ge<CR>is a global find-and-replace command, which deletes all
^Mcharacters in the current buffer (to find the gremlins, we search for
'bmoves the cursor to mark
b, the previous top of screen.
ztforces a redraw, to restore the original scroll position.
'amoves 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 (
b) are completely arbitrary. You can use whatever letters you want.