mdx_wikipath.py 3.02 KB
Newer Older
Piotr Mitros committed
1 2
#!/usr/bin/env python

3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
'''
Wikipath Extension for Python-Markdown
======================================

Converts [Link Name](wiki:ArticleName) to relative links pointing to article.  Requires Python-Markdown 2.0+

Basic usage:

    >>> import markdown
    >>> text = "Some text with a [Link Name](wiki:ArticleName)."
    >>> html = markdown.markdown(text, ['wikipath(base_url="/wiki/view/")'])
    >>> html
    u'<p>Some text with a <a class="wikipath" href="/wiki/view/ArticleName/">Link Name</a>.</p>'

Dependencies:
* [Python 2.3+](http://python.org)
* [Markdown 2.0+](http://www.freewisdom.org/projects/python-markdown/)
'''

Piotr Mitros committed
22 23

import markdown
24 25 26 27 28 29 30
try:
    # Markdown 2.1.0 changed from 2.0.3. We try importing the new version first,
    # but import the 2.0.3 version if it fails
    from markdown.util import etree
except:
    from markdown import etree

Piotr Mitros committed
31

32
class WikiPathExtension(markdown.Extension):
Piotr Mitros committed
33 34 35
    def __init__(self, configs):
        # set extension defaults
        self.config = {
36 37
                        'default_namespace': ['edX', 'Default namespace for when one isn\'t specified.'],
                        'html_class': ['wikipath', 'CSS hook. Leave blank for none.']
Piotr Mitros committed
38
        }
39

Piotr Mitros committed
40
        # Override defaults with user settings
41
        for key, value in configs:
Piotr Mitros committed
42 43
            # self.config[key][0] = value
            self.setConfig(key, value)
44

Piotr Mitros committed
45
    def extendMarkdown(self, md, md_globals):
46
        self.md = md
47

48
        # append to end of inline patterns
49
        WIKI_RE = r'\[(?P<linkTitle>.+?)\]\(wiki:(?P<wikiTitle>[a-zA-Z\d/_-]*)\)'
50
        wikiPathPattern = WikiPath(WIKI_RE, self.config)
51 52 53
        wikiPathPattern.md = md
        md.inlinePatterns.add('wikipath', wikiPathPattern, "<reference")

54

55 56 57 58
class WikiPath(markdown.inlinepatterns.Pattern):
    def __init__(self, pattern, config):
        markdown.inlinepatterns.Pattern.__init__(self, pattern)
        self.config = config
59 60

    def handleMatch(self, m):
61 62 63
        article_title = m.group('wikiTitle')
        if article_title.startswith("/"):
            article_title = article_title[1:]
64

65 66
        if not "/" in article_title:
            article_title = self.config['default_namespace'][0] + "/" + article_title
67

68
        url = "../" + article_title
69 70 71 72
        label = m.group('linkTitle')
        a = etree.Element('a')
        a.set('href', url)
        a.text = label
73

74 75
        if self.config['html_class'][0]:
            a.set('class', self.config['html_class'][0])
76

Piotr Mitros committed
77
        return a
78

79 80
    def _getMeta(self):
        """ Return meta data or config data. """
81 82
        base_url = self.config['base_url'][0]
        html_class = self.config['html_class'][0]
Piotr Mitros committed
83 84
        if hasattr(self.md, 'Meta'):
            if self.md.Meta.has_key('wiki_base_url'):
85
                base_url = self.md.Meta['wiki_base_url'][0]
Piotr Mitros committed
86
            if self.md.Meta.has_key('wiki_html_class'):
87
                html_class = self.md.Meta['wiki_html_class'][0]
88
        return base_url, html_class
Piotr Mitros committed
89

90 91

def makeExtension(configs=None):
92
    return WikiPathExtension(configs=configs)
Piotr Mitros committed
93 94 95 96

if __name__ == "__main__":
    import doctest
    doctest.testmod()