Created
March 27, 2012 15:57
-
-
Save trey/2217444 to your computer and use it in GitHub Desktop.
TextMate snippet to create a link from a URL in the format <a href="url">page title</a>
This file contains 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
#!/usr/bin/env ruby -wKU | |
require ENV['TM_SUPPORT_PATH'] + '/lib/escape.rb' | |
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 | |
else | |
title = url | |
end | |
input = STDIN.read | |
puts '<a href="' + url + '">' + title + '</a>' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just copied the TextMate 1.5.10
Wrap Word / Selection as Link
snippet and simplified the output.Using the Key Equivalent ⌃⌥⌘L