25

Vim always adds a new line at the end of my files when saving, and it is causing errors in my PHP scripts.

How can I make vim not add this new line on save?

4
  • 10
    "it is causing errors in my PHP scripts" -> This is strange? PHP should work fine with a trailing newline. In fact, this is pretty much standard. Perhaps you have a blank line after the ?> which PHP outputs to the browser (causing the "headers already sent"-error)? You don't need a trailing ?>, and it is usually recommended to leave it out to prevent exactly this problem. Commented May 28, 2015 at 15:53
  • I guess thats misleading. Our scripts interpret any output as an error.
    – Dan
    Commented May 28, 2015 at 15:55
  • 2
    Also, related question: How to make vim automatically add a newline to the end of a file? Commented May 28, 2015 at 15:55
  • 1
    No. Vim is not adding a new line.
    – romainl
    Commented May 28, 2015 at 16:13

4 Answers 4

16

This isn't a full empty line, just a final newline at the end of the last line. Unix tools (like Vim's heritage) insist on adding that, whereas the Windows operating system is not so strict. You can read more on that at Why should files end with a newline?

Unfortunately, it's quite complex to prevent Vim from writing the final newline. My PreserveNoEOL plugin can do this. For a discussion of approaches, also see VIM Disable Automatic Newline At End Of File.

1
25

In new versions of Vim there's finally an option for this

Vim 7.4.785 adds the 'fixeol' option that can be disabled to automatically preserve any missing EOL at the end of the file.

(see wiki page: http://vim.wikia.com/wiki/Do_not_auto-add_a_newline_at_EOF)

In your ~/.vimrc add this line:

set nofixeol

Relaunch vim, now it shouldn't add the newline at the end of the file.

(works only since vim version 7.4.785)

8

What eventually worked for me was:

vim -b <filename>

Then in vim:

:set noeol
:wq

Credit

1
  • This also works for removing the ending newline from a file which already has it, which the other answers don't help with.
    – Tgr
    Commented Feb 19, 2021 at 0:29
2

Have you tried opening the file in binary mode? Try vim -b file_name. It should not add the new line at end of file.

1
  • I tried doing this, and then using xxd to verify, but it still adds a linefeed (0a) even in binary mode.
    – DJMcMayhem
    Commented Oct 5, 2016 at 22:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.