How to configure vim to automatically convert line endings of any text file that I open for unix, if it is not already unix?

I'm looking for some kind of plugin / vi code that detects if there are any ^M (carriage returns?) In any files or any signs that the line endings are not unix, and if so, delete them or run dos2unix in the file.

I need this to work automatically before / during file opening.

Also, for people who are going to suggest ways to convert line endings manually, one answer points to :set ff=unix , but that doesn't kill ^M in the unix file, I think.

And is there a trick to use :%s/^M//g , because using the literal ^ doesn't match char?

+6
vim
source share
3 answers

The function below is interesting in that it holds the cursor to its original position, put it in your own. vimrc

 " dos2unix ^M fun! Dos2unixFunction() let _s=@ / let l = line(".") let c = col(".") try set ff=unix w! "%s/\%x0d$//e catch /E32:/ echo "Sorry, the file is not saved." endtry let @/=_s call cursor(l, c) endfun com! Dos2Unix keepjumps call Dos2unixFunction() au BufReadPost * keepjumps call Dos2unixFunction() 
+3
source share

Since you checked this git, you can have git convert line endings to s checkin / out automatically (http://www.kernel.org/pub/software/scm/git/docs/git -config.html)

ps. The trick to doing ^ M in replacement is

:%s/{Ctrl+V}{Ctrl+M}//{Enter}

+1
source share

If you want to replace any ^ M in any file you open, then autocmd, like the one below in vimrc, can help:

 au BufReadPost * %s/^M//g 

Insert ^ M as indicated in the previous answer.

0
source share

All Articles