diff --git a/README.md b/README.md index 0514044..0533e6d 100644 --- a/README.md +++ b/README.md @@ -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. Paragraph base sizes come from `\fontsize{}{}` 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 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{}{}` 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. The class options `10pt`/`11pt`/`12pt` on `\documentclass[...]` set the default base size (and article `\baselineskip` of 12pt/13.6pt/14.5pt); a size command inside a paragraph still overrides the class default. 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. diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index 13414ea..e477a0c 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`). 594 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 597 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 85deec3..52e225f 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -133,7 +133,7 @@ and justification. | 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; 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 | +| M6 | class/package execution (`article`, `sn-jnl`) | **partial**: `\documentclass[...]` options are read and the article `10pt`/`11pt`/`12pt` base size sets the default paragraph font size and `\baselineskip` (13.6pt/14.5pt); executing the class file itself and package code remains open | | M7 | `\special`, PDF XObjects, hyperref annotations | PDF structure parity | ## Current limits @@ -332,7 +332,7 @@ for a later overlaid slash. | M3 halign | partial | natural columns, spans, omit, hline rows, templates, noalign skip, rules; no PDF painter | | M4 math | partial | atoms, scripts, fractions (including infix `\over`/`\atop`/`\choose`), roots, delimiters, accents, operators, classes, braces, boxed, negated, math alphabets (incl. `\mathcal`, `\mathbb` and `\mathfrak`), `align`/`gather` rows with per-row tags; no math painter/shrink wrapping | | M5 NFSS/TFM | partial | runtime `cmr10.tfm` widths/heights/depths/kern pairs and ff/fi/fl/ffi/ffl ligatures; text faces embed Liberation Serif/Mono as Type0 CID fonts with Identity-H, ToUnicode and width arrays; used faces embed per-document TrueType glyf subsets that keep the original glyph IDs, include composite components, and carry a matching ToUnicode CMap; ASCII documents use the compact tier; no Base-14 dependency; SVG carries family/weight/style; route-D PDFs embed Knuth's Computer Modern Type1 programs (cmr10/cmbx10/cmti10/cmbxti10/cmtt10/cmss10/cmssbx10/cmssi10/cmcsc10/cmsl10/cmbxsl10/cmitt10) as `/Subtype /Type1` fonts with `/FontFile` (`Length1/2/3`), `/Encoding /Differences` and TFM `/Widths`, falling back per face to Liberation when the program does not encode every character | -| M6 specials/XObject | partial | raw specials, RGB image XObjects, URI link annotations; class/package execution absent | +| M6 specials/XObject | partial | raw specials, RGB image XObjects, URI link annotations; route-D reads `\documentclass` size options (10/11/12pt) into the paragraph base size and `\baselineskip`; executing class or package code remains absent | | M7 incremental integration | partial | route-D preview/PDF/edit endpoints plus opt-in `?engine=route-d` project preview, content-based page hashes and section/emphasis/display-math/itemize/enumerate/description/quote/center/flushright mapping; editor toggle in `texrra-web`; inline math pending | v1 remains the production renderer; the route-D core is additive and tested independently. @@ -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 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. +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 597 tests (401 route-D unit, 50 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 diff --git a/src/route_d.rs b/src/route_d.rs index 9e456ba..8303277 100755 --- a/src/route_d.rs +++ b/src/route_d.rs @@ -139,6 +139,8 @@ struct PageGeometry { line_penalty: Option, adj_demerits: Option, space_factor_codes: Vec<(char, i64)>, + /// Base font size from `\documentclass[11pt]`-style options. + base_font_size: Option, /// Captured `tabular` environments: (column spec, halign source). tabular: Vec<(String, String)>, } @@ -147,6 +149,34 @@ struct PageGeometry { /// `\textheight` assignments out of the source and return the remaining body. /// Each command takes a TeX dimension. LaTeX resets `\vsize` from /// `\textheight` at every page, so `\textheight` wins when both appear. +/// Read the base font size from a class option list such as +/// `\documentclass[11pt,a4paper]{article}`. +fn document_class_size(line: &str) -> Option { + let rest = line.strip_prefix("\\documentclass")?.trim_start(); + let rest = rest.strip_prefix('[')?; + let end = rest.find(']')?; + for option in rest[..end].split(',') { + match option.trim() { + "10pt" => return Some(10 * SCALE), + "11pt" => return Some(11 * SCALE), + "12pt" => return Some(12 * SCALE), + _ => {} + } + } + None +} + +/// LaTeX's article class sets `\baselineskip` from the base size. +fn class_baselineskip(font_size: i64) -> i64 { + if font_size >= 12 * 65_536 { + 14 * 65_536 + 32_768 + } else if font_size >= 11 * 65_536 { + 13 * 65_536 + 39_322 + } else { + 12 * 65_536 + } +} + fn strip_page_geometry(source: &str) -> (String, PageGeometry) { let mut geometry = PageGeometry::default(); let mut body = String::new(); @@ -175,6 +205,10 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) { } continue; } + if trimmed.starts_with("\\documentclass") { + geometry.base_font_size = document_class_size(trimmed); + continue; + } if let Some(value) = dimension_assignment(trimmed, "hoffset") { geometry.origin.h_offset = value; } else if let Some(value) = dimension_assignment(trimmed, "voffset") { @@ -1668,6 +1702,13 @@ fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Do unit.space_shrink = paragraph.space_shrink; return unit; } + let base_font_size = paragraph + .font_size + .or(geometry.base_font_size) + .unwrap_or(655_360); + let baselineskip = geometry + .baseline_skip + .unwrap_or_else(|| class_baselineskip(base_font_size)); let style = ParagraphStyle { line_width: 480 * SCALE, left_skip: paragraph.left_skip * SCALE + geometry.left_skip.unwrap_or(0), @@ -1690,7 +1731,7 @@ fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Do par_fillskip_fil: geometry.par_fillskip.map(|(_, _, fil)| fil).unwrap_or(true), frenchspacing: geometry.french_spacing.unwrap_or(false), space_factor_codes: geometry.space_factor_codes.clone(), - baselineskip: geometry.baseline_skip.unwrap_or(12 * 65536), + baselineskip, lineskip: geometry.lineskip.unwrap_or(65536), lineskiplimit: geometry.lineskiplimit.unwrap_or(0), par_indent: geometry.par_indent.unwrap_or(0), @@ -1705,11 +1746,11 @@ fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Do adj_demerits: geometry.adj_demerits.unwrap_or(10_000), hyphenation_exceptions: geometry.hyphenation_exceptions.clone(), line_height: if paragraph.line_height == 12 { - geometry.baseline_skip.unwrap_or(12 * 65536) + baselineskip } else { paragraph.line_height * SCALE }, - font_size: paragraph.font_size.unwrap_or(655_360), + font_size: base_font_size, char_width: 10 * SCALE, space_width: 4 * SCALE, space_stretch: 6 * SCALE, @@ -1848,6 +1889,40 @@ mod tests { assert_eq!(unit.source, "Huge text"); } + #[test] + fn documentclass_size_options_set_the_base_size() { + let source = + "\\documentclass[12pt]{article}\n\\begin{document}\n\nPlain text\n\n\\end{document}"; + let (body, geometry) = geometry_and_body(source); + assert_eq!(geometry.base_font_size, Some(12 * SCALE)); + let paragraphs = paragraphs(&body).unwrap(); + let document = build_document(¶graphs, &geometry); + let style = document.units[0].paragraph_style.as_ref().unwrap(); + assert_eq!(style.font_size, 12 * SCALE); + assert_eq!(style.baselineskip, 14 * 65_536 + 32_768); + } + + #[test] + fn explicit_size_commands_override_the_class_size() { + let source = "\\documentclass[12pt]{article}\n\\begin{document}\n\n\\small Small text\n\n\\end{document}"; + let (body, geometry) = geometry_and_body(source); + let paragraphs = paragraphs(&body).unwrap(); + let document = build_document(¶graphs, &geometry); + let style = document.units[0].paragraph_style.as_ref().unwrap(); + assert_eq!(style.font_size, 9 * SCALE); + } + + #[test] + fn documentclass_defaults_to_ten_point() { + let source = "\\documentclass{article}\n\\begin{document}\n\nPlain text\n\n\\end{document}"; + let (body, geometry) = geometry_and_body(source); + let paragraphs = paragraphs(&body).unwrap(); + let document = build_document(¶graphs, &geometry); + let style = document.units[0].paragraph_style.as_ref().unwrap(); + assert_eq!(style.font_size, 10 * SCALE); + assert_eq!(style.baselineskip, 12 * 65_536); + } + #[test] fn engine_template_keeps_paragraph_columns() { assert_eq!(engine_template("{|l|c|p{3cm}|}"), "lcp{3cm}");