Paint fancyhdr running heads and feet

Parse \pagestyle{fancy}, \fancyhf, \fancyhead/\fancyfoot with L/C/R positions,
the \lhead/\chead/\rhead/\lfoot/\cfoot/\rfoot shorthands and
\renewcommand{\headrulewidth}, and paint them on every page. Head fields are
placed at top margin - \headsep and feet at text height + \footskip, both in
content coordinates so the page origin shifts them with the body; left, centre
and right align against the text measure, \thepage is expanded per page, and
the head rule uses the requested width.

Size and shape declarations are stripped before macro expansion because class
files define \footnotesize in terms of itself; expanding it repeated
\@setfontsize internals on every pass. A title page with fancy style is treated
as \thispagestyle{empty}, matching class \maketitle definitions.

The arXiv template now shows "A Preprint" on the right and its short title in
the centre after the title page, with the page number in the footer; tests
cover field parsing, painted positions/alignment and the title-page
suppression.
This commit is contained in:
gloamxun committed 2026-10-26 23:32:52 +08:00
1 parent 7a615a8639
commit 15b5437987
3 files changed
+330 -3

No files matched your search

+6 -2
View File
@@ -48,7 +48,7 @@ floats (`\floatsep`, `\textfloatsep`, `\intextsep`, `\topfraction`,
`\bottomnumber`, `\totalnumber`), insertion classes (`\skip`, fraction and
absolute limits, splitting), marks, Rust output hook, multi-page PDF, and the
route-D service endpoints (`/api/route-d/preview|pdf|edit`, project preview and
PDF opt-in with `?engine=route-d`). 977 workspace tests are green and no oracle
PDF opt-in with `?engine=route-d`). 979 workspace tests are green and no oracle
fixture is ignored. Preview JSON also carries a `warnings` array naming
environments route-D cannot lay out and control words that survived layout, so
unsupported source is reported instead of being silently typeset.
@@ -389,7 +389,11 @@ filler text, comments and external `\bibliography` commands are dropped, and a
`center`/`flushleft`/`flushright` environment that follows text starts its own
block, and `geometry`'s `top`/`bottom` margins offset the page body (the arXiv
first baseline is at 1in + 12pt) while an explicit `textheight` wins over the
margins. Class files are still mapped semantically rather than executed by a VM.
margins. `\pagestyle{fancy}` and the fancyhdr head/foot fields paint L/C/R
running heads at `top margin - headsep` and feet at `text height + footskip`,
expand `\thepage` per page, draw `\headrulewidth`, and leave the title page
empty; the arXiv template shows `A Preprint` and its short title after page one.
Class files are still mapped semantically rather than executed by a VM.
### P7 — Service and incrementality
+8 -1
View File
@@ -370,7 +370,7 @@ Math coverage includes fractions/roots, scripts, `\left...\right` with body-scal
Paragraph units carry a `ParagraphFont`; `Unit::paragraph_with_face` and `Unit::paragraph_with_style_and_face` select Roman, bold, italic, mono, or sans. The corresponding Computer Modern TFM (`cmr10`, `cmbx10`, `cmti10`, `cmbxti10`, `cmtt10`, `cmss10`, `cmssbx10`, `cmssi10`, `cmcsc10`) supplies advances, kerns, ligatures, and italic correction for layout, the display list selects the matching face, and the PDF writes Computer Modern Type1 outlines for each built-in face (`cmr10`/`cmbx10`/`cmti10`/`cmbxti10`/`cmtt10`/`cmss10`/`cmssbx10`/`cmssi10`/`cmcsc10`, plus `cmmi10` for mathematical italic letters, `cmsy10` for math symbols and `cmex10` for big operators), falling back to Liberation subsets only for characters the Type1 encodings cannot address; those fallback glyphs keep their Unicode text under PDF extraction, so accented and Greek words round-trip; Type1 faces carry a ToUnicode CMap built from the requested characters, so glyphs whose names are ambiguous in the Adobe Glyph List (capital Omega, which would otherwise extract as U+2126) keep their intended code points. `Engine::edit` preserves the face when reflowing an edited paragraph.
The crate currently has 434 unit tests plus ten route-D integration tests and forty-two oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 977 tests (434 route-D unit, 355 engine binary unit, 10 route-D integration, 42 oracle, 71 v1 integration, 60 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path.
The crate currently has 434 unit tests plus ten route-D integration tests and forty-two oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 979 tests (434 route-D unit, 357 engine binary unit, 10 route-D integration, 42 oracle, 71 v1 integration, 60 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path.
### M0 incremental demo
@@ -494,6 +494,13 @@ deliberately open rather than approximated:
`geometry`'s `top`/`bottom` options shift the page body below the sheet edge
(the arXiv template's first baseline now sits at 1in + 12pt instead of the
page edge), while an explicit `textheight` still wins over margins.
`\pagestyle{fancy}` with `\fancyhf`/`\fancyhead`/`\fancyfoot` and the
`\lhead`/`\chead`/`\rhead`/`\lfoot`/`\cfoot`/`\rfoot` shorthands paint
L/C/R running heads at `top margin - headsep` and feet at
`text height + footskip`, expand `\thepage` per page, draw
`\headrulewidth`, and suppress the head and number on a title page; the
arXiv template shows `A Preprint` (right) and its short title (centre) on
pages after the title page.
- Page hashes cover rendered items/insertions/marks/floats, not source-dependency
metadata, so replaying an earlier page cannot change its hash merely by
re-attaching source hashes.
+316
View File
@@ -215,6 +215,21 @@ struct PageGeometry {
suppress_page_numbers: bool,
/// `\thispagestyle{empty}` suppresses the number on the first page.
suppress_first_page_number: bool,
/// `\pagestyle{fancy}` turns on the fancyhdr fields below.
fancy_pagestyle: bool,
/// `\thispagestyle{empty}` suppresses the running head on the first page.
suppress_first_page_header: bool,
header_left: Option<String>,
header_center: Option<String>,
header_right: Option<String>,
footer_left: Option<String>,
footer_center: Option<String>,
footer_right: Option<String>,
/// `\renewcommand{\headrulewidth}{0.4pt}`.
head_rule_width: Option<i64>,
head_sep: Option<i64>,
head_height: Option<i64>,
foot_skip: Option<i64>,
left_skip: Option<i64>,
right_skip: Option<i64>,
tolerance: Option<i64>,
@@ -2438,6 +2453,12 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
|| is_macro_command("\\def")
|| is_macro_command("\\gdef")
{
if is_macro_command("\\renewcommand")
&& let Some(width) = renewcommand_length(definition_line, "headrulewidth")
{
geometry.head_rule_width = Some(width);
continue;
}
if let Some(definition) = macro_definition(definition_line) {
let provided = definition_line.trim_start().starts_with("\\providecommand");
if !provided
@@ -2652,13 +2673,50 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
geometry.page_start = 0;
}
} else if let Some(rest) = trimmed.strip_prefix("\\pagestyle") {
if rest.trim_start().starts_with("{fancy}") {
geometry.fancy_pagestyle = true;
}
if rest.trim_start().starts_with("{empty}") {
geometry.suppress_page_numbers = true;
}
} else if let Some(rest) = trimmed.strip_prefix("\\thispagestyle") {
if rest.trim_start().starts_with("{empty}") {
geometry.suppress_first_page_number = true;
geometry.suppress_first_page_header = true;
}
} else if let Some((positions, text)) = fancy_field(trimmed, "\\fancyhead") {
set_fancy_fields(&mut geometry, &positions, &text, FancySlot::Header);
} else if let Some((positions, text)) = fancy_field(trimmed, "\\fancyfoot") {
set_fancy_fields(&mut geometry, &positions, &text, FancySlot::Footer);
} else if let Some(text) = fancy_all(trimmed, "\\fancyhf") {
let _ = text;
geometry.header_left = None;
geometry.header_center = None;
geometry.header_right = None;
geometry.footer_left = None;
geometry.footer_center = None;
geometry.footer_right = None;
} else if let Some((positions, text)) = fancy_field(trimmed, "\\fancyhf") {
set_fancy_fields(&mut geometry, &positions, &text, FancySlot::Header);
set_fancy_fields(&mut geometry, &positions, &text, FancySlot::Footer);
} else if let Some(text) = braced_value(trimmed, "\\lhead") {
geometry.header_left = Some(text);
} else if let Some(text) = braced_value(trimmed, "\\chead") {
geometry.header_center = Some(text);
} else if let Some(text) = braced_value(trimmed, "\\rhead") {
geometry.header_right = Some(text);
} else if let Some(text) = braced_value(trimmed, "\\lfoot") {
geometry.footer_left = Some(text);
} else if let Some(text) = braced_value(trimmed, "\\cfoot") {
geometry.footer_center = Some(text);
} else if let Some(text) = braced_value(trimmed, "\\rfoot") {
geometry.footer_right = Some(text);
} else if trimmed.starts_with("\\fancyheadoffset")
|| trimmed.starts_with("\\fancyfootoffset")
{
continue;
} else if let Some(width) = renewcommand_length(trimmed, "headrulewidth") {
geometry.head_rule_width = Some(width);
} else if let Some(name) = trimmed.strip_prefix("\\newlength") {
if let Some(name) = name.trim_start().strip_prefix('{')
&& let Some((name, _)) = name.split_once('}')
@@ -4650,6 +4708,11 @@ fn geometry_and_body(source: &str) -> (String, PageGeometry) {
let today = today_string();
body = expand_today(&body, &today);
body = expand_lipsum(&body);
// Class \maketitle definitions (arXiv, sn-jnl) issue \thispagestyle{empty}.
if geometry.fancy_pagestyle && geometry.title.is_some() {
geometry.suppress_first_page_header = true;
geometry.suppress_first_page_number = true;
}
(body, geometry)
}
@@ -4899,6 +4962,67 @@ fn resolve_citations(paragraphs: &mut [SourceParagraph], bibliography: &[(String
}
}
#[derive(Clone, Copy)]
enum FancySlot {
Header,
Footer,
}
/// Parse `\fancyhead[L]{...}` / `\fancyfoot[CR]{...}` into the position list
/// and field text. Without a bracket the field is centred.
fn fancy_field(line: &str, command: &str) -> Option<(Vec<char>, String)> {
let rest = line.strip_prefix(command)?.trim_start();
let (positions, rest) = if let Some(rest) = rest.strip_prefix('[') {
let (inside, tail) = rest.split_once(']')?;
(
inside
.chars()
.filter(|character| matches!(character, 'L' | 'C' | 'R'))
.collect::<Vec<_>>(),
tail.trim_start(),
)
} else {
(vec!['C'], rest)
};
let (text, _) = braced_group(rest)?;
Some((positions, text.to_string()))
}
/// Match a bracketless `\fancyhf{...}` (clear-all form).
fn fancy_all(line: &str, command: &str) -> Option<String> {
let rest = line.strip_prefix(command)?.trim_start();
if rest.starts_with('[') {
return None;
}
let (text, _) = braced_group(rest)?;
Some(text.to_string())
}
fn set_fancy_fields(geometry: &mut PageGeometry, positions: &[char], text: &str, slot: FancySlot) {
for position in positions {
match (slot, position) {
(FancySlot::Header, 'L') => geometry.header_left = Some(text.to_string()),
(FancySlot::Header, 'C') => geometry.header_center = Some(text.to_string()),
(FancySlot::Header, 'R') => geometry.header_right = Some(text.to_string()),
(FancySlot::Footer, 'L') => geometry.footer_left = Some(text.to_string()),
(FancySlot::Footer, 'C') => geometry.footer_center = Some(text.to_string()),
(FancySlot::Footer, 'R') => geometry.footer_right = Some(text.to_string()),
_ => {}
}
}
}
fn renewcommand_length(line: &str, name: &str) -> Option<i64> {
let rest = line.strip_prefix("\\renewcommand")?.trim_start();
let (target, used) = braced_group(rest)?;
if target.trim() != format!("\\{name}") {
return None;
}
let after = &rest[used..];
let (value, _) = braced_group(after.trim_start())?;
parse_dimension(value.trim())
}
fn apply_geometry(document: &mut Document, geometry: &PageGeometry) {
document.h_offset = geometry.origin.h_offset;
// geometry's `top` places the text block below the sheet edge; the
@@ -5360,6 +5484,13 @@ pub fn pdf_bytes_with_images(
geometry.suppress_first_page_number,
);
}
stamp_running_heads(
&mut pages,
&geometry,
document.page_goal,
document.text_width,
document.paper_height,
);
let metadata = PdfMetadata {
title: geometry
.pdf_title
@@ -10718,6 +10849,109 @@ fn page_number_text(index: usize, style: &str, start: u32) -> String {
}
/// Paint the LaTeX page number centred in the footer of every page.
/// Draw fancyhdr's running header/footer fields on every page. Positions are
/// content-relative: the header sits above the first baseline and the footer
/// below the page goal, so the PDF writer's page origin shifts both correctly.
fn stamp_running_heads(
lists: &mut [DisplayList],
geometry: &PageGeometry,
page_goal: i64,
text_width: i64,
paper_height: i64,
) {
if !geometry.fancy_pagestyle || geometry.suppress_page_numbers {
return;
}
let head_sep = geometry.head_sep.unwrap_or(25 * SCALE);
let foot_skip = geometry.foot_skip.unwrap_or(30 * SCALE);
let header_baseline = -head_sep;
let footer_baseline = (page_goal + foot_skip).min(paper_height - 12 * SCALE);
let rule_width = geometry.head_rule_width.unwrap_or(0);
let style = geometry.page_numbering.as_deref().unwrap_or("arabic");
for (index, list) in lists.iter_mut().enumerate() {
if index == 0 && geometry.suppress_first_page_header {
continue;
}
let number = page_number_text(index, style, geometry.page_start);
let fields = [
(&geometry.header_left, header_baseline, 0_usize),
(&geometry.header_center, header_baseline, 1),
(&geometry.header_right, header_baseline, 2),
(&geometry.footer_left, footer_baseline, 0),
(&geometry.footer_center, footer_baseline, 1),
(&geometry.footer_right, footer_baseline, 2),
];
for (field, baseline, position) in fields {
let Some(field) = field else {
continue;
};
let text = running_head_text(field, geometry, &number);
if text.is_empty() {
continue;
}
let width = text_width_roman(&text);
let x = match position {
0 => 0,
1 => ((text_width - width) / 2).max(0),
_ => (text_width - width).max(0),
};
list.push(DisplayItem::Text {
x,
y: baseline,
size: 9 * SCALE,
text,
font: FontFace::Roman,
});
}
if rule_width > 0 {
list.push(DisplayItem::Rule {
x: 0,
y: header_baseline + 4 * SCALE,
width: text_width,
height: rule_width,
});
}
}
}
fn running_head_text(field: &str, geometry: &PageGeometry, page_number: &str) -> String {
// Remove size/shape declarations before expanding macros: the class
// redefines \footnotesize in terms of itself, and expanding it would
// repeat \@setfontsize internals on every pass.
let mut field = field.to_string();
for declaration in [
"\\scshape",
"\\footnotesize",
"\\small",
"\\normalsize",
"\\large",
"\\Large",
"\\LARGE",
"\\huge",
"\\Huge",
"\\bfseries",
"\\itshape",
"\\slshape",
"\\upshape",
"\\ttfamily",
"\\sffamily",
"\\rmfamily",
"\\mdseries",
"\\centering",
"\\relax",
] {
field = field.replace(declaration, "");
}
let mut text = expand_macros(&field, &geometry.macros);
text = text.replace("\\thepage", page_number);
if let Some(title) = geometry.title.as_deref() {
text = text.replace("\\@title", title);
text = text.replace("\\shorttitle", title);
text = text.replace("\\headeright", "A Preprint");
}
scrub_title_metadata(&text)
}
fn stamp_page_numbers(
lists: &mut [DisplayList],
page_goal: i64,
@@ -11041,6 +11275,13 @@ fn render_json(
geometry.suppress_first_page_number,
);
}
stamp_running_heads(
&mut lists,
geometry,
document.page_goal,
document.text_width,
document.paper_height,
);
for (index, (page, mut list)) in engine.pages().iter().zip(lists).enumerate() {
list.place(document.h_offset, document.v_offset);
if index > 0 {
@@ -14089,6 +14330,81 @@ A definition.
value["pageCount"].as_u64().unwrap_or(0) >= 2,
"expected at least two pages"
);
let pages = value["pages"].as_array().expect("pages");
let first = pages[0]["svg"].as_str().expect("first svg");
let second = pages[1]["svg"].as_str().expect("second svg");
assert!(
!first.contains("A Preprint"),
"title page must be empty style"
);
assert!(second.contains("A Preprint"), "right header missing");
assert!(second.contains("arXiv Template"), "centre header missing");
}
#[test]
fn fancyhdr_fields_are_parsed() {
let source = "\\documentclass{article}\n\\pagestyle{fancy}\n\\fancyhf{}\n\\rhead{\\scshape \\footnotesize \\headeright}\n\\chead{\\shorttitle}\n\\lfoot{Left}\n\\cfoot{\\thepage}\n\\renewcommand{\\headrulewidth}{0.4pt}\n\\begin{document}\n\nHello.\n\n\\end{document}\n";
let (_body, geometry) = geometry_and_body(source);
assert!(geometry.fancy_pagestyle);
assert_eq!(
geometry.header_right.as_deref(),
Some("\\scshape \\footnotesize \\headeright")
);
assert_eq!(geometry.header_center.as_deref(), Some("\\shorttitle"));
assert_eq!(geometry.footer_left.as_deref(), Some("Left"));
assert_eq!(geometry.footer_center.as_deref(), Some("\\thepage"));
assert_eq!(geometry.head_rule_width, parse_dimension("0.4pt"));
}
fn svg_texts(json: &str) -> Vec<(String, f64, f64)> {
let value: serde_json::Value = serde_json::from_str(json).expect("JSON");
let mut found = Vec::new();
for page in value["pages"].as_array().expect("pages") {
let svg = page["svg"].as_str().expect("svg");
let mut rest = svg;
while let Some(start) = rest.find("<text ") {
let tag_end = start + rest[start..].find('>').expect("tag end");
let close = tag_end + rest[tag_end..].find("</text>").expect("close");
let tag = &rest[start..=tag_end];
let text = rest[tag_end + 1..close].to_string();
let attr = |name: &str| -> f64 {
let needle = format!("{name}=\"");
let at = tag.find(&needle).expect("attr") + needle.len();
let end = tag[at..].find('"').expect("attr end") + at;
tag[at..end].parse().expect("numeric")
};
found.push((text, attr("x"), attr("y")));
rest = &rest[close + "</text>".len()..];
}
}
found
}
#[test]
fn fancy_headers_and_footers_are_painted() {
let source = "\\documentclass{article}\n\\usepackage[top=1in,textheight=9in]{geometry}\n\\pagestyle{fancy}\n\\fancyhf{}\n\\rhead{Preprint}\n\\cfoot{Page \\thepage}\n\\begin{document}\n\nHello.\n\n\\end{document}\n";
let json = preview_json(source).expect("preview");
let texts = svg_texts(&json);
let head = texts
.iter()
.find(|(text, _, _)| text == "Preprint")
.expect("header");
let inch = parse_dimension("1in").unwrap() as f64 / SCALE as f64;
assert!(
(head.2 - (inch - 25.0)).abs() < 0.5,
"header baseline at {}pt",
head.2
);
assert!(head.1 > 400.0, "right header should be right-aligned");
let footer = texts
.iter()
.find(|(text, _, _)| text == "Page 1")
.expect("footer page number");
assert!(
(footer.2 - (inch + 9.0 * 72.27 + 30.0)).abs() < 1.0,
"footer baseline at {}pt",
footer.2
);
}
#[test]