Shortened URLs in Emacs using is.gd (like tinyurl)
September 15, 2008 at 11:11 AM | categories: python, emacs | View CommentsI've casually been teaching myself emacs lisp lately. Today I wrote a utility that shortens long urls within regions using the http://is.gd URL shortening service. There's plenty of existing code out there that is more lisp like, but this is supposed to be a learning experience for me so I did it myself. I like python and so I used python for most of the heavy lifting.
I created a directory to hold all of my emacs specific python functions: ~/.emacs.d/ryan-pymacs-extensions
I wrote the following python function, shorten_url.py in that directory:
!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = "Ryan McGuire (ryan@enigmacurry.com)" __date__ = "Mon Sep 15 12:27:14 2008" import doctest import urllib2 import re def shorten_with_is_gd(url): """Shorten a URL with is.gd >>> shorten_with_is_gd('http://www.enigmacurry.com') 'http://is.gd/FFP' """ u = urllib2.urlopen("http://is.gd/api.php?longurl="+url) return u.read() def shorten_in_text(text): """Shorten all the urls found inside some text >>> shorten_in_text('Hi from http://www.enigmacurry.com') 'Hi from http://is.gd/FFP' """ replacements = {} #URL -> is.gd URL #Only check for urls that start with "http://" for now for m in re.finditer("http://[^ \n\r]*", text): try: replacements[m.group()] = shorten_with_is_gd(m.group()) except: replacements[m.group()] = m.group() for url,replacement in replacements.items(): text = text.replace(url, replacement) return text if __name__ == '__main__': doctest.testmod(verbose=True)
and the following lisp makes "M-x shorten-url" do the rest of the replacement work:
;add ~/.emacs.d/ryan-python-extensions to python path (pymacs-exec "import sys, os") (pymacs-exec "sys.path.append(os.path.join(os.path.expanduser('~'),'.emacs.d','ryan-pymacs-extensions'))") ;;Shorten URLs with is.gd (pymacs-exec "import shorten_url") (defun shorten-url (start end) (interactive "r") (let ((region (buffer-substring start end))) (let ((rt (pymacs-eval (format "shorten_url.shorten_in_text('''%s''')" region)))) (kill-region start end) (insert rt) ) ))