Wrap p-column cells and keep wrapped rows splittable

This commit is contained in:
gloamxun committed 2026-10-24 00:57:09 +08:00
1 parent 4153657d0a
commit d1b93ac9be
4 files changed
+346 -63

No files matched your search

+314 -52
View File
@@ -55,6 +55,9 @@ pub struct HalignRow {
pub struct Halign {
pub rows: Vec<HalignRow>,
pub column_widths: Vec<i64>,
/// Per-column `p{width}` declarations; `Some` makes the column wrap.
#[serde(default)]
pub column_wrap: Vec<Option<i64>>,
pub width: i64,
pub height: i64,
pub line_height: i64,
@@ -97,12 +100,13 @@ impl Halign {
let mut chunks = Vec::new();
let mut start = 0_usize;
let mut height = 0_i64;
for (index, row) in self.rows.iter().enumerate() {
let row_height = if row.rule { 26_214 } else { self.line_height };
for index in 0..self.rows.len() {
let row_height = self.row_height(index);
if index > start && height + row_height > max_height {
chunks.push(Self {
rows: self.rows[start..index].to_vec(),
column_widths: self.column_widths.clone(),
column_wrap: self.column_wrap.clone(),
width: self.width,
height,
line_height: self.line_height,
@@ -115,6 +119,7 @@ impl Halign {
chunks.push(Self {
rows: self.rows[start..].to_vec(),
column_widths: self.column_widths.clone(),
column_wrap: self.column_wrap.clone(),
width: self.width,
height,
line_height: self.line_height,
@@ -122,11 +127,30 @@ impl Halign {
chunks
}
/// The horizontal rectangle occupied by a cell's text: `(x, width)`.
///
/// Spanned cells include the intercolumn gaps they cover. The x offset is
/// the aligned start inside that rectangle.
/// Column index of `cell_index` inside `row`.
fn cell_column(&self, row: &HalignRow, cell_index: usize) -> usize {
row.cells[..cell_index.min(row.cells.len())]
.iter()
.map(|cell| cell.span.max(1))
.sum()
}
/// The aligned rectangle of a cell: `(x, width)`.
pub fn cell_box(&self, row_index: usize, cell_index: usize) -> Option<(i64, i64)> {
let (x, width) = self.cell_span(row_index, cell_index)?;
let row = self.rows.get(row_index)?;
let cell = row.cells.get(cell_index)?;
let text_width = text_width(&cell.text);
let offset = match cell.alignment {
CellAlignment::Left => 0,
CellAlignment::Center => (width - text_width).max(0) / 2,
CellAlignment::Right => (width - text_width).max(0),
};
Some((x + offset, width))
}
/// The rectangle of the columns a cell covers, before alignment.
pub fn cell_span(&self, row_index: usize, cell_index: usize) -> Option<(i64, i64)> {
let row = self.rows.get(row_index)?;
let cell = row.cells.get(cell_index)?;
let mut column = 0_usize;
@@ -152,24 +176,175 @@ impl Halign {
.sum::<i64>()
+ gaps;
let x: i64 = self.column_widths[..column].iter().sum::<i64>() + intercolumn * column as i64;
let text_width = cell
.text
.chars()
.map(|character| {
if character.is_whitespace() {
Some((x, width))
}
/// The wrapped lines of a cell; a single line unless its column declares
/// `p{width}`.
pub fn cell_lines(&self, row_index: usize, cell_index: usize) -> Vec<String> {
let row = match self.rows.get(row_index) {
Some(row) => row,
None => return Vec::new(),
};
let cell = match row.cells.get(cell_index) {
Some(cell) => cell,
None => return Vec::new(),
};
if cell.span.max(1) == 1 {
let column = self.cell_column(row, cell_index);
if let Some(Some(width)) = self.column_wrap.get(column) {
return wrap_cell_text(&cell.text, *width);
}
}
vec![cell.text.clone()]
}
/// Height of one row, counting wrapped cell lines.
pub fn row_height(&self, row_index: usize) -> i64 {
let row = match self.rows.get(row_index) {
Some(row) => row,
None => return 0,
};
if row.rule {
return 26_214;
}
let lines = (0..row.cells.len())
.map(|index| self.cell_lines(row_index, index).len())
.max()
.unwrap_or(1)
.max(1);
self.line_height * lines as i64
}
}
/// Natural width of a run of text at the illustrative 10pt metrics.
pub(crate) fn text_width(text: &str) -> i64 {
text.chars()
.map(|character| {
if character.is_whitespace() {
4 * 65_536
} else {
10 * 65_536
}
})
.sum()
}
/// Greedily wrap `text` so each line fits `width`.
fn wrap_cell_text(text: &str, width: i64) -> Vec<String> {
let width = width.max(65_536);
let mut lines = Vec::new();
let mut line = String::new();
let mut line_width = 0_i64;
for word in text.split_whitespace() {
let word_width = text_width(word);
let gap = if line.is_empty() { 0 } else { 4 * 65_536 };
if !line.is_empty() && line_width + gap + word_width > width {
lines.push(std::mem::take(&mut line));
line_width = 0;
}
if !line.is_empty() && line_width + gap <= width {
line.push(' ');
line_width += gap;
}
if word_width <= width - line_width {
line.push_str(word);
line_width += word_width;
} else {
for character in word.chars() {
let character_width = if character.is_whitespace() {
4 * 65_536
} else {
10 * 65_536
};
if line_width + character_width > width && !line.is_empty() {
lines.push(std::mem::take(&mut line));
line_width = 0;
}
})
.sum::<i64>();
let offset = match cell.alignment {
CellAlignment::Left => 0,
CellAlignment::Center => (width - text_width).max(0) / 2,
CellAlignment::Right => (width - text_width).max(0),
};
Some((x + offset, width))
line.push(character);
line_width += character_width;
}
}
}
if !line.is_empty() {
lines.push(line);
}
if lines.is_empty() {
lines.push(String::new());
}
lines
}
/// Parse a TeX dimension such as `25mm`, `2cm`, `72bp` or `10pt`.
fn parse_tex_dimension(spec: &str) -> Option<i64> {
let spec = spec.trim();
if spec.is_empty() {
return None;
}
let split = spec
.find(|character: char| character.is_alphabetic())
.unwrap_or(spec.len());
let (number, unit) = spec.split_at(split);
let value: f64 = number.trim().parse().ok()?;
let points_per_unit = match unit.trim() {
"pt" => 1.0,
"bp" => 72.27 / 72.0,
"mm" => 72.27 / 25.4,
"cm" => 72.27 / 2.54,
"in" => 72.27,
"em" => 10.0,
_ => return None,
};
Some((value * points_per_unit * 65_536.0).round() as i64)
}
/// Parse an alignment template into per-column alignment and wrap widths.
fn parse_column_template(template: &str) -> (Vec<CellAlignment>, Vec<Option<i64>>) {
let mut alignments = Vec::new();
let mut wraps = Vec::new();
let mut characters = template.chars().peekable();
while let Some(character) = characters.next() {
match character {
'l' | 'L' => {
alignments.push(CellAlignment::Left);
wraps.push(None);
}
'c' | 'C' => {
alignments.push(CellAlignment::Center);
wraps.push(None);
}
'r' | 'R' => {
alignments.push(CellAlignment::Right);
wraps.push(None);
}
'p' | 'P' => {
let mut wrap = None;
if characters.peek() == Some(&'{') {
characters.next();
let mut spec = String::new();
for inner in characters.by_ref() {
if inner == '}' {
break;
}
spec.push(inner);
}
wrap = parse_tex_dimension(&spec);
}
alignments.push(CellAlignment::Left);
wraps.push(wrap);
}
'|' | '@' | ' ' => {}
_ => {
alignments.push(CellAlignment::Left);
wraps.push(None);
}
}
}
if alignments.is_empty() {
alignments.push(CellAlignment::Left);
wraps.push(None);
}
(alignments, wraps)
}
/// Vertical material reserved at the bottom of a page (footnotes etc.).
@@ -257,6 +432,23 @@ pub struct Unit {
impl Unit {
/// Build a simple `\halign` table with natural column widths.
pub fn halign(id: UnitId, rows: Vec<HalignRow>, column_count: usize, intercolumn: i64) -> Self {
Self::halign_with_wraps(
id,
rows,
column_count,
intercolumn,
vec![None; column_count],
)
}
/// Build a `\halign` table, honouring `p{width}` column declarations.
pub fn halign_with_wraps(
id: UnitId,
rows: Vec<HalignRow>,
column_count: usize,
intercolumn: i64,
wraps: Vec<Option<i64>>,
) -> Self {
let intercolumn = intercolumn.saturating_mul(65_536);
let mut column_widths = vec![0_i64; column_count];
for row in &rows {
@@ -264,17 +456,7 @@ impl Unit {
for cell in &row.cells {
let span = cell.span.max(1).min(column_count.saturating_sub(column));
if span == 1 {
let width: i64 = cell
.text
.chars()
.map(|character| {
if character.is_whitespace() {
4 * 65_536
} else {
10 * 65_536
}
})
.sum();
let width = text_width(&cell.text);
if let Some(slot) = column_widths.get_mut(column) {
*slot = (*slot).max(width);
}
@@ -293,8 +475,7 @@ impl Unit {
.copied()
.sum::<i64>()
+ gaps;
let needed: i64 = cell.text.chars().count() as i64 * 10 * 65_536;
let extra = (needed - available).max(0);
let extra = (text_width(&cell.text) - available).max(0);
for offset in 0..span {
column_widths[column + offset] += extra / span as i64;
}
@@ -302,13 +483,24 @@ impl Unit {
column += span;
}
}
for (index, wrap) in wraps.iter().enumerate() {
if let (Some(width), Some(slot)) = (wrap, column_widths.get_mut(index)) {
*slot = (*width).max(10 * 65_536);
}
}
let gaps = intercolumn * column_count.saturating_sub(1) as i64;
let width = column_widths.iter().sum::<i64>() + gaps;
let line_height = 12 * 65_536;
let rule_height = 26_214; // 0.4pt
let height = rows
.iter()
.map(|row| if row.rule { rule_height } else { line_height })
let mut halign = Halign {
rows,
column_widths,
column_wrap: wraps,
width,
height: 0,
line_height,
};
halign.height = (0..halign.rows.len())
.map(|index| halign.row_height(index))
.sum();
Self {
id,
@@ -317,13 +509,7 @@ impl Unit {
space_before: 0,
space_stretch: 0,
space_shrink: 0,
items: vec![VerticalItem::Halign(Halign {
rows,
column_widths,
width,
height,
line_height,
})],
items: vec![VerticalItem::Halign(halign)],
}
}
@@ -345,14 +531,7 @@ impl Unit {
source: &str,
intercolumn: i64,
) -> Self {
let alignments: Vec<CellAlignment> = template
.chars()
.map(|character| match character {
'c' => CellAlignment::Center,
'r' => CellAlignment::Right,
_ => CellAlignment::Left,
})
.collect();
let (alignments, wraps) = parse_column_template(template);
let column_count = alignments.len().max(1);
let mut rows = Vec::new();
for raw_row in source.split(r"\\") {
@@ -414,7 +593,7 @@ impl Unit {
}
rows.push(HalignRow { cells, rule: false });
}
Self::halign(id, rows, column_count, intercolumn)
Self::halign_with_wraps(id, rows, column_count, intercolumn, wraps)
}
/// A running mark item, recorded on the page where it is shipped out.
@@ -6207,6 +6386,89 @@ mod tests {
assert!(widths.windows(2).all(|pair| pair[0] == pair[1]));
}
#[test]
fn paragraph_columns_wrap_cell_text() {
let unit = Unit::halign_from_source_with_template(
1,
"p{25mm}l",
"alpha beta gamma delta & short \\\\
second row & right\n",
0,
);
let VerticalItem::Halign(halign) = &unit.items[0] else {
panic!("expected halign");
};
let wrap = halign.column_wrap[0].expect("p column");
let expected = (25.0_f64 * 72.27 / 25.4 * 65_536.0).round() as i64;
assert!(
(wrap - expected).abs() <= 2,
"wrap {wrap} expected {expected}"
);
assert_eq!(halign.column_widths[0], wrap);
let lines = halign.cell_lines(0, 0);
assert!(lines.len() >= 3, "lines: {lines:?}");
assert!(lines.iter().all(|line| crate::text_width(line) <= wrap));
assert_eq!(
halign.row_height(0),
halign.line_height * lines.len() as i64
);
assert_eq!(
halign.cell_lines(1, 0),
vec!["second".to_owned(), "row".to_owned()]
);
}
#[test]
fn paragraph_columns_paint_wrapped_lines_and_split_rows() {
let unit = Unit::halign_from_source_with_template(
1,
"p{20mm}l",
"alpha beta gamma delta & x \\\\
second row text & y\n",
0,
);
let VerticalItem::Halign(halign) = &unit.items[0] else {
panic!("expected halign");
};
let lines = halign.cell_lines(0, 0);
assert!(lines.len() >= 4, "lines: {lines:?}");
let list = halign.display_list();
let texts: Vec<&str> = list
.items
.iter()
.filter_map(|item| match item {
DisplayItem::Text { text, .. } => Some(text.as_str()),
_ => None,
})
.collect();
assert!(texts.contains(&"alpha"), "texts: {texts:?}");
assert!(texts.contains(&"beta"), "texts: {texts:?}");
let alpha_y = list
.items
.iter()
.find_map(|item| match item {
DisplayItem::Text { text, y, .. } if text == "alpha" => Some(*y),
_ => None,
})
.unwrap();
let beta_y = list
.items
.iter()
.find_map(|item| match item {
DisplayItem::Text { text, y, .. } if text == "beta" => Some(*y),
_ => None,
})
.unwrap();
assert!(beta_y > alpha_y, "alpha {alpha_y} beta {beta_y}");
let chunks = halign.split_for_height(halign.line_height * 2);
assert!(chunks.len() >= 2);
assert_eq!(
chunks.iter().map(|chunk| chunk.rows.len()).sum::<usize>(),
2
);
assert_eq!(chunks[0].column_widths, chunks[1].column_widths);
}
#[test]
fn checkpoint_round_trips_through_serde() {
let engine = Engine::layout(&document());
+28 -7
View File
@@ -8,7 +8,7 @@
use crate::cmr10::Cmr10Metrics;
use crate::math::{self, MathAtom};
use crate::paragraph::ParagraphFont;
use crate::{Float, FloatPlacement, Halign, HorizontalItem, Page, VerticalItem};
use crate::{CellAlignment, Float, FloatPlacement, Halign, HorizontalItem, Page, VerticalItem};
/// One absolute drawing primitive in scaled points.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
@@ -284,19 +284,40 @@ impl Halign {
y += height;
continue;
}
let baseline = y + (self.line_height as f64 * 0.8) as i64;
for (index, cell) in row.cells.iter().enumerate() {
if let Some((x, _)) = self.cell_box(row_index, index) {
let row_height = self.row_height(row_index);
let lines_in_row = (0..row.cells.len())
.map(|index| self.cell_lines(row_index, index).len())
.max()
.unwrap_or(1)
.max(1);
for line_index in 0..lines_in_row {
let baseline = y
+ (self.line_height as f64 * 0.8) as i64
+ line_index as i64 * self.line_height;
for (index, cell) in row.cells.iter().enumerate() {
let lines = self.cell_lines(row_index, index);
let Some(line) = lines.get(line_index) else {
continue;
};
let Some((x, width)) = self.cell_span(row_index, index) else {
continue;
};
let text_width = crate::text_width(line);
let offset = match cell.alignment {
CellAlignment::Left => 0,
CellAlignment::Center => (width - text_width).max(0) / 2,
CellAlignment::Right => (width - text_width).max(0),
};
list.push(DisplayItem::Text {
font: FontFace::Roman,
x,
x: x + offset,
y: baseline,
size: 10 * 65_536,
text: cell.text.clone(),
text: line.clone(),
});
}
}
y += self.line_height;
y += row_height;
}
list
}
+2 -2
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`). 477 workspace tests are green and no oracle
PDF opt-in with `?engine=route-d`). 479 workspace tests are green and no oracle
fixture is ignored.
Status after G1 (P0-P2): the paragraph model reproduces TeX's passes,
@@ -60,7 +60,7 @@ table in [`TEX_CORE.md`](TEX_CORE.md) lists the evidence per milestone.
Remaining gaps:
1. `\halign` handles spans/omit/templates and row-level page splitting (chunks keep the table's column widths), but not the full TeX column algorithm (`p{width}` cells, `\tabskip` arrays, booktabs/longtable, multi-line cells);
1. `\halign` handles spans/omit/templates, `p{width}` paragraph columns (wrapped cell text grows row heights and participates in row-level page splitting) and page-sized row chunks that keep the table's column widths, but not the full TeX column algorithm (`\tabskip` arrays, booktabs/longtable, `\valign` interleaving);
2. math is a compact subset without the CM math fonts (`cmmi`, `cmsy`, `cmex`),
display-math line breaking or `\mathchoice`-level styling;
3. text fonts are Liberation, not Computer Modern; Type1 fonts are not embeddable
+2 -2
View File
@@ -130,7 +130,7 @@ and justification.
| M0 | vertical list, page builder, checkpoint, page hash, edit demo | edit on page 2 rebuilds only page 2 |
| M1 | TeX box/glue/penalty + paragraph builder (`\par`, `\hsize`, `\parindent`) | **partial**: item stream, CMR10 metrics, TeX Live en-US hyphenation, TeX demerits and tolerance passes, `\hangindent`/`\parshape`, `\parfillskip`, sentence spacing, `\spaceskip`/`\xspaceskip`, `\raggedright` (infinite `\rightskip`), `\looseness`, `\baselineskip`/`\lineskip`/`\parskip` interline glue, pdfLaTeX oracle matrix 90-240pt plus register, geometry, `\sfcode`, `\parindent`, `\parshape`, `\leftskip`/`\rightskip`, `\hfil`/`\hfill` glue orders, `\prevgraf` in the output routine, and vertical-glue fixtures |
| M2 | page builder + `\output`, `\vsize`, `\topskip`, footnotes, floats | **partial**: `\vsize` page goal, `\topskip`, forced penalties, `Insertion` reserve, running `Mark`s, `OutputRoutine` hook, top/bottom `Float` placement; `page::PageBuilder` scores candidate breakpoints with TeX page badness, glue setting (with `\raggedbottom`/`\flushbottom` applied when pages are materialised, and TeX glue orders `\vfil`/`\vfill`/`\vfilll` honoured so only the highest order with stretch is used), `\topskip`/`\maxdepth`, and `Engine::layout_paged` uses it for documents whose units are single vertical items, placing top and bottom floats (with `\floatsep`, a `\bottomfraction` cap and the `\topnumber`/`\bottomnumber`/`\totalnumber` limits, with `\floatpagefraction` deciding when a float-heavy page ships without body) and insertion classes on that path, while in-text floats flow inline as body material; paged layouts replay edits from the edited unit's page and fall back to a full rebuild only when insertions, bottom floats or an interpreted `\output` are present; `\output` is interpreted for a `\shipout`/`\ifdim`/`\ifnum`/`\ifodd`/`\ifcase` subset, and `\mark{...}`/`\marks<n>{...}` writes inside the routine are carried to the following page's mark list with their class; `\pageno`, `\outputpenalty` and `\deadcycles` are readable and assignable registers (`\pageno=...` carries into the next page, and an assigned `\vsize` retargets the pages the routine has not seen yet, even when the document raises insertion material; only a document that defers bottom floats keeps its initial goal, because the carried queue cannot be rebuilt after a retarget), `\ht255`, `\dp255` and `\wd255` expose the page box height, depth and width to the routine, and `\hsize` is readable (and assignable for the rest of the run) while `\wd255` tracks it; route-D sets `\hsize` from its 480pt text measure, insertion class registers `\count<n>`/`\dimen<n>`/`\skip<n>` read the configured multiplier, maximum height and skip of class `n` (with `\count0` reading `\pageno`) and accept assignments that outlive the routine (the paged builder runs the routine after each page, so an assigned `\dimen<n>` or `\count<n>` changes the insertion capacity and reservation of later pages); the configured `\skip<n>` also reserves space above its class once per page in the paged builder, and a `\skip<n>` assignment rebuilds the pages the routine has not seen yet with the new reservation, `\deadcycles` accumulates pages the output routine did not ship and resets on the next shipout, `\maxdeadcycles` (default 25, assignable) makes the page builder ship the page itself once that many dead cycles have accumulated, `PageFragment::penalty` carries the break penalty (`\outputpenalty`: the penalty value when the break landed on a penalty, otherwise 10000, as TeX reports for glue breaks, goal overflow and the final page), and `PageFragment::stretches` records glue stretch per TeX order so `\pagefilstretch`/`\pagefillstretch`/`\pagefilllstretch` are readable in the output routine; `\vbadness` reports the badness of the break that produced the page and `\insertpenalties` the number of insertion items held over from it |
| M3 | `\halign`, `\omit`, `\span`, `\multispan`, booktabs/longtable | **partial**: source parsing, natural column widths, spans, rule rows, 10pt display-list painting and row-level page splitting; the paged builder splits a tall alignment into page-sized row chunks that keep the table's column widths, so long tables continue across pages; no booktabs/longtable, `p{width}` cells or `\tabskip` arrays yet |
| M3 | `\halign`, `\omit`, `\span`, `\multispan`, booktabs/longtable | **partial**: source parsing, natural column widths, spans, rule rows, 10pt display-list painting and row-level page splitting; the paged builder splits a tall alignment into page-sized row chunks that keep the table's column widths, so long tables continue across pages; `p{width}` paragraph columns wrap cell text and grow row heights, and wrapped rows participate in row-level splitting; no booktabs/longtable, `\tabskip` arrays or full tabular parity yet |
| M4 | math lists, scripts, fractions, radicals, accents, delimiters | **partial**: token parser, atom boxes with CMR10 metrics, delimiter scaling, accents and a display-list painter; no CMEX size variants or TeX math spacing classes yet |
| M5 | NFSS/TFM metrics, CM/Latin Modern | same line/page breaks as reference |
| M6 | class/package execution (`article`, `sn-jnl`) | Overleaf page-count parity |
@@ -367,7 +367,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`) supplies advances, kerns, ligatures, and italic correction for layout, while the display list and PDF select the matching Liberation face. `Engine::edit` preserves the face when reflowing an edited paragraph.
The crate currently has 320 unit tests plus seven route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 477 tests (320 route-D unit, 7 route-D integration, 35 oracle, 71 v1 integration, 26 server, 4 v1 unit, 1 core unit, 13 binary units), with none ignored. v1 remains the live server path.
The crate currently has 322 unit tests plus seven route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 479 tests (322 route-D unit, 7 route-D integration, 35 oracle, 71 v1 integration, 26 server, 4 v1 unit, 1 core unit, 13 binary units), with none ignored. v1 remains the live server path.
### M0 incremental demo