[vim] VIM Disable Automatic Newline At End Of File

So I work in a PHP shop, and we all use different editors, and we all have to work on windows. I use vim, and everyone in the shop keeps complaining that whenever I edit a file there is a newline at the bottom. I've searched around and found that this is a documented behavior of vi & vim... but I was wondering if there was some way to disable this feature. (It wouldbe best if I could disable it for specific file extensions).

If anyone knows about this, that would be great!

This question is related to vim settings newline

The answer is


I think I've found a better solution than the accepted answer. The alternative solutions weren't working for me and I didn't want to have to work in binary mode all the time. Fortunately this seems to get the job done and I haven't encountered any nasty side-effects yet: preserve missing end-of-line at end of text files. I just added the whole thing to my ~/.vimrc.


I found this vimscript plugin is helpful for this situation.

Plugin 'vim-scripts/PreserveNoEOL'

Or read more at github


I've added a tip on the Vim wiki for a similar (though different) problem:

http://vim.wikia.com/wiki/Do_not_auto-add_a_newline_at_EOF


OK, you being on Windows complicates things ;)

As the 'binary' option resets the 'fileformat' option (and writing with 'binary' set always writes with unix line endings), let's take out the big hammer and do it externally!

How about defining an autocommand (:help autocommand) for the BufWritePost event? This autocommand is executed after every time you write a whole buffer. In this autocommand call a small external tool (php, perl or whatever script) that strips off the last newline of the just written file.

So this would look something like this and would go into your .vimrc file:

autocmd!   "Remove all autocmds (for current group), see below"
autocmd BufWritePost *.php !your-script <afile>

Be sure to read the whole vim documentation about autocommands if this is your first time dealing with autocommands. There are some caveats, e.g. it's recommended to remove all autocmds in your .vimrc in case your .vimrc might get sourced multiple times.


Would it be possible for you to use a special command for saving these files?

If you do :set binary, :w and :set nobinary the file will be written without newline if there was none to start with.

This sequence of commands could be put into a user defined command or a mapping, of course.


There is another way to approach this if you are using Git for source control. Inspired by an answer here, I wrote my own filter for use in a gitattributes file.

To install this filter, save it as noeol_filter somewhere in your $PATH, make it executable, and run the following commands:

git config --global filter.noeol.clean noeol_filter
git config --global filter.noeol.smudge cat

To start using the filter only for yourself, put the following line in your $GIT_DIR/info/attributes:

*.php filter=noeol

This will make sure you do not commit any newline at eof in a .php file, no matter what Vim does.

And now, the script itself:

#!/usr/bin/python

# a filter that strips newline from last line of its stdin
# if the last line is empty, leave it as-is, to make the operation idempotent
# inspired by: https://stackoverflow.com/questions/1654021/how-can-i-delete-a-newline-if-it-is-the-last-character-in-a-file/1663283#1663283

import sys

if __name__ == '__main__':
    try:
        pline = sys.stdin.next()
    except StopIteration:
        # no input, nothing to do
        sys.exit(0)

    # spit out all but the last line
    for line in sys.stdin:
        sys.stdout.write(pline)
        pline = line

    # strip newline from last line before spitting it out
    if len(pline) > 2 and pline.endswith("\r\n"):
        sys.stdout.write(pline[:-2])
    elif len(pline) > 1 and pline.endswith("\n"):
        sys.stdout.write(pline[:-1])
    else:
        sys.stdout.write(pline)

Try to add in .vimrc

set binary

I've implemented Blixtor's suggestions with Perl and Python post-processing, either running inside Vim (if it is compiled with such language support), or via an external Perl script. It's available as the PreserveNoEOL plugin on vim.org.


Starting with vim v7.4 you can use

:set nofixendofline

There is some information about that change here: http://ftp.vim.org/vim/patches/7.4/7.4.785 .


Maybe you could look at why they are complaining. If a php file has a newline after the ending ?>, php will output it as part of the page. This is not a problem unless you try to send headers after the file is included.

However, the ?> at the end of a php file is optional. No ending ?>, no problem with a newline at the end of the file.


I have not tried this option, but the following information is given in the vim help system (i.e. help eol):

'endofline' 'eol'   boolean (default on)
            local to buffer
            {not in Vi}

When writing a file and this option is off and the 'binary' option
is on, no <EOL> will be written for the last line in the file.  This
option is automatically set when starting to edit a new file, unless
the file does not have an <EOL> for the last line in the file, in
which case it is reset.  

Normally you don't have to set or reset this option. When 'binary' is off the value is not used when writing the file. When 'binary' is on it is used to remember the presence of a for the last line in the file, so that when you write the file the situation from the original file can be kept. But you can change it if you want to.

You may be interested in the answer to a previous question as well: "Why should files end with a newline".


Add the following command to your .vimrc to turn of the end-of-line option:

autocmd FileType php setlocal noeol binary fileformat=dos

However, PHP itself will ignore that last end-of-line - it shouldn't be an issue. I am almost certain that in your case there is something else which is adding the last newline character, or possibly there is a mixup with windows/unix line ending types (\n or \r\n, etc).

Update:

An alternative solution might be to just add this line to your .vimrc:

set fileformats+=dos

Examples related to vim

Why does using from __future__ import print_function breaks Python2-style print? How to run vi on docker container? How can I install MacVim on OS X? Find and replace strings in vim on multiple lines Running Python code in Vim How do I set the default font size in Vim? Move cursor to end of file in vim Set encoding and fileencoding to utf-8 in Vim How to select all and copy in vim? Why I've got no crontab entry on OS X when using vim?

Examples related to settings

How to configure "Shorten command line" method for whole project in IntelliJ Error: Module not specified (IntelliJ IDEA) Instant run in Android Studio 2.0 (how to turn off) How do I open phone settings when a button is clicked? Google Chrome: This setting is enforced by your administrator maven command line how to point to a specific settings.xml for a single command? Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty Python: How would you save a simple settings/config file? How to set my phpmyadmin user session to not time out so quickly? Setting DEBUG = False causes 500 Error

Examples related to newline

How can I insert a line break into a <Text> component in React Native? Print "\n" or newline characters as part of the output on terminal Using tr to replace newline with space How to write one new line in Bitbucket markdown? Line break in SSRS expression How to insert a new line in Linux shell script? Replace CRLF using powershell How to write new line character to a file in Java What is the newline character in the C language: \r or \n? How to print values separated by spaces instead of new lines in Python 2.7