/
sphinx_renderer.py
339 lines (296 loc) · 12.6 KB
/
sphinx_renderer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
import copy
import os
import tempfile
from contextlib import contextmanager
from io import StringIO
from pathlib import Path
from typing import Optional, cast
from urllib.parse import unquote
from uuid import uuid4
from docutils import nodes
from docutils.parsers.rst import directives, roles
from markdown_it.tree import SyntaxTreeNode
from sphinx import addnodes
from sphinx.application import Sphinx, builtin_extensions
from sphinx.config import Config
from sphinx.domains.math import MathDomain
from sphinx.domains.std import StandardDomain
from sphinx.environment import BuildEnvironment
from sphinx.events import EventManager
from sphinx.project import Project
from sphinx.registry import SphinxComponentRegistry
from sphinx.util import logging
from sphinx.util.docutils import additional_nodes, sphinx_domains, unregister_node
from sphinx.util.nodes import clean_astext
from sphinx.util.tags import Tags
from myst_parser.docutils_renderer import DocutilsRenderer
LOGGER = logging.getLogger(__name__)
class SphinxRenderer(DocutilsRenderer):
"""A markdown-it-py renderer to populate (in-place) a `docutils.document` AST.
This is sub-class of `DocutilsRenderer` that handles sphinx specific aspects,
such as cross-referencing.
"""
@property
def doc_env(self) -> BuildEnvironment:
return self.document.settings.env
def create_warning(
self,
message: str,
*,
line: Optional[int] = None,
append_to: Optional[nodes.Element] = None,
wtype: str = "myst",
subtype: str = "other",
) -> Optional[nodes.system_message]:
"""Generate a warning, logging it if necessary.
If the warning type is listed in the ``suppress_warnings`` configuration,
then ``None`` will be returned and no warning logged.
"""
message = f"{message} [{wtype}.{subtype}]"
kwargs = {"line": line} if line is not None else {}
if not logging.is_suppressed_warning(
wtype, subtype, self.doc_env.app.config.suppress_warnings
):
msg_node = self.reporter.warning(message, **kwargs)
if append_to is not None:
append_to.append(msg_node)
return None
def render_internal_link(self, token: SyntaxTreeNode) -> None:
"""Render link token `[text](link "title")`,
where the link has not been identified as an external URL.
"""
destination = unquote(cast(str, token.attrGet("href") or ""))
# make the path relative to an "including" document
# this is set when using the `relative-docs` option of the MyST `include` directive
relative_include = self.config.get("relative-docs", None)
if relative_include is not None and destination.startswith(relative_include[0]):
source_dir, include_dir = relative_include[1:]
destination = os.path.relpath(
os.path.join(include_dir, os.path.normpath(destination)), source_dir
)
potential_path = (
Path(self.doc_env.doc2path(self.doc_env.docname)).parent / destination
if self.doc_env.srcdir # not set in some test situations
else None
)
if (
potential_path
and potential_path.is_file()
and not any(
destination.endswith(suffix)
for suffix in self.doc_env.config.source_suffix
)
):
wrap_node = addnodes.download_reference(
refdoc=self.doc_env.docname,
reftarget=destination,
reftype="myst",
refdomain=None, # Added to enable cross-linking
refexplicit=len(token.children or []) > 0,
refwarn=False,
)
classes = ["xref", "download", "myst"]
text = destination if not token.children else ""
else:
wrap_node = addnodes.pending_xref(
refdoc=self.doc_env.docname,
reftarget=destination,
reftype="myst",
refdomain=None, # Added to enable cross-linking
refexplicit=len(token.children or []) > 0,
refwarn=True,
)
classes = ["xref", "myst"]
text = ""
self.add_line_and_source_path(wrap_node, token)
title = token.attrGet("title")
if title:
wrap_node["title"] = title
self.current_node.append(wrap_node)
inner_node = nodes.inline("", text, classes=classes)
wrap_node.append(inner_node)
with self.current_node_context(inner_node):
self.render_children(token)
def render_heading(self, token: SyntaxTreeNode) -> None:
"""This extends the docutils method, to allow for the addition of heading ids.
These ids are computed by the ``markdown-it-py`` ``anchors_plugin``
as "slugs" which are unique to a document.
The approach is similar to ``sphinx.ext.autosectionlabel``
"""
super().render_heading(token)
if not isinstance(self.current_node, nodes.section):
return
# create the slug string
slug = cast(str, token.attrGet("id"))
if slug is None:
return
section = self.current_node
doc_slug = self.doc_env.doc2path(self.doc_env.docname, base=False) + "#" + slug
# save the reference in the standard domain, so that it can be handled properly
domain = cast(StandardDomain, self.doc_env.get_domain("std"))
if doc_slug in domain.labels:
other_doc = self.doc_env.doc2path(domain.labels[doc_slug][0])
self.create_warning(
f"duplicate label {doc_slug}, other instance in {other_doc}",
line=section.line,
subtype="anchor",
)
labelid = section["ids"][0]
domain.anonlabels[doc_slug] = self.doc_env.docname, labelid
domain.labels[doc_slug] = (
self.doc_env.docname,
labelid,
clean_astext(section[0]),
)
# for debugging
if not hasattr(self.doc_env, "myst_anchors"):
self.doc_env.myst_anchors = True # type: ignore[attr-defined]
section["myst-anchor"] = doc_slug
def render_math_block_label(self, token: SyntaxTreeNode) -> None:
"""Render math with referencable labels, e.g. ``$a=1$ (label)``."""
label = token.info
content = token.content
node = nodes.math_block(
content, content, nowrap=False, number=None, label=label
)
target = self.add_math_target(node)
self.add_line_and_source_path(target, token)
self.current_node.append(target)
self.add_line_and_source_path(node, token)
self.current_node.append(node)
def _random_label(self) -> str:
return str(uuid4())
def render_amsmath(self, token: SyntaxTreeNode) -> None:
# environment = token.meta["environment"]
content = token.content
if token.meta["numbered"] != "*":
# TODO how to parse and reference labels within environment?
# for now we give create a unique hash, so the equation will be numbered
# but there will be no reference clashes
label = self._random_label()
node = nodes.math_block(
content,
content,
nowrap=True,
number=None,
classes=["amsmath"],
label=label,
)
target = self.add_math_target(node)
self.add_line_and_source_path(target, token)
self.current_node.append(target)
else:
node = nodes.math_block(
content, content, nowrap=True, number=None, classes=["amsmath"]
)
self.add_line_and_source_path(node, token)
self.current_node.append(node)
def add_math_target(self, node: nodes.math_block) -> nodes.target:
# Code mainly copied from sphinx.directives.patches.MathDirective
# register label to domain
domain = cast(MathDomain, self.doc_env.get_domain("math"))
domain.note_equation(self.doc_env.docname, node["label"], location=node)
node["number"] = domain.get_equation_number_for(node["label"])
node["docname"] = self.doc_env.docname
# create target node
node_id = nodes.make_id("equation-%s" % node["label"])
target = nodes.target("", "", ids=[node_id])
self.document.note_explicit_target(target)
return target
def minimal_sphinx_app(
configuration=None, sourcedir=None, with_builder=False, raise_on_warning=False
):
"""Create a minimal Sphinx environment; loading sphinx roles, directives, etc."""
class MockSphinx(Sphinx):
"""Minimal sphinx init to load roles and directives."""
def __init__(self, confoverrides=None, srcdir=None, raise_on_warning=False):
self.extensions = {}
self.registry = SphinxComponentRegistry()
try:
self.html_themes = {}
except AttributeError:
# changed to property in sphinx 4.1
pass
self.events = EventManager(self)
# logging
self.verbosity = 0
self._warncount = 0
self.warningiserror = raise_on_warning
self._status = StringIO()
self._warning = StringIO()
logging.setup(self, self._status, self._warning)
self.tags = Tags([])
self.config = Config({}, confoverrides or {})
self.config.pre_init_values()
self._init_i18n()
for extension in builtin_extensions:
self.registry.load_extension(self, extension)
# fresh env
self.doctreedir = ""
self.srcdir = srcdir
self.confdir = None
self.outdir = ""
self.project = Project(srcdir=srcdir, source_suffix={".md": "markdown"})
self.project.docnames = {"mock_docname"}
self.env = BuildEnvironment(self)
self.env.setup(self)
self.env.temp_data["docname"] = "mock_docname"
# Ignore type checkers because we disrespect superclass typing here
self.builder = None # type: ignore[assignment]
if not with_builder:
return
# this code is only required for more complex parsing with extensions
for extension in self.config.extensions:
self.setup_extension(extension)
buildername = "dummy"
self.preload_builder(buildername)
self.config.init_values()
self.events.emit("config-inited", self.config)
with tempfile.TemporaryDirectory() as tempdir:
# creating a builder attempts to make the doctreedir
self.doctreedir = tempdir
self.builder = self.create_builder(buildername)
self.doctreedir = ""
app = MockSphinx(
confoverrides=configuration, srcdir=sourcedir, raise_on_warning=raise_on_warning
)
return app
@contextmanager
def mock_sphinx_env(
conf=None, srcdir=None, document=None, with_builder=False, raise_on_warning=False
):
"""Set up an environment, to parse sphinx roles/directives,
outside of a `sphinx-build`.
:param conf: a dictionary representation of the sphinx `conf.py`
:param srcdir: a path to a source directory
(for example, can be used for `include` statements)
This primarily copies the code in `sphinx.util.docutils.docutils_namespace`
and `sphinx.util.docutils.sphinx_domains`.
"""
# store currently loaded roles/directives, so we can revert on exit
_directives = copy.copy(directives._directives)
_roles = copy.copy(roles._roles)
# Monkey-patch directive and role dispatch,
# so that sphinx domain-specific markup takes precedence.
app = minimal_sphinx_app(
configuration=conf,
sourcedir=srcdir,
with_builder=with_builder,
raise_on_warning=raise_on_warning,
)
_sphinx_domains = sphinx_domains(app.env)
_sphinx_domains.enable()
if document is not None:
document.settings.env = app.env
try:
yield app
finally:
# revert loaded roles/directives
directives._directives = _directives
roles._roles = _roles
# TODO unregister nodes (see `sphinx.util.docutils.docutils_namespace`)
for node in list(additional_nodes):
unregister_node(node)
additional_nodes.discard(node)
# revert directive/role function (see `sphinx.util.docutils.sphinx_domains`)
_sphinx_domains.disable()