Add math stdlib with formulas/plots and polish the docs view.

Ship Num/Formula runtime, bilingual math libs, SVG plots with axes/grid, and view UX for collapsible folders plus centered plots.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-08-05 11:30:47 +08:00
1 parent a53ebb65ee
commit dcd0cdb8f7
40 files changed
+3553 -276

No files matched your search

+178 -35
View File
@@ -169,12 +169,49 @@ a:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; }
opacity: 1;
font-weight: 500;
}
.nav-root { margin: 0; padding: 0; list-style: none; }
.folder {
margin: 0.55rem 0 0.2rem;
border: none;
}
.folder > summary {
list-style: none;
cursor: pointer;
user-select: none;
color: var(--muted);
font-size: 0.72rem;
margin: 1rem 0.35rem 0.35rem;
font-weight: 600;
letter-spacing: 0.01em;
padding: 0.35rem 0.45rem;
border-radius: 8px;
display: flex;
align-items: center;
gap: 0.35rem;
transition: background 0.12s ease, color 0.12s ease;
}
.folder > summary::-webkit-details-marker { display: none; }
.folder > summary::before {
content: "";
width: 0;
height: 0;
border-style: solid;
border-width: 4px 0 4px 6px;
border-color: transparent transparent transparent var(--muted);
opacity: 0.85;
transition: transform 0.12s ease;
flex-shrink: 0;
}
.folder[open] > summary::before {
transform: rotate(90deg);
}
.folder > summary:hover {
background: var(--hover);
color: var(--ink);
}
.folder > ul {
list-style: none;
padding: 0.1rem 0 0.15rem 0.55rem;
margin: 0;
}
.panel-wrap {
min-width: 0;
@@ -231,7 +268,7 @@ section.block > h2 {
}
.stdin-form label {
font-size: 0.85rem;
color: var(--text);
color: var(--ink);
}
.stdin-form .hint {
color: var(--muted);
@@ -243,10 +280,10 @@ section.block > h2 {
font-family: var(--mono);
font-size: 0.9rem;
padding: 0.65rem 0.75rem;
border: 1px solid var(--border);
border: 1px solid var(--line);
border-radius: 8px;
background: var(--surface);
color: var(--text);
color: var(--ink);
resize: vertical;
min-height: 4.5rem;
}
@@ -254,14 +291,19 @@ section.block > h2 {
justify-self: start;
font: inherit;
font-size: 0.9rem;
padding: 0.45rem 0.9rem;
border: 1px solid var(--border);
font-weight: 600;
padding: 0.5rem 1rem;
border: 1px solid var(--ink);
border-radius: 8px;
background: var(--text);
color: var(--bg);
background: var(--ink);
color: #ffffff;
cursor: pointer;
}
.stdin-form button:hover { opacity: 0.88; }
.stdin-form button:focus-visible {
outline: 2px solid var(--focus);
outline-offset: 2px;
}
.structure {
background: var(--surface);
border: 1px solid var(--line);
@@ -342,6 +384,38 @@ section.block > h2 {
color: var(--ink);
font-weight: 500;
}
.formula-card .math-block {
display: inline-block;
margin: 0.25rem 0 0.1rem 0.25rem;
vertical-align: middle;
overflow-x: auto;
max-width: 100%;
}
.formula-card .katex-display {
margin: 0.2rem 0;
}
.plots {
display: grid;
gap: 1rem;
margin-top: 1rem;
justify-items: center;
}
.plot {
overflow: auto;
background: var(--surface);
border: 1px solid var(--line);
border-radius: var(--radius);
padding: 0.75rem;
width: 100%;
display: flex;
justify-content: center;
}
.plot svg {
display: block;
max-width: 100%;
height: auto;
margin-inline: auto;
}
.comment-text {
color: var(--muted);
font-size: 0.92rem;
@@ -439,6 +513,7 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String {
<link rel="icon" href="https://s3.cflmy.cn/logo/Logo.ico" type="image/x-icon"/>
<link rel="shortcut icon" href="https://s3.cflmy.cn/logo/Logo.ico" type="image/x-icon"/>
<link rel="apple-touch-icon" href="https://s3.cflmy.cn/logo/Logo.png"/>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.css" crossorigin="anonymous"/>
<style>{css}</style>
</head>
<body>
@@ -470,6 +545,9 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String {
</main>
</div>
</div>
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.js" crossorigin="anonymous"></script>
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/contrib/auto-render.min.js" crossorigin="anonymous"
onload="renderMathInElement(document.body,{{delimiters:[{{left:'$$',right:'$$',display:true}},{{left:'\\(',right:'\\)',display:false}}],ignoredTags:['script','noscript','style','textarea','pre','code','kbd']}});"></script>
</body>
</html>
"##,
@@ -481,23 +559,22 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String {
}
pub fn nav_html(files: &[PathBuf], active: Option<&str>, links: &LinkMode) -> String {
let mut out = String::from("<h2>Files</h2><ul>");
let mut last_folder = String::new();
let mut out = String::from("<h2>Files</h2>");
let mut last_folder: Option<String> = None;
for f in files {
let rel = f.to_string_lossy().replace('\\', "/");
let folder = Path::new(&rel)
.parent()
.map(|p| p.to_string_lossy().to_string())
.map(|p| p.to_string_lossy().replace('\\', "/"))
.unwrap_or_default();
if folder != last_folder {
if !folder.is_empty() {
out.push_str(&format!(
"</ul><div class=\"folder\">{}</div><ul>",
escape(&folder)
));
}
last_folder = folder;
if last_folder.as_deref() != Some(folder.as_str()) {
close_nav_group(&mut out, last_folder.as_deref());
open_nav_group(&mut out, &folder, active);
last_folder = Some(folder);
}
let name = Path::new(&rel)
.file_name()
.and_then(|s| s.to_str())
@@ -514,7 +591,8 @@ pub fn nav_html(files: &[PathBuf], active: Option<&str>, links: &LinkMode) -> St
escape(name)
));
}
out.push_str("</ul>");
close_nav_group(&mut out, last_folder.as_deref());
// index link for static pages
if matches!(links, LinkMode::Static { from: Some(_) }) {
let home = href_index(links);
@@ -529,6 +607,37 @@ pub fn nav_html(files: &[PathBuf], active: Option<&str>, links: &LinkMode) -> St
out
}
fn close_nav_group(out: &mut String, folder: Option<&str>) {
match folder {
None => {}
Some("") => out.push_str("</ul>"),
Some(_) => out.push_str("</ul></details>"),
}
}
fn open_nav_group(out: &mut String, folder: &str, active: Option<&str>) {
if folder.is_empty() {
out.push_str("<ul class=\"nav-root\">");
return;
}
let contains_active = active.is_some_and(|a| {
Path::new(a)
.parent()
.map(|p| p.to_string_lossy().replace('\\', "/") == folder)
.unwrap_or(false)
});
// Index (no active): keep folders open for browsing; else open only the active folder.
let open_attr = if active.is_none() || contains_active {
" open"
} else {
""
};
out.push_str(&format!(
"<details class=\"folder\"{open_attr}><summary>{}</summary><ul>",
escape(folder)
));
}
fn href_file(links: &LinkMode, target_rel: &str) -> String {
match links {
LinkMode::Live => format!("/file?path={}", urlencoding_encode(target_rel)),
@@ -620,27 +729,47 @@ pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkM
} else {
escape(&vm.stderr)
};
let stdin_panel = match links {
LinkMode::Live => format!(
r#"<form class="stdin-form" method="get" action="/file">
let stdin_panel = if vm.input_prompts.is_empty() {
String::new()
} else {
let placeholder = vm.input_prompts.join("\n");
let rows = vm.input_prompts.len().clamp(2, 8);
match links {
LinkMode::Live => {
let hint = if vm.input_prompts.iter().any(|p| !p.is_empty()) {
format!(
"prompts: {}",
escape(&vm.input_prompts.join(" · "))
)
} else {
"one line per <code>input</code>".into()
};
format!(
r#"<form class="stdin-form" method="get" action="/file">
<input type="hidden" name="path" value="{path}"/>
<label for="stdin">Preset input <span class="hint">one line per <code>input</code>; overrides frontmatter <code>stdin:</code> / <code>输入:</code></span></label>
<textarea id="stdin" name="stdin" rows="3" placeholder="Alice">{stdin}</textarea>
<label for="stdin">Preset input <span class="hint">{hint}</span></label>
<textarea id="stdin" name="stdin" rows="{rows}" placeholder="{placeholder}">{stdin}</textarea>
<button type="submit">Run with input</button>
</form>"#,
path = escape(rel),
stdin = escape(&vm.preset_stdin),
),
LinkMode::Static { .. } => {
if vm.preset_stdin.is_empty() {
String::new()
} else {
format!(
r#"<p class="hint">Demo stdin from frontmatter (static export cannot re-run interactively):</p>
<pre class="source" style="margin-bottom:0.75rem">{stdin}</pre>"#,
path = escape(rel),
hint = hint,
rows = rows,
placeholder = escape(&placeholder),
stdin = escape(&vm.preset_stdin),
)
}
LinkMode::Static { .. } => {
if vm.preset_stdin.is_empty() {
String::new()
} else {
format!(
r#"<p class="hint">Demo stdin (static export cannot re-run interactively); prompts: {prompts}</p>
<pre class="source" style="margin-bottom:0.75rem">{stdin}</pre>"#,
prompts = escape(&vm.input_prompts.join(" · ")),
stdin = escape(&vm.preset_stdin),
)
}
}
}
};
let title = Path::new(rel)
@@ -648,6 +777,18 @@ pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkM
.and_then(|s| s.to_str())
.unwrap_or(rel)
.trim_end_matches(".mq.md");
let plots_html = if vm.plots.is_empty() {
String::new()
} else {
let mut s = String::from(r#"<div class="plots">"#);
for svg in &vm.plots {
s.push_str(r#"<div class="plot">"#);
s.push_str(svg);
s.push_str("</div>");
}
s.push_str("</div>");
s
};
let main = format!(
r#"
<h1 class="page">{title}<span class="status-pill {status}">{status_label}</span></h1>
@@ -660,6 +801,7 @@ pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkM
<h2>Execution</h2>
{stdin_panel}
<div class="out {status}">{out}</div>
{plots}
</section>
<section class="block">
<h2>Source</h2>
@@ -673,6 +815,7 @@ pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkM
structure = vm.structure_html,
stdin_panel = stdin_panel,
out = out_text,
plots = plots_html,
source = escape(&vm.source),
);
layout(rel, &nav, &main)
+23 -8
View File
@@ -16,7 +16,7 @@ use tiny_http::{Header, Method, Request, Response, Server, StatusCode};
use crate::input_feed::{effective_stdin, split_stdin_text};
use crate::view::html::{escape, page_file, page_index, LinkMode};
use crate::view::render::{render_module_structure, FileViewModel};
use crate::view::render::{collect_input_prompts, render_module_structure, FileViewModel};
use crate::{run_file_capture, RunOptions};
pub struct ViewOptions {
@@ -167,11 +167,18 @@ pub(crate) fn build_file_view(
live: bool,
) -> Result<FileViewModel> {
let source = fs::read_to_string(abs).with_context(|| format!("read {}", abs.display()))?;
let structure = match crate::load::load_module(abs) {
Ok(module) => render_module_structure(&module, &source),
Err(e) => format!(
"<div class=\"err\">parse/load error: {}</div>",
escape(&tidy_user_error(&format!("{e:#}"), abs, rel))
// Structure shows this file only — do not merge imported lib bodies into the tree.
let (structure, input_prompts) = match crate::parse::parse_source(&source) {
Ok(module) => (
render_module_structure(&module, &source),
collect_input_prompts(&module),
),
Err(e) => (
format!(
"<div class=\"err\">parse/load error: {}</div>",
escape(&tidy_user_error(&format!("{e:#}"), abs, rel))
),
Vec::new(),
),
};
let effective = effective_stdin(&source, stdin_lines);
@@ -181,12 +188,18 @@ pub(crate) fn build_file_view(
opts.sleep_limit_ms = if live { Some(30_000) } else { Some(0) };
// Optional: sandbox to the whole view tree so sibling folders are reachable.
opts.fs_root = Some(root.root.clone());
let (stdout, stderr, ok) = match run_file_capture(abs, &opts) {
Ok(cap) => (cap.stdout, String::new(), true),
let (stdout, stderr, ok, plots) = match run_file_capture(abs, &opts) {
Ok(cap) => (
cap.stdout,
String::new(),
true,
cap.plots.into_iter().map(|p| p.svg).collect(),
),
Err(e) => (
String::new(),
tidy_user_error(&format!("{e:#}"), abs, rel),
false,
Vec::new(),
),
};
Ok(FileViewModel {
@@ -197,6 +210,8 @@ pub(crate) fn build_file_view(
stderr,
ok,
preset_stdin: effective.join("\n"),
input_prompts,
plots,
})
}
+1
View File
@@ -30,6 +30,7 @@ pub fn write_static(opts: OutputOptions) -> Result<()> {
vm.stdout.clear();
vm.stderr = "execution skipped (--no-exec)".into();
vm.ok = true;
vm.plots.clear();
}
let links = LinkMode::Static {
from: Some(rel.clone()),
+245 -8
View File
@@ -20,6 +20,123 @@ pub struct FileViewModel {
pub ok: bool,
/// Text shown in the live-view preset stdin box.
pub preset_stdin: String,
/// One entry per `input` / `输入` call (prompt text; may be empty).
/// Empty vec → page does not use input; hide the preset form.
pub input_prompts: Vec<String>,
/// SVG plots from math lib (embedded in Execution).
pub plots: Vec<String>,
}
/// Collect prompt strings from every `input` / `输入` call in the module (pre-order).
pub fn collect_input_prompts(module: &Module) -> Vec<String> {
let mut out = Vec::new();
for fun in &module.functions {
collect_input_prompts_fun(fun, &mut out);
}
out
}
fn collect_input_prompts_fun(fun: &Function, out: &mut Vec<String>) {
for stmt in &fun.body {
collect_input_prompts_stmt(stmt, out);
}
for child in &fun.children {
collect_input_prompts_fun(child, out);
}
}
fn collect_input_prompts_stmt(stmt: &Stmt, out: &mut Vec<String>) {
match stmt {
Stmt::Assign { value, .. } | Stmt::Return { value, .. } => {
collect_input_prompts_expr(value, out);
}
Stmt::Call { call, .. } => {
push_input_prompt(call, out);
for a in &call.args {
match a {
Arg::Positional(e) | Arg::Named { value: e, .. } => {
collect_input_prompts_expr(e, out);
}
}
}
}
Stmt::Branch { arms, .. } => {
for arm in arms {
if let Some(c) = &arm.condition {
collect_input_prompts_expr(c, out);
}
for s in &arm.body {
collect_input_prompts_stmt(s, out);
}
}
}
Stmt::While {
condition, body, ..
} => {
collect_input_prompts_expr(condition, out);
for s in body {
collect_input_prompts_stmt(s, out);
}
}
Stmt::ForEach { body, .. } => {
for s in body {
collect_input_prompts_stmt(s, out);
}
}
}
}
fn collect_input_prompts_expr(expr: &Expr, out: &mut Vec<String>) {
match expr {
Expr::Call(call) => {
push_input_prompt(call, out);
for a in &call.args {
match a {
Arg::Positional(e) | Arg::Named { value: e, .. } => {
collect_input_prompts_expr(e, out);
}
}
}
}
Expr::Unary { expr, .. } => collect_input_prompts_expr(expr, out),
Expr::Binary { left, right, .. } => {
collect_input_prompts_expr(left, out);
collect_input_prompts_expr(right, out);
}
Expr::List(items) => {
for e in items {
collect_input_prompts_expr(e, out);
}
}
Expr::Literal(_) | Expr::Var(_) | Expr::Interp(_) | Expr::Formula(_) => {}
}
}
fn push_input_prompt(call: &CallExpr, out: &mut Vec<String>) {
if crate::aliases::canonical_builtin(&call.callee) != Some("input") {
return;
}
for a in &call.args {
if let Arg::Named { name, value } = a {
if crate::aliases::canonical_param("input", name) == "prompt" {
out.push(prompt_expr_text(value));
return;
}
}
}
if let Some(Arg::Positional(value)) = call.args.first() {
out.push(prompt_expr_text(value));
return;
}
out.push(String::new());
}
fn prompt_expr_text(expr: &Expr) -> String {
match expr {
Expr::Literal(Literal::Text(t)) => t.clone(),
Expr::Literal(lit) => lit_display(lit),
other => expr_display(other),
}
}
pub fn render_module_structure(module: &Module, source: &str) -> String {
@@ -209,9 +326,8 @@ fn stmt_start(stmt: &Stmt) -> u32 {
fn stmt_end_line(stmt: &Stmt) -> u32 {
match stmt {
Stmt::Assign { span, .. } | Stmt::Return { span, .. } | Stmt::Call { span, .. } => {
span.line + 1
}
Stmt::Assign { end_line, .. } => end_line + 1,
Stmt::Return { span, .. } | Stmt::Call { span, .. } => span.line + 1,
Stmt::Branch { arms, span, .. } => {
let mut end = span.line + 1;
for arm in arms {
@@ -234,11 +350,25 @@ fn stmt_end_line(stmt: &Stmt) -> u32 {
fn render_stmt(stmt: &Stmt, lines: &[ClassifiedLine]) -> (String, u32) {
let end = stmt_end_line(stmt);
let html = match stmt {
Stmt::Assign { name, value, .. } => format!(
"<div class=\"card\"><span class=\"badge\">bind</span><code class=\"expr\">`{}` = {}</code></div>",
escape(name),
escape(&expr_display(value))
),
Stmt::Assign {
name,
value: Expr::Formula(e),
..
} => {
let tex = escape(&formula_ascii_to_tex(&e.as_display()));
format!(
"<div class=\"card formula-card\"><span class=\"badge\">formula</span> \
<code class=\"expr\">`{}` =</code> \
<div class=\"math-block\">$${}$$</div></div>",
escape(name),
tex
)
}
Stmt::Assign { name, value, .. } => format!(
"<div class=\"card\"><span class=\"badge\">bind</span> <code class=\"expr\">`{}` = {}</code></div>",
escape(name),
escape(&expr_display(value))
),
Stmt::Return { value, .. } => format!(
"<div class=\"card ret-card\"><span class=\"badge\">return</span><code class=\"expr\">{}</code></div>",
escape(&expr_display(value))
@@ -388,9 +518,67 @@ fn expr_prec(expr: &Expr, parent_prec: u8) -> String {
let parts: Vec<String> = items.iter().map(|e| expr_prec(e, 0)).collect();
format!("[{}]", parts.join(", "))
}
Expr::Formula(e) => format!("$$ {} $$", e.as_display()),
}
}
/// Best-effort ASCII formula → TeX for KaTeX in view Structure.
fn formula_ascii_to_tex(ascii: &str) -> String {
let mut out = String::new();
let chars: Vec<char> = ascii.chars().collect();
let mut i = 0usize;
while i < chars.len() {
let c = chars[i];
if c == '*' {
// multiplication: a*b → a \cdot b
out.push_str(r" \cdot ");
i += 1;
continue;
}
if c == '^' {
out.push('^');
i += 1;
if i < chars.len() && chars[i] == '(' {
out.push('{');
i += 1;
let start = i;
let mut depth = 1i32;
while i < chars.len() && depth > 0 {
match chars[i] {
'(' => depth += 1,
')' => depth -= 1,
_ => {}
}
if depth > 0 {
i += 1;
}
}
out.push_str(&chars[start..i].iter().collect::<String>());
if i < chars.len() && chars[i] == ')' {
i += 1;
}
out.push('}');
} else if i < chars.len() {
out.push('{');
out.push(chars[i]);
out.push('}');
i += 1;
}
continue;
}
// TeX specials that may appear in identifiers rarely
match c {
'{' | '}' | '%' | '&' | '#' | '$' => {
out.push('\\');
out.push(c);
}
_ => out.push(c),
}
i += 1;
}
out
}
fn wrap(inner: String, prec: u8, parent_prec: u8) -> String {
if prec < parent_prec {
format!("({inner})")
@@ -476,4 +664,53 @@ mod tests {
assert!(html.contains("<code>code</code>"), "{html}");
assert!(!html.contains("[仓库](https://github.com/cflmy/marqdo)"));
}
#[test]
fn collect_input_prompts_from_fixture() {
let src = include_str!("../../tests/keywords/input.mq.md");
let module = crate::parse::parse_source(src).unwrap();
let prompts = collect_input_prompts(&module);
assert_eq!(prompts, vec!["Name:".to_string()]);
}
#[test]
fn collect_input_prompts_absent_without_input() {
let src = include_str!("../../tests/structure/hello.mq.md");
let module = crate::parse::parse_source(src).unwrap();
assert!(collect_input_prompts(&module).is_empty());
}
#[test]
fn structure_omits_imported_lib_bodies() {
let src = "---\ntitle: t\n> lib/text.mq.md\n---\n\n# main\n\n> print text=hi\n";
let local = crate::parse::parse_source(src).unwrap();
let html = render_module_structure(&local, src);
assert!(html.contains("badge\">import"), "{html}");
assert!(html.contains("lib/text.mq.md"), "{html}");
assert!(html.contains("main"), "{html}");
assert!(!html.contains("trim"), "{html}");
assert_eq!(local.functions.len(), 1);
assert_eq!(local.functions[0].name, "main");
}
#[test]
fn structure_formula_assign_not_comment() {
let src = include_str!("../../tests/lib/math-formula.mq.md");
let module = crate::parse::parse_source(src).unwrap();
let html = render_module_structure(&module, src);
assert!(html.contains("badge\">formula"), "{html}");
assert!(html.contains("math-block"), "{html}");
assert!(html.contains("$$"), "{html}");
assert!(
!html.contains("comment-text\">x^2 - 2")
&& !html.contains("comment-text\"><p>x^2 - 2"),
"formula fence leaked into comments: {html}"
);
}
#[test]
fn formula_ascii_to_tex_pow_and_mul() {
assert_eq!(formula_ascii_to_tex("x^2 - 2"), "x^{2} - 2");
assert_eq!(formula_ascii_to_tex("2*x"), r"2 \cdot x");
}
}