Anchors used for links to headings

8 views
Skip to first unread message

bradley...@gmail.com

unread,
Dec 27, 2021, 6:10:16 AM12/27/21
to sphinx-users
I want to generate links from web pages that are not generated by sphinx,
to headings and sub-headings in web pages that are generated by sphinx.

I have noticed that sphinx automatically generates anchors for such links.
For example, using sphinx v4.1.2, if the test_link.rst file contains the text

        Title
        #####

        Heading 1
        *********

        Heading 2
        *********

        Heading-2
        *********

The the file test_link.hmtl generated by sphinx will contain the following
link anchor for the headings in test_link.html:

        Title: href="#title"
        Heading 1: href="#heading-1"
        Heading 2: href="#heading-2"
        Heading-2: href="#id1"

It seems that the heading text has been converted to lower case and that
spaces ' ' have been converted to dashes '-'. It also seems if a conversion
would yield the same value as a previous coversion, then a numbered id, that
increases by one each time it is needed, is used for the link.

1.  Are these conversion rules for link anchors correct ?

2.  Are there ther conversion rules; e.g., other times that the numbered ids
    are inserted (and hence increase by one).

2.  Are these rules part of the sphinx API; i.e., will it be the same in
    future versions of sphinx ?

Matt Documatt

unread,
Dec 27, 2021, 9:29:31 AM12/27/21
to sphinx...@googlegroups.com
Hello Bradley!
It is generally as you said.

Actually, these web-safe anchors are generated by Docutils, not Sphinx. Firstly, by nodes.make_id() function (https://repo.or.cz/docutils.git/blob/refs/heads/master:/docutils/docutils/nodes.py#l2232). In case of collision, "id1" anchors are coming from here https://repo.or.cz/docutils.git/blob/refs/heads/master:/docutils/docutils/nodes.py#l1423. I would not say it is a part of public API but is unlikely to be changed.

You might also consider setting explicit labels before titles. Either, manually

.. _my-custom-label:

Title
#####

.. _set-to-anything-1:

Heading 1
*********

Or, using an autosectionlabel builtin extension (https://www.sphinx-doc.org/en/master/usage/extensions/autosectionlabel.html).

--
Matt
https://techwriter.documatt.com
> --
> You received this message because you are subscribed to the Google Groups "sphinx-users" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to sphinx-users...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/sphinx-users/fb03ed68-56ee-4611-af6b-a246bb7c7bben%40googlegroups.com.

Reply all
Reply to author
Forward
0 new messages