Using $environment variables for configuring Vim

I didn’t manage to convince people in my team to use tabs instead of spaces, but I didn’t want to change to another editor in order to have a different profile for that, and didn’t want to be activating the “use spaces” setting each time I need to work on Mozilla code. I still wanted to use Vim and my config, so how could I have my cake and eat it too, so to speak?

Well, I thought, since I use a different computer for Mozilla stuff, the solution is easy: define a certain environment variable in my .bashrc file, and if .vimrc finds that variable, changes my profile to use spaces. Else it’s tabs and business as normal. This is how I did it:

First, I defined and exported the $MOZILLAENV variable in .bashrc:

$MOZILLAENV = 1
export $MOZILLAENV

It’s important that you also export the variable, otherwise it will be available to bash, and

echo $MOZILLAENV

will return ‘1’ as expected, but it won’t be made available to programs launched from bash, and you’ll get mad (you don’t want to get mad).

Secondly, this is how you I read the $MOZILLAENV environment variable in .vimrc:

let mozillaenv=$MOZILLAENV

if mozillaenv == '1'
call UseMozillaStyle()
endif

(maybe it could be simplified but I’m a Vim newbie so it’s OK)

UseMozillaStyle is a function that sets Vim to use spaces and expand to spaces when pressing Tab. It also sets the tab width to 4 spaces. I can accept/understand using spaces instead of tabs, but using 2 spaces is just unreadable–there’s not enough indenting for me to say ah yes that’s an indent! (and that’s one of my main gripes with the Closure style guide, by the way!)

function! UseMozillaStyle()
    set tabstop=4
    set softtabstop=4
    set shiftwidth=4
    set expandtab
endfunction

And now I can still keep using my git-versioned Vim config in all my computers, and not worry about introducing tabs where I shouldn’t! Setting up my work environment in a new computer just involves downloading and installing git and Vim, cloning my repository and running the init script for getting plugins installed. That’s like, 15 minutes? Isn’t it great!? 🙂

2 Replies to “Using $environment variables for configuring Vim”

    1. I think that considering *everything else*, them using spaces is like a VERY MICROSCOPICALLY MINOR drawback!! 😀

Comments are closed.