Why I don’t see the difference between two different files in insert mode in vim

newlinesvim

Let's create two files:

$ echo -n 'test' > test.txt
$ wc test.txt 
0 1 4 test.txt

The file test.txt doesn't contain the trailing newline.

$ echo 'test' > test_n.txt
$ wc test_n.txt 
1 1 5 test_n.txt

The file test_n.txt contains the trailing newline.

The above two files are obviously different, but the preview of both files in vim in insert mode does not contain any differences:

$ vim test.txt

enter image description here

$ vim test_n.txt

enter image description here

Why is there no difference (new line or some special distinction)?

And what can I do to add or remove such an additional character in vim in insert mode?

Best Answer

vim has a mode "eol" (for end-of-line) to tell what to if the last line in the file lacks a newline character. You can see all of the mode settings in vim (or any program like vi) by

:set all

POSIX vi does not have a feature for this: files are either zero-length, or have a trailing newline. That's because POSIX vi only deals with text files, which by definition are lines that end with newlines. In a quick check, nvi and elvis do not have modes for this. In my comment, I had forgotten a detail of vim: unlike vile, a ":set list" does not readily show the missing newline. Here's what I see in vim:

ssss$
test$
~
~

while in vile:

ssss^J
test
~
~

For either editor, you can read the file in, change the mode, e.g.,

:set noeol

and write the file out, to get a newline on the updated file. Rather than showing it directly, you can modify the status line of vim to show this information. By default, it does not appear to do this, but some packagers have customized this, e.g.,

"foo" [noeol] 2L, 9C                                          1,1           All

One of the comments suggests using the "?" modifier of the set command, e.g.,

:set eol?

which might show something like this:

noendofline                                                   2,1           All

but in insert-mode, that is replaced by

-- INSERT --                                                  2,1           All

so the status line seems the right place to maintain this information.

The features have been there a while:

  • The eol feature first appeared in vim 2.4 (July 1994), according to a comment in its source code.

  • vile's newline mode appeared in July 1993.

(nvi, elvis, vim and vile all handle binary files in addition to the POSIX vi's text files).

Related Question