Attach heading labels that follow on the next line

A \label on the line after \section without a blank line was discarded with the
rest of the text after the heading's closing brace, so \ref printed "??".
heading_command now keeps any immediately following \label groups (allowing
whitespace/newlines) in the heading text, which lets the numbering pass attach
them to that heading; other trailing text is still ignored as before.

A preview test puts \label{sec:intro} directly under \section{Introduction},
refers to it, and checks "See 1." with no warnings and no "??".
This commit is contained in:
gloamxun committed 2026-10-27 02:27:17 +08:00
1 parent 723b9e220f
commit d3baa78e1e
4 files changed
+45 -8

No files matched your search

+39 -2
View File
@@ -10934,8 +10934,22 @@ fn heading_command(raw: &str) -> Option<(u8, bool, String, Option<String>)> {
},
None => (rest, None),
};
let (body, _) = braced_group(rest)?;
return Some((level, starred, body.trim().to_string(), short));
let (body, used) = braced_group(rest)?;
let mut title = body.trim().to_string();
// A label may follow the heading on the same line or on the next line
// without a blank line; keep it in the heading text so the numbering
// pass can attach it to this heading.
let mut tail = rest[used..].trim_start();
while let Some(after) = tail.strip_prefix("\\label") {
let after = after.trim_start();
let Some((_, label_used)) = braced_group(after) else {
break;
};
let consumed = tail.len() - after.len() + label_used;
title.push_str(&tail[..consumed]);
tail = tail[consumed..].trim_start();
}
return Some((level, starred, title, short));
}
None
}
@@ -16625,6 +16639,29 @@ A definition.
assert!(!svg.contains("numberwithin"), "{svg}");
}
#[test]
fn heading_labels_on_the_next_line_resolve() {
let source = "\\documentclass{article}\n\\begin{document}\n\n\\section{Introduction}\n\\label{sec:intro}\n\nSee \\ref{sec:intro}.\n\n\\end{document}\n";
let json = preview_json(source).expect("preview");
let value: serde_json::Value = serde_json::from_str(&json).expect("JSON");
assert_eq!(
value["warnings"].as_array().map(Vec::len),
Some(0),
"{}",
value["warnings"]
);
let svg = value["pages"][0]["svg"].as_str().expect("svg");
let text: String = svg
.split('>')
.filter_map(|piece| piece.split('<').next())
.collect::<String>()
.split_whitespace()
.collect();
assert!(text.contains("See1."), "{text}");
assert!(!text.contains("??"), "{text}");
assert!(!text.contains("label"), "{text}");
}
#[test]
fn acknowledgement_environments_render_a_heading() {
let source = "\\documentclass{article}\n\\begin{document}\n\nBody.\n\n\\begin{acks}\nThanks.\n\\end{acks}\n\n\\end{document}\n";