Skip to content

Instantly share code, notes, and snippets.

@ericmoritz
Created September 14, 2010 01:41
Show Gist options
  • Save ericmoritz/578389 to your computer and use it in GitHub Desktop.
Save ericmoritz/578389 to your computer and use it in GitHub Desktop.
"""Converts Restructured Text into a HTML5 friendly format"""
from docutils.writers.html4css1 import HTMLTranslator, Writer
from docutils.core import publish_parts
from docutils import frontend, nodes, utils, writers, languages, io
import re
class HTML5Translator(HTMLTranslator):
def visit_section(self, node):
self.section_level += 1
self.body.append(
self.starttag(node, 'section'))
def depart_section(self, node):
self.section_level -= 1
self.body.append('</section>\n')
def visit_title(self, node):
"""Only 6 section levels are supported by HTML."""
check_id = 0
close_tag = '</p>\n'
if isinstance(node.parent, nodes.topic):
self.body.append(
self.starttag(node, 'p', '', CLASS='topic-title first'))
elif isinstance(node.parent, nodes.sidebar):
self.body.append(
self.starttag(node, 'p', '', CLASS='sidebar-title'))
elif isinstance(node.parent, nodes.Admonition):
self.body.append(
self.starttag(node, 'p', '', CLASS='admonition-title'))
elif isinstance(node.parent, nodes.table):
self.body.append(
self.starttag(node, 'caption', ''))
close_tag = '</caption>\n'
elif isinstance(node.parent, nodes.document):
self.body.append(self.starttag(node, 'h1', '', CLASS='title'))
close_tag = '</h1>\n'
self.in_document_title = len(self.body)
else:
assert isinstance(node.parent, nodes.section)
h_level = self.section_level + self.initial_header_level - 1
atts = {}
if (len(node.parent) >= 2 and
isinstance(node.parent[1], nodes.subtitle)):
atts['CLASS'] = 'with-subtitle'
self.body.append(
self.starttag(node, 'h%s' % h_level, '', **atts))
atts = {}
if node.hasattr('refid'):
atts['class'] = 'toc-backref'
atts['href'] = '#' + node['refid']
if atts:
close_tag = '</h%s>\n' % (h_level)
else:
close_tag = '</h%s>\n' % (h_level)
self.context.append(close_tag)
def write_colspecs(self):
for node in self.colspecs:
self.body.append(self.emptytag(node, 'col'))
self.colspecs = []
def visit_table(self, node):
classes = 'docutils'
self.body.append(
self.starttag(node, 'table', CLASS=classes))
def ReST2HTML(src):
writer = Writer()
writer.translator_class = HTML5Translator
html = publish_parts(source=data['body_source'],
writer=writer)["fragment"]
html = re.sub(r'valign="[^"]+"', '', data['body'])
return html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment