I accidentally pressed "k" (a magit command) and discarded some unstaged changes. Is there a way to undo this? Or did I discover one of the few ways to actually lose work while using git?

  • Have you tried using undo in the affected buffers? (Assuming you had them open.) – phils Oct 2 '18 at 0:39
  • Note that if the changes were never staged then you weren't "using git" so to speak -- git never knew about those changes. – phils Oct 2 '18 at 0:41
  • @phils great suggestion. I didn't think of this during my panic, unfortunately. – truthling Oct 2 '18 at 20:44
  • @phils git knew about them, but only in a general sense, i.e. git knew there were unstaged changes to files it was tracking. And it was a git command that discarded those changes. But your point is well taken. – truthling Oct 2 '18 at 20:47
  • Right, although it's more that git will figure out on demand if there are unstaged changes (and then, I believe, immediately forget again). Unless it's told to store the changeset in some way, it won't remember it. – phils Oct 2 '18 at 22:25

As mention in the comments, if, at the time you discard a change, a buffer is visiting the file that is modified by the discard, then you can simply go to that buffer and undo the change.

The comments also mention that Magit could create a commit whenever it performs an action that destroys data that could otherwise not be recovered. Turns out Magit has been doing that for years, but only if told to do so.

This is implemented using several minor-modes that can be enabled individually. To enable them all use this.

(use-package magit-wip
  :after magit

You should also add this line at the top-level (not inside use-package):

(add-hook 'before-save-hook 'magit-wip-commit-initial-backup)

Some other related settings:

(use-package magit
  (setq magit-wip-merge-branch t)
  (magit-define-popup-action 'magit-log-popup
    ?i "Index wipref" 'magit-wip-log-index)
  (magit-define-popup-action 'magit-log-popup
    ?w "Worktree wipref" 'magit-wip-log-worktree))

Most of this is documented in the manual. Also see the doc-string of magit-wip-merge-branch.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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