Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I setup vim to automatically convert the line endings of any text file I open to unix if it already isn't unix?

Tags:

vim

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

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

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

And isn't there a trick to using :%s/^M//g because using a literal ^ wont match the char?

like image 638
meder omuraliev Avatar asked Mar 18 '11 20:03

meder omuraliev


1 Answers

The function below is interesting because it keeps the cursor to its original position put it in your. 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()
like image 155
SergioAraujo Avatar answered Oct 12 '22 02:10

SergioAraujo