Undo recovery from swap file in vim

The following works for me to recover the file, with undo history as well:

  1. Assume you have my_file, that has some persistent undo history + unsaved changes in .my_file.swp
  2. Open file with vim, and press r to get the recovery version
  3. Save recovery version to temporary location e.g. :w /tmp/%
  4. Close without saving (:q!). Open file again, and press d to delete swap file
  5. Optional: compare /tmp/my_file and my_file to make sure you want the recovered version
  6. Manually add changes from /tmp/my_file (e.g. ggdG and :r /tmp/% )

This can probably be simplified, but this works for me.

PS: This does not give you the undo history for the changes between the on-disk and recovered version of the file, that appears as one big edit in the history.


I just tried this myself (with persistent undo enabled; Vim version 7.3.823). The old changes were still showing (in :undolist, though I usually use a plugin like Gundo or Undotree to visualize it), but when attempting to restore, I get

E438: u_undo: line numbers wrong

Seems like Vim cannot handle this situation. Note that you've been warned; the recovery explictly warns:

Recovery completed. You should check if everything is OK.
E308: Warning: Original file may have been changed

After accidentally recovering the file you can simply type :q! to exit vim without saving the recovered changes - this will leave your original file intact and the swap file where it is.

The next time you open the file, you'll see the same prompt - press D to delete the swap file, or abort and find it manually (and possibly delete any other swap files in the same location)

Tags:

Vim