Created
August 27, 2012 11:35
-
-
Save slig/3487734 to your computer and use it in GitHub Desktop.
admonitions extension for python-markdown
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
import markdown | |
from markdown.util import etree | |
class AdmonitionExtension(markdown.Extension): | |
def extendMarkdown(self, md, md_globals): | |
md.registerExtension(self) | |
md.parser.blockprocessors.add('admonition', | |
AdmonitionProcessor(md.parser, self.config), | |
'_begin') | |
class AdmonitionProcessor(markdown.blockprocessors.BlockProcessor): | |
CLASSNAME = 'admonition' | |
CLASSNAME_TITLE = 'admonition-title' | |
RE = re.compile(r'(?:^|\n)!!!\ ?([\w\-]+)(?:\ "?([^"\n]+)"?)?') | |
def __init__(self, parser, config): | |
markdown.blockprocessors.BlockProcessor.__init__(self, parser) | |
self.config = config | |
def test(self, parent, block): | |
sibling = self.lastChild(parent) | |
return self.RE.search(block) or \ | |
(block.startswith(' ' * self.tab_length) and sibling and \ | |
sibling.get('class', '').find(self.CLASSNAME) != -1) | |
def run(self, parent, blocks): | |
sibling = self.lastChild(parent) | |
block = blocks.pop(0) | |
m = self.RE.search(block) | |
if m: | |
block = block[m.end() + 1:] # remove the first line | |
block, theRest = self.detab(block) | |
if m: | |
klass, title = self.get_class_and_title(m.group(1), m.group(2)) | |
div = etree.SubElement(parent, 'div') | |
div.set('class', u'%s %s' % (self.CLASSNAME, klass)) | |
if title: | |
p = etree.SubElement(div, 'p') | |
p.text = title | |
p.set('class', self.CLASSNAME_TITLE) | |
else: | |
div = sibling | |
self.parser.parseChunk(div, block) | |
if theRest: | |
# This block contained unindented line(s) after the first indented | |
# line. Insert these lines as the first block of the master blocks | |
# list for future processing. | |
blocks.insert(0, theRest) | |
def get_class_and_title(self, klass, title): | |
styles = self.config.get('types', None) | |
if styles and styles.get(klass, None): | |
style = styles.get(klass) | |
return style.get('className', klass), title or style.get('title', '') | |
else: | |
return klass, title | |
def makeExtension(configs={}): | |
# configs = { | |
# 'style': { | |
# 'note': { | |
# 'className': 'note', | |
# 'title': 'Note', | |
# }, | |
# 'warning': { | |
# 'className': 'warning', | |
# 'title': 'Warning!', | |
# }, | |
# } | |
# } | |
return AdmonitionExtension(configs=configs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment