__init__.py

Summary

Lines:

367 of 396 covered (92.7%)

Branches:

108 of 124 taken (87.1%), 8 lines partially

Coverage:

91.3%

Directory:

Sphinx

Missed lines:

352, 357, 384, 391, 493-509, 572, 750, 821, 885, 912-914, 936-944

Source

pyTooling/Sphinx/__init__.pycoveredpartialuncoveredexcludednot executable
1# ==================================================================================================================== #
2#             _____           _ _               ____        _     _                                                    #
3#  _ __  _   |_   _|__   ___ | (_)_ __   __ _  / ___| _ __ | |__ (_)_ __ __  __                                        #
4# | '_ \| | | || |/ _ \ / _ \| | | '_ \ / _` | \___ \| '_ \| '_ \| | '_ \\ \/ /                                        #
5# | |_) | |_| || | (_) | (_) | | | | | | (_| |_ ___) | |_) | | | | | | | |>  <                                         #
6# | .__/ \__, ||_|\___/ \___/|_|_|_| |_|\__, (_)____/| .__/|_| |_|_|_| |_/_/\_\                                        #
7# |_|    |___/                          |___/        |_|                                                               #
8# ==================================================================================================================== #
9# Authors:                                                                                                             #
10#   Patrick Lehmann                                                                                                    #
11#                                                                                                                      #
12# License:                                                                                                             #
13# ==================================================================================================================== #
14# Copyright 2023-2026 Patrick Lehmann - Bötzingen, Germany                                                             #
15#                                                                                                                      #
16# Licensed under the Apache License, Version 2.0 (the "License");                                                      #
17# you may not use this file except in compliance with the License.                                                     #
18# You may obtain a copy of the License at                                                                              #
19#                                                                                                                      #
20#   http://www.apache.org/licenses/LICENSE-2.0                                                                         #
21#                                                                                                                      #
22# Unless required by applicable law or agreed to in writing, software                                                  #
23# distributed under the License is distributed on an "AS IS" BASIS,                                                    #
24# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.                                             #
25# See the License for the specific language governing permissions and                                                  #
26# limitations under the License.                                                                                       #
27#                                                                                                                      #
28# SPDX-License-Identifier: Apache-2.0                                                                                  #
29# ==================================================================================================================== #
30#
31"""
32A Sphinx extension providing the roles, nodes and directives shared by pyTooling and its sibling projects.
33
34Every project in the family used to carry its own :file:`doc/prolog.inc` - eighteen hand-copied files, 36 to 67
35lines each, already drifted apart - declaring the same roles as **ReST source** that is re-parsed into every
36document of every project. This extension declares them once:
37
38.. code-block:: Python
39
40   # doc/conf.py
41   extensions = [
42     ...,
43     "pyTooling.Sphinx",
44   ]
45
46.. rubric:: What it registers
47
48* the **style roles**, together with the stylesheet they need - so the styling is a CSS file instead of a
49  ``raw:: html`` block smuggled into every page - and the LaTeX package :file:`pyTooling.Sphinx.sty`, which strikes
50  through and underlines in LaTeX:
51
52  * ``:bolditalic:``, ``:underline:``, ``:strike:`` and ``:xlarge:`` - weight, decoration and size;
53  * ``:red:``, ``:green:``, ``:blue:`` and ``:purple:`` - colour, each from a CSS custom property a project can
54    redefine;
55  * ``:deletion:`` and ``:addition:`` - the two a diff needs.
56
57* the **code role**:
58
59  * ``:pycode:`` - highlights inline Python.
60
61* the **abbreviation roles**, named as in LaTeX' ``acro`` package:
62
63  * ``:acs:``, ``:acl:`` and ``:acf:`` - an abbreviation, its long form, or both;
64  * ``:acsp:``, ``:aclp:`` and ``:acfp:`` - their plurals.
65
66* the **directives**:
67
68  * :rst:dir:`condensed-class` - renders a class' public interface from its source;
69  * :rst:dir:`dependency-table` - renders a project's dependencies from its requirements files, which
70    :file:`conf.py` declares under ``pyTooling_Dependency_Requirements``;
71  * :rst:dir:`xmlschema-graph` - draws an XML schema as a Graphviz graph. It sets up :mod:`sphinx.ext.graphviz`
72    itself, and needs :mod:`xmlschema` only in a project that uses it.
73  * :rst:dir:`shields` - renders a project's badges from shields.io, in rows, from the coordinates its options
74    state: the GitHub repository, the PyPI package, the licenses, the workflow and the documentation's URL.
75  * :rst:dir:`tree` - draws a hierarchy written as an indented list as a tree, each node foldable in HTML.
76  * :rst:dir:`unicode-table` - lists icons with their Unicode names and code points, which HTML copies into the
77    clipboard on a click; the script doing so is linked like the stylesheet.
78  * :rst:dir:`abbreviations` - lists abbreviations, which the abbreviation roles refer to.
79
80* the domain ``report`` - unit test, code coverage and documentation coverage reports as tables -, with the
81  configuration values ``pyTooling_Unittest_Testsuites``, ``pyTooling_CodeCoverage_Packages`` and
82  ``pyTooling_DocCoverage_Packages`` declaring the reports. Reading a report needs the extra ``reports``
83  (pyEDAA.Reports), which is imported only then:
84
85  * :rst:dir:`report:unittest-summary` - a unit test report, per testsuite and testcase; a report declared with
86    ``pages`` gets a page per testsuite and testcase (:mod:`~pyTooling.Sphinx.UnittestPages`), which the roles
87    ``:ts:`` and ``:tc:`` - also ``:report:ts:`` and ``:report:tc:`` - refer to;
88  * :rst:dir:`report:code-coverage` and :rst:dir:`report:code-coverage-legend` - a code coverage report and its
89    coverage levels;
90  * :rst:dir:`report:doc-coverage` and :rst:dir:`report:doc-coverage-legend` - a package's documentation coverage
91    and its coverage levels; a package declared with ``pages`` gets a page per package and module
92    (:class:`~pyTooling.Sphinx.DocCoverage.DocCoverageReportPages`), which the role ``:doccov:`` refers to.
93
94* the **nodes** the directives emit, listed in :data:`NODES` with their visitors per output format.
95
96* the **external link icons** - in HTML, an icon behind each external link, chosen by its target, and the size behind
97  each download -, with the configuration values ``pyTooling_ExternalLink_Icons``, ``pyTooling_ExternalLink_NewTab``,
98  ``pyTooling_ExternalLink_Hosts``, ``pyTooling_ExternalLink_DownloadSizes``, ``pyTooling_ExternalLink_RemoteSizes``
99  and ``pyTooling_ExternalLink_RemoteSizeTimeout`` (:mod:`~pyTooling.Sphinx.ExternalLink`).
100
101Two classes aren't registered, because they are base-classes for a project's own directives:
102:class:`~pyTooling.Sphinx.BaseDirective` offers typed option access and table construction
103over the untyped mapping and the hand-assembled node trees docutils presents, and
104:class:`~pyTooling.Sphinx.SchemaGraph.SchemaGraph` draws a schema file named as a directive's
105argument, leaving only the reading of that schema to a derived class.
106
107.. attention::
108
109   This package requires **Python 3.12 or newer**, because it requires Sphinx 9.1 and Sphinx 9.1 does.
110
111.. seealso::
112
113   :mod:`pyTooling.Documentation`
114      |rarr| The doc-string helpers, which need no Sphinx.
115"""
116__author__ =            "Patrick Lehmann"
117__email__ =             "Paebbels@gmail.com"
118__copyright__ =         "2026-2026, Patrick Lehmann"
119__license__ =           "Apache License, Version 2.0"
120__version__ =           "1.1.0"
121__keywords__ =          ["Sphinx", "Sphinx Extension", "Documentation", "Directive", "Role", "Domain", "docutils"]
122__project_url__ =       "https://github.com/pyTooling/pyTooling.Sphinx"
123__documentation_url__ = "https://pyTooling.github.io/pyTooling.Sphinx"
124__issue_tracker_url__ = "https://GitHub.com/pyTooling/pyTooling.Sphinx/issues"
125
126from hashlib                 import md5
127from pathlib                 import Path
128from re                      import MULTILINE, compile as re_compile, match as re_match
129from typing                  import Any, ClassVar, Iterable, Iterator, NamedTuple, Optional as Nullable
130
131from docutils                import nodes
132from sphinx.addnodes         import pending_xref
133from sphinx.application      import Sphinx
134from sphinx.builders         import Builder
135from sphinx.config           import Config
136from sphinx.directives       import ObjectDescription
137from sphinx.domains          import Domain, ObjType
138from sphinx.environment      import BuildEnvironment
139from sphinx.errors           import ExtensionError, NoUri
140from sphinx.roles            import XRefRole
141from sphinx.util.logging     import getLogger
142from sphinx.util.nodes       import make_refnode
143
144from pyTooling.Common        import StringEnum, getFullyQualifiedName, getTypeName, readResourceFile
145from pyTooling.Decorators    import export, readonly
146from pyTooling.Documentation import DocumentationError
147
148from pyTooling.Sphinx        import Resources as SphinxResources
149from pyTooling.Sphinx.HTML   import translateLandscape as translateLandscapeAsHTML, \
150                                    translateCoverageListing as translateCoverageListingAsHTML, \
151                                    translateDocCoverageListing as translateDocCoverageListingAsHTML, \
152                                    translateAbbreviation, translateTreeItem, translateTreeLabel, \
153                                    translateTreeSeparator, translateTreeDescription, translateTreeLegend, \
154                                    translateTreeLegendItem, translateCopyButton, translateEmoji, \
155                                    translateLineBreak as translateLineBreakAsHTML, \
156                                    translateReportIndentation as translateReportIndentationAsHTML, \
157                                    translateTaskListCheckbox as translateTaskListCheckboxAsHTML, \
158                                    translateFoldedDependencies, translateFoldedSummary
159from pyTooling.Sphinx.LaTeX  import translateLandscape as translateLandscapeAsLaTeX, \
160                                    translateCoverageListing as translateCoverageListingAsLaTeX, \
161                                    translateDocCoverageListing as translateDocCoverageListingAsLaTeX, \
162                                    translateLineBreak as translateLineBreakAsLaTeX, \
163                                    translateReportIndentation as translateReportIndentationAsLaTeX, \
164                                    translateTaskListCheckbox as translateTaskListCheckboxAsLaTeX
165from pyTooling.Sphinx.Node   import Abbreviation, Landscape, RegisteredNode, TreeItem, TreeLabel, TreeSeparator, \
166                                    CopyButton, CoverageListing, DocCoverageListing, TreeDescription, TreeLegend, \
167                                    Emoji, LineBreak, ReportIndentation, TaskListCheckbox, TreeLegendItem, \
168                                    FoldedDependencies, FoldedSummary
169
170
171__all__ = [
172	"STYLESHEET", "SCRIPT", "LATEX_PACKAGE", "SUBSTITUTIONS", "NODES", "LINE_ANCHOR", "REPORT_ROLES"
173]
174
175STYLESHEET = "pyTooling.css"
176"""Name of the stylesheet, in :mod:`pyTooling.Sphinx.Resources`."""
177
178SCRIPT = "pyTooling.js"
179"""
180Name of the script, in :mod:`pyTooling.Sphinx.Resources`: it gives the copy buttons of the ``unicode-table``
181directive their function.
182"""
183
184LATEX_PACKAGE = "pyTooling.Sphinx"
185"""
186Name of the LaTeX package, whose file :file:`pyTooling.Sphinx.sty` is in :mod:`pyTooling.Sphinx.Resources`: it
187defines the commands LaTeX writes for the style roles ``:strike:`` and ``:underline:``.
188"""
189
190SUBSTITUTIONS = """
191.. include:: <isonum.txt>
192
193.. include:: <mmlalias.txt>
194
195.. |degree| unicode:: U+00B0
196   :trim:
197
198.. |br| replace:: :br:`.`
199
200.. |hr| replace:: :hr:`.`
201"""
202"""
203Substitutions that have to stay substitutions, because ``|br|`` is written as one in every project.
204
205The docutils substitution files ``isonum.txt`` and ``mmlalias.txt`` define ``|rarr|``, ``|copy|`` and the like.
206``|br|`` and ``|hr|`` delegate to the ``:br:`` and ``:hr:`` roles rather than writing HTML themselves, so they
207reach every output format instead of only HTML - see :func:`~pyTooling.Sphinx.Roles.breakRole`.
208"""
209
210NODES: tuple[RegisteredNode, ...] = (
211	{"name": "TreeItem",           "node": TreeItem,           "html": translateTreeItem},
212	{"name": "TreeLabel",          "node": TreeLabel,          "html": translateTreeLabel},
213	{"name": "TreeSeparator",      "node": TreeSeparator,      "html": translateTreeSeparator},
214	{"name": "TreeDescription",    "node": TreeDescription,    "html": translateTreeDescription},
215	{"name": "TreeLegend",         "node": TreeLegend,         "html": translateTreeLegend},
216	{"name": "TreeLegendItem",     "node": TreeLegendItem,     "html": translateTreeLegendItem},
217	{"name": "CopyButton",         "node": CopyButton,         "html": translateCopyButton},
218	{"name": "Abbreviation",       "node": Abbreviation,       "html": translateAbbreviation},
219	{"name": "Landscape",          "node": Landscape,          "html": translateLandscapeAsHTML,
220	 "latex": translateLandscapeAsLaTeX},
221	{"name": "CoverageListing",    "node": CoverageListing,    "html": translateCoverageListingAsHTML,
222	 "latex": translateCoverageListingAsLaTeX},
223	{"name": "DocCoverageListing", "node": DocCoverageListing, "html": translateDocCoverageListingAsHTML,
224	 "latex": translateDocCoverageListingAsLaTeX},
225	{"name": "Emoji",              "node": Emoji,              "html": translateEmoji},
226	{"name": "TaskListCheckbox",   "node": TaskListCheckbox,   "html": translateTaskListCheckboxAsHTML,
227	 "latex": translateTaskListCheckboxAsLaTeX},
228	{"name": "LineBreak",          "node": LineBreak,          "html": translateLineBreakAsHTML,
229	 "latex": translateLineBreakAsLaTeX},
230	{"name": "ReportIndentation",  "node": ReportIndentation,  "html": translateReportIndentationAsHTML,
231	 "latex": translateReportIndentationAsLaTeX},
232	{"name": "FoldedDependencies", "node": FoldedDependencies, "html": translateFoldedDependencies},
233	{"name": "FoldedSummary",      "node": FoldedSummary,      "html": translateFoldedSummary},
234)
235"""
236The nodes the extension registers, each with its visitors per output format.
237
238A format without visitors of its own - e.g. LaTeX for the tree's nodes - writes a node with the visitors of its
239base-class.
240"""
241
242
243@export
244class SphinxExtensionError(ExtensionError, DocumentationError):
245	"""
246	Base-exception of all exceptions raised by :mod:`pyTooling.Sphinx`.
247
248	It derives from **both** hierarchies on purpose: :exc:`~sphinx.errors.ExtensionError` is what Sphinx catches and
249	reports with the position of the directive, and :exc:`~pyTooling.Documentation.DocumentationError` is what a
250	caller of pyTooling catches. Neither would be enough alone.
251	"""
252
253
254@export
255class ReportExtensionError(SphinxExtensionError):
256	"""
257	The exception raised by the ``report`` domain.
258
259	It is raised e.g. for a mistake in the domain's configuration values or options.
260	"""
261
262
263@export
264class ReportsPackageMissingError(ReportExtensionError):
265	"""
266	The exception raised when a report is read, but the optional packages of the extra ``reports`` aren't installed.
267
268	The message names what was attempted and the packages it needs; a note says how to install them.
269	"""
270
271	def __init__(self, task: str, packages: str = "'pyEDAA.Reports'") -> None:
272		"""
273		Initialize the exception with what was attempted and the packages it needs.
274
275		:param task:     What needs the packages, e.g. ``Reading a unit test report``.
276		:param packages: Optional, the packages needed, quoted. Default: ``'pyEDAA.Reports'``.
277		"""
278		super().__init__(f"{task} needs {packages}, which isn't installed.")
279		self.add_note("Install it with: pip install pyTooling.Sphinx[reports]")
280
281
282@export
283class LegendStyle(StringEnum):
284	"""
285	How a legend directive of domain ``report`` lays out the coverage levels, as its option ``:style:`` states it.
286	"""
287
288	HorizontalTable = "horizontal-table"  #: A table with a column per level.
289	VerticalTable =   "vertical-table"    #: A table with a row per level.
290
291	DEFAULT =         HorizontalTable     #: Without the option, a legend has a column per level.
292
293
294@export
295def strip(option: str) -> str:
296	"""
297	Option converter removing surrounding whitespace.
298
299	:param option: The option's value as it was written.
300	:returns:      The value without surrounding whitespace.
301	"""
302	return option.strip()
303
304
305@export
306def stripAndNormalize(option: str) -> str:
307	"""
308	Option converter removing surrounding whitespace and lowering the case.
309
310	:param option: The option's value as it was written.
311	:returns:      The value without surrounding whitespace, in lower case.
312	"""
313	return option.strip().lower()
314
315
316@export
317class BaseDirective(ObjectDescription[str]):
318	"""
319	Base-class for a directive, offering typed option access and table construction.
320
321	A derived class sets :attr:`directiveName` - which is what the error messages name - and declares
322	``option_spec`` as any directive does. What it gets in return is a ``_Parse***Option`` per type instead of
323	reaching into :attr:`options` and validating by hand, and a ``_Create***TableHeader`` per table shape instead of
324	assembling :class:`~docutils.nodes.tgroup`, :class:`~docutils.nodes.colspec`, :class:`~docutils.nodes.thead`
325	and :class:`~docutils.nodes.row` in the right order.
326	"""
327
328	has_content =               False  #: A boolean; ``True`` if content is allowed.
329	required_arguments =        0      #: Number of required directive arguments.
330	optional_arguments =        0      #: Number of optional arguments after the required ones.
331	final_argument_whitespace = False  #: A boolean; ``True`` if the last argument may contain spaces.
332	option_spec =               {}     #: Mapping of option names to validator functions.
333
334	directiveName: str  #: Name the directive is invoked by, used in every error message.
335
336	def _ParseBooleanOption(self, optionName: str, default: Nullable[bool] = None) -> bool:
337		"""
338		Read an option written as ``yes``/``true`` or ``no``/``false``.
339
340		:param optionName:             Name of the option to read.
341		:param default:                Optional, the value to return when the option wasn't given.
342		:returns:                      The option's value.
343		:raises SphinxExtensionError:  If the option wasn't given and has no default.
344		:raises SphinxExtensionError:  If the option's value is neither of the two accepted spellings.
345		"""
346		try:
347			option = self.options[optionName]
348		except KeyError as cause:
349			if default is not None:
350				return default
351
352			raise SphinxExtensionError(
353				f"{self.directiveName}: Required option '{optionName}' not found for directive."
354			) from cause
355
356		if option in ("yes", "true"):
357			return True
358		elif option in ("no", "false"):
359			return False
360
361		raise SphinxExtensionError(
362			f"{self.directiveName}::{optionName}: '{option}' not supported for a boolean value (yes/true, no/false)."
363		)
364
365	def _ParseStringOption(self, optionName: str, default: Nullable[str] = None, regexp: str = "\\w+") -> str:
366		"""
367		Read an option that has to match a regular expression.
368
369		The pattern defaults to one or more word characters.
370
371		:param optionName:             Name of the option to read.
372		:param default:                Optional, the value to return when the option wasn't given.
373		:param regexp:                 Optional, the pattern the value has to match.
374		:returns:                      The option's value.
375		:raises SphinxExtensionError:  If the option wasn't given and has no default.
376		:raises SphinxExtensionError:  If the option's value doesn't match the pattern.
377		"""
378		try:
379			option: str = self.options[optionName]
380		except KeyError as cause:
381			if default is not None:
382				return default
383
384			raise SphinxExtensionError(
385				f"{self.directiveName}: Required option '{optionName}' not found for directive."
386			) from cause
387
388		if re_match(regexp, option):
389			return option
390
391		raise SphinxExtensionError(
392			f"{self.directiveName}::{optionName}: '{option}' not an accepted value for regexp '{regexp}'."
393		)
394
395	def _CreateSingleRowTableHeader(
396		self,
397		columns: list[tuple[str, Nullable[int]]],
398		identifier: str,
399		classes: list[str]
400	) -> nodes.tgroup:
401		"""
402		Create a table with a single header row.
403
404		:param columns:    One ``(title, width)`` pair per column; a width of ``None`` leaves it to the writer.
405		:param identifier: Identifier of the table.
406		:param classes:    CSS classes to put on the table.
407		:returns:          The table's column group, with the header row already in it.
408		"""
409		table = nodes.table("", identifier=identifier, classes=classes)
410		table += (tableGroup := nodes.tgroup(cols=(len(columns))))
411
412		# Setup column specifications
413		for _, width in columns:
414			tableGroup += nodes.colspec(colwidth=width)
415
416		tableGroup += (tableHeader := nodes.thead())
417		tableHeader += (headerRow := nodes.row())
418
419		# Setup header row
420		for columnTitle, _ in columns:
421			headerRow += nodes.entry("", nodes.Text(columnTitle))
422
423		return tableGroup
424
425	def _CreateDoubleRowTableHeader(
426		self,
427		columns: list[tuple[str, Nullable[list[tuple[str, int]]], Nullable[int]]],
428		identifier: str,
429		classes: list[str]
430	) -> nodes.tgroup:
431		"""
432		Create a table whose header spans two rows, so a column can group sub-columns.
433
434		A column's ``subColumns`` is ``None`` when it spans both header rows, and otherwise holds the
435		``(title, width)`` pairs below it.
436
437		:param columns:    One ``(title, subColumns, width)`` triple per column.
438		:param identifier: Identifier of the table.
439		:param classes:    CSS classes to put on the table.
440		:returns:          The table's column group, with both header rows already in it.
441		"""
442		columnCount = sum(len(groupColumn[1]) if groupColumn[1] is not None else 1 for groupColumn in columns)
443
444		# Create table with N columns
445		table = nodes.table("", identifier=identifier, classes=classes)
446		table += (tableGroup := nodes.tgroup(cols=columnCount))
447
448		# Setup column specifications
449		for _, more, width in columns:
450			if more is None:
451				tableGroup += nodes.colspec(colwidth=width)
452			else:
453				for _, width in more:
454					tableGroup += nodes.colspec(colwidth=width)
455
456		tableGroup += (tableHeader := nodes.thead())
457		tableHeader += (headerRow1 := nodes.row())
458
459		# Setup primary header row
460		for columnTitle, more, _ in columns:
461			if more is None:
462				headerRow1 += nodes.entry("", nodes.Text(columnTitle), morerows=1)
463			else:
464				headerRow1 += nodes.entry("", nodes.Text(columnTitle), morecols=(morecols := len(more) - 1))
465				for _ in range(morecols):
466					headerRow1 += None
467
468		# Setup secondary header row
469		tableHeader += (headerRow2 := nodes.row())
470		for columnTitle, more, _ in columns:
471			if more is None:
472				headerRow2 += None
473			else:
474				for columnTitle, _ in more:
475					headerRow2 += nodes.entry("", nodes.Text(columnTitle))
476
477		return tableGroup
478
479	def _CreateRotatedTableHeader(
480		self,
481		columns: list[tuple[str, Nullable[list[str]]]],
482		identifier: str,
483		classes: list[str]
484	) -> nodes.tgroup:
485		"""
486		Create a table whose header titles are rotated, for many narrow columns.
487
488		:param columns:    One ``(title, classes)`` pair per column; the classes are put on the header cell.
489		:param identifier: Identifier of the table.
490		:param classes:    CSS classes to put on the table.
491		:returns:          The table's column group, with the header row already in it.
492		"""
493		table = nodes.table("", identifier=identifier, classes=classes)
494		table += (tableGroup := nodes.tgroup(cols=len(columns)))
495
496		# Setup column specifications
497		for i, _ in enumerate(columns):
498			tableGroup += nodes.colspec(classes=[f"col-{i}"])
499
500		tableGroup += (tableHeader := nodes.thead())
501		tableHeader += (headerRow := nodes.row())
502
503		# Setup header row
504		for columnTitle, columnClasses in columns:
505			span = nodes.inline("", text=columnTitle)
506			div = nodes.container("", span)
507			headerRow += nodes.entry("", div, classes=[] if columnClasses is None else columnClasses)
508
509		return tableGroup
510
511	def _internalError(
512		self,
513		container: nodes.container,
514		location: str,
515		message: str,
516		exception: Exception
517	) -> list[nodes.Node]:
518		"""
519		Report an exception a directive couldn't recover from, in the log **and** on the page.
520
521		A directive that fails silently leaves a hole in the documentation that nobody notices. This puts the message
522		where a reader sees it and the traceback where a maintainer does. The exception's notes - e.g. how to install a
523		missing package - are logged below it.
524
525		:param container: The container the message is put into.
526		:param location:  Name of the logger, which is what the log line is attributed to.
527		:param message:   What went wrong, in one sentence.
528		:param exception: The exception that was caught.
529		:returns:         The container, as the list a directive's ``run`` returns.
530		"""
531		logger = getLogger(location)
532		logger.error(f"{message}")
533		logger.error(f"  {getTypeName(exception)}: {exception}")
534		for note in getattr(exception, "__notes__", ()):
535			logger.error(f"    {note}")
536
537		if exception.__cause__ is not None:
538			logger.error(f"    {getTypeName(exception.__cause__)}: {exception.__cause__}")
539		logger.exception(exception)
540
541		container += nodes.paragraph(text=message)
542
543		return [container]
544
545
546@export
547def installStaticFiles(sphinx: Sphinx) -> None:
548	"""
549	Call-back for Sphinx' ``builder-inited`` event, writing the stylesheet and the script into the build and linking
550	them.
551
552	A file is named by the hash of its content, so a browser re-reads it when it changes and re-uses it when it doesn't.
553	Older copies are removed when the content changed.
554
555	:param sphinx: The Sphinx application.
556	"""
557	staticDirectory = (Path(sphinx.outdir) / "_pyTooling_static").resolve()
558	staticDirectory.mkdir(exist_ok=True)
559	sphinx.config.html_static_path.append(str(staticDirectory))
560
561	for resource, addFile in ((STYLESHEET, sphinx.add_css_file), (SCRIPT, sphinx.add_js_file)):
562		stem, _, suffix = resource.rpartition(".")
563		content = readResourceFile(SphinxResources, resource)
564		digest = md5(content.encode("utf-8")).hexdigest()  # nosec B324 - a cache-busting name, not a signature
565		staticFile = staticDirectory / f"{stem}.{digest}.{suffix}"
566		addFile(staticFile.name)
567
568		if not staticFile.exists():
569			# Only this package's own copies - the directory is on 'html_static_path', so another extension may
570			# have written its files beside ours.
571			for outdated in staticDirectory.glob(f"{stem}.*.{suffix}"):
572				outdated.unlink()
573
574			staticFile.write_text(content, encoding="utf-8")
575
576
577@export
578def installLaTeXPackage(sphinx: Sphinx) -> None:
579	"""
580	Call-back for Sphinx' ``builder-inited`` event, writing the LaTeX package :data:`LATEX_PACKAGE` into the build of a
581	LaTeX builder, where the document's ``\\usepackage`` finds it.
582
583	:param sphinx: The Sphinx application.
584	"""
585	if sphinx.builder.format != "latex":
586		return
587
588	content = readResourceFile(SphinxResources, f"{LATEX_PACKAGE}.sty")
589	with (Path(sphinx.outdir) / f"{LATEX_PACKAGE}.sty").open("w", encoding="utf-8") as file:
590		file.write(content)
591
592
593@export
594def extendProlog(sphinx: Sphinx, config: Any) -> None:
595	"""
596	Call-back for Sphinx' ``config-inited`` event, appending the shared substitutions to ``rst_prolog``.
597
598	A role can be registered; a **substitution** cannot - ``|br|`` is substitution syntax, and every project writes
599	it that way already. Appending them here is what lets a project delete them from its own prolog without changing
600	a single document.
601
602	A substitution or an included substitution file the project's prolog defines already is not appended, so the
603	project's definition stays and docutils reports no duplicate definition.
604
605	:param sphinx: The Sphinx application.
606	:param config: The configuration, after :file:`conf.py` was read.
607	"""
608	definition = re_compile(r"^\.\. (\|[^|]+\||include:: \S+)", MULTILINE)
609
610	prolog =  "" if config.rst_prolog is None else config.rst_prolog
611	defined = set(definition.findall(prolog))
612
613	blocks = []
614	for block in SUBSTITUTIONS.strip("\n").split("\n\n"):
615		if definition.match(block)[1] not in defined:
616			blocks.append(block)
617
618	config.rst_prolog = prolog + "\n\n" + "\n\n".join(blocks) + "\n"
619
620
621@export
622def setLaTeXDefaults(sphinx: Sphinx, config: Config) -> None:
623	"""
624	Call-back for Sphinx' ``config-inited`` event, setting LaTeX defaults, unless :file:`conf.py` sets them.
625
626	* ``latex_table_style``: ``["booktabs"]``, without Sphinx' default ``colorrows``.
627	* ``latex_elements["maxlistdepth"]``: ``"10"`` nested lists, e.g. a :rst:dir:`tree` with more than 4 levels.
628
629	:param sphinx: The Sphinx application.
630	:param config: The configuration, after :file:`conf.py` was read.
631	"""
632	if "latex_table_style" not in config._raw_config and "latex_table_style" not in config.overrides:
633		config.latex_table_style = ["booktabs"]
634
635	config.latex_elements = {"maxlistdepth": "10"} | config.latex_elements
636
637
638@export
639class ReportEntry(NamedTuple):
640	"""
641	An object of a report shown by a generated page - a testcase, a source file, ...: where it is, and its names.
642
643	An object is shown by a page of its own, or - with an anchor - by a part of another page.
644	"""
645
646	docName:   str                    #: Name of the generated document showing the object.
647	reportID:  str                    #: Identifier of the report in its configuration value.
648	path:      tuple[str, ...]        #: Names of the objects from the report's root down to this object's own name.
649	separator: str                    #: Separator of the names in a qualified name, e.g. ``.`` or ``/``.
650	title:     Nullable[str]          #: Title of the object written for a reader, if the report has one.
651	anchor:    Nullable[str] = None   #: Anchor of the object's part of the page, or ``None`` for the whole page.
652
653	@readonly
654	def Name(self) -> str:
655		"""
656		Read-only property to return the object's own name, the last element of :attr:`path`.
657
658		:returns: The name.
659		"""
660		return self.path[-1]
661
662	@readonly
663	def QualifiedName(self) -> str:
664		"""
665		Read-only property to return the qualified name: the names of :attr:`path` joined by :attr:`separator`.
666
667		:returns: The qualified name, e.g. ``pytest.tests.unit.Arithmetic.Addition.test_Positive``.
668		"""
669		return self.separator.join(self.path)
670
671	def Matches(self, name: str) -> bool:
672		"""
673		Check whether a name is the qualified name or a suffix of it, which starts at an element of :attr:`path`.
674
675		:param name: The name as written in a reference, without a report ID.
676		:returns:    ``True`` if the name is the qualified name or one of its suffixes.
677		"""
678		return any(self.separator.join(self.path[index:]) == name for index in range(len(self.path)))
679
680
681@export
682class ReportRoleDefinition(NamedTuple):
683	"""
684	What a role of domain ``report`` refers to: a kind of object of the reports declared in a configuration value.
685	"""
686
687	objectType:  str           #: The object type, as listed by the domain, e.g. ``testcase``.
688	configValue: str           #: The configuration value declaring the reports; its first report is the default one.
689	reports:     str           #: The reports, as a warning names them, e.g. ``unit test reports``.
690	lineAnchors: bool = False  #: Whether a target may end in ``#<line number>``, linking to the line on the page.
691
692
693LINE_ANCHOR = re_compile(r"#(\d+)$")
694"""The line number a target of a role with line anchors may end in, e.g. ``#12`` of ``src/Counter.vhdl#12``."""
695
696REPORT_ROLES = {
697	"tc":     ReportRoleDefinition("testcase",  "pyTooling_Unittest_Testsuites",   "unit test reports"),
698	"ts":     ReportRoleDefinition("testsuite", "pyTooling_Unittest_Testsuites",   "unit test reports"),
699	"cov":    ReportRoleDefinition("source",    "pyTooling_CodeCoverage_Packages", "code coverage reports", True),
700	"doccov": ReportRoleDefinition("module",    "pyTooling_DocCoverage_Packages",  "documentation coverage reports"),
701}
702"""The roles referring to the objects of reports with pages, by role name."""
703
704
705@export
706class ReportRole(XRefRole):
707	"""
708	A role of domain ``report`` referring to an object of a report with pages.
709
710	Role ``tc`` refers to a testcase, ``ts`` to a testsuite.
711
712	Sphinx registers a role outside a domain without one, so the reference would be resolved by nobody; this role puts
713	its domain - ``report``, or the one of a domain derived from :class:`ReportDomain` - on the reference, and uses its
714	name as the reference's type. So it works as ``:report:tc:`` and as the global ``:tc:``.
715	"""
716
717	_domain: str  #: Name of the domain resolving the role's references.
718
719	def __init__(self, *, domain: str = "report", **kwargs: Any) -> None:
720		"""
721		Initializes a role of domain ``report``, or of a domain derived from :class:`ReportDomain`.
722
723		:param domain:      Optional, name of the domain resolving the role's references. Default: ``"report"``.
724		:param kwargs:      The parameters of :class:`~sphinx.roles.XRefRole`, e.g. ``innernodeclass``.
725		:raises ValueError: If parameter 'domain' is None.
726		:raises TypeError:  If parameter 'domain' is not of type :class:`str`.
727		"""
728		super().__init__(**kwargs)
729
730		if domain is None:
731			raise ValueError("Parameter 'domain' is None.")
732		elif not isinstance(domain, str):
733			ex = TypeError("Parameter 'domain' is not of type 'str'.")
734			ex.add_note(f"Got type '{getFullyQualifiedName(domain)}'.")
735			raise ex
736
737		self._domain = domain
738
739	def run(self) -> tuple[list[nodes.Node], list[nodes.system_message]]:
740		"""
741		Create the reference, or only the text if the role is written with ``!``.
742
743		:returns: The nodes and messages a role returns.
744		"""
745		self.refdomain = self._domain
746		self.reftype = self.name.rpartition(":")[2]
747		self.classes = ["xref", self._domain, f"{self._domain}-{self.reftype}"]
748
749		if self.disabled:
750			return self.create_non_xref_node()
751
752		return self.create_xref_node()
753
754
755@export
756class ReportDomain(Domain):
757	"""
758	The Sphinx domain ``report``, integrating unit test, code coverage and documentation coverage reports.
759
760	Its directives are registered by :func:`setup`, and read their reports from the files declared in :file:`conf.py`.
761
762	A report with generated pages contributes an object per page - e.g. a unit test report its testsuites and
763	testcases -, which the roles of :data:`REPORT_ROLES` refer to, e.g. ``:report:tc:``, also registered as ``:tc:``. A
764	reference names an object by its qualified name, or by a suffix of it, optionally preceded by the report's
765	identifier and a colon; without one, the first report of the role's configuration value is meant.
766
767	A domain of another family of reports - e.g. a build summary of a simulation framework - derives from it: it names
768	its roles in :attr:`_ROLES`, and declares :attr:`name`, :attr:`object_types`, :attr:`initial_data`, :attr:`roles` and
769	:attr:`dangling_warnings` from them, as this domain does from :data:`REPORT_ROLES`. Its roles are
770	:class:`ReportRole` instances naming the domain.
771	"""
772
773	_ROLES: ClassVar[dict[str, ReportRoleDefinition]] = REPORT_ROLES  #: The domain's roles, by role name.
774
775	name =         "report"  #: Name of the domain, the prefix of its directives.
776	label =        "rpt"     #: Name of the domain, as displayed.
777	data_version = 2         #: Version of the domain data's layout; a pickled environment of another version is dropped.
778
779	object_types = {
780		definition.objectType: ObjType(definition.objectType, roleName) for roleName, definition in REPORT_ROLES.items()
781	}  #: The objects: per role, the objects of the reports with generated pages.
782	initial_data: dict[str, Any] = {
783		roleName: {} for roleName in REPORT_ROLES
784	}  #: The data of an empty documentation: per role, no object.
785	roles = {
786		roleName: ReportRole(innernodeclass=nodes.inline, warn_dangling=True) for roleName in REPORT_ROLES
787	}  #: The roles, also registered without the domain's prefix.
788	dangling_warnings = {
789		roleName: f"{definition.objectType} '%(target)s' not found in the {definition.reports}"
790		for roleName, definition in REPORT_ROLES.items()
791	}  #: The warning for a reference to an unknown object, per role.
792
793	def AddEntry(self, roleName: str, entry: ReportEntry) -> None:
794		"""
795		Register an object, which has a generated page.
796
797		:param roleName: The role referring to the object, e.g. ``tc`` for a testcase.
798		:param entry:    The object.
799		"""
800		self.data[roleName].setdefault(entry.reportID, {})[entry.QualifiedName] = entry
801
802	def FindEntries(self, roleName: str, target: str) -> list[ReportEntry]:
803		"""
804		Find the objects a reference's target names.
805
806		A target is ``[<report ID>:]<name>``. If the part before the first colon isn't the identifier of a report, the
807		whole target is the name in the default report - the first one of the role's configuration value -, as e.g. a
808		parametrized testcase's name may contain a colon. A name is a qualified name or a suffix of one (see
809		:meth:`ReportEntry.Matches`); an exact qualified name wins over suffixes.
810
811		:param roleName: The role referring to the object, e.g. ``tc`` for a testcase.
812		:param target:   The reference's target.
813		:returns:        The matching entries: none, one, or several if the name is ambiguous.
814		"""
815		reports: dict[str, dict[str, ReportEntry]] = self.data[roleName]
816		configuredReports = list(self.env.config[self._ROLES[roleName].configValue])
817
818		reportID, separator, name = target.partition(":")
819		if separator == "" or reportID not in configuredReports:
820			if len(configuredReports) == 0:
821				return []
822
823			reportID, name = configuredReports[0], target
824
825		entries = reports.get(reportID, {})
826		if (entry := entries.get(name)) is not None:
827			return [entry]
828
829		return [entry for entry in entries.values() if entry.Matches(name)]
830
831	def clear_doc(self, docname: str) -> None:
832		"""
833		Forget the objects of a document, before it is generated again.
834
835		:param docname: Name of the document.
836		"""
837		for roleName in self._ROLES:
838			for entries in self.data[roleName].values():
839				for qualifiedName in [name for name, entry in entries.items() if entry.docName == docname]:
840					del entries[qualifiedName]
841
842	def merge_domaindata(self, docnames: Iterable[str], otherdata: dict[str, Any]) -> None:
843		"""
844		Take over the objects a parallel reader collected for its documents.
845
846		:param docnames:  Names of the documents the other reader read.
847		:param otherdata: The other reader's domain data.
848		"""
849		documents = set(docnames)
850		for roleName in self._ROLES:
851			for reportID, entries in otherdata[roleName].items():
852				ownEntries = self.data[roleName].setdefault(reportID, {})
853				for qualifiedName, entry in entries.items():
854					if entry.docName in documents:
855						ownEntries[qualifiedName] = entry
856
857	def resolve_xref(
858		self,
859		env: BuildEnvironment,
860		fromdocname: str,
861		builder: Builder,
862		typ: str,
863		target: str,
864		node: pending_xref,
865		contnode: nodes.Element
866	) -> Nullable[nodes.Element]:
867		"""
868		Resolve a reference to an object of a report into a link to its page.
869
870		The link shows the object's name, or the title written in the role; in HTML, its title written for a reader - if
871		the report has one - is shown on hover. It points to the object's anchor, if it has one, and to a line, if the
872		target ends in one. An ambiguous name is warned about and shown as text.
873
874		:param env:         The build environment.
875		:param fromdocname: Name of the document holding the reference.
876		:param builder:     The builder writing the documents.
877		:param typ:         The role's name, e.g. ``tc``.
878		:param target:      The object referred to.
879		:param node:        The reference.
880		:param contnode:    The reference's text.
881		:returns:           The link, the text if the name is ambiguous or the builder doesn't write the page, or
882		                    ``None`` if nothing matches.
883		"""
884		if typ not in self._ROLES:
885			return None
886
887		anchor = line = ""
888		if self._ROLES[typ].lineAnchors and (match := LINE_ANCHOR.search(target)) is not None:
889			target, line = target[:match.start()], match[1]
890			anchor = f"L{line}"
891
892		entries = self.FindEntries(typ, target)
893		if len(entries) == 0:
894			return None
895		elif len(entries) > 1:
896			candidates = ", ".join(sorted(f"{entry.reportID}:{entry.QualifiedName}" for entry in entries))
897			getLogger(__name__).warning(
898				f"{self._ROLES[typ].objectType} '{target}' is ambiguous, candidates: {candidates}",
899				location=node, type="ref", subtype=typ
900			)
901			return contnode
902
903		entry = entries[0]
904		if node.get("refexplicit", False):
905			content = contnode
906		else:
907			text = entry.Name if line == "" else f"{entry.Name}:{line}"
908			content = nodes.inline(text, text, classes=contnode["classes"])
909
910		try:
911			return make_refnode(builder, fromdocname, entry.docName, anchor or entry.anchor, content, entry.title)
912		except NoUri:
913			# a builder may not write every document, so a link to a page becomes the name
914			return content
915
916	def resolve_any_xref(
917		self,
918		env: BuildEnvironment,
919		fromdocname: str,
920		builder: Builder,
921		target: str,
922		node: pending_xref,
923		contnode: nodes.Element
924	) -> list[tuple[str, nodes.reference]]:
925		"""
926		Resolve a reference of role ``:any:`` to an object of a report with an unambiguous name.
927
928		:param env:         The build environment.
929		:param fromdocname: Name of the document holding the reference.
930		:param builder:     The builder writing the documents.
931		:param target:      The text referred to.
932		:param node:        The reference.
933		:param contnode:    The reference's text.
934		:returns:           A role and link per kind of object the text names unambiguously.
935		"""
936		results: list[tuple[str, nodes.reference]] = []
937		for roleName in self._ROLES:
938			if len(entries := self.FindEntries(roleName, target)) == 1:
939				entry = entries[0]
940				content = nodes.inline(entry.Name, entry.Name, classes=contnode["classes"])
941				reference = make_refnode(builder, fromdocname, entry.docName, entry.anchor, content, entry.title)
942				results.append((f"{self.name}:{roleName}", reference))
943
944		return results
945
946	def get_objects(self) -> Iterator[tuple[str, str, str, str, str, int]]:
947		"""
948		Name the objects of the reports, for the search and for other documentations referring to them.
949
950		An object's name is ``<report ID>:<qualified name>``. A testcase gets a lower search priority than a testsuite,
951		as a report may have thousands of them.
952
953		:returns: A tuple per object: name, display name, type, document, anchor and search priority.
954		"""
955		for roleName, definition in self._ROLES.items():
956			priority = 2 if roleName == "tc" else 1
957			for reportID, entries in self.data[roleName].items():
958				for qualifiedName, entry in entries.items():
959					yield (
960						f"{reportID}:{qualifiedName}", entry.QualifiedName, definition.objectType, entry.docName,
961						entry.anchor or "", priority
962					)
963
964
965@export
966def checkReportConfiguration(sphinx: Sphinx, config: Config) -> None:
967	"""
968	Call-back for Sphinx' ``config-inited`` event, checking the reports' configuration values and loading their settings.
969
970	A mistake is logged as an error rather than stopping the build; a directive naming that report fails on its own.
971
972	:param sphinx: The Sphinx application.
973	:param config: The configuration, after :file:`conf.py` was read.
974	"""
975	from pyTooling.Sphinx.CodeCoverage import CodeCoverageBase
976	from pyTooling.Sphinx.DocCoverage  import DocCoverageBase
977	from pyTooling.Sphinx.Unittest     import UnittestSummary
978
979	checkConfigurations = (
980		CodeCoverageBase.CheckConfiguration,
981		DocCoverageBase.CheckConfiguration,
982		UnittestSummary.CheckConfiguration,
983	)
984
985	for check in checkConfigurations:
986		try:
987			check(sphinx, config)
988		except ReportExtensionError as ex:
989			getLogger(__name__).error(f"Caught {getTypeName(ex)} when checking configuration variables.\n  {ex}")
990
991
992@export
993def readReports(sphinx: Sphinx) -> None:
994	"""
995	Call-back for Sphinx' ``builder-inited`` event, reading the report files, analyzing the documented packages, and
996	registering the reports' pages.
997
998	:param sphinx: The Sphinx application.
999	"""
1000	from pyTooling.Sphinx.CodeCoverage      import CodeCoverageBase
1001	from pyTooling.Sphinx.CodeCoveragePages import CodeCoverageReportPages
1002	from pyTooling.Sphinx.DocCoverage       import DocCoverageBase, DocCoverageReportPages
1003	from pyTooling.Sphinx.Unittest          import UnittestSummary
1004	from pyTooling.Sphinx.UnittestPages     import UnittestReportPages
1005
1006	CodeCoverageBase.ReadReports(sphinx)
1007	DocCoverageBase.AnalyzePackages(sphinx)
1008	UnittestSummary.ReadReports(sphinx)
1009	CodeCoverageReportPages.CreatePages(sphinx)
1010	DocCoverageReportPages.CreatePages(sphinx)
1011	UnittestReportPages.CreatePages(sphinx)
1012
1013
1014@export
1015def setup(sphinx: Sphinx) -> dict[str, Any]:
1016	"""
1017	Register the roles, the nodes, the directives and the domain ``report`` with Sphinx.
1018
1019	The modules are imported here rather than with the package, and none of them imports an optional dependency at
1020	module level - e.g. pyEDAA.Reports is imported only when a report is read - so the extension works without them.
1021
1022	:param sphinx: The Sphinx application to register with.
1023	:returns:      The extension's metadata.
1024	"""
1025	from pyTooling.Sphinx.Abbreviation      import CONFIG_PREFIX as ABBREVIATION_PREFIX, ROLES as ABBREVIATION_ROLES, \
1026	                                               AbbreviationDomain, AbbreviationRole, Abbreviations
1027	from pyTooling.Sphinx.CodeCoverage      import CONFIG_PREFIX as CODE_COVERAGE_PREFIX, CodeCoverage, \
1028	                                               CodeCoverageBase, CodeCoverageLegend, FileCoverage
1029	from pyTooling.Sphinx.CodeCoveragePages import CodeCoverageReportPages
1030	from pyTooling.Sphinx.CondensedClass    import CondensedClass
1031	from pyTooling.Sphinx.DependencyTable   import CONFIG_PREFIX, PROJECT_ROOT_CONFIG, DependencyTable, \
1032	                                               ReplaceFoldedDependencies, prepareEntrypoints, reportBuildTime
1033	from pyTooling.Sphinx.DocCoverage       import CONFIG_PREFIX as DOC_COVERAGE_PREFIX, DocCoverageBase, \
1034	                                               DocCoverageLegend, DocCoverageReportPages, DocStrCoverage
1035	from pyTooling.Sphinx.ExternalLink      import CONFIG_PREFIX as EXTERNAL_LINK_PREFIX, BaseExternalLinkTransform, \
1036	                                               MarkDownloadLinks, MarkExternalLinks, MarkIntersphinxLinks, \
1037	                                               AddDownloadSizes, checkExternalLinkConfiguration
1038	from pyTooling.Sphinx.GitHubMarkdown    import RasterizeShieldsBadges
1039	from pyTooling.Sphinx.Roles             import BREAK_ROLES, PYTHON_CODE_ROLE, STYLE_ROLES, breakRole, \
1040	                                               pythonCodeRole, styleRole
1041	from pyTooling.Sphinx.Shields           import Shields
1042	from pyTooling.Sphinx.Tree              import RemoveTreeLegends, Tree
1043	from pyTooling.Sphinx.UnicodeTable      import RemoveUnicodeGlyphs, UnicodeTable
1044	from pyTooling.Sphinx.Unittest          import CONFIG_PREFIX as UNITTEST_PREFIX, UnittestSummary
1045	from pyTooling.Sphinx.UnittestPages     import UnittestReportPages
1046	from pyTooling.Sphinx.Workaround        import FixLatexTableWidths
1047	from pyTooling.Sphinx.XMLSchemaGraph    import XMLSchemaGraph
1048
1049	for roleName in STYLE_ROLES:
1050		sphinx.add_role(roleName, styleRole)
1051
1052	for roleName in BREAK_ROLES:
1053		sphinx.add_role(roleName, breakRole)
1054
1055	sphinx.add_role(PYTHON_CODE_ROLE, pythonCodeRole)
1056
1057	# the abbreviation roles outside their domain too, as LaTeX' 'acro' names them: ':acs:', not ':abbreviation:acs:'
1058	sphinx.add_domain(AbbreviationDomain)
1059	for roleName in ABBREVIATION_ROLES:
1060		sphinx.add_role(roleName, AbbreviationRole(innernodeclass=nodes.inline, warn_dangling=True))
1061
1062	# the report roles outside their domain too: ':tc:', not only ':report:tc:'
1063	for roleName in REPORT_ROLES:
1064		sphinx.add_role(roleName, ReportRole(innernodeclass=nodes.inline, warn_dangling=True))
1065
1066	sphinx.add_directive("condensed-class", CondensedClass)
1067	sphinx.add_directive("dependency-table", DependencyTable)
1068	sphinx.add_directive("xmlschema-graph", XMLSchemaGraph)
1069	sphinx.add_directive("shields", Shields)
1070	sphinx.add_directive("tree", Tree)
1071	sphinx.add_directive("unicode-table", UnicodeTable)
1072	sphinx.add_directive("abbreviations", Abbreviations)
1073
1074	# Without the domain, these become global directives: 'add_directive' instead of 'add_directive_to_domain'.
1075	reportDirectives = {
1076		"code-coverage":        CodeCoverage,
1077		"code-coverage-legend": CodeCoverageLegend,
1078		"file-coverage":        FileCoverage,
1079		"doc-coverage":         DocStrCoverage,
1080		"doc-coverage-legend":  DocCoverageLegend,
1081		"unittest-summary":     UnittestSummary,
1082	}
1083	sphinx.add_domain(ReportDomain)
1084	for directiveName, directive in reportDirectives.items():
1085		sphinx.add_directive_to_domain(ReportDomain.name, directiveName, directive)
1086
1087	for registeredNode in NODES:
1088		if "latex" in registeredNode:
1089			sphinx.add_node(registeredNode["node"], html=registeredNode["html"], latex=registeredNode["latex"])
1090		else:
1091			sphinx.add_node(registeredNode["node"], html=registeredNode["html"])
1092
1093	# the report tables are put into 'Landscape' nodes, whose LaTeX environment is package 'pdflscape''s
1094	sphinx.add_latex_package("pdflscape")
1095	# the extension's own package, which 'installLaTeXPackage' copies into the build
1096	sphinx.add_latex_package(LATEX_PACKAGE)
1097	sphinx.add_post_transform(FixLatexTableWidths)
1098	sphinx.add_post_transform(RemoveTreeLegends)
1099	sphinx.add_post_transform(ReplaceFoldedDependencies)
1100	sphinx.add_post_transform(RemoveUnicodeGlyphs)
1101	sphinx.add_post_transform(RasterizeShieldsBadges)
1102
1103	sphinx.setup_extension("sphinx.ext.graphviz")
1104	sphinx.setup_extension("sphinx.ext.imgconverter")
1105
1106	for prefix, configValues in (
1107		(CONFIG_PREFIX,        DependencyTable.configValues),
1108		(CODE_COVERAGE_PREFIX, CodeCoverageBase.configValues),
1109		(DOC_COVERAGE_PREFIX,  DocCoverageBase.configValues),
1110		(UNITTEST_PREFIX,      UnittestSummary.configValues),
1111		(EXTERNAL_LINK_PREFIX, BaseExternalLinkTransform.configValues),
1112	):
1113		for configName, (default, rebuild, types) in configValues.items():
1114			sphinx.add_config_value(f"{prefix}_{configName}", default, rebuild, types)
1115
1116	for configName, (default, rebuild, types) in Abbreviations.configValues.items():
1117		sphinx.add_config_value(f"{ABBREVIATION_PREFIX}_{configName}", default, rebuild, types)
1118
1119	sphinx.add_config_value(PROJECT_ROOT_CONFIG, None, "env", (str, Path))
1120
1121	# HTML only: the first marks the links written with their URI, the second the links resolved in between
1122	sphinx.add_post_transform(MarkExternalLinks)
1123	sphinx.add_post_transform(MarkIntersphinxLinks)
1124	sphinx.add_post_transform(MarkDownloadLinks)
1125	sphinx.add_post_transform(AddDownloadSizes)
1126
1127	sphinx.connect("config-inited", extendProlog)
1128	sphinx.connect("config-inited", setLaTeXDefaults)
1129	# after the configuration values above are registered, and before any document is read - a requirements file
1130	# that doesn't exist should end the build here rather than in the middle of a page
1131	sphinx.connect("config-inited", prepareEntrypoints)
1132	sphinx.connect("config-inited", checkReportConfiguration)
1133	sphinx.connect("config-inited", checkExternalLinkConfiguration)
1134	sphinx.connect("builder-inited", readReports)
1135	for reportPages in (CodeCoverageReportPages, DocCoverageReportPages, UnittestReportPages):
1136		sphinx.connect("env-before-read-docs", reportPages.GenerateAll)
1137		sphinx.connect("html-page-context", reportPages.HideSource)
1138	sphinx.connect("build-finished", reportBuildTime)
1139	sphinx.connect("builder-inited", installStaticFiles)
1140	sphinx.connect("builder-inited", installLaTeXPackage)
1141
1142	# The extension's version is the package's, so a second number to keep in step would only ever disagree.
1143	return {"version": __version__, "parallel_read_safe": True, "parallel_write_safe": True}