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

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.


Solution 1:

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.)

Solution 2:

Heptite is correct, and to make this setting automatically whenever you edit a PHP file, you can add the following to your ~/_vimrc file:

au BufRead,BufNewFile *.php set fileformat=unix

This is an autocommand that is run whenever you read a file into a buffer or create a new buffer that has a filename that matches the pattern "*.php", and sets the fileformat to "unix", as per Heptite's answer.