0

I'm trying to map a command in my vimrc to remove the carriage return character ^M that I sometimes see in files. :%s/^M//g (^M from ctrl-v, ctrl-m) works pretty easily when I'm in the file, but when I save that in my vimrc, it's no good.

nmap ,dm  :%s/^M//g <cr>

I'm guessing it's because ^M is interpretted differently when mapped via vimrc, so I tried escaping it with \, to no avail. How can I map this command so that it removes the carriage return characters?

FWIW, I'm using gVim on Windows.

Matthew Woo
  • 1,288
  • 15
  • 28

1 Answers1

0

Almost every vim user reaches a moment he wants to solve this issue elegantly and one thing I figured out is that we also need a solution to get rid of ^M and keep the cursor position at once.

Personally I use a function to preserve my cursor position, because when we get rid of ^M the cursor position will change:

" preserve function
if !exists('*Preserve')
    function! Preserve(command)
        try
            let l:win_view = winsaveview()
            "silent! keepjumps keeppatterns execute a:command
            silent! execute 'keeppatterns keepjumps ' . a:command
        finally
            call winrestview(l:win_view)
        endtry
    endfunction
endif

The propper function to get rid of ^M

" dos2unix ^M
if !exists('*Dos2unixFunction')
    fun! Dos2unixFunction() abort
        "call Preserve('%s/ $//ge')
        call Preserve(":%s/\x0D$//e")
        set ff=unix
        set bomb
        set encoding=utf-8
        set fileencoding=utf-8
    endfun
endif
com! Dos2Unix :call Dos2unixFunction()

As you can see we are using \x0D$ instead of ^M, which is the hexadecimal code for the ^M

The option set bomb helps considering the file as UTF-8 help here. It helps solving encoding issues.

The function "Preserve" can also be used to many other stuff like reindenting the whole file without "moving" our cursor

command! -nargs=0 Reindent :call Preserve('exec "normal! gg=G"')

The above line will set a "Reindent" command with no arguments "-nargs=0". By the way feel free to stell some pieces of my init.vim here

NOTE: It is worth mention the "ifs" preceding the two functions above, it is called guard, it helps us to avoid loading functions twice in the memory, thus, keeping our vim/neovim responsible as much as possible.

SergioAraujo
  • 11,069
  • 3
  • 50
  • 40