Commits

Anonymous committed 2c59937

conforming to PEP8 and PyFlakes

  • Participants
  • Parent commits c48161e

Comments (0)

Files changed (4)

 
 __docformat__ = 'reStructuredText'
 
-import os
 import re
-import docutils
 from docutils import nodes, writers, frontend
 from docutils.math import pick_math_environment
-from genshi.builder import tag, Fragment
+from genshi.builder import tag
 from genshi.output import XHTMLSerializer
 from genshi.core import Markup
 
+
 class HTML5Writer(writers.Writer):
 
     supported = ('html', 'html5', 'html5css3')
         'HTML5 Specific Options',
         None, (
         ('Specify comma separated list of stylesheet URLs.',
-          ['--stylesheet'],
-          {'metavar': '<URL or path>', 'default': None, }),
+            ['--stylesheet'],
+            {'metavar': '<URL or path>', 'default': None, }),
         ('Specify comma separated list of script URLs.',
-          ['--script'],
-          {'metavar': '<URL or path>', 'default': None, }),
+            ['--script'],
+            {'metavar': '<URL or path>', 'default': None, }),
         ("Don't indent output", ['--no-indent'],
             {'default': 1, 'action': 'store_false', 'dest': 'indent_output'}),
         ('Specify the maximum width (in characters) for options in option '
          'lists.  Longer options will span an entire row of the table used '
-         'to render the option list. Default is 0 characters which means "no limit". ',
+         'to render the option list. Default is 0 characters which means '
+         '"no limit". ',
             ['--option-limit'],
             {'default': 0, 'metavar': '<level>',
              'validator': frontend.validate_nonnegative_int}),
-    ))
+        )
+    )
 
     settings_defaults = {'tab_width': 4}
 
         return
 
 
-
 class ElemStack(object):
     def __init__(self, settings):
         self.stack = []
             result.append(indentation)
         result.append(element)
         if self.indent_output and indent:
-            indentation = '\n' + self.indent_width * (self.indent_level - 1) * ' '
+            indentation = '\n' + self.indent_width * \
+                          (self.indent_level - 1) * ' '
             result.append(indentation)
         return result
 
         return result
 
 
-
 dv = 'default_visit'
 dp = 'default_departure'
 pass_ = 'no_op'
 
+
 class HTML5Translator(nodes.NodeVisitor):
 
     rst_terms = {
-        # 'term': ('tag', 'visit_func', 'depart_func', use_term_in_class, indent_elem)
-        # use_term_in_class and indent_elem are optionals. If not given, the default is False, True
+        # 'term': ('tag', 'visit_func', 'depart_func', use_term_in_class,
+        #          indent_elem)
+        # use_term_in_class and indent_elem are optionals.
+        # If not given, the default is False, True
         'Text': (None, 'visit_Text', None),
         'abbreviation': ('abbr', dv, dp),
         'acronym': (None, dv, dp),
         'caption': ('figcaption', dv, dp, False),
         'caution': ('aside', 'visit_aside', 'depart_aside', True),
         'citation': (None, 'visit_citation', 'depart_citation', True),
-        'citation_reference': ('a', 'visit_citation_reference', 'depart_citation_reference', True, False),
+        'citation_reference': ('a', 'visit_citation_reference',
+                               'depart_citation_reference', True, False),
         'classifier': (None, 'visit_classifier', None),
         'colspec': ('col', dv, 'depart_colspec'),
         'comment': (None, 'skip_node', None),
         'definition_list_item': (None, 'do_nothing', None),
         'description': ('td', dv, dp),
         'docinfo': (None, 'visit_docinfo', 'depart_docinfo', True),
-        'doctest_block': ('pre', 'visit_literal_block', 'depart_literal_block', True),
+        'doctest_block': ('pre', 'visit_literal_block',
+                          'depart_literal_block', True),
         'document': (None, 'visit_document', 'depart_document'),
         'emphasis': ('em', dv, dp, False, False),
         'entry': (None, dv, 'depart_entry'),
         'figure': (None, dv, dp),
         'footer': (None, dv, dp),
         'footnote': (None, 'visit_citation', 'depart_citation', True),
-        'footnote_reference': ('a', 'visit_label', 'depart_citation_reference', True, False),
+        'footnote_reference': ('a', 'visit_label',
+                               'depart_citation_reference', True, False),
         'generated': (None, 'do_nothing', None),
         'header': (None, dv, dp),
         'hint': ('aside', 'visit_aside', 'depart_aside', True),
         'line_block': ('pre', 'visit_line_block', 'depart_line_block', True),
         'list_item': ('li', dv, dp),
         'literal': ('code', 'visit_literal', None),
-        'literal_block': ('pre', 'visit_literal_block', 'depart_literal_block'),
+        'literal_block': ('pre', 'visit_literal_block',
+                          'depart_literal_block'),
         'math': (None, 'visit_math_block', None),
         'math_block': (None, 'visit_math_block', None),
         'meta': (None, 'visit_meta', None),
         'option_list': (None, 'visit_docinfo', 'depart_docinfo', True),
         'option_list_item': ('tr', dv, dp),
         'option_string': (None, 'do_nothing', None),
-        'organization': (None, 'visit_field_list_item', 'depart_field_list_item'),
+        'organization': (None, 'visit_field_list_item',
+                         'depart_field_list_item'),
         'paragraph': ('p', 'visit_paragraph', dp),
         'pending': (None, dv, dp),
-        'problematic': ('a', 'visit_problematic', 'depart_reference', True, False),
+        'problematic': ('a', 'visit_problematic', 'depart_reference', True,
+                        False),
         'raw': (None, 'visit_raw', None),
-        'reference': ('a', 'visit_reference', 'depart_reference', False, False),
+        'reference': ('a', 'visit_reference', 'depart_reference', False,
+                      False),
         'revision': (None, 'visit_field_list_item', 'depart_field_list_item'),
         'row': ('tr', 'visit_row', 'depart_row'),
         'rubric': ('p', dv, 'depart_rubric', True),
         Map terms to visit and departure functions
         '''
         for term, spec in HTML5Translator.rst_terms.items():
-            visit_func = spec[1] and getattr(HTML5Translator, spec[1], HTML5Translator.unknown_visit)
-            depart_func = spec[2] and getattr(HTML5Translator, spec[2], HTML5Translator.unknown_departure)
+            visit_func = spec[1] and \
+                getattr(HTML5Translator, spec[1],
+                        HTML5Translator.unknown_visit)
+            depart_func = spec[2] and \
+                getattr(HTML5Translator, spec[2],
+                        HTML5Translator.unknown_departure)
             if visit_func:
                 setattr(HTML5Translator, 'visit_' + term, visit_func)
             if depart_func:
         nodes.NodeVisitor.__init__(self, document)
         self.heading_level = 0
         self.context = ElemStack(document.settings)
-        self.template = '<!DOCTYPE html>\n<html{language}>\n<head>{head}</head>\n' \
-                        '<body>{body}</body>\n</html>'
+        self.template = '<!DOCTYPE html>\n<html{language}>\n' \
+                        '<head>{head}</head>\n<body>{body}</body>\n</html>'
         self.head = []
-        self.head.append(tag.meta(charset=self.document.settings.output_encoding))
+        self.head.append(
+            tag.meta(charset=self.document.settings.output_encoding))
         self.add_stylesheets(document.settings.stylesheet)
         self.add_scripts(document.settings.script)
         self._map_terms_to_functions()
         return
 
     def add_stylesheets(self, stylesheets):
-        stylesheets = stylesheets and re.sub(r'\s+', '', stylesheets).split(',') or []
+        stylesheets = stylesheets and \
+            re.sub(r'\s+', '', stylesheets).split(',') or []
         for href in stylesheets:
             self.head.append(tag.link(rel='stylesheet', href=href))
         return
         language = ' lang="%s"' % self.document.settings.language_code
         self.head = ''.join(XHTMLSerializer()(tag(*self.head)))
         self.body = ''.join(XHTMLSerializer()(tag(*self.context.stack)))
-        return self.template.format(language=language, head=self.head, body=self.body)
+        return self.template.format(language=language, head=self.head,
+                                    body=self.body)
 
     def set_next_elem_attr(self, name, value):
         '''
-        The given attribute will be inserted into the attributes of the next element.
+        The given attribute will be inserted into the attributes of the
+        next element.
         '''
         self.next_elem_attr = {name: value}
 
     def parse(self, node):
         '''
-        Get tag name, indentantion and correct attributes of a node according to its class
+        Get tag name, indentantion and correct attributes of a node according
+        to its class
         '''
         node_class_name = node.__class__.__name__
         spec = self.rst_terms[node_class_name]
             node['classes'].insert(0, node_class_name)
 
         attrs = {}
-        replacements = {'refuri': 'href', 'uri': 'src', 'refid': 'href',
-            'morerows': 'rowspan', 'morecols': 'colspan', 'classes': 'class', 'ids': 'id', }
-        ignores = ('names', 'dupnames', 'bullet', 'enumtype', 'colwidth', 'stub', 'backrefs',
-                   'auto', 'anonymous', )
+        replacements = {
+            'refuri': 'href', 'uri': 'src', 'refid': 'href',
+            'morerows': 'rowspan', 'morecols': 'colspan', 'classes': 'class',
+            'ids': 'id',
+        }
+        ignores = (
+            'names', 'dupnames', 'bullet', 'enumtype', 'colwidth', 'stub',
+            'backrefs', 'auto', 'anonymous',
+        )
         for k, v in node.attributes.items():
             if not v:
                 continue
         else:
             return default
 
-
     def default_visit(self, node):
         '''
         Initiate a new context to store inner HTML5 elements.
         '''
-        if 'ids' in node and self.once_attr('expand_id_to_anchor', default=True):
+        if 'ids' in node and self.once_attr('expand_id_to_anchor',
+                                            default=True):
             '''
-            create an anchor <a id=id></a> for each id found before the current element.
+            create an anchor <a id=id></a> for each id found before the
+            current element.
             '''
             for id in node['ids']:
                 self.context.begin_elem()
 
     def default_departure(self, node):
         '''
-        Create the node's corresponding HTML5 element and combine it with its stored context.
+        Create the node's corresponding HTML5 element and combine it with its
+        stored context.
         '''
         name, indent, attr = self.parse(node)
         elem = getattr(tag, name)(**attr)
         Determine if the <p> tags around paragraph ``node`` can be omitted.
         Based on :func:`docutils.writers.html4css1.HTMLTranslator.should_be_compact_paragraph`
         """
-        if (isinstance(node.parent, (nodes.document, nodes.compound, nodes.block_quote,
-           nodes.system_message, )) or node['classes'] or 'paragraph' != node.__class__.__name__):
+        # extra oarenthesis for pep8 alignment conformity
+        if ((isinstance(node.parent, (nodes.document, nodes.compound,
+                        nodes.block_quote, nodes.system_message, )) or
+             node['classes'] or 'paragraph' != node.__class__.__name__)):
             return False
-        first = isinstance(node.parent[0], nodes.label) # skip label
+        first = isinstance(node.parent[0], nodes.label)  # skip label
         for child in node.parent.children[first:]:
             # only first paragraph can be compact
             if isinstance(child, nodes.Invisible):
     def depart_enumerated_list(self, node):
         '''
         Ordered list.
-        It may have a preffix and suffix that must be handled by CSS3 and javascript to
-        be presented as intended.
+        It may have a preffix and suffix that must be handled by CSS3 and
+        javascript to be presented as intended.
 
         See:
 
         '''
         term = self.context.pop()
         term(' ', tag.span(':', class_='classifier-delimiter'), ' ',
-                           tag.span(node.astext(), class_='classifier'))
+             tag.span(node.astext(), class_='classifier'))
         self.context.append(term)
         raise nodes.SkipNode
 
         self.in_thead = True
         self.default_visit(node)
 
-    def depart_thead(self,node):
+    def depart_thead(self, node):
         self.in_thead = False
         self.default_departure(node)
 
 
     def visit_literal_block(self, node):
         if 'code' in node['classes']:
-            self.context.begin_elem() # <pre>. The next will be for <code>
+            self.context.begin_elem()  # <pre>. The next will be for <code>
         self.preserve_space = True
         self.default_visit(node)
         return
         math_code = node.astext()
         math_env = pick_math_environment(math_code)
         if 'align' in math_env:
-            template = '\\begin{%s}\n%s\n\\end{%s}' % (math_env, math_code, math_env)
+            template = '\\begin{%s}\n%s\n\\end{%s}' % (math_env, math_code,
+                                                       math_env)
             elem = tag.div(template)
-        else: # equation
+        else:  # equation
             template = '\(%s\)' % math_code
             elem = tag.span(template)
         elem(class_='math')
         self.context.append(elem)
-        src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"
+        src = "http://cdn.mathjax.org/mathjax/latest/MathJax.js" \
+              "?config=TeX-AMS-MML_HTMLorMML"
         self.head.append(tag.script(src=src))
         raise nodes.SkipNode
 
         self.default_departure(node)
 
     def visit_field_list_item(self, node):
-        self.context.begin_elem() # tr
+        self.context.begin_elem()  # tr
         self.context.append(tag.th(node.__class__.__name__))
-        self.context.begin_elem() # td
+        self.context.begin_elem()  # td
 
     def depart_field_list_item(self, node):
         self.context.commit_elem(tag.td)
 
     def depart_address(self, node):
         del self.preserve_space
-        self.context.commit_elem(tag.pre(class_='docinfo-' + node.__class__.__name__))
+        self.context.commit_elem(tag.pre(class_='docinfo-' +
+                                         node.__class__.__name__))
         self.depart_field_list_item(node)
 
     def visit_docinfo(self, node):
-        self.context.begin_elem() # table
+        self.context.begin_elem()  # table
         col = tag.col
         self.context.append(col)
         self.context.append(col)
-        self.context.begin_elem() # tbody
+        self.context.begin_elem()  # tbody
 
     def depart_docinfo(self, node):
         self.context.commit_elem(tag.tbody)
 
     def visit_citation(self, node):
         self.visit_docinfo(node)
-        self.context.begin_elem() # tr
+        self.context.begin_elem()  # tr
 
     def depart_citation(self, node):
         # td initiated at depart_label
 
     def depart_option_group(self, node):
         if self.document.settings.option_limit and \
-           len(node.astext()) > self.document.settings.option_limit:
+                len(node.astext()) > self.document.settings.option_limit:
             node['morecols'] = 2
             self.default_departure(node)
-            self.context.commit_elem(tag.tr) # closes this tr
-            self.context.begin_elem() # begins another tr
-            self.context.append(tag.td) # empty td due to colspan
+            self.context.commit_elem(tag.tr)  # closes this tr
+            self.context.begin_elem()  # begins another tr
+            self.context.append(tag.td)  # empty td due to colspan
         else:
             self.default_departure(node)
 
     def depart_label(self, node):
         self.context.append(']', indent=False)
         self.default_departure(node)
-        self.context.begin_elem() # next td
+        self.context.begin_elem()  # next td
 
     '''
     Line blocks use <pre>. lines breaks and spacing are reconstructured
 
     def visit_system_message(self, node):
         self.default_visit(node)
-        self.context.begin_elem() # h1
+        self.context.begin_elem()  # h1
         backrefs = [tag(' ', tag.a(v, href="#" + v)) for v in node['backrefs']]
         node.attributes.setdefault('line', '')
-        text = 'System Message: {type}/{level} ({source} line {line})'.format(**node.attributes)
+        text = 'System Message: {type}/{level} ({source} line ' \
+               '{line})'.format(**node.attributes)
         h1 = tag.h1(text, *backrefs)
         self.context.commit_elem(h1)
         node.attributes = {'classes': []}
         return
 
+
 def main():
     from docutils.core import publish_cmdline, default_description
 
-    description = 'Generates (X)HTML5 documents from standalone reStructuredText sources.' + default_description
+    description = 'Generates (X)HTML5 documents from standalone ' \
+                  'reStructuredText sources.' + default_description
     publish_cmdline(writer=HTML5Writer(), description=description)
 
 if __name__ == '__main__':
-    main()
+    main()
     author='André Felipe Dias',
     author_email='andref.dias@gmailself.com',
     url='https://bitbucket.org/andre_felipe_dias/rst2html5',
-    keywords = ["restructuredtext", "rst", "html5", "doctutils"]    ,
-    description='Generates (X)HTML5 documents from standalone reStructuredText sources',
+    keywords=["restructuredtext", "rst", "html5", "doctutils"],
+    description='Generates (X)HTML5 documents from standalone '
+                'reStructuredText sources',
     long_description=long_description,
     license='MIT License',
     platforms='any',
         'Topic :: Documentation',
         'Topic :: Utilities',
         'Topic :: Text Processing :: Markup :: HTML',
-      ],
+    ],
     zip_safe=False,
     py_modules=['rst2html5'],
     entry_points={
-            'console_scripts': [
-                    'rst2html5 = rst2html5:main',
-            ],
+        'console_scripts': [
+            'rst2html5 = rst2html5:main',
+        ],
     },
 )
 }
 
 title_2 = {
-        'rst': '''
+    'rst': '''
 Level 1
 =======
 
 
 Level 1 Again
 =============''',
-    'out': '<a id="level-1"></a><section><h1>Level 1</h1><p>some text</p></section>'
-           '<a id="level-1-again"></a><section><h1>Level 1 Again</h1></section>',
+    'out': '<a id="level-1"></a><section><h1>Level 1</h1>'
+           '<p>some text</p></section>'
+           '<a id="level-1-again"></a><section><h1>Level 1 Again</h1>'
+           '</section>',
     'indent_output': False,
     'part': 'body',
 }
 
 ...''',
     'out': '<hgroup><h1>Document Title</h1><h2>Subtitle</h2></hgroup>'
-           '<a id="section-title"></a><section><h1>Section Title</h1><p>...</p></section>',
+           '<a id="section-title"></a><section><h1>Section Title</h1>'
+           '<p>...</p></section>',
     'indent_output': False,
     'part': 'body',
 }
 The subtitle processing should deal with indentation
 '''
 subtitle_2 = {
-        'rst': '''
+    'rst': '''
 ================
  Document Title
 ================
 =============
 
 ...''',
-        'out': '''
+    'out': '''
     <hgroup>
         <h1>Document Title</h1>
         <h2>Subtitle</h2>
 paragraph = {
     'rst': 'Lorem    ipsum dolor sit amet,        consectetur '
            'adipiscing          elit.\n'
-            'Vestibulum    dignissim lacinia blandit. Suspendisse potenti.',
+           'Vestibulum    dignissim lacinia blandit. Suspendisse potenti.',
     'out': '<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. '
            'Vestibulum dignissim lacinia blandit. Suspendisse potenti.</p>',
     'indent_output': False,
 
 accented_paragraph = {
     'rst': 'Não há ninguém que ame a dor por si só, que a busque e '
-          'queira tê-la, simplesmente por ser dor...',
+           'queira tê-la, simplesmente por ser dor...',
     'out': '<p>Não há ninguém que ame a dor por si só, que a busque e '
            'queira tê-la, simplesmente por ser dor...</p>',
     'indent_output': False,
 
 This is another one.''',
     'out': "<p>This is a paragraph. It's quite short.</p>"
-               "<blockquote><p>This paragraph will result in an indented "
-               "block of text, typically used for quoting other text."
-               "</p></blockquote><p>This is another one.</p>",
+           "<blockquote><p>This paragraph will result in an indented "
+           "block of text, typically used for quoting other text."
+           "</p></blockquote><p>This is another one.</p>",
     'indent_output': False,
     'part': 'body',
 }
     'out': '''
     <figure>
         <img src="picture.png" alt="map to buried treasure" scale="50" />
-        <figcaption>This is the caption of the figure (a simple paragraph).</figcaption>
+        <figcaption>This is the caption of the figure \
+(a simple paragraph).</figcaption>
     </figure>
 ''',
     'part': 'body'
 ``inline  <pre>   text``
 ''',
     'out': '''
-    <p><em>emphasis</em> <strong>strong emphasis</strong> <cite>interpreted text</cite> \
-<sup>superscript</sup> <em>interpreted text with role</em> <sub>subscript</sub> \
+    <p><em>emphasis</em> <strong>strong emphasis</strong> \
+<cite>interpreted text</cite> <sup>superscript</sup> \
+<em>interpreted text with role</em> <sub>subscript</sub> \
 <code>inline&nbsp;&nbsp;&lt;pre&gt;&nbsp;&nbsp;&nbsp;text</code></p>
 ''',
     'part': 'body'
     'rst': '''This is a paragraph that contains `a link`_.
 
 .. _a link: http://example.com/''',
-    'out': '<p>This is a paragraph that contains <a href="http://example.com/">a link</a>.</p>',
+    'out': '<p>This is a paragraph that contains '
+           '<a href="http://example.com/">a link</a>.</p>',
     'indent_output': False,
     'part': 'body',
 }
 The targets "target1" and "target2" are synonyms; they both
 point to this paragraph.''',
     'out': '''
-    <p>Links to <a href="#target1">target1</a> and <a href="#target2">target2</a>.</p>
+    <p>Links to <a href="#target1">target1</a> and \
+<a href="#target2">target2</a>.</p>
     <a id="target2"></a>
     <a id="target1"></a>
-    <p>The targets "target1" and "target2" are synonyms; they both point to this paragraph.</p>
+    <p>The targets "target1" and "target2" are synonyms; \
+they both point to this paragraph.</p>
 ''',
     'part': 'body'
 }
 .. _archive:
 .. _Doc-SIG: http://mail.python.org/pipermail/doc-sig/''',
     'out': '''
-    <p>Link to <a href="http://mail.python.org/pipermail/doc-sig/">archive</a>.</p>
+    <p>Link to \
+<a href="http://mail.python.org/pipermail/doc-sig/">archive</a>.</p>
 ''',
     'part': 'body'
 }
 
 inline_and_indirect_target = {
-    'rst': '''This is a _`inline hyperlink target` that corresponds to a <target> in doctree.
+    'rst': '''This is a _`inline hyperlink target` that corresponds to \
+a <target> in doctree.
 
 Link to one_.
 
 ''',
 
     'out': '''
-    <p>This is a <a id="inline-hyperlink-target">inline hyperlink target</a> that corresponds \
-to a &lt;target&gt; in doctree.</p>
+    <p>This is a <a id="inline-hyperlink-target">inline hyperlink target</a> \
+that corresponds to a &lt;target&gt; in doctree.</p>
     <p>Link to <a href="#three">one</a>.</p>
     <a id="three"></a>
     <p>Target paragraph.</p>
-    <p>Referencing the <a href="#inline-hyperlink-target">inline hyperlink target</a>.</p>
+    <p>Referencing the \
+<a href="#inline-hyperlink-target">inline hyperlink target</a>.</p>
 ''',
     'part': 'body'
 }
 __ http://www.python.org/
 __ http://docutils.sourceforge.net/''',
     'out': '''
-    <p>Paragraphs contain text and may contain <a href="http://www.python.org/">anonymous \
-hyperlink references</a> (<a href="http://docutils.sourceforge.net/">a second reference</a>).</p>
+    <p>Paragraphs contain text and may contain \
+<a href="http://www.python.org/">anonymous hyperlink references</a> \
+(<a href="http://docutils.sourceforge.net/">a second reference</a>).</p>
 ''',
     'part': 'body',
 }
    Inline markup is supported, e.g. *emphasis*, **strong**, ``literal
    text``, _`hyperlink targets`, and `references <http://www.python.org/>`_.
 ''',
-   'out': '''
+    'out': '''
     <pre>This is a parsed literal block.
     This line is indented.  The next line is blank.
 
-Inline markup is supported, e.g. <em>emphasis</em>, <strong>strong</strong>, <code>literal
-text</code>, <a id="hyperlink-targets">hyperlink targets</a>, and <a href="http://www.python.org/">\
-references</a>.</pre>
+Inline markup is supported, e.g. <em>emphasis</em>, <strong>strong</strong>, \
+<code>literal
+text</code>, <a id="hyperlink-targets">hyperlink targets</a>, \
+and <a href="http://www.python.org/">references</a>.</pre>
 ''',
-   'part': 'body',
+    'part': 'body',
 }
 
-
 parsed_literal_as_code_block = {
     'rst': """.. class:: code language-python
 
     For example, {'rst': rst, 'out':out, ...}
     '''
     return ((v, getattr(module, v)) for v in dir(module)
-        if not v.startswith('__') and isinstance(getattr(module, v), dict))</code></pre>
+        if not v.startswith('__') and isinstance(getattr(module, v), \
+dict))</code></pre>
 """,
     'part': 'body',
 }
             if not v.startswith('__') and isinstance(getattr(module, v), dict))
 """,
     'out': """
-    <pre><code class="python"><span class="k">def</span> <span class="nf">extract_variables</span>\
+    <pre><code class="python"><span class="k">def</span> \
+<span class="nf">extract_variables</span>\
 <span class="p">(</span><span class="n">module</span><span class="p">):</span>
     <span class="sd">'''
     Extract variables of a test data module.
     Variables should be a dict().
     For example, {'rst': rst, 'out':out, ...}
     '''</span>
-    <span class="k">return</span> <span class="p">((</span><span class="n">v</span>\
-<span class="p">,</span> <span class="nb">getattr</span><span class="p">(</span><span class="n">\
-module</span><span class="p">,</span> <span class="n">v</span><span class="p">))</span>\
- <span class="k">for</span> <span class="n">v</span> <span class="ow">in</span> <span class="nb">\
-dir</span><span class="p">(</span><span class="n">module</span><span class="p">)</span>
-        <span class="k">if</span> <span class="ow">not</span> <span class="n">v</span>\
-<span class="o">.</span><span class="n">startswith</span><span class="p">(</span><span class="s">\
-'__'</span><span class="p">)</span> <span class="ow">and</span> <span class="nb">isinstance</span>\
-<span class="p">(</span><span class="nb">getattr</span><span class="p">(</span><span class="n">\
-module</span><span class="p">,</span> <span class="n">v</span><span class="p">),\
-</span> <span class="nb">dict</span><span class="p">))</span></code></pre>
+    <span class="k">return</span> <span class="p">((</span>\
+<span class="n">v</span><span class="p">,</span> \
+<span class="nb">getattr</span><span class="p">(</span>\
+<span class="n">module</span><span class="p">,</span> \
+<span class="n">v</span><span class="p">))</span> \
+<span class="k">for</span> <span class="n">v</span> \
+<span class="ow">in</span> <span class="nb">\
+dir</span><span class="p">\
+(</span><span class="n">module</span><span class="p">)</span>
+        <span class="k">if</span> <span class="ow">not</span> \
+<span class="n">v</span><span class="o">.</span>\
+<span class="n">startswith</span><span class="p">(</span><span class="s">\
+'__'</span><span class="p">)</span> <span class="ow">and</span> \
+<span class="nb">isinstance</span><span class="p">(</span>\
+<span class="nb">getattr</span><span class="p">(</span><span class="n">\
+module</span><span class="p">,</span> <span class="n">v</span>\
+<span class="p">),</span> <span class="nb">dict</span>\
+<span class="p">))</span></code></pre>
 """,
     'part': 'body'
 }
     <br />
 
 more text''',
-    'out': '\n    <p>some text</p>\n<hr width=50 size=10 />\n<br />\n    <p>more text</p>\n',
+    'out': '\n    <p>some text</p>\n<hr width=50 size=10 />\n<br />'
+           '\n    <p>more text</p>\n',
     'part': 'body'
 }
 
 
 Section Title
 =============''',
-    'out': '<p class="nav special">paragraph with some text</p><a id="section-title"></a>'
+    'out': '<p class="nav special">paragraph with some text</p>'
+           '<a id="section-title"></a>'
            '<section class="heading top">'
            '<h1>Section Title</h1></section>',
     'indent_output': False,
         <p>more text</p>
         <aside class="topic">
             <h1>Topic Title</h1>
-            <p>Subsequent indented lines comprise the body of the topic, and are interpreted as \
-body elements.</p>
+            <p>Subsequent indented lines comprise the body of the topic, \
+and are interpreted as body elements.</p>
         </aside>
     </section>
     <a id="another-subtitle"></a>
     </aside>
     <aside class="note">This is a note.</aside>
     <aside class="tip">15% if the service is good.</aside>
-    <aside class="warning">Strong prose may provoke extreme mental exertion. Reader discretion is strongly advised.</aside>
+    <aside class="warning">Strong prose may provoke extreme mental exertion. \
+Reader discretion is strongly advised.</aside>
     <aside class="admonition">
         <h1>And, by the way...</h1>
         <p>You can make up your own admonition too.</p>
             <h1>This is a note admonition.</h1>
             <p>This is the second line of the first paragraph.</p>
             <ul>
-                <li>The note contains all indented body elements following.</li>
+                <li>The note contains all indented body elements \
+following.</li>
                 <li>It includes this bullet list.</li>
             </ul>
         </aside>
             </hgroup>
             <p>This is the second line of the first paragraph.</p>
             <ul>
-                <li>The note contains all indented body elements following.</li>
+                <li>The note contains all indented body elements \
+following.</li>
                 <li>It includes this bullet list.</li>
             </ul>
         </aside>
 }
 
 rubric = {
-    'rst': 'some text\n\n.. rubric:: RuBriC\n    :class: special heading\n\nmore text',
+    'rst': 'some text\n\n.. rubric:: RuBriC\n    :class: special heading'
+           '\n\nmore text',
     'out': '<p>some text</p><p class="rubric">RuBriC</p><p>more text</p>',
     'indent_output': False,
     'part': 'body',
     'rst': '''.. epigraph::
 
    No matter where you go, there you are.''',
-    'out': '<blockquote class="epigraph"><p>No matter where you go, there you are.</p>'
-           '</blockquote>',
+    'out': '<blockquote class="epigraph"><p>No matter where you go, there you '
+           'are.</p></blockquote>',
     'indent_output': False,
     'part': 'body',
 }
    you will erase the entire contents of your file system.''',
     'out': '''
     <div class="compound">
-        <p>The 'rm' command is very dangerous. If you are logged in as root and enter</p>
+        <p>The 'rm' command is very dangerous. If you are logged in as \
+root and enter</p>
         <pre>cd /
 rm -rf *</pre>
         <p>you will erase the entire contents of your file system.</p>
     'rst': '''.. container:: custom
 
    This paragraph might be rendered in a custom way.''',
-    'out': '<div class="container custom">This paragraph might be rendered in a custom way.</div>',
+    'out': '<div class="container custom">This paragraph might be rendered '
+           'in a custom way.</div>',
     'indent_output': False,
     'part': 'body',
 }
 Basic Usage
 ===========
 
-To start using subrepositories, you need two repositories, a main repo and a nested repo''',
+To start using subrepositories, you need two repositories, a main repo and \
+a nested repo''',
     'out': '''
     <a id="table-of-contents"></a>
     <aside class="topic contents">
     <a id="basic-usage"></a>
     <section>
         <h1>Basic Usage</h1>
-        <p>To start using subrepositories, you need two repositories, a main repo and a nested repo</p>
+        <p>To start using subrepositories, you need two repositories, a main \
+repo and a nested repo</p>
     </section>
 ''',
     'part': 'body',
 
 Yes, |reST| is a long word, so I can't blame anyone for wanting to
 abbreviate it.''',
-    'out': "<p>Yes, reStructuredText is a long word, so I can't blame anyone for wanting to "
-           "abbreviate it.</p>",
+    'out': "<p>Yes, reStructuredText is a long word, so I can't blame "
+           "anyone for wanting to abbreviate it.</p>",
     'indent_output': False,
     'part': 'body',
 }
 :Date: 2012-07-29
 :Copyright: André Felipe Dias
 :Dedication: To Andréa, Dexter e DeeDee
-:Abstract: Generates (X)HTML5 documents from standalone reStructuredText sources.
+:Abstract: Generates (X)HTML5 documents from standalone reStructuredText \
+sources.
 :Indentation: Since the field marker may be quite long, the second
    and subsequent lines of the field body do not have to line up
    with the first line, but they must be indented relative to the
             </tr>
             <tr>
                 <th>contact</th>
-                <td><a href="mailto:andref.dias@pronus.eng.br">andref.dias@pronus.eng.br</a></td>
+                <td><a href="mailto:andref.dias@pronus.eng.br">\
+andref.dias@pronus.eng.br</a></td>
             </tr>
             <tr>
                 <th>address</th>
             <tr>
                 <th>Indentation</th>
                 <td>Since the field marker may be quite long, the second and \
-subsequent lines of the field body do not have to line up with the first line, \
-but they must be indented relative to the field name marker, and they must line \
-up with each other.</td>
+subsequent lines of the field body do not have to line up with the \
+first line, but they must be indented relative to the field name marker, \
+and they must line up with each other.</td>
             </tr>
             <tr>
                 <th>Parameter i</th>
     </aside>
     <aside class="topic abstract">
         <h1>Abstract</h1>
-        <p>Generates (X)HTML5 documents from standalone reStructuredText sources.</p>
+        <p>Generates (X)HTML5 documents from standalone reStructuredText \
+sources.</p>
     </aside>
 ''',
     'part': 'body',
         <tbody>
             <tr>
                 <th>Info</th>
-                <td>See <a href="https://bitbucket.org/andre_felipe_dias/rst2html5">\
-https://bitbucket.org/andre_felipe_dias/rst2html5</a></td>
+                <td>See <a href="https://bitbucket.org/\
+andre_felipe_dias/rst2html5">https://bitbucket.org/andre_felipe_dias/\
+rst2html5</a></td>
             </tr>
             <tr>
                 <th>author</th>
-                <td>André Felipe Dias &lt;<a href="mailto:andref.dias@gmail.com">\
-andref.dias@gmail.com</a>&gt;</td>
+                <td>André Felipe Dias &lt;<a href="mailto:\
+andref.dias@gmail.com">andref.dias@gmail.com</a>&gt;</td>
             </tr>
             <tr>
                 <th>date</th>
 .. [CIT2012] A citation
 .. [TEST2] Test text''',
     'out': '''
-    <p>this is a citation <a href="#cit2012" id="id1" class="citation_reference">[CIT2012]</a></p>
-    <p>Another <a href="#test2" id="id2" class="citation_reference">[TEST2]</a>.</p>
+    <p>this is a citation <a href="#cit2012" id="id1" \
+class="citation_reference">[CIT2012]</a></p>
+    <p>Another <a href="#test2" id="id2" \
+class="citation_reference">[TEST2]</a>.</p>
     <table class="citation" id="cit2012">
         <col />
         <col />
 attribution = {
     'rst': '''Quote:
 
-    "Choose a job you love, and you will never have to work a day in your life."
+    "Choose a job you love, and you will never have to work a day \
+in your life."
 
     -- Confucius''',
     'out': '''
     <p>Quote:</p>
     <blockquote>
-        <p>"Choose a job you love, and you will never have to work a day in your life."</p>
+        <p>"Choose a job you love, and you will never have to work a day \
+in your life."</p>
         <p class="attribution">Confucius</p>
     </blockquote>
 ''',
             <tr>
                 <td><kbd>-p</kbd></td>
                 <td>
-                    <p>This option has two paragraphs in the description. This is the first.</p>
-                    <p>This is the second. Blank lines may be omitted between options (as above) or left in (as here and below).</p>
+                    <p>This option has two paragraphs in the description. \
+This is the first.</p>
+                    <p>This is the second. Blank lines may be omitted \
+between options (as above) or left in (as here and below).</p>
                 </td>
             </tr>
             <tr>
             </tr>
             <tr>
                 <td></td>
-                <td>A VMS-style option. Note the adjustment for the required two spaces.</td>
+                <td>A VMS-style option. Note the adjustment for the required \
+two spaces.</td>
             </tr>
             <tr>
                 <td colspan="2"><kbd>--an-even-longer-option</kbd></td>
                 <td>This option has two variants.</td>
             </tr>
             <tr>
-                <td colspan="2"><kbd>-f <var>FILE</var></kbd>, <kbd>--file=<var>FILE</var></kbd></td>
+                <td colspan="2"><kbd>-f <var>FILE</var></kbd>, \
+<kbd>--file=<var>FILE</var></kbd></td>
             </tr>
             <tr>
                 <td></td>
 
 .. [#] This footnote will be labeled "3".  It is the second
    auto-numbered footnote, but footnote label "2" is already used.''',
-   'out': '''
-    <p><a href="#id4" id="id1" class="footnote_reference">[2]</a> will be "2" (manually numbered), \
-<a href="#id5" id="id2" class="footnote_reference">[3]</a> will be "3" (anonymous auto-numbered), \
+    'out': '''
+    <p><a href="#id4" id="id1" class="footnote_reference">[2]</a> \
+will be "2" (manually numbered), <a href="#id5" id="id2" \
+class="footnote_reference">[3]</a> will be "3" (anonymous auto-numbered), \
 and <a href="#label" id="id3" class="footnote_reference">[1]</a> will be "1" \
 (labeled auto-numbered).</p>
     <table id="label" class="footnote">
             <tr>
                 <th>[1]</th>
                 <td>
-                    <p>This autonumber-labeled footnote will be labeled "1".</p>
-                    <p>It is the first auto-numbered footnote and no other footnote with label \
-"1" exists.</p>
-                    <p>The order of the footnotes is used to determine numbering, not the order \
-of the footnote references.</p>
+                    <p>This autonumber-labeled footnote will be \
+labeled "1".</p>
+                    <p>It is the first auto-numbered footnote and no other \
+footnote with label "1" exists.</p>
+                    <p>The order of the footnotes is used to determine \
+numbering, not the order of the footnote references.</p>
                 </td>
             </tr>
         </tbody>
         <tbody>
             <tr>
                 <th>[2]</th>
-                <td>This footnote is labeled manually, so its number is fixed.</td>
+                <td>This footnote is labeled manually, so its number is \
+fixed.</td>
             </tr>
         </tbody>
     </table>
         <tbody>
             <tr>
                 <th>[3]</th>
-                <td>This footnote will be labeled "3". It is the second auto-numbered footnote, but footnote label "2" is already used.</td>
+                <td>This footnote will be labeled "3". It is the second \
+auto-numbered footnote, but footnote label "2" is already used.</td>
             </tr>
         </tbody>
     </table>
 ''',
-   'part': 'body',
+    'part': 'body',
 }
 
 
     'out': '''
     <figure>
         <img src="picture.png" alt="map to buried treasure" scale="50" />
-        <figcaption>This is the caption of the figure (a simple paragraph).</figcaption>
-        <div class="legend">The legend consists of all elements after the caption. In this case, the legend consists of this paragraph.</div>
+        <figcaption>This is the caption of the figure (a simple paragraph).\
+</figcaption>
+        <div class="legend">The legend consists of all elements after the \
+caption. In this case, the legend consists of this paragraph.</div>
     </figure>
 ''',
     'part': 'body'
 }
 
-
-
 # stderr should present: <string>:1: (ERROR/3) Unknown target name: "target"
 system_message = {
     'rst': 'target_',
         <h1>Docutils System Messages</h1>
         <a id="id1"></a>
         <div>
-            <h1>System Message: ERROR/3 (&lt;string&gt; line 1) <a href="#id2">id2</a></h1>
+            <h1>System Message: ERROR/3 (&lt;string&gt; line 1) \
+<a href="#id2">id2</a></h1>
             <p>Unknown target name: "target".</p>
         </div>
     </section>
 .. __: http://opensource.org/licenses/MIT
 ''',
     'out': '''
-    <p><a href="#id2" id="id3" class="problematic">Target1__</a> <a href="#id2" id="id4" \
+    <p><a href="#id2" id="id3" class="problematic">Target1__</a> \
+<a href="#id2" id="id4" \
 class="problematic">Target2__</a></p>
     <section class="system-messages">
         <h1>Docutils System Messages</h1>
         <a id="id2"></a>
         <div>
-            <h1>System Message: ERROR/3 (&lt;string&gt; line ) <a href="#id3">id3</a> \
+            <h1>System Message: ERROR/3 (&lt;string&gt; line ) \
+<a href="#id3">id3</a> \
 <a href="#id4">id4</a></h1>
-            <p>Anonymous hyperlink mismatch: 2 references but 1 targets. See "backrefs" \
-attribute for IDs.</p>
+            <p>Anonymous hyperlink mismatch: 2 references but 1 targets. \
+See "backrefs" attribute for IDs.</p>
         </div>
     </section>
 ''',
         <h1>Docutils System Messages</h1>
         <a id="id3"></a>
         <div>
-            <h1>System Message: ERROR/3 (&lt;string&gt; line 1) <a href="#id4">id4</a></h1>
+            <h1>System Message: ERROR/3 (&lt;string&gt; line 1) \
+<a href="#id4">id4</a></h1>
             <p>Unknown target name: "2".</p>
         </div>
     </section>
 
 math_role = {
     'rst': r':math:`\sqrt{3x-1}+(1+x)^2`',
-    'out': '<meta charset="utf-8" /><script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js'\
+    'out': '<meta charset="utf-8" />\
+<script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js'
            '?config=TeX-AMS-MML_HTMLorMML"></script>',
     'indent_output': False,
     'part': 'head',
     <link href="http://www.pronus.eng.br/css/standard.css" rel="stylesheet" />
 ''',
     'part': 'head',
-    'stylesheet': 'http://test.com/css/default.css, http://www.pronus.eng.br/css/standard.css'
+    'stylesheet': 'http://test.com/css/default.css, '
+                  'http://www.pronus.eng.br/css/standard.css'
 }
 
 javascript = {
     'rst': 'ordinary paragraph',
     'out': '''
     <meta charset="utf-8" />
-    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
+    <script src="https://ajax.googleapis.com/ajax/libs/jquery/\
+1.7.2/jquery.min.js"></script>
 ''',
-    'script': 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js',
+    'script': 'https://ajax.googleapis.com/ajax/libs/jquery/\
+1.7.2/jquery.min.js',
     'part': 'head',
 }
 
 ''',
     'part': 'head',
 }
-

tests/test_html5writer.py

 import unittest
 
 from rst2html5 import HTML5Writer
-from docutils.core import publish_parts, publish_string
+from docutils.core import publish_parts
 from nose.tools import assert_equals
 from tempfile import gettempdir
 
 tmpdir = gettempdir()
 unittest.TestCase.maxDiff = None
 
+
 def rst_to_html5_part(case):
     overrides = case.copy()
     rst = overrides.pop('rst')
     overrides.pop('out')
     overrides.setdefault('indent_output', True)
     return publish_parts(writer=HTML5Writer(), source=rst,
-                          settings_overrides=overrides)[part]
+                         settings_overrides=overrides)[part]
+
 
 def extract_variables(module):
     '''
     For example, {'rst': rst, 'out':out, ...}
     '''
     return ((v, getattr(module, v)) for v in dir(module)
-        if not v.startswith('__') and isinstance(getattr(module, v), dict))
+            if not v.startswith('__') and isinstance(getattr(module, v), dict))
 
 
 def test():
         filename = os.path.join(tmpdir, test_name)
         with codecs.open(filename + '.rst', encoding='utf-8', mode='w') as f:
             f.write(case['rst'])
-        with codecs.open(filename + '.result', encoding='utf-8', mode='w') as f:
+        with codecs.open(filename + '.result', encoding='utf-8',
+                         mode='w') as f:
             f.write(result)
-        with codecs.open(filename + '.expected', encoding='utf-8', mode='w') as f:
+        with codecs.open(filename + '.expected', encoding='utf-8',
+                         mode='w') as f:
             f.write(case['out'])
 
         if isinstance(error, AssertionError):