summaryrefslogtreecommitdiffstats
path: root/tmux/.bin/tmux-clipboard
diff options
context:
space:
mode:
Diffstat (limited to 'tmux/.bin/tmux-clipboard')
-rwxr-xr-xtmux/.bin/tmux-clipboard74
1 files changed, 74 insertions, 0 deletions
diff --git a/tmux/.bin/tmux-clipboard b/tmux/.bin/tmux-clipboard
new file mode 100755
index 0000000..dae796b
--- /dev/null
+++ b/tmux/.bin/tmux-clipboard
@@ -0,0 +1,74 @@
+#!/usr/bin/env perl
+use strict;
+use warnings;
+use 5.020;
+use feature 'signatures';
+no warnings 'experimental::signatures';
+
+use Config;
+
+use constant {
+ COPY_CMD => ($Config{osname} eq 'linux' ? 'xclip -i' : 'pbcopy'),
+ PASTE_CMD => ($Config{osname} eq 'linux' ? 'xclip -o' : 'pbpaste'),
+};
+
+sub main($cmd, $selection) {
+ if ($cmd eq 'copy') {
+ tmux_copy($selection);
+ }
+ elsif ($cmd eq 'paste') {
+ tmux_paste($selection);
+ }
+ else {
+ die "usage: $0 [copy|paste]";
+ }
+}
+
+sub tmux_copy($selection='primary') {
+ set_clipboard_contents(get_tmux_buffer(), $selection);
+}
+
+sub tmux_paste($selection='primary') {
+ write_to_tmux(get_clipboard_contents($selection));
+}
+
+sub set_clipboard_contents($contents, $selection) {
+ my $copy_cmd = COPY_CMD;
+ if ($Config{osname} eq 'linux') {
+ $copy_cmd .= " -selection $selection";
+ }
+
+ open my $clipboard, '|-', $copy_cmd
+ or die "can't set clipboard contents using `$copy_cmd`: $!";
+ print $clipboard $contents;
+ close $clipboard;
+}
+
+sub get_clipboard_contents($selection) {
+ my $paste_cmd = PASTE_CMD;
+ if ($Config{osname} eq 'linux') {
+ $paste_cmd .= " -selection $selection";
+ }
+
+ open my $clipboard, '-|', $paste_cmd
+ or die "can't get clipboard contents using `$paste_cmd`: $!";
+ my $contents = do { local $/; <$clipboard> };
+ close $clipboard;
+ $contents
+}
+
+sub get_tmux_buffer {
+ scalar `tmux show-buffer`
+}
+
+sub write_to_tmux($contents) {
+ my $tmux_cmd = "tmux load-buffer -b tmux-clipboard -";
+ open my $tmux, '|-', $tmux_cmd
+ or die "can't set tmux buffer contents using `$tmux_cmd`: $!";
+ print $tmux $contents;
+ close $tmux;
+
+ system("tmux paste-buffer -b tmux-clipboard -dp");
+}
+
+main(@ARGV)