1#! perl -w
2# Author:   Bert Muennich
3# Website:  http://www.github.com/muennich/urxvt-perls
4# Version:  2.0
5# License:  GPLv2
6
7# Use keyboard shortcuts to copy the selection to the clipboard and to paste
8# the clipboard contents (optionally escaping all special characters).
9# Requires xsel to be installed!
10
11# Usage: put the following lines in your .Xdefaults/.Xresources:
12#   URxvt.perl-ext-common: ...,clipboard
13#   URxvt.keysym.M-c:   perl:clipboard:copy
14#   URxvt.keysym.M-v:   perl:clipboard:paste
15#   URxvt.keysym.M-C-v: perl:clipboard:paste_escaped
16
17# You can also overwrite the system commands to use for copying/pasting.
18# The default ones are:
19#   URxvt.clipboard.copycmd:  xsel -ib
20#   URxvt.clipboard.pastecmd: xsel -ob
21# If you prefer xclip, then put these lines in your .Xdefaults/.Xresources:
22#   URxvt.clipboard.copycmd:  xclip -i -selection clipboard
23#   URxvt.clipboard.pastecmd: xclip -o -selection clipboard
24# On Mac OS X, put these lines in your .Xdefaults/.Xresources:
25#   URxvt.clipboard.copycmd:  pbcopy
26#   URxvt.clipboard.pastecmd: pbpaste
27
28# The use of the functions should be self-explanatory!
29
30use strict;
31
32sub on_start {
33	my ($self) = @_;
34
35	$self->{copy_cmd} = $self->x_resource('clipboard.copycmd') || 'xsel -ib';
36	$self->{paste_cmd} = $self->x_resource('clipboard.pastecmd') || 'xsel -ob';
37
38	()
39}
40
41sub copy {
42	my ($self) = @_;
43
44	if (open(CLIPBOARD, "| $self->{copy_cmd}")) {
45		my $sel = $self->selection();
46		utf8::encode($sel);
47		print CLIPBOARD $sel;
48		close(CLIPBOARD);
49	} else {
50		print STDERR "error running '$self->{copy_cmd}': $!\n";
51	}
52
53	()
54}
55
56sub paste {
57	my ($self) = @_;
58
59	my $str = `$self->{paste_cmd}`;
60	if ($? == 0) {
61		$self->tt_paste($str);
62	} else {
63		print STDERR "error running '$self->{paste_cmd}': $!\n";
64	}
65
66	()
67}
68
69sub paste_escaped {
70	my ($self) = @_;
71
72	my $str = `$self->{paste_cmd}`;
73	if ($? == 0) {
74		$str =~ s/([!#\$%&\*\(\) ='"\\\|\[\]`~,<>\?])/\\\1/g;
75		$self->tt_paste($str);
76	} else {
77		print STDERR "error running '$self->{paste_cmd}': $!\n";
78	}
79
80	()
81}
82
83sub on_user_command {
84	my ($self, $cmd) = @_;
85
86	if ($cmd eq "clipboard:copy") {
87	   $self->copy;
88	} elsif ($cmd eq "clipboard:paste") {
89	   $self->paste;
90	} elsif ($cmd eq "clipboard:paste_escaped") {
91	   $self->paste_escaped;
92	}
93
94	()
95}
96