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?

Dan
  • 485
  • 2
  • 5
  • 8

4 Answers4

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)

DarthVanger
  • 351
  • 3
  • 5
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.

Ingo Karkat
  • 17,819
  • 1
  • 45
  • 61
7

What eventually worked for me was:

vim -b <filename>

Then in vim:

:set noeol
:wq

Credit

Tom Hale
  • 2,681
  • 14
  • 32
  • This also works for removing the ending newline from a file which already has it, which the other answers don't help with. – Tgr Feb 19 '21 at 00: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.

DJMcMayhem
  • 17,581
  • 5
  • 53
  • 85
Ali
  • 121
  • 1