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
feat(markdown): allow mo.latex to accept text directly (#10723)
Kushaan koul160274c466f2
diff --git a/docs/api/markdown.md b/docs/api/markdown.mdindex 8fe41bbbe5..74b70f2852 100644--- a/docs/api/markdown.md+++ b/docs/api/markdown.md@@ -8,7 +8,7 @@ elements.## Loading LaTeX macros-You can load LaTeX macros using `mo.latex(filename=...)`.+You can load LaTeX macros directly using `mo.latex(r"...")` or from a file/URL using `mo.latex(filename=...)`.::: marimo.latexdiff --git a/marimo/_output/md.py b/marimo/_output/md.pyindex e800c109db..7c2bf047f3 100644--- a/marimo/_output/md.py+++ b/marimo/_output/md.py@@ -383,43 +383,65 @@ def md(text: str) -> Html:return _md(text)-def latex(*, filename: str | Path) -> None:- """Load LaTeX from a file or URL.+@mddoc+def latex(+ text: str | None = None,+ *,+ filename: str | Path | None = None,+) -> None:+ r"""Load LaTeX macros from a string, file, or URL.- ```python- import marimo as mo+ Loads LaTeX macros into the notebook environment so they can be+ referenced across cells in math equations.- mo.latex(filename="macros.tex")- ```+ Examples:+ Load LaTeX directly from text:+ ```python+ import marimo as mo- or+ mo.latex(r"\newcommand{\R}{\mathbb{R}}")+ ```- ```python- import marimo as mo+ or from a file:+ ```python+ import marimo as mo- mo.latex(filename="https://example.com/macros.tex")- ```+ mo.latex(filename="macros.tex")+ ```++ or from a URL:+ ```python+ import marimo as mo++ mo.latex(filename="https://example.com/macros.tex")+ ```Args:- filename: Path to a LaTeX file+ text: LaTeX string to load directly+ filename: Path or URL to a LaTeX file- Returns:- An `Html` object+ Raises:+ ValueError: If neither or both `text` and `filename` are provided,+ or if `filename` cannot be found."""-- if isinstance(filename, Path):- text = filename.read_text()- elif is_url(filename):- with urlopen(filename) as response:- text = response.read().decode("utf-8")- elif (file := Path(filename)).exists():- text = file.read_text(encoding="utf-8")+ if text is not None and filename is not None:+ raise ValueError("Cannot provide both 'text' and 'filename'.")+ elif text is not None:+ latex_text = text+ elif filename is not None:+ if isinstance(filename, str) and is_url(filename):+ with urlopen(filename) as response:+ latex_text = response.read().decode("utf-8")+ elif (file := Path(filename)).exists():+ latex_text = file.read_text(encoding="utf-8")+ else:+ raise ValueError(f"Invalid filename: {filename}")else:- raise ValueError(f"Invalid filename: {filename}")+ raise ValueError("Must provide either 'text' or 'filename'.")from marimo._runtime import output# Append the LaTeX to the output, in case this# is not the last expression of the cell- output.append(_md(f"$$\n{text.strip()}\n$$"))+ output.append(_md(f"$$\n{latex_text.strip()}\n$$"))returndiff --git a/tests/_output/test_md.py b/tests/_output/test_md.pyindex f464a0b0ff..38f79f2033 100644--- a/tests/_output/test_md.py+++ b/tests/_output/test_md.py@@ -1,7 +1,7 @@from __future__ import annotationsimport re-from typing import TYPE_CHECKING+from pathlib import Pathfrom unittest.mock import MagicMock, patchimport pytest@@ -10,9 +10,6 @@ from inline_snapshot import snapshotfrom marimo._output.md import _md, latexfrom tests.mocks import normalize_html_entities-if TYPE_CHECKING:- from pathlib import Path-def test_md() -> None:# Test basic markdown conversion@@ -669,6 +666,57 @@ def test_latex_via_url(mock_urlopen: MagicMock, output: MagicMock) -> None:)+@patch("marimo._runtime.output")+def test_latex_via_text(output: MagicMock) -> None:+ latex("\\newcommand{\\\\foo}{bar}")+ assert (+ output.append.call_args[0][0].text+ == '<span class="markdown prose dark:prose-invert contents"><marimo-tex class="arithmatex">||[\n\\newcommand{\\\\foo}{bar}\n||]</marimo-tex></span>'+ )+++@patch("marimo._runtime.output")+def test_latex_via_text_keyword(output: MagicMock) -> None:+ latex(text="\\newcommand{\\\\foo}{bar}")+ assert (+ output.append.call_args[0][0].text+ == '<span class="markdown prose dark:prose-invert contents"><marimo-tex class="arithmatex">||[\n\\newcommand{\\\\foo}{bar}\n||]</marimo-tex></span>'+ )+++def test_latex_both_args_raises(tmp_path: Path) -> None:+ filename = tmp_path / "macros.tex"+ filename.write_text("\\newcommand{\\\\foo}{bar}")+ with pytest.raises(+ ValueError, match=r"Cannot provide both 'text' and 'filename'\."+ ):+ latex("\\newcommand{\\\\foo}{bar}", filename=filename)++ with pytest.raises(+ ValueError, match=r"Cannot provide both 'text' and 'filename'\."+ ):+ latex(text="\\newcommand{\\\\foo}{bar}", filename=filename)+++def test_latex_neither_arg_raises() -> None:+ with pytest.raises(+ ValueError, match=r"Must provide either 'text' or 'filename'\."+ ):+ latex()+++def test_latex_invalid_filename_raises() -> None:+ with pytest.raises(+ ValueError, match=r"Invalid filename: nonexistent\.tex"+ ):+ latex(filename="nonexistent.tex")++ with pytest.raises(+ ValueError, match=r"Invalid filename: nonexistent\.tex"+ ):+ latex(filename=Path("nonexistent.tex"))++@patch("marimo._output.md.is_pyodide")def test_b64_extension_not_in_non_wasm(mock_is_pyodide: MagicMock) -> None:# Test that b64 extension is NOT included in non-WASM mode