Tmux Clipboard – How to Copy a Buffer to the Clipboard

clipboardkeyboard shortcutstmuxxclip

I am trying to figure out a decent way to copy what I have in a tmux buffer into my clipboard. I have tried a couple of different things like

bind-key p select-pane -t 2 \; split-window 'xsel -i -b' \; paste-buffer

which gets me fairly close, all I have to do is hit control-d after I do prefix-p.

I tried fixing that by doing

bind-key p select-pane -t 2 \; split-window 'xsel -i -b << HERE\; tmux paste-buffer\; echo HERE'

But that just doesn't work. In fact if I pair this down to just

bind-key p select-pane -t 2 \; split-window 'xsel -i -b << HERE'

it doesn't do anything so I am assuming that split-window doesn't like << in a shell command.

Any ideas?

Edit:
You can skip the select-pane -t 2 if you want, it isn't really important. I just use a specific layout and pane 2 is the one I prefer to split when I doing something else so that goes into my bindings involving splits by default.

Best Answer

Here documents need newlines. For example, in a shell script, you can write

cat <<EOF >somefile; echo  done
file contents
EOF

I don't think tmux lets you put newlines there, and even if it did, this wouldn't be a good approach. What if the data itself contains HERE alone on a line (e.g. because you're copying your .tmux.conf)?

I suggest to write the buffer contents to a temporary file. Untested:

bind-key p save-buffer ~/.tmux-buffer \; run-shell "xsel -i -b <~/.tmux-buffer && rm ~/.tmux-buffer"

There's a race condition if you use this command in two separate tmux instances. I don't know how to solve this.

Related Question