summaryrefslogtreecommitdiff
path: root/ext/mymatcher
blob: 7760d1b00e10779844aab8ca1176de6516a9add4 (plain)
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
#! perl 
use utf8;
use lib '/home/dakkar/perl5/perlbrew/perls/perl-5.18.1/lib/site_perl/5.18.1';
use URI::Find;
# Author: Tim Pope <rxvt-unicodeNOSPAM@tpope.org> 
#          Bob Farrell <robertanthonyfarrell@gmail.com> 
 
#:META:X_RESOURCE:%.launcher:string:default launcher command 
#:META:X_RESOURCE:%.button:string:the button, yeah 
#:META:X_RESOURCE:%.scheme.:string:URI scheme to match 
#:META:X_RESOURCE:%.launcher.:string:custom launcher for scheme 
#:META:X_RESOURCE:%.rend.:string:custom rendition for scheme 
 
=head1 NAME
 
matcher - match strings in terminal output and change their rendition
 
=head1 DESCRIPTION
 
Uses per-line display filtering (C<on_line_update>) to underline URIs
in text and make it clickable. When clicked with the mouse button
specified in the C<matcher.button> resource (default 2, or middle),
the program specified in the C<matcher.launcher> resource (default,
the C<urlLauncher> resource, C<sensible-browser>) will be started with
the matched text as first argument.  The default configuration is
suitable for matching URLs and launching a web browser, like the
former "mark-urls" extension.
 
The default scheme to match URLs can be overridden with the
C<matcher.scheme.0> resource, and additional patterns can be specified
with numbered patterns, in a manner similar to the "selection" extension.
The launcher can also be overridden on a per-pattern basis.
 
It is possible to activate the most recently seen match or a list of matches
from the keyboard.  Simply bind a keysym to "perl:matcher:last" or
"perl:matcher:list" as seen in the example below.
 
Example configuration:
 
    URxvt.perl-ext:           default,matcher
    URxvt.url-launcher:       sensible-browser
    URxvt.keysym.C-Delete:    perl:matcher:last
    URxvt.keysym.M-Delete:    perl:matcher:list
    URxvt.matcher.button:     1
    URxvt.matcher.scheme.1:   gopher
    URxvt.matcher.scheme.2:   file
    URxvt.matcher.launcher.2: gvim +$2 $1
 
=cut
 
sub on_key_press {
   my ($self$event$keysym$octets) = @_;
 
   if (! $self->{showing} ) {
      return;
   }
 
   my $i = ($keysym == 96 ? 0 : $keysym - 48);
   if (($i > scalar(@{$self->{urls_and_comm}})) || ($i < 0)) {
      $self->matchlist();
      return;
   }
 
   my ($url,@comm) = @{$self->{urls_and_comm}[ -$i-1 ]};
   $self->matchlist();
 
   $self->exec_async( @comm ) if @comm;
}
 
sub on_user_command {
   my ($self$cmd) = @_;
 
   if($cmd =~ s/^mymatcher:list\b//) {
      $self->matchlist();
   } else {
      if($cmd =~ s/^mymatcher:last\b//) {
         $self->most_recent;
      }
   # For backward compatibility 
    else {
      if($cmd =~ s/^mymatcher\b//) {
         $self->most_recent;
      }
   }
  }
   ()
}
 
sub matchlist {
   my ($self) = @_;
   if ( $self->{showing} ) {
     $self->{url_overlay}->hide();
     $self->{showing} = 0;
     return;
   }
  @{$self->{urls_and_comm}} = ();
  my $line;
  for (my $i = 0; $i < $self->nrow; $i ++) {
     $line = $self->line($i);
     next if ($line->beg != $i);
     for my $url ($self->get_urls_and_commands_from_line($line->t)) {
        if (scalar(@{$self->{urls_and_comm}}) == 10) {
            shift @{$self->{urls_and_comm}};
        }
        push @{$self->{urls_and_comm}}, $url;
     }
  }
 
  if (! scalar(@{$self->{urls_and_comm}})) {
    return;
  }
 
  my $max = 0;
  my $i = scalar( @{$self->{urls_and_comm}} ) - 1 ;;
 
  my @temp = ();
 
  for my $url_and_comm (@{$self->{urls_and_comm}}) {
     my ($url,@comm) = @$url_and_comm;
     my $url = "$i»$url";
     my $xpos = 0;
 
     if ($self->ncol + (length $url) >= $self->ncol) {
        $url = substr$url, 0, $self->ncol );
     }
 
     push @temp$url;
 
     iflength $url > $max ) {
        $max = length $url;
     }
 
     $i--;
  }
 
  @temp = reverse @temp;
 
  $self->{url_overlay} = $self->overlay(0, 0, $maxscalar@temp ), urxvt::OVERLAY_RSTYLE, 2);
  my $i = 0;
  for my $url (@temp) {
     $self->{url_overlay}->set( 0, $i$url, [(urxvt::OVERLAY_RSTYLE) x length $url]);
$self->{showing} = 1;
     $i++;
  }
 
}
 
sub most_recent {
   my ($self) = shift;
   my $row = $self->nrow;
   my @urls_and_comm;
   while($row-- > $self->top_row) {
      @urls_and_comm = $self->get_urls_and_commands_from_line(undef,$row);
      last if @urls_and_comm;
   }
 
   if(@urls_and_comm) {
       my ($url,@comm) = @{$urls_and_comm[-1]};
      return $self->exec_async (@comm);
   }
   ()
}
 
sub my_resource {
   $_[0]->x_resource ("%.$_[1]")
}
 
# turn a rendition spec in the resource into a sub that implements it on $_ 
sub parse_rend {
   my ($self$str) = @_;
   my ($mask$fg$bg$failed) = $str ? urxvt::rend2mask($str)
                                        : (urxvt::RS_Uline, undefundef, []);
   warn "Failed to parse rendition string: " . join(','@$failedif @$failed;
   my @rend;
   push @rend, sub { $_ |= $mask } if $mask;
   push @rend, sub { $_ = urxvt::SET_FGCOLOR($_$fg) } if defined $fg;
   push @rend, sub { $_ = urxvt::SET_BGCOLOR($_$bg) } if defined $bg;
   sub {
      for my $s ( @rend ) { &$s };
   }
}
 
sub on_start {
   my ($self) = @_;
 
   $self->{launcher} = $self->my_resource ("launcher") || $self->x_resource("url-launcher") || "sensible-browser";
 
   $self->{urls_and_comm} = [];
   $self->{showing} = 0;
   $self->{button}  = 2;
   $self->{state}   = 0;
   if($self->{argv}[0] || $self->my_resource ("button")) {
      my @mods = split ''$self->{argv}[0] || $self->my_resource ("button");
      for my $mod (@mods) {
         if($mod =~ /^\d+$/) {
            $self->{button} = $mod;
         elsif($mod eq "C") {
            $self->{state} |= urxvt::ControlMask;
         elsif($mod eq "S") {
            $self->{state} |= urxvt::ShiftMask;
         elsif($mod eq "M") {
            $self->{state} |= $self->ModMetaMask;
         elsif($mod ne "-" && $mod ne " ") {
            warn("$mod is invalid in $self->{_name}<$self->{argv}[0]>\n");
         }
      }
   }
 
   my @defaults = ('');
   my @matchers;
   for (my $idx = 0; defined (my $res = $self->my_resource ("scheme.$idx") || $defaults[$idx]); $idx++) {
      $res = $self->locale_decode ($res);
      utf8::encode $res;
      my $launcher = $self->my_resource ("launcher.$idx");
      $launcher =~ s/\$&|\$\{&\}/\${0}/g if $launcher;
      my $rend = $self->parse_rend($self->my_resource ("rend.$idx"));
      unshift @matchers, [qr($res)x,$launcher,$rend];
   }
   $self->{matchers} = \@matchers;
 
   ()
}
 
sub on_line_update {
   my ($self$row) = @_;
 
   # fetch the line that has changed 
   my $line = $self->line ($row);
   my $text = $line->t;
 
   URI::Find->new(
       sub {
           my ($uri,$match) = @_;
 
           my $scheme = $uri->scheme;
           my ($matcher) = grep {
               my $scheme_re = $_->[0];
               $scheme =~ m{$scheme_re};
           } @{$self->{matchers}};
 
           $text =~ m{\Q$match};
           my $rend = $line->r;
           # mark all characters as underlined. we _must_ not toggle 
           # underline, as we might get called on an already-marked 
           # url. 
           &{$matcher->[2]}
               for @{$rend}[ $-[0] .. $+[0] - 1];
 
           $line->r ($rend);
       }
   )->find(\$text);
 
   ()
}
 
sub valid_button {
   my ($self$event) = @_;
   my $mask = $self->ModLevel3Mask | $self->ModMetaMask
   | urxvt::ShiftMask | urxvt::ControlMask;
   return ($event->{button} == $self->{button} &&
      ($event->{state} & $mask) == $self->{state});
}
 
sub get_urls_and_commands_from_line {
   my ($self$text$row$col) = @_;
   if (!defined $text) {
       my $line = $self->line ($row);
       $text = $line->t;
   }
 
   my @ret;
 
   URI::Find->new(
       sub {
           my ($uri,$match) = @_;
 
           my $scheme = $uri->scheme;
           my ($matcher) = grep {
               my $scheme_re = $_->[0];
               $scheme =~ m{$scheme_re};
           } @{$self->{matchers}};
           my $launcher = $matcher->[1] || $self->{launcher};
 
           $text =~ m{\Q$match};
 
           my @begin = @-;
           my @end = @+;
           if (!defined($col) || ($-[0] <= $col && $+[0] >= $col)) {
               if ($launcher !~ /\$/) {
                   push @ret, [$match,$launcher,$match];
               }
               else {
                   # It'd be nice to just access a list like ($&,$1,$2...), 
                   # but alas, m//g behaves differently in list context. 
                   my @exec = map { s/\$(\d+)|\$\{(\d+)\}/$match/gx$_ } split(/\s+/$launcher);
                   push @ret,[$match,@exec];
               }
           }
       }
   )->find(\$text);
 
   return @ret;
}
 
sub on_button_press {
   my ($self$event) = @_;
   if($self->valid_button($event)
      && (my ($url_and_comm) = $self->get_urls_and_commands_from_line(undef,$event->{row},$event->{col}))) {
       my ($url,@comm) = @$url_and_comm;
      $self->{row} = $event->{row};
      $self->{col} = $event->{col};
      $self->{cmd} = \@comm;
      return 1;
   } else {
      delete $self->{row};
      delete $self->{col};
      delete $self->{cmd};
   }
 
   ()
}
 
sub on_button_release {
   my ($self$event) = @_;
 
   my $row = delete $self->{row};
   my $col = delete $self->{col};
   my $cmd = delete $self->{cmd};
 
   return if !defined $row;
 
   my ($url_and_comm) = $self->get_urls_and_commands_from_line(undef,$event->{row},$event->{col});
   my ($url,@comm) = @$url_and_comm;
 
   if($row == $event->{row} && abs($col-$event->{col}) < 2
          && join("\x00"@$cmdeq join("\x00"@comm)) {
      if($self->valid_button($event)) {
 
 $self->exec_async (@$cmd);
 
      }
   }
 
   1;
}
 
# vim:set sw=3 sts=3 et: