marimo-md-export 0.4.3__tar.gz → 0.5.2__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,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: marimo-md-export
3
- Version: 0.4.3
3
+ Version: 0.5.2
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
6
  Author: Joe Marsh Rossney
@@ -4,7 +4,7 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "marimo-md-export"
7
- version = "0.4.3"
7
+ version = "0.5.2"
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
10
  { name = "Joe Marsh Rossney", email = "17361029+jmarshrossney@users.noreply.github.com" }
@@ -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",
@@ -61,6 +62,11 @@ test = [
61
62
  {include-group = "examples"},
62
63
  ]
63
64
 
65
+ [tool.pyright]
66
+ venvPath = "."
67
+ venv = ".venv"
68
+ include = ["src/", "tests/"]
69
+
64
70
  [tool.ruff]
65
71
  line-length = 88
66
72
  indent-width = 4
@@ -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
@@ -75,7 +75,6 @@ def _table_html_from_marimo_table(marimo_table_html: str) -> str:
75
75
  if elem is None:
76
76
  return marimo_table_html
77
77
 
78
- # Variable names follow HTML data-* attribute naming (hyphenated → snake_case)
79
78
  data_data_attr = elem.get("data-data")
80
79
  if not isinstance(data_data_attr, str):
81
80
  return marimo_table_html
@@ -87,12 +86,8 @@ def _table_html_from_marimo_table(marimo_table_html: str) -> str:
87
86
  else:
88
87
  field_types_raw = "[]"
89
88
 
90
- # data-data is a JSON-quoted string containing an array of row objects.
91
- # It may contain literal NaN (not valid JSON). Replace only bare NaN
92
- # tokens (not inside quoted string values) to avoid clobbering strings
93
- # like "NaN handling".
94
89
  try:
95
- inner = json.loads(data_data) # unwrap outer JSON string
90
+ inner = json.loads(data_data)
96
91
  cleaned = re.sub(r'(?<!")\bNaN\b(?!")', "null", inner)
97
92
  rows = json.loads(cleaned)
98
93
  except (json.JSONDecodeError, AttributeError):
@@ -137,7 +132,6 @@ def _format_error(output: dict) -> str:
137
132
  traceback_lines = output.get("traceback") or []
138
133
  traceback_text = "\n".join(traceback_lines)
139
134
  if traceback_text.strip():
140
- # Traceback lines may contain HTML markup from Pygments
141
135
  traceback_text = _html_to_plain_text(traceback_text)
142
136
  combined = f"{traceback_text}\n{ename}: {evalue}"
143
137
  else:
@@ -145,7 +139,7 @@ def _format_error(output: dict) -> str:
145
139
  return f"<pre>{escape(combined)}</pre>"
146
140
 
147
141
 
148
- _MARIMO_TYPE_RE = re.compile(r"^text/plain\+(\w+):(.*)$", re.DOTALL)
142
+ _MARIMO_TYPE_RE = re.compile(r"^text/plain(?:\+(\w+))?:(.*)$", re.DOTALL)
149
143
 
150
144
 
151
145
  def _strip_marimo_type_prefixes(obj: object) -> object:
@@ -182,18 +176,22 @@ def _strip_marimo_type_prefixes(obj: object) -> object:
182
176
  return obj
183
177
 
184
178
 
185
- 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:
186
182
  """
187
183
  Given the output data dict (MIME → value), return (output_type, raw_html)
188
184
  or None if there is nothing renderable.
189
185
  """
190
- # Figure: marimo mimebundle — try representations in priority order
191
186
  bundle_raw = data.get("application/vnd.marimo+mimebundle")
192
187
  if bundle_raw:
193
- try:
194
- bundle = json.loads(bundle_raw)
195
- except json.JSONDecodeError:
196
- bundle = {}
188
+ if isinstance(bundle_raw, dict):
189
+ bundle = bundle_raw
190
+ else:
191
+ try:
192
+ bundle = json.loads(bundle_raw)
193
+ except json.JSONDecodeError:
194
+ bundle = {}
197
195
  for mime_key in ("image/png", "image/svg+xml", "text/html", "text/plain"):
198
196
  val = bundle.get(mime_key)
199
197
  if val:
@@ -205,9 +203,11 @@ def _classify_and_build(data: dict[str, str]) -> tuple[str, str] | None:
205
203
  if mime_key == "text/html":
206
204
  return "html", unescape(val)
207
205
  if mime_key == "text/plain" and val.strip():
208
- return "text", f"<pre>{escape(val)}</pre>"
206
+ return (
207
+ "text",
208
+ f"<pre>{escape(val)}</pre>",
209
+ )
209
210
 
210
- # Standalone image MIME types
211
211
  for mime_type in (
212
212
  "image/png",
213
213
  "image/jpeg",
@@ -226,7 +226,6 @@ def _classify_and_build(data: dict[str, str]) -> tuple[str, str] | None:
226
226
  f'<img src="{escape(img_val, quote=True)}" alt="{escape(fmt, quote=True)}">',
227
227
  )
228
228
 
229
- # JSON output (dicts, lists, tuples)
230
229
  json_val = data.get("application/json")
231
230
  if json_val:
232
231
  try:
@@ -235,14 +234,11 @@ def _classify_and_build(data: dict[str, str]) -> tuple[str, str] | None:
235
234
  formatted = pprint.pformat(cleaned)
236
235
  except (json.JSONDecodeError, TypeError):
237
236
  formatted = json_val
238
- return "json", f"<pre>{escape(formatted)}</pre>"
239
-
240
- # LaTeX output — wrap in $$ delimiters for math rendering.
241
- # NOTE: text/latex is a fallback MIME type and is not expected to appear
242
- # in normal marimo usage. LaTeX in marimo is typically rendered inside
243
- # mo.md() blocks, which produce text/markdown output (suppressed to avoid
244
- # duplication with the markdown export). This handler exists for
245
- # robustness in case a library emits standalone text/latex.
237
+ return (
238
+ "json",
239
+ f"<pre>{escape(formatted)}</pre>",
240
+ )
241
+
246
242
  latex_val = data.get("text/latex", "")
247
243
  if latex_val and latex_val.strip():
248
244
  content = latex_val.strip()
@@ -256,16 +252,16 @@ def _classify_and_build(data: dict[str, str]) -> tuple[str, str] | None:
256
252
  return "latex", f"${content[1:-1]}$"
257
253
  return "latex", f"$$\n{content}\n$$"
258
254
 
259
- # CSV output — render as a plain text code block
260
255
  csv_val = data.get("text/csv", "")
261
256
  if csv_val and csv_val.strip():
262
- return "csv", f"<pre><code>{escape(csv_val)}</code></pre>"
257
+ return (
258
+ "csv",
259
+ f"<pre><code>{escape(csv_val)}</code></pre>",
260
+ )
263
261
 
264
- # HTML output (may be a marimo-table web component)
265
262
  html_val = data.get("text/html")
266
263
  if html_val:
267
264
  decoded = unescape(html_val)
268
- # Check for <pre> tag containing a Python string repr
269
265
  pre_match = re.match(r"<pre[^>]*>(.*?)</pre>", decoded, re.DOTALL)
270
266
  if pre_match:
271
267
  content = pre_match.group(1)
@@ -277,13 +273,19 @@ def _classify_and_build(data: dict[str, str]) -> tuple[str, str] | None:
277
273
  try:
278
274
  content = ast.literal_eval(content)
279
275
  except (ValueError, SyntaxError):
280
- content = None
281
- if content is not None:
282
- return "text", f"<pre>{escape(content)}</pre>"
276
+ pass
277
+ if isinstance(content, str):
278
+ return (
279
+ "text",
280
+ f"<pre>{escape(content)}</pre>",
281
+ )
282
+ return (
283
+ "text",
284
+ f"<pre>{escape(content)}</pre>",
285
+ )
283
286
  if "<marimo-table" in decoded:
284
287
  table_html = _table_html_from_marimo_table(decoded)
285
288
  return "table", table_html
286
- # Generic HTML (e.g. styled dataframe rendered as <table>)
287
289
  if "<table" in decoded:
288
290
  return "table", decoded
289
291
  return "html", decoded
@@ -299,9 +301,11 @@ def _classify_and_build(data: dict[str, str]) -> tuple[str, str] | None:
299
301
  plain = ast.literal_eval(plain)
300
302
  except (ValueError, SyntaxError):
301
303
  pass
302
- return "text", f"<pre>{escape(plain)}</pre>"
304
+ return (
305
+ "text",
306
+ f"<pre>{escape(plain)}</pre>",
307
+ )
303
308
 
304
- # Unsupported MIME types — leave a comment for debugging
305
309
  unsupported = {
306
310
  "application/vnd.vega.v5+json",
307
311
  "application/vnd.vega.v6+json",
@@ -321,7 +325,9 @@ def _classify_and_build(data: dict[str, str]) -> tuple[str, str] | None:
321
325
  return None
322
326
 
323
327
 
324
- def extract_outputs(html: bytes) -> dict[str, ExtractedOutput]:
328
+ def extract_outputs(
329
+ html: bytes,
330
+ ) -> dict[str, ExtractedOutput]:
325
331
  """Extract rendered outputs from the marimo HTML export.
326
332
 
327
333
  Returns a dict mapping source_hash → ExtractedOutput for each cell
@@ -351,7 +357,6 @@ def extract_outputs(html: bytes) -> dict[str, ExtractedOutput]:
351
357
  )
352
358
  console_html = f"<pre>{escape(stdout)}</pre>" if stdout.strip() else ""
353
359
 
354
- # Stderr may contain Pygments-highlighted HTML; strip it to plain text
355
360
  stderr = "".join(
356
361
  c.get("text", "")
357
362
  for c in cell.get("console", [])
@@ -362,7 +367,6 @@ def extract_outputs(html: bytes) -> dict[str, ExtractedOutput]:
362
367
  f'<pre class="stderr">{escape(stderr)}</pre>' if stderr.strip() else ""
363
368
  )
364
369
 
365
- # Console media output (images printed to console)
366
370
  media_parts = []
367
371
  for c in cell.get("console", []):
368
372
  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