How can I reverse order the toctree provided by the "glob" flag option?

This adds a reversed option to toctree.

from sphinx.directives import TocTree
from docutils.parsers.rst import directives

class NewTocTree(TocTree):
    option_spec = dict(TocTree.option_spec,
                       reversed=directives.flag)

    def run(self):
        rst = super(NewTocTree, self).run()
        if 'reversed' in self.options:
            rst[0][0]['entries'].reverse()
        return rst

def setup(app):
    app.add_directive('toctree', NewTocTree)

Which lets you do:

Contents:

.. toctree::
   :maxdepth: 2
   :reversed:
   :glob:

   20*

As of Sphinx 1.5+ there is a built-in :reversed: flag you can add to a toctree:

.. toctree::
   :glob:
   :reversed:

   2011*

For more information, see the Sphinx documentation.


There is no simple option to reverse-sort the toctree. But you can do it by modifying the document structure before it is written to file. Here is a suggestion. Add the following code to conf.py:

def reverse_toctree(app, doctree, docname):
    """Reverse the order of entries in the root toctree if 'glob' is used."""
    if docname == "index":
        for node in doctree.traverse():
            if node.tagname == "toctree" and node.get("glob"):
                node["entries"].reverse()
                break

def setup(app):
    app.connect("doctree-resolved", reverse_toctree)

The reverse_toctree() callback function is called when the doctree-resolved event is fired. The function locates the toctree node in the document tree and changes it in-place.

More details about Sphinx and Docutils APIs:

  • https://www.sphinx-doc.org/en/master/extdev/appapi.html
  • http://docutils.sourceforge.net/docs/ref/doctree.html