diff --git a/exts/ferrocene_spec/__init__.py b/exts/ferrocene_spec/__init__.py index 1b4f5977..4e068ae0 100644 --- a/exts/ferrocene_spec/__init__.py +++ b/exts/ferrocene_spec/__init__.py @@ -3,8 +3,9 @@ from . import definitions, informational, syntax_directive, std_role, paragraph_ids from . import items_with_rubric +from .utils import FlsSortIds from sphinx.domains import Domain - +import sphinx class SpecDomain(Domain): name = "spec" @@ -34,9 +35,9 @@ def is_empty(data): "there is data in the domain, merge_domaindata should be implemented" ) - 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..8036a806 100644 --- a/exts/ferrocene_spec/utils.py +++ b/exts/ferrocene_spec/utils.py @@ -2,7 +2,7 @@ # SPDX-FileCopyrightText: The Ferrocene Developers from docutils import nodes - +from sphinx import transforms def section_id_and_anchor(section): if "names" in section: @@ -23,3 +23,24 @@ 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]]