-
Notifications
You must be signed in to change notification settings - Fork 91
Expand file tree
/
Copy pathroles.py
More file actions
183 lines (161 loc) · 5.76 KB
/
roles.py
File metadata and controls
183 lines (161 loc) · 5.76 KB
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
"""Roles which can be used by both docutils and sphinx.
We intentionally do no import sphinx in this module,
in order to allow docutils-only use without sphinx installed.
"""
from __future__ import annotations
from docutils import nodes
from myst_nb.core.render import MimeData
from myst_nb.core.variables import (
RetrievalError,
format_plain_text,
render_variable_outputs,
)
from myst_nb.ext.utils import RoleBase
from .utils import (
PendingGlueReferenceError,
create_pending_glue_ref,
glue_warning,
retrieve_glue_data,
)
class PasteRoleAny(RoleBase):
"""A role for pasting inline code outputs from notebooks,
using render priority to decide the output mime type.
"""
def run(self) -> tuple[list[nodes.Node], list[nodes.system_message]]:
# check if this is a pending reference
doc_key = self.text.split("::", 1)
if len(doc_key) == 2:
doc, key = doc_key
try:
ref = create_pending_glue_ref(
self.document, self.source, self.line, doc, key, inline=True
)
except PendingGlueReferenceError as exc:
return [], [
glue_warning(
str(exc),
self.document,
self.line,
)
]
return [ref], []
try:
data = retrieve_glue_data(self.document, self.text)
except RetrievalError as exc:
return [], [glue_warning(str(exc), self.document, self.line)]
paste_nodes = render_variable_outputs(
[data],
self.document,
self.line,
self.source,
inline=True,
)
return paste_nodes, []
class PasteTextRole(RoleBase):
"""A role for pasting text/plain outputs from notebooks.
The role content should follow the format: ``<docpath>::<key>:<format_spec>``, where:
- ``<docpath>`` (optional) is the relative path to another notebook, defaults to local.
- ``<key>`` is the key
- ``<format_spec>`` (optional) is a format specifier,
defined in: https://docs.python.org/3/library/string.html#format-specification-mini-language,
it must end in the type character.
"""
def run(self) -> tuple[list[nodes.Node], list[nodes.system_message]]:
# check if we have both key:format in the key
key_format = self.text.rsplit(":", 1)
if len(key_format) == 2:
key, fmt_spec = key_format
else:
key = key_format[0]
fmt_spec = "s"
# check if this is a pending reference
doc_key = key.split("::", 1)
if len(doc_key) == 2:
doc, key = doc_key
try:
ref = create_pending_glue_ref(
self.document,
self.source,
self.line,
doc,
key,
inline=True,
gtype="text",
fmt_spec=fmt_spec,
)
except PendingGlueReferenceError as exc:
return [], [
glue_warning(
str(exc),
self.document,
self.line,
)
]
return [ref], []
# now retrieve the data
try:
result = retrieve_glue_data(self.document, key)
except RetrievalError as exc:
return [], [
glue_warning(
f"{exc} (use `path::key`, to glue from another document)",
self.document,
self.line,
)
]
if "text/plain" not in result.data:
return [], [
glue_warning(
f"No text/plain found in {key!r} data", self.document, self.line
)
]
try:
text = format_plain_text(result.data["text/plain"], fmt_spec)
except Exception as exc:
return [], [
glue_warning(
f"Failed to format text/plain data: {exc}", self.document, self.line
)
]
node = nodes.inline(text, text, classes=["pasted-text"])
self.set_source_info(node)
return [node], []
class PasteMarkdownRole(RoleBase):
"""A role for pasting markdown outputs from notebooks as inline MyST Markdown."""
def run(self) -> tuple[list[nodes.Node], list[nodes.system_message]]:
# check if we have both key:format in the key
parts = self.text.rsplit(":", 1)
if len(parts) == 2:
key, fmt = parts
else:
key = parts[0]
fmt = "commonmark"
# TODO - check fmt is valid
# retrieve the data
try:
result = retrieve_glue_data(self.document, key)
except RetrievalError as exc:
return [], [glue_warning(str(exc), self.document, self.line)]
if "text/markdown" not in result.data:
return [], [
glue_warning(
f"No text/markdown found in {key!r} data",
self.document,
self.line,
)
]
# TODO this feels a bit hacky
cell_key = result.nb_renderer.renderer.nb_config.cell_metadata_key
mime = MimeData(
"text/markdown",
result.data["text/markdown"],
cell_metadata={
cell_key: {"markdown_format": fmt},
},
output_metadata=result.metadata,
line=self.line,
)
_nodes = result.nb_renderer.render_markdown_inline(mime)
for node in _nodes:
self.set_source_info(node)
return _nodes, []