From e91470f43d37eff43dca30625bba2149f6d6c0d6 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Wed, 19 Jun 2024 13:40:42 +0200 Subject: [PATCH] Add transform pass to sort fls_ ids to the back --- exts/ferrocene_spec/__init__.py | 2 ++ exts/ferrocene_spec/utils.py | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/exts/ferrocene_spec/__init__.py b/exts/ferrocene_spec/__init__.py index 1b4f5977..91d3ca33 100644 --- a/exts/ferrocene_spec/__init__.py +++ b/exts/ferrocene_spec/__init__.py @@ -3,6 +3,7 @@ from . import definitions, informational, syntax_directive, std_role, paragraph_ids from . import items_with_rubric +from .utils import FlsSortIds from sphinx.domains import Domain @@ -37,6 +38,7 @@ def is_empty(data): def setup(app): app.add_domain(SpecDomain) + app.add_transform(FlsSortIds) definitions.setup(app) paragraph_ids.setup(app) informational.setup(app) diff --git a/exts/ferrocene_spec/utils.py b/exts/ferrocene_spec/utils.py index b2634f70..24fce985 100644 --- a/exts/ferrocene_spec/utils.py +++ b/exts/ferrocene_spec/utils.py @@ -2,6 +2,7 @@ # SPDX-FileCopyrightText: The Ferrocene Developers from docutils import nodes +from sphinx import transforms def section_id_and_anchor(section): @@ -23,3 +24,25 @@ def section_id_and_anchor(section): class NoSectionIdError(RuntimeError): pass + + +# Sphinx by default 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 overwrite 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. +class FlsSortIds(transforms.SphinxTransform): + # Run this step after sphinx sorted. + default_priority = transforms.SortIds.default_priority + 1 + + def apply(self, **kwargs): + 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]]