diff --git a/README.md b/README.md index 0043374..08ceec9 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. A `thebibliography` environment turns its `\bibitem` entries into numbered `[n]` paragraphs, and `\cite{...}` resolves to `[n]`/`[n, m]` (unknown keys print `[?]`). A `figure` environment becomes a float at its `[t]`/`[b]`/`[h]` placement, its `\caption` numbers as `Figure n:` and feeds `\ref`, and `\includegraphics[width=...]` reserves a rule placeholder. `table` environments likewise become floats carrying their captured `tabular` body, with `Table n:` captions that resolve from `\ref`. 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. Inside a project preview, `\input{...}` and `\include{...}` expand from files in the same project (a missing `.tex` suffix is added), so chapter files render in place; unknown paths stay as literal text. `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 — `, and each depth adds 12pt of indentation. +Route-D text faces follow the NFSS declarations and compose with the surrounding run: `\sffamily\bfseries` selects cmssbx10, `\sffamily\itshape` selects cmssi10, and bold italic sans substitutes cmssbx10 because Computer Modern has no sans bold italic. `\scshape`/`\textsc` select the real cmcsc10 small-caps face, `\slshape`/`\textsl` use cmsl10 (or cmbxsl10 when bold) rather than the italic cmti10, and `\ttfamily\itshape` reaches cmitt10. All twelve text programs (cmr10, cmbx10, cmti10, cmbxti10, cmtt10, cmss10, cmssbx10, cmssi10, cmcsc10, cmsl10, cmbxsl10, cmitt10) are embedded as Type1 outlines. Because Computer Modern has no bold small caps, a bold small-caps request falls back to cmbx10. Section-wide declarations such as `\bfseries` apply from where they appear to the end of their group, and `\em` toggles emphasis relative to the surrounding face. Paragraph base sizes come from `\fontsize{}{}` and the article size commands (`\tiny` through `\Huge`), scaling glyph metrics and the default interline glue while the measure, indentation and authored skips stay absolute. The class options `10pt`/`11pt`/`12pt` on `\documentclass[...]` set the default base size (and article `\baselineskip` of 12pt/13.6pt/14.5pt); a size command inside a paragraph 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 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, and the `abstract` environment expands to its heading and body. In route-D, math uses Computer Modern metrics from the bundled `cmmi10`, `cmsy10`, `cmex10`, `msbm10` and `eufm10` TFMs and embeds their Type1 programs, so italic letters, relation symbols, big operators, `\mathcal` capitals, `\mathbb` capitals and `\mathfrak` Fraktur letters each paint with their own face. Fractions can be written as `\frac` or with TeX's infix forms (`\over`, `\atop`, `\choose`, `\brace`, `\brack`, `\overwithdelims`, `\atopwithdelims`); only `\over`-style fractions draw a bar and fractions never draw parentheses. `\left`/`\right` choose CMEX delimiter sizes from the body extent using TeX's delimiterfactor and shortfall, `\middle` delimiters are sized with their group, and `\big`/`\Big`/`\bigg`/`\Bigg` paint at their selected CMEX size. `align`/`align*` displays share column widths, right-align even columns at their relations, and number each row (with `\tag`/`\notag` per row); `gather`/`gather*` centre each row instead. Inter-atom spacing uses TeX's 3/4/5mu classes (`1mu` is `1/18em`), `\mid` is a relation and `\colon` punctuation, and `\mskip`/`\mkern`/`\mspace`/`\hskip`/`\kern`/`\hspace` scan TeX dimensions, taking the natural width of any `plus`/`minus` parts. `\footnote{...}` leaves a numbered marker in the paragraph and sets the note as a 9pt page insertion at the bottom of the page that mentions it. A `thebibliography` environment turns its `\bibitem` entries into numbered `[n]` paragraphs, and `\cite{...}` resolves to `[n]`/`[n, m]` (unknown keys print `[?]`). A `figure` environment becomes a float at its `[t]`/`[b]`/`[h]` placement, its `\caption` numbers as `Figure n:` and feeds `\ref`, and `\includegraphics[width=...]` reserves a rule placeholder. `table` environments likewise become floats carrying their captured `tabular` body, with `Table n:` captions that resolve from `\ref`. Table captions sit above the tabular as in LaTeX, figure captions below the graphic, and `\caption*` leaves either unnumbered. Theorem-like environments (`theorem`, `lemma`, `corollary`, `proposition`, `definition`, `example`, `remark`, `proof`) produce a bold numbered heading with an optional `[title]`, italic statements for the theorem group, and unnumbered proofs, with `\label`/`\ref` resolving to the theorem number. `\newtheorem{env}[shared]{Display}`, `\newtheorem{env}{Display}[section]` and `\newtheorem*{env}{Display}` add custom theorem environments: a shared counter numbers the env with its parent, `[section]` scopes numbers to the enclosing section, and the starred form stays unnumbered. Inside a project preview, `\input{...}` and `\include{...}` expand from files in the same project (a missing `.tex` suffix is added), so chapter files render in place; unknown paths stay as literal text. `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 — `, and each depth adds 12pt of indentation. 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 023742c..afe24a2 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`). 637 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 640 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 ab460b2..263d8e4 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; a `thebibliography` environment is removed from the body, its `\bibitem` entries become numbered `[n]` paragraphs, and `\cite{...}` resolves to `[n]`/`[n, m]` (unknown keys print `[?]`); a `figure` environment becomes a float at its `[t]`/`[b]`/`[h]` placement, its `\caption` numbers as `Figure n:` and resolves `\ref`, and `\includegraphics[width=...,height=...]` reserves a rule placeholder; a `table` environment becomes a float that carries its captured `tabular` body and a numbered `Table n:` caption; `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; inside a project preview `\input{...}`/`\include{...}` expand from the project's files (the `.tex` suffix may be omitted) while unknown files stay literal text; 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 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`); `\footnote{...}` becomes a numbered 9pt page insertion on the page that mentions it; a `thebibliography` environment is removed from the body, its `\bibitem` entries become numbered `[n]` paragraphs, and `\cite{...}` resolves to `[n]`/`[n, m]` (unknown keys print `[?]`); a `figure` environment becomes a float at its `[t]`/`[b]`/`[h]` placement, its `\caption` numbers as `Figure n:` and resolves `\ref`, and `\includegraphics[width=...,height=...]` reserves a rule placeholder; a `table` environment becomes a float that carries its captured `tabular` body and a numbered `Table n:` caption whose text sits above the tabular as in LaTeX, while `\caption*` stays unnumbered for either float kind; `theorem`/`lemma`/`corollary`/`proposition`/`definition`/`example`/`remark`/`proof` environments get a bold numbered heading (optionally with `[title]`), italic statements for the theorem group, an unnumbered proof, and `\label`/`\ref` targets; `\newtheorem{env}[shared]{Display}`, `\newtheorem{env}{Display}[section]` and `\newtheorem*{env}{Display}` define custom environments with shared counters and section-scoped numbers; `itemize`/`enumerate`/`description` lists nest with depth-aware bullets (`•`, `–`, `*`), lettered/roman sub-labels and 12pt-per-level indentation; inside a project preview `\input{...}`/`\include{...}` expand from the project's files (the `.tex` suffix may be omitted) while unknown files stay literal text; 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 637 tests (402 route-D unit, 85 engine binary unit, 8 route-D integration, 35 oracle, 71 v1 integration, 31 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 640 tests (402 route-D unit, 88 engine binary unit, 8 route-D integration, 35 oracle, 71 v1 integration, 31 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 6aece89..3a63ee3 100755 --- a/src/route_d.rs +++ b/src/route_d.rs @@ -1042,6 +1042,7 @@ struct FloatSpec { width: Option, height: Option, caption: Option, + caption_starred: bool, /// Index into `PageGeometry::tabular` for a captured table body. table: Option, } @@ -1324,9 +1325,12 @@ fn float_block(raw: &str) -> Option { } None => (FloatPlacement::Top, inner), }; - let mut caption = figure_caption(inner); + let (mut caption, caption_starred) = match figure_caption(inner) { + Some((text, starred)) => (Some(text), starred), + None => (None, false), + }; let labels = figure_labels(inner); - if !labels.is_empty() { + if !labels.is_empty() && !caption_starred { let mut text = caption.unwrap_or_default(); for label in labels { let _ = write!(text, "\\label{{{label}}}"); @@ -1363,6 +1367,7 @@ fn float_block(raw: &str) -> Option { width, height, caption, + caption_starred, table, }), }) @@ -1388,9 +1393,13 @@ fn figure_placement(spec: &str) -> FloatPlacement { FloatPlacement::Top } -fn figure_caption(inner: &str) -> Option { +fn figure_caption(inner: &str) -> Option<(String, bool)> { let index = inner.find("\\caption")?; let after = inner[index + "\\caption".len()..].trim_start(); + let (after, starred) = match after.strip_prefix('*') { + Some(rest) => (rest.trim_start(), true), + None => (after, false), + }; let after = match after.strip_prefix('[') { Some(short) => match short.find(']') { Some(end) => short[end + 1..].trim_start(), @@ -1399,7 +1408,7 @@ fn figure_caption(inner: &str) -> Option { None => after, }; let (body, _) = braced_group(after)?; - Some(body.trim().to_string()) + Some((body.trim().to_string(), starred)) } fn figure_labels(inner: &str) -> Vec { @@ -2726,6 +2735,32 @@ fn title_large_size(base_font_size: i64) -> f64 { } /// Remove `\thanks{...}` groups and join multiple authors set with `\and`. +/// Rewrite `\thanks{...}` notes as footnotes so they become page insertions +/// instead of disappearing with the title block. +fn thanks_to_footnotes(text: &str) -> String { + let mut out = String::new(); + let mut rest = text; + loop { + let Some(index) = rest.find("\\thanks") else { + out.push_str(rest); + break; + }; + out.push_str(&rest[..index]); + let after = &rest[index + "\\thanks".len()..]; + let trimmed = after.trim_start(); + let Some((inner, consumed)) = braced_group(trimmed) else { + out.push_str("\\thanks"); + rest = after; + continue; + }; + out.push_str("\\footnote{"); + out.push_str(&inner); + out.push('}'); + rest = &trimmed[consumed..]; + } + out +} + fn clean_title_value(text: &str) -> String { let mut out = String::new(); let mut rest = text; @@ -2814,7 +2849,7 @@ fn expand_maketitle(blocks: &[SourceParagraph], geometry: &PageGeometry) -> Vec< } if let Some(title) = geometry.title.as_deref().filter(|title| !title.is_empty()) { let mut paragraph = title_block( - clean_title_value(title), + clean_title_value(&thanks_to_footnotes(title)), title_size(base), block.space_before, ); @@ -2828,14 +2863,14 @@ fn expand_maketitle(blocks: &[SourceParagraph], geometry: &PageGeometry) -> Vec< .filter(|author| !author.is_empty()) { result.push(title_block( - clean_title_value(author), + clean_title_value(&thanks_to_footnotes(author)), title_large_size(base), author_space, )); } if let Some(date) = geometry.date.as_deref().filter(|date| !date.is_empty()) { result.push(title_block( - clean_title_value(date), + clean_title_value(&thanks_to_footnotes(date)), title_large_size(base), 12 * SCALE, )); @@ -3061,6 +3096,11 @@ fn number_floats(paragraphs: &mut [SourceParagraph]) -> Vec<(String, String)> { let Some(caption) = spec.caption.as_mut() else { continue; }; + let found = take_labels(caption); + if spec.caption_starred { + *caption = caption.trim().to_string(); + continue; + } let number = match spec.kind { FloatKind::Figure => { figures += 1; @@ -3071,7 +3111,6 @@ fn number_floats(paragraphs: &mut [SourceParagraph]) -> Vec<(String, String)> { tables } }; - let found = take_labels(caption); *caption = format!( "{} {number}: {}", spec.kind.caption_prefix(), @@ -3135,6 +3174,28 @@ fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Do if let Some(spec) = ¶graph.float { let width = line_width; let mut content = Vec::new(); + let caption_unit = spec.caption.as_ref().map(|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() + }; + Unit::paragraph_with_style_and_face( + index as u64, + caption.clone(), + style, + ParagraphFont::Roman, + ) + }); + if spec.kind == FloatKind::Table { + if let Some(caption) = &caption_unit { + content.extend(caption.items.clone()); + } + } 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); @@ -3155,23 +3216,10 @@ fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Do content.extend(table_unit.items); } } - 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); + if spec.kind == FloatKind::Figure { + if let Some(caption) = &caption_unit { + content.extend(caption.items.clone()); + } } let mut unit = Unit::float_with_content(index as u64, spec.placement, width, 0, content); @@ -3684,6 +3732,50 @@ mod source_tests { assert_eq!(*height, 100 * SCALE); } + #[test] + fn table_captions_sit_above_their_tabular() { + let source = "\\begin{table}[t]\n\\caption{Numbers}\n\\begin{tabular}{ll}\na & b \\\\\n\\end{tabular}\n\\end{table}"; + let (body, geometry) = geometry_and_body(source); + let blocks = paragraphs(&body).expect("blocks"); + assert_eq!(blocks.len(), 1); + let document = build_document(&blocks, &geometry); + let VerticalItem::Float(float) = &document.units[0].items[0] else { + panic!("expected a float"); + }; + let caption = match &float.content[0] { + VerticalItem::Paragraph(paragraph) => paragraph, + other => panic!("expected the caption first, got {other:?}"), + }; + let text: String = caption + .lines + .iter() + .flatten() + .map(|item| match item { + texrra_tex_core::paragraph::HorizontalItem::Box(character) => { + character.character.unwrap_or(' ') + } + texrra_tex_core::paragraph::HorizontalItem::Glue { width, .. } if *width > 0 => ' ', + _ => '\0', + }) + .filter(|character| *character != '\0') + .collect(); + assert_eq!(text, "Table 1: Numbers"); + assert!(matches!(float.content[1], VerticalItem::Halign(_))); + } + + #[test] + fn starred_captions_stay_unnumbered() { + let source = "\\begin{figure}[t]\n\\caption*{Note}\n\\end{figure}\n\n\\begin{figure}[t]\n\\caption{Numbered}\n\\end{figure}"; + let (body, _) = geometry_and_body(source); + let mut blocks = paragraphs(&body).expect("blocks"); + assert_eq!(blocks.len(), 2); + number_floats(&mut blocks); + let first = blocks[0].float.as_ref().expect("first float"); + assert_eq!(first.caption.as_deref(), Some("Note")); + let second = blocks[1].float.as_ref().expect("second float"); + assert_eq!(second.caption.as_deref(), Some("Figure 1: Numbered")); + } + #[test] fn table_floats_carry_their_tabular() { let source = r"\begin{table}[t] @@ -4301,15 +4393,60 @@ A definition. } #[test] - fn maketitle_joins_authors_and_drops_thanks() { + fn maketitle_joins_authors_and_turns_thanks_into_footnotes() { let source = "\\title{Paper}\n\\author{A \\and B \\thanks{Support}}\n\n\\maketitle\n\nBody"; let (body, geometry) = geometry_and_body(source); let blocks = paragraphs(&body).expect("blocks"); let expanded = expand_maketitle(&blocks, &geometry); - assert_eq!(expanded[1].text, "A, B"); + assert_eq!(expanded[1].text, "A, B \\footnote{Support}"); assert!(!expanded[1].text.contains("thanks")); } + #[test] + fn title_thanks_becomes_a_page_footnote() { + let source = "\\title{Paper}\n\\author{Ada\\thanks{Funded}}\n\n\\maketitle\n\nBody"; + let (body, geometry) = geometry_and_body(source); + let blocks = paragraphs(&body).expect("blocks"); + let document = build_document(&blocks, &geometry); + let author = document + .units + .iter() + .find(|unit| unit.source.starts_with("Ada")) + .expect("author unit"); + assert_eq!(author.source, "Ada (1)"); + let insertion = document + .units + .iter() + .find_map(|unit| { + unit.items.iter().find_map(|item| match item { + VerticalItem::Insertion(insertion) => Some(insertion), + _ => None, + }) + }) + .expect("footnote insertion"); + let text: String = insertion + .items + .iter() + .find_map(|item| match item { + VerticalItem::Paragraph(paragraph) => Some( + paragraph + .lines + .iter() + .flatten() + .filter_map(|item| match item { + texrra_tex_core::paragraph::HorizontalItem::Box(character) => { + character.character + } + _ => None, + }) + .collect::(), + ), + _ => None, + }) + .expect("footnote paragraph"); + assert_eq!(text, "Funded"); + } + #[test] fn maketitle_paints_its_title_block() { let source = "\\title{Paper}\n\\author{Ada}\n\n\\maketitle\n\nBody";