1 """A more liberal autolinker
3 Inspired by Django's urlize function.
8 >>> md = markdown.Markdown(extensions=['urlize'])
10 >>> md.convert('http://example.com/')
11 u'<p><a href="http://example.com/">http://example.com/</a></p>'
13 >>> md.convert('go to http://example.com')
14 u'<p>go to <a href="http://example.com">http://example.com</a></p>'
16 >>> md.convert('example.com')
17 u'<p><a href="http://example.com">example.com</a></p>'
19 >>> md.convert('example.net')
20 u'<p><a href="http://example.net">example.net</a></p>'
22 >>> md.convert('www.example.us')
23 u'<p><a href="http://www.example.us">www.example.us</a></p>'
25 >>> md.convert('(www.example.us/path/?name=val)')
26 u'<p>(<a href="http://www.example.us/path/?name=val">www.example.us/path/?name=val</a>)</p>'
28 >>> md.convert('go to <http://example.com> now!')
29 u'<p>go to <a href="http://example.com">http://example.com</a> now!</p>'
33 >>> md.convert('del.icio.us')
41 URLIZE_RE = '(%s)' % '|'.join([
42 r'<(?:f|ht)tps?://[^>]*>',
43 r'\b(?:f|ht)tps?://[^)<>\s]+[^.,)<>\s]',
44 r'\bwww\.[^)<>\s]+[^.,)<>\s]',
45 r'[^(<\s]+\.(?:com|net|org)\b',
48 class UrlizePattern(markdown.inlinepatterns.Pattern):
49 """ Return a link Element given an autolink (`http://example/com`). """
50 def handleMatch(self, m):
53 if url.startswith('<'):
58 if not url.split('://')[0] in ('http','https','ftp'):
59 if '@' in url and not '/' in url:
64 el = markdown.etree.Element("a")
66 el.text = markdown.AtomicString(text)
69 class UrlizeExtension(markdown.Extension):
70 """ Urlize Extension for Python-Markdown. """
72 def extendMarkdown(self, md, md_globals):
73 """ Replace autolink with UrlizePattern """
74 md.inlinePatterns['autolink'] = UrlizePattern(URLIZE_RE, md)
76 def makeExtension(configs=None):
77 return UrlizeExtension(configs=configs)
79 if __name__ == "__main__":