Reserve registers declared in the body

This commit is contained in:
gloamxun committed 2026-10-26 20:35:42 +08:00
1 parent 13de893c46
commit eaebb1edbf
3 files changed
+64 -2

No files matched your search

+62
View File
@@ -4196,6 +4196,55 @@ fn handle_savebox_line(line: &str, macros: &mut Vec<MacroDefinition>) {
}
/// Capture `\def` lines written in the document body, before macro expansion.
/// Reserve `\newcount`/`\newdimen`/`\newskip` registers declared in the body.
fn capture_body_registers(
body: &mut String,
counts: &mut Vec<(String, i64)>,
dimens: &mut Vec<(String, i64)>,
skips: &mut Vec<(String, [i64; 3])>,
) {
let mut kept = String::new();
let mut changed = false;
for line in body.lines() {
let trimmed = line.trim_start();
let mut handled = false;
if let Some(rest) = trimmed.strip_prefix("\\newcount") {
if let Some((command, _)) = control_sequence(rest.trim_start()) {
let name = command.trim_start_matches('\\').to_string();
if !counts.iter().any(|(known, _)| known == &name) {
counts.push((name, 0));
}
handled = true;
}
} else if let Some(rest) = trimmed.strip_prefix("\\newdimen") {
if let Some((command, _)) = control_sequence(rest.trim_start()) {
let name = command.trim_start_matches('\\').to_string();
if !dimens.iter().any(|(known, _)| known == &name) {
dimens.push((name, 0));
}
handled = true;
}
} else if let Some(rest) = trimmed.strip_prefix("\\newskip") {
if let Some((command, _)) = control_sequence(rest.trim_start()) {
let name = command.trim_start_matches('\\').to_string();
if !skips.iter().any(|(known, _)| known == &name) {
skips.push((name, [0, 0, 0]));
}
handled = true;
}
}
if handled {
changed = true;
continue;
}
kept.push_str(line);
kept.push('\n');
}
if changed {
*body = kept.trim_end_matches('\n').to_string();
}
}
fn capture_body_definitions(
body: &mut String,
macros: &mut Vec<MacroDefinition>,
@@ -4260,6 +4309,12 @@ fn geometry_and_body(source: &str) -> (String, PageGeometry) {
geometry.bibliography = extract_bibliography(&mut body);
body = expand_environments(&body, &geometry.environments);
body = expand_saveboxes(&body, &mut geometry.macros);
capture_body_registers(
&mut body,
&mut geometry.count_registers,
&mut geometry.dimension_registers,
&mut geometry.skip_registers,
);
capture_body_definitions(&mut body, &mut geometry.macros, &mut geometry.conditionals);
dedupe_macros(&mut geometry.macros);
let macros = geometry.macros.clone();
@@ -12674,6 +12729,13 @@ See \ref{fig:a} and \ref{tab:b}.";
assert_eq!(body.trim(), "Final");
}
#[test]
fn body_count_declarations_are_reserved() {
let source = "\\newcount\\total\n\\total=3\n\nValue \\the\\total.";
let (body, _geometry) = geometry_and_body(source);
assert_eq!(body.trim(), "Value 3.");
}
#[test]
fn body_definitions_expand_later_in_the_document() {
let source = "\\def\\greet{Hello}\n\n\\greet world.";