From ea06e299d6f5e100af6f3e9fbb3a914bb631ce56 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Sat, 24 Oct 2026 20:38:44 +0800 Subject: [PATCH] Resolve citations from a thebibliography block --- README.md | 2 +- docs/ROUTE_D_PLAN.md | 2 +- docs/TEX_CORE.md | 4 +- src/route_d.rs | 130 ++++++++++++++++++++++++++++++++++++++++++- tests/server.rs | 18 ++++++ 5 files changed, 150 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index b1eef3f..008f4e4 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. `\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 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. A `thebibliography` environment turns its `\bibitem` entries into numbered `[n]` paragraphs, and `\cite{...}` resolves to `[n]`/`[n, m]` (unknown keys print `[?]`). 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 66b613c..a6cfc89 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`). 618 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 621 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 5bd0294..874716c 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`); `\footnote{...}` becomes a numbered 9pt page insertion on the page that mentions it; 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; 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 `[?]`); 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 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. +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 621 tests (402 route-D unit, 70 engine binary unit, 8 route-D integration, 35 oracle, 71 v1 integration, 30 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 2fafc34..69df5b0 100755 --- a/src/route_d.rs +++ b/src/route_d.rs @@ -161,6 +161,8 @@ struct PageGeometry { author: Option, /// `\date{...}` captured from the preamble. date: Option, + /// `thebibliography` entries: label key and entry text, in order. + bibliography: Vec<(String, String)>, } /// Pull `\hoffset`/`\voffset`/`\paperwidth`/`\paperheight`/`\vsize`/ @@ -512,13 +514,83 @@ fn table_reference(text: &str) -> Option { /// Strip geometry assignments from the whole source (preamble included) and /// return the LaTeX body with them removed. fn geometry_and_body(source: &str) -> (String, PageGeometry) { - let (stripped, geometry) = strip_page_geometry(source); + let (stripped, mut geometry) = strip_page_geometry(source); // Removed assignments can leave blank lines at the edges; they are not // paragraphs of their own. - let body = latex_body(&stripped).trim_matches('\n').to_string(); + let mut body = latex_body(&stripped).trim_matches('\n').to_string(); + geometry.bibliography = extract_bibliography(&mut body); (body, geometry) } +/// Remove a `thebibliography` environment from the body and return its +/// `\bibitem{key}` entries in order. +fn extract_bibliography(body: &mut String) -> Vec<(String, String)> { + let begin = r"\begin{thebibliography}"; + let end = r"\end{thebibliography}"; + let Some(start) = body.find(begin) else { + return Vec::new(); + }; + let after_begin = start + begin.len(); + let Some(offset) = body[after_begin..].find(end) else { + return Vec::new(); + }; + let inner_start = body[after_begin..] + .find('}') + .map_or(after_begin, |close| after_begin + close + 1); + let inner = body[inner_start..after_begin + offset].to_string(); + body.replace_range(start..after_begin + offset + end.len(), ""); + let mut entries = Vec::new(); + let mut rest = inner.as_str(); + while let Some(index) = rest.find(r"\bibitem") { + let after = rest[index + r"\bibitem".len()..].trim_start(); + let after = match after.strip_prefix('[') { + Some(label) => match label.split_once(']') { + Some((_, tail)) => tail.trim_start(), + None => after, + }, + None => after, + }; + let Some((key, consumed)) = braced_group(after) else { + break; + }; + let tail = &after[consumed..]; + let next = tail.find(r"\bibitem").unwrap_or(tail.len()); + entries.push((key.trim().to_string(), tail[..next].trim().to_string())); + rest = &tail[next..]; + } + entries +} + +/// Replace `\cite{...}` with `[n]`/`[n, m]` from the bibliography order. +fn resolve_citations(paragraphs: &mut [SourceParagraph], bibliography: &[(String, String)]) { + let keys: Vec<&str> = bibliography.iter().map(|(key, _)| key.as_str()).collect(); + for paragraph in paragraphs { + let mut text = String::with_capacity(paragraph.text.len()); + let mut rest = paragraph.text.as_str(); + while let Some(index) = rest.find(r"\cite") { + text.push_str(&rest[..index]); + let after = rest[index + r"\cite".len()..].trim_start(); + let Some((body, consumed)) = braced_group(after) else { + text.push_str(&rest[index..]); + rest = ""; + break; + }; + let numbers: Vec = body + .split(',') + .map(|key| { + keys.iter() + .position(|candidate| *candidate == key.trim()) + .map_or_else(|| "?".to_string(), |position| (position + 1).to_string()) + }) + .collect(); + let _ = write!(text, "[{}]", numbers.join(", ")); + rest = &after[consumed..]; + } + text.push_str(rest); + paragraph.text = text; + } +} + fn apply_geometry(document: &mut Document, geometry: &PageGeometry) { document.h_offset = geometry.origin.h_offset; document.v_offset = geometry.origin.v_offset; @@ -2273,11 +2345,41 @@ fn number_footnotes(paragraphs: &mut [SourceParagraph]) { } } +/// Append `thebibliography` entries as numbered paragraphs. +fn append_bibliography(paragraphs: &mut Vec, bibliography: &[(String, String)]) { + for (index, (_, entry)) in bibliography.iter().enumerate() { + paragraphs.push(SourceParagraph { + text: format!("[{}] {entry}", index + 1), + page_break: false, + centered: false, + right_aligned: false, + font: ParagraphFont::Roman, + line_height: 12, + math: false, + left_skip: 0, + space_before: if index == 0 { 12 * SCALE } else { 4 * SCALE }, + space_stretch: 2 * SCALE, + space_shrink: 0, + equation_number: None, + equation_tag: None, + equation_rows: Vec::new(), + align_centered: false, + heading_level: None, + heading_starred: false, + heading_number: None, + footnotes: Vec::new(), + font_size: None, + }); + } +} + 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); + resolve_citations(&mut paragraphs, &geometry.bibliography); + append_bibliography(&mut paragraphs, &geometry.bibliography); let line_width = geometry.line_width.unwrap_or(480 * SCALE); let base_units: Vec = paragraphs .iter() @@ -2725,6 +2827,30 @@ mod source_tests { })); } + #[test] + fn bibliography_entries_resolve_citations() { + let source = "See \\cite{alpha} and \\cite{alpha,beta}.\n\n\\begin{thebibliography}{9}\n\\bibitem{alpha} Alpha entry.\n\\bibitem{beta} Beta entry.\n\\end{thebibliography}"; + let (body, geometry) = geometry_and_body(source); + assert_eq!(geometry.bibliography.len(), 2); + let blocks = paragraphs(&body).unwrap(); + let document = build_document(&blocks, &geometry); + let sources: Vec<&str> = document + .units + .iter() + .map(|unit| unit.source.as_str()) + .collect(); + assert!(sources.contains(&"See [1] and [1, 2]."), "{sources:?}"); + assert!(sources.contains(&"[1] Alpha entry."), "{sources:?}"); + assert!(sources.contains(&"[2] Beta entry."), "{sources:?}"); + } + + #[test] + fn missing_citations_print_a_question_mark() { + let blocks = paragraphs("See \\cite{missing}.").unwrap(); + let document = build_document(&blocks, &PageGeometry::default()); + assert_eq!(document.units[0].source, "See [?]."); + } + #[test] fn footnotes_number_across_paragraphs() { let blocks = paragraphs("One\\footnote{A}\n\nTwo\\footnote{B}").unwrap(); diff --git a/tests/server.rs b/tests/server.rs index 99180c1..1c13b0e 100644 --- a/tests/server.rs +++ b/tests/server.rs @@ -500,6 +500,24 @@ fn route_d_renders_footnotes_as_insertions() { assert!(svg.contains("font-size=\"9.000\""), "{svg}"); } +#[test] +fn route_d_renders_bibliography_citations() { + let server = TestServer::start("route-d-bibliography"); + let source = "See \\cite{alpha}.\n\n\\begin{thebibliography}{9}\n\\bibitem{alpha} Zeta entry.\n\\end{thebibliography}"; + let response = server.request( + "POST", + "/api/route-d/preview", + source.as_bytes(), + "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(">["), "{svg}"); + assert!(!svg.contains("bibitem"), "{svg}"); +} + #[test] fn route_d_maps_sections_and_emphasis() { let server = TestServer::start("route-d-markup");