Set parent .git directory to current path in vim

Update: Turns out ctrl+p already does this! See the github repo for details. I’ll leave this here for reference anyway

I’ve been playing around with vimscript this afternoon, trying to work out what it can do. One of my main issues when I’ve previously tried to use vim is that ctrl+t/ctrl+p/molly/anything else would always have the wrong base directory for searching. To work around this, I decided to see if I could programatically change the working directory to the root of my git dir. This is what I’ve come up with - it’s probably not the best way to do it, but it works for me.

function! SetGitDir()
    " Change working dir to the current file
    cd %:p:h
    " Set 'gitdir' to be the folder containing .git
    let gitdir=system("git rev-parse --show-toplevel")
    " See if the command output starts with 'fatal' (if it does, not in a git repo)
    let isnotgitdir=matchstr(gitdir, '^fatal:.*')
    " If it empty, there was no error. Let's cd
    if empty(isnotgitdir)
        cd `=gitdir`

" Remap to <leader>g for easy use
nnoremap <silent> <leader>g :call SetGitDir()<CR>

If you can improve it, let me know. Like I said, it works, but half an hour ago I didn’t know any vimscript at all so it can most definitely be improved.

October 30, 2012

How To