Using vimdiff to compare two files
We can call
vimdiff from the command line giving it two or more filenames. vimdiff launches Vim, creates a window for each specified file, and highlights the differences between them.
In the video demonstration, one of the files that I wanted to compare was on my local filesystem, while the other file was in a textarea on a webpage. Before I could use
vimdiff, I had to copy the text from that textarea into a local file. I did so using my system clipboard, then running the command:
pbpaste > 45-shownotes-latest.md
pbpaste command is specific to os x, but similar commands are available on other systems.
We can now compare the two drafts by running:
vimdiff 45-shownotes-draft.md 45-shownotes-latest.md
I’m not keen on this workflow for a couple of reasons. I have no further use for the temporary file, so I’d have to clean up afterwards by removing it. Also, I usually have an instance of Vim open already, and I’d prefer a workflow that didn’t require me to open a fresh instance of Vim.
:diffthis to compare two buffers
:diffthis command allows us to compare two (or more) buffers that are open in an existing Vim session. If we have two split windows containing buffers that we want to compare, then we can diff them by running:
We can turn diff mode off just as easily, by running:
The nice thing about this technique is that we can use an unnamed buffer. There’s no need to write the text to a temporary file. In the video demonstration, the buffer on the left corresponds to a file on my local filesystem, while the buffer on the right has no associated file. This technique would work just as well if neither buffer had been saved to disk, which makes it pretty flexible.
Getting around in diff mode
In diff mode, Vim provides two handy motions for getting around:
]c jump back and forward between changes. If you want to resolve the differences between files, you can do so using the
:diffput commands. Check out episodes 32 and 33 for a detailed demonstration of how to use these commands.