From 3406f84e86d89a7582dd6555675dcecd7f1107ca Mon Sep 17 00:00:00 2001 From: GloamXun Date: Mon, 19 Oct 2026 15:28:54 +0800 Subject: [PATCH] Expand fancy headers at document start and add header rules --- README.md | 5 +- docs/STATUS.md | 3 +- src/rust_typeset/pdf/layout.rs | 50 +++++++++++++++++-- src/rust_typeset/texlang_adapter.rs | 76 +++++++++++++++++++++++++++++ tests/typeset.rs | 29 +++++++++++ 5 files changed, 157 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 748c0b0..59d203a 100644 --- a/README.md +++ b/README.md @@ -176,7 +176,10 @@ Page styles are painted in both the PDF and the SVG preview: `\thispagestyle{...}` overrides one page, and fancyhdr's `\fancyhead`/ `\fancyfoot` plus `\lhead`/`\chead`/`\rhead`/`\lfoot`/`\cfoot`/`\rfoot` place runs in the left, center, or right slot. `\thepage` is resolved when the -page is painted, so the footer shows the real page number. The default style is +page is painted, so the footer shows the real page number. Decoration tokens +are expanded at the start of the document, after packages have renewed macros +such as the short title, and fancy headers get the usual 0.4pt rule below them. +The default style is `plain` (a centered page number). The following packages are accepted as built-ins: `geometry`, `graphicx`, diff --git a/docs/STATUS.md b/docs/STATUS.md index 142e7f8..1de48fa 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -35,7 +35,8 @@ the source changes; the SVG preview is refreshed per page. default `plain` page numbers, `\pagestyle{empty|plain|fancy}`, `\thispagestyle`, fancyhdr `\fancyhead`/`\fancyfoot` (L/C/R) and `\lhead`/`\chead`/`\rhead`/`\lfoot`/`\cfoot`/`\rfoot`, with `\thepage` - resolved at paint time. + resolved at paint time; decoration tokens are expanded at the start of the + document, after packages have renewed macros, and fancy headers get a 0.4pt rule. - Notes: `\footnote{...}` page-bottom insertion area with separator rule, superscript markers, and title/author `\thanks`. - Contents: `\tableofcontents`, `\listoffigures`, and `\listoftables` diff --git a/src/rust_typeset/pdf/layout.rs b/src/rust_typeset/pdf/layout.rs index b9eb6c0..2d86da4 100644 --- a/src/rust_typeset/pdf/layout.rs +++ b/src/rust_typeset/pdf/layout.rs @@ -2844,13 +2844,14 @@ fn append_page_decorations( let page_count = pages.len(); for (index, page) in pages.iter_mut().enumerate() { let page_number = index + 1; + let mut header_bottom: Option = None; let kind = effective_page_style_kind(model, index, page_count, block_start_pages); if kind == PageStyleKind::Empty { continue; } if kind == PageStyleKind::Plain { let runs = [Run::plain(page_number.to_string())]; - append_decoration( + let _ = append_decoration( page, &runs, page_number, @@ -2884,7 +2885,7 @@ fn append_page_decorations( if runs.is_empty() { continue; } - append_decoration( + let end_y = append_decoration( page, runs, page_number, @@ -2901,8 +2902,20 @@ fn append_page_decorations( math_layout, cache, ); + if is_header && let Some(end_y) = end_y { + header_bottom = + Some(header_bottom.map_or(end_y, |current: i64| current.max(end_y))); + } } } + if let Some(bottom) = header_bottom { + append_header_rule( + page, + page_number, + bottom.saturating_add(i64::from(scaled_points(2.0).0)), + content_width_mm, + ); + } } } @@ -2923,7 +2936,7 @@ fn append_decoration( math_metrics: &math_font::MathFontMetrics, math_layout: &MathLayoutEnvironment, cache: &mut ParagraphLayoutCache, -) { +) -> Option { let runs = resolved_page_number_runs(runs, page_number); let lines = measure_positioned_lines( &runs, @@ -2939,7 +2952,7 @@ fn append_decoration( cache, ); if lines.is_empty() { - return; + return None; } let body_width = millimeters_to_scaled(content_width_mm); let content_height = millimeters_to_scaled(content_height_mm); @@ -2981,6 +2994,35 @@ fn append_decoration( })); y = y.saturating_add(line.height); } + is_header.then_some(y) +} + +fn append_header_rule(page: &mut PositionedPage, page_number: usize, y: i64, width_mm: f64) { + let rule_height = i64::from(scaled_points(0.4).0).max(1); + let width = millimeters_to_scaled(width_mm); + page.items.push(PositionedPageItem::Line(PositionedLine { + anchor: PageAnchor { + block: usize::MAX, + line: page_number.saturating_mul(1024).saturating_add(99), + }, + content: PositionedLineContent::Text { + line: text_layout::LineBox { + width: common::Scaled(width as i32), + items: vec![text_layout::LineItem::Rule { + width: common::Scaled(width as i32), + raise: common::Scaled::ZERO, + height: common::Scaled(rule_height as i32), + y_offset: common::Scaled::ZERO, + }], + pre_display_size: None, + }, + font_size: 9, + }, + y, + x: 0, + centered: false, + ragged: false, + })); } fn display_math_style() -> Style { diff --git a/src/rust_typeset/texlang_adapter.rs b/src/rust_typeset/texlang_adapter.rs index bf375cb..0ecf107 100644 --- a/src/rust_typeset/texlang_adapter.rs +++ b/src/rust_typeset/texlang_adapter.rs @@ -523,6 +523,20 @@ struct CompilerState { geometry_page: texrra_core::document::PageSize, #[serde(skip)] geometry_margins: texrra_core::document::PageMargins, + /// Header/footer definitions are stored as token lists until + /// `\begin{document}` so that later `\renewcommand`s (for example + /// `\shorttitle` in journal styles) are visible when they expand. + #[serde(skip)] + pending_page_decorations: Vec, + #[serde(skip)] + document_started: bool, +} + +struct PendingPageDecoration { + token: token::Token, + header: bool, + position: texrra_core::document::PageDecorationPosition, + inner: Vec, } struct TexlangInputTrace { @@ -1812,6 +1826,18 @@ fn fancy_decoration_primitive( ); return Ok(()); } + if !input.state().document_started { + input + .state_mut() + .pending_page_decorations + .push(PendingPageDecoration { + token, + header, + position, + inner, + }); + return Ok(()); + } write_event( input, token, @@ -1831,6 +1857,44 @@ fn fancy_decoration_primitive( Ok(()) } +fn flush_pending_page_decorations( + token: token::Token, + input: &mut vm::ExecutionInput, +) -> texlang::prelude::Result<()> { + let Some(pending) = (!input.state().pending_page_decorations.is_empty()) + .then(|| input.state_mut().pending_page_decorations.remove(0)) + else { + return Ok(()); + }; + write_event( + input, + pending.token, + FrontendEventKind::PageDecorationStart { + header: pending.header, + position: pending.position, + }, + ); + let trace_key = pending.token.trace_key(); + let mut expansion = pending.inner; + expansion.push(control_sequence_token( + input, + "texrrapagedecorationend", + trace_key, + )); + if !input.state().pending_page_decorations.is_empty() { + expansion.push(control_sequence_token( + input, + "texrraflushpagedecorations", + token.trace_key(), + )); + } + input + .as_mut() + .expansions_mut() + .extend(expansion.into_iter().rev()); + Ok(()) +} + fn fancy_head_primitive( token: token::Token, input: &mut vm::ExecutionInput, @@ -5801,6 +5865,14 @@ fn begin_environment_primitive( .filter_map(|token| token.char()) .collect::(); let name = name.trim().to_string(); + if name == "document" && !input.state().document_started { + input.state_mut().document_started = true; + if !input.state().pending_page_decorations.is_empty() { + let trace_key = token.trace_key(); + let flush = control_sequence_token(input, "texrraflushpagedecorations", trace_key); + input.as_mut().expansions_mut().push(flush); + } + } let argument = if matches!( name.as_str(), "array" | "tabular" | "alignedat" | "alignat" | "alignat*" @@ -6941,6 +7013,10 @@ fn built_in_commands() -> HashMap<&'static str, texlang::command::BuiltInBefore."), "text before vbox missing"); assert!(svg.contains(">After"), "text after vbox missing"); } + +#[test] +fn page_decorations_expand_declarations_at_document_start() { + let source = r#"\documentclass{article} +\usepackage{fancyhdr} +\pagestyle{fancy} +\fancyhf{} +\chead{\shorttitle} +\def\shorttitle{First title} +\def\shorttitle{Renewed title} +\begin{document} +First page. +\newpage +Second page. +\end{document} +"#; + let value = fresh_preview(source, "header-declarations.tex"); + assert_eq!(value["status"], "ok", "{}", value["message"]); + assert_eq!(pages(&value).len(), 2, "expected two pages: {value}"); + let second = page_svg(&value, 1); + assert!( + second.contains(">Renewed"), + "header did not see the renewed shorttitle: {second}" + ); + assert!( + !second.contains(">First"), + "header was expanded too early: {second}" + ); +}