Skip to content

Instantly share code, notes, and snippets.

@AstraLuma
Created June 15, 2025 21:25
Show Gist options
  • Save AstraLuma/2c209dffe3e21fdcb526b304f45222d1 to your computer and use it in GitHub Desktop.
Save AstraLuma/2c209dffe3e21fdcb526b304f45222d1 to your computer and use it in GitHub Desktop.
build TOC files next to sphinx xml
import docutils
from docutils.io import StringOutput
import sphinx.builders.xml
class TOCXMLBuilder(sphinx.builders.xml.XMLBuilder):
name = "tocxml"
def write_doc(self, docname: str, doctree: docutils.nodes.document):
print(f"write_doc {docname=} {doctree=}")
from sphinx.environment.adapters.toctree import global_toctree_for_doc
toctree = global_toctree_for_doc(self.env, docname, self)
print(f"{toctree=}")
print(toctree.pformat())
super().write_doc(docname, doctree)
for node in toctree.findall(docutils.nodes.Element):
print(f"{node=}")
node.reporter = None
toctree.settings = doctree.settings
toctree.reporter = doctree.reporter
# This writer produces the wrong doctype, and we haven't dealt with any
# namespacing.
destination = StringOutput(encoding='utf-8')
self.writer.write(toctree, destination)
out_file_name = self.outdir / (docname + ".toc")
out_file_name.parent.mkdir(parents=True, exist_ok=True)
try:
with open(out_file_name, 'w', encoding='utf-8') as f:
f.write(self.writer.output)
except OSError as err:
logger.warning(__('error writing file %s: %s'), out_file_name, err)
def setup(app):
app.add_builder(TOCXMLBuilder)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment