Transpose valign into a table

\valign had no handler. Add a preprocessing pass that finds \valign{...},
splits the group at \cr, treats each remaining \cr-separated line as one column
(entries split on &), and emits an equivalent tabular with the matrix
transposed; the existing capture then lays it out. Column alignment defaults to
left because the \valign preamble describes vertical alignment here.

A test transposes \valign{\cr a & b & c \cr d & e & f \cr} into two columns and
three rows, checking (a,d) and (c,f).
This commit is contained in:
gloamxun committed 2026-10-27 01:23:20 +08:00
1 parent 05e1bd096b
commit 7a9e28d0f4
3 files changed
+90 -4

No files matched your search

+1 -1
View File
@@ -49,7 +49,7 @@ floats (`\floatsep`, `\textfloatsep`, `\intextsep`, `\topfraction`,
absolute limits, splitting), marks, Rust output hook, multi-page PDF, and the 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 route-D service endpoints (`/api/route-d/preview|pdf|edit`, project preview and
PDF opt-in with `?engine=route-d`; flat `/preview` and project previews now PDF opt-in with `?engine=route-d`; flat `/preview` and project previews now
prefer route-D with a v1 fallback). 1008 workspace tests are green and no oracle prefer route-D with a v1 fallback). 1009 workspace tests are green and no oracle
fixture is ignored. Preview JSON also carries a `warnings` array naming fixture is ignored. Preview JSON also carries a `warnings` array naming
environments route-D cannot lay out and control words that survived layout, so environments route-D cannot lay out and control words that survived layout, so
unsupported source is reported instead of being silently typeset. unsupported source is reported instead of being silently typeset.
+4 -3
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. 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 437 unit tests plus ten route-D integration tests and forty-two oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 1008 tests (437 route-D unit, 381 engine binary unit, 10 route-D integration, 42 oracle, 71 v1 integration, 62 server, 4 engine unit, 1 core unit), with none ignored. The flat `/preview` endpoint and the project preview/PDF endpoints now try route-D first and fall back to v1 on error (`?engine=v1` or `TEXRRA_ENGINE=v1` forces v1; the flat response carries `X-Preview-Engine`, naming the engine used). A geometry-less project now defaults to Letter, matching pdfLaTeX, where the old v1 path used A4. The crate currently has 437 unit tests plus ten route-D integration tests and forty-two oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 1009 tests (437 route-D unit, 382 engine binary unit, 10 route-D integration, 42 oracle, 71 v1 integration, 62 server, 4 engine unit, 1 core unit), with none ignored. The flat `/preview` endpoint and the project preview/PDF endpoints now try route-D first and fall back to v1 on error (`?engine=v1` or `TEXRRA_ENGINE=v1` forces v1; the flat response carries `X-Preview-Engine`, naming the engine used). A geometry-less project now defaults to Letter, matching pdfLaTeX, where the old v1 path used A4.
### M0 incremental demo ### M0 incremental demo
@@ -589,8 +589,9 @@ are:
`tabular` is attached to its outer cell as a real inner table: column widths `tabular` is attached to its outer cell as a real inner table: column widths
and row heights account for it, the inner table is painted at the cell and row heights account for it, the inner table is painted at the cell
position, and page splitting remaps its row index. Images inside a nested position, and page splitting remaps its row index. Images inside a nested
table are not merged into the outer display list, and `\valign` remains table are not merged into the outer display list. `\valign` is rewritten into
unmodelled. a transposed `tabular` (column-major input becomes rows); its preamble
alignments and vertical rules are ignored and the cells are left-aligned.
- **Fonts**: the twelve Computer Modern faces and four math faces are embedded - **Fonts**: the twelve Computer Modern faces and four math faces are embedded
as Type1 with per-glyph Liberation fallback. Greek math commands map to their as Type1 with per-glyph Liberation fallback. Greek math commands map to their
Unicode letters and render through the math-italic fallback (widths Unicode letters and render through the math-italic fallback (widths
+85
View File
@@ -5874,6 +5874,57 @@ fn is_internal_at_command(name: &str) -> bool {
.is_some_and(|rest| INTERNAL_AT_COMMANDS.contains(&rest)) .is_some_and(|rest| INTERNAL_AT_COMMANDS.contains(&rest))
} }
/// Rewrite `\valign{...}` into a transposed `tabular`: each `\cr`-separated
/// input line is one column, and the output rows take one entry from each line.
fn expand_valign(source: &str) -> String {
let mut out = String::new();
let mut rest = source;
while let Some(position) = rest.find("\\valign") {
out.push_str(&rest[..position]);
let after = &rest[position + "\\valign".len()..];
let trimmed = after.trim_start();
let Some((content, used)) = braced_group(trimmed) else {
out.push_str(&rest[position..]);
return out;
};
out.push_str(&render_valign(content));
rest = &trimmed[used..];
}
out.push_str(rest);
out
}
fn render_valign(content: &str) -> String {
let body = match content.split_once("\\cr") {
Some((_preamble, body)) => body,
None => content,
};
let columns: Vec<Vec<String>> = body
.split("\\cr")
.map(|line| {
line.split('&')
.map(|cell| cell.trim().to_string())
.collect::<Vec<_>>()
})
.filter(|cells| cells.iter().any(|cell| !cell.is_empty()))
.collect();
if columns.is_empty() {
return String::new();
}
let height = columns.iter().map(Vec::len).max().unwrap_or(0);
let mut out = format!("\\begin{{tabular}}{{{}}}\n", "l".repeat(columns.len()));
for row in 0..height {
let cells: Vec<&str> = columns
.iter()
.map(|column| column.get(row).map(String::as_str).unwrap_or(""))
.collect();
out.push_str(&cells.join(" & "));
out.push_str(" \\\\\n");
}
out.push_str("\\end{tabular}");
out
}
/// Parse the `\catcode` target and value that follow the command, supporting /// Parse the `\catcode` target and value that follow the command, supporting
/// the backtick form (`\catcode`\@=11`), a bare character, or a code point. /// the backtick form (`\catcode`\@=11`), a bare character, or a code point.
fn catcode_assignment(characters: &[char], start: usize) -> Option<(char, i64, usize)> { fn catcode_assignment(characters: &[char], start: usize) -> Option<(char, i64, usize)> {
@@ -6158,6 +6209,7 @@ fn geometry_and_body_with_images(
// body before `\begin{document}` so its commands are consumed as setup // body before `\begin{document}` so its commands are consumed as setup
// instead of being typeset as text at the top of page one. // instead of being typeset as text at the top of page one.
let source = lift_at_begin_document(source); let source = lift_at_begin_document(source);
let source = expand_valign(&source);
let source = canonicalize_at_catcodes(&source); let source = canonicalize_at_catcodes(&source);
let source = collapse_definition_bodies(&source); let source = collapse_definition_bodies(&source);
let source = collapse_braced_command(&source, "\\newgeometry"); let source = collapse_braced_command(&source, "\\newgeometry");
@@ -16081,6 +16133,39 @@ A definition.
assert!(!text.contains("makeatletter"), "{text}"); assert!(!text.contains("makeatletter"), "{text}");
} }
#[test]
fn valign_transposes_into_a_table() {
let source = "\\valign{\\cr a & b & c \\cr d & e & f \\cr}";
let (body, geometry) = geometry_and_body(source);
assert_eq!(geometry.tabular.len(), 1);
let blocks = paragraphs(&body).expect("paragraphs");
let document = build_document(&blocks, &geometry);
let halign = document
.units
.iter()
.find_map(|unit| {
unit.items.iter().find_map(|item| match item {
VerticalItem::Halign(halign) => Some(halign),
_ => None,
})
})
.expect("halign");
assert_eq!(halign.column_widths.len(), 2);
assert_eq!(halign.rows.len(), 3);
let row0: Vec<&str> = halign.rows[0]
.cells
.iter()
.map(|cell| cell.text.as_str())
.collect();
let row2: Vec<&str> = halign.rows[2]
.cells
.iter()
.map(|cell| cell.text.as_str())
.collect();
assert_eq!(row0, vec!["a", "d"]);
assert_eq!(row2, vec!["c", "f"]);
}
#[test] #[test]
fn percent_catcode_turns_comments_literal() { fn percent_catcode_turns_comments_literal() {
let literal = "\\documentclass{article}\n\\catcode`\\%=12\n\\begin{document}\n\n100% sure\n\n\\end{document}\n"; let literal = "\\documentclass{article}\n\\catcode`\\%=12\n\\begin{document}\n\n100% sure\n\n\\end{document}\n";