Skip to content

Backport PR #28289 on branch v3.9.x (Promote mpltype Sphinx role to a public extension) #28472

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/api/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ Alphabetical list of modules:
sphinxext_mathmpl_api.rst
sphinxext_plot_directive_api.rst
sphinxext_figmpl_directive_api.rst
sphinxext_roles.rst
spines_api.rst
style_api.rst
table_api.rst
Expand Down
7 changes: 7 additions & 0 deletions doc/api/next_api_changes/development/28289-ES.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Documentation-specific custom Sphinx roles are now semi-public
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

For third-party packages that derive types from Matplotlib, our use of custom roles may
prevent Sphinx from building their docs. These custom Sphinx roles are now public solely
for the purposes of use within projects that derive from Matplotlib types. See
:mod:`matplotlib.sphinxext.roles` for details.
7 changes: 7 additions & 0 deletions doc/api/sphinxext_roles.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
==============================
``matplotlib.sphinxext.roles``
==============================

.. automodule:: matplotlib.sphinxext.roles
:no-undoc-members:
:private-members: _rcparam_role, _mpltype_role
2 changes: 1 addition & 1 deletion doc/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,9 +116,9 @@ def _parse_skip_subdirs_file():
'sphinx_gallery.gen_gallery',
'matplotlib.sphinxext.mathmpl',
'matplotlib.sphinxext.plot_directive',
'matplotlib.sphinxext.roles',
'matplotlib.sphinxext.figmpl_directive',
'sphinxcontrib.inkscapeconverter',
'sphinxext.custom_roles',
'sphinxext.github',
'sphinxext.math_symbol_table',
'sphinxext.missing_references',
Expand Down
89 changes: 0 additions & 89 deletions doc/sphinxext/custom_roles.py

This file was deleted.

1 change: 1 addition & 0 deletions lib/matplotlib/sphinxext/meson.build
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ python_sources = [
'figmpl_directive.py',
'mathmpl.py',
'plot_directive.py',
'roles.py',
]

typing_sources = [
Expand Down
147 changes: 147 additions & 0 deletions lib/matplotlib/sphinxext/roles.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
"""
Custom roles for the Matplotlib documentation.

.. warning::

These roles are considered semi-public. They are only intended to be used in
the Matplotlib documentation.

However, it can happen that downstream packages end up pulling these roles into
their documentation, which will result in documentation build errors. The following
describes the exact mechanism and how to fix the errors.

There are two ways, Matplotlib docstrings can end up in downstream documentation.
You have to subclass a Matplotlib class and either use the ``:inherited-members:``
option in your autodoc configuration, or you have to override a method without
specifying a new docstring; the new method will inherit the original docstring and
still render in your autodoc. If the docstring contains one of the custom sphinx
roles, you'll see one of the following error messages:

.. code-block:: none

Unknown interpreted text role "mpltype".
Unknown interpreted text role "rc".

To fix this, you can add this module as extension to your sphinx :file:`conf.py`::

extensions = [
'matplotlib.sphinxext.roles',
# Other extensions.
]

.. warning::

Direct use of these roles in other packages is not officially supported. We
reserve the right to modify or remove these roles without prior notification.
"""

from urllib.parse import urlsplit, urlunsplit

from docutils import nodes

import matplotlib
from matplotlib import rcParamsDefault


class _QueryReference(nodes.Inline, nodes.TextElement):
"""
Wraps a reference or pending reference to add a query string.

The query string is generated from the attributes added to this node.

Also equivalent to a `~docutils.nodes.literal` node.
"""

def to_query_string(self):
"""Generate query string from node attributes."""
return '&'.join(f'{name}={value}' for name, value in self.attlist())


def _visit_query_reference_node(self, node):
"""
Resolve *node* into query strings on its ``reference`` children.

Then act as if this is a `~docutils.nodes.literal`.
"""
query = node.to_query_string()

Check warning on line 66 in lib/matplotlib/sphinxext/roles.py

View check run for this annotation

Codecov / codecov/patch

lib/matplotlib/sphinxext/roles.py#L66

Added line #L66 was not covered by tests
for refnode in node.findall(nodes.reference):
uri = urlsplit(refnode['refuri'])._replace(query=query)
refnode['refuri'] = urlunsplit(uri)

Check warning on line 69 in lib/matplotlib/sphinxext/roles.py

View check run for this annotation

Codecov / codecov/patch

lib/matplotlib/sphinxext/roles.py#L68-L69

Added lines #L68 - L69 were not covered by tests

self.visit_literal(node)

Check warning on line 71 in lib/matplotlib/sphinxext/roles.py

View check run for this annotation

Codecov / codecov/patch

lib/matplotlib/sphinxext/roles.py#L71

Added line #L71 was not covered by tests


def _depart_query_reference_node(self, node):
"""
Act as if this is a `~docutils.nodes.literal`.
"""
self.depart_literal(node)

Check warning on line 78 in lib/matplotlib/sphinxext/roles.py

View check run for this annotation

Codecov / codecov/patch

lib/matplotlib/sphinxext/roles.py#L78

Added line #L78 was not covered by tests


def _rcparam_role(name, rawtext, text, lineno, inliner, options=None, content=None):
"""
Sphinx role ``:rc:`` to highlight and link ``rcParams`` entries.

Usage: Give the desired ``rcParams`` key as parameter.

:code:`:rc:`figure.dpi`` will render as: :rc:`figure.dpi`
"""
# Generate a pending cross-reference so that Sphinx will ensure this link
# isn't broken at some point in the future.
title = f'rcParams["{text}"]'
target = 'matplotlibrc-sample'
ref_nodes, messages = inliner.interpreted(title, f'{title} <{target}>',

Check warning on line 93 in lib/matplotlib/sphinxext/roles.py

View check run for this annotation

Codecov / codecov/patch

lib/matplotlib/sphinxext/roles.py#L91-L93

Added lines #L91 - L93 were not covered by tests
'ref', lineno)

qr = _QueryReference(rawtext, highlight=text)
qr += ref_nodes
node_list = [qr]

Check warning on line 98 in lib/matplotlib/sphinxext/roles.py

View check run for this annotation

Codecov / codecov/patch

lib/matplotlib/sphinxext/roles.py#L96-L98

Added lines #L96 - L98 were not covered by tests

# The default backend would be printed as "agg", but that's not correct (as
# the default is actually determined by fallback).
if text in rcParamsDefault and text != "backend":
node_list.extend([

Check warning on line 103 in lib/matplotlib/sphinxext/roles.py

View check run for this annotation

Codecov / codecov/patch

lib/matplotlib/sphinxext/roles.py#L103

Added line #L103 was not covered by tests
nodes.Text(' (default: '),
nodes.literal('', repr(rcParamsDefault[text])),
nodes.Text(')'),
])

return node_list, messages

Check warning on line 109 in lib/matplotlib/sphinxext/roles.py

View check run for this annotation

Codecov / codecov/patch

lib/matplotlib/sphinxext/roles.py#L109

Added line #L109 was not covered by tests


def _mpltype_role(name, rawtext, text, lineno, inliner, options=None, content=None):
"""
Sphinx role ``:mpltype:`` for custom matplotlib types.

In Matplotlib, there are a number of type-like concepts that do not have a
direct type representation; example: color. This role allows to properly
highlight them in the docs and link to their definition.

Currently supported values:

- :code:`:mpltype:`color`` will render as: :mpltype:`color`

"""
mpltype = text
type_to_link_target = {

Check warning on line 126 in lib/matplotlib/sphinxext/roles.py

View check run for this annotation

Codecov / codecov/patch

lib/matplotlib/sphinxext/roles.py#L125-L126

Added lines #L125 - L126 were not covered by tests
'color': 'colors_def',
}
if mpltype not in type_to_link_target:
raise ValueError(f"Unknown mpltype: {mpltype!r}")

Check warning on line 130 in lib/matplotlib/sphinxext/roles.py

View check run for this annotation

Codecov / codecov/patch

lib/matplotlib/sphinxext/roles.py#L130

Added line #L130 was not covered by tests

node_list, messages = inliner.interpreted(

Check warning on line 132 in lib/matplotlib/sphinxext/roles.py

View check run for this annotation

Codecov / codecov/patch

lib/matplotlib/sphinxext/roles.py#L132

Added line #L132 was not covered by tests
mpltype, f'{mpltype} <{type_to_link_target[mpltype]}>', 'ref', lineno)
return node_list, messages

Check warning on line 134 in lib/matplotlib/sphinxext/roles.py

View check run for this annotation

Codecov / codecov/patch

lib/matplotlib/sphinxext/roles.py#L134

Added line #L134 was not covered by tests


def setup(app):
app.add_role("rc", _rcparam_role)
app.add_role("mpltype", _mpltype_role)
app.add_node(

Check warning on line 140 in lib/matplotlib/sphinxext/roles.py

View check run for this annotation

Codecov / codecov/patch

lib/matplotlib/sphinxext/roles.py#L138-L140

Added lines #L138 - L140 were not covered by tests
_QueryReference,
html=(_visit_query_reference_node, _depart_query_reference_node),
latex=(_visit_query_reference_node, _depart_query_reference_node),
text=(_visit_query_reference_node, _depart_query_reference_node),
)
return {"version": matplotlib.__version__,

Check warning on line 146 in lib/matplotlib/sphinxext/roles.py

View check run for this annotation

Codecov / codecov/patch

lib/matplotlib/sphinxext/roles.py#L146

Added line #L146 was not covered by tests
"parallel_read_safe": True, "parallel_write_safe": True}
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -283,11 +283,11 @@ ignore_directives = [
"include"
]
ignore_roles = [
# sphinxext.custom_roles
"rc",
# matplotlib.sphinxext.mathmpl
"mathmpl",
"math-stix",
# matplotlib.sphinxext.roles
"rc",
# sphinxext.github
"ghissue",
"ghpull",
Expand Down
Loading