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.
This commit is contained in:
gloamxun committed 2026-10-24 21:00:45 +08:00
1 parent 9599436447
commit 4ca3302367
4 files changed
+203 -45

No files matched your search

+199 -41
View File
@@ -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<String, 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(&paragraphs, &geometry);
apply_geometry(&mut document, &geometry);
let mut sessions = project_sessions()
@@ -164,6 +164,55 @@ struct PageGeometry {
date: Option<String>,
/// `thebibliography` entries: label key and entry text, in order.
bibliography: Vec<(String, String)>,
/// `\newtheorem` definitions from the preamble.
theorem_definitions: Vec<TheoremDefinition>,
}
/// A `\newtheorem` declaration: display name, shared counter and section scope.
#[derive(Clone, Debug, PartialEq, Eq)]
struct TheoremDefinition {
name: String,
display: String,
shared: Option<String>,
within: Option<String>,
starred: bool,
}
/// Parse `\newtheorem{env}[shared]{Display}`,
/// `\newtheorem{env}{Display}[within]` and `\newtheorem*{env}{Display}`.
fn newtheorem_definition(line: &str) -> Option<TheoremDefinition> {
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<String, 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(&paragraphs, &geometry);
apply_geometry(&mut document, &geometry);
let engine = layout_document(&document);
@@ -856,7 +911,7 @@ pub fn preview_json(source: &str) -> Result<String, String> {
/// Render the same checkpointed document as a route-D PDF.
pub fn pdf_bytes(source: &str) -> Result<Vec<u8>, 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(&paragraphs, &geometry);
apply_geometry(&mut document, &geometry);
let engine = layout_document(&document);
@@ -883,7 +938,7 @@ pub fn pdf_bytes(source: &str) -> Result<Vec<u8>, String> {
/// checkpoints that were reused versus rebuilt.
pub fn edit_json(source: &str, unit: usize) -> Result<String, String> {
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<String>,
starred: bool,
number: Option<u32>,
number: Option<String>,
labels: Vec<String>,
}
@@ -1082,6 +1138,13 @@ where
}
fn paragraphs(source: &str) -> Result<Vec<SourceParagraph>, String> {
paragraphs_with_definitions(source, &[])
}
fn paragraphs_with_definitions(
source: &str,
definitions: &[TheoremDefinition],
) -> Result<Vec<SourceParagraph>, String> {
let paragraphs: Vec<&str> = source
.split("\n\n")
.map(str::trim)
@@ -1133,7 +1196,7 @@ fn paragraphs(source: &str) -> Result<Vec<SourceParagraph>, 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<Vec<SourceParagraph>> {
fn theorem_block(raw: &str, definitions: &[TheoremDefinition]) -> 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 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<Vec<SourceParagraph>> {
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<Vec<SourceParagraph>> {
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<Vec<SourceParagraph>> {
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<Vec<SourceParagraph>> {
Some(vec![heading, statement])
}
fn parse_blocks_raw(raw: &str) -> Vec<SourceParagraph> {
fn parse_blocks_raw(raw: &str, definitions: &[TheoremDefinition]) -> Vec<SourceParagraph> {
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<String> = 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 &section {
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}