Can I see changes before I save my file in Vim?
:w !diff % -
Because some people asked about an explanation for the command
:w !diff % -
Here is my attempt on writing a more detailed answer:
I am assuming that you are working on a system with cat
and echo
installed (e.g. almost any GNU/Linux, Mac OS, BSD and other UNIX-like systems).
The above command works as follows:
The syntax for saving a file in vim is:
:w <filename>
The syntax for executing a shell command in vim is:
:!<command>
Inside the shell environment issued by vim
%
happens to point to the current filename. You can verify this by executing the following::!echo %
This should output the filename (or an error, if vim was run without a filename).
Using cat we can also output the content of the file:
:!cat %
This should return the files content in its last saved state or an error if it has never been saved.
The program diff is able to read from standard input (stdin). Its man page states the following:
[...] If a FILE is '-', read standard input. [...]
Executing the save command without a filename but rather a shell command behind it causes vim to write the files content to stdin of the shell instead of saving it in a physical file. You can verify this by executing
:w !cat
This should always print the files current content (which would have been written to a file instead).
Putting it together (or tl;dr): The file is "saved" to stdin, diff is run with the filename and stdin as input.
Knowing this one could also compare files with vimdiff doing something like this - this is just an idea you do not want to do this:
:w !cat > /tmp/tempFile && vimdiff /tmp/tempFile % && rm /tmp/tempFile
(Then open readonly and close vimdiff using :qall
)