50

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.

50

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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