From time to time, I contribute to several projects or work on my own or professional projects. This means diverse teams. Which means different coding conventions among other things. This applies to code formatting - such as braces, tabs, tabstops. It's a PITA to switch different coding styles, especially when working on several projects simultaneously. So I went through a solution to make Vim help me with this.
Override Vim Settings in Project Folder
Looong time ago, Vi implemented a feature which allowed us to have specific configuration per folder. You just had to place a
.exrc file in the concerned folder and kick off Vi.
These feature still exists in Vim but is disabled by default. The reason is that using this feature can be dangerous. According to Vim documentation, it's a security leak. You can do pretty much everything within a VIM configuration file, including shell execution and write operations. To avoid those destructive operations,
set secure on your
Now, you can safely
set exrc in
~/.vimrc and start configuring your project in
Override Vim Settings in global Vim configuration
Since projects are almost always in independant project, you can use their paths to let Vim knows what rules to apply for each individual project.
For example, I have an adserver project and more projects aside with the following details:
- The first project resides in
/Users/adrien/code/adserver, and the rules state that tabs remains tabs in all files and they should be treated as being equal with 4 spaces.
- All other projects reside in
/Users/adrien/codeand have the rules that tabs should be replaced with 2 spaces in all files.
function! SetupEnvironment() let l:path = expand('%:p') if l:path =~ '/Users/adrien/code/adserver' setlocal noexpandtab tabstop=4 shiftwidth=4 elseif l:path =~ '/Users/adrien/code' setlocal tabstop=2 shiftwidth=2 expandtab endif endfunction autocmd! BufReadPost,BufNewFile * call SetupEnvironment()