Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recover a vim file from the .un~ file without the undo command

Tags:

vim

How can I restore a vim file from the undo file without hitting undo?

I had a vim file that I saved while adding text. Then I ran a python command that emptied the file's contents, and I can see some of the words the file contained in the file's .un~ file. When I try to undo in the file, it says Already at latest change. I can't find the swap file in my swap files directory.

like image 469
Rose Perrone Avatar asked Sep 05 '13 08:09

Rose Perrone


3 Answers

As the other answers have noted, you can't recover the whole file from vim's undo files, simply because vim seems to only keep diffs in the undo files, not the whole contents. (That makes a lot of sense, as it's space efficient.)

One thing you can try though, is to extract what's possible from your undo file:

$ strings <undo-file>

The output will not be pretty, but you could end up finding something that's valuable to you.

like image 171
aude Avatar answered Nov 01 '22 18:11

aude


You can't. The undo information is linked to Vim's last knowledge of the file's contents; when they don't correspond any more, Vim cannot re-apply the changes. This is documented at :help undo-persistence:

Vim will detect if an undo file is no longer synchronized with the file it was written for (with a hash of the file contents) and ignore it when the file was changed after the undo file was written, to prevent corruption.

Best you can do is try to manually salvage recognizable bits in the undo file, e.g. with a hex editor, or Vim's binary mode.

like image 28
Ingo Karkat Avatar answered Nov 01 '22 19:11

Ingo Karkat


It is not exactly possible, as the undo file only contains the text that was changed in a single change. If you at some point reloaded the file, the undofile should contain the complete buffer for that and starting from there one could theorectically recover the file (by going through the undo states).

I have written about this before at the vim_use mailinglist here and here (which even contains a patch, that let's you force reading in the undo-file)

You could try to patch vim and see if you can recover at least some data.

like image 7
Christian Brabandt Avatar answered Nov 01 '22 19:11

Christian Brabandt