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
|
"""Simple sphinx extension that executes code in jupyter and inserts output."""
from pathlib import Path
import docutils
import ipywidgets
from IPython.lib.lexers import IPython3Lexer, IPythonTracebackLexer
from sphinx.errors import ExtensionError
from sphinx.util import logging
from sphinx.util.fileutil import copy_asset
from ._version import __version__
from .ast import (
WIDGET_VIEW_MIMETYPE,
CellInput,
CellInputNode,
CellOutput,
CellOutputNode,
CombineCellInputOutput,
JupyterCell,
JupyterCellNode,
JupyterDownloadRole,
JupyterKernelNode,
JupyterWidgetStateNode,
JupyterWidgetViewNode,
MimeBundleNode,
)
from .execute import ExecuteJupyterCells, JupyterKernel
from .thebelab import ThebeButton, ThebeButtonNode, ThebeOutputNode, ThebeSourceNode
REQUIRE_URL_DEFAULT = (
"file:///usr/share/javascript/requirejs/require.min.js"
)
THEBELAB_URL_DEFAULT = "https://unpkg.com/thebelab@^0.4.0"
logger = logging.getLogger(__name__)
# Constants and functions we'll use later
# Used for nodes that do not need to be rendered
def skip(self, node):
raise docutils.nodes.SkipNode
# Used for nodes that should be gone by rendering time (OutputMimeBundleNode)
def halt(self, node):
raise ExtensionError(
"Rendering encountered a node type that should "
"have been removed before rendering: %s" % type(node)
)
# Renders the children of a container
render_container = (
lambda self, node: self.visit_container(node),
lambda self, node: self.depart_container(node),
)
# Used to render the container and its children as HTML
def visit_container_html(self, node):
self.body.append(node.visit_html())
self.visit_container(node)
def depart_container_html(self, node):
self.depart_container(node)
self.body.append(node.depart_html())
# Used to render an element node as HTML
def visit_element_html(self, node):
self.body.append(node.html())
raise docutils.nodes.SkipNode
# Used to render the ThebeSourceNode conditionally for non-HTML builders
def visit_thebe_source(self, node):
if node["hide_code"]:
raise docutils.nodes.SkipNode
else:
self.visit_container(node)
render_thebe_source = (
visit_thebe_source,
lambda self, node: self.depart_container(node),
)
# Sphinx callback functions
def builder_inited(app):
"""
2 cases
case 1: ipywidgets 7, with require
case 2: ipywidgets 7, no require
"""
require_url = app.config.jupyter_sphinx_require_url
if require_url:
app.add_js_file(require_url)
embed_url = (
app.config.jupyter_sphinx_embed_url
or ipywidgets.embed.DEFAULT_EMBED_REQUIREJS_URL
)
else:
embed_url = (
app.config.jupyter_sphinx_embed_url
or ipywidgets.embed.DEFAULT_EMBED_SCRIPT_URL
)
if embed_url:
app.add_js_file(embed_url)
def copy_file(src, dst):
if not (dst / src.name).exists():
copy_asset(str(src), str(dst))
def build_finished(app, env):
if app.builder.format != "html":
return
module_dir = Path(__file__).parent
static = Path(app.outdir) / "_static"
# Copy stylesheet
src = module_dir / "css" / "jupyter-sphinx.css"
copy_file(src, static)
thebe_config = app.config.jupyter_sphinx_thebelab_config
if not thebe_config:
return
# Copy all thebelab related assets
src_dir = module_dir / "thebelab"
for fname in ["thebelab-helper.js", "thebelab.css"]:
copy_file(src_dir / fname, static)
##############################################################################
# Main setup
def setup(app):
"""A temporary setup function so that we can use it here and in execute.
This should be removed and converted into `setup` after a deprecation
cycle.
"""
# Configuration
app.add_config_value(
"jupyter_execute_kwargs",
dict(timeout=-1, allow_errors=True, store_widget_state=True),
"env",
)
app.add_config_value("jupyter_execute_default_kernel", "python3", "env")
app.add_config_value(
"render_priority_html",
[
WIDGET_VIEW_MIMETYPE,
"application/javascript",
"text/html",
"image/svg+xml",
"image/png",
"image/jpeg",
"text/latex",
"text/plain",
],
"env",
)
app.add_config_value(
"render_priority_latex",
[
"image/svg+xml",
"image/png",
"image/jpeg",
"text/latex",
"text/plain",
],
"env",
)
# ipywidgets config
app.add_config_value("jupyter_sphinx_require_url", REQUIRE_URL_DEFAULT, "html")
app.add_config_value("jupyter_sphinx_embed_url", None, "html")
# thebelab config, can be either a filename or a dict
app.add_config_value("jupyter_sphinx_thebelab_config", None, "html")
app.add_config_value("jupyter_sphinx_thebelab_url", THEBELAB_URL_DEFAULT, "html")
# linenos config
app.add_config_value("jupyter_sphinx_linenos", False, "env")
app.add_config_value("jupyter_sphinx_continue_linenos", False, "env")
# JupyterKernelNode is just a doctree marker for the
# ExecuteJupyterCells transform, so we don't actually render it.
app.add_node(
JupyterKernelNode,
html=(skip, None),
latex=(skip, None),
textinfo=(skip, None),
text=(skip, None),
man=(skip, None),
)
# Register our container nodes, these should behave just like a regular container
for node in [JupyterCellNode, CellInputNode, CellOutputNode, MimeBundleNode]:
app.add_node(
node,
override=True,
html=(render_container),
latex=(render_container),
textinfo=(render_container),
text=(render_container),
man=(render_container),
)
# JupyterWidgetViewNode holds widget view JSON,
# but is only rendered properly in HTML documents.
app.add_node(
JupyterWidgetViewNode,
html=(visit_element_html, None),
latex=(skip, None),
textinfo=(skip, None),
text=(skip, None),
man=(skip, None),
)
# JupyterWidgetStateNode holds the widget state JSON,
# but is only rendered in HTML documents.
app.add_node(
JupyterWidgetStateNode,
html=(visit_element_html, None),
latex=(skip, None),
textinfo=(skip, None),
text=(skip, None),
man=(skip, None),
)
# ThebeSourceNode holds the source code and is rendered if
# hide-code is not specified. For HTML it is always rendered,
# but hidden using the stylesheet
app.add_node(
ThebeSourceNode,
html=(visit_container_html, depart_container_html),
latex=render_thebe_source,
textinfo=render_thebe_source,
text=render_thebe_source,
man=render_thebe_source,
)
# ThebeOutputNode holds the output of the Jupyter cells
# and is rendered if hide-output is not specified.
app.add_node(
ThebeOutputNode,
html=(visit_container_html, depart_container_html),
latex=render_container,
textinfo=render_container,
text=render_container,
man=render_container,
)
# ThebeButtonNode is the button that activates thebelab
# and is only rendered for the HTML builder
app.add_node(
ThebeButtonNode,
html=(visit_element_html, None),
latex=(skip, None),
textinfo=(skip, None),
text=(skip, None),
man=(skip, None),
)
app.add_directive("jupyter-execute", JupyterCell)
app.add_directive("jupyter-kernel", JupyterKernel)
app.add_directive("jupyter-input", CellInput)
app.add_directive("jupyter-output", CellOutput)
app.add_directive("thebe-button", ThebeButton)
for sep in [":", "-"]:
# Since Sphinx 4.0.0 using ":" inside of a role/directive does not work.
# Therefore, we add "-" as separator to get e.g., jupyter-download-notebook
# We leave the ":" syntax for backward compatibility reasons.
app.add_role(f"jupyter-download{sep}notebook", JupyterDownloadRole())
app.add_role(f"jupyter-download{sep}nb", JupyterDownloadRole())
app.add_role(f"jupyter-download{sep}script", JupyterDownloadRole())
app.add_transform(CombineCellInputOutput)
app.add_transform(ExecuteJupyterCells)
# For syntax highlighting
app.add_lexer("ipythontb", IPythonTracebackLexer)
app.add_lexer("ipython3", IPython3Lexer)
app.connect("builder-inited", builder_inited)
app.connect("build-finished", build_finished)
# add jupyter-sphinx and thebelab js and css
app.add_css_file("jupyter-sphinx.css")
app.add_js_file("thebelab-helper.js")
app.add_css_file("thebelab.css")
return {"version": __version__, "parallel_read_safe": True}
|