Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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:
   :glob:

   2011*

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

like image 452
Philipp der Rautenberg Avatar asked Nov 30 '11 11:11

Philipp der Rautenberg


3 Answers

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
like image 98
mzjn Avatar answered Nov 15 '22 05:11

mzjn


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*
like image 42
Wraithan Avatar answered Nov 15 '22 06:11

Wraithan


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.

like image 3
brunston Avatar answered Nov 15 '22 07:11

brunston