58

Sometimes it happens: emacs prompts you about recovering unsaved changes to a file, but you cannot remember if you want those changes or not.

Starting at the recover-this-file buffer, is there a way to view a diff or otherwise directly see the changes?

For example, something like what magit-mode gives when tabbing on a edited file in the status buffer.

daveloyall
  • 1,300
  • 9
  • 21
Sparx
  • 1,121
  • 10
  • 20

1 Answers1

58

After running recover-this-file and accepting the autosave version, you'll have a modified buffer containing the autosave contents. At this point you can use M-x diff-buffer-with-file RET to see the differences between the modified buffer and the saved file.

The key I've bound for this actually runs a custom function, in order to produce a unified diff, and to skip the prompt for the buffer (it assumes the current buffer).

(defun my-diff-buffer-with-file ()
  "Compare the current modified buffer with the saved version."
  (interactive)
  (let ((diff-switches "-u")) ;; unified diff
    (diff-buffer-with-file (current-buffer))))

There's also an ediff equivalent (which I generally prefer, although I do use both) which is available at M-x ediff-current-file RET

If you wish to reject the modifications after checking the diff, you should be able to simply undo the recovery. (Failing that you can always use revert-buffer or find-alternate-file.)

As keybindings for diff commands often involve =, I find the following convenient (n.b. I've unbound the default C-z binding, and moved it instead to C-z C-z, which opens up C-z as a prefix for custom bindings):

(global-set-key (kbd "C-z =") 'my-diff-buffer-with-file)
(global-set-key (kbd "C-z C-=") 'ediff-current-file)
phils
  • 50,977
  • 3
  • 79
  • 122
  • 1
    You mention ediff-current-file, and I find almost does this, and has several add'l features (figures out the auto-save file name, . It's a builtin defined in ediff.el. C-h f ediff-current-file ... for info. Really should be an add'l command available from the recover-this-file buffer. If I get one working better, I'll post. (It - M-x ediff-current-file n - sometimes worked when testing (it kinda works when the current buffer has changes) but does not work in the situation we're talking about.) – user1521620 Nov 02 '20 at 04:10