Skip to content

Commit 08943f5

Browse files
committed
strip Latex math delimiters that would be rendered by math blocks
Closes #90
1 parent 9641d94 commit 08943f5

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

jupyter_sphinx/execute.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -492,6 +492,25 @@ def count(x):
492492
return (list(x) for _, x in groupby(it, count))
493493

494494

495+
def strip_latex_delimiters(source):
496+
"""Remove LaTeX math delimiters that would be rendered by the math block.
497+
498+
These are: ``\(…\)``, ``\[…\]``, ``$…$``, and ``$$…$$``.
499+
This is necessary because sphinx does not have a dedicated role for
500+
generic LaTeX, while Jupyter only defines generic LaTeX output, see
501+
https://github.com/jupyter/jupyter-sphinx/issues/90 for discussion.
502+
"""
503+
source = source.strip()
504+
delimiter_pairs = (
505+
pair.split() for pair in r'\( \),\[ \],$$ $$,$ $'.split(',')
506+
)
507+
for start, end in delimiter_pairs:
508+
if source.startswith(start) and source.endswith(end):
509+
return source[len(start):-len(end)]
510+
511+
return source
512+
513+
495514
def cell_output_to_nodes(cell, data_priority, write_stderr, dir, thebe_config):
496515
"""Convert a jupyter cell with outputs and filenames to doctree nodes.
497516
@@ -582,7 +601,7 @@ def cell_output_to_nodes(cell, data_priority, write_stderr, dir, thebe_config):
582601
))
583602
elif mime_type == 'text/latex':
584603
to_add.append(math_block(
585-
text=data,
604+
text=strip_latex_delimiters(data),
586605
nowrap=False,
587606
number=None,
588607
classes=["output", "text_latex"]

tests/test_execute.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -407,3 +407,21 @@ def test_thebe_button_none(doctree):
407407
source = "No Jupyter cells"
408408
tree = doctree(source, config)
409409
assert len(tree.traverse(ThebeButtonNode)) == 0
410+
411+
412+
def test_latex(doctree):
413+
source = r"""
414+
.. jupyter-execute::
415+
416+
from IPython.display import Latex
417+
Latex(r"{}\int{}")
418+
"""
419+
420+
delimiter_pairs = (
421+
pair.split() for pair in r'\( \),\[ \],$$ $$,$ $'.split(',')
422+
)
423+
424+
for start, end in delimiter_pairs:
425+
tree = doctree(source.format(start, end))
426+
cell, = tree.traverse(JupyterCellNode)
427+
assert cell.children[1].astext() == r'\int'

0 commit comments

Comments
 (0)