Restore Vim Backups

那年仲夏 提交于 2019-12-05 01:07:59

From what I can tell, Vim doesn't save any information at all regarding the file's original location.

Saving a backup of two same-name files could either overwrite the existing backup or use a different name, depending on what's set in your .vimrc. The option 'backup' will overwrite an existing backup file, but 'writebackup' will re-name a new backup in order to avoid an overwrite.

Check out Vim's documentation for more info - :help backup

docwhat

To answer the question about restoring, Vim doesn't know anything about the backups. It's backup system is very simple -- write a file. To restore, you have to do it manually.

However, you can add more info to your backups to make it easier to restore.

Ideally, the backupdir would honor trailing // to force it to expand the path of the file and replace / with %. e.g. /tmp/foo.rb would become the backup file `tmp%foo.rb'.

See :help undodir and :help directory for the undo and *.swp directory settings which do take //.

But we can fake this!

" Prevent backups from overwriting each other. The naming is weird,
" since I'm using the 'backupext' variable to append the path.
" So the file '/home/docwhat/.vimrc' becomes '.vimrc%home%docwhat~'
au BufWritePre * let &backupext ='@'.substitute(substitute(substitute(expand('%:p:h'), '/', '%', 'g'), '\', '%', 'g'),  ':', '', 'g').'~'

The backup files read filename-then-directory but it does work and should be sufficiently unique.

Example: .vimrc%home%docwhat~ is as backup of /home/docwhat/.vimrc

If you wanted minute by minute backups, so you loose less work, you can append a timestamp to the file name:

au BufWritePre * let &backupext = substitute(expand('%:p:h'), '/', '%', 'g') . '%' . strftime('%FT%T') .  '~'

But I'd recommend you setup a cron job to clean this directory regularly. If you edit as many files of me, this file would become huge quickly.

Alternatively, you could do something clever and change the backupdir before writing (with the BufWritePre hook), but that level of cleverness with vim is beyond me (at the moment).

Ciao!

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