Using the system clipboard in tmux, Emacs and Vim

One "unconventional" default behaviour of tmux, Emacs and Vim is that they maintain their own internal clipboards, which can make it awkward to copy/paste between programs. I prefer to use the system clipboard by default, which can be achieved with minimal changes.

1. tmux

Tmux requires the most setup. The below example can be used in tmux.conf to support both macOS and Linux:

bind-key -T copy-mode-vi 'y' send -X copy-pipe \
  "if command -v reattach-to-user-namespace >/dev/null; \
   then reattach-to-user-namespace pbcopy; \
   elif command -v xclip >/dev/null; \
   then xclip -selection clipboard; fi"
  • The copy-pipe command was added in tmux 1.8. It sends the selected text to stdin for a given command, which can be an appropriate system clipboard tool.
  • On macOS, pbcopy and pbpaste can be used to interact with the system clipboard. To use these with tmux, you have to use reattach-to-user-namespace.
  • GNU/Linux systems can install various X clipboard tools. xclip is a common choice.

2. Emacs

The ELPA package xclip provides cross-platform integration with the GUI clipboard for terminal Emacs. Despite using the xclip name, it supports multiple clipboard programs. You just have to initialise it in init.el. I've had this running for years without issue:

(require 'xclip)
(xclip-mode 1)

3. Vim

Vim must have been compiled with +clipboard and +X11, which can be checked using vim --version. On Arch this means installing the gvim package rather than vim.

  • You can either use set clipboard=unnamed, which will use the primary X selection,
  • or set clipboard=unnamedplus, which will use the clipboard X selection. My experience on Arch is that most programs use the clipboard selection, so I use unnamedplus.