diff --git a/README.md b/README.md index 9058764..b1eef3f 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, and `\maketitle` expands into a centered title block at the article class sizes. `\section`, `\subsection` and `\subsubsection` advance article counters, prefix their titles with the number, and paint bold at `\Large`/`\large`/`\normalsize`; 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 while dropping `\thanks` notes. 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, 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. +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, and `\maketitle` expands into a centered title block at the article class sizes. `\section`, `\subsection` and `\subsubsection` advance article counters, prefix their titles with the number, and paint bold at `\Large`/`\large`/`\normalsize`; 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 while dropping `\thanks` notes. 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, 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. Route-D integration can also be checked against a real TeX page: `cargo test -p texrra-tex-core --test route_d` includes `route_d_page_matches_pdftex_raster_geometry`, which renders the route-D PDF and a pdfTeX Letter page at the same scaled-point geometry, rasterizes both with `pdftoppm`, and compares ink line count plus left, right, and bottom edges. It is skipped when `pdflatex`/`pdftoppm` are unavailable. `route_d_multiline_bands_track_pdftex` extends that check to a wrapped paragraph: the pixel rows that carry ink form one band per TeX line, and every band top, bottom, left edge and (except for the last line, whose width follows the break point) right edge must land within a couple of pixels of the pdfTeX page. diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index aec1fae..66b613c 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`). 615 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 618 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 4b2ba4c..5bd0294 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -133,7 +133,7 @@ and justification. | M3 | `\halign`, `\omit`, `\span`, `\multispan`, booktabs/longtable | **partial**: source parsing, natural column widths, spans, rule rows, 10pt display-list painting and row-level page splitting; the paged builder splits a tall alignment into page-sized row chunks that keep the table's column widths, so long tables continue across pages; `p{width}` paragraph columns wrap cell text and grow row heights, wrapped rows participate in row-level splitting, explicit per-column `\tabskip` glue is honoured through layout, painting and page chunks, and booktabs rules carry their own weights and spans (`\toprule`/`\bottomrule` 0.8pt, `\midrule`/`\cmidrule` 0.5pt, with `\cmidrule(lr){a-b}` trimming and column ranges), `@{}` / `@{\hspace{...}}` column expressions override the inter-column glue, and row-boundary `\noalign{\vskip ...}` glue is honoured by layout, painting and page chunks; longtable head/foot sections (`\endfirsthead`/`\endhead`/`\endfoot`/`\endlastfoot`) are parsed, continuation chunks repeat the head rows and the foot block paints once at the end, LaTeX `tabular` environments are captured and laid out through the same `\halign` path (rules are stripped from the column spec, `p{...}`/`m{...}`/`b{...}` become wrapping columns, `@{}` expressions are ignored for spacing), though `\valign`, nested tables and full tabular parity remain open | | M4 | math lists, scripts, fractions, radicals, accents, delimiters | **partial**: token parser, atom boxes with Computer Modern metrics (italic letters from the bundled `cmmi10`, big operators from `cmex10`, symbols such as `\times`/`\leq`/`\infty` from `cmsy10`, with `cmmi10`, `cmsy10` and `cmex10` glyphs embedded as Type1 outlines), `\left...\right` delimiter selection through CMEX size variants using TeX's delimiterfactor and shortfall, accents and a display-list painter; display formulas wider than the measure are split at top-level binary/relation operators into multiple lines (an approximation of TeX's `\split` behaviour; `align`/`align*` displays share column widths and number each row, while `gather`/`gather*` centre every row); CMEX delimiter size variants back `\big`/`\Big`/`\bigg`/`\Bigg`; inter-atom spacing uses TeX's full atom-class table with binary-operator normalisation, with `1mu` = `1/18em` (a thin space is 3mu = 1.67pt at 10pt); `\mid` is a relation while `\colon` is punctuation; `\mskip`, `\mkern`, `\mspace`, `\hskip`, `\kern` and `\hspace` scan TeX dimensions (`mu`, `pt`, `em`, ...) and contribute their natural width, accepting `plus`/`minus` parts even though math boxes are not glue lists; route-D numbers `equation` environments and resolves `\eqref`/`\ref` through their labels; `\tag` overrides the number and `\notag`/`\nonumber` suppress it; math italic letters are embedded as Computer Modern Type1 outlines (`cmmi10`), and math alphabets map `\\mathbf`/`\\mathit`/`\\mathsf`/`\\mathtt` onto the bold, math-italic, sans and mono faces with their TFMs and `\\mathcal` onto the cmsy10 calligraphic capitals; `\mathfrak` maps onto the bundled eufm10 Fraktur letters (embedded as Type1 outlines); infix fractions `\over`, `\atop`, `\choose`, `\brace`, `\brack` and their `withdelims` forms build fractions from the current row, with the bar only for the `\over` forms; `\middle` delimiters are sized with their enclosing `\left`/`\right` group and `\big`/`\Big`/`\bigg`/`\Bigg` paint at their selected CMEX size | | M5 | NFSS/TFM metrics, CM/Latin Modern | **partial**: paragraph-level NFSS declarations and inline run composition over the built-in Roman/Bold/Italic/BoldItalic/Mono/MonoItalic/Sans/SansBold/SansItalic/SmallCaps/Slanted/BoldSlanted faces (CM has no sans bold-italic, so `cmss/bx/it` substitutes `cmss/bx/n`; `\scshape` selects cmcsc10 and a bold small caps request falls back to cmbx10; `\slshape` uses the slanted cmsl10 rather than the italic cmti10 and `\ttfamily\itshape` reaches cmitt10), per-face Computer Modern TFM metrics, and Type1 (PFB) outline embedding for every built-in face plus `cmmi10` math italics, `cmsy10` math symbols and `cmex10` big operators, with Liberation subsets used only as a fallback for characters outside the Type1 encodings; paragraph base sizes from `\fontsize` and the article size commands scale glyph metrics and the default interline glue while the measure and authored skips stay absolute; full NFSS family/shape state and Type1 coverage for arbitrary Unicode remain open | -| M6 | class/package execution (`article`, `sn-jnl`) | **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 and `\maketitle` expands into the centered article title block at the class sizes; numbered `\section`/`\subsection`/`\subsubsection` headings advance article counters and paint at `\Large`/`\large`/`\normalsize`, 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 while dropping `\thanks` notes, 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`); executing the class file itself and arbitrary package code remains 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 and `\maketitle` expands into the centered article title block at the class sizes; numbered `\section`/`\subsection`/`\subsubsection` headings advance article counters and paint at `\Large`/`\large`/`\normalsize`, 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 while dropping `\thanks` notes, 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`); `\footnote{...}` becomes a numbered 9pt page insertion on the page that mentions it; executing the class file itself and arbitrary package code remains open | | M7 | `\special`, PDF XObjects, hyperref annotations | PDF structure parity | ## Current limits @@ -367,7 +367,7 @@ Math coverage includes fractions/roots, scripts, `\left...\right` with body-scal Paragraph units carry a `ParagraphFont`; `Unit::paragraph_with_face` and `Unit::paragraph_with_style_and_face` select Roman, bold, italic, mono, or sans. The corresponding Computer Modern TFM (`cmr10`, `cmbx10`, `cmti10`, `cmbxti10`, `cmtt10`, `cmss10`, `cmssbx10`, `cmssi10`, `cmcsc10`) supplies advances, kerns, ligatures, and italic correction for layout, the display list selects the matching face, and the PDF writes Computer Modern Type1 outlines for each built-in face (`cmr10`/`cmbx10`/`cmti10`/`cmbxti10`/`cmtt10`/`cmss10`/`cmssbx10`/`cmssi10`/`cmcsc10`, plus `cmmi10` for mathematical italic letters, `cmsy10` for math symbols and `cmex10` for big operators), falling back to Liberation subsets only for characters the Type1 encodings cannot address. `Engine::edit` preserves the face when reflowing an edited paragraph. -The crate currently has 401 unit tests plus eight route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 615 tests (402 route-D unit, 66 engine binary unit, 8 route-D integration, 35 oracle, 71 v1 integration, 28 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path. +The crate currently has 402 unit tests plus eight route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 618 tests (402 route-D unit, 68 engine binary unit, 8 route-D integration, 35 oracle, 71 v1 integration, 29 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 b38ee4e..2fafc34 100755 --- a/src/route_d.rs +++ b/src/route_d.rs @@ -12,7 +12,9 @@ use std::sync::{Mutex, OnceLock}; use texrra_tex_core::cmr10::Cmr10Metrics; use texrra_tex_core::math::{AlignedRow, MathAtom, parse_math, split_math_lines}; use texrra_tex_core::pdf::{PageOrigin, display_lists_to_pdf_with_cm_type1}; -use texrra_tex_core::{Document, Engine, ParagraphFont, ParagraphStyle, Unit}; +use texrra_tex_core::{ + Document, Engine, InsertionClass, ParagraphFont, ParagraphStyle, Unit, VerticalItem, +}; const SCALE: i64 = 65_536; @@ -55,7 +57,15 @@ pub fn project_preview_json(project_id: &str, source: &str) -> Result { if session.paragraphs == paragraphs && session.geometry == geometry { (session.engine, Vec::new(), 0) - } else if session.geometry == geometry { + } else if session.geometry == geometry + && session + .paragraphs + .iter() + .all(|paragraph| paragraph.footnotes.is_empty()) + && paragraphs + .iter() + .all(|paragraph| paragraph.footnotes.is_empty()) + { let prefix = session .paragraphs .iter() @@ -860,6 +870,8 @@ struct SourceParagraph { heading_starred: bool, /// The section number assigned by the numbering pass. heading_number: Option, + /// Footnote bodies extracted from this paragraph, with their numbers. + footnotes: Vec<(u32, String)>, font_size: Option, } @@ -940,6 +952,7 @@ fn paragraphs(source: &str) -> Result, String> { heading_level: None, heading_starred: false, heading_number: None, + footnotes: Vec::new(), font_size: None, }); pending = (0, 0, 0); @@ -1085,6 +1098,7 @@ fn parse_blocks_raw(raw: &str) -> Vec { heading_level: None, heading_starred: false, heading_number: None, + footnotes: Vec::new(), font_size: Some((12.0 * SCALE as f64) as i64), }; let body = SourceParagraph { @@ -1106,6 +1120,7 @@ fn parse_blocks_raw(raw: &str) -> Vec { heading_level: None, heading_starred: false, heading_number: None, + footnotes: Vec::new(), font_size: Some((9.0 * SCALE as f64) as i64), }; if body.text.is_empty() { @@ -1175,6 +1190,7 @@ fn parse_blocks_raw(raw: &str) -> Vec { heading_level: None, heading_starred: false, heading_number: None, + footnotes: Vec::new(), font_size: None, } }) @@ -1208,6 +1224,7 @@ fn parse_blocks_raw(raw: &str) -> Vec { heading_level: None, heading_starred: false, heading_number: None, + footnotes: Vec::new(), font_size: None, }]; } @@ -1250,6 +1267,7 @@ fn parse_blocks_raw(raw: &str) -> Vec { heading_level: None, heading_starred: false, heading_number: None, + footnotes: Vec::new(), font_size: None, } }) @@ -1772,6 +1790,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph { heading_level: None, heading_starred: false, heading_number: None, + footnotes: Vec::new(), font_size: None, }; } @@ -1797,6 +1816,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph { heading_level: None, heading_starred: false, heading_number: None, + footnotes: Vec::new(), }; } if let Some(inner) = raw @@ -1822,6 +1842,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph { heading_level: None, heading_starred: false, heading_number: None, + footnotes: Vec::new(), font_size: None, }; } @@ -1848,6 +1869,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph { heading_level: None, heading_starred: false, heading_number: None, + footnotes: Vec::new(), font_size: None, }; } @@ -1878,6 +1900,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph { heading_level: None, heading_starred: false, heading_number: None, + footnotes: Vec::new(), font_size: None, }; } @@ -1905,6 +1928,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph { heading_level: Some(level), heading_starred: starred, heading_number: None, + footnotes: Vec::new(), font_size: None, }; } @@ -1936,6 +1960,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph { heading_level: None, heading_starred: false, heading_number: None, + footnotes: Vec::new(), font_size: None, }; } @@ -1959,6 +1984,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph { heading_level: None, heading_starred: false, heading_number: None, + footnotes: Vec::new(), font_size: None, } } @@ -2057,6 +2083,7 @@ fn title_block(text: String, size: f64, space_before: i64) -> SourceParagraph { heading_level: None, heading_starred: false, heading_number: None, + footnotes: Vec::new(), font_size: Some((size * SCALE as f64) as i64), } } @@ -2220,12 +2247,39 @@ fn heading_font_size(level: u8, base: i64) -> i64 { base.saturating_mul(percent) / 100 } +/// Pull `\footnote{...}` bodies out of a paragraph, leaving a numbered +/// reference in the running text. Footnote numbers run across the document. +fn number_footnotes(paragraphs: &mut [SourceParagraph]) { + let mut number = 0u32; + for paragraph in paragraphs { + let source = paragraph.text.clone(); + let mut text = String::with_capacity(source.len()); + let mut rest = source.as_str(); + while let Some(index) = rest.find("\\footnote") { + text.push_str(&rest[..index]); + let after = rest[index + "\\footnote".len()..].trim_start(); + let Some((body, consumed)) = braced_group(after) else { + text.push_str(&rest[index..]); + rest = ""; + break; + }; + number += 1; + let _ = write!(text, " ({number})"); + paragraph.footnotes.push((number, body.trim().to_string())); + rest = &after[consumed..]; + } + text.push_str(rest); + paragraph.text = text; + } +} + fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Document { let mut paragraphs = expand_maketitle(paragraphs, geometry); let section_labels = number_sections(&mut paragraphs); resolve_section_refs(&mut paragraphs, §ion_labels); + number_footnotes(&mut paragraphs); let line_width = geometry.line_width.unwrap_or(480 * SCALE); - let units = paragraphs + let base_units: Vec = paragraphs .iter() .enumerate() .map(|(index, paragraph)| { @@ -2371,7 +2425,56 @@ fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Do unit }) .collect(); + // Footnotes follow their anchor paragraph as insertion units, so the page + // builder reserves room for them on the page that mentions them. + let mut units: Vec = Vec::with_capacity(base_units.len()); + let mut unit_for_paragraph = Vec::with_capacity(paragraphs.len()); + let mut footnote_count = 0usize; + for (paragraph, unit) in paragraphs.iter().zip(base_units) { + unit_for_paragraph.push(units.len()); + units.push(unit); + for (number, body) in ¶graph.footnotes { + footnote_count += 1; + let style = ParagraphStyle { + line_width, + font_size: 9 * SCALE, + par_indent: 0, + baselineskip: 11 * SCALE, + line_height: 11 * SCALE, + ..ParagraphStyle::default() + }; + let id = 1_000_000 + *number as u64; + let footnote = match inline_runs(body, ParagraphFont::Roman) { + Some(runs) => Unit::paragraph_with_style_and_runs(id, body.clone(), style, runs), + None => Unit::paragraph_with_style_and_face( + id, + body.clone(), + style, + ParagraphFont::Roman, + ), + }; + let height = footnote + .items + .iter() + .map(|item| match item { + VerticalItem::Paragraph(paragraph) => paragraph.height + paragraph.depth, + _ => 0, + }) + .sum::(); + units.push(Unit::insertion(id, 0, height, footnote.items)); + } + } let mut document = Document::new(700 * SCALE, units); + if footnote_count > 0 { + document.insertion_classes.push(InsertionClass { + number: 0, + fraction_percent: 100, + max_height: None, + skip: Some(12 * SCALE), + multiplier: 1000, + }); + document.insertion_skip = 12 * SCALE; + } // LaTeX sets \maxdepth=.5\topskip; sources may override it later. document.max_depth = 5 * SCALE; document.text_width = line_width; @@ -2379,7 +2482,7 @@ fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Do .iter() .enumerate() .filter(|(_, paragraph)| paragraph.page_break) - .map(|(index, _)| index) + .map(|(index, _)| unit_for_paragraph[index]) .collect(); document } @@ -2600,6 +2703,37 @@ mod tests { mod source_tests { use super::*; + #[test] + fn footnotes_become_page_insertions() { + let blocks = paragraphs("Body\\footnote{Note} tail").unwrap(); + let document = build_document(&blocks, &PageGeometry::default()); + assert_eq!(document.units.len(), 2); + assert_eq!(document.units[0].source, "Body (1) tail"); + let Some(VerticalItem::Insertion(insertion)) = document.units[1].items.first() else { + panic!("expected an insertion unit"); + }; + assert_eq!(insertion.class, 0); + assert!(insertion.height > 0); + assert_eq!(document.insertion_classes.len(), 1); + let engine = Engine::layout_paged(&document).expect("paged layout"); + assert_eq!(engine.pages().len(), 1); + assert_eq!(engine.pages()[0].insertions.len(), 1); + let list = + engine.pages()[0].display_list_with_layout(document.page_goal, document.text_float_sep); + assert!(list.items.iter().any(|item| { + matches!(item, texrra_tex_core::DisplayItem::Text { text, .. } if text == "N") + })); + } + + #[test] + fn footnotes_number_across_paragraphs() { + let blocks = paragraphs("One\\footnote{A}\n\nTwo\\footnote{B}").unwrap(); + let document = build_document(&blocks, &PageGeometry::default()); + assert_eq!(document.units[0].source, "One (1)"); + assert_eq!(document.units[2].source, "Two (2)"); + assert_eq!(document.units.len(), 4); + } + #[test] fn reads_hang_registers_from_the_preamble() { let (body, geometry) = geometry_and_body( diff --git a/tests/server.rs b/tests/server.rs index b729717..99180c1 100644 --- a/tests/server.rs +++ b/tests/server.rs @@ -484,6 +484,22 @@ fn route_d_renders_class_metadata_and_appendix() { assert!(svg.contains(">E"), "{svg}"); } +#[test] +fn route_d_renders_footnotes_as_insertions() { + let server = TestServer::start("route-d-footnotes"); + let response = server.request( + "POST", + "/api/route-d/preview", + b"Body text\\footnote{Zebra}.", + "text/plain", + ); + assert_eq!(response.status, 200, "{}", response.text()); + let value: Value = serde_json::from_slice(&response.body).expect("route-D JSON"); + let svg = value["pages"][0]["svg"].as_str().unwrap(); + assert!(svg.contains(">Z"), "{svg}"); + assert!(svg.contains("font-size=\"9.000\""), "{svg}"); +} + #[test] fn route_d_maps_sections_and_emphasis() { let server = TestServer::start("route-d-markup");