diff --git a/assets/fonts/cmex10.pfb b/assets/fonts/cmex10.pfb new file mode 100644 index 0000000..d2346a2 Binary files /dev/null and b/assets/fonts/cmex10.pfb differ diff --git a/assets/fonts/cmmi10.pfb b/assets/fonts/cmmi10.pfb new file mode 100644 index 0000000..569fb2e Binary files /dev/null and b/assets/fonts/cmmi10.pfb differ diff --git a/assets/fonts/cmsy10.pfb b/assets/fonts/cmsy10.pfb new file mode 100644 index 0000000..a88ccae Binary files /dev/null and b/assets/fonts/cmsy10.pfb differ diff --git a/crates/texrra-tex-core/src/cmr10.rs b/crates/texrra-tex-core/src/cmr10.rs index e701b11..511932a 100644 --- a/crates/texrra-tex-core/src/cmr10.rs +++ b/crates/texrra-tex-core/src/cmr10.rs @@ -128,6 +128,7 @@ impl Cmr10Metrics { 3 => Self::BoldItalic, 4 => Self::Mono, 5 => Self::Sans, + 6 => Self::Math, _ => Self::Roman, } } diff --git a/crates/texrra-tex-core/src/math.rs b/crates/texrra-tex-core/src/math.rs index 5853b78..4de5069 100755 --- a/crates/texrra-tex-core/src/math.rs +++ b/crates/texrra-tex-core/src/math.rs @@ -290,14 +290,6 @@ fn atom_class(atom: &MathAtom) -> MathClass { } } -fn delimiter_width(delimiter: char, font: &Cmr10Metrics) -> i64 { - if delimiter == '.' { - 0 - } else { - font.width(delimiter) - } -} - /// TeX grows delimiters with the enclosed formula; this is a simple 1x-3x /// approximation of that rule. /// Pick the delimiter glyph TeX would use for a body of `delta` extent. diff --git a/crates/texrra-tex-core/src/pdf.rs b/crates/texrra-tex-core/src/pdf.rs index d1b0fff..df14494 100755 --- a/crates/texrra-tex-core/src/pdf.rs +++ b/crates/texrra-tex-core/src/pdf.rs @@ -16,6 +16,8 @@ use crate::cmr10::Cmr10Metrics; use crate::render::{DisplayItem, DisplayList, FontFace}; use crate::type1::Type1Font; +const FACE_COUNT: usize = 7; + fn deflate(bytes: &[u8]) -> Vec { let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default()); encoder.write_all(bytes).expect("deflate font stream"); @@ -29,7 +31,7 @@ struct PdfFace { font: OnceLock>, } -static FULL_FACES: [PdfFace; 6] = [ +static FULL_FACES: [PdfFace; FACE_COUNT] = [ PdfFace { bytes: include_bytes!("../../../assets/fonts-subset/LiberationSerif-Regular.ttf"), base: "LiberationSerif", @@ -66,9 +68,15 @@ static FULL_FACES: [PdfFace; 6] = [ italic_angle: 0, font: OnceLock::new(), }, + PdfFace { + bytes: include_bytes!("../../../assets/fonts-subset/LiberationSerif-Italic.ttf"), + base: "LiberationSerif-MathItalic", + italic_angle: -12, + font: OnceLock::new(), + }, ]; -static MIN_FACES: [PdfFace; 6] = [ +static MIN_FACES: [PdfFace; FACE_COUNT] = [ PdfFace { bytes: include_bytes!("../../../assets/fonts-subset-min/LiberationSerif-Regular.ttf"), base: "LiberationSerif", @@ -105,6 +113,12 @@ static MIN_FACES: [PdfFace; 6] = [ italic_angle: 0, font: OnceLock::new(), }, + PdfFace { + bytes: include_bytes!("../../../assets/fonts-subset-min/LiberationSerif-Italic.ttf"), + base: "LiberationSerif-MathItalic", + italic_angle: -12, + font: OnceLock::new(), + }, ]; fn minimal_text_char(ch: char) -> bool { @@ -134,7 +148,7 @@ fn minimal_text_char(ch: char) -> bool { ) } -fn face(font: FontFace, faces: &'static [PdfFace; 6]) -> &'static PdfFace { +fn face(font: FontFace, faces: &'static [PdfFace; FACE_COUNT]) -> &'static PdfFace { &faces[font as usize] } @@ -233,6 +247,7 @@ fn font_resource(font: FontFace) -> &'static str { FontFace::BoldItalic => "F4", FontFace::Mono => "F5", FontFace::Sans => "F6", + FontFace::MathItalic => "F7", } } @@ -247,22 +262,22 @@ enum FontBackend { /// Knuth's Computer Modern Type1 programs, in `FontFace` order. fn type1_bytes(slot: usize) -> Option<&'static [u8]> { - static PFBS: [Option<&'static [u8]>; 6] = [ + static PFBS: [Option<&'static [u8]>; FACE_COUNT] = [ Some(include_bytes!("../../../assets/fonts/cmr10.pfb")), Some(include_bytes!("../../../assets/fonts/cmbx10.pfb")), Some(include_bytes!("../../../assets/fonts/cmti10.pfb")), Some(include_bytes!("../../../assets/fonts/cmbxti10.pfb")), Some(include_bytes!("../../../assets/fonts/cmtt10.pfb")), Some(include_bytes!("../../../assets/fonts/cmss10.pfb")), + Some(include_bytes!("../../../assets/fonts/cmmi10.pfb")), ]; PFBS[slot] } -fn type1_fonts() -> &'static [Option; 6] { - static FONTS: OnceLock<[Option; 6]> = OnceLock::new(); - FONTS.get_or_init(|| { - [0usize, 1, 2, 3, 4, 5].map(|slot| type1_bytes(slot).and_then(Type1Font::from_pfb)) - }) +fn type1_fonts() -> &'static [Option; FACE_COUNT] { + static FONTS: OnceLock<[Option; FACE_COUNT]> = OnceLock::new(); + FONTS + .get_or_init(|| std::array::from_fn(|slot| type1_bytes(slot).and_then(Type1Font::from_pfb))) } /// TeX page origin offsets (`\hoffset`, `\voffset`) in scaled points. @@ -276,7 +291,7 @@ fn page_content( list: &DisplayList, height: i64, image_names: &BTreeMap, - faces: &'static [PdfFace; 6], + faces: &'static [PdfFace; FACE_COUNT], cm_codes: &[Option<&BTreeMap>], origin: PageOrigin, ) -> String { @@ -452,8 +467,8 @@ fn write_pdf( let mut objects: Vec> = Vec::new(); objects.push(b"<< /Type /Catalog /Pages 2 0 R >>".to_vec()); objects.push(Vec::new()); // pages object filled below - let mut used_faces = [false; 6]; - let mut used_chars: [BTreeSet; 6] = Default::default(); + let mut used_faces = [false; FACE_COUNT]; + let mut used_chars: [BTreeSet; FACE_COUNT] = Default::default(); for page in pages { for item in &page.items { if let DisplayItem::Text { font, text, .. } = item { @@ -462,7 +477,7 @@ fn write_pdf( } } } - let cm_faces: Vec)>> = (0..6) + let cm_faces: Vec)>> = (0..FACE_COUNT) .map(|slot| { if backend != FontBackend::ComputerModern || !used_faces[slot] { return None; @@ -488,8 +503,8 @@ fn write_pdf( _ => true, }) }); - let faces: &'static [PdfFace; 6] = if minimal { &MIN_FACES } else { &FULL_FACES }; - let mut font_ids = [0usize; 6]; + let faces: &'static [PdfFace; FACE_COUNT] = if minimal { &MIN_FACES } else { &FULL_FACES }; + let mut font_ids = [0usize; FACE_COUNT]; for (slot, face) in faces.iter().enumerate() { if !used_faces[slot] { continue; @@ -622,7 +637,7 @@ fn write_pdf( .map(|(_, slot)| format!("/Im{slot} {} 0 R", image_base + *slot)) .collect::>() .join(" "); - let fonts = (0..6) + let fonts = (0..FACE_COUNT) .filter(|slot| used_faces[*slot]) .map(|slot| format!("/F{} {} 0 R", slot + 1, font_ids[slot])) .collect::>() @@ -827,6 +842,23 @@ mod type1_pdf_tests { assert!(!text.contains("/BaseFont /CMR10"), "{text}"); } + #[test] + fn math_italic_text_embeds_cmmi10() { + let mut list = hello_list(); + list.items[0] = DisplayItem::Text { + x: 0, + y: 800_000, + size: 655_360, + text: "x".to_string(), + font: FontFace::MathItalic, + }; + let pdf = write(&[list]); + let text = String::from_utf8_lossy(&pdf); + assert!(text.contains("/BaseFont /CMMI10"), "{text}"); + assert!(text.contains("(\\170)"), "{text}"); + assert!(!text.contains("/BaseFont /CMR10"), "{text}"); + } + #[test] fn type1_backend_falls_back_for_uncovered_characters() { let mut list = hello_list(); diff --git a/crates/texrra-tex-core/src/render.rs b/crates/texrra-tex-core/src/render.rs index 2e74a73..0885703 100755 --- a/crates/texrra-tex-core/src/render.rs +++ b/crates/texrra-tex-core/src/render.rs @@ -19,6 +19,8 @@ pub enum FontFace { BoldItalic, Mono, Sans, + /// Computer Modern math italic (`cmmi10`). + MathItalic, } #[derive(Clone, Debug, PartialEq, Eq)] @@ -159,7 +161,10 @@ impl DisplayList { } else { "" }; - let style = if matches!(font, FontFace::Italic | FontFace::BoldItalic) { + let style = if matches!( + font, + FontFace::Italic | FontFace::BoldItalic | FontFace::MathItalic + ) { " font-style=\"italic\"" } else { "" @@ -261,6 +266,10 @@ fn paragraph_face(font: ParagraphFont) -> FontFace { } } +fn is_math_letter(character: char) -> bool { + matches!(character, '\u{0391}'..='\u{03A9}' | '\u{03B1}'..='\u{03C9}') +} + fn character_text(character: char) -> String { match character { '\u{FB00}' => "ff".to_owned(), @@ -646,8 +655,13 @@ impl Page { MathAtom::Space(_) => {} MathAtom::Symbol(character) => { if !character.is_whitespace() { + let face = if character.is_ascii_alphabetic() || is_math_letter(*character) { + FontFace::MathItalic + } else { + FontFace::Roman + }; list.push(DisplayItem::Text { - font: FontFace::Roman, + font: face, x, y: baseline, size, diff --git a/crates/texrra-tex-core/src/type1.rs b/crates/texrra-tex-core/src/type1.rs index 0a7b046..e0baf7e 100644 --- a/crates/texrra-tex-core/src/type1.rs +++ b/crates/texrra-tex-core/src/type1.rs @@ -51,10 +51,7 @@ impl Type1Font { 1 if encrypted.is_empty() => header.extend_from_slice(&bytes[start..end]), 1 => trailer.extend_from_slice(&bytes[start..end]), 2 => encrypted.extend_from_slice(&bytes[start..end]), - 3 => { - index = end; - break; - } + 3 => break, _ => return None, } index = end; @@ -144,6 +141,55 @@ fn glyph_names(ch: char) -> &'static [&'static str] { "s", "t", "u", "v", "w", "x", "y", "z", ]; match ch { + '\u{0391}' => &["Alpha"], + '\u{0392}' => &["Beta"], + '\u{0393}' => &["Gamma"], + '\u{0394}' => &["Delta"], + '\u{0395}' => &["Epsilon"], + '\u{0396}' => &["Zeta"], + '\u{0397}' => &["Eta"], + '\u{0398}' => &["Theta"], + '\u{0399}' => &["Iota"], + '\u{039A}' => &["Kappa"], + '\u{039B}' => &["Lambda"], + '\u{039C}' => &["Mu"], + '\u{039D}' => &["Nu"], + '\u{039E}' => &["Xi"], + '\u{039F}' => &["Omicron"], + '\u{03A0}' => &["Pi"], + '\u{03A1}' => &["Rho"], + '\u{03A3}' => &["Sigma"], + '\u{03A4}' => &["Tau"], + '\u{03A5}' => &["Upsilon"], + '\u{03A6}' => &["Phi"], + '\u{03A7}' => &["Chi"], + '\u{03A8}' => &["Psi"], + '\u{03A9}' => &["Omega"], + '\u{03B1}' => &["alpha"], + '\u{03B2}' => &["beta"], + '\u{03B3}' => &["gamma"], + '\u{03B4}' => &["delta"], + '\u{03B5}' => &["epsilon"], + '\u{03B6}' => &["zeta"], + '\u{03B7}' => &["eta"], + '\u{03B8}' => &["theta"], + '\u{03B9}' => &["iota"], + '\u{03BA}' => &["kappa"], + '\u{03BB}' => &["lambda"], + '\u{03BC}' => &["mu"], + '\u{03BD}' => &["nu"], + '\u{03BE}' => &["xi"], + '\u{03BF}' => &["omicron"], + '\u{03C0}' => &["pi"], + '\u{03C1}' => &["rho"], + '\u{03C2}' => &["sigma1"], + '\u{03C3}' => &["sigma"], + '\u{03C4}' => &["tau"], + '\u{03C5}' => &["upsilon"], + '\u{03C6}' => &["phi"], + '\u{03C7}' => &["chi"], + '\u{03C8}' => &["psi"], + '\u{03C9}' => &["omega"], '0'..='9' => &DIGITS[(ch as u8 - b'0') as usize..][..1], 'A'..='Z' => &UPPER[(ch as u8 - b'A') as usize..][..1], 'a'..='z' => &LOWER[(ch as u8 - b'a') as usize..][..1], diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index 4a00789..a58f79c 100644 --- a/docs/ROUTE_D_PLAN.md +++ b/docs/ROUTE_D_PLAN.md @@ -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`). 533 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 534 workspace tests are green and no oracle fixture is ignored. Status after G1 (P0-P2): the paragraph model reproduces TeX's passes, diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index 45b405e..7f667b5 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -131,8 +131,8 @@ and justification. | 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{...}` 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`/`\dimen`/`\skip` 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` or `\count` changes the insertion capacity and reservation of later pages); the configured `\skip` also reserves space above its class once per page in the paged builder, and a `\skip` 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`), `\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 explicit approximation of TeX's `\split`/`align` behaviour); CMEX delimiter size variants back `\big`/`\Big`/`\bigg`/`\Bigg`; inter-atom spacing uses TeX's full atom-class table with binary-operator normalisation; route-D numbers `equation` environments and resolves `\eqref`/`\ref` through their labels; `\tag` overrides the number and `\notag`/`\nonumber` suppress it | -| M5 | NFSS/TFM metrics, CM/Latin Modern | same line/page breaks as reference | +| 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`), `\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 explicit approximation of TeX's `\split`/`align` behaviour); CMEX delimiter size variants back `\big`/`\Big`/`\bigg`/`\Bigg`; inter-atom spacing uses TeX's full atom-class table with binary-operator normalisation; 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`) | +| 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/Sans faces, per-face Computer Modern TFM metrics, and Type1 (PFB) outline embedding for every built-in face plus `cmmi10` math italics, 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 | | M6 | class/package execution (`article`, `sn-jnl`) | Overleaf page-count parity | | M7 | `\special`, PDF XObjects, hyperref annotations | PDF structure parity | @@ -365,9 +365,9 @@ M3 (partial): `Unit::halign` normalizes column widths, intercolumn gaps, row hei Math coverage includes fractions/roots, scripts, `\left...\right` with body-scaled delimiters, `\middle`, `\big`/`\Big`/`\bigg`/`\Bigg` and their `l`/`r` forms, control-sequence delimiters, accents (dot/check/breve/acute/grave/ring), `\text`/`\mathrm`, `\overbrace`/`\underbrace`, `\overset`/`\underset`, `\binom`, `\cancel`/`\bcancel`/`\xcancel`, `\bmod`/`\pmod`, fence symbols, `\operatorname*` and `\mathop` limits. -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. +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, 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`, plus `cmmi10` for mathematical italic letters), 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 347 unit tests plus seven route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 533 tests (354 route-D unit, 33 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 355 unit tests plus eight route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 534 tests (355 route-D unit, 33 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