1#!/usr/bin/env python
2
3'''
4WikiLinks Extension for Python-Markdown
5======================================
6
7Converts [[WikiLinks]] to relative links.  Requires Python-Markdown 2.0+
8
9Basic usage:
10
11    >>> import markdown
12    >>> text = "Some text with a [[WikiLink]]."
13    >>> html = markdown.markdown(text, ['wikilinks'])
14    >>> html
15    u'<p>Some text with a <a class="wikilink" href="/WikiLink/">WikiLink</a>.</p>'
16
17Whitespace behavior:
18
19    >>> markdown.markdown('[[ foo bar_baz ]]', ['wikilinks'])
20    u'<p><a class="wikilink" href="/foo_bar_baz/">foo bar_baz</a></p>'
21    >>> markdown.markdown('foo [[ ]] bar', ['wikilinks'])
22    u'<p>foo  bar</p>'
23
24To define custom settings the simple way:
25
26    >>> markdown.markdown(text,
27    ...     ['wikilinks(base_url=/wiki/,end_url=.html,html_class=foo)']
28    ... )
29    u'<p>Some text with a <a class="foo" href="/wiki/WikiLink.html">WikiLink</a>.</p>'
30
31Custom settings the complex way:
32
33    >>> md = markdown.Markdown(
34    ...     extensions = ['wikilinks'],
35    ...     extension_configs = {'wikilinks': [
36    ...                                 ('base_url', 'http://example.com/'),
37    ...                                 ('end_url', '.html'),
38    ...                                 ('html_class', '') ]},
39    ...     safe_mode = True)
40    >>> md.convert(text)
41    u'<p>Some text with a <a href="http://example.com/WikiLink.html">WikiLink</a>.</p>'
42
43Use MetaData with mdx_meta.py (Note the blank html_class in MetaData):
44
45    >>> text = """wiki_base_url: http://example.com/
46    ... wiki_end_url:   .html
47    ... wiki_html_class:
48    ...
49    ... Some text with a [[WikiLink]]."""
50    >>> md = markdown.Markdown(extensions=['meta', 'wikilinks'])
51    >>> md.convert(text)
52    u'<p>Some text with a <a href="http://example.com/WikiLink.html">WikiLink</a>.</p>'
53
54MetaData should not carry over to next document:
55
56    >>> md.convert("No [[MetaData]] here.")
57    u'<p>No <a class="wikilink" href="/MetaData/">MetaData</a> here.</p>'
58
59Define a custom URL builder:
60
61    >>> def my_url_builder(label, base, end):
62    ...     return '/bar/'
63    >>> md = markdown.Markdown(extensions=['wikilinks'],
64    ...         extension_configs={'wikilinks' : [('build_url', my_url_builder)]})
65    >>> md.convert('[[foo]]')
66    u'<p><a class="wikilink" href="/bar/">foo</a></p>'
67
68From the command line:
69
70    python markdown.py -x wikilinks(base_url=http://example.com/,end_url=.html,html_class=foo) src.txt
71
72By [Waylan Limberg](http://achinghead.com/).
73
74License: [BSD](http://www.opensource.org/licenses/bsd-license.php)
75
76Dependencies:
77* [Python 2.3+](http://python.org)
78* [Markdown 2.0+](http://www.freewisdom.org/projects/python-markdown/)
79'''
80
81import markdown
82import re
83
84def build_url(label, base, end):
85    """ Build a url from the label, a base, and an end. """
86    clean_label = re.sub(r'([ ]+_)|(_[ ]+)|([ ]+)', '_', label)
87    return '%s%s%s'% (base, clean_label, end)
88
89
90class WikiLinkExtension(markdown.Extension):
91    def __init__(self, configs):
92        # set extension defaults
93        self.config = {
94                        'base_url' : ['/', 'String to append to beginning or URL.'],
95                        'end_url' : ['/', 'String to append to end of URL.'],
96                        'html_class' : ['wikilink', 'CSS hook. Leave blank for none.'],
97                        'build_url' : [build_url, 'Callable formats URL from label.'],
98        }
99
100        # Override defaults with user settings
101        for key, value in configs :
102            self.setConfig(key, value)
103
104    def extendMarkdown(self, md, md_globals):
105        self.md = md
106
107        # append to end of inline patterns
108        WIKILINK_RE = r'\[\[([A-Za-z0-9_ -]+)\]\]'
109        wikilinkPattern = WikiLinks(WIKILINK_RE, self.config)
110        wikilinkPattern.md = md
111        md.inlinePatterns.add('wikilink', wikilinkPattern, "<not_strong")
112
113
114class WikiLinks(markdown.inlinepatterns.Pattern):
115    def __init__(self, pattern, config):
116        markdown.inlinepatterns.Pattern.__init__(self, pattern)
117        self.config = config
118
119    def handleMatch(self, m):
120        if m.group(2).strip():
121            base_url, end_url, html_class = self._getMeta()
122            label = m.group(2).strip()
123            url = self.config['build_url'][0](label, base_url, end_url)
124            a = markdown.etree.Element('a')
125            a.text = label
126            a.set('href', url)
127            if html_class:
128                a.set('class', html_class)
129        else:
130            a = ''
131        return a
132
133    def _getMeta(self):
134        """ Return meta data or config data. """
135        base_url = self.config['base_url'][0]
136        end_url = self.config['end_url'][0]
137        html_class = self.config['html_class'][0]
138        if hasattr(self.md, 'Meta'):
139            if self.md.Meta.has_key('wiki_base_url'):
140                base_url = self.md.Meta['wiki_base_url'][0]
141            if self.md.Meta.has_key('wiki_end_url'):
142                end_url = self.md.Meta['wiki_end_url'][0]
143            if self.md.Meta.has_key('wiki_html_class'):
144                html_class = self.md.Meta['wiki_html_class'][0]
145        return base_url, end_url, html_class
146
147
148def makeExtension(configs=None) :
149    return WikiLinkExtension(configs=configs)
150
151
152if __name__ == "__main__":
153    import doctest
154    doctest.testmod()
155
156