diff --git a/doc/design/stdlib-writeback.md b/doc/design/stdlib-writeback.md index 9ef9042..44da73c 100644 --- a/doc/design/stdlib-writeback.md +++ b/doc/design/stdlib-writeback.md @@ -8,9 +8,11 @@ ## 定位 -**Jupyter 输出单元的 Marqdo 等价物**:执行得到结果 → `record` / `写回` 写入入口 `.mq.md` 的 `` → `marqdo view` 在对应语句下显示 **output-card**。普通 Markdown 预览不显示该区域。 +**Jupyter 输出单元的 Marqdo 等价物**:执行得到结果 → `record` / `写回` 写入入口 `.mq.md` → `marqdo view`(及静态 `view output`)在对应语句下显示 **output-card**,并在源码面用 **writeback** 样式标出块本身。 -## 存储格式 +## 存储格式(两种,可并存) + +### 1. HTML 注释(文本 / 结构化输出) ```markdown *`n` = > len value=`xs` * @@ -30,11 +32,26 @@ pending --> ``` -- 注释内为 `marqdo-out`,可选后跟槽名(`ok` / `error` 等),**不存行号** +### 2. Markdown 图片(生成图 / 审计友好) + +当 `value` **看起来像图片引用**(扩展名 `.png` / `.jpg` / `.jpeg` / `.gif` / `.webp` / `.svg` / …,或 `data:image/…`)时,`record` **自动**写成: + +```markdown +![marqdo-out](plots/out.svg) +![marqdo-out ok](plots/ok.png) +``` + +- 普通 Markdown 预览即可看见图;view / 静态站额外加 writeback 标记与 output-card 中的 ``。 +- 非图片路径仍走注释块;把非图片硬写成 `![marqdo-out](…)` 时扫描会忽略(校验失败)。 +- `list` / `scan_path` 结果带 `kind`: `comment` | `image`。 + +### 共用规则 + +- 标记字为 `marqdo-out`,可选后跟槽名(`ok` / `error` 等),**不存行号** - 默认在**调用行下方**插入或替换紧邻**无键**块 - `at_end=true`:替换文件末尾的**无键**块 -- `key=` / `键=`:在**当前调用锚点下方**创建或替换该命名槽(智能体单步用父调用行,即 `step` 语句下方);`ensure` 在缺失时写入占位且不覆盖已有正文。命名槽互不覆盖,也不使用文件末尾单块。 -- `line=` / `行=`:显式锚点行号。子任务 / 异步写回必须带上,否则会锚到子任务内部调用行。主机侧有全局互斥锁,写前从磁盘重读入口源,避免并发写互相覆盖。 +- `key=` / `键=`:在**当前调用锚点下方**创建或替换该命名槽;`ensure` 在缺失时写入占位且不覆盖已有正文 +- `line=` / `行=`:显式锚点行号;主机侧有全局互斥锁 ### 替换跨度与空行 diff --git a/lib/writeback.mq.md b/lib/writeback.mq.md index ab98e3e..bccbd6e 100644 --- a/lib/writeback.mq.md +++ b/lib/writeback.mq.md @@ -11,7 +11,7 @@ Persist run output in .mq.md (Jupyter-style writeback) + `key`=None + `line`=None -Write `value` to `` in the entry file. Default: insert or replace the block immediately below the call; `at_end=true` replaces the unkeyed EOF block. With `key=` (e.g. `ok` / `error`), replace or create that named slot only — slots do not overwrite each other. Optional `line=` anchors the block under that source line (needed when writing from a subtask). +Write `value` into the entry file. Image-like values (`.png` / `.svg` / … or `data:image/…`) become `![marqdo-out](…)` (or `![marqdo-out key](…)`); other values use ``. Default: insert or replace the block immediately below the call; `at_end=true` replaces the unkeyed EOF block. With `key=` (e.g. `ok` / `error`), replace or create that named slot only — slots do not overwrite each other. Optional `line=` anchors the block under that source line (needed when writing from a subtask). *> host_writeback_record value=`value` at_end=`at_end` key=`key` line=`line`* @@ -51,6 +51,6 @@ List all output blocks in the entry file (includes `key` when named). ## scan_path + `path` -List `` slots in any file (workbook inspection). +List writeback slots in any file (HTML comment and `![marqdo-out](…)` image forms; workbook inspection). *> host_writeback_scan_path path=`path`* diff --git a/lib/自写回.mq.md b/lib/自写回.mq.md index 87d5c42..a7748f0 100644 --- a/lib/自写回.mq.md +++ b/lib/自写回.mq.md @@ -11,7 +11,7 @@ description: 将运行结果写回 .mq.md(Jupyter 式自写回) + `键`=None + `行`=None -在入口文件中写入 ``。默认在调用行下方插入或替换;`末尾=true` 时替换无键末尾块。带 `键=`(如 `ok` / `error` / `成功` / `失败`)时只更新该命名槽,互不覆盖。可选 `行=` 锚定到指定源码行(子任务写回时需要)。 +在入口文件中写入自写回块:若 `值` 像图片路径/URL(`.png` / `.svg` / … 或 `data:image/…`)则写成 `![marqdo-out](…)`,否则写成 ``。默认在调用行下方插入或替换;`末尾=true` 时替换无键末尾块。带 `键=`(如 `ok` / `error` / `成功` / `失败`)时只更新该命名槽,互不覆盖。可选 `行=` 锚定到指定源码行(子任务写回时需要)。 *> host_writeback_record value=`值` at_end=`末尾` key=`键` line=`行`* @@ -51,6 +51,6 @@ description: 将运行结果写回 .mq.md(Jupyter 式自写回) ## 扫描路径 + `路径` -扫描任意文件中的 `` 槽(工作簿观察)。 +扫描任意文件中的自写回槽(注释块与 `![marqdo-out](…)` 图片;工作簿观察)。 *> host_writeback_scan_path path=`路径`* diff --git a/src/host/writeback.rs b/src/host/writeback.rs index a93b6ec..91ad329 100644 --- a/src/host/writeback.rs +++ b/src/host/writeback.rs @@ -1,7 +1,11 @@ -//! Jupyter-style output persistence in `.mq.md` (``). +//! Jupyter-style output persistence in `.mq.md`. //! -//! Optional **named slots**: `` / `` -//! so success and failure results do not overwrite each other. +//! Two surface forms (both scanned / replaced): +//! - HTML comment: `` (text / structured output) +//! - Markdown image: `![marqdo-out](path-or-url)` (image refs; validated) +//! +//! Optional **named slots**: `marqdo-out ok` / `marqdo-out error` so success and +//! failure results do not overwrite each other. use std::collections::HashMap; use std::sync::Mutex; @@ -14,14 +18,30 @@ const MAGIC: &str = "marqdo-out"; /// Serialize all writeback file mutations (sync + subtask writers). static WRITEBACK_LOCK: Mutex<()> = Mutex::new(()); +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum BlockKind { + Comment, + Image, +} + #[derive(Debug, Clone, PartialEq, Eq)] struct BlockSpan { start: usize, end: usize, + /// Comment body text, or image URL/path for [`BlockKind::Image`]. body: String, start_line: u32, /// Named slot from header (`marqdo-out ok` → `ok`); `None` = legacy unkeyed. key: Option, + kind: BlockKind, +} + +/// View-facing writeback piece under a statement line. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct WritebackEntry { + pub key: Option, + pub body: String, + pub is_image: bool, } fn display_value(v: &Value) -> String { @@ -119,13 +139,71 @@ fn line_number_at(source: &str, byte: usize) -> u32 { + 1 } -fn format_block(body: &str, key: Option<&str>) -> String { +fn format_comment_block(body: &str, key: Option<&str>) -> String { match key { Some(k) => format!(""), None => format!(""), } } +fn format_image_block(url: &str, key: Option<&str>) -> String { + match key { + Some(k) => format!("![{MAGIC} {k}]({url})"), + None => format!("![{MAGIC}]({url})"), + } +} + +fn format_block_for_value(body: &str, key: Option<&str>) -> Result { + if looks_like_image_ref(body) { + validate_image_ref(body)?; + Ok(format_image_block(body.trim(), key)) + } else { + Ok(format_comment_block(body, key)) + } +} + +/// True when `s` looks like a path/URL that should persist as `![marqdo-out](…)`. +pub fn looks_like_image_ref(s: &str) -> bool { + validate_image_ref(s).is_ok() +} + +/// Accept local/relative paths and http(s) URLs with a known image extension, +/// or `data:image/…` URIs. +pub fn validate_image_ref(s: &str) -> Result<(), String> { + let t = s.trim().trim_matches('"').trim_matches('\''); + if t.is_empty() { + return Err("writeback image: empty path".into()); + } + if t.starts_with("data:image/") { + return Ok(()); + } + // Strip query/fragment for extension check. + let no_query = t.split_once('?').map(|(p, _)| p).unwrap_or(t); + let path_part = no_query.split_once('#').map(|(p, _)| p).unwrap_or(no_query); + let file = path_part.rsplit('/').next().unwrap_or(path_part); + // Require a real extension (reject bare names like `svg` / `png`). + let Some((stem, ext)) = file.rsplit_once('.') else { + return Err(format!( + "writeback image: path needs an image extension (got `{t}`)" + )); + }; + if stem.is_empty() { + return Err(format!("writeback image: invalid file name `{t}`")); + } + let ext = ext.to_ascii_lowercase(); + const OK: &[&str] = &[ + "png", "jpg", "jpeg", "gif", "webp", "svg", "bmp", "ico", "avif", "tif", "tiff", + ]; + if OK.contains(&ext.as_str()) { + Ok(()) + } else { + Err(format!( + "writeback image: not an image path/URL (got `{t}`; need .{})", + OK.join("/.") + )) + } +} + fn parse_header_key(header: &str) -> Option { let mut parts = header.split_whitespace(); let first = parts.next()?; @@ -160,11 +238,43 @@ fn parse_one_block(block: &str, start_byte: usize, source: &str) -> Option Option { + let trimmed = line.trim(); + let rest = trimmed.strip_prefix("![")?; + let alt_end = rest.find("](")?; + let alt = rest[..alt_end].trim(); + if !alt.split_whitespace().any(|t| t == MAGIC) { + return None; + } + let key = parse_header_key(alt); + let after_alt = &rest[alt_end + 2..]; + let url_end = after_alt.rfind(')')?; + let url = after_alt[..url_end].trim(); + if url.is_empty() || validate_image_ref(url).is_err() { + return None; + } + // Span covers the trimmed image on its line (indent kept outside). + let trim_start = line.find(trimmed).unwrap_or(0); + let start = line_start + trim_start; + let end = start + trimmed.len(); + Some(BlockSpan { + start, + end, + body: url.to_string(), + start_line: line_number_at(source, start), + key, + kind: BlockKind::Image, }) } fn scan_blocks(source: &str) -> Vec { let mut out = Vec::new(); + // HTML comment blocks let mut i = 0usize; while i < source.len() { let rest = &source[i..]; @@ -186,6 +296,16 @@ fn scan_blocks(source: &str) -> Vec { } i = abs + end_rel + 3; } + // Image writebacks (line-oriented) + let mut line_start = 0usize; + for line in source.split_inclusive('\n') { + let content = line.trim_end_matches(['\r', '\n']); + if let Some(b) = parse_image_line(content, line_start, source) { + out.push(b); + } + line_start += line.len(); + } + out.sort_by_key(|b| b.start); out } @@ -323,7 +443,7 @@ fn find_keyed_in_cluster(source: &str, after_line: u32, key: &str) -> Option Result { let key = normalize_slot_key(key); - let block = format_block(body, Some(&key)); + let block = format_block_for_value(body, Some(&key))?; if let Some(existing) = find_keyed_in_cluster(source, anchor, &key) { return Ok(splice_block(source, existing.start, existing.end, &block)); } @@ -438,13 +558,13 @@ pub fn record( let stripped = find_eof_block(&source) .map(|b| strip_span(&source, b.start, span_end_including_nl(&source, b.end))) .unwrap_or_else(|| source.clone()); - append_eof(&stripped, &format_block(&body, None)) + append_eof(&stripped, &format_block_for_value(&body, None)?) } else { let line = anchor.ok_or_else(|| "writeback: missing anchor line".to_string())?; let stripped = find_adjacent_block(&source, line) .map(|b| strip_span(&source, b.start, span_end_including_nl(&source, b.end))) .unwrap_or_else(|| source.clone()); - insert_after_line(&stripped, line, &format_block(&body, None))? + insert_after_line(&stripped, line, &format_block_for_value(&body, None)?)? }; persist(ctx, &next)?; Ok(Value::Text(body.clone())) @@ -549,10 +669,15 @@ fn slots_from_source(source: &str) -> Value { .map(|b| { let anchor = anchor_line_above(source, b.start_line); let at_eof = b.key.is_none() && is_eof_block(source, &b); + let kind = match b.kind { + BlockKind::Comment => "comment", + BlockKind::Image => "image", + }; let mut entries = vec![ ("line".into(), Value::Int(anchor as i64)), ("body".into(), Value::Text(b.body)), ("at_end".into(), Value::Bool(at_eof)), + ("kind".into(), Value::Text(kind.into())), ]; if let Some(k) = b.key { entries.push(("key".into(), Value::Text(k))); @@ -584,29 +709,49 @@ pub fn ensure_slot( }) } -/// Map statement line → body for adjacent blocks (keyed slots included under their anchor). -pub fn writeback_map(source: &str) -> HashMap { - let mut map = HashMap::new(); +/// Structured writebacks keyed by the statement line above the block cluster. +pub fn writeback_entries(source: &str) -> HashMap> { + let mut map: HashMap> = HashMap::new(); for b in scan_blocks(source) { - let anchor = anchor_line_above(source, b.start_line); - let piece = match &b.key { - Some(k) => format!("[{k}]\n{}", b.body), - None => b.body.clone(), - }; - if b.key.is_none() && is_eof_block(source, &b) { - map.insert(0, piece); + let anchor = if b.key.is_none() && is_eof_block(source, &b) { + 0 } else { - map.entry(anchor) - .and_modify(|e| { - e.push_str("\n\n"); - e.push_str(&piece); - }) - .or_insert(piece); - } + anchor_line_above(source, b.start_line) + }; + let entry = WritebackEntry { + key: b.key.clone(), + body: b.body.clone(), + is_image: b.kind == BlockKind::Image, + }; + map.entry(anchor).or_default().push(entry); } map } +/// Map statement line → combined body for adjacent blocks (keyed slots included). +/// Image slots are encoded as a markdown image line so view/static can render ``. +pub fn writeback_map(source: &str) -> HashMap { + let mut map = HashMap::new(); + for (anchor, entries) in writeback_entries(source) { + let mut pieces = Vec::new(); + for e in entries { + let content = if e.is_image { + format!("![]({})", e.body) + } else { + e.body + }; + let piece = match &e.key { + Some(k) => format!("[{k}]\n{content}"), + None => content, + }; + pieces.push(piece); + } + map.insert(anchor, pieces.join("\n\n")); + } + map +} + + #[cfg(test)] mod tests { use super::*; @@ -614,7 +759,7 @@ mod tests { #[test] fn parse_and_insert_adjacent() { let src = "# main\n\n**x = 1**\n"; - let block = format_block("1", None); + let block = format_comment_block("1", None); let next = insert_after_line(src, 3, &block).unwrap(); assert!(next.contains("marqdo-out")); assert!(!next.contains("@line")); @@ -625,6 +770,79 @@ mod tests { assert!(!replaced.contains("marqdo-out")); } + #[test] + fn image_writeback_scan_and_format() { + assert!(looks_like_image_ref("plot.svg")); + assert!(looks_like_image_ref("https://ex.com/a.PNG")); + assert!(looks_like_image_ref("data:image/png;base64,xx")); + assert!(looks_like_image_ref("plots/a.svg?v=1")); + assert!(!looks_like_image_ref("readme.txt")); + assert!(!looks_like_image_ref("42")); + assert!(!looks_like_image_ref("svg")); // bare name, not an extension + assert!(!looks_like_image_ref(".svg")); + let block = format_image_block("out/plot.svg", Some("ok")); + assert_eq!(block, "![marqdo-out ok](out/plot.svg)"); + let src = "# main\n\n**x = 1**\n![marqdo-out ok](out/plot.svg)\n\n> print text=tail\n"; + let blocks = scan_blocks(src); + assert_eq!(blocks.len(), 1); + assert_eq!(blocks[0].kind, BlockKind::Image); + assert_eq!(blocks[0].body, "out/plot.svg"); + assert_eq!(blocks[0].key.as_deref(), Some("ok")); + let map = writeback_map(src); + assert_eq!( + map.get(&3).map(|s| s.as_str()), + Some("[ok]\n![](out/plot.svg)") + ); + // Invalid image URL in marqdo-out alt → not a writeback slot + let bad = "# main\n\n![marqdo-out](notes.txt)\n"; + assert!(scan_blocks(bad).is_empty()); + } + + #[test] + fn unkeyed_comment_and_image_replace_each_other() { + let src = "# main\n\n**x = 1**\n\n\n> print text=tail\n"; + let line = 3u32; + let to_image = { + let stripped = find_adjacent_block(src, line) + .map(|b| strip_span(src, b.start, span_end_including_nl(src, b.end))) + .unwrap_or_else(|| src.to_string()); + insert_after_line( + &stripped, + line, + &format_block_for_value("fig.svg", None).unwrap(), + ) + .unwrap() + }; + assert!(to_image.contains("![marqdo-out](fig.svg)")); + assert!(!to_image.contains("")); + assert!(!to_text.contains("![marqdo-out]")); + } + + #[test] + fn record_format_picks_image_for_svg_path() { + let s = format_block_for_value("figs/a.svg", None).unwrap(); + assert_eq!(s, "![marqdo-out](figs/a.svg)"); + let t = format_block_for_value("hello", None).unwrap(); + assert!(t.contains("\n\n> print text=tail\n"; @@ -671,7 +889,7 @@ mod tests { let stripped = find_adjacent_block(s, line) .map(|b| strip_span(s, b.start, span_end_including_nl(s, b.end))) .unwrap_or_else(|| s.to_string()); - insert_after_line(&stripped, line, &format_block(body, None)).unwrap() + insert_after_line(&stripped, line, &format_comment_block(body, None)).unwrap() }; let once = strip_insert(src, "a"); let twice = strip_insert(&once, "b"); diff --git a/src/lex/mod.rs b/src/lex/mod.rs index 06ef21d..ba119ad 100644 --- a/src/lex/mod.rs +++ b/src/lex/mod.rs @@ -292,9 +292,25 @@ fn breaks_comment_paragraph(trimmed: &str) -> bool { if trimmed.starts_with('+') { return true; } + if is_image_writeback_line(trimmed) { + return true; + } false } +/// `![marqdo-out …](image-url)` — image writeback surface (see stdlib-writeback). +pub fn is_image_writeback_line(trimmed: &str) -> bool { + let t = trimmed.trim(); + let Some(rest) = t.strip_prefix("![") else { + return false; + }; + let Some(alt_end) = rest.find("](") else { + return false; + }; + let alt = rest[..alt_end].trim(); + alt.split_whitespace().any(|tok| tok == "marqdo-out") +} + fn looks_like_ordered_list_item(trimmed: &str) -> bool { let mut chars = trimmed.chars(); let mut saw_digit = false; @@ -382,6 +398,9 @@ pub fn classify_source(source: &str) -> Vec { in_writeback = false; } LineKind::Writeback + } else if is_image_writeback_line(trimmed) { + in_comment_paragraph = false; + LineKind::Writeback } else { match base { LineKind::Blank => { @@ -547,6 +566,17 @@ mod tests { assert_eq!(lines[3].kind, LineKind::Writeback); } + #[test] + fn image_writeback_line_classified() { + assert!(is_image_writeback_line("![marqdo-out](a.svg)")); + assert!(is_image_writeback_line("![marqdo-out ok](plots/x.png)")); + assert!(!is_image_writeback_line("![plot](a.svg)")); + let src = "# main\n\n**x = 1**\n![marqdo-out](out.svg)\n\n> print text=x\n"; + let lines = classify_source(src); + let img = lines.iter().find(|l| l.text.contains("marqdo-out]")).unwrap(); + assert_eq!(img.kind, LineKind::Writeback, "{:?}", lines); + } + #[test] fn paragraph_comment_keeps_backtick_continuation() { let src = "采用了\n`.mq.md`的双层后缀\n\n> print text=ok\n"; diff --git a/src/view/document.rs b/src/view/document.rs index 1446a61..b1e489b 100644 --- a/src/view/document.rs +++ b/src/view/document.rs @@ -101,6 +101,10 @@ pub fn render_module_document(module: &Module, source: &str, annots: &[ViewAnnot } LineKind::Writeback => { flush_para(&mut para, &mut out); + out.push_str(&crate::view::render::render_writeback_source_line( + l.line_no, + l.text.trim_end_matches(['\r', '\n']), + )); i += 1; } LineKind::Comment => { @@ -313,11 +317,7 @@ fn render_table_block( } } if let Some(body) = writebacks.get(&first_line) { - html.push_str(&format!( - r#"
{}
"#, - escape(body), - line = first_line - )); + html.push_str(&crate::view::render::render_output_card(first_line, body)); } html.push_str(""); (html, i) @@ -746,11 +746,7 @@ fn render_line_block( } if let Some(body) = writeback_body { - s.push_str(&format!( - r#"
{}
"#, - escape(body), - line = line_no - )); + s.push_str(&crate::view::render::render_output_card(line_no, body)); } // Formula/code cards are the single visual truth — do not stack Bind chips diff --git a/src/view/html.rs b/src/view/html.rs index 1eb35be..6c445ed 100644 --- a/src/view/html.rs +++ b/src/view/html.rs @@ -972,6 +972,9 @@ ul.doc-loop, ol.doc-branch { border-left: 3px solid #2563eb; background: #f8fafc; } +.output-card.output-card-image { + border-left-color: #0d9488; +} .output-card .wb-badges { display: flex; flex-wrap: wrap; @@ -987,6 +990,58 @@ ul.doc-loop, ol.doc-branch { white-space: pre-wrap; color: #0f172a; } +.wb-figure { + margin: 0.5rem 0 0; + padding: 0; +} +.wb-image { + display: block; + max-width: 100%; + height: auto; + border-radius: 6px; + border: 1px solid var(--line); + background: #fff; +} +.wb-image-url { + margin: 0.35rem 0 0; + font: 0.75rem/1.35 var(--mono); + color: var(--muted); + word-break: break-all; +} +.doc-writeback { + margin: 0.35rem 0; + padding: 0.4rem 0.55rem; + border-radius: 8px; + border: 1px dashed #94a3b8; + background: #f1f5f9; + display: flex; + flex-wrap: wrap; + gap: 0.4rem 0.65rem; + align-items: baseline; +} +.doc-writeback[data-wb-kind="image"] { + border-color: #0d9488; + background: #f0fdfa; +} +.wb-source-badge { + font: 0.68rem/1.2 var(--sans); + letter-spacing: 0.04em; + text-transform: uppercase; + color: #334155; + background: #e2e8f0; + padding: 0.12rem 0.4rem; + border-radius: 4px; +} +.doc-writeback[data-wb-kind="image"] .wb-source-badge { + background: #ccfbf1; + color: #115e59; +} +.wb-source-text { + font: 0.82rem/1.4 var(--mono); + color: #0f172a; + white-space: pre-wrap; + word-break: break-all; +} .wb-outline { margin-top: 0.75rem; padding-top: 0.75rem; diff --git a/src/view/render.rs b/src/view/render.rs index 797d8e2..2237f8a 100644 --- a/src/view/render.rs +++ b/src/view/render.rs @@ -1070,17 +1070,89 @@ fn stmt_end_line(stmt: &Stmt) -> u32 { fn output_card(line: u32, writebacks: &HashMap) -> String { match writebacks.get(&line) { - Some(body) => { - let badges = writeback_badges(body); - format!( - r#"
{badges}
{}
"#, - escape(body) - ) - } + Some(body) => render_output_card(line, body), None => String::new(), } } +/// Live view + static site: text `
` and/or `` for image writebacks.
+pub fn render_output_card(line: u32, combined: &str) -> String {
+    if combined.trim().is_empty() {
+        return String::new();
+    }
+    let badges = writeback_badges(combined);
+    let mut body_html = String::new();
+    let mut buf_text = String::new();
+    let flush_text = |buf: &mut String, out: &mut String| {
+        if buf.is_empty() {
+            return;
+        }
+        out.push_str(&format!(
+            r#"
{}
"#, + escape(buf.trim_end()) + )); + buf.clear(); + }; + for line_s in combined.lines() { + let t = line_s.trim(); + if let Some(url) = extract_md_image_url(t) { + flush_text(&mut buf_text, &mut body_html); + body_html.push_str(&format!( + r#"
writeback
{cap}
"#, + src = escape(&url), + cap = escape(&url), + )); + } else { + if !buf_text.is_empty() { + buf_text.push('\n'); + } + buf_text.push_str(line_s); + } + } + flush_text(&mut buf_text, &mut body_html); + let has_img = body_html.contains("wb-image"); + format!( + r#"
{badges}
{body}
"#, + line = line, + img_cls = if has_img { " output-card-image" } else { "" }, + badges = badges, + body = body_html, + ) +} + +fn extract_md_image_url(line: &str) -> Option { + let t = line.trim(); + let rest = t.strip_prefix("![")?; + let alt_end = rest.find("](")?; + let after = &rest[alt_end + 2..]; + let url_end = after.rfind(')')?; + let url = after[..url_end].trim(); + if url.is_empty() { + None + } else { + Some(url.to_string()) + } +} + +/// Document-surface marker for a writeback source line (comment or image). +pub fn render_writeback_source_line(line_no: u32, text: &str) -> String { + let trimmed = text.trim(); + let is_image = trimmed.starts_with("![") && trimmed.contains("marqdo-out"); + let kind = if is_image { "image" } else { "comment" }; + let label = if is_image { + "writeback · image" + } else { + "writeback" + }; + format!( + r#"
{label}{text}
"#, + line = line_no, + kind = kind, + label = label, + text = escape(trimmed), + ) +} + fn writeback_badges(body: &str) -> String { let mut keys = Vec::new(); for line in body.lines() { @@ -1739,6 +1811,20 @@ mod tests { assert!(html.contains(">xs<") || html.contains("vars-name\">xs"), "{html}"); } + #[test] + fn output_card_renders_image_writeback() { + let html = render_output_card(3, "[ok]\n![](plots/a.svg)"); + assert!(html.contains("output-card-image"), "{html}"); + assert!(html.contains(r#"src="plots/a.svg""#), "{html}"); + assert!(html.contains("wb-ok") || html.contains(">ok<"), "{html}"); + let text = render_output_card(1, "plain-42"); + assert!(text.contains("output-body"), "{text}"); + assert!(!text.contains("wb-image"), "{text}"); + let src = render_writeback_source_line(4, "![marqdo-out](plots/a.svg)"); + assert!(src.contains(r#"data-wb-kind="image""#), "{src}"); + assert!(src.contains("writeback · image"), "{src}"); + } + #[test] fn structure_marks_inferred_params() { let src = include_str!("../../tests/markup-v03/inc-prose.mq.md");