Freeze savebox metrics and expand wd/ht/dp

\sbox/\savebox now measure their content at definition with the Roman metrics
at the class base size and store width/height/depth. \usebox carries that size
into the no-break segment, which scales the box back to its definition size
inside a differently sized paragraph, and \wd/\ht/\dp\boxname expand to the
frozen metrics before paragraph parsing.

\mbox/\hbox/\makebox keep following the surrounding size (their marker carries
size 0). A core test checks that a box frozen at 20pt is twice as wide as the
10pt one, and a route-D test checks the measured dimensions and a
\hspace{\wd\box} expansion. Image-only boxes still measure as empty text.

Three savebox tests strip the internal markers (now with their size prefix)
before comparing visible text.
This commit is contained in:
gloamxun committed 2026-10-26 23:48:42 +08:00
1 parent 95a6a1291a
commit 5a1a04d029
4 files changed
+251 -26

No files matched your search

+91 -3
View File
@@ -58,7 +58,9 @@ pub enum InlineSegment {
Math(crate::math::MathAtom),
/// Material that never breaks internally, like an `\mbox` or a measured
/// savebox: interword spaces become fixed-width boxes instead of glue.
NoBreak(ParagraphFont, String),
/// A positive size freezes the box at the size it was measured at; zero
/// follows the surrounding paragraph size.
NoBreak(ParagraphFont, i64, String),
Link {
font: ParagraphFont,
url: String,
@@ -580,6 +582,43 @@ fn scale_font_size(value: i64, size: i64) -> i64 {
value.saturating_mul(size) / BASE_FONT_SIZE
}
/// Scale a shaped run by an arbitrary rational factor (used to freeze a
/// savebox measured at another base size).
fn scale_items_ratio(items: &mut [HorizontalItem], numerator: i64, denominator: i64) {
if numerator == denominator || denominator == 0 {
return;
}
let scale = |value: i64| value.saturating_mul(numerator) / denominator;
for item in items {
match item {
HorizontalItem::Box(box_) => {
box_.width = scale(box_.width);
box_.height = scale(box_.height);
box_.depth = scale(box_.depth);
box_.italic = scale(box_.italic);
}
HorizontalItem::Glue {
width,
stretch,
shrink,
..
} => {
*width = scale(*width);
*stretch = scale(*stretch);
*shrink = scale(*shrink);
}
HorizontalItem::Penalty { width, .. } => *width = scale(*width),
HorizontalItem::Discretionary {
pre_break_width,
no_break_width,
} => {
*pre_break_width = scale(*pre_break_width);
*no_break_width = scale(*no_break_width);
}
}
}
}
/// Scale every glyph and glue in a shaped item stream for the paragraph's
/// base font size. Scaling after shaping is linear, so it matches shaping with
/// scaled TFM metrics.
@@ -1877,7 +1916,7 @@ pub fn layout_paragraph_segments(segments: &[InlineSegment], style: &ParagraphSt
previous = Some((*font, text.clone()));
seen_content = true;
}
InlineSegment::NoBreak(font, text) => {
InlineSegment::NoBreak(font, block_size, text) => {
if text.is_empty() {
continue;
}
@@ -1904,11 +1943,20 @@ pub fn layout_paragraph_segments(segments: &[InlineSegment], style: &ParagraphSt
});
}
let metrics = crate::cmr10::Cmr10Metrics::for_paragraph_font(*font);
let freeze_ratio = if *block_size > 0 && *block_size != style.font_size {
Some((*block_size, style.font_size.max(1)))
} else {
None
};
let space_width = match freeze_ratio {
Some((numerator, denominator)) => metrics.space() * numerator / denominator,
None => metrics.space(),
};
let mut first_word = true;
for word in text.split_whitespace() {
if !first_word {
items.push(HorizontalItem::Box(HorizontalBox {
width: metrics.space(),
width: space_width,
height: 0,
depth: 0,
character: None,
@@ -1926,6 +1974,9 @@ pub fn layout_paragraph_segments(segments: &[InlineSegment], style: &ParagraphSt
first_word = false;
let mut run = text_items_with_font(word, style, &metrics);
run.retain(|item| matches!(item, HorizontalItem::Box(_)));
if let Some((numerator, denominator)) = freeze_ratio {
scale_items_ratio(&mut run, numerator, denominator);
}
for item in &mut run {
if let HorizontalItem::Box(box_) = item {
box_.font = Some(*font);
@@ -2396,6 +2447,7 @@ mod tests {
};
let segments = vec![InlineSegment::NoBreak(
ParagraphFont::Roman,
0,
"alpha beta gamma".to_string(),
)];
let paragraph = layout_paragraph_segments(&segments, &style);
@@ -2417,6 +2469,42 @@ mod tests {
assert_eq!(characters, "alphabetagamma");
}
#[test]
fn frozen_no_break_box_keeps_its_definition_size() {
let style = ParagraphStyle {
line_width: 200 * 65_536,
..ParagraphStyle::default()
};
let width = |paragraph: &Paragraph| -> i64 {
paragraph.lines[0]
.iter()
.map(|item| match item {
HorizontalItem::Box(box_) => box_.width,
HorizontalItem::Glue { width, .. } => *width,
_ => 0,
})
.sum()
};
let normal = layout_paragraph_segments(
&[InlineSegment::NoBreak(
ParagraphFont::Roman,
0,
"ab".to_string(),
)],
&style,
);
let frozen = layout_paragraph_segments(
&[InlineSegment::NoBreak(
ParagraphFont::Roman,
2 * 655_360,
"ab".to_string(),
)],
&style,
);
let ratio = width(&frozen) as f64 / width(&normal) as f64;
assert!((ratio - 2.0).abs() < 0.05, "frozen ratio {ratio}");
}
#[test]
fn sized_segments_keep_their_own_glyph_size() {
let style = ParagraphStyle {
+1 -1
View File
@@ -48,7 +48,7 @@ floats (`\floatsep`, `\textfloatsep`, `\intextsep`, `\topfraction`,
`\bottomnumber`, `\totalnumber`), insertion classes (`\skip`, fraction and
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
PDF opt-in with `?engine=route-d`). 982 workspace tests are green and no oracle
PDF opt-in with `?engine=route-d`). 984 workspace tests are green and no oracle
fixture is ignored. Preview JSON also carries a `warnings` array naming
environments route-D cannot lay out and control words that survived layout, so
unsupported source is reported instead of being silently typeset.
+6 -4
View File
@@ -370,7 +370,7 @@ Math coverage includes fractions/roots, scripts, `\left...\right` with body-scal
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 435 unit tests plus ten route-D integration tests and forty-two oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 982 tests (435 route-D unit, 359 engine binary unit, 10 route-D integration, 42 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 436 unit tests plus ten route-D integration tests and forty-two oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 984 tests (436 route-D unit, 360 engine binary unit, 10 route-D integration, 42 oracle, 71 v1 integration, 60 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path.
### M0 incremental demo
@@ -531,9 +531,11 @@ honest open items against the "feature-complete LaTeX compiler" objective are:
that relies on those semantics still degrades.
- **Boxes**: `\sbox`/`\savebox` content and `\mbox`/`\hbox`/`\makebox`
bodies are inserted as one unbreakable inline box (interword spaces become
fixed-width boxes), so `\usebox` no longer reflows across lines; the box is
still measured at the use site rather than frozen at definition, and
`\wd`/`\ht`/`\dp` accessors remain open.
fixed-width boxes), so `\usebox` no longer reflows across lines. Savebox
width/height/depth are measured at definition and frozen (a box keeps its
definition size inside differently sized text), and `\wd`/`\ht`/`\dp`
expand to those metrics; a box whose content is only an image still measures
as empty text.
- **Tables**: `\multirow` centres over its rows, `array` column modifiers
`>{}`/`<{}` and the outer `\tabcolsep` margins are parsed; nested tables and
`\valign` remain unmodelled.
+153 -18
View File
@@ -227,6 +227,8 @@ struct PageGeometry {
footer_right: Option<String>,
/// `\renewcommand{\headrulewidth}{0.4pt}`.
head_rule_width: Option<i64>,
/// Frozen `\sbox`/`\savebox` metrics: name -> (width, height, depth), sp.
savebox_dimensions: Vec<(String, (i64, i64, i64))>,
head_sep: Option<i64>,
head_height: Option<i64>,
foot_skip: Option<i64>,
@@ -2241,7 +2243,13 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
|| trimmed.starts_with("\\sbox")
|| trimmed.starts_with("\\savebox")
{
handle_savebox_line(trimmed, &mut geometry.macros);
let base = geometry.base_font_size.unwrap_or(655_360);
handle_savebox_line(
trimmed,
&mut geometry.macros,
&mut geometry.savebox_dimensions,
base,
);
continue;
}
if let Some(rest) = trimmed.strip_prefix("\\newcount") {
@@ -4248,7 +4256,28 @@ fn dedupe_macros(macros: &mut Vec<MacroDefinition>) {
}
/// Replace `\usebox{name}` with stored content and store `\sbox`/`\savebox` bodies.
fn expand_saveboxes(body: &str, macros: &mut Vec<MacroDefinition>) -> String {
/// Replace `\wd`/`\ht`/`\dp\boxname` with the frozen savebox metrics.
fn expand_box_dimensions(body: &str, dimensions: &[(String, (i64, i64, i64))]) -> String {
let mut out = body.to_string();
let mut ordered = dimensions.to_vec();
ordered.sort_by_key(|(name, _)| std::cmp::Reverse(name.len()));
for (name, (width, height, depth)) in ordered {
for (command, value) in [("\\wd", width), ("\\ht", height), ("\\dp", depth)] {
let needle = format!("{command}{name}");
if out.contains(&needle) {
out = out.replace(&needle, &format!("{:.4}pt", value as f64 / 65536.0));
}
}
}
out
}
fn expand_saveboxes(
body: &str,
macros: &mut Vec<MacroDefinition>,
dimensions: &mut Vec<(String, (i64, i64, i64))>,
base_size: i64,
) -> String {
let mut out = String::new();
let mut index = 0;
while index < body.len() {
@@ -4259,6 +4288,8 @@ fn expand_saveboxes(body: &str, macros: &mut Vec<MacroDefinition>) -> String {
let name = format!("\\{}", name.trim().trim_start_matches('\\'));
if let Some(definition) = macros.iter().find(|m| m.name == name) {
out.push('\u{E010}');
out.push_str(&base_size.to_string());
out.push(';');
out.push_str(&definition.body);
out.push('\u{E011}');
}
@@ -4281,13 +4312,14 @@ fn expand_saveboxes(body: &str, macros: &mut Vec<MacroDefinition>) -> String {
existing.params = None;
} else {
macros.push(MacroDefinition {
name,
name: name.clone(),
args: 0,
default: None,
params: None,
body: content.to_string(),
});
}
set_savebox_dimensions(dimensions, &name, measure_savebox(content, base_size));
index += rest.len() - body_rest.len() + used_body;
continue;
}
@@ -4301,7 +4333,12 @@ fn expand_saveboxes(body: &str, macros: &mut Vec<MacroDefinition>) -> String {
}
/// Register the content of a `\sbox`/`\savebox` or reserve a `\newsavebox` name.
fn handle_savebox_line(line: &str, macros: &mut Vec<MacroDefinition>) {
fn handle_savebox_line(
line: &str,
macros: &mut Vec<MacroDefinition>,
dimensions: &mut Vec<(String, (i64, i64, i64))>,
base_size: i64,
) {
let rest = line.trim_start();
if let Some(after) = rest.strip_prefix("\\newsavebox") {
let after = after.trim_start();
@@ -4337,13 +4374,38 @@ fn handle_savebox_line(line: &str, macros: &mut Vec<MacroDefinition>) {
existing.params = None;
} else {
macros.push(MacroDefinition {
name,
name: name.clone(),
args: 0,
default: None,
params: None,
body: body.to_string(),
});
}
set_savebox_dimensions(dimensions, &name, measure_savebox(body, base_size));
}
fn set_savebox_dimensions(
dimensions: &mut Vec<(String, (i64, i64, i64))>,
name: &str,
metrics: (i64, i64, i64),
) {
if let Some(existing) = dimensions.iter_mut().find(|(known, _)| known == name) {
existing.1 = metrics;
} else {
dimensions.push((name.to_string(), metrics));
}
}
/// Measure a savebox body with the Roman metrics at `base_size`.
fn measure_savebox(content: &str, base_size: i64) -> (i64, i64, i64) {
let cleaned = scrub_title_metadata(&strip_box_commands(content));
let metrics = Cmr10Metrics::Roman;
let scale = |value: i64| value.saturating_mul(base_size) / 655_360;
(
scale(text_width_roman(&cleaned)),
scale(metrics.height('M').max(1)),
scale(metrics.depth('g').max(0)),
)
}
/// Capture `\def` lines written in the document body, before macro expansion.
@@ -4421,7 +4483,10 @@ fn capture_body_definitions(
continue;
}
if trimmed.starts_with("\\newsavebox") {
handle_savebox_line(trimmed, macros);
// Only the name is reserved here; the body's \sbox is measured by
// expand_saveboxes once the geometry is available.
let mut ignored_dimensions = Vec::new();
handle_savebox_line(trimmed, macros, &mut ignored_dimensions, 655_360);
changed = true;
continue;
}
@@ -4670,7 +4735,14 @@ fn geometry_and_body(source: &str) -> (String, PageGeometry) {
body = expand_environments(&body, &geometry.environments);
body = expand_keywords(&body);
body = drop_bibliography_commands(&body);
body = expand_saveboxes(&body, &mut geometry.macros);
let savebox_base = geometry.base_font_size.unwrap_or(655_360);
body = expand_saveboxes(
&body,
&mut geometry.macros,
&mut geometry.savebox_dimensions,
savebox_base,
);
body = expand_box_dimensions(&body, &geometry.savebox_dimensions);
dedupe_macros(&mut geometry.macros);
let macros = geometry.macros.clone();
body = expand_conditionals(
@@ -8090,6 +8162,7 @@ fn strip_box_commands(text: &str) -> String {
return out;
};
out.push('\u{E010}');
out.push_str("0;");
out.push_str(&strip_box_commands(&stripped[..close]));
out.push('\u{E011}');
after = &stripped[close + 1..];
@@ -8122,6 +8195,7 @@ fn strip_box_commands(text: &str) -> String {
out.push_str(&strip_box_commands(&after[..end]));
} else {
out.push('\u{E010}');
out.push_str("0;");
out.push_str(&strip_box_commands(&after[..end]));
out.push('\u{E011}');
}
@@ -8277,24 +8351,31 @@ fn expand_ensuremath(text: &str) -> String {
/// Split text at the private-use markers that wrap `\mbox`/`\usebox`
/// material: `true` means a no-break region, `false` plain text.
fn split_no_break(text: &str) -> Vec<(bool, String)> {
fn split_no_break(text: &str) -> Vec<(bool, i64, String)> {
let mut chunks = Vec::new();
let mut rest = text;
while let Some(open) = rest.find('\u{E010}') {
if open > 0 {
chunks.push((false, rest[..open].to_string()));
chunks.push((false, 0, rest[..open].to_string()));
}
let after = &rest[open + '\u{E010}'.len_utf8()..];
if let Some(close) = after.find('\u{E011}') {
chunks.push((true, after[..close].to_string()));
let inner = &after[..close];
let (size, content) = match inner.split_once(';') {
Some((digits, content)) => {
(digits.parse::<i64>().unwrap_or(0), content.to_string())
}
None => (0, inner.to_string()),
};
chunks.push((true, size, content));
rest = &after[close + '\u{E011}'.len_utf8()..];
} else {
chunks.push((false, after.to_string()));
chunks.push((false, 0, after.to_string()));
return chunks;
}
}
if !rest.is_empty() {
chunks.push((false, rest.to_string()));
chunks.push((false, 0, rest.to_string()));
}
chunks
}
@@ -8311,7 +8392,7 @@ fn inline_segments_with_boxes(
return inline_math_segments(text, base, style, custom, link_color);
}
let mut segments = Vec::new();
for (is_box, piece) in split_no_break(text) {
for (is_box, size, piece) in split_no_break(text) {
if piece.trim().is_empty() {
continue;
}
@@ -8319,7 +8400,7 @@ fn inline_segments_with_boxes(
if is_box {
let runs = inline_runs(&plain, base).unwrap_or_else(|| vec![(base, plain.clone())]);
for (font, run) in runs {
segments.push(InlineSegment::NoBreak(font, run));
segments.push(InlineSegment::NoBreak(font, size, run));
}
} else if let Some(found) = inline_math_segments(&plain, base, style, custom, link_color) {
segments.extend(found);
@@ -11408,9 +11489,28 @@ fn escape_json(value: &str) -> String {
mod tests {
use super::*;
/// Drop the internal no-break markers that `\usebox`/`\mbox` insert.
/// Drop the internal no-break markers (and their size prefix) that
/// `\usebox`/`\mbox` insert.
fn visible(text: &str) -> String {
text.replace(['\u{E010}', '\u{E011}'], "")
let mut out = String::new();
let mut rest = text;
while let Some(open) = rest.find('\u{E010}') {
out.push_str(&rest[..open]);
let after = &rest[open + '\u{E010}'.len_utf8()..];
let content = match after.find(';') {
Some(semi) if after[..semi].chars().all(|c| c.is_ascii_digit()) => {
&after[semi + 1..]
}
_ => after,
};
let close = content.find('\u{E011}').unwrap_or(content.len());
out.push_str(&content[..close]);
rest = content[close..]
.strip_prefix('\u{E011}')
.unwrap_or(&content[close..]);
}
out.push_str(rest);
out
}
#[test]
@@ -11741,9 +11841,28 @@ mod tests {
mod source_tests {
use super::*;
/// Drop the internal no-break markers that `\usebox`/`\mbox` insert.
/// Drop the internal no-break markers (and their size prefix) that
/// `\usebox`/`\mbox` insert.
fn visible(text: &str) -> String {
text.replace(['\u{E010}', '\u{E011}'], "")
let mut out = String::new();
let mut rest = text;
while let Some(open) = rest.find('\u{E010}') {
out.push_str(&rest[..open]);
let after = &rest[open + '\u{E010}'.len_utf8()..];
let content = match after.find(';') {
Some(semi) if after[..semi].chars().all(|c| c.is_ascii_digit()) => {
&after[semi + 1..]
}
_ => after,
};
let close = content.find('\u{E011}').unwrap_or(content.len());
out.push_str(&content[..close]);
rest = content[close..]
.strip_prefix('\u{E011}')
.unwrap_or(&content[close..]);
}
out.push_str(rest);
out
}
#[test]
@@ -14345,6 +14464,22 @@ A definition.
assert_eq!(document.widow_penalty, 88);
}
#[test]
fn savebox_dimensions_are_frozen_and_readable() {
let source = "\\newsavebox{\\b}\n\\sbox{\\b}{abc}\n\nX\\hspace{\\wd\\b}Y";
let (body, geometry) = geometry_and_body(source);
let (_, (width, height, depth)) = geometry
.savebox_dimensions
.iter()
.find(|(name, _)| name == "\\b")
.expect("savebox dimensions");
assert!(*width > 0, "width {width}");
assert!(*height > 0, "height {height}");
assert!(*depth >= 0, "depth {depth}");
assert!(!body.contains("\\wd"), "{body}");
assert!(body.contains("pt"), "dimension not expanded: {body}");
}
#[test]
fn mbox_and_usebox_stay_on_one_line() {
let measure = |source: &str| {