Vim style copy paste in Tmux

Tmux is a terminal multiplexer which allows us to create and manage multiple terminal windows. In this post we will configure tmux to have vim style copy and paste.

By Subash Adhikari · · 1 min read

Updated . Written in 2017. Commands, prices, and links in this piece may be out of date.

Share on X


Close-up of a laptop keyboard with code on the screen

Tmux is a terminal multiplexer that lets you create and manage multiple terminal windows. In this post we'll set up tmux to copy and paste the way Vim does.

The tmux configuration file lives at ~/.tmux.conf. Add the following to it.

bash
set-window-option -g mode-keys vi
bind-key -T copy-mode-vi 'v' send-keys -X begin-selection
bind-key -T copy-mode-vi 'y' send-keys -X copy-selection-and-cancel
bind-key p paste-buffer

To reload the config, run tmux source-file ~/.tmux.conf in your terminal. That applies the updated configuration.

Once it's applied, press Ctrl+a v to enter visual mode in tmux and make a selection. Use Ctrl+a y to copy the selection and Ctrl+a p to paste it.

This config works on most operating systems, but it needs a small tweak to work on OS X. There's a bug in OS X that stops tmux from sending copied output to the clipboard. It was fixed in El Capitan but came back again in Sierra. A small utility called reattach-to-user-namespace fixes it.

Install it with brew install reattach-to-user-namespace, then add the following to ~/.tmux.conf.

bash
set -g default-command "reattach-to-user-namespace -l ${SHELL}"
bash
bind-key -T copy-mode-vi 'y' send-keys -X copy-pipe-and-cancel 'reattach-to-user-namespace pbcopy'

This pipes whatever you yank in tmux to the pbcopy command, which copies it to the OS X clipboard.

I keep one tmux config and use it across several machines and operating systems. At work I'm on CentOS and my personal laptop runs OS X. So let's update the config to work on both.

bash
set-window-option -g mode-keys vi
bind-key -T copy-mode-vi 'v' send-keys -X begin-selection
bind-key -T copy-mode-vi 'y' send-keys -X copy-selection-and-cancel
bind-key p paste-buffer
 
if-shell 'test "$(uname)" = "Darwin"' 'source ~/.tmux-osx.conf'

The only change is that on OS X we also source an OS X specific config file called ~/.tmux-osx.conf, which holds the following.

bash
set -g default-command "reattach-to-user-namespace -l ${SHELL}"
bash
bind-key -T copy-mode-vi 'y' send-keys -X copy-pipe-and-cancel 'reattach-to-user-namespace pbcopy'

Thanks for reading. You can also follow along on X or with RSS.