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

+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| {