Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
66926e9e0a | ||
|
|
dcf4c05663 | ||
|
|
f47a1e143a | ||
|
|
9cf98a98b5 | ||
|
|
f99d552d87 | ||
|
|
7d49c358c1 | ||
|
|
a32c0cd78f |
No files matched your search
@@ -113,8 +113,10 @@ printf '%s\n' '{"id":5,"method":"repair_targets","params":{"code":"contract.arg_
|
||||
| `****` / whole-line `**` / `*None*` | Return `None` and end function body |
|
||||
| Lone `---` / `***` | Markdown thematic break (skip; not function end) |
|
||||
| GFM table after empty RHS bind | Collection; get with `[key](coll)` (preferred) or legacy `` `m`[^key] `` |
|
||||
| `- [item](coll)` | Foreach (unchanged) |
|
||||
| `` ```lang `` | Foreign code block (via `lib/foreign`) |
|
||||
| `` ```lang `` | Foreign code block (via `lib/foreign`); bind with `` `name` = `` then fence |
|
||||
| `$$` + `% marqdo: var=name` | Block formula bind (TeX comment; prefer over empty RHS) |
|
||||
| `- [item](coll)` | Foreach (**preferred**, nestable). Sugar: `- 对`coll`的每一项`item`` / `- for each `item` in `coll`` |
|
||||
| `` | Image writeback form (validated stem.ext / URL); text writeback stays HTML comment |
|
||||
| `` `"text"` `` | Quoted string (`\n` `\t` `\\` `\"`; `` `var` `` inside); bare tokens unescaped |
|
||||
| Unmarked prose | Comment |
|
||||
|
||||
@@ -138,20 +140,19 @@ Chinese builtins (same functions, no import):
|
||||
|
||||
## Functions, calls, end-body
|
||||
|
||||
Prefer **body-inferred params** and **prose-unified** wording (v0.3). `` + `name` `` still works, but teach the inferred form first:
|
||||
|
||||
```markdown
|
||||
# main
|
||||
|
||||
> greet who=Marqdo
|
||||
**greet who="Marqdo"**
|
||||
|
||||
## greet
|
||||
+ `who`
|
||||
|
||||
> print text=Hello, `who`!
|
||||
|
||||
*None*
|
||||
When we meet`who`, we **print text="Hello, `who`!"** and close with*None*.
|
||||
```
|
||||
|
||||
- Call: `> name key=value` or `> name value`.
|
||||
- Call: `**fn key="text"**` (bold; quote text literals) or `> fn key=text` (standalone `>`; bare words are text).
|
||||
- Nested helpers use deeper `#` (`##`, `###`, …).
|
||||
- After a helper with only side effects, end with `*None*` / whole-line `**` / `****` when later lines must stay in the outer function. Lone `---` is only a thematic break (skipped).
|
||||
- In bold assigns, prefer bare calls: `**摘要 = 结账摘要 …**` (omit `>`).
|
||||
@@ -163,9 +164,8 @@ Chinese builtins (same functions, no import):
|
||||
**y = x + 2**
|
||||
|
||||
## add_one
|
||||
+ `n`
|
||||
|
||||
*n + 1*
|
||||
For input`n`, do **n = n + 1** and return*n*.
|
||||
```
|
||||
|
||||
```markdown
|
||||
|
||||
@@ -126,6 +126,8 @@ jobs:
|
||||
## Marqdo ${{ github.ref_name }}
|
||||
|
||||
### 亮点 / Highlights
|
||||
- **v1.4.0**:叙述统一——`% marqdo: var=` · 臂/循环体叙述 · foreach 中英糖 · 图片自写回 · view 推断形参
|
||||
- **v1.4.0**: Prose-unified control flow — formula meta bind, arm/loop narrative, foreach sugar, image writeback, inferred-param view
|
||||
- **v1.3.3**:view 文档面 Structure——叙述保真 · 标记面 · 调用/循环帧 · `#mq-view-trace` · 静态站同源
|
||||
- **v1.3.3**: Browse document-surface Structure — narration, markers, call/loop frames, `#mq-view-trace`, static site parity
|
||||
- **v1.3.0**:Engineering Knowledge Compiler——L0–L4 · `reuse`/`find`/`duplicate` · Agent preflight(REUSE→ADAPT→CREATE)
|
||||
|
||||
@@ -8,6 +8,37 @@
|
||||
|
||||
### Changed
|
||||
|
||||
## v1.4.0 — 2026-10-15
|
||||
|
||||
### Highlights
|
||||
|
||||
**叙述统一 + 公式 meta + 图片自写回**:块公式 `% marqdo: var=`;分支/循环体与函数体同权叙述;foreach 中英糖;自写回图片 ``(扩展名校验)与 view/静态站同源标记;view 展示推断形参实值;欢迎页迁到 v0.3 叙述面。
|
||||
|
||||
```bash
|
||||
git checkout v1.4.0 && cargo build --release
|
||||
marqdo run tests/markup-v03/formula-meta-var.mq.md
|
||||
marqdo run tests/markup-v03/foreach-narrative.mq.md
|
||||
marqdo view tests/view/document-annot-demo.mq.md --no-open
|
||||
# Ubuntu: sudo apt update && sudo apt install marqdo
|
||||
marqdo ext add web # CDN latest → 1.4.0
|
||||
```
|
||||
|
||||
**核心表面 Δ(Core surface Δ)**:**无增删**——19 个核心构造不变。Language 层在既有 `formula` / `branch-list` / `loop-list` 上扩展语义(块公式 TeX 注释绑定、臂/循环体叙述、foreach 糖);Runtime:自写回图片形态 + view 推断形参展示。设计:[fence-meta-and-control-prose.md](doc/design/fence-meta-and-control-prose.md) · [stdlib-writeback.md](doc/design/stdlib-writeback.md)。
|
||||
|
||||
### Added
|
||||
- **块公式 meta 绑定**:`$$` 内 `% marqdo: var=<ident>`(剥离后解析;可无空 RHS);金样 `tests/markup-v03/formula-meta-var.mq.md`。
|
||||
- **控制流叙述统一**:臂/循环体 `parse_indented_body` 与函数体同权;分支条件行支持叙述前缀与行内 `**…**`;foreach 糖 `- 对…的每一项…` / `- for each … in …`。
|
||||
- **图片自写回**:路径/URL 且扩展名合法 → ``;文本仍 HTML 注释;view / `view output` 同源样式卡与 `<img>`。
|
||||
- **view 推断形参实值**:Browse 展示 body-inferred 参数绑定值;欢迎页 EN/ZH 迁 v0.3 叙述。
|
||||
|
||||
### Fixed
|
||||
- `ext/net/url.encode`:经 `lib/net` 包装,不再直接 `host_*`(金样 `ext_mq_md_never_calls_host`)。
|
||||
- PPA 源包:`ppa-build-source.sh` 本地 `.orig` 已在 build-area 时跳过重复 `cp`。
|
||||
- view:嵌套调用欢迎页与公式/代码卡渲染清理。
|
||||
|
||||
### Changed
|
||||
- CLI / wasm / `ext/VERSION` **同步 1.4.0**;词法评论段遇有序分支臂 / 循环头 / 图片自写回标记时断开,避免吞掉控制流行。
|
||||
|
||||
## v1.3.3 — 2026-10-15
|
||||
|
||||
### Highlights
|
||||
|
||||
Generated
+2
-2
@@ -572,7 +572,7 @@ checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
|
||||
|
||||
[[package]]
|
||||
name = "marqdo"
|
||||
version = "1.3.3"
|
||||
version = "1.4.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"assert_cmd",
|
||||
@@ -603,7 +603,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "marqdo-wasm"
|
||||
version = "1.3.3"
|
||||
version = "1.4.0"
|
||||
dependencies = [
|
||||
"marqdo",
|
||||
"serde_json",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "marqdo"
|
||||
version = "1.3.3"
|
||||
version = "1.4.0"
|
||||
edition = "2021"
|
||||
license = "Apache-2.0"
|
||||
description = "Marqdo — Markdown markers as an interpreted programming language"
|
||||
|
||||
@@ -149,8 +149,9 @@ marqdo catalog public -o .marqdo
|
||||
|
||||
---
|
||||
|
||||
## 现状(v1.3.3)
|
||||
## 现状(v1.4.0)
|
||||
|
||||
- **叙述统一 / 公式 meta / 图片自写回(v1.4.0)**:`% marqdo: var=` 块公式绑定 · 臂/循环体叙述与 foreach 中英糖 · `` 图片自写回 · view 推断形参实值 · [fence-meta-and-control-prose.md](doc/design/fence-meta-and-control-prose.md) · [stdlib-writeback.md](doc/design/stdlib-writeback.md)
|
||||
- **view 文档面(v1.3.3)**:Browse Structure 叙述保真 · 标记面 · 分支/循环帧下拉 · AI `#mq-view-trace` · 静态 `view output` / gh-pages 同源 · [view-document-annotations.md](doc/design/view-document-annotations.md)
|
||||
- **Engineering Knowledge(v1.3.0)**:EKC L0–L4 · `marqdo knowledge|find|reuse|duplicate|verify|…` · Agent `preflight` / REUSE→ADAPT→CREATE · [engineering-knowledge.md](doc/design/engineering-knowledge.md)
|
||||
- **Web Artifact(v1.2.0 · ADR 0007)**:Document/Endpoint 一等公民(`type: web|endpoint`)· facade `page`/`route`/`serve`/`render`/`inspect`/`use` · Resource 拆到 `ext/data`/`security`/`net` · 统一 View 表 · 破坏性移除 `compose_*`/`configure`
|
||||
@@ -177,7 +178,7 @@ marqdo catalog public -o .marqdo
|
||||
- **浏览器 Marqdo(WASM)**:`marqdo wasm build` + 官方 bridge 自启(作者零业务 JS;桥内可含列表/路由/storage/ws/文件/Canvas/音频/Observer/拖放);`lib/browser` + GFM;`web.client_embed`;示例 [browser-hello](examples/browser-hello/) · [browser-app](examples/browser-app/) · [browser-media](examples/browser-media/) · [web-client-site](examples/web-client-site/)([ADR 0002](doc/adr/0002-browser-marqdo-wasm.md) · [D](doc/roadmap/browser-wasm-d.md) · [E](doc/roadmap/browser-wasm-e.md) · [F](doc/roadmap/browser-wasm-f.md))
|
||||
- 选型:[ADR 0001 — Rust](doc/adr/0001-implementation-language.md) · [ADR 0002 — 浏览器 WASM](doc/adr/0002-browser-marqdo-wasm.md)(C0–C5 完结,见 [roadmap/browser-wasm.md](doc/roadmap/browser-wasm.md))· [ADR 0003 — 异步效应](doc/adr/0003-browser-async-effects.md)
|
||||
|
||||
### 如何使用最新 Marqdo(v1.3.3)
|
||||
### 如何使用最新 Marqdo(v1.4.0)
|
||||
|
||||
**安装解释器(任选其一)**
|
||||
|
||||
@@ -192,7 +193,7 @@ marqdo catalog public -o .marqdo
|
||||
```bash
|
||||
# 1) 源码安装(跟 tag 或 main)
|
||||
git clone https://github.com/cflmy/marqdo.git && cd marqdo
|
||||
git checkout v1.3.3 # 或留在 main
|
||||
git checkout v1.4.0 # 或留在 main
|
||||
cargo build --release
|
||||
export PATH="$PWD/target/release:$PATH"
|
||||
marqdo version
|
||||
@@ -231,7 +232,7 @@ marqdo wasm build
|
||||
# → dist/wasm/ … 见 examples/browser-hello/
|
||||
|
||||
# 6) Releases:Windows exe/zip/vsix;Linux CLI zip + native `.so` zip
|
||||
# https://github.com/cflmy/marqdo/releases/tag/v1.3.3
|
||||
# https://github.com/cflmy/marqdo/releases/tag/v1.4.0
|
||||
```
|
||||
|
||||
开发期也可用 `cargo run -- …` 代替已安装的 `marqdo`:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "marqdo-wasm"
|
||||
version = "1.3.3"
|
||||
version = "1.4.0"
|
||||
edition = "2021"
|
||||
license = "Apache-2.0"
|
||||
description = "Marqdo interpreter as WebAssembly (browser host bridge)"
|
||||
|
||||
Vendored
+8
@@ -1,3 +1,11 @@
|
||||
marqdo (1.4.0-1ppa1) noble; urgency=medium
|
||||
|
||||
* Marqdo 1.4.0: Prose-unified control flow — block formula % marqdo: var=,
|
||||
arm/loop narrative + foreach sugar, image writeback ,
|
||||
view inferred-param values; welcome pages on v0.3 prose surface.
|
||||
|
||||
-- cflmy <pingan@cflmy.cn> Wed, 15 Oct 2026 15:53:00 +0800
|
||||
|
||||
marqdo (1.3.3-1ppa1) noble; urgency=medium
|
||||
|
||||
* Marqdo 1.3.3: Browse document-surface Structure — narration-preserving
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
# 块公式元数据绑定 · 控制流叙述统一
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | Active |
|
||||
| 日期 | 2026-10-15 |
|
||||
| 相关 | [stdlib-math.md](stdlib-math.md) · [markdown-mapping-v0.3.md](markdown-mapping-v0.3.md) · [code-as-docs-gaps.md](code-as-docs-gaps.md) |
|
||||
|
||||
---
|
||||
|
||||
## 1. 块公式 `% marqdo: var=`
|
||||
|
||||
在 `$$…$$` 块内用 **TeX 行注释**声明绑定名(渲染通常不可见;运行时剥离后解析公式体):
|
||||
|
||||
```markdown
|
||||
$$
|
||||
% marqdo: var=f
|
||||
x^2 - 2
|
||||
$$
|
||||
```
|
||||
|
||||
- 指令:`% marqdo:` + 空白 + `var=<ident>`;未知键 → Error。
|
||||
- 可无前置 `` `f` = ``;若同时写空 RHS 与 `var=`,**同名允许、异名 Error**。
|
||||
- **保留**旧空 RHS + 后随 `$$`。
|
||||
- **不做**:行内 `$% marqdo:…$`;\`\`\` 代码围栏内语言注释 meta(本波)。
|
||||
- 行内公式继续传统绑定:`` `g` = $x+1$ ``(单 `$…$` → `formula`)或 `` `g` = $$x+1$$ ``。
|
||||
|
||||
无名叙述区 `$$` 仍仅展示;可执行区裸块既无空 RHS 又无 `var=` → Error。
|
||||
|
||||
---
|
||||
|
||||
## 2. 臂 / 循环体叙述(与函数体同权)
|
||||
|
||||
`parse_indented_body` 与函数体相同:消费 `` `名` `` / `**代码**` / `*返回*`;纯叙述跳过。
|
||||
斜体返回结束**当前臂或当前循环体**,不结束外层函数。
|
||||
|
||||
---
|
||||
|
||||
## 3. 循环头
|
||||
|
||||
| 面 | 写法 | 说明 |
|
||||
|----|------|------|
|
||||
| **推荐** | `- [项](xs)` / `- [`项`](`xs`)` | 支持嵌套 |
|
||||
| 中文糖 | `- 对`xs`的每一项`项`` | 可选后缀「遍历」 |
|
||||
| 英文糖 | `- for each `item` in `xs`` | 大小写不敏感 `for each` / `in` |
|
||||
|
||||
糖与链接头语义相同,可混用嵌套。
|
||||
|
||||
---
|
||||
|
||||
## 4. 分支条件行叙述
|
||||
|
||||
结构行仍以 `1.` / `2.` 开头。条件提取顺序:
|
||||
|
||||
1. 整段可解析为表达式(现状);
|
||||
2. 行内粗体代码条件 `**`n` > 0**`;
|
||||
3. 剥离「当/若/如果/when/if」与「时/则」后,将「大于/小于/等于…」映射为运算符再解析。
|
||||
|
||||
else:`N. *`(可夹「否则」等叙述,条件位仍为 `*`)。
|
||||
禁止无标记自然语言整句当条件。
|
||||
@@ -215,7 +215,9 @@ v0.3:
|
||||
| 表达式 `[键](集合)` | **取元**(与 foreach 同形;见 [collection-access-link.md](collection-access-link.md)) |
|
||||
| `修饰… [函数名] 实参…` | **方括号标记调用**(前置修饰 → `名=True`;见 [bracket-call-modifiers.md](bracket-call-modifiers.md)) |
|
||||
| `` 集合[^键] `` | **过渡**:旧脚注取元(仍可用) |
|
||||
| ` ```lang ` | 外联(不变) |
|
||||
| ` ```lang ` | 外联(不变;绑定仍用 `` `名` = `` + 围栏) |
|
||||
| `$$` 内 `% marqdo: var=名` | 块公式绑定([fence-meta-and-control-prose.md](fence-meta-and-control-prose.md)) |
|
||||
| `- 对`集`的每一项`项`` / `for each` | foreach 叙述糖;推荐 `- [项](集)` |
|
||||
| 单独一行 `---` / `***` | **叙述分隔**(跳过;模块顶与函数体内相同) |
|
||||
| 整行恰 `**` 或 `****` / `*None*` / `*无*` | **空返回**并结束本函数体(见 §7.2) |
|
||||
|
||||
|
||||
@@ -34,7 +34,16 @@
|
||||
|
||||
### 2.2 文档中的 `$$` = 公式赋值(与表格同构)
|
||||
|
||||
在可执行面用 **空 RHS 赋值** 后跟展示数学块,把公式绑到变量(与 `` `xs` = `` 后跟表格一致):
|
||||
**推荐(块内元数据)**:在 `$$` 体内用 TeX 注释声明变量(见 [fence-meta-and-control-prose.md](fence-meta-and-control-prose.md)):
|
||||
|
||||
````markdown
|
||||
$$
|
||||
% marqdo: var=f
|
||||
sin(x) + x
|
||||
$$
|
||||
````
|
||||
|
||||
**兼容**:空 RHS 赋值后跟展示数学块(与 `` `xs` = `` 后跟表格一致):
|
||||
|
||||
````markdown
|
||||
# main
|
||||
@@ -52,13 +61,14 @@ $$
|
||||
也支持:
|
||||
|
||||
- 单行围栏:下一行 `$$x^2 - 2$$`
|
||||
- 同行 compact:`*`f` = $$x^2 - 2$$ *`
|
||||
- 同行 compact:`*`f` = $$x^2 - 2$$ *`(历史面)
|
||||
- 行内:`` `g` = $x+1$ `` 或 `` `g` = $$x+1$$ ``
|
||||
|
||||
**废除:** `$$:name` / `$$ name=…` 模块级具名块(不再产生绑定)。
|
||||
|
||||
**无名 `$$…$$`:** 仅在成段注释(叙述面)里作展示,**不**进入运行时。可执行区若出现未挂在赋值上的裸 `$$` 围栏 → 报错,提示使用 `` `name` = `` + 围栏。
|
||||
**无名 `$$…$$`:** 仅在成段注释(叙述面)里作展示,**不**进入运行时。可执行区裸 `$$` 若既无空 RHS 又无 `% marqdo: var=` → 报错。
|
||||
|
||||
**行内 `$…$`:** v1 不做绑定;需要时用 `> formula text=…` 显式构造。
|
||||
**行内 `$…$`:** 传统绑定 `` `名` = $…$ `` → `formula`;**不**使用 `$% marqdo:…$`(会破坏 Markdown/TeX 识别)。
|
||||
|
||||
### 2.3 从文本构造
|
||||
|
||||
|
||||
@@ -8,9 +8,11 @@
|
||||
|
||||
## 定位
|
||||
|
||||
**Jupyter 输出单元的 Marqdo 等价物**:执行得到结果 → `record` / `写回` 写入入口 `.mq.md` 的 `<!-- marqdo-out … -->` → `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
|
||||

|
||||

|
||||
```
|
||||
|
||||
- 普通 Markdown 预览即可看见图;view / 静态站额外加 writeback 标记与 output-card 中的 `<img>`。
|
||||
- 非图片路径仍走注释块;把非图片硬写成 `` 时扫描会忽略(校验失败)。
|
||||
- `list` / `scan_path` 结果带 `kind`: `comment` | `image`。
|
||||
|
||||
### 共用规则
|
||||
|
||||
- 标记字为 `marqdo-out`,可选后跟槽名(`ok` / `error` 等),**不存行号**
|
||||
- 默认在**调用行下方**插入或替换紧邻**无键**块
|
||||
- `at_end=true`:替换文件末尾的**无键**块
|
||||
- `key=` / `键=`:在**当前调用锚点下方**创建或替换该命名槽(智能体单步用父调用行,即 `step` 语句下方);`ensure` 在缺失时写入占位且不覆盖已有正文。命名槽互不覆盖,也不使用文件末尾单块。
|
||||
- `line=` / `行=`:显式锚点行号。子任务 / 异步写回必须带上,否则会锚到子任务内部调用行。主机侧有全局互斥锁,写前从磁盘重读入口源,避免并发写互相覆盖。
|
||||
- `key=` / `键=`:在**当前调用锚点下方**创建或替换该命名槽;`ensure` 在缺失时写入占位且不覆盖已有正文
|
||||
- `line=` / `行=`:显式锚点行号;主机侧有全局互斥锁
|
||||
|
||||
### 替换跨度与空行
|
||||
|
||||
|
||||
@@ -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/) |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -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 否则隐藏 |
|
||||
+1
-1
@@ -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) |
|
||||
|
||||
---
|
||||
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
1.3.3
|
||||
1.4.0
|
||||
+3
-2
@@ -1,9 +1,10 @@
|
||||
---
|
||||
title: ext/net/url
|
||||
description: URL helpers (stdlib host wrappers). ADR 0007.
|
||||
description: URL helpers (stdlib wrappers). ADR 0007.
|
||||
import net:lib/net.mq.md
|
||||
---
|
||||
|
||||
## encode
|
||||
+ `text`
|
||||
|
||||
*> host_url_encode text=`text`*
|
||||
*> net.url_encode text=`text`*
|
||||
+2
-2
@@ -11,7 +11,7 @@ Persist run output in .mq.md (Jupyter-style writeback)
|
||||
+ `key`=None
|
||||
+ `line`=None
|
||||
|
||||
Write `value` to `<!-- marqdo-out … -->` 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 `` (or ``); other values use `<!-- marqdo-out … -->`. 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 `<!-- marqdo-out … -->` slots in any file (workbook inspection).
|
||||
List writeback slots in any file (HTML comment and `` image forms; workbook inspection).
|
||||
|
||||
*> host_writeback_scan_path path=`path`*
|
||||
+2
-2
@@ -11,7 +11,7 @@ description: 将运行结果写回 .mq.md(Jupyter 式自写回)
|
||||
+ `键`=None
|
||||
+ `行`=None
|
||||
|
||||
在入口文件中写入 `<!-- marqdo-out … -->`。默认在调用行下方插入或替换;`末尾=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=`路径`*
|
||||
+41
-52
@@ -1,29 +1,59 @@
|
||||
---
|
||||
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).
|
||||
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).
|
||||
|
||||
## Install
|
||||
中文文档请看同目录的 [`00-欢迎.mq.md`](00-欢迎.mq.md)(叙述与内置均用中文)。
|
||||
|
||||
Pick one way to get the CLI:
|
||||
Want a quick hello? Calls only run when they sit in the entry `# main` — `##` children are methods until something calls them. Try **greet who="marqdo"**. Names can include spaces: **greet who="marqdo user"**.
|
||||
|
||||
| Method | Notes |
|
||||
|--------|-------|
|
||||
Beyond the basics, Marqdo ships table, time, text, files, system, math, foreign, and more. Math and foreign deserve a special mention.
|
||||
|
||||
Write a math block and bind it with a TeX comment:
|
||||
|
||||
$$
|
||||
% marqdo: var=f
|
||||
x^2 - 2
|
||||
$$
|
||||
|
||||
Then plot it: **_svg = math.plot formula=`f` var="x" min=-3 max=3**
|
||||
|
||||
Foreign lets you embed another language. Bind `hi` to a small Python block:
|
||||
|
||||
`hi` =
|
||||
```python
|
||||
print("hello-from-python")
|
||||
```
|
||||
|
||||
Under Markdown this stays easy to read — which is the point: code as documentation, documentation as code.
|
||||
|
||||
Welcome again — enjoy exploring Marqdo.
|
||||
|
||||
## greet
|
||||
|
||||
When we meet a visitor `who`, we **print text="Welcome, `who`!"** and close with*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 zips at [releases](https://github.com/cflmy/marqdo/releases) |
|
||||
| From source | `cargo build --release` (needs Rust) |
|
||||
| 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 version independently of the CLI:
|
||||
Official extensions update independently of the CLI:
|
||||
|
||||
```text
|
||||
marqdo ext add web
|
||||
@@ -31,44 +61,3 @@ 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).
|
||||
|
||||
中文文档请看同目录的 [`00-欢迎.mq.md`](00-欢迎.mq.md)(叙述与内置均用中文)。
|
||||
|
||||
A small function to say hello:
|
||||
|
||||
> greet who=marqdo
|
||||
|
||||
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:
|
||||
|
||||
`f` =
|
||||
$$
|
||||
x^2 - 2
|
||||
$$
|
||||
|
||||
Then plot it:
|
||||
|
||||
**`_svg` = > math.plot formula=`f` var="x" min=-3 max=3**
|
||||
|
||||
The foreign library lets you call external code, for example:
|
||||
|
||||
`hi` =
|
||||
```python
|
||||
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.
|
||||
+32
-44
@@ -7,12 +7,42 @@ description: 用户文档首页 — 代码即文档(中文版)
|
||||
|
||||
# main
|
||||
|
||||
阅读到这里的朋友你好!我是 Marqdo 的开发者。Marqdo 是一门*代码即文档,文档即代码*的语言:Markdown 标记就是程序结构,你读到的就是能跑的程序。
|
||||
阅读到这里的朋友你好!我是 Marqdo 的开发者。Marqdo 是一门「代码即文档,文档即代码」的语言:Markdown 标记就是程序结构,你读到的就是能跑的程序。
|
||||
|
||||
AI 偏爱 Markdown结构的输出。作者的念头是:何必再把文档和代码拆成两套?我们来实现一个文档即代码的语言,所以marqdo应运而生,为了确保代码一定可以被渲染,marqdo的文件后缀定义为了`.mq.md`。在开发之处我们就尝试希望更丰富的支持,自动生成一个yaml文件使得 OKF 式知识库便捷的自动配置,乃至自动生成ppt,自然这都是以后的目标了。不过相当不错的是,至少这会成为一个不错的博客工具——对,这个站点就是 Marqdo 生成的,而且AI输出的时候会节约不少token,你知道的,token烧的太多,钱包会可怜的饿瘦的。
|
||||
AI 偏爱 Markdown 结构的输出。我当时的念头很简单——何必再把文档和代码拆成两套?于是有了 marqdo。为了让文件既能当文档渲染又能执行,后缀定为 `.mq.md`。更远的目标还有 OKF 式知识库的 YAML、甚至自动生成 PPT;眼下它至少已经是个不错的博客工具——对,这个站点就是 Marqdo 生成的。AI 写 `.mq.md` 时往往更省 token,钱包也会轻松一点。
|
||||
|
||||
语言仍在起步:结构标记、中英内核双名(`打印` / `print` …)、可导入的标准库(见本站 [`stdlib/`](stdlib/))、本地 `view` 与静态导出。欢迎到 [GitHub](https://github.com/cflmy/marqdo) 一起做。
|
||||
|
||||
English docs: [`00-welcome.mq.md`](00-welcome.mq.md)(English prose and English builtins).
|
||||
|
||||
想先打个招呼?调用写在入口 `# main` 里才会真的跑——子标题里的方法要等你叫到它。比如:**问候 谁="marqdo"**。名字里可以带空格:**问候 谁="marqdo user"**。
|
||||
|
||||
除了这些基本面,标准库里还有表、时间、文本、文件、系统、数学、外联等。我特别想提数学和外联。
|
||||
|
||||
比方说,直接写一块公式,并用 TeX 注释标上变量名:
|
||||
|
||||
$$
|
||||
% marqdo: var=f
|
||||
x^2 - 2
|
||||
$$
|
||||
|
||||
接着画出来:**_svg = 数学.绘图 formula=`f` var="x" min=-3 max=3**
|
||||
|
||||
外联则允许嵌一段别的语言。把`hi`绑成下面这样即可:
|
||||
|
||||
`hi` =
|
||||
```python
|
||||
print("hello-from-python")
|
||||
```
|
||||
|
||||
这些在 Markdown 里读起来仍然像文章——这就是 marqdo 想坚持的:代码即文档,文档即代码。
|
||||
|
||||
最后,再次欢迎你,尽情体验 marqdo 吧!
|
||||
|
||||
## 问候
|
||||
|
||||
见到访客`谁`时,我们 **打印 内容="欢迎,`谁`!"**,然后收束为*None*。
|
||||
|
||||
## 安装
|
||||
|
||||
解释器(CLI)任选其一:
|
||||
@@ -31,45 +61,3 @@ 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).
|
||||
|
||||
用一个小函数打个招呼:
|
||||
|
||||
> 问候 谁=marqdo
|
||||
|
||||
具名实参可以带空格:
|
||||
|
||||
> 问候 谁=marqdo user
|
||||
|
||||
## 问候
|
||||
+ `谁`
|
||||
|
||||
> 打印 内容=欢迎,`谁`!
|
||||
|
||||
*None*
|
||||
|
||||
除了上面的一些基本内容之外,我还开发了这个语言的一些标准库,包括表、时间、文本、文件、系统、数学和外联等标准库。
|
||||
|
||||
其中数学库和外联库是我要着重提到的,例如数学库,你可以通过下面的方式调用:
|
||||
|
||||
`f` =
|
||||
$$
|
||||
x^2 - 2
|
||||
$$
|
||||
|
||||
之后让我们画个图像吧!
|
||||
|
||||
**`_svg` = > 数学.绘图 formula=`f` var="x" min=-3 max=3**
|
||||
|
||||
外联库则允许你调用外部代码,例如:
|
||||
|
||||
`hi` =
|
||||
```python
|
||||
print("hello-from-python")
|
||||
```
|
||||
|
||||
这些代码在markdown下面都非常的易读,就像我说的,marqdo的设计思想就是代码即文档,
|
||||
文档即代码。
|
||||
|
||||
最后,再次欢迎你,尽情体验marqdo吧!
|
||||
@@ -5,7 +5,7 @@ description: Local browse and static export from the interpreter
|
||||
|
||||
# main
|
||||
|
||||
Milestone: `marqdo view` and `view output` (v1.3.3 document surface).
|
||||
Milestone: `marqdo view` and `view output` (v1.4.0 document surface + inferred params).
|
||||
|
||||
Local: `marqdo view public`
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ description: 本地浏览与静态导出由解释器生成
|
||||
|
||||
# main
|
||||
|
||||
里程碑:`marqdo view` 与 `view output`(v1.3.3 文档面)。
|
||||
里程碑:`marqdo view` 与 `view output`(v1.4.0 文档面 + 推断形参)。
|
||||
|
||||
本地浏览:`marqdo view public`
|
||||
|
||||
|
||||
@@ -124,7 +124,10 @@ if [ "$REUSE_ORIG" -eq 1 ]; then
|
||||
echo "==> reusing published ${ORIG_NAME} (debian-only bump; do not rewrite orig)"
|
||||
echo " source: ${ORIG_SRC}"
|
||||
sha256sum "$ORIG_SRC"
|
||||
cp -f "$ORIG_SRC" "$BUILD_AREA/$ORIG_NAME"
|
||||
# Local fallback may already be build-area/ORIG_NAME — do not cp onto itself.
|
||||
if [ "$(realpath "$ORIG_SRC")" != "$(realpath "$BUILD_AREA/$ORIG_NAME" 2>/dev/null || echo "")" ]; then
|
||||
cp -f "$ORIG_SRC" "$BUILD_AREA/$ORIG_NAME"
|
||||
fi
|
||||
# Unpack orig (top dir is usually ${VER} or marqdo-${VER})
|
||||
tar -xJf "$BUILD_AREA/$ORIG_NAME" -C "$(dirname "$PKG_ROOT")"
|
||||
if [ ! -d "$PKG_ROOT" ]; then
|
||||
|
||||
+244
-26
@@ -1,7 +1,11 @@
|
||||
//! Jupyter-style output persistence in `.mq.md` (`<!-- marqdo-out … -->`).
|
||||
//! Jupyter-style output persistence in `.mq.md`.
|
||||
//!
|
||||
//! Optional **named slots**: `<!-- marqdo-out ok -->` / `<!-- marqdo-out error -->`
|
||||
//! so success and failure results do not overwrite each other.
|
||||
//! Two surface forms (both scanned / replaced):
|
||||
//! - HTML comment: `<!-- marqdo-out … -->` (text / structured output)
|
||||
//! - Markdown image: `` (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<String>,
|
||||
kind: BlockKind,
|
||||
}
|
||||
|
||||
/// View-facing writeback piece under a statement line.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct WritebackEntry {
|
||||
pub key: Option<String>,
|
||||
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!("<!-- {MAGIC} {k}\n{body}\n-->"),
|
||||
None => format!("<!-- {MAGIC}\n{body}\n-->"),
|
||||
}
|
||||
}
|
||||
|
||||
fn format_image_block(url: &str, key: Option<&str>) -> String {
|
||||
match key {
|
||||
Some(k) => format!(""),
|
||||
None => format!(""),
|
||||
}
|
||||
}
|
||||
|
||||
fn format_block_for_value(body: &str, key: Option<&str>) -> Result<String, String> {
|
||||
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 ``.
|
||||
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<String> {
|
||||
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<Block
|
||||
body,
|
||||
start_line: line_number_at(source, start_byte),
|
||||
key,
|
||||
kind: BlockKind::Comment,
|
||||
})
|
||||
}
|
||||
|
||||
/// `` on a single source line.
|
||||
fn parse_image_line(line: &str, line_start: usize, source: &str) -> Option<BlockSpan> {
|
||||
let trimmed = line.trim();
|
||||
let rest = trimmed.strip_prefix("?;
|
||||
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<BlockSpan> {
|
||||
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<BlockSpan> {
|
||||
}
|
||||
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<Blo
|
||||
/// Replace keyed block under `anchor` line, or insert into that cluster (not EOF).
|
||||
fn replace_or_insert_keyed_at(source: &str, anchor: u32, key: &str, body: &str) -> Result<String, String> {
|
||||
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<u32, String> {
|
||||
let mut map = HashMap::new();
|
||||
/// Structured writebacks keyed by the statement line above the block cluster.
|
||||
pub fn writeback_entries(source: &str) -> HashMap<u32, Vec<WritebackEntry>> {
|
||||
let mut map: HashMap<u32, Vec<WritebackEntry>> = 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 `<img>`.
|
||||
pub fn writeback_map(source: &str) -> HashMap<u32, String> {
|
||||
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, "");
|
||||
let src = "# main\n\n**x = 1**\n\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")
|
||||
);
|
||||
// Invalid image URL in marqdo-out alt → not a writeback slot
|
||||
let bad = "# main\n\n\n";
|
||||
assert!(scan_blocks(bad).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unkeyed_comment_and_image_replace_each_other() {
|
||||
let src = "# main\n\n**x = 1**\n<!-- marqdo-out\nold\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(""));
|
||||
assert!(!to_image.contains("<!-- marqdo-out"));
|
||||
let blocks = scan_blocks(&to_image);
|
||||
assert_eq!(blocks.len(), 1);
|
||||
assert_eq!(blocks[0].kind, BlockKind::Image);
|
||||
|
||||
let to_text = {
|
||||
let stripped = find_adjacent_block(&to_image, line)
|
||||
.map(|b| strip_span(&to_image, b.start, span_end_including_nl(&to_image, b.end)))
|
||||
.unwrap_or_else(|| to_image.clone());
|
||||
insert_after_line(
|
||||
&stripped,
|
||||
line,
|
||||
&format_block_for_value("hello", None).unwrap(),
|
||||
)
|
||||
.unwrap()
|
||||
};
|
||||
assert!(to_text.contains("<!-- marqdo-out\nhello\n-->"));
|
||||
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, "");
|
||||
let t = format_block_for_value("hello", None).unwrap();
|
||||
assert!(t.contains("<!-- marqdo-out"));
|
||||
assert!(format_block_for_value("notes.txt", None).unwrap().contains("<!--"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writeback_map_uses_line_above() {
|
||||
let src = "# main\n\n**x = 1**\n<!-- marqdo-out\n42\n-->\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");
|
||||
|
||||
+80
-1
@@ -279,7 +279,52 @@ fn breaks_comment_paragraph(trimmed: &str) -> bool {
|
||||
if trimmed.starts_with('#') || trimmed.starts_with('>') {
|
||||
return true;
|
||||
}
|
||||
is_marqdo_star_line(trimmed)
|
||||
if is_marqdo_star_line(trimmed) {
|
||||
return true;
|
||||
}
|
||||
// Branch arms / loops / params must not be swallowed after prose in an arm body.
|
||||
if looks_like_ordered_list_item(trimmed) {
|
||||
return true;
|
||||
}
|
||||
if trimmed.starts_with("- ") || trimmed.starts_with("-\t") || trimmed == "-" {
|
||||
return true;
|
||||
}
|
||||
if trimmed.starts_with('+') {
|
||||
return true;
|
||||
}
|
||||
if is_image_writeback_line(trimmed) {
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// `` — 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 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;
|
||||
while let Some(c) = chars.next() {
|
||||
if c.is_ascii_digit() {
|
||||
saw_digit = true;
|
||||
continue;
|
||||
}
|
||||
if c == '.' && saw_digit {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Classify a single logical line (no trailing newline required).
|
||||
@@ -353,6 +398,9 @@ pub fn classify_source(source: &str) -> Vec<ClassifiedLine> {
|
||||
in_writeback = false;
|
||||
}
|
||||
LineKind::Writeback
|
||||
} else if is_image_writeback_line(trimmed) {
|
||||
in_comment_paragraph = false;
|
||||
LineKind::Writeback
|
||||
} else {
|
||||
match base {
|
||||
LineKind::Blank => {
|
||||
@@ -439,6 +487,26 @@ pub fn format_lines_dump(path: &str, lines: &[ClassifiedLine]) -> String {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn ordered_arm_breaks_prose_paragraph() {
|
||||
let src = "\
|
||||
# main\n\
|
||||
\n\
|
||||
1. `n` > 0\n\
|
||||
此时我们 **打印 内容=\"正\"**\n\
|
||||
2. *\n\
|
||||
否则 **打印 内容=\"非正\"**\n\
|
||||
";
|
||||
let lines = classify_source(src);
|
||||
let l12 = lines.iter().find(|l| l.text.trim() == "2. *").expect("2. *");
|
||||
assert_eq!(
|
||||
l12.kind,
|
||||
LineKind::Code,
|
||||
"else arm must stay Code after prose, got dump:\n{}",
|
||||
format_lines_dump("t", &lines)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blank_and_comment_and_code() {
|
||||
assert_eq!(classify_line(""), LineKind::Blank);
|
||||
@@ -498,6 +566,17 @@ mod tests {
|
||||
assert_eq!(lines[3].kind, LineKind::Writeback);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_writeback_line_classified() {
|
||||
assert!(is_image_writeback_line(""));
|
||||
assert!(is_image_writeback_line(""));
|
||||
assert!(!is_image_writeback_line(""));
|
||||
let src = "# main\n\n**x = 1**\n\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";
|
||||
|
||||
+411
-30
@@ -358,6 +358,13 @@ impl<'a> Cursor<'a> {
|
||||
continue;
|
||||
}
|
||||
|
||||
if self.peek_is_formula_fence() {
|
||||
if let Some(stmt) = self.try_parse_meta_formula_assign()? {
|
||||
fun.body.push(stmt);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if is_ordered_branch(trimmed) {
|
||||
fun.body.push(self.parse_branch()?);
|
||||
continue;
|
||||
@@ -405,9 +412,10 @@ impl<'a> Cursor<'a> {
|
||||
}
|
||||
|
||||
if trimmed.starts_with("$$") {
|
||||
// Standalone meta formulas are handled before parse_simple_stmt.
|
||||
bail!(
|
||||
"{span}: formula fence must follow an empty assignment (`name` =); \
|
||||
`$$:name` binding was removed"
|
||||
"{span}: formula fence must follow an empty assignment (`name` =) \
|
||||
or include `% marqdo: var=name` inside the block"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -503,7 +511,7 @@ impl<'a> Cursor<'a> {
|
||||
if crate::aliases::is_reserved_keyword(&name) {
|
||||
bail!("{span}: `{name}` is a reserved keyword");
|
||||
}
|
||||
let (value, end_line) = self.resolve_assign_rhs(&rhs, span, true)?;
|
||||
let (value, end_line) = self.resolve_assign_rhs(&name, &rhs, span, true)?;
|
||||
return Ok(Stmt::Assign {
|
||||
name,
|
||||
value,
|
||||
@@ -544,7 +552,7 @@ impl<'a> Cursor<'a> {
|
||||
if crate::aliases::is_reserved_keyword(&name) {
|
||||
bail!("{span}: `{name}` is a reserved keyword");
|
||||
}
|
||||
let (value, end_line) = self.resolve_assign_rhs(&rhs, span, true)?;
|
||||
let (value, end_line) = self.resolve_assign_rhs(&name, &rhs, span, true)?;
|
||||
Ok(Stmt::Assign {
|
||||
name,
|
||||
value,
|
||||
@@ -570,7 +578,7 @@ impl<'a> Cursor<'a> {
|
||||
return Ok(None);
|
||||
}
|
||||
let rhs = after[1..].trim().to_string();
|
||||
let (value, end_line) = self.resolve_assign_rhs(&rhs, span, false)?;
|
||||
let (value, end_line) = self.resolve_assign_rhs(&name, &rhs, span, false)?;
|
||||
Ok(Some(Stmt::Assign {
|
||||
name,
|
||||
value,
|
||||
@@ -584,6 +592,7 @@ impl<'a> Cursor<'a> {
|
||||
/// `prefer_var`: italic RHS uses variable-preferring expression syntax.
|
||||
fn resolve_assign_rhs(
|
||||
&mut self,
|
||||
assign_name: &str,
|
||||
rhs: &str,
|
||||
span: Span,
|
||||
prefer_var: bool,
|
||||
@@ -592,7 +601,9 @@ impl<'a> Cursor<'a> {
|
||||
if rhs.is_empty() {
|
||||
self.skip_blanks();
|
||||
if self.peek_is_formula_fence() {
|
||||
return self.consume_formula_fence(span);
|
||||
let (expr, end_line, meta_var) = self.consume_formula_fence(span)?;
|
||||
check_formula_meta_var(assign_name, meta_var.as_deref(), span)?;
|
||||
return Ok((expr, end_line));
|
||||
}
|
||||
if self.peek_is_code_fence() {
|
||||
return self.consume_code_fence(span);
|
||||
@@ -698,7 +709,8 @@ impl<'a> Cursor<'a> {
|
||||
))
|
||||
}
|
||||
|
||||
fn consume_formula_fence(&mut self, span: Span) -> Result<(Expr, u32)> {
|
||||
/// Consume `$$…$$`. Returns `(expr, end_line, optional var from % marqdo: var=)`.
|
||||
fn consume_formula_fence(&mut self, span: Span) -> Result<(Expr, u32, Option<String>)> {
|
||||
let open = self
|
||||
.bump()
|
||||
.ok_or_else(|| anyhow::anyhow!("{span}: expected `$$` formula fence"))?;
|
||||
@@ -707,7 +719,7 @@ impl<'a> Cursor<'a> {
|
||||
if trimmed.starts_with("$$:") || trimmed.starts_with("$$ name=") {
|
||||
bail!(
|
||||
"{open_line}:1: `$$:name` / `$$ name=` binding was removed; \
|
||||
use `name` = then a `$$…$$` fence"
|
||||
use `% marqdo: var=name` inside `$$…$$` or `name` = then a fence"
|
||||
);
|
||||
}
|
||||
// Single-line: $$body$$
|
||||
@@ -716,15 +728,21 @@ impl<'a> Cursor<'a> {
|
||||
if body.is_empty() {
|
||||
bail!("{open_line}:1: empty formula");
|
||||
}
|
||||
let (meta_var, tex) = strip_formula_marqdo_meta(body)
|
||||
.map_err(|e| anyhow::anyhow!("{open_line}:1: {e}"))?;
|
||||
if tex.is_empty() {
|
||||
bail!("{open_line}:1: empty formula");
|
||||
}
|
||||
return Ok((
|
||||
formula_fence_to_expr(body)
|
||||
formula_fence_to_expr(&tex)
|
||||
.map_err(|e| anyhow::anyhow!("{open_line}:1: formula: {e}"))?,
|
||||
open_line,
|
||||
meta_var,
|
||||
));
|
||||
}
|
||||
if trimmed != "$$" {
|
||||
bail!(
|
||||
"{open_line}:1: expected `$$` fence opener after empty assignment, got: {trimmed}"
|
||||
"{open_line}:1: expected `$$` fence opener, got: {trimmed}"
|
||||
);
|
||||
}
|
||||
let mut body_lines: Vec<String> = Vec::new();
|
||||
@@ -743,13 +761,45 @@ impl<'a> Cursor<'a> {
|
||||
if !closed {
|
||||
bail!("{open_line}:1: unclosed formula fence `$$`");
|
||||
}
|
||||
let text = body_lines.join("\n").trim().to_string();
|
||||
if text.is_empty() {
|
||||
let raw = body_lines.join("\n");
|
||||
let (meta_var, tex) = strip_formula_marqdo_meta(&raw)
|
||||
.map_err(|e| anyhow::anyhow!("{open_line}:1: {e}"))?;
|
||||
if tex.is_empty() {
|
||||
bail!("{open_line}:1: empty formula");
|
||||
}
|
||||
let expr = formula_fence_to_expr(&text)
|
||||
let expr = formula_fence_to_expr(&tex)
|
||||
.map_err(|e| anyhow::anyhow!("{open_line}:1: formula: {e}"))?;
|
||||
Ok((expr, end_line))
|
||||
Ok((expr, end_line, meta_var))
|
||||
}
|
||||
|
||||
/// Standalone `$$` with `% marqdo: var=` → Assign (no empty RHS required).
|
||||
fn try_parse_meta_formula_assign(&mut self) -> Result<Option<Stmt>> {
|
||||
if !self.peek_is_formula_fence() {
|
||||
return Ok(None);
|
||||
}
|
||||
let Some(l) = self.peek() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let span = Span {
|
||||
line: l.line_no,
|
||||
col: 1,
|
||||
};
|
||||
let (value, end_line, meta_var) = self.consume_formula_fence(span)?;
|
||||
let Some(name) = meta_var else {
|
||||
bail!(
|
||||
"{span}: formula fence must follow an empty assignment (`name` =) \
|
||||
or include `% marqdo: var=name` inside the block"
|
||||
);
|
||||
};
|
||||
if crate::aliases::is_reserved_keyword(&name) {
|
||||
bail!("{span}: `{name}` is a reserved keyword");
|
||||
}
|
||||
Ok(Some(Stmt::Assign {
|
||||
name,
|
||||
value,
|
||||
span,
|
||||
end_line,
|
||||
}))
|
||||
}
|
||||
|
||||
/// GFM table after empty RHS:
|
||||
@@ -878,11 +928,7 @@ impl<'a> Cursor<'a> {
|
||||
let cond_src = strip_ordered(trimmed).unwrap();
|
||||
self.bump();
|
||||
|
||||
let condition = if cond_src == "*" || cond_src.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(parse_expr_str(cond_src)?)
|
||||
};
|
||||
let condition = parse_branch_condition(cond_src)?;
|
||||
|
||||
let body = self.parse_indented_body(base_indent)?;
|
||||
arms.push(BranchArm { condition, body });
|
||||
@@ -904,8 +950,10 @@ impl<'a> Cursor<'a> {
|
||||
let trimmed = line.text.trim();
|
||||
let rest = trimmed.strip_prefix('-').unwrap().trim();
|
||||
|
||||
// foreach: [item](collection)
|
||||
if let Some((item, coll)) = parse_foreach_header(rest) {
|
||||
// foreach: [item](collection) or narrative sugar
|
||||
if let Some((item, coll)) = parse_foreach_header(rest)
|
||||
.or_else(|| parse_foreach_narrative(rest))
|
||||
{
|
||||
let body = self.parse_indented_body(base_indent)?;
|
||||
return Ok(Stmt::ForEach {
|
||||
item,
|
||||
@@ -931,7 +979,7 @@ impl<'a> Cursor<'a> {
|
||||
let Some(l) = self.peek() else { break };
|
||||
let ind = indent_of(&l.text);
|
||||
if ind <= parent_indent {
|
||||
// Same-indent `+`/`-` ends body (next arm / sibling).
|
||||
// Same-indent `2.` / `-` ends body (next arm / sibling).
|
||||
break;
|
||||
}
|
||||
let trimmed = l.text.trim();
|
||||
@@ -951,6 +999,39 @@ impl<'a> Cursor<'a> {
|
||||
body.push(self.parse_loop_or_err()?);
|
||||
continue;
|
||||
}
|
||||
// Same prose rights as function body (fixes arm/loop narrative escape).
|
||||
if self.peek_is_prose() {
|
||||
let line = self.bump().unwrap();
|
||||
let span = Span {
|
||||
line: line.line_no,
|
||||
col: 1,
|
||||
};
|
||||
let bits = scan_prose_line(line.text.trim_end_matches(['\r', '\n']));
|
||||
let mut end_arm = false;
|
||||
for bit in bits {
|
||||
match bit {
|
||||
ProseBit::Decl { .. } => {}
|
||||
ProseBit::BoldCode { inner, .. } => {
|
||||
body.push(self.stmt_from_bold_inner(&inner, span.clone())?);
|
||||
}
|
||||
ProseBit::ItalicReturn { inner, .. } => {
|
||||
body.push(stmt_from_italic_return(&inner, span.clone())?);
|
||||
end_arm = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if end_arm {
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if self.peek_is_formula_fence() {
|
||||
if let Some(stmt) = self.try_parse_meta_formula_assign()? {
|
||||
body.push(stmt);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let stmt = self.parse_simple_stmt()?;
|
||||
let end_arm = matches!(stmt, Stmt::Return { .. });
|
||||
body.push(stmt);
|
||||
@@ -998,26 +1079,101 @@ fn is_bare_assign_ident(s: &str) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// Same-line `$$body$$` → Formula or numeric matrix List; otherwise None.
|
||||
/// Same-line `$$body$$` or `$body$` → Formula; otherwise None.
|
||||
fn try_parse_inline_formula(rhs: &str) -> Result<Option<Expr>> {
|
||||
let rhs = rhs.trim();
|
||||
if !rhs.starts_with("$$") {
|
||||
return Ok(None);
|
||||
}
|
||||
if rhs.starts_with("$$:") || rhs.starts_with("$$ name=") {
|
||||
bail!(
|
||||
"`$$:name` / `$$ name=` binding was removed; use `name` = then a `$$…$$` fence"
|
||||
"`$$:name` / `$$ name=` binding was removed; use `% marqdo: var=name` \
|
||||
inside `$$…$$` or `name` = then a fence"
|
||||
);
|
||||
}
|
||||
if rhs.ends_with("$$") && rhs.len() > 4 {
|
||||
let body = rhs[2..rhs.len() - 2].trim();
|
||||
if rhs.starts_with("$$") {
|
||||
if rhs.ends_with("$$") && rhs.len() > 4 {
|
||||
let body = rhs[2..rhs.len() - 2].trim();
|
||||
if body.is_empty() {
|
||||
bail!("empty formula");
|
||||
}
|
||||
let (_meta, tex) = strip_formula_marqdo_meta(body)
|
||||
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||
if tex.is_empty() {
|
||||
bail!("empty formula");
|
||||
}
|
||||
let expr = formula_fence_to_expr(&tex).map_err(|e| anyhow::anyhow!("formula: {e}"))?;
|
||||
return Ok(Some(expr));
|
||||
}
|
||||
bail!("incomplete inline formula (expected `$$…$$` on one line)");
|
||||
}
|
||||
// Traditional inline: $…$ (not $$)
|
||||
if rhs.starts_with('$') && rhs.ends_with('$') && rhs.len() > 2 && !rhs.starts_with("$$") {
|
||||
let body = rhs[1..rhs.len() - 1].trim();
|
||||
if body.is_empty() {
|
||||
bail!("empty formula");
|
||||
}
|
||||
if body.contains('%') && body.to_lowercase().contains("marqdo:") {
|
||||
bail!(
|
||||
"inline `$…$` must not use `% marqdo:` (breaks Markdown/TeX); \
|
||||
bind with `name` = $…$ or use a `$$` block with `% marqdo: var=`"
|
||||
);
|
||||
}
|
||||
let expr = formula_fence_to_expr(body).map_err(|e| anyhow::anyhow!("formula: {e}"))?;
|
||||
return Ok(Some(expr));
|
||||
}
|
||||
bail!("incomplete inline formula (expected `$$…$$` on one line)");
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Strip `% marqdo: var=name` directive lines from formula fence body.
|
||||
/// Returns `(optional var name, remaining TeX)`.
|
||||
fn strip_formula_marqdo_meta(body: &str) -> Result<(Option<String>, String), String> {
|
||||
let mut meta_var: Option<String> = None;
|
||||
let mut out: Vec<&str> = Vec::new();
|
||||
for line in body.lines() {
|
||||
let t = line.trim();
|
||||
if let Some(rest) = t.strip_prefix('%') {
|
||||
let rest = rest.trim_start();
|
||||
if rest.to_ascii_lowercase().starts_with("marqdo:") {
|
||||
let after = rest["marqdo:".len()..].trim_start();
|
||||
let mut got_var = false;
|
||||
for part in after.split_whitespace() {
|
||||
if let Some(v) = part.strip_prefix("var=") {
|
||||
if v.is_empty() {
|
||||
return Err("% marqdo: var= requires a name".into());
|
||||
}
|
||||
if !is_bare_assign_ident(v) {
|
||||
return Err(format!("invalid marqdo var name `{v}`"));
|
||||
}
|
||||
if meta_var.as_deref() == Some(v) || meta_var.is_none() {
|
||||
meta_var = Some(v.to_string());
|
||||
} else {
|
||||
return Err(format!(
|
||||
"conflicting % marqdo: var= ({} vs {v})",
|
||||
meta_var.as_deref().unwrap_or("")
|
||||
));
|
||||
}
|
||||
got_var = true;
|
||||
} else {
|
||||
return Err(format!("unknown marqdo key `{part}` (only var= is supported)"));
|
||||
}
|
||||
}
|
||||
if !got_var {
|
||||
return Err("% marqdo: requires var=<name>".into());
|
||||
}
|
||||
continue; // strip directive line
|
||||
}
|
||||
}
|
||||
out.push(line);
|
||||
}
|
||||
Ok((meta_var, out.join("\n").trim().to_string()))
|
||||
}
|
||||
|
||||
fn check_formula_meta_var(assign_name: &str, meta: Option<&str>, span: Span) -> Result<()> {
|
||||
match meta {
|
||||
None => Ok(()),
|
||||
Some(v) if v == assign_name => Ok(()),
|
||||
Some(v) => bail!(
|
||||
"{span}: formula `% marqdo: var={v}` conflicts with assignment `{assign_name}`"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn formula_fence_to_expr(body: &str) -> Result<Expr, String> {
|
||||
@@ -1112,6 +1268,148 @@ fn parse_foreach_header(rest: &str) -> Option<(String, String)> {
|
||||
Some((item, coll))
|
||||
}
|
||||
|
||||
/// Narrative foreach sugar (recommended remains `- [item](coll)`).
|
||||
/// - ZH: `对`xs`的每一项`项`` optional `遍历`
|
||||
/// - EN: `for each `item` in `xs``
|
||||
fn parse_foreach_narrative(rest: &str) -> Option<(String, String)> {
|
||||
let rest = rest.trim();
|
||||
if let Some(after) = rest.strip_prefix('对') {
|
||||
let (coll, after) = take_backtick_token(after.trim_start())?;
|
||||
let after = after.trim_start().strip_prefix("的每一项")?;
|
||||
let (item, after) = take_backtick_token(after.trim_start())?;
|
||||
let after = after
|
||||
.trim()
|
||||
.trim_end_matches('。')
|
||||
.trim();
|
||||
let after = after.strip_prefix("遍历").unwrap_or(after).trim();
|
||||
if after.is_empty() {
|
||||
return Some((item, coll));
|
||||
}
|
||||
return None;
|
||||
}
|
||||
let lower = rest.to_ascii_lowercase();
|
||||
let Some(idx) = lower.find("for each ") else {
|
||||
return None;
|
||||
};
|
||||
if idx != 0 {
|
||||
return None;
|
||||
}
|
||||
let after = rest["for each ".len()..].trim_start();
|
||||
let (item, after) = take_backtick_token(after)?;
|
||||
let after = after.trim_start();
|
||||
let after_l = after.to_ascii_lowercase();
|
||||
if !after_l.starts_with("in ") && !after_l.starts_with("in\t") {
|
||||
// require ` in `
|
||||
let Some(in_at) = after_l.find("in ") else {
|
||||
return None;
|
||||
};
|
||||
if in_at != 0 {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let after = after["in ".len()..].trim_start();
|
||||
let (coll, after) = take_backtick_token(after)?;
|
||||
if after.trim().is_empty() {
|
||||
return Some((item, coll));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn take_backtick_token(s: &str) -> Option<(String, &str)> {
|
||||
let s = s.trim_start();
|
||||
if !s.starts_with('`') {
|
||||
return None;
|
||||
}
|
||||
let end = s[1..].find('`')?;
|
||||
let name = s[1..1 + end].to_string();
|
||||
if name.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some((name, &s[1 + end + 1..]))
|
||||
}
|
||||
|
||||
/// Branch arm condition: expr, bold code, narrative (当`n`大于 0 时), or else `*`.
|
||||
fn parse_branch_condition(cond_src: &str) -> Result<Option<Expr>> {
|
||||
let t = cond_src.trim();
|
||||
if t.is_empty() || t == "*" {
|
||||
return Ok(None);
|
||||
}
|
||||
// "否则 *" / "else *"
|
||||
if let Some(before) = t.strip_suffix('*') {
|
||||
let before = before.trim();
|
||||
if before.is_empty()
|
||||
|| before == "否则"
|
||||
|| before == "其它"
|
||||
|| before == "其他"
|
||||
|| before.eq_ignore_ascii_case("else")
|
||||
|| before.eq_ignore_ascii_case("otherwise")
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
if let Ok(e) = parse_expr_str(t) {
|
||||
return Ok(Some(e));
|
||||
}
|
||||
if let Some(inner) = extract_first_bold_inner(t) {
|
||||
if let Ok(e) = parse_expr_str(inner.trim()) {
|
||||
return Ok(Some(e));
|
||||
}
|
||||
}
|
||||
if let Some(e) = try_narrative_condition(t) {
|
||||
return Ok(Some(e));
|
||||
}
|
||||
bail!(
|
||||
"branch condition: cannot parse `{t}` \
|
||||
(use an expression, **`n` > 0**, or 当`n`大于 0 时)"
|
||||
)
|
||||
}
|
||||
|
||||
fn extract_first_bold_inner(s: &str) -> Option<&str> {
|
||||
let start = s.find("**")?;
|
||||
let rest = &s[start + 2..];
|
||||
let end = rest.find("**")?;
|
||||
Some(&rest[..end])
|
||||
}
|
||||
|
||||
fn try_narrative_condition(s: &str) -> Option<Expr> {
|
||||
let mut s = s.trim();
|
||||
for p in ["当且仅当", "当", "若", "如果"] {
|
||||
if let Some(r) = s.strip_prefix(p) {
|
||||
s = r.trim_start();
|
||||
break;
|
||||
}
|
||||
}
|
||||
let lower = s.to_ascii_lowercase();
|
||||
if let Some(r) = lower.strip_prefix("when ") {
|
||||
let _ = r;
|
||||
s = s[5..].trim_start();
|
||||
} else if let Some(r) = lower.strip_prefix("if ") {
|
||||
let _ = r;
|
||||
s = s[3..].trim_start();
|
||||
}
|
||||
for suf in ["的话", "时", "则"] {
|
||||
if let Some(r) = s.strip_suffix(suf) {
|
||||
s = r.trim_end();
|
||||
}
|
||||
}
|
||||
let mut mapped = s.to_string();
|
||||
let replacements = [
|
||||
("大于等于", ">="),
|
||||
("小于等于", "<="),
|
||||
("不等于", "!="),
|
||||
("等于", "=="),
|
||||
("大于", ">"),
|
||||
("小于", "<"),
|
||||
];
|
||||
for (zh, op) in replacements {
|
||||
if mapped.contains(zh) {
|
||||
mapped = mapped.replace(zh, op);
|
||||
break;
|
||||
}
|
||||
}
|
||||
parse_expr_str(mapped.trim()).ok()
|
||||
}
|
||||
|
||||
fn parse_heading(trimmed: &str) -> Option<(u8, &str)> {
|
||||
if !trimmed.starts_with('#') {
|
||||
return None;
|
||||
@@ -1882,6 +2180,89 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::ast::Stmt;
|
||||
|
||||
#[test]
|
||||
fn parse_formula_meta_var_standalone() {
|
||||
let src = "# main\n\n$$\n% marqdo: var=f\nx^2 - 2\n$$\n";
|
||||
let m = parse_source(src).unwrap();
|
||||
match &m.functions[0].body[0] {
|
||||
Stmt::Assign { name, value, .. } => {
|
||||
assert_eq!(name, "f");
|
||||
assert!(matches!(value, Expr::Formula(_)));
|
||||
}
|
||||
other => panic!("expected formula assign, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_formula_meta_conflicts_with_assign() {
|
||||
let src = "# main\n\n`f` =\n$$\n% marqdo: var=g\nx\n$$\n";
|
||||
let err = parse_source(src).unwrap_err().to_string();
|
||||
assert!(
|
||||
err.contains("conflicts") || err.contains("var=g"),
|
||||
"{err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_foreach_narrative_zh_en() {
|
||||
let src = "# main\n\n- 对`xs`的每一项`项`\n > print text=`项`\n\n- for each `item` in `ys`\n > print text=`item`\n";
|
||||
let m = parse_source(src).unwrap();
|
||||
match &m.functions[0].body[0] {
|
||||
Stmt::ForEach { item, collection, .. } => {
|
||||
assert_eq!(item, "项");
|
||||
assert_eq!(collection, "xs");
|
||||
}
|
||||
other => panic!("zh foreach: {other:?}"),
|
||||
}
|
||||
match &m.functions[0].body[1] {
|
||||
Stmt::ForEach { item, collection, .. } => {
|
||||
assert_eq!(item, "item");
|
||||
assert_eq!(collection, "ys");
|
||||
}
|
||||
other => panic!("en foreach: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn branch_arm_prose_stays_inside_arm() {
|
||||
let src = include_str!("../../tests/markup-v03/branch-arm-prose.mq.md");
|
||||
let m = parse_source(src).unwrap();
|
||||
let main = &m.functions[0];
|
||||
let branches: Vec<_> = main
|
||||
.body
|
||||
.iter()
|
||||
.filter(|s| matches!(s, Stmt::Branch { .. }))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
branches.len(),
|
||||
1,
|
||||
"expected one Branch, body={:?}",
|
||||
main.body
|
||||
);
|
||||
match &main.body[1] {
|
||||
Stmt::Branch { arms, .. } => {
|
||||
assert_eq!(arms.len(), 2, "arms={arms:?}");
|
||||
assert!(
|
||||
!arms[0].body.is_empty(),
|
||||
"then arm must contain prose stmts: {:?}",
|
||||
arms[0].body
|
||||
);
|
||||
assert!(
|
||||
!arms[1].body.is_empty(),
|
||||
"else arm must contain prose stmts: {:?}",
|
||||
arms[1].body
|
||||
);
|
||||
}
|
||||
other => panic!("expected Branch as body[1] after assign, got {other:?}"),
|
||||
}
|
||||
// No Call/Assign print siblings after the branch
|
||||
assert!(
|
||||
!main.body.iter().skip(2).any(|s| matches!(s, Stmt::Call { .. } | Stmt::Assign { .. })),
|
||||
"prose escaped branch: {:?}",
|
||||
main.body
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_hello() {
|
||||
let src = include_str!("../../tests/structure/hello.mq.md");
|
||||
|
||||
@@ -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 {
|
||||
|
||||
+191
-26
@@ -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()) {
|
||||
@@ -94,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 => {
|
||||
@@ -306,11 +317,7 @@ fn render_table_block(
|
||||
}
|
||||
}
|
||||
if let Some(body) = writebacks.get(&first_line) {
|
||||
html.push_str(&format!(
|
||||
r#"<div class="card output-card" id="wb-{line}"><pre class="output-body">{}</pre></div>"#,
|
||||
escape(body),
|
||||
line = first_line
|
||||
));
|
||||
html.push_str(&crate::view::render::render_output_card(first_line, body));
|
||||
}
|
||||
html.push_str("</div>");
|
||||
(html, i)
|
||||
@@ -626,6 +633,11 @@ fn render_fun_heading(fun: &Function, annots: &[ViewAnnot]) -> String {
|
||||
}
|
||||
s.push_str("</div>");
|
||||
if !fun.params.is_empty() {
|
||||
// Default SSR values = last call frame (matches picker default = last option).
|
||||
let default_args = call_labels
|
||||
.last()
|
||||
.map(|a| parse_args_brief(&a.value))
|
||||
.unwrap_or_default();
|
||||
s.push_str(r#"<div class="params">"#);
|
||||
for p in &fun.params {
|
||||
let cls = if p.inferred {
|
||||
@@ -638,11 +650,19 @@ fn render_fun_heading(fun: &Function, annots: &[ViewAnnot]) -> String {
|
||||
} else {
|
||||
"explicit + param"
|
||||
};
|
||||
let val = default_args
|
||||
.get(p.name.as_str())
|
||||
.filter(|v| !v.is_empty())
|
||||
.map(|v| format!("={}", escape(v)))
|
||||
.unwrap_or_default();
|
||||
// Always emit chip-val so call-picker JS can refresh per frame.
|
||||
s.push_str(&format!(
|
||||
r#"<span class="{cls}" title="{title}">{name}</span>"#,
|
||||
r#"<span class="{cls}" data-param-name="{name}" data-fn="{fn}" title="{title}">{name}<span class="chip-val">{val}</span></span>"#,
|
||||
cls = cls,
|
||||
title = title,
|
||||
name = escape(&p.name),
|
||||
fn = escape(&fun.name),
|
||||
val = val,
|
||||
));
|
||||
}
|
||||
s.push_str("</div>");
|
||||
@@ -651,6 +671,22 @@ fn render_fun_heading(fun: &Function, annots: &[ViewAnnot]) -> String {
|
||||
s
|
||||
}
|
||||
|
||||
/// Parse `args_brief` (`谁=marqdo, n=37`) into name → value.
|
||||
fn parse_args_brief(brief: &str) -> HashMap<String, String> {
|
||||
let mut m = HashMap::new();
|
||||
if brief.trim().is_empty() {
|
||||
return m;
|
||||
}
|
||||
for part in brief.split(", ") {
|
||||
if let Some((k, v)) = part.split_once('=') {
|
||||
if !k.is_empty() {
|
||||
m.insert(k.to_string(), v.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
fn render_line_block(
|
||||
line_no: u32,
|
||||
text: &str,
|
||||
@@ -671,13 +707,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));
|
||||
}
|
||||
@@ -709,22 +746,37 @@ fn render_line_block(
|
||||
}
|
||||
|
||||
if let Some(body) = writeback_body {
|
||||
s.push_str(&format!(
|
||||
r#"<div class="card output-card" id="wb-{line}"><pre class="output-body">{}</pre></div>"#,
|
||||
escape(body),
|
||||
line = line_no
|
||||
));
|
||||
s.push_str(&crate::view::render::render_output_card(line_no, body));
|
||||
}
|
||||
|
||||
if !annots.is_empty() {
|
||||
let owned: Vec<ViewAnnot> = 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<ViewAnnot> = 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("</div>");
|
||||
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("<svg") || v.contains("```") || v.chars().count() > 96
|
||||
}
|
||||
|
||||
/// Render prose with markers stripped; show surface inner text only.
|
||||
fn render_prose_with_marks(
|
||||
line_no: u32,
|
||||
@@ -792,8 +844,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<u32, SpecialAssign>) -> HashSet<u32> {
|
||||
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<u32, &Function> {
|
||||
@@ -858,48 +938,52 @@ fn stmt_line(st: &Stmt) -> u32 {
|
||||
}
|
||||
}
|
||||
|
||||
fn index_special_assigns(module: &Module) -> HashMap<u32, SpecialAssign> {
|
||||
fn index_special_assigns(module: &Module, source: &str) -> HashMap<u32, SpecialAssign> {
|
||||
let src_lines: Vec<&str> = source.lines().collect();
|
||||
let mut m = HashMap::new();
|
||||
fn walk(fun: &Function, m: &mut HashMap<u32, SpecialAssign>) {
|
||||
fn walk(fun: &Function, m: &mut HashMap<u32, SpecialAssign>, 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<u32, SpecialAssign>) {
|
||||
fn record(st: &Stmt, m: &mut HashMap<u32, SpecialAssign>, src_lines: &[&str]) {
|
||||
match st {
|
||||
Stmt::Assign {
|
||||
name,
|
||||
value: crate::ast::Expr::Formula(e),
|
||||
span,
|
||||
end_line,
|
||||
..
|
||||
} => {
|
||||
let tex = match e {
|
||||
crate::formula::Expr::Matrix { source, .. } => source.clone(),
|
||||
_ => crate::view::render::formula_ascii_to_tex_pub(&e.as_display()),
|
||||
};
|
||||
let end_line = (*end_line).max(fence_block_end(src_lines, span.line, "$$"));
|
||||
m.insert(
|
||||
span.line,
|
||||
SpecialAssign::Formula {
|
||||
name: name.clone(),
|
||||
tex,
|
||||
end_line,
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -907,14 +991,17 @@ fn index_special_assigns(module: &Module) -> HashMap<u32, SpecialAssign> {
|
||||
name,
|
||||
value: crate::ast::Expr::Code(c),
|
||||
span,
|
||||
end_line,
|
||||
..
|
||||
} => {
|
||||
let end_line = (*end_line).max(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 +1009,66 @@ fn index_special_assigns(module: &Module) -> HashMap<u32, SpecialAssign> {
|
||||
}
|
||||
}
|
||||
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 {
|
||||
if assign_line == 0 || assign_line as usize > src_lines.len() {
|
||||
return assign_line;
|
||||
}
|
||||
let assign = src_lines[assign_line as usize - 1].trim();
|
||||
// Meta formula: assign span is the opening `$$` line itself.
|
||||
if fence == "$$" && assign == "$$" {
|
||||
let mut i = assign_line as usize; // 0-based next line
|
||||
while i < src_lines.len() {
|
||||
if src_lines[i].trim() == "$$" {
|
||||
return (i + 1) as u32;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
return assign_line;
|
||||
}
|
||||
if fence == "$$" && assign.starts_with("$$") && assign.ends_with("$$") && assign.len() > 4 {
|
||||
return assign_line;
|
||||
}
|
||||
let mut i = assign_line as usize; // 0-based index of line after assign
|
||||
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 == "```" {
|
||||
return line_no;
|
||||
}
|
||||
if fence == "$$" && t == "$$" {
|
||||
i += 1;
|
||||
while i < src_lines.len() {
|
||||
if src_lines[i].trim() == "$$" {
|
||||
return (i + 1) as u32;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
return line_no;
|
||||
}
|
||||
} else if t.is_empty() {
|
||||
i += 1;
|
||||
continue;
|
||||
} else {
|
||||
return assign_line;
|
||||
}
|
||||
} else if fence == "```" && t.starts_with("```") {
|
||||
return line_no;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
assign_line
|
||||
}
|
||||
|
||||
fn skip_frontmatter_end(lines: &[ClassifiedLine]) -> Option<u32> {
|
||||
let first_code = lines.iter().find(|l| l.kind == LineKind::Code)?;
|
||||
if first_code.text.trim() != "---" {
|
||||
@@ -1051,6 +1193,29 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inferred_param_chip_shows_call_value() {
|
||||
let src = include_str!("../../tests/markup-v03/inc-prose.mq.md");
|
||||
let module = crate::parse::parse_source(src).unwrap();
|
||||
let add = module
|
||||
.functions
|
||||
.iter()
|
||||
.find(|f| f.name == "加一函数")
|
||||
.expect("加一函数");
|
||||
assert!(add.params.iter().any(|p| p.name == "n" && p.inferred));
|
||||
let cap = crate::run_source(src, &crate::RunOptions::default()).unwrap();
|
||||
let annots = build_view_annots(&module, src, &cap);
|
||||
let html = render_module_document(&module, src, &annots);
|
||||
assert!(
|
||||
html.contains(r#"data-param-name="n""#) && html.contains("chip inferred"),
|
||||
"inferred param chip missing: {html}"
|
||||
);
|
||||
assert!(
|
||||
html.contains(r#"class="chip-val">=37"#) || html.contains("chip-val\">=37"),
|
||||
"expected param chip value from call frame: {html}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_frame_pickers_and_all_arms() {
|
||||
let src = include_str!("../../tests/view/document-annot-demo.mq.md");
|
||||
|
||||
@@ -593,6 +593,15 @@ ul.doc-loop, ol.doc-branch {
|
||||
font-size: 0.65em;
|
||||
opacity: 0.7;
|
||||
}
|
||||
.chip .chip-val {
|
||||
font-weight: 500;
|
||||
opacity: 0.78;
|
||||
font-family: var(--mono);
|
||||
font-size: 0.92em;
|
||||
}
|
||||
.chip .chip-val:empty {
|
||||
display: none;
|
||||
}
|
||||
.nested {
|
||||
margin: 0.45rem 0 0.15rem 0.15rem;
|
||||
padding-left: 0.85rem;
|
||||
@@ -963,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;
|
||||
@@ -978,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;
|
||||
@@ -2185,11 +2249,43 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String {
|
||||
try {{ return JSON.parse(el.textContent || "{{}}"); }} catch (e) {{ return null; }}
|
||||
}}
|
||||
|
||||
function parseArgsBrief(brief) {{
|
||||
var out = {{}};
|
||||
if (!brief) return out;
|
||||
String(brief).split(", ").forEach(function (part) {{
|
||||
var i = part.indexOf("=");
|
||||
if (i <= 0) return;
|
||||
out[part.slice(0, i)] = part.slice(i + 1);
|
||||
}});
|
||||
return out;
|
||||
}}
|
||||
|
||||
function applyParamChipValues(fnName, callId, trace) {{
|
||||
if (!trace || !Array.isArray(trace.calls)) return;
|
||||
var brief = "";
|
||||
for (var i = 0; i < trace.calls.length; i++) {{
|
||||
var c = trace.calls[i];
|
||||
if (String(c.call_id) === String(callId) && String(c.fn || "") === String(fnName)) {{
|
||||
brief = c.args_brief || "";
|
||||
break;
|
||||
}}
|
||||
}}
|
||||
var args = parseArgsBrief(brief);
|
||||
document.querySelectorAll('.chip[data-fn="' + fnName + '"][data-param-name]').forEach(function (chip) {{
|
||||
var name = chip.getAttribute("data-param-name") || "";
|
||||
var slot = chip.querySelector(".chip-val");
|
||||
if (!slot) return;
|
||||
var v = args[name];
|
||||
slot.textContent = v ? ("=" + v) : "";
|
||||
}});
|
||||
}}
|
||||
|
||||
/** Source structure always stays visible; only chips + arm classes follow the frame. */
|
||||
function initCallPickers() {{
|
||||
document.querySelectorAll(".call-picker").forEach(function (sel) {{
|
||||
function apply() {{
|
||||
var callId = String(sel.value || "");
|
||||
var fnName = String(sel.getAttribute("data-fn") || "");
|
||||
var allowed = {{}};
|
||||
Array.prototype.forEach.call(sel.options, function (o) {{
|
||||
allowed[String(o.value)] = true;
|
||||
@@ -2202,6 +2298,7 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String {
|
||||
chip.hidden = cid !== callId;
|
||||
}});
|
||||
var trace = readViewTrace();
|
||||
applyParamChipValues(fnName, callId, trace);
|
||||
if (trace && Array.isArray(trace.events)) {{
|
||||
var takenByLine = {{}};
|
||||
trace.events.forEach(function (ev) {{
|
||||
|
||||
+107
-18
@@ -971,10 +971,11 @@ fn render_fun(
|
||||
("chip", "explicit + param")
|
||||
};
|
||||
s.push_str(&format!(
|
||||
"<span class=\"{cls}\" title=\"{title}\">{name}</span>",
|
||||
"<span class=\"{cls}\" data-param-name=\"{name}\" data-fn=\"{fn}\" title=\"{title}\">{name}<span class=\"chip-val\"></span></span>",
|
||||
cls = cls,
|
||||
title = title,
|
||||
name = escape(&p.name),
|
||||
fn = escape(&fun.name),
|
||||
));
|
||||
}
|
||||
s.push_str("</div>");
|
||||
@@ -1069,17 +1070,89 @@ fn stmt_end_line(stmt: &Stmt) -> u32 {
|
||||
|
||||
fn output_card(line: u32, writebacks: &HashMap<u32, String>) -> String {
|
||||
match writebacks.get(&line) {
|
||||
Some(body) => {
|
||||
let badges = writeback_badges(body);
|
||||
format!(
|
||||
r#"<div class="card output-card" id="wb-{line}"><div class="wb-badges">{badges}</div><pre class="output-body">{}</pre></div>"#,
|
||||
escape(body)
|
||||
)
|
||||
}
|
||||
Some(body) => render_output_card(line, body),
|
||||
None => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Live view + static site: text `<pre>` and/or `<img>` 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#"<pre class="output-body">{}</pre>"#,
|
||||
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#"<figure class="wb-figure"><img class="wb-image" src="{src}" alt="writeback"/><figcaption class="wb-image-url">{cap}</figcaption></figure>"#,
|
||||
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#"<div class="card output-card{img_cls}" id="wb-{line}" data-wb="1"><div class="wb-badges">{badges}</div>{body}</div>"#,
|
||||
line = line,
|
||||
img_cls = if has_img { " output-card-image" } else { "" },
|
||||
badges = badges,
|
||||
body = body_html,
|
||||
)
|
||||
}
|
||||
|
||||
fn extract_md_image_url(line: &str) -> Option<String> {
|
||||
let t = line.trim();
|
||||
let rest = t.strip_prefix("?;
|
||||
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#"<div class="doc-block doc-writeback" data-line="{line}" data-wb-kind="{kind}"><span class="wb-source-badge">{label}</span><code class="wb-source-text">{text}</code></div>"#,
|
||||
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() {
|
||||
@@ -1440,25 +1513,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!(
|
||||
"<div class=\"card formula-card\"><span class=\"badge\">formula</span> \
|
||||
<code class=\"expr\">`{}` =</code> \
|
||||
<div class=\"math-block\">$${}$$</div></div>",
|
||||
escape(name),
|
||||
escape(tex),
|
||||
r#"<div class="card formula-card" data-formula-name="{name}">
|
||||
<div class="formula-head"><span class="badge">formula</span> <span class="formula-name">{name}</span></div>
|
||||
<div class="math-block">$${tex}$$</div>
|
||||
</div>"#,
|
||||
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#"<div class="card code-card" data-lang="{lang}">
|
||||
r#"<div class="card code-card" data-lang="{lang}" data-code-name="{name}">
|
||||
<div class="code-head">
|
||||
<span class="badge">code</span>
|
||||
<code class="expr">`{name}` =</code>
|
||||
<span class="code-name">{name}</span>
|
||||
<span class="code-lang">{lang}</span>
|
||||
<div class="code-actions">
|
||||
<input type="text" class="code-cmd" placeholder="{placeholder}" spellcheck="false" autocomplete="off"/>
|
||||
@@ -1737,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");
|
||||
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, "");
|
||||
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");
|
||||
@@ -1749,7 +1837,8 @@ mod tests {
|
||||
assert!(add.params.iter().any(|p| p.name == "n" && p.inferred));
|
||||
let html = render_module_structure(&module, src);
|
||||
assert!(
|
||||
html.contains("chip inferred") && html.contains(">n<"),
|
||||
html.contains("chip inferred")
|
||||
&& (html.contains(">n<") || html.contains(r#"data-param-name="n""#)),
|
||||
"expected inferred chip for n: {html}"
|
||||
);
|
||||
let outline = render_function_outline(&module);
|
||||
|
||||
@@ -3365,3 +3365,33 @@ fn markup_v03_decl_ident_only() {
|
||||
fn markup_v03_bold_expr() {
|
||||
assert_out_v03("tests/markup-v03/bold-expr.mq.md", "42");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn markup_v03_formula_meta_var() {
|
||||
assert_out_v03("tests/markup-v03/formula-meta-var.mq.md", "x^2 - 2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn markup_v03_inline_dollar_formula() {
|
||||
assert_out_v03("tests/markup-v03/inline-dollar-formula.mq.md", "x + 1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn markup_v03_branch_arm_prose() {
|
||||
assert_out_v03("tests/markup-v03/branch-arm-prose.mq.md", "正");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn markup_v03_branch_cond_narrative() {
|
||||
assert_out_v03("tests/markup-v03/branch-cond-narrative.mq.md", "正");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn markup_v03_foreach_narrative() {
|
||||
assert_out_v03("tests/markup-v03/foreach-narrative.mq.md", "a\nb\n1\n2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn markup_v03_foreach_nested_link() {
|
||||
assert_out_v03("tests/markup-v03/foreach-nested-link.mq.md", "x\ny");
|
||||
}
|
||||
@@ -17,6 +17,8 @@
|
||||
|
||||
代码即文档叙述面(G1–G4):`module-hr` / `soft-emphasis` / `float-discount` / `dynamic-footnote` —— 设计见 [code-as-docs-gaps.md](../../doc/design/code-as-docs-gaps.md)。
|
||||
|
||||
块公式 meta / 控制流叙述:`formula-meta-var` / `inline-dollar-formula` / `branch-arm-prose` / `branch-cond-narrative` / `foreach-narrative` / `foreach-nested-link` —— 见 [fence-meta-and-control-prose.md](../../doc/design/fence-meta-and-control-prose.md)。
|
||||
|
||||
```bash
|
||||
cargo test --test gold markup_v03
|
||||
marqdo run tests/markup-v03/inc-prose.mq.md
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
---
|
||||
title: v0.3 分支臂内叙述
|
||||
description: 臂内 prose 不得逃逸;n>0 时仅 then
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
**n = 1**
|
||||
|
||||
1. `n` > 0
|
||||
此时`n`为正,我们 **打印 内容="正"**
|
||||
2. *
|
||||
否则 **打印 内容="非正"**
|
||||
|
||||
*None*
|
||||
@@ -0,0 +1,15 @@
|
||||
---
|
||||
title: v0.3 条件行夹叙述
|
||||
description: 当`n`大于 0 时 / 否则 *
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
**n = 1**
|
||||
|
||||
1. 当`n`大于 0 时
|
||||
我们 **打印 内容="正"**
|
||||
2. 否则 *
|
||||
我们 **打印 内容="非正"**
|
||||
|
||||
*None*
|
||||
@@ -0,0 +1,28 @@
|
||||
---
|
||||
title: v0.3 循环头叙述糖
|
||||
description: 对`xs`的每一项`项` / for each `item` in `ys`
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
`xs` =
|
||||
|
||||
| v |
|
||||
|---|
|
||||
| a |
|
||||
| b |
|
||||
|
||||
- 对`xs`的每一项`项`
|
||||
**打印 内容=`项`**
|
||||
|
||||
`ys` =
|
||||
|
||||
| v |
|
||||
|---|
|
||||
| 1 |
|
||||
| 2 |
|
||||
|
||||
- for each `item` in `ys`
|
||||
**print text=`item`**
|
||||
|
||||
*None*
|
||||
@@ -0,0 +1,25 @@
|
||||
---
|
||||
title: v0.3 推荐循环头嵌套
|
||||
description: `- [o](外层)` 内再 `- [i](内层)`
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
`外层` =
|
||||
|
||||
| a |
|
||||
|---|
|
||||
| x |
|
||||
| y |
|
||||
|
||||
`内层` =
|
||||
|
||||
| b |
|
||||
|---|
|
||||
| 1 |
|
||||
|
||||
- [o](外层)
|
||||
- [i](内层)
|
||||
**print text=`o`**
|
||||
|
||||
*None*
|
||||
@@ -0,0 +1,14 @@
|
||||
---
|
||||
title: v0.3 块公式 % marqdo: var=
|
||||
description: 无空 RHS;块内 TeX 注释绑定 formula
|
||||
import math:lib/math.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
$$
|
||||
% marqdo: var=f
|
||||
x^2 - 2
|
||||
$$
|
||||
|
||||
**print text=`f`**
|
||||
@@ -0,0 +1,10 @@
|
||||
---
|
||||
title: v0.3 行内 $ 传统绑定
|
||||
description: `g` = $x+1$ → formula(无 % marqdo)
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
`g` = $x + 1$
|
||||
|
||||
**print text=`g`**
|
||||
Reference in new issue
Block a user