Blog

Thoughts from my daily grind

tmux on macOS - copy to system clipboard

Posted by Ziyan Junaideen |Published: 30 April 2021 |Category: Apple
Tmux Select | Tmux configuration in macOS ready to copy to system clipboard through visual selection.

I have been using tmux since 2010. It is one of the most useful software utilities in my iMac and HP Envy running Ubuntu Linux. I use tmux daily alongside nvim, my preferred code editor. I would usually have nvim in the first window. The second window will usually split into panes both horizontally and vertically. Once you have a vertical split selecting from the mouse and copying is an option. That is why I will show you how to configure tmux to copy to the system clipboard.

Notice

For this method to work, you will have to enable terminal applications to access the system clipboard. This is a risk, but I don't see how we copy from tmux to the system clipboard.

  • Open the iTerm2 menu
  • Select Preferences
  • On the "General" tab, select "Selection."
  • Check "Applications in the terminal may access the clipboard."

Setup

First, we need to install the plugin reattach-to-user-namespace. It is available in homebrew for an easy install.

brew install reattach-to-user-namespace

Then we need to create a config file ~/.tmux.conf. That is where we will notify tmux to channel the copied text buffer to pbcopy. My config file is as follows.

cat ~/.tmux.conf
bind-key -T copy-mode-vi 'y' send -X copy-pipe-and-cancel 'reattach-to-user-namespace pbcopy'
bind-key -T copy-mode-vi Enter send -X copy-pipe-and-cancel 'reattach-to-user-namespace pbcopy'

Now you have what it takes to copy to the system.

Practice

Let's open a new tmux session, tmux new -s test. Let's split it into 2 vertical windows using "control + b" followed by %. Run a command in the first tab pane (ex: tree ~/Desktop) so that you have something to copy. Then we need to go to visual select mode. Press control b followed by [. Use the h-j-k-l or arrow keys to move to the line you need to select. "Shift + v" will select the whole line. Now move to the other end of the selection. Tmux will highlight your selection in yellow. Then press y or return to copy it to the clipboard.

Extra

There is an article on ThoughtBot with the title tmux Copy & Paste on OS X: A Better Future. The article is outdated and if you try it out you will come up with an error due to changes in the API.

.tmux.conf:9: usage: bind-key [-nr] [-T key-table] [-N note] key [command [arguments]]
Tags
About the Author

Ziyan Junaideen -

Ziyan is an expert Ruby on Rails web developer with 8 years of experience specializing in SaaS applications. He spends his free time he writes blogs, drawing on his iPad, shoots photos.

Comments