You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
HTML5 permalinks are not permanent if section header starts with number #8709
In pipChangelog slugs in html anchors are not permanently pointed to corresponding version. Instead, they are incremental position numbers, which start with #id1, so when new version of pip is released all anchors shift and start to point to a different version.
<h1>Hi<a class="headerlink" href="#hi" title="Permalink to this headline">¶</a></h1>
<h2>1.2.0<a class="headerlink" href="#id1" title="Permalink to this headline">¶</a></h2>
<h2>1.1.0<a class="headerlink" href="#id2" title="Permalink to this headline">¶</a></h2>
<h2>1.0.0<a class="headerlink" href="#id3" title="Permalink to this headline">¶</a></h2>
Expected behavior
<h1>Hi<a class="headerlink" href="#hi" title="Permalink to this headline">¶</a></h1>
<h2>1.2.0<a class="headerlink" href="#1.2.0" title="Permalink to this headline">¶</a></h2>
<h2>1.1.0<a class="headerlink" href="#1.1.0" title="Permalink to this headline">¶</a></h2>
<h2>1.0.0<a class="headerlink" href="#1.0.0" title="Permalink to this headline">¶</a></h2>
The reason to the current behaviour is likely due to the HTML4 spec:
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
So id="1.2.0" is technically invalid (although I suspect many browsers would handle it fine, since HTML5 loosened the restriction).
The behaviour still feels quite unintuitive to me, however. I would expect Sphinx to generate something more stable, such as id="id-1_2_0" instead.
With that said, you can always specify an explicit reference yourself:
The same behavior also goes with non-ASCII headers, producing idX. If a header consists of both ASCII and non-ASCII characters, all non-ASCII parts will be removed.
Sphinx has still supported HTML4 output. The HTML Help builder also depends on HTML4. In addition to this, I can't say the change does not affect other builders. Sphinx is not only for building HTML5.
I can't promise the option works fine for "all" builders. If I added it to Sphinx, I'll describe it as "it might work. But not promised. Please don't report us even if something broken" :-p
I think I can't provide such an option from the official. Please hack your own risk.
The workaround with an id-prefix can be used with current Docutils and Sphinx:
Example
In docutils.conf, set:
[parsers]
id_prefix: black:
Then, the "self-link" for the heading 25.1.0 becomes <a class="headerlink" href="#black:25-1-0" title="Link to this heading">¶</a>.
Side-effect: all ids in the project are prefixed with black: (reStructuredText "reference names" are not affected).
A simpler workaround would be to use headings starting with an ASCII letter (release 25.1.0 or similar) or to provide explicit targets like
.. _release 25.1.0:
25.1.0
=====
A configurable ID generation is still on the TODO list. Doing this right will break a lot of existing behaviour, so this needs to be done very carefully.
A configurable ID generation is still on the TODO list. Doing this right will break a lot of existing behaviour, so this need to be done very carefully.
Fixing permalinks for numbered headers will be sufficient to close this issue.
I've looked into this, and this may be a bug in both docutils and sphinx. I'm not entirely sure if sphinx.util.nodes._make_id overrides every instance of the fragment/anchor definition, but I can see this behaviour is present in docutils as well as sphinx.
Changing the end of this definition in docutils to use the following seems to work
# shrink runs of whitespace and replace by hyphenid=_non_id_chars.sub('-', ' '.join(id.split()))
id=id.rstrip('-+')
ifnot (clean_id:=id.lstrip('0123456789-')):
clean_id="id-"+idreturnstr(clean_id)
This could probably be optimized further, but it converts _non_id_at_ends: re.Pattern[str] = re.compile('^[-0-9]+|-+$') to be applied without regex, and continues to trim the end of the ID. If the ID is zeroed from the regex, then we take the original ID and apply id- to the front of it.
This may break existing fragments on existing projects, so proper thought and consideration is necessary for this bugfix.
Alternative implementation
If the id starts with a disallowed character, prepend id- to it, after using lstrip('-')
This would keep the entire string, where existing names such as 3 ways to contribute now becomes id-3-ways-to-contribute rather than ways-to-contribute (which might be a downside in this particular example.
# shrink runs of whitespace and replace by hyphenid=_non_id_chars.sub('-', ' '.join(id.split()))
id=id.lstrip('-').rstrip('-+')
if_non_id_at_ends.match(id):
id="id-"+id.lstrip()
returnstr(id)
_non_id_chars: re.Pattern[str] =re.compile('[^a-z0-9]+')
_non_id_at_ends: re.Pattern[str] =re.compile('^[0-9]')
I'm hoping to fix this as I was interesting in fixing this on the likes of black, pytest-cov, and more, but would love to fix it upstream so the entire ecosystem can benefit from this.
As changed IDs will affect all websites that link to Docutils/Sphinx-generated page fragments, this must be guarded with an opt-in setting.
I would treat (de-)capitalization different from allowed characters, as the rationale here is not compatibility with all output formats but author convenience (linking to a capitalized section in running text).
Getting a new refname/ID framework right is a quite complex issue, so I propose to use the Docutils EP framework for discussion and planning.
Further analysis means that we could check if the id is empty before making the id-xyz ID
If it's empty, re-perform normalisation, but before zeroing, add a id- prefix to the original ID, such that 7.0.0 (2025-10-3) becomes id-7-0-0-2025-10-3 which is different only in the leading characters if it were to start with an alphabet character. (id-7-0-0-2025-10-3 vs v7-0-0-2025-10-3)
But in the event of 7.0.0 release, normalisation would continue to normalize to release, and not have an impact.
This should keep nearly everything backwards compatible: the only IDs that would be impacted are ones that already have inconsistent (id-) IDs, such that the entire header is normalized to removed code and therefore not used.
Given that there is an easy workaround (use a section title or an explicit target with leading letter), adding some "magic" remedy for digit-only sections may be more trouble than its worth.
Getting a new refname/ID framework right is a quite complex issue, so I propose to use the Docutils EP framework for discussion and planning.
@gmilde just writing an article describing how the existing ID framework works, what is it goals, modularity/API, gotchas - would be a big deal, solving 80% of mental fog around this issue. What is refname and what is ID for the start.
Then, if Sphinx IDs are global and hierarchical, the HTML5 anchors are local to the page. Maintaining mapping of local anchor IDs to global ones may be the solution. If we have the map, we don't need to bother with the conversion rules. Moreover, the function that does the mapping could be overridden. It can even produce non-unique outputs, because there might be no requirement to go back from HTML5 anchor back to Sphinx ID. But the most benefit is that the ID assignment pipeline and process are crystal clear.
just writing an article describing how the existing ID framework works, what is it goals, modularity/API, gotchas - would be a big deal, solving 80% of mental fog around this issue. What is refname and what is ID for the start.
Reference names are specified by the author in rST input to identify an element of the document as possible target. They are also used in rST cross references to internal targets.
Identifiers are used to identify fragments of the output document and in cross-links to them from other parts of the output document, Sphinx-generated project documentation or external documents somewhere in the internet. They must adhere to all limitations imposed by the output-format.
Docutils recently completed the "Docutils Document Tree" reference. There you find a glossary with explanations for reference names and identifiers. It includes links to detailled descriptions of used terms.
Identifiers are used to identify fragments of the output document and in cross-links to them from other parts of the output document,
What about identifiers for source fragments?
We are dealing here with information loss when going from source NodeID to HTML markup anchor. I don't see that Docutils describes the tree of NodeIDs. NodeIDs should be address in the tree. Then it should be possible to dump the tree of NodeIDs. Then it should be possible to access all related NodeIDs in the hierarchy when generating certain element in output format. I don't see that spec covers it.
Identifiers are used to identify fragments of the output document and in cross-links to them from other parts of the output document,
What about identifiers for source fragments?
Which source?
In rST markup, we use "refeferene names" to specify anchors in the document and for references to them.
In the "Document Tree" and its "native Docutils XML" representation, nodes can be identified by a "refname" in the names attribute or by an "identifier" in the ids attribute. Both are comparable to the "id" attribute of XML and HTML elements. Both, "refname" and "identifier" must be unique in their namespace. However, "DocTree" elements may have more than one "refname" and more than one "identifier".
We are dealing here with information loss when going from source NodeID to HTML markup anchor. I don't see that Docutils describes the tree of NodeIDs. NodeIDs should be address in the tree. Then it should be possible to dump the tree of NodeIDs.
What do you mean by "tree of NodeIDs"? In XML and HTML, IDs are optional. Not all elements have one.
Can you give an example "NodeID", please? Do you mean something similar to an element's "xpath"?
Then it should be possible to access all related NodeIDs in the hierarchy when generating certain element in output format. I don't see that spec covers it.
In the Python implementation of the DocTree in the docutils.nodes module, there is a provision to access a document's elements by "identifier" (one of its ids) or "refname" (one of its names) via "internal attributes" of the "document" root element. This is documented in the docutils.nodes docstrings.
Do you mean something similar to an element's "xpath"?
Yes.By NodeID I think about XPath like "address".
The resulting HTML5 generator can then use the "address" and any associated fields for it to render content. And if is it a component based generator - like one responsible for HTML5 anchors - it could maintain own state and mapping how to transform "address" + fields into "anchor". Then we could just patch the component and cover it with tests.
The resulting HTML5 generator can then use the "address" and any associated fields for it to render content.
I don't think this would be an improvement over the current framework, where the output writer gets the "document" tree as a Python data structure and the "HTML translator" uses a "visitor pattern" calling transformation methods for each of the document tree's node.
The "element visiting" methods are called with the respective element node object as argument and hence have access to all its attributes + internal attributes + parents + children.
@gmilde am I right that the "HTML translator" is rooted deep inside Docutils, and that's the reason why is not easy to factor out "anchor writer" out of it? Component as I see it is a visitor, yes. But the one that internally maintains global mappings for consistency.
A HTML element's "id" and "href" attributes written as part of the start tag by docutils.writers._html_base.HTMLTranslator.starttag().
However, this "anchor writer" part does not do the work of maintaining global mappings.
In Docutils, the mappings are internal attributes of the "document" element (docutils.nodes.document). They are filled by the parser component and updated by several "transforms" (using auxiliary functions and methods in docutils.nodes).
Sphinx adds its own layer for the coordination of references across documents of a project.
For patching the section title "self-link" in Sphinx, look at the implementation added by Sphinx. (It differs from the implementation in docutils.writers.html5_polyglot.HTMLTranslator.section_title_tags().)
Activity
uranusjr commentedon Jan 20, 2021
The reason to the current behaviour is likely due to the HTML4 spec:
So
id="1.2.0"is technically invalid (although I suspect many browsers would handle it fine, since HTML5 loosened the restriction).The behaviour still feels quite unintuitive to me, however. I would expect Sphinx to generate something more stable, such as
id="id-1_2_0"instead.With that said, you can always specify an explicit reference yourself:
This would always work regardless of the section title.
abitrolly commentedon Jan 20, 2021
Sphinx generates HTML5 by default since 2.0 #4587
tk0miya commentedon Jan 20, 2021
It comes from the node ID generation rule of docutils; the core library of Sphinx. It was defined to support many kinds of formats.
https://repo.or.cz/docutils.git/blob/HEAD:/docutils/docutils/nodes.py#l2220
abitrolly commentedon Jan 20, 2021
What is the role of this function then?
sphinx/sphinx/util/nodes.py
Lines 435 to 439 in 3ed7590
tk0miya commentedon Jan 20, 2021
It's a local ID generator for Sphinx domains. It does not relate to the section IDs.
abitrolly commentedon Jan 20, 2021
It looks like an override by import path. Although it doesn't make it any better.
Is it possible to define a function
html5_id(string: str)and delegate HTML id generation to it?madjxatw commentedon Jan 21, 2021
The same behavior also goes with non-ASCII headers, producing
idX. If a header consists of both ASCII and non-ASCII characters, all non-ASCII parts will be removed.abitrolly commentedon Jan 21, 2021
@madjxatw understood. HTML5 removes all restrictions from IDs, which makes even these valid.
https://mathiasbynens.be/notes/html5-id-class
madjxatw commentedon Jan 21, 2021
@abitrolly, exactly, so Sphinx needs to implement a HTML5 version of
make_id()to keep consistency with its default HTML5 output.abitrolly commentedon Jan 21, 2021
@madjxatw not Sphinx, some human needs to sit down and write the code. While the code seems trivial, right now it is unclear where to place the code.
madjxatw commentedon Jan 21, 2021
@abitrolly, hopefully some unicode slugifier (e.g. https://github.com/mozilla/unicode-slugify) could be used as an extension or be integrated somehow into Sphinx.
tk0miya commentedon Jan 21, 2021
Sphinx has still supported HTML4 output. The HTML Help builder also depends on HTML4. In addition to this, I can't say the change does not affect other builders. Sphinx is not only for building HTML5.
madjxatw commentedon Jan 21, 2021
@tk0miya, is it possible to have an option that lets users decide whether to enable unicode permalink?
tk0miya commentedon Jan 21, 2021
I can't promise the option works fine for "all" builders. If I added it to Sphinx, I'll describe it as "it might work. But not promised. Please don't report us even if something broken" :-p
I think I can't provide such an option from the official. Please hack your own risk.
14 remaining items
gmilde commentedon Jul 30, 2025
The workaround with an id-prefix can be used with current Docutils and Sphinx:
Example
In
docutils.conf, set:Then, the "self-link" for the heading
25.1.0becomes<a class="headerlink" href="#black:25-1-0" title="Link to this heading">¶</a>.Side-effect: all ids in the project are prefixed with
black:(reStructuredText "reference names" are not affected).A simpler workaround would be to use headings starting with an ASCII letter (
release 25.1.0or similar) or to provide explicit targets likeA configurable ID generation is still on the TODO list. Doing this right will break a lot of existing behaviour, so this needs to be done very carefully.
abitrolly commentedon Jul 31, 2025
Fixing permalinks for numbered headers will be sufficient to close this issue.
onerandomusername commentedon Nov 5, 2025
I've looked into this, and this may be a bug in both docutils and sphinx. I'm not entirely sure if
sphinx.util.nodes._make_idoverrides every instance of the fragment/anchor definition, but I can see this behaviour is present in docutils as well as sphinx.sphinx/sphinx/util/nodes.py
Lines 538 to 562 in 9eb3d79
https://github.com/docutils/docutils/blob/a5b983b73263445510d032845a70082eec7e2ca9/docutils/docutils/nodes.py#L2942-L2987 (not sure why this isn't embedding)
Changing the end of this definition in docutils to use the following seems to work
This could probably be optimized further, but it converts
_non_id_at_ends: re.Pattern[str] = re.compile('^[-0-9]+|-+$')to be applied without regex, and continues to trim the end of the ID. If the ID is zeroed from the regex, then we take the original ID and applyid-to the front of it.This may break existing fragments on existing projects, so proper thought and consideration is necessary for this bugfix.
Alternative implementation
If the id starts with a disallowed character, prepend
id-to it, after usinglstrip('-')This would keep the entire string, where existing names such as
3 ways to contributenow becomesid-3-ways-to-contributerather thanways-to-contribute(which might be a downside in this particular example.I'm hoping to fix this as I was interesting in fixing this on the likes of black, pytest-cov, and more, but would love to fix it upstream so the entire ecosystem can benefit from this.
onerandomusername commentedon Nov 5, 2025
I've done some checking of the ecosystem to see what's affected on other projects, as this would impact a swath of notable projects.
Known affected projects (incomplete)
requests: https://requests.readthedocs.io/en/latest/community/updates/#id2
urllib3: https://urllib3.readthedocs.io/en/stable/changelog.html#id1
pypa: https://www.pypa.io/en/latest/history/#id1
flake8: https://flake8.pycqa.org/en/latest/release-notes/7.3.0.html#id1
PyNaCl: https://pynacl.readthedocs.io/en/latest/changelog/#id1
django: https://docs.djangoproject.com/en/5.2/releases/#id1
black: https://black.readthedocs.io/en/stable/change_log.html#id1
cython: https://cython.readthedocs.io/en/latest/src/changes.html#id1
Existing projects with workarounds
sqlalchemy: https://docs.sqlalchemy.org/en/20/changelog/changelog_20.html#change-2.0.42
alembic https://alembic.sqlalchemy.org/en/latest/changelog.html#change-1.17.2
cryptography*: https://cryptography.io/en/latest/changelog/#v46-0-3 (seems to have a workaround but would otherwise be impacted)
furo*: https://pradyunsg.me/furo/changelog/#energetic-eminence (less of an impact because each version has a code name)
pip*: https://pip.pypa.io/en/stable/news/#v25-3 (patched with a local plugin)
Potential negative impacts
https://bugzilla.readthedocs.io/en/latest/using/creating-an-account.html#creating-an-account (at least one example but more exist)
Source of these projects: https://www.sphinx-doc.org/en/master/examples.html, combined with some moderately random selection, and manual checking of changelog pages.
gmilde commentedon Nov 6, 2025
As changed IDs will affect all websites that link to Docutils/Sphinx-generated page fragments, this must be guarded with an opt-in setting.
I would treat (de-)capitalization different from allowed characters, as the rationale here is not compatibility with all output formats but author convenience (linking to a capitalized section in running text).
Getting a new refname/ID framework right is a quite complex issue, so I propose to use the Docutils EP framework for discussion and planning.
onerandomusername commentedon Nov 6, 2025
Further analysis means that we could check if the id is empty before making the id-xyz ID
If it's empty, re-perform normalisation, but before zeroing, add a id- prefix to the original ID, such that
7.0.0 (2025-10-3)becomesid-7-0-0-2025-10-3which is different only in the leading characters if it were to start with an alphabet character. (id-7-0-0-2025-10-3vsv7-0-0-2025-10-3)But in the event of
7.0.0 release, normalisation would continue to normalize torelease, and not have an impact.This should keep nearly everything backwards compatible: the only IDs that would be impacted are ones that already have inconsistent (id-) IDs, such that the entire header is normalized to removed code and therefore not used.
gmilde commentedon Nov 7, 2025
Given that there is an easy workaround (use a section title or an explicit target with leading letter), adding some "magic" remedy for digit-only sections may be more trouble than its worth.
An option to allow more permissive rules for ID formation will solve both, this issue and the issue of auto-generated IDs for sections that don't use the Latin alphabet.
cf. Support Chinese in html permalink href #13800 and Docutils feature request #66.
abitrolly commentedon Nov 21, 2025
@gmilde just writing an article describing how the existing ID framework works, what is it goals, modularity/API, gotchas - would be a big deal, solving 80% of mental fog around this issue. What is refname and what is ID for the start.
Then, if Sphinx IDs are global and hierarchical, the HTML5 anchors are local to the page. Maintaining mapping of local anchor IDs to global ones may be the solution. If we have the map, we don't need to bother with the conversion rules. Moreover, the function that does the mapping could be overridden. It can even produce non-unique outputs, because there might be no requirement to go back from HTML5 anchor back to Sphinx ID. But the most benefit is that the ID assignment pipeline and process are crystal clear.
gmilde commentedon Nov 21, 2025
Reference names are specified by the author in rST input to identify an element of the document as possible target. They are also used in rST cross references to internal targets.
Identifiers are used to identify fragments of the output document and in cross-links to them from other parts of the output document, Sphinx-generated project documentation or external documents somewhere in the internet. They must adhere to all limitations imposed by the output-format.
Docutils recently completed the "Docutils Document Tree" reference. There you find a glossary with explanations for reference names and identifiers. It includes links to detailled descriptions of used terms.
abitrolly commentedon Nov 22, 2025
What about identifiers for source fragments?
We are dealing here with information loss when going from source NodeID to HTML markup anchor. I don't see that Docutils describes the tree of NodeIDs. NodeIDs should be address in the tree. Then it should be possible to dump the tree of NodeIDs. Then it should be possible to access all related NodeIDs in the hierarchy when generating certain element in output format. I don't see that spec covers it.
gmilde commentedon Nov 22, 2025
Which source?
What do you mean by "tree of NodeIDs"? In XML and HTML, IDs are optional. Not all elements have one.
Can you give an example "NodeID", please? Do you mean something similar to an element's "xpath"?
In the Python implementation of the DocTree in the
docutils.nodesmodule, there is a provision to access a document's elements by "identifier" (one of its ids) or "refname" (one of its names) via "internal attributes" of the "document" root element. This is documented in thedocutils.nodesdocstrings.abitrolly commentedon Nov 22, 2025
Yes.By NodeID I think about XPath like "address".
The resulting HTML5 generator can then use the "address" and any associated fields for it to render content. And if is it a component based generator - like one responsible for HTML5 anchors - it could maintain own state and mapping how to transform "address" + fields into "anchor". Then we could just patch the component and cover it with tests.
gmilde commentedon Nov 22, 2025
I don't think this would be an improvement over the current framework, where the output writer gets the "document" tree as a Python data structure and the "HTML translator" uses a "visitor pattern" calling transformation methods for each of the document tree's node.
The "element visiting" methods are called with the respective element node object as argument and hence have access to all its attributes + internal attributes + parents + children.
abitrolly commentedon Nov 22, 2025
@gmilde am I right that the "HTML translator" is rooted deep inside Docutils, and that's the reason why is not easy to factor out "anchor writer" out of it? Component as I see it is a visitor, yes. But the one that internally maintains global mappings for consistency.
gmilde commentedon Nov 22, 2025
A HTML element's "id" and "href" attributes written as part of the start tag by
docutils.writers._html_base.HTMLTranslator.starttag().However, this "anchor writer" part does not do the work of maintaining global mappings.
In Docutils, the mappings are internal attributes of the "document" element (
docutils.nodes.document). They are filled by the parser component and updated by several "transforms" (using auxiliary functions and methods indocutils.nodes).Sphinx adds its own layer for the coordination of references across documents of a project.
For patching the section title "self-link" in Sphinx, look at the implementation added by Sphinx. (It differs from the implementation in
docutils.writers.html5_polyglot.HTMLTranslator.section_title_tags().)