Run AtBeginDocument setup and newgeometry as preamble

Class files such as the arXiv template set the page block inside
\AtBeginDocument{\newgeometry{...}}. Route-D treated the hook body as document
text, so the setup commands were typeset at the top of page one and the page
measure stayed at its default.

Lift \AtBeginDocument bodies in front of \begin{document}, join a multi-line
\newgeometry argument into one line, and read it through the geometry option
parser. Explicit textheight/textwidth options now win over margins, so
textheight=9in with top=1in keeps 9in instead of recomputing it from the
paper height.

The arXiv project now applies its 6.5in/9in block and no longer reports a
\newgeometry warning; unit tests cover the multi-line hook, the option
precedence, and the no-leak case. A remaining leak from multi-line macro
definitions in the same class file is separate work.
This commit is contained in:
gloamxun committed 2026-10-26 23:03:37 +08:00
1 parent 2f9b18c95c
commit ebf2070295
3 files changed
+117 -6

No files matched your search

+110 -3
View File
@@ -1477,6 +1477,10 @@ fn geometry_package_options(line: &str) -> Option<String> {
let (options, _) = braced(rest.trim_start())?;
return Some(options.to_string());
}
if let Some(rest) = line.strip_prefix("\\newgeometry") {
let (options, _) = braced(rest.trim_start())?;
return Some(options.to_string());
}
let rest = line.strip_prefix("\\usepackage")?;
let rest = rest.trim_start().strip_prefix('[')?;
let (options, rest) = rest.split_once(']')?;
@@ -1528,13 +1532,22 @@ fn apply_geometry_package(geometry: &mut PageGeometry, options: &str) {
_ => {}
}
}
let explicit_width = geometry.line_width;
let explicit_height = geometry.textheight;
if left.is_some() || right.is_some() || top.is_some() || bottom.is_some() {
let left = left.unwrap_or(0);
let right = right.unwrap_or(0);
let top = top.unwrap_or(0);
let bottom = bottom.unwrap_or(0);
geometry.line_width = Some(paper_width - left - right);
geometry.textheight = Some(paper_height - top - bottom);
// A `textwidth`/`textheight` option is authoritative; the arXiv
// template's `\newgeometry{textheight=9in,textwidth=6.5in,top=1in}`
// must keep its 9in/6.5in block instead of deriving it from margins.
if explicit_width.is_none() {
geometry.line_width = Some(paper_width - left - right);
}
if explicit_height.is_none() {
geometry.textheight = Some(paper_height - top - bottom);
}
}
}
@@ -4363,8 +4376,73 @@ fn capture_body_definitions(
}
}
/// Move `\AtBeginDocument{...}` bodies in front of `\begin{document}`.
fn lift_at_begin_document(source: &str) -> String {
let mut hooks = String::new();
let mut out = String::new();
let mut rest = source;
while let Some(index) = rest.find("\\AtBeginDocument") {
out.push_str(&rest[..index]);
let after = &rest[index + "\\AtBeginDocument".len()..];
let trimmed = after.trim_start();
let leading = after.len() - trimmed.len();
let Some((content, used)) = braced_group(trimmed) else {
out.push_str(&rest[index..]);
rest = "";
break;
};
if !content.trim().is_empty() {
hooks.push_str(content.trim());
hooks.push('\n');
}
rest = &after[leading + used..];
}
out.push_str(rest);
if hooks.trim().is_empty() {
return out;
}
if let Some(position) = out.find("\\begin{document}") {
let mut lifted = String::with_capacity(out.len() + hooks.len());
lifted.push_str(&out[..position]);
lifted.push_str(&hooks);
lifted.push_str(&out[position..]);
lifted
} else {
hooks + &out
}
}
/// Join a multi-line braced argument such as `\newgeometry{ ... }` into one
/// line so the line-oriented preamble parser can read it.
fn collapse_braced_command(source: &str, command: &str) -> String {
let mut out = String::new();
let mut rest = source;
while let Some(index) = rest.find(command) {
out.push_str(&rest[..index + command.len()]);
let after = &rest[index + command.len()..];
let trimmed = after.trim_start();
let leading = after.len() - trimmed.len();
if let Some((content, used)) = braced_group(trimmed) {
out.push('{');
out.push_str(&content.replace('\n', " "));
out.push('}');
rest = &after[leading + used..];
} else {
rest = after;
break;
}
}
out.push_str(rest);
out
}
fn geometry_and_body(source: &str) -> (String, PageGeometry) {
let (stripped, mut geometry) = strip_page_geometry(source);
// Class files put page setup inside `\AtBeginDocument{...}`; run that
// 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_braced_command(&source, "\\newgeometry");
let (stripped, mut geometry) = strip_page_geometry(&source);
dedupe_macros(&mut geometry.macros);
// Removed assignments can leave blank lines at the edges; they are not
// paragraphs of their own.
@@ -13551,6 +13629,35 @@ A definition.
assert_eq!(after.space_shrink, 5 * SCALE);
}
#[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";
let (body, geometry) = geometry_and_body(source);
assert_eq!(geometry.line_width, parse_dimension("6.5in"));
assert_eq!(geometry.textheight, parse_dimension("9in"));
assert!(!body.contains("newgeometry"));
assert!(!body.contains("AtBeginDocument"));
let paragraphs = paragraphs(&body).expect("paragraphs");
let document = build_document(&paragraphs, &geometry);
assert_eq!(document.text_width, parse_dimension("6.5in").unwrap());
}
#[test]
fn at_begin_document_setup_does_not_leak_into_text() {
let source = "\\documentclass{article}\n\\AtBeginDocument{\\newgeometry{textwidth=200pt}}\n\\begin{document}\n\nHello world.\n\n\\end{document}\n";
let (body, geometry) = geometry_and_body(source);
assert_eq!(geometry.line_width, Some(200 * SCALE));
assert!(!body.contains("AtBeginDocument"));
assert!(!body.contains("newgeometry"));
let warnings = source_warnings(source, &geometry);
assert!(
!warnings
.iter()
.any(|warning| warning.contains("newgeometry")),
"{warnings:?}"
);
}
#[test]
fn display_skips_accept_class_file_spelling() {
let source = "\\documentclass{article}\n\\abovedisplayskip 7\\p@ \\@plus 2\\p@ \\@minus 5\\p@\n\\abovedisplayshortskip \\z@ \\@plus 3\\p@\n\\belowdisplayskip \\abovedisplayskip\n\\belowdisplayshortskip 4\\p@ \\@plus 3\\p@ \\@minus 3\\p@\n\\begin{document}\n\nBefore.\n\n\\[ x \\]\n\nAfter.\n\n\\end{document}\n";