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.