mdx_wikipath.py 2.98 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 36
    def __init__(self, configs):
        # set extension defaults
        self.config = {
                        'base_url' : ['/', 'String to append to beginning or URL.'],
37
                        'html_class' : ['wikipath', 'CSS hook. Leave blank for none.']
Piotr Mitros committed
38 39 40 41 42 43
        }
        
        # Override defaults with user settings
        for key, value in configs :
            # self.config[key][0] = value
            self.setConfig(key, value)
44 45
                
                
Piotr Mitros committed
46
    def extendMarkdown(self, md, md_globals):
47 48 49 50
        self.md = md
        
        # append to end of inline patterns
        WIKI_RE =  r'\[(?P<linkTitle>.+?)\]\(wiki:(?P<wikiTitle>[a-zA-Z\d/_-]*)\)'
51
        wikiPathPattern = WikiPath(WIKI_RE, self.config)
52 53 54 55 56 57 58 59
        wikiPathPattern.md = md
        md.inlinePatterns.add('wikipath', wikiPathPattern, "<reference")

class WikiPath(markdown.inlinepatterns.Pattern):
    def __init__(self, pattern, config):
        markdown.inlinepatterns.Pattern.__init__(self, pattern)
        self.config = config
    
Piotr Mitros committed
60
    def handleMatch(self, m) :
61 62 63 64
        article_title = m.group('wikiTitle')
        if article_title.startswith("/"):
            article_title = article_title[1:]
        
65
        url = self.config['base_url'][0] + article_title
66 67 68 69 70
        label = m.group('linkTitle')
        a = etree.Element('a')
        a.set('href', url)
        a.text = label
        
71 72
        if self.config['html_class'][0]:
            a.set('class', self.config['html_class'][0])
73
            
Piotr Mitros committed
74 75
        return a
        
76 77
    def _getMeta(self):
        """ Return meta data or config data. """
78 79
        base_url = self.config['base_url'][0]
        html_class = self.config['html_class'][0]
Piotr Mitros committed
80 81
        if hasattr(self.md, 'Meta'):
            if self.md.Meta.has_key('wiki_base_url'):
82
                base_url = self.md.Meta['wiki_base_url'][0]
Piotr Mitros committed
83
            if self.md.Meta.has_key('wiki_html_class'):
84
                html_class = self.md.Meta['wiki_html_class'][0]
85
        return base_url, html_class
Piotr Mitros committed
86 87

def makeExtension(configs=None) :
88
    return WikiPathExtension(configs=configs)
Piotr Mitros committed
89 90 91 92

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