Look in doctrees for toctree and replace with custom render
8831
def render_toctrees(kb_app: kb, sphinx_app: Sphinx, doctree: doctree,
                    fromdocname: str):
    

    # Only do any of this if toctree support is turned on in KaybeeSettings.
    # By default, this is off.
    settings: KaybeeSettings = sphinx_app.config.kaybee_settings
    if not settings.articles.use_toctree:
        return

    # Setup a template and context
    builder: StandaloneHTMLBuilder = sphinx_app.builder
    env: BuildEnvironment = sphinx_app.env

    # Toctree support. First, get the registered toctree class, if any
    registered_toctree = ToctreeAction.get_for_context(kb_app)
    for node in doctree.traverse(toctree):
        if node.attributes['hidden']:
            continue
        custom_toctree = registered_toctree(fromdocname)
        context = builder.globalcontext.copy()
        context['sphinx_app'] = sphinx_app

        # Get the toctree entries. We only handle one level of depth for
        # now. To go further, we need to recurse like sphinx's
        # adapters.toctree._toctree_add_classes function
        entries = node.attributes['entries']

        # The challenge here is that some items in a toctree
        # might not be resources in our "database". So we have
        # to ask Sphinx to get us the titles.
        custom_toctree.set_entries(entries, env.titles,
                                   sphinx_app.env.resources)
        output = custom_toctree.render(builder, context, sphinx_app)

        # Put the output into the node contents
        listing = [nodes.raw('', output, format='html')]
        node.replace_self(listing)
403705
def _build_toctree(self):
        
        dirname = posixpath.dirname(self._env.docname)
        tree_prefix = self.options['toctree'].strip()
        root = posixpath.normpath(posixpath.join(dirname, tree_prefix))
        docnames = [docname for docname in self._env.found_docs
                    if docname.startswith(root)]

        # Sort docnames alphabetically based on **class** name.
        # The standard we assume is that task doc pages are named after
        # their Python namespace.
        # NOTE: this ordering only applies to the toctree; the visual ordering
        # is set by `process_task_topic_list`.
        # NOTE: docnames are **always** POSIX-like paths
        class_names = [docname.split('/')[-1].split('.')[-1]
                       for docname in docnames]
        docnames = [docname for docname, _ in
                    sorted(zip(docnames, class_names),
                           key=lambda pair: pair[1])]

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

        return tocnode
856909
function buildTree(tokens) {
  var items = _.map(tokens, function(token) {
    return tartan.utils.node.newStripe(token);
  });
  var isReflected = (tokens.length >= 2) && (tokens[0].isPivot);
  return tartan.utils.node.newRootBlock(items, isReflected);
}
47117
def process_need_nodes(app, doctree, fromdocname):
    
    if not app.config.needs_include_needs:
        for node in doctree.traverse(Need):
            node.parent.remove(node)
        return

    env = app.builder.env

    # If no needs were defined, we do not need to do anything
    if not hasattr(env, "needs_all_needs"):
        return

    needs = env.needs_all_needs

    # Call dynamic functions and replace related note data with their return values
    resolve_dynamic_values(env)

    create_back_links(env)

    for node_need in doctree.traverse(Need):
        need_id = node_need.attributes["ids"][0]
        need_data = needs[need_id]

        find_and_replace_node_content(node_need, env, need_data)

        node_headline = construct_headline(need_data, app)
        node_meta = construct_meta(need_data, env)

        # Collapse check
        if need_data["collapse"] and "HTML" in app.builder.name.upper():
            # HEADER
            node_need_toogle_container = nodes.container(classes=['toggle'])
            node_need_toogle_head_container = nodes.container(classes=['header'])
            node_need_toogle_head_container += node_headline.children

            node_need_toogle_container.append(node_need_toogle_head_container)

            # Only add node_meta(line_block), if it has lines in it
            # Otherwise the pdf/latex build will claim about an empty line_block.
            if node_meta.children:
                node_need_toogle_container.append(node_meta)

            node_need.insert(0, node_need_toogle_container)
        else:
            node_meta.insert(0, node_headline)
            node_need.insert(0, node_meta)
291887
function renderPageTree(root, renderOpts) {

    renderOpts = u.assign({ openClass:'open' }, renderOpts);

    if (renderOpts.groupBy) {
      var folderPages =
        u.map(u.groupBy(root._children, renderOpts.groupBy), function(children, name) {
          if (name === 'undefined') { name = renderOpts.defaultGroup || ''; }
          return { folderPage: true,
                   _href:      name ? '/' + u.slugify(name) + '/' : '',
                   _children:  children,
                   name:       name };
        });
      return recurse(folderPages);
    }
    else return recurse(root._children);

    function recurse(children, pid) {
      pid = pid || renderOpts.pageTreeID || 'page-tree';
      var out = '\n<ul>';

      u.each(children, function(page) {
        var ppid = (pid + '-' + page._href).replace(/\W+/g, '-').replace(/^-|-$/g,'');
        out += '\n<li' + (page._children ? ' id="' + ppid + '" class="folder"' : '') + '>'
            + (page.folderPage ?
              ((page.name || page._href) ? '<span class="folderPage">' + (page.name || u.unslugify(page._href)) + '</span>' : '') :
              renderLink(u.assign({}, renderOpts, { href:page._href, title:(page.title || page.name) })))
            + (page._children ? recurse(page._children, ppid) : '')
            + '</li>';
      });
      return out + '\n</ul>';
    }
  }
398271
function renderTemplate(engine, filePath, content, context) {
    context = context || {};

    // Mutable objects to contains all blocks requiring post-processing
    var blocks = {};

    // Create nunjucks environment
    var env = engine.toNunjucks(blocks);

    // Replace shortcuts from plugin's blocks
    content = replaceShortcuts(engine.getBlocks(), filePath, content);

    return timing.measure(
        'template.render',

        Promise.nfcall(
            env.renderString.bind(env),
            content,
            context,
            {
                path: filePath
            }
        )
        .then(function(content) {
            return TemplateOutput.create(content, blocks);
        })
    );
}
1064752
function renderWithIntl (node, { context, childContextTypes } = {}) {
    const intlProvider = new IntlProvider({locale: locale, messages }, {});
    const { intl } = intlProvider.getChildContext();
    return render(React.cloneElement(node, { intl }), {
        context: Object.assign({}, context, {intl}),
        childContextTypes: Object.assign({}, { intl: intlShape }, childContextTypes)
    });
}
1003815
def build_full_toctree(builder, docname, prune, collapse):
    
    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
180865
def render(self, parsed, page=False, minify=False):
        
        rendered = []
        for i, p in enumerate(parsed):
            if i == 0:
                settings = p.get("settings", {})
                self.direction = settings.get("direction", DEFAULT_DIR)
                self.lang = settings.get("lang", DEFAULT_LANG)
            rendered.append(self.render_ents(p["text"], p["ents"], p.get("title")))
        if page:
            docs = "".join([TPL_FIGURE.format(content=doc) for doc in rendered])
            markup = TPL_PAGE.format(content=docs, lang=self.lang, dir=self.direction)
        else:
            markup = "".join(rendered)
        if minify:
            return minify_html(markup)
        return markup
399586
function renderTemplate(template, context) {
    var esc = $(document.createElement('div'));

    function handle(ph, escape) {
      var cur = context;
      $.each(ph.split('.'), function() {
        cur = cur[this];
      });
      return escape ? esc.text(cur || "").html() : cur;
    }

    return template.replace(/<([%#])([\w\.]*)\1>/g, function() {
      return handle(arguments[2], arguments[1] == '%' ? true : false);
    });
  }
246096
def render_tree(self, data):
        
        # TODO: find a way to make this localization aware...
        # because ATM it formats texts using French style numbers...
        # best way would be to let the user inject its own vars...
        # but this would not work on fusion servers...
        # so we must find a way to localize this a bit... or remove it and
        # consider our caller must pre - render its variables to the desired
        # locale...?
        new_data = dict(
            decimal=decimal,
            format_float=(
                lambda val: (
                    isinstance(
                        val, decimal.Decimal
                    ) or isinstance(
                        val, float
                    )
                ) and str(val).replace('.', ',') or val
            ),
            format_percentage=(
                lambda val: ("%0.2f %%" % val).replace('.', ',')
            )
        )

        # Soft page breaks are hints for applications for rendering a page
        # break. Soft page breaks in for loops may compromise the paragraph
        # formatting especially the margins. Open-/LibreOffice will regenerate
        # the page breaks when displaying the document. Therefore it is save to
        # remove them.
        self.remove_soft_breaks()

        # first we need to transform the py3o template into a valid
        # Genshi template.
        starting_tags, closing_tags = self.handle_instructions(
            self.content_trees,
            self.namespaces
        )
        parents = [tag[0].getparent() for tag in starting_tags]
        linknum = len(parents)
        parentnum = len(set(parents))
        if not linknum == parentnum:
            raise TemplateException(
                "Every py3o link instruction should be on its own line"
            )

        for link, py3o_base in starting_tags:
            self.handle_link(
                link,
                py3o_base,
                closing_tags[id(link)]
            )

        self.__prepare_userfield_decl()
        self.__prepare_usertexts()

        self.__replace_image_links()
        self.__add_images_to_manifest()

        for fnum, content_tree in enumerate(self.content_trees):
            content = lxml.etree.tostring(content_tree.getroot())
            if self.ignore_undefined_variables:
                template = MarkupTemplate(content, lookup='lenient')
            else:
                template = MarkupTemplate(content)

            # then we need to render the genshi template itself by
            # providing the data to genshi

            template_dict = {}
            template_dict.update(data.items())
            template_dict.update(new_data.items())

            self.output_streams.append(
                (
                    self.templated_files[fnum],
                    template.generate(**template_dict)
                )
            )
754848
def reverse_toctree(app, doctree, docname):
    """"""
    if docname == "changes":
        for node in doctree.traverse():
            if node.tagname == "toctree" and node.get("glob"):
                node["entries"].reverse()
                break
157771
function renderTypesWithChildrenToc( types, tocTemplate, transformers ) {
   const tocString = types.map( type =>
      ({
         name: type.name + transformers._deprecationTitle( type ),
         link: `#${type.name}`,
         children: ( type.children || [] )
            .map( member => {
               const commonPrefix = `${type.name}.${member.name}`;
               return {
                  link: `#${commonPrefix}`,
                  name: commonPrefix + ( isFunction( member ) ? '()' : '' ) +
                     transformers._deprecationTitle( member )
               };
            } )
      })
   );

   return tocTemplate( { entries: tocString } ).trim();
}
899119
function toHast(tree, options) {
  var h = factory(tree, options)
  var node = one(h, tree)
  var footnotes = footer(h)

  if (node && node.children && footnotes) {
    node.children = node.children.concat(u('text', '\n'), footnotes)
  }

  return node
}
1087041
function drawNodeContext(nodeId, nbHops){
    clearGraph();

    var node = searchNodeInTree(gTree, nodeId);
    if (!contains(gNodesDisplayed, node.node)){
        addNodeToGraph(node.node);
        addRelToGraph(node.node);
    }

    if (node.childNodes){
        var lastNode;
        var nodesWithChildren = [node];
        for (var i = 0; i < nbHops; ++i){
            var currentNode = nodesWithChildren[i];
            if (currentNode){
                var childNodes = currentNode.childNodes;
                for (var j = 0; j < childNodes.length; ++j){
                    var currChild = childNodes[j];
                    if (!contains(gNodesDisplayed, currChild.node)){
                        addNodeToGraph(currChild.node);
                    }
                    if (contains (gNodesWithRel, currChild.node)){
                        addRelToGraph(currChild.node);
                        nodesWithChildren.push(currChild);
                    }
                }
                lastNode = currentNode;
            } else {
                nbHops = (nodesWithChildren.length > nbHops ? nbHops : nodesWithChildren.length);
            }
        }
    }

    if (isPaused){
        renderer.rerender();
    }
}
983066
def render(pieces, style):
    """"""
    if pieces["error"]:
        return {"version": "unknown",
                "full-revisionid": pieces.get("long"),
                "dirty": None,
                "error": pieces["error"],
                "date": None}

    if not style or style == "default":
        style = "pep440"  # the default

    if style == "pep440":
        rendered = render_pep440(pieces)
    elif style == "pep440-pre":
        rendered = render_pep440_pre(pieces)
    elif style == "pep440-post":
        rendered = render_pep440_post(pieces)
    elif style == "pep440-old":
        rendered = render_pep440_old(pieces)
    elif style == "pep440-branch-based":
        rendered = render_pep440_branch_based(pieces)
    elif style == "git-describe":
        rendered = render_git_describe(pieces)
    elif style == "git-describe-long":
        rendered = render_git_describe_long(pieces)
    else:
        raise ValueError("unknown style '%s'" % style)

    return {"version": rendered, "full-revisionid": pieces["long"],
            "dirty": pieces["dirty"], "error": None,
            "date": pieces.get("date")}
584767
def _render_content(self, content, **settings):
        
        if isinstance(content, dict):
            return self._render_content_dict(content, 0, [], **settings)
        elif isinstance(content, list):
            return self._render_content_list(content, 0, [], **settings)
        else:
            raise Exception("Received invalid data tree for rendering.")