Sunday, March 20, 2016

[How-to] Copy Contents of Tmux Pane to File

There are many cases where you might want to copy part of (or the entire) contents of a tmux pane into file for further usage. This post explains how to that. Before we proceed, you need to be aware that my tmux key binding is probably different from yours, see: http://darmawan-salihun.blogspot.co.id/2015/02/zsh-tmux-configuration-for-arch-linux.html. I'm using vi mode-keys.

The steps to copy contents of a tmux pane are as follows:
  1. Enter copy mode. The key combo to enter copy mode depends on your tmux configuration, but the principle never change: press your tmux prefix key combo--in my case, this is Ctrl+A--and then press your tmux copy mode key-in my case the key is Escape. If you look at my tmux configuration file linked above, I should press: Ctrl+A, then Escape to enter tmux copy mode
  2. Select the text that you want to copy. I'm using the v key to select the text because that's how my tmux key binding is configured (~/.tmux.conf: bind -t vi-copy 'v' begin-selection). This is how it looks like once I have selected some text in copy mode with vi-like keys (the selected text is in yellow background):
    tmux copy mode
  3. Copy the selected text into tmux buffer. I'm using y (yank) key to select the text because that's how my tmux key binding is configured (~/.tmux.conf: bind -t vi-copy 'y' copy-selection). Now the selected text is in tmux buffer.
You can "save" contents of the tmux buffer to a file with this command:
$ tmux save-buffer -b [the_buffer_yo_want_to_save] -a [name_of_the_file_you_want_to_append_the_buffer_to]
If you want to just overwrite the contents of the "target" file with the tmux buffer contents, you can omit the -a flag. You can select your "source" tmux buffer before saving the tmux buffer contents by using the command completion key in your shell (in my case TAB -- I'm using zsh). Tmux buffer possibly contains more than one buffer if you previously "copy" something into the buffer, either inadvertently or on-purpose. This is how tmux buffer looks like in my shell as I'm trying to save one of its entries:
Tmux "copy buffer" number 0 to number 10

Anyway, you can also bind keys to the tmux save buffer command in order to make the text available for GUI application as in my tmux.conf shown in the link above. This is the configuration snippet (I'm using icccm clipboard for that):
# extra commands for interacting with the ICCCM clipboard
bind C-c run "tmux save-buffer - | xclip -i -sel clipboard"
bind C-v run "tmux set-buffer \"$(xclip -o -sel clipboard)\"; tmux paste-buffer"
That's it. I hope the explanation is clear enough because there are many explanation on the web that's not quite well-suited for newbie.

Post a Comment

No comments: