VIM - set background={light,dark} automatically based on terminal settings

It can not be done by VIM alone - but with a few hacks, it can be done.

Problem

You are using VIM v7 on a group of servers and you have a collegue which does the same. For some strange reason you have chosen to have a black background color on your monitor or you might be using the hardware terminal attached to the server which has a black background as it always has. Your collegue uses white background on his GUI terminal. And both of you want this fancy syntax highlight enabled but with different colors.

We want VIM on the server we are ssh'ing to and sudo'ing, to read/detect our terminal background color and set it all up right. VIM can not do that. We have to make a hack.

The program 'konsole' in KDE automatically sets COLORFGBG for you.

Solution

This last command above is really what we try to do, but the only thing we can test is if exists("$BACKGROUND") and that we have to set ourself. This is troublesome to get through ssh...

Copy & paste

Change the user name and server name below....

From the command line on your local pc it is done like this, if you are using bash:

# Only users of Gnome.term: echo 'export COLORFGBG=0;15' >> ~/.bashrc
echo -e 'Host *\n\tSendEnv COLORFGBG' >> ~/.ssh/config

Server

echo -e "Defaults\tenv_keep=\"VISUAL EMAIL COLORFGBG\"" >> /etc/sudoers
echo "AcceptEnv COLORFGBG" >> /etc/ssh/sshd_config'
/etc/init.d/ssh restart

Test

Start a new terminal window and test that your environment has been set:

joe@localhost:~$ echo $COLORFGBG
15;0

Ssh to your server and test that the environment variable has been transferred by the client and accepted by the server:

joe@localhost:~$ ssh example.com
joe@example.com:~$ echo $COLORFGBG
15;0

Test if the environment got read by VIM, start VIM and type :set background:

joe@example.com:~$ vim foo.bar
:set background
   background=dark

Alternative

If the hack above does not work, then convince your collegue to use dark background. After all, black is the default background color for terminals and he is doing it wrong!!! All that GUI is 'so last year' ;-)


Powered by: Linux, Apache, Kim Hansen & Hans Schou

ISO/IEC 15445