Scale paragraphs by their declared base font size

This commit is contained in:
gloamxun committed 2026-10-24 13:04:19 +08:00
1 parent aa4d86d735
commit 9876895a84
8 files changed
+249 -17

No files matched your search

+1 -1
View File
@@ -467,7 +467,7 @@ from the font's MATH assembly parts. `\\left...\\right` target sizing follows
the assignable TeX parameters `\\delimiterfactor` (default 901) and
`\\delimitershortfall` (default 5pt), including local and global assignments.
Route-D text faces follow the NFSS declarations and compose with the surrounding run: `\sffamily\bfseries` selects cmssbx10, `\sffamily\itshape` selects cmssi10, and bold italic sans substitutes cmssbx10 because Computer Modern has no sans bold italic. `\scshape`/`\textsc` select the real cmcsc10 small-caps face, `\slshape`/`\textsl` use cmsl10 (or cmbxsl10 when bold) rather than the italic cmti10, and `\ttfamily\itshape` reaches cmitt10. All twelve text programs (cmr10, cmbx10, cmti10, cmbxti10, cmtt10, cmss10, cmssbx10, cmssi10, cmcsc10, cmsl10, cmbxsl10, cmitt10) are embedded as Type1 outlines. Because Computer Modern has no bold small caps, a bold small-caps request falls back to cmbx10. Section-wide declarations such as `\bfseries` apply from where they appear to the end of their group, and `\em` toggles emphasis relative to the surrounding face. In route-D, math uses Computer Modern metrics from the bundled `cmmi10`, `cmsy10`, `cmex10`, `msbm10` and `eufm10` TFMs and embeds their Type1 programs, so italic letters, relation symbols, big operators, `\mathcal` capitals, `\mathbb` capitals and `\mathfrak` Fraktur letters each paint with their own face. Fractions can be written as `\frac` or with TeX's infix forms (`\over`, `\atop`, `\choose`, `\brace`, `\brack`, `\overwithdelims`, `\atopwithdelims`); only `\over`-style fractions draw a bar and fractions never draw parentheses. `\left`/`\right` choose CMEX delimiter sizes from the body extent using TeX's delimiterfactor and shortfall, `\middle` delimiters are sized with their group, and `\big`/`\Big`/`\bigg`/`\Bigg` paint at their selected CMEX size. `align`/`align*` displays share column widths, right-align even columns at their relations, and number each row (with `\tag`/`\notag` per row); `gather`/`gather*` centre each row instead. Inter-atom spacing uses TeX's 3/4/5mu classes (`1mu` is `1/18em`), `\mid` is a relation and `\colon` punctuation, and `\mskip`/`\mkern`/`\mspace`/`\hskip`/`\kern`/`\hspace` scan TeX dimensions, taking the natural width of any `plus`/`minus` parts.
Route-D text faces follow the NFSS declarations and compose with the surrounding run: `\sffamily\bfseries` selects cmssbx10, `\sffamily\itshape` selects cmssi10, and bold italic sans substitutes cmssbx10 because Computer Modern has no sans bold italic. `\scshape`/`\textsc` select the real cmcsc10 small-caps face, `\slshape`/`\textsl` use cmsl10 (or cmbxsl10 when bold) rather than the italic cmti10, and `\ttfamily\itshape` reaches cmitt10. All twelve text programs (cmr10, cmbx10, cmti10, cmbxti10, cmtt10, cmss10, cmssbx10, cmssi10, cmcsc10, cmsl10, cmbxsl10, cmitt10) are embedded as Type1 outlines. Because Computer Modern has no bold small caps, a bold small-caps request falls back to cmbx10. Section-wide declarations such as `\bfseries` apply from where they appear to the end of their group, and `\em` toggles emphasis relative to the surrounding face. Paragraph base sizes come from `\fontsize{<size>}{<baselineskip>}` and the article size commands (`\tiny` through `\Huge`), scaling glyph metrics and the default interline glue while the measure, indentation and authored skips stay absolute. In route-D, math uses Computer Modern metrics from the bundled `cmmi10`, `cmsy10`, `cmex10`, `msbm10` and `eufm10` TFMs and embeds their Type1 programs, so italic letters, relation symbols, big operators, `\mathcal` capitals, `\mathbb` capitals and `\mathfrak` Fraktur letters each paint with their own face. Fractions can be written as `\frac` or with TeX's infix forms (`\over`, `\atop`, `\choose`, `\brace`, `\brack`, `\overwithdelims`, `\atopwithdelims`); only `\over`-style fractions draw a bar and fractions never draw parentheses. `\left`/`\right` choose CMEX delimiter sizes from the body extent using TeX's delimiterfactor and shortfall, `\middle` delimiters are sized with their group, and `\big`/`\Big`/`\bigg`/`\Bigg` paint at their selected CMEX size. `align`/`align*` displays share column widths, right-align even columns at their relations, and number each row (with `\tag`/`\notag` per row); `gather`/`gather*` centre each row instead. Inter-atom spacing uses TeX's 3/4/5mu classes (`1mu` is `1/18em`), `\mid` is a relation and `\colon` punctuation, and `\mskip`/`\mkern`/`\mspace`/`\hskip`/`\kern`/`\hspace` scan TeX dimensions, taking the natural width of any `plus`/`minus` parts.
Route-D integration can also be checked against a real TeX page: `cargo test -p texrra-tex-core --test route_d` includes `route_d_page_matches_pdftex_raster_geometry`, which renders the route-D PDF and a pdfTeX Letter page at the same scaled-point geometry, rasterizes both with `pdftoppm`, and compares ink line count plus left, right, and bottom edges. It is skipped when `pdflatex`/`pdftoppm` are unavailable. `route_d_multiline_bands_track_pdftex` extends that check to a wrapped paragraph: the pixel rows that carry ink form one band per TeX line, and every band top, bottom, left edge and (except for the last line, whose width follows the break point) right edge must land within a couple of pixels of the pdfTeX page.
+26
View File
@@ -6306,6 +6306,30 @@ mod tests {
assert!(svg.contains("font-style=\"italic\""));
}
#[test]
fn sized_paragraphs_paint_at_their_font_size() {
let style = crate::paragraph::ParagraphStyle {
font_size: 12 * 65_536,
..crate::paragraph::ParagraphStyle::default()
};
let unit =
Unit::paragraph_with_style_and_face(1, "large text", style, ParagraphFont::Roman);
let page = Page {
items: unit.items,
insertions: Vec::new(),
marks: Vec::new(),
floats: Vec::new(),
sources: Vec::new(),
hash: 0,
};
let list = page.display_list();
assert!(
list.items
.iter()
.any(|item| matches!(item, crate::render::DisplayItem::Text { size: 786_432, .. }))
);
}
#[test]
fn mono_paragraph_paints_with_a_mono_face() {
let unit = Unit::paragraph_with_face(1, "code 123", ParagraphFont::Mono);
@@ -6859,6 +6883,7 @@ mod tests {
width: 50,
depth: 0,
font: ParagraphFont::Roman,
font_size: 10 * 65_536,
left_skip: 0,
line_indents: vec![0; 10],
line_baselines: (0..10).map(|line| 8 + line * 10).collect(),
@@ -8433,6 +8458,7 @@ b & 2 \\
width: 5 * 65_536,
depth: 2 * 65_536,
font: ParagraphFont::Roman,
font_size: 10 * 65_536,
left_skip: 0,
line_indents: vec![0],
line_baselines: vec![8 * 65_536],
+122 -5
View File
@@ -73,6 +73,13 @@ fn default_adj_demerits() -> i64 {
10_000
}
/// Base font size for unscaled paragraphs (10pt in scaled points).
const BASE_FONT_SIZE: i64 = 655_360;
fn default_font_size() -> i64 {
BASE_FONT_SIZE
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ParagraphStyle {
pub line_width: i64,
@@ -169,6 +176,10 @@ pub struct ParagraphStyle {
#[serde(default)]
pub hyphenation_exceptions: Vec<String>,
pub line_height: i64,
/// Base font size in scaled points (`\fontsize`, `\large`, ...). Glyph
/// metrics and the default interline glue scale by this over 10pt.
#[serde(default = "default_font_size")]
pub font_size: i64,
pub char_width: i64,
pub space_width: i64,
pub space_stretch: i64,
@@ -274,6 +285,7 @@ impl Default for ParagraphStyle {
adj_demerits: 10_000,
hyphenation_exceptions: Vec::new(),
line_height: 12,
font_size: BASE_FONT_SIZE,
char_width: 10,
space_width: 4,
space_stretch: 6,
@@ -447,6 +459,9 @@ pub struct Paragraph {
pub depth: i64,
#[serde(default)]
pub font: ParagraphFont,
/// Base font size used when painting the glyphs of this paragraph.
#[serde(default = "default_font_size")]
pub font_size: i64,
#[serde(default)]
pub left_skip: i64,
/// Left offset for each line, from `\hangindent`/`\parshape`.
@@ -499,6 +514,7 @@ impl Paragraph {
width: self.width,
depth: tail_depth,
font: self.font,
font_size: self.font_size,
left_skip: self.left_skip,
line_indents: tail_indents,
line_baselines: tail_baselines,
@@ -508,6 +524,70 @@ impl Paragraph {
}
}
/// Scale a font-derived dimension by the paragraph's base font size.
fn scale_font_size(value: i64, size: i64) -> i64 {
value.saturating_mul(size) / BASE_FONT_SIZE
}
/// Scale every glyph and glue in a shaped item stream for the paragraph's
/// base font size. Scaling after shaping is linear, so it matches shaping with
/// scaled TFM metrics.
fn scale_items_for_size(items: &mut [HorizontalItem], size: i64) {
if size == BASE_FONT_SIZE {
return;
}
for item in items {
match item {
HorizontalItem::Box(box_) => {
box_.width = scale_font_size(box_.width, size);
box_.height = scale_font_size(box_.height, size);
box_.depth = scale_font_size(box_.depth, size);
box_.italic = scale_font_size(box_.italic, size);
}
HorizontalItem::Glue {
width,
stretch,
shrink,
..
} => {
*width = scale_font_size(*width, size);
*stretch = scale_font_size(*stretch, size);
*shrink = scale_font_size(*shrink, size);
}
HorizontalItem::Discretionary {
pre_break_width,
no_break_width,
} => {
*pre_break_width = scale_font_size(*pre_break_width, size);
*no_break_width = scale_font_size(*no_break_width, size);
}
HorizontalItem::Penalty { .. } => {}
}
}
}
/// Clone a paragraph style with its font-derived defaults scaled to the
/// paragraph's base size. Explicitly authored glue is left alone, and the
/// measure, indentation and skips stay absolute as in TeX.
fn sized_style(style: &ParagraphStyle) -> ParagraphStyle {
if style.font_size == BASE_FONT_SIZE {
return style.clone();
}
let mut sized = style.clone();
if sized.baselineskip == default_baselineskip() {
sized.baselineskip = scale_font_size(sized.baselineskip, style.font_size);
}
if sized.lineskip == default_lineskip() {
sized.lineskip = scale_font_size(sized.lineskip, style.font_size);
}
sized.line_height = scale_font_size(sized.line_height, style.font_size);
sized.char_width = scale_font_size(sized.char_width, style.font_size);
sized.space_width = scale_font_size(sized.space_width, style.font_size);
sized.space_stretch = scale_font_size(sized.space_stretch, style.font_size);
sized.space_shrink = scale_font_size(sized.space_shrink, style.font_size);
sized
}
/// Convert text into a horizontal item stream: one box per character, one
/// glue per space, and a final penalty.
pub fn text_items(text: &str, style: &ParagraphStyle) -> Vec<HorizontalItem> {
@@ -561,6 +641,7 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
width: 0,
depth: 0,
font: ParagraphFont::Roman,
font_size: style.font_size,
left_skip: style.left_skip,
line_indents: Vec::new(),
line_baselines: Vec::new(),
@@ -1171,6 +1252,7 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
depth,
lines,
font: ParagraphFont::Roman,
font_size: style.font_size,
left_skip: style.left_skip,
line_indents,
line_baselines,
@@ -1407,8 +1489,11 @@ pub fn layout_paragraph_with_font(
style: &ParagraphStyle,
font: &crate::cmr10::Cmr10Metrics,
) -> Paragraph {
let items = text_items_with_font(text, style, font);
layout_items(&items, style)
let mut items = text_items_with_font(text, style, font);
scale_items_for_size(&mut items, style.font_size);
let mut paragraph = layout_items(&items, &sized_style(style));
paragraph.font_size = style.font_size;
paragraph
}
/// Lay out a paragraph whose text is split into styled runs.
@@ -1452,14 +1537,19 @@ pub fn layout_paragraph_runs(
items.extend(run);
previous = Some((*font, text.clone()));
}
let mut paragraph = layout_items(&items, style);
scale_items_for_size(&mut items, style.font_size);
let mut paragraph = layout_items(&items, &sized_style(style));
paragraph.font = runs.first().map(|run| run.0).unwrap_or_default();
paragraph.font_size = style.font_size;
paragraph
}
pub fn layout_paragraph(text: &str, style: &ParagraphStyle) -> Paragraph {
let items = text_items(text, style);
layout_items(&items, style)
let mut items = text_items(text, style);
scale_items_for_size(&mut items, style.font_size);
let mut paragraph = layout_items(&items, &sized_style(style));
paragraph.font_size = style.font_size;
paragraph
}
#[cfg(test)]
@@ -1478,6 +1568,33 @@ mod tests {
.count()
}
#[test]
fn font_size_scales_glyphs_and_line_spacing() {
let font = crate::cmr10::Cmr10Metrics::Roman;
let base = ParagraphStyle {
line_width: 150 * 65_536,
par_indent: 0,
..ParagraphStyle::default()
};
let ten = layout_paragraph_with_font("hello world", &base, &font);
let large = ParagraphStyle {
font_size: 12 * 65_536,
..base.clone()
};
let twelve = layout_paragraph_with_font("hello world", &large, &font);
assert!(twelve.width > ten.width);
assert!(twelve.height > ten.height);
let glyphs = |paragraph: &Paragraph| {
paragraph
.lines
.iter()
.flatten()
.filter(|item| matches!(item, HorizontalItem::Box(_)))
.count()
};
assert_eq!(glyphs(&ten), glyphs(&twelve));
}
#[test]
fn overfull_lines_do_not_exceed_the_declared_shrink() {
let font = crate::cmr10::Cmr10Metrics::Roman;
+1 -1
View File
@@ -502,7 +502,7 @@ impl Page {
let face = paragraph_face(paragraph.font);
let lines = paragraph.lines.len().max(1) as i64;
let line_height = (paragraph.height / lines).max(1);
let size = 10 * 65_536;
let size = paragraph.font_size.max(1);
for (line_index, line) in paragraph.lines.iter().enumerate() {
let indent = paragraph.line_indents.get(line_index).copied().unwrap_or(0);
let baseline = y + paragraph
+4
View File
@@ -14,6 +14,7 @@ use texrra_tex_core::{
fn body_style() -> ParagraphStyle {
let font = Cmr10Metrics::default();
ParagraphStyle {
font_size: 10 * 65_536,
line_width: 480 * 65_536,
left_skip: 0,
right_skip: 0,
@@ -185,6 +186,7 @@ fn route_d_page_matches_pdftex_raster_geometry() {
std::fs::create_dir_all(&root).expect("create raster dir");
let style = ParagraphStyle {
font_size: 10 * 65_536,
line_width: 480 * 65_536,
left_skip: 0,
right_skip: 0,
@@ -365,6 +367,7 @@ fn route_d_two_pages_match_pdftex_raster_geometry() {
std::fs::create_dir_all(&root).expect("create raster dir");
let style = ParagraphStyle {
font_size: 10 * 65_536,
line_width: 480 * 65_536,
left_skip: 0,
right_skip: 0,
@@ -717,6 +720,7 @@ fn route_d_multiline_bands_track_pdftex() {
let text = "alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu";
let style = ParagraphStyle {
font_size: 10 * 65_536,
line_width: 150 * 65_536,
left_skip: 0,
right_skip: 0,
+1 -1
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`). 589 workspace tests are green and no oracle
PDF opt-in with `?engine=route-d`). 594 workspace tests are green and no oracle
fixture is ignored.
Status after G1 (P0-P2): the paragraph model reproduces TeX's passes,
+3 -3
View File
@@ -132,7 +132,7 @@ and justification.
| 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; `p{width}` paragraph columns wrap cell text and grow row heights, wrapped rows participate in row-level splitting, explicit per-column `\tabskip` glue is honoured through layout, painting and page chunks, and booktabs rules carry their own weights and spans (`\toprule`/`\bottomrule` 0.8pt, `\midrule`/`\cmidrule` 0.5pt, with `\cmidrule(lr){a-b}` trimming and column ranges), `@{}` / `@{\hspace{...}}` column expressions override the inter-column glue, and row-boundary `\noalign{\vskip ...}` glue is honoured by layout, painting and page chunks; longtable head/foot sections (`\endfirsthead`/`\endhead`/`\endfoot`/`\endlastfoot`) are parsed, continuation chunks repeat the head rows and the foot block paints once at the end, LaTeX `tabular` environments are captured and laid out through the same `\halign` path (rules are stripped from the column spec, `p{...}`/`m{...}`/`b{...}` become wrapping columns, `@{}` expressions are ignored for spacing), though `\valign`, nested tables and full tabular parity remain open |
| M4 | math lists, scripts, fractions, radicals, accents, delimiters | **partial**: token parser, atom boxes with Computer Modern metrics (italic letters from the bundled `cmmi10`, big operators from `cmex10`, symbols such as `\times`/`\leq`/`\infty` from `cmsy10`, with `cmmi10`, `cmsy10` and `cmex10` glyphs embedded as Type1 outlines), `\left...\right` delimiter selection through CMEX size variants using TeX's delimiterfactor and shortfall, accents and a display-list painter; display formulas wider than the measure are split at top-level binary/relation operators into multiple lines (an approximation of TeX's `\split` behaviour; `align`/`align*` displays share column widths and number each row, while `gather`/`gather*` centre every row); CMEX delimiter size variants back `\big`/`\Big`/`\bigg`/`\Bigg`; inter-atom spacing uses TeX's full atom-class table with binary-operator normalisation, with `1mu` = `1/18em` (a thin space is 3mu = 1.67pt at 10pt); `\mid` is a relation while `\colon` is punctuation; `\mskip`, `\mkern`, `\mspace`, `\hskip`, `\kern` and `\hspace` scan TeX dimensions (`mu`, `pt`, `em`, ...) and contribute their natural width, accepting `plus`/`minus` parts even though math boxes are not glue lists; route-D numbers `equation` environments and resolves `\eqref`/`\ref` through their labels; `\tag` overrides the number and `\notag`/`\nonumber` suppress it; math italic letters are embedded as Computer Modern Type1 outlines (`cmmi10`), and math alphabets map `\\mathbf`/`\\mathit`/`\\mathsf`/`\\mathtt` onto the bold, math-italic, sans and mono faces with their TFMs and `\\mathcal` onto the cmsy10 calligraphic capitals; `\mathfrak` maps onto the bundled eufm10 Fraktur letters (embedded as Type1 outlines); infix fractions `\over`, `\atop`, `\choose`, `\brace`, `\brack` and their `withdelims` forms build fractions from the current row, with the bar only for the `\over` forms; `\middle` delimiters are sized with their enclosing `\left`/`\right` group and `\big`/`\Big`/`\bigg`/`\Bigg` paint at their selected CMEX size |
| M5 | NFSS/TFM metrics, CM/Latin Modern | **partial**: paragraph-level NFSS declarations and inline run composition over the built-in Roman/Bold/Italic/BoldItalic/Mono/MonoItalic/Sans/SansBold/SansItalic/SmallCaps/Slanted/BoldSlanted faces (CM has no sans bold-italic, so `cmss/bx/it` substitutes `cmss/bx/n`; `\scshape` selects cmcsc10 and a bold small caps request falls back to cmbx10; `\slshape` uses the slanted cmsl10 rather than the italic cmti10 and `\ttfamily\itshape` reaches cmitt10), per-face Computer Modern TFM metrics, and Type1 (PFB) outline embedding for every built-in face plus `cmmi10` math italics, `cmsy10` math symbols and `cmex10` big operators, with Liberation subsets used only as a fallback for characters outside the Type1 encodings; full NFSS family/shape state and Type1 coverage for arbitrary Unicode remain open |
| M5 | NFSS/TFM metrics, CM/Latin Modern | **partial**: paragraph-level NFSS declarations and inline run composition over the built-in Roman/Bold/Italic/BoldItalic/Mono/MonoItalic/Sans/SansBold/SansItalic/SmallCaps/Slanted/BoldSlanted faces (CM has no sans bold-italic, so `cmss/bx/it` substitutes `cmss/bx/n`; `\scshape` selects cmcsc10 and a bold small caps request falls back to cmbx10; `\slshape` uses the slanted cmsl10 rather than the italic cmti10 and `\ttfamily\itshape` reaches cmitt10), per-face Computer Modern TFM metrics, and Type1 (PFB) outline embedding for every built-in face plus `cmmi10` math italics, `cmsy10` math symbols and `cmex10` big operators, with Liberation subsets used only as a fallback for characters outside the Type1 encodings; paragraph base sizes from `\fontsize` and the article size commands scale glyph metrics and the default interline glue while the measure and authored skips stay absolute; full NFSS family/shape state and Type1 coverage for arbitrary Unicode remain open |
| M6 | class/package execution (`article`, `sn-jnl`) | Overleaf page-count parity |
| M7 | `\special`, PDF XObjects, hyperref annotations | PDF structure parity |
@@ -353,7 +353,7 @@ M3 painter: `Page::display_list()` and `Halign::display_list()` produce absolute
PDF writer: `crates/texrra-tex-core/src/pdf.rs` writes multi-page PDF 1.4 with five embedded Liberation Type0/CID faces (Identity-H + ToUnicode + `/W` arrays), filled rectangles, diagonal rules, raw-RGB `/XObject` images, `/Annots` URI links and arbitrary `/special` operators. Ligature substitution and line-end italic correction are implemented; full NFSS family switching remains open.
M5 (partial): display-list text carries `FontFace::{Roman,Bold,Italic,BoldItalic,Mono,MonoItalic,Sans,SansBold,SansItalic,SmallCaps,Slanted,BoldSlanted}` plus the math faces. Roman/Bold/Italic/BoldItalic/Mono text are painted with embedded Liberation Type0/CID fonts, each with a ToUnicode CMap and `/W` width array. `cmr10.tfm` is parsed at runtime for widths, heights/depths, kern pairs and ff/fi/fl/ffi/ffl ligatures; line-end and math-script italic corrections and monospace/sans paragraph faces are applied; paragraph-level NFSS declarations (`\rmfamily`, `\sffamily`, `\ttfamily`, `\bfseries`, `\itshape`, `\texttt`, `\textsf`) select those faces and the `\fontfamily`/`\fontseries`/`\fontshape`/`\fontencoding`/`\selectfont` command forms plus legacy `\rm`/`\sf`/`\tt`/`\bf`/`\it`/`\sl`/`\up`/`\normalfont` declarations are parsed; inline `\textbf`/`\emph`/`\textit`/`\texttt`/`\textsf` groups and `{\bfseries ...}` declaration groups (including nesting) split a paragraph into styled runs, each shaped by its own TFM and painted with its own face; nested faces compose relatively (`\emph` inside bold yields bold italic via cmbxti10, `\emph` inside italic returns upright, `\sffamily\bfseries` yields cmssbx10 and `\sffamily\itshape` cmssi10, while bold-italic sans falls back to cmssbx10 as TeX's OT1 substitution does; `\scshape`/`\textsc` select cmcsc10, with the last shape command winning and bold small caps substituting cmbx10; `\slshape`/`\textsl` select cmsl10 (or cmbxsl10 with a bold series) instead of the italic cmti10, and `\ttfamily\itshape` selects cmitt10; declarations such as `\bfseries` also switch the face for the rest of their group, and `\em` toggles emphasis relative to the current run); styled runs are stored on the paragraph unit, so incremental edits rebuild them through `Engine::edit_runs` instead of flattening the paragraph back to one face; true family/series/shape switching remains open; route-D PDFs now embed all twelve Knuth Computer Modern Type1 programs (cmr10, cmbx10, cmti10, cmbxti10, cmtt10, cmss10, cmssbx10, cmssi10, cmcsc10, cmsl10, cmbxsl10, cmitt10) as simple fonts (PFB `Length1/2/3`, `/Encoding /Differences` from each program's built-in encoding, `/Widths` in 1000-unit text space from that face's TFM advances) whenever the program covers every character of that face on the page, and fall back per face to the Liberation Type0 subset otherwise; `pdffonts` reports `Type 1` faces (CMR10, CMBX10, ...) and `pdftotext` still extracts the text. `Unit::paragraph` now builds its item stream with `layout_paragraph_with_font`, so CMR10 advances, kerns and ligatures drive paragraph widths; each glyph box also carries the TFM height/depth, and the painter emits 10pt glyphs and the Type0 `/W` array reports CMR10 advances, and ligature boxes paint their component letters, so `pdftotext` keeps word boundaries instead of inserting spaces between letters.
M5 (partial): display-list text carries `FontFace::{Roman,Bold,Italic,BoldItalic,Mono,MonoItalic,Sans,SansBold,SansItalic,SmallCaps,Slanted,BoldSlanted}` plus the math faces. Roman/Bold/Italic/BoldItalic/Mono text are painted with embedded Liberation Type0/CID fonts, each with a ToUnicode CMap and `/W` width array. `cmr10.tfm` is parsed at runtime for widths, heights/depths, kern pairs and ff/fi/fl/ffi/ffl ligatures; line-end and math-script italic corrections and monospace/sans paragraph faces are applied; paragraph-level NFSS declarations (`\rmfamily`, `\sffamily`, `\ttfamily`, `\bfseries`, `\itshape`, `\texttt`, `\textsf`) select those faces and the `\fontfamily`/`\fontseries`/`\fontshape`/`\fontencoding`/`\selectfont` command forms plus legacy `\rm`/`\sf`/`\tt`/`\bf`/`\it`/`\sl`/`\up`/`\normalfont` declarations are parsed; inline `\textbf`/`\emph`/`\textit`/`\texttt`/`\textsf` groups and `{\bfseries ...}` declaration groups (including nesting) split a paragraph into styled runs, each shaped by its own TFM and painted with its own face; nested faces compose relatively (`\emph` inside bold yields bold italic via cmbxti10, `\emph` inside italic returns upright, `\sffamily\bfseries` yields cmssbx10 and `\sffamily\itshape` cmssi10, while bold-italic sans falls back to cmssbx10 as TeX's OT1 substitution does; `\scshape`/`\textsc` select cmcsc10, with the last shape command winning and bold small caps substituting cmbx10; `\slshape`/`\textsl` select cmsl10 (or cmbxsl10 with a bold series) instead of the italic cmti10, and `\ttfamily\itshape` selects cmitt10; declarations such as `\bfseries` also switch the face for the rest of their group, and `\em` toggles emphasis relative to the current run); styled runs are stored on the paragraph unit, so incremental edits rebuild them through `Engine::edit_runs` instead of flattening the paragraph back to one face; true family/series/shape switching remains open; route-D PDFs now embed all twelve Knuth Computer Modern Type1 programs (cmr10, cmbx10, cmti10, cmbxti10, cmtt10, cmss10, cmssbx10, cmssi10, cmcsc10, cmsl10, cmbxsl10, cmitt10) as simple fonts (PFB `Length1/2/3`, `/Encoding /Differences` from each program's built-in encoding, `/Widths` in 1000-unit text space from that face's TFM advances) whenever the program covers every character of that face on the page, and fall back per face to the Liberation Type0 subset otherwise; `pdffonts` reports `Type 1` faces (CMR10, CMBX10, ...) and `pdftotext` still extracts the text. `Unit::paragraph` now builds its item stream with `layout_paragraph_with_font`, so CMR10 advances, kerns and ligatures drive paragraph widths; each glyph box also carries the TFM height/depth, and the painter emits glyphs at the paragraph's base size (`\fontsize` and `\tiny`...`\Huge` scale the shaped metrics and default interline glue, while `\hsize`, `\parindent` and authored skips stay absolute) and the Type0 `/W` array reports CMR10 advances, and ligature boxes paint their component letters, so `pdftotext` keeps word boundaries instead of inserting spaces between letters.
M6 (partial): `DisplayItem::Image` becomes a PDF XObject; `DisplayItem::Link` becomes `/Annots /Subtype /Link /URI`; `DisplayItem::Special` injects raw content-stream operators. SVG previews show images as grey rectangles and specials as comments.
@@ -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`, `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. `Engine::edit` preserves the face when reflowing an edited paragraph.
The crate currently has 395 unit tests plus eight route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 589 tests (399 route-D unit, 44 engine binary unit, 8 route-D integration, 35 oracle, 71 v1 integration, 27 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path.
The crate currently has 401 unit tests plus eight route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 594 tests (401 route-D unit, 47 engine binary unit, 8 route-D integration, 35 oracle, 71 v1 integration, 27 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path.
### M0 incremental demo
+91 -6
View File
@@ -11,9 +11,7 @@ use std::sync::{Mutex, OnceLock};
use texrra_tex_core::cmr10::Cmr10Metrics;
use texrra_tex_core::math::{AlignedRow, MathAtom, parse_math, split_math_lines};
use texrra_tex_core::pdf::{
PageOrigin, display_lists_to_pdf_with_cm_type1, display_lists_to_pdf_with_paper,
};
use texrra_tex_core::pdf::{PageOrigin, display_lists_to_pdf_with_cm_type1};
use texrra_tex_core::{Document, Engine, ParagraphFont, ParagraphStyle, Unit};
const SCALE: i64 = 65_536;
@@ -654,6 +652,7 @@ struct SourceParagraph {
equation_rows: Vec<EquationRow>,
/// Whether the rows are centred (`gather`) rather than column-aligned.
align_centered: bool,
font_size: Option<i64>,
}
/// One row of an `align`/`gather` environment.
@@ -730,6 +729,7 @@ fn paragraphs(source: &str) -> Result<Vec<SourceParagraph>, String> {
equation_tag: None,
equation_rows: Vec::new(),
align_centered: false,
font_size: None,
});
pending = (0, 0, 0);
pending_break = false;
@@ -887,6 +887,7 @@ fn parse_blocks_raw(raw: &str) -> Vec<SourceParagraph> {
equation_tag: None,
equation_rows: Vec::new(),
align_centered: false,
font_size: None,
}
})
.collect();
@@ -916,6 +917,7 @@ fn parse_blocks_raw(raw: &str) -> Vec<SourceParagraph> {
equation_tag: None,
equation_rows: Vec::new(),
align_centered: false,
font_size: None,
}];
}
}
@@ -954,6 +956,7 @@ fn parse_blocks_raw(raw: &str) -> Vec<SourceParagraph> {
equation_tag: None,
equation_rows: Vec::new(),
align_centered: false,
font_size: None,
}
})
.collect();
@@ -1030,7 +1033,56 @@ fn nfss_declaration<'a>(text: &'a str, command: &str) -> Option<&'a str> {
Some(rest)
}
/// TeX size commands with the article-class 10pt point size values.
const SIZE_COMMANDS: [(&str, f64); 10] = [
("\\tiny", 5.0),
("\\scriptsize", 7.0),
("\\footnotesize", 8.0),
("\\small", 9.0),
("\\normalsize", 10.0),
("\\large", 12.0),
("\\Large", 14.4),
("\\LARGE", 17.28),
("\\huge", 20.74),
("\\Huge", 24.88),
];
/// Scan a size declaration such as `\large` or
/// `\fontsize{14pt}{18pt}\selectfont`, returning the size and the rest.
fn font_size_command(rest: &str) -> Option<(i64, &str)> {
for (command, points) in SIZE_COMMANDS {
if let Some(after) = nfss_declaration(rest, command) {
return Some(((points * 65_536.0).round() as i64, after));
}
}
let after = rest.strip_prefix("\\fontsize")?;
if after
.chars()
.next()
.is_some_and(|character| character.is_ascii_alphabetic())
{
return None;
}
let after = after.trim_start();
let (size_text, length) = braced_group(after)?;
let size = parse_dimension(size_text.trim())?;
let after = after[length..].trim_start();
let (_, length) = braced_group(after)?;
let mut after = after[length..].trim_start();
if let Some(rest) = after.strip_prefix("\\selectfont") {
after = rest;
}
Some((size, after))
}
fn nfss_font(raw: &str, base: ParagraphFont) -> Option<(ParagraphFont, String)> {
nfss_font_with_size(raw, base).map(|(font, _, body)| (font, body))
}
fn nfss_font_with_size(
raw: &str,
base: ParagraphFont,
) -> Option<(ParagraphFont, Option<i64>, String)> {
let (mut family, mut bold, mut italic) = match base {
ParagraphFont::Roman => (Family::Roman, false, false),
ParagraphFont::Bold => (Family::Roman, true, false),
@@ -1047,10 +1099,14 @@ fn nfss_font(raw: &str, base: ParagraphFont) -> Option<(ParagraphFont, String)>
};
let mut small_caps = base == ParagraphFont::SmallCaps;
let mut slanted = matches!(base, ParagraphFont::Slanted | ParagraphFont::BoldSlanted);
let mut font_size: Option<i64> = None;
let mut text = raw.trim_start();
let mut consumed = false;
loop {
if let Some((name, rest)) = nfss_braced(text, "\\fontfamily") {
if let Some((size, rest)) = font_size_command(text) {
font_size = Some(size);
text = rest;
} else if let Some((name, rest)) = nfss_braced(text, "\\fontfamily") {
family = nfss_family_name(&name);
text = rest;
} else if let Some((name, rest)) = nfss_braced(text, "\\fontseries") {
@@ -1202,7 +1258,7 @@ fn nfss_font(raw: &str, base: ParagraphFont) -> Option<(ParagraphFont, String)>
}
}
};
Some((font, text.to_string()))
Some((font, font_size, text.to_string()))
}
/// Split a paragraph containing inline style commands into styled runs.
@@ -1389,13 +1445,15 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
equation_tag: None,
equation_rows: rows,
align_centered: centered,
font_size: None,
};
}
}
if let Some((font, body)) = nfss_font(raw, ParagraphFont::Roman) {
if let Some((font, font_size, body)) = nfss_font_with_size(raw, ParagraphFont::Roman) {
return SourceParagraph {
text: body,
font,
font_size,
line_height: 12,
math: false,
left_skip: 0,
@@ -1431,6 +1489,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
equation_tag: None,
equation_rows: Vec::new(),
align_centered: false,
font_size: None,
};
}
if let Some(inner) = raw
@@ -1453,6 +1512,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
equation_tag: None,
equation_rows: Vec::new(),
align_centered: false,
font_size: None,
};
}
if let Some(math) = raw
@@ -1479,6 +1539,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
equation_tag: None,
equation_rows: Vec::new(),
align_centered: false,
font_size: None,
};
}
let candidates = [
@@ -1506,6 +1567,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
equation_tag: None,
equation_rows: Vec::new(),
align_centered: false,
font_size: None,
};
}
}
@@ -1525,6 +1587,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
equation_tag: None,
equation_rows: Vec::new(),
align_centered: false,
font_size: None,
}
}
@@ -1646,6 +1709,7 @@ fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Do
} else {
paragraph.line_height * SCALE
},
font_size: paragraph.font_size.unwrap_or(655_360),
char_width: 10 * SCALE,
space_width: 4 * SCALE,
space_stretch: 6 * SCALE,
@@ -1764,6 +1828,26 @@ mod tests {
);
}
#[test]
fn size_commands_set_the_paragraph_font_size() {
let (body, geometry) = geometry_and_body("\\large Big text");
let paragraphs = paragraphs(&body).unwrap();
let document = build_document(&paragraphs, &geometry);
let unit = &document.units[0];
assert_eq!(unit.paragraph_style.as_ref().unwrap().font_size, 12 * SCALE);
assert_eq!(unit.source, "Big text");
}
#[test]
fn fontsize_sets_the_exact_paragraph_size() {
let (body, geometry) = geometry_and_body("\\fontsize{20pt}{24pt}\\selectfont Huge text");
let paragraphs = paragraphs(&body).unwrap();
let document = build_document(&paragraphs, &geometry);
let unit = &document.units[0];
assert_eq!(unit.paragraph_style.as_ref().unwrap().font_size, 20 * SCALE);
assert_eq!(unit.source, "Huge text");
}
#[test]
fn engine_template_keeps_paragraph_columns() {
assert_eq!(engine_template("{|l|c|p{3cm}|}"), "lcp{3cm}");
@@ -2522,6 +2606,7 @@ mod inline_tests {
assert_eq!(runs, vec![(ParagraphFont::Bold, "a b c".to_string())]);
}
#[test]
fn styled_runs_paint_with_their_face() {
let document = Document::new(
550 * 65_536,