forked from plugboy/mdx_custom_span_class
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcustom-span-class.py
72 lines (50 loc) · 1.99 KB
/
custom-span-class.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
"""
Markdown Custom class extension for Python-Markdown
=========================================
Markdown extension that allows defining span element
with custom class for a given text. Usage:
>>> import markdown
>>> md = markdown.Markdown(extensions=['custom_span_class'])
>>> md.convert('i love !!text-alert|spam!!')
u'<p>i love <span class="text-alert">spam</span></p>'
>>> md.convert('i love !!|spam!!')
u'<p>i love !!|spam!!</p>'
>>> md.convert('i love !!text-alert|!!')
u'<p>i love !!text-alert|!!</p>'
>>> md.convert('i love !! |spam!!')
u'<p>i love !! |spam!!</p>'
If the | symbol causes conflicts with your Markdown tables, use ^ instead of |.
copyright @2014 Konrad Wasowicz <[email protected]>
"""
from __future__ import absolute_import
from __future__ import unicode_literals
import markdown
from markdown import Extension
from markdown.preprocessors import Preprocessor
from markdown.inlinepatterns import Pattern
CUSTOM_CLS_RE = r'[!]{2}(?P<class>.+?)[|\^](?P<text>.+?(?=[!]{2}))(?=(?P<lookahead>[!]{3}))?(?(lookahead)(?P<exclaim>!))[!]{2}'
class CustomSpanClassExtension(Extension):
""" Extension class for markdown """
def extendMarkdown(self, md, md_globals):
md.inlinePatterns["custom_span_class"] = CustomSpanClassPattern(CUSTOM_CLS_RE, md)
class CustomSpanClassPattern(Pattern):
def handleMatch(self, matched):
"""
If string matched
regexp expression create
new span elem with given class
"""
cls = matched.group("class")
text = matched.group("text")
exclaim_ending = matched.group("exclaim")
if exclaim_ending is not None:
text += "!"
elem = markdown.util.etree.Element("span")
elem.set("class", cls)
elem.text = markdown.util.AtomicString(text)
return elem
def makeExtension(*args, **kwargs):
return CustomSpanClassExtension(*args, **kwargs)
if __name__ == "__main__":
import doctest
doctest.testmod()