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.

1

1 Answer 1

59

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)
1
  • 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.) Commented Nov 2, 2020 at 4:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.