"""
Replace headers by appropriate images:
text
becomes

The URL can be configured via the URL parameter: it should be a format string
accepting header_level and text attributes, e.g.
'img/%(header_level)d/%(text)s' (which is the example used above).
Additionally, if md is the Markdown instance used, md.image_headers will
contain a list of (header_level, text) tuples (where header_level is the
element name, typically h1 or h2).
"""
# Copyright (c) 2008, 2009 Joachim Schipper
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
import markdown
import itertools
class ImageHeadersProcessor(markdown.treeprocessors.Treeprocessor):
def __init__(self, config, md):
self.config = config
self.md = md
def run(self, doc):
self.md.image_headers = []
for elt in itertools.chain(*(doc.findall('h%d' % level) for level in xrange(1, 5))):
# Replace text of element by an image representing that
# text
self.md.image_headers.append((elt.tag, elt.text))
elt.insert(0, markdown.etree.Element('img', {'alt': elt.text, 'src': self.config['URL'][0] % {'header_level': elt.tag, 'text': elt.text}}))
elt.text = ''
class ImageHeadersExtension(markdown.Extension):
def __init__(self, configs):
self.config = {'URL': ['img/%(header_level)d/%(text)s', 'URL format string for images']}
for k, v in configs:
assert(self.config.has_key(k))
self.config[k][0] = v
def extendMarkdown(self, md, md_globals):
md.treeprocessors.add('ImageHeaders', ImageHeadersProcessor(self.config, md), '>inline')
def makeExtension(configs={}):
return ImageHeadersExtension(configs)