Capture multi-line macro definitions and mode conditionals

The preamble parser is line-oriented, so a multi-line \newcommand, \def or
\newenvironment contributed only its first line to the macro table while the
remaining body lines fell through to the document text. In the assembled arXiv
source that also swallowed the \begin{document} marker, so the whole class
preamble was laid out as one page of \NeedsTeXFormat/\fancyhf text.

Join definition bodies at balanced braces before stripping: comments are
removed, a `%` line continuation joins without adding a space, and a blank line
becomes \par. Definitions now reach the existing single-line capture whole.

Resolve \ifhmode as true and \ifvmode/\ifmmode as false for the text expansion
path, so class macros such as \and expand.

The arXiv fixture body no longer contains NeedsTeXFormat, fancyhf or ifhmode and
the project preview lays out four pages instead of one; unit tests cover a
multi-line \newcommand/\def and the arXiv preamble containment. Remaining
warnings are now body commands (\maketitle, \thanks, \lipsum, \addvspace and the
footnote machinery), which are separate work.
This commit is contained in:
gloamxun committed 2026-10-26 23:08:35 +08:00
1 parent ebf2070295
commit 1b7baa0257
3 files changed
+150 -2

No files matched your search

+142
View File
@@ -1656,6 +1656,14 @@ fn conditional_at(
if word == "iffalse" {
return Some((false, consumed));
}
// Route-D expands macros while building paragraph text, which is
// horizontal mode; vertical and math mode are not modelled here.
if word == "ifhmode" {
return Some((true, consumed));
}
if word == "ifvmode" || word == "ifmmode" {
return Some((false, consumed));
}
if word == "ifdefined" {
let after = text.get(index + consumed..)?;
let trimmed = after.trim_start();
@@ -4376,6 +4384,111 @@ fn capture_body_definitions(
}
}
/// Join multi-line `\newcommand`/`\def`/`\newenvironment` definitions into
/// one line so the line-oriented preamble parser can capture the whole body.
fn collapse_definition_bodies(source: &str) -> String {
const COMMANDS: [&str; 9] = [
"\\newcommand",
"\\renewcommand",
"\\providecommand",
"\\def",
"\\gdef",
"\\edef",
"\\xdef",
"\\newenvironment",
"\\renewenvironment",
];
let starts_definition = |line: &str| {
COMMANDS.iter().any(|command| {
line.strip_prefix(command)
.is_some_and(|rest| !rest.starts_with(|c: char| c.is_ascii_alphabetic()))
})
};
let mut out = String::new();
let mut pending: Option<String> = None;
let mut depth = 0_i64;
for line in source.lines() {
if let Some(buffer) = pending.as_mut() {
let continues = line.trim_end().ends_with('%');
let code = strip_tex_comment(line);
if code.trim().is_empty() {
buffer.push_str(" \\par ");
} else if continues {
buffer.push_str(code.trim());
} else {
buffer.push(' ');
buffer.push_str(code.trim());
}
depth += brace_delta(&code);
if depth <= 0 {
out.push_str(buffer);
out.push('\n');
pending = None;
depth = 0;
}
continue;
}
let code = strip_tex_comment(line);
let trimmed = code.trim_start();
if starts_definition(trimmed) {
let delta = brace_delta(&code);
if delta > 0 {
pending = Some(code.trim_end().to_string());
depth = delta;
continue;
}
}
out.push_str(line);
out.push('\n');
}
if let Some(buffer) = pending {
out.push_str(&buffer);
out.push('\n');
}
out
}
/// Drop an unescaped `%` comment from the end of a source line.
fn strip_tex_comment(line: &str) -> String {
let mut out = String::with_capacity(line.len());
let mut escaped = false;
for character in line.chars() {
if escaped {
escaped = false;
out.push(character);
continue;
}
if character == '\\' {
escaped = true;
out.push(character);
continue;
}
if character == '%' {
break;
}
out.push(character);
}
out
}
fn brace_delta(text: &str) -> i64 {
let mut depth = 0_i64;
let mut escaped = false;
for character in text.chars() {
if escaped {
escaped = false;
continue;
}
match character {
'\\' => escaped = true,
'{' => depth += 1,
'}' => depth -= 1,
_ => {}
}
}
depth
}
/// Move `\AtBeginDocument{...}` bodies in front of `\begin{document}`.
fn lift_at_begin_document(source: &str) -> String {
let mut hooks = String::new();
@@ -4441,6 +4554,7 @@ fn geometry_and_body(source: &str) -> (String, PageGeometry) {
// body before `\begin{document}` so its commands are consumed as setup
// instead of being typeset as text at the top of page one.
let source = lift_at_begin_document(source);
let source = collapse_definition_bodies(&source);
let source = collapse_braced_command(&source, "\\newgeometry");
let (stripped, mut geometry) = strip_page_geometry(&source);
dedupe_macros(&mut geometry.macros);
@@ -13629,6 +13743,34 @@ A definition.
assert_eq!(after.space_shrink, 5 * SCALE);
}
#[test]
fn multiline_macro_definitions_do_not_leak_into_the_body() {
let source = "\\documentclass{article}\n\\newcommand{\\kw}[1]{%\n \\textbf{#1}%\n}\n\\def\\and{\\ifhmode\n\\fi}\n\\begin{document}\n\nSee \\kw{Hi} and \\and there.\n\n\\end{document}\n";
let (body, _) = geometry_and_body(source);
assert!(!body.contains("newcommand"), "{body}");
assert!(!body.contains("ifhmode"), "{body}");
assert!(body.contains("Hi"), "{body}");
}
#[test]
fn arxiv_class_preamble_does_not_reach_the_body() {
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
let template = std::fs::read_to_string(root.join("fixtures/arxiv-template/template.tex"))
.expect("template");
let sty =
std::fs::read_to_string(root.join("fixtures/arxiv-template/arxiv.sty")).expect("sty");
let assembled = template.replace("\\usepackage{arxiv}", &sty);
let (body, _) = geometry_and_body(&assembled);
for needle in ["NeedsTeXFormat", "fancyhf", "ifhmode"] {
assert!(!body.contains(needle), "`{needle}` leaked into the body");
}
assert!(
body.contains("Introduction"),
"body lost the document text: {}",
body.chars().take(200).collect::<String>()
);
}
#[test]
fn at_begin_document_newgeometry_sets_the_text_block() {
let source = "\\documentclass{article}\n\\usepackage{geometry}\n\\AtBeginDocument{\n \\newgeometry{\n textheight=9in,\n textwidth=6.5in,\n top=1in,\n headheight=14pt,\n headsep=25pt,\n footskip=30pt\n }\n}\n\\begin{document}\n\nSome words here.\n\n\\end{document}\n";