Search

Recent

Tags

Rendering MediaWiki markup in reStructuredText

Filed under Python, hacks on oct 22, 2009

For my django-restwiki project, I was looking for a way to be able to support MediaWiki formatting, to allow for easier transitions between wiki articles. On pypi I ran across the mwlib package.

# docutils
from docutils.parsers.rst import directives, Parser
# mwlib
from mwlib.dummydb import DummyDB
from mwlib.uparser import parseString
from mwlib.xhtmlwriter import MWXHTMLWriter, preprocess
# elementtree (used by mwlib XHTML renderer)
try:
    import xml.etree.ElementTree as ET
except:
    from elementtree import ElementTree as ET

def mwlib_directive(name, arguments, options, content, lineno,
                    content_offset, block_text, state, state_machine):
    # empty wikidb
    db = DummyDB()
    # run parser and pre-processors
    parsed = parseString(title='Export', raw=u'\n'.join(content), wikidb=db)
    preprocess(parsed)
    # write XHTML
    xhtml = MWXHTMLWriter()
    xhtml.writeBook(parsed)
    # remove the H1 heading (title) from the document
    article = xhtml.xmlbody.getchildren()[0]
    article.remove(article.getchildren()[0]) # remove caption
    # render to string
    block = ET.tostring(xhtml.xmlbody)
    return [nodes.raw('', block, format='html')]

# this directive allows content
mwlib_directive.content = 1
# add processors
directives.register_directive('mw', mwlib_directive)
directives.register_directive('mediawiki', mwlib_directive)

Now we can use MediaWiki formatting in our reStructuredText document:

.. mediawiki::

    == MediaWiki article ==

    This is an '''example''' [http://href.be/0c MediaWiki] article.

    == reStructuredText ==

    Is the ''bomb''!

Add to

Post your feedback

You can use this form to leave your feedback. Your insights are always appreciated.

Tools

View document source in text/plain