Write PDF bookmarks for section headings
This commit is contained in:
1 parent
863e7c1a81
commit
5f98c199a5
5 files changed
+146
-9
No files matched your search
@@ -469,7 +469,7 @@ from the font's MATH assembly parts. `\\left...\\right` target sizing follows
|
||||
the assignable TeX parameters `\\delimiterfactor` (default 901) and
|
||||
`\\delimitershortfall` (default 5pt), including local and global assignments.
|
||||
|
||||
Route-D text faces follow the NFSS declarations and compose with the surrounding run: `\sffamily\bfseries` selects cmssbx10, `\sffamily\itshape` selects cmssi10, and bold italic sans substitutes cmssbx10 because Computer Modern has no sans bold italic. `\scshape`/`\textsc` select the real cmcsc10 small-caps face, `\slshape`/`\textsl` use cmsl10 (or cmbxsl10 when bold) rather than the italic cmti10, and `\ttfamily\itshape` reaches cmitt10. All twelve text programs (cmr10, cmbx10, cmti10, cmbxti10, cmtt10, cmss10, cmssbx10, cmssi10, cmcsc10, cmsl10, cmbxsl10, cmitt10) are embedded as Type1 outlines. Characters outside a program's encoding fall back per glyph to a Liberation subset, so the ASCII letters of an accented word still use Computer Modern and Greek text keeps its Unicode text under PDF extraction, including capital Omega, because the embedded Type1 faces carry a ToUnicode CMap built from the requested characters rather than relying on glyph names. Accent commands such as `\'`, `` \` ``, `\"`, `\^`, `\~`, `\c`, `\v` and `\=` compose precomposed Unicode letters and fall back to the base letter plus a combining mark. `\textsuperscript` and `\textsubscript` set a 70% run raised or lowered by 0.4em. `\MakeUppercase` and `\MakeLowercase` (also `\uppercase`/`\lowercase`) transform their braced text while keeping the surrounding face. Because Computer Modern has no bold small caps, a bold small-caps request falls back to cmbx10. Section-wide declarations such as `\bfseries` apply from where they appear to the end of their group, and `\em` toggles emphasis relative to the surrounding face. Paragraph base sizes come from `\fontsize{<size>}{<baselineskip>}` and the article size commands (`\tiny` through `\Huge`), scaling glyph metrics and the default interline glue while the measure, indentation and authored skips stay absolute. The class options `10pt`/`11pt`/`12pt` on `\documentclass[...]` set the default base size (and article `\baselineskip` of 12pt/13.6pt/14.5pt), and `\linespread{factor}` (or `\renewcommand{\baselinestretch}{factor}`) scales that baseline; a size command inside a paragraph overrides the class default and keeps its own glyph size in that run. Inline math inside a styled run keeps its math face while the surrounding text retains its style. The paragraph measure follows `\textwidth`/`\hsize` (or `\setlength{\textwidth}{...}`), and `\setlength` accepts the other supported layout lengths, including a `\parskip` with plus/minus glue; a counter declared with `\newcounter{name}` starts at zero and can be changed by `\setcounter`/`\addtocounter`, and a length declared with `\newlength{\name}` can be set by `\setlength{\name}{...}` and then used as the value of a later `\setlength{\parindent}{\name}`, and `\addtolength{\name}{...}` adds to such a length, so class code that stores its dimensions in named lengths takes effect. The `geometry` package's `margin`/`hmargin`/`vmargin`/`left`/`right`/`top`/`bottom`/`textwidth`/`textheight` options (or `\geometry{...}`) are applied to the page measure and height; other package code is not executed. Block environments `center`, `flushleft` and `flushright` set the paragraph alignment, and aligned short lines are centring/flushing within the full measure rather than at the natural line width. A leading `\noindent` starts its paragraph flush with the measure. Page numbers print centred below the text block, `\setcounter{page}` offsets the printed number, `\addtocounter{page}` shifts it (`\pagenumbering` resets it to 1), and `\pagenumbering{roman|Roman|alph|Alph|arabic}` changes their format and `\pagestyle{empty}` suppresses them on every page and `\thispagestyle{empty}` on the first page. `\hypersetup{pdftitle=...}` writes the PDF Info dictionary (title, author, subject and keywords, UTF-16BE for non-ASCII text), `\title`, `\author` and `\date` are captured from the preamble, `\today` expands to the current date, and `\maketitle` expands into a centered title block at the article class sizes (using today's date when `\date` is absent and none for `\date{}`). `\section`, `\subsection`, `\subsubsection`, `\paragraph` and `\subparagraph` advance five-level article counters, prefix their titles with the number, and paint bold at `\Large`/`\large`/`\normalsize` (the two deepest levels stay 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, and `\maketitle` joins multiple `\and` authors and turns `\thanks` notes into title footnotes. Section labels resolve `\ref`/`\eqref` to the heading number (standalone `\label` lines attach to the previous heading, unknown references print `??`), and `\pageref{label}` reports that heading's formatted page number after a probe layout, `\appendix` restarts sectioning with letter numbers, `\tableofcontents` lists the numbered headings through `\subsubsection` with theirLine truncated
|
||||
Route-D text faces follow the NFSS declarations and compose with the surrounding run: `\sffamily\bfseries` selects cmssbx10, `\sffamily\itshape` selects cmssi10, and bold italic sans substitutes cmssbx10 because Computer Modern has no sans bold italic. `\scshape`/`\textsc` select the real cmcsc10 small-caps face, `\slshape`/`\textsl` use cmsl10 (or cmbxsl10 when bold) rather than the italic cmti10, and `\ttfamily\itshape` reaches cmitt10. All twelve text programs (cmr10, cmbx10, cmti10, cmbxti10, cmtt10, cmss10, cmssbx10, cmssi10, cmcsc10, cmsl10, cmbxsl10, cmitt10) are embedded as Type1 outlines. Characters outside a program's encoding fall back per glyph to a Liberation subset, so the ASCII letters of an accented word still use Computer Modern and Greek text keeps its Unicode text under PDF extraction, including capital Omega, because the embedded Type1 faces carry a ToUnicode CMap built from the requested characters rather than relying on glyph names. Accent commands such as `\'`, `` \` ``, `\"`, `\^`, `\~`, `\c`, `\v` and `\=` compose precomposed Unicode letters and fall back to the base letter plus a combining mark. `\textsuperscript` and `\textsubscript` set a 70% run raised or lowered by 0.4em. `\MakeUppercase` and `\MakeLowercase` (also `\uppercase`/`\lowercase`) transform their braced text while keeping the surrounding face. Because Computer Modern has no bold small caps, a bold small-caps request falls back to cmbx10. Section-wide declarations such as `\bfseries` apply from where they appear to the end of their group, and `\em` toggles emphasis relative to the surrounding face. Paragraph base sizes come from `\fontsize{<size>}{<baselineskip>}` and the article size commands (`\tiny` through `\Huge`), scaling glyph metrics and the default interline glue while the measure, indentation and authored skips stay absolute. The class options `10pt`/`11pt`/`12pt` on `\documentclass[...]` set the default base size (and article `\baselineskip` of 12pt/13.6pt/14.5pt), and `\linespread{factor}` (or `\renewcommand{\baselinestretch}{factor}`) scales that baseline; a size command inside a paragraph overrides the class default and keeps its own glyph size in that run. Inline math inside a styled run keeps its math face while the surrounding text retains its style. The paragraph measure follows `\textwidth`/`\hsize` (or `\setlength{\textwidth}{...}`), and `\setlength` accepts the other supported layout lengths, including a `\parskip` with plus/minus glue; a counter declared with `\newcounter{name}` starts at zero and can be changed by `\setcounter`/`\addtocounter`, and a length declared with `\newlength{\name}` can be set by `\setlength{\name}{...}` and then used as the value of a later `\setlength{\parindent}{\name}`, and `\addtolength{\name}{...}` adds to such a length, so class code that stores its dimensions in named lengths takes effect. The `geometry` package's `margin`/`hmargin`/`vmargin`/`left`/`right`/`top`/`bottom`/`textwidth`/`textheight` options (or `\geometry{...}`) are applied to the page measure and height; other package code is not executed. Block environments `center`, `flushleft` and `flushright` set the paragraph alignment, and aligned short lines are centring/flushing within the full measure rather than at the natural line width. A leading `\noindent` starts its paragraph flush with the measure. Page numbers print centred below the text block, `\setcounter{page}` offsets the printed number, `\addtocounter{page}` shifts it (`\pagenumbering` resets it to 1), and `\pagenumbering{roman|Roman|alph|Alph|arabic}` changes their format and `\pagestyle{empty}` suppresses them on every page and `\thispagestyle{empty}` on the first page. `\hypersetup{pdftitle=...}` writes the PDF Info dictionary (title, author, subject and keywords, UTF-16BE for non-ASCII text), each numbered heading becomes a flat PDF bookmark pointing at its page, `\title`, `\author` and `\date` are captured from the preamble, `\today` expands to the current date, and `\maketitle` expands into a centered title block at the article class sizes (using today's date when `\date` is absent and none for `\date{}`). `\section`, `\subsection`, `\subsubsection`, `\paragraph` and `\subparagraph` advance five-level article counters, prefix their titles with the number, and paint bold at `\Large`/`\large`/`\normalsize` (the two deepest levels stay 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, and `\maketitle` joins multiple `\and` authors and turns `\thanks` notes into title footnotes. Section labels resolve `\ref`/`\eqref` to the heading number (standalone `\label` lines attach to the previous heading, unknown references print `??`), and `\pageref{label}` reports that heading's formatted page number after a probe layout, `\appendix` restarts sectioning with letter numbers, `\tableofcLine truncated
|
||||
|
||||
Inline `$...$` and `\(...\)` math is laid out inside 10pt paragraphs (larger sizes keep the delimiters literal). `\newcommand`/`\renewcommand` definitions are captured from the preamble and expanded textually, including numbered arguments and one `[default]` optional first argument; TeX's `\def` parameter texts and `\let` aliases are executed the same way, and `\newenvironment` definitions wrap their bodies with the declared begin/end material. `\newif` flags select between `\if...\else...\fi` branches, with assignments honoured in the preamble or the body, so class conditionals like `\ifdraft` work.
|
||||
|
||||
|
||||
@@ -627,6 +627,14 @@ pub struct PdfMetadata {
|
||||
pub author: Option<String>,
|
||||
pub subject: Option<String>,
|
||||
pub keywords: Option<String>,
|
||||
pub outline: Vec<PdfOutlineEntry>,
|
||||
}
|
||||
|
||||
/// One flat bookmark pointing at a page of the exported document.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct PdfOutlineEntry {
|
||||
pub title: String,
|
||||
pub page: usize,
|
||||
}
|
||||
|
||||
fn pdf_text(value: &str) -> String {
|
||||
@@ -919,6 +927,7 @@ fn write_pdf(
|
||||
}
|
||||
|
||||
let mut kids = Vec::new();
|
||||
let mut page_ids: Vec<usize> = Vec::new();
|
||||
for list in pages {
|
||||
let mut used = BTreeMap::new();
|
||||
for item in &list.items {
|
||||
@@ -983,6 +992,7 @@ fn write_pdf(
|
||||
.join(" ");
|
||||
format!(" /Annots [{refs}]")
|
||||
};
|
||||
page_ids.push(page_id);
|
||||
kids.push(format!("{page_id} 0 R"));
|
||||
objects.push(
|
||||
format!(
|
||||
@@ -1051,6 +1061,47 @@ fn write_pdf(
|
||||
)
|
||||
.into_bytes();
|
||||
|
||||
if !metadata.outline.is_empty() {
|
||||
let root_id = objects.len() + 1;
|
||||
objects.push(Vec::new());
|
||||
let item_ids: Vec<usize> = (0..metadata.outline.len())
|
||||
.map(|_| {
|
||||
objects.push(Vec::new());
|
||||
objects.len()
|
||||
})
|
||||
.collect();
|
||||
for (index, entry) in metadata.outline.iter().enumerate() {
|
||||
let page_id = page_ids
|
||||
.get(entry.page)
|
||||
.or_else(|| page_ids.last())
|
||||
.copied()
|
||||
.unwrap_or(0);
|
||||
let mut dict = format!(
|
||||
"<< /Title {} /Parent {} 0 R /Dest [{} 0 R /Fit]",
|
||||
pdf_text(&entry.title),
|
||||
root_id,
|
||||
page_id
|
||||
);
|
||||
if index > 0 {
|
||||
dict.push_str(&format!(" /Prev {} 0 R", item_ids[index - 1]));
|
||||
}
|
||||
if index + 1 < item_ids.len() {
|
||||
dict.push_str(&format!(" /Next {} 0 R", item_ids[index + 1]));
|
||||
}
|
||||
dict.push_str(" >>");
|
||||
objects[item_ids[index] - 1] = dict.into_bytes();
|
||||
}
|
||||
objects[root_id - 1] = format!(
|
||||
"<< /Type /Outlines /First {} 0 R /Last {} 0 R /Count {} >>",
|
||||
item_ids[0],
|
||||
item_ids[item_ids.len() - 1],
|
||||
item_ids.len()
|
||||
)
|
||||
.into_bytes();
|
||||
objects[0] =
|
||||
format!("<< /Type /Catalog /Pages 2 0 R /Outlines {root_id} 0 R >>").into_bytes();
|
||||
}
|
||||
|
||||
let info_ref = match metadata_object(metadata) {
|
||||
Some(object) => {
|
||||
objects.push(object.into_bytes());
|
||||
@@ -1152,6 +1203,52 @@ mod type1_pdf_tests {
|
||||
|
||||
#[test]
|
||||
#[test]
|
||||
#[test]
|
||||
fn outline_entries_become_pdf_bookmarks() {
|
||||
let pages = vec![
|
||||
DisplayList {
|
||||
width: 612 * 65536,
|
||||
height: 792 * 65536,
|
||||
items: Vec::new(),
|
||||
images: Vec::new(),
|
||||
},
|
||||
DisplayList {
|
||||
width: 612 * 65536,
|
||||
height: 792 * 65536,
|
||||
items: Vec::new(),
|
||||
images: Vec::new(),
|
||||
},
|
||||
];
|
||||
let metadata = PdfMetadata {
|
||||
title: Some("Book".into()),
|
||||
outline: vec![
|
||||
PdfOutlineEntry {
|
||||
title: "1 One".into(),
|
||||
page: 0,
|
||||
},
|
||||
PdfOutlineEntry {
|
||||
title: "2 Two".into(),
|
||||
page: 1,
|
||||
},
|
||||
],
|
||||
..PdfMetadata::default()
|
||||
};
|
||||
let pdf = String::from_utf8_lossy(&display_lists_to_pdf_with_cm_type1_and_metadata(
|
||||
&pages,
|
||||
612 * 65536,
|
||||
792 * 65536,
|
||||
PageOrigin::default(),
|
||||
&metadata,
|
||||
))
|
||||
.to_string();
|
||||
assert!(pdf.contains("/Type /Outlines"));
|
||||
assert!(pdf.contains("/Title (1 One)"));
|
||||
assert!(pdf.contains("/Title (2 Two)"));
|
||||
assert!(pdf.contains("/Count 2"));
|
||||
assert!(pdf.contains("/Dest ["));
|
||||
assert!(pdf.contains("/Outlines"));
|
||||
}
|
||||
|
||||
fn metadata_writes_the_pdf_info_dictionary() {
|
||||
let pages = vec![DisplayList {
|
||||
width: 612 * 65536,
|
||||
@@ -1164,6 +1261,7 @@ mod type1_pdf_tests {
|
||||
author: Some("Ada".into()),
|
||||
subject: None,
|
||||
keywords: None,
|
||||
outline: Vec::new(),
|
||||
};
|
||||
let pdf = String::from_utf8_lossy(&display_lists_to_pdf_with_cm_type1_and_metadata(
|
||||
&pages,
|
||||
|
||||
@@ -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`). 825 workspace tests are green and no oracle
|
||||
PDF opt-in with `?engine=route-d`). 827 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.
|
||||
|
||||
+3
-3
@@ -133,7 +133,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`/`\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, `\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, `\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`), `\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, `\maketitle` joins `\and` authors and turns `\thanks` notes into title footnotes, and `\label` inside a heading (or on its own line after it) resolves `\ref`/`\eqref` to the section number while unknown references print `??`, and `\pageref{label}` reports the formatted page number of that heading 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 `\textdegree`/`\textmu`/`\textonehalf`/`\texteuro` expand to their characters, and a control word swallows the spaces that follow it, `\href{url}{text}` keeps its text, and `\url{...}` becomes typewriter text; `\footnote{...}` becomes a numbered 9pt page insertion on the page that mentions it; a `thebibliography` environment is removed from the body, its `\bibitem` entries become numbered `[n]` paragraphs, and `\cite{...}` resolves to `[n]`/`[n, m]` (unknown keys print `[?]`, an optional note like `\cite[p.~3]{...}` is dropped, `\citep`/`\citet` behave like `\cite`, `\nocite` is ignored, and `\bibliography`/`\bibliographystyle` lines are consumed without running BibTeX); a `figure` environment becomes a float at its `[t]`/`[b]`/`[h]` placement, its `\caption` numbers as `Figure n:` and resolves `\ref`, and `\includegraphics` embeds the referenced project image (PNG/JPEG/BMP are decoded into a PDF XObject, with a rule placeholder when the file is missing or cannot be decoded), and a standalone `\includegraphics` paragraph becomes an in-text graphic float, while a standalone `\rule{width}{height}` becomes an in-text rule box, with `width=`/`height=` taking dimensions or fractions of `\textwidth`/`\textheight`, `scale=` a percentage of the natural size, `keepaspectratio` shrinking both dimensions to fit, and `\graphicspath` directories searched with common image extensions when the path has no suffix; `longtable` environments are captured through the same tabular path (including their `\endfirsthead`/`\endhead` Line truncated
|
||||
| M6 | class/package execution (`article`, `sn-jnl`) | **partial**: a leading `\noindent` starts a paragraph flush with the measure, `\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, `\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 flat PDF bookmark in `/Outlines` 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, `\maketitle` joins `\and` authors and turns `\thanks` notes into title footnotes, and `\label` inside a heading (or on its own line after it) resolves `\ref`/`\eqref` to the section number while unknown references print `??`, and `\pageref{label}` reports the formatted page number of that heading 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 `\textdegree`/`\textmu`/`\textonehalf`/`\texteuro` expand to their characters, and a control word swallows the spaces that follow it, `\href{url}{text}` keeps its text, and `\url{...}` becomes typewriter text; `\footnote{...}` becomes a numbered 9pt page insertion on the page that mentions it; a `thebibliography` environment is removed from the body, its `\bibitem` entries become numbered `[n]` paragraphs, and `\cite{...}` resolves to `[n]`/`[n, m]` (unknown keys print `[?]`, an optional note like `\cite[p.~3]{...}` is dropped, `\citep`/`\citet` behave like `\cite`, `\nocite` is ignored, and `\bibliography`/`\bibliographystyle` lines are consumed without running BibTeX); a `figure` environment becomes a float at its `[t]`/`[b]`/`[h]` placement, its `\caption` numbers as `Figure n:` and resolves `\ref`, and `\includegraphics` embeds the referenced project image (PNG/JPEG/BMP are decoded into a PDF XObject, with a rule placeholder when the file is missing or cannot be decoded), and a standalone `\includegraphics` paragraph becomes an in-text graphic float, while a standalone `\rule{width}{height}` becomes an in-text rule box, with `width=`/`height=` taking dimensions or fractions of `\textwidth`/`\textheight`, `scale=` a percentage of the natural size, `keepaspectratio` shrinking both dimensions to fit, and `\graphicspath` directories searched with common image extensions when the path has no suffix; `longtable` environments Line truncated
|
||||
| M7 | `\special`, PDF XObjects, hyperref annotations | PDF structure parity |
|
||||
|
||||
## Current limits
|
||||
@@ -367,7 +367,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 423 unit tests plus ten route-D integration tests and thirty-eight oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 825 tests (423 route-D unit, 218 engine binary unit, 10 route-D integration, 38 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 424 unit tests plus ten route-D integration tests and thirty-eight oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 827 tests (424 route-D unit, 219 engine binary unit, 10 route-D integration, 38 oracle, 71 v1 integration, 60 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path.
|
||||
|
||||
### M0 incremental demo
|
||||
|
||||
@@ -415,7 +415,7 @@ Residual approximations, documented rather than special-cased:
|
||||
|
||||
The `M3`-`M7` stage of the roadmap is implemented to the extent recorded below.
|
||||
The goal ran for 90 rounds and landed 123 commits (`8c42f2d..c9a074b`); the
|
||||
workspace suite is at 825 tests.
|
||||
workspace suite is at 827 tests.
|
||||
|
||||
| Milestone | Evidence |
|
||||
| --- | --- |
|
||||
|
||||
+43
-4
@@ -13,7 +13,7 @@ use texrra_tex_core::cmr10::Cmr10Metrics;
|
||||
use texrra_tex_core::math::{AlignedRow, MathAtom, parse_math, split_math_lines};
|
||||
use texrra_tex_core::paragraph::HorizontalItem;
|
||||
use texrra_tex_core::pdf::{
|
||||
PageOrigin, PdfMetadata, display_lists_to_pdf_with_cm_type1_and_metadata,
|
||||
PageOrigin, PdfMetadata, PdfOutlineEntry, display_lists_to_pdf_with_cm_type1_and_metadata,
|
||||
};
|
||||
pub use texrra_tex_core::render::RasterImage;
|
||||
use texrra_tex_core::render::{DisplayItem, DisplayList, FontFace};
|
||||
@@ -2056,7 +2056,8 @@ fn page_refs_for(body: &str, geometry: &PageGeometry) -> HashMap<String, String>
|
||||
Err(_) => return pages,
|
||||
};
|
||||
let mut label_units = HashMap::new();
|
||||
let mut document = build_document_with_labels(¶graphs, geometry, &mut label_units);
|
||||
let mut document =
|
||||
build_document_with_labels(¶graphs, geometry, &mut label_units, &mut Vec::new());
|
||||
apply_geometry(&mut document, geometry);
|
||||
let engine = layout_document(&document);
|
||||
let mut unit_page = HashMap::new();
|
||||
@@ -2143,9 +2144,30 @@ pub fn pdf_bytes_with_images(
|
||||
geometry_counter(&geometry, "equation"),
|
||||
&geometry,
|
||||
)?;
|
||||
let mut document = build_document(¶graphs, &geometry);
|
||||
let mut outline_units = Vec::new();
|
||||
let mut document = build_document_with_labels(
|
||||
¶graphs,
|
||||
&geometry,
|
||||
&mut HashMap::new(),
|
||||
&mut outline_units,
|
||||
);
|
||||
apply_geometry(&mut document, &geometry);
|
||||
let engine = layout_document(&document);
|
||||
let mut page_of: HashMap<u64, usize> = HashMap::new();
|
||||
for (index, page) in engine.pages().iter().enumerate() {
|
||||
for (unit, _) in &page.sources {
|
||||
page_of.entry(*unit).or_insert(index);
|
||||
}
|
||||
}
|
||||
let outline: Vec<PdfOutlineEntry> = outline_units
|
||||
.iter()
|
||||
.filter_map(|(title, unit)| {
|
||||
page_of.get(unit).map(|page| PdfOutlineEntry {
|
||||
title: title.clone(),
|
||||
page: *page,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let mut pages: Vec<_> = engine
|
||||
.pages()
|
||||
.iter()
|
||||
@@ -2180,6 +2202,7 @@ pub fn pdf_bytes_with_images(
|
||||
.or_else(|| geometry.author.clone()),
|
||||
subject: geometry.pdf_subject.clone(),
|
||||
keywords: geometry.pdf_keywords.clone(),
|
||||
outline,
|
||||
};
|
||||
Ok(display_lists_to_pdf_with_cm_type1_and_metadata(
|
||||
&pages,
|
||||
@@ -6042,13 +6065,14 @@ fn expand_float_lists(
|
||||
}
|
||||
|
||||
fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Document {
|
||||
build_document_with_labels(paragraphs, geometry, &mut HashMap::new())
|
||||
build_document_with_labels(paragraphs, geometry, &mut HashMap::new(), &mut Vec::new())
|
||||
}
|
||||
|
||||
fn build_document_with_labels(
|
||||
paragraphs: &[SourceParagraph],
|
||||
geometry: &PageGeometry,
|
||||
label_units: &mut HashMap<String, u64>,
|
||||
outline_units: &mut Vec<(String, u64)>,
|
||||
) -> Document {
|
||||
let mut paragraphs = expand_maketitle(paragraphs, geometry);
|
||||
if let Some(name) = geometry.abstract_name.as_deref() {
|
||||
@@ -6498,6 +6522,11 @@ fn build_document_with_labels(
|
||||
label_units.insert(label.clone(), *unit);
|
||||
}
|
||||
}
|
||||
for (index, paragraph) in paragraphs.iter().enumerate() {
|
||||
if paragraph.heading_level.is_some() && paragraph.heading_number.is_some() {
|
||||
outline_units.push((paragraph.text.clone(), unit_for_paragraph[index] as u64));
|
||||
}
|
||||
}
|
||||
let mut document = Document::new(700 * SCALE, units);
|
||||
if footnote_count > 0 {
|
||||
document.insertion_classes.push(InsertionClass {
|
||||
@@ -7596,6 +7625,16 @@ a & b
|
||||
|
||||
#[test]
|
||||
#[test]
|
||||
#[test]
|
||||
fn headings_become_pdf_bookmarks() {
|
||||
let pdf = pdf_bytes("\\section{One}\n\nFirst.\n\n\\newpage\n\n\\section{Two}\n\nSecond.")
|
||||
.expect("pdf");
|
||||
let text = String::from_utf8_lossy(&pdf);
|
||||
assert!(text.contains("/Type /Outlines"));
|
||||
assert!(text.contains("/Title (1 One)"));
|
||||
assert!(text.contains("/Title (2 Two)"));
|
||||
}
|
||||
|
||||
fn hypersetup_writes_the_pdf_info_dictionary() {
|
||||
let pdf =
|
||||
pdf_bytes("\\hypersetup{pdftitle={My Title},pdfauthor={Ada}}\n\nBody.").expect("pdf");
|
||||
|
||||
Reference in new issue
Block a user