4

I've run into the problem mentioned here, but in a context in which I don't have an easy alternative that I can think of.

I'm trying to add a mapping to fix bad newline characters in a file. I would generally type: :%s/^M//g to remove all of the ^M characters. My mapping attempt to do this (and save) is as follows:

nnoremap <Leader>fix :%s/^M//g<Bar>w<CR>

The problem with my mapping is that the ^M gets automatically converted to <CR> and the mapping breaks, of course. I have also tried:

nnoremap <Leader>fix :%s/<c-v><c-m>//g<Bar>w<CR>

...and that fails as well.

I've noticed that if I leave off the <CR> at the end to debug the mapping, I get //g|w as the only thing on the command prompt. Ideally, this would be %s/^M//g|w to achieve the desired behavior.

JayD
  • 43
  • 3

1 Answers1

5

To match carriage return, <cr>, ^M, ASCII value 13, you should use \r in the pattern: %s/\r//.... This is documented at :help /\r.

Note that \r in the substitution part (:s//<here>/), rather than in the pattern part, has a completely different meaning which is "split the line in two."

Mass
  • 14,080
  • 1
  • 22
  • 47
  • Another token that matches <CR> is character class [:return:]. So :s/[[:return:]]//... ... \r is easier to type, obviously (though maybe not easier to remember). – B Layer Jul 02 '18 at 04:05