Skip to content

Commit

Permalink
render_math_src
Browse files Browse the repository at this point in the history
  • Loading branch information
jschueller committed Sep 14, 2022
1 parent 3e645e0 commit d04a440
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
9 changes: 5 additions & 4 deletions sphinx/ext/imgmath.py
Expand Up @@ -263,19 +263,20 @@ def render_math(self: HTMLTranslator, math: str) -> Tuple[Optional[str], Optiona
return relfn, depth, imgpath, outfn


def render_math_src(self: HTMLTranslator, math: str) -> str, int:
def render_math_src(self: HTMLTranslator, math: str) -> Tuple[Optional[str], Optional[int]]:
fname, depth, imgpath, outfn = render_math(self, math)
if self.builder.config.imgmath_embed:
image_format = self.builder.config.imgmath_image_format.lower()
mimetype = {'png': 'image/png', 'svg': 'image/svg+xml'}[image_format]
encoded = base64.b64encode(open(outfn, "rb").read()).decode()
return f'data:{mimetype};base64,{encoded}', depth
img_src = f'data:{mimetype};base64,{encoded}'
else:
# Move generated image on tempdir to build dir
if imgpath is not None:
ensuredir(path.dirname(outfn))
shutil.move(imgpath, outfn)
return fname, depth
img_src = fname
return img_src, depth


def cleanup_tempdir(app: Sphinx, exc: Exception) -> None:
Expand Down Expand Up @@ -323,7 +324,7 @@ def html_visit_displaymath(self: HTMLTranslator, node: nodes.math_block) -> None
else:
latex = wrap_displaymath(node.astext(), None, False)
try:
img_src, depth = render_math(self, latex)
img_src, depth = render_math_src(self, latex)
except MathExtError as exc:
msg = str(exc)
sm = nodes.system_message(msg, type='WARNING', level=2,
Expand Down
18 changes: 18 additions & 0 deletions tests/test_ext_math.py
Expand Up @@ -56,6 +56,24 @@ def test_imgmath_svg(app, status, warning):
assert re.search(html, content, re.S)


@pytest.mark.skipif(not has_binary('dvisvgm'),
reason='Requires dvisvgm" binary')
@pytest.mark.sphinx('html', testroot='ext-math-simple',
confoverrides={'extensions': ['sphinx.ext.imgmath'],
'imgmath_image_format': 'svg',
'imgmath_embed': True})
def test_imgmath_svg_embed(app, status, warning):
app.builder.build_all()
if "LaTeX command 'latex' cannot be run" in warning.getvalue():
raise pytest.skip.Exception('LaTeX command "latex" is not available')
if "dvisvgm command 'dvisvgm' cannot be run" in warning.getvalue():
raise pytest.skip.Exception('dvisvgm command "dvisvgm" is not available')

content = (app.outdir / 'index.html').read_text(encoding='utf8')
html=r'<img src="data:image/svg\+xml;base64,[\w\+/=]+"'
assert re.search(html, content, re.S)


@pytest.mark.sphinx('html', testroot='ext-math',
confoverrides={'extensions': ['sphinx.ext.mathjax'],
'mathjax_options': {'integrity': 'sha384-0123456789'}})
Expand Down

0 comments on commit d04a440

Please sign in to comment.