Show the current heading in headings-style headers
The headings page style only painted the page number. Document now records its heading units (unit index and title) during layout, and a page_headings helper carries the latest heading from page to page through the page sources. The running-head pass uses that list in headings style: the numbered heading title is uppercased at the left of the header and the page number stays right-aligned, with the first page still plain. The headings test gains a section and checks "1 INTRODUCTION" sits at the left of the header baseline.
This commit is contained in:
1 parent
ae810867f7
commit
9da0f136a4
3 files changed
+55
-2
No files matched your search
@@ -1782,6 +1782,9 @@ pub struct Document {
|
||||
/// Unit indices that start on a fresh page (TeX `\newpage` forced breaks).
|
||||
#[serde(default)]
|
||||
pub page_breaks: Vec<usize>,
|
||||
/// Heading units (unit index, title) in document order, for running heads.
|
||||
#[serde(default)]
|
||||
pub headings: Vec<(u64, String)>,
|
||||
/// TeX `\paperwidth`: width of the output page.
|
||||
#[serde(default = "default_paper_width")]
|
||||
pub paper_width: i64,
|
||||
@@ -1962,6 +1965,7 @@ impl Document {
|
||||
units,
|
||||
page_goal,
|
||||
page_breaks: Vec::new(),
|
||||
headings: Vec::new(),
|
||||
paper_width: default_paper_width(),
|
||||
paper_height: default_paper_height(),
|
||||
text_width: default_text_width(),
|
||||
|
||||
+1
-1
@@ -136,7 +136,7 @@ and justification.
|
||||
| M3 | `\halign`, `\omit`, `\span`, `\multispan`, booktabs/longtable | **partial**: source parsing, natural column widths, spans, rule rows, 10pt display-list painting and row-level page splitting; the paged builder splits a tall alignment into page-sized row chunks that keep the table's column widths, so long tables continue across pages; `p{width}` paragraph columns wrap cell text and grow row heights, wrapped rows participate in row-level splitting, explicit per-column `\tabskip` glue is honoured through layout, painting and page chunks, and booktabs rules carry their own weights and spans (`\toprule`/`\bottomrule` 0.8pt, `\midrule`/`\addlinespace`/`\cmidrule` 0.5pt, with `\cmidrule(lr){a-b}` trimming and column ranges), `@{}` / `@{\hspace{...}}` column expressions override the inter-column glue, and row-boundary `\noalign{\vskip ...}` glue is honoured by layout, painting and page chunks; longtable head/foot sections (`\endfirsthead`/`\endhead`/`\endfoot`/`\endlastfoot`) are parsed, continuation chunks repeat the head rows and the foot block paints once at the end, LaTeX `tabular` environments are captured and laid out through the same `\halign` path (rules are stripped from the column spec, `p{...}`/`m{...}`/`b{...}` become wrapping columns, `@{}` expressions are ignored for spacing), `\multicolumn{n}{align}{...}` cells span columns with the requested alignment, `\cline{a-b}` draws a 0.4pt partial rule over a column range, though `\valign`, nested tables and full tabular parity remain open |
|
||||
| M4 | math lists, scripts, fractions, radicals, accents, delimiters | **partial**: token parser, atom boxes with Computer Modern metrics (italic letters from the bundled `cmmi10`, big operators from `cmex10`, symbols such as `\times`/`\leq`/`\infty` from `cmsy10`, with `cmmi10`, `cmsy10` and `cmex10` glyphs embedded as Type1 outlines), `\left...\right` delimiter selection through CMEX size variants using TeX's delimiterfactor and shortfall, accents and a display-list painter; display formulas wider than the measure are split at top-level binary/relation operators into multiple lines (an approximation of TeX's `\split` behaviour; `align`/`align*` displays share column widths and number each row, while `gather`/`gather*` centre every row, `alignat` numbers rows the same way while ignoring its column-count argument, a `split` body inside `equation` is numbered once, and `multline` rows flush left and right around a single number); CMEX delimiter size variants back `\big`/`\Big`/`\bigg`/`\Bigg`; inter-atom spacing uses TeX's full atom-class table with binary-operator normalisation, with `1mu` = `1/18em` (a thin space is 3mu = 1.67pt at 10pt); `\mid` is a relation while `\colon` is punctuation; `\limits` stacks an operator's scripts above and below at TeX's script size and clearance (checked against pdfLaTeX word positions, including descender bases) while `\nolimits` keeps them beside the operator, `\substack{...}` stacks its rows with TeX's inter-row gaps, and an integral keeps its scripts beside it unless `\limits` asks otherwise, as TeX's display rules do; `\mskip`, `\mkern`, `\mspace`, `\hskip`, `\kern` and `\hspace` scan TeX dimensions (`mu`, `pt`, `em`, ...) and contribute their natural width, accepting `plus`/`minus` parts even though math boxes are not glue lists; route-D numbers `equation` environments and resolves `\eqref`/`\ref` through their labels; `\tag` overrides the number and `\notag`/`\nonumber` suppress it; `displaymath` environments (and `$$`/`\[` displays) stay unnumbered while `math` environments select inline math; math italic letters are embedded as Computer Modern Type1 outlines (`cmmi10`), and math alphabets map `\\mathbf`/`\\mathit`/`\\mathsf`/`\\mathtt` onto the bold, math-italic, sans and mono faces with their TFMs and `\\mathcal` onto the cmsy10 calligraphic capitals; `\mathfrak` maps onto the bundled eufm10 Fraktur letters (embedded as Type1 outlines); infix fractions `\over`, `\atop`, `\choose`, `\brace`, `\brack` and their `withdelims` forms build fractions from the current row, with the bar only for the `\over` forms; `\genfrac{left}{right}{thickness}{style}{num}{den}` builds a fraction with optional delimiters and no rule for an empty or `0pt` thickness; `\middle` delimiters are sized with their enclosing `\left`/`\right` group and `\big`/`\Big`/`\bigg`/`\Bigg` paint at their selected CMEX size |
|
||||
| M5 | NFSS/TFM metrics, CM/Latin Modern | **partial**: paragraph-level NFSS declarations and inline run composition over the built-in Roman/Bold/Italic/BoldItalic/Mono/MonoItalic/Sans/SansBold/SansItalic/SmallCaps/Slanted/BoldSlanted faces (CM has no sans bold-italic, so `cmss/bx/it` substitutes `cmss/bx/n`; `\scshape` selects cmcsc10 and a bold small caps request falls back to cmbx10; `\slshape` uses the slanted cmsl10 rather than the italic cmti10 and `\ttfamily\itshape` reaches cmitt10), per-face Computer Modern TFM metrics, and Type1 (PFB) outline embedding for every built-in face plus `cmmi10` math italics, `cmsy10` math symbols and `cmex10` big operators, with a Liberation subset falling back per glyph for characters outside the Type1 encodings, so ASCII on an accented line still uses the Computer Modern face, and Type1 faces carry a ToUnicode CMap built from the requested characters so extraction does not depend on ambiguous glyph names; paragraph base sizes from `\fontsize` and the article size commands scale glyph metrics and the default interline glue while the measure and authored skips stay absolute, a size command in the middle of a paragraph splits a sized run that is shaped and painted at its own type size, and inline math inside a styled run keeps its math boxes while the surrounding text keeps its face; accent commands such as `\'`, `` \` ``, `\"`, `\^`, `\~`, `\c`, `\v` and `\=` compose precomposed Unicode letters and fall back to the base letter plus a combining mark, while `\textsuperscript` and `\textsubscript` set a 70% run raised or lowered by 0.4em; `\MakeUppercase`/`\MakeLowercase` (and `\uppercase`/`\lowercase`) transform their braced text and keep the surrounding face; full NFSS family/shape state and Type1 coverage for arbitrary Unicode remain open |
|
||||
| M6 | class/package execution (`article`, `sn-jnl`) | **partial**: a leading `\noindent` starts a paragraph flush with the measure, box commands `\mbox{...}`, `\hbox{...}` and `\makebox[width][position]{...}` keep their text in the flow, and `\hspace{...}`/`\hspace*{...}` reserve their TeX width in the running text, text-mode `\quad`/`\qquad` and `\,`/`\:`/`\;` insert the corresponding TeX spaces, `\enspace`, `\thinspace`, `\medspace` and `\thickspace` insert their named TeX widths, `\documentclass[...]` options are read and the article `10pt`/`11pt`/`12pt` base size sets the default paragraph font size and `\baselineskip` (13.6pt/14.5pt), and `\linespread{factor}` (or `\renewcommand{\baselinestretch}{factor}`/`\def\baselinestretch{factor}`) scales that class baseline, while `\newlength{\name}` registers a named length that `\setlength` can assign and a later `\setlength{\parindent}{\name}` can read, and `\addtolength{\name}{...}` adjusts it; the `geometry` package's `margin`/`hmargin`/`vmargin`/`left`/`right`/`top`/`bottom` options (and `\geometry{...}`) adjust the measure and page height; page numbers print centred below the text block (or right-aligned in a header on pages after the first under `\pagestyle{headings}`/`{myheadings}`), `\setcounter{page}` offsets the printed number, `\addtocounter{page}` shifts it (`\pagenumbering` resets it to 1), `\pagenumbering{roman|Roman|alph|Alph|arabic}` selects the format and `\pagestyle{empty}` suppresses them on every page and `\thispagestyle{empty}` on the first page; `\title`/`\author`/`\date` are captured, `\hypersetup{pdftitle=...}` (also `pdfauthor`/`pdfsubject`/`pdfkeywords`) writes the PDF Info dictionary with UTF-16BE values for non-ASCII text (falling back to `\title`/`\author`), each numbered heading becomes a PDF bookmark in `/Outlines`, nested by heading level and pointing at its page, `\today` expands to the UTC calendar date in the title block and the body, and `\maketitle` expands into the centered article title block at the class sizes (with today's date when `\date` is absent and no date for `\date{}`); numbered `\section`/`\subsection`/`\subsubsection`/`\paragraph`/`\subparagraph` headings advance five-level article counters (article's `\setcounter{secnumdepth}` default of 3 numbers through `\subsubsection`, and raising it numbers the two deeper levels; `\setcounter{section}`/`{figure}`/`{table}`/`{equation}`/`{theorem}` offsets the next counter value) and paint at `\Large`/`\large`/`\normalsize` (the two deepest levels stay bold at the base size), starred headings stay unnumbered, and an optional `[short]` title replaces the long title in the table of contents; the `abstract` environment expands into a centered bold heading and a 9pt body, `acks`/`acknowledgments`/`acknowledgements` environments render an unnumbered Acknowledgments heading, `\maketitle` joins `\and` authors and turns `\thanks` notes into title footnotes, and `\label` inside a heading (or immediately after it, with or without a blank line) resolves `\ref`/`\eqref` to the section number while unknown references print `??`, and `\pageref{label}` reports the formatted page number of that heading, figure, table or equation after a probe layout (unknown labels print `??`), and `\appendix` restarts sectioning with letters (`A`, `A.1`), and `\tableofcontents` lists the numbered headings through `\subsubsection` with 12pt per-level indentation and a right-aligned page number reached by dot leaders that fill the measure (the default article `tocdepth` of 3; `\setcounter{tocdepth}` changes the depth) while `\listoffigures`/`\listoftables` reproduce the numbered figure/table captions and append each float's page number after dot leaders that fill the measure (an optional `[short]` caption is used there while the long caption stays on the float); `verbatim` environments keep each source line as a monospaced 9pt paragraph indented by 12pt (leading whitespace is normalised), `\verb|...|` renders inline literal text in the mono face, common text commands such as `\LaTeX`, `\TeX`, `\ldots`, `\dots`, `\S`, `\copyright`, `\pounds`, `\ss`/`\ae`/`\oe`/`\o`/`\l`/`\dh`/`\th` and symbol commands such as `\textquotesingle`, `\textunderscore`, `\textbraceleft`, `\textbraceright`, `\textdegree`/`\textmu`/`\textonehalf`/`\texteuro` expand to their characters, and a control word swallows the spaces that follow it, layout-only commands such as `\protect`, `\relax`, `\ignorespaces`, `\unskip`, `\nobreak` and `\phantomsection` are dropped, `\phantom`/`\hphantom` reserve their measured width invisibly while `\vphantom` adds no width, `\href{url}{text}` keeps its text, `\url{...}` becomes typewriter text, and `\hyperref[label]{text}`, `\hyperlink{name}{text}` and `\hypertarget{name}{text}` keep their visible label (internal PDF targets are not modelled), `\autoref{label}` resolves a section label to `Section <number>`, and `\nameref{label}` resolves it to the heading title (falling back to the number); a `~` Line truncated
|
||||
| M6 | class/package execution (`article`, `sn-jnl`) | **partial**: a leading `\noindent` starts a paragraph flush with the measure, box commands `\mbox{...}`, `\hbox{...}` and `\makebox[width][position]{...}` keep their text in the flow, and `\hspace{...}`/`\hspace*{...}` reserve their TeX width in the running text, text-mode `\quad`/`\qquad` and `\,`/`\:`/`\;` insert the corresponding TeX spaces, `\enspace`, `\thinspace`, `\medspace` and `\thickspace` insert their named TeX widths, `\documentclass[...]` options are read and the article `10pt`/`11pt`/`12pt` base size sets the default paragraph font size and `\baselineskip` (13.6pt/14.5pt), and `\linespread{factor}` (or `\renewcommand{\baselinestretch}{factor}`/`\def\baselinestretch{factor}`) scales that class baseline, while `\newlength{\name}` registers a named length that `\setlength` can assign and a later `\setlength{\parindent}{\name}` can read, and `\addtolength{\name}{...}` adjusts it; the `geometry` package's `margin`/`hmargin`/`vmargin`/`left`/`right`/`top`/`bottom` options (and `\geometry{...}`) adjust the measure and page height; page numbers print centred below the text block (or right-aligned in a header on pages after the first under `\pagestyle{headings}`/`{myheadings}`, with the current numbered heading title uppercased at the header's left), `\setcounter{page}` offsets the printed number, `\addtocounter{page}` shifts it (`\pagenumbering` resets it to 1), `\pagenumbering{roman|Roman|alph|Alph|arabic}` selects the format and `\pagestyle{empty}` suppresses them on every page and `\thispagestyle{empty}` on the first page; `\title`/`\author`/`\date` are captured, `\hypersetup{pdftitle=...}` (also `pdfauthor`/`pdfsubject`/`pdfkeywords`) writes the PDF Info dictionary with UTF-16BE values for non-ASCII text (falling back to `\title`/`\author`), each numbered heading becomes a PDF bookmark in `/Outlines`, nested by heading level and pointing at its page, `\today` expands to the UTC calendar date in the title block and the body, and `\maketitle` expands into the centered article title block at the class sizes (with today's date when `\date` is absent and no date for `\date{}`); numbered `\section`/`\subsection`/`\subsubsection`/`\paragraph`/`\subparagraph` headings advance five-level article counters (article's `\setcounter{secnumdepth}` default of 3 numbers through `\subsubsection`, and raising it numbers the two deeper levels; `\setcounter{section}`/`{figure}`/`{table}`/`{equation}`/`{theorem}` offsets the next counter value) and paint at `\Large`/`\large`/`\normalsize` (the two deepest levels stay bold at the base size), starred headings stay unnumbered, and an optional `[short]` title replaces the long title in the table of contents; the `abstract` environment expands into a centered bold heading and a 9pt body, `acks`/`acknowledgments`/`acknowledgements` environments render an unnumbered Acknowledgments heading, `\maketitle` joins `\and` authors and turns `\thanks` notes into title footnotes, and `\label` inside a heading (or immediately after it, with or without a blank line) resolves `\ref`/`\eqref` to the section number while unknown references print `??`, and `\pageref{label}` reports the formatted page number of that heading, figure, table or equation after a probe layout (unknown labels print `??`), and `\appendix` restarts sectioning with letters (`A`, `A.1`), and `\tableofcontents` lists the numbered headings through `\subsubsection` with 12pt per-level indentation and a right-aligned page number reached by dot leaders that fill the measure (the default article `tocdepth` of 3; `\setcounter{tocdepth}` changes the depth) while `\listoffigures`/`\listoftables` reproduce the numbered figure/table captions and append each float's page number after dot leaders that fill the measure (an optional `[short]` caption is used there while the long caption stays on the float); `verbatim` environments keep each source line as a monospaced 9pt paragraph indented by 12pt (leading whitespace is normalised), `\verb|...|` renders inline literal text in the mono face, common text commands such as `\LaTeX`, `\TeX`, `\ldots`, `\dots`, `\S`, `\copyright`, `\pounds`, `\ss`/`\ae`/`\oe`/`\o`/`\l`/`\dh`/`\th` and symbol commands such as `\textquotesingle`, `\textunderscore`, `\textbraceleft`, `\textbraceright`, `\textdegree`/`\textmu`/`\textonehalf`/`\texteuro` expand to their characters, and a control word swallows the spaces that follow it, layout-only commands such as `\protect`, `\relax`, `\ignorespaces`, `\unskip`, `\nobreak` and `\phantomsection` are dropped, `\phantom`/`\hphantom` reserve their measured width invisibly while `\vphantom` adds no width, `\href{url}{text}` keeps its text, `\url{...}` becomes typewriter text, and `\hyperref[label]{text}`, `\hyperlink{name}{text}` and `\hypertarget{name}{text}` keep their visible label (internal PDF targets are not modelled), `\autoref{label}` resolves a section label to `Section <number>`, and `\nameref{labeLine truncated
|
||||
| M7 | `\special`, PDF XObjects, hyperref annotations | PDF structure parity |
|
||||
|
||||
## Current limits
|
||||
|
||||
+50
-1
@@ -7246,12 +7246,14 @@ pub fn pdf_bytes_with_images(
|
||||
geometry.suppress_first_page_number,
|
||||
);
|
||||
}
|
||||
let headings = page_headings(&document, &engine);
|
||||
stamp_running_heads(
|
||||
&mut pages,
|
||||
&geometry,
|
||||
document.page_goal,
|
||||
document.text_width,
|
||||
document.paper_height,
|
||||
&headings,
|
||||
);
|
||||
let metadata = PdfMetadata {
|
||||
title: geometry
|
||||
@@ -13011,6 +13013,15 @@ fn build_document_with_labels(
|
||||
}
|
||||
}
|
||||
let mut document = Document::new(700 * SCALE, units);
|
||||
for (index, paragraph) in paragraphs.iter().enumerate() {
|
||||
if paragraph.heading_level.is_some()
|
||||
&& let Some(unit) = unit_for_paragraph.get(index)
|
||||
{
|
||||
document
|
||||
.headings
|
||||
.push((*unit as u64, scrub_title_metadata(¶graph.text)));
|
||||
}
|
||||
}
|
||||
if footnote_count > 0 {
|
||||
document.insertion_classes.push(InsertionClass {
|
||||
number: 0,
|
||||
@@ -13088,12 +13099,33 @@ fn page_number_text(index: usize, style: &str, start: u32) -> String {
|
||||
/// 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.
|
||||
/// Latest heading title in force on each page, derived from the page sources.
|
||||
fn page_headings(document: &Document, engine: &Engine) -> Vec<Option<String>> {
|
||||
let by_unit: std::collections::HashMap<u64, &str> = document
|
||||
.headings
|
||||
.iter()
|
||||
.map(|(unit, title)| (*unit, title.as_str()))
|
||||
.collect();
|
||||
let mut current: Option<String> = None;
|
||||
let mut result = Vec::new();
|
||||
for page in engine.pages() {
|
||||
for (unit, _) in &page.sources {
|
||||
if let Some(title) = by_unit.get(unit) {
|
||||
current = Some((*title).to_string());
|
||||
}
|
||||
}
|
||||
result.push(current.clone());
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn stamp_running_heads(
|
||||
lists: &mut [DisplayList],
|
||||
geometry: &PageGeometry,
|
||||
page_goal: i64,
|
||||
text_width: i64,
|
||||
paper_height: i64,
|
||||
headings: &[Option<String>],
|
||||
) {
|
||||
if (!geometry.fancy_pagestyle && !geometry.headings_pagestyle) || geometry.suppress_page_numbers
|
||||
{
|
||||
@@ -13108,6 +13140,15 @@ fn stamp_running_heads(
|
||||
// LaTeX's headings style uses plain on the first page.
|
||||
continue;
|
||||
}
|
||||
if let Some(Some(title)) = headings.get(index) {
|
||||
list.push(DisplayItem::Text {
|
||||
x: 0,
|
||||
y: baseline,
|
||||
size: 9 * SCALE,
|
||||
text: title.to_uppercase(),
|
||||
font: FontFace::Roman,
|
||||
});
|
||||
}
|
||||
let number = page_number_text(index, style, geometry.page_start);
|
||||
let width = text_width_roman(&number);
|
||||
list.push(DisplayItem::Text {
|
||||
@@ -13542,12 +13583,14 @@ fn render_json(
|
||||
geometry.suppress_first_page_number,
|
||||
);
|
||||
}
|
||||
let headings = page_headings(document, engine);
|
||||
stamp_running_heads(
|
||||
&mut lists,
|
||||
geometry,
|
||||
document.page_goal,
|
||||
document.text_width,
|
||||
document.paper_height,
|
||||
&headings,
|
||||
);
|
||||
for (index, (page, mut list)) in engine.pages().iter().zip(lists).enumerate() {
|
||||
list.place(document.h_offset, document.v_offset);
|
||||
@@ -16746,7 +16789,7 @@ A definition.
|
||||
|
||||
#[test]
|
||||
fn headings_pagestyle_puts_the_number_in_the_header() {
|
||||
let source = "\\documentclass{article}\n\\pagestyle{headings}\n\\begin{document}\n\nFirst.\n\n\\newpage\n\nSecond.\n\n\\end{document}\n";
|
||||
let source = "\\documentclass{article}\n\\pagestyle{headings}\n\\begin{document}\n\n\\section{Introduction}\n\nFirst.\n\n\\newpage\n\nSecond.\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!(
|
||||
@@ -16757,6 +16800,12 @@ A definition.
|
||||
);
|
||||
assert_eq!(value["pageCount"].as_u64(), Some(2));
|
||||
let texts = svg_texts(&json);
|
||||
let title = texts
|
||||
.iter()
|
||||
.find(|(text, _, _)| text == "1 INTRODUCTION")
|
||||
.expect("header heading");
|
||||
assert!(title.1 < 100.0, "title should be left-aligned");
|
||||
assert!(title.2 < 0.0, "title should sit in the header");
|
||||
let number = texts
|
||||
.iter()
|
||||
.find(|(text, _, _)| text == "2")
|
||||
|
||||
Reference in new issue
Block a user