2020-02-17

Load Local Vimrc Automatically From Parent Directories

It is common to have different indention settings for different programming projects. For example:

    /path/to/my/project/.vimrc:
    autocmd FileType cpp setl ts=4 sts=4 sw=4 expandtab

Add the following snippet to the end of your Vimrc, so that when opening Vim, it will traverse all parent directories and open any local Vimrc file it finds. To avoid infinite recursion, traversal ends in $HOME.

    let b:dir=resolve(expand('%:p:h'))
    let b:home=resolve($HOME)

    while b:dir != $HOME && b:dir != '/'
        if (filereadable(b:dir.'/.vimrc'))
            execute 'source '.b:dir.'/.vimrc'
        endif
        let b:dir=fnamemodify(b:dir, ':h')
    endwhile

Note that the starting directory is of the first file in your Vim command. Not the current directory, and not all directories of all files given.

I prefer simple solutions over plugins, but for completeness sake I need to mention that localrc.vim and localvimrc do the same, and likely better.