Carry figure environments as floats

This commit is contained in:
gloamxun committed 2026-10-24 20:44:37 +08:00
1 parent ea06e299d6
commit 5c04fa83ab
4 files changed
+277 -6

No files matched your search

+1 -1
View File
@@ -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{<size>}{<baselineskip>}` 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 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{<size>}{<baselineskip>}` 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 `[?]`). A `figure` environment becomes a float at its `[t]`/`[b]`/`[h]` placement, its `\caption` numbers as `Figure n:` and feeds `\ref`, and `\includegraphics[width=...]` reserves a rule placeholder.
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.
+1 -1
View File
@@ -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`). 621 workspace tests are green and no oracle
PDF opt-in with `?engine=route-d`). 624 workspace tests are green and no oracle
fixture is ignored.
Status after G1 (P0-P2): the paragraph model reproduces TeX's passes,
+2 -2
View File
@@ -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; 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 |
| 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 `[?]`); a `figure` environment becomes a float at its `[t]`/`[b]`/`[h]` placement, its `\caption` numbers as `Figure n:` and resolves `\ref`, and `\includegraphics[width=...,height=...]` reserves a rule placeholder; 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 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.
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 624 tests (402 route-D unit, 73 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
+273 -2
View File
@@ -13,7 +13,8 @@ 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, InsertionClass, ParagraphFont, ParagraphStyle, Unit, VerticalItem,
Document, Engine, FloatPlacement, InsertionClass, ParagraphFont, ParagraphStyle, Unit,
VerticalItem,
};
const SCALE: i64 = 65_536;
@@ -945,6 +946,17 @@ struct SourceParagraph {
/// Footnote bodies extracted from this paragraph, with their numbers.
footnotes: Vec<(u32, String)>,
font_size: Option<i64>,
/// A `figure` environment carried as a float unit.
float: Option<FloatSpec>,
}
/// A `figure` environment: placement, graphics size and caption.
#[derive(Clone, PartialEq, Eq)]
struct FloatSpec {
placement: FloatPlacement,
width: Option<i64>,
height: Option<i64>,
caption: Option<String>,
}
/// One row of an `align`/`gather` environment.
@@ -1025,6 +1037,7 @@ fn paragraphs(source: &str) -> Result<Vec<SourceParagraph>, String> {
heading_starred: false,
heading_number: None,
footnotes: Vec::new(),
float: None,
font_size: None,
});
pending = (0, 0, 0);
@@ -1145,7 +1158,129 @@ fn take_labels(text: &mut String) -> Vec<String> {
labels
}
/// Parse a `figure` environment into a single float block.
fn figure_block(raw: &str) -> Option<SourceParagraph> {
let inner = raw
.trim()
.strip_prefix("\\begin{figure}")?
.strip_suffix("\\end{figure}")?
.trim();
let (placement, inner) = match inner.strip_prefix('[') {
Some(rest) => {
let end = rest.find(']')?;
(figure_placement(&rest[..end]), rest[end + 1..].trim_start())
}
None => (FloatPlacement::Top, inner),
};
let mut caption = figure_caption(inner);
let labels = figure_labels(inner);
if !labels.is_empty() {
let mut text = caption.unwrap_or_default();
for label in labels {
let _ = write!(text, "\\label{{{label}}}");
}
caption = Some(text);
}
let (width, height) = figure_graphic(inner).unwrap_or((None, None));
Some(SourceParagraph {
text: String::new(),
font: ParagraphFont::Roman,
line_height: 12,
math: false,
left_skip: 0,
centered: false,
right_aligned: false,
space_before: 8 * SCALE,
space_stretch: 2 * SCALE,
space_shrink: 0,
page_break: false,
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,
float: Some(FloatSpec {
placement,
width,
height,
caption,
}),
})
}
fn figure_placement(spec: &str) -> FloatPlacement {
for option in spec.chars() {
match option {
'b' => return FloatPlacement::Bottom,
'h' => return FloatPlacement::Here,
't' => return FloatPlacement::Top,
_ => {}
}
}
FloatPlacement::Top
}
fn figure_caption(inner: &str) -> Option<String> {
let index = inner.find("\\caption")?;
let after = inner[index + "\\caption".len()..].trim_start();
let after = match after.strip_prefix('[') {
Some(short) => match short.find(']') {
Some(end) => short[end + 1..].trim_start(),
None => after,
},
None => after,
};
let (body, _) = braced_group(after)?;
Some(body.trim().to_string())
}
fn figure_labels(inner: &str) -> Vec<String> {
let mut labels = Vec::new();
let mut rest = inner;
while let Some(index) = rest.find("\\label") {
let after = rest[index + "\\label".len()..].trim_start();
let Some((label, consumed)) = braced_group(after) else {
break;
};
labels.push(label.trim().to_string());
rest = &after[consumed..];
}
labels
}
/// Read the placeholder dimensions from an `\includegraphics` option list.
fn figure_graphic(inner: &str) -> Option<(Option<i64>, Option<i64>)> {
let index = inner.find("\\includegraphics")?;
let after = inner[index + "\\includegraphics".len()..].trim_start();
let (options, after) = match after.strip_prefix('[') {
Some(rest) => {
let end = rest.find(']')?;
(&rest[..end], rest[end + 1..].trim_start())
}
None => ("", after),
};
let (_, _) = braced_group(after)?;
let mut width = None;
let mut height = None;
for part in options.split(',') {
let part = part.trim();
if let Some(value) = part.strip_prefix("width=") {
width = parse_dimension(value.trim());
} else if let Some(value) = part.strip_prefix("height=") {
height = parse_dimension(value.trim());
}
}
Some((width, height))
}
fn parse_blocks_raw(raw: &str) -> Vec<SourceParagraph> {
if let Some(block) = figure_block(raw) {
return vec![block];
}
if let Some(body) = raw
.trim()
.strip_prefix("\\begin{abstract}")
@@ -1171,6 +1306,7 @@ fn parse_blocks_raw(raw: &str) -> Vec<SourceParagraph> {
heading_starred: false,
heading_number: None,
footnotes: Vec::new(),
float: None,
font_size: Some((12.0 * SCALE as f64) as i64),
};
let body = SourceParagraph {
@@ -1193,6 +1329,7 @@ fn parse_blocks_raw(raw: &str) -> Vec<SourceParagraph> {
heading_starred: false,
heading_number: None,
footnotes: Vec::new(),
float: None,
font_size: Some((9.0 * SCALE as f64) as i64),
};
if body.text.is_empty() {
@@ -1263,6 +1400,7 @@ fn parse_blocks_raw(raw: &str) -> Vec<SourceParagraph> {
heading_starred: false,
heading_number: None,
footnotes: Vec::new(),
float: None,
font_size: None,
}
})
@@ -1297,6 +1435,7 @@ fn parse_blocks_raw(raw: &str) -> Vec<SourceParagraph> {
heading_starred: false,
heading_number: None,
footnotes: Vec::new(),
float: None,
font_size: None,
}];
}
@@ -1340,6 +1479,7 @@ fn parse_blocks_raw(raw: &str) -> Vec<SourceParagraph> {
heading_starred: false,
heading_number: None,
footnotes: Vec::new(),
float: None,
font_size: None,
}
})
@@ -1863,6 +2003,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
heading_starred: false,
heading_number: None,
footnotes: Vec::new(),
float: None,
font_size: None,
};
}
@@ -1889,6 +2030,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
heading_starred: false,
heading_number: None,
footnotes: Vec::new(),
float: None,
};
}
if let Some(inner) = raw
@@ -1915,6 +2057,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
heading_starred: false,
heading_number: None,
footnotes: Vec::new(),
float: None,
font_size: None,
};
}
@@ -1942,6 +2085,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
heading_starred: false,
heading_number: None,
footnotes: Vec::new(),
float: None,
font_size: None,
};
}
@@ -1973,6 +2117,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
heading_starred: false,
heading_number: None,
footnotes: Vec::new(),
float: None,
font_size: None,
};
}
@@ -2001,6 +2146,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
heading_starred: starred,
heading_number: None,
footnotes: Vec::new(),
float: None,
font_size: None,
};
}
@@ -2033,6 +2179,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
heading_starred: false,
heading_number: None,
footnotes: Vec::new(),
float: None,
font_size: None,
};
}
@@ -2057,6 +2204,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
heading_starred: false,
heading_number: None,
footnotes: Vec::new(),
float: None,
font_size: None,
}
}
@@ -2156,6 +2304,7 @@ fn title_block(text: String, size: f64, space_before: i64) -> SourceParagraph {
heading_starred: false,
heading_number: None,
footnotes: Vec::new(),
float: None,
font_size: Some((size * SCALE as f64) as i64),
}
}
@@ -2345,6 +2494,27 @@ fn number_footnotes(paragraphs: &mut [SourceParagraph]) {
}
}
/// Number figure captions and return their label targets.
fn number_figures(paragraphs: &mut [SourceParagraph]) -> Vec<(String, String)> {
let mut number = 0u32;
let mut labels = Vec::new();
for paragraph in paragraphs {
let Some(spec) = paragraph.float.as_mut() else {
continue;
};
let Some(caption) = spec.caption.as_mut() else {
continue;
};
number += 1;
let found = take_labels(caption);
*caption = format!("Figure {number}: {}", caption.trim());
for label in found {
labels.push((label, number.to_string()));
}
}
labels
}
/// Append `thebibliography` entries as numbered paragraphs.
fn append_bibliography(paragraphs: &mut Vec<SourceParagraph>, bibliography: &[(String, String)]) {
for (index, (_, entry)) in bibliography.iter().enumerate() {
@@ -2368,6 +2538,7 @@ fn append_bibliography(paragraphs: &mut Vec<SourceParagraph>, bibliography: &[(S
heading_starred: false,
heading_number: None,
footnotes: Vec::new(),
float: None,
font_size: None,
});
}
@@ -2376,7 +2547,9 @@ fn append_bibliography(paragraphs: &mut Vec<SourceParagraph>, bibliography: &[(S
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, &section_labels);
let mut references = section_labels;
references.extend(number_figures(&mut paragraphs));
resolve_section_refs(&mut paragraphs, &references);
number_footnotes(&mut paragraphs);
resolve_citations(&mut paragraphs, &geometry.bibliography);
append_bibliography(&mut paragraphs, &geometry.bibliography);
@@ -2385,6 +2558,42 @@ fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Do
.iter()
.enumerate()
.map(|(index, paragraph)| {
if let Some(spec) = &paragraph.float {
let width = line_width;
let mut content = Vec::new();
if spec.height.is_some() || spec.width.is_some() {
let rule_width = spec.width.unwrap_or(width).min(width);
let rule_height = spec.height.unwrap_or(rule_width / 2);
content.push(VerticalItem::Rule {
width: rule_width,
height: rule_height,
});
}
if let Some(caption) = &spec.caption {
let style = ParagraphStyle {
line_width: width,
centered: true,
par_indent: 0,
font_size: 9 * SCALE,
baselineskip: 11 * SCALE,
line_height: 11 * SCALE,
..ParagraphStyle::default()
};
let caption_unit = Unit::paragraph_with_style_and_face(
index as u64,
caption.clone(),
style,
ParagraphFont::Roman,
);
content.extend(caption_unit.items);
}
let mut unit =
Unit::float_with_content(index as u64, spec.placement, width, 0, content);
unit.space_before = paragraph.space_before;
unit.space_stretch = paragraph.space_stretch;
unit.space_shrink = paragraph.space_shrink;
return unit;
}
if let Some(table) = table_reference(&paragraph.text) {
if let Some((template, source)) = geometry.tabular.get(table) {
let mut unit = Unit::halign_from_source_with_template_and_tabskips(
@@ -2827,6 +3036,68 @@ mod source_tests {
}));
}
#[test]
fn figures_become_float_units() {
let source = "\\begin{figure}[h]\n\\caption{A caption}\\label{fig:a}\n\\end{figure}";
let (body, geometry) = geometry_and_body(source);
let blocks = paragraphs(&body).unwrap();
let document = build_document(&blocks, &geometry);
assert_eq!(document.units.len(), 1);
let Some(VerticalItem::Float(float)) = document.units[0].items.first() else {
panic!("expected a float unit");
};
assert_eq!(float.placement, FloatPlacement::Here);
let mut caption = String::new();
for item in &float.content {
if let VerticalItem::Paragraph(paragraph) = item {
for line in &paragraph.lines {
for item in line {
match item {
texrra_tex_core::paragraph::HorizontalItem::Box(box_) => {
if let Some(character) = box_.character {
caption.push(character);
}
}
texrra_tex_core::paragraph::HorizontalItem::Glue { width, .. } => {
if *width > 0 {
caption.push(' ');
}
}
_ => {}
}
}
}
}
}
assert_eq!(caption, "Figure 1: A caption");
}
#[test]
fn figure_labels_resolve_references() {
let source = "See \\ref{fig:a}.\n\n\\begin{figure}\n\\caption{Caption}\n\\label{fig:a}\n\\end{figure}";
let (body, geometry) = geometry_and_body(source);
let blocks = paragraphs(&body).unwrap();
let document = build_document(&blocks, &geometry);
assert_eq!(document.units[0].source, "See 1.");
}
#[test]
fn figure_graphics_reserve_a_placeholder() {
let source = "\\begin{figure}[b]\n\\includegraphics[width=200pt]{plot.pdf}\\caption{Plot}\n\\end{figure}";
let (body, geometry) = geometry_and_body(source);
let blocks = paragraphs(&body).unwrap();
let document = build_document(&blocks, &geometry);
let Some(VerticalItem::Float(float)) = document.units[0].items.first() else {
panic!("expected a float unit");
};
assert_eq!(float.placement, FloatPlacement::Bottom);
let Some(VerticalItem::Rule { width, height }) = float.content.first() else {
panic!("expected a graphics rule");
};
assert_eq!(*width, 200 * SCALE);
assert_eq!(*height, 100 * SCALE);
}
#[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}";