Skip to content

Instantly share code, notes, and snippets.

@jacobian
Created January 15, 2010 21:41
Show Gist options
  • Save jacobian/278439 to your computer and use it in GitHub Desktop.
Save jacobian/278439 to your computer and use it in GitHub Desktop.
My custom reStructuredText rendering tag for my blog
from django import template
from django.utils.encoding import smart_str, force_unicode
from django.utils.safestring import mark_safe
import docutils.nodes
from docutils.core import publish_parts
from docutils.writers import html4css1
register = template.Library()
def restructuredtext(value):
parts = publish_parts(
source = smart_str(value),
writer = HTMLWriter(),
settings_overrides = {
'initial_header_level': 3,
'footnote_references': 'superscript',
}
)
return mark_safe(force_unicode(parts['fragment']))
class HTMLWriter(html4css1.Writer):
def __init__(self):
html4css1.Writer.__init__(self)
self.translator_class = HTMLTranslator
class HTMLTranslator(html4css1.HTMLTranslator):
#
# Remove the stupid "border=1" default on tables.
#
def visit_table(self, node):
self.body.append(self.starttag(node, 'table', CLASS='docutils'))
#
# Prevent <h3> from becoming <h3><a id=...>
#
def visit_title(self, node, move_ids=1):
if isinstance(node.parent, docutils.nodes.Admonition):
self.body.append(self.starttag(node, 'p', '', CLASS='admonition-title'))
self.context.append("</p>\n")
else:
html4css1.HTMLTranslator.visit_title(self, node)
#
# Avoid doing <blockquote><ul>...
# Adapted from http://thread.gmane.org/gmane.text.docutils.user/742/focus=804
#
_suppress_blockquote_child_nodes = (docutils.nodes.bullet_list,
docutils.nodes.enumerated_list,
docutils.nodes.definition_list,
docutils.nodes.literal_block,
docutils.nodes.doctest_block,
docutils.nodes.line_block,
docutils.nodes.table)
def visit_block_quote(self, node):
if len(node.children) != 1 or not isinstance(node.children[0], self._suppress_blockquote_child_nodes):
html4css1.HTMLTranslator.visit_block_quote(self, node)
def depart_block_quote(self, node):
if len(node.children) != 1 or not isinstance(node.children[0], self._suppress_blockquote_child_nodes):
html4css1.HTMLTranslator.depart_block_quote(self, node)
#
# Avoid using reserved words in section titles
#
def visit_section(self, node):
node['ids'] = ['s-' + i for i in node.get('ids', [])]
html4css1.HTMLTranslator.visit_section(self, node)
restructuredtext.is_safe = True
register.filter(restructuredtext)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment