summaryrefslogtreecommitdiffstats
path: root/bin/tmux-clipboard
blob: 1e10fcfd476b485df9aa64682984aa7ba1d76831 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#!/usr/bin/env perl
use strict;
use warnings;
use 5.014;

use Config;
use Path::Class;
use POSIX qw(mkfifo);

use constant {
    FIFO_PATH => "$ENV{HOME}/.cache/tmux/clipboard/",
    COPY_CMD => ($Config{osname} eq 'linux' ? 'xclip -i' : 'pbcopy'),
    PASTE_CMD => ($Config{osname} eq 'linux' ? 'xclip -o' : 'pbpaste'),
};

my $fifo_file = file(FIFO_PATH, $$);
$fifo_file->dir->mkpath;
$fifo_file->remove;
END { $fifo_file->remove }
mkfifo("$fifo_file", 0700);

if ($ARGV[0] eq 'copy') {
    if (fork) {
        close STDIN;
        close STDOUT;
        close STDERR;

        open my $clipboard, '|-', COPY_CMD
            or die "can't copy from clipboard using ${\COPY_CMD}: $!";
        $clipboard->print($fifo_file->slurp);
        $clipboard->close;
    }
    else {
        exec("tmux save-buffer -a $fifo_file");
    }
}
elsif ($ARGV[0] eq 'paste') {
    if (fork) {
        close STDIN;
        close STDOUT;
        close STDERR;

        open my $clipboard, '-|', PASTE_CMD
            or die "can't paste from clipboard using ${\PASTE_CMD}: $!";
        my $contents = do { local $/; <$clipboard> };
        $clipboard->close;
        $fifo_file->spew(iomode => 'a', $contents);
    }
    else {
        system("tmux load-buffer -b tmux-clipboard $fifo_file");
        exec("tmux paste-buffer -b tmux-clipboard -dp");
    }
}
else {
    die "usage: $0 [copy|paste]";
}