Emacs Advent Calendar 20: Diff

Sun 2015-12-20

One some occasions you might want to compare the contents of two files. Emacs can help you with that.

The most general command is M-x diff. It prompts for two file names, runs diff on them and displays the output in a special *diff* buffer (which has bells and whistles provided by Diff mode, see below).

To compare a file with its most recent backup, run M-x diff-backup. The command M-x diff-buffer-with-file compares a buffer's (unsaved) content with the content of the file on disk. This is useful to find out what would be overwritten on a save.

In Dired you can put point on the new file, press = and enter the name of the old file to compare the new file to.

In the output of diff, changes are grouped into sections of so called hunks. Each hunk has a header showing its location in the source files, the affected lines and a bit of context. M-n and M-p move through the hunks, refining the granularity of the diff if possible. This can also be accomplished by hand for the hunk at point with C-c C-b.

To look at a hunk in the corresponding source file, press C-c C-c. To apply a hunk, press C-c C-a. If the hunk has already been applied, it will be reverted. Executing C-u C-c C-a will also revert a hunk.

More information on this can be found in sections 18.0 (Comparing Files) and 19.10 (Diff Mode) of the Emacs Reference Manual.

Tags:

This text by Ludger Sandig is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.