Offset counters with stepcounter

\stepcounter and \refstepcounter were unsupported, so a document that advanced a
counter before its next heading kept the old number. The geometry pass consumes
both commands and bumps the named counter in the stored counter table (creating
it at one when it was absent); page counters keep their dedicated
\addtocounter page handling.

A unit test steps section before \section{Introduction} and checks the heading
renders as "2 Introduction".
This commit is contained in:
gloamxun committed 2026-10-27 03:21:48 +08:00
1 parent 4068366190
commit 1d1009395b
4 files changed
+40 -6

No files matched your search

+34
View File
@@ -3076,6 +3076,18 @@ fn strip_page_geometry(
}
continue;
}
if let Some(rest) = trimmed.strip_prefix("\\stepcounter") {
if let Some((name, _)) = braced_group(rest.trim_start()) {
bump_geometry_counter(&mut geometry, name.trim(), 1);
}
continue;
}
if let Some(rest) = trimmed.strip_prefix("\\refstepcounter") {
if let Some((name, _)) = braced_group(rest.trim_start()) {
bump_geometry_counter(&mut geometry, name.trim(), 1);
}
continue;
}
if trimmed.starts_with("\\captionsetup")
|| trimmed.starts_with("\\numberwithin")
|| trimmed.starts_with("\\DeclareCaption")
@@ -6524,6 +6536,19 @@ fn unwrap_scaled_tables(source: &str) -> String {
output
}
/// Adjust a document counter from `\stepcounter`/`\addtocounter`.
fn bump_geometry_counter(geometry: &mut PageGeometry, name: &str, delta: i64) {
if let Some(entry) = geometry
.counters
.iter_mut()
.find(|(counter, _)| counter == name)
{
entry.1 = (entry.1 as i64 + delta).max(0) as u32;
} else if delta > 0 {
geometry.counters.push((name.to_string(), delta as u32));
}
}
/// Turn an explicit `\par` token into a paragraph break.
fn expand_par_breaks(body: &str) -> String {
let mut output = String::with_capacity(body.len());
@@ -17124,6 +17149,15 @@ A definition.
assert!(text.contains("D"), "{text}");
}
#[test]
fn stepcounter_offsets_the_next_heading() {
let source = "\\stepcounter{section}\n\n\\section{Introduction}";
let (body, geometry) = geometry_and_body(source);
let blocks = paragraphs(&body).expect("blocks");
let document = build_document(&blocks, &geometry);
assert_eq!(document.units[0].source, "2 Introduction");
}
#[test]
fn heading_headers_use_the_short_title() {
let source = "\\documentclass{article}\n\\pagestyle{headings}\n\\begin{document}\n\n\\section[Short]{A long title}\n\nFirst.\n\n\\newpage\n\nSecond.\n\n\\end{document}\n";