Skip to content

Instantly share code, notes, and snippets.

@arthurk
Created March 21, 2010 16:01
Show Gist options
  • Save arthurk/339373 to your computer and use it in GitHub Desktop.
Save arthurk/339373 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# encoding: utf-8
import sys
import os
from docutils.core import publish_parts
from docutils.writers import html4css1
class MyHTMLWriter(html4css1.Writer):
"""
This docutils writer will use the MyHTMLTranslator class.
"""
def __init__(self):
html4css1.Writer.__init__(self)
self.translator_class = MyHTMLTranslator
class MyHTMLTranslator(html4css1.HTMLTranslator):
"""
This is a translator class for the docutils system.
It will append a unique id attribute to paragraphs.
"""
def __init__(self, document):
html4css1.HTMLTranslator.__init__(self, document)
self.paragraph_counter = 0
def visit_paragraph(self, node):
if self.should_be_compact_paragraph(node):
self.context.append('')
else:
self.body.append(self.starttag(node, 'p', '', **{
'ids': ['para-%s' % self.paragraph_counter,]}))
self.context.append('</p>\n')
def depart_paragraph(self, node):
self.body.append(self.context.pop())
self.paragraph_counter += 1
def main():
text = """foobar
This is some text from an online boo
foo bar foobar
bar foo xasdasd"""
parts = publish_parts(source=text, writer=MyHTMLWriter())
print parts['fragment']
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment