Search code examples
vim

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


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.


Solution

  • 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.