Number theorem-like environments and resolve their labels

This commit is contained in:
gloamxun committed 2026-10-24 20:53:43 +08:00
1 parent a9fbc9b850
commit 67eb719cbd
4 files changed
+261 -4

No files matched your search

+257
View File
@@ -948,6 +948,8 @@ struct SourceParagraph {
font_size: Option<i64>,
/// A `figure` environment carried as a float unit.
float: Option<FloatSpec>,
/// A theorem-like environment heading.
theorem: Option<TheoremSpec>,
}
/// The kind of a LaTeX float environment.
@@ -966,6 +968,16 @@ impl FloatKind {
}
}
/// A theorem-like environment: numbering state and label targets.
#[derive(Clone, PartialEq, Eq)]
struct TheoremSpec {
name: String,
title: Option<String>,
starred: bool,
number: Option<u32>,
labels: Vec<String>,
}
/// A `figure` or `table` environment: placement, graphics size and caption.
#[derive(Clone, PartialEq, Eq)]
struct FloatSpec {
@@ -1056,6 +1068,7 @@ fn paragraphs(source: &str) -> Result<Vec<SourceParagraph>, String> {
heading_starred: false,
heading_number: None,
footnotes: Vec::new(),
theorem: None,
float: None,
font_size: None,
});
@@ -1232,6 +1245,7 @@ fn float_block(raw: &str) -> Option<SourceParagraph> {
heading_starred: false,
heading_number: None,
footnotes: Vec::new(),
theorem: None,
font_size: None,
float: Some(FloatSpec {
kind,
@@ -1317,10 +1331,137 @@ fn figure_graphic(inner: &str) -> Option<(Option<i64>, Option<i64>)> {
Some((width, height))
}
const THEOREM_ENVIRONMENTS: [&str; 8] = [
"theorem",
"lemma",
"corollary",
"proposition",
"definition",
"example",
"remark",
"proof",
];
fn environment_label(name: &str) -> String {
let mut characters = name.chars();
match characters.next() {
Some(first) => first.to_uppercase().collect::<String>() + characters.as_str(),
None => String::new(),
}
}
/// A `theorem`-like environment: a bold heading plus an indented statement.
fn theorem_block(raw: &str) -> Option<Vec<SourceParagraph>> {
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 begin = if starred {
format!("\\begin{{{name}*}}")
} else {
format!("\\begin{{{name}}}")
};
let end = if starred {
format!("\\end{{{name}*}}")
} else {
format!("\\end{{{name}}}")
};
let body = trimmed.strip_prefix(&begin)?.strip_suffix(&end)?.trim();
let (title, body) = match body.strip_prefix('[') {
Some(rest) => {
let close = rest.find(']')?;
(
Some(rest[..close].trim().to_string()),
rest[close + 1..].trim(),
)
}
None => (None, body),
};
let mut body = body.to_string();
let labels = take_labels(&mut body);
body = body.trim().to_string();
if body.is_empty() {
return None;
}
let label = environment_label(name);
let heading = SourceParagraph {
text: format!("{label}."),
font: ParagraphFont::Bold,
line_height: 14,
math: false,
left_skip: 0,
centered: false,
right_aligned: false,
space_before: 12 * SCALE,
space_stretch: 2 * SCALE,
space_shrink: 0,
page_break: false,
equation_number: None,
equation_tag: None,
equation_rows: Vec::new(),
align_centered: false,
heading_level: None,
heading_starred: false,
heading_number: None,
footnotes: Vec::new(),
theorem: Some(TheoremSpec {
name: name.to_string(),
title,
starred,
number: None,
labels,
}),
font_size: None,
float: None,
};
let italic = matches!(
name,
"theorem" | "lemma" | "corollary" | "proposition" | "proof"
);
let statement = SourceParagraph {
text: body,
font: if italic {
ParagraphFont::Italic
} else {
ParagraphFont::Roman
},
line_height: 12,
math: false,
left_skip: 0,
centered: false,
right_aligned: false,
space_before: 4 * SCALE,
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,
font_size: None,
float: None,
};
Some(vec![heading, statement])
}
fn parse_blocks_raw(raw: &str) -> Vec<SourceParagraph> {
if let Some(block) = float_block(raw) {
return vec![block];
}
if let Some(blocks) = theorem_block(raw) {
return blocks;
}
if let Some(body) = raw
.trim()
.strip_prefix("\\begin{abstract}")
@@ -1346,6 +1487,7 @@ fn parse_blocks_raw(raw: &str) -> Vec<SourceParagraph> {
heading_starred: false,
heading_number: None,
footnotes: Vec::new(),
theorem: None,
float: None,
font_size: Some((12.0 * SCALE as f64) as i64),
};
@@ -1369,6 +1511,7 @@ fn parse_blocks_raw(raw: &str) -> Vec<SourceParagraph> {
heading_starred: false,
heading_number: None,
footnotes: Vec::new(),
theorem: None,
float: None,
font_size: Some((9.0 * SCALE as f64) as i64),
};
@@ -1440,6 +1583,7 @@ fn parse_blocks_raw(raw: &str) -> Vec<SourceParagraph> {
heading_starred: false,
heading_number: None,
footnotes: Vec::new(),
theorem: None,
float: None,
font_size: None,
}
@@ -1475,6 +1619,7 @@ fn parse_blocks_raw(raw: &str) -> Vec<SourceParagraph> {
heading_starred: false,
heading_number: None,
footnotes: Vec::new(),
theorem: None,
float: None,
font_size: None,
}];
@@ -1519,6 +1664,7 @@ fn parse_blocks_raw(raw: &str) -> Vec<SourceParagraph> {
heading_starred: false,
heading_number: None,
footnotes: Vec::new(),
theorem: None,
float: None,
font_size: None,
}
@@ -2043,6 +2189,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
heading_starred: false,
heading_number: None,
footnotes: Vec::new(),
theorem: None,
float: None,
font_size: None,
};
@@ -2070,6 +2217,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
heading_starred: false,
heading_number: None,
footnotes: Vec::new(),
theorem: None,
float: None,
};
}
@@ -2097,6 +2245,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
heading_starred: false,
heading_number: None,
footnotes: Vec::new(),
theorem: None,
float: None,
font_size: None,
};
@@ -2125,6 +2274,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
heading_starred: false,
heading_number: None,
footnotes: Vec::new(),
theorem: None,
float: None,
font_size: None,
};
@@ -2157,6 +2307,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
heading_starred: false,
heading_number: None,
footnotes: Vec::new(),
theorem: None,
float: None,
font_size: None,
};
@@ -2186,6 +2337,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
heading_starred: starred,
heading_number: None,
footnotes: Vec::new(),
theorem: None,
float: None,
font_size: None,
};
@@ -2219,6 +2371,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
heading_starred: false,
heading_number: None,
footnotes: Vec::new(),
theorem: None,
float: None,
font_size: None,
};
@@ -2244,6 +2397,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
heading_starred: false,
heading_number: None,
footnotes: Vec::new(),
theorem: None,
float: None,
font_size: None,
}
@@ -2344,6 +2498,7 @@ fn title_block(text: String, size: f64, space_before: i64) -> SourceParagraph {
heading_starred: false,
heading_number: None,
footnotes: Vec::new(),
theorem: None,
float: None,
font_size: Some((size * SCALE as f64) as i64),
}
@@ -2534,6 +2689,46 @@ fn number_footnotes(paragraphs: &mut [SourceParagraph]) {
}
}
/// Number theorem-like headings and return their label targets.
fn number_theorems(paragraphs: &mut [SourceParagraph]) -> Vec<(String, String)> {
let mut counters: Vec<(String, u32)> = Vec::new();
let mut labels = Vec::new();
for paragraph in paragraphs {
let Some(theorem) = paragraph.theorem.as_mut() else {
continue;
};
if !theorem.starred && theorem.name != "proof" {
if let Some((_, counter)) = counters.iter_mut().find(|(name, _)| *name == theorem.name)
{
*counter += 1;
theorem.number = Some(*counter);
} else {
counters.push((theorem.name.clone(), 1));
theorem.number = Some(1);
}
}
let label = environment_label(&theorem.name);
let number = theorem
.number
.map(|number| format!(" {number}"))
.unwrap_or_default();
let title = theorem
.title
.as_ref()
.map(|title| format!(" ({title})"))
.unwrap_or_default();
paragraph.text = format!("{label}{number}{title}.");
if theorem.number.is_some() {
for label in theorem.labels.drain(..) {
labels.push((label, theorem.number.unwrap().to_string()));
}
} else {
theorem.labels.clear();
}
}
labels
}
/// Number float captions and return their label targets.
fn number_floats(paragraphs: &mut [SourceParagraph]) -> Vec<(String, String)> {
let mut figures = 0u32;
@@ -2592,6 +2787,7 @@ fn append_bibliography(paragraphs: &mut Vec<SourceParagraph>, bibliography: &[(S
heading_starred: false,
heading_number: None,
footnotes: Vec::new(),
theorem: None,
float: None,
font_size: None,
});
@@ -2602,6 +2798,7 @@ 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_floats(&mut paragraphs));
resolve_section_refs(&mut paragraphs, &references);
number_footnotes(&mut paragraphs);
@@ -3231,6 +3428,66 @@ See \ref{fig:a} and \ref{tab:b}.";
assert_eq!(document.units[2].source, "See 1 and 1.");
}
#[test]
fn theorem_environments_number_and_label() {
let source = r"\begin{theorem}\label{thm:a}
Every group has an identity.
\end{theorem}
\begin{lemma}
A lemma follows.
\end{lemma}
See \ref{thm:a}.";
let (body, geometry) = geometry_and_body(source);
let blocks = paragraphs(&body).unwrap();
let document = build_document(&blocks, &geometry);
assert_eq!(document.units.len(), 5);
assert_eq!(document.units[0].source, "Theorem 1.");
assert_eq!(document.units[1].source, "Every group has an identity.");
assert!(matches!(
document.units[1].items.first(),
Some(VerticalItem::Paragraph(paragraph)) if paragraph.font == ParagraphFont::Italic
));
assert_eq!(document.units[2].source, "Lemma 1.");
assert_eq!(document.units[4].source, "See 1.");
}
#[test]
fn theorem_titles_are_appended_to_the_heading() {
let source = r"\begin{theorem}[Main result]
Body.
\end{theorem}";
let (body, geometry) = geometry_and_body(source);
let blocks = paragraphs(&body).unwrap();
let document = build_document(&blocks, &geometry);
assert_eq!(document.units[0].source, "Theorem 1 (Main result).");
}
#[test]
fn proof_is_unnumbered_and_definitions_stay_roman() {
let source = r"\begin{proof}
It follows.
\end{proof}
\begin{definition}
A definition.
\end{definition}";
let (body, geometry) = geometry_and_body(source);
let blocks = paragraphs(&body).unwrap();
let document = build_document(&blocks, &geometry);
assert_eq!(document.units[0].source, "Proof.");
assert!(matches!(
document.units[1].items.first(),
Some(VerticalItem::Paragraph(paragraph)) if paragraph.font == ParagraphFont::Italic
));
assert_eq!(document.units[2].source, "Definition 1.");
assert!(matches!(
document.units[3].items.first(),
Some(VerticalItem::Paragraph(paragraph)) if paragraph.font == ParagraphFont::Roman
));
}
#[test]
fn bibliography_entries_resolve_citations() {
let source = "See \\cite{alpha} and \\cite{alpha,beta}.\n\n\\begin{thebibliography}{9}\n\\bibitem{alpha} Alpha entry.\n\\bibitem{beta} Beta entry.\n\\end{thebibliography}";