Copy the URLs in a selected text using Bellhop

I've been checking out Bellhop, a free tool that allows you to easily create Mac OS X system services in scripting languages (currently AppleScript, F-Script, Perl, Python, and Ruby), and I've created a simple service in Perl that will copy all the absolute URLs from a selected piece of text to the clipboard.

My code is highlighted below. The regular expression is adapted from Drupal's filter.module (see the _filter_url() function). There may be bugs, and it could probably be improved; however, it does work reasonably well. You can copy and paste this into a new Perl service in Bellhop, or you can simply drag the attachment link directly into Bellhop (I'm using version 2.0.4), which will accomplish the same thing. You may also download the attached file and import it into Bellhop, if you prefer.

Copy URLs to Clipboard

  1. sub runService {
  2.  
  3. # aPasteboard identifies the unique pasteboard name reserved for
  4. # the service transaction. Use this name as the argument to the
  5. # various methods that get and set data from the pasteboard.
  6. #
  7. my $aPasteboard = shift(@_);
  8.  
  9. # Put your custom Perl code below.
  10. #
  11. $text = Pasteboard::read_string($aPasteboard, $NSStringPboardType);
  12.  
  13. # The following regular expressions are adapted from Drupal's
  14. # filter.module. See the _filter_url() function:
  15. # http://api.drupal.org/api/function/_filter_url
  16.  
  17. # Convert www domains to absolute URLs.
  18. $text =~ s!(?<\!://)(www\.[a-zA-Z0-9@:%_+*~#?&=.,/;-]*[a-zA-Z0-9@:%_+~#\&=/;-])(?:[.,?\!]*?)!http://$1!gi;
  19.  
  20. # Match absolute URLs.
  21. @matches = $text =~ m!((?:http://|https://|ftp://|mailto:|smb://|afp://|file://|gopher://|news://|ssl://|sslv2://|sslv3://|tls://|tcp://|udp://)(?:[a-zA-Z0-9@:%_+*~#?&=.,/;-]*[a-zA-Z0-9@:%_+*~#&=/;-]))(?:[.,?\!]*?)!gi;
  22.  
  23. # Write a new string to the general clipboard.
  24. Pasteboard::declare_types($NSGeneralPboard, [$NSStringPboardType]);
  25. Pasteboard::write_string($NSGeneralPboard, $NSStringPboardType, join("\n", @matches)."\n");
  26.  
  27. }

Hat tip to @skry for prompting me to find Bellhop and try my hand at creating this particular system service.

AttachmentSize
Bellhop Service Pack - Copy URLs to Clipboard3.62 KB