Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undo recovery from swap file in vim

Tags:

vim

Right before committing a major change, I accidentally "recovered" the file from an old and outdated swap file in vim. My changes seem to be gone. I've tried exploring the undo tree but large chunks of changes are still missing. Is there anyway I can undo the recover operation or am I doomed?

like image 962
Zach Conn Avatar asked Jan 27 '14 16:01

Zach Conn


People also ask

Where are Vim swap files saved?

While editing a file, you can see which swap file is being used by entering :sw . The location of this file is set with directory option. The default value is .,~/tmp,/var/tmp,/tmp . This means Vim will try to save this file in the order of . , and then ~/tmp , and then /var/tmp , and finally /tmp .

How do I exit swap file?

Press Q to "(Q)uit" the vim swap file recovery for now, then use the " kill " command with the process ID to end your previous vim session, e.g. to "really" kill the vim session.

What is SWP file in Vim?

An SWP file is a swap file created by the Vi text editor or one of its variants, such as Vim (Vi iMproved) and gVim. It stores the recovery version of a file being edited in the program. SWP files also serve as lock files, so no other Vi editing session can concurrently write to the currently-open file.


2 Answers

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.

like image 146
related Avatar answered Oct 26 '22 00:10

related


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)

like image 23
stlasalle Avatar answered Oct 25 '22 22:10

stlasalle