Skip to content

Instantly share code, notes, and snippets.

@trey
Created March 27, 2012 15:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trey/2217444 to your computer and use it in GitHub Desktop.
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>
#!/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]+);)/, '&amp;')
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>'
@trey
Copy link
Author

trey commented Mar 27, 2012

Just copied the TextMate 1.5.10 Wrap Word / Selection as Link snippet and simplified the output.

Using the Key Equivalent ⌃⌥⌘L

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment