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
update: update code block to ```python {.marimo} (#3387)
Dylan Madisetti7a61a27e1db8
diff --git a/marimo/_ast/cell.py b/marimo/_ast/cell.pyindex 2ef2bfa1ee..f2fb2acb68 100644--- a/marimo/_ast/cell.py+++ b/marimo/_ast/cell.py@@ -146,6 +146,7 @@ class CellImpl:mod: ast.Moduledefs: set[Name]refs: set[Name]+ # Variables that should only live for the duration of the celltemporaries: set[Name]# metadata about definitions@@ -178,6 +179,9 @@ class CellImpl:_sqls: ParsedSQLStatements = dataclasses.field(default_factory=ParsedSQLStatements)+ _raw_sqls: ParsedSQLStatements = dataclasses.field(+ default_factory=ParsedSQLStatements+ )def configure(self, update: dict[str, Any] | CellConfig) -> CellImpl:"""Update the cell config.@@ -205,6 +209,14 @@ class CellImpl:def run_result_status(self) -> Optional[RunResultStatusType]:return self._run_result_status.state+ def _get_sqls(self, raw: bool = False) -> list[str]:+ try:+ visitor = SQLVisitor(raw=raw)+ visitor.visit(ast.parse(self.code))+ return visitor.get_sqls()+ except Exception:+ return []+@propertydef sqls(self) -> list[str]:"""Returns parsed SQL statements from this cell.@@ -215,16 +227,22 @@ class CellImpl:if self._sqls.parsed is not None:return self._sqls.parsed- try:- visitor = SQLVisitor()- visitor.visit(ast.parse(self.code))- sqls = visitor.get_sqls()- self._sqls.parsed = sqls- except Exception:- self._sqls.parsed = []-+ self._sqls.parsed = self._get_sqls()return self._sqls.parsed+ @property+ def raw_sqls(self) -> list[str]:+ """Returns unparsed SQL statements from this cell.++ Returns:+ list[str]: List of SQL statements verbatim from the cell code.+ """+ if self._raw_sqls.parsed is not None:+ return self._raw_sqls.parsed++ self._raw_sqls.parsed = self._get_sqls(raw=True)+ return self._raw_sqls.parsed+@propertydef stale(self) -> bool:return self._stale.statediff --git a/marimo/_ast/sql_visitor.py b/marimo/_ast/sql_visitor.pyindex 837e012dc8..bd6ba24c18 100644--- a/marimo/_ast/sql_visitor.py+++ b/marimo/_ast/sql_visitor.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport astimport refrom dataclasses import dataclass, field+from textwrap import dedentfrom typing import Any, List, Optionalfrom marimo import _loggers@@ -18,9 +19,10 @@ class SQLVisitor(ast.NodeVisitor):This should be inside a function called `.execute` or `.sql`."""- def __init__(self) -> None:+ def __init__(self, raw: bool = False) -> None:super().__init__()self._sqls: list[str] = []+ self._raw = rawdef visit_Call(self, node: ast.Call) -> None:# Check if the call is a method call and the method is named@@ -35,9 +37,18 @@ class SQLVisitor(ast.NodeVisitor):first_arg = node.args[0]sql: Optional[str] = Noneif isinstance(first_arg, ast.Constant):- sql = first_arg.s+ sql = first_arg.valueelif isinstance(first_arg, ast.JoinedStr):- sql = normalize_sql_f_string(first_arg)+ if self._raw:+ f_sql = ast.unparse(first_arg)+ sql = dedent(+ f_sql[1:]+ .strip(f_sql[1])+ .encode()+ .decode("unicode_escape")+ )+ else:+ sql = normalize_sql_f_string(first_arg)if sql is not None:# Append the SQL query to the list@@ -64,7 +75,7 @@ def normalize_sql_f_string(node: ast.JoinedStr) -> str:elif isinstance(part, ast.JoinedStr):return normalize_sql_f_string(part)elif isinstance(part, ast.Constant):- return str(part.s)+ return str(part.value)else:# Just add null as a placeholder for {...} expressionsreturn "null"diff --git a/marimo/_cli/convert/markdown.py b/marimo/_cli/convert/markdown.pyindex d04e843a4e..0e2c97f9db 100644--- a/marimo/_cli/convert/markdown.py+++ b/marimo/_cli/convert/markdown.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport refrom dataclasses import dataclass-from typing import Any, Callable, Literal, Optional, Union+from typing import Any, Callable, Literal, Optional, Union, cast# Native to pythonfrom xml.etree.ElementTree import Element, SubElement@@ -22,22 +22,71 @@ from pymdownx.superfences import ( # type: ignoreSuperFencesCodeExtension,)+from marimo import _loggersfrom marimo._ast import codegenfrom marimo._ast.app import App, InternalApp, _AppConfigfrom marimo._ast.cell import Cell, CellConfigfrom marimo._ast.compiler import compile_cellfrom marimo._ast.names import DEFAULT_CELL_NAME-from marimo._convert.utils import markdown_to_marimo+from marimo._convert.utils import markdown_to_marimo, sql_to_marimo+from marimo._dependencies.dependencies import DependencyManager++LOGGER = _loggers.marimo_logger()MARIMO_MD = "marimo-md"MARIMO_CODE = "marimo-code"ConvertKeys = Union[Literal["marimo"], Literal["marimo-app"]]+# Regex captures loose yaml for frontmatter+# Should match the following:+# ---+# title: "Title"+# whatever+# ---+YAML_FRONT_MATTER_REGEX = re.compile(+ r"^---\s*\n(.*?\n?)(?:---)\s*\n", re.UNICODE | re.DOTALL+)+++def backwards_compatible_sanitization(line: str) -> str:+ return line+++def extract_attribs(+ line: str, fence_start: Optional[re.Match[str]] = None+) -> dict[str, str]:+ # Extract attributes from the code block.+ # Blocks are expected to be like this:+ # python {.marimo disabled="true"}+ if fence_start is None:+ fence_start = RE_NESTED_FENCE_START.match(line)++ if fence_start:+ # attrs is a bit of a misnomer, matches+ # .python.marimo disabled="true"+ inner = fence_start.group("attrs")+ if inner:+ return dict(re.findall(r'(\w+)="([^"]*)"', inner))+ return {}+def _is_code_tag(text: str) -> bool:head = text.split("\n")[0].strip()- return bool(re.search(r"\{.*python.*\}", head))+ legacy_format = bool(re.search(r"\{.*python.*\}", head))+ legacy_format |= bool(re.search(r"\{.*sql.*\}", head))+ if DependencyManager.new_superfences.has_required_version(quiet=True):+ supported_format = bool(re.search(r".*\{.*marimo.*\}", head))+ return legacy_format or supported_format+ return legacy_format+++def _get_language(text: str) -> str:+ header = text.split("\n").pop(0)+ match = RE_NESTED_FENCE_START.match(header)+ if match and match.group("lang"):+ return str(match.group("lang"))+ return "python"def formatted_code_block(@@ -46,14 +95,24 @@ def formatted_code_block("""Wraps code in a fenced code block with marimo attributes."""if attributes is None:attributes = {}+ language = attributes.pop("language", "python")attribute_str = " ".join([""] + [f'{key}="{value}"' for key, value in attributes.items()])guard = "```"while guard in code:guard += "`"+ if DependencyManager.new_superfences.has_required_version(quiet=True):+ return "\n".join(+ [+ f"""{guard}{language} {{.marimo{attribute_str}}}""",+ code,+ guard,+ "",+ ]+ )return "\n".join(- [f"""{guard}{{.python.marimo{attribute_str}}}""", code, guard, ""]+ [f"""{guard}{{.{language}.marimo{attribute_str}}}""", code, guard, ""])@@ -82,6 +141,8 @@ def get_source_from_tag(tag: Element) -> str:if not (source and source.strip()):return ""source = markdown_to_marimo(source)+ elif tag.attrib.get("language") == "sql":+ source = sql_to_marimo(source, tag.attrib.get("query", "_df"))else:assert tag.tag == MARIMO_CODE, f"Unknown tag: {tag.tag}"return source@@ -150,7 +211,10 @@ def _tree_to_app(root: Element) -> str:cell_config: list[CellConfig] = []for child in root:names.append(child.get("name", DEFAULT_CELL_NAME))- cell_config.append(get_cell_config_from_tag(child))+ # Default to hiding markdown cells.+ cell_config.append(+ get_cell_config_from_tag(child, hide_code=child.tag == MARIMO_MD)+ )sources.append(get_source_from_tag(child))return codegen.generate_filecontents(@@ -272,15 +336,6 @@ class FrontMatterPreprocessor(Preprocessor):super().__init__(md)self.md = mdself.md.meta = {}- # Regex captures loose yaml for frontmatter- # Should match the following:- # ---- # title: "Title"- # whatever- # ---- self.yaml_front_matter_regex = re.compile(- r"^---\s*\n(.*?\n?)(?:---)\s*\n", re.UNICODE | re.DOTALL- )def run(self, lines: list[str]) -> list[str]:import yaml@@ -295,7 +350,7 @@ class FrontMatterPreprocessor(Preprocessor):return linesdoc = "\n".join(lines)- result = self.yaml_front_matter_regex.match(doc)+ result = YAML_FRONT_MATTER_REGEX.match(doc)if result:yaml_content = result.group(1)@@ -414,25 +469,27 @@ class ExpandAndClassifyProcessor(BlockProcessor):code_block = SubElement(parent, MARIMO_CODE)block_lines = code.split("\n")code_block.text = "\n".join(block_lines[1:-1])- # Extract attributes from the code block.- # Blocks are expected to be like this:- # {.python.marimo disabled="true"}- fence_start = RE_NESTED_FENCE_START.match(block_lines[0])- if fence_start:- # attrs is a bit of a misnomer, matches- # .python.marimo disabled="true"- inner = fence_start.group("attrs")- if inner:- code_block.attrib = dict(- re.findall(r'(\w+)="([^"]*)"', inner)- )++ attribs = extract_attribs(block_lines[0])+ if attribs:+ code_block.attrib = attribs++ # Set after to prevent lang being flushed.+ code_block.set("language", _get_language(code))+add_paragraph()# Flush to indicate all blocks have been processed.blocks.clear()def convert_from_md_to_app(text: str) -> App:- return MarimoParser(output_format="marimo-app").convert(text) # type: ignore[arg-type, return-value]+ if not text.strip():+ app = App()+ else:+ app = cast(App, MarimoParser(output_format="marimo-app").convert(text))++ app._cell_manager.ensure_one_cell()+ return appdef convert_from_md(text: str) -> str:diff --git a/marimo/_convert/utils.py b/marimo/_convert/utils.pyindex 6a0ec05083..006ee51ccf 100644--- a/marimo/_convert/utils.py+++ b/marimo/_convert/utils.py@@ -23,6 +23,19 @@ def markdown_to_marimo(source: str) -> str:)+def sql_to_marimo(source: str, table: str) -> str:+ return "\n".join(+ [+ f"{table} = mo.sql(",+ # f-string: expected for sql+ codegen.indent_text('f"""'),+ codegen.indent_text(source),+ codegen.indent_text('"""'),+ ")",+ ]+ )++def generate_from_sources(*,sources: list[str],diff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.pyindex 0b8da2cb6d..0a3a102382 100644--- a/marimo/_dependencies/dependencies.py+++ b/marimo/_dependencies/dependencies.py@@ -14,7 +14,7 @@ class Dependency:min_version: str | None = Nonemax_version: str | None = None- def has(self) -> bool:+ def has(self, quiet: bool = False) -> bool:"""Return True if the dependency is installed."""try:has_dep = importlib.util.find_spec(self.pkg) is not None@@ -24,20 +24,32 @@ class Dependency:# Could happen for nested imports (e.g. foo.bar)return False- if self.min_version or self.max_version:+ if not quiet and (self.min_version or self.max_version):self.warn_if_mismatch_version(self.min_version, self.max_version)return Truedef has_at_version(- self, *, min_version: str | None, max_version: str | None = None+ self,+ *,+ min_version: str | None,+ max_version: str | None = None,+ quiet: bool = False,) -> bool:- if not self.has():+ if not self.has(quiet=quiet):return Falsereturn _version_check(pkg=self.pkg,v=self.get_version(),min_v=min_version,max_v=max_version,+ quiet=quiet,+ )++ def has_required_version(self, quiet: bool = False) -> bool:+ return self.has_at_version(+ min_version=self.min_version,+ max_version=self.max_version,+ quiet=quiet,)def imported(self) -> bool:@@ -75,7 +87,10 @@ class Dependency:)def get_version(self) -> str:- return importlib.metadata.version(self.pkg)+ try:+ return importlib.metadata.version(self.pkg)+ except importlib.metadata.PackageNotFoundError:+ return f"{__import__(self.pkg).__version__}"def warn_if_mismatch_version(self,@@ -111,6 +126,7 @@ def _version_check(min_v: str | None = None,max_v: str | None = None,raise_error: bool = False,+ quiet: bool = False,) -> bool:if min_v is None and max_v is None:return True@@ -125,14 +141,16 @@ def _version_check(msg = f"Mismatched version of {pkg}: expected >={min_v}, got {v}"if raise_error:raise RuntimeError(msg)- sys.stderr.write(f"{msg}. Some features may not work correctly.")+ if not quiet:+ sys.stderr.write(f"{msg}. Some features may not work correctly.")return Falseif parsed_max_version is not None and parsed_v >= parsed_max_version:msg = f"Mismatched version of {pkg}: expected <{max_v}, got {v}"if raise_error:raise RuntimeError(msg)- sys.stderr.write(f"{msg}. Some features may not work correctly.")+ if not quiet:+ sys.stderr.write(f"{msg}. Some features may not work correctly.")return Falsereturn True@@ -171,6 +189,10 @@ class DependencyManager:panel = Dependency("panel")sqlalchemy = Dependency("sqlalchemy")+ # Version requirements to properly support the new superfences introduced in+ # pymdown#2470+ new_superfences = Dependency("pymdownx", min_version="10.11.0")+@staticmethoddef has(pkg: str) -> bool:"""Return True if any lib is installed."""diff --git a/marimo/_server/export/exporter.py b/marimo/_server/export/exporter.pyindex 592662de02..66bcd5be28 100644--- a/marimo/_server/export/exporter.py+++ b/marimo/_server/export/exporter.py@@ -297,8 +297,6 @@ class Exporter:except SyntaxError:pass- # Definitely no "cell"; as such, treat as code, as everything in- # marimo is code.if cell:markdown = get_markdown_from_cell(cell, code)# Unsanitized markdown is forced to code.@@ -309,6 +307,40 @@ class Exporter:previous_was_markdown = Truedocument.append(markdown)continue+ attributes["language"] = cell._cell.language+ # Definitely a code cell, but need to determine if it can be+ # formatted as non-python.+ if attributes["language"] == "sql":+ # Note frontend/src/core/codemirror/language/sql.ts+ # Determines sql structure by regex, but having access to+ # the AST gives us more flexibility.+ query = None+ valid_sql = True+ for (+ maybe_query,+ def_vars,+ ) in cell._cell.variable_data.items():+ if query:+ # query has already been set, hence this breaks+ # the expected format.+ query = None+ attributes.pop("language")+ valid_sql = False+ break+ for var in def_vars:+ # We are looking for the case where we assign a+ # query output to python.+ if var.language == "python":+ query = maybe_query+ break++ if valid_sql:+ code = "\n".join(cell._cell.raw_sqls).strip()+ if query:+ attributes["query"] = query++ # Definitely no "cell"; as such, treat as code, as everything in+ # marimo is code.else:attributes["unparsable"] = "true"# Add a blank line between markdown and codediff --git a/marimo/_tutorials/markdown_format.md b/marimo/_tutorials/markdown_format.mdindex cf0a688523..318221140f 100644--- a/marimo/_tutorials/markdown_format.md+++ b/marimo/_tutorials/markdown_format.md@@ -1,6 +1,6 @@---title: Markdown-marimo-version: 0.4.11+marimo-version: 0.10.9---# Markdown file format@@ -12,6 +12,7 @@ work on prose-heavy marimo notebooks in your editor of choice._Make sure to look at the markdown[source code](https://github.com/marimo-team/marimo/blob/main/marimo/_tutorials/markdown_format.md)of this tutorial!_+## Running markdown notebooksTo edit a markdown notebook, use@@ -35,14 +36,13 @@ by running the following command:$ marimo export md notebook.py > notebook.md```<!---->-## Creating Python cellsWhen you do need to create a Python cell in the markdown format, you can use aspecial code block:````md-```{.python.marimo}+```python {.marimo}import matplotlib.pyplot as pltplt.plot([1, 2, 3, 4])```@@ -50,15 +50,16 @@ plt.plot([1, 2, 3, 4])This will create the following cell:-```{.python.marimo}+```python {.marimo}import matplotlib.pyplot as plt+plt.plot([1, 2, 3, 4])plt.gca()```-As long as your code block contains the word `python` in a brace, like-`{python}`, or `{.python note="Whatever you want"}`, marimo will treat it as a-Python cell.+As long as your code block contains the word `marimo` in a brace, like+`{marimo}`, or `{.marimo note="Whatever you want"}`, marimo will treat it as a Python cell.+## `mo` tricks and tipsYou can break up markdown into multiple cells by using an empty html tag `<!---->`:@@ -68,31 +69,32 @@ View the source of this notebook to see how this cell was created.You can still hide and disable code cells in markdown notebooks:````md-```{python hide_code="true"}+```python {.marimo hide_code="true"}import pandas as pdpd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})```````-```{.python.marimo hide_code="true"}+```python {.marimo hide_code="true"}import pandas as pd-pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})++pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})```````md-```{python disabled="true"}+```python {.marimo disabled="true"}print("This code cell is disabled, there should be no output!")```````-```{.python.marimo disabled="true"}+```python {.marimo disabled="true"}print("This code cell is disabled, there should be no output!")```Additionally, marimo knows when your code has a syntax issue:````md-```{python}+```python {.marimo}print("This code cell has a syntax error"```````@@ -100,12 +102,12 @@ print("This code cell has a syntax error"and on notebook save, will annotate the cell for you:````md-```{python unparseable="true"}+```python {.marimo unparseable="true"}print("This code cell has a syntax error"```````-```{.python.marimo unparsable="true"}+```python {.marimo unparsable="true"}print("This code cell has a syntax error"```@@ -117,8 +119,8 @@ just give you the raw string. This lets you clearly delineate what values aresupposed to be computed, and what values are static. To interpolate Pythonvalues, just use a Python cell:-```{.python.marimo}-'🍃' * 7+```python {.marimo}+"🍃" * 7```### Limitations on conversion@@ -126,7 +128,7 @@ values, just use a Python cell:Whenever you try to implement a cell block like this:````md-```{python}+```python {.marimo}mo.md("This is a markdown cell")```````@@ -134,13 +136,15 @@ mo.md("This is a markdown cell")The markdown format will know to automatically keep this as markdown. However,some ambiguous cases can't be converted to markdown like this:-````{.python.marimo}-mo.md("""- This is a markdown cell with an execution block in it- ```{python}- # Too ambiguous to convert- ```- """)+````python {.marimo}+mo.md(+ """+ This is a markdown cell with an execution block in it+ ```python {.marimo}+ # Too ambiguous to convert+ ```+ """+)````It's not likely that you'll run into this issue, but rest assured that marimo@@ -154,16 +158,17 @@ markdown notebook cells like you can in a python notebook; but you can stillgive your cells a name:````md-```{.python.marimo name="maybe"}+```python {.marimo name="maybe"}# 🎵 Hey, I just met you, and this is crazy```````-```{.python.marimo name="maybe"}+```python {.marimo name="maybe"}# But here's my `cell_id`, so call me, `maybe` 🎶```## Converting back to the Python file format+The markdown format is supposed to lower the barrier for writing text heavydocuments, it's not meant to be a full replacement for the Python notebookformat. You can always convert back to a Python notebook if you need to:@@ -172,11 +177,45 @@ format. You can always convert back to a Python notebook if you need to:$ marimo convert my_marimo.md > my_marimo.py```+<!---->++## SQL in markdown++You can also run parameterized SQL queries in markdown cells through marimo.++```python {.marimo hide_code="true"}+num = mo.ui.slider(1, 15, label="Fibonacci numbers")+num+```++```python {.marimo}+_df = mo.sql(+ f"""+ WITH RECURSIVE fibonacci AS (+ SELECT+ 1 as n,+ 1 as fib,+ 1 as prev+ UNION ALL+ SELECT+ n + 1,+ fib + prev,+ fib+ FROM fibonacci+ WHERE n < {num.value}+ )+ SELECT n, fib+ FROM fibonacci+ ORDER BY n;+ """+)+```+## More on markdownBe sure to checkout the markdown.py tutorial (`marimo tutorial markdown`) formore information on to type-set and render markdown in marimo.-```{.python.marimo hide_code="true"}+```python {.marimo hide_code="true"}import marimo as mo-```+```\ No newline at end of filediff --git a/pyproject.toml b/pyproject.tomlindex 11cff4b93d..2d2340ce48 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -17,7 +17,8 @@ dependencies = [# compile markdown to html"markdown>=3.4,<4",# add features to markdown- "pymdown-extensions>=10,<11",+ # Pinned to specific version for introduction of codeblock handling.+ "pymdown-extensions>=10.11.2,<11",# syntax highlighting of code in markdown"pygments>=2.13,<3",# for reading, writing configsdiff --git a/tests/_cli/snapshots/async.txt b/tests/_cli/snapshots/async.txtindex 34badf80f2..a29ff20a16 100644--- a/tests/_cli/snapshots/async.txt+++ b/tests/_cli/snapshots/async.txt@@ -3,7 +3,7 @@ title: Notebookmarimo-version: 0.0.0----```{.python.marimo}+```python {.marimo}import asyncioawait asyncio.sleep(0.1)```diff --git a/tests/_cli/snapshots/broken.txt b/tests/_cli/snapshots/broken.txtindex 04bb48df46..8aea641ac2 100644--- a/tests/_cli/snapshots/broken.txt+++ b/tests/_cli/snapshots/broken.txt@@ -3,14 +3,14 @@ title: Notebookmarimo-version: 0.0.0----```{.python.marimo unparsable="true"}+```python {.marimo unparsable="true"}return```-```{.python.marimo unparsable="true"}+```python {.marimo unparsable="true"}partial_statement =```-```{.python.marimo}+```python {.marimo}valid_statement = 1```diff --git a/tests/_cli/snapshots/dataflow.md.txt b/tests/_cli/snapshots/dataflow.md.txtindex c1e46eedce..8a21ce589c 100644--- a/tests/_cli/snapshots/dataflow.md.txt+++ b/tests/_cli/snapshots/dataflow.md.txt@@ -44,7 +44,7 @@ a cell is run, its descendants are run automatically.The next four cells plot a sine wave with a given period and amplitude.Each cell is labeled with its refs and defs.-```{.python.marimo hide_code="true"}+```python {.marimo hide_code="true"}mo.accordion({"Tip: inspecting refs and defs": f"""@@ -59,7 +59,7 @@ mo.accordion()```-```{.python.marimo}+```python {.marimo}mo.md(f"""{mo.as_html(plot_wave(amplitude, period))}@@ -70,7 +70,7 @@ mo.md()```-```{.python.marimo}+```python {.marimo}period = 2 * 3.14159mo.md(@@ -81,7 +81,7 @@ mo.md()```-```{.python.marimo}+```python {.marimo}amplitude = 1mo.md(@@ -92,7 +92,7 @@ mo.md()```-```{.python.marimo}+```python {.marimo}def plot_wave(amplitude, period):if not numpy_installed:return mo.md(@@ -170,12 +170,12 @@ execute cells in.If you violate this constraint, marimo provides a helpfulerror message, like below:-```{.python.marimo}+```python {.marimo}planet = "Mars"planet```-```{.python.marimo}+```python {.marimo}planet = "Earth"planet```@@ -190,11 +190,11 @@ them; these operators count as redefinitions of a name.**🌊 Try it!** Get rid of the following errors by merging the next twocells into a single cell.-```{.python.marimo}+```python {.marimo}count = 0```-```{.python.marimo}+```python {.marimo}count += 1```@@ -207,17 +207,17 @@ made available to other cells.**Example**.-```{.python.marimo}+```python {.marimo}_private_variable, _ = 1, 2_private_variable, _```-```{.python.marimo}+```python {.marimo}_private_variable, _ = 3, 4_private_variable, _```-```{.python.marimo}+```python {.marimo}# `_private_variable` and `_` are not defined in this cell_private_variable, _```@@ -229,7 +229,7 @@ then runs all cells that reference them. This prevents severe bugs thatcan arise when state has been deleted from the editor but not from theprogram memory.-```{.python.marimo}+```python {.marimo}to_be_deleted = "variable still exists"mo.md(@@ -241,7 +241,7 @@ mo.md()```-```{.python.marimo}+```python {.marimo}to_be_deleted```@@ -249,11 +249,11 @@ to_be_deletedCycles among cells are not allowed. For example:-```{.python.marimo}+```python {.marimo}one = two - 1```-```{.python.marimo}+```python {.marimo}two = one + 1```@@ -265,15 +265,15 @@ trigger reactive execution.**🌊 Example**. Change the value of `state.number` in the next cell, thenrun the cell. Notice how the subsequent cell isn't updated.-```{.python.marimo}+```python {.marimo}state.number = 1```-```{.python.marimo}+```python {.marimo}state.number```-```{.python.marimo}+```python {.marimo}class namespace:pass@@ -281,7 +281,7 @@ state = namespace()state.number = 0```-```{.python.marimo hide_code="true"}+```python {.marimo hide_code="true"}mo.accordion({"Why not track attributes?": """@@ -299,7 +299,7 @@ In Python, it's impossible to know whether code willmutate an object without running it. So: mutations (such asappending to a list) will not trigger reactive execution.-```{.python.marimo hide_code="true"}+```python {.marimo hide_code="true"}mo.accordion({"Tip (advanced): mutable state": (@@ -325,7 +325,7 @@ and apps, and they'll encourage you to write clean, reproducible code.Follow these tips to stay on the marimo way:-```{.python.marimo}+```python {.marimo}mo.accordion(tips)```@@ -337,7 +337,7 @@ Check out the tutorial on interactivity for a tour of UI elements:marimo tutorial ui```-```{.python.marimo hide_code="true"}+```python {.marimo hide_code="true"}matplotlib_installed = Falsenumpy_installed = False@@ -356,7 +356,7 @@ except ModuleNotFoundError:pass```-````{.python.marimo hide_code="true"}+````python {.marimo hide_code="true"}tips = {"Use global variables sparingly": ("""@@ -456,6 +456,6 @@ tips = {}````-```{.python.marimo}+```python {.marimo}import marimo as mo```\ No newline at end of filediff --git a/tests/_cli/snapshots/export_markdown_with_errors.txt b/tests/_cli/snapshots/export_markdown_with_errors.txtindex e7542d5d64..8ffd58552a 100644--- a/tests/_cli/snapshots/export_markdown_with_errors.txt+++ b/tests/_cli/snapshots/export_markdown_with_errors.txt@@ -3,14 +3,14 @@ title: Notebookmarimo-version: 0.0.0----```{.python.marimo}+```python {.marimo}import marimo as mo```-```{.python.marimo}+```python {.marimo}slider = mo.ui.slider(0, 10)```-```{.python.marimo}+```python {.marimo}1 / 0```diff --git a/tests/_cli/snapshots/frontmatter-only.py.txt b/tests/_cli/snapshots/frontmatter-only.py.txtnew file mode 100644index 0000000000..59bff4f87b--- /dev/null+++ b/tests/_cli/snapshots/frontmatter-only.py.txt@@ -0,0 +1,11 @@+import marimo++__generated_with = "0.0.0"+app = marimo.App(app_title="My Title")++++++if __name__ == "__main__":+ app.run()\ No newline at end of filediff --git a/tests/_cli/snapshots/frontmatter-test.py.txt b/tests/_cli/snapshots/frontmatter-test.py.txtindex bac7c77ccf..8f9d6c934b 100644--- a/tests/_cli/snapshots/frontmatter-test.py.txt+++ b/tests/_cli/snapshots/frontmatter-test.py.txt@@ -4,7 +4,7 @@ __generated_with = "0.0.0"app = marimo.App(app_title="My Title")[email protected](hide_code=True)def _(mo):mo.md(r"""diff --git a/tests/_cli/snapshots/marimo_for_jupyter_users.md.txt b/tests/_cli/snapshots/marimo_for_jupyter_users.md.txtindex ec2c2cccf5..267908f569 100644--- a/tests/_cli/snapshots/marimo_for_jupyter_users.md.txt+++ b/tests/_cli/snapshots/marimo_for_jupyter_users.md.txt@@ -14,11 +14,11 @@ The biggest difference between marimo and Jupyter is *reactive execution*.Try updating the value of x in the next cell, then run it.-```{.python.marimo}+```python {.marimo}x = 0; x```-```{.python.marimo}+```python {.marimo}y = x + 1; y```@@ -48,16 +48,16 @@ This makes marimo notebooks as reproducible as regular Python scripts.marimo comes with a [large library of UI elements](https://docs.marimo.io/guides/interactivity.html) that are automaticallysynchronized with Python.-```{.python.marimo}+```python {.marimo}import marimo as mo```-```{.python.marimo}+```python {.marimo}slider = mo.ui.slider(start=1, stop=10, label="$x$")slider```-```{.python.marimo}+```python {.marimo}slider.value```@@ -86,11 +86,11 @@ for both Jupyter and Streamlit.In marimo, cells can be arranged in any order — marimo figures out the one true way to execute them based on variable declarations and references (in a ["topologically sorted"](https://en.wikipedia.org/wiki/Topological_sorting#:~:text=In%20computer%20science%2C%20a%20topological,before%20v%20in%20the%20ordering.) order)-```{.python.marimo}+```python {.marimo}z.value```-```{.python.marimo}+```python {.marimo}z = mo.ui.slider(1, 10, label="$z$"); z```@@ -102,15 +102,15 @@ In contrast, Jupyter notebooks implicitly assume a top-to-bottom execution ordermarimo disallows variable re-assignment. Here is something commonly done in Jupyter notebooks that cannot be done in marimo:-```{.python.marimo}+```python {.marimo}df = 0```-```{.python.marimo}+```python {.marimo}df = 1```-```{.python.marimo}+```python {.marimo}results = df.groupby(["my_column"]).sum()```@@ -126,7 +126,7 @@ If you run into this error, here are your options:marimo only has Python cells, but you can still write Markdown: `import marimo as mo` and use `mo.md` to write Markdown.-```{.python.marimo}+```python {.marimo}mo.md(f"""The value of {slider} is {slider.value}.diff --git a/tests/_cli/snapshots/markdown.txt b/tests/_cli/snapshots/markdown.txtindex 24ce211de7..c47f1ed46a 100644--- a/tests/_cli/snapshots/markdown.txt+++ b/tests/_cli/snapshots/markdown.txt@@ -3,10 +3,10 @@ title: Notebookmarimo-version: 0.0.0----```{.python.marimo}+```python {.marimo}import marimo as mo```-```{.python.marimo}+```python {.marimo}slider = mo.ui.slider(0, 10)```diff --git a/tests/_cli/snapshots/markdown_to_marimo.txt b/tests/_cli/snapshots/markdown_to_marimo.txtindex c876da843f..5d452464f1 100644--- a/tests/_cli/snapshots/markdown_to_marimo.txt+++ b/tests/_cli/snapshots/markdown_to_marimo.txt@@ -4,7 +4,7 @@ import marimoapp = marimo.App()[email protected](hide_code=True)def _(mo):mo.md(r"""diff --git a/tests/_cli/snapshots/no-frontmatter.py.txt b/tests/_cli/snapshots/no-frontmatter.py.txtnew file mode 100644index 0000000000..d33114d915--- /dev/null+++ b/tests/_cli/snapshots/no-frontmatter.py.txt@@ -0,0 +1,35 @@+import marimo++__generated_with = "0.0.0"+app = marimo.App()++[email protected](hide_code=True)+def _(mo):+ mo.md(+ r"""+ # My Notebook+ """+ )+ return+++def _():+ print("Hello, World!")+ return++[email protected](hide_code=True)+def _(mo):+ mo.md(+ r"""+ **Appendix**+ - This is the end of the notebook+ """+ )+ return+++if __name__ == "__main__":+ app.run()\ No newline at end of filediff --git a/tests/_cli/snapshots/sql-notebook.py.txt b/tests/_cli/snapshots/sql-notebook.py.txtnew file mode 100644index 0000000000..36460f2943--- /dev/null+++ b/tests/_cli/snapshots/sql-notebook.py.txt@@ -0,0 +1,34 @@+import marimo++__generated_with = "0.0.0"+app = marimo.App(app_title="My Title")++[email protected](hide_code=True)+def _(mo):+ mo.md(+ r"""+ # SQL notebook+ """+ )+ return+++def _(mo, my_table):+ export = mo.sql(+ f"""+ SELECT * FROM my_table;+ """+ )+ return (export,)+++def _(export, mo):+ _df = mo.sql("SELECT * FROM export;")+ return+++if __name__ == "__main__":+ app.run()\ No newline at end of filediff --git a/tests/_cli/snapshots/sql.md.txt b/tests/_cli/snapshots/sql.md.txtnew file mode 100644index 0000000000..5dd2969687--- /dev/null+++ b/tests/_cli/snapshots/sql.md.txt@@ -0,0 +1,304 @@+---+title: Sql+marimo-version: 0.0.0+---++# Hello, SQL!++_Let's dive into the world of SQL where we don't just address tables, we also join them!_+<!---->+With marimo, you can mix-and-match both **Python and SQL**. To create a+SQL cell, you first need to install some additional dependencies,+including [duckdb](https://duckdb.org/). Obtain these dependencies with++```bash+pip install 'marimo[sql]'+```++```python {.marimo hide_code="true"}+has_duckdb_installed = False+try:+ import duckdb++ has_duckdb_installed = True+except ImportError:+ pass++has_polars_installed = False+try:+ import polars++ has_polars_installed = True+except ImportError:+ pass++has_pandas_installed = False+try:+ import pandas++ has_pandas_installed = True+except ImportError:+ pass+```++```python {.marimo hide_code="true"}+if has_duckdb_installed:+ mo.output.replace(+ mo.md(+ """+ !!! Tip "Installed"+ If you see this, DuckDB is already installed.+ """+ )+ )+else:+ mo.output.replace(+ mo.md(+ """+ !!! Warning "Not Installed"+ If you see this, DuckDB is not installed.+ """+ )+ )+```++Once the required dependencies are installed, you can create SQL cells+by either right clicking the **Add Cell** buttons on the left of a+cell, or click the **Add SQL Cell** at the bottom of the page.++marimo is still just Python, even when using SQL. Here is an example of+how marimo embeds SQL in Python in its file format:++```python+output_df = mo.sql(f"SELECT * FROM my_table LIMIT {max_rows.value}")+```++Notice that we have an **`output_df`** variable in the cell. This is a+resulting Polars DataFrame (if you have `polars` installed) or a Pandas+DataFrame (if you don't). One of them must be installed in order to+interact with the SQL result.++The SQL statement itself is an formatted string (f-string), so this+means they can contain any valid Python code, such as the values of UI+elements. This means your SQL statement and results can be reactive! 🚀+<!---->+## Querying dataframes with SQL+<!---->+Let's take a look at a SQL cell. The next cell generates a dataframe called `df`.++```python {.marimo hide_code="true"}+_SIZE = 1000+++def _create_token_data(n_items=100):+ import random+ import string++ def generate_random_string(length):+ letters = string.ascii_lowercase+ result_str = "".join(random.choice(letters) for i in range(length))+ return result_str++ def generate_random_numbers(mean, std_dev, num_samples):+ return [int(random.gauss(mean, std_dev)) for _ in range(num_samples)]++ random_numbers = generate_random_numbers(50, 15, n_items)+ random_strings = sorted(+ list(set([generate_random_string(3) for _ in range(n_items)]))+ )++ return {+ "token": random_strings,+ "count": random_numbers[: len(random_strings)],+ }+++_data = _create_token_data(_SIZE)++# Try polars+if has_polars_installed:+ import polars as pl++ df = pl.DataFrame(_data)+# Fallback to pandas (maybe trying to install it)+else:+ import pandas as pd++ df = pd.DataFrame(_data)+```++Next, we create a SQL query, refercing the Python dataframe `df` directly.++```sql {.marimo}+-- This SQL cell is special since we can reference existing dataframes in the global scope as a table in the SQL query. For example, we can reference the `df` dataframe in the global scope, which was defined in another cell using Python.++SELECT * FROM df;++-- By default, the output variable starts with an underscore (`_df`), making it private to this cell. To access the query result in another cell, change the name of the output variable.+```++## From Python to SQL and back+<!---->+You can create SQL statements that depend on Python values, such as UI elements:++```python {.marimo hide_code="true"}+token_prefix = mo.ui.dropdown(+ list(string.ascii_lowercase), label="token prefix", value="a"+)+token_prefix+```++```sql {.marimo query="result"}+-- Change the dropdown to see the SQL query filter itself!+--+-- Here we use a duckdb function called `starts_with`:+SELECT * FROM df WHERE starts_with(token, '{token_prefix.value}')++-- Notice that we named the output variable `result`+```++Since we named the output variable above **`result`**,+we can use it back in Python.++```python {.marimo hide_code="true"}+charting_library = mo.ui.radio(["matplotlib", "altair", "plotly"])++mo.md(+ f"""+ Let's chart the result with a library of your choice:++ {charting_library}+ """+)+```++```python {.marimo hide_code="true"}+_header = mo.md(+ f"""+ We can re-use the dropdown from above: {token_prefix}++ Now we have a histogram visualizing the token count distribution of tokens starting+ with {token_prefix.value}, powered by your SQL query and UI element.+ """+)++render_chart(+ charting_library.value, _header+) if charting_library.value else None+```++```python {.marimo hide_code="true"}+def render_chart(charting_library, header):+ return mo.vstack(+ [header, render_charting_library(charting_library)]+ ).center()+++def render_charting_library(charting_library):+ if charting_library == "matplotlib":+ return render_matplotlib()+ if charting_library == "altair":+ return render_altair()+ if charting_library == "plotly":+ return render_plotly()+++def render_matplotlib():+ import matplotlib.pyplot as plt++ plt.hist(result["count"], label=token_prefix.value)+ plt.xlabel("token count")+ plt.legend()+ plt.tight_layout()+ return plt.gcf()+++def render_altair():+ import altair as alt++ chart = (+ alt.Chart(result)+ .mark_bar()+ .encode(x=alt.X("count", bin=True), y=alt.Y("count()"))+ )+ return mo.ui.altair_chart(chart, chart_selection=False)+++def render_plotly():+ import plotly.graph_objects as go++ return go.Figure(data=[go.Histogram(x=result["count"])])+```++## CSVs, Parquet, Postgres, and more ...+<!---->+We're not limited to querying dataframes. We can also query an **HTTP URL, S3 path, or a file path to a local csv or parquet file**.++```sql+-- or+SELECT * FROM 's3://my-bucket/file.parquet';+-- or+SELECT * FROM read_csv('path/to/example.csv');+-- or+SELECT * FROM read_parquet('path/to/example.parquet');+```++With a bit of boilerplate, you can even read and write to **Postgres**, and join Postgres tables with dataframes in the same query. For a full list of supported data sources, check out the [duckdb extensions](https://duckdb.org/docs/extensions/overview) and our [example notebook on duckdb connections](https://github.com/marimo-team/marimo/blob/main/examples/sql/duckdb_connections.**py**).++For this example, we will query an HTTP endpoint of a csv.++```sql {.marimo query="cars"}+-- Download a CSV and create an in-memory table; this is optional.+CREATE OR replace TABLE cars as+FROM 'https://datasets.marimo.app/cars.csv';++-- Query the table+SELECT * from cars;+```++!!! Tip "Data sources panel"+ Click the database "barrel" icon in the left toolbar to see all dataframes and in-+ memory tables that you're notebook has access to.++```python {.marimo hide_code="true"}+cylinders_dropdown = mo.ui.range_slider.from_series(+ cars["Cylinders"], debounce=True, show_value=True+)+origin_dropdown = mo.ui.dropdown.from_series(cars["Origin"], value="Asia")+mo.hstack([cylinders_dropdown, origin_dropdown]).left()+```++```sql {.marimo query="filtered_cars"}+SELECT * FROM cars+WHERE+ Cylinders >= {cylinders_dropdown.value[0]}+ AND+ Cylinders <= {cylinders_dropdown.value[1]}+ AND+ ORIGIN = '{origin_dropdown.value}'+```++```python {.marimo hide_code="true"}+mo.hstack(+ [+ mo.stat(label="Total cars", value=str(len(filtered_cars))),+ mo.stat(+ label="Average MPG Highway",+ value=f"{filtered_cars['MPG_Highway'].mean() or 0:.1f}",+ ),+ mo.stat(+ label="Average MPG City",+ value=f"{filtered_cars['MPG_City'].mean() or 0:.1f}",+ ),+ ]+)+```++```python {.marimo hide_code="true"}+import marimo as mo+import random+```++```python {.marimo hide_code="true"}+import string+```\ No newline at end of filediff --git a/tests/_cli/snapshots/unsafe-app.md.txt b/tests/_cli/snapshots/unsafe-app.md.txtindex 6bf55e98aa..6027c670db 100644--- a/tests/_cli/snapshots/unsafe-app.md.txt+++ b/tests/_cli/snapshots/unsafe-app.md.txt@@ -3,11 +3,11 @@ title: Test Notebookmarimo-version: 0.0.0----```{.python.marimo}+```python {.marimo}import marimo as mo```-````{.python.marimo}+````python {.marimo}mo.md("""# Code blocks in code blocksOutput code for Hello World!@@ -15,25 +15,25 @@ mo.md("""print("Hello World")```Execute print- ```{python}+ ```python {.marimo}print("Hello World")```""")````-````{.python.marimo}+````python {.marimo}mo.md(f"""with f-string too!- ```{{python}}+ ```python {{.marimo}}print("Hello World")```""")````-````{.python.marimo}+````python {.marimo}mo.md(f"""Not markdown- ```{{python}}+ ```python {{.marimo}}print("1 + 1 = {1 + 1}")```""")@@ -42,27 +42,27 @@ mo.md(f"""Nested fence````textThe guards are-```{python}+```python {.marimo}````-````{.python.marimo}+````python {.marimo}"""```"""````-````{.python.marimo}+````python {.marimo}mo.md("""Cross cell injection```python""")````-```{.python.marimo}+```python {.marimo}1 + 1```-```{.python.marimo}+```python {.marimo}# Actual printprint("Hello World")```\ No newline at end of filediff --git a/tests/_cli/snapshots/unsafe-app.py.txt b/tests/_cli/snapshots/unsafe-app.py.txtindex 69787965fe..774cfc76ee 100644--- a/tests/_cli/snapshots/unsafe-app.py.txt+++ b/tests/_cli/snapshots/unsafe-app.py.txt@@ -19,7 +19,7 @@ def _(mo):print("Hello World")```Execute print- ```{python}+ ```python {.marimo}print("Hello World")```""")@@ -30,7 +30,7 @@ def _(mo):def _(mo):mo.md(f"""with f-string too!- ```{{python}}+ ```python {{.marimo}}print("Hello World")```""")@@ -41,21 +41,21 @@ def _(mo):def _(mo):mo.md(f"""Not markdown- ```{{python}}+ ```python {{.marimo}}print("1 + 1 = {1 + 1}")```""")return[email protected](hide_code=True)def _(mo):mo.md(r"""Nested fence````textThe guards are- ```{python}+ ```python {.marimo}````""")diff --git a/tests/_cli/snapshots/unsafe-doc-old.md.txt b/tests/_cli/snapshots/unsafe-doc-old.md.txtnew file mode 100644index 0000000000..b4f3d85b80--- /dev/null+++ b/tests/_cli/snapshots/unsafe-doc-old.md.txt@@ -0,0 +1,76 @@+---+title: Casually malicious md+marimo-version: 0.0.0+---++What happens if I just leave a \"\"\"+" ' ! @ # $ % ^ & * ( ) + = - _ [ ] { } | \ /++# Notebook+<!--+\++```python {.marimo}+print("Hello, World!")+```++-->++```marimo run convert document.md```++```python {.marimo unparsable="true"}+it's an unparsable cell+```++<!-- Actually markdown -->+```{python} `+ print("Hello, World!")++<!-- Disabled code block -->++```python {.marimo disabled="true"}+1 + 1+```++<!-- Hidden code block -->++```python {.marimo hide_code="true"}+1 + 1+```++<!-- Empty code block -->++```python {.marimo}++```++<!-- Improperly nested code block -->++````python {.marimo unparsable="true"}+"""+```{python}+print("Hello, World!")+````++\"\"\"+```++<!-- Improperly nested code block -->+```{python}+````{python}+print("Hello, World!")+````+```++-->++<!-- from the notebook, should remain unchanged -->++````python {.marimo}+mo.md("""+ This is a markdown cell with an execution block in it+ ```{python}+ # To ambiguous to convert+ ```+ """)+````\ No newline at end of filediff --git a/tests/_cli/snapshots/unsafe-doc-old.py.txt b/tests/_cli/snapshots/unsafe-doc-old.py.txtnew file mode 100644index 0000000000..53cc9b8037--- /dev/null+++ b/tests/_cli/snapshots/unsafe-doc-old.py.txt@@ -0,0 +1,153 @@+import marimo++__generated_with = "0.0.0"+app = marimo.App(app_title="Casually malicious md")++[email protected](hide_code=True)+def _(mo):+ mo.md(+ r"""+ What happens if I just leave a \"\"\"+ " ' ! @ # $ % ^ & * ( ) + = - _ [ ] { } | \ /++ # Notebook+ <!--+ \+ """+ )+ return+++def _():+ print("Hello, World!")+ return++[email protected](hide_code=True)+def _(mo):+ mo.md(+ r"""+ -->++ ```marimo run convert document.md```+ """+ )+ return+++app._unparsable_cell(+ r"""+ it's an unparsable cell+ """,+ name="_"+)++[email protected](hide_code=True)+def _(mo):+ mo.md(+ r"""+ <!-- Actually markdown -->+ ```{python} `+ print("Hello, World!")++ <!-- Disabled code block -->+ """+ )+ return++[email protected](disabled=True)+def _():+ 1 + 1+ return++[email protected](hide_code=True)+def _(mo):+ mo.md(+ r"""+ <!-- Hidden code block -->+ """+ )+ return++[email protected](hide_code=True)+def _():+ 1 + 1+ return++[email protected](hide_code=True)+def _(mo):+ mo.md(+ r"""+ <!-- Empty code block -->+ """+ )+ return+++def _():+ return++[email protected](hide_code=True)+def _(mo):+ mo.md(+ r"""+ <!-- Improperly nested code block -->+ """+ )+ return+++app._unparsable_cell(+ r"""+ \"\"\"+ ```{python}+ print(\"Hello, World!\")+ """,+ name="_"+)++[email protected](hide_code=True)+def _(mo):+ mo.md(+ r"""+ \"\"\"+ ```++ <!-- Improperly nested code block -->+ ```{python}+ ````{python}+ print("Hello, World!")+ ````+ ```++ -->++ <!-- from the notebook, should remain unchanged -->+ """+ )+ return+++def _(mo):+ mo.md("""+ This is a markdown cell with an execution block in it+ ```{python}+ # To ambiguous to convert+ ```+ """)+ return+++if __name__ == "__main__":+ app.run()\ No newline at end of filediff --git a/tests/_cli/snapshots/unsafe-doc.md.txt b/tests/_cli/snapshots/unsafe-doc.md.txtindex 111f85afc8..dbfb360351 100644--- a/tests/_cli/snapshots/unsafe-doc.md.txt+++ b/tests/_cli/snapshots/unsafe-doc.md.txt@@ -10,7 +10,7 @@ What happens if I just leave a \"\"\"<!--\-```{.python.marimo}+```python {.marimo}print("Hello, World!")```@@ -18,37 +18,37 @@ print("Hello, World!")```marimo run convert document.md```-```{.python.marimo unparsable="true"}+```python {.marimo unparsable="true"}it's an unparsable cell```<!-- Actually markdown -->-```{python} `+```python {.marimo} `print("Hello, World!")<!-- Disabled code block -->-```{.python.marimo disabled="true"}+```python {.marimo disabled="true"}1 + 1```<!-- Hidden code block -->-```{.python.marimo hide_code="true"}+```python {.marimo hide_code="true"}1 + 1```<!-- Empty code block -->-```{.python.marimo}+```python {.marimo}```<!-- Improperly nested code block -->-````{.python.marimo unparsable="true"}+````python {.marimo unparsable="true"}"""-```{python}+```python {.marimo}print("Hello, World!")````@@ -56,8 +56,8 @@ print("Hello, World!")```<!-- Improperly nested code block -->-```{python}-````{python}+```python {.marimo}+````python {.marimo}print("Hello, World!")```````@@ -66,15 +66,11 @@ print("Hello, World!")<!-- from the notebook, should remain unchanged -->-````{.python.marimo}+````python {.marimo}mo.md("""This is a markdown cell with an execution block in it- ```{python}+ ```python {.marimo}# To ambiguous to convert```""")-````--```{.python.marimo}--```\ No newline at end of file+````\ No newline at end of filediff --git a/tests/_cli/snapshots/unsafe-doc.py.txt b/tests/_cli/snapshots/unsafe-doc.py.txtindex 69a880c9cb..402ca8af4c 100644--- a/tests/_cli/snapshots/unsafe-doc.py.txt+++ b/tests/_cli/snapshots/unsafe-doc.py.txt@@ -4,7 +4,7 @@ __generated_with = "0.0.0"app = marimo.App(app_title="Casually malicious md")[email protected](hide_code=True)def _(mo):mo.md(r"""@@ -25,7 +25,7 @@ def _():return[email protected](hide_code=True)def _(mo):mo.md(r"""@@ -45,12 +45,12 @@ app._unparsable_cell()[email protected](hide_code=True)def _(mo):mo.md(r"""<!-- Actually markdown -->- ```{python} `+ ```python {.marimo} `print("Hello, World!")<!-- Disabled code block -->@@ -65,7 +65,7 @@ def _():return[email protected](hide_code=True)def _(mo):mo.md(r"""@@ -81,7 +81,7 @@ def _():return[email protected](hide_code=True)def _(mo):mo.md(r"""@@ -96,7 +96,7 @@ def _():return[email protected](hide_code=True)def _(mo):mo.md(r"""@@ -109,14 +109,14 @@ def _(mo):app._unparsable_cell(r"""\"\"\"- ```{python}+ ```python {.marimo}print(\"Hello, World!\")""",name="_")[email protected](hide_code=True)def _(mo):mo.md(r"""@@ -124,8 +124,8 @@ def _(mo):```<!-- Improperly nested code block -->- ```{python}- ````{python}+ ```python {.marimo}+ ````python {.marimo}print("Hello, World!")```````@@ -142,17 +142,12 @@ def _(mo):def _(mo):mo.md("""This is a markdown cell with an execution block in it- ```{python}+ ```python {.marimo}# To ambiguous to convert```""")return-def _():- return--if __name__ == "__main__":app.run()\ No newline at end of filediff --git a/tests/_cli/test_markdown_conversion.py b/tests/_cli/test_markdown_conversion.pyindex c119229573..03ca9bfd14 100644--- a/tests/_cli/test_markdown_conversion.py+++ b/tests/_cli/test_markdown_conversion.py@@ -10,18 +10,23 @@ from textwrap import dedentimport pytestfrom marimo import __version__-from marimo._cli.convert.markdown import convert_from_md+from marimo._ast.app import InternalApp+from marimo._cli.convert.markdown import (+ convert_from_md,+ convert_from_md_to_app,+)from marimo._server.export import export_as_mdfrom marimo._server.export.utils import format_filename_title# Just a handful of scripts to test-from marimo._tutorials import dataflow, for_jupyter_users+from marimo._tutorials import dataflow, for_jupyter_users, sqlfrom marimo._utils.marimo_path import MarimoPathfrom tests.mocks import snapshottermodules = {"marimo_for_jupyter_users": for_jupyter_users,"dataflow": dataflow,+ "sql": sql,}DIR_PATH = os.path.dirname(os.path.realpath(__file__))@@ -81,7 +86,8 @@ def test_idempotent_markdown_to_marimo() -> None:def test_markdown_frontmatter() -> None:script = dedent(- """+ remove_empty_lines(+ """---title: "My Title"description: "My Description"@@ -93,19 +99,61 @@ def test_markdown_frontmatter() -> None:# Notebook- ```{.python.marimo}+ ```python {.marimo}print("Hello, World!")```- """[1:]+ """+ ))- output = convert_from_md(script)++ # As python file+ output = sanitized_version(convert_from_md(script))assert 'app_title="My Title"' in outputsnapshot("frontmatter-test.py.txt", output)+ # As python object+ app = InternalApp(convert_from_md_to_app(script))+ assert app.config.app_title == "My Title"+ ids = list(app.cell_manager.cell_ids())+ assert len(ids) == 2+ assert app.cell_manager.cell_data_at(ids[0]).code.startswith("mo.md")+ assert app.cell_manager.cell_data_at(ids[0]).config.hide_code is True+ assert (+ app.cell_manager.cell_data_at(ids[1]).code == 'print("Hello, World!")'+ )+ assert app.cell_manager.cell_data_at(ids[1]).config.hide_code is False+++def test_no_frontmatter() -> None:+ script = dedent(+ remove_empty_lines(+ """+ # My Notebook++ ```python {.marimo}+ print("Hello, World!")+ ```++ **Appendix**+ - This is the end of the notebook+ """+ )+ )+ output = sanitized_version(convert_from_md(script))+ snapshot("no-frontmatter.py.txt", output)++ # As python object+ app = InternalApp(convert_from_md_to_app(script))+ # TODO: Ideally extract notebook title.+ # i.e. assert app.config.app_title == "My Notebook"+ ids = list(app.cell_manager.cell_ids())+ assert len(ids) == 3+def test_markdown_just_frontmatter() -> None:script = dedent(- """+ remove_empty_lines(+ """---title: "My Title"description: "My Description"@@ -114,19 +162,76 @@ def test_markdown_just_frontmatter() -> None:- name: "filter1"- name: "filter2"---- """[1:]++ """+ ))output = sanitized_version(convert_from_md(script))assert 'app_title="My Title"' in output+ snapshot("frontmatter-only.py.txt", output)++ # As python object+ app = InternalApp(convert_from_md_to_app(script))+ assert app.config.app_title == "My Title"+ ids = list(app.cell_manager.cell_ids())+ assert len(ids) == 1+ assert app.cell_manager.cell_data_at(ids[0]).code == ""+++def test_markdown_with_sql() -> None:+ script = dedent(+ remove_empty_lines(+ """+ ---+ title: "My Title"+ description: "My Description"+ tags: ["tag1", "tag2"]+ filters:+ - name: "filter1"+ - name: "filter2"+ ---++ # SQL notebook++ ```sql {.marimo query="export"}+ SELECT * FROM my_table;+ ```++ ```python {.marimo}+ _df = mo.sql("SELECT * FROM export;")+ ```+ """+ )+ )+ output = sanitized_version(convert_from_md(script))+ snapshot("sql-notebook.py.txt", output)++ # As python object+ app = InternalApp(convert_from_md_to_app(script))+ assert app.config.app_title == "My Title"+ ids = list(app.cell_manager.cell_ids())+ assert len(ids) == 3+ for i in range(3):+ # Unparsables are None+ assert app.cell_manager.cell_data_at(ids[i]).cell is not None+ assert app.cell_manager.cell_data_at(ids[1]).cell.defs == {"export"}def test_markdown_empty() -> None:assert convert_from_md("") == ""+ # As python object+ app = InternalApp(convert_from_md_to_app(""))+ assert app.config.app_title is None+ ids = list(app.cell_manager.cell_ids())+ assert len(ids) == 1+ assert app.cell_manager.cell_data_at(ids[0]).code == ""+def test_python_to_md_code_injection() -> None:unsafe_app = dedent(- """+ remove_empty_lines(+ """import marimo__generated_with = "0.0.0"app = marimo.App()@@ -143,7 +248,7 @@ def test_python_to_md_code_injection() -> None:print("Hello World")```Execute print- ```{python}+ ```python {.marimo}print("Hello World")```\""")@@ -152,7 +257,7 @@ def test_python_to_md_code_injection() -> None:def __(mo):mo.md(f\"""with f-string too!- ```{{python}}+ ```python {{.marimo}}print("Hello World")```\""")@@ -161,7 +266,7 @@ def test_python_to_md_code_injection() -> None:def __(mo):mo.md(f\"""Not markdown- ```{{python}}+ ```python {{.marimo}}print("1 + 1 = {1 + 1}")```\""")@@ -172,7 +277,7 @@ def test_python_to_md_code_injection() -> None:Nested fence````textThe guards are- ```{python}+ ```python {.marimo}````\""")return@@ -205,7 +310,8 @@ def test_python_to_md_code_injection() -> None:returnif __name__ == "__main__":app.run()- """[1:]+ """+ ))maybe_unsafe_md = convert_from_py(unsafe_app).strip()maybe_unsafe_py = convert_from_md(maybe_unsafe_md).strip()@@ -223,9 +329,10 @@ def test_python_to_md_code_injection() -> None:)-def test_md_to_python_code_injection() -> None:+def test_old_md_to_python_code_injection() -> None:script = dedent(- """+ remove_empty_lines(+ """---title: "Casually malicious md"---@@ -293,7 +400,95 @@ def test_md_to_python_code_injection() -> None:\""")````- """[1:]+ """+ )+ )++ maybe_unsafe_py = sanitized_version(convert_from_md(script).strip())+ maybe_unsafe_md = convert_from_py(maybe_unsafe_py)++ # Idempotent even under strange conditions.+ assert maybe_unsafe_py == sanitized_version(+ convert_from_md(maybe_unsafe_md).strip()+ )++ snapshot("unsafe-doc-old.py.txt", maybe_unsafe_py)+ snapshot("unsafe-doc-old.md.txt", maybe_unsafe_md)+++def test_md_to_python_code_injection() -> None:+ script = dedent(+ remove_empty_lines(+ """+ ---+ title: "Casually malicious md"+ ---++ What happens if I just leave a \"""+ " ' ! @ # $ % ^ & * ( ) + = - _ [ ] { } | \\ /++ # Notebook+ <!--+ \\+ ```python {.marimo}+ print("Hello, World!")+ ```+ -->++ ```marimo run convert document.md```++ ```python {.marimo}+ it's an unparsable cell+ ```++ <!-- Actually markdown -->+ ```python {.marimo} `+ print("Hello, World!")++ <!-- Disabled code block -->+ ```python {.marimo disabled="true"}+ 1 + 1+ ```++ <!-- Hidden code block -->+ ```python {.marimo hide_code="true"}+ 1 + 1+ ```++ <!-- Empty code block -->+ ```python {.marimo}+ ```++ <!-- Improperly nested code block -->+ ```python {.marimo}+ \"""+ ```python {.marimo}+ print("Hello, World!")+ ```+ \"""+ ```++ <!-- Improperly nested code block -->+ ```python {.marimo}+ ````python {.marimo}+ print("Hello, World!")+ ````+ ```++ -->++ <!-- from the notebook, should remain unchanged -->+ ````python {.marimo}+ mo.md(\"""+ This is a markdown cell with an execution block in it+ ```python {.marimo}+ # To ambiguous to convert+ ```+ \""")+ ````++ """+ ))maybe_unsafe_py = sanitized_version(convert_from_md(script).strip())@@ -306,3 +501,13 @@ def test_md_to_python_code_injection() -> None:snapshot("unsafe-doc.py.txt", maybe_unsafe_py)snapshot("unsafe-doc.md.txt", maybe_unsafe_md)+++def remove_empty_lines(s: str) -> str:+ "Just remove the first and last lines if they are empty"+ lines = s.splitlines()+ if not lines[0].strip():+ lines = lines[1:]+ if not lines[-1].strip():+ lines = lines[:-1]+ return "\n".join(lines)diff --git a/tests/_server/api/endpoints/test_export.py b/tests/_server/api/endpoints/test_export.pyindex 1a8b7c387e..33fe49c7fe 100644--- a/tests/_server/api/endpoints/test_export.py+++ b/tests/_server/api/endpoints/test_export.py@@ -164,7 +164,7 @@ def test_export_markdown(client: TestClient) -> None:)assert response.status_code == 200assert f"marimo-version: {__version__}" in response.text- assert "```{.python.marimo}" in response.text+ assert "```python {.marimo}" in response.text@with_read_session(SESSION_ID)diff --git a/tests/conftest.py b/tests/conftest.pyindex f4f7fbc1a4..38e014a26d 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -438,6 +438,39 @@ def temp_marimo_file_with_md() -> Generator[str, None, None]:@pytest.fixturedef temp_md_marimo_file() -> Generator[str, None, None]:+ tmp_dir = TemporaryDirectory()+ tmp_file = os.path.join(tmp_dir.name, "notebook.md")+ content = inspect.cleandoc(+ """+ ---+ title: Notebook+ marimo-version: 0.0.0+ ---++ # This is a markdown document.+ <!---->+ This is a another cell.++ ```python {.marimo}+ import marimo as mo+ ```++ ```python {.marimo}+ slider = mo.ui.slider(0, 10)+ ```+ """+ )++ try:+ with open(tmp_file, "w") as f:+ f.write(content)+ yield tmp_file+ finally:+ tmp_dir.cleanup()+++def old_temp_md_marimo_file() -> Generator[str, None, None]:tmp_dir = TemporaryDirectory()tmp_file = os.path.join(tmp_dir.name, "notebook.md")content = inspect.cleandoc(