From 4ca3302367b49844e4d375762c17ed4be3a1591a Mon Sep 17 00:00:00 2001 From: GloamXun Date: Sat, 24 Oct 2026 21:00:45 +0800 Subject: [PATCH] Define custom theorem environments with newtheorem Parse \newtheorem{env}[shared]{Display}, \newtheorem{env}{Display}[within] and \newtheorem*{env}{Display} from the preamble. Custom environments gain a bold heading with their display name, share counters through the optional parent, and can scope their numbers to the enclosing section; the starred form stays unnumbered. Unrecognised files and cycles are unaffected. --- README.md | 2 +- docs/ROUTE_D_PLAN.md | 2 +- docs/TEX_CORE.md | 4 +- src/route_d.rs | 240 +++++++++++++++++++++++++++++++++++-------- 4 files changed, 203 insertions(+), 45 deletions(-) diff --git a/README.md b/README.md index 15099b3..f4b3954 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. 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. +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. 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 60982eb..b72989a 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`). 631 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 634 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 a7f92ec..b284b4e 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; 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 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; 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 631 tests (402 route-D unit, 79 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 634 tests (402 route-D unit, 82 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 4fa91df..f695164 100755 --- a/src/route_d.rs +++ b/src/route_d.rs @@ -47,7 +47,7 @@ fn latex_body(source: &str) -> &str { /// edits fall back to a full layout. The v1 project preview remains the default. pub fn project_preview_json(project_id: &str, source: &str) -> Result { let (body, geometry) = geometry_and_body(source); - let paragraphs = paragraphs(&body)?; + let paragraphs = paragraphs_with_definitions(&body, &geometry.theorem_definitions)?; let mut document = build_document(¶graphs, &geometry); apply_geometry(&mut document, &geometry); let mut sessions = project_sessions() @@ -164,6 +164,55 @@ struct PageGeometry { date: Option, /// `thebibliography` entries: label key and entry text, in order. bibliography: Vec<(String, String)>, + /// `\newtheorem` definitions from the preamble. + theorem_definitions: Vec, +} + +/// A `\newtheorem` declaration: display name, shared counter and section scope. +#[derive(Clone, Debug, PartialEq, Eq)] +struct TheoremDefinition { + name: String, + display: String, + shared: Option, + within: Option, + starred: bool, +} + +/// Parse `\newtheorem{env}[shared]{Display}`, +/// `\newtheorem{env}{Display}[within]` and `\newtheorem*{env}{Display}`. +fn newtheorem_definition(line: &str) -> Option { + let rest = line.strip_prefix("\\newtheorem")?; + let (starred, rest) = match rest.strip_prefix('*') { + Some(rest) => (true, rest), + None => (false, rest), + }; + let rest = rest.trim_start(); + let (name, consumed) = braced_group(rest)?; + let mut rest = rest[consumed..].trim_start(); + let mut shared = None; + if let Some(tail) = rest.strip_prefix('[') { + let (counter, tail) = tail.split_once(']')?; + shared = Some(counter.trim().to_string()); + rest = tail.trim_start(); + } + let (display, consumed) = braced_group(rest)?; + let rest = rest[consumed..].trim_start(); + let within = rest + .strip_prefix('[') + .and_then(|tail| tail.split_once(']')) + .map(|(counter, _)| counter.trim().to_string()); + let name = name.trim(); + let display = display.trim(); + if name.is_empty() || display.is_empty() { + return None; + } + Some(TheoremDefinition { + name: name.to_string(), + display: display.to_string(), + shared, + within, + starred, + }) } /// Pull `\hoffset`/`\voffset`/`\paperwidth`/`\paperheight`/`\vsize`/ @@ -300,6 +349,12 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) { } continue; } + if trimmed.starts_with("\\newtheorem") { + if let Some(definition) = newtheorem_definition(trimmed) { + geometry.theorem_definitions.push(definition); + } + continue; + } if let Some(value) = braced_value(trimmed, "\\title") { geometry.title = Some(value); continue; @@ -840,7 +895,7 @@ fn layout_document(document: &Document) -> Engine { /// Build a JSON preview from blank-line-separated plain-text paragraphs. pub fn preview_json(source: &str) -> Result { let (body, geometry) = geometry_and_body(source); - let paragraphs = paragraphs(&body)?; + let paragraphs = paragraphs_with_definitions(&body, &geometry.theorem_definitions)?; let mut document = build_document(¶graphs, &geometry); apply_geometry(&mut document, &geometry); let engine = layout_document(&document); @@ -856,7 +911,7 @@ pub fn preview_json(source: &str) -> Result { /// Render the same checkpointed document as a route-D PDF. pub fn pdf_bytes(source: &str) -> Result, String> { let (body, geometry) = geometry_and_body(source); - let paragraphs = paragraphs(&body)?; + let paragraphs = paragraphs_with_definitions(&body, &geometry.theorem_definitions)?; let mut document = build_document(¶graphs, &geometry); apply_geometry(&mut document, &geometry); let engine = layout_document(&document); @@ -883,7 +938,7 @@ pub fn pdf_bytes(source: &str) -> Result, String> { /// checkpoints that were reused versus rebuilt. pub fn edit_json(source: &str, unit: usize) -> Result { let (body, geometry) = geometry_and_body(source); - let paragraphs = paragraphs(&body)?; + let paragraphs = paragraphs_with_definitions(&body, &geometry.theorem_definitions)?; if unit >= paragraphs.len() { return Err(format!( "unit {unit} is out of range for {} paragraphs", @@ -972,9 +1027,10 @@ impl FloatKind { #[derive(Clone, PartialEq, Eq)] struct TheoremSpec { name: String, + display: String, title: Option, starred: bool, - number: Option, + number: Option, labels: Vec, } @@ -1082,6 +1138,13 @@ where } fn paragraphs(source: &str) -> Result, String> { + paragraphs_with_definitions(source, &[]) +} + +fn paragraphs_with_definitions( + source: &str, + definitions: &[TheoremDefinition], +) -> Result, String> { let paragraphs: Vec<&str> = source .split("\n\n") .map(str::trim) @@ -1133,7 +1196,7 @@ fn paragraphs(source: &str) -> Result, String> { pending.2 += skip.2; continue; } - let mut blocks = parse_blocks_raw(chunk); + let mut blocks = parse_blocks_raw(chunk, definitions); if let Some(first) = blocks.first_mut() { first.space_before += pending.0; first.space_stretch += pending.1; @@ -1398,27 +1461,45 @@ fn environment_label(name: &str) -> String { } /// A `theorem`-like environment: a bold heading plus an indented statement. -fn theorem_block(raw: &str) -> Option> { +fn theorem_block(raw: &str, definitions: &[TheoremDefinition]) -> Option> { let trimmed = raw.trim(); - let (name, starred) = THEOREM_ENVIRONMENTS.iter().find_map(|name| { - if trimmed.starts_with(&format!("\\begin{{{name}}}")) { - Some((*name, false)) - } else if trimmed.starts_with(&format!("\\begin{{{name}*}}")) { - Some((*name, true)) - } else { - None + let definition = definitions.iter().find(|definition| { + trimmed.starts_with(&format!("\\begin{{{}}}", definition.name)) + || trimmed.starts_with(&format!("\\begin{{{}*}}", definition.name)) + }); + let (name, display, starred_definition) = match definition { + Some(definition) => ( + definition.name.clone(), + definition.display.clone(), + definition.starred, + ), + None => { + let (name, starred) = THEOREM_ENVIRONMENTS.iter().find_map(|name| { + if trimmed.starts_with(&format!("\\begin{{{name}}}")) { + Some((*name, false)) + } else if trimmed.starts_with(&format!("\\begin{{{name}*}}")) { + Some((*name, true)) + } else { + None + } + })?; + (name.to_string(), environment_label(name), starred) } - })?; - let begin = if starred { - format!("\\begin{{{name}*}}") - } else { - format!("\\begin{{{name}}}") }; - let end = if starred { - format!("\\end{{{name}*}}") + let (begin, end, starred_marker) = if trimmed.starts_with(&format!("\\begin{{{name}*}}")) { + ( + format!("\\begin{{{name}*}}"), + format!("\\end{{{name}*}}"), + true, + ) } else { - format!("\\end{{{name}}}") + ( + format!("\\begin{{{name}}}"), + format!("\\end{{{name}}}"), + false, + ) }; + let starred = starred_definition || starred_marker; let body = trimmed.strip_prefix(&begin)?.strip_suffix(&end)?.trim(); let (title, body) = match body.strip_prefix('[') { Some(rest) => { @@ -1436,9 +1517,8 @@ fn theorem_block(raw: &str) -> Option> { if body.is_empty() { return None; } - let label = environment_label(name); let heading = SourceParagraph { - text: format!("{label}."), + text: format!("{display}."), font: ParagraphFont::Bold, line_height: 14, math: false, @@ -1458,7 +1538,8 @@ fn theorem_block(raw: &str) -> Option> { heading_number: None, footnotes: Vec::new(), theorem: Some(TheoremSpec { - name: name.to_string(), + name: name.clone(), + display, title, starred, number: None, @@ -1468,7 +1549,7 @@ fn theorem_block(raw: &str) -> Option> { float: None, }; let italic = matches!( - name, + name.as_str(), "theorem" | "lemma" | "corollary" | "proposition" | "proof" ); let statement = SourceParagraph { @@ -1502,11 +1583,11 @@ fn theorem_block(raw: &str) -> Option> { Some(vec![heading, statement]) } -fn parse_blocks_raw(raw: &str) -> Vec { +fn parse_blocks_raw(raw: &str, definitions: &[TheoremDefinition]) -> Vec { if let Some(block) = float_block(raw) { return vec![block]; } - if let Some(blocks) = theorem_block(raw) { + if let Some(blocks) = theorem_block(raw, definitions) { return blocks; } if let Some(body) = raw @@ -2737,26 +2818,52 @@ fn number_footnotes(paragraphs: &mut [SourceParagraph]) { } /// Number theorem-like headings and return their label targets. -fn number_theorems(paragraphs: &mut [SourceParagraph]) -> Vec<(String, String)> { +fn number_theorems( + paragraphs: &mut [SourceParagraph], + definitions: &[TheoremDefinition], +) -> Vec<(String, String)> { let mut counters: Vec<(String, u32)> = Vec::new(); let mut labels = Vec::new(); + let mut section: Option = None; for paragraph in paragraphs { + if paragraph.heading_level.is_some() { + section = paragraph.heading_number.clone(); + } let Some(theorem) = paragraph.theorem.as_mut() else { continue; }; + let definition = definitions + .iter() + .find(|definition| definition.name == theorem.name); if !theorem.starred && theorem.name != "proof" { - if let Some((_, counter)) = counters.iter_mut().find(|(name, _)| *name == theorem.name) - { - *counter += 1; - theorem.number = Some(*counter); + let counter = definition + .and_then(|definition| definition.shared.clone()) + .unwrap_or_else(|| theorem.name.clone()); + let value = match counters.iter_mut().find(|(name, _)| *name == counter) { + Some((_, count)) => { + *count += 1; + *count + } + None => { + counters.push((counter, 1)); + 1 + } + }; + let within_section = + definition.and_then(|definition| definition.within.as_deref()) == Some("section"); + theorem.number = Some(if within_section { + match §ion { + Some(section) => format!("{section}.{value}"), + None => value.to_string(), + } } else { - counters.push((theorem.name.clone(), 1)); - theorem.number = Some(1); - } + value.to_string() + }); } - let label = environment_label(&theorem.name); + let display = theorem.display.clone(); let number = theorem .number + .as_ref() .map(|number| format!(" {number}")) .unwrap_or_default(); let title = theorem @@ -2764,10 +2871,11 @@ fn number_theorems(paragraphs: &mut [SourceParagraph]) -> Vec<(String, String)> .as_ref() .map(|title| format!(" ({title})")) .unwrap_or_default(); - paragraph.text = format!("{label}{number}{title}."); - if theorem.number.is_some() { + paragraph.text = format!("{display}{number}{title}."); + let number = theorem.number.clone(); + if let Some(number) = number { for label in theorem.labels.drain(..) { - labels.push((label, theorem.number.unwrap().to_string())); + labels.push((label, number.clone())); } } else { theorem.labels.clear(); @@ -2845,7 +2953,10 @@ fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Do let mut paragraphs = expand_maketitle(paragraphs, geometry); let section_labels = number_sections(&mut paragraphs); let mut references = section_labels; - references.extend(number_theorems(&mut paragraphs)); + references.extend(number_theorems( + &mut paragraphs, + &geometry.theorem_definitions, + )); references.extend(number_floats(&mut paragraphs)); resolve_section_refs(&mut paragraphs, &references); number_footnotes(&mut paragraphs); @@ -3475,6 +3586,53 @@ See \ref{fig:a} and \ref{tab:b}."; assert_eq!(document.units[2].source, "See 1 and 1."); } + #[test] + fn newtheorem_definitions_are_captured() { + let source = "\\newtheorem{claim}[theorem]{Claim}\n\\newtheorem*{note}{Note}\n\\newtheorem{observation}{Observation}[section]\n\nBody."; + let (body, geometry) = geometry_and_body(source); + assert_eq!(geometry.theorem_definitions.len(), 3); + assert_eq!(geometry.theorem_definitions[0].name, "claim"); + assert_eq!(geometry.theorem_definitions[0].display, "Claim"); + assert_eq!( + geometry.theorem_definitions[0].shared.as_deref(), + Some("theorem") + ); + assert!(geometry.theorem_definitions[1].starred); + assert_eq!( + geometry.theorem_definitions[2].within.as_deref(), + Some("section") + ); + assert!(!body.contains("newtheorem"), "{body}"); + } + + #[test] + fn custom_theorems_share_counters_and_sections() { + let source = "\\newtheorem{claim}[theorem]{Claim}\n\\newtheorem{observation}{Observation}[section]\n\n\\section{One}\n\n\\begin{theorem}\nA theorem.\n\\end{theorem}\n\n\\begin{claim}\nA claim.\n\\end{claim}\n\n\\begin{observation}\n\\label{obs:a}An observation.\n\\end{observation}\n\nSee \\ref{obs:a}."; + let (body, geometry) = geometry_and_body(source); + let blocks = paragraphs_with_definitions(&body, &geometry.theorem_definitions).unwrap(); + let document = build_document(&blocks, &geometry); + let sources: Vec<&str> = document + .units + .iter() + .map(|unit| unit.source.as_str()) + .collect(); + assert!(sources.contains(&"1 One"), "{sources:?}"); + assert!(sources.contains(&"Theorem 1."), "{sources:?}"); + assert!(sources.contains(&"Claim 2."), "{sources:?}"); + assert!(sources.contains(&"Observation 1.1."), "{sources:?}"); + assert!(sources.contains(&"See 1.1."), "{sources:?}"); + } + + #[test] + fn starred_newtheorem_stays_unnumbered() { + let source = "\\newtheorem*{aside}{Aside}\n\n\\begin{aside}\nA remark.\n\\end{aside}"; + let (body, geometry) = geometry_and_body(source); + let blocks = paragraphs_with_definitions(&body, &geometry.theorem_definitions).unwrap(); + let document = build_document(&blocks, &geometry); + assert_eq!(document.units[0].source, "Aside."); + assert_eq!(document.units[1].source, "A remark."); + } + #[test] fn theorem_environments_number_and_label() { let source = r"\begin{theorem}\label{thm:a}