Number sectioning headings with article counters

This commit is contained in:
gloamxun committed 2026-10-24 20:22:31 +08:00
1 parent 569bec31b6
commit 5ff94d8f92
4 files changed
+191 -8

No files matched your search

+187 -4
View File
@@ -853,6 +853,13 @@ struct SourceParagraph {
equation_rows: Vec<EquationRow>,
/// Whether the rows are centred (`gather`) rather than column-aligned.
align_centered: bool,
/// Sectioning level: 1 for `\section`, 2 for `\subsection`, 3 for
/// `\subsubsection`.
heading_level: Option<u8>,
/// Starred headings are unnumbered and do not advance the counters.
heading_starred: bool,
/// The section number assigned by the numbering pass.
heading_number: Option<String>,
font_size: Option<i64>,
}
@@ -930,6 +937,9 @@ fn paragraphs(source: &str) -> Result<Vec<SourceParagraph>, String> {
equation_tag: None,
equation_rows: Vec::new(),
align_centered: false,
heading_level: None,
heading_starred: false,
heading_number: None,
font_size: None,
});
pending = (0, 0, 0);
@@ -1110,6 +1120,9 @@ fn parse_blocks_raw(raw: &str) -> Vec<SourceParagraph> {
equation_tag: None,
equation_rows: Vec::new(),
align_centered: false,
heading_level: None,
heading_starred: false,
heading_number: None,
font_size: None,
}
})
@@ -1140,6 +1153,9 @@ fn parse_blocks_raw(raw: &str) -> Vec<SourceParagraph> {
equation_tag: None,
equation_rows: Vec::new(),
align_centered: false,
heading_level: None,
heading_starred: false,
heading_number: None,
font_size: None,
}];
}
@@ -1179,6 +1195,9 @@ fn parse_blocks_raw(raw: &str) -> Vec<SourceParagraph> {
equation_tag: None,
equation_rows: Vec::new(),
align_centered: false,
heading_level: None,
heading_starred: false,
heading_number: None,
font_size: None,
}
})
@@ -1629,6 +1648,36 @@ fn parse_runs(
}
}
/// Recognize a `\section`-family command: level, starred, and title.
fn heading_command(raw: &str) -> Option<(u8, bool, String)> {
let raw = raw.trim();
for (command, level) in [
("\\section", 1u8),
("\\subsection", 2),
("\\subsubsection", 3),
] {
let Some(rest) = raw.strip_prefix(command) else {
continue;
};
let (rest, starred) = match rest.strip_prefix('*') {
Some(rest) => (rest, true),
None => (rest, false),
};
let rest = rest.trim_start();
// Discard the optional short title: `\section[Short]{Long}`.
let rest = match rest.strip_prefix('[') {
Some(short) => match short.split_once(']') {
Some((_, rest)) => rest.trim_start(),
None => rest,
},
None => rest,
};
let (body, _) = braced_group(rest)?;
return Some((level, starred, body.trim().to_string()));
}
None
}
fn parse_paragraph(raw: &str) -> SourceParagraph {
for (environment, starred, centered) in [
("align", false, false),
@@ -1668,6 +1717,9 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
equation_tag: None,
equation_rows: rows,
align_centered: centered,
heading_level: None,
heading_starred: false,
heading_number: None,
font_size: None,
};
}
@@ -1690,6 +1742,9 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
equation_tag: None,
equation_rows: Vec::new(),
align_centered: false,
heading_level: None,
heading_starred: false,
heading_number: None,
};
}
if let Some(inner) = raw
@@ -1712,6 +1767,9 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
equation_tag: None,
equation_rows: Vec::new(),
align_centered: false,
heading_level: None,
heading_starred: false,
heading_number: None,
font_size: None,
};
}
@@ -1735,6 +1793,9 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
equation_tag: None,
equation_rows: Vec::new(),
align_centered: false,
heading_level: None,
heading_starred: false,
heading_number: None,
font_size: None,
};
}
@@ -1762,11 +1823,41 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
equation_tag: None,
equation_rows: Vec::new(),
align_centered: false,
heading_level: None,
heading_starred: false,
heading_number: None,
font_size: None,
};
}
if let Some((level, starred, title)) = heading_command(raw) {
return SourceParagraph {
text: title,
font: ParagraphFont::Bold,
line_height: if level == 1 { 18 } else { 14 },
math: false,
left_skip: 0,
centered: false,
right_aligned: false,
space_before: match level {
1 => 12 * SCALE,
2 => 10 * SCALE,
_ => 8 * SCALE,
},
space_stretch: 4 * SCALE,
space_shrink: SCALE,
page_break: false,
equation_number: None,
equation_tag: None,
equation_rows: Vec::new(),
align_centered: false,
heading_level: Some(level),
heading_starred: starred,
heading_number: None,
font_size: None,
};
}
let candidates = [
("\\section", ParagraphFont::Bold, 18),
("\\textbf", ParagraphFont::Bold, 12),
("\\textbf", ParagraphFont::Bold, 12),
("\\emph", ParagraphFont::Italic, 12),
("\\texttt", ParagraphFont::Mono, 12),
@@ -1790,6 +1881,9 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
equation_tag: None,
equation_rows: Vec::new(),
align_centered: false,
heading_level: None,
heading_starred: false,
heading_number: None,
font_size: None,
};
}
@@ -1810,6 +1904,9 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
equation_tag: None,
equation_rows: Vec::new(),
align_centered: false,
heading_level: None,
heading_starred: false,
heading_number: None,
font_size: None,
}
}
@@ -1860,6 +1957,9 @@ fn title_block(text: String, size: f64, space_before: i64) -> SourceParagraph {
equation_tag: None,
equation_rows: Vec::new(),
align_centered: false,
heading_level: None,
heading_starred: false,
heading_number: None,
font_size: Some((size * SCALE as f64) as i64),
}
}
@@ -1908,8 +2008,45 @@ fn expand_maketitle(blocks: &[SourceParagraph], geometry: &PageGeometry) -> Vec<
result
}
/// Advance the section counters and prefix each numbered heading with its number.
fn number_sections(blocks: &mut [SourceParagraph]) {
let mut counters = [0u32; 3];
for block in blocks {
let Some(level) = block.heading_level else {
continue;
};
if block.heading_starred {
continue;
}
let index = level as usize - 1;
counters[index] += 1;
for deeper in counters.iter_mut().skip(index + 1) {
*deeper = 0;
}
let number = match level {
1 => format!("{}", counters[0]),
2 => format!("{}.{}", counters[0], counters[1]),
_ => format!("{}.{}.{}", counters[0], counters[1], counters[2]),
};
block.heading_number = Some(number.clone());
block.text = format!("{number} {}", block.text);
}
}
/// Heading size relative to the base size: article's `\Large`, `\large`
/// and `\normalsize`.
fn heading_font_size(level: u8, base: i64) -> i64 {
let percent = match level {
1 => 144,
2 => 120,
_ => 100,
};
base.saturating_mul(percent) / 100
}
fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Document {
let paragraphs = expand_maketitle(paragraphs, geometry);
let mut paragraphs = expand_maketitle(paragraphs, geometry);
number_sections(&mut paragraphs);
let line_width = geometry.line_width.unwrap_or(480 * SCALE);
let units = paragraphs
.iter()
@@ -1975,10 +2112,14 @@ fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Do
unit.space_shrink = paragraph.space_shrink;
return unit;
}
let base_font_size = paragraph
let class_size = paragraph
.font_size
.or(geometry.base_font_size)
.unwrap_or(655_360);
let base_font_size = match paragraph.heading_level {
Some(level) => heading_font_size(level, class_size),
None => class_size,
};
let baselineskip = geometry
.baseline_skip
.unwrap_or_else(|| class_baselineskip(base_font_size));
@@ -2018,7 +2159,9 @@ fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Do
line_penalty: geometry.line_penalty.unwrap_or(10),
adj_demerits: geometry.adj_demerits.unwrap_or(10_000),
hyphenation_exceptions: geometry.hyphenation_exceptions.clone(),
line_height: if paragraph.line_height == 12 {
line_height: if paragraph.heading_level.is_some() {
base_font_size * 13 / 10
} else if paragraph.line_height == 12 {
baselineskip
} else {
paragraph.line_height * SCALE
@@ -2536,6 +2679,46 @@ mod source_tests {
assert_eq!(glue.par_skip_shrink, Some(SCALE));
}
#[test]
fn headings_are_numbered_and_starred_headings_are_not() {
let source = "\\section{One}\n\n\\subsection{Two}\n\n\\section*{Star}\n\n\\section{Three}";
let mut blocks = paragraphs(source).expect("blocks");
number_sections(&mut blocks);
assert_eq!(blocks[0].text, "1 One");
assert_eq!(blocks[1].text, "1.1 Two");
assert_eq!(blocks[2].text, "Star");
assert_eq!(blocks[3].text, "2 Three");
assert_eq!(blocks[1].heading_number.as_deref(), Some("1.1"));
assert_eq!(blocks[2].heading_number, None);
}
#[test]
fn headings_add_vertical_space_and_allow_short_titles() {
let blocks = paragraphs("\\section[Short]{Long title}").expect("blocks");
assert_eq!(blocks[0].text, "Long title");
assert!(blocks[0].space_before >= 12 * SCALE);
}
#[test]
fn heading_sizes_are_painted() {
let json = preview_json("\\section{Intro}\n\nBody").expect("preview");
assert!(json.contains("font-size=\\\"14.400\\\""), "{json}");
}
#[test]
fn heading_sizes_follow_the_class_base() {
let source = "\\section{One}\n\nBody";
let (body, geometry) = geometry_and_body(source);
let blocks = paragraphs(&body).expect("blocks");
let document = build_document(&blocks, &geometry);
let style = document.units[0]
.paragraph_style
.clone()
.expect("heading style");
assert_eq!(style.font_size, 655_360 * 144 / 100);
assert!(style.line_height > style.font_size);
}
#[test]
fn maketitle_expands_title_author_and_date() {
let source = "\\title{Paper}\n\\author{Ada}\n\\date{2024}\n\n\\maketitle\n\nBody";