How to force vim to end all lines with a single linefeed character (LF)

gvimtext formattingvim

As the title says, I need to force vim (in my case gVim) end all lines with a single linefeed character (LF). How can I do this?

I'm trying to follow the standards for PHP coding, specifically http://framework.zend.com/manual/en/coding-standard.php-file-formatting.html#coding-standard.php-file-formatting.line-termination.

Best Answer

The short answer is to open the file in Vim and then type ":set fileformat=unix" then write the file. From that point on, Vim should treat the file as Unix fileformat and only use newline characters instead of carriage-return+newline.

The long answer is that this sometimes does not work, because when you open the file in Vim you see actual ^M characters at the end of most of the lines. In this case it could be for two reasons:

  1. The most likely is that it was saved originally as DOS file format, then "damaged" by another editor that assumed it could treat it as Unix format without conversion and left a few lines without DOS line endings. In this case you should just do something like :%s/\%x0d$//g then write.
  2. The file is a proper DOS file format but Vim is not recognizing this fact. This probably means that your 'fileformats' option is not properly set. To learn more about this, see ":help 'fileformats'" (the single quotes are part of the help command).

Finally, if you are using Vim on a Windows machine you may need to change the mentioned 'fileformats' option to "unix,dos" in your ~/_vimrc instead of the default "dos,unix" that it is set to in DOS/Windows environments. This will cause Vim to create new buffers in the Unix format instead of DOS format. (Again, refer to the help for details.)

Related Question