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
improvement: mo.latex() to load macros (#3790)
Myles Scolnickba6a16227c6d
diff --git a/docs/api/markdown.md b/docs/api/markdown.mdindex c398643ca7..8fe41bbbe5 100644--- a/docs/api/markdown.md+++ b/docs/api/markdown.md@@ -6,6 +6,15 @@ elements.::: marimo.md+## Loading LaTeX macros++You can load LaTeX macros using `mo.latex(filename=...)`.++::: marimo.latex++!!! warning "Side effects"+ The `mo.latex()` function has side effects (registering the LaTeX macros) and should be used in the same cell as `import marimo`. Otherwise, the LaTeX macros may not be loaded before the cells that use them.+## IconsWe support rendering icons from [Iconify](https://icon-sets.iconify.design/).diff --git a/marimo/__init__.py b/marimo/__init__.pyindex 35d0d78ff9..fa4147a066 100644--- a/marimo/__init__.py+++ b/marimo/__init__.py@@ -48,6 +48,7 @@ __all__ = ["icon","iframe","image",+ "latex","lazy","left","lru_cache",@@ -93,7 +94,7 @@ from marimo._output.doc import docfrom marimo._output.formatting import as_html, iframe, plainfrom marimo._output.hypertext import Htmlfrom marimo._output.justify import center, left, right-from marimo._output.md import md+from marimo._output.md import latex, mdfrom marimo._output.show_code import show_codefrom marimo._plugins import uifrom marimo._plugins.stateless import mpl, statusdiff --git a/marimo/_output/md.py b/marimo/_output/md.pyindex 4d4f527c0d..c4842155b2 100644--- a/marimo/_output/md.py+++ b/marimo/_output/md.py@@ -4,7 +4,9 @@ from __future__ import annotationsfrom functools import cachefrom importlib.util import find_specfrom inspect import cleandoc+from pathlib import Pathfrom typing import Any, Literal, Optional, Union+from urllib.request import urlopenimport markdown # type: ignoreimport pymdownx.emoji # type: ignore@@ -13,6 +15,7 @@ from marimo._output.hypertext import Htmlfrom marimo._output.md_extensions.external_links import ExternalLinksExtensionfrom marimo._output.md_extensions.iconify import IconifyExtensionfrom marimo._output.rich_help import mddoc+from marimo._utils.url import is_urlextension_configs: dict[str, dict[str, Any]] = {"pymdownx.arithmatex": {@@ -164,7 +167,7 @@ def md(text: str) -> Html:using f-strings. Html objects and UI elements can be directly interpolated.For example:- ```python3+ ```pythontext_input = mo.ui.text()md(f"Enter some text: {text_input}")```@@ -172,7 +175,7 @@ def md(text: str) -> Html:For other objects, like plots, use marimo's `as_html` method to embedthem in markdown:- ```python3+ ```pythonimport matplotlib.pyplot as pltplt.plot([1, 2])@@ -186,7 +189,7 @@ def md(text: str) -> Html:display math or square brackets for display math. (Use raw strings,prefixed with an "r", to use single backslashes.) For example:- ```python3+ ```pythonmo.md(r'''The exponential function $f(x) = e^x$ can be represented as@@ -215,3 +218,45 @@ def md(text: str) -> Html:- An `Html` object."""return _md(text)+++def latex(*, filename: Union[str, Path]) -> None:+ """Load LaTeX from a file or URL.++ ```python+ import marimo as mo++ mo.latex(filename="macros.tex")+ ```++ or++ ```python+ import marimo as mo++ mo.latex(filename="https://example.com/macros.tex")+ ```++ **Args**:+ - `filename`: Path to a LaTeX file++ **Returns**:+ - An `Html` object+ """++ 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()+ else:+ raise ValueError(f"Invalid filename: {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$$"))+ returndiff --git a/marimo/_smoke_tests/latex/global_defs.py b/marimo/_smoke_tests/latex/global_defs.pyindex a56756ee32..84743cd993 100644--- a/marimo/_smoke_tests/latex/global_defs.py+++ b/marimo/_smoke_tests/latex/global_defs.py@@ -1,6 +1,6 @@import marimo-__generated_with = "0.11.2"+__generated_with = "0.11.3"app = marimo.App(width="medium")@@ -9,7 +9,7 @@ def _():import marimo as mo# Register globals- mo.md(f"$$\n{(mo.notebook_dir() / 'macros.tex').read_text().strip()}\n$$")+ mo.latex(filename=mo.notebook_dir() / "macros.tex")return (mo,)diff --git a/tests/_output/test_md.py b/tests/_output/test_md.pyindex 72c5d2293a..a0a7e6aabb 100644--- a/tests/_output/test_md.py+++ b/tests/_output/test_md.py@@ -1,6 +1,12 @@from __future__ import annotations-from marimo._output.md import _md+from typing import TYPE_CHECKING+from unittest.mock import MagicMock, patch++from marimo._output.md import _md, latex++if TYPE_CHECKING:+ from pathlib import Pathdef test_md() -> None:@@ -31,12 +37,34 @@ def test_md_code_blocks() -> None:def test_md_latex() -> None:- # Test LaTeX conversion- latex_input = "Here is an equation: ||(E=mc^2||)"- expected_output = (- '<span class="paragraph">Here is an equation: ||(E=mc^2||)</span>' # noqa: E501+ # Test inline LaTeX+ inline_latex = "Here is an inline equation $||(E=mc^2||)$"+ expected_inline = '<span class="paragraph">Here is an inline equation <marimo-tex class="arithmatex">||(||(E=mc^2||)||)</marimo-tex></span>'+ assert (+ _md(inline_latex, apply_markdown_class=False).text == expected_inline+ )++ # Test display LaTeX+ display_latex = "Here is a display equation:\n\n||[\nE = mc^2\n||]"+ expected_display = '<span class="paragraph">Here is a display equation:</span>\n<span class="paragraph">||[\nE = mc^2\n||]</span>'+ assert (+ _md(display_latex, apply_markdown_class=False).text == expected_display+ )++ # Test multiple LaTeX expressions+ multiple_latex = (+ "Equation 1: ||(a^2 + b^2 = c^2||) and equation 2: ||(E=mc^2||)"+ )+ expected_multiple = '<span class="paragraph">Equation 1: ||(a^2 + b^2 = c^2||) and equation 2: ||(E=mc^2||)</span>'+ assert (+ _md(multiple_latex, apply_markdown_class=False).text+ == expected_multiple)- assert _md(latex_input, apply_markdown_class=False).text == expected_output++ # Test LaTeX with markdown formatting+ mixed_latex = "**Bold** ||(x^2||) and _italic_ ||[y = mx + b||]"+ expected_mixed = '<span class="paragraph"><strong>Bold</strong> ||(x^2||) and <em>italic</em> ||[y = mx + b||]</span>'+ assert _md(mixed_latex, apply_markdown_class=False).text == expected_mixeddef test_md_links() -> None:@@ -91,3 +119,28 @@ def test_md_repr_markdown():input_text = "This is **bold** and this is _italic_."md = _md(input_text)assert md._repr_markdown_() == input_text+++@patch("marimo._runtime.output")+def test_latex_via_path(output: MagicMock, tmp_path: Path) -> None:+ filename = tmp_path / "macros.tex"+ filename.write_text("\\newcommand{\\\foo}{bar}")+ latex(filename=filename)+ assert (+ output.append.call_args[0][0].text+ == '<span class="markdown prose dark:prose-invert"><marimo-tex class="arithmatex">||[\n\\newcommand{\\\x0coo}{bar}\n||]</marimo-tex></span>'+ )+++@patch("marimo._runtime.output")+@patch("marimo._output.md.urlopen")+def test_latex_via_url(mock_urlopen: MagicMock, output: MagicMock) -> None:+ mock_response = MagicMock()+ mock_response.read.return_value = b"\\newcommand{\\\foo}{bar}"+ mock_urlopen.return_value.__enter__.return_value = mock_response++ latex(filename="https://example.com/macros.tex")+ assert (+ output.append.call_args[0][0].text+ == '<span class="markdown prose dark:prose-invert"><marimo-tex class="arithmatex">||[\n\\newcommand{\\\foo}{bar}\n||]</marimo-tex></span>'+ )