Nest list environments with depth-aware indentation

This commit is contained in:
gloamxun committed 2026-10-24 21:04:21 +08:00
1 parent 4ca3302367
commit ac1bf660af
4 files changed
+303 -103

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 `[?]`). 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 theoreLine truncated
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. `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 theoreLine truncated
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`). 634 workspace tests are green and no oracle
PDF opt-in with `?engine=route-d`). 637 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 `[?]`); 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 |
| 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 |
| 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 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.
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.
### M0 incremental demo
+299 -99
View File
@@ -1583,6 +1583,268 @@ fn theorem_block(raw: &str, definitions: &[TheoremDefinition]) -> Option<Vec<Sou
Some(vec![heading, statement])
}
/// Recognise a list environment chunk and return its kind and body.
fn list_environment(raw: &str) -> Option<(&'static str, &str)> {
for environment in ["itemize", "enumerate", "description"] {
let begin = format!("\\begin{{{environment}}}");
let end = format!("\\end{{{environment}}}");
if let Some(body) = raw
.trim()
.strip_prefix(&begin)
.and_then(|text| text.strip_suffix(&end))
{
return Some((environment, body));
}
}
None
}
/// Split a list body at top-level `\\item` commands, keeping nested lists
/// inside the item that contains them.
fn split_list_items(body: &str) -> Vec<&str> {
let bytes = body.as_bytes();
let mut items = Vec::new();
let mut start = None;
let mut environment_depth = 0_usize;
let mut brace_depth = 0_usize;
let mut index = 0;
while index < bytes.len() {
match bytes[index] {
b'{' => {
brace_depth += 1;
index += 1;
continue;
}
b'}' => {
brace_depth = brace_depth.saturating_sub(1);
index += 1;
continue;
}
b'\\' => {
let rest = &body[index..];
if rest.starts_with("\\begin{") {
environment_depth += 1;
index += "\\begin{".len();
continue;
}
if rest.starts_with("\\end{") {
environment_depth = environment_depth.saturating_sub(1);
index += "\\end{".len();
continue;
}
if environment_depth == 0 && brace_depth == 0 && rest.starts_with("\\item") {
let after = index + "\\item".len();
let boundary = rest["\\item".len()..]
.chars()
.next()
.is_none_or(|character| !character.is_ascii_alphabetic());
if boundary {
if let Some(previous) = start {
items.push(&body[previous..index]);
}
start = Some(after);
index = after;
continue;
}
}
}
_ => {}
}
index += 1;
}
if let Some(previous) = start {
items.push(&body[previous..]);
}
items
}
/// Split item text into the part before a nested list, the nested list itself
/// and the continuation after it.
fn split_nested_list(text: &str) -> (String, Option<String>, String) {
let candidates = [
"\\begin{itemize}",
"\\begin{enumerate}",
"\\begin{description}",
];
let Some((start, environment)) = candidates
.iter()
.filter_map(|begin| {
let environment = begin.trim_start_matches("\\begin{").trim_end_matches('}');
text.find(begin).map(|index| (index, environment))
})
.min_by_key(|(index, _)| *index)
else {
return (text.to_string(), None, String::new());
};
let begin = format!("\\begin{{{environment}}}");
let end = format!("\\end{{{environment}}}");
let after_begin = start + begin.len();
let mut depth = 1_usize;
let mut cursor = after_begin;
while depth > 0 {
let next_begin = text[cursor..].find(&begin).map(|offset| cursor + offset);
let next_end = text[cursor..].find(&end).map(|offset| cursor + offset);
match (next_begin, next_end) {
(Some(begin_index), Some(end_index)) if begin_index < end_index => {
depth += 1;
cursor = begin_index + begin.len();
}
(_, Some(end_index)) => {
depth -= 1;
cursor = end_index + end.len();
}
(_, None) => return (text.to_string(), None, String::new()),
}
}
(
text[..start].to_string(),
Some(text[start..cursor].to_string()),
text[cursor..].to_string(),
)
}
fn alphabetic_label(mut number: u32, upper: bool) -> String {
let mut label = String::new();
while number > 0 {
let digit = ((number - 1) % 26) as u8;
label.insert(0, (b'a' + digit) as char);
number = (number - 1) / 26;
}
if upper {
label.to_ascii_uppercase()
} else {
label
}
}
fn roman_label(number: u32) -> String {
const VALUES: [(u32, &str); 13] = [
(1000, "m"),
(900, "cm"),
(500, "d"),
(400, "cd"),
(100, "c"),
(90, "xc"),
(50, "l"),
(40, "xl"),
(10, "x"),
(9, "ix"),
(5, "v"),
(4, "iv"),
(1, "i"),
];
let mut value = number;
let mut label = String::new();
for (amount, glyph) in VALUES {
while value >= amount {
label.push_str(glyph);
value -= amount;
}
}
if label.is_empty() {
number.to_string()
} else {
label
}
}
fn enumerate_label(number: u32, depth: usize) -> String {
match depth % 4 {
1 => format!("({}) ", alphabetic_label(number, false)),
2 => format!("{}. ", roman_label(number)),
3 => format!("{}. ", alphabetic_label(number, true)),
_ => format!("{number}. "),
}
}
fn bullet_label(depth: usize) -> &'static str {
match depth % 3 {
1 => "– ",
2 => "* ",
_ => "• ",
}
}
fn list_paragraph(text: String, depth: usize) -> SourceParagraph {
SourceParagraph {
text,
font: ParagraphFont::Roman,
line_height: 12,
math: false,
left_skip: 12 * (depth as i64 + 1),
centered: false,
right_aligned: false,
space_before: 0,
space_stretch: 0,
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(),
theorem: None,
float: None,
font_size: None,
}
}
/// Lay out a list environment, recursing into lists nested in its items.
fn list_blocks(
raw: &str,
depth: usize,
_definitions: &[TheoremDefinition],
) -> Option<Vec<SourceParagraph>> {
let (environment, body) = list_environment(raw)?;
let mut blocks = Vec::new();
let mut number = 0_u32;
for item in split_list_items(body) {
let item = item.trim();
if item.is_empty() {
continue;
}
let (label, rest) = match environment {
"description" => {
let (term, rest) = item
.strip_prefix('[')
.and_then(|text| text.split_once(']'))
.map(|(term, rest)| (term.trim(), rest.trim()))
.unwrap_or(("", item));
if term.is_empty() {
(String::new(), rest)
} else {
(format!("{term} — "), rest)
}
}
"enumerate" => {
number += 1;
(enumerate_label(number, depth), item)
}
_ => (bullet_label(depth).to_string(), item),
};
let (before, nested, after) = split_nested_list(rest);
if !before.trim().is_empty() {
blocks.push(list_paragraph(format!("{label}{}", before.trim()), depth));
}
if let Some(nested) = nested {
if let Some(nested_blocks) = list_blocks(&nested, depth + 1, _definitions) {
blocks.extend(nested_blocks);
}
}
if !after.trim().is_empty() {
blocks.push(list_paragraph(after.trim().to_string(), depth));
}
}
if blocks.is_empty() {
None
} else {
Some(blocks)
}
}
fn parse_blocks_raw(raw: &str, definitions: &[TheoremDefinition]) -> Vec<SourceParagraph> {
if let Some(block) = float_block(raw) {
return vec![block];
@@ -1670,56 +1932,8 @@ fn parse_blocks_raw(raw: &str, definitions: &[TheoremDefinition]) -> Vec<SourceP
block.right_aligned = right_aligned;
return vec![block];
}
for (environment, numbered) in [("itemize", false), ("enumerate", true)] {
let begin = format!("\\begin{{{environment}}}");
let finish = format!("\\end{{{environment}}}");
let Some(body) = raw
.strip_prefix(&begin)
.and_then(|text| text.strip_suffix(&finish))
else {
continue;
};
let mut number = 0;
let items: Vec<SourceParagraph> = body
.split("\\item")
.map(str::trim)
.filter(|item| !item.is_empty())
.map(|item| {
number += 1;
let prefix = if numbered {
format!("{number}. ")
} else {
"• ".to_string()
};
SourceParagraph {
text: format!("{prefix}{item}"),
font: ParagraphFont::Roman,
line_height: 12,
math: false,
left_skip: 12,
centered: false,
right_aligned: false,
space_before: 0,
space_stretch: 0,
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(),
theorem: None,
float: None,
font_size: None,
}
})
.collect();
if !items.is_empty() {
return items;
}
if let Some(blocks) = list_blocks(raw, 0, definitions) {
return blocks;
}
if let Some(body) = raw
.strip_prefix("\\begin{quote}")
@@ -1753,55 +1967,6 @@ fn parse_blocks_raw(raw: &str, definitions: &[TheoremDefinition]) -> Vec<SourceP
}];
}
}
if let Some(body) = raw
.strip_prefix("\\begin{description}")
.and_then(|text| text.strip_suffix("\\end{description}"))
{
let items: Vec<SourceParagraph> = body
.split("\\item")
.map(str::trim)
.filter(|item| !item.is_empty())
.map(|item| {
let (term, rest) = item
.strip_prefix('[')
.and_then(|text| text.split_once(']'))
.map(|(term, rest)| (term.trim(), rest.trim()))
.unwrap_or(("", item));
let text = if term.is_empty() {
rest.to_string()
} else {
format!("{term} — {rest}")
};
SourceParagraph {
text,
font: ParagraphFont::Roman,
line_height: 12,
math: false,
left_skip: 12,
centered: false,
right_aligned: false,
space_before: 0,
space_stretch: 0,
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(),
theorem: None,
float: None,
font_size: None,
}
})
.collect();
if !items.is_empty() {
return items;
}
}
vec![parse_paragraph(raw)]
}
@@ -3586,6 +3751,41 @@ See \ref{fig:a} and \ref{tab:b}.";
assert_eq!(document.units[2].source, "See 1 and 1.");
}
#[test]
fn nested_itemize_indents_and_relabels() {
let source = "\\begin{itemize}\n\\item Outer\n\\begin{itemize}\n\\item Inner\n\\end{itemize}\n\\end{itemize}";
let blocks = paragraphs(source).unwrap();
assert_eq!(
blocks.len(),
2,
"{:?}",
blocks.iter().map(|b| &b.text).collect::<Vec<_>>()
);
assert_eq!(blocks[0].text, "• Outer");
assert_eq!(blocks[0].left_skip, 12);
assert_eq!(blocks[1].text, "– Inner");
assert_eq!(blocks[1].left_skip, 24);
}
#[test]
fn nested_enumerate_uses_letter_labels() {
let source = "\\begin{enumerate}\n\\item First\n\\begin{enumerate}\n\\item Alpha\n\\item Beta\n\\end{enumerate}\n\\item Second\n\\end{enumerate}";
let blocks = paragraphs(source).unwrap();
let texts: Vec<&str> = blocks.iter().map(|block| block.text.as_str()).collect();
assert_eq!(texts, ["1. First", "(a) Alpha", "(b) Beta", "2. Second"]);
let skips: Vec<i64> = blocks.iter().map(|block| block.left_skip).collect();
assert_eq!(skips, [12, 24, 24, 12]);
}
#[test]
fn description_items_keep_their_terms() {
let source = "\\begin{description}\n\\item[Term] Definition\n\\end{description}";
let blocks = paragraphs(source).unwrap();
assert_eq!(blocks.len(), 1);
assert_eq!(blocks[0].text, "Term — Definition");
assert_eq!(blocks[0].left_skip, 12);
}
#[test]
fn newtheorem_definitions_are_captured() {
let source = "\\newtheorem{claim}[theorem]{Claim}\n\\newtheorem*{note}{Note}\n\\newtheorem{observation}{Observation}[section]\n\nBody.";