Using tmux is huge win while working in a terminal, help make
it better by adding support for your system clipboard.
The Problem
Although tmux does provide a built-in clipboard, the contents
of this clipboard are not synchronized with the system clipboard. Lucky for us, this problem
can be solved (and in a way that will allow us to share our tmux config across multiple platforms).
The Solution
Thanks to the way tmux is designed we are able to script it via
the shell. If we bind shell commands to the default copy/paste keychords in ~/.tmux.conf we
can take full control of what happens when we copy and paste.
Here is an example of what what you would put in your ~/.tmux.conf :
copy-pipe : runs the command you specify and passes the tmux clipboard buffer via stdin.
run : executes a shell command.
load-buffer : load text into the tmux buffer (will load via stdin when followed by a single ‘-’).
paste-buffer : paste the tmux buffer into the active tmux pane.
By mixing the above example with the if_shell command we can specify different behavior for
individual platforms:
In order to use the clipboard on OS X with tmux you will need to install
reattach-to-user-namespace. (e.g. of installing with homebrew.)
The reattach-to-user-namespace command will be used as a wrapper around the pbcopy
and pbpaste commands.
Linux
On Linux we can use the xclip command to handle clipboard synchronization.
Cygwin
The clipboard on cygwin is available via /dev/clipboard.
Putting It All Together
Place the following in ~/.tmux.clipboard.conf
Next add a new line to ~/.tmux.conf
Running tmux Outside of a Window Manager
Chances are that if you are running tmux without a window manager you won’t want any of the
custom clipboard configuration. Because we split the clipboard config into a separate file
we can use the if-shell tmux command to limit when the .tmux.clipboard.conf file is
sourced.
Bonus Round: Emacs in tmux on OS X
Running Emacs inside of tmux on OS X is pretty straightforward; add the following code to your .emacs config file to allow copy/paste with the system clipboard.