Expand newenvironment definitions in the preamble

This commit is contained in:
gloamxun committed 2026-10-24 22:15:51 +08:00
1 parent 568442a75b
commit e99fab2086
4 files changed
+172 -7

No files matched your search

+168 -3
View File
@@ -168,6 +168,7 @@ struct PageGeometry {
theorem_definitions: Vec<TheoremDefinition>,
/// `\newcommand` definitions from the preamble.
macros: Vec<MacroDefinition>,
environments: Vec<EnvironmentDefinition>,
}
/// A `\newtheorem` declaration: display name, shared counter and section scope.
@@ -180,9 +181,7 @@ struct TheoremDefinition {
starred: bool,
}
/// Parse `\newtheorem{env}[shared]{Display}`,
/// `\newtheorem{env}{Display}[within]` and `\newtheorem*{env}{Display}`.
/// A user macro captured from `\newcommand`.
/// A user macro captured from `\newcommand` or `\def`.
#[derive(Clone, Debug, PartialEq, Eq)]
struct MacroDefinition {
name: String,
@@ -190,6 +189,15 @@ struct MacroDefinition {
body: String,
}
/// A `\newenvironment` definition expanded textually in the body.
#[derive(Clone, Debug, PartialEq, Eq)]
struct EnvironmentDefinition {
name: String,
args: u8,
begin: String,
end: String,
}
/// Consume a braced group; the returned count includes the closing brace.
fn take_group_after_open(text: &str) -> Option<(String, usize)> {
let mut depth = 0_i32;
@@ -207,6 +215,38 @@ fn take_group_after_open(text: &str) -> Option<(String, usize)> {
}
/// Parse `\newcommand{\name}[n]{body}` (and renew/provide variants).
fn environment_definition(line: &str) -> Option<EnvironmentDefinition> {
let rest = line
.strip_prefix("\\newenvironment")
.or_else(|| line.strip_prefix("\\renewenvironment"))?;
let rest = rest.trim_start();
let rest = rest.strip_prefix('*').unwrap_or(rest).trim_start();
let (name, consumed) = braced_group(rest)?;
let mut rest = rest[consumed..].trim_start();
let mut args = 0_u8;
if let Some(after_bracket) = rest.strip_prefix('[') {
let close = after_bracket.find(']')?;
args = after_bracket[..close].trim().parse().ok()?;
rest = after_bracket[close + 1..].trim_start();
}
if rest.starts_with('[') {
return None;
}
let (begin, consumed) = braced_group(rest)?;
let rest = rest[consumed..].trim_start();
let (end, _) = braced_group(rest)?;
let name = name.trim().to_string();
if name.is_empty() {
return None;
}
Some(EnvironmentDefinition {
name,
args,
begin: begin.to_string(),
end: end.to_string(),
})
}
fn control_sequence(text: &str) -> Option<(String, usize)> {
let after_slash = text.strip_prefix('\\')?;
let first = after_slash.chars().next()?;
@@ -381,6 +421,86 @@ fn expand_macros(source: &str, macros: &[MacroDefinition]) -> String {
text
}
/// Find the matching `\end{name}` for an already-opened environment and
/// return the body plus the bytes consumed through the closing command.
fn environment_body(text: &str, name: &str) -> Option<(String, usize)> {
let begin = format!("\\begin{{{}}}", name);
let end = format!("\\end{{{}}}", name);
let mut depth = 1_usize;
let mut cursor = 0_usize;
while cursor < text.len() {
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_at), Some(end_at)) if begin_at < end_at => {
depth += 1;
cursor = begin_at + begin.len();
}
(_, Some(end_at)) => {
depth -= 1;
if depth == 0 {
return Some((text[..end_at].to_string(), end_at + end.len()));
}
cursor = end_at + end.len();
}
(Some(begin_at), None) => {
depth += 1;
cursor = begin_at + begin.len();
}
(None, None) => return None,
}
}
None
}
fn expand_environments(source: &str, definitions: &[EnvironmentDefinition]) -> String {
if definitions.is_empty() {
return source.to_string();
}
let mut text = source.to_string();
for _ in 0..8 {
let mut output = String::with_capacity(text.len());
let mut index = 0_usize;
let mut changed = false;
while index < text.len() {
let rest = &text[index..];
if let Some(after) = rest.strip_prefix("\\begin{")
&& let Some(close) = after.find('}')
{
let name = &after[..close];
if let Some(definition) = definitions
.iter()
.find(|definition| definition.name == name)
{
let after_begin = &after[close + 1..];
if let Some((args, consumed)) = macro_arguments(after_begin, definition.args) {
let content_start = index + "\\begin{".len() + close + 1 + consumed;
if let Some((inner, end_len)) =
environment_body(&text[content_start..], name)
{
let expanded_inner = expand_environments(&inner, definitions);
output.push_str(&substitute_macro_args(&definition.begin, &args));
output.push_str(&expanded_inner);
output.push_str(&substitute_macro_args(&definition.end, &args));
index = content_start + end_len;
changed = true;
continue;
}
}
}
}
let character = rest.chars().next().expect("non-empty tail");
output.push(character);
index += character.len_utf8();
}
text = output;
if !changed {
break;
}
}
text
}
fn newtheorem_definition(line: &str) -> Option<TheoremDefinition> {
let rest = line.strip_prefix("\\newtheorem")?;
let (starred, rest) = match rest.strip_prefix('*') {
@@ -550,6 +670,12 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
}
continue;
}
if trimmed.starts_with("\\newenvironment") || trimmed.starts_with("\\renewenvironment") {
if let Some(definition) = environment_definition(trimmed) {
geometry.environments.push(definition);
}
continue;
}
if trimmed.starts_with("\\newcommand")
|| trimmed.starts_with("\\renewcommand")
|| trimmed.starts_with("\\providecommand")
@@ -804,6 +930,7 @@ fn geometry_and_body(source: &str) -> (String, PageGeometry) {
// paragraphs of their own.
let mut body = latex_body(&stripped).trim_matches('\n').to_string();
geometry.bibliography = extract_bibliography(&mut body);
body = expand_environments(&body, &geometry.environments);
body = expand_macros(&body, &geometry.macros);
(body, geometry)
}
@@ -4212,6 +4339,44 @@ See \ref{fig:a} and \ref{tab:b}.";
assert_eq!(blocks[0].left_skip, 12);
}
#[test]
fn newenvironment_wraps_its_body() {
let source = "\\newenvironment{note}{\\textbf{Note: }}{}\n\n\\begin{note}body\\end{note}.";
let (body, geometry) = geometry_and_body(source);
assert_eq!(geometry.environments.len(), 1);
assert_eq!(body.trim(), "\\textbf{Note: }body.");
}
#[test]
fn environment_arguments_reach_begin_and_end_codes() {
let source = "\\newenvironment{pair}[1]{(#1)}{!}\n\n\\begin{pair}{A}body\\end{pair}";
let (body, _) = geometry_and_body(source);
assert_eq!(body.trim(), "(A)body!");
}
#[test]
fn nested_environments_expand_recursively() {
let source =
"\\newenvironment{box}{(}{)}\n\n\\begin{box}a\\begin{box}b\\end{box}c\\end{box}";
let (body, _) = geometry_and_body(source);
assert_eq!(body.trim(), "(a(b)c)");
}
#[test]
fn environment_codes_expand_macros() {
let source = "\\def\\x{A}\n\\newenvironment{e}{[\\x]}{}\n\n\\begin{e}body\\end{e}";
let (body, _) = geometry_and_body(source);
assert_eq!(body.trim(), "[A]body");
}
#[test]
fn undefined_environments_stay_literal() {
let source = "\\begin{figure}x\\end{figure}";
let (body, geometry) = geometry_and_body(source);
assert!(geometry.environments.is_empty());
assert_eq!(body.trim(), "\\begin{figure}x\\end{figure}");
}
#[test]
fn newcommand_definitions_expand_in_the_body() {
let source = "\\newcommand{\\R}{\\mathbb{R}}\n\\newcommand{\\pair}[2]{(#1,#2)}\n\n$\\R$ and $\\pair{x}{y}$";