Beispiel #1
0
    def __init__(self,
                 document,
                 docstring_linker=None,
                 directory=None,
                 docindex=None,
                 context=None):
        # Set the document's settings.
        if self.settings is None:
            settings = OptionParser([LaTeXWriter()]).get_default_values()
            settings.output_encoding = 'utf-8'

            # This forces eg \EpydocUserSection rather than
            # \EpydocUserSEction*:
            settings.use_latex_toc = True

            self.__class__.settings = settings
        document.settings = self.settings

        LaTeXTranslator.__init__(self, document)
        self._linker = docstring_linker
        self._directory = directory
        self._docindex = docindex
        self._context = context

        # Use custom section names.
        self.d_class = _EpydocDocumentClass()
Beispiel #2
0
    def run(self):
        env = self.state.document.settings.env
        baseurl = env.config.rss_baseurl
        assert baseurl, "rss_baseurl must be defined in your config.py"

        source = self.state_machine.input_lines.source(self.lineno - self.state_machine.input_offset - 1)

        rss_doc = utils.new_document(b("<rss>"), self.state.document.settings)
        Parser().parse("\n".join(self.content), rss_doc)

        rst_suffix = env.config.source_suffix
        path = os.path.relpath(source, env.srcdir).replace(rst_suffix, ".html")

        builder = env.app.builder
        docwriter = HTMLWriter(self)
        docsettings = OptionParser(defaults=env.settings, components=(docwriter,)).get_default_values()
        docsettings.compact_lists = bool(env.config.html_compact_lists)

        dest = os.path.join(env.app.outdir, os_path(env.docname) + ".rss")
        pageurl = "%s/%s" % (baseurl, path)
        with open(dest, "w") as rss:
            title = self.options.get("title", "")
            description = self.options.get("description", None)
            rss.write('<?xml version="1.0" encoding="ISO-8859-1" ?>\n')
            rss.write('<rss version="2.0">\n')
            rss.write("<channel>\n")
            rss.write("<title>%s</title>\n" % cgi.escape(title))
            rss.write("<link>%s</link>\n" % pageurl)
            if description:
                rss.write("<description>%s</description>\n" % cgi.escape(description))

            for child in rss_doc.children:
                if not isinstance(child, nodes.section):
                    continue

                title_index = child.first_child_matching_class(nodes.title)
                if title_index is None:
                    continue

                node = nodes.paragraph()
                node.extend(child.children[title_index + 1 :])

                sec_doc = utils.new_document(b("<rss-section>"), docsettings)
                sec_doc.append(node)
                visitor = RssTranslator(builder, sec_doc)
                sec_doc.walkabout(visitor)

                title = child.children[title_index].astext()
                sectionurl = "%s#%s" % (pageurl, child.get("ids")[0])
                description = "".join(visitor.body)

                rss.write("<item>\n")
                rss.write("<title>%s</title>\n" % cgi.escape(title))
                rss.write("<link>%s</link>\n" % sectionurl)
                rss.write("<description><![CDATA[%s]]></description>\n" % description)
                rss.write("</item>\n")
            rss.write("</channel>\n")
            rss.write("</rss>\n")

        return []
Beispiel #3
0
 def _get_document_settings(self):
     """Get settings for the docutils components."""
     components = (self.parser, self.reader)
     defaults = dict(read_config_files=False,
                     report_level=5,
                     halt_level=10,
                     warning_stream=False)
     opt_parser = OptionParser(components=components, defaults=defaults)
     return opt_parser.get_default_values()
Beispiel #4
0
def parseRst(filename):
    '''Load a text file and use the .rst parser to build a docutils node tree.'''
    settings = OptionParser(components=(Parser, )).get_default_values()
    settings.input_encoding = 'utf8'  # This does not work, old version of docutils?
    source = open(filename).read()
    parser = Parser()
    doc = docutils.utils.new_document('slides.rst', settings)
    parser.parse(source, doc)
    return doc
def setup():
    global _parser, _settings
    _parser = Parser()
    _settings = OptionParser().get_default_values()
    _settings.tab_width = 8
    _settings.pep_references = False
    _settings.rfc_references = False
    app = FakeSphinx()
    plantuml.setup(app)
Beispiel #6
0
def setup():
    global _parser, _settings
    _parser = Parser()
    _settings = OptionParser().get_default_values()
    _settings.tab_width = 8
    _settings.pep_references = False
    _settings.rfc_references = False
    app = FakeSphinx()
    sadisp.setup(app)
Beispiel #7
0
 def write(self, *ignored):
     self.init_document_data()
     for entry in self.document_data:
         docname, targetname, title, author = entry[:4]
         targetname += '.texi'
         direntry = description = category = ''
         if len(entry) > 6:
             direntry, description, category = entry[4:7]
         toctree_only = False
         if len(entry) > 7:
             toctree_only = entry[7]
         destination = FileOutput(
             destination_path=path.join(self.outdir, targetname),
             encoding='utf-8')
         self.info("processing " + targetname + "... ", nonl=1)
         doctree = self.assemble_doctree(docname, toctree_only,
             appendices=(self.config.texinfo_appendices or []))
         self.info("writing... ", nonl=1)
         self.post_process_images(doctree)
         docwriter = TexinfoWriter(self)
         settings = OptionParser(
             defaults=self.env.settings,
             components=(docwriter,)).get_default_values()
         settings.author = author
         settings.title = title
         settings.texinfo_filename = targetname[:-5] + '.info'
         settings.texinfo_elements = self.config.texinfo_elements
         settings.texinfo_dir_entry = direntry or ''
         settings.texinfo_dir_category = category or ''
         settings.texinfo_dir_description = description or ''
         settings.docname = docname
         doctree.settings = settings
         docwriter.write(doctree, destination)
         self.info("done")
Beispiel #8
0
def load_rst(filename):
    # use the docutils option parser to get defaults for our efforts
    opts = OptionParser(components=(Parser, ))
    defaults = opts.get_default_values()

    # shut up the warnings
    defaults.warning_stream = StringIO()

    doc = new_document(filename, defaults)
    with open(filename) as f:
        Parser().parse(f.read(), doc)

    return doc
Beispiel #9
0
def find_autoasdf_directives(env, filename):

    parser = RSTParser()
    settings = OptionParser(components=(RSTParser, )).get_default_values()
    settings.env = env
    document = new_document(filename, settings)

    with open(filename) as ff:
        parser.parse(ff.read(), document)

    return [
        x.children[0].astext() for x in document.traverse()
        if isinstance(x, schema_def)
    ]
Beispiel #10
0
def main():
    # process cmdline arguments:
    inputFile, outputFile, outputFormat, optargs = getArgs()
    settings = OptionParser(components=(Parser, )).get_default_values()
    settings.debug = optargs['debug']
    parser = Parser()
    input = inputFile.read()
    document = new_document(inputFile.name, settings)
    parser.parse(input, document)
    output = format(outputFormat, input, document, optargs)
    outputFile.write(output)
    if optargs['attributes']:
        import pprint
        pprint.pprint(document.__dict__)
Beispiel #11
0
def main():
    # process cmdline arguments:
    inputFile, outputFile, outputFormat, optargs = getArgs()
    settings = OptionParser(components=(Parser,)).get_default_values()
    settings.debug = optargs['debug']
    parser = Parser()
    input = inputFile.read()
    document = new_document(inputFile.name, settings)
    parser.parse(input, document)
    output = format(outputFormat, input, document, optargs)
    outputFile.write(output)
    if optargs['attributes']:
        import pprint
        pprint.pprint(document.__dict__)
Beispiel #12
0
def get_settings():
  settings = OptionParser().get_default_values()
  ## parser settings
  settings.tab_width = 2
  settings.pep_references = None
  settings.rfc_references = None
  ## html settinfgs
  settings.xml_declaration = None
  settings.stylesheet = None
  settings.stylesheet_path = None
  settings.initial_header_level = 1
  settings.math_output = "X"
  settings.template = Writer.default_template_path
  return settings
Beispiel #13
0
def _write_html(document) -> str:
    builder = _get_builder()

    destination = StringOutput(encoding="utf-8")
    docwriter = HTMLWriter(builder)
    docsettings = OptionParser(defaults=builder.env.settings,
                               components=(docwriter, ),
                               read_config_files=True).get_default_values()
    docsettings.compact_lists = True

    document.settings = docsettings

    docwriter.write(document, destination)
    docwriter.assemble_parts()
    return docwriter.parts["body"]
    def write(self, *ignored):
        self.init_document_data()
        for entry in self.document_data:
            docname, targetname, title, author = entry[:4]
            targetname += '.texi'
            direntry = description = category = ''
            if len(entry) > 6:
                direntry, description, category = entry[4:7]
            toctree_only = False
            if len(entry) > 7:
                toctree_only = entry[7]
            destination = FileOutput(destination_path=path.join(
                self.outdir, targetname),
                                     encoding='utf-8')
            self.info("processing " + targetname + "... ", nonl=1)
            doctree = self.assemble_doctree(
                docname,
                toctree_only,
                appendices=(self.config.texinfo_appendices or []))
            self.info("writing... ", nonl=1)

            # Add an Index section
            if self.config.texinfo_domain_indices:
                doctree.append(
                    nodes.section(
                        '',
                        nodes.title(_("Index"),
                                    nodes.Text(_('Index'), _('Index'))),
                        nodes.raw('@printindex ge\n',
                                  nodes.Text('@printindex ge\n',
                                             '@printindex ge\n'),
                                  format="texinfo")))
            self.post_process_images(doctree)
            docwriter = TexinfoWriter(self)
            settings = OptionParser(
                defaults=self.env.settings,
                components=(docwriter, )).get_default_values()
            settings.author = author
            settings.title = title
            settings.texinfo_filename = targetname[:-5] + '.info'
            settings.texinfo_elements = self.config.texinfo_elements
            settings.texinfo_dir_entry = direntry or ''
            settings.texinfo_dir_category = category or ''
            settings.texinfo_dir_description = description or ''
            settings.docname = docname
            doctree.settings = settings
            docwriter.write(doctree, destination)
            self.info("done")
Beispiel #15
0
def test_help_text():
    """Test retrieving settings help text."""
    from docutils.frontend import OptionParser

    stream = io.StringIO()
    OptionParser(components=(Parser, )).print_help(stream)
    assert "MyST options" in stream.getvalue()
Beispiel #16
0
    def __init__(self, document, docstring_linker):
        # Set the document's settings.
        if self.settings is None:
            settings = OptionParser([LaTeXWriter()]).get_default_values()
            settings.output_encoding = 'utf-8'
            self.__class__.settings = settings
        document.settings = self.settings

        LaTeXTranslator.__init__(self, document)
        self._linker = docstring_linker

        # Start at section level 3.  (Unfortunately, we now have to
        # set a private variable to make this work; perhaps the standard
        # latex translator should grow an official way to spell this?)
        self.section_level = 3
        self._section_number = [0]*self.section_level
Beispiel #17
0
    def _generate_preview(self, page_id, contents):
        """
        Generate a preview for suggested changes.
        """
        handle, pathname = tempfile.mkstemp()
        os.write(handle, contents.encode('utf-8'))
        os.close(handle)

        warning_stream = StringIO.StringIO()
        env2 = copy.deepcopy(self.env)
        destination = StringOutput(encoding='utf-8')
        builder = MockBuilder()
        builder.config = env2.config
        writer = HTMLWriter(builder)
        doctree = env2.read_doc(page_id, pathname, save_parsed=False)
        doctree = env2.get_and_resolve_doctree(page_id + '.rst', builder,
                                               doctree)
        doctree.settings = OptionParser(
            defaults=env2.settings,
            components=(writer, )).get_default_values()
        doctree.reporter = Reporter(page_id + '.rst',
                                    2,
                                    4,
                                    stream=warning_stream)
        output = writer.write(doctree, destination)
        writer.assemble_parts()
        return writer.parts['fragment']
Beispiel #18
0
    def write(self, *ignored):
        super(CustomLaTeXBuilder, self).write(*ignored)

        backup_translator = sphinx.writers.latex.LaTeXTranslator
        sphinx.writers.latex.LaTeXTranslator = CustomLaTeXTranslator
        backup_doc = sphinx.writers.latex.BEGIN_DOC
        sphinx.writers.latex.BEGIN_DOC = ''

        # output these as include files
        for docname in ['abstract', 'dedication', 'acknowledgements']:
            destination = FileOutput(destination_path=os.path.join(
                self.outdir, '%s.inc' % docname),
                                     encoding='utf-8')

            docwriter = LaTeXWriter(self)
            doctree = self.env.get_doctree(docname)

            docsettings = OptionParser(
                defaults=self.env.settings,
                components=(docwriter, )).get_default_values()
            doctree.settings = docsettings
            docwriter.write(doctree, destination)

        sphinx.writers.latex.LaTeXTranslator = backup_translator
        sphinx.writers.latex.BEGIN_DOC = backup_doc
Beispiel #19
0
def parse_document(input_filename):
    with open(input_filename, 'r') as f:
        option_parser = OptionParser(components=(Parser, ), )

        default_settings = option_parser.get_default_values()

        settings = default_settings.copy()
        settings.update({
            'report_level': 100,
        }, option_parser)

        document = new_document(input_filename, settings)
        parser = Parser()
        parser.parse(f.read(), document)

        return document
Beispiel #20
0
def renderList(l, markDownHelp, settings=None):
    """
    Given a list of reStructuredText or MarkDown sections, return a docutils node list
    """
    if len(l) == 0:
        return []
    if markDownHelp:
        from sphinxarg.markdown import parseMarkDownBlock
        return parseMarkDownBlock('\n\n'.join(l) + '\n')
    else:
        all_children = []
        for element in l:
            if isinstance(element, str):
                if settings is None:
                    settings = OptionParser(
                        components=(Parser, )).get_default_values()
                document = new_document(None, settings)
                Parser().parse(element + '\n', document)
                all_children += document.children
            elif isinstance(element, (nodes.definition, nodes.description)):
                all_children += element
            else:
                assert False, element

        return all_children
Beispiel #21
0
    def __init__(self, document, docstring_linker):
        # Set the document's settings.
        if self.settings is None:
            settings = OptionParser([LaTeXWriter()]).get_default_values()
            settings.output_encoding = 'utf-8'
            self.__class__.settings = settings
        document.settings = self.settings

        LaTeXTranslator.__init__(self, document)
        self._linker = docstring_linker

        # Start at section level 3.  (Unfortunately, we now have to
        # set a private variable to make this work; perhaps the standard
        # latex translator should grow an official way to spell this?)
        self.section_level = 3
        self._section_number = [0]*self.section_level
Beispiel #22
0
    def write(self, *ignored):
        docwriter = LaTeXWriter(self)
        docsettings = OptionParser(
            defaults=self.env.settings,
            components=(docwriter,)).get_default_values()

        self.init_document_data()

        for entry in self.document_data:
            docname, targetname, title, author, docclass = entry[:5]
            toctree_only = False
            if len(entry) > 5:
                toctree_only = entry[5]
            destination = FileOutput(
                destination_path=path.join(self.outdir, targetname),
                encoding='utf-8')
            self.info("processing " + targetname + "... ", nonl=1)
            doctree = self.assemble_doctree(docname, toctree_only,
                appendices=((docclass != 'howto') and
                            self.config.latex_appendices or []))
            self.post_process_images(doctree)
            self.info("writing... ", nonl=1)
            doctree.settings = docsettings
            doctree.settings.author = author
            doctree.settings.title = title
            doctree.settings.docname = docname
            doctree.settings.docclass = docclass
            docwriter.write(doctree, destination)
            self.info("done")
Beispiel #23
0
    def write(self, *ignored):
        # type: (Any) -> None
        docwriter = ManualPageWriter(self)
        docsettings = OptionParser(
            defaults=self.env.settings,
            components=(docwriter,),
            read_config_files=True).get_default_values()  # type: Any

        logger.info(bold(__('writing... ')), nonl=True)

        for info in self.config.man_pages:
            docname, name, description, authors, section = info
            if docname not in self.env.all_docs:
                logger.warning(__('"man_pages" config value references unknown '
                                  'document %s'), docname)
                continue
            if isinstance(authors, str):
                if authors:
                    authors = [authors]
                else:
                    authors = []

            docsettings.title = name
            docsettings.subtitle = description
            docsettings.authors = authors
            docsettings.section = section

            targetname = '%s.%s' % (name, section)
            logger.info(darkgreen(targetname) + ' { ', nonl=True)
            destination = FileOutput(
                destination_path=path.join(self.outdir, targetname),
                encoding='utf-8')

            tree = self.env.get_doctree(docname)
            docnames = set()  # type: Set[str]
            largetree = inline_all_toctrees(self, docnames, docname, tree,
                                            darkgreen, [docname])
            largetree.settings = docsettings
            logger.info('} ', nonl=True)
            self.env.resolve_references(largetree, docname, self)
            # remove pending_xref nodes
            for pendingnode in largetree.traverse(addnodes.pending_xref):
                pendingnode.replace_self(pendingnode.children)

            docwriter.write(largetree, destination)
        logger.info('')
Beispiel #24
0
 def run(self):
     """Run the directive."""
     stream = io.StringIO()
     OptionParser(
         components=(DocutilsParser, ),
         usage="myst-docutils-<writer> [options] [<source> [<destination>]]",
     ).print_help(stream)
     return [nodes.literal_block("", stream.getvalue())]
Beispiel #25
0
        def __init__(self, document):
            # Copied from epydoc.markup.restructuredtext._EpydocHTMLTranslator
            if self.settings is None:
                settings = OptionParser([HTMLWriter()]).get_default_values()
                self.__class__.settings = settings
            document.settings = self.settings

            HTMLTranslator.__init__(self, document)
Beispiel #26
0
 def get_attr_types(docstring):
     parser = Parser()
     default_settings = OptionParser(components=(Parser,)).get_default_values()
     document = new_document('test_data', default_settings)
     parser.parse(docstring, document)
     visitor = AttrVisitor(document)
     document.walk(visitor)
     return visitor.args, visitor.returns
    def write_latex_document(self, latex_document_node,
                             all_latex_document_nodes):
        output_filename = latex_document_node["multilatex-filename"]
        variables       = latex_document_node["multilatex-variables"]
        content         = latex_document_node["multilatex-content"]
        options         = latex_document_node["multilatex-options"]
        docname         = latex_document_node["multilatex-docname"]
        doctree         = latex_document_node["multilatex-doctree"]

        if not output_filename.endswith(".tex"):
            output_filename += ".tex"
        self.info("processing {0}...".format(output_filename), nonl=1)

#        for node in doctree.traverse(latex_document):
#            node.parent.remove(node)
#        parent_node = latex_document_node.parent
#        parent_node.remove(latex_document_node)

        self.post_process_images(doctree)

        self.info("writing...", nonl=1)
        docwriter = LaTeXWriter(self)
        option_parser = OptionParser(
            defaults=self.env.settings,
            components=(docwriter,),
            read_config_files=True)

        doctree.settings = option_parser.get_default_values()
        settings = doctree.settings
        settings.contentsname = None
        settings.docname = docname
        for name, value in options.items():
            setattr(settings, name, value)
        settings.multilatex_options = options
        settings.multilatex_variables = variables
        settings.multilatex_content = content
        settings.multilatex_output_filename = output_filename
        settings.multilatex_all_latex_document_nodes = all_latex_document_nodes

        destination = FileOutput(
            destination_path=os.path.join(self.outdir, output_filename),
            encoding="utf-8")

        docwriter.write(doctree, destination)
        self.info("done")
Beispiel #28
0
def parse_rst(rst_string):
    parser = Parser()
    for name, class_ in []:  # Add custom directives here
        directives.register(name, class_)
    settings = OptionParser(components=(Parser, )).get_default_values()
    document = new_document("test", settings)
    parser.parse(rst_string, document)
    document = parser.document
    return document
    def build_markup(self):
        """Build markup"""
        from docutils.readers import Reader

        internal_rst = self.prepare_rst()
        self.info("Changelog code:\n%s" % internal_rst)
        internal_rst_fh = StringInput(source=internal_rst)
        reader = Reader(parser_name='rst')

        option_parser = OptionParser()
        settings = option_parser.get_default_values()
        settings.update(
            dict(tab_width=3,
                 pep_references=False,
                 rfc_references=False,
                 file_insertion_enabled=True), option_parser)
        document = reader.read(internal_rst_fh, reader.parser, settings)
        return document.children
Beispiel #30
0
    def write_latex_document(self, latex_document_node,
                             all_latex_document_nodes):
        output_filename = latex_document_node["multilatex-filename"]
        variables = latex_document_node["multilatex-variables"]
        content = latex_document_node["multilatex-content"]
        options = latex_document_node["multilatex-options"]
        docname = latex_document_node["multilatex-docname"]
        doctree = latex_document_node["multilatex-doctree"]

        if not output_filename.endswith(".tex"):
            output_filename += ".tex"
        self.info("processing {0}...".format(output_filename), nonl=1)

        #        for node in doctree.traverse(latex_document):
        #            node.parent.remove(node)
        #        parent_node = latex_document_node.parent
        #        parent_node.remove(latex_document_node)

        self.post_process_images(doctree)

        self.info("writing...", nonl=1)
        docwriter = LaTeXWriter(self)
        option_parser = OptionParser(defaults=self.env.settings,
                                     components=(docwriter, ),
                                     read_config_files=True)

        doctree.settings = option_parser.get_default_values()
        settings = doctree.settings
        settings.contentsname = None
        settings.docname = docname
        for name, value in options.items():
            setattr(settings, name, value)
        settings.multilatex_options = options
        settings.multilatex_variables = variables
        settings.multilatex_content = content
        settings.multilatex_output_filename = output_filename
        settings.multilatex_all_latex_document_nodes = all_latex_document_nodes

        destination = FileOutput(destination_path=os.path.join(
            self.outdir, output_filename),
                                 encoding="utf-8")

        docwriter.write(doctree, destination)
        self.info("done")
Beispiel #31
0
 def walk(p):
     d2 = new_document(
         p.pageName(),
         OptionParser(components=(Parser, )).get_default_values())
     Parser().parse(p.text(), d2)
     d += d2.traverse()
     for c in page.childrenNesting():
         c = p.pageWithName(c)
         walk(c)
         c.delete()
Beispiel #32
0
    def _parse_file(self, file: Path):
        settings = OptionParser(components=(Parser, )).get_default_values()
        parser = Parser()
        document = new_document(str(file), settings)
        with file.open() as f:
            input = f.read()

        directives.register_directive("test", TestDirective)
        parser.parse(input, document)
        return document
Beispiel #33
0
    def parse_rst(self, text: str) -> docutils.nodes.document:
        parser = sphinx.parsers.RSTParser()
        parser.set_application(self.env.app)

        settings = OptionParser(
            defaults=self.env.settings, components=(sphinx.parsers.RSTParser,), read_config_files=True
        ).get_default_values()
        document = docutils.utils.new_document("<rst-doc>", settings=settings)
        parser.parse(text, document)
        return document
Beispiel #34
0
    def __init__(self):

        self.settings = OptionParser(
            components=(rst.Parser, )).get_default_values()

        self.depth = 0
        self.doc = ""
        self.name = ""
        self.attributes = {}
        self.parameters = []
        self.state = []
Beispiel #35
0
def _lint_docutils(source, fpath, Parser, traceback):
    from io import StringIO
    from docutils.utils import new_document
    from docutils.frontend import OptionParser
    from docutils.utils import Reporter
    from .docutils import JsErrorPrinter

    parser = Parser()
    settings = OptionParser(components=(Parser, )).get_default_values()
    settings.traceback = traceback
    observer = JsErrorPrinter(StringIO(), settings)
    document = new_document(fpath, settings)

    document.reporter.report_level = 0  # Report all messages
    document.reporter.halt_level = Reporter.SEVERE_LEVEL + 1  # Do not exit early
    document.reporter.stream = False  # Disable textual reporting
    document.reporter.attach_observer(observer)
    parser.parse(source, document)

    return observer.stream.getvalue()
Beispiel #36
0
    def _get_document(self, content):
        settings = OptionParser(components=(Parser, )).get_default_values()
        directives.register_directive("test-block", TestBlockDirective)
        directives.register_directive("code-block", CodeBlockDirective)

        parser = Parser()
        source = str(self.source) if self.source else "lira-unknown-source"
        document = new_document(source, settings)

        parser.parse(content, document)
        return document
Beispiel #37
0
    def __init__(self, document: docutils.nodes.document,
                 docstring_linker: DocstringLinker):
        self._linker = docstring_linker

        # Set the document's settings.
        if self.settings is None:
            settings = OptionParser([HTMLWriter()]).get_default_values()
            self.__class__.settings = settings
        document.settings = self.settings

        super().__init__(document)
Beispiel #38
0
    def __init__(self, document, docstring_linker):
        self._linker = docstring_linker

        # Set the document's settings.
        if self.settings is None:
            settings = OptionParser([HTMLWriter()]).get_default_values()
            self.__class__.settings = settings
        document.settings = self.settings

        # Call the parent constructor.
        HTMLTranslator.__init__(self, document)
Beispiel #39
0
    def __init__(self, document, docstring_linker=None, directory=None,
                 docindex=None, context=None):
        # Set the document's settings.
        if self.settings is None:
            settings = OptionParser([LaTeXWriter()]).get_default_values()
            settings.output_encoding = 'utf-8'
            
            # This forces eg \EpydocUserSection rather than
            # \EpydocUserSEction*:
            settings.use_latex_toc = True
            
            self.__class__.settings = settings
        document.settings = self.settings

        LaTeXTranslator.__init__(self, document)
        self._linker = docstring_linker
        self._directory = directory
        self._docindex = docindex
        self._context = context

        # Use custom section names.
        self.d_class = _EpydocDocumentClass()
Beispiel #40
0
def parse_testplan(source, parsed, is_spec,check_errors=False):
    register_testplan_directives()
    oldstderr = sys.stderr
    docutils_out = StringIO.StringIO()
#    sys.stderr = docutils_out    
    valid = True
    reader_class=docutils.readers.get_reader_class("standalone")
    reader=reader_class(None,"rst")
    option_parser = OptionParser(
        components=(reader.parser, reader),
        defaults=[], read_config_files=1,
        usage="", description="")
    settings = option_parser.get_default_values()
#    try:
    reader.source = source
    reader.settings = settings
    reader.input = reader.source.read()
    reader.document = doc = reader.new_document()
    doc.parsed = parsed
    doc.check_errors = check_errors
    reader.parser.parse(reader.input, doc)
    doc.current_source = doc.current_line = None
    parsed = doc.parsed
#    except:
#        valid = False
#        parsed = None
    sys.stderr = oldstderr    
    err_msg = docutils_out.getvalue()
    
    if 'feature' in parsed:
        for f in parsed['feature']:
            try:
                f.from_spec
            except:
                f.from_spec = is_spec

    return (valid and err_msg.find("ERROR") == -1), err_msg, parsed
Beispiel #41
0
    def write(self, *ignored):
        # type: (Any) -> None
        self.init_document_data()
        for entry in self.document_data:
            docname, targetname, title, author = entry[:4]
            targetname += '.texi'
            direntry = description = category = ''
            if len(entry) > 6:
                direntry, description, category = entry[4:7]
            toctree_only = False
            if len(entry) > 7:
                toctree_only = entry[7]
            destination = FileOutput(
                destination_path=path.join(self.outdir, targetname),
                encoding='utf-8')
            with progress_message(__("processing %s") % targetname):
                appendices = self.config.texinfo_appendices or []
                doctree = self.assemble_doctree(docname, toctree_only, appendices=appendices)

            with progress_message(__("writing")):
                self.post_process_images(doctree)
                docwriter = TexinfoWriter(self)
                settings = OptionParser(
                    defaults=self.env.settings,
                    components=(docwriter,),
                    read_config_files=True).get_default_values()  # type: Any
                settings.author = author
                settings.title = title
                settings.texinfo_filename = targetname[:-5] + '.info'
                settings.texinfo_elements = self.config.texinfo_elements
                settings.texinfo_dir_entry = direntry or ''
                settings.texinfo_dir_category = category or ''
                settings.texinfo_dir_description = description or ''
                settings.docname = docname
                doctree.settings = settings
                docwriter.write(doctree, destination)
                self.copy_image_files(targetname[:-5])
Beispiel #42
0
    def write(self, *ignored):
        # type: (Any) -> None
        docwriter = LaTeXWriter(self)
        docsettings = OptionParser(
            defaults=self.env.settings,
            components=(docwriter,),
            read_config_files=True).get_default_values()  # type: Any

        self.init_document_data()
        self.write_stylesheet()

        for entry in self.document_data:
            docname, targetname, title, author, docclass = entry[:5]
            toctree_only = False
            if len(entry) > 5:
                toctree_only = entry[5]
            destination = SphinxFileOutput(destination_path=path.join(self.outdir, targetname),
                                           encoding='utf-8', overwrite_if_changed=True)
            logger.info(__("processing %s..."), targetname, nonl=1)
            toctrees = self.env.get_doctree(docname).traverse(addnodes.toctree)
            if toctrees:
                if toctrees[0].get('maxdepth') > 0:
                    tocdepth = toctrees[0].get('maxdepth')
                else:
                    tocdepth = None
            else:
                tocdepth = None
            doctree = self.assemble_doctree(
                docname, toctree_only,
                appendices=((docclass != 'howto') and self.config.latex_appendices or []))
            doctree['tocdepth'] = tocdepth
            self.apply_transforms(doctree)
            self.post_process_images(doctree)
            self.update_doc_context(title, author)

            logger.info(__("writing... "), nonl=1)
            docsettings.author = author
            docsettings.title = title
            docsettings.contentsname = self.get_contentsname(docname)
            docsettings.docname = docname
            docsettings.docclass = docclass

            doctree.settings = docsettings
            docwriter.write(doctree, destination)
            logger.info("done")
Beispiel #43
0
    def run(self):
        env = self.state.document.settings.env
        baseurl = env.config.rss_baseurl
        assert baseurl, 'rss_baseurl must be defined in your config.py'

        source = self.state_machine.input_lines.source(
            self.lineno - self.state_machine.input_offset - 1)

        rss_doc = utils.new_document('<rss>', self.state.document.settings)
        Parser().parse('\n'.join(self.content), rss_doc)

        path = os.path.relpath(source, env.srcdir)

        suffixes = env.config.source_suffix
        # retain backwards compatibility with sphinx < 1.3
        if isinstance(suffixes, basestring):
            suffixes = [suffixes]

        for suffix in suffixes:
            if path.endswith(suffix):
                path = '%s.html' % path[:-len(suffix)]
                break

        builder = env.app.builder
        docwriter = HTMLWriter(self)
        docsettings = OptionParser(
            defaults=env.settings,
            components=(docwriter,)).get_default_values()
        docsettings.compact_lists = bool(env.config.html_compact_lists)

        dest = os.path.join(env.app.outdir, os_path(env.docname) + '.rss')
        pageurl = '%s/%s' % (baseurl, path)
        with open(dest, 'w') as rss:
            title = self.options.get('title', '')
            description = self.options.get('description', None)
            rss.write('<?xml version="1.0" encoding="ISO-8859-1" ?>\n')
            rss.write('<rss version="2.0">\n')
            rss.write('<channel>\n')
            rss.write('<title>%s</title>\n' % cgi.escape(title))
            rss.write('<link>%s</link>\n' % pageurl)
            if description:
                rss.write('<description>%s</description>\n' % cgi.escape(description))

            for child in rss_doc.children:
                if not isinstance(child, nodes.section):
                    continue

                title_index = child.first_child_matching_class(nodes.title)
                if title_index is None:
                    continue

                node = nodes.paragraph()
                node.extend(child.children[title_index + 1:])

                sec_doc = utils.new_document('<rss-section>', docsettings)
                sec_doc.append(node)
                visitor = RssTranslator(builder, sec_doc)
                sec_doc.walkabout(visitor)

                title = child.children[title_index].astext()
                sectionurl = '%s#%s' % (pageurl, child.get('ids')[0])
                description = ''.join(visitor.body)

                rss.write('<item>\n')
                rss.write('<title>%s</title>\n' % cgi.escape(title))
                rss.write('<link>%s</link>\n' % sectionurl)
                rss.write('<description><![CDATA[%s]]></description>\n' % description)
                rss.write('</item>\n')
            rss.write('</channel>\n')
            rss.write('</rss>\n')

        return []
Beispiel #44
0
__docformat__ = 'reStructuredText'

import sys
from package import parse_package_or_module
import transform
from docutils.writers.html4css1 import Writer
from docutils.frontend import OptionParser

usage = '%prog [options] [<package-directory> | <python-file> [html-file]]'
description = ('Generates .html documentation for the given Python package'
               ' or module.')

writer = Writer()

option_parser = OptionParser(components=[writer],
                             usage=usage,description=description)

settings = option_parser.parse_args(sys.argv[1:])

source_path = settings._source
target_path = settings._destination

nodes = parse_package_or_module(source_path)

# That then needs converting to a docutils tree
document = transform.make_document(nodes,settings)

# And *that* wants converting to the appropriate output format
try:
    target = open(target_path,"w")
    writer.write(document,target)