Lay out ensuremath bodies as math

This commit is contained in:
gloamxun committed 2026-10-26 04:14:38 +08:00
1 parent 0340878909
commit 0c8228eced
4 files changed
+87 -3

No files matched your search

+14
View File
@@ -2186,6 +2186,10 @@ fn parse_atom(chars: &[char], index: usize) -> (MathAtom, usize) {
end, end,
) )
} }
"ensuremath" => match read_braced_text(chars, next) {
Some((inner, after)) => (parse_math(&inner), after),
None => (MathAtom::Symbol('?'), next),
},
"operatorname" => { "operatorname" => {
let mut after = next; let mut after = next;
while chars.get(after) == Some(&'\u{0}') while chars.get(after) == Some(&'\u{0}')
@@ -3217,6 +3221,16 @@ mod tests {
let limited = layout_math(&parse_math(r"\mathop{argmax}_{x}"), &font); let limited = layout_math(&parse_math(r"\mathop{argmax}_{x}"), &font);
assert!(limited.depth > plain.depth); assert!(limited.depth > plain.depth);
} }
#[test]
fn ensuremath_inside_math_is_transparent() {
let font = Cmr10Metrics::Roman;
let with = layout_math(&parse_math("\\ensuremath{a+b}"), &font);
let plain = layout_math(&parse_math("a+b"), &font);
assert_eq!(with.width, plain.width);
assert_eq!(with.height, plain.height);
assert_eq!(with.depth, plain.depth);
}
#[test] #[test]
fn operator_names_are_upright_and_stack_when_starred() { fn operator_names_are_upright_and_stack_when_starred() {
let font = Cmr10Metrics::default(); let font = Cmr10Metrics::default();
+1 -1
View File
@@ -48,7 +48,7 @@ floats (`\floatsep`, `\textfloatsep`, `\intextsep`, `\topfraction`,
`\bottomnumber`, `\totalnumber`), insertion classes (`\skip`, fraction and `\bottomnumber`, `\totalnumber`), insertion classes (`\skip`, fraction and
absolute limits, splitting), marks, Rust output hook, multi-page PDF, and the absolute limits, splitting), marks, Rust output hook, multi-page PDF, and the
route-D service endpoints (`/api/route-d/preview|pdf|edit`, project preview and route-D service endpoints (`/api/route-d/preview|pdf|edit`, project preview and
PDF opt-in with `?engine=route-d`). 909 workspace tests are green and no oracle PDF opt-in with `?engine=route-d`). 911 workspace tests are green and no oracle
fixture is ignored. Preview JSON also carries a `warnings` array naming fixture is ignored. Preview JSON also carries a `warnings` array naming
environments route-D cannot lay out and control words that survived layout, so environments route-D cannot lay out and control words that survived layout, so
unsupported source is reported instead of being silently typeset. unsupported source is reported instead of being silently typeset.
+2 -2
View File
@@ -363,11 +363,11 @@ PDF agree. `Document::paper_width` and `paper_height` (TeX `\paperwidth`/`\paper
M3 (partial): `Unit::halign` normalizes column widths, intercolumn gaps, row heights and cell text widths to scaled points; the painter uses 10pt glyphs in 12pt rows. Rules and spans are painted; tall tables split at row boundaries (`Halign::split_for_height`) with column widths preserved. M3 (partial): `Unit::halign` normalizes column widths, intercolumn gaps, row heights and cell text widths to scaled points; the painter uses 10pt glyphs in 12pt rows. Rules and spans are painted; tall tables split at row boundaries (`Halign::split_for_height`) with column widths preserved.
Math coverage includes fractions/roots, scripts, `\left...\right` with body-scaled delimiters, `\middle`, `\big`/`\Big`/`\bigg`/`\Bigg` and their `l`/`r` forms, control-sequence delimiters, accents (dot/check/breve/acute/grave/ring), `\text`/`\mathrm`, `\overbrace`/`\underbrace`, `\overset`/`\underset`, `\binom`, `\cancel`/`\bcancel`/`\xcancel`, `\bmod`/`\pmod`, fence symbols, `\operatorname*` and `\mathop` limits. Math coverage includes fractions/roots, scripts, `\left...\right` with body-scaled delimiters, `\middle`, `\big`/`\Big`/`\bigg`/`\Bigg` and their `l`/`r` forms, control-sequence delimiters, accents (dot/check/breve/acute/grave/ring), `\text`/`\mathrm`, `\overbrace`/`\underbrace`, `\overset`/`\underset`, `\binom`, `\cancel`/`\bcancel`/`\xcancel`, `\bmod`/`\pmod`, fence symbols, `\operatorname*` and `\mathop` limits, and `\ensuremath{...}` lays its body out as math and re-enters text otherwise.
Paragraph units carry a `ParagraphFont`; `Unit::paragraph_with_face` and `Unit::paragraph_with_style_and_face` select Roman, bold, italic, mono, or sans. The corresponding Computer Modern TFM (`cmr10`, `cmbx10`, `cmti10`, `cmbxti10`, `cmtt10`, `cmss10`, `cmssbx10`, `cmssi10`, `cmcsc10`) supplies advances, kerns, ligatures, and italic correction for layout, the display list selects the matching face, and the PDF writes Computer Modern Type1 outlines for each built-in face (`cmr10`/`cmbx10`/`cmti10`/`cmbxti10`/`cmtt10`/`cmss10`/`cmssbx10`/`cmssi10`/`cmcsc10`, plus `cmmi10` for mathematical italic letters, `cmsy10` for math symbols and `cmex10` for big operators), falling back to Liberation subsets only for characters the Type1 encodings cannot address; those fallback glyphs keep their Unicode text under PDF extraction, so accented and Greek words round-trip; Type1 faces carry a ToUnicode CMap built from the requested characters, so glyphs whose names are ambiguous in the Adobe Glyph List (capital Omega, which would otherwise extract as U+2126) keep their intended code points. `Engine::edit` preserves the face when reflowing an edited paragraph. Paragraph units carry a `ParagraphFont`; `Unit::paragraph_with_face` and `Unit::paragraph_with_style_and_face` select Roman, bold, italic, mono, or sans. The corresponding Computer Modern TFM (`cmr10`, `cmbx10`, `cmti10`, `cmbxti10`, `cmtt10`, `cmss10`, `cmssbx10`, `cmssi10`, `cmcsc10`) supplies advances, kerns, ligatures, and italic correction for layout, the display list selects the matching face, and the PDF writes Computer Modern Type1 outlines for each built-in face (`cmr10`/`cmbx10`/`cmti10`/`cmbxti10`/`cmtt10`/`cmss10`/`cmssbx10`/`cmssi10`/`cmcsc10`, plus `cmmi10` for mathematical italic letters, `cmsy10` for math symbols and `cmex10` for big operators), falling back to Liberation subsets only for characters the Type1 encodings cannot address; those fallback glyphs keep their Unicode text under PDF extraction, so accented and Greek words round-trip; Type1 faces carry a ToUnicode CMap built from the requested characters, so glyphs whose names are ambiguous in the Adobe Glyph List (capital Omega, which would otherwise extract as U+2126) keep their intended code points. `Engine::edit` preserves the face when reflowing an edited paragraph.
The crate currently has 427 unit tests plus ten route-D integration tests and thirty-eight oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 909 tests (427 route-D unit, 297 engine binary unit, 10 route-D integration, 39 oracle, 71 v1 integration, 60 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path. The crate currently has 427 unit tests plus ten route-D integration tests and thirty-eight oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 911 tests (428 route-D unit, 298 engine binary unit, 10 route-D integration, 39 oracle, 71 v1 integration, 60 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path.
### M0 incremental demo ### M0 incremental demo
+70
View File
@@ -6798,6 +6798,68 @@ fn split_color_runs(
out out
} }
fn expand_ensuremath_plain(text: &str) -> String {
let mut out = String::new();
let mut rest = text;
while let Some(index) = rest.find("\\ensuremath{") {
out.push_str(&rest[..index]);
let after_open = &rest[index + "\\ensuremath{".len()..];
let mut depth = 1_usize;
let mut end = None;
for (offset, character) in after_open.char_indices() {
match character {
'{' => depth += 1,
'}' => {
depth -= 1;
if depth == 0 {
end = Some(offset);
break;
}
}
_ => {}
}
}
let Some(end) = end else {
out.push_str(&rest[index..]);
return out;
};
out.push('$');
out.push_str(&after_open[..end]);
out.push('$');
rest = &after_open[end + 1..];
}
out.push_str(rest);
out
}
/// Expand `\\ensuremath{...}` outside math mode into an inline math run.
fn expand_ensuremath(text: &str) -> String {
let mut out = String::new();
let mut rest = text;
let mut math_mode = false;
while !rest.is_empty() {
if math_mode {
if let Some(position) = rest.find('$') {
out.push_str(&rest[..=position]);
rest = &rest[position + 1..];
math_mode = false;
} else {
out.push_str(rest);
break;
}
} else if let Some(position) = rest.find('$') {
out.push_str(&expand_ensuremath_plain(&rest[..position]));
out.push('$');
rest = &rest[position + 1..];
math_mode = true;
} else {
out.push_str(&expand_ensuremath_plain(rest));
break;
}
}
out
}
fn inline_math_segments( fn inline_math_segments(
text: &str, text: &str,
base: ParagraphFont, base: ParagraphFont,
@@ -8857,6 +8919,7 @@ fn build_document_with_labels(
.trim_start() .trim_start()
.to_string(); .to_string();
} }
text = expand_ensuremath(&text);
if let Some((color, rest)) = color_switch(&text) { if let Some((color, rest)) = color_switch(&text) {
text = format!("\\textcolor{{{color}}}{{{rest}}}"); text = format!("\\textcolor{{{color}}}{{{rest}}}");
} }
@@ -12921,6 +12984,13 @@ A definition.
assert_eq!(runs[0].3, "Boxed"); assert_eq!(runs[0].3, "Boxed");
} }
#[test]
fn ensuremath_makes_inline_math() {
let preview = preview_json("A \\ensuremath{x^2} B").expect("preview");
assert!(preview.contains("font-style=\\\"italic\\\""));
assert!(!preview.contains("ensuremath"));
}
#[test] #[test]
fn tildes_make_spaces() { fn tildes_make_spaces() {
let json = preview_json("Figure~1.").expect("preview"); let json = preview_json("Figure~1.").expect("preview");