From 9f24b25a619b21e77f9c3659432cd04a863c8eb4 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Wed, 19 Jun 2024 13:40:42 +0200 Subject: [PATCH] Monkey patch sphinx SortIDs transform to sort our own IDs --- exts/ferrocene_spec/__init__.py | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/exts/ferrocene_spec/__init__.py b/exts/ferrocene_spec/__init__.py index 1b4f5977..f27f4227 100644 --- a/exts/ferrocene_spec/__init__.py +++ b/exts/ferrocene_spec/__init__.py @@ -34,8 +34,8 @@ def is_empty(data): "there is data in the domain, merge_domaindata should be implemented" ) - def setup(app): + path_id_sorting() app.add_domain(SpecDomain) definitions.setup(app) paragraph_ids.setup(app) @@ -62,3 +62,26 @@ def setup(app): # - 1: changed how informational sections and pages are stored "env_version": "1", } + +# By default this transform sorts all ids of the form `id[0-9]+` to the end. +# Our IDs are section name and fls_ id pairs, so in some cases this transform +# will instead sort the section name to the back, but not always! +# So we patch the transform instead so that our fls ids are sorted to the back. +# In addition to that we normalize them, as sphinx turns the `_` in `fls_{id}` +# into `fls-{id}` which can break the link check from working correctly. +def path_id_sorting(): + def sort_and_patch_underscore(self, **kwargs) -> None: + from docutils import nodes + + for node in self.document.findall(nodes.section): + for n, id in enumerate(node["ids"]): + if id.startswith("fls-"): + node["ids"][n] = id[:3] + "_" + id[4:] + # sort the fls id to the back + if len(node["ids"]) > 1 and node["ids"][0].startswith("fls_"): + node["ids"] = node["ids"][1:] + [node["ids"][0]] + + from sphinx.transforms import SortIds + + SortIds.apply = sort_and_patch_underscore +