summaryrefslogtreecommitdiff
path: root/docs/_ext/autosectionlabel.py
blob: a6777b27a40fa9f5331282a228efb412ba268b9c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# -*- coding: utf-8 -*-
"""
    sphinx.ext.autosectionlabel
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~

    Allow reference sections by :ref: role using its title.

    :copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
    :license: BSD, see LICENSE for details.

    from sphinx version 1.8.4 to get readthedocs working
"""

from docutils import nodes

from sphinx.locale import __
from sphinx.util import logging
from sphinx.util.nodes import clean_astext

if False:
    # For type annotation
    from typing import Any, Dict  # NOQA
    from sphinx.application import Sphinx  # NOQA


logger = logging.getLogger(__name__)

if False:
    # For type annotation
    from typing import Any, Dict  # NOQA
    from sphinx.application import Sphinx  # NOQA


def register_sections_as_label(app, document):
    # type: (Sphinx, nodes.Node) -> None
    labels = app.env.domaindata['std']['labels']
    anonlabels = app.env.domaindata['std']['anonlabels']
    for node in document.traverse(nodes.section):
        labelid = node['ids'][0]
        docname = app.env.docname
        ref_name = getattr(node[0], 'rawsource', node[0].astext())
        if app.config.autosectionlabel_prefix_document:
            name = nodes.fully_normalize_name(docname + ':' + ref_name)
        else:
            name = nodes.fully_normalize_name(ref_name)
        sectname = clean_astext(node[0])

        if name in labels:
            if len(node['ids']) > 1:
                continue
            logger.warning(__('duplicate label %s, other instance in %s'),
                           name, app.env.doc2path(labels[name][0]),
                           location=node)

        anonlabels[name] = docname, labelid
        labels[name] = docname, labelid, sectname


def setup(app):
    # type: (Sphinx) -> Dict[unicode, Any]
    app.add_config_value('autosectionlabel_prefix_document', False, 'env')
    app.connect('doctree-read', register_sections_as_label)

    return {
        'version': 'builtin',
        'parallel_read_safe': True,
        'parallel_write_safe': True,
    }