Python sphinx.addnodes.toctree() Examples

The following are 24 code examples of sphinx.addnodes.toctree(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sphinx.addnodes , or try the search function .
Example #1
Source File: fulltoc.py    From toil with Apache License 2.0 6 votes vote down vote up
def get_rendered_toctree(builder, docname, **kwargs):
    """Build the toctree relative to the named document,
    with the given parameters, and then return the rendered
    HTML fragment.
    """
    
    if kwargs.get('prune', None) is None:
        kwargs['prune'] = False
    if kwargs.get('collapse', None) is None:
        kwargs['collapse'] = True
    
    fulltoc = build_full_toctree(builder,
                                 docname,
                                 **kwargs
                                 )
    rendered_toc = builder.render_partial(fulltoc)['fragment']
    return rendered_toc 
Example #2
Source File: pdfbuilder.py    From rst2pdf with MIT License 6 votes vote down vote up
def get_target_uri(self, docname, typ=None):
        # print 'GTU',docname,typ
        # FIXME: production lists are not supported yet!
        if typ == 'token':
            # token references are always inside production lists and must be
            # replaced by \token{} in LaTeX
            return '@token'
        if docname not in self.docnames:

            # It can be a 'main' document:
            for doc in self.document_data:
                if doc[0] == docname:
                    return "pdf:" + doc[1] + '.pdf'
            # It can be in some other document's toctree
            for indexname, toctree in self.env.toctree_includes.items():
                if docname in toctree:
                    for doc in self.document_data:
                        if doc[0] == indexname:
                            return "pdf:" + doc[1] + '.pdf'
            # No idea
            raise NoUri
        else:  # Local link
            return "" 
Example #3
Source File: __init__.py    From artview with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def process_autosummary_toc(app, doctree):
    """Insert items described in autosummary:: to the TOC tree, but do
    not generate the toctree:: list.
    """
    env = app.builder.env
    crawled = {}
    def crawl_toc(node, depth=1):
        crawled[node] = True
        for j, subnode in enumerate(node):
            try:
                if (isinstance(subnode, autosummary_toc)
                    and isinstance(subnode[0], addnodes.toctree)):
                    env.note_toctree(env.docname, subnode[0])
                    continue
            except IndexError:
                continue
            if not isinstance(subnode, nodes.section):
                continue
            if subnode not in crawled:
                crawl_toc(subnode, depth+1)
    crawl_toc(doctree) 
Example #4
Source File: fulltoc.py    From autopilot with Mozilla Public License 2.0 6 votes vote down vote up
def build_full_toctree(builder, docname, prune, collapse):
    """Return a single toctree starting from docname containing all
    sub-document doctrees.
    """
    env = builder.env
    doctree = env.get_doctree(env.config.master_doc)
    toctrees = []
    for toctreenode in doctree.traverse(addnodes.toctree):
        toctree = env.resolve_toctree(docname, builder, toctreenode,
                                      collapse=collapse,
                                      prune=prune,
                                      includehidden=True,
                                      )
        pdb.set_trace()
        if toctree is not None:
            toctrees.append(toctree)

    if not toctrees:
        return None
    result = toctrees[0]
    for toctree in toctrees[1:]:
        if toctree:
            result.extend(toctree.children)
    env.resolve_references(result, docname, builder)
    return result 
Example #5
Source File: fulltoc.py    From toil with Apache License 2.0 6 votes vote down vote up
def build_full_toctree(builder, docname, prune, collapse, **kwargs):
    """Return a single toctree starting from docname containing all
    sub-document doctrees.
    """
    env = builder.env
    doctree = env.get_doctree(env.config.master_doc)
    toctrees = []
    for toctreenode in doctree.traverse(addnodes.toctree):
        toctree = env.resolve_toctree(docname, builder, toctreenode,
                                      collapse=collapse,
                                      prune=prune,
                                      **kwargs
                                      )
        toctrees.append(toctree)
    if not toctrees:
        return None
    result = toctrees[0]
    for toctree in toctrees[1:]:
        if toctree:
            result.extend(toctree.children)
    env.resolve_references(result, docname, builder)
    return result 
Example #6
Source File: fulltoc.py    From RocketCEA with GNU General Public License v3.0 6 votes vote down vote up
def build_full_toctree(builder, docname, prune, collapse):
    """Return a single toctree starting from docname containing all
    sub-document doctrees.
    """
    env = builder.env
    doctree = env.get_doctree(env.config.master_doc)
    toctrees = []
    for toctreenode in doctree.traverse(addnodes.toctree):
        toctree = env.resolve_toctree(docname, builder, toctreenode,
                                      collapse=collapse,
                                      prune=prune,
                                      )
        toctrees.append(toctree)
    if not toctrees:
        return None
    result = toctrees[0]
    for toctree in toctrees[1:]:
        if toctree:
            result.extend(toctree.children)
    env.resolve_references(result, docname, builder)
    return result 
Example #7
Source File: fulltoc.py    From autopilot with Mozilla Public License 2.0 5 votes vote down vote up
def html_page_context(app, pagename, templatename, context, doctree):
    """Event handler for the html-page-context signal.
    Modifies the context directly.
     - Replaces the 'toc' value created by the HTML builder with one
       that shows all document titles and the local table of contents.
     - Sets display_toc to True so the table of contents is always
       displayed, even on empty pages.
     - Replaces the 'toctree' function with one that uses the entire
       document structure, ignores the maxdepth argument, and uses
       only prune and collapse.
    """
    rendered_toc = get_rendered_toctree(app.builder, pagename)

    context['toc'] = rendered_toc
    context['display_toc'] = True  # force toctree to display

    if "toctree" not in context:
        # json builder doesn't use toctree func, so nothing to replace
        return
    def make_toctree(collapse=True, maxdepth=-1, includehidden=True):
        return get_rendered_toctree(app.builder,
                                    pagename,
                                    prune=False,
                                    collapse=collapse,
                                    )
    context['toctree'] = make_toctree 
Example #8
Source File: autosummary__init__.py    From pyGSTi with Apache License 2.0 5 votes vote down vote up
def autosummary_toc_visit_html(self, node):
    """Hide autosummary toctree list in HTML output."""
    #print "DEBUG: SKIPPING ",node
    raise nodes.SkipNode 
Example #9
Source File: scope.py    From mindmeld with Apache License 2.0 5 votes vote down vote up
def doctree_read(app, doctree):
    for toctreenode in doctree.traverse(addnodes.toctree):
        for e in toctreenode["entries"]:
            ref = str(e[1])
            if ref in docs_to_remove:
                toctreenode["entries"].remove(e) 
Example #10
Source File: tocdepthfix.py    From megaman with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def fix_toc_entries(app, doctree):
    # Get the docname; I don't know why this isn't just passed in to the
    # callback
    # This seems a bit unreliable as it's undocumented, but it's not "private"
    # either:
    docname = app.builder.env.temp_data['docname']
    if app.builder.env.metadata[docname].get('tocdepth', 0) != 0:
        # We need to reprocess any TOC nodes in the doctree and make sure all
        # the files listed in any TOCs are noted
        for treenode in doctree.traverse(addnodes.toctree):
            app.builder.env.note_toctree(docname, treenode) 
Example #11
Source File: __init__.py    From artview with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def run(self):
        self.env = env = self.state.document.settings.env
        self.genopt = {}
        self.warnings = []

        names = [x.strip().split()[0] for x in self.content
                 if x.strip() and re.search(r'^[~a-zA-Z_]', x.strip()[0])]
        items = self.get_items(names)
        nodes = self.get_table(items)

        if 'toctree' in self.options:
            try:
                suffix = env.config.source_suffix[0]
            except:
                suffix = env.config.source_suffix
            dirname = posixpath.dirname(env.docname)

            tree_prefix = self.options['toctree'].strip()
            docnames = []
            for name, sig, summary, real_name in items:
                docname = posixpath.join(tree_prefix, real_name)
                if docname.endswith(suffix):
                    docname = docname[:-len(suffix)]
                docname = posixpath.normpath(posixpath.join(dirname, docname))
                if docname not in env.found_docs:
                    self.warn('toctree references unknown document %r'
                              % docname)
                docnames.append(docname)

            tocnode = addnodes.toctree()
            tocnode['includefiles'] = docnames
            tocnode['entries'] = [(None, docname) for docname in docnames]
            tocnode['maxdepth'] = -1
            tocnode['glob'] = None

            tocnode = autosummary_toc('', '', tocnode)
            nodes.append(tocnode)

        return self.warnings + nodes 
Example #12
Source File: __init__.py    From artview with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def autosummary_toc_visit_html(self, node):
    """Hide autosummary toctree list in HTML output."""
    raise nodes.SkipNode 
Example #13
Source File: autosummary__init__.py    From pyGSTi with Apache License 2.0 5 votes vote down vote up
def run(self):
        self.env = env = self.state.document.settings.env
        self.genopt = Options()
        self.warnings = []
        self.result = ViewList()

        names = [x.strip().split()[0] for x in self.content
                 if x.strip() and re.search(r'^[~a-zA-Z_]', x.strip()[0])]
        #print "DEBUG: running for ",names
        items = self.get_items(names)
        nodes = self.get_table(items)

        if 'toctree' in self.options:
            dirname = posixpath.dirname(env.docname)

            tree_prefix = self.options['toctree'].strip()
            docnames = []
            for name, sig, summary, real_name in items:
                docname = posixpath.join(tree_prefix, real_name)
                docname = posixpath.normpath(posixpath.join(dirname, docname))
                if docname not in env.found_docs:
                    self.warn('toctree references unknown document %r'
                              % docname)
                docnames.append(docname)

            tocnode = addnodes.toctree()
            tocnode['includefiles'] = docnames
            tocnode['entries'] = [(None, docn) for docn in docnames]
            tocnode['maxdepth'] = -1
            tocnode['glob'] = None

            tocnode = autosummary_toc('', '', tocnode)
            #print "DEBUG: appending toc node:",tocnode
            nodes.append(tocnode)

        return self.warnings + nodes 
Example #14
Source File: fulltoc.py    From autopilot with Mozilla Public License 2.0 5 votes vote down vote up
def get_rendered_toctree(builder, docname, prune=False, collapse=True):
    """Build the toctree relative to the named document,
    with the given parameters, and then return the rendered
    HTML fragment.
    """
    fulltoc = build_full_toctree(builder,
                                 docname,
                                 prune=prune,
                                 collapse=collapse,
                                 )
    rendered_toc = builder.render_partial(fulltoc)['fragment']
    return rendered_toc 
Example #15
Source File: tocdepthfix.py    From supersmoother with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def fix_toc_entries(app, doctree):
    # Get the docname; I don't know why this isn't just passed in to the
    # callback
    # This seems a bit unreliable as it's undocumented, but it's not "private"
    # either:
    docname = app.builder.env.temp_data['docname']
    if app.builder.env.metadata[docname].get('tocdepth', 0) != 0:
        # We need to reprocess any TOC nodes in the doctree and make sure all
        # the files listed in any TOCs are noted
        for treenode in doctree.traverse(addnodes.toctree):
            app.builder.env.note_toctree(docname, treenode) 
Example #16
Source File: conf.py    From incubator-ariatosca with Apache License 2.0 5 votes vote down vote up
def on_doctree_read(app, doctree):
    # Remove TOC entry (see: https://gist.github.com/kakawait/9215487)
    for toctreenode in doctree.traverse(addnodes.toctree):
        for e in toctreenode['entries']:
            ref = str(e[1])
            if ref in SKIP_DOCUMENTS:
                toctreenode['entries'].remove(e) 
Example #17
Source File: test_builders.py    From doepy with MIT License 5 votes vote down vote up
def test_empty():
    """Local TOC is showing, as toctree was empty"""
    for (app, status, warning) in build_all('test-empty'):
        assert app.env.get_doctree('index').traverse(addnodes.toctree)
        content = open(os.path.join(app.outdir, 'index.html')).read()
        if sphinx.version_info < (1, 4):
            if isinstance(app.builder, SingleFileHTMLBuilder):
                assert '<div class="toctree-wrapper compound">\n</div>' in content
                assert '<div class="local-toc">' in content
            else:
                global_toc = (
                    '<div class="toctree-wrapper compound">\n'
                    '<ul class="simple">\n</ul>\n'
                    '</div>'
                )
                local_toc = (
                    '<div class="local-toc"><ul class="simple">'
                    '</ul>\n</div>'
                )
                assert global_toc in content
                assert local_toc not in content
        else:
            global_toc = '<div class="toctree-wrapper compound">\n</div>'
            local_toc = (
                '<div class="local-toc"><ul>\n'
                '<li><a class="reference internal" href="#">test-empty</a></li>'
                '</ul>\n</div>'
            )
            assert global_toc in content
            assert local_toc not in content 
Example #18
Source File: autosummary__init__.py    From pyGSTi with Apache License 2.0 5 votes vote down vote up
def process_autosummary_toc(app, doctree):
    """Insert items described in autosummary:: to the TOC tree, but do
    not generate the toctree:: list.
    """
    #print "DEBUG: process_autosummary_toc"
    env = app.builder.env
    crawled = {}

    def crawl_toc(node, depth=1):
        crawled[node] = True
        for j, subnode in enumerate(node):
            #print "DEBUG: processing ",(j,subnode)
            try:
                if (isinstance(subnode, autosummary_toc) and
                        isinstance(subnode[0], addnodes.toctree)):
                    env.note_toctree(env.docname, subnode[0])
                    #print "DEBUG: ADDIND DOC!"
                    continue
            except IndexError:
                #print "DEBUG: indexerror"
                continue
            if not isinstance(subnode, nodes.section):
                #print "DEBUG: not instance"
                continue
            if subnode not in crawled:
                crawl_toc(subnode, depth+1)
    crawl_toc(doctree) 
Example #19
Source File: fulltoc.py    From toil with Apache License 2.0 5 votes vote down vote up
def html_page_context(app, pagename, templatename, context, doctree):
    """Event handler for the html-page-context signal.
    Modifies the context directly.
     - Replaces the 'toc' value created by the HTML builder with one
       that shows all document titles and the local table of contents.
     - Sets display_toc to True so the table of contents is always
       displayed, even on empty pages.
     - Replaces the 'toctree' function with one that uses the entire
       document structure, ignores the maxdepth argument, and uses
       only prune and collapse.
    """
    rendered_toc = get_rendered_toctree(app.builder, pagename)
    context['toc'] = rendered_toc
    context['display_toc'] = True  # force toctree to display

    if "toctree" not in context:
        # json builder doesn't use toctree func, so nothing to replace
        return

    def make_toctree(**kwargs):
        kwargs['prune'] = False
        return get_rendered_toctree(app.builder,
                                    pagename,
                                    **kwargs,
                                    )

    context['toctree'] = make_toctree 
Example #20
Source File: tocdepthfix.py    From gatspy with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def fix_toc_entries(app, doctree):
    # Get the docname; I don't know why this isn't just passed in to the
    # callback
    # This seems a bit unreliable as it's undocumented, but it's not "private"
    # either:
    docname = app.builder.env.temp_data['docname']
    if app.builder.env.metadata[docname].get('tocdepth', 0) != 0:
        # We need to reprocess any TOC nodes in the doctree and make sure all
        # the files listed in any TOCs are noted
        for treenode in doctree.traverse(addnodes.toctree):
            app.builder.env.note_toctree(docname, treenode) 
Example #21
Source File: test_builders.py    From doepy with MIT License 5 votes vote down vote up
def test_missing_toctree():
    """Local TOC is showing, as toctree was missing"""
    for (app, status, warning) in build_all('test-missing-toctree'):
        assert app.env.get_doctree('index').traverse(addnodes.toctree) == []
        content = open(os.path.join(app.outdir, 'index.html')).read()
        assert '<div class="toctree' not in content
        assert '<div class="local-toc">' in content 
Example #22
Source File: fulltoc.py    From RocketCEA with GNU General Public License v3.0 5 votes vote down vote up
def get_rendered_toctree(builder, docname, prune=False, collapse=True):
    """Build the toctree relative to the named document,
    with the given parameters, and then return the rendered
    HTML fragment.
    """
    fulltoc = build_full_toctree(builder,
                                 docname,
                                 prune=prune,
                                 collapse=collapse,
                                 )
    rendered_toc = builder.render_partial(fulltoc)['fragment']
    return rendered_toc 
Example #23
Source File: fulltoc.py    From RocketCEA with GNU General Public License v3.0 5 votes vote down vote up
def html_page_context(app, pagename, templatename, context, doctree):
    """Event handler for the html-page-context signal.

    Modifies the context directly.

     - Replaces the 'toc' value created by the HTML builder with one
       that shows all document titles and the local table of contents.
     - Sets display_toc to True so the table of contents is always
       displayed, even on empty pages.
     - Replaces the 'toctree' function with one that uses the entire
       document structure, ignores the maxdepth argument, and uses
       only prune and collapse.
    """
    rendered_toc = get_rendered_toctree(app.builder, pagename)
    context['toc'] = rendered_toc
    context['display_toc'] = True  # force toctree to display

    # Commented out the following on Sept 5, 2015 (sonofeft)
    #   On ReadTheDocs it was causing:
    #  "TypeError: <function make_toctree at 0x7f200cb11b90> is not JSON serializable"
    #def make_toctree(collapse=True):
    #    return get_rendered_toctree(app.builder,
    #                                pagename,
    #                                prune=False,
    #                                collapse=collapse,
    #                                )
    #context['toctree'] = make_toctree 
Example #24
Source File: test_builders.py    From doepy with MIT License 4 votes vote down vote up
def test_basic():
    for (app, status, warning) in build_all('test-basic'):
        assert app.env.get_doctree('index').traverse(addnodes.toctree)
        content = open(os.path.join(app.outdir, 'index.html')).read()

        if isinstance(app.builder, DirectoryHTMLBuilder):
            search = (
                '<div class="toctree-wrapper compound">\n'
                '<ul>\n'
                '<li class="toctree-l1">'
                '<a class="reference internal" href="foo/">foo</a>'
                '<ul>\n'
                '<li class="toctree-l2">'
                '<a class="reference internal" href="bar/">bar</a></li>\n'
                '</ul>\n'
                '</li>\n'
                '</ul>\n'
                '</div>'
            )
            assert search in content
        elif isinstance(app.builder, SingleFileHTMLBuilder):
            search = (
                '<div class="local-toc"><ul>\n'
                '<li class="toctree-l1">'
                '<a class="reference internal" href="index.html#document-foo">foo</a>'
                '<ul>\n'
                '<li class="toctree-l2">'
                '<a class="reference internal" href="index.html#document-bar">bar</a>'
                '</li>\n'
                '</ul>'
            )
            assert search in content
        else:
            search = (
                '<div class="toctree-wrapper compound">\n'
                '<ul>\n'
                '<li class="toctree-l1">'
                '<a class="reference internal" href="foo.html">foo</a>'
                '<ul>\n'
                '<li class="toctree-l2">'
                '<a class="reference internal" href="bar.html">bar</a></li>\n'
                '</ul>\n'
                '</li>\n'
                '</ul>\n'
                '</div>'
            )
            assert search in content, ('Missing search with builder {0}'
                                       .format(app.builder.name))