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: ensure correct markdown serialization (#7016)

Dylan Madisetti1b61c86ce468
diff --git a/marimo/_ast/codegen.py b/marimo/_ast/codegen.py
index 69e0d160bf..4af45b450e 100644
--- a/marimo/_ast/codegen.py
+++ b/marimo/_ast/codegen.py
@@ -183,6 +183,7 @@ def format_markdown(cell: CellImpl) -> str:
# We can blanket replace, because cell.markdown is not set
# on f-strings with values.
markdown = markdown.replace("{", "{{").replace("}", "}}")
+ markdown = markdown.replace('""', '"\\"')
# We always use """ as per front end.
body = construct_markdown_call(markdown, '"""', tag)
diff --git a/marimo/_ast/load.py b/marimo/_ast/load.py
index b207adc987..44192e1b4a 100644
--- a/marimo/_ast/load.py
+++ b/marimo/_ast/load.py
@@ -35,6 +35,15 @@ LOGGER = _loggers.marimo_logger()
@dataclass
class LoadResult:
+ """Result of attempting to load a marimo notebook.
+
+ status can be one of:
+ - empty: No content, or only comments / a doc string
+ - has_errors: Parsed, but has marimo-specific errors (**can load!!**)
+ - invalid: Could not be parsed as a marimo notebook (**cannot load**)
+ - valid: Parsed and valid marimo notebook
+ """
+
status: Literal["empty", "has_errors", "invalid", "valid"] = "empty"
notebook: Optional[NotebookSerialization] = None
contents: Optional[str] = None
diff --git a/tests/_ast/codegen_data/_test_not_parsable.py b/tests/_ast/codegen_data/_test_not_parsable.py
new file mode 100644
index 0000000000..0a3de33cad
--- /dev/null
+++ b/tests/_ast/codegen_data/_test_not_parsable.py
@@ -0,0 +1,2 @@
+# INTENTIONALLY BROKEN!
+print("hello world
diff --git a/tests/_ast/codegen_data/_test_parse_error_in_notebook.py b/tests/_ast/codegen_data/_test_parse_error_in_notebook.py
new file mode 100644
index 0000000000..2a857d072d
--- /dev/null
+++ b/tests/_ast/codegen_data/_test_parse_error_in_notebook.py
@@ -0,0 +1,27 @@
+import marimo
+
+__generated_with = "0.17.4"
+app = marimo.App(width="medium")
+
+
+def _(mo):
+ mo.md("""
+ r"""Markdown cell with error"""
+ """)
+ return
+
+
+def _():
+ import marimo as mo
+ return (mo,)
+
+
+def _():
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_ast/codegen_data/test_get_app_kwargs.py b/tests/_ast/codegen_data/test_get_app_kwargs.py
index babd68a3fb..fbbc3e1015 100644
--- a/tests/_ast/codegen_data/test_get_app_kwargs.py
+++ b/tests/_ast/codegen_data/test_get_app_kwargs.py
@@ -1,5 +1,4 @@
import marimo
-
app = marimo.App(
app_title="title",
auto_download="html",
diff --git a/tests/_ast/codegen_data/test_with_bad_decorator.py b/tests/_ast/codegen_data/test_with_decorator.py
similarity index 100%
rename from tests/_ast/codegen_data/test_with_bad_decorator.py
rename to tests/_ast/codegen_data/test_with_decorator.py
diff --git a/tests/_ast/test_codegen.py b/tests/_ast/test_codegen.py
index c2d50e0314..604ed7bdae 100644
--- a/tests/_ast/test_codegen.py
+++ b/tests/_ast/test_codegen.py
@@ -1,6 +1,7 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+import ast
import json
from functools import partial
from inspect import cleandoc
@@ -722,6 +723,406 @@ class TestToFunctionDef:
assert fndef == expected
+def test_markdown_invalid() -> None:
+ expected = wrap_generate_filecontents(
+ ['mo.md("Unclosed string)', "import marimo as mo"], ["a", "b"]
+ )
+ ast.parse(expected) # should not raise
+ expected = wrap_generate_filecontents(
+ ['mo.md("Unclosed call"', "import marimo as mo"], ["a", "b"]
+ )
+ ast.parse(expected) # should not raise
+
+ # Unparsable: triple quotes close prematurely leaving invalid syntax
+ expected = wrap_generate_filecontents(
+ ['mo.md("""some text """ and more)', "import marimo as mo"], ["a", "b"]
+ )
+ ast.parse(expected) # should not raise
+
+ # Unparsable: triple quotes in middle breaking the call
+ expected = wrap_generate_filecontents(
+ ['mo.md("""content """ extra stuff""")', "import marimo as mo"],
+ ["a", "b"],
+ )
+ ast.parse(expected) # should not raise
+
+ # Unparsable: f-string with triple quotes breaking syntax
+ expected = wrap_generate_filecontents(
+ ['mo.md(f"""value {x} """ broken)', "import marimo as mo"], ["a", "b"]
+ )
+ ast.parse(expected) # should not raise
+
+ # Unparsable: nested quotes causing premature closure
+ expected = wrap_generate_filecontents(
+ ['mo.md("""text with """ in middle""")', "import marimo as mo"],
+ ["a", "b"],
+ )
+ ast.parse(expected) # should not raise
+
+ # Unparsable: double-quoted string with triple quotes breaking it
+ expected = wrap_generate_filecontents(
+ ['mo.md("some """ text")', "import marimo as mo"], ["a", "b"]
+ )
+ ast.parse(expected) # should not raise
+
+ # Unparsable: f-string with triple quotes inside interpolation
+ expected = wrap_generate_filecontents(
+ ['mo.md(f"value {"""test"""} more")', "import marimo as mo"],
+ ["a", "b"],
+ )
+ ast.parse(expected) # should not raise
+
+ # Unparsable: f-string with triple quotes breaking the f-string itself
+ expected = wrap_generate_filecontents(
+ ['mo.md(f"text """ {x}")', "import marimo as mo"], ["a", "b"]
+ )
+ ast.parse(expected) # should not raise
+
+ # Unparsable: triple-quoted f-string with triple quotes in content
+ expected = wrap_generate_filecontents(
+ ['mo.md(f"""start """ middle {y}""")', "import marimo as mo"],
+ ["a", "b"],
+ )
+ ast.parse(expected) # should not raise
+
+ # Unparsable: f-string with triple quotes AND invalid syntax in interpolation
+ expected = wrap_generate_filecontents(
+ ['mo.md(f"text {$$$}")', "import marimo as mo"], ["a", "b"]
+ )
+ ast.parse(expected) # should not raise
+
+ # Unparsable: unclosed triple-quote docstring with content
+ expected = wrap_generate_filecontents(
+ ['"""unclosed docstring\nwith """ content', "import marimo as mo"],
+ ["a", "b"],
+ )
+ ast.parse(expected) # should not raise
+
+ # Unparsable: broken f-string with triple quotes
+ expected = wrap_generate_filecontents(
+ ['f"value {x} with """', "import marimo as mo"], ["a", "b"]
+ )
+ ast.parse(expected) # should not raise
+
+ # Unparsable: string with triple quotes not closed properly
+ expected = wrap_generate_filecontents(
+ ['"string content """', "import marimo as mo"], ["a", "b"]
+ )
+ ast.parse(expected) # should not raise
+
+ # 0.17.3 parse variation
+ expected = wrap_generate_filecontents(
+ [
+ '''mo.md("
+ r"""some text"""
+ )''',
+ "import marimo as mo",
+ ],
+ ["a", "b"],
+ )
+ ast.parse(expected) # should not raise
+
+
+def test_markdown_with_alt_strings() -> None:
+ # Basic triple quotes in middle
+ expected = wrap_generate_filecontents(
+ ['mo.md(\'has """\')', "import marimo as mo"], ["a", "b"]
+ )
+ ast.parse(expected) # should not raise
+
+ expected = wrap_generate_filecontents(
+ ['mo.md(\'has """\\"\\\')', "import marimo as mo"], ["a", "b"]
+ )
+ ast.parse(expected) # should not raise
+
+ # Triple quotes at start
+ expected = wrap_generate_filecontents(
+ ['mo.md(\'"""followed by text\')', "import marimo as mo"], ["a", "b"]
+ )
+ ast.parse(expected) # should not raise
+
+ # Triple quotes at end
+ expected = wrap_generate_filecontents(
+ ['mo.md(\'text followed by"""\')', "import marimo as mo"], ["a", "b"]
+ )
+ ast.parse(expected) # should not raise
+
+ # Only triple quotes
+ expected = wrap_generate_filecontents(
+ ['mo.md(\'"""\')', "import marimo as mo"], ["a", "b"]
+ )
+ ast.parse(expected) # should not raise
+
+ # Multiple triple quotes
+ expected = wrap_generate_filecontents(
+ ['mo.md(\'first""" middle """end\')', "import marimo as mo"],
+ ["a", "b"],
+ )
+ ast.parse(expected) # should not raise
+
+ # Four consecutive quotes
+ expected = wrap_generate_filecontents(
+ ['mo.md(\'Text with """"more\')', "import marimo as mo"], ["a", "b"]
+ )
+ ast.parse(expected) # should not raise
+
+ # Five consecutive quotes
+ expected = wrap_generate_filecontents(
+ ['mo.md(\'Text with """""more\')', "import marimo as mo"], ["a", "b"]
+ )
+ ast.parse(expected) # should not raise
+
+ # Six consecutive quotes
+ expected = wrap_generate_filecontents(
+ ['mo.md(\'Text with """"""more\')', "import marimo as mo"], ["a", "b"]
+ )
+ ast.parse(expected) # should not raise
+
+ # Escaped quote before triple
+ expected = wrap_generate_filecontents(
+ ['mo.md(\'Text with \\\\"""""more\')', "import marimo as mo"],
+ ["a", "b"],
+ )
+ ast.parse(expected) # should not raise
+
+ # Triple quotes with whitespace
+ expected = wrap_generate_filecontents(
+ ['mo.md(\' """ \')', "import marimo as mo"], ["a", "b"]
+ )
+ ast.parse(expected) # should not raise
+
+ # Inline code with triple quotes
+ expected = wrap_generate_filecontents(
+ ['mo.md(\'Use `"""` for docstrings\')', "import marimo as mo"],
+ ["a", "b"],
+ )
+ ast.parse(expected) # should not raise
+
+ # HTML/markdown with triple quotes
+ expected = wrap_generate_filecontents(
+ ['mo.md(\'<div>"""</div>\')', "import marimo as mo"], ["a", "b"]
+ )
+ ast.parse(expected) # should not raise
+
+ # JSON with many quotes
+ expected = wrap_generate_filecontents(
+ ['mo.md(\'{"key": """value"""}\')', "import marimo as mo"], ["a", "b"]
+ )
+ ast.parse(expected) # should not raise
+
+ # With headers
+ expected = wrap_generate_filecontents(
+ ['mo.md(\'# Header with """\')', "import marimo as mo"], ["a", "b"]
+ )
+ ast.parse(expected) # should not raise
+
+ # With links
+ expected = wrap_generate_filecontents(
+ ['mo.md(\'[link](""") more\')', "import marimo as mo"], ["a", "b"]
+ )
+ ast.parse(expected) # should not raise
+
+ # With bold/italic
+ expected = wrap_generate_filecontents(
+ ['mo.md(\'**bold """ text**\')', "import marimo as mo"], ["a", "b"]
+ )
+ ast.parse(expected) # should not raise
+
+ # Simplest case - space-separated triple quotes
+ expected = wrap_generate_filecontents(
+ ['mo.md(\' """ \')', "import marimo as mo"], ["a", "b"]
+ )
+ ast.parse(expected) # should not raise
+
+ # With one char separator
+ expected = wrap_generate_filecontents(
+ ['mo.md(\'a"""b\')', "import marimo as mo"], ["a", "b"]
+ )
+ ast.parse(expected) # should not raise
+
+ # Alternating quote patterns
+ expected = wrap_generate_filecontents(
+ ['mo.md(\'Text " "" """ """\')', "import marimo as mo"], ["a", "b"]
+ )
+ ast.parse(expected) # should not raise
+
+ # Two quotes (not triple)
+ expected = wrap_generate_filecontents(
+ ["mo.md('Text with \"\" quotes')", "import marimo as mo"], ["a", "b"]
+ )
+ ast.parse(expected) # should not raise
+
+ # Seven quotes
+ expected = wrap_generate_filecontents(
+ ['mo.md(\'Text with """"""" quotes\')', "import marimo as mo"],
+ ["a", "b"],
+ )
+ ast.parse(expected) # should not raise
+
+ # No space around triple quotes
+ expected = wrap_generate_filecontents(
+ ['mo.md(\'a"""b\')', "import marimo as mo"], ["a", "b"]
+ )
+ ast.parse(expected) # should not raise
+
+ # Space before only
+ expected = wrap_generate_filecontents(
+ ['mo.md(\'a """b\')', "import marimo as mo"], ["a", "b"]
+ )
+ ast.parse(expected) # should not raise
+
+ # Space after only
+ expected = wrap_generate_filecontents(
+ ['mo.md(\'a""" b\')', "import marimo as mo"], ["a", "b"]
+ )
+ ast.parse(expected) # should not raise
+
+ # Space both sides
+ expected = wrap_generate_filecontents(
+ ['mo.md(\'a """ b\')', "import marimo as mo"], ["a", "b"]
+ )
+ ast.parse(expected) # should not raise
+
+ # Using f-string single quotes with triple quotes
+ expected = wrap_generate_filecontents(
+ ['mo.md(f\'value {x} with """\')', "import marimo as mo", "x = 1"],
+ ["a", "b", "c"],
+ )
+ ast.parse(expected) # should not raise
+
+ # Using f-string double quotes with escaped triple quotes
+ expected = wrap_generate_filecontents(
+ [
+ 'mo.md(f"value {y} with \\"\\"\\" here")',
+ "import marimo as mo",
+ "y = 2",
+ ],
+ ["a", "b", "c"],
+ )
+ ast.parse(expected) # should not raise
+
+ # Using f-string triple quotes with escaped triple quotes
+ expected = wrap_generate_filecontents(
+ [
+ 'mo.md(f"""value {z} with \\"\\"\\" content""")',
+ "import marimo as mo",
+ "z = 3",
+ ],
+ ["a", "b", "c"],
+ )
+ ast.parse(expected) # should not raise
+
+ # f-string with multiple interpolations and triple quotes
+ expected = wrap_generate_filecontents(
+ [
+ 'mo.md(f"first {a} then \\"\\"\\" then {b}")',
+ "import marimo as mo",
+ "a = 1; b = 2",
+ ],
+ ["a", "b", "c"],
+ )
+ ast.parse(expected) # should not raise
+
+ # Raw f-string triple quotes with content
+ expected = wrap_generate_filecontents(
+ [
+ 'mo.md(fr"""raw {c} with \\"\\"\\" text""")',
+ "import marimo as mo",
+ "c = 4",
+ ],
+ ["a", "b", "c"],
+ )
+ ast.parse(expected) # should not raise
+
+
+def test_previous_problematic_cases() -> None:
+ # All of these cases fail under 0.17.3 but should parse correctly now.
+ # Bug resulting from mixed quote types.
+
+ # Using double quotes with escaped triple quotes
+ expected = wrap_generate_filecontents(
+ ['mo.md("text with \\"\\"\\" here")', "import marimo as mo"],
+ ["a", "b"],
+ )
+ ast.parse(expected) # should not raise
+
+ # Using triple quotes with escaped triple quotes inside
+ expected = wrap_generate_filecontents(
+ ['mo.md("""content with \\"\\"\\" inside""")', "import marimo as mo"],
+ ["a", "b"],
+ )
+ ast.parse(expected) # should not raise
+
+ # With lists
+ expected = wrap_generate_filecontents(
+ ['mo.md(\'- item with """\\n- another item\')', "import marimo as mo"],
+ ["a", "b"],
+ )
+ ast.parse(expected) # should not raise
+
+ # Shell commands with quotes
+ expected = wrap_generate_filecontents(
+ ['mo.md(\'Run: echo """hello"""\\\'\')', "import marimo as mo"],
+ ["a", "b"],
+ )
+ ast.parse(expected) # should not raise
+
+ # Quote blocks with triple quotes
+ expected = wrap_generate_filecontents(
+ [
+ 'mo.md(\'> Quote with """\\n> More content\')',
+ "import marimo as mo",
+ ],
+ ["a", "b"],
+ )
+ ast.parse(expected) # should not raise
+ # Docstring examples in markdown
+ expected = wrap_generate_filecontents(
+ [
+ 'mo.md(\'Python docstrings use triple quotes:\\n"""\\nThis is a docstring\\n"""\')',
+ "import marimo as mo",
+ ],
+ ["a", "b"],
+ )
+ ast.parse(expected) # should not raise
+
+ # Markdown with code blocks containing quotes
+ expected = wrap_generate_filecontents(
+ [
+ 'mo.md(\'```python\\nprint(""" hello """)\\n```\')',
+ "import marimo as mo",
+ ],
+ ["a", "b"],
+ )
+ ast.parse(expected) # should not raise
+
+ # Triple quotes with newlines
+ expected = wrap_generate_filecontents(
+ ['mo.md(\'\\nline1 with """\\nline2\\n\')', "import marimo as mo"],
+ ["a", "b"],
+ )
+ ast.parse(expected) # should not raise
+
+ # Triple quotes with single quotes
+ expected = wrap_generate_filecontents(
+ ["mo.md('Text with \"\"\" and \\'single\\'')", "import marimo as mo"],
+ ["a", "b"],
+ )
+ ast.parse(expected) # should not raise
+
+ # Double quotes with triple quotes at start
+ expected = wrap_generate_filecontents(
+ ['mo.md("\\"\\"\\" at start")', "import marimo as mo"], ["a", "b"]
+ )
+ ast.parse(expected) # should not raise
+
+ # Triple quotes with triple quotes at end
+ expected = wrap_generate_filecontents(
+ ['mo.md("""at end \\"\\"\\"""")', "import marimo as mo"], ["a", "b"]
+ )
+ ast.parse(expected) # should not raise
+
+
def test_recover(tmp_path: Path) -> None:
cells: NotebookV1 = {
"version": "1",
diff --git a/tests/_ast/test_load.py b/tests/_ast/test_load.py
index 3443b210b9..c004e97931 100644
--- a/tests/_ast/test_load.py
+++ b/tests/_ast/test_load.py
@@ -291,8 +291,8 @@ class TestGetCodes:
assert "kwarg_that_doesnt_exist" in caplog.text
@staticmethod
- def test_get_app_with_bad_decorator(static_load) -> None:
- app = static_load(get_filepath("test_with_bad_decorator"))
+ def test_get_app_with_decorator(static_load) -> None:
+ app = static_load(get_filepath("test_with_decorator"))
assert app is not None
assert app._cell_manager.get_cell_data_by_name("wrap").cell.defs == {
"wrap"
@@ -300,38 +300,86 @@ class TestGetCodes:
assert app._cell_manager.get_cell_data_by_name(
"hundred"
).cell.defs == {"hundred"}
- from codegen_data.test_with_bad_decorator import hundred
+ from codegen_data.test_with_decorator import hundred
assert hundred == 100
class TestGetStatus:
@staticmethod
- def test_get_status_valid() -> None:
- assert (
- load.get_notebook_status(get_filepath("test_main")).status
- == "valid"
- )
-
- @staticmethod
- def test_get_status_empty() -> None:
- assert (
- load.get_notebook_status(get_filepath("test_empty")).status
- == "empty"
- )
+ @pytest.mark.parametrize(
+ ("filename", "expected_status"),
+ [
+ # Valid marimo apps
+ ("test_main", "valid"),
+ ("test_generate_filecontents", "valid"),
+ ("test_generate_filecontents_async", "valid"),
+ ("test_generate_filecontents_async_long_signature", "valid"),
+ ("test_generate_filecontents_single_cell", "valid"),
+ ("test_generate_filecontents_toplevel", "valid"),
+ ("test_generate_filecontents_toplevel_pytest", "valid"),
+ ("test_decorators", "valid"),
+ ("test_get_codes_multiline_string", "valid"),
+ ("test_get_codes_messy", "valid"),
+ ("test_get_codes_single_line_fn", "valid"),
+ ("test_get_codes_multiline_fndef", "valid"),
+ ("test_get_codes_comment_after_sig", "valid"),
+ ("test_get_codes_empty", "valid"),
+ ("test_get_header_comments", "valid"),
+ ("test_get_setup", "valid"),
+ ("test_get_setup_blank", "valid"),
+ ("test_generate_filecontents_shadowed_builtin", "valid"),
+ ("test_generate_filecontents_unshadowed_builtin", "valid"),
+ ("test_app_with_annotation_typing", "valid"),
+ ("test_long_line_in_main", "valid"),
+ ("test_with_decorator", "valid"),
+ # Potentially confusing but valid
+ ("test_get_codes_with_name_error", "valid"), # runtime error
+ ("test_syntax_errors", "valid"), # runtime syntax errors
+ # Broken signature, but fine otherwise
+ ("test_get_codes_with_incorrect_args_rets", "valid"),
+ # unparse cells
+ ("test_generate_filecontents_with_syntax_error", "valid"),
+ # Empty files
+ ("test_empty", "empty"),
+ # No cells
+ ("test_app_with_only_comments", "invalid"),
+ # Invalid (not marimo apps)
+ ("test_invalid", "invalid"),
+ # Has errors
+ ("test_get_codes_messy_toplevel", "has_errors"),
+ ("test_get_header_comments_invalid", "has_errors"),
+ ("test_get_bad_kwargs", "has_errors"),
+ # Unparsable
+ (
+ "test_get_codes_non_marimo_python_script",
+ "invalid",
+ ), # not marimo
+ # Potentially confusing and has_errors
+ ("test_get_alias_import", "has_errors"), # not official format
+ ("test_get_app_kwargs", "has_errors"), # Intentionally bad kwargs
+ # Empty files can still be opened.
+ (
+ "test_generate_filecontents_empty_with_config",
+ "has_errors",
+ ), # no body
+ ("test_generate_filecontents_empty", "has_errors"), # no body
+ ("test_app_with_no_cells", "has_errors"), # No body is an error
+ # Syntax errors in code
+ ("_test_not_parsable", "broken"),
+ ("_test_parse_error_in_notebook", "broken"),
+ # A script that is not a marimo notebook, but uses marimo is
+ # indeterminant, so throws an exception.
+ ("test_non_marimo", "broken"),
+ ],
+ )
+ def test_get_status(filename: str, expected_status: str) -> None:
+ if expected_status == "broken":
+ with pytest.raises((MarimoFileError, SyntaxError)):
+ load.get_notebook_status(get_filepath(filename))
+ return
- @staticmethod
- def test_get_status_invalid() -> None:
- assert (
- load.get_notebook_status(get_filepath("test_invalid")).status
- == "invalid"
- )
-
- @staticmethod
- def test_get_status_warn() -> None:
assert (
- load.get_notebook_status(
- get_filepath("test_get_codes_messy_toplevel")
- ).status
- == "has_errors"
+ load.get_notebook_status(get_filepath(filename)).status
+ == expected_status
)