Skip to content

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.

improvement: katex global/macros (#3785)

Myles Scolnick582f25f46b70
diff --git a/frontend/src/plugins/layout/TexPlugin.tsx b/frontend/src/plugins/layout/TexPlugin.tsx
index d09ad5ed75..cb43e5e25e 100644
--- a/frontend/src/plugins/layout/TexPlugin.tsx
+++ b/frontend/src/plugins/layout/TexPlugin.tsx
@@ -35,23 +35,34 @@ const importMhChem = once(async () => {
await import("katex/contrib/mhchem");
});
+// Required, even if empty. (see https://github.com/KaTeX/KaTeX/issues/2513)
+const macros = {};
+
async function renderLatex(mount: HTMLElement, tex: string): Promise<void> {
const [katex] = await Promise.all([importKatex(), importMhChem()]);
if (tex.startsWith("||(||(") && tex.endsWith("||)||)")) {
// when $$...$$ is used without newlines before/after the $$.
katex.render(tex.slice(6, -6), mount, {
displayMode: true,
+ globalGroup: true,
throwOnError: false,
+ macros: macros,
});
} else if (tex.startsWith("||(") && tex.endsWith("||)")) {
+ // Inline math, via $...$
katex.render(tex.slice(3, -3), mount, {
displayMode: false,
+ globalGroup: true,
throwOnError: false,
+ macros: macros,
});
} else if (tex.startsWith("||[") && tex.endsWith("||]")) {
+ // Display math, via $$...$$
katex.render(tex.slice(3, -3), mount, {
displayMode: true,
+ globalGroup: true,
throwOnError: false,
+ macros: macros,
});
}
}
diff --git a/marimo/_smoke_tests/latex/global_defs.py b/marimo/_smoke_tests/latex/global_defs.py
new file mode 100644
index 0000000000..a56756ee32
--- /dev/null
+++ b/marimo/_smoke_tests/latex/global_defs.py
@@ -0,0 +1,35 @@
+import marimo
+
+__generated_with = "0.11.2"
+app = marimo.App(width="medium")
+
+
+def _():
+ import marimo as mo
+
+ # Register globals
+ mo.md(f"$$\n{(mo.notebook_dir() / 'macros.tex').read_text().strip()}\n$$")
+ return (mo,)
+
+
+def _(mo):
+ mo.md(
+ r"""
+ $$
+ c = \pm\root{a^2 + b^2}\in\RR
+ $$
+ """
+ )
+ return
+
+
+def _(mo):
+ mo.md(r"""$c = \pm\root{a^2 + b^2}\in\RR$""")
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_smoke_tests/latex.py b/marimo/_smoke_tests/latex/latex.py
similarity index 100%
rename from marimo/_smoke_tests/latex.py
rename to marimo/_smoke_tests/latex/latex.py
diff --git a/marimo/_smoke_tests/latex/macros.tex b/marimo/_smoke_tests/latex/macros.tex
new file mode 100644
index 0000000000..b081366e97
--- /dev/null
+++ b/marimo/_smoke_tests/latex/macros.tex
@@ -0,0 +1,5 @@
+\let\root=\sqrt
+\newcommand{\rot}[1]{{\rm curl }\left( #1 \right)}
+\newcommand{\Grad}[1]{{\rm Grad}\left( #1 \right)}
+\newcommand{\Div}[1]{{\rm Div }\left( #1 \right)}
+\newcommand{\invp}{{\it Inv}^{\small +}}