Пример #1
0
    def render_partial(self, node):
        # type: (nodes.Node) -> Dict[str, str]
        """Utility: Render a lone doctree node."""
        if node is None:
            return {'fragment': ''}
        doc = new_document('<partial node>')
        doc.append(node)

        if self._publisher is None:
            self._publisher = Publisher(
                source_class = DocTreeInput,
                destination_class=StringOutput)
            self._publisher.set_components('standalone',
                                           'restructuredtext', 'pseudoxml')

        pub = self._publisher

        pub.reader = DoctreeReader()
        pub.writer = HTMLWriter(self)
        pub.process_programmatic_settings(
            None, {'output_encoding': 'unicode'}, None)
        pub.set_source(doc, None)
        pub.set_destination(None, None)
        pub.publish()
        return pub.writer.parts
Пример #2
0
def get_sphinx():
    sphinx = getattr(local_data, 'sphinx', None)
    if sphinx is None:
        sphinx = Sphinx(tempdir,
                        tempdir,
                        tempdir,
                        tempdir,
                        'json',
                        status=None,
                        warning=None)
        sphinx.builder.translator_class = CustomHTMLTranslator

        sphinx.env.patch_lookup_functions()
        sphinx.env.temp_data['docname'] = 'text'
        sphinx.env.temp_data['default_domain'] = 'py'

        pub = Publisher(reader=None,
                        parser=None,
                        writer=HTMLWriter(sphinx.builder),
                        source_class=io.StringInput,
                        destination_class=io.NullOutput)
        pub.set_components('standalone', 'restructuredtext', None)
        pub.process_programmatic_settings(None, sphinx.env.settings, None)
        pub.set_destination(None, None)

        sphinx.publisher = pub

        local_data.sphinx = sphinx

    return sphinx, sphinx.publisher
Пример #3
0
 def render_partial(self, node):
     """Utility: Render a lone doctree node."""
     doc = new_document('<partial node>')
     doc.append(node)
     return publish_parts(doc,
                          source_class=DocTreeInput,
                          reader=DoctreeReader(),
                          writer=HTMLWriter(self),
                          settings_overrides={'output_encoding': 'unicode'})
Пример #4
0
 def prepare_writing(self, docnames):
     # type: (Set[unicode]) -> None
     """A place where you can add logic before :meth:`write_doc` is run"""
     self.writer = HTMLWriter(self)
     self.settings = OptionParser(
         defaults=self.env.settings,
         components=(self.writer,),
         read_config_files=True).get_default_values()
     self.settings.compact_lists = bool(self.config.html_compact_lists)
     # disable splitting field list table rows with too long field names,
     # fixing https://gitlab.com/mbukatov/pylatest/issues/44
     self.settings.field_name_limit = 0
Пример #5
0
    def render_partial(self, node: Node) -> Dict[str, str]:
        """Utility: Render a lone doctree node."""
        if node is None:
            return {'fragment': ''}
        doc = new_document('<partial node>')
        doc.append(node)

        writer = HTMLWriter(self)
        return publish_parts(reader_name='doctree',
                             writer=writer,
                             source_class=DocTreeInput,
                             settings_overrides={'output_encoding': 'unicode'},
                             source=doc)
Пример #6
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"]
Пример #7
0
 def prepare_writing(self, _doc_names: set[str]) -> None:
     self.docwriter = HTMLWriter(self)
     _opt_parser = OptionParser([self.docwriter],
                                defaults=self.env.settings,
                                read_config_files=True)
     self.docsettings = _opt_parser.get_default_values()
Пример #8
0
    def prepare_writing(self, docnames):
        # create the search indexer
        from sphinx.search import IndexBuilder, languages
        lang = self.config.html_search_language or self.config.language
        if not lang or lang not in languages:
            lang = 'en'
        self.indexer = IndexBuilder(self.env, lang,
                                    self.config.html_search_options,
                                    self.config.html_search_scorer)
        self.load_indexer(docnames)

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

        # determine the additional indices to include
        self.domain_indices = []
        # html_domain_indices can be False/True or a list of index names
        indices_config = self.config.html_domain_indices
        if indices_config:
            for domain in self.env.domains.itervalues():
                for indexcls in domain.indices:
                    indexname = '%s-%s' % (domain.name, indexcls.name)
                    if isinstance(indices_config, list):
                        if indexname not in indices_config:
                            continue
                    # deprecated config value
                    if indexname == 'py-modindex' and \
                           not self.config.html_use_modindex:
                        continue
                    content, collapse = indexcls(domain).generate()
                    if content:
                        self.domain_indices.append(
                            (indexname, indexcls, content, collapse))

        # format the "last updated on" string, only once is enough since it
        # typically doesn't include the time of day
        lufmt = self.config.html_last_updated_fmt
        if lufmt is not None:
            self.last_updated = ustrftime(lufmt or _('%b %d, %Y'))
        else:
            self.last_updated = None

        logo = self.config.html_logo and \
               path.basename(self.config.html_logo) or ''

        favicon = self.config.html_favicon and \
                  path.basename(self.config.html_favicon) or ''
        if favicon and os.path.splitext(favicon)[1] != '.ico':
            self.warn('html_favicon is not an .ico file')

        if not isinstance(self.config.html_use_opensearch, basestring):
            self.warn('html_use_opensearch config value must now be a string')

        self.relations = self.env.collect_relations()

        rellinks = []
        if self.get_builder_config('use_index', 'html'):
            rellinks.append(('genindex', _('General Index'), 'I', _('index')))
        for indexname, indexcls, content, collapse in self.domain_indices:
            # if it has a short name
            if indexcls.shortname:
                rellinks.append(
                    (indexname, indexcls.localname, '', indexcls.shortname))

        if self.config.html_style is not None:
            stylename = self.config.html_style
        elif self.theme:
            stylename = self.theme.get_confstr('theme', 'stylesheet')
        else:
            stylename = 'default.css'

        self.globalcontext = dict(
            embedded=self.embedded,
            project=self.config.project,
            release=self.config.release,
            version=self.config.version,
            last_updated=self.last_updated,
            copyright=self.config.copyright,
            master_doc=self.config.master_doc,
            use_opensearch=self.config.html_use_opensearch,
            docstitle=self.config.html_title,
            shorttitle=self.config.html_short_title,
            show_copyright=self.config.html_show_copyright,
            show_sphinx=self.config.html_show_sphinx,
            has_source=self.config.html_copy_source,
            show_source=self.config.html_show_sourcelink,
            file_suffix=self.out_suffix,
            script_files=self.script_files,
            css_files=self.css_files,
            sphinx_version=__version__,
            style=stylename,
            rellinks=rellinks,
            builder=self.name,
            parents=[],
            logo=logo,
            favicon=favicon,
        )
        if self.theme:
            self.globalcontext.update(('theme_' + key, val) for (
                key,
                val) in self.theme.get_options(self.theme_options).iteritems())
        self.globalcontext.update(self.config.html_context)
Пример #9
0
    def prepare_writing(self, docnames: Set[str]) -> None:
        # create the search indexer
        self.indexer = None
        if self.search:
            from sphinx.search import IndexBuilder
            lang = self.config.html_search_language or self.config.language
            if not lang:
                lang = 'en'
            self.indexer = IndexBuilder(self.env, lang,
                                        self.config.html_search_options,
                                        self.config.html_search_scorer)
            self.load_indexer(docnames)

        self.docwriter = HTMLWriter(self)
        self.docsettings = OptionParser(
            defaults=self.env.settings,
            components=(self.docwriter,),
            read_config_files=True).get_default_values()  # type: Any
        self.docsettings.compact_lists = bool(self.config.html_compact_lists)

        # determine the additional indices to include
        self.domain_indices = []
        # html_domain_indices can be False/True or a list of index names
        indices_config = self.config.html_domain_indices
        if indices_config:
            for domain_name in sorted(self.env.domains):
                domain = None  # type: Domain
                domain = self.env.domains[domain_name]
                for indexcls in domain.indices:
                    indexname = '%s-%s' % (domain.name, indexcls.name)
                    if isinstance(indices_config, list):
                        if indexname not in indices_config:
                            continue
                    content, collapse = indexcls(domain).generate()
                    if content:
                        self.domain_indices.append(
                            (indexname, indexcls, content, collapse))

        # format the "last updated on" string, only once is enough since it
        # typically doesn't include the time of day
        lufmt = self.config.html_last_updated_fmt
        if lufmt is not None:
            self.last_updated = format_date(lufmt or _('%b %d, %Y'),
                                            language=self.config.language)
        else:
            self.last_updated = None

        logo = self.config.html_logo and \
            path.basename(self.config.html_logo) or ''

        favicon = self.config.html_favicon and \
            path.basename(self.config.html_favicon) or ''

        if not isinstance(self.config.html_use_opensearch, str):
            logger.warning(__('html_use_opensearch config value must now be a string'))

        self.relations = self.env.collect_relations()

        rellinks = []  # type: List[Tuple[str, str, str, str]]
        if self.use_index:
            rellinks.append(('genindex', _('General Index'), 'I', _('index')))
        for indexname, indexcls, content, collapse in self.domain_indices:
            # if it has a short name
            if indexcls.shortname:
                rellinks.append((indexname, indexcls.localname,
                                 '', indexcls.shortname))

        if self.config.html_style is not None:
            stylename = self.config.html_style
        elif self.theme:
            stylename = self.theme.get_config('theme', 'stylesheet')
        else:
            stylename = 'default.css'

        self.globalcontext = {
            'embedded': self.embedded,
            'project': self.config.project,
            'release': return_codes_re.sub('', self.config.release),
            'version': self.config.version,
            'last_updated': self.last_updated,
            'copyright': self.config.copyright,
            'master_doc': self.config.master_doc,
            'use_opensearch': self.config.html_use_opensearch,
            'docstitle': self.config.html_title,
            'shorttitle': self.config.html_short_title,
            'show_copyright': self.config.html_show_copyright,
            'show_sphinx': self.config.html_show_sphinx,
            'has_source': self.config.html_copy_source,
            'show_source': self.config.html_show_sourcelink,
            'sourcelink_suffix': self.config.html_sourcelink_suffix,
            'file_suffix': self.out_suffix,
            'script_files': self.script_files,
            'language': self.config.language,
            'css_files': self.css_files,
            'sphinx_version': __display_version__,
            'style': stylename,
            'rellinks': rellinks,
            'builder': self.name,
            'parents': [],
            'logo': logo,
            'favicon': favicon,
            'html5_doctype': html5_ready and not self.config.html4_writer
        }
        if self.theme:
            self.globalcontext.update(
                ('theme_' + key, val) for (key, val) in
                self.theme.get_options(self.theme_options).items())
        self.globalcontext.update(self.config.html_context)
Пример #10
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 []
Пример #11
0
    def prepare_writing(self, docnames):
        from sphinx.search import IndexBuilder

        self.indexer = IndexBuilder(self.env)
        self.load_indexer(docnames)
        self.docwriter = HTMLWriter(self)
        self.docsettings = OptionParser(
            defaults=self.env.settings,
            components=(self.docwriter, )).get_default_values()

        # format the "last updated on" string, only once is enough since it
        # typically doesn't include the time of day
        lufmt = self.config.html_last_updated_fmt
        if lufmt is not None:
            self.last_updated = ustrftime(lufmt or _('%b %d, %Y'))
        else:
            self.last_updated = None

        logo = self.config.html_logo and \
               path.basename(self.config.html_logo) or ''

        favicon = self.config.html_favicon and \
                  path.basename(self.config.html_favicon) or ''
        if favicon and os.path.splitext(favicon)[1] != '.ico':
            self.warn('html_favicon is not an .ico file')

        if not isinstance(self.config.html_use_opensearch, basestring):
            self.warn('html_use_opensearch config value must now be a string')

        self.relations = self.env.collect_relations()

        rellinks = []
        if self.config.html_use_index:
            rellinks.append(('genindex', _('General Index'), 'I', _('index')))
        if self.config.html_use_modindex and self.env.modules:
            rellinks.append(
                ('modindex', _('Global Module Index'), 'M', _('modules')))

        if self.config.html_style is not None:
            stylename = self.config.html_style
        elif self.theme:
            stylename = self.theme.get_confstr('theme', 'stylesheet')
        else:
            stylename = 'default.css'

        self.globalcontext = dict(
            embedded=self.embedded,
            project=self.config.project,
            release=self.config.release,
            version=self.config.version,
            last_updated=self.last_updated,
            copyright=self.config.copyright,
            master_doc=self.config.master_doc,
            use_opensearch=self.config.html_use_opensearch,
            docstitle=self.config.html_title,
            shorttitle=self.config.html_short_title,
            show_copyright=self.config.html_show_copyright,
            show_sphinx=self.config.html_show_sphinx,
            has_source=self.config.html_copy_source,
            show_source=self.config.html_show_sourcelink,
            file_suffix=self.out_suffix,
            script_files=self.script_files,
            css_files=self.css_files,
            sphinx_version=__version__,
            style=stylename,
            rellinks=rellinks,
            builder=self.name,
            parents=[],
            logo=logo,
            favicon=favicon,
        )
        if self.theme:
            self.globalcontext.update(
                ('theme_' + key, val) for (key, val) in self.theme.get_options(
                    self.config.html_theme_options).iteritems())
        self.globalcontext.update(self.config.html_context)