marimo-md-export 0.4.2__tar.gz → 0.5.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,10 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: marimo-md-export
3
- Version: 0.4.2
3
+ Version: 0.5.0
4
4
  Summary: A minimal solution for exporting marimo notebooks to markdown *with* rendered HTML outputs, designed for mkdocs/zensical sites.
5
5
  Keywords: marimo,markdown,documentation
6
- Author: jmarshrossney
7
- Author-email: jmarshrossney <17361029+jmarshrossney@users.noreply.github.com>
6
+ Author: Joe Marsh Rossney
7
+ Author-email: Joe Marsh Rossney <17361029+jmarshrossney@users.noreply.github.com>
8
8
  License-Expression: MIT
9
9
  License-File: LICENSE
10
10
  Classifier: Development Status :: 3 - Alpha
@@ -32,9 +32,8 @@ Description-Content-Type: text/markdown
32
32
  [![CI](https://github.com/jmarshrossney/marimo-md-export/actions/workflows/ci.yml/badge.svg)](https://github.com/jmarshrossney/marimo-md-export/actions/workflows/ci.yml)
33
33
  [![Docs](https://github.com/jmarshrossney/marimo-md-export/actions/workflows/docs.yml/badge.svg)](https://jmarshrossney.github.io/marimo-md-export)
34
34
 
35
- A `uv` tool that wraps `marimo export`, extracts rendered outputs from the HTML export,
36
- and injects them into the markdown export. The result is a self-contained markdown
37
- document with embedded figures (as base64 `<img>` tags), tables (as GFM or HTML), and other cell outputs.
35
+ A `uv` tool that wraps `marimo export`, extracts rendered outputs from the HTML export, and injects them into the markdown export.
36
+ The result is a self-contained markdown document with embedded figures (as base64 `<img>` tags), tables (as GFM or HTML), and other cell outputs.
38
37
 
39
38
  **[Full documentation](https://jmarshrossney.github.io/marimo-md-export)**
40
39
 
@@ -56,9 +55,8 @@ uvx marimo-md-export notebook.py output.md
56
55
 
57
56
  ## Integrating with documentation sites
58
57
 
59
- `marimo-md-export` is designed to produce markdown pages for static site generators like
60
- [mkdocs](https://www.mkdocs.org/) (Python) or
61
- [zensical](https://zensical.org/) (Rust). Both work identically for this purpose.
58
+ `marimo-md-export` is designed to produce markdown pages for static site generators like [mkdocs](https://www.mkdocs.org/) or [zensical](https://zensical.org/).
59
+ Both work identically for this purpose.
62
60
 
63
61
  **1. Add as a docs dependency:**
64
62
 
@@ -76,8 +74,7 @@ docs:
76
74
  zensical build
77
75
  ```
78
76
 
79
- This runs `marimo-md-export` to produce a self-contained markdown page (with cell
80
- outputs injected), then builds the site.
77
+ This runs `marimo-md-export` to produce a self-contained markdown page (with cell outputs injected), then builds the site.
81
78
 
82
79
  ## Development
83
80
 
@@ -6,9 +6,8 @@
6
6
  [![CI](https://github.com/jmarshrossney/marimo-md-export/actions/workflows/ci.yml/badge.svg)](https://github.com/jmarshrossney/marimo-md-export/actions/workflows/ci.yml)
7
7
  [![Docs](https://github.com/jmarshrossney/marimo-md-export/actions/workflows/docs.yml/badge.svg)](https://jmarshrossney.github.io/marimo-md-export)
8
8
 
9
- A `uv` tool that wraps `marimo export`, extracts rendered outputs from the HTML export,
10
- and injects them into the markdown export. The result is a self-contained markdown
11
- document with embedded figures (as base64 `<img>` tags), tables (as GFM or HTML), and other cell outputs.
9
+ A `uv` tool that wraps `marimo export`, extracts rendered outputs from the HTML export, and injects them into the markdown export.
10
+ The result is a self-contained markdown document with embedded figures (as base64 `<img>` tags), tables (as GFM or HTML), and other cell outputs.
12
11
 
13
12
  **[Full documentation](https://jmarshrossney.github.io/marimo-md-export)**
14
13
 
@@ -30,9 +29,8 @@ uvx marimo-md-export notebook.py output.md
30
29
 
31
30
  ## Integrating with documentation sites
32
31
 
33
- `marimo-md-export` is designed to produce markdown pages for static site generators like
34
- [mkdocs](https://www.mkdocs.org/) (Python) or
35
- [zensical](https://zensical.org/) (Rust). Both work identically for this purpose.
32
+ `marimo-md-export` is designed to produce markdown pages for static site generators like [mkdocs](https://www.mkdocs.org/) or [zensical](https://zensical.org/).
33
+ Both work identically for this purpose.
36
34
 
37
35
  **1. Add as a docs dependency:**
38
36
 
@@ -50,8 +48,7 @@ docs:
50
48
  zensical build
51
49
  ```
52
50
 
53
- This runs `marimo-md-export` to produce a self-contained markdown page (with cell
54
- outputs injected), then builds the site.
51
+ This runs `marimo-md-export` to produce a self-contained markdown page (with cell outputs injected), then builds the site.
55
52
 
56
53
  ## Development
57
54
 
@@ -4,10 +4,10 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "marimo-md-export"
7
- version = "0.4.2"
7
+ version = "0.5.0"
8
8
  description = "A minimal solution for exporting marimo notebooks to markdown *with* rendered HTML outputs, designed for mkdocs/zensical sites."
9
9
  authors = [
10
- { name = "jmarshrossney", email = "17361029+jmarshrossney@users.noreply.github.com" }
10
+ { name = "Joe Marsh Rossney", email = "17361029+jmarshrossney@users.noreply.github.com" }
11
11
  ]
12
12
  readme = "README.md"
13
13
  license = "MIT"
@@ -40,6 +40,7 @@ marimo-md-export = "marimo_md_export:main"
40
40
 
41
41
  [dependency-groups]
42
42
  dev = [
43
+ "pre-commit>=4.6.0",
43
44
  "pyright>=1.1.409",
44
45
  "ruff>=0.15.12",
45
46
  "rust-just>=1.50.0",
@@ -4,7 +4,11 @@ import typer
4
4
  from rich.console import Console
5
5
 
6
6
  from .export import export_html, export_md, strip_header_from_frontmatter
7
- from .inject import inject_outputs
7
+ from .inject import (
8
+ _PRE_STYLE_SCROLL,
9
+ _PRE_STYLE_WRAP,
10
+ inject_outputs,
11
+ )
8
12
  from .parse_html import extract_outputs
9
13
  from .parse_md import collect_cells
10
14
 
@@ -56,6 +60,12 @@ def main(
56
60
  help="Maximum seconds to wait for each marimo export subprocess "
57
61
  "(default: no timeout).",
58
62
  ),
63
+ overflow: str = typer.Option(
64
+ "wrap",
65
+ "--overflow",
66
+ help="Default overflow behavior for long output lines: 'wrap' (default) or 'scroll'. "
67
+ "Can be overridden per cell with # @scroll or # @wrap.",
68
+ ),
59
69
  ) -> None:
60
70
  """Export a marimo notebook to markdown with rendered outputs injected.
61
71
 
@@ -95,8 +105,19 @@ def main(
95
105
  if verbose:
96
106
  typer.echo(f"Wrote {html_output}")
97
107
 
108
+ if overflow == "scroll":
109
+ pre_style = _PRE_STYLE_SCROLL
110
+ elif overflow == "wrap":
111
+ pre_style = _PRE_STYLE_WRAP
112
+ else:
113
+ typer.echo(
114
+ f"Invalid overflow value: {overflow!r}. Must be 'wrap' or 'scroll'.",
115
+ err=True,
116
+ )
117
+ raise typer.Exit(2)
118
+
98
119
  outputs = extract_outputs(html)
99
- result, warnings = inject_outputs(md, cells, outputs)
120
+ result, warnings = inject_outputs(md, cells, outputs, default_pre_style=pre_style)
100
121
 
101
122
  for warning in warnings:
102
123
  _err_console.print(f"WARNING: {warning}", style="bold yellow")
@@ -4,6 +4,19 @@ from bs4 import BeautifulSoup
4
4
 
5
5
  from .models import Cell, ExtractedOutput
6
6
 
7
+ _PRE_STYLE_WRAP = "white-space: pre-wrap; overflow-wrap: break-word;"
8
+ _PRE_STYLE_SCROLL = "white-space: pre; overflow-x: auto;"
9
+
10
+ _PRE_STYLE_RE = re.compile(r"<pre\b([^>]*)>")
11
+
12
+
13
+ def _inject_pre_style(html: str, style: str) -> str:
14
+ """Add a style attribute to every <pre> tag in *html*."""
15
+ return _PRE_STYLE_RE.sub(
16
+ lambda m: f'<pre{m.group(1)} style="{style}">',
17
+ html,
18
+ )
19
+
7
20
 
8
21
  def _table_to_gfm(html: str) -> str | None:
9
22
  """Convert a plain HTML <table> to GFM markdown, or return None on failure."""
@@ -12,7 +25,6 @@ def _table_to_gfm(html: str) -> str | None:
12
25
  if table is None:
13
26
  return None
14
27
 
15
- # Reject tables with merged cells — fall back to HTML
16
28
  if table.find(attrs={"colspan": True}) or table.find(attrs={"rowspan": True}):
17
29
  return None
18
30
 
@@ -27,7 +39,6 @@ def _table_to_gfm(html: str) -> str | None:
27
39
  header = rows[0]
28
40
  body = rows[1:]
29
41
 
30
- # Reject tables with inconsistent row widths — fall back to HTML
31
42
  ncols = len(header)
32
43
  if any(len(row) != ncols for row in rows):
33
44
  return None
@@ -55,24 +66,34 @@ def _escape_brackets_in_pre(html: str) -> str:
55
66
  )
56
67
 
57
68
 
58
- def _format_output(output: ExtractedOutput) -> str:
69
+ def _format_output(output: ExtractedOutput, pre_style: str) -> str:
59
70
  comment = f"<!-- @output:{output.cell_id} -->"
60
71
 
61
72
  parts = []
62
73
  if output.console_html:
63
- parts.append(_escape_brackets_in_pre(output.console_html))
74
+ parts.append(
75
+ _escape_brackets_in_pre(_inject_pre_style(output.console_html, pre_style))
76
+ )
64
77
  if output.stderr_html:
65
- parts.append(_escape_brackets_in_pre(output.stderr_html))
78
+ parts.append(
79
+ _escape_brackets_in_pre(_inject_pre_style(output.stderr_html, pre_style))
80
+ )
66
81
  if output.media_html:
67
82
  parts.append(_escape_brackets_in_pre(output.media_html))
68
83
  if output.raw_html:
69
84
  if output.output_type == "table":
70
85
  gfm = _table_to_gfm(output.raw_html)
71
86
  parts.append(
72
- gfm if gfm is not None else _escape_brackets_in_pre(output.raw_html)
87
+ gfm
88
+ if gfm is not None
89
+ else _escape_brackets_in_pre(
90
+ _inject_pre_style(output.raw_html, pre_style)
91
+ )
73
92
  )
74
93
  else:
75
- parts.append(_escape_brackets_in_pre(output.raw_html))
94
+ parts.append(
95
+ _escape_brackets_in_pre(_inject_pre_style(output.raw_html, pre_style))
96
+ )
76
97
 
77
98
  return comment + "\n\n" + "\n\n".join(parts)
78
99
 
@@ -81,6 +102,7 @@ def inject_outputs(
81
102
  md: str,
82
103
  cells: list[Cell],
83
104
  outputs: dict[str, ExtractedOutput],
105
+ default_pre_style: str = _PRE_STYLE_WRAP,
84
106
  ) -> tuple[str, list[str]]:
85
107
  """Inject rendered outputs into the markdown after each code block.
86
108
 
@@ -88,6 +110,9 @@ def inject_outputs(
88
110
  source_hash → ExtractedOutput. Cell IDs from the HTML export are used
89
111
  as labels in the output anchor comments.
90
112
 
113
+ default_pre_style is applied to all cells unless overridden by a
114
+ cell-level overflow marker (# @scroll / # @wrap).
115
+
91
116
  Returns (result_markdown, warnings) where warnings is a list of
92
117
  human-readable messages.
93
118
  """
@@ -98,10 +123,16 @@ def inject_outputs(
98
123
  continue
99
124
  matched = outputs.get(cell.source_hash)
100
125
  if matched is None:
101
- # No renderable output — expected for import/setup cells
102
126
  continue
103
127
 
104
- formatted = _format_output(matched)
128
+ pre_style = (
129
+ _PRE_STYLE_SCROLL
130
+ if cell.overflow == "scroll"
131
+ else _PRE_STYLE_WRAP
132
+ if cell.overflow == "wrap"
133
+ else default_pre_style
134
+ )
135
+ formatted = _format_output(matched, pre_style)
105
136
  result = result.replace(
106
137
  cell.block_text, cell.block_text + "\n\n" + formatted, 1
107
138
  )
@@ -9,6 +9,7 @@ class Cell:
9
9
  source_hash: str
10
10
  block_text: str
11
11
  suppressed: bool = False
12
+ overflow: str | None = None
12
13
 
13
14
 
14
15
  @dataclass
@@ -31,7 +31,9 @@
31
31
  # Tables are stored as <marimo-table data-data='...'> web components.
32
32
  # `data-data` is a JSON-quoted string of row objects; NaN appears literally.
33
33
 
34
+ import ast
34
35
  import json
36
+ import pprint
35
37
  import re
36
38
  from html import escape, unescape
37
39
 
@@ -73,7 +75,6 @@ def _table_html_from_marimo_table(marimo_table_html: str) -> str:
73
75
  if elem is None:
74
76
  return marimo_table_html
75
77
 
76
- # Variable names follow HTML data-* attribute naming (hyphenated → snake_case)
77
78
  data_data_attr = elem.get("data-data")
78
79
  if not isinstance(data_data_attr, str):
79
80
  return marimo_table_html
@@ -85,12 +86,8 @@ def _table_html_from_marimo_table(marimo_table_html: str) -> str:
85
86
  else:
86
87
  field_types_raw = "[]"
87
88
 
88
- # data-data is a JSON-quoted string containing an array of row objects.
89
- # It may contain literal NaN (not valid JSON). Replace only bare NaN
90
- # tokens (not inside quoted string values) to avoid clobbering strings
91
- # like "NaN handling".
92
89
  try:
93
- inner = json.loads(data_data) # unwrap outer JSON string
90
+ inner = json.loads(data_data)
94
91
  cleaned = re.sub(r'(?<!")\bNaN\b(?!")', "null", inner)
95
92
  rows = json.loads(cleaned)
96
93
  except (json.JSONDecodeError, AttributeError):
@@ -135,7 +132,6 @@ def _format_error(output: dict) -> str:
135
132
  traceback_lines = output.get("traceback") or []
136
133
  traceback_text = "\n".join(traceback_lines)
137
134
  if traceback_text.strip():
138
- # Traceback lines may contain HTML markup from Pygments
139
135
  traceback_text = _html_to_plain_text(traceback_text)
140
136
  combined = f"{traceback_text}\n{ename}: {evalue}"
141
137
  else:
@@ -180,12 +176,13 @@ def _strip_marimo_type_prefixes(obj: object) -> object:
180
176
  return obj
181
177
 
182
178
 
183
- def _classify_and_build(data: dict[str, str]) -> tuple[str, str] | None:
179
+ def _classify_and_build(
180
+ data: dict[str, str],
181
+ ) -> tuple[str, str] | None:
184
182
  """
185
183
  Given the output data dict (MIME → value), return (output_type, raw_html)
186
184
  or None if there is nothing renderable.
187
185
  """
188
- # Figure: marimo mimebundle — try representations in priority order
189
186
  bundle_raw = data.get("application/vnd.marimo+mimebundle")
190
187
  if bundle_raw:
191
188
  try:
@@ -203,9 +200,11 @@ def _classify_and_build(data: dict[str, str]) -> tuple[str, str] | None:
203
200
  if mime_key == "text/html":
204
201
  return "html", unescape(val)
205
202
  if mime_key == "text/plain" and val.strip():
206
- return "text", f"<pre>{escape(val)}</pre>"
203
+ return (
204
+ "text",
205
+ f"<pre>{escape(val)}</pre>",
206
+ )
207
207
 
208
- # Standalone image MIME types
209
208
  for mime_type in (
210
209
  "image/png",
211
210
  "image/jpeg",
@@ -224,23 +223,19 @@ def _classify_and_build(data: dict[str, str]) -> tuple[str, str] | None:
224
223
  f'<img src="{escape(img_val, quote=True)}" alt="{escape(fmt, quote=True)}">',
225
224
  )
226
225
 
227
- # JSON output (dicts, lists, tuples)
228
226
  json_val = data.get("application/json")
229
227
  if json_val:
230
228
  try:
231
229
  parsed = json.loads(json_val)
232
230
  cleaned = _strip_marimo_type_prefixes(parsed)
233
- formatted = json.dumps(cleaned, indent=2, ensure_ascii=False)
231
+ formatted = pprint.pformat(cleaned)
234
232
  except (json.JSONDecodeError, TypeError):
235
233
  formatted = json_val
236
- return "json", f"<pre><code>{escape(formatted)}</code></pre>"
237
-
238
- # LaTeX output — wrap in $$ delimiters for math rendering.
239
- # NOTE: text/latex is a fallback MIME type and is not expected to appear
240
- # in normal marimo usage. LaTeX in marimo is typically rendered inside
241
- # mo.md() blocks, which produce text/markdown output (suppressed to avoid
242
- # duplication with the markdown export). This handler exists for
243
- # robustness in case a library emits standalone text/latex.
234
+ return (
235
+ "json",
236
+ f"<pre>{escape(formatted)}</pre>",
237
+ )
238
+
244
239
  latex_val = data.get("text/latex", "")
245
240
  if latex_val and latex_val.strip():
246
241
  content = latex_val.strip()
@@ -254,28 +249,60 @@ def _classify_and_build(data: dict[str, str]) -> tuple[str, str] | None:
254
249
  return "latex", f"${content[1:-1]}$"
255
250
  return "latex", f"$$\n{content}\n$$"
256
251
 
257
- # CSV output — render as a plain text code block
258
252
  csv_val = data.get("text/csv", "")
259
253
  if csv_val and csv_val.strip():
260
- return "csv", f"<pre><code>{escape(csv_val)}</code></pre>"
254
+ return (
255
+ "csv",
256
+ f"<pre><code>{escape(csv_val)}</code></pre>",
257
+ )
261
258
 
262
- # HTML output (may be a marimo-table web component)
263
259
  html_val = data.get("text/html")
264
260
  if html_val:
265
261
  decoded = unescape(html_val)
262
+ pre_match = re.match(r"<pre[^>]*>(.*?)</pre>", decoded, re.DOTALL)
263
+ if pre_match:
264
+ content = pre_match.group(1)
265
+ if (
266
+ content.startswith(("'", '"'))
267
+ and content.endswith(("'", '"'))
268
+ and len(content) >= 2
269
+ ):
270
+ try:
271
+ content = ast.literal_eval(content)
272
+ except (ValueError, SyntaxError):
273
+ pass
274
+ if isinstance(content, str):
275
+ return (
276
+ "text",
277
+ f"<pre>{escape(content)}</pre>",
278
+ )
279
+ return (
280
+ "text",
281
+ f"<pre>{escape(content)}</pre>",
282
+ )
266
283
  if "<marimo-table" in decoded:
267
284
  table_html = _table_html_from_marimo_table(decoded)
268
285
  return "table", table_html
269
- # Generic HTML (e.g. styled dataframe rendered as <table>)
270
286
  if "<table" in decoded:
271
287
  return "table", decoded
272
288
  return "html", decoded
273
289
 
274
290
  plain = data.get("text/plain", "")
275
291
  if plain and plain.strip():
276
- return "text", f"<pre>{escape(plain)}</pre>"
292
+ if (
293
+ plain.startswith(("'", '"'))
294
+ and plain.endswith(("'", '"'))
295
+ and len(plain) >= 2
296
+ ):
297
+ try:
298
+ plain = ast.literal_eval(plain)
299
+ except (ValueError, SyntaxError):
300
+ pass
301
+ return (
302
+ "text",
303
+ f"<pre>{escape(plain)}</pre>",
304
+ )
277
305
 
278
- # Unsupported MIME types — leave a comment for debugging
279
306
  unsupported = {
280
307
  "application/vnd.vega.v5+json",
281
308
  "application/vnd.vega.v6+json",
@@ -295,7 +322,9 @@ def _classify_and_build(data: dict[str, str]) -> tuple[str, str] | None:
295
322
  return None
296
323
 
297
324
 
298
- def extract_outputs(html: bytes) -> dict[str, ExtractedOutput]:
325
+ def extract_outputs(
326
+ html: bytes,
327
+ ) -> dict[str, ExtractedOutput]:
299
328
  """Extract rendered outputs from the marimo HTML export.
300
329
 
301
330
  Returns a dict mapping source_hash → ExtractedOutput for each cell
@@ -325,7 +354,6 @@ def extract_outputs(html: bytes) -> dict[str, ExtractedOutput]:
325
354
  )
326
355
  console_html = f"<pre>{escape(stdout)}</pre>" if stdout.strip() else ""
327
356
 
328
- # Stderr may contain Pygments-highlighted HTML; strip it to plain text
329
357
  stderr = "".join(
330
358
  c.get("text", "")
331
359
  for c in cell.get("console", [])
@@ -336,7 +364,6 @@ def extract_outputs(html: bytes) -> dict[str, ExtractedOutput]:
336
364
  f'<pre class="stderr">{escape(stderr)}</pre>' if stderr.strip() else ""
337
365
  )
338
366
 
339
- # Console media output (images printed to console)
340
367
  media_parts = []
341
368
  for c in cell.get("console", []):
342
369
  if c.get("type") != "streamMedia":
@@ -3,9 +3,10 @@ import re
3
3
 
4
4
  from .models import Cell
5
5
 
6
- # Matches fenced code blocks produced by `marimo export md`
7
6
  _BLOCK_RE = re.compile(r"(```python \{\.marimo\}\n(.*?)```)", re.DOTALL)
8
7
  _SUPPRESS_RE = re.compile(r"#\s*@suppress")
8
+ _SCROLL_RE = re.compile(r"#\s*@scroll")
9
+ _WRAP_RE = re.compile(r"#\s*@wrap")
9
10
 
10
11
 
11
12
  def _md5(text: str) -> str:
@@ -22,12 +23,24 @@ def collect_cells(md: str) -> list[Cell]:
22
23
 
23
24
  suppressed = _SUPPRESS_RE.search(source) is not None
24
25
 
26
+ overflow: str | None = None
27
+ last_pos = -1
28
+ for m in _WRAP_RE.finditer(source):
29
+ if m.start() > last_pos:
30
+ last_pos = m.start()
31
+ overflow = "wrap"
32
+ for m in _SCROLL_RE.finditer(source):
33
+ if m.start() > last_pos:
34
+ last_pos = m.start()
35
+ overflow = "scroll"
36
+
25
37
  results.append(
26
38
  Cell(
27
39
  source=source,
28
40
  source_hash=_md5(source.strip()),
29
41
  block_text=block_text,
30
42
  suppressed=suppressed,
43
+ overflow=overflow,
31
44
  )
32
45
  )
33
46