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.

fix: display math rendering (#8348)

Akshay Agrawala9ebe714ed6f
diff --git a/marimo/_output/md.py b/marimo/_output/md.py
index 253ebc4719..8c47acfb76 100644
--- a/marimo/_output/md.py
+++ b/marimo/_output/md.py
@@ -18,6 +18,7 @@ from marimo._output.hypertext import Html, is_non_interactive
from marimo._output.md_extensions.breakless_lists import (
BreaklessListsExtension,
)
+from marimo._output.md_extensions.display_math import DisplayMathExtension
from marimo._output.md_extensions.external_links import ExternalLinksExtension
from marimo._output.md_extensions.flexible_indent import (
FlexibleIndentExtension,
@@ -175,6 +176,7 @@ def _get_extensions() -> list[Union[str, markdown.Extension]]:
"tables",
# LaTeX
"pymdownx.arithmatex",
+ DisplayMathExtension(),
# Subscripts and strikethrough
"pymdownx.tilde",
# Superscripts and insert
diff --git a/marimo/_output/md_extensions/display_math.py b/marimo/_output/md_extensions/display_math.py
new file mode 100644
index 0000000000..97f2ff02c6
--- /dev/null
+++ b/marimo/_output/md_extensions/display_math.py
@@ -0,0 +1,88 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+import re
+
+from markdown import Extension, Markdown, preprocessors # type: ignore
+
+
+class DisplayMathPreprocessor(preprocessors.Preprocessor): # type: ignore[misc]
+ """
+ Ensures $$...$$ display math blocks are surrounded by blank lines.
+
+ The pymdownx.arithmatex block processor requires $$...$$ to be in its
+ own markdown "block" (between blank lines) to recognize it as display
+ math. Without blank lines, it either produces nested tags with inline
+ delimiters or fails entirely.
+
+ This preprocessor inserts blank lines around $$...$$ blocks so that
+ arithmatex always processes them as display math.
+ """
+
+ # Single-line display math: $$...$$ on its own line
+ SINGLE_LINE_PATTERN = re.compile(r"^\s*\$\$(.+)\$\$\s*$")
+
+ # Opening or closing $$ on its own line
+ DOLLAR_DOLLAR_PATTERN = re.compile(r"^\s*\$\$\s*$")
+
+ def __init__(self, md: Markdown) -> None:
+ super().__init__(md)
+
+ def run(self, lines: list[str]) -> list[str]:
+ # Fast path: skip processing if no $$ appears anywhere
+ if not any("$$" in line for line in lines):
+ return lines
+
+ result: list[str] = []
+ i = 0
+ in_multiline = False
+
+ while i < len(lines):
+ line = lines[i]
+
+ if in_multiline:
+ # Looking for closing $$
+ if self.DOLLAR_DOLLAR_PATTERN.match(line):
+ result.append(line)
+ # Add blank line after closing $$ if next line is non-empty
+ if i + 1 < len(lines) and lines[i + 1].strip() != "":
+ result.append("")
+ in_multiline = False
+ else:
+ result.append(line)
+ elif self.SINGLE_LINE_PATTERN.match(line):
+ # Single-line $$...$$ — add blank lines around it
+ if result and result[-1].strip() != "":
+ result.append("")
+ result.append(line)
+ if i + 1 < len(lines) and lines[i + 1].strip() != "":
+ result.append("")
+ elif self.DOLLAR_DOLLAR_PATTERN.match(line):
+ # Opening $$ of a multi-line block
+ if result and result[-1].strip() != "":
+ result.append("")
+ result.append(line)
+ in_multiline = True
+ else:
+ result.append(line)
+
+ i += 1
+
+ return result
+
+
+class DisplayMathExtension(Extension): # type: ignore[misc]
+ """
+ Extension to ensure $$...$$ display math renders correctly
+ without requiring surrounding blank lines.
+ """
+
+ def extendMarkdown(self, md: Markdown) -> None:
+ md.preprocessors.register(
+ DisplayMathPreprocessor(md),
+ "display_math_preproc",
+ # Priority 24: runs AFTER fenced_code_block/superfences (25)
+ # which stash code blocks as tokens, so we never modify
+ # $$ inside code fences.
+ 24,
+ )
diff --git a/marimo/_smoke_tests/markdown/latex_display_math.py b/marimo/_smoke_tests/markdown/latex_display_math.py
new file mode 100644
index 0000000000..a3152d4f94
--- /dev/null
+++ b/marimo/_smoke_tests/markdown/latex_display_math.py
@@ -0,0 +1,43 @@
+import marimo
+
+__generated_with = "0.19.10"
+app = marimo.App()
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md(r"""
+ hello $$f(x) = y$$ world
+ """)
+ return
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md(r"""
+ hello
+ $$f(x) = y$$
+ world
+ """)
+ return
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md(r"""
+ hello $$this is not latex
+
+ $$ this is still not latex
+ """)
+ return
+
+
+def _():
+ import marimo as mo
+
+ return (mo,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_output/test_md.py b/tests/_output/test_md.py
index 4be66a82a7..c2317551ad 100644
--- a/tests/_output/test_md.py
+++ b/tests/_output/test_md.py
@@ -647,3 +647,62 @@ And more text"""
# Test that the text before and after is preserved
assert "This is some text" in result
assert "And more text" in result
+
+
+def test_md_display_math_without_blank_lines() -> None:
+ # Single-line $$...$$ without blank lines should render as display math
+ result = _md("Hello\n$$f(x)$$\nworld", apply_markdown_class=False).text
+ assert "||[" in result # block delimiters
+ assert "||(" not in result # NOT inline delimiters
+ assert "marimo-tex" in result
+
+ # Same with blank lines (regression check) — should produce same output
+ result_with_blanks = _md(
+ "Hello\n\n$$f(x)$$\n\nworld", apply_markdown_class=False
+ ).text
+ assert result == result_with_blanks
+
+ # Multi-line $$...$$ without blank lines
+ result_multi = _md(
+ "Hello\n$$\nf(x)\n$$\nworld", apply_markdown_class=False
+ ).text
+ assert "||[" in result_multi
+ assert "||(" not in result_multi
+ assert "marimo-tex" in result_multi
+
+ # Multiple $$ blocks without blank lines
+ result_multiple = _md("$$a$$\n$$b$$", apply_markdown_class=False).text
+ assert result_multiple.count("||[") == 2
+ assert "||(" not in result_multiple
+
+ # $$ at start of text
+ result_start = _md("$$f(x)$$\nworld", apply_markdown_class=False).text
+ assert "||[" in result_start
+ assert "||(" not in result_start
+
+ # $$ at end of text
+ result_end = _md("Hello\n$$f(x)$$", apply_markdown_class=False).text
+ assert "||[" in result_end
+ assert "||(" not in result_end
+
+ # Inline $...$ should NOT be affected
+ result_inline = _md("Hello $f(x)$ world", apply_markdown_class=False).text
+ assert "||(" in result_inline # inline delimiters
+ assert "||[" not in result_inline # NOT block delimiters
+
+ # $$ inside code blocks should NOT be affected
+ result_code = _md(
+ "```\na = 1\n$$ not math\n```", apply_markdown_class=False
+ ).text
+ assert "marimo-tex" not in result_code
+ assert "$$ not math" in result_code
+
+
+def test_md_display_math_format_preserved() -> None:
+ # __format__ should return original markdown text
+ text = "Hello\n$$f(x)$$\nworld"
+ md_obj = _md(text)
+ assert f"{md_obj}" == text
+
+ # _repr_markdown_ should return original markdown text
+ assert md_obj._repr_markdown_() == text