Automatic session restore in git directories
Talk0
1,599pages on
this wiki
this wiki
Revision as of 22:18, February 5, 2013 by 131.181.251.21 (Talk)
Daily I need to switch between different git projects. This script automatically saves vim sessions per git directory.
Usage
Edit
- Starting vim with no filename argument in a git directory will load a previously stored session if one exists.
- Exiting vim (with no filename argument given at invocation) in a git directory will store the current session.
- Starting vim with a filename argument doesn't restore nor save a session.
Caveats
Edit
-
$HOME/.vim/sessionsmust exist.
Script
Edit
function! FindProjectName()
let s:name = getcwd()
if !isdirectory(".git")
let s:name = substitute(finddir(".git", ".;"), "/.git", "", "")
end
if s:name != ""
let s:name = matchstr(s:name, ".*", strridx(s:name, "/") + 1)
end
return s:name
endfunction
" Sessions only restored if we start vim without args.
function! RestoreSession(name)
if a:name != ""
if filereadable($HOME . "/.vim/sessions/" . a:name)
execute 'source ' . $HOME . "/.vim/sessions/" . a:name
end
end
endfunction
" Sessions only saved if we start vim without args.
function! SaveSession(name)
if a:name != ""
execute 'mksession! ' . $HOME . '/.vim/sessions/' . a:name
end
endfunction
"
" Restore and save sessions.
"
if argc() == 0
autocmd VimEnter * call RestoreSession(FindProjectName())
autocmd VimLeave * call SaveSession(FindProjectName())
end