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(markdown): render display math nested in list item continuations (#10785)

Sergey Slizovskiy5aa823f95cfa
diff --git a/marimo/_output/md_extensions/display_math.py b/marimo/_output/md_extensions/display_math.py
index 835c5fd12d..d7ef29c1ba 100644
--- a/marimo/_output/md_extensions/display_math.py
+++ b/marimo/_output/md_extensions/display_math.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import re
from markdown import Extension, Markdown, preprocessors # type: ignore
+from markdown.blockprocessors import HRProcessor # type: ignore
class DisplayMathPreprocessor(preprocessors.Preprocessor): # type: ignore[misc]
@@ -25,6 +26,9 @@ class DisplayMathPreprocessor(preprocessors.Preprocessor): # type: ignore[misc]
# Opening or closing $$ on its own line
DOLLAR_DOLLAR_PATTERN = re.compile(r"^\s*\$\$\s*$")
+ # Python-Markdown accepts "1." markers, but not "1)".
+ LIST_MARKER_PATTERN = re.compile(r"^\s*([0-9]+\.|[-*+])\s+")
+
# Matches inline RST math role: :math:`...`
INLINE_MATH_ROLE_PATTERN = re.compile(r"(?<!`):math:`([^`\n]+)`")
# Matches role variant with embedded HTML code tag: :math:<code>...</code>
@@ -100,6 +104,8 @@ class DisplayMathPreprocessor(preprocessors.Preprocessor): # type: ignore[misc]
return "".join(converted_segments)
def _normalize_display_math_spacing(self, lines: list[str]) -> list[str]:
+ lines = self._reindent_list_continuations(lines)
+
result: list[str] = []
i = 0
in_multiline = False
@@ -137,6 +143,87 @@ class DisplayMathPreprocessor(preprocessors.Preprocessor): # type: ignore[misc]
return result
+ def _reindent_list_continuations(self, lines: list[str]) -> list[str]:
+ """Keep list continuations inside the item after adding blank lines.
+
+ Python-Markdown requires loose list content to use `tab_length`
+ indentation, even when the list marker is narrower.
+ """
+ result = list(lines)
+ n = len(result)
+ i = 0
+ while i < n:
+ line = result[i]
+ if not line.strip() or self._count_indent(line) == 0:
+ i += 1
+ continue
+
+ start = i
+ in_dollar_block = False
+ while i < n:
+ current = result[i]
+ if not current.strip():
+ # Keep blank lines inside a math block in the same run.
+ if not in_dollar_block:
+ break
+ elif self._count_indent(current) == 0:
+ break
+ elif self.DOLLAR_DOLLAR_PATTERN.match(current):
+ in_dollar_block = not in_dollar_block
+ i += 1
+ end = i
+
+ preceding = result[start - 1] if start > 0 else ""
+ if self.LIST_MARKER_PATTERN.match(
+ preceding
+ ) and not HRProcessor.SEARCH_RE.fullmatch(preceding):
+ self._pad_math_segments(result, start, end, self.md.tab_length)
+
+ return result
+
+ def _pad_math_segments(
+ self, result: list[str], start: int, end: int, tab_length: int
+ ) -> None:
+ """Pad each block separately so deeper math keeps its indentation."""
+ j = start
+ while j < end:
+ seg_start = j
+ if self.SINGLE_LINE_PATTERN.match(result[j]):
+ j += 1
+ elif self.DOLLAR_DOLLAR_PATTERN.match(result[j]):
+ j += 1
+ while j < end and not self.DOLLAR_DOLLAR_PATTERN.match(
+ result[j]
+ ):
+ j += 1
+ if j < end:
+ j += 1 # include the closing "$$" line
+ else:
+ while j < end and not (
+ self.SINGLE_LINE_PATTERN.match(result[j])
+ or self.DOLLAR_DOLLAR_PATTERN.match(result[j])
+ ):
+ j += 1
+ if seg_start == start:
+ # Leading prose stays in the list marker's paragraph.
+ continue
+
+ segment = result[seg_start:j]
+ min_indent = min(
+ (
+ self._count_indent(line_)
+ for line_ in segment
+ if line_.strip()
+ ),
+ default=0,
+ )
+ if 0 < min_indent < tab_length:
+ padding = " " * (tab_length - min_indent)
+ result[seg_start:j] = [
+ padding + line_ if line_.strip() else line_
+ for line_ in segment
+ ]
+
def _split_by_inline_code(self, text: str) -> list[tuple[str, bool]]:
"""Split text into inline-code and non-code segments.
diff --git a/marimo/_smoke_tests/display_math_lists.py b/marimo/_smoke_tests/display_math_lists.py
new file mode 100644
index 0000000000..9dbf199c77
--- /dev/null
+++ b/marimo/_smoke_tests/display_math_lists.py
@@ -0,0 +1,99 @@
+# Copyright 2026 Marimo. All rights reserved.
+
+import marimo
+
+__generated_with = "0.24.0"
+app = marimo.App()
+
+
+def _():
+ import marimo as mo
+ return (mo,)
+
+
+def _(mo):
+ mo.md("""
+ # Display math in lists
+
+ Check that equations and following text stay inside their list items.
+ The numbered list should have three items.
+ """)
+ return
+
+
+def _(mo):
+ mo.md(r"""
+ 1. First item.
+ 2. Inline $a^2$ and display math:
+ $$
+ E = mc^2
+ $$
+ This text belongs to item two.
+ 3. Third item.
+ """)
+ return
+
+
+def _(mo):
+ mo.vstack([
+ mo.md(
+ f"{_marker} First item.\n"
+ f"{_marker} Display math:\n"
+ " $$x^2 + y^2 = z^2$$\n"
+ " This text belongs to the second bullet.\n"
+ f"{_marker} Third item."
+ )
+ for _marker in ["-", "*", "+"]
+ ])
+ return
+
+
+def _(mo):
+ mo.md("""
+ ## Horizontal rules
+
+ Each separator below should be followed by ordinary text, with no code
+ block. Display math at this indentation still has a pre-existing rendering
+ issue; this check only verifies that the content does not become code.
+ """)
+ return
+
+
+def _(mo):
+ mo.vstack([
+ mo.md(
+ f"Separator `{_rule}`:\n\n"
+ f"{_rule}\n"
+ " $$x$$\n"
+ " This should remain prose.\n\n"
+ "End of example."
+ )
+ for _rule in ["- - -", "* * *", "- --", "* **"]
+ ])
+ return
+
+
+def _(mo):
+ mo.md("""
+ ## Mixed indentation
+
+ The equation and following text should stay inside the first item.
+
+ - First item
+ continued here:
+ $$x$$
+ Text after the equation.
+ - Second item.
+ """)
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_output/test_md.py b/tests/_output/test_md.py
index 38f79f2033..2794d0bf18 100644
--- a/tests/_output/test_md.py
+++ b/tests/_output/test_md.py
@@ -928,6 +928,149 @@ def test_md_math_normalization_skips_fenced_and_inline_code() -> None:
assert "||(y||)" in result
+def test_md_display_math_inside_list_item() -> None:
+ text = (
+ "1. Item one.\n"
+ "2. Item two with inline $a^2$ math, then a display block:\n"
+ " $$\n"
+ " E = mc^2\n"
+ " $$\n"
+ " and continuing text.\n"
+ "3. Item three.\n"
+ )
+ result = _md(text, apply_markdown_class=False).text
+
+ assert result == snapshot(
+ "<ol>\n"
+ "<li>Item one.</li>\n"
+ "<li>\n"
+ '<span class="paragraph">Item two with inline <marimo-tex class="arithmatex">||(a^2||)</marimo-tex> math, then a display block:</span>\n'
+ '<marimo-tex class="arithmatex">||[\n'
+ "E = mc^2\n"
+ '||]</marimo-tex><span class="paragraph">and continuing text.</span>\n'
+ "</li>\n"
+ "<li>Item three.</li>\n"
+ "</ol>"
+ )
+
+
+def test_md_display_math_paren_marker_not_treated_as_list() -> None:
+ text = (
+ "Some intro text.\n"
+ "\n"
+ "1) Not actually a list item, just prose ending in a number.\n"
+ " $$\n"
+ " E = mc^2\n"
+ " $$\n"
+ " trailing text.\n"
+ )
+ result = _md(text, apply_markdown_class=False).text
+ assert "<pre>" not in result
+ assert "codehilite" not in result
+ assert "highlight" not in result
+
+
+def test_md_display_math_list_item_with_blank_line_in_block() -> None:
+ text = (
+ "1. Item one.\n"
+ "2. Item two with a multi-part display block:\n"
+ " $$\n"
+ " a = 1\n"
+ "\n"
+ " b = 2\n"
+ " $$\n"
+ " trailing text.\n"
+ "3. Item three.\n"
+ )
+ result = _md(text, apply_markdown_class=False).text
+ assert result.count("<ol") == 1
+ assert 'start="3"' not in result
+ assert "Item three" in result
+ assert "trailing text." in result
+
+
+def test_md_display_math_deeper_indent_than_continuation() -> None:
+ text = "- Item\n continuation\n $$x$$\n- Next\n"
+ result = _md(text, apply_markdown_class=False).text
+ assert result.count("<ul") == 1
+ assert "||[x||]" in result
+ assert "$$" not in result
+ assert "Next" in result
+
+
[email protected](("first_indent", "second_indent"), [(2, 4), (4, 2)])
[email protected]("multiline", [False, True])
+def test_md_display_math_multiple_list_blocks(
+ first_indent: int, second_indent: int, multiline: bool
+) -> None:
+ first_padding = " " * first_indent
+ second_padding = " " * second_indent
+ if multiline:
+ first_math = f"{first_padding}$$\n{first_padding}x\n{first_padding}$$"
+ second_math = (
+ f"{second_padding}$$\n{second_padding}y\n{second_padding}$$"
+ )
+ rendered_x = "\nx\n"
+ rendered_y = "\ny\n"
+ else:
+ first_math = f"{first_padding}$$x$$"
+ second_math = f"{second_padding}$$y$$"
+ rendered_x = "x"
+ rendered_y = "y"
+ text = (
+ f"- Item\n continuation\n{first_math}\n"
+ f" after\n{second_math}\n end\n- Next"
+ )
+ assert _md(text, apply_markdown_class=False).text == (
+ "<ul>\n<li>\n"
+ '<span class="paragraph">Item\n continuation</span>\n'
+ f'<marimo-tex class="arithmatex">||[{rendered_x}||]</marimo-tex>'
+ '<span class="paragraph">after</span>\n'
+ f'<marimo-tex class="arithmatex">||[{rendered_y}||]</marimo-tex>'
+ '<span class="paragraph">end</span>\n'
+ "</li>\n<li>Next</li>\n</ul>"
+ )
+
+
+def test_md_list_continuation_without_math() -> None:
+ text = "- Item\n continuation\n- Next\n\n$$x$$"
+ assert _md(text, apply_markdown_class=False).text == snapshot(
+ "<ul>\n<li>Item\n continuation</li>\n<li>Next</li>\n</ul>\n"
+ '<marimo-tex class="arithmatex">||[x||]</marimo-tex>'
+ )
+
+
[email protected]("marker", ["-", "*", "+"])
+def test_md_display_math_bullet_markers(marker: str) -> None:
+ text = (
+ f"{marker} Item one, no math here.\n"
+ f"{marker} Item two with a display block:\n"
+ " $$\n"
+ " E = mc^2\n"
+ " $$\n"
+ " and continuing text.\n"
+ f"{marker} Item three, plain.\n"
+ )
+ result = _md(text, apply_markdown_class=False).text
+ assert result.count("<ul") == 1
+ assert "||[" in result
+ assert "$$" not in result
+ assert "Item three, plain." in result
+ assert "and continuing text." in result
+
+
[email protected]("rule", ["- - -", "* * *", "- --", "* **"])
+def test_md_display_math_after_horizontal_rule(rule: str) -> None:
+ text = f"Intro\n\n{rule}\n $$x$$\n This should remain prose.\n\nEnd"
+ assert _md(text, apply_markdown_class=False).text == snapshot(
+ '<span class="paragraph">Intro</span>\n'
+ "<hr />\n"
+ '<span class="paragraph">$<marimo-tex class="arithmatex">||(x||)</marimo-tex>$</span>\n'
+ '<span class="paragraph">This should remain prose.</span>\n'
+ '<span class="paragraph">End</span>'
+ )
+
+
def test_md_display_math_format_preserved() -> None:
# __format__ should return original markdown text
text = "Hello\n$$f(x)$$\nworld"