[Zope-Checkins] CVS: Zope/lib/python/docutils/writers - __init__.py:1.2 docutils_xml.py:1.2 html4css1.py:1.2 html4zope.py:1.2 pep_html.py:1.2 pseudoxml.py:1.2

Andreas Jung andreas@andreas-jung.com
Sat, 1 Feb 2003 04:26:54 -0500


Update of /cvs-repository/Zope/lib/python/docutils/writers
In directory cvs.zope.org:/tmp/cvs-serv18056/docutils/writers

Added Files:
	__init__.py docutils_xml.py html4css1.py html4zope.py 
	pep_html.py pseudoxml.py 
Log Message:
merge from ajung-restructuredtext-integration-branch


=== Zope/lib/python/docutils/writers/__init__.py 1.1 => 1.2 ===
--- /dev/null	Sat Feb  1 04:26:53 2003
+++ Zope/lib/python/docutils/writers/__init__.py	Sat Feb  1 04:26:20 2003
@@ -0,0 +1,82 @@
+# Authors: David Goodger
+# Contact: goodger@users.sourceforge.net
+# Revision: $Revision$
+# Date: $Date$
+# Copyright: This module has been placed in the public domain.
+
+"""
+This package contains Docutils Writer modules.
+"""
+
+__docformat__ = 'reStructuredText'
+
+
+import sys
+import docutils
+from docutils import languages, Component
+from docutils.transforms import universal
+
+
+class Writer(Component):
+
+    """
+    Abstract base class for docutils Writers.
+
+    Each writer module or package must export a subclass also called 'Writer'.
+    Each writer must support all standard node types listed in
+    `docutils.nodes.node_class_names`.
+
+    Call `write()` to process a document.
+    """
+
+    component_type = 'writer'
+
+    document = None
+    """The document to write."""
+
+    language = None
+    """Language module for the document."""
+
+    destination = None
+    """`docutils.io` IO object; where to write the document."""
+
+    def __init__(self):
+        """Initialize the Writer instance."""
+
+    def write(self, document, destination):
+        self.document = document
+        self.language = languages.get_language(
+            document.settings.language_code)
+        self.destination = destination
+        self.translate()
+        output = self.destination.write(self.output)
+        return output
+
+    def translate(self):
+        """
+        Override to do final document tree translation.
+
+        This is usually done with a `docutils.nodes.NodeVisitor` subclass, in
+        combination with a call to `docutils.nodes.Node.walk()` or
+        `docutils.nodes.Node.walkabout()`.  The ``NodeVisitor`` subclass must
+        support all standard elements (listed in
+        `docutils.nodes.node_class_names`) and possibly non-standard elements
+        used by the current Reader as well.
+        """
+        raise NotImplementedError('subclass must override this method')
+
+
+_writer_aliases = {
+      'html': 'html4css1',
+      'pprint': 'pseudoxml',
+      'pformat': 'pseudoxml',
+      'pdf': 'rlpdf',
+      'xml': 'docutils_xml',}
+
+def get_writer_class(writer_name):
+    """Return the Writer class from the `writer_name` module."""
+    writer_name = writer_name.lower()
+    if _writer_aliases.has_key(writer_name):
+        writer_name = _writer_aliases[writer_name]
+    module = __import__(writer_name, globals(), locals())
+    return module.Writer


=== Zope/lib/python/docutils/writers/docutils_xml.py 1.1 => 1.2 ===
--- /dev/null	Sat Feb  1 04:26:53 2003
+++ Zope/lib/python/docutils/writers/docutils_xml.py	Sat Feb  1 04:26:20 2003
@@ -0,0 +1,66 @@
+# Authors: David Goodger
+# Contact: goodger@users.sourceforge.net
+# Revision: $Revision$
+# Date: $Date$
+# Copyright: This module has been placed in the public domain.
+
+"""
+Simple internal document tree Writer, writes Docutils XML.
+"""
+
+__docformat__ = 'reStructuredText'
+
+
+import docutils
+from docutils import writers
+
+
+class Writer(writers.Writer):
+
+    supported = ('xml',)
+    """Formats this writer supports."""
+
+    settings_spec = (
+        '"Docutils XML" Writer Options',
+        'Warning: the --newlines and --indents options may adversely affect '
+        'whitespace; use them only for reading convenience.',
+        (('Generate XML with newlines before and after tags.',
+          ['--newlines'], {'action': 'store_true'}),
+         ('Generate XML with indents and newlines.',
+          ['--indents'], {'action': 'store_true'}),
+         ('Omit the XML declaration.  Use with caution.',
+          ['--no-xml-declaration'], {'dest': 'xml_declaration', 'default': 1,
+                                     'action': 'store_false'}),
+         ('Omit the DOCTYPE declaration.',
+          ['--no-doctype'], {'dest': 'doctype_declaration', 'default': 1,
+                             'action': 'store_false'}),))
+
+    output = None
+    """Final translated form of `document`."""
+
+    xml_declaration = '<?xml version="1.0" encoding="%s"?>\n'
+    #xml_stylesheet = '<?xml-stylesheet type="text/xsl" href="%s"?>\n'
+    doctype = (
+        '<!DOCTYPE document PUBLIC'
+        ' "+//IDN docutils.sourceforge.net//DTD Docutils Generic//EN//XML"'
+        ' "http://docutils.sourceforge.net/spec/docutils.dtd">\n')
+    generator = '<!-- Generated by Docutils %s -->\n'
+
+    def translate(self):
+        settings = self.document.settings
+        indent = newline = ''
+        if settings.newlines:
+            newline = '\n'
+        if settings.indents:
+            newline = '\n'
+            indent = '    '
+        output_prefix = []
+        if settings.xml_declaration:
+            output_prefix.append(
+                self.xml_declaration % settings.output_encoding)
+        if settings.doctype_declaration:
+            output_prefix.append(self.doctype)
+        output_prefix.append(self.generator % docutils.__version__)
+        docnode = self.document.asdom().childNodes[0]
+        self.output = (''.join(output_prefix)
+                       + docnode.toprettyxml(indent, newline))


=== Zope/lib/python/docutils/writers/html4css1.py 1.1 => 1.2 === (1051/1151 lines abridged)
--- /dev/null	Sat Feb  1 04:26:54 2003
+++ Zope/lib/python/docutils/writers/html4css1.py	Sat Feb  1 04:26:20 2003
@@ -0,0 +1,1148 @@
+# Author: David Goodger
+# Contact: goodger@users.sourceforge.net
+# Revision: $Revision$
+# Date: $Date$
+# Copyright: This module has been placed in the public domain.
+
+"""
+Simple HyperText Markup Language document tree Writer.
+
+The output conforms to the HTML 4.01 Transitional DTD and to the Extensible
+HTML version 1.0 Transitional DTD (*almost* strict).  The output contains a
+minimum of formatting information.  A cascading style sheet ("default.css" by
+default) is required for proper viewing with a modern graphical browser.
+"""
+
+__docformat__ = 'reStructuredText'
+
+
+import sys
+import os
+import time
+import re
+from types import ListType
+import docutils
+from docutils import nodes, utils, writers, languages
+
+
+class Writer(writers.Writer):
+
+    supported = ('html', 'html4css1', 'xhtml')
+    """Formats this writer supports."""
+
+    settings_spec = (
+        'HTML-Specific Options',
+        None,
+        (('Specify a stylesheet URL, used verbatim.  Default is '
+          '"default.css".  Overridden by --stylesheet-path.',
+          ['--stylesheet'],
+          {'default': 'default.css', 'metavar': '<URL>'}),
+         ('Specify a stylesheet file, relative to the current working '
+          'directory.  The path is adjusted relative to the output HTML '
+          'file.  Overrides --stylesheet.',
+          ['--stylesheet-path'],
+          {'metavar': '<file>'}),
+         ('Link to the stylesheet in the output HTML file.  This is the '
+          'default.',
+          ['--link-stylesheet'],

[-=- -=- -=- 1051 lines omitted -=- -=- -=-]

+        self.depart_admonition()
+
+    def unimplemented_visit(self, node):
+        raise NotImplementedError('visiting unimplemented node type: %s'
+                                  % node.__class__.__name__)
+
+
+class SimpleListChecker(nodes.GenericNodeVisitor):
+
+    """
+    Raise `nodes.SkipNode` if non-simple list item is encountered.
+
+    Here "simple" means a list item containing nothing other than a single
+    paragraph, a simple list, or a paragraph followed by a simple list.
+    """
+
+    def default_visit(self, node):
+        raise nodes.NodeFound
+
+    def visit_bullet_list(self, node):
+        pass
+
+    def visit_enumerated_list(self, node):
+        pass
+
+    def visit_list_item(self, node):
+        children = []
+        for child in node.get_children():
+            if not isinstance(child, nodes.Invisible):
+                children.append(child)
+        if (children and isinstance(children[0], nodes.paragraph)
+            and (isinstance(children[-1], nodes.bullet_list)
+                 or isinstance(children[-1], nodes.enumerated_list))):
+            children.pop()
+        if len(children) <= 1:
+            return
+        else:
+            raise nodes.NodeFound
+
+    def visit_paragraph(self, node):
+        raise nodes.SkipNode
+
+    def invisible_visit(self, node):
+        """Invisible nodes should be ignored."""
+        pass
+
+    visit_comment = invisible_visit
+    visit_substitution_definition = invisible_visit
+    visit_target = invisible_visit
+    visit_pending = invisible_visit


=== Zope/lib/python/docutils/writers/html4zope.py 1.1 => 1.2 ===
--- /dev/null	Sat Feb  1 04:26:54 2003
+++ Zope/lib/python/docutils/writers/html4zope.py	Sat Feb  1 04:26:20 2003
@@ -0,0 +1,59 @@
+# Author: Andreas Jung
+# Contact: andreas@andreas-jung.com
+# Revision: $Revision$
+# Date: $Date$
+# Copyright: This module has been placed in the public domain.
+
+"""
+Writer module to integrate reST into Zope.  This writer subclasses the standard
+html4css1 writer and changes the starting level for <H> elements from 1 to 3
+(default behaviour inside Zope.
+"""
+
+__docformat__ = 'reStructuredText'
+
+from docutils import nodes
+from html4css1 import Writer  as CSS1Writer, HTMLTranslator as CSS1HTMLTranslator
+import os
+
+default_level = int(os.environ.get('STX_DEFAULT_LEVEL', 3))
+
+class Writer(CSS1Writer):
+    def __init__(self):
+        CSS1Writer.__init__(self)
+        self.translator_class = HTMLTranslator
+
+class HTMLTranslator(CSS1HTMLTranslator):
+
+    def astext(self):
+        return ''.join(self.body)
+
+    def visit_title(self, node):
+        """Only 6 section levels are supported by HTML."""
+
+        if isinstance(node.parent, nodes.topic):
+            self.body.append(
+                  self.starttag(node, 'p', '', CLASS='topic-title'))
+            if node.parent.hasattr('id'):
+                self.body.append(
+                    self.starttag({}, 'a', '', name=node.parent['id']))
+                self.context.append('</a></p>\n')
+            else:
+                self.context.append('</p>\n')
+        elif self.section_level == 0:
+            # document title
+            self.head.append('<title>%s</title>\n'
+                             % self.encode(node.astext()))
+            self.body.append(self.starttag(node, 'h%d' % default_level, '', CLASS='title'))
+            self.context.append('</h%d>\n' % default_level)
+        else:
+            self.body.append(
+                  self.starttag(node, 'h%s' % (default_level+self.section_level-1), ''))
+            atts = {}
+            if node.parent.hasattr('id'):
+                atts['name'] = node.parent['id']
+            if node.hasattr('refid'):
+                atts['class'] = 'toc-backref'
+                atts['href'] = '#' + node['refid']
+            self.body.append(self.starttag({}, 'a', '', **atts))
+            self.context.append('</a></h%s>\n' % ((default_level+self.section_level-1)))


=== Zope/lib/python/docutils/writers/pep_html.py 1.1 => 1.2 ===
--- /dev/null	Sat Feb  1 04:26:54 2003
+++ Zope/lib/python/docutils/writers/pep_html.py	Sat Feb  1 04:26:20 2003
@@ -0,0 +1,113 @@
+# Author: David Goodger
+# Contact: goodger@users.sourceforge.net
+# Revision: $Revision$
+# Date: $Date$
+# Copyright: This module has been placed in the public domain.
+
+"""
+PEP HTML Writer.
+"""
+
+__docformat__ = 'reStructuredText'
+
+
+import sys
+import docutils
+from docutils import nodes, optik, utils
+from docutils.writers import html4css1
+
+
+class Writer(html4css1.Writer):
+
+    settings_spec = html4css1.Writer.settings_spec + (
+        'PEP/HTML-Specific Options',
+        'The HTML --footnote-references option is set to "brackets" by '
+        'default.',
+        (('Specify a PEP stylesheet URL, used verbatim.  Default is '
+          '--stylesheet\'s value.  If given, --pep-stylesheet overrides '
+          '--stylesheet.',
+          ['--pep-stylesheet'],
+          {'metavar': '<URL>'}),
+         ('Specify a PEP stylesheet file, relative to the current working '
+          'directory.  The path is adjusted relative to the output HTML '
+          'file.  Overrides --pep-stylesheet and --stylesheet-path.',
+          ['--pep-stylesheet-path'],
+          {'metavar': '<path>'}),
+         ('Specify a template file.  Default is "pep-html-template".',
+          ['--pep-template'],
+          {'default': 'pep-html-template', 'metavar': '<file>'}),
+         ('Python\'s home URL.  Default is ".." (parent directory).',
+          ['--python-home'],
+          {'default': '..', 'metavar': '<URL>'}),
+         ('Home URL prefix for PEPs.  Default is "." (current directory).',
+          ['--pep-home'],
+          {'default': '.', 'metavar': '<URL>'}),
+         # Workaround for SourceForge's broken Python
+         # (``import random`` causes a segfault).
+         (optik.SUPPRESS_HELP,
+          ['--no-random'], {'action': 'store_true'}),))
+
+    settings_default_overrides = {'footnote_references': 'brackets'}
+
+    relative_path_settings = ('pep_stylesheet_path', 'pep_template')
+
+    def __init__(self):
+        html4css1.Writer.__init__(self)
+        self.translator_class = HTMLTranslator
+
+    def translate(self):
+        html4css1.Writer.translate(self)
+        settings = self.document.settings
+        template = open(settings.pep_template).read()
+        # Substitutions dict for template:
+        subs = {}
+        subs['encoding'] = settings.output_encoding
+        subs['version'] = docutils.__version__
+        subs['stylesheet'] = ''.join(self.stylesheet)
+        pyhome = settings.python_home
+        subs['pyhome'] = pyhome
+        subs['pephome'] = settings.pep_home
+        if pyhome == '..':
+            subs['pepindex'] = '.'
+        else:
+            subs['pepindex'] = pyhome + '/peps/'
+        index = self.document.first_child_matching_class(nodes.field_list)
+        header = self.document[index]
+        pepnum = header[0][1].astext()
+        subs['pep'] = pepnum
+        if settings.no_random:
+            subs['banner'] = 0
+        else:
+            import random
+            subs['banner'] = random.randrange(64)
+        try:
+            subs['pepnum'] = '%04i' % int(pepnum)
+        except:
+            subs['pepnum'] = pepnum
+        subs['title'] = header[1][1].astext()
+        subs['body'] = ''.join(
+            self.body_pre_docinfo + self.docinfo + self.body)
+        subs['body_suffix'] = ''.join(self.body_suffix)
+        self.output = template % subs
+
+
+class HTMLTranslator(html4css1.HTMLTranslator):
+
+    def get_stylesheet_reference(self, relative_to=None):
+        settings = self.settings
+        if relative_to == None:
+            relative_to = settings._destination
+        if settings.pep_stylesheet_path:
+            return utils.relative_path(relative_to,
+                                       settings.pep_stylesheet_path)
+        elif settings.pep_stylesheet:
+            return settings.pep_stylesheet
+        elif settings._stylesheet_path:
+            return utils.relative_path(relative_to, settings.stylesheet_path)
+        else:
+            return settings.stylesheet
+
+    def depart_field_list(self, node):
+        html4css1.HTMLTranslator.depart_field_list(self, node)
+        if node.get('class') == 'rfc2822':
+             self.body.append('<hr />\n')


=== Zope/lib/python/docutils/writers/pseudoxml.py 1.1 => 1.2 ===
--- /dev/null	Sat Feb  1 04:26:54 2003
+++ Zope/lib/python/docutils/writers/pseudoxml.py	Sat Feb  1 04:26:20 2003
@@ -0,0 +1,30 @@
+# Authors: David Goodger
+# Contact: goodger@users.sourceforge.net
+# Revision: $Revision$
+# Date: $Date$
+# Copyright: This module has been placed in the public domain.
+
+"""
+Simple internal document tree Writer, writes indented pseudo-XML.
+"""
+
+__docformat__ = 'reStructuredText'
+
+
+from docutils import writers
+
+
+class Writer(writers.Writer):
+
+    supported = ('pprint', 'pformat', 'pseudoxml')
+    """Formats this writer supports."""
+
+    output = None
+    """Final translated form of `document`."""
+
+    def translate(self):
+        self.output = self.document.pformat()
+
+    def supports(self, format):
+        """This writer supports all format-specific elements."""
+        return 1