diff --git a/README.md b/README.md index 060b2e3..0aef739 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. 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. The paragraph measure follows `\textwidth`/`\hsize` (or `\setlength{\textwidth}{...}`), and `\setlength` accepts the other supported layout lengths, including a `\parskip` with plus/minus glue. The `geometry` package's `margin`/`hmargin`/`vmargin`/`left`/`right`/`top`/`bottom`/`textwidth`/`textheight` options (or `\geometry{...}`) are applied to the page measure and height; other package code is not executed. Block environments `center`, `flushleft` and `flushright` set the paragraph alignment, and aligned short lines are centring/flushing within the full measure rather than at the natural line width. `\title`, `\author` and `\date` are captured from the preamble, `\today` expands to the current date, and `\maketitle` expands into a centered title block at the article class sizes (using today's date when `\date` is absent and none for `\date{}`). `\section`, `\subsection`, `\subsubsection`, `\paragraph` and `\subparagraph` advance five-level article counters, prefix their titles with the number, and paint bold at `\Large`/`\large`/`\normalsize` (the two deepest levels stay at the base size); starred headings stay unnumbered and an optional `[short]` title is dropped. The `abstract` environment expands into a centered bold heading and a 9pt body, and `\maketitle` joins multiple `\and` authors and turns `\thanks` notes into title footnotes. Section labels resolve `\ref`/`\eqref` to the heading number (standalone `\label` lines attach to the previous heading, unknown references print `??`), `\appendix` restarts sectioning with letter numbers, `\tableofcontents` lists the numbered headings through `\subsubsection`, `\listoffigures`/`\listoftables` reproduce the numbered captions, `verbatim` keeps monospaced source lines, `\href` keeps its link text and paints a PDF `/Link` URI annotation over the label, and `\url` becomes typewriter text, and the `abstract` environment expands to its heading and body. 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. `\footnote{...}` leaves a numbered marker in the paragraph and sets the note as a 9pt page insertion at the bottom of the page that mentions it. A `thebibliography` environment turns its `\bibitem` entries into numbered `[n]` paragraphs, and `\cite{...}` resolves to `[n]`/`[n, m]` (unknown keys print `[?]`). A `figure` environment becomes a float at its `[t]`/`[b]`/`[h]` placement, its `\caption` numbers as `Figure n:` and feeds `\ref`, and `\includegraphics[width=...]` reserves a rule placeholder. `table` environments likewise become floats carrying their captured `tabular` body, with `Table n:` captions that resolve from `\ref`. Table captions sit above the tabular as in LaTeX, figure captions below the graphic, and `\caption*` leaves either unnumbered. Theorem-like environments (`theorem`, `lemma`, `corollary`, `proposition`, `definition`, `example`, `remark`, `proof`) produce a bold numbered heading with an optional `[title]`, italic statements for the theorem group, and unnumbered proofs, with `\label`/`\ref` resolving to the theorem number. `\newtheorem{env}[shared]{Display}`, `\newtheorem{env}{Display}[section]` and `\newtheorem*{env}{Display}` add custom theorem environments: a shared counter numbers the env with its parent, `[section]` scopes numbers to the enclosing section, and the starred form stays unnumbered. In project previews and PDF exports, `\input{...}` and `\include{...}` expand from files in the same project (a missing `.tex` suffix is added), so chapter files render in place; a project's own `.sty`/`.cls` files are inlined for `\usepackage{name}`/`\documentclass{name}` with local `\RequirePackage` dependencies inlined recursively, local base classes named by `\LoadClass`/`\LoadClassWithOptions` inlined the same way, and package/class boilerplate dropped; local class and package files run their `\DeclareOption` code for the options named on `\documentclass[...]` / `\usepackage[...]` (with `\ExecuteOptions` defaults), and unknown paths stay as literal text. Route-D project previews are memoised by a hash of the expanded source (32 entries) and invalidated on edit. `itemize`/`enumerate`/`description` environments nest arbitrarily: bullet labels cycle `•`/`–`/`*`, sub-enumerations use `(a)`, roman and upper-letter labels, description items keep their `[term]` as `term — `, an optional `\item[label]` replaces the generated marker, and each depth adds 12pt of indentation. +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 overrides the class default and keeps its own glyph size in that run. The paragraph measure follows `\textwidth`/`\hsize` (or `\setlength{\textwidth}{...}`), and `\setlength` accepts the other supported layout lengths, including a `\parskip` with plus/minus glue. The `geometry` package's `margin`/`hmargin`/`vmargin`/`left`/`right`/`top`/`bottom`/`textwidth`/`textheight` options (or `\geometry{...}`) are applied to the page measure and height; other package code is not executed. Block environments `center`, `flushleft` and `flushright` set the paragraph alignment, and aligned short lines are centring/flushing within the full measure rather than at the natural line width. `\title`, `\author` and `\date` are captured from the preamble, `\today` expands to the current date, and `\maketitle` expands into a centered title block at the article class sizes (using today's date when `\date` is absent and none for `\date{}`). `\section`, `\subsection`, `\subsubsection`, `\paragraph` and `\subparagraph` advance five-level article counters, prefix their titles with the number, and paint bold at `\Large`/`\large`/`\normalsize` (the two deepest levels stay at the base size); starred headings stay unnumbered and an optional `[short]` title is dropped. The `abstract` environment expands into a centered bold heading and a 9pt body, and `\maketitle` joins multiple `\and` authors and turns `\thanks` notes into title footnotes. Section labels resolve `\ref`/`\eqref` to the heading number (standalone `\label` lines attach to the previous heading, unknown references print `??`), `\appendix` restarts sectioning with letter numbers, `\tableofcontents` lists the numbered headings through `\subsubsection`, `\listoffigures`/`\listoftables` reproduce the numbered captions, `verbatim` keeps monospaced source lines, `\href` keeps its link text and paints a PDF `/Link` URI annotation over the label, and `\url` becomes typewriter text, and the `abstract` environment expands to its heading and body. 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. `\footnote{...}` leaves a numbered marker in the paragraph and sets the note as a 9pt page insertion at the bottom of the page that mentions it. A `thebibliography` environment turns its `\bibitem` entries into numbered `[n]` paragraphs, and `\cite{...}` resolves to `[n]`/`[n, m]` (unknown keys print `[?]`). A `figure` environment becomes a float at its `[t]`/`[b]`/`[h]` placement, its `\caption` numbers as `Figure n:` and feeds `\ref`, and `\includegraphics[width=...]` reserves a rule placeholder. `table` environments likewise become floats carrying their captured `tabular` body, with `Table n:` captions that resolve from `\ref`. Table captions sit above the tabular as in LaTeX, figure captions below the graphic, and `\caption*` leaves either unnumbered. Theorem-like environments (`theorem`, `lemma`, `corollary`, `proposition`, `definition`, `example`, `remark`, `proof`) produce a bold numbered heading with an optional `[title]`, italic statements for the theorem group, and unnumbered proofs, with `\label`/`\ref` resolving to the theorem number. `\newtheorem{env}[shared]{Display}`, `\newtheorem{env}{Display}[section]` and `\newtheorem*{env}{Display}` add custom theorem environments: a shared counter numbers the env with its parent, `[section]` scopes numbers to the enclosing section, and the starred form stays unnumbered. In project previews and PDF exports, `\input{...}` and `\include{...}` expand from files in the same project (a missing `.tex` suffix is added), so chapter files render in place; a project's own `.sty`/`.cls` files are inlined for `\usepackage{name}`/`\documentclass{name}` with local `\RequirePackage` dependencies inlined recursively, local base classes named by `\LoadClass`/`\LoadClassWithOptions` inlined the same way, and package/class boilerplate dropped; local class and package files run their `\DeclareOption` code for the options named on `\documentclass[...]` / `\usepackage[...]` (with `\ExecuteOptions` defaults), and unknown paths stay as literal text. Route-D project previews are memoised by a hash of the expanded source (32 entries) and invalidated on edit. `itemize`/`enumerate`/`description` environments nest arbitrarily: bullet labels cycle `•`/`–`/`*`, sub-enumerations use `(a)`, roman and upper-letter labels, description items keep their `[term]` as `term — `, an optional `\item[label]` replaces the generated marker, and each depth adds 12pt of indentation. Inline `$...$` and `\(...\)` math is laid out inside 10pt paragraphs (larger sizes keep the delimiters literal). `\newcommand`/`\renewcommand` definitions are captured from the preamble and expanded textually, including numbered arguments; TeX's `\def` parameter texts and `\let` aliases are executed the same way, and `\newenvironment` definitions wrap their bodies with the declared begin/end material. `\newif` flags select between `\if...\else...\fi` branches, with assignments honoured in the preamble or the body, so class conditionals like `\ifdraft` work. diff --git a/crates/texrra-tex-core/src/paragraph.rs b/crates/texrra-tex-core/src/paragraph.rs index 4d2bfad..a42c1ae 100755 --- a/crates/texrra-tex-core/src/paragraph.rs +++ b/crates/texrra-tex-core/src/paragraph.rs @@ -20,12 +20,17 @@ pub struct HorizontalBox { /// Link target when this glyph came from `\href`. #[serde(default)] pub link: Option, + /// Explicit glyph size in scaled points for a sized run. + #[serde(default)] + pub size: Option, } /// A run of paragraph material: text in one face or an inline formula. #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum InlineSegment { Text(ParagraphFont, String), + /// A run carrying its own type size, such as `{\small ...}`. + SizedText(ParagraphFont, i64, String), Math(crate::math::MathAtom), Link { font: ParagraphFont, @@ -629,6 +634,7 @@ pub fn text_items(text: &str, style: &ParagraphStyle) -> Vec { italic: 0, font: None, math: None, + size: None, link: None, })); } @@ -1097,6 +1103,7 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra italic: 0, font: None, math: None, + size: None, link: None, })); } else if *no_break_width > 0 { @@ -1108,6 +1115,7 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra italic: 0, font: None, math: None, + size: None, link: None, })); } @@ -1453,6 +1461,7 @@ pub fn text_items_with_font( italic: font.italic(character), font: None, math: None, + size: None, link: None, })); let boundary = character_index + 1; @@ -1620,6 +1629,45 @@ pub fn layout_paragraph_segments(segments: &[InlineSegment], style: &ParagraphSt previous = Some((*font, text.clone())); seen_content = true; } + InlineSegment::SizedText(font, size, text) => { + if text.is_empty() { + continue; + } + let starts_with_space = text.chars().next().is_some_and(char::is_whitespace); + let boundary_space = match &previous { + Some((_previous_font, previous_text)) => { + previous_text + .chars() + .next_back() + .is_some_and(char::is_whitespace) + || starts_with_space + } + None => seen_content && starts_with_space, + }; + if boundary_space { + let metrics = crate::cmr10::Cmr10Metrics::for_paragraph_font( + previous.as_ref().map_or(*font, |(font, _)| *font), + ); + items.push(HorizontalItem::Glue { + width: scale_font_size(metrics.space(), *size), + stretch: scale_font_size(metrics.stretch(), *size), + shrink: scale_font_size(metrics.shrink(), *size), + order: 0, + }); + } + let metrics = crate::cmr10::Cmr10Metrics::for_paragraph_font(*font); + let mut run = text_items_with_font(text, style, &metrics); + scale_items_for_size(&mut run, *size); + for item in &mut run { + if let HorizontalItem::Box(box_) = item { + box_.font = Some(*font); + box_.size = Some(*size); + } + } + items.extend(run); + previous = Some((*font, text.clone())); + seen_content = true; + } InlineSegment::Link { font, url, text } => { if text.is_empty() { continue; @@ -1682,6 +1730,7 @@ pub fn layout_paragraph_segments(segments: &[InlineSegment], style: &ParagraphSt italic: 0, font: None, math: Some(Box::new(atom.clone())), + size: None, link: None, })); previous = None; @@ -1692,7 +1741,9 @@ pub fn layout_paragraph_segments(segments: &[InlineSegment], style: &ParagraphSt scale_items_for_size(&mut items, style.font_size); let mut paragraph = layout_items(&items, &sized_style(style)); paragraph.font = match segments.first() { - Some(InlineSegment::Text(font, _)) | Some(InlineSegment::Link { font, .. }) => *font, + Some(InlineSegment::Text(font, _)) + | Some(InlineSegment::SizedText(font, _, _)) + | Some(InlineSegment::Link { font, .. }) => *font, _ => ParagraphFont::Roman, }; paragraph.font_size = style.font_size; @@ -1978,6 +2029,32 @@ mod tests { assert!(linked.iter().all(|box_| box_.character.is_some())); } + #[test] + fn sized_segments_keep_their_own_glyph_size() { + let style = ParagraphStyle { + line_width: 480 * 65_536, + ..ParagraphStyle::default() + }; + let segments = vec![ + InlineSegment::Text(ParagraphFont::Roman, "x ".into()), + InlineSegment::SizedText(ParagraphFont::Roman, 786_432, "x".into()), + ]; + let paragraph = layout_paragraph_segments(&segments, &style); + let boxes: Vec<&HorizontalBox> = paragraph + .lines + .iter() + .flatten() + .filter_map(|item| match item { + HorizontalItem::Box(box_) => Some(box_), + _ => None, + }) + .collect(); + assert_eq!(boxes.len(), 2); + assert_eq!(boxes[0].size, None); + assert_eq!(boxes[1].size, Some(786_432)); + assert!(boxes[1].width > boxes[0].width); + } + #[test] fn inline_math_boxes_sit_between_words() { let style = ParagraphStyle { @@ -2031,6 +2108,7 @@ mod tests { italic: 0, font: None, math: None, + size: None, link: None, }) }; diff --git a/crates/texrra-tex-core/src/render.rs b/crates/texrra-tex-core/src/render.rs index ae9278b..36e4491 100755 --- a/crates/texrra-tex-core/src/render.rs +++ b/crates/texrra-tex-core/src/render.rs @@ -550,6 +550,7 @@ impl Page { } else { flush_link(&mut link_run, &mut list.items); } + let glyph_size = box_.size.unwrap_or(size); if let Some(math) = &box_.math { let math_font = Cmr10Metrics::default(); Self::paint_math( @@ -557,7 +558,7 @@ impl Page { &math_font, x, baseline, - size, + glyph_size, &mut list.items, ); } @@ -566,7 +567,7 @@ impl Page { font: box_.font.map_or(face, paragraph_face), x, y: baseline, - size, + size: glyph_size, text: character_text(character), }); } diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index a669ad1..9c4adeb 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`). 696 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 699 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 da04999..e683e37 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -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{...}` 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`, 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 | +| 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, and a size command in the middle of a paragraph splits a sized run that is shaped and painted at its own type size; full NFSS family/shape state and Type1 coverage for arbitrary Unicode remain open | | 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); the `geometry` package's `margin`/`hmargin`/`vmargin`/`left`/`right`/`top`/`bottom` options (and `\geometry{...}`) adjust the measure and page height; `\title`/`\author`/`\date` are captured, `\today` expands to the UTC calendar date in the title block and the body, and `\maketitle` expands into the centered article title block at the class sizes (with today's date when `\date` is absent and no date for `\date{}`); numbered `\section`/`\subsection`/`\subsubsection`/`\paragraph`/`\subparagraph` headings advance five-level article counters and paint at `\Large`/`\large`/`\normalsize` (the two deepest levels stay bold at the base size), starred headings stay unnumbered, and an optional `[short]` title is dropped; the `abstract` environment expands into a centered bold heading and a 9pt body, `\maketitle` joins `\and` authors and turns `\thanks` notes into title footnotes, and `\label` inside a heading (or on its own line after it) resolves `\ref`/`\eqref` to the section number while unknown references print `??`, and `\appendix` restarts sectioning with letters (`A`, `A.1`), and `\tableofcontents` lists the numbered headings through `\subsubsection` with 12pt per-level indentation while `\listoffigures`/`\listoftables` reproduce the numbered figure/table captions; `verbatim` environments keep each source line as a monospaced 9pt paragraph indented by 12pt (leading whitespace is normalised), `\href{url}{text}` keeps its text, and `\url{...}` becomes typewriter text; `\footnote{...}` becomes a numbered 9pt page insertion on the page that mentions it; a `thebibliography` environment is removed from the body, its `\bibitem` entries become numbered `[n]` paragraphs, and `\cite{...}` resolves to `[n]`/`[n, m]` (unknown keys print `[?]`); a `figure` environment becomes a float at its `[t]`/`[b]`/`[h]` placement, its `\caption` numbers as `Figure n:` and resolves `\ref`, and `\includegraphics[width=...,height=...]` reserves a rule placeholder; a `table` environment becomes a float that carries its captured `tabular` body and a numbered `Table n:` caption whose text sits above the tabular as in LaTeX, while `\caption*` stays unnumbered for either float kind; `theorem`/`lemma`/`corollary`/`proposition`/`definition`/`example`/`remark`/`proof` environments get a bold numbered heading (optionally with `[title]`), italic statements for the theorem group, an unnumbered proof, and `\label`/`\ref` targets; `\newtheorem{env}[shared]{Display}`, `\newtheorem{env}{Display}[section]` and `\newtheorem*{env}{Display}` define custom environments with shared counters and section-scoped numbers; `itemize`/`enumerate`/`description` lists nest with depth-aware bullets (`•`, `–`, `*`), lettered/roman sub-labels and 12pt-per-level indentation, and an optional `\item[label]` overrides the generated marker; `\def\name#1{...}` parameter texts and `\let\alias=\other` aliases are executed as textual definitions; `\newenvironment{name}[n]{begin}{end}` definitions expand their begin/end codes around the environment body, with numbered arguments available in both; `\newif\ifname` flags default to false and `\nametrue`/`\namefalse` assignments, whether in the preamble or the body, select between `\ifname ... \else ... \fi` branches; project previews and PDF exports expand `\input{...}`/`\include{...}` from the project's files (the `.tex` suffix may be omitted) while unknown files stay literal text, and inline a project's own `.sty` files for `\usepackage{name}` and `.cls` files for `\documentclass` (rewritten to `article` with the original options kept), recursively inlining local `\RequirePackage` dependencies (up to eight levels, cycles skipped), dropping package/class boilerplate (`\ProvidesPackage`/`\ProvidesClass`, `\NeedsTeXFormat`, `\RequirePackage`) and inlining local base classes requested with `\LoadClass`/`\LoadClassWithOptions` (unknown bases keep LaTeX's article fallback); local class and package files execute their `\DeclareOption`/`\ExecuteOptions`/`\ProcessOptions` subset, so options named on `\documentclass[...]` or `\usepackage[...]` run their declaration code and `\ExecuteOptions` supplies defaults; a full class layout implementation and arbitrary package code remain open | | 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 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. +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 box's own size when a mid-paragraph size command split the run (otherwise 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 405 unit tests plus eight route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 696 tests (405 route-D unit, 126 engine binary unit, 8 route-D integration, 35 oracle, 71 v1 integration, 46 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path. +The crate currently has 405 unit tests plus eight route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 699 tests (406 route-D unit, 128 engine binary unit, 8 route-D integration, 35 oracle, 71 v1 integration, 46 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 b8841c8..1d00782 100755 --- a/src/route_d.rs +++ b/src/route_d.rs @@ -3059,11 +3059,13 @@ fn inline_math_segments( let mut segments = Vec::new(); let mut found_math = false; let mut found_link = false; + let mut found_size = false; for part in split_hrefs(text) { match part { HrefPart::Plain(piece) => { - let runs = inline_runs(&piece, base).unwrap_or_else(|| vec![(base, piece.clone())]); - for (font, run_text) in runs { + let runs = inline_sized_runs(&piece, base) + .unwrap_or_else(|| vec![(base, style.font_size, piece.clone())]); + for (font, size, run_text) in runs { for (is_math, piece) in split_inline_math(&run_text) { if is_math { found_math = true; @@ -3071,8 +3073,18 @@ fn inline_math_segments( parse_math(&piece), )); } else if !piece.is_empty() { - segments - .push(texrra_tex_core::paragraph::InlineSegment::Text(font, piece)); + if size == 655_360 { + segments.push(texrra_tex_core::paragraph::InlineSegment::Text( + font, piece, + )); + } else { + found_size = true; + segments.push( + texrra_tex_core::paragraph::InlineSegment::SizedText( + font, size, piece, + ), + ); + } } } } @@ -3090,30 +3102,45 @@ fn inline_math_segments( } } } - (found_math || found_link).then_some(segments) + (found_math || found_link || found_size).then_some(segments) } fn inline_runs(text: &str, base: ParagraphFont) -> Option> { + Some( + inline_sized_runs(text, base)? + .into_iter() + .map(|(font, _, text)| (font, text)) + .collect(), + ) +} + +fn inline_sized_runs(text: &str, base: ParagraphFont) -> Option> { let mut runs = Vec::new(); let mut found = false; - parse_runs(text, base, &mut runs, &mut found); + parse_runs(text, base, 655_360, &mut runs, &mut found); if !found { return None; } Some(runs) } -fn push_run(runs: &mut Vec<(ParagraphFont, String)>, font: ParagraphFont, text: &str) { +fn push_run( + runs: &mut Vec<(ParagraphFont, i64, String)>, + font: ParagraphFont, + size: i64, + text: &str, +) { if text.is_empty() { return; } - if let Some((last_font, last_text)) = runs.last_mut() + if let Some((last_font, last_size, last_text)) = runs.last_mut() && *last_font == font + && *last_size == size { last_text.push_str(text); return; } - runs.push((font, text.to_string())); + runs.push((font, size, text.to_string())); } /// Match a balanced `{...}` at the start of `rest`, returning its contents and @@ -3182,32 +3209,35 @@ fn inline_wrapper(rest: &str, base: ParagraphFont) -> Option<(ParagraphFont, &st fn parse_runs( text: &str, font: ParagraphFont, - runs: &mut Vec<(ParagraphFont, String)>, + size: i64, + runs: &mut Vec<(ParagraphFont, i64, String)>, found: &mut bool, ) { let mut index = 0; while index < text.len() { let rest = &text[index..]; - if let Some((declared, body)) = nfss_font(rest, font) { + if let Some((declared, declared_size, body)) = nfss_font_with_size(rest, font) { *found = true; - parse_runs(&body, declared, runs, found); + parse_runs(&body, declared, declared_size.unwrap_or(size), runs, found); return; } if let Some((inner, length)) = braced_group(rest) { - let (inner_font, inner_text) = match nfss_font(inner, font) { - Some((declared, body)) => (declared, body), - None => (font, inner.to_string()), + let (inner_font, inner_size, inner_text) = match nfss_font_with_size(inner, font) { + Some((declared, declared_size, body)) => { + (declared, declared_size.unwrap_or(size), body) + } + None => (font, size, inner.to_string()), }; - if nfss_font(inner, font).is_some() { + if nfss_font_with_size(inner, font).is_some() { *found = true; } - parse_runs(&inner_text, inner_font, runs, found); + parse_runs(&inner_text, inner_font, inner_size, runs, found); index += length; continue; } if let Some((wrapper_font, inner, length)) = inline_wrapper(rest, font) { *found = true; - parse_runs(inner, wrapper_font, runs, found); + parse_runs(inner, wrapper_font, size, runs, found); index += length; continue; } @@ -3218,7 +3248,7 @@ fn parse_runs( .find(|(_, character)| !character.is_ascii_alphabetic()) .map(|(offset, _)| offset.max(1)) .unwrap_or(rest.len()); - push_run(runs, font, &rest[..step]); + push_run(runs, font, size, &rest[..step]); index += step; continue; } @@ -3228,7 +3258,7 @@ fn parse_runs( .find(|(_, character)| *character == '{' || *character == '\\') .map(|(offset, _)| offset) .unwrap_or(rest.len()); - push_run(runs, font, &rest[..step]); + push_run(runs, font, size, &rest[..step]); index += step; } } @@ -5629,6 +5659,27 @@ A definition. ); } + #[test] + fn size_commands_split_sized_runs() { + let runs = inline_sized_runs("plain \\large large text", ParagraphFont::Roman) + .expect("sized runs"); + assert_eq!( + runs, + vec![ + (ParagraphFont::Roman, 655_360, "plain ".to_string()), + (ParagraphFont::Roman, 786_432, "large text".to_string()), + ] + ); + } + + #[test] + fn inline_size_commands_paint_bigger_glyphs() { + let json = preview_json("Body \\large Big.").expect("preview"); + assert!(json.contains("12.000"), "{json}"); + assert!(json.contains("10.000"), "{json}"); + assert!(!json.contains("\\large"), "{json}"); + } + #[test] fn href_creates_link_boxes() { let source = "Visit \\href{https://example.com}{the site} now.";