Proposed tip Please edit this page to improve it, or add your comments below (do not use the discussion page).
By default, Vim adds a newline after the last line of each file. That's great for new files, but when you edit other people's files and they don't have newlines at the end, the diff gets cluttered with an extra chunk like this, because Vim "helpfully" added a newline:
- } \ No newline at end of file + }
To stop this from happening, add this to your .vimrc:
set binary
Caveats:
- This will silently convert all line endings to Unix format, so it's probably not usable on Windows.
- Options textwidth, wrapmargin, modeline and expandtab are reset by :set binary, so make sure that "set binary" comes before setting any of these options.
Always remove newlines at EOF
If you want to always strip newlines from files (even new ones), you can try this:[1]
au BufWritePre * :set binary | set noeol au BufWritePost * :set nobinary | set eol
References
Comments
Though, I don't know why this is really useful, but since this has been asked in the mailinglist at least twice, I have come up with the following workaround, that keeps the DOS Line-endings while writing without a final EOF:
fun! WriteFileWithoutEOF()
let a=getline(1,line('$')-1)
call map(a, 'v:val . nr2char(13)')
call extend(a, getline('$', '$'))
call writefile(a,fnamemodify(@%, ':p'), 'b')
unlet a
endfun
au BufWriteCmd filename :call WriteFileWithoutEOF()
Disclaimer: This should work, but I haven't tested it. Chrisbra 22:18, January 25, 2011 (UTC)
- Ah, thanks for posting a solution for them Windows folks. Since you asked why this is useful: Quite a few editors and IDEs (especially on Windows, I'll presume) display an extra blank line if you have a newline at the end. That's probably not correct behavior, but it might have led some shops to have a no-newline-at-EOF,-ever policy. If you come from Unix, you'll probably find that cringeworthy, but hey... -- Jo Liss 23:55, January 25, 2011 (UTC)