Take the 2-minute tour ×

Does anyone know any option to order toctree in descending order of the filenames? In case of ascending order, we can use :glob: option like this:

.. toctree:


This would be handy for daily notes written in restructured text that should be reported within a Sphinx document.

share|improve this question
add comment

2 Answers

up vote 6 down vote accepted

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"):

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:

share|improve this answer
Nice. Wouldn't this reverse every toctree though? You can probably add a check for a `:reversed: parameter to the toctree node to control this behavior, no? –  Kevin Horn Dec 24 '11 at 2:18
@Kevin Horn: The code reverses the toctree in the "index" (root) document if the :glob: option is used. The OP has not specified any detailed requirements, and I did not intend this answer to be more than a humble suggestion. I am sure that there are many ways to tweak it. Thanks for the comment and the upvote! –  mzjn Dec 24 '11 at 11:14
But this doesn't reverse the ToC in the sidebar. –  Adobe Nov 16 '12 at 8:22
add comment

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,

    def run(self):
        rst = super(NewTocTree, self).run()
        if 'reversed' in self.options:
        return rst

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

Which lets you do:


.. toctree::
   :maxdepth: 2

share|improve this answer
add comment

Your Answer


