The git repo behind my blog.

specific_vim_config_git.md 1.5KB

Title: Specific Vim config per Git repository Date: 2014-07-15 22:20 Category: ConfigPorn Alias: /2014/specific-vim-config-per-git-repository

I was looking for a way to add custom vim options on a per-repo basis. The standard way I saw for now, was adding some comments to change the Vim config on a per-file basis. There were some alternatives which were working for any project folder (and not only git repos) but they were only working if you start Vim from the root of the project, or they were exploring the tree from local folder up to root (and needed a plugin). None of them were satisfactory.

When I edit a file and need specific Vim configuration, it is usually inside a git repo. So, it is easy to know what is the root folder, and I just wanted to search for a Vimrc file in this folder. No complicated tree searching, working from anywhere inside the repo, no per-file specific configuration.

First of all, the magic command I used to find the git root folder is git rev-parse --show-top-level.

Then, all I had to do is wrap it correctly in my .vimrc:

" Git specific configuration
let git_path = system("git rev-parse --show-toplevel 2>/dev/null")
let git_vimrc = substitute(git_path, '\n', '', '') . "/.vimrc"
if !empty(glob(git_vimrc))
    sandbox exec ":source " . git_vimrc
endif

Note: I use sandbox to prevent arbitrary functions from being executed.

This small code, added at the end of your .vimrc will just look for a .vimrc at the root the git repository and source it if possible. That’s exactly what I wanted :)