Created
November 19, 2010 23:28
-
-
Save codingisacopingstrategy/707406 to your computer and use it in GitHub Desktop.
Textmate’s hyperlink helper standalone.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Textmate’s hyperlink helper standalone. | |
# Recieve’s text on StdIn, uses the url that’s on the pasteboard | |
require 'erb' | |
require 'open-uri' | |
require 'net/http' | |
def entity_escape(text) | |
text.gsub(/&(?!([a-zA-Z0-9]+|#[0-9]+|#x[0-9a-fA-F]+);)/, '&') | |
end | |
def make_link(text) | |
case text | |
when %r{\A(mailto:)?(.*?@.*\..*)\z}: | |
"mailto:#{$2.gsub(/./) {sprintf("&#x%02X;", $&.unpack("U")[0])}}" | |
when %r{http://www.(amazon.(?:com|co.uk|co.jp|ca|fr|de))/.+?/([A-Z0-9]{10})/[-a-zA-Z0-9_./%?=&]+}: | |
"http://#{$1}/dp/#{$2}" | |
when %r{\A[a-zA-Z][a-zA-Z0-9.+-]*://.*\z}: | |
entity_escape(text) | |
when %r{\A(www\..*|.*\.(com|uk|net|org|info))\z}: | |
"http://#{entity_escape text}" | |
when %r{\A.*\.(com|uk|net|org|info)\z}: | |
"http://#{entity_escape text}" | |
when %r{\A\S+\z}: | |
entity_escape(text) | |
else | |
"http://example.com/" | |
end | |
end | |
url = make_link %x{__CF_USER_TEXT_ENCODING=$UID:0x8000100:0x8000100 pbpaste}.strip | |
if url =~ /^http:\/\// and url != 'http://example.com/' | |
eval 'title = fp.read.match(/<title>([^<>]*)<\/title>/i).to_a[1].strip rescue nil' if fp = open(url) rescue nil | |
end | |
input = STDIN.read | |
print ERB.new('<a href="<%= url %>"<%= " title=\"#{title}\"" if defined? title %>><%= input %></a>').result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment