From 7d49c358c10d4a0c3fafb3508bcdc3768e6eba04 Mon Sep 17 00:00:00 2001 From: cflmy Date: Thu, 15 Oct 2026 14:13:42 +0800 Subject: [PATCH] fix(view): nested-call welcome + clean formula/code cards Welcome pages put greet calls in # main so CallFrames/pickers appear; document surface skips fence body lines and Bind chips under formula/code cards. Adds view-static-interactive design and entry-vs-method regression tests. Co-authored-by: Cursor --- doc/design/user-site.md | 2 +- doc/design/view-static-interactive.md | 239 ++++++++++++++++++++++++++ doc/design/view.md | 2 +- public/00-welcome.mq.md | 62 +++---- public/00-欢迎.mq.md | 56 +++--- src/view/annot.rs | 67 ++++++++ src/view/document.rs | 142 +++++++++++++-- src/view/render.rs | 19 +- 8 files changed, 504 insertions(+), 85 deletions(-) create mode 100644 doc/design/view-static-interactive.md diff --git a/doc/design/user-site.md b/doc/design/user-site.md index 7414671..bbcc34b 100644 --- a/doc/design/user-site.md +++ b/doc/design/user-site.md @@ -4,7 +4,7 @@ |---|---| | 状态 | 已定 | | 日期 | 2026-08-04 | -| 相关 | [view.md](view.md) · 源目录 [`public/`](../../public/) | +| 相关 | [view.md](view.md) · [view-static-interactive.md](view-static-interactive.md)(静态交互 / 公式代码视觉 · Proposal) · 源目录 [`public/`](../../public/) | --- diff --git a/doc/design/view-static-interactive.md b/doc/design/view-static-interactive.md new file mode 100644 index 0000000..a23dc21 --- /dev/null +++ b/doc/design/view-static-interactive.md @@ -0,0 +1,239 @@ +# View:静态页交互与公式/代码卡视觉 + +| | | +|---|---| +| 状态 | **Active** | +| 日期 | 2026-10-15 | +| 相关 | [view.md](view.md) · [user-site.md](user-site.md) · [view-document-annotations.md](view-document-annotations.md) · [view-frame-selection.md](view-frame-selection.md) · [ADR 0002 browser WASM](../adr/0002-browser-marqdo-wasm.md) | + +**已确认(2026-10-15)** + +| 决策 | 选择 | +|------|------| +| 引擎 | **B**(快照 + S1 帧切换 + 可选懒加载 WASM S2) | +| 体验原则 | 静态页与 live view **尽量同构**;控件形态对齐;无服务端时用 WASM/JS 补齐 | +| 视觉原则 | **一层主视觉**;一眼能懂;公式/代码不与 Bind chip / 源残留叠床架屋 | +| 演示参数条 | **要**(历史实参 select + 可编辑;S1 切帧 / S2 重跑) | +| code-card Run | 有 WASM 时可用;否则隐藏(不对齐「假按钮」) | +| 公式 Bind chip | **卡内不显示**;Variables 可留终值 | + +--- + +## 1. 动机(对照 `public/00-欢迎.mq.md` / gh-pages) + +静态导出(`marqdo view output` → `gh-pages`)与 live `marqdo view` 已共用**文档面 Structure** 渲染路径,但用户站实测仍有三类落差: + +1. **交互控件缺失 / 偏弱** + - 函数「问候」仅有参数 chip「谁」,没有可切换的调用帧下拉(即便源里 `> 问候` 写了两次)。 + - 参数行 `+ 谁` 在文档面呈声明高亮,读者无法在静态页改「谁」并看到新输出。 + - 外联 `code-card` 的 Run 在静态模式被禁用(`Run is available in live marqdo view`)。 + - 静态 stdin 仅在有 preset 时显示只读提示,**不能**再跑。 + +2. **无服务端时仍可交互的预期** + 用户站是纯静态托管:没有 `/api/run`。合理路径是 **页内 JS** 和/或 **嵌入 Marqdo WASM**,在浏览器里重算 Structure 标注、Execution 区,甚至模拟 `input` / 外联(沙箱约束另定)。 + +3. **公式 / 代码块视觉凌乱** + 同一赋值同时出现多层表象,信息重复、线框错位: + + | 层 | 公式 `f = $$…$$` | 外联 `hi = ```python…``` | + |----|------------------|---------------------------| + | A 卡片 | `formula` badge + KaTeX | `code` badge + 高亮源码 + cmd/Run | + | B 标注 chip | `f` → `x^2 - 2` | `hi` → 整段 fence 摘要 | + | C 源残留 | 卡片外/旁再露 `$$` 或 ASCII | 卡片下再露 `python print…` 明文 | + + 再叠加 CSS L-leader 与卡内边框,首屏显得碎、重复、「坏掉的线」。 + +**本文件只定问题与方案;确认前不改代码。** + +--- + +## 2. 现状解剖 + +### 2.1 静态 vs live(同一 `page_file`) + +| 能力 | Live | Static(`LinkMode::Static`) | +|------|------|------------------------------| +| 文档面 Structure + annot | ✅(跑后) | ✅(导出时跑后写入) | +| call / loop picker JS | ✅(读 `#mq-view-trace`) | ✅(同源 JS;若轨迹未写入则无控件) | +| `/api/run` · Stream | ✅ | ❌ | +| stdin 表单 | ✅ 可再跑 | 只读 hint(或无) | +| code-card Run | ✅ `POST` 外联 | ❌ 禁用按钮 | +| WASM 重算 | ❌(未接) | ❌(未接) | + +结论:**不是「静态另做一套皮肤」**,而是「导出瞬间的快照 + 部分 JS 帧切换」;**没有**浏览器内重执行闭环。 + +### 2.2 欢迎页结构(问题复现源) + +```text +> 问候 谁=marqdo +> 问候 谁=marqdo user +## 问候 + + `谁` +> 打印 内容=欢迎,`谁`! +`f` = $$ x^2 - 2 $$ +`hi` = ```python … ``` +``` + +- 期望:`## 问候` 旁 **调用** 下拉(`1: 谁=marqdo` / `2: 谁=marqdo user`),切换时打印行的绑定/输出随帧变。 +- 现状风险:若导出时 CallFrame < 2、或 picker 未挂上、或读者期望的是「编辑谁」而非「选历史调用」,都会表现为「没有下拉框」。 +- 公式/代码:`SpecialAssign` → formula/code **card**,同时又对同名绑定建 **Bind annot**,文档面还可能保留块源视觉 → 三重展示。 + +### 2.3 已有红线(方案不得破坏) + +- 代码即文档:`.mq.md` 源可读;不发明第二套嵌套 DSL(见 web-artifact / marqdo-dev)。 +- Browse ≠ Debug:静态站不做断点。 +- `public/**/*.html` 不入库;gh-pages 由 CI/`view output` 生成([user-site.md](user-site.md))。 +- 外链字体禁令仍在 [view.md](view.md);WASM/重型资源须 **可选加载**,默认站可降级为纯快照。 + +--- + +## 3. 目标(验收口径) + +### G1 — 帧与参数交互(静态可读、可拨) + +1. 同函数 ≥2 次调用时,静态页 **必有**「调用」下拉;默认末次;切换只改 chip/臂/相关输出,**源码常显**(同 [view-frame-selection.md](view-frame-selection.md))。 +2. 导出保证写入完整 `#mq-view-trace`(含 `calls` / `events` / 可选 `loops`)。 +3. (增强)演示向参数可提供 **受控输入**:默认值来自末次调用或 FM;改参后可触发页内重算(见 §5 引擎选项)。 + +### G2 — 无服务端可重算(可选引擎) + +| 档位 | 能力 | 依赖 | +|------|------|------| +| **S0 快照**(现状加强) | 导出时跑完;帧 picker;只读 Execution | 无 WASM | +| **S1 页内重放轨迹** | 不重跑程序,只切换已序列化帧/标注 | JSON only | +| **S2 WASM 重跑** | `marqdo_wasm` + bridge:改 stdin/实参后重跑,刷新 Structure/Execution | WASM 包(可 CDN/`public/wasm/`) | +| **S3 外联沙箱** | code-card Run:浏览器内 pyodide **或** 明确标「仅 live」 | 可选;默认可关 | + +默认用户站:**S0 + S1 必达**;**S2 为推荐主路径**(与「用 wasm 模拟输出」对齐);S3 单独开关。 + +### G3 — 公式 / 代码视觉单层真相 + +对「特殊赋值」块约定 **一层主视觉 + 至多一层结果**: + +| 块 | 主视觉 | 允许的结果层 | 禁止 | +|----|--------|--------------|------| +| 公式 | KaTeX(formula-card 精简) | 无 Bind chip,或仅在 Variables | 再渲一份 `$$` 明文;annot 与卡重复同一 TeX | +| 外联代码 | 高亮源码(code-card) | 运行输出区 `code-out`;静态可藏 Run 或接 S2/S3 | annot 再贴整段 fence;卡下重复裸源 | +| 普通赋值 | 标记面语句 | Bind chip + L-leader | — | + +Leader:仅连接「主视觉锚点 → 唯一结果 chip」;卡内不用第二套 L 线。 + +--- + +## 4. 问题清单(成文) + +| ID | 问题 | 严重度 | 根因假设 | +|----|------|--------|----------| +| P1 | 静态页看不到调用/循环下拉 | 高 | 轨迹未导出完整 / picker 条件(≥2)未满足 / 读者要的是编辑参而非选帧 | +| P2 | 不能改参/stdin 再看输出 | 高 | Static 禁用 `/api/run`;无 WASM 闭环 | +| P3 | code-card Run 静态无效 | 中 | `initForeignCards` 显式禁用 | +| P4 | 公式卡 + chip + `$$` 三重 | 高 | card 与 Bind annot 叠加;块源未完全被 SpecialAssign 吞掉 | +| P5 | 代码卡 + chip + 明文三重 | 高 | 同 P4 | +| P6 | 卡内/旁碎线、错位 | 中 | leader 锚到错误节点;卡 CSS 与 annot-band 叠层 | +| P7 | 静态 stdin 体验差 | 中 | 仅有只读 hint | + +--- + +## 5. 解决方案(详案,待选) + +### 5.1 引擎策略(三选一,推荐 **B**) + +| 方案 | 做法 | 优点 | 代价 | +|------|------|------|------| +| **A. 纯快照 + S1** | 加强导出轨迹与 picker;不引入 WASM | 体积小、离线稳 | 不能改参真重算 | +| **B. 快照默认 + 可选 WASM(S0/S1/S2)** | `view output` 仍嵌入跑后 HTML;页脚/侧栏「在浏览器中重跑」懒加载 WASM;改参后 patch Structure/Execution | 对齐用户预期;无 WASM 时仍可读 | 打包/加载体积;宿主能力子集 | +| **C. 静态页全面 WASM 首屏** | 打开即 WASM 跑 | 交互最强 | 冷启动慢;gh-pages 带宽;与「文档先可读」冲突 | + +**推荐 B**:文档先可读(S0),帧切换不依赖 WASM(S1),需要改参/演示时再拉 WASM(S2)。 + +### 5.2 交互控件(与文档面一致) + +1. **调用 / 循环 picker**(已有组件) + - 导出验收:欢迎页「问候」必须出现调用下拉。 + - 单测:对 `00-欢迎.mq.md` / `document-annot-demo` 断言 HTML 含 `call-picker` 且 options≥2。 + +2. **演示参数条(新,窄范围)** + - 仅当函数被标记为「可演示」**或**静态页检测到 ≥1 形参且存在 CallFrame 时,在函数标题旁增加: + `谁 [ text input | select(历史实参) ] [应用]` + - **不**改 `.mq.md` 语法;数据来自 trace 的 `args_brief` / 末次绑定。 + - 「应用」:S1 仅切换已有帧;S2 调 WASM `run` 后替换 `#structure` / Execution。 + +3. **stdin** + - 静态:若源含 `input`,渲染与 live 同形的 textarea +「重跑」(S2)或说明「需 WASM」。 + - 无 input 则不显示。 + +### 5.3 公式 / 代码去重(视觉) + +**规则:SpecialAssign 行只走 card,不再为同名同值挂 Bind chip。** + +```text +公式赋值行 + └─ formula-card(badge + 名 + KaTeX) + └─ ✗ 不再 render_annot_band(Bind f) + └─ ✗ 不再在卡外输出 $$ 源 + +外联赋值行 + └─ code-card(badge + 名 + 高亮体 + 可选 Run) + └─ ✗ 不再 Bind chip 贴 fence 全文 + └─ 运行结果只进 .code-out +``` + +静态 Run 策略(与 §5.1 对齐): + +- S0:隐藏 Run,或保留禁用并 tooltip「打开 live view / 启用 WASM」。 +- S2:Run → WASM 宿主 `foreign`(若 WASM 支持)或提示不支持。 +- S3:可选 Pyodide(默认关)。 + +CSS:formula-card / code-card 与 `.annot-band` 垂直节奏统一;禁止对 KaTeX 节点拉 L-leader。 + +### 5.4 导出管线 + +```text +marqdo view output + → build_file_view(跑 + annot + trace_json) // 已有 + → page_file(Static) + + 嵌入 #mq-view-trace + + (可选)data-wasm-url / 懒加载脚本 + + 公式/代码去重后的 structure_html + → public/ + gh-pages +``` + +`--no-exec`:文档面无标注;可提示「本页为结构-only」;S2 仍可尝试 WASM 首跑(可选,默认关以免惊喜执行)。 + +### 5.5 明确不做(本提案) + +- 静态页断点调试(仍属 `marqdo debug`)。 +- 在 `public/*.mq.md` 发明新的「交互表」DSL(除非另开设计并获批)。 +- 默认全站加载 Pyodide。 +- 提交生成 HTML 进 `main`。 + +--- + +## 6. 分阶段开发计划(确认后执行) + +| 阶段 | 内容 | 交付 | 依赖确认 | +|------|------|------|----------| +| **D0** | 本文定稿;选定引擎 **A/B/C**;是否要「演示参数条」 | 状态 → Active | **本次决策** | +| **D1** | P4/P5/P6:SpecialAssign 与 Bind 互斥;卡 CSS;去掉重复源 | 欢迎页公式/代码干净;单测 | D0 | +| **D2** | P1:导出轨迹验收 + 欢迎页 call-picker 金样;修任何「≥2 调用无下拉」bug | HTML 断言 | D0 | +| **D3** | P2/P7 S1 夯实:静态 stdin UI 形态;无 WASM 时文案清晰 | UX | D0 | +| **D4** | (若选 B)S2:静态页懒加载 WASM;「应用参数 / 重跑」刷新 Structure+Execution | `public/wasm` 或 CDN 策略;体积预算 | D0=B | +| **D5** | P3:code-card 与 S2/S3 策略落地;默认隐藏无效 Run | — | D1+D4 | +| **D6** | `build-public` / pages CI 回归;更新 [user-site.md](user-site.md) · [view.md](view.md) 验收条 | gh-pages 抽检欢迎页 | D1–D5 | + +建议默认路径:**D0 选 B → D1 → D2 → D3 → D4 → D5 → D6**。 + +--- + +## 7. 决策记录 + +见文首「已确认」。开发按 §6:D1 → D2 → D3 → D4 → D5 → D6。 + +--- + +## 8. 修订历史 + +| 日期 | 说明 | +|------|------| +| 2026-10-15 | 初稿:静态交互缺口、公式/代码凌乱、S0–S3 与阶段 D0–D6 | +| 2026-10-15 | Active:引擎 B;对齐 live;干净视觉;演示参数条;Run 接 WASM 否则隐藏 | diff --git a/doc/design/view.md b/doc/design/view.md index b478b69..3bf8fd4 100644 --- a/doc/design/view.md +++ b/doc/design/view.md @@ -4,7 +4,7 @@ |---|---| | 状态 | 已定(v0.0.2 方向) | | 日期 | 2026-08-04 | -| 相关 | [examples-and-tests.md](examples-and-tests.md) · [view-markup-surface.md](view-markup-surface.md) · [view-document-annotations.md](view-document-annotations.md) · [generated-yaml-manifest.md](generated-yaml-manifest.md) · 视觉参考 [id.cflmy.cn](https://id.cflmy.cn) | +| 相关 | [examples-and-tests.md](examples-and-tests.md) · [view-markup-surface.md](view-markup-surface.md) · [view-document-annotations.md](view-document-annotations.md) · [view-static-interactive.md](view-static-interactive.md) · [generated-yaml-manifest.md](generated-yaml-manifest.md) · 视觉参考 [id.cflmy.cn](https://id.cflmy.cn) | --- diff --git a/public/00-welcome.mq.md b/public/00-welcome.mq.md index 061d067..cd8cce7 100644 --- a/public/00-welcome.mq.md +++ b/public/00-welcome.mq.md @@ -1,40 +1,21 @@ --- title: Welcome to Marqdo -description: User docs home — code is documentation (English) +description: User-docs home — code as documentation (English) import math:lib/math.mq.md import foreign:lib/foreign.mq.md --- # main -Hi — thanks for reading this far. I am Marqdo’s developer. Marqdo is a language where *code is documentation, and documentation is code*: Markdown markers are the program structure, so what you read is what runs. +Hello — and welcome. I built Marqdo so that *code is documentation and documentation is code*: Markdown markers are the program structure, so what you read is what runs. -AI already prefers Markdown-shaped output. The idea was: why keep docs and code as two separate worlds? So Marqdo was born as a “docs are code” language. To keep every source renderable as Markdown, files use the `.mq.md` suffix. From early on we aimed for richer tooling — auto-generated YAML for OKF-style knowledge bases, even auto-generated slides — those are later goals. Happily, it already works well as a blogging tool: yes, this site is generated by Marqdo. And when AI writes Marqdo, you tend to burn fewer tokens — wallets everywhere thank you. +AI systems already favor Markdown-shaped output. That raised a simple question: why keep docs and programs as two separate artifacts? Marqdo is the answer. The `.mq.md` suffix exists so a file stays renderable as Markdown while remaining executable. Richer OKF-style YAML catalogs and even slide decks are on the roadmap; for now this site itself is generated by Marqdo — and that often saves tokens when an AI is writing with you. -The language is still young: structure markers, bilingual core names (`print` / `打印`, …), importable stdlibs (see [`stdlib/`](stdlib/) on this site), local `view`, and static export. Contribute on [GitHub](https://github.com/cflmy/marqdo). - -## Install - -Pick one way to get the CLI: - -| Method | Notes | -|--------|-------| -| Ubuntu PPA | `sudo add-apt-repository ppa:cflmy/marqdo` then `sudo apt install marqdo` | -| GitHub Releases | Prebuilt Windows / Linux zips at [releases](https://github.com/cflmy/marqdo/releases) | -| From source | `cargo build --release` (needs Rust) | - -Official extensions version independently of the CLI: - -```text -marqdo ext add web -marqdo ext add quantum -``` - -`ext add` tries CDN https://ext.marqdo.com first, then GitHub, then the proxy mirror. See [`features/05-extensions.mq.md`](features/05-extensions.mq.md). +The language is still early: structural markers, English/Chinese builtin aliases (`print` / `打印` …), an importable standard library (see [`stdlib/`](stdlib/) on this site), local `view`, and static export. Join in at [GitHub](https://github.com/cflmy/marqdo). 中文文档请看同目录的 [`00-欢迎.mq.md`](00-欢迎.mq.md)(叙述与内置均用中文)。 -A small function to say hello: +A small function to say hello (calls in entry `# main` actually run; `##` children are methods and do not auto-run): > greet who=marqdo @@ -42,13 +23,6 @@ Named args can include spaces: > greet who=marqdo user -## greet - + `who` - -> print text=Welcome, `who`! - -*None* - Beyond the basics above, Marqdo also ships standard libraries: table, time, text, files, system, math, foreign, and more. Math and foreign deserve a special mention. With the math library you can bind a formula like this: @@ -72,3 +46,29 @@ print("hello-from-python") Under Markdown this stays easy to read — which is the point: Marqdo’s design is code as documentation, documentation as code. Welcome again — enjoy exploring Marqdo. + +## greet + + `who` + +> print text=Welcome, `who`! + +*None* + +## install + +Install the interpreter (CLI) in any of these ways: + +| Way | Notes | +|------|------| +| Ubuntu PPA | `sudo add-apt-repository ppa:cflmy/marqdo` then `sudo apt install marqdo` | +| GitHub Releases | Prebuilt Windows / Linux packages from [releases](https://github.com/cflmy/marqdo/releases) | +| From source | `cargo build --release` (needs a local Rust toolchain) | + +Official extensions update independently of the CLI: + +```text +marqdo ext add web +marqdo ext add quantum +``` + +`ext add` tries CDN https://ext.marqdo.com first, then GitHub, then the proxy mirror. See [`features/05-extensions.mq.md`](features/05-extensions.mq.md). diff --git a/public/00-欢迎.mq.md b/public/00-欢迎.mq.md index f109480..97bf98d 100644 --- a/public/00-欢迎.mq.md +++ b/public/00-欢迎.mq.md @@ -13,28 +13,9 @@ AI 偏爱 Markdown结构的输出。作者的念头是:何必再把文档和 语言仍在起步:结构标记、中英内核双名(`打印` / `print` …)、可导入的标准库(见本站 [`stdlib/`](stdlib/))、本地 `view` 与静态导出。欢迎到 [GitHub](https://github.com/cflmy/marqdo) 一起做。 -## 安装 - -解释器(CLI)任选其一: - -| 方式 | 说明 | -|------|------| -| Ubuntu PPA | `sudo add-apt-repository ppa:cflmy/marqdo` 后 `sudo apt install marqdo` | -| GitHub Releases | [releases](https://github.com/cflmy/marqdo/releases) 下载 Windows / Linux 预编译包 | -| 源码 | `cargo build --release`(需本机 Rust) | - -官方扩展与 CLI 可分开更新。安装扩展: - -```text -marqdo ext add web -marqdo ext add quantum -``` - -`ext add` 下载顺序:CDN https://ext.marqdo.com → GitHub → proxy 镜像。详见本站 [`features/05-扩展.mq.md`](features/05-扩展.mq.md)。 - English docs: [`00-welcome.mq.md`](00-welcome.mq.md) (English prose and English builtins). -用一个小函数打个招呼: +用一个小函数打个招呼(入口 `# main` 里的调用会真正执行;`##` 子标题是方法,不会自动跑): > 问候 谁=marqdo @@ -42,13 +23,6 @@ English docs: [`00-welcome.mq.md`](00-welcome.mq.md) (English prose and English > 问候 谁=marqdo user -## 问候 - + `谁` - -> 打印 内容=欢迎,`谁`! - -*None* - 除了上面的一些基本内容之外,我还开发了这个语言的一些标准库,包括表、时间、文本、文件、系统、数学和外联等标准库。 其中数学库和外联库是我要着重提到的,例如数学库,你可以通过下面的方式调用: @@ -72,4 +46,30 @@ print("hello-from-python") 这些代码在markdown下面都非常的易读,就像我说的,marqdo的设计思想就是代码即文档, 文档即代码。 -最后,再次欢迎你,尽情体验marqdo吧! \ No newline at end of file +最后,再次欢迎你,尽情体验marqdo吧! + +## 问候 + + `谁` + +> 打印 内容=欢迎,`谁`! + +*None* + +## 安装 + +解释器(CLI)任选其一: + +| 方式 | 说明 | +|------|------| +| Ubuntu PPA | `sudo add-apt-repository ppa:cflmy/marqdo` 后 `sudo apt install marqdo` | +| GitHub Releases | [releases](https://github.com/cflmy/marqdo/releases) 下载 Windows / Linux 预编译包 | +| 源码 | `cargo build --release`(需本机 Rust) | + +官方扩展与 CLI 可分开更新。安装扩展: + +```text +marqdo ext add web +marqdo ext add quantum +``` + +`ext add` 下载顺序:CDN https://ext.marqdo.com → GitHub → proxy 镜像。详见本站 [`features/05-扩展.mq.md`](features/05-扩展.mq.md)。 diff --git a/src/view/annot.rs b/src/view/annot.rs index 4ba424e..8ec363c 100644 --- a/src/view/annot.rs +++ b/src/view/annot.rs @@ -835,6 +835,73 @@ mod tests { ); } + + /// `# main` is the entry object; `##` children are methods. A `>` call under + /// `## 安装` belongs to that method — it does **not** run until something + /// calls `安装`. This is object semantics, not a parser failure. + #[test] + fn call_under_child_heading_does_not_auto_run() { + let src = r#"--- +title: t +--- + +# main + +## 安装 + +> 问候 谁=a + +## 问候 + + `谁` + +> print text=hi `谁` +"#; + let module = crate::parse::parse_source(src).unwrap(); + let main = &module.functions[0]; + assert_eq!(main.name, "main"); + let install = main.children.iter().find(|c| c.name == "安装").expect("安装"); + let install_calls: Vec<_> = install + .body + .iter() + .filter_map(|s| match s { + crate::ast::Stmt::Call { call, .. } => Some(call.callee.as_str()), + _ => None, + }) + .collect(); + let main_calls: Vec<_> = main + .body + .iter() + .filter_map(|s| match s { + crate::ast::Stmt::Call { call, .. } => Some(call.callee.as_str()), + _ => None, + }) + .collect(); + assert!(main_calls.is_empty()); + assert_eq!(install_calls, ["问候"]); + let cap = crate::run_source(src, &crate::RunOptions::default()).unwrap(); + assert!( + cap.stdout.trim().is_empty(), + "entry does not auto-run ## 安装; stdout={:?}", + cap.stdout + ); + assert!( + !cap.view_trace.calls.iter().any(|c| c.fn_name == "问候"), + "no CallFrame for 问候 when only nested under uncalled ## 安装" + ); + } + + #[test] + fn call_in_main_before_child_def_runs_like_nested_call() { + let src = include_str!("../../tests/structure/nested-call.mq.md"); + let cap = crate::run_source(src, &crate::RunOptions::default()).unwrap(); + assert!(cap.stdout.contains("Hello"), "{:?}", cap.stdout); + assert!( + cap.view_trace.calls.iter().any(|c| c.fn_name == "问候"), + "expected CallFrame for 问候: {:?}", + cap.view_trace.calls + ); + } + #[test] fn report_json_has_version() { let cap = RunCapture { diff --git a/src/view/document.rs b/src/view/document.rs index 2a17539..1d649f9 100644 --- a/src/view/document.rs +++ b/src/view/document.rs @@ -23,7 +23,8 @@ pub fn render_module_document(module: &Module, source: &str, annots: &[ViewAnnot let lines = classify_source(source); let by_line = annots_by_line(annots); let fun_by_line = index_functions(module); - let special = index_special_assigns(module); + let special = index_special_assigns(module, source); + let skip_body = special_body_lines(&special); let stmt_lines = index_stmt_lines(module); let writebacks = writeback::writeback_map(source); let taken_arms = taken_arms_by_branch_line(annots); @@ -77,6 +78,12 @@ pub fn render_module_document(module: &Module, source: &str, annots: &[ViewAnnot i += 1; continue; } + // Body lines of $$ / ``` already folded into formula/code cards. + if skip_body.contains(&l.line_no) { + flush_para(&mut para, &mut out); + i += 1; + continue; + } // GFM table block (may be Comment or Code classified). if looks_like_table_row(l.text.trim()) { @@ -671,13 +678,14 @@ fn render_line_block( ); match special { - Some(SpecialAssign::Formula { name, tex }) => { + Some(SpecialAssign::Formula { name, tex, .. }) => { s.push_str(&render_formula_assign_card(name, tex)); } Some(SpecialAssign::Code { name, lang, source, + .. }) => { s.push_str(&render_code_assign_card(name, lang, source)); } @@ -716,15 +724,34 @@ fn render_line_block( )); } - if !annots.is_empty() { - let owned: Vec = annots.iter().map(|a| (*a).clone()).collect(); - s.push_str(&render_annot_band(&owned, MAX_VISIBLE_ANNOTS)); + // Formula/code cards are the single visual truth — do not stack Bind chips + // (or fence/SVG dumps) underneath. Variables rail still has final values. + let band_annots: Vec = if special.is_some() { + Vec::new() + } else { + annots + .iter() + .filter(|a| !is_noisy_result_chip(a)) + .map(|a| (*a).clone()) + .collect() + }; + if !band_annots.is_empty() { + s.push_str(&render_annot_band(&band_annots, MAX_VISIBLE_ANNOTS)); } s.push_str(""); s } +/// Huge SVG / fenced code dumps make annot bands unreadable — keep those out of chips. +fn is_noisy_result_chip(a: &ViewAnnot) -> bool { + if a.kind != crate::view::annot::AnnotKind::Bind { + return false; + } + let v = a.detail.as_str(); + v.contains(" 96 +} + /// Render prose with markers stripped; show surface inner text only. fn render_prose_with_marks( line_no: u32, @@ -792,8 +819,36 @@ fn match_annot_for_span<'a>( #[derive(Clone)] enum SpecialAssign { - Formula { name: String, tex: String }, - Code { name: String, lang: String, source: String }, + Formula { + name: String, + tex: String, + /// Last source line of the `$$ … $$` block (inclusive). + end_line: u32, + }, + Code { + name: String, + lang: String, + source: String, + /// Last source line of the fenced block (inclusive). + end_line: u32, + }, +} + +fn special_body_lines(special: &HashMap) -> HashSet { + let mut s = HashSet::new(); + for (start, sp) in special { + let end = match sp { + SpecialAssign::Formula { end_line, .. } | SpecialAssign::Code { end_line, .. } => { + *end_line + } + }; + let mut ln = *start + 1; + while ln <= end { + s.insert(ln); + ln += 1; + } + } + s } fn index_functions(module: &Module) -> HashMap { @@ -858,32 +913,33 @@ fn stmt_line(st: &Stmt) -> u32 { } } -fn index_special_assigns(module: &Module) -> HashMap { +fn index_special_assigns(module: &Module, source: &str) -> HashMap { + let src_lines: Vec<&str> = source.lines().collect(); let mut m = HashMap::new(); - fn walk(fun: &Function, m: &mut HashMap) { + fn walk(fun: &Function, m: &mut HashMap, src_lines: &[&str]) { for st in &fun.body { - record(st, m); + record(st, m, src_lines); match st { Stmt::Branch { arms, .. } => { for arm in arms { for b in &arm.body { - record(b, m); + record(b, m, src_lines); } } } Stmt::While { body, .. } | Stmt::ForEach { body, .. } => { for b in body { - record(b, m); + record(b, m, src_lines); } } _ => {} } } for c in &fun.children { - walk(c, m); + walk(c, m, src_lines); } } - fn record(st: &Stmt, m: &mut HashMap) { + fn record(st: &Stmt, m: &mut HashMap, src_lines: &[&str]) { match st { Stmt::Assign { name, @@ -895,11 +951,13 @@ fn index_special_assigns(module: &Module) -> HashMap { crate::formula::Expr::Matrix { source, .. } => source.clone(), _ => crate::view::render::formula_ascii_to_tex_pub(&e.as_display()), }; + let end_line = fence_block_end(src_lines, span.line, "$$"); m.insert( span.line, SpecialAssign::Formula { name: name.clone(), tex, + end_line, }, ); } @@ -909,12 +967,14 @@ fn index_special_assigns(module: &Module) -> HashMap { span, .. } => { + let end_line = fence_block_end(src_lines, span.line, "```"); m.insert( span.line, SpecialAssign::Code { name: name.clone(), lang: c.lang.clone(), source: c.source.clone(), + end_line, }, ); } @@ -922,11 +982,63 @@ fn index_special_assigns(module: &Module) -> HashMap { } } for f in &module.functions { - walk(f, &mut m); + walk(f, &mut m, &src_lines); } m } +/// Inclusive end line of a `$$` / ` ``` ` block starting on or after `assign_line`. +fn fence_block_end(src_lines: &[&str], assign_line: u32, fence: &str) -> u32 { + let start = assign_line as usize; // 1-based → index of next line candidate + if start == 0 || start > src_lines.len() { + return assign_line; + } + let mut i = start; // 0-based index of line after assign (assign_line is 1-based) + // Allow fence on the assign line itself after `=`. + let assign = src_lines.get(assign_line as usize - 1).copied().unwrap_or(""); + if assign.contains(fence) && fence == "$$" { + // rare one-liner + } + let mut seen_open = false; + while i < src_lines.len() { + let t = src_lines[i].trim(); + let line_no = (i + 1) as u32; + if !seen_open { + if t.starts_with(fence) { + seen_open = true; + if fence == "```" && t == "```" { + // closing without open — stop + return line_no; + } + // opening ```lang or $$ + if fence == "$$" && t == "$$" { + // look for closing $$ + i += 1; + while i < src_lines.len() { + let t2 = src_lines[i].trim(); + let ln = (i + 1) as u32; + if t2 == "$$" { + return ln; + } + i += 1; + } + return line_no; + } + } else if t.is_empty() { + i += 1; + continue; + } else { + // no fence body + return assign_line; + } + } else if fence == "```" && t.starts_with("```") { + return line_no; + } + i += 1; + } + assign_line +} + fn skip_frontmatter_end(lines: &[ClassifiedLine]) -> Option { let first_code = lines.iter().find(|l| l.kind == LineKind::Code)?; if first_code.text.trim() != "---" { diff --git a/src/view/render.rs b/src/view/render.rs index ddb0947..67fc450 100644 --- a/src/view/render.rs +++ b/src/view/render.rs @@ -1440,25 +1440,26 @@ pub(crate) fn formula_ascii_to_tex_pub(ascii: &str) -> String { formula_ascii_to_tex(ascii) } -/// Formula assign card for document surface embedding. +/// Formula assign card for document surface embedding (single visual layer). pub(crate) fn render_formula_assign_card(name: &str, tex: &str) -> String { format!( - "
formula \ - `{}` = \ -
$${}$$
", - escape(name), - escape(tex), + r#"
+
formula {name}
+
$${tex}$$
+
"#, + name = escape(name), + tex = escape(tex), ) } -/// Foreign code assign card for document surface embedding. +/// Foreign code assign card for document surface embedding (single visual layer). pub(crate) fn render_code_assign_card(name: &str, lang: &str, source: &str) -> String { let placeholder = escape(&crate::foreign::default_cmd_display(lang)); format!( - r#"
+ r#"
code - `{name}` = + {name} {lang}