X11 forwarding over remote SSH tmux

I’m starting to do all my development remotely on a development server that I’m hosting at home over a VPN.

This means that all my devices are basically thin-clients.

Pre-requisite

Make sure that you’ve already allowed X11 forwarding over your remote user account.

If not, do this (in your remote server logged in as your remote user account)

# in ~/.ssh/config (create if its not there)
# add the following
ForwardX11 yes

One of the problems I had encountered was attempting to do X11 forwarding over TMUX.

As Tmux and most screen multiplexers have an issue with setting the $DISPLAY environment that is required to do X11 forwarding, this had initially prevented me from using the full extent of my workflow like running a ‘gitk’ command.

To solve this, I just have to ensure that my bash knows how to set the $DISPLAY environment variable properly.

# in your ~/.bashrc, add the following

# -- Improved X11 forwarding through GNU Screen (or tmux).
# If not in screen or tmux, update the DISPLAY cache.
# If we are, update the value of DISPLAY to be that in the cache.
function update-x11-forwarding
{
    if [ -z "$STY" -a -z "$TMUX" ]; then
        echo $DISPLAY > ~/.display.txt
    else
        export DISPLAY=`cat ~/.display.txt`
    fi
}

# This is run before every command.
preexec() {
    # Don't cause a preexec for PROMPT_COMMAND.
    # Beware!  This fails if PROMPT_COMMAND is a string containing more than one command.
    [ "$BASH_COMMAND" = "$PROMPT_COMMAND" ] && return 

    update-x11-forwarding

    # Debugging.
    #echo DISPLAY = $DISPLAY, display.txt = `cat ~/.display.txt`, STY = $STY, TMUX = $TMUX  
}
trap 'preexec' DEBUG

Then, in your home directory, do the following outside of your tmux session (if you’re remotely attached to it)

> touch ~/.display.txt

And you’re done!

Reference: X11 Forwarding and Terminal Multiplexers