Why would Vim add a new line at the end of a file?

All the answers I’ve seen here address the question “how could I prevent Vim from adding a newline character at the end of the file?“, while the question was “Why would Vim add a new line at the end of a file?“. My browser’s search engine brought me here, and I didn’t find the answer to that question.

It is related with how the POSIX standard defines a line (see Why should files end with a newline?). So, basically, a line is:

3.206 Line
A sequence of zero or more non- <newline> characters plus a terminating <newline> character.

And, therefore, they all need to end with a newline character. That’s why Vim always adds a newline by default (because, according to POSIX, it should always be there).

It is not the only editor doing that. Gedit, the default text editor in GNOME, does the same exact thing.


Edit

Many other tools also expect that newline character. See for example:

Also, you may be interested in: Vim show newline at the end of file.

Leave a Comment