Sphinx extensions
Reference documentation for the modules under sphinx/_extensions/: directives, roles and
builders loaded by zdocs_conf.configure(). The plain modules they share are on
Support modules. See the companion
manual’s Directives and roles
page for how a document author uses each one.
doc_control
The .. doc_control:: directive — the controlled-document header table.
- class doc_control.DocCtrlDirective(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine)[source]
- has_content = False
May the directive have content?
- option_spec = {'approval_date': <function unchanged_required>, 'approved_by': <function unchanged_required>, 'author': <function unchanged_required>, 'based_on_template': <function unchanged>, 'classification': <function unchanged>, 'effective_date': <function unchanged>, 'owner': <function unchanged_required>, 'reviewed_by': <function unchanged_required>, 'supersedes': <function unchanged>, 'version': <function unchanged_required>}
Mapping of option names to validator functions.
- doc_control.latex_escape(text)[source]
Escape text for use in a LaTeX string.
Public because
zdocs_confneeds the same escaping for the running header and footer it builds out of consumer-supplied values (project name, copyright holder, document id). Those are the strings most likely to contain an&or an_, and a second copy of this table living in the config module is how the two would stop agreeing.
qms_ref
The .. qms_role:: directive.
latexinclude
The .. latexinclude:: directive.
The latexinclude directive — include an RST file in the PDF only.
.. latexinclude:: ../_glossary_terms.rst # relative to the AUTHORED file
.. latexinclude:: /_glossary_terms.rst # relative to the SOURCE TREE
A printed document carries no hyperlinks, so anything an HTML reader would reach by following a link has to travel with the PDF instead: a shared glossary, a terms-and-abbreviations appendix, a standards list. Inlining the same content into the HTML would just give that reader a second copy of a page they can already open, so this includes for LaTeX builders and does nothing everywhere else.
The path is relative to the including file as AUTHORED, which is not where
Sphinx parses it from. external_content copies each document’s folder into
<build>/<doc>/src and the build runs from that copy, so resolving the
argument against the parse location sends .. into <build>/<doc> — a
directory of doctrees and logs, never of authored RST. The only file worth
including this way is a SHARED one (a file inside the document would simply be
part of it), and a shared file is by definition outside the folder that gets
copied. So the wrong base directory does not degrade this directive, it breaks
every legitimate use of it.
The authored location is reconstructed from Sphinx’s own two facts: confdir
is the document’s authored directory (cmake passes it as -c), and docname
is the including file’s path within the document. Together they give the file the
author was looking at when they counted the ...
A leading ``/`` means relative to the source tree instead, exactly as it does
for Sphinx’s own include directive (“interprets absolute paths correctly,
i.e. relative to source directory”). The same spelling then works from both
directives and from any depth, which is the point: an authored-relative path
encodes how far the including file sits below the shared file, so moving a
document from doc/<id>/ to doc/<group>/<id>/ silently changes what
../ means and turns a working glossary into a build failure. A source-tree
path says where the file IS, not how far away the author happened to be.
That spelling requires the shared file to be present in the source tree, which
it is not by default – external_content copies only the document’s own
folder. A consumer that wants it adds it to external_content_contents (and
to exclude_patterns, since an include fragment is not a document). Both
spellings are supported and neither is deprecated: the authored-relative one
remains correct for a file that is deliberately NOT copied into the build.
- class latexinclude.LatexIncludeDirective(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine)[source]
Include an RST file for LaTeX builders, skipping it for every other.
- has_content = False
May the directive have content?
- required_arguments = 1
Number of required directive arguments.
- optional_arguments = 0
Number of optional arguments after the required arguments.
- final_argument_whitespace = False
May the final argument contain whitespace?
- option_spec = {}
Mapping of option names to validator functions.
test_module
The .. testmodule::, .. testreport:: and .. twisterinfo::
directives.
Sphinx extension: testmodule and testreport directives (Route B — sphinx-needs).
- test_module.suite_name_from_group(group_name, qualifier='')[source]
The ztest suite name a suite group’s compoundname stands for.
With a testmodule_suite_qualifier, the part after its LAST occurrence (
kernel_workq_user_work_module__workqueue_api->workqueue_apifor"__"), so two test modules declaring the same ZTEST_SUITE can give it distinct Doxygen groups. Without a qualifier, without an occurrence of it, or with nothing after it, the whole name.
- class test_module.TestModuleDirective(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine)[source]
Emit sphinx-needs test_case nodes for all ZTEST functions in a module group.
Usage:
.. testmodule:: kernel_queue_module :module: tests/kernel/queue
- required_arguments = 1
Number of required directive arguments.
- optional_arguments = 0
Number of optional arguments after the required arguments.
- has_content = False
May the directive have content?
- option_spec = {'module': <function unchanged>}
Mapping of option names to validator functions.
- class test_module.TestReportDirective(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine)[source]
Emit sphinx-needs test_result nodes from a twister_report.xml.
Usage:
.. testreport:: twister_report.xml :path: tests/kernel/queue
:path:selects the runs of one test directory, as twister.json records it;:module:selects by scenario-name prefix. With both, a run must match both.- required_arguments = 1
Number of required directive arguments.
- optional_arguments = 0
Number of optional arguments after the required arguments.
- has_content = False
May the directive have content?
- option_spec = {'module': <function unchanged>, 'path': <function unchanged>}
Mapping of option names to validator functions.
- class test_module.TwisterInfoDirective(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine)[source]
Emit a run-metadata block and per-platform summary table from twister.json.
Usage:
.. twisterinfo:: twister.json
- required_arguments = 1
Number of required directive arguments.
- optional_arguments = 0
Number of optional arguments after the required arguments.
- has_content = False
May the directive have content?
- option_spec = {}
Mapping of option names to validator functions.
test_coverage
The .. testcoverage:: directive. test_module loads it.
Sphinx extension: the testcoverage directive (coverage adequacy as needs).
.. testcoverage:: reads a per-test coverage run (adequacy) and emits one
adequacy need per requirement that the run can assess. Each need links to its
requirement (link role assesses) and carries the verdict. The directive
also writes a summary of the run and the distribution of the verdicts.
- test_coverage.ADEQUACY_FIELD_ROLES = ('verdict', 'evidence', 'coverage_run', 'judged_symbols', 'symbol_hits')
The adequacy field roles (testcoverage_need_fields).
- test_coverage.VERDICT_MEANING = {'broken': "Tests of the run reach the code. The requirement's own tests never do.", 'no-cov': 'The verifying tests have no coverage data in this run.', 'no-impl': 'No symbol satisfies the requirement.', 'partial': 'The own tests run some of the satisfying symbols, not all.', 'true': 'The own tests run every symbol that coverage can judge.', 'unattributed': 'No test of the run covers any body. Coverage cannot judge the link.', 'unresolved': 'No satisfying symbol maps to a body (a macro).'}
What each verdict says, for the distribution table.
- test_coverage.CELL_ROLES = ('zd-adq-ok', 'zd-adq-miss', 'zd-adq-none')
each gives an inline node with the role name as its class, for
zdocs-needs.css. The place of a body is a paragraph of classzd-adq-loc.- Type:
The roles of the body table cells
- test_coverage.adequacy_need_id(run, req, prefix='ADQ')[source]
<prefix>-<run>/<req>, the id ofreq’s adequacy need inrun.
- test_coverage.adequacy_summary(res)[source]
One sentence (RST) that says why the verdict of
resis what it is.
- test_coverage.build_adequacy_rst(req, res, run, need_names=None, fields=(), prefix='ADQ', layout='', title=None, body_url=None)[source]
RST lines for the adequacy need of
req(resfrom adequacy.assess).layout: the sphinx-needs layout of the need, if not empty.title: the title of the requirement; the need has it as its own title. Without it, the title isAdequacy of <req>.The body says why the verdict is what it is. A table gives each body of a satisfying symbol: the lines that the own tests ran, of the lines that any test of the run ran, and the number of other test cases that ran it. For a body that the own tests never run, the body names the other tests that do. A field that the consumer does not declare is in the body too.
body_url(file, line): the source listing of a body at its first line, or""; the place of the body links to it.
- test_coverage.build_coverage_rst(results, run, source, impl_loc, need_names=None, fields=(), prefix='ADQ', layout='', impl_files=('kernel/*.c', 'kernel/**/*.c', 'include/zephyr/kernel.h', 'include/zephyr/kernel/**/*.h', 'include/zephyr/sys/**/*.h'), titles=None, body_url=None)[source]
RST lines for the whole directive: run summary, distribution, needs by verdict.
impl_files: the body files that the run searched, for the summary.titles: the title of each requirement, for the title of its need.body_url: see build_adequacy_rst.
- class test_coverage.TestCoverageDirective(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine)[source]
Emit one adequacy need per requirement that a per-test coverage run can assess.
Usage:
.. testcoverage:: :run: my-run :layout: adequacy
The optional argument is the run directory. Without it, the directive reads
coverage_output_dir(ZDOCS_COVERAGE_OUT).:run:names the run in the need ids. Without it, the name is the first tag on the run commit, or else the name of the run directory.:layout:sets the sphinx-needs layout of each need.testcoverage_impl_filessets the files that hold the bodies of the satisfying symbols.- required_arguments = 0
Number of required directive arguments.
- optional_arguments = 1
Number of optional arguments after the required arguments.
- has_content = False
May the directive have content?
- option_spec = {'layout': <function unchanged>, 'run': <function unchanged>}
Mapping of option names to validator functions.
symbol_needs
The .. symbolneeds:: directive.
Sphinx extension: the symbolneeds directive — one need per API symbol that satisfies a requirement.
A Doxygen 1.16 \satisfies <UID> on a function or macro becomes, in the XML,
a <satisfies> child of its memberdef. This directive turns each such symbol
into a need (the implementation role) linked to those requirements (the
satisfies role), so a requirement’s page shows what implements it next to
what verifies it.
Loaded only for a document whose registry entry has a symbol_needs: block,
which also names the Doxygen document whose XML is read.
- symbol_needs.symbol_needs_rst(xml_dir, html_dir, group=None, need_names=None, note_input=None, depends_field=None)[source]
RST lines for the symbol needs of
group(or the whole project).With no group, the needs are sectioned by compound (group or file), each heading taken from the compound’s title. A member is emitted once, where Doxygen defines it, however many compounds list it.
note_inputis called with every XML file read.depends_field(conditions, subject)decides whether a need gets thedepends_onfield (needs_fields.depends_field); without it, none does. “Declared in” links to the source listing of the run, if it wrote one (doxygen_parser.SourcePages).
- class symbol_needs.SymbolNeedsDirective(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine)[source]
Emit one need per API symbol carrying a Doxygen
\satisfies.Usage:
.. symbolneeds:: .. symbolneeds:: queue_apis
The optional argument is a Doxygen group name; without it every annotated symbol in the project is emitted, sectioned by group or file.
- required_arguments = 0
Number of required directive arguments.
- optional_arguments = 1
Number of optional arguments after the required arguments.
- has_content = False
May the directive have content?
- option_spec = {}
Mapping of option names to validator functions.
input_tracking
Re-reads a document when an input from outside the source tree changes.
Sphinx extension: track a document’s inputs from outside the source tree.
The testmodule, testreport, twisterinfo and symbolneeds directives read files Sphinx knows nothing about: Doxygen XML, twister’s XML/JSON, a spec’s needs.json. Sphinx re-reads a document only when a tracked input is missing or NEWER than the document’s last read. That is not enough here: twister output often arrives with an older mtime (a CI artifact or cache restored with its timestamps, a copy that preserves them), and the report then stays stale without a warning. So each input’s signature is recorded at read time, and a document is re-read whenever a signature differs, in either direction.
Loaded by the extensions that use it (app.setup_extension), which Sphinx
does once however many ask.
needs_config_state
Re-reads a document when its sphinx-needs TOML file or the needs it imports change.
Sphinx extension: re-read a document when its needs vocabulary or imports change.
A document’s need types, links and fields come from a TOML file
(needs_from_toml, set by zdocs_conf from ZDOCS_NEEDS_CONFIG).
Sphinx re-reads every document when a config value registered with rebuild
"env" changes, but sphinx-needs registers needs_types,
needs_links and needs_fields with rebuild "html", and the config
value needs_from_toml is only the file’s path. So after the file gains a
link type, an incremental build reuses the pickled needs, which have no entry
for the new link, and the first new need that uses it crashes the build:
KeyError: "Link type 'fulfills' does not exist in backlinks.". A clean
build works.
This extension registers zdocs_needs_config_digest, rebuild "env",
and sets it to the SHA-256 of the file’s content. A change to the file changes
the value, and Sphinx re-reads the document (“config changed”). The value is
the same for both build stages, so the stage caches stay valid while the file
does not change.
Re-reading is not enough when a link type is REMOVED: the pickled environment
still holds needs imported from a peer’s needs.json under the old vocabulary,
and the importing document crashes the same way once, although the peer’s
file no longer has the link. So on a change the pickled environment is also
dropped before Sphinx loads it (config-inited runs first), and the
document starts from a fresh one, as in a clean build. The digests the
environment was built with are kept beside it, in the doctree directory.
The needs that a document imports (needs_external_needs) have a
similar problem. sphinx-needs loads them again on each build, but Sphinx
writes only the pages of the documents that it read. When a peer’s
needs.json gains a need that links to a need of this document, the source of
the page with that need does not change. So Sphinx does not write the page
again, and the page does not show the new incoming link. For example, a
requirement page did not show “assessed by” after the test report gained
adequacy needs.
So the extension also registers zdocs_imported_needs_digest, rebuild
"env": a SHA-256 over the needs that each imported file gives. A change
to it also starts from a fresh environment. This also removes the needs that
a peer no longer has.
- needs_config_state.STAMP_NAME = 'zdocs-needs-config.sha256'
the digests it was built with.
- Type:
Beside the pickled environment
- needs_config_state.ENV_PICKLE = 'environment.pickle'
Sphinx’s pickled environment in the doctree directory.
- needs_config_state.needs_config_digest(confdir, from_toml)[source]
SHA-256 of the needs TOML file, or
""if none is set or it is unreadable.from_tomlis resolved againstconfdir, as sphinx-needs resolves it.
- needs_config_state.imported_needs_digest(confdir, external_needs)[source]
SHA-256 over the needs that
needs_external_needsimports, or""if none.Only
json_pathsources count. A relative path is resolved againstconfdir, as sphinx-needs resolves it. Ajson_urlsource is not read.The settings of each source (
base_urland the others) count too: the pickled environment keeps each imported need with its URL. Without them, a newZDOCS_DOC_BASE_URLleft the links of a PDF on the old one.
- needs_config_state.drop_stale_environment(doctreedir, digest)[source]
Delete the pickled environment in
doctreedirunless it was built withdigest.An environment with no recorded digest (a build dir from before this extension) counts as stale. Returns whether one was deleted; records
digesteither way.
need_cards
The type colors, the status and verdict classes and the previews of the zdocs need cards, and the card in a PDF.
What the zdocs need cards (zdocs-needs.css) need from the build.
The color of each need type. A need type in needs_config.toml has a
color; sphinx-needs uses it in need flows. This extension writes
_static/zdocs-need-types.css with one rule per type, so that a card has the
same color as the type has in a flow:
table.need.need.need.need.needs_type_req { --zd-type: #FDEBD0; }
A type without a color, or with a value that is no CSS color, gets no rule; its cards stay grey.
The status and the verdict of each need. sphinx-needs gives the table of
a need no class for a field value, and CSS cannot read the text. After
sphinx-needs has rendered the needs of a page, the extension adds
zd-status-<status> and zd-verdict-<verdict> to each need table that
has the field (zd-status-passed, zd-verdict-partial), so that the card
can color the pill. The need data does not change.
A preview of the linked need. The extension adds zdocs-need-preview.js
to each page. When the pointer stays on a link in a card, and the link goes
to another card, a popup shows a copy of that card. The script fetches the
target page in the browser, so it needs a page served over HTTP; a page
opened as file:// gets previews of the needs on the same page only.
The card in a PDF. CSS does not reach LaTeX: there, sphinx-needs writes a
card as a table of grey rows. In a LaTeX build the extension replaces the
table of each zdocs card (layout name zdocs...) with a zd_need node, and
writes it with the macros of zdocs.sty:
\begin{zdneed}{<accent RRGGBB>}
\zdneedhead{<type>}{<ID>}{<tone>}{<status>}
\zdneedtitle{<title>}
<text of the need>
\zdneedfield{<label>}{<value>} (each field and link)
\end{zdneed}
The accent is the type color of the HTML card, made darker. The tone of the
status (good, bad, gap, none or accent) is the color of
the pill in zdocs-needs.css. The links in the card stay links, and the
label of the need stays a LaTeX label, so links into the card still work.
- need_cards.type_colors_css(types)[source]
The CSS rules for
types(the sphinx-needsneeds_typeslist).
- need_cards.NEED_REF_CLASS = 'zd-need-ref'
the preview script takes only these links, and so fetches no page that has no card (a Doxygen source listing or API page).
- Type:
The class of a link in a card that goes to a need
- need_cards.PILL_FIELDS = ('status', 'verdict')
the engine’s status and verdict.
- Type:
The fields that a card shows as a pill
- need_cards.status_class(value, field='status')[source]
The class for
valueoffield:zd-<field>-and the value in lower case, with each run of other characters than letters and digits as one-.Nonefor no value.
- need_cards.TONES = {'bad': ('zd-status-failed', 'zd-status-error', 'zd-verdict-broken'), 'gap': ('zd-verdict-partial', 'zd-verdict-no-impl'), 'good': ('zd-status-passed', 'zd-verdict-true'), 'none': ('zd-status-skipped', 'zd-status-filtered', 'zd-status-blocked', 'zd-status-not-run', 'zd-verdict-unattributed', 'zd-verdict-unresolved', 'zd-verdict-no-cov')}
The tone of a status or verdict value (its class), as zdocs-needs.css colors the pill. Other values have the tone “accent”, the type color.
- need_cards.accent(color)[source]
The accent of a card of type color
color(#rrggbb,#rgb), asRRGGBB;Nonefor no such color.The same as
--zd-accentin zdocs-needs.css: the hue of the type color, lightness 0.52 and four times the chroma plus 0.02 (OKLCH), so that a pastel type color gives a line that is dark enough on paper. A chroma that sRGB cannot show is made smaller until it fits.
- need_cards.DEFAULT_ACCENT = '666666'
the grey of the HTML card.
- Type:
The accent of a type without a color
- class need_cards.zd_need(rawsource: str = '', *children, **attributes: Any)[source]
A zdocs card in a LaTeX build. Attributes:
accent,type_name,need_id,tone,pill. Children: one zd_need_title, then the text of the need, then one zd_need_field for each field and link.
- class need_cards.zd_need_title(rawsource: str = '', text: str = '', *children, **attributes: Any)[source]
The title of a card.
pdf_links
Writes a link that is dead in a PDF (a local server, a relative HTML path) as its text.
Sphinx extension: the links of a PDF go into the PDF set, and none is dead.
Into the PDF set. The PDFs of a document set go into one folder,
deploy/pdf, as <title>_<version>.pdf (docrefs.py pdf-deliver). A
link to a page of a peer in the set (<peer URL>/<page>.html#<anchor>)
becomes a link to the peer’s PDF and the named destination of that label:
<file>#<page>:<anchor>, or <file>#<page>::doc for a page without an
anchor. The destinations exist because zdocs_conf sets hyperref’s
destlabel: each LaTeX label is a destination of the same name. hyperref
writes such a link as a “go to remote” action (GoToR), file and destination.
zdocs_pdf_peers (from docrefs) maps each peer’s URL to its file.
No dead link. A PDF has no sibling tree of HTML pages. Two kinds of link from the HTML world are dead in it:
a relative link, such as
../../dox-api/main_8c_source.html: it resolves against the folder of the PDF, where no such page is;a link to a local server (
localhostor a loopback address): the registry’sbase_urlof a development build.
In a LaTeX build, this extension writes such a link as its text, without the
link, and warns once per document. Set ZDOCS_DOC_BASE_URL to the
published site to keep the links to other documents. Links inside the PDF and
links to another host stay as they are.
It runs on doctree-resolved, after sphinx-needs has written the links of
the needs (doctree-resolved at the default priority 500).
pdf_tables
Gives a need table in a PDF column widths from its content, and lets it break across pages.
Need tables in a PDF: column widths from the content, and page breaks.
sphinx-needs gives a needtable without :colwidths: fixed widths: 15
parts for the title, 5 for each other column. In a PDF, a column of long
values (tags, Kconfig names) then runs past the edge of the page, and a
column of short ones (need IDs) is so narrow that each ID breaks in two. And
Sphinx writes a table of 30 rows or fewer as a tabular, which does not
break across pages: a long table moves to the next page and leaves an empty
page before it.
In a LaTeX build, this extension gives each such table:
column widths from its content (column_widths): each column is as wide as its longest word, and the rest of the line goes to the columns with the most text;
the class
longtable, so that it breaks across pages and repeats its header row;the container class
zd-needtable: text not justified, which zdocs.sty sets (Sphinx’ssphinxclass<name>environment);if it is too wide for the line, a smaller font and less cell padding: the class
zd-table-smallorzd-table-smallertoo;a possible line break after each
/, and after each.before a letter, in its text:native_sim/native/64,safe_data.api.timeout. (After an underscore, zdocs.sty allows a break everywhere.)
A needtable with :colwidths: keeps its widths.
- pdf_tables.LINE = 90
The width of a line of a table, in characters of the table font. Only the ratio of the widths is in the PDF (X{w}{sum}), so this is the scale on which a column is “as wide as its longest word”.
- pdf_tables.SMALLER = (('zd-table-small', 108), ('zd-table-smaller', 124))
The classes for a table that is too wide, and the line width in their font: footnotesize and scriptsize, with less padding (zdocs.sty).
- pdf_tables.LONGEST_WORD = 24
A word longer than this breaks (after an underscore, zdocs.sty) and does not make its column wider.
- pdf_tables.PADDING = 3
2 \tabcolsep).
- Type:
The padding of a cell, in characters (Sphinx
xref_builder
The stage-1 xref builder for the two-stage documentation build.
Stage-1 xref builder for the two-stage documentation build.
Cross-referenced documents form a dependency cycle: each doc’s HTML needs the
indexes (objects.inv / needs.json / Doxygen tag files) of the docs it
links to. Those indexes depend only on a doc’s own content, so the build is
split in two:
stage 1 — every doc emits just its index (this builder), no HTML;
stage 2 — every doc builds HTML with all indexes present, so cross references resolve.
This builder subclasses Sphinx’s dummy builder: it reads/parses the whole
project (populating the environment) but writes no HTML. In finish() it
dumps objects.inv for intersphinx. needs.json is handled separately by
sphinx-needs itself: when needs_build_json = True its build-finished
hook writes needs.json into the same output directory regardless of the
active builder — so a sphinx-needs doc gets both artifacts from one xref build.
Stage 2 uses a SEPARATE doctree cache (-d) and parses for itself, once every
peer index exists. Sharing one cache is what this build system used to do, and it
was wrong: a role that resolves at parse time — :external+<inv>: is one — was
resolved during stage 1 against inventories that did not exist yet, and stage 2,
reusing that parse, wrote the empty result out. See the doctree comment in
zdocs/cmake/sphinx.cmake.
- class xref_builder.XrefBuilder(app: Sphinx, env: BuildEnvironment)[source]
- name = 'xref'
The builder’s name. This is the value used to select builders on the command line.
- epilog = 'Cross-reference index written to %(outdir)s.'
The message emitted upon successful build completion. This can be a printf-style template string with the following keys:
outdir,project