How to loop over all documents and get meta information about existing directives in Sphinx?

89 Views Asked by At

I would like to create a custom Sphinx extension, that shows a list of all figures. Also see related question How to create list of all figures (tables) in Sphinx?

In the Sphinx documentation there is a ToDo example, where the ToDos instances are registered/managed in a global variable:

self.env.todo_all_todos.append...)

https://www.sphinx-doc.org/en/master/development/tutorials/todo.html

Instead of creating a custom .. my-figure:: directive, I would prefer to loop over the existing .. figure:: directives to extract the corresponding meta data.

=> How can I do so?

Below are some dummy code versions that have been hallucinated by AI. Unfortunately they do not work because the corresponding properties do not exist. At least they illustrate what I am looking for.

from docutils import nodes
from sphinx.util.docutils import SphinxDirective

class FigureListDirective(SphinxDirective):
       def run(self):
           env = self.state.document.settings.env
           figures = env.metadata.get('figures', [])
           return [nodes.paragraph('', '', nodes.Text(f'Figures: {", ".join(figures)}'))]

from docutils import nodes
from sphinx.util.docutils import SphinxDirective

class FigureListDirective(SphinxDirective):
    def run(self):
        env = self.state.document.settings.env
        figures = []

        # Loop over all figure nodes in the document
        for figure_node in env.get_domain('std').data['objects']['figure']:
            # Access the figure metadata
            figure_data = figure_node[0]['object']
            figures.append(figure_data)

        # Create a list node to hold the figures
        list_node = nodes.bullet_list()

        # Create list item nodes for each figure
        for figure_data in figures:
            list_item_node = nodes.list_item()
            list_item_node.append(nodes.paragraph(text=figure_data['name']))
            list_node.append(list_item_node)

        return [list_node]
0

There are 0 best solutions below