Last week, I’ve discovered by accident, that Vim exposes environment variables to all scripts it executes (including your .vimrc ). Knowing that, opens up entirely new possibilities for plugins and smarter .vimrc s.

Let’s say you start your Vim from the command-line and set the env variable FOO=bar :

$ FOO=bar vim

In your .vimrc you can get the value of FOO with $FOO ( $ prefix, similar to shell scripts). For instance, to print the value of FOO when you start Vim, you could add the following line to your .vimrc :

echo $FOO

Even better, you can use if ... else ... endif statements to do different things depending on FOO ’s value. Observe:

if $FOO == 'bar' " Vimscript to execute when the value of " the env variable FOO equals 'bar'. else " Vimscript to execute otherwise. endif

Practical Example

I use iTerm on my Mac with two profiles: Solarized Light and Dark. And, for various reasons, I’m frequently switching between these two profiles. However, in the past, whenever I switched the profile, I also had to update my .vimrc to match the current iTerm profile (i.e. set background=dark or set background=light ). Now, thanks to env variables in Vimscript, I can automate this.

As it turns out, when you create a new tab (or window) in iTerm it sets an env variable called ITERM_PROFILE for you. Its value is simply the name of the profile the new tab was created with. That being so, you can do something like the following in your .vimrc :

colorscheme solarized " If the current iTerm tab has been " created using the **dark** profile: if $ITERM_PROFILE == 'Solarized Dark' set background=dark endif " If the current iTerm tab has been " created using the **light** profile: if $ITERM_PROFILE == 'Solarized Light' set background=light endif