A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
Handle marimo tex components when exporting to PDF (#8062)
Shahmir Varqhab36ff2e83ed2
diff --git a/marimo/_convert/ipynb/from_ir.py b/marimo/_convert/ipynb/from_ir.pyindex d2e8fc026d..e4970d97f4 100644--- a/marimo/_convert/ipynb/from_ir.py+++ b/marimo/_convert/ipynb/from_ir.py@@ -154,6 +154,9 @@ def _create_ipynb_cell(if cell is not None:markdown_string = get_markdown_from_cell(cell, code)if markdown_string is not None:+ markdown_string = _convert_latex_delimiters_for_jupyter(+ markdown_string+ )node = cast(nbformat.NotebookNode,nbformat.v4.new_markdown_cell(markdown_string, id=cell_id), # type: ignore[no-untyped-call]@@ -269,10 +272,12 @@ def _get_error_info(return error_dict.get("type", "Error"), error.describe()-def _convert_rich_output_to_ipynb(+def _convert_output_to_ipynb(output: CellOutput,) -> Optional[NotebookNode]:- """Convert a rich output (OUTPUT/MEDIA channel) to IPython notebook format.+ """Convert certain outputs (OUTPUT/MEDIA channel) to IPython notebook format.++ Outputs like rich elements and LaTeX are converted to ensure they are compatible with IPython notebook format.Returns None if the output should be skipped or produces no data."""@@ -289,7 +294,6 @@ def _convert_rich_output_to_ipynb():return None- # Handle rich outputdata: dict[str, Any] = {}metadata: dict[str, Any] = {}@@ -313,6 +317,8 @@ def _convert_rich_output_to_ipynb(continueelse:data[mime] = _maybe_extract_dataurl(content)+ elif output.mimetype == "text/markdown" and isinstance(output.data, str):+ data[output.mimetype] = _convert_marimo_tex_to_latex(output.data)else:data[output.mimetype] = _maybe_extract_dataurl(output.data)@@ -384,10 +390,9 @@ def _convert_marimo_output_to_ipynb())elif console_out.channel in (CellChannel.OUTPUT, CellChannel.MEDIA):- # Handle rich outputs in console area (e.g., plt.show())- rich_output = _convert_rich_output_to_ipynb(console_out)- if rich_output is not None:- ipynb_outputs.append(rich_output)+ ipynb_compatible_output = _convert_output_to_ipynb(console_out)+ if ipynb_compatible_output is not None:+ ipynb_outputs.append(ipynb_compatible_output)if not cell_output:return ipynb_outputs@@ -415,9 +420,70 @@ def _convert_marimo_output_to_ipynb()return ipynb_outputs- # Handle rich output from cell- rich_output = _convert_rich_output_to_ipynb(cell_output)- if rich_output is not None:- ipynb_outputs.append(rich_output)+ ipynb_compatible_output = _convert_output_to_ipynb(cell_output)+ if ipynb_compatible_output is not None:+ ipynb_outputs.append(ipynb_compatible_output)return ipynb_outputs+++def _convert_latex_delimiters_for_jupyter(markdown_string: str) -> str:+ """Convert LaTeX delimiters that nbconvert can't handle. See https://github.com/jupyter/nbconvert/issues/477"""++ # Convert display math \[...\] to $$...$$+ # Preserve internal whitespace but trim the delimiter boundaries+ def replace_display(match: re.Match[str]) -> str:+ content = match.group(1)+ return f"$${content.strip()}$$"++ markdown_string = re.sub(+ r"\\\[(.*?)\\\]", replace_display, markdown_string, flags=re.DOTALL+ )++ # Convert inline math \(...\) to $...$+ # Remove spaces adjacent to delimiters+ def replace_inline(match: re.Match[str]) -> str:+ content = match.group(1)+ return f"${content.strip()}$"++ markdown_string = re.sub(+ r"\\\((.*?)\\\)", replace_inline, markdown_string, flags=re.DOTALL+ )++ return markdown_string+++def _convert_marimo_tex_to_latex(html_string: str) -> str:+ """Convert marimo-tex elements back to standard LaTeX delimiters.+ Keep in sync with TexPlugin.tsx++ Converts:+ - <marimo-tex ...>||(content||)</marimo-tex> → $content$ (inline)+ - <marimo-tex ...>||[content||]</marimo-tex> → $$content$$ (block)+ - <marimo-tex ...>||(||(content||)||)</marimo-tex> → $$content$$ (nested display)+ """++ def replace_tex(match: re.Match[str]) -> str:+ content = match.group(1)++ # Handle nested display math: ||(||(content||)||)+ # Must check this FIRST and be more specific+ if content.startswith("||(||(") and content.endswith("||)||)"):+ inner = content[6:-6] # Strip ||(||( and ||)||)+ return f"$${inner}$$"+ # Handle block math: ||[content||]+ elif content.startswith("||[") and content.endswith("||]"):+ inner = content[3:-3]+ return f"$${inner}$$"+ # Handle inline math: ||(content||)+ elif content.startswith("||(") and content.endswith("||)"):+ inner = content[3:-3]+ return f"${inner}$" # Single $ for inline!+ else:+ return content++ # Match <marimo-tex ...>content</marimo-tex>+ # Use non-greedy matching and handle potential attributes+ pattern = r"<marimo-tex[^>]*>(.*?)</marimo-tex>"++ return re.sub(pattern, replace_tex, html_string, flags=re.DOTALL)diff --git a/marimo/_smoke_tests/latex/704.py b/marimo/_smoke_tests/latex/704.pynew file mode 100644index 0000000000..9769193e8a--- /dev/null+++ b/marimo/_smoke_tests/latex/704.py@@ -0,0 +1,35 @@+import marimo++__generated_with = "0.19.6"+app = marimo.App(width="medium")+++def _():+ import marimo as mo+ return (mo,)++[email protected](hide_code=True)+def _(mo):+ mo.md(r"""+ # Incrementing functions+ Bug from [#704](https://github.com/marimo-team/marimo/discussions/704)+ """)+ return++[email protected](hide_code=True)+def _(mo):+ mo.md(r"""+ \begin{align}+ B' &=-\nabla \times E,\\+ E' &=\nabla \times B - 4\pi j\\+ e^{\pi i} + 1 = 0+ \end{align}+ """)+ return+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_smoke_tests/latex/latex.md b/marimo/_smoke_tests/latex/latex.mdnew file mode 100644index 0000000000..af063541a9--- /dev/null+++ b/marimo/_smoke_tests/latex/latex.md@@ -0,0 +1,182 @@+---+title: Latex+marimo-version: 0.19.6+header: |-+ # Copyright 2026 Marimo. All rights reserved.+---++```python {.marimo}+import marimo as mo+```++# LaTeX Smoke Test++This notebook tests various LaTeX writing styles and configurations.+<!---->+## 1. Inline Math Delimiters++Different ways to write inline math:+<!---->+- Dollar signs: The equation $E = mc^2$ is famous.+- Backslash parens: The equation \(E = mc^2\) also works.+- With spaces: $ a + b = c $ (spaces around content).+- Complex inline: $\frac{x^2}{y^2} + \sqrt{z}$ in a sentence.+<!---->+## 2. Display Math Delimiters++Different ways to write display/block math:+<!---->+Double dollar signs:++$$+f(x) = \int_{-\infty}^{\infty} e^{-x^2} dx = \sqrt{\pi}+$$+<!---->+Backslash brackets:++\[+\sum_{n=1}^{\infty} \frac{1}{n^2} = \frac{\pi^2}{6}+\]+<!---->+Inline display (no newlines): \[ x^2 + y^2 = z^2 \]+<!---->+## 3. LaTeX Environments+<!---->+### Align environment (multi-line equations):++\begin{align}+ B' &= -\nabla \times E \\+ E' &= \nabla \times B - 4\pi j \\+ e^{\pi i} + 1 &= 0+\end{align}+<!---->+### Equation environment:++\begin{equation}+\mathcal{L} = \int_\Omega \left( \frac{1}{2} |\nabla u|^2 - f u \right) dx+\end{equation}+<!---->+### Matrix environments:++Regular matrix: $\begin{matrix} a & b \\ c & d \end{matrix}$++Parentheses: $\begin{pmatrix} 1 & 2 \\ 3 & 4 \end{pmatrix}$++Brackets: $\begin{bmatrix} x \\ y \\ z \end{bmatrix}$++Determinant: $\begin{vmatrix} a & b \\ c & d \end{vmatrix} = ad - bc$+<!---->+### Cases environment:++$$+|x| = \begin{cases}+ x & \text{if } x \geq 0 \\+ -x & \text{if } x < 0+\end{cases}+$$+<!---->+## 4. Greek Letters and Symbols+<!---->+- Lowercase: $\alpha, \beta, \gamma, \delta, \epsilon, \zeta, \eta, \theta$+- More: $\iota, \kappa, \lambda, \mu, \nu, \xi, \pi, \rho, \sigma, \tau$+- And: $\upsilon, \phi, \chi, \psi, \omega$+- Uppercase: $\Gamma, \Delta, \Theta, \Lambda, \Xi, \Pi, \Sigma, \Phi, \Psi, \Omega$+- Operators: $\partial, \nabla, \infty, \forall, \exists, \emptyset$+- Relations: $\leq, \geq, \neq, \approx, \equiv, \sim, \propto$+- Arrows: $\leftarrow, \rightarrow, \leftrightarrow, \Rightarrow, \Leftrightarrow$+<!---->+## 5. Common Mathematical Expressions+<!---->+### Fractions and roots:++$$\frac{a}{b}, \quad \frac{x+1}{x-1}, \quad \dfrac{\partial f}{\partial x}$$++$$\sqrt{x}, \quad \sqrt[3]{x}, \quad \sqrt{x^2 + y^2}$$+<!---->+### Subscripts and superscripts:++$$x_i, \quad x^2, \quad x_i^2, \quad x_{i,j}^{(n)}, \quad e^{i\pi}$$+<!---->+### Sums, products, integrals, limits:++$$\sum_{i=1}^{n} x_i, \quad \prod_{i=1}^{n} x_i, \quad \int_a^b f(x)\,dx, \quad \lim_{x \to \infty} f(x)$$++$$\iint_D f(x,y)\,dx\,dy, \quad \oint_C \vec{F} \cdot d\vec{r}$$+<!---->+### Brackets and delimiters:++$$\left( \frac{a}{b} \right), \quad \left[ \frac{a}{b} \right], \quad \left\{ \frac{a}{b} \right\}$$++$$\left\langle \psi | \phi \right\rangle, \quad \left\| \vec{v} \right\|, \quad \left\lfloor x \right\rfloor, \quad \left\lceil x \right\rceil$$+<!---->+## 6. Chemistry (mhchem)++Using the mhchem extension for chemical equations:+<!---->+- Water: $\ce{H2O}$+- Sulfuric acid: $\ce{H2SO4}$+- Chemical reaction: $\ce{2H2 + O2 -> 2H2O}$+- Equilibrium: $\ce{N2 + 3H2 <=> 2NH3}$+- Isotopes: $\ce{^{14}C}$, $\ce{^{238}U}$+<!---->+## 7. Edge Cases+<!---->+### Math in lists:++1. First item: $a^2 + b^2 = c^2$+2. Second item: $\sin^2\theta + \cos^2\theta = 1$+3. Third item: $e^{i\theta} = \cos\theta + i\sin\theta$++- Bullet with math: $\vec{F} = m\vec{a}$+- Another: $\nabla \cdot \vec{E} = \frac{\rho}{\epsilon_0}$+<!---->+### Multiple inline math in one paragraph:++The function $f(x) = x^2$ has derivative $f'(x) = 2x$ and second derivative $f''(x) = 2$.+At $x = 0$, we have $f(0) = 0$, $f'(0) = 0$, and $f''(0) = 2 > 0$, so $x = 0$ is a local minimum.+<!---->+### Special characters that need escaping:++- Percent: $100\%$ confidence+- Ampersand in align: handled by environment+- Backslash: $\backslash$+- Tilde: $\tilde{x}$, $\widetilde{xyz}$+- Hat: $\hat{x}$, $\widehat{xyz}$+- Bar: $\bar{x}$, $\overline{xyz}$+<!---->+## 8. Real-World Examples+<!---->+### Euler's identity (the most beautiful equation):++$$e^{i\pi} + 1 = 0$$+<!---->+### Quadratic formula:++The solutions to $ax^2 + bx + c = 0$ are:++$$x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$+<!---->+### Gaussian integral:++$$\int_{-\infty}^{\infty} e^{-x^2} dx = \sqrt{\pi}$$+<!---->+### Maxwell's equations:++\begin{align}+ \nabla \cdot \vec{E} &= \frac{\rho}{\epsilon_0} \\+ \nabla \cdot \vec{B} &= 0 \\+ \nabla \times \vec{E} &= -\frac{\partial \vec{B}}{\partial t} \\+ \nabla \times \vec{B} &= \mu_0 \vec{J} + \mu_0 \epsilon_0 \frac{\partial \vec{E}}{\partial t}+\end{align}+<!---->+### Schrödinger equation:++$$i\hbar\frac{\partial}{\partial t}\Psi(\vec{r},t) = \hat{H}\Psi(\vec{r},t) = \left[-\frac{\hbar^2}{2m}\nabla^2 + V(\vec{r},t)\right]\Psi(\vec{r},t)$$+<!---->+### Bayes' theorem:++$$P(A|B) = \frac{P(B|A) \cdot P(A)}{P(B)}$$+<!---->+### Taylor series:++$$f(x) = \sum_{n=0}^{\infty} \frac{f^{(n)}(a)}{n!}(x-a)^n = f(a) + f'(a)(x-a) + \frac{f''(a)}{2!}(x-a)^2 + \cdots$$\ No newline at end of filediff --git a/marimo/_smoke_tests/latex/latex.py b/marimo/_smoke_tests/latex/latex.pyindex f2459516f0..802431d7a0 100644--- a/marimo/_smoke_tests/latex/latex.py+++ b/marimo/_smoke_tests/latex/latex.py@@ -2,7 +2,7 @@import marimo-__generated_with = "0.15.5"+__generated_with = "0.19.6"app = marimo.App()@@ -12,28 +12,373 @@ def _():return (mo,)[email protected](hide_code=True)+def _(mo):+ mo.md("""+ # LaTeX Smoke Test++ This notebook tests various LaTeX writing styles and configurations.+ """)+ return++[email protected](hide_code=True)+def _(mo):+ mo.md("""+ ## 1. Inline Math Delimiters++ Different ways to write inline math:+ """)+ return+++def _(mo):+ mo.md(r"""+ - Dollar signs: The equation $E = mc^2$ is famous.+ - Backslash parens: The equation \(E = mc^2\) also works.+ - With spaces: $ a + b = c $ (spaces around content).+ - Complex inline: $\frac{x^2}{y^2} + \sqrt{z}$ in a sentence.+ """)+ return++[email protected](hide_code=True)+def _(mo):+ mo.md("""+ ## 2. Display Math Delimiters++ Different ways to write display/block math:+ """)+ return+++def _(mo):+ mo.md(r"""+ Double dollar signs:++ $$+ f(x) = \int_{-\infty}^{\infty} e^{-x^2} dx = \sqrt{\pi}+ $$+ """)+ return+++def _(mo):+ mo.md(r"""+ Backslash brackets:++ \[+ \sum_{n=1}^{\infty} \frac{1}{n^2} = \frac{\pi^2}{6}+ \]+ """)+ return+++def _(mo):+ mo.md(r"""+ Inline display (no newlines): \[ x^2 + y^2 = z^2 \]+ """)+ return++[email protected](hide_code=True)+def _(mo):+ mo.md("""+ ## 3. LaTeX Environments+ """)+ return+++def _(mo):+ mo.md(r"""+ ### Align environment (multi-line equations):++ \begin{align}+ B' &= -\nabla \times E \\+ E' &= \nabla \times B - 4\pi j \\+ e^{\pi i} + 1 &= 0+ \end{align}+ """)+ return+++def _(mo):+ mo.md(r"""+ ### Equation environment:++ \begin{equation}+ \mathcal{L} = \int_\Omega \left( \frac{1}{2} |\nabla u|^2 - f u \right) dx+ \end{equation}+ """)+ return+++def _(mo):+ mo.md(r"""+ ### Matrix environments:++ Regular matrix: $\begin{matrix} a & b \\ c & d \end{matrix}$++ Parentheses: $\begin{pmatrix} 1 & 2 \\ 3 & 4 \end{pmatrix}$++ Brackets: $\begin{bmatrix} x \\ y \\ z \end{bmatrix}$++ Determinant: $\begin{vmatrix} a & b \\ c & d \end{vmatrix} = ad - bc$+ """)+ return+++def _(mo):+ mo.md(r"""+ ### Cases environment:++ $$+ |x| = \begin{cases}+ x & \text{if } x \geq 0 \\+ -x & \text{if } x < 0+ \end{cases}+ $$+ """)+ return++[email protected](hide_code=True)+def _(mo):+ mo.md("""+ ## 4. Greek Letters and Symbols+ """)+ return+++def _(mo):+ mo.md(r"""+ - Lowercase: $\alpha, \beta, \gamma, \delta, \epsilon, \zeta, \eta, \theta$+ - More: $\iota, \kappa, \lambda, \mu, \nu, \xi, \pi, \rho, \sigma, \tau$+ - And: $\upsilon, \phi, \chi, \psi, \omega$+ - Uppercase: $\Gamma, \Delta, \Theta, \Lambda, \Xi, \Pi, \Sigma, \Phi, \Psi, \Omega$+ - Operators: $\partial, \nabla, \infty, \forall, \exists, \emptyset$+ - Relations: $\leq, \geq, \neq, \approx, \equiv, \sim, \propto$+ - Arrows: $\leftarrow, \rightarrow, \leftrightarrow, \Rightarrow, \Leftrightarrow$+ """)+ return++[email protected](hide_code=True)+def _(mo):+ mo.md("""+ ## 5. Common Mathematical Expressions+ """)+ return+++def _(mo):+ mo.md(r"""+ ### Fractions and roots:++ $$\frac{a}{b}, \quad \frac{x+1}{x-1}, \quad \dfrac{\partial f}{\partial x}$$++ $$\sqrt{x}, \quad \sqrt[3]{x}, \quad \sqrt{x^2 + y^2}$$+ """)+ return+++def _(mo):+ mo.md(r"""+ ### Subscripts and superscripts:++ $$x_i, \quad x^2, \quad x_i^2, \quad x_{i,j}^{(n)}, \quad e^{i\pi}$$+ """)+ return++@app.celldef _(mo):- mo.md(- """- # Incrementing functions- Bug from [#704](https://github.com/marimo-team/marimo/discussions/704)- """- )+ mo.md(r"""+ ### Sums, products, integrals, limits:++ $$\sum_{i=1}^{n} x_i, \quad \prod_{i=1}^{n} x_i, \quad \int_a^b f(x)\,dx, \quad \lim_{x \to \infty} f(x)$$++ $$\iint_D f(x,y)\,dx\,dy, \quad \oint_C \vec{F} \cdot d\vec{r}$$+ """)return@app.celldef _(mo):- mo.md(- r"""- \begin{align}- B' &=-\nabla \times E,\\- E' &=\nabla \times B - 4\pi j\\- e^{\pi i} + 1 = 0- \end{align}- """- )+ mo.md(r"""+ ### Brackets and delimiters:++ $$\left( \frac{a}{b} \right), \quad \left[ \frac{a}{b} \right], \quad \left\{ \frac{a}{b} \right\}$$++ $$\left\langle \psi | \phi \right\rangle, \quad \left\| \vec{v} \right\|, \quad \left\lfloor x \right\rfloor, \quad \left\lceil x \right\rceil$$+ """)+ return++[email protected](hide_code=True)+def _(mo):+ mo.md("""+ ## 6. Chemistry (mhchem)++ Using the mhchem extension for chemical equations:+ """)+ return+++def _(mo):+ mo.md(r"""+ - Water: $\ce{H2O}$+ - Sulfuric acid: $\ce{H2SO4}$+ - Chemical reaction: $\ce{2H2 + O2 -> 2H2O}$+ - Equilibrium: $\ce{N2 + 3H2 <=> 2NH3}$+ - Isotopes: $\ce{^{14}C}$, $\ce{^{238}U}$+ """)+ return++[email protected](hide_code=True)+def _(mo):+ mo.md("""+ ## 7. Edge Cases+ """)+ return+++def _(mo):+ mo.md(r"""+ ### Math in lists:++ 1. First item: $a^2 + b^2 = c^2$+ 2. Second item: $\sin^2\theta + \cos^2\theta = 1$+ 3. Third item: $e^{i\theta} = \cos\theta + i\sin\theta$++ - Bullet with math: $\vec{F} = m\vec{a}$+ - Another: $\nabla \cdot \vec{E} = \frac{\rho}{\epsilon_0}$+ """)+ return+++def _(mo):+ mo.md(r"""+ ### Multiple inline math in one paragraph:++ The function $f(x) = x^2$ has derivative $f'(x) = 2x$ and second derivative $f''(x) = 2$.+ At $x = 0$, we have $f(0) = 0$, $f'(0) = 0$, and $f''(0) = 2 > 0$, so $x = 0$ is a local minimum.+ """)+ return+++def _(mo):+ mo.md(r"""+ ### Special characters that need escaping:++ - Percent: $100\%$ confidence+ - Ampersand in align: handled by environment+ - Backslash: $\backslash$+ - Tilde: $\tilde{x}$, $\widetilde{xyz}$+ - Hat: $\hat{x}$, $\widehat{xyz}$+ - Bar: $\bar{x}$, $\overline{xyz}$+ """)+ return++[email protected](hide_code=True)+def _(mo):+ mo.md("""+ ## 8. Real-World Examples+ """)+ return+++def _(mo):+ mo.md(r"""+ ### Euler's identity (the most beautiful equation):++ $$e^{i\pi} + 1 = 0$$+ """)+ return+++def _(mo):+ mo.md(r"""+ ### Quadratic formula:++ The solutions to $ax^2 + bx + c = 0$ are:++ $$x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$+ """)+ return+++def _(mo):+ mo.md(r"""+ ### Gaussian integral:++ $$\int_{-\infty}^{\infty} e^{-x^2} dx = \sqrt{\pi}$$+ """)+ return+++def _(mo):+ mo.md(r"""+ ### Maxwell's equations:++ \begin{align}+ \nabla \cdot \vec{E} &= \frac{\rho}{\epsilon_0} \\+ \nabla \cdot \vec{B} &= 0 \\+ \nabla \times \vec{E} &= -\frac{\partial \vec{B}}{\partial t} \\+ \nabla \times \vec{B} &= \mu_0 \vec{J} + \mu_0 \epsilon_0 \frac{\partial \vec{E}}{\partial t}+ \end{align}+ """)+ return+++def _(mo):+ mo.md(r"""+ ### Schrödinger equation:++ $$i\hbar\frac{\partial}{\partial t}\Psi(\vec{r},t) = \hat{H}\Psi(\vec{r},t) = \left[-\frac{\hbar^2}{2m}\nabla^2 + V(\vec{r},t)\right]\Psi(\vec{r},t)$$+ """)+ return+++def _(mo):+ mo.md(r"""+ ### Bayes' theorem:++ $$P(A|B) = \frac{P(B|A) \cdot P(A)}{P(B)}$$+ """)+ return+++def _(mo):+ mo.md(r"""+ ### Taylor series:++ $$f(x) = \sum_{n=0}^{\infty} \frac{f^{(n)}(a)}{n!}(x-a)^n = f(a) + f'(a)(x-a) + \frac{f''(a)}{2!}(x-a)^2 + \cdots$$+ """)returndiff --git a/tests/_convert/ipynb/test_from_ir.py b/tests/_convert/ipynb/test_from_ir.pyindex 8364d530a9..ef33bbd5c3 100644--- a/tests/_convert/ipynb/test_from_ir.py+++ b/tests/_convert/ipynb/test_from_ir.py@@ -11,11 +11,14 @@ from marimo._ast.load import load_appfrom marimo._convert.ipynb import convert_from_ir_to_ipynbfrom marimo._convert.ipynb.from_ir import (_clean_ansi_for_export,+ _convert_latex_delimiters_for_jupyter,_convert_marimo_output_to_ipynb,+ _convert_marimo_tex_to_latex,_is_marimo_component,_maybe_extract_dataurl,)from marimo._messaging.cell_output import CellChannel, CellOutput+from marimo._output.md import _mdfrom tests.mocks import snapshotterSELF_DIR = pathlib.Path(__file__).parent@@ -781,3 +784,305 @@ class TestCleanAnsiForExport:assert isinstance(pdf_output, bytes)assert len(pdf_output) > 0+++class TestConvertMarimoTexToLatex:+ """Test conversion of marimo-tex HTML elements to standard LaTeX.++ These tests use the actual _md() function which causes LaTeX to be converted to marimo-tex HTML elements.+ """++ @pytest.mark.parametrize(+ ("latex_input", "expected_output"),+ [+ # Inline math+ (r"$f(x) = e^x$", "$f(x) = e^x$"),+ (r"$x^2 + y^2$", "$x^2 + y^2$"),+ # Block math+ (r"$$f(x) = e^x$$", "$$f(x) = e^x$$"),+ # Fractions+ (r"$\frac{x^2}{2!}$", r"$\frac{x^2}{2!}$"),+ # Greek letters+ (r"$\alpha + \beta = \gamma$", r"$\alpha + \beta = \gamma$"),+ # Square root+ (r"$\sqrt{x}$", r"$\sqrt{x}$"),+ # Subscript and superscript+ (r"$x_i^2$", r"$x_i^2$"),+ # Summation+ (r"$\sum_{i=1}^{n} x_i$", r"$\sum_{i=1}^{n} x_i$"),+ # Integral+ (r"$\int_0^1 x dx$", r"$\int_0^1 x dx$"),+ # Limits+ (+ r"$\lim_{x \to 0} \frac{\sin x}{x}$",+ r"$\lim_{x \to 0} \frac{\sin x}{x}$",+ ),+ ],+ ids=[+ "inline_exponential",+ "inline_polynomial",+ "block_exponential",+ "fractions",+ "greek_letters",+ "square_root",+ "subscript_superscript",+ "summation",+ "integral",+ "limits",+ ],+ )+ def test_simple_latex_conversion(+ self, latex_input: str, expected_output: str+ ) -> None:+ """Test simple LaTeX expressions are converted correctly."""+ html = _md(latex_input).text+ result = _convert_marimo_tex_to_latex(html)+ assert expected_output in result+ assert "marimo-tex" not in result++ def test_block_math_multiline(self) -> None:+ """Test multiline block math conversion."""+ html = _md(+ r"""$$+f(x) = 1 + x+$$"""+ ).text+ result = _convert_marimo_tex_to_latex(html)+ assert "$$" in result+ assert "f(x) = 1 + x" in result+ assert "marimo-tex" not in result++ def test_mixed_content(self) -> None:+ """Test text with embedded inline math."""+ html = _md(r"The equation $E = mc^2$ is famous.").text+ result = _convert_marimo_tex_to_latex(html)+ assert "$E = mc^2$" in result+ assert "The equation" in result+ assert "is famous" in result+ assert "marimo-tex" not in result++ def test_multiple_inline_math(self) -> None:+ """Test multiple inline math expressions."""+ html = _md(r"$a$ and $b$ and $c$").text+ result = _convert_marimo_tex_to_latex(html)+ assert "$a$" in result+ assert "$b$" in result+ assert "$c$" in result+ assert "marimo-tex" not in result++ def test_complex_document(self) -> None:+ """Test conversion of a complex document with multiple math types."""+ html = _md(+ r"""The exponential function $f(x) = e^x$ can be represented as++$$+f(x) = 1 + x + \frac{x^2}{2!} + \frac{x^3}{3!} + \ldots+$$"""+ ).text+ result = _convert_marimo_tex_to_latex(html)+ assert "$f(x) = e^x$" in result+ assert "$$" in result+ assert r"\frac{x^2}{2!}" in result+ assert "marimo-tex" not in result++ def test_no_math_passes_through(self) -> None:+ """Test that text without math passes through unchanged."""+ html = _md("Just plain text here.").text+ result = _convert_marimo_tex_to_latex(html)+ assert "Just plain text here" in result++ def test_align_environment(self) -> None:+ """Test LaTeX align environment."""+ html = _md(+ r"""$$+\begin{align}+a &= b \\+c &= d+\end{align}+$$"""+ ).text+ result = _convert_marimo_tex_to_latex(html)+ assert "$$" in result+ assert r"\begin{align}" in result+ assert "marimo-tex" not in result++ def test_nested_md_with_inline_math(self) -> None:+ """Test nested mo.md() calls with inline math."""++ inner = _md(r"$x^2$")+ outer_html = _md(f"The value is {inner}").text++ result = _convert_marimo_tex_to_latex(outer_html)++ assert "$x^2$" in result+ assert "marimo-tex" not in result+ assert "||(" not in result++ def test_nested_md_with_block_math(self) -> None:+ """Test nested mo.md() calls with block math."""++ inner = _md(r"$$y^2$$")+ outer_html = _md(f"Result: {inner}").text++ result = _convert_marimo_tex_to_latex(outer_html)++ assert "y^2" in result+ assert "marimo-tex" not in result+ assert "||(" not in result+ assert "||[" not in result++ def test_fstring_md_with_variable(self) -> None:+ """Test mo.md() with f-string variable interpolation."""++ var = 42+ html = _md(f"Value is {var} and $x^2$").text++ result = _convert_marimo_tex_to_latex(html)++ assert "42" in result+ assert "$x^2$" in result+ assert "marimo-tex" not in result++ def test_complex_nested_md(self) -> None:+ """Test complex nested mo.md() with mixed content."""++ math_part = _md(r"$\frac{a}{b}$")+ text_with_math = _md(f"Equation: {math_part} is important").text++ result = _convert_marimo_tex_to_latex(text_with_math)++ assert r"\frac{a}{b}" in result+ assert "marimo-tex" not in result+++class TestConvertLatexDelimitersForJupyter:+ """Test conversion of LaTeX delimiters for Jupyter compatibility."""++ @pytest.mark.parametrize(+ ("markdown_input", "expected"),+ [+ # Display math: \[...\] → $$...$$+ (+ r"Display math: \[f(x) = e^x\]",+ "Display math: $$f(x) = e^x$$",+ ),+ # Display math with whitespace - gets stripped+ (+ r"\[ f(x) = e^x \]",+ "$$f(x) = e^x$$",+ ),+ # Multiline display math+ (+ r"""\[+ f(x) = 1 + x + \frac{x^2}{2!}+\]""",+ r"$$f(x) = 1 + x + \frac{x^2}{2!}$$",+ ),+ # Inline math: \(...\) → $...$+ (+ r"Inline math: \(f(x) = e^x\)",+ "Inline math: $f(x) = e^x$",+ ),+ # Inline math with whitespace - gets stripped+ (+ r"\( f(x) \)",+ "$f(x)$",+ ),+ # Mixed delimiters+ (+ r"Inline \(x^2\) and display \[y^2\]",+ "Inline $x^2$ and display $$y^2$$",+ ),+ # Already using $...$ passes through unchanged+ (+ "Already $x^2$ and $$y^2$$ work",+ "Already $x^2$ and $$y^2$$ work",+ ),+ # No LaTeX at all+ (+ "Plain text without math",+ "Plain text without math",+ ),+ # Complex expression+ (+ r"\(\sigma\sqrt{100}\)",+ r"$\sigma\sqrt{100}$",+ ),+ # Multiple inline+ (+ r"\(a\) and \(b\) and \(c\)",+ "$a$ and $b$ and $c$",+ ),+ ],+ ids=[+ "display_simple",+ "display_with_spaces",+ "display_multiline",+ "inline_simple",+ "inline_with_spaces",+ "mixed_delimiters",+ "already_dollar_signs",+ "no_latex",+ "complex_expression",+ "multiple_inline",+ ],+ )+ def test_convert_latex_delimiters(+ self, markdown_input: str, expected: str+ ) -> None:+ """Test LaTeX delimiter conversion."""+ result = _convert_latex_delimiters_for_jupyter(markdown_input)+ assert result == expected++ def test_convert_latex_in_code_blocks_limitation(self) -> None:+ r"""Test that documents a known limitation with code blocks.++ Note: The simple regex approach will convert \[...\] even inside+ code blocks. This is acceptable because:+ 1. Code blocks in markdown cells are rare+ 2. Having \[ and \] on different lines in code is also rare+ 3. A proper fix would require a full markdown parser+ """+ # This test verifies the conversion works for standalone math+ markdown = r"""Some text++\[x^2\]++More text"""++ result = _convert_latex_delimiters_for_jupyter(markdown)+ assert "$$x^2$$" in result+ assert r"\[" not in result++ def test_convert_latex_real_world_example(self) -> None:+ """Test a real-world markdown example."""+ markdown = r"""## Markdown / LaTeX++**bold** and _italic_++$\sigma\sqrt{100}$++$$+\sigma\sqrt{100}+$$++\[ \sigma\sqrt{100} \]++\( \sigma\sqrt{100} \)+"""+ expected = r"""## Markdown / LaTeX++**bold** and _italic_++$\sigma\sqrt{100}$++$$+\sigma\sqrt{100}+$$++$$\sigma\sqrt{100}$$++$\sigma\sqrt{100}$+"""+ result = _convert_latex_delimiters_for_jupyter(markdown)+ assert result == expected