From c6860b7b4ac40096d1c6ed416bba3c077d7ff330 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Sun, 25 Oct 2026 00:03:19 +0800 Subject: [PATCH] Fall back per glyph outside the Type1 encodings --- README.md | 2 +- crates/texrra-tex-core/src/pdf.rs | 189 +++++++++++++++--------- crates/texrra-tex-core/tests/route_d.rs | 28 ++++ docs/ROUTE_D_PLAN.md | 2 +- docs/TEX_CORE.md | 8 +- 5 files changed, 155 insertions(+), 74 deletions(-) diff --git a/README.md b/README.md index c15d1fc..0c16823 100644 --- a/README.md +++ b/README.md @@ -469,7 +469,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 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` (the default article `tocdepth` of 3, changed by `\setcounter{tocdepth}`), `\setcounter{secnumdepth}` limits which levels are numbered, `\listoffigures`/`\listoftables` reproduce the numbered captions, `verbatim` keeps monospaced source lines, `\verb|...|` renders inline literal text monospaced, `\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` embeds the referenced project image when it decodes (PNG/JPEG/BMP become a PDF XObject; missing files keep the rule placeholder), a standalone `\includegraphics` paragraph becomes an in-text graphic float; `width=`/`height=` take dimensions or fractions of `\textwidth`/`\textheight`, `scale=` a percentage, `keepaspectratio` fits both dimensions, and `\graphicspath` directories are searched (with `.png`/`.jpg`/`.bmp` fallbacks) when a path has no suffix. `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, class and package bodies inlining their local `\input{...}` files (missing files are dropped), 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; PDF exports cache the last eight results and the cache key also covers decoded image bytes, so replacing an image re-renders both. `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. Characters outside a program's encoding fall back per glyph to a Liberation subset, so the ASCII letters of an accented word still use Computer Modern. 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` (the default article `tocdepth` of 3, changed by `\setcounter{tocdepth}`), `\setcounter{secnumdepth}` limits which levels are numbered, `\listoffigures`/`\listoftables` reproduce the numbered captions, `verbatim` keeps monospaced source lines, `\verb|...|` renders inline literal text monospaced, `\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` embeds the referenced project image when it decodes (PNG/JPEG/BMP become a PDF XObject; missing files keep the rule placeholder), a standalone `\includegraphics` paragraph becomes an in-text graphic float; `width=`/`height=` take dimensions or fractions of `\textwidth`/`\textheight`, `scale=` a percentage, `keepaspectratio` fits both dimensions, and `\graphicspath` directories are searched (with `.png`/`.jpg`/`.bmp` fallbacks) when a path has no suffix. `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, class and package bodies inlining their local `\input{...}` files (missing files are dropped), 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; PDF exports cache the last eight results and the cache key also covers decoded image bytes, so replacing an image re-renders both. `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/pdf.rs b/crates/texrra-tex-core/src/pdf.rs index 3e27a0e..18fe49b 100755 --- a/crates/texrra-tex-core/src/pdf.rs +++ b/crates/texrra-tex-core/src/pdf.rs @@ -427,12 +427,69 @@ pub struct PageOrigin { pub v_offset: i64, } +fn write_type0_font( + objects: &mut Vec>, + face: &'static PdfFace, + slot: usize, + used: &BTreeSet, +) -> usize { + let type0_id = objects.len() + 1; + let cid_id = type0_id + 1; + let descriptor_id = type0_id + 2; + let file_id = type0_id + 3; + let tounicode_id = type0_id + 4; + let base = face.base; + objects.push( + format!( + "<< /Type /Font /Subtype /Type0 /BaseFont /{base} /Encoding /Identity-H /DescendantFonts [{cid_id} 0 R] /ToUnicode {tounicode_id} 0 R >>" + ) + .into_bytes(), + ); + objects.push( + format!( + "<< /Type /Font /Subtype /CIDFontType2 /BaseFont /{base} /CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> /FontDescriptor {descriptor_id} 0 R /DW 500 /W {} >>", + cid_widths(face, slot, used) + ) + .into_bytes(), + ); + objects.push( + format!( + "<< /Type /FontDescriptor /FontName /{base} /Flags 32 /FontBBox [-500 -300 1200 1000] /ItalicAngle {} /Ascent 900 /Descent -250 /CapHeight 700 /StemV 80 /FontFile2 {file_id} 0 R >>", + face.italic_angle + ) + .into_bytes(), + ); + let font_bytes = crate::subset::subset_font(face.bytes, face_font(face), used); + let compressed = deflate(&font_bytes); + let mut font_stream = format!( + "<< /Length {} /Length1 {} /Filter /FlateDecode >>\nstream\n", + compressed.len(), + font_bytes.len() + ) + .into_bytes(); + font_stream.extend_from_slice(&compressed); + font_stream.extend_from_slice(b"\nendstream"); + objects.push(font_stream); + let cmap = tounicode_cmap(face, used); + let compressed_cmap = deflate(&cmap); + let mut cmap_object = format!( + "<< /Length {} /Filter /FlateDecode >>\nstream\n", + compressed_cmap.len() + ) + .into_bytes(); + cmap_object.extend_from_slice(&compressed_cmap); + cmap_object.extend_from_slice(b"\nendstream"); + objects.push(cmap_object); + type0_id +} + fn page_content( list: &DisplayList, height: i64, image_names: &BTreeMap, faces: &'static [PdfFace; FACE_COUNT], cm_codes: &[Option<&BTreeMap>], + fallback_ids: &[usize; FACE_COUNT], origin: PageOrigin, ) -> String { let mut content = String::from("q\n0 0 0 rg\n"); @@ -452,10 +509,12 @@ fn page_content( text, font, } => { - let operand = match cm_codes - .get(*font as usize) + let slot = *font as usize; + let covered = cm_codes + .get(slot) .and_then(|entry| entry.as_ref()) - { + .filter(|codes| text.chars().all(|character| codes.contains_key(&character))); + let (operand, resource) = match covered { Some(codes) => { let mut literal = String::from("("); for character in text.chars() { @@ -464,13 +523,20 @@ fn page_content( } } literal.push(')'); - literal + (literal, font_resource(*font).to_string()) } - _ => format!("<{}>", glyph_hex(face(*font, faces), text)), + None if fallback_ids[slot] != 0 => ( + format!("<{}>", glyph_hex(face(*font, faces), text)), + format!("T{}", slot + 1), + ), + None => ( + format!("<{}>", glyph_hex(face(*font, faces), text)), + font_resource(*font).to_string(), + ), }; content.push_str(&format!( "BT /{} {} Tf 1 0 0 1 {} {} Tm {} Tj ET\n", - font_resource(*font), + resource, pt(*size), pt(*x), pt(height - *y), @@ -639,9 +705,6 @@ fn write_pdf( .collect(); return Some((font, codes)); } - if !font.covers(used_chars[slot].iter().copied()) { - return None; - } let codes = used_chars[slot] .iter() .filter_map(|character| font.code_for(*character).map(|code| (*character, code))) @@ -653,6 +716,16 @@ fn write_pdf( .iter() .map(|entry| entry.as_ref().map(|(_, codes)| codes)) .collect(); + let mut fallback_chars: [BTreeSet; FACE_COUNT] = Default::default(); + for slot in 0..FACE_COUNT { + if let Some((_, codes)) = &cm_faces[slot] { + for character in &used_chars[slot] { + if !codes.contains_key(character) { + fallback_chars[slot].insert(*character); + } + } + } + } let minimal = pages.iter().all(|page| { page.items.iter().all(|item| match item { DisplayItem::Text { text, .. } => text.chars().all(minimal_text_char), @@ -661,6 +734,7 @@ fn write_pdf( }); let faces: &'static [PdfFace; FACE_COUNT] = if minimal { &MIN_FACES } else { &FULL_FACES }; let mut font_ids = [0usize; FACE_COUNT]; + let mut fallback_font_ids = [0usize; FACE_COUNT]; for (slot, face) in faces.iter().enumerate() { if !used_faces[slot] { continue; @@ -740,56 +814,13 @@ fn write_pdf( stream.extend_from_slice(&font.program); stream.extend_from_slice(b"\nendstream"); objects.push(stream); + if !fallback_chars[slot].is_empty() { + fallback_font_ids[slot] = + write_type0_font(&mut objects, face, slot, &fallback_chars[slot]); + } continue; } - let type0_id = objects.len() + 1; - let cid_id = type0_id + 1; - let descriptor_id = type0_id + 2; - let file_id = type0_id + 3; - let tounicode_id = type0_id + 4; - font_ids[slot] = type0_id; - let base = face.base; - objects.push( - format!( - "<< /Type /Font /Subtype /Type0 /BaseFont /{base} /Encoding /Identity-H /DescendantFonts [{cid_id} 0 R] /ToUnicode {tounicode_id} 0 R >>" - ) - .into_bytes(), - ); - objects.push( - format!( - "<< /Type /Font /Subtype /CIDFontType2 /BaseFont /{base} /CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> /FontDescriptor {descriptor_id} 0 R /DW 500 /W {} >>", - cid_widths(face, slot, &used_chars[slot]) - ) - .into_bytes(), - ); - objects.push( - format!( - "<< /Type /FontDescriptor /FontName /{base} /Flags 32 /FontBBox [-500 -300 1200 1000] /ItalicAngle {} /Ascent 900 /Descent -250 /CapHeight 700 /StemV 80 /FontFile2 {file_id} 0 R >>", - face.italic_angle - ) - .into_bytes(), - ); - let font_bytes = crate::subset::subset_font(face.bytes, face_font(face), &used_chars[slot]); - let compressed = deflate(&font_bytes); - let mut font_stream = format!( - "<< /Length {} /Length1 {} /Filter /FlateDecode >>\nstream\n", - compressed.len(), - font_bytes.len() - ) - .into_bytes(); - font_stream.extend_from_slice(&compressed); - font_stream.extend_from_slice(b"\nendstream"); - objects.push(font_stream); - let cmap = tounicode_cmap(face, &used_chars[slot]); - let compressed_cmap = deflate(&cmap); - let mut cmap_object = format!( - "<< /Length {} /Filter /FlateDecode >>\nstream\n", - compressed_cmap.len() - ) - .into_bytes(); - cmap_object.extend_from_slice(&compressed_cmap); - cmap_object.extend_from_slice(b"\nendstream"); - objects.push(cmap_object); + font_ids[slot] = write_type0_font(&mut objects, face, slot, &used_chars[slot]); } let mut kids = Vec::new(); @@ -812,7 +843,16 @@ fn write_pdf( .join(" "); let fonts = (0..FACE_COUNT) .filter(|slot| used_faces[*slot]) - .map(|slot| format!("/F{} {} 0 R", slot + 1, font_ids[slot])) + .flat_map(|slot| { + let mut entries = Vec::new(); + if font_ids[slot] != 0 { + entries.push(format!("/F{} {} 0 R", slot + 1, font_ids[slot])); + } + if fallback_font_ids[slot] != 0 { + entries.push(format!("/T{} {} 0 R", slot + 1, fallback_font_ids[slot])); + } + entries + }) .collect::>() .join(" "); let resources = if used.is_empty() { @@ -862,7 +902,15 @@ fn write_pdf( for (index, slot) in &used { names.insert(*index, format!("Im{slot}")); } - let content = page_content(list, height, &names, faces, &cm_views, origin); + let content = page_content( + list, + height, + &names, + faces, + &cm_views, + &fallback_font_ids, + origin, + ); objects.push( format!( "<< /Length {} >>\nstream\n{}endstream", @@ -1204,19 +1252,24 @@ mod type1_pdf_tests { } #[test] - fn type1_backend_falls_back_for_uncovered_characters() { + fn type1_backend_mixes_type1_and_fallback_fonts() { let mut list = hello_list(); - list.items[0] = DisplayItem::Text { - x: 0, - y: 800_000, - size: 655_360, - text: "café".to_string(), - font: FontFace::Roman, - }; + list.items.clear(); + for (index, character) in "café".chars().enumerate() { + list.items.push(DisplayItem::Text { + x: index as i64 * 20 * 65_536, + y: 800_000, + size: 655_360, + text: character.to_string(), + font: FontFace::Roman, + }); + } let pdf = write(&[list]); let text = String::from_utf8_lossy(&pdf); - assert!(!text.contains("/BaseFont /CMR10"), "{text}"); + assert!(text.contains("/BaseFont /CMR10"), "{text}"); + assert!(text.contains("(\\143)"), "{text}"); assert!(text.contains("/Subtype /Type0"), "{text}"); + assert!(text.contains("/T1 "), "{text}"); } #[test] diff --git a/crates/texrra-tex-core/tests/route_d.rs b/crates/texrra-tex-core/tests/route_d.rs index fde267e..2c2fc77 100755 --- a/crates/texrra-tex-core/tests/route_d.rs +++ b/crates/texrra-tex-core/tests/route_d.rs @@ -59,6 +59,34 @@ fn paragraph(id: u64, marker: &str) -> Unit { Unit::paragraph_with_style(id, text, body_style()) } +#[test] +fn accented_text_keeps_type1_ascii_and_falls_back_per_glyph() { + let mut document = Document::new( + 1, + vec![Unit::paragraph_with_style( + 1, + "caf\u{e9}".to_string(), + body_style(), + )], + ); + document.page_goal = 200 * 65_536; + let engine = Engine::layout_paged(&document).expect("paged layout"); + let lists: Vec<_> = engine + .pages() + .iter() + .map(|page| page.display_list()) + .collect(); + let pdf = display_lists_to_pdf_with_cm_type1( + &lists, + 300 * 65_536, + 300 * 65_536, + PageOrigin::default(), + ); + let text = String::from_utf8_lossy(&pdf); + assert!(text.contains("/BaseFont /CMR10"), "{text}"); + assert!(text.contains("/Subtype /Type0"), "{text}"); +} + #[test] fn route_d_article_exports_pdf_and_reflows_only_the_edited_page() { let mut document = Document::new( diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index d760675..b7b2f60 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`). 719 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 720 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 262d7e8..d6ad52f 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), `\multicolumn{n}{align}{...}` cells span columns with the requested alignment, `\cline{a-b}` draws a 0.4pt partial rule over a column range, 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, 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 | +| 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 a Liberation subset falling back per glyph for characters outside the Type1 encodings, so ASCII on an accented line still uses the Computer Modern face; 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 (article's `\setcounter{secnumdepth}` default of 3 numbers through `\subsubsection`, and raising it numbers the two deeper levels) 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 (the default article `tocdepth` of 3; `\setcounter{tocdepth}` changes the depth) 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), `\verb|...|` renders inline literal text in the mono face, `\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` embeds the referenced project image (PNG/JPEG/BMP are decoded into a PDF XObject, with a rule placeholder when the file is missing), and a standalone `\includegraphics` paragraph becomes an in-text graphic float, with `width=`/`height=` taking dimensions or fractions of `\textwidth`/`\textheight`, `scale=` a percentage of the natural size, `keepaspectratio` shrinking both dimensions to fit, and `\graphicspath` directories searched with common image extensions when the path has no suffix; 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), inlining local `\input{...}` files inside class/package bodies (unresolved ones are dropped), 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 | @@ -331,7 +331,7 @@ for a later overlaid slash. | M2 vertical/page builder | partial | vsize, topskip, insertions, marks, Rust output hook, top/bottom floats, float-page/text fractions, rules, vskip, penalties; `page::PageBuilder` scores breakpoints with page badness and penalties and models `\topskip`/`\maxdepth`; `Engine::layout_paged` builds pages through it for documents made of box/glue/penalty/mark vertical material (a unit may span pages), while in-text floats flow inline through the page builder; paged layouts replay edits from the edited page (insertions, bottom floats and interpreted `\output` force a full rebuild), and insertions are placed through the builder too; `\output` interpreted for a `\shipout`/`\ifdim`/`\ifnum` register subset over page globals and `\outputpenalty`/`\pageno`/`\deadcycles` | | 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 | +| 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 glyph to a Liberation subset when a character is outside the encoding while the rest of the face stays in Computer Modern | | 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`, executes `\newcommand`/`\renewcommand` macros textually (with numbered arguments and an eight-pass recursion guard), and expands `geometry`, `\setlength`, title/author/date, `\maketitle`, sectioning, theorem, float and bibliography markup; local `.cls`/`.sty` files are inlined, execute their `\DeclareOption` subset for the options given on `\documentclass`/`\usepackage`, and recurse through local `\LoadClass` bases, while full class layout execution 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/inline-math/itemize/enumerate/description/quote/center/flushleft/flushright mapping; editor toggle in `texrra-web`; project route-D previews are memoised by a hash of the expanded source (32 entries) and invalidated automatically when the source changes; project route-D PDF exports are cached by the same expanded-source hash (eight entries) and report `X-Texrra-Cache: hit`/`miss`; the flat `POST /api/route-d/preview` and `/api/route-d/pdf` endpoints likewise memoise the last 32 previews and eight PDFs by source hash and report the same header; a deployment can default to route-D with `TEXRRA_ENGINE=route-d`, and an explicit `?engine=v1` still overrides it; inline `$...$`/`\(...\)` math is laid out inside 10pt paragraphs, while larger paragraphs keep delimiters literal; `\href` labels paint PDF `/Link` URI annotations over their runs | @@ -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 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. +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) for the characters the program encodes and a Liberation Type0 subset for the uncovered ones on the same page; `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 410 unit tests plus eight route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 719 tests (410 route-D unit, 140 engine binary unit, 8 route-D integration, 35 oracle, 71 v1 integration, 50 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path. +The crate currently has 410 unit tests plus nine route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 720 tests (410 route-D unit, 140 engine binary unit, 9 route-D integration, 35 oracle, 71 v1 integration, 50 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path. ### M0 incremental demo