256 Colors in Vim in tmux

Most solutions I’ve found for getting 256 colors in Vim inside tmux have you configure your terminal to report its type as having 256 colors, by setting the type to screen-256color. While this solution works, it means that when you log into servers via ssh that don’t know the screen-256color terminal type, you have to jump through hoops to get things working again. Either by again resetting your terminal type, or by compiling and installing terminfo files.

An ideal solution for the colors problem doesn’t change change your default terminal type but leaves it as something basic and understood by practically all servers (e.g. xterm or screen).

tmux’s own FAQ suggests the -2 flag, but that didn’t work for me.

Here’s the solution I’ve come up with:

In your .vimrc file, tell Vim to use 256 colors:

set t_Co=256

Now, tmux needs to report supporting 256 colors as well. tmux has a configuration option for setting terminal overrides. Basically, all terminals have this string that describe their capabilities, and the terminal-overrides tmux function allows us to selectively change certain capabilities. So, the following line makes tmux report itself as being able to use 256 colors:

set -g terminal-overrides 'xterm:colors=256'

You’ll have to change xterm in there to whatever type your terminal reports itself as (both iTerm and gnome-terminal, the programs I use, report xterm as their default).