comparison tools/mdx_urlize.py @ 356:f54bf3b3bece

Fix 180; Add strikethrough capability to markdown via an extension. Also control in SVN the extensions we are using.
author Brian Neal <bgneal@gmail.com>
date Fri, 04 Mar 2011 02:10:37 +0000
parents
children 2adf01661ac5
comparison
equal deleted inserted replaced
355:a1e3724f0799 356:f54bf3b3bece
1 """
2 Taken from: https://github.com/r0wb0t/markdown-urlize
3
4 A more liberal autolinker
5
6 Inspired by Django's urlize function.
7
8 Positive examples:
9
10 >>> import markdown
11 >>> md = markdown.Markdown(extensions=['urlize'])
12
13 >>> md.convert('http://example.com/')
14 u'<p><a href="http://example.com/">http://example.com/</a></p>'
15
16 >>> md.convert('go to http://example.com')
17 u'<p>go to <a href="http://example.com">http://example.com</a></p>'
18
19 >>> md.convert('example.com')
20 u'<p><a href="http://example.com">example.com</a></p>'
21
22 >>> md.convert('example.net')
23 u'<p><a href="http://example.net">example.net</a></p>'
24
25 >>> md.convert('www.example.us')
26 u'<p><a href="http://www.example.us">www.example.us</a></p>'
27
28 >>> md.convert('(www.example.us/path/?name=val)')
29 u'<p>(<a href="http://www.example.us/path/?name=val">www.example.us/path/?name=val</a>)</p>'
30
31 >>> md.convert('go to <http://example.com> now!')
32 u'<p>go to <a href="http://example.com">http://example.com</a> now!</p>'
33
34 Negative examples:
35
36 >>> md.convert('del.icio.us')
37 u'<p>del.icio.us</p>'
38
39 """
40
41 import markdown
42
43 # Global Vars
44 URLIZE_RE = '(%s)' % '|'.join([
45 r'<(?:f|ht)tps?://[^>]*>',
46 r'\b(?:f|ht)tps?://[^)<>\s]+[^.,)<>\s]',
47 r'\bwww\.[^)<>\s]+[^.,)<>\s]',
48 r'[^(<\s]+\.(?:com|net|org)\b',
49 ])
50
51 class UrlizePattern(markdown.inlinepatterns.Pattern):
52 """ Return a link Element given an autolink (`http://example/com`). """
53 def handleMatch(self, m):
54 url = m.group(2)
55
56 if url.startswith('<'):
57 url = url[1:-1]
58
59 text = url
60
61 if not url.split('://')[0] in ('http','https','ftp'):
62 if '@' in url and not '/' in url:
63 url = 'mailto:' + url
64 else:
65 url = 'http://' + url
66
67 el = markdown.etree.Element("a")
68 el.set('href', url)
69 el.text = markdown.AtomicString(text)
70 return el
71
72 class UrlizeExtension(markdown.Extension):
73 """ Urlize Extension for Python-Markdown. """
74
75 def extendMarkdown(self, md, md_globals):
76 """ Replace autolink with UrlizePattern """
77 md.inlinePatterns['autolink'] = UrlizePattern(URLIZE_RE, md)
78
79 def makeExtension(configs=None):
80 return UrlizeExtension(configs=configs)
81
82 if __name__ == "__main__":
83 import doctest
84 doctest.testmod()