Skip to content

HTML5 permalinks are not permanent if section header starts with number #8709

Open

Description

@abitrolly

In pip Changelog 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.

To Reproduce

#!/bin/bash

DOCDIR=testnumslug

rm -rf $DOCDIR
mkdir $DOCDIR

cat <<EOF > $DOCDIR/index.rst
Hi
==

1.2.0
-----

1.1.0
-----

1.0.0
-----
EOF

# Application error:
# config directory doesn't contain a conf.py file (testnumslug)
touch $DOCDIR/conf.py

sphinx-build $DOCDIR $DOCDIR/_html

echo -e "\n-----\n"

grep -R 'Permalink' $DOCDIR/_html/index.html

This gives the output.

<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>

Environment info

  • Python version: 3.9.1
  • Sphinx version: 3.2.1

Additional context

Activity

  1. uranusjr commented on Jan 20, 2021

    @uranusjr

    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:

    Hi
    ==
    
    .. _v1_2_0:
    
    1.2.0
    -----
    
    .. _v1_1_0:
    
    1.1.0
    -----
    
    .. _v1_0_0:
    
    1.0.0
    -----
    

    This would always work regardless of the section title.

  2. abitrolly commented on Jan 20, 2021

    @abitrolly
    ContributorAuthor

    Sphinx generates HTML5 by default since 2.0 #4587

  3. tk0miya commented on Jan 20, 2021

    @tk0miya
    Member

    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

  4. abitrolly commented on Jan 20, 2021

    @abitrolly
    ContributorAuthor

    What is the role of this function then?

    sphinx/sphinx/util/nodes.py

    Lines 435 to 439 in 3ed7590

    def _make_id(string: str) -> str:
    """Convert `string` into an identifier and return it.
    This function is a modified version of ``docutils.nodes.make_id()`` of
    docutils-0.16.

  5. tk0miya commented on Jan 20, 2021

    @tk0miya
    Member

    It's a local ID generator for Sphinx domains. It does not relate to the section IDs.

  6. abitrolly commented on Jan 20, 2021

    @abitrolly
    ContributorAuthor

    It looks like an override by import path. Although it doesn't make it any better.

    In [2]: from docutils.nodes import make_id                                                                                                                                
    In [3]: make_id('1.2.0')                                                                                                                                                  
    Out[3]: ''
    
    In [7]: from sphinx.util.nodes import _make_id                                                                                                                            
    In [8]: _make_id('1.2.0')                                                                                                                                                 
    Out[8]: ''
    

    Is it possible to define a function html5_id(string: str) and delegate HTML id generation to it?

  7. madjxatw commented on Jan 21, 2021

    @madjxatw

    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.

  8. abitrolly commented on Jan 21, 2021

    @abitrolly
    ContributorAuthor

    @madjxatw understood. HTML5 removes all restrictions from IDs, which makes even these valid.

    <p id="#">Foo.
    <p id="##">Bar.
    <p id="♥">Baz.
    <p id="©">Inga.
    <p id="{}">Lorem.
    <p id="“‘’”">Ipsum.
    <p id="⌘⌥">Dolor.
    <p id="{}">Sit.
    <p id="[attr=value]">Amet.
    <p id="++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.">Hello world!
    

    https://mathiasbynens.be/notes/html5-id-class

  9. madjxatw commented on Jan 21, 2021

    @madjxatw

    @abitrolly, exactly, so Sphinx needs to implement a HTML5 version of make_id() to keep consistency with its default HTML5 output.

  10. abitrolly commented on Jan 21, 2021

    @abitrolly
    ContributorAuthor

    @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.

  11. madjxatw commented on Jan 21, 2021

    @madjxatw

    @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.

  12. tk0miya commented on Jan 21, 2021

    @tk0miya
    Member

    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.

  13. madjxatw commented on Jan 21, 2021

    @madjxatw

    @tk0miya, is it possible to have an option that lets users decide whether to enable unicode permalink?

  14. tk0miya commented on Jan 21, 2021

    @tk0miya
    Member

    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.

  15. 14 remaining items

  16. gmilde commented on Jul 30, 2025

    @gmilde
    Contributor

    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.

  17. abitrolly commented on Jul 31, 2025

    @abitrolly
    ContributorAuthor

    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.

  18. onerandomusername commented on Nov 5, 2025

    @onerandomusername

    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.

    sphinx/sphinx/util/nodes.py

    Lines 538 to 562 in 9eb3d79

    def _make_id(string: str) -> str:
    """Convert `string` into an identifier and return it.
    This function is a modified version of ``docutils.nodes.make_id()`` of
    docutils-0.16.
    Changes:
    * Allow to use capital alphabet characters
    * Allow to use dots (".") and underscores ("_") for an identifier
    without a leading character.
    # Author: David Goodger <[email protected]>
    # Maintainer: [email protected]
    # Copyright: This module has been placed in the public domain.
    """
    id = string.translate(_non_id_translate_digraphs)
    id = id.translate(_non_id_translate)
    # get rid of non-ascii characters.
    # 'ascii' lowercase to prevent problems with turkish locale.
    id = unicodedata.normalize('NFKD', id).encode('ascii', 'ignore').decode('ascii')
    # shrink runs of whitespace and replace by hyphen
    id = _non_id_chars.sub('-', ' '.join(id.split()))
    id = _non_id_at_ends.sub('', id)
    return str(id)

    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

        # shrink runs of whitespace and replace by hyphen
        id = _non_id_chars.sub('-', ' '.join(id.split()))
        id = id.rstrip('-+')
        if not (clean_id := id.lstrip('0123456789-')):
            clean_id = "id-" + id
        return str(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 hyphen
        id = _non_id_chars.sub('-', ' '.join(id.split()))
        id = id.lstrip('-').rstrip('-+')
        if _non_id_at_ends.match(id):
            id = "id-" + id.lstrip()
        return str(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.

  19. onerandomusername commented on Nov 5, 2025

    @onerandomusername

    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.

  20. gmilde commented on Nov 6, 2025

    @gmilde
    Contributor

    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.

  21. onerandomusername commented on Nov 6, 2025

    @onerandomusername

    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.

  22. gmilde commented on Nov 7, 2025

    @gmilde
    Contributor

    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.

  23. abitrolly commented on Nov 21, 2025

    @abitrolly
    ContributorAuthor

    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.

  24. gmilde commented on Nov 21, 2025

    @gmilde
    Contributor

    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.

  25. abitrolly commented on Nov 22, 2025

    @abitrolly
    ContributorAuthor

    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.

  26. gmilde commented on Nov 22, 2025

    @gmilde
    Contributor

    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.

  27. abitrolly commented on Nov 22, 2025

    @abitrolly
    ContributorAuthor

    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.

  28. gmilde commented on Nov 22, 2025

    @gmilde
    Contributor

    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.

  29. abitrolly commented on Nov 22, 2025

    @abitrolly
    ContributorAuthor

    @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.

  30. gmilde commented on Nov 22, 2025

    @gmilde
    Contributor

    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().)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions