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`
    endif
endfunction

" 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.

Michael is a polyglot software engineer, committed to reducing complexity in systems and making them more predictable. Working with a variety of languages and tools, he shares his technical expertise to audiences all around the world at user groups and conferences. You can follow @mheap on Twitter

Thoughts on this post

Leave a comment?

Leave a Reply