From d1c4480f2a8e828c585794584ed016d05244f978 Mon Sep 17 00:00:00 2001 From: James Knight Date: Sun, 6 Oct 2024 17:54:02 -0400 Subject: [PATCH] Allow builders to override support for linkcode references (#12852) Signed-off-by: James Knight Co-authored-by: Adam Turner <9087854+aa-turner@users.noreply.github.com> --- CHANGES.rst | 3 +++ doc/extdev/builderapi.rst | 22 ++++++++++++++++++++++ sphinx/ext/linkcode.py | 8 +++++++- 3 files changed, 32 insertions(+), 1 deletion(-) diff --git a/CHANGES.rst b/CHANGES.rst index a0acf5227..7fa71f3d4 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -66,6 +66,9 @@ Features added Patch by Hugo van Kemenade. * #11809: Improve the formatting for RFC section anchors. Patch by Jakub Stasiak and Adam Turner. +* #12852: Support a :attr:`.Builder.supported_linkcode` attribute + for builders to enable use of :mod:`sphinx.ext.linkcode`-generated + references. Bugs fixed ---------- diff --git a/doc/extdev/builderapi.rst b/doc/extdev/builderapi.rst index 9259aaa73..b5520d332 100644 --- a/doc/extdev/builderapi.rst +++ b/doc/extdev/builderapi.rst @@ -64,3 +64,25 @@ Builder API .. attribute:: events An :class:`.EventManager` object. + + .. rubric:: Overridable Attributes (extensions) + + Builder sub-classes can set these attributes to support built-in extensions: + + .. attribute:: supported_linkcode + + By default, the :mod:`linkcode ` extension will + only inject references for an ``html`` builder. + The ``supported_linkcode`` attribute can be defined in a non-HTML builder + to support managing references generated by linkcode. + The expected value for this attribute is an expression + which is compatible with :rst:dir:`only`. + + For example, if a builder was named ``custom-builder``, + the following can be used: + + .. code-block:: python + + class CustomBuilder(Builder): + supported_linkcode = 'custom-builder' + ... diff --git a/sphinx/ext/linkcode.py b/sphinx/ext/linkcode.py index 93118cd67..6b722b483 100644 --- a/sphinx/ext/linkcode.py +++ b/sphinx/ext/linkcode.py @@ -31,6 +31,12 @@ def doctree_read(app: Sphinx, doctree: Node) -> None: raise LinkcodeError(msg) assert resolve_target is not None # for mypy + # By default, the linkcode extension will only inject references + # for an ``html`` builder. If a builder wishes to support managing + # references generated by linkcode as well, it can define the + # ``supported_linkcode`` attribute. + node_only_expr = getattr(app.builder, 'supported_linkcode', 'html') + domain_keys = { 'py': ['module', 'fullname'], 'c': ['names'], @@ -67,7 +73,7 @@ def doctree_read(app: Sphinx, doctree: Node) -> None: uris.add(uri) inline = nodes.inline('', _('[source]'), classes=['viewcode-link']) - onlynode = addnodes.only(expr='html') + onlynode = addnodes.only(expr=node_only_expr) onlynode += nodes.reference('', '', inline, internal=False, refuri=uri) signode += onlynode