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

南笙酒味 提交于 2019-12-21 07:30:34

问题


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.


回答1:


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.




回答2:


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.




回答3:


As the other answers have noted, you can't recover the whole file from vim's undo files, simply because vim seems to keep edit differences only 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.




回答4:


A reminder that if you have set in your .vimrc file

set backupdir=$HOME/tmp

You may have temp copies of the files that are readable and that can be renamed



来源:https://stackoverflow.com/questions/18630937/recover-a-vim-file-from-the-un-file-without-the-undo-command

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!