Vim Tips Wiki

Automatically create tmp or backup directories

1,613pages on
this wiki
Revision as of 09:40, April 25, 2008 by JohnBot (Talk | contribs)

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 separator = "_"
    let separator = "."
  let parent = $HOME .'/' . separator . 'vim/'
  let backup = parent . 'backup/'
  let tmp = parent . 'tmp/'
  if exists("*mkdir")
    if !isdirectory(parent)
      call mkdir(parent)
    if !isdirectory(backup)
      call mkdir(backup)
    if !isdirectory(tmp)
      call mkdir(tmp)
  let missing_dir = 0
  if isdirectory(tmp)
    execute 'set backupdir=' . escape(backup, " ") . "/,."
    let missing_dir = 1
  if isdirectory(backup)
    execute 'set directory=' . escape(tmp, " ") . "/,."
    let missing_dir = 1
  if missing_dir
    echo "Warning: Unable to create backup directories: " . backup ." and " . tmp
    echo "Try: mkdir -p " . backup
    echo "and: mkdir -p " . 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.

Around Wikia's network

Random Wiki