Keep mbox and savebox content on one line

Add InlineSegment::NoBreak: it shapes each word and replaces the interword
glue with fixed-width boxes, so the run has no breakpoints and behaves like
TeX's unbreakable hbox rather than reflowing at the use site.

Route-D wraps \usebox bodies and \mbox/\hbox/\makebox arguments in private-use
markers; the paragraph text builder splits on them and emits NoBreak runs,
leaving ordinary text and styling on the existing path. \underline keeps its
old inline behaviour.

A 60pt measure now keeps \mbox{alpha beta gamma} and a stored
\sbox{alpha beta gamma} on one line, covered by a core segment test and a
route-D test. Savebox dimensions are still measured at the use site instead of
being frozen at definition, and \wd/\ht/\dp accessors remain open.
This commit is contained in:
gloamxun committed 2026-10-26 23:43:53 +08:00
1 parent 56faec6046
commit 95a6a1291a
4 files changed
+213 -13

No files matched your search

+112 -5
View File
@@ -4258,7 +4258,9 @@ fn expand_saveboxes(body: &str, macros: &mut Vec<MacroDefinition>) -> String {
if let Some((name, used)) = braced_group(after) {
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(&definition.body);
out.push('\u{E011}');
}
index += rest.len() - after.len() + used;
continue;
@@ -8087,7 +8089,9 @@ fn strip_box_commands(text: &str) -> String {
out.push_str(&rest[index..]);
return out;
};
out.push('\u{E010}');
out.push_str(&strip_box_commands(&stripped[..close]));
out.push('\u{E011}');
after = &stripped[close + 1..];
rest = after;
continue;
@@ -8114,7 +8118,13 @@ fn strip_box_commands(text: &str) -> String {
out.push_str(&rest[index..]);
return out;
};
out.push_str(&strip_box_commands(&after[..end]));
if command == "\\underline{" {
out.push_str(&strip_box_commands(&after[..end]));
} else {
out.push('\u{E010}');
out.push_str(&strip_box_commands(&after[..end]));
out.push('\u{E011}');
}
rest = &after[end + 1..];
}
}
@@ -8265,6 +8275,64 @@ fn expand_ensuremath(text: &str) -> String {
out
}
/// 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)> {
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()));
}
let after = &rest[open + '\u{E010}'.len_utf8()..];
if let Some(close) = after.find('\u{E011}') {
chunks.push((true, after[..close].to_string()));
rest = &after[close + '\u{E011}'.len_utf8()..];
} else {
chunks.push((false, after.to_string()));
return chunks;
}
}
if !rest.is_empty() {
chunks.push((false, rest.to_string()));
}
chunks
}
fn inline_segments_with_boxes(
text: &str,
base: ParagraphFont,
style: &ParagraphStyle,
custom: &[(String, [u8; 3])],
link_color: Option<[u8; 3]>,
) -> Option<Vec<texrra_tex_core::paragraph::InlineSegment>> {
use texrra_tex_core::paragraph::InlineSegment;
if !text.contains('\u{E010}') {
return inline_math_segments(text, base, style, custom, link_color);
}
let mut segments = Vec::new();
for (is_box, piece) in split_no_break(text) {
if piece.trim().is_empty() {
continue;
}
let plain = piece.replace('~', " ");
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));
}
} else if let Some(found) = inline_math_segments(&plain, base, style, custom, link_color) {
segments.extend(found);
} else {
let runs = inline_runs(&plain, base).unwrap_or_else(|| vec![(base, plain.clone())]);
for (font, run) in runs {
segments.push(InlineSegment::Text(font, run));
}
}
}
(!segments.is_empty()).then_some(segments)
}
fn inline_math_segments(
text: &str,
base: ParagraphFont,
@@ -10600,7 +10668,7 @@ fn build_document_with_labels(
xspace_skip: geometry.xspace_skip,
};
let plain = strip_hrefs(&text).replace('~', " ");
let mut unit = match inline_math_segments(
let mut unit = match inline_segments_with_boxes(
&text,
paragraph.font,
&style,
@@ -11340,6 +11408,11 @@ fn escape_json(value: &str) -> String {
mod tests {
use super::*;
/// Drop the internal no-break markers that `\usebox`/`\mbox` insert.
fn visible(text: &str) -> String {
text.replace(['\u{E010}', '\u{E011}'], "")
}
#[test]
fn display_math_is_split_to_the_measure() {
let mut formula = String::from("$$");
@@ -11668,6 +11741,11 @@ mod tests {
mod source_tests {
use super::*;
/// Drop the internal no-break markers that `\usebox`/`\mbox` insert.
fn visible(text: &str) -> String {
text.replace(['\u{E010}', '\u{E011}'], "")
}
#[test]
fn footnotes_become_page_insertions() {
let blocks = paragraphs("Body\\footnote{Note} tail").unwrap();
@@ -13652,7 +13730,7 @@ See \ref{fig:a} and \ref{tab:b}.";
fn body_newsavebox_declarations_are_reserved() {
let source = "\\newsavebox{\\boxa}\n\\sbox{\\boxa}{Stored}\n\nFirst \\usebox{\\boxa}.";
let (body, _geometry) = geometry_and_body(source);
assert_eq!(body.trim(), "First Stored.");
assert_eq!(visible(body.trim()), "First Stored.");
}
#[test]
@@ -14267,6 +14345,35 @@ A definition.
assert_eq!(document.widow_penalty, 88);
}
#[test]
fn mbox_and_usebox_stay_on_one_line() {
let measure = |source: &str| {
let (body, mut geometry) = geometry_and_body(source);
geometry.line_width = Some(60 * SCALE);
let blocks = paragraphs(&body).expect("paragraphs");
let document = build_document(&blocks, &geometry);
let paragraph = document.units[0]
.items
.iter()
.find_map(|item| match item {
VerticalItem::Paragraph(paragraph) => Some(paragraph),
_ => None,
})
.expect("paragraph");
paragraph.lines.len()
};
assert_eq!(
measure("\\mbox{alpha beta gamma}"),
1,
"mbox must not break"
);
assert_eq!(
measure("\\newsavebox{\\b}\n\\sbox{\\b}{alpha beta gamma}\n\n\\usebox{\\b}"),
1,
"usebox content must not break"
);
}
#[test]
fn inline_colours_and_links_work_at_twelve_point() {
let source = "\\documentclass[12pt]{article}\n\\begin{document}\n\nA \\textcolor{red}{red word} and a \\href{https://example.com}{link} and x\\textsuperscript{2}.\n\n\\end{document}\n";
@@ -15337,7 +15444,7 @@ A definition.
let (body, geometry) = geometry_and_body(source);
assert_eq!(geometry.macros.len(), 1);
let blocks = paragraphs(&body).expect("paragraphs");
assert_eq!(blocks[0].text, "First Stored.");
assert_eq!(visible(&blocks[0].text), "First Stored.");
}
#[test]
@@ -15348,7 +15455,7 @@ A definition.
let (body, _geometry) =
geometry_and_body("\\sbox{\\boxb}{In body}\n\nSee \\usebox{\\boxb}.");
let blocks = paragraphs(&body).expect("paragraphs");
assert_eq!(blocks[0].text, "See In body.");
assert_eq!(visible(&blocks[0].text), "See In body.");
}
#[test]