George Kastrinis
George Kastrinis

Reputation: 5172

Load functions/mappings etc in vim only when working in a specific repo

I want to know if it's possible to setup vim in a way that when I am working in a certain repo, it will load additional functions/mappings etc.

Like ftplugin with file types, but the type is not defined by the file itself but by its location (or by the result of a command, e.g. hg path default).

Upvotes: 0

Views: 205

Answers (2)

Ingo Karkat
Ingo Karkat

Reputation: 172510

Central configuration

If it's okay to configure the specific commands / local exceptions centrally, you can put such autocmds into your ~/.vimrc:

:autocmd BufRead,BufNewFile /path/to/dir/* setlocal ts=4 sw=4

It is important to use :setlocal instead of :set, and likewise :map <buffer> ... and :command! -buffer ....

On the other hand, if you want the specific configuration stored with the project (and don't want to embed this in all files via modelines), you have the following two options:

Local config with built-in functionality

If you always start Vim from the project root directory, the built-in

:set exrc

enables the reading of a .vimrc file from the current directory. You can place the :set ts=4 sw=4 commands in there.

Local config through plugin

Otherwise, you need the help of a plugin; there are several on vim.org; I can recommend the localrc plugin, which even allows local filetype-specific configuration.

Note that reading configuration from the file system has security implications; you may want to :set secure.

Upvotes: 2

Kent
Kent

Reputation: 195029

This may work for your need, but it is just an example.

augroup repo
    autocmd!
    autocmd BufReadPost * call RepoMappings()
augroup END

function! RepoMappings()
    let repo = '^/tmp/test/'
    if expand('%:p') =~# repo
        nnoremap <buffer> <f7> :echo 'yohoo'<cr>
    endif
endfunction

You change the let repo = '^/tmp/test/', which would be the prefix of your repo path. In the above example, only for files in your "repo", the <f7> mapping works.

You can extend the repo variable to a list, or for different repo call different functions...

One thing is not handled, if you open a new buffer, without filename, you may want to check the pwd to see if it is in the "repo". But you got the idea, you can impl. it on your own if it was required.

Just give it a try.

Upvotes: 2

Related Questions