#! perl

# same url as used in "selection"
my $url =
   qr{(
      (?:https?|ftp|news|mailto|file)://[ab-zA-Z0-9\-\@;\/?:&=%\$_.+!*\x27(),~]+
      [ab-zA-Z0-9\-\@;\/?:&=%\$_+!*\x27()~]   # exclude some trailing characters (heuristic)
   )}x;

sub on_start {
   my ($self) = @_;

   $self->{browser} = $self->x_resource ("urlLauncher") || "x-www-browser";

   ()
}

sub on_line_update {
   my ($self, $row) = @_;

   # fetch the line that has changed
   my $line = $self->line ($row);
   my $text = $line->t;

   # find all urls (if any)
   while ($text =~ /$url/g) {
      my $rend = $line->r;

      # mark all characters as underlined. we _must_ not toggle underline,
      # as we might get called on an already-marked url.
      $_ |= urxvt::RS_Uline
         for @{$rend}[ $-[1] .. $+[1] - 1];

      $line->r ($rend);
   }

   ()
}

sub on_button_release {
    my ($self, $event) = @_;

    my $mask = $self->ModLevel3Mask | $self->ModMetaMask
             | urxvt::ShiftMask | urxvt::ControlMask;

    if ($event->{button} == 2 && ($event->{state} & $mask) == 0) {
       my $row = $event->{row};
       my $col = $event->{col};

       my $line = $self->line ($row);
       my $text = $line->t;
    
       while ($text =~ /$url/g) {
           if ($-[1] <= $col && $+[1] >= $col) {
               $self->exec_async ($self->{browser}, $1);
               return 1;
           }
       }
    }

    ()
}

