5

By default, Vim appends a tilde ~ to backup files. I know there's a configuration option to customize the backup file extension: If you set backupext=.bak in your .vimrc file, your backup files will have .bak appended to them instead of a tilde.

I'm wondering what's the best way to have Vim automatically prepend characters to the backup file name. Specifically, I'd like Vim to prepend a period . while continuing to append a tilde ~.

(If you're wondering why, I use KDE and don't like Dolphin to display backup files - see http://forum.kde.org/viewtopic.php?f=17&t=82350).

I also looked at this thread, but I don't want to create a custom backups directory, I just want to prepend a character to the backup file name.

Community
  • 1
  • 1

2 Answers2

3

One potential solution is to

mkdir ~/.vim/backup

and then add

set backupdir=~/.vim/backup

in your ~/.vimrc so that you don't have to look at them.

However if you want to keep them in the same directory you could rename them when you write them like this:

au BufWritePost * exe "silent !mv ".expand("%:p").&bex." ".expand("%:p:h")."/.".expand("%:t").&bex
Conner
  • 30,144
  • 8
  • 52
  • 73
  • For me, the problem with that is the high likelihood that backups would be overwritten. For example, if I edited multiple README.txt files in various places on my machine, all backups except that last would be overwritten. – user1615153 Aug 21 '12 at 20:42
  • @user1615153 Added alternative. – Conner Aug 21 '12 at 21:11
  • That does the trick. Thanks a lot! Now I have to press twice to confirm renaming the backup file but I can live with that. – user1615153 Aug 21 '12 at 21:44
  • Even better! Just decided to move to Vim from jEdit. Don't think I'll regret it. I'll have to learn more about Vim autocommands. – user1615153 Aug 21 '12 at 22:07
  • @user1615153 That's unfortunate. This is probably one of the most complex cases/autocommands I've ever written. – Conner Aug 21 '12 at 22:30
0

You could use vim's backupdir option to write your backups to specific directory (or even a specific directory in your working directory, see http://vim.wikia.com/wiki/Remove_swap_and_backup_files_from_your_working_directory) The other option is to drop vim's own backup file feature and to replace it yourself. I'm less familiar with Vimscript than I'd wish, but this is as far as I got:

:au BufWritePre * exe 'write! ' expand("%:h") . "." . expand("%:t")

If you want to use backupdir but avoid overwriting files, use something like

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

(stolen from https://stackoverflow.com/a/9528517/49047)

Community
  • 1
  • 1
edef
  • 743
  • 4
  • 13