### Complete Analysis Document Setup (YAML) Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/09-code-examples.md Set up a complete analysis document with Marimo, including project title, format, engine, and Python dependencies. This example defines requirements for Marimo, Pandas, and Plotly. ```yaml --- title: Sales Dashboard subtitle: Interactive analysis with marimo format: html engine: marimo pyproject: | requires-python = ">=3.11" dependencies = [ "marimo>=0.23.1", "pandas>=2.0", "plotly", ] --- # Sales Dashboard This dashboard analyzes Q4 sales performance. ```{python .marimo} #| include: false import pandas as pd import plotly.express as px import marimo as mo # Load data df = pd.read_csv("sales.csv") ``` ``` -------------------------------- ### Install Development Environment Source: https://github.com/marimo-team/quarto-marimo/blob/main/CONTRIBUTING.md Installs all Python and system dependencies using pixi. This command sets up the isolated development environment. ```bash pixi install ``` -------------------------------- ### Code Examples Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/COMPLETION_REPORT.txt A collection of over 25 code examples demonstrating various features and workflows. ```APIDOC ## Code Examples ### Categories - Basic setup and dependencies - Interactive widgets - Data analysis workflows - SQL queries - Error handling - Advanced patterns - Multi-format output - Performance optimization ### Example Snippets [Code blocks demonstrating specific features and workflows] ``` -------------------------------- ### Example Input for Command Script Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/03-command-python.md Sample content for the dependency header file, specifying Python dependencies. ```bash dependencies = ["pandas"] ``` -------------------------------- ### Document Function with Live Marimo Example Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/09-code-examples.md Demonstrates documenting a Python function with a docstring and providing a live, executable example within a Marimo notebook. This allows users to see the function's behavior with sample input. ```python import marimo as mo def process_data(x): """Process data.""" return x * 2 # Example example_input = [1, 2, 3] example_output = [process_data(x) for x in example_input] mo.md(f"Input: {example_input}\nOutput: {example_output}") ``` -------------------------------- ### Marimo Cell Configuration Example Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/06-configuration-options.md Demonstrates multiple cell-level configuration options including eval, echo, and basic Marimo markdown output. ```python #| eval: false #| echo: true import marimo as mo mo.md("Hello") ``` -------------------------------- ### TOML Project Format Example Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/03-command-python.md Example of specifying project dependencies using the TOML format, commonly found in `pyproject.toml` files. ```toml [project] requires-python = ">=3.10" dependencies = [ "marimo>=0.23.1", "pandas", ] ``` -------------------------------- ### Example CLI Invocation Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/02-extract-python.md An example of how to invoke the extraction script using uv run. This example sets mime_sensitive to False and eval to True, outputting JSON. ```bash uv run --with marimo extract.py index.qmd no yes # Reads markdown from stdin # mime_sensitive = False (no), eval = True (yes) # Outputs JSON: {"header": "...", "outputs": [...], "count": N} ``` -------------------------------- ### checkInstallation Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/01-marimo-engine-typescript.md Verifies that Marimo is installed, displaying a spinner during the check. ```APIDOC ## checkInstallation ### Description Verifies marimo is installed. Displays a spinner while checking. ### Method ```typescript checkInstallation(): Promise ``` ``` -------------------------------- ### Example of Converted SQL to Marimo Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/08-execution-pipeline.md This is an example of the Python code generated after converting SQL input. It uses `mo.sql` to execute the query within Marimo. ```python _df = mo.sql("SELECT ...", output=False, engine=duckdb) ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/marimo-team/quarto-marimo/blob/main/CONTRIBUTING.md Installs the pre-commit package and configures git hooks to run automatically on commit. This ensures code quality before committing. ```bash pip install pre-commit pre-commit install ``` -------------------------------- ### Minimal Marimo Document Setup Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/09-code-examples.md A basic Quarto document with Marimo engine enabled, containing a single markdown cell. ```yaml --- title: My Marimo Notebook format: html engine: marimo --- # Introduction ```{python .marimo} import marimo as mo mo.md("Hello, marimo!") ``` ``` -------------------------------- ### Start Local Marimo Development Server Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/09-code-examples.md Configure environment variables to run Quarto with a local checkout of Marimo for development. This is essential for frontend debugging and local Marimo development. ```bash # Start with local marimo checkout export QUARTO_MARIMO_DEBUG_ENDPOINT=/marimo-frontend export QUARTO_MARIMO_LOCAL_FRONTEND_ROOT=../marimo quarto preview ``` -------------------------------- ### Example Output from Command Script Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/03-command-python.md The JSON array output generated by the command script, representing parsed dependencies and flags. ```json ["run", "--with", "pandas"] ``` -------------------------------- ### PEP 723 Script Metadata Example Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/03-command-python.md An example of PEP 723 compliant script metadata block within a Python file, specifying Python version and dependencies. ```python # /// script # requires-python = ">=3.10" # dependencies = [ # "marimo>=0.23.1", # "pandas", # "requests>=2.25.0", # ] # /// ``` -------------------------------- ### Invoke Marimo Command with UV Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/03-command-python.md Example of invoking the Marimo command script using `uv run`, piping input from a dependency header file. ```bash uv run --with marimo command.py < dependency_header.txt ``` -------------------------------- ### Hidden Environment Setup in Marimo Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/09-code-examples.md Use `#| include: false` to run setup code, such as setting environment variables or modifying the Python path, without displaying it in the final document. This is useful for configuring the environment for subsequent cells. ```python #| include: false import os import sys os.environ["DEBUG"] = "true" sys.path.insert(0, "/custom/path") # Custom imports from local code from my_module import utilities ``` -------------------------------- ### Generate Multi-Format Output (Web/PDF) Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/09-code-examples.md Use this to create visualizations that render interactively on the web and as static images in PDFs. Ensure Matplotlib is installed. ```python import marimo as mo import matplotlib.pyplot as plt # Create visualization fig, ax = plt.subplots() ax.plot([1, 2, 3], [1, 4, 9]) plt.show() ``` -------------------------------- ### Constructing UV Command for Dependencies Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/08-execution-pipeline.md Builds the command arguments for dependency resolution using uv, based on metadata like 'pyproject'. This example shows how flags are constructed and combined with the extract path. ```typescript const header = 'dependencies = ["pandas"]'; const flags = await constructUvCommand(header); // flags = ["run", "--with", "pandas"] const args = [...flags, extractPath]; // ["run", "--with", "pandas", "extract.py"] ``` -------------------------------- ### Conditional Output Based on Format Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/09-code-examples.md Conditionally render content based on whether the output is for PDF or web. This example checks an environment variable to determine the rendering context. ```python import marimo as mo import os # Check if rendering for PDF is_pdf = os.environ.get("QUARTO_MARIMO_DEBUG_ENDPOINT") == "true" if is_pdf: mo.md("# PDF Version") else: mo.md("# Web Version") ``` -------------------------------- ### Global YAML Settings for Quarto Documents Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/06-configuration-options.md Configure default settings for all Quarto documents in a project using the _quarto.yml file. This example sets external environment usage, specifies Python dependencies via pyproject, and disables cell evaluation by default. ```yaml _quarto.yml: external-env: true pyproject: | dependencies = ["pandas", "numpy"] eval: false ``` -------------------------------- ### Run Unit Tests in Marimo Notebook Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/09-code-examples.md This example shows how to include unit tests within a Marimo notebook. The `include: false` directive ensures tests are run but not displayed to the reader, useful for CI/CD or internal checks. ```python #| include: false def test_calculation(): assert calculate(2, 3) == 5 assert calculate(-1, 1) == 0 test_calculation() mo.md("✅ Tests passed") ``` -------------------------------- ### Example Runtime Error Output Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/07-error-handling.md Demonstrates the format of an error output when a cell raises an exception during execution. The mimetype indicates an error, followed by the exception details. ```text application/vnd.marimo+error ValueError: invalid literal for int(): 'abc' ``` -------------------------------- ### Document Front Matter Configuration Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/06-configuration-options.md Set document-specific options within the YAML front matter of a .qmd or .md file. This example configures the document title, enables external environment usage, defines Python dependencies, sets cell evaluation to true, and specifies HTML format. ```yaml --- title: My Document external-env: true pyproject: | requires-python = ">=3.11" dependencies = ["marimo>=0.23.1", "pandas"] eval: true format: html --- ``` -------------------------------- ### Global Execution Settings (YAML) Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/09-code-examples.md Configure global execution settings for a Marimo document using YAML front matter. This example enables table of contents for HTML output and uses the ambient Python environment. ```yaml --- title: My Project format: html: toc: true engine: marimo external-env: true eval: true --- ``` -------------------------------- ### Class-based Markdown Fence Syntax for Marimo Cells Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/05-types-and-interfaces.md Example of using class-based syntax (preferred) to denote a Marimo cell within markdown fences. ```markdown ```{python .marimo} ``` ``` ```markdown ```{sql .marimo} ``` ``` -------------------------------- ### Enable Ambient Python Environment Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/06-configuration-options.md Configure a document to use the ambient Python environment by setting 'external-env' to true in the YAML front matter. This bypasses the creation of a 'uv' sandbox and ignores 'pyproject' dependencies, requiring Marimo to be installed in the current environment. ```yaml --- external-env: true --- ``` -------------------------------- ### Declare Python Dependencies using PEP 723 Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/06-configuration-options.md Specify Python dependencies for the sandboxed environment using the 'pyproject' option in YAML front matter. This example uses the PEP 723 inline script metadata format to declare required packages and Python version. ```yaml pyproject: | requires-python = ">=3.10" dependencies = [ "marimo>=0.23.1", "pandas", "numpy", "scikit-learn>=1.0.0", ] ``` -------------------------------- ### Declare Python Dependencies using TOML Project Format Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/06-configuration-options.md Specify Python dependencies for the sandboxed environment using the 'pyproject' option in YAML front matter. This example uses the TOML project format to declare required packages and Python version. ```yaml pyproject: | [project] requires-python = ">=3.10" dependencies = [ "marimo>=0.23.1", "pandas>=2.0", ] ``` -------------------------------- ### Create Quarto Project Source: https://github.com/marimo-team/quarto-marimo/blob/main/README.md Use this command to create a new Quarto project. ```bash quarto create project ``` -------------------------------- ### Preview Quarto Project Source: https://github.com/marimo-team/quarto-marimo/blob/main/README.md Use this command to preview your Quarto project with the Marimo extension. ```bash quarto preview ``` ```bash uvx --with marimo --from quarto-cli quarto preview ``` -------------------------------- ### constructUvCommand Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/01-marimo-engine-typescript.md Builds `uv run` arguments from a dependency block. It invokes a Python script to parse the header and return the appropriate uv command arguments. ```APIDOC ## constructUvCommand(header: string): Promise ### Description Builds `uv run` arguments from a dependency block. It invokes a Python script to parse the header and return the appropriate uv command arguments. ### Parameters #### Parameters - **header** (string) - Required - YAML/pyproject dependency block ### Returns Promise — uv command arguments starting with "run" ### Example ```typescript const header = `dependencies = ["pandas", "numpy"]`; const flags = await constructUvCommand(header); // Result: ["run", "--with", "pandas", "--with", "numpy", ...] ``` ``` -------------------------------- ### Handle Parse Errors in Marimo Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/05-types-and-interfaces.md Example of catching a SyntaxError during code addition and appending a _ParseError stub. ```python try: stub = app.add_code("import sys", is_raw=True) except SyntaxError as e: stubs.append((config, _ParseError(f"SyntaxError: {e}"))) ``` -------------------------------- ### Handle Cell Parsing Errors Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/07-error-handling.md Example of catching `SyntaxError` during `app.add_code()`. Errors are logged to stderr and wrapped in `_ParseError`. ```python try: stub = app.add_code("import sys", is_raw=True) except SyntaxError as exc: msg = f"SyntaxError: {exc}" sys.stderr.write(f"marimo: failed to parse cell: {msg}\n") stubs.append((config, _ParseError(msg))) continue ``` -------------------------------- ### Preview with Local Frontend Debug Endpoint Source: https://github.com/marimo-team/quarto-marimo/blob/main/CONTRIBUTING.md Serves the project locally with live reload, using a local frontend build. This is useful for debugging the frontend runtime. ```bash QUARTO_MARIMO_DEBUG_ENDPOINT=/marimo-frontend quarto preview ``` -------------------------------- ### launch Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/01-marimo-engine-typescript.md Returns an engine instance for a specific project, providing methods for file processing and execution. ```APIDOC ## launch ### Description Returns an engine instance for a specific project. The instance has methods for processing and executing Marimo documents. ### Method ```typescript launch(context: EngineProjectContext): ExecutionEngineInstance ``` ### Parameters * **context** (EngineProjectContext) - The project context for the engine. ### Returns An `ExecutionEngineInstance` object with the following methods: #### markdownForFile(file: string): Promise Reads a file as a mapped string for position tracking. #### target(file: string, quiet?: boolean, markdown?: MappedString): Promise Prepares a file for execution by extracting YAML metadata. ##### Parameters * **file** (string) - File path * **quiet** (boolean | undefined) - Suppress output * **markdown** (MappedString | undefined) - Pre-loaded markdown (optional) ##### Returns `ExecutionTarget` containing source, input, markdown, and metadata #### partitionedMarkdown(file: string): Promise Breaks markdown into cells for processing. #### execute(options: ExecuteOptions): Promise Executes all marimo cells in a document. ##### Parameters ```typescript options: { target: ExecutionTarget; format: QuartoFormat; tempDir: string; // ... other Quarto fields } ``` ##### Process 1. Determines output format (html, pdf, latex, typst) 2. Sets `mime_sensitive` flag: true for PDF/LaTeX/typst, false for HTML 3. Reads document metadata (`external-env`, `pyproject`, `eval`) 4. Constructs `uv run` command with dependencies (or uses Python directly if `external-env: true`) 5. Invokes `extract.py` with full markdown via stdin 6. Receives JSON: `{header, outputs, count}` 7. Breaks markdown into cells using `MARIMO_CELL_REGEX` 8. Replaces each marimo cell with rendered output (HTML for web, static for PDF) 9. Returns processed markdown + includes (header injected into `` for HTML) ##### Returns `ExecuteResult` with markdown, supporting files, filters, and includes. ##### Error handling: On failure, returns error message wrapped in a code block, preserving original markdown. #### dependencies(options: DependenciesOptions): Promise Returns build dependencies (unused, returns empty includes). #### postprocess(options: PostProcessOptions): Promise Post-processing hook (no-op). ``` -------------------------------- ### Dot-joined Markdown Fence Syntax for Marimo Cells Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/05-types-and-interfaces.md Example of using dot-joined syntax to denote a Marimo cell within markdown fences. ```markdown ```{python.marimo} ``` ``` ```markdown ```{sql.marimo} ``` ``` -------------------------------- ### init Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/01-marimo-engine-typescript.md Initializes the Marimo engine with the Quarto API. This method must be called before any other engine methods. ```APIDOC ## init ### Description Initializes the engine with Quarto's API. Must be called before any other methods. ### Method ```typescript init(quartoAPI: QuartoAPI): void ``` ### Parameters * **quartoAPI** (QuartoAPI) - The Quarto API object. ``` -------------------------------- ### HTML to Markdown Conversion Function Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/04-utility-modules-typescript.md An example implementation of `htmlToMarkdown` using Quarto's system to convert HTML to markdown via Pandoc. ```typescript async function htmlToMarkdown(html: string): Promise { const result = await quarto.system.pandoc( ["-f", "html", "-t", "markdown"], html ); return result.success ? (result.stdout || "") : html; } ``` -------------------------------- ### Point to Local Marimo Debug Endpoint Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/07-error-handling.md Use the QUARTO_MARIMO_DEBUG_ENDPOINT environment variable to direct Quarto to a local Marimo instance. Execute 'quarto preview' after setting the variable. ```bash export QUARTO_MARIMO_DEBUG_ENDPOINT=http://localhost:5173 quarto preview ``` -------------------------------- ### Hide All Content in Marimo Cell Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/09-code-examples.md Marimo cell configured to run its code but not display either the code or the output, useful for setup or background tasks. ```python #| include: false # Setup that shouldn't appear in document cache = initialize_cache() ``` -------------------------------- ### Build Process for Marimo Engine Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/10-module-graph.md This bash script outlines the build process for the Marimo engine extension, involving compilation steps using esbuild/deno. ```bash make build # → quarto call build-ts-extension # → esbuild/deno compile marimo-engine.ts # → output to marimo-engine.js # → restore from git (maintains committed version) ``` -------------------------------- ### Build Local Islands Bundle Source: https://github.com/marimo-team/quarto-marimo/blob/main/CONTRIBUTING.md Builds the islands bundle in the sibling 'marimo' repository's frontend directory. This is a prerequisite for using a local frontend build. ```bash cd ../marimo/frontend pnpm build:islands ``` -------------------------------- ### Main Entry Point for command.py Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/10-module-graph.md This snippet illustrates the main execution flow for the command.py script, which reads a header from stdin, processes it using extract_command, and writes the resulting command list as JSON to stdout. ```python if __name__ == "__main__": header = dedent(sys.stdin.read()) command = extract_command(header) sys.stdout.write(json.dumps(command)) ``` -------------------------------- ### Legacy Markdown Fence Syntax for Marimo Cells Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/05-types-and-interfaces.md Example of using legacy syntax (language outside braces) to denote a Marimo cell within markdown fences. ```markdown ```python {.marimo} ``` ``` ```markdown ```sql {.marimo} ``` ``` -------------------------------- ### Specify SQL Engine for Execution Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/06-configuration-options.md Use the 'engine' attribute to select the SQL engine for executing the query. Valid values depend on the marimo version and installed engines. ```sql SELECT * FROM data ``` -------------------------------- ### Override Marimo Version in pyproject Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/06-configuration-options.md Specify a particular version of the Marimo package to be installed in the sandboxed environment by including it in the 'dependencies' list within the 'pyproject' YAML block. ```yaml pyproject: | dependencies = ["marimo>=0.24.0", "pandas"] ``` -------------------------------- ### Hide Cell from Output in Marimo Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/00-index.md Use the `#| include: false` directive to prevent a Marimo cell and its output from appearing in the final rendered document. This is useful for setup code. ```python #| include: false # Setup code data = load_data() ``` -------------------------------- ### Implement Reactive Dependencies in Marimo Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/09-code-examples.md Use `@mo.reactive` to create computations that automatically update when their dependencies change. This example shows a data filtering operation that reacts to a UI slider's value. ```python import marimo as mo # Input threshold = mo.ui.slider(0, 100, value=50) # Dependent computation @mo.reactive def filtered_data(): return load_data().query(f"value > {threshold.value}") # Output filtered_data() ``` -------------------------------- ### Render with Local Frontend Debug Endpoint Source: https://github.com/marimo-team/quarto-marimo/blob/main/CONTRIBUTING.md Renders the project using a local frontend build by setting the QUARTO_MARIMO_DEBUG_ENDPOINT environment variable. This allows testing local frontend changes with Quarto. ```bash cd ../../quarto-marimo QUARTO_MARIMO_DEBUG_ENDPOINT=/marimo-frontend quarto render ``` -------------------------------- ### Execution Pipeline Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/COMPLETION_REPORT.txt A walkthrough of the complete execution pipeline, including error handling and data flow. ```APIDOC ## Execution Pipeline ### Overview This section details the complete execution pipeline, comprising 8 major steps. ### Steps 1. **Step 1**: Description 2. **Step 2**: Description ... (8 major steps) ### Error Handling [Explanation of error handling at each stage] ### Subprocess Invocations [Details on subprocesses used in the pipeline] ### Data Flow [Description of data flow between modules] ### Performance Considerations [Notes on performance optimization] ``` -------------------------------- ### Set QUARTO_MARIMO_LOCAL_FRONTEND_ROOT for Debug Builds Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/06-configuration-options.md Specify the path to a local marimo checkout for debug builds. This is used by sync scripts to copy the built frontend to the output directory. ```bash export QUARTO_MARIMO_LOCAL_FRONTEND_ROOT=../marimo export QUARTO_MARIMO_DEBUG_ENDPOINT=/marimo-frontend quarto preview ``` -------------------------------- ### Embed Marimo Notebook in Quarto Document Source: https://github.com/marimo-team/quarto-marimo/blob/main/README.md Embed a Marimo notebook within an index.qmd file using a Python code block with the {.marimo} class. This example includes a slider and reactive text output. ```yaml --- title: My Document --- # Just another Quarto project ```python {.marimo} #| echo: true import marimo as mo slider = mo.ui.slider(1, 10, 1, label="Look, a slider!") slider ``` ## More things And we can respond! ```python {.marimo} # No echo here means we do not show the code mo.md("NaN" * slider.value + " Batman!") ``` ``` -------------------------------- ### Hide Cell Output with output: false Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/06-configuration-options.md Use `output: false` to prevent the output of a Marimo cell from being displayed. This is helpful for cells that perform setup or calculations whose results are not needed in the final document. ```python #| output: false df = load_data() # Result not shown ``` -------------------------------- ### SQL Query with Custom Engine (DuckDB) Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/09-code-examples.md Demonstrates executing an SQL query using a custom engine, specifically DuckDB. This is useful for leveraging specific database features or performance optimizations. ```sql SELECT DATE_TRUNC('month', date) as month, SUM(amount) as total FROM transactions GROUP BY 1 ORDER BY 1 ``` -------------------------------- ### Configuration Options Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/COMPLETION_REPORT.txt Details on document-level YAML options, cell-level directives, SQL attributes, and environment variables. ```APIDOC ## Configuration ### Document-level YAML Options - **option1** (type) - Default: value - Description - **option2** (type) - Default: value - Description - **option3** (type) - Default: value - Description ### Cell-level #| Directives - **directive1** (type) - Description - **directive2** (type) - Description ... (7 directives documented) ### SQL Cell Attributes - **attribute1** (type) - Description - **attribute2** (type) - Description - **attribute3** (type) - Description ### Environment Variables - **VAR1** (type) - Description - **VAR2** (type) - Description - **VAR3** (type) - Description - **VAR4** (type) - Description ### Option Precedence Rules [Explanation of how options are prioritized] ### Format-specific Settings [Details on settings for different output formats] ``` -------------------------------- ### Exclude Cell Output with include: false Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/06-configuration-options.md Set `include: false` to prevent a Marimo cell's output from being included in the final rendered document. This is ideal for setup or helper cells whose logic is needed but whose results should not be visible. ```python #| include: false # Setup code that shouldn't appear setup_data() ``` -------------------------------- ### Construct UV Flags from PyProject Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/03-command-python.md Shows how to generate `uv run` flags using `construct_uv_flags` based on parsed project metadata. ```python flags = construct_uv_flags(pyproject, temp_file, [], []) ``` -------------------------------- ### Set Local Marimo Frontend Root Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/00-index.md Specify a local checkout of the marimo frontend to use by setting the QUARTO_MARIMO_LOCAL_FRONTEND_ROOT environment variable. ```bash export QUARTO_MARIMO_LOCAL_FRONTEND_ROOT=../marimo quarto preview ``` -------------------------------- ### Render Quarto Document Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/00-index.md Renders a Quarto document to HTML format. This is a standard Quarto command used to generate output files. ```bash quarto render index.qmd --to html ``` -------------------------------- ### Quarto YAML Front Matter Configuration Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/00-index.md Configures a Quarto document using YAML front matter. Supports options like external environment usage, Python dependencies, and cell evaluation. ```yaml --- title: My Document format: html external-env: false # Use uv sandbox pyproject: | dependencies = ["pandas", "numpy"] eval: true # Execute cells --- ``` -------------------------------- ### Main Entry Point for extract.py Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/10-module-graph.md This snippet shows the main execution block for the extract.py script, indicating its command-line argument parsing, stdin reading, core function call, and JSON output. ```python if __name__ == "__main__": # Parse command-line arguments # Read stdin # Call convert_from_md_to_pandoc_export() # Output JSON ``` -------------------------------- ### Add Marimo Quarto Extension Source: https://github.com/marimo-team/quarto-marimo/blob/main/README.md Add the quarto-marimo extension to your Quarto project. ```bash quarto add marimo-team/quarto-marimo ``` -------------------------------- ### Initialize Marimo Engine Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/01-marimo-engine-typescript.md Initializes the Marimo engine with Quarto's API. This must be called before any other methods. ```typescript init: (quartoAPI: QuartoAPI) => { quarto = quartoAPI; } ``` -------------------------------- ### Run Single TypeScript Test File Source: https://github.com/marimo-team/quarto-marimo/blob/main/AGENTS.md Execute a specific TypeScript test file using Deno, granting read, write, and environment permissions. ```bash deno test --no-check --allow-read --allow-write --allow-env tests/cell-execution-regex.test.ts ``` -------------------------------- ### Skip Execution During Preview (CLI) Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/09-code-examples.md Use the `quarto preview` command without any additional flags to preview your document with code execution disabled. Use `quarto render` for a full execution and rendering. ```bash quarto preview # No execution quarto render # Full execution ``` -------------------------------- ### executePython Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/01-marimo-engine-typescript.md Spawns a child process and executes a Python command. It handles piping stdin, awaiting completion, logging stderr, and returning stdout. ```APIDOC ## executePython(command: string, args: string[], stdin?: string): Promise ### Description Spawns a child process and executes a Python command. It handles piping stdin, awaiting completion, logging stderr, and returning stdout. ### Parameters #### Parameters - **command** (string) - Required - Command to execute (e.g., "python", "uv") - **args** (string[]) - Optional - Command-line arguments. Defaults to []. - **stdin** (string) - Optional - Input data to send to stdin. Defaults to "". ### Returns Promise — stdout as decoded UTF-8 text ### Throws Error if process exits non-zero ### Example ```typescript const result = await executePython("python", ["script.py"], "input data"); ``` ``` -------------------------------- ### Execute Marimo Command Script Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/03-command-python.md Run the main Marimo command script. It reads dependency blocks from stdin and expects a script path as an argument. ```bash python command.py ``` -------------------------------- ### Partitioning Markdown with Custom Regex Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/04-utility-modules-typescript.md Demonstrates how to use a custom regex, MARIMO_CELL_REGEX, to partition Quarto Markdown content into chunks, separating Marimo cells from standard Markdown. ```typescript const chunks = await quarto.markdownRegex.breakQuartoMd( target.markdown, false, false, MARIMO_CELL_REGEX // ← custom regex ); for (const cell of chunks.cells) { if (isMarimoCell(cell)) { // ← type check const rendered = await renderOutput(output, mimeSensitive); // ← render processedCells.push(rendered); } } ``` -------------------------------- ### Supported File Extensions Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/01-marimo-engine-typescript.md Returns an array of supported file extensions for Marimo documents. ```typescript validExtensions: () => [".qmd", ".md"] ``` -------------------------------- ### Handle Missing Required Arguments Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/07-error-handling.md The entry point raises an AssertionError if the incorrect number of command-line arguments are provided. Ensure the engine is called with the expected number of arguments (3 or 4). ```python assert len(sys.argv) in (3, 4), f"Unexpected call format got {sys.argv}" ``` -------------------------------- ### Execute Marimo Document Options Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/01-marimo-engine-typescript.md Defines the options required for executing a Marimo document, including the execution target, output format, and temporary directory. ```typescript options: { target: ExecutionTarget; format: QuartoFormat; tempDir: string; // ... other Quarto fields } ``` -------------------------------- ### Version-Aware Imports for command.py Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/10-module-graph.md Shows version-aware import logic for Marimo modules in command.py, prioritizing newer internal sandbox modules and providing fallbacks for older versions. ```python # Standard library import json, sys, tempfile from textwrap import dedent from typing import TYPE_CHECKING # Marimo (version-aware) try: from marimo._internal.sandbox import PyProjectReader, construct_uv_flags except ImportError: from marimo._cli.sandbox import construct_uv_flags from marimo._utils.inline_script_metadata import PyProjectReader ``` -------------------------------- ### Display Code and Output in Marimo Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/00-index.md This snippet shows how to display both the Python code and its output within a Marimo cell in Quarto. Use the `#| echo: true` directive to enable this. ```python #| echo: true import pandas as pd df = pd.read_csv("data.csv") df.head() ``` -------------------------------- ### Release Script (Minor) Source: https://github.com/marimo-team/quarto-marimo/blob/main/AGENTS.md Increment the minor version (e.g., 0.x.0) of the extension using the release script. ```bash ./scripts/release.sh minor ``` -------------------------------- ### Type Definitions Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/COMPLETION_REPORT.txt Documentation for key type definitions used within the Marimo and Quarto projects. ```APIDOC ## Type Definitions ### MarimoOutput - **field1** (type) - Description - **field2** (type) - Description - **field3** (type) - Description - **field4** (type) - Description - **field5** (type) - Description ### MarimoExecutionResult - **field1** (type) - Description - **field2** (type) - Description - **field3** (type) - Description ### _ParseError - **field1** (type) - Description ### Quarto Types - **ExecutionEngineDiscovery** (fields) - Description - **ExecuteOptions** (fields) - Description ... (other Quarto types) ### Marimo Types - **MarimoIslandGenerator** (fields) - Description - **MarimoIslandStub** (fields) - Description ... (other Marimo types) ``` -------------------------------- ### pyproject_to_script_metadata Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/02-extract-python.md Converts Quarto's `pyproject` YAML content into a PEP 723 compliant script metadata block. It formats the input YAML by adding a header and footer, or returns it as-is if it already contains the script marker. ```APIDOC ## pyproject_to_script_metadata(pyproject: str) -> str ### Description Converts Quarto's `pyproject` YAML into PEP 723 script metadata, formatting it with a header and footer. ### Parameters #### Path Parameters - **pyproject** (str) - Required - YAML dependency block from front matter ### Returns str - Commented script metadata block or an empty string. ### Process If the input already starts with `# ///`, it is returned as-is with a trailing newline. Otherwise, each line is prefixed with `# ` and `# /// script` is added as a header and `# ///` as a footer. ### Example ```python pyproject = "dependencies = ['pandas', 'numpy']" metadata = pyproject_to_script_metadata(pyproject) # Expected output: # # /// script # # dependencies = ['pandas', 'numpy'] # # /// ``` ``` -------------------------------- ### Run All Tests (TypeScript + Python) Source: https://github.com/marimo-team/quarto-marimo/blob/main/AGENTS.md Execute all automated tests for both TypeScript and Python components of the extension. ```bash make test ``` -------------------------------- ### Version-Aware Imports for extract.py Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/10-module-graph.md Demonstrates version-aware import handling for Marimo modules, attempting to import from newer locations first and falling back to older ones if necessary. ```python # Standard library import asyncio, json, keyword, os, re, sys from collections.abc import Callable from dataclasses import dataclass from textwrap import dedent from typing import Any, ClassVar, Optional from urllib.parse import quote from xml.etree.ElementTree import Element # Marimo (direct imports) import marimo from marimo import App, MarimoIslandGenerator from marimo._convert.common.format import sql_to_marimo from marimo._session.notebook import AppFileManager from marimo._islands import MarimoIslandStub # Marimo (version-aware imports) try: from marimo._convert.markdown.to_ir import ( MARIMO_MD, MarimoMdParser as MarimoParser, SafeWrap as SafeWrapGeneric ) except ImportError: from marimo._convert.markdown.markdown import (...) # Fallback ``` -------------------------------- ### Lazy Loading with Marimo UI Inputs Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/09-code-examples.md Implement lazy loading by integrating data loading with Marimo UI elements like dropdowns. This ensures that data is only loaded when a user makes a selection, improving initial load times. ```python import marimo as mo file_selector = mo.ui.dropdown( options=available_files(), label="Select file" ) if file_selector.value: df = load_file(file_selector.value) # Only loads on selection mo.md(f"Loaded {len(df)} rows") ``` -------------------------------- ### Test Quarto with Specific Marimo Versions Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/09-code-examples.md Set the QUARTO_MARIMO_VERSION environment variable to test your Quarto project against different Marimo versions. This helps ensure compatibility and allows for testing upgrades. ```bash # Test with specific version export QUARTO_MARIMO_VERSION=0.23.1 quarto render test.qmd # Test with another version export QUARTO_MARIMO_VERSION=0.24.0 quarto render test.qmd ``` -------------------------------- ### validExtensions Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/01-marimo-engine-typescript.md Returns a list of file extensions supported by the Marimo engine. ```APIDOC ## validExtensions ### Description Returns supported file extensions. ### Method ```typescript validExtensions(): string[] ``` ### Returns An array of strings representing supported file extensions (e.g., ".qmd", ".md"). ``` -------------------------------- ### Run TypeScript Tests Source: https://github.com/marimo-team/quarto-marimo/blob/main/AGENTS.md Execute only the TypeScript tests using Deno. Ensure necessary file system and environment access is granted. ```bash deno test --no-check --allow-read --allow-write --allow-env ``` -------------------------------- ### Execute Python Command Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/01-marimo-engine-typescript.md Spawns a child process to execute a Python command with arguments and optional stdin. Use this for running Python scripts or tools like 'uv'. ```typescript const result = await executePython("python", ["script.py"], "input data"); ``` -------------------------------- ### Utility Functions Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/COMPLETION_REPORT.txt Documentation for exported utility functions. ```APIDOC ## Utility Functions ### Description Provides various utility functions for common tasks. ### Functions - **utility1** (params) - Returns: type - Description - **utility2** (params) - Returns: type - Description - **utility3** (params) - Returns: type - Description ``` -------------------------------- ### Generate Export Context Script Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/08-execution-pipeline.md This code prepares the header for HTML exports by generating metadata, notebook code, and rendering export context scripts. It allows islands to validate export authenticity and restore the full notebook. ```python script_metadata = pyproject_to_script_metadata(str(pyproject)) notebook_code = build_export_notebook_code(app, script_metadata) header = ( render_export_context_script(notebook_code) + render_hidden_marimo_code(notebook_code) + header # app.render_head() ) ``` -------------------------------- ### Set QUARTO_MARIMO_DEBUG_ENDPOINT for Local Development Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/06-configuration-options.md Override where marimo islands JavaScript is loaded from. Use a relative site path for local development. ```bash export QUARTO_MARIMO_DEBUG_ENDPOINT=/marimo-frontend quarto preview ``` -------------------------------- ### Build TypeScript Engine Extension Source: https://github.com/marimo-team/quarto-marimo/blob/main/README.md Build the TypeScript engine extension for Marimo in Quarto. This command bundles the TypeScript source into a JavaScript file. ```bash quarto call build-ts-extension ``` -------------------------------- ### extract_command Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/03-command-python.md Builds the `uv run` argument list for a Quarto document based on its dependency declarations. ```APIDOC ## extract_command(header: str) -> list[str] ### Description Builds the `uv run` argument list for one Quarto document. ### Parameters #### Path Parameters - **header** (str) - Required - Dependency declaration (YAML or PEP 723 script metadata) ### Returns list[str] — uv command arguments (first element is always "run") ### Process 1. If `header` does not start with "#", wraps it in PEP 723 format. 2. Parses via `PyProjectReader.from_script(header)`. 3. Creates a temp file for uv configuration. 4. Calls `construct_uv_flags(pyproject, temp_file, [], [])`. 5. Prepends "run" to the flags. 6. Returns the full command array. ### Example ```python header = '[project]\ndependencies = ["pandas", "numpy"]' flags = extract_command(header) # Returns: ["run", "--with", "pandas", "--with", "numpy", ...] ``` ### Example with PEP 723 ```python header = """# /// script # dependencies = ["marimo>=0.23.1", "requests"] # ///""" flags = extract_command(header) # Returns: ["run", "--with", "marimo", "--with", "requests", ...] ``` ``` -------------------------------- ### Import renderOutput and MarimoOutput Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/10-module-graph.md Imports the renderOutput function and MarimoOutput type from the render-output library for testing. ```typescript import { renderOutput, MarimoOutput } from "../lib/render-output.ts"; ``` -------------------------------- ### Marimo Version Compatibility Handling (Python) Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/10-module-graph.md This Python code demonstrates how to handle different Marimo versions by using a try-except block to import specific modules based on availability. It ensures compatibility with both newer (0.24+) and older (0.23.x) Marimo releases. ```python try: from marimo._convert.markdown.to_ir import (...) # 0.24+ except ImportError: from marimo._convert.markdown.markdown import (...) # 0.23.x ``` ```python try: from marimo._internal.sandbox import (...) # 0.24+ except ImportError: from marimo._cli.sandbox import (...) # 0.23.x ``` -------------------------------- ### Construct uv Command Arguments Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/01-marimo-engine-typescript.md Builds arguments for 'uv run' based on a YAML/pyproject dependency header. This is useful for setting up Python environments with specific packages. ```typescript const header = `dependencies = ["pandas", "numpy"]`; const flags = await constructUvCommand(header); // Result: ["run", "--with", "pandas", "--with", "numpy", ...] ``` -------------------------------- ### Conditional Rendering with Marimo UI Source: https://github.com/marimo-team/quarto-marimo/blob/main/_autodocs/09-code-examples.md Shows how to use Marimo's UI elements for conditional rendering. The output changes dynamically based on the value of a slider. ```python import marimo as mo x = mo.ui.slider(0, 100) if x.value > 50: mo.md(f"# High Value: {x.value}") else: mo.md(f"# Low Value: {x.value}") ```