Vim Tips Wiki

Automatically create tmp or backup directories

Redirected from VimTip1393

1,623pages on
this wiki
Add New Page
Add New Page Talk0
Tip 1393 Printable Monobook Previous Next

created November 22, 2006 · complexity intermediate · author Clayton · version 5.7

I needed a way to automate creating the backup/tmp directories. It is especially annoying when I am in a new environment and I have to manually create the directories. I also prefer to use _vim rather then .vim on a Windows system so it checks for that.

function! InitBackupDir()
  if has('win32') || has('win32unix') "windows/cygwin
    let l:separator = '_'
    let l:separator = '.'
  let l:parent = $HOME . '/' . l:separator . 'vim/'
  let l:backup = l:parent . 'backup/'
  let l:tmp = l:parent . 'tmp/'
  if exists('*mkdir')
    if !isdirectory(l:parent)
      call mkdir(l:parent)
    if !isdirectory(l:backup)
      call mkdir(l:backup)
    if !isdirectory(l:tmp)
      call mkdir(l:tmp)
  let l:missing_dir = 0
  if isdirectory(l:tmp)
    execute 'set backupdir=' . escape(l:backup, ' ') . '/,.'
    let l:missing_dir = 1
  if isdirectory(l:backup)
    execute 'set directory=' . escape(l:tmp, ' ') . '/,.'
    let l:missing_dir = 1
  if l:missing_dir
    echo 'Warning: Unable to create backup directories:' l:backup 'and' l:tmp
    echo 'Try: mkdir -p' l:backup
    echo 'and: mkdir -p' l:tmp
    set backupdir=.
    set directory=.
call InitBackupDir()

If you found this tip useful, you may also want to check out VimTip20.


Of course using just one backup/swapfile directory will mean that the following command won't work any more:

vimdiff old/foe.txt new/foe.txt

especialy if you need to merge/change both ways.

That's why in script#1537 I use local directories. But the "set directory=" might be a worthy addition to my script.

Actually, that command does work and it won't clobber the file, in :help 'directory'

For Unix and Win32, if a directory ends in two path separators, the swap file name will be built from the complete path to the file with all path separators substituted to percent '%' signs. This will ensure file name uniqueness in the preserve directory.

Example swap files in ~/.vim/tmp:

%home%user%tmp2%test1.txt.swp %home%user%tmp%test1.txt.swp

Maybe you can clarify if I am misunderstanding what you're saying. In a test I did, even without having the extra slash it will have two different swap files called test.txt.swp and test.txt.swo.

Also on Fandom

Random Wiki