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:
1 parent
56faec6046
commit
95a6a1291a
4 files changed
+213
-13
No files matched your search
@@ -56,6 +56,9 @@ pub enum InlineSegment {
|
||||
String,
|
||||
),
|
||||
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),
|
||||
Link {
|
||||
font: ParagraphFont,
|
||||
url: String,
|
||||
@@ -1874,6 +1877,65 @@ pub fn layout_paragraph_segments(segments: &[InlineSegment], style: &ParagraphSt
|
||||
previous = Some((*font, text.clone()));
|
||||
seen_content = true;
|
||||
}
|
||||
InlineSegment::NoBreak(font, text) => {
|
||||
if text.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let starts_with_space = text.chars().next().is_some_and(char::is_whitespace);
|
||||
let boundary_space = match &previous {
|
||||
Some((_previous_font, previous_text)) => {
|
||||
previous_text
|
||||
.chars()
|
||||
.next_back()
|
||||
.is_some_and(char::is_whitespace)
|
||||
|| starts_with_space
|
||||
}
|
||||
None => seen_content && starts_with_space,
|
||||
};
|
||||
if boundary_space {
|
||||
let metrics = crate::cmr10::Cmr10Metrics::for_paragraph_font(
|
||||
previous.as_ref().map_or(*font, |(font, _)| *font),
|
||||
);
|
||||
items.push(HorizontalItem::Glue {
|
||||
width: metrics.space(),
|
||||
stretch: metrics.stretch(),
|
||||
shrink: metrics.shrink(),
|
||||
order: 0,
|
||||
});
|
||||
}
|
||||
let metrics = crate::cmr10::Cmr10Metrics::for_paragraph_font(*font);
|
||||
let mut first_word = true;
|
||||
for word in text.split_whitespace() {
|
||||
if !first_word {
|
||||
items.push(HorizontalItem::Box(HorizontalBox {
|
||||
width: metrics.space(),
|
||||
height: 0,
|
||||
depth: 0,
|
||||
character: None,
|
||||
italic: 0,
|
||||
font: Some(*font),
|
||||
math: None,
|
||||
raise: 0,
|
||||
color: None,
|
||||
background: None,
|
||||
frame: None,
|
||||
size: None,
|
||||
link: None,
|
||||
}));
|
||||
}
|
||||
first_word = false;
|
||||
let mut run = text_items_with_font(word, style, &metrics);
|
||||
run.retain(|item| matches!(item, HorizontalItem::Box(_)));
|
||||
for item in &mut run {
|
||||
if let HorizontalItem::Box(box_) = item {
|
||||
box_.font = Some(*font);
|
||||
}
|
||||
}
|
||||
items.extend(run);
|
||||
}
|
||||
previous = Some((*font, text.clone()));
|
||||
seen_content = true;
|
||||
}
|
||||
InlineSegment::Link {
|
||||
font,
|
||||
url,
|
||||
@@ -2326,6 +2388,35 @@ mod tests {
|
||||
assert!(elapsed < std::time::Duration::from_secs(10), "{elapsed:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_break_segments_replace_spaces_with_fixed_boxes() {
|
||||
let style = ParagraphStyle {
|
||||
line_width: 40 * 65_536,
|
||||
..ParagraphStyle::default()
|
||||
};
|
||||
let segments = vec![InlineSegment::NoBreak(
|
||||
ParagraphFont::Roman,
|
||||
"alpha beta gamma".to_string(),
|
||||
)];
|
||||
let paragraph = layout_paragraph_segments(&segments, &style);
|
||||
assert_eq!(paragraph.lines.len(), 1, "the box must not wrap");
|
||||
let line = ¶graph.lines[0];
|
||||
assert!(
|
||||
!line
|
||||
.iter()
|
||||
.any(|item| matches!(item, HorizontalItem::Glue { .. })),
|
||||
"spaces inside a no-break box must be fixed boxes"
|
||||
);
|
||||
let characters: String = line
|
||||
.iter()
|
||||
.filter_map(|item| match item {
|
||||
HorizontalItem::Box(box_) => box_.character,
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(characters, "alphabetagamma");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sized_segments_keep_their_own_glyph_size() {
|
||||
let style = ParagraphStyle {
|
||||
|
||||
@@ -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`). 980 workspace tests are green and no oracle
|
||||
PDF opt-in with `?engine=route-d`). 982 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.
|
||||
|
||||
+9
-7
@@ -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 434 unit tests plus ten route-D integration tests and forty-two oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 980 tests (434 route-D unit, 358 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 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.
|
||||
|
||||
### M0 incremental demo
|
||||
|
||||
@@ -529,12 +529,14 @@ honest open items against the "feature-complete LaTeX compiler" objective are:
|
||||
textually, but there is no real group scoping, no catcode state (the `@`
|
||||
letter assumption is unconditional), and no token stream. Class/package code
|
||||
that relies on those semantics still degrades.
|
||||
- **Boxes**: `\sbox`/`\savebox` store text, not a measured box; `\usebox`
|
||||
re-flows content at the new location, and savebox width/height are not
|
||||
frozen.
|
||||
- **Tables**: `\multirow` keeps its text on the first row (no vertical
|
||||
centring), `array` column modifiers `>{}`/`<{}` are ignored, nested tables
|
||||
and the outer tabcolsep margins are unmodelled.
|
||||
- **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.
|
||||
- **Tables**: `\multirow` centres over its rows, `array` column modifiers
|
||||
`>{}`/`<{}` and the outer `\tabcolsep` margins are parsed; nested tables and
|
||||
`\valign` remain unmodelled.
|
||||
- **Fonts**: the twelve Computer Modern faces and four math faces are embedded
|
||||
as Type1 with per-glyph Liberation fallback; arbitrary NFSS families,
|
||||
font subsetting and broad Unicode coverage (including more than the current
|
||||
|
||||
+112
-5
@@ -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]
|
||||
|
||||
Reference in new issue
Block a user