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.

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

  • 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 2 '18 at 4:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.