Short answer:
Use the mkdir()
function to create those subdirectories and then set undodir
, backupdir
and directory
to tell vim to use them. This snippet of code should work just fine:
function! Mkdir(path)
if !isdirectory(resolve(a:path))
try
call mkdir(a:path, "p", 0775)
catch
return ''
endtry
endif
return a:path
endfunction
" Find the nearest .git directory
let s:repo_root = ''
let s:cwd = getcwd()
while getcwd() != '/'
if isdirectory('.git')
let s:repo_root = getcwd()
break
endif
cd ..
endwhile
exec 'cd '.s:cwd
" If we found a .git/ directory somewhere, create directories there
if s:repo_root != ''
set undofile
set backup
set swapfile
let s:dirpath = s:repo_root."/.vimfiles"
let &undodir = Mkdir(s:dirpath."/undo")
let &backupdir = Mkdir(s:dirpath."/backup")
let &directory = Mkdir(s:dirpath."/swp")
endif
Long answer
It's probably not a good idea to sync those files with git. Keep in mind that they will be constantly changing, and that will add a lot of clutter to your commits. Also there is no point in syncing .swp
files, since the whole point of having .swp
files is to avoid having two instances of the editor working on the same file at once. If you are syncing between different machines, these files stop making any sense.
I would suggest you don't put those files under your projects directory, but rather save them in subdirectories inside ~/.vim
. In that case you only have to slightly modify the snippet above to remove the .git/
discovery part, and to replace s:dir_path
with ~/.vim/
vim
to that. Or perhaps use autocommands (not sure off the top of my head if an event comes early enough to create swap dirs before vim complains).