Completed
Push — master ( 32cfa8...ec62d3 )
by Dongxin
48s
created

WikiLinks.__init__()   A

Complexity

Conditions 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
1
'''
2
WikiLinks Extension for Python-Markdown
3
======================================
4
5
Converts [[WikiLinks]] to relative links.
6
7
See <https://pythonhosted.org/Markdown/extensions/wikilinks.html>
8
for documentation.
9
10
Original code Copyright [Waylan Limberg](http://achinghead.com/).
11
12
All changes Copyright The Python Markdown Project
13
14
License: [BSD](http://www.opensource.org/licenses/bsd-license.php)
15
16
'''
17
18
from __future__ import absolute_import
19
from __future__ import unicode_literals
20
from . import Extension
21
from ..inlinepatterns import Pattern
22
from ..util import etree
23
import re
24
25
26
def build_url(label, base, end):
27
    """ Build a url from the label, a base, and an end. """
28
    clean_label = re.sub(r'([ ]+_)|(_[ ]+)|([ ]+)', '_', label)
29
    return '%s%s%s' % (base, clean_label, end)
30
31
32
class WikiLinkExtension(Extension):
33
34
    def __init__(self, *args, **kwargs):
35
        self.config = {
36
            'base_url': ['/', 'String to append to beginning or URL.'],
37
            'end_url': ['/', 'String to append to end of URL.'],
38
            'html_class': ['wikilink', 'CSS hook. Leave blank for none.'],
39
            'build_url': [build_url, 'Callable formats URL from label.'],
40
        }
41
42
        super(WikiLinkExtension, self).__init__(*args, **kwargs)
43
44
    def extendMarkdown(self, md, md_globals):
45
        self.md = md
46
47
        # append to end of inline patterns
48
        WIKILINK_RE = r'\[\[([\w0-9_ -]+)\]\]'
49
        wikilinkPattern = WikiLinks(WIKILINK_RE, self.getConfigs())
50
        wikilinkPattern.md = md
51
        md.inlinePatterns.add('wikilink', wikilinkPattern, "<not_strong")
52
53
54
class WikiLinks(Pattern):
55
    def __init__(self, pattern, config):
56
        super(WikiLinks, self).__init__(pattern)
57
        self.config = config
58
59
    def handleMatch(self, m):
60
        if m.group(2).strip():
61
            base_url, end_url, html_class = self._getMeta()
62
            label = m.group(2).strip()
63
            url = self.config['build_url'](label, base_url, end_url)
64
            a = etree.Element('a')
65
            a.text = label
66
            a.set('href', url)
67
            if html_class:
68
                a.set('class', html_class)
69
        else:
70
            a = ''
71
        return a
72
73
    def _getMeta(self):
74
        """ Return meta data or config data. """
75
        base_url = self.config['base_url']
76
        end_url = self.config['end_url']
77
        html_class = self.config['html_class']
78
        if hasattr(self.md, 'Meta'):
79
            if 'wiki_base_url' in self.md.Meta:
80
                base_url = self.md.Meta['wiki_base_url'][0]
81
            if 'wiki_end_url' in self.md.Meta:
82
                end_url = self.md.Meta['wiki_end_url'][0]
83
            if 'wiki_html_class' in self.md.Meta:
84
                html_class = self.md.Meta['wiki_html_class'][0]
85
        return base_url, end_url, html_class
86
87
88
def makeExtension(*args, **kwargs):
89
    return WikiLinkExtension(*args, **kwargs)
90