~widelands-dev/widelands-website/django_staticfiles

« back to all changes in this revision

Viewing changes to markdownextensions/semanticwikilinks/mdx_semanticwikilinks.py

  • Committer: Holger Rapp
  • Date: 2009-02-20 12:25:18 UTC
  • Revision ID: holgerrapp@gmx.net-20090220122518-feaq34ta973snnct
Imported wikiapp into our repository, because we did some local changes (users must be logged in to edit wiki pages)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#! /usr/bin/env python
2
 
 
3
 
 
4
 
'''
5
 
SemanticWikiLinks Extension for Python-Markdown
6
 
===============================================
7
 
 
8
 
Adds support for semantic (wiki)links (RDFa).
9
 
 
10
 
Converts links of style `[[rel :: target | label ]]`, where `rel` and `label`
11
 
are optional.
12
 
 
13
 
Customizable with `make_link` option as to what the actual element is.
14
 
 
15
 
 
16
 
Usage
17
 
-----
18
 
 
19
 
    >>> text = "Some text with a [[WikiLink]]."
20
 
    >>> html = markdown.markdown(text, ['semanticwikilinks'])
21
 
    >>> print(html)
22
 
    <p>Some text with a <a href="WikiLink">WikiLink</a>.</p>
23
 
 
24
 
    >>> text = "[[http://activearchives.org/]], [[#id|anchor]], [[../index.html|a relative link]], [[/|an absolute link]], [[/index.html|another absolute link]]"
25
 
    >>> html = markdown.markdown(text, ['semanticwikilinks'])
26
 
    >>> print(html)
27
 
    <p><a href="http://activearchives.org/">http://activearchives.org/</a>, <a href="#id">anchor</a>, <a href="../index.html">a relative link</a>, <a href="/">an absolute link</a>, <a href="/index.html">another absolute link</a></p>
28
 
 
29
 
Define a custom URL builder:
30
 
 
31
 
    >>> from markdown.util import etree
32
 
    >>> def make_rdfa(md, rel, target, label):
33
 
    ...     # `md` is the Markdown instance
34
 
    ...     elt = etree.Element("span")
35
 
    ...     elt.set("property", rel)
36
 
    ...     elt.set("value", target)
37
 
    ...     elt.text = label or target
38
 
    ...     return elt
39
 
 
40
 
    >>> md = markdown.Markdown(extensions=['semanticwikilinks'],
41
 
    ...         extension_configs={'semanticwikilinks' : [('make_link', make_rdfa)]})
42
 
    >>> html = md.convert('[[ Speaker :: Sherry Turkle | Second Self ]]')
43
 
    >>> print(html)
44
 
    <p><span property="aa:Speaker" value="Sherry Turkle">Second Self</span></p>
45
 
 
46
 
Change the default namespace (which is "aa"):
47
 
 
48
 
    >>> md = markdown.Markdown(extensions=['semanticwikilinks'],
49
 
    ...         extension_configs={'semanticwikilinks' : [('namespace', 'mynamespace')]})
50
 
    >>> html = md.convert('[[ Speaker :: Sherry Turkle | Second Self ]]')
51
 
    >>> print(html)
52
 
    <p><a href="Sherry Turkle" rel="mynamespace:Speaker">Second Self</a></p>
53
 
 
54
 
To do
55
 
-----
56
 
 
57
 
- An optional function to wikify names? (It is already possible to achieve
58
 
this with the custom `make_link` function).
59
 
 
60
 
 
61
 
Dependencies
62
 
------------
63
 
 
64
 
* [Markdown 2.0+](http://www.freewisdom.org/projects/python-markdown/)
65
 
 
66
 
 
67
 
Copyright
68
 
---------
69
 
 
70
 
2011, 2012 [The active archives contributors](http://activearchives.org/)
71
 
2011, 2012 [Michael Murtaugh](http://automatist.org/)
72
 
2011, 2012 [Alexandre Leray](http://stdin.fr/)
73
 
 
74
 
All rights reserved.
75
 
 
76
 
This software is released under the modified BSD License. 
77
 
See LICENSE.md for details.
78
 
'''
79
 
 
80
 
 
81
 
import markdown
82
 
try:
83
 
    from markdown import etree
84
 
except ImportError:
85
 
    from markdown.util import etree
86
 
import re
87
 
 
88
 
 
89
 
__version__ = '1.1.1'
90
 
 
91
 
 
92
 
WIKILINK_RE = r"""
93
 
\[\[\s*
94
 
    (?:((?P<namespace>\w+):)?(?P<rel>[^\]#]+?) \s* ::)? \s*
95
 
    (?P<target>.+?) \s*
96
 
    (?:\| \s* (?P<label>.+?) \s*)?
97
 
\]\](?!\])
98
 
""".strip()
99
 
 
100
 
 
101
 
def make_link(md, rel, target, label):
102
 
    a = etree.Element('a')
103
 
    a.set('href', target)
104
 
    if rel:
105
 
        a.set('rel', rel)
106
 
    a.text = label or target
107
 
    return a
108
 
 
109
 
 
110
 
def make_wikilink(md, rel, target, label):
111
 
    # Turns a link from Syntax [[ Page Name | linktext ]]
112
 
    a = etree.Element('a')
113
 
    a.set('href', '/wiki/' + target)
114
 
    a.set('class', 'wikilink')
115
 
    if rel:
116
 
        pass
117
 
    a.text = label or target
118
 
    return a
119
 
 
120
 
 
121
 
class SemanticWikiLinkExtension(markdown.Extension):
122
 
 
123
 
    def __init__(self, *args, **kwargs):
124
 
        self.config = {
125
 
            'make_link': [make_wikilink, 'Callback to convert link parts into an HTML/etree element'],
126
 
            'namespace': ['aa', 'Default namespace'],
127
 
        }
128
 
        super(SemanticWikiLinkExtension, self).__init__(*args, **kwargs)
129
 
 
130
 
    def extendMarkdown(self, md, md_globals):
131
 
        self.md = md
132
 
 
133
 
        # append to end of inline patterns
134
 
        ext = SemanticWikiLinkPattern(self.config, md)
135
 
        md.inlinePatterns.add('semanticwikilink', ext, '<not_strong')
136
 
 
137
 
 
138
 
class SemanticWikiLinkPattern(markdown.inlinepatterns.Pattern):
139
 
 
140
 
    def __init__(self, config, md=None):
141
 
        markdown.inlinepatterns.Pattern.__init__(self, '', md)
142
 
        self.compiled_re = re.compile(
143
 
            '^(.*?)%s(.*?)$' % WIKILINK_RE, re.DOTALL | re.X)
144
 
        self.config = config
145
 
 
146
 
    def getCompiledRegExp(self):
147
 
        return self.compiled_re
148
 
 
149
 
    def handleMatch(self, m):
150
 
        """Returns etree."""
151
 
        d = m.groupdict()
152
 
        fn = self.config['make_link'][0]
153
 
        namespace = d.get('namespace') or self.config['namespace'][0]
154
 
        rel = d.get('rel')
155
 
 
156
 
        if rel:
157
 
            rel = '%s:%s' % (namespace, d.get('rel'))
158
 
 
159
 
        return fn(self.markdown, rel, d.get('target'), d.get('label'))
160
 
 
161
 
 
162
 
def makeExtension(*args, **kwargs):
163
 
    return SemanticWikiLinkExtension(*args, **kwargs)
164
 
 
165
 
 
166
 
if __name__ == '__main__':
167
 
    import doctest
168
 
    doctest.testmod()