Add float placement and page headers/footers

This commit is contained in:
gloamxun committed 2026-10-19 13:41:29 +08:00
1 parent 1da46c61d6
commit ed1da06685
16 files changed
+953 -69

No files matched your search

Generated
+1
View File
@@ -950,6 +950,7 @@ dependencies = [
"genpdf", "genpdf",
"hyphenate", "hyphenate",
"image", "image",
"printpdf",
"rmp-serde", "rmp-serde",
"rusttype", "rusttype",
"serde", "serde",
+1
View File
@@ -18,6 +18,7 @@ texrra-core = { path = "crates/texrra-core", features = ["serde"] }
flate2 = "1.1" flate2 = "1.1"
hyphenate = { path = "vendor/hyphenate" } hyphenate = { path = "vendor/hyphenate" }
genpdf = { version = "0.2.0", features = ["images"] } genpdf = { version = "0.2.0", features = ["images"] }
printpdf = "0.3.4"
image = { version = "0.23.12", default-features = false, features = ["png", "jpeg", "bmp"] } image = { version = "0.23.12", default-features = false, features = ["png", "jpeg", "bmp"] }
common = { git = "https://github.com/jamespfennell/texcraft", rev = "c1dbf5dfe3a480daf73972c394ac8231e0c6ebd0", features = ["serde"] } common = { git = "https://github.com/jamespfennell/texcraft", rev = "c1dbf5dfe3a480daf73972c394ac8231e0c6ebd0", features = ["serde"] }
boxworks = { git = "https://github.com/jamespfennell/texcraft", rev = "c1dbf5dfe3a480daf73972c394ac8231e0c6ebd0" } boxworks = { git = "https://github.com/jamespfennell/texcraft", rev = "c1dbf5dfe3a480daf73972c394ac8231e0c6ebd0" }
+12 -4
View File
@@ -165,13 +165,21 @@ options/`\geometry{...}` settings, including `paperwidth`, `paperheight`,
`textheight` sizes it below the current top margin. The chosen page size drives `textheight` sizes it below the current top margin. The chosen page size drives
the PDF pages, the positioned layout, and the SVG preview. the PDF pages, the positioned layout, and the SVG preview.
Page styles are painted in both the PDF and the SVG preview:
`\pagestyle{empty|plain|fancy}` sets the document default,
`\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
`plain` (a centered page number).
The following packages are accepted as built-ins: `geometry`, `graphicx`, The following packages are accepted as built-ins: `geometry`, `graphicx`,
`amsmath`, `amssymb`, `amsfonts`, `booktabs`, `hyperref`, `cite`, `natbib`, `amsmath`, `amssymb`, `amsfonts`, `booktabs`, `hyperref`, `cite`, `natbib`,
`inputenc`, `fontenc`, `url`, `nicefrac`, `microtype`, `cleveref`, `lipsum`, `inputenc`, `fontenc`, `url`, `nicefrac`, `microtype`, `cleveref`, `lipsum`,
`doi`, `authblk`, and `fancyhdr`. Their commands are approximated where they `doi`, `authblk`, and `fancyhdr`. Their commands are approximated where they
affect text (`\url` becomes breakable monospace, `\nicefrac`, `\cref`, affect text (`\url` becomes breakable monospace, `\nicefrac`, `\cref`,
`\doi`, `\lipsum`, `\verb`), and are no-ops where they only affect the PDF `\doi`, `\lipsum`, `\verb`); `\hypersetup` and `\microtypesetup` remain
back end (`\hypersetup`, `\fancyhf`, `\microtypesetup`). PDF-backend no-ops, while fancyhdr's page decorations are painted natively.
Figure and table captions are numbered (`Figure 1: ...`, `Table 1: ...`), and Figure and table captions are numbered (`Figure 1: ...`, `Table 1: ...`), and
`\ref` to a figure/table label resolves to that number. Display math that is `\ref` to a figure/table label resolves to that number. Display math that is
@@ -464,8 +472,8 @@ advisory breaks, starred `\vspace`/`\hspace`, `center`, `\hrule`, `\fbox`,
| Boxes | `\rule`, inline framed `\fbox`, block `\parbox`/`\minipage`, `\vbox`/`\vtop` (as full-width block), inline `\mbox`/`\makebox`, `\raisebox`, `center`, `\hrule` | true nested VBox material | | Boxes | `\rule`, inline framed `\fbox`, block `\parbox`/`\minipage`, `\vbox`/`\vtop` (as full-width block), inline `\mbox`/`\makebox`, `\raisebox`, `center`, `\hrule` | true nested VBox material |
| Fonts | serif/sans/mono faces, bold/italic/mono/sans declarations, group scoping, true scaled small caps | — | | Fonts | serif/sans/mono faces, bold/italic/mono/sans declarations, group scoping, true scaled small caps | — |
| Paragraphs | Knuth-Plass breaking, TeX hyphenation, justification, centering, `\parindent` (17pt default), `\hfill`/`\hfil` | `\raggedright`/`\raggedleft` | | Paragraphs | Knuth-Plass breaking, TeX hyphenation, justification, centering, `\parindent` (17pt default), `\hfill`/`\hfil` | `\raggedright`/`\raggedleft` |
| Notes/floats | footnotes with page-bottom insertion area, title/author `\thanks` | figure/table floats | | Notes/floats | footnotes with page-bottom insertion area, title/author `\thanks`, figure/table `[htbp]` placement (top/bottom/page/here approximations) | deferred float queue, `\textfraction` |
| Pages | A4/Letter/... page sizes, margins/geometry, automatic pagination, `\newpage`, `\pagebreak` | headers/footers (`fancyhdr`), unified planner/renderer | | Pages | A4/Letter/... page sizes, margins/geometry, automatic pagination, `\newpage`, `\pagebreak`, plain/fancy page styles, `\thispagestyle`, fancyhdr L/C/R headers and footers | unified planner/renderer |
| Classes/packages | built-in + local classes, option protocol, local package options | base font-size options (10/11/12pt) | | Classes/packages | built-in + local classes, option protocol, local package options | base font-size options (10/11/12pt) |
| Live preview | incremental paragraph/page caches, page-hash diffing, SVG refresh | — | | Live preview | incremental paragraph/page caches, page-hash diffing, SVG refresh | — |
+77
View File
@@ -75,6 +75,8 @@ pub struct DocumentModel {
pub labels: HashMap<String, String>, pub labels: HashMap<String, String>,
pub citations: HashMap<String, usize>, pub citations: HashMap<String, usize>,
pub footnotes: Vec<Footnote>, pub footnotes: Vec<Footnote>,
pub page_style: PageStyle,
pub page_style_overrides: Vec<PageStyleOverride>,
} }
impl Default for DocumentModel { impl Default for DocumentModel {
@@ -93,10 +95,81 @@ impl Default for DocumentModel {
labels: HashMap::new(), labels: HashMap::new(),
citations: HashMap::new(), citations: HashMap::new(),
footnotes: Vec::new(), footnotes: Vec::new(),
page_style: PageStyle::default(),
page_style_overrides: Vec::new(),
} }
} }
} }
/// Page style selected by `\pagestyle`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum PageStyleKind {
Empty,
/// LaTeX's default: a centered page number in the footer.
#[default]
Plain,
/// fancyhdr-style header/footer declared with `\fancyhead`/`\fancyfoot`.
Fancy,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum PageDecorationPosition {
#[default]
Center,
Left,
Right,
}
/// Header or footer runs for one edge of the page.
#[derive(Clone, Default, PartialEq, Eq, Hash)]
pub struct PageDecoration {
pub left: Vec<Run>,
pub center: Vec<Run>,
pub right: Vec<Run>,
}
impl PageDecoration {
pub fn slot_mut(&mut self, position: PageDecorationPosition) -> &mut Vec<Run> {
match position {
PageDecorationPosition::Left => &mut self.left,
PageDecorationPosition::Center => &mut self.center,
PageDecorationPosition::Right => &mut self.right,
}
}
pub fn is_empty(&self) -> bool {
self.left.is_empty() && self.center.is_empty() && self.right.is_empty()
}
pub fn clear(&mut self) {
self.left.clear();
self.center.clear();
self.right.clear();
}
}
#[derive(Clone, Default, PartialEq, Eq, Hash)]
pub struct PageStyle {
pub kind: PageStyleKind,
pub header: PageDecoration,
pub footer: PageDecoration,
}
/// A `\thispagestyle` override, anchored at the block it was issued before.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct PageStyleOverride {
pub anchor: usize,
pub kind: PageStyleKind,
}
/// Marker character used by `\thepage` inside header/footer runs; the page
/// renderer substitutes the concrete page number before measuring and painting.
pub const PAGE_NUMBER_MARKER: char = '\u{F5000}';
pub fn page_number_marker_text() -> String {
PAGE_NUMBER_MARKER.to_string()
}
pub struct ParsedDocument(pub DocumentModel); pub struct ParsedDocument(pub DocumentModel);
#[derive(Clone)] #[derive(Clone)]
@@ -137,11 +210,15 @@ pub enum Block {
caption: Option<Vec<Run>>, caption: Option<Vec<Run>>,
alignments: Vec<ColumnAlignment>, alignments: Vec<ColumnAlignment>,
rules: Vec<usize>, rules: Vec<usize>,
/// Float placement hints from `[htbp]`.
placement: String,
}, },
Image { Image {
path: String, path: String,
options: String, options: String,
caption: Option<Vec<Run>>, caption: Option<Vec<Run>>,
/// Float placement hints from `[htbp]`.
placement: String,
}, },
Bibliography(Vec<(String, Vec<Run>)>), Bibliography(Vec<(String, Vec<Run>)>),
/// A box such as `\fbox{...}` (framed) or `\parbox{width}{...}`. /// A box such as `\fbox{...}` (framed) or `\parbox{width}{...}`.
+147 -10
View File
@@ -4,8 +4,8 @@ use crate::{
TeXGlue, TeXGlue,
document::{ document::{
Block, ColumnAlignment, DocumentModel, EquationNumber, InlineBox, InlineBoxAlign, Block, ColumnAlignment, DocumentModel, EquationNumber, InlineBox, InlineBoxAlign,
ListBlock, ListItem, PageMargins, PageSize, ParsedDocument, RuleBox, Run, ListBlock, ListItem, PageMargins, PageSize, PageStyleOverride, ParsedDocument, RuleBox,
UnresolvedReference, Run, UnresolvedReference,
}, },
expanded, expanded,
math_expr::*, math_expr::*,
@@ -300,7 +300,7 @@ fn consume_environment_preamble(
expanded: &expanded::ExpandedTokenStream, expanded: &expanded::ExpandedTokenStream,
start_index: usize, start_index: usize,
environment: &str, environment: &str,
) -> usize { ) -> (usize, Option<String>) {
use expanded::{ExpandedItemKind, ExpandedTokenValue, FrontendEventKind as Event}; use expanded::{ExpandedItemKind, ExpandedTokenValue, FrontendEventKind as Event};
let mut argument_start = start_index; let mut argument_start = start_index;
@@ -320,7 +320,7 @@ fn consume_environment_preamble(
let Some(ExpandedItemKind::Event(Event::GroupStart)) = let Some(ExpandedItemKind::Event(Event::GroupStart)) =
expanded.items.get(argument_start).map(|item| &item.kind) expanded.items.get(argument_start).map(|item| &item.kind)
else { else {
return start_index; return (start_index, None);
}; };
let mut depth = 0usize; let mut depth = 0usize;
for (index, item) in expanded.items.iter().enumerate().skip(argument_start) { for (index, item) in expanded.items.iter().enumerate().skip(argument_start) {
@@ -329,13 +329,13 @@ fn consume_environment_preamble(
ExpandedItemKind::Event(Event::GroupEnd) => { ExpandedItemKind::Event(Event::GroupEnd) => {
depth -= 1; depth -= 1;
if depth == 0 { if depth == 0 {
return index + 1; return (index + 1, None);
} }
} }
_ => {} _ => {}
} }
} }
return start_index; return (start_index, None);
} }
if !matches!(environment, "figure" | "table") if !matches!(environment, "figure" | "table")
@@ -348,11 +348,12 @@ fn consume_environment_preamble(
}) })
!= Some('[') != Some('[')
{ {
return start_index; return (start_index, None);
} }
let mut bracket_depth = 0usize; let mut bracket_depth = 0usize;
let mut group_depth = 0usize; let mut group_depth = 0usize;
let mut placement = String::new();
for (index, item) in expanded.items.iter().enumerate().skip(argument_start) { for (index, item) in expanded.items.iter().enumerate().skip(argument_start) {
match &item.kind { match &item.kind {
ExpandedItemKind::Event(Event::GroupStart) => group_depth += 1, ExpandedItemKind::Event(Event::GroupStart) => group_depth += 1,
@@ -364,15 +365,16 @@ fn consume_environment_preamble(
Some(']') => { Some(']') => {
bracket_depth = bracket_depth.saturating_sub(1); bracket_depth = bracket_depth.saturating_sub(1);
if bracket_depth == 0 { if bracket_depth == 0 {
return index + 1; return (index + 1, Some(placement));
} }
} }
Some(character) if bracket_depth == 1 => placement.push(character),
_ => {} _ => {}
}, },
_ => {} _ => {}
} }
} }
start_index (start_index, None)
} }
struct MinipageBuilder { struct MinipageBuilder {
@@ -422,6 +424,19 @@ struct Parser {
minipage: Option<MinipageBuilder>, minipage: Option<MinipageBuilder>,
footnote_capture: Option<Vec<Run>>, footnote_capture: Option<Vec<Run>>,
footnote_counter: u32, footnote_counter: u32,
page_decoration_capture: Option<(
bool,
crate::document::PageDecorationPosition,
Vec<Run>,
usize,
bool,
bool,
bool,
bool,
bool,
)>,
float_placement: String,
table_placement: String,
centered: Option<Vec<Run>>, centered: Option<Vec<Run>>,
current_source: Option<SourceLocation>, current_source: Option<SourceLocation>,
paragraph_source: Option<SourceLocation>, paragraph_source: Option<SourceLocation>,
@@ -465,6 +480,9 @@ impl Parser {
minipage: None, minipage: None,
footnote_capture: None, footnote_capture: None,
footnote_counter: 0, footnote_counter: 0,
page_decoration_capture: None,
float_placement: String::new(),
table_placement: String::new(),
centered: None, centered: None,
current_source: None, current_source: None,
paragraph_source: None, paragraph_source: None,
@@ -553,8 +571,16 @@ impl Parser {
name: environment, .. name: environment, ..
} = kind } = kind
{ {
item_index = let (next_index, placement) =
consume_environment_preamble(expanded, item_index, environment); consume_environment_preamble(expanded, item_index, environment);
item_index = next_index;
if let Some(placement) = placement {
match environment.as_str() {
"figure" => self.float_placement = placement,
"table" => self.table_placement = placement,
_ => {}
}
}
} }
if paragraph_break { if paragraph_break {
@@ -835,6 +861,83 @@ impl Parser {
self.begin_style(*style); self.begin_style(*style);
self.style_declarations.push((self.group_depth, *style)); self.style_declarations.push((self.group_depth, *style));
} }
expanded::FrontendEventKind::PageStyle(kind) => {
self.document.page_style.kind = *kind;
}
expanded::FrontendEventKind::ThisPageStyle(kind) => {
self.document.page_style_overrides.push(PageStyleOverride {
anchor: self.document.blocks.len(),
kind: *kind,
});
}
expanded::FrontendEventKind::PageDecorationStart { header, position } => {
self.page_decoration_capture = Some((
*header,
*position,
Vec::new(),
self.group_depth,
self.bold,
self.italic,
self.monospace,
self.sans,
self.small_caps,
));
self.group_depth += 1;
}
expanded::FrontendEventKind::PageDecorationEnd => {
if let Some((
header,
position,
mut runs,
depth,
bold,
italic,
monospace,
sans,
small_caps,
)) = self.page_decoration_capture.take()
{
while self
.style_declarations
.last()
.is_some_and(|(declaration_depth, _)| *declaration_depth > depth)
{
if let Some((_, style)) = self.style_declarations.pop() {
self.end_style(style);
}
}
self.group_depth = depth;
self.bold = bold;
self.italic = italic;
self.monospace = monospace;
self.sans = sans;
self.small_caps = small_caps;
trim_run_end(&mut runs);
let decoration = if header {
&mut self.document.page_style.header
} else {
&mut self.document.page_style.footer
};
*decoration.slot_mut(position) = runs;
}
}
expanded::FrontendEventKind::PageDecorationClear { header } => {
let decoration = if *header {
&mut self.document.page_style.header
} else {
&mut self.document.page_style.footer
};
decoration.clear();
}
expanded::FrontendEventKind::PageNumber => {
let mut run = Run::plain(crate::document::page_number_marker_text());
run.bold = self.bold;
run.italic = self.italic;
run.monospace = self.monospace;
run.sans = self.sans;
run.small_caps = self.small_caps;
self.target_runs().push(run);
}
expanded::FrontendEventKind::GroupStart => self.group_depth += 1, expanded::FrontendEventKind::GroupStart => self.group_depth += 1,
expanded::FrontendEventKind::GroupEnd => { expanded::FrontendEventKind::GroupEnd => {
let depth = self.group_depth; let depth = self.group_depth;
@@ -1342,6 +1445,13 @@ impl Parser {
} }
fn target_runs(&mut self) -> &mut Vec<Run> { fn target_runs(&mut self) -> &mut Vec<Run> {
if self.page_decoration_capture.is_some() {
return &mut self
.page_decoration_capture
.as_mut()
.expect("page decoration capture was checked")
.2;
}
if self.footnote_capture.is_some() { if self.footnote_capture.is_some() {
return self return self
.footnote_capture .footnote_capture
@@ -1357,6 +1467,7 @@ impl Parser {
&& self.centered.is_none() && self.centered.is_none()
&& self.framed_box.is_none() && self.framed_box.is_none()
&& self.metadata_capture.is_none() && self.metadata_capture.is_none()
&& self.page_decoration_capture.is_none()
&& self.caption_capture.is_none() && self.caption_capture.is_none()
&& self.heading.is_none() && self.heading.is_none()
&& self.table.is_none() && self.table.is_none()
@@ -1546,6 +1657,7 @@ impl Parser {
(false, "tabular") => self.finish_table(), (false, "tabular") => self.finish_table(),
(true, "figure") => { (true, "figure") => {
self.flush_paragraph(); self.flush_paragraph();
self.float_placement = String::new();
self.figure_active = true; self.figure_active = true;
self.figure_image = None; self.figure_image = None;
self.figure_number += 1; self.figure_number += 1;
@@ -1553,11 +1665,18 @@ impl Parser {
} }
(false, "figure") => { (false, "figure") => {
self.flush_paragraph(); self.flush_paragraph();
if self.figure_active
&& !self.float_placement.is_empty()
&& self.float_placement.contains('p')
{
self.push_block(Block::PageBreak);
}
self.figure_active = false; self.figure_active = false;
self.figure_image = None; self.figure_image = None;
} }
(true, "table") => { (true, "table") => {
self.flush_paragraph(); self.flush_paragraph();
self.table_placement = String::new();
self.table_active = true; self.table_active = true;
self.current_table_block = None; self.current_table_block = None;
self.pending_table_caption = None; self.pending_table_caption = None;
@@ -1620,11 +1739,19 @@ impl Parser {
self.figure_number += 1; self.figure_number += 1;
} }
self.current_reference = self.figure_number.to_string(); self.current_reference = self.figure_number.to_string();
if self.figure_active
&& !self.float_placement.is_empty()
&& !self.float_placement.contains('h')
&& (self.float_placement.contains('t') || self.float_placement.contains('p'))
{
self.push_block(Block::PageBreak);
}
let index = self.document.blocks.len(); let index = self.document.blocks.len();
self.push_block(Block::Image { self.push_block(Block::Image {
path, path,
options, options,
caption: None, caption: None,
placement: self.float_placement.clone(),
}); });
if self.figure_active { if self.figure_active {
self.figure_image = Some(index); self.figure_image = Some(index);
@@ -1695,6 +1822,12 @@ impl Parser {
if let Some(table) = self.table.take() if let Some(table) = self.table.take()
&& !table.rows.is_empty() && !table.rows.is_empty()
{ {
if !self.table_placement.is_empty()
&& !self.table_placement.contains('h')
&& (self.table_placement.contains('t') || self.table_placement.contains('p'))
{
self.push_block(Block::PageBreak);
}
let index = self.document.blocks.len(); let index = self.document.blocks.len();
let caption = table.caption.or_else(|| self.pending_table_caption.take()); let caption = table.caption.or_else(|| self.pending_table_caption.take());
self.push_block(Block::Table { self.push_block(Block::Table {
@@ -1702,10 +1835,14 @@ impl Parser {
caption, caption,
alignments: table.alignments, alignments: table.alignments,
rules: table.rules, rules: table.rules,
placement: self.table_placement.clone(),
}); });
if self.table_active { if self.table_active {
self.current_table_block = Some(index); self.current_table_block = Some(index);
} }
if !self.table_placement.is_empty() && self.table_placement.contains('p') {
self.push_block(Block::PageBreak);
}
} }
} }
+11
View File
@@ -234,6 +234,17 @@ pub enum FrontendEventKind {
Reference(String), Reference(String),
Citation(String), Citation(String),
BibliographyItem(String), BibliographyItem(String),
PageStyle(crate::document::PageStyleKind),
ThisPageStyle(crate::document::PageStyleKind),
PageDecorationStart {
header: bool,
position: crate::document::PageDecorationPosition,
},
PageDecorationEnd,
PageDecorationClear {
header: bool,
},
PageNumber,
GroupStart, GroupStart,
GroupEnd, GroupEnd,
} }
+26 -18
View File
@@ -5,26 +5,34 @@ are still missing. Each item names the files/functions to touch.
Completed: paragraph indentation (`\parindent`) and `\hfill`/`\hfil`; sans Completed: paragraph indentation (`\parindent`) and `\hfill`/`\hfil`; sans
family and true scaled small caps; inline box geometry (`\fbox`, `\makebox`, family and true scaled small caps; inline box geometry (`\fbox`, `\makebox`,
`\raisebox`), `\minipage`, `\vbox`/`\vtop` block approximations, and `\raisebox`), `\minipage`, `\vbox`/`\vtop` block approximations;
footnotes/`\thanks` (see `docs/STATUS.md`). footnotes/`\thanks`; figure/table `[htbp]` placement approximations; and page
styles (plain/fancy, `\thispagestyle`, fancyhdr headers/footers, `\thepage`).
## 1. Floats ## 1. Unified pagination
- Classify figure/table blocks as floats with `[htbp]` placement hints.
- Planner: maintain pending floats and try top/bottom/page placements; keep
reading order for text and defer floats when they do not fit.
- Renderer: place deferred floats at the saved slots; page keys must include
float placement decisions.
## 2. Page styles / headers-footers
- `DocumentModel` fields for header/footer runs and `\pagestyle`/`\thispagestyle`.
- Paint headers/footers in the page margins in both PDF and SVG; page numbers
need a page index placeholder resolved at paint time.
## 3. Unified pagination
- Extract the current duplicated planner (`build_page_break_plan`) and renderer - Extract the current duplicated planner (`build_page_break_plan`) and renderer
(`build_positioned_pages`) vertical logic into one page builder returning an (`build_positioned_pages`) vertical logic into one page builder returning an
ordered list of placed items, then use it for both page-break decisions and ordered list of placed items, then use it for both page-break decisions and
final painting. final painting. This is the prerequisite for a true deferred float queue.
## 2. Lengths and base font size
- Emit geometry changes into named length registers so `\textwidth`,
`\textheight`, `\linewidth`, and `\columnwidth` track `\geometry` and
paper-size options instead of fixed A4 defaults.
- Thread the `10pt`/`11pt`/`12pt` class option through the parser, line metrics,
headings, and the PDF so the base size changes consistently.
## 3. Table of contents and lists
- Record section/figure/table entries while parsing, then generate
`\tableofcontents`, `\listoffigures`, and `\listoftables` blocks with
resolved page numbers after pagination.
## 4. PDF painting and title blocks
- Paint rules and frames as native PDF rectangles (`printpdf` operators)
instead of 1x1 image XObjects.
- Let a document-level `\renewcommand{\maketitle}` contribute a real title
block once the engine's title model can run box material.
+16 -8
View File
@@ -23,7 +23,12 @@ the source changes; the SVG preview is refreshed per page.
centering, first-line `\parindent` (17pt default, group-scoped, `\setlength`/ centering, first-line `\parindent` (17pt default, group-scoped, `\setlength`/
`\addtolength`/`\noindent` aware), and `\hfill`/`\hfil` infinite glue. `\addtolength`/`\noindent` aware), and `\hfill`/`\hfil` infinite glue.
- Pages: A4/A5/B5/Letter/Legal/Executive, landscape, geometry margins and - Pages: A4/A5/B5/Letter/Legal/Executive, landscape, geometry margins and
text block, automatic pagination, `\newpage`/`\pagebreak`. text block, automatic pagination, `\newpage`/`\pagebreak`; figures/tables
honor `[htbp]` hints with top/bottom/page/here approximations. Page styles:
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.
- Notes: `\footnote{...}` page-bottom insertion area with separator rule, - Notes: `\footnote{...}` page-bottom insertion area with separator rule,
superscript markers, and title/author `\thanks`. superscript markers, and title/author `\thanks`.
- Classes/packages: built-in classes, local `.cls`/`.sty`, paper options, - Classes/packages: built-in classes, local `.cls`/`.sty`, paper options,
@@ -42,8 +47,9 @@ See `docs/ROADMAP.md` for concrete implementation plans.
- Boxes: `\parbox`/`\minipage` are block-level; `\vbox`/`\vtop` map to a - Boxes: `\parbox`/`\minipage` are block-level; `\vbox`/`\vtop` map to a
full-width block rather than true nested VBox material. full-width block rather than true nested VBox material.
- Pages: no floats, no headers/footers (fancyhdr commands are accepted as - Pages: float placement is immediate rather than a deferred float queue
no-ops), planner and renderer are separate. (no `\textfraction` tuning, no reordering around later text); planner and
renderer are still separate.
- Notes: footnotes inside captions, floats, or arbitrary boxes are not - Notes: footnotes inside captions, floats, or arbitrary boxes are not
collected; the insertion area currently follows the page where the paragraph collected; the insertion area currently follows the page where the paragraph
ends rather than the exact reference line. ends rather than the exact reference line.
@@ -51,14 +57,16 @@ See `docs/ROADMAP.md` for concrete implementation plans.
A4-content defaults, not geometry-aware. A4-content defaults, not geometry-aware.
- Miscellaneous: `\tableofcontents`/list commands are no-ops; base font-size - Miscellaneous: `\tableofcontents`/list commands are no-ops; base font-size
class options (10/11/12pt) are parsed but unused; rules are painted with 1x1 class options (10/11/12pt) are parsed but unused; rules are painted with 1x1
images in PDF. images in PDF; a document-level `\renewcommand{\maketitle}` is ignored in
favor of the engine title block.
## Verification ## Verification
- `examples/hello.tex`, `examples/boxes.tex`, `examples/compat.tex` compile to - `examples/hello.tex`, `examples/boxes.tex`, `examples/compat.tex` compile to
one A4 page each; the arXiv template project compiles to 3 Letter pages. one A4 page each; the arXiv template project compiles to 3 Letter pages.
- `cargo fmt --check` passes; `cargo test --workspace` (23 tests) covers the three - `cargo fmt --check` passes; `cargo test --offline` (26 tests: 22 compiler
examples, the arXiv fixture, SVG/PDF output, project API, static frontend integration tests + 4 server tests) covers the three examples, the arXiv
assets, path traversal, the legacy `/texrra` endpoint, and page-hash cache fixture, floats/newpage, page styles and `\thispagestyle`, SVG/PDF output,
stability. project API, static frontend assets, path traversal, the legacy
`/texrra` endpoint, and page-hash cache stability.
- Warm preview: hello ~0.6ms, arXiv ~13ms (release server, page layout cached). - Warm preview: hello ~0.6ms, arXiv ~13ms (release server, page layout cached).
+3 -1
View File
@@ -33,7 +33,7 @@ use document::{
MathDelimiterSettings, MathExpr, MathFontFamilies, MathFontSelection, MathFontStyle, MathDelimiterSettings, MathExpr, MathFontFamilies, MathFontSelection, MathFontStyle,
MathFractionDelimiters, MathFractionStyle, MathInfixFractionKind, MathLimitMode, MathFractionDelimiters, MathFractionStyle, MathInfixFractionKind, MathLimitMode,
MathLineBreakPenalties, MathMuGlue, MathPhantomKind, MathRowSpacing, MathSpacingSettings, MathLineBreakPenalties, MathMuGlue, MathPhantomKind, MathRowSpacing, MathSpacingSettings,
RuleBox, Run, PAGE_NUMBER_MARKER, PageDecoration, PageDecorationPosition, PageStyleKind, RuleBox, Run,
}; };
use parser::parse_dimension; use parser::parse_dimension;
@@ -444,6 +444,7 @@ fn render_html_document(
caption, caption,
alignments, alignments,
rules, rules,
..
} => { } => {
html.push_str(&format!( html.push_str(&format!(
"<table class=\"texrra-table\"{source_attributes}>" "<table class=\"texrra-table\"{source_attributes}>"
@@ -482,6 +483,7 @@ fn render_html_document(
path, path,
options, options,
caption, caption,
..
} => { } => {
let image_path = PathBuf::from(&path); let image_path = PathBuf::from(&path);
let image_path = if image_path.is_absolute() { let image_path = if image_path.is_absolute() {
+2 -1
View File
@@ -1,4 +1,5 @@
pub(super) use texrra_core::document::{ pub(super) use texrra_core::document::{
Block, ColumnAlignment, DocumentModel, EquationNumber, ListBlock, RuleBox, Run, Block, ColumnAlignment, DocumentModel, EquationNumber, ListBlock, PAGE_NUMBER_MARKER,
PageDecoration, PageDecorationPosition, PageStyleKind, RuleBox, Run,
}; };
pub(super) use texrra_core::math_expr::*; pub(super) use texrra_core::math_expr::*;
+6 -12
View File
@@ -350,21 +350,15 @@ const PRELUDE: &str = r#"
\def~{ } \def~{ }
\def\AtBeginDocument#1{#1} \def\AtBeginDocument#1{#1}
\def\newgeometry#1{\texrrageometry{#1}} \def\newgeometry#1{\texrrageometry{#1}}
\def\fancyhf{}
\def\fancyheadoffset#1{} \def\fancyheadoffset#1{}
\def\fancyhead#1{} \def\lhead#1{\fancyhead[L]{#1}}
\def\fancyfoot#1{} \def\chead#1{\fancyhead[C]{#1}}
\def\lhead#1{} \def\rhead#1{\fancyhead[R]{#1}}
\def\chead#1{} \def\lfoot#1{\fancyfoot[L]{#1}}
\def\rhead#1{} \def\cfoot#1{\fancyfoot[C]{#1}}
\def\lfoot#1{} \def\rfoot#1{\fancyfoot[R]{#1}}
\def\cfoot#1{}
\def\rfoot#1{}
\def\headrulewidth{0.4pt} \def\headrulewidth{0.4pt}
\def\footrulewidth{0pt} \def\footrulewidth{0pt}
\def\pagestyle#1{}
\def\thispagestyle#1{}
\def\thepage{1}
\def\hypersetup#1{} \def\hypersetup#1{}
\def\microtypesetup#1{} \def\microtypesetup#1{}
\def\urlstyle#1{} \def\urlstyle#1{}
+48 -15
View File
@@ -22,7 +22,8 @@ use super::engine::glue::TeXGlue;
use super::page_builder::{self, GlueOrder, PageAnchor, VerticalNode}; use super::page_builder::{self, GlueOrder, PageAnchor, VerticalNode};
use super::{ use super::{
Block, ColumnAlignment, DocumentModel, EquationNumber, ListBlock, MathExpr, Block, ColumnAlignment, DocumentModel, EquationNumber, ListBlock, MathExpr,
MathLayoutEnvironment, PDF_POINTS_PER_INCH, RuleBox, Run, MathLayoutEnvironment, PAGE_NUMBER_MARKER, PDF_POINTS_PER_INCH, PageDecoration,
PageDecorationPosition, PageStyleKind, RuleBox, Run,
box_font::{BoxFont, TeXHyphenator, scaled_points}, box_font::{BoxFont, TeXHyphenator, scaled_points},
is_cjk, math_font, math_layout, parse_dimension, prohibits_cjk_line_break, text_layout, is_cjk, math_font, math_layout, parse_dimension, prohibits_cjk_line_break, text_layout,
}; };
@@ -76,6 +77,7 @@ enum PageBlockKey {
path: PathBuf, path: PathBuf,
options: String, options: String,
caption: Option<Vec<Run>>, caption: Option<Vec<Run>>,
placement: String,
fingerprint: u64, fingerprint: u64,
}, },
Bibliography(Vec<(String, Vec<Run>)>), Bibliography(Vec<(String, Vec<Run>)>),
@@ -108,6 +110,7 @@ struct PageLayoutConfig {
text_font_fingerprint: u64, text_font_fingerprint: u64,
math_font_fingerprint: u64, math_font_fingerprint: u64,
math_layout_font_fingerprint: u64, math_layout_font_fingerprint: u64,
page_style_fingerprint: u64,
} }
struct PageLayoutSnapshot { struct PageLayoutSnapshot {
@@ -490,6 +493,8 @@ impl PositionedCentered {
struct PositionedPages { struct PositionedPages {
pages: Vec<PositionedPage>, pages: Vec<PositionedPage>,
content_margins: Margins,
left_margin_mm: f64,
next_page: usize, next_page: usize,
cjk_family: Option<FontFamily<fonts::Font>>, cjk_family: Option<FontFamily<fonts::Font>>,
mono_family: Option<FontFamily<fonts::Font>>, mono_family: Option<FontFamily<fonts::Font>>,
@@ -499,12 +504,16 @@ struct PositionedPages {
impl PositionedPages { impl PositionedPages {
fn new( fn new(
pages: Vec<PositionedPage>, pages: Vec<PositionedPage>,
content_margins: Margins,
left_margin_mm: f64,
cjk_family: Option<FontFamily<fonts::Font>>, cjk_family: Option<FontFamily<fonts::Font>>,
mono_family: Option<FontFamily<fonts::Font>>, mono_family: Option<FontFamily<fonts::Font>>,
sans_family: Option<FontFamily<fonts::Font>>, sans_family: Option<FontFamily<fonts::Font>>,
) -> Self { ) -> Self {
Self { Self {
pages, pages,
content_margins,
left_margin_mm,
next_page: 0, next_page: 0,
cjk_family, cjk_family,
mono_family, mono_family,
@@ -526,6 +535,9 @@ impl Element for PositionedPages {
let page_index = self.next_page; let page_index = self.next_page;
self.next_page += 1; self.next_page += 1;
let page = &mut self.pages[page_index]; let page = &mut self.pages[page_index];
let mut body_area = area.clone();
body_area.add_margins(self.content_margins);
let body_height = f64::from(body_area.size().height);
let mut used_height = 0.0_f64; let mut used_height = 0.0_f64;
for item in &mut page.items { for item in &mut page.items {
@@ -540,8 +552,20 @@ impl Element for PositionedPages {
let (result, y) = match item { let (result, y) = match item {
PositionedPageItem::Line(planned_line) => { PositionedPageItem::Line(planned_line) => {
let y = scaled_units_to_mm(planned_line.y); let y = scaled_units_to_mm(planned_line.y);
let mut line_area = area.clone(); let is_decoration = planned_line.anchor.block == usize::MAX;
line_area.add_offset(Position::new(scaled_units_to_mm(planned_line.x), y)); let line_area = if is_decoration {
let mut decoration_area = area.clone();
decoration_area.add_offset(Position::new(
self.left_margin_mm + scaled_units_to_mm(planned_line.x),
y,
));
decoration_area
} else {
let mut content_area = body_area.clone();
content_area
.add_offset(Position::new(scaled_units_to_mm(planned_line.x), y));
content_area
};
let result = match &mut planned_line.content { let result = match &mut planned_line.content {
PositionedLineContent::Text { line, font_size } => { PositionedLineContent::Text { line, font_size } => {
let text_line = text_layout::TextLine::new( let text_line = text_layout::TextLine::new(
@@ -568,13 +592,13 @@ impl Element for PositionedPages {
element, style, y, .. element, style, y, ..
} => { } => {
let y = scaled_units_to_mm(*y); let y = scaled_units_to_mm(*y);
let mut math_area = area.clone(); let mut math_area = body_area.clone();
math_area.add_offset(Position::new(0.0, y)); math_area.add_offset(Position::new(0.0, y));
(element.render(context, math_area, *style)?, y) (element.render(context, math_area, *style)?, y)
} }
PositionedPageItem::Table { element, y, .. } => { PositionedPageItem::Table { element, y, .. } => {
let y = scaled_units_to_mm(*y); let y = scaled_units_to_mm(*y);
let mut table_area = area.clone(); let mut table_area = body_area.clone();
table_area.add_offset(Position::new(0.0, y)); table_area.add_offset(Position::new(0.0, y));
( (
element.render( element.render(
@@ -590,7 +614,7 @@ impl Element for PositionedPages {
} }
PositionedPageItem::Image { element, y, .. } => { PositionedPageItem::Image { element, y, .. } => {
let y = scaled_units_to_mm(*y); let y = scaled_units_to_mm(*y);
let mut image_area = area.clone(); let mut image_area = body_area.clone();
image_area.add_offset(Position::new(0.0, y)); image_area.add_offset(Position::new(0.0, y));
( (
element.render( element.render(
@@ -606,7 +630,7 @@ impl Element for PositionedPages {
} }
PositionedPageItem::FramedBox { element, y, .. } => { PositionedPageItem::FramedBox { element, y, .. } => {
let y = scaled_units_to_mm(*y); let y = scaled_units_to_mm(*y);
let mut box_area = area.clone(); let mut box_area = body_area.clone();
box_area.add_offset(Position::new(0.0, y)); box_area.add_offset(Position::new(0.0, y));
( (
element.render( element.render(
@@ -622,7 +646,7 @@ impl Element for PositionedPages {
} }
PositionedPageItem::Centered { element, y, .. } => { PositionedPageItem::Centered { element, y, .. } => {
let y = scaled_units_to_mm(*y); let y = scaled_units_to_mm(*y);
let mut centered_area = area.clone(); let mut centered_area = body_area.clone();
centered_area.add_offset(Position::new(0.0, y)); centered_area.add_offset(Position::new(0.0, y));
( (
element.render( element.render(
@@ -642,7 +666,12 @@ impl Element for PositionedPages {
format!( format!(
"Rust page layout placed a {kind} outside its page frame (page {}, y {y:.2}mm, area {:.2}mm)", "Rust page layout placed a {kind} outside its page frame (page {}, y {y:.2}mm, area {:.2}mm)",
page_index + 1, page_index + 1,
f64::from(area.size().height), if matches!(item, PositionedPageItem::Line(line) if line.anchor.block == usize::MAX)
{
f64::from(area.size().height)
} else {
body_height
},
), ),
genpdf::error::ErrorKind::PageSizeExceeded, genpdf::error::ErrorKind::PageSizeExceeded,
)); ));
@@ -2066,12 +2095,7 @@ impl RenderResources {
model.page.height_mm as f32, model.page.height_mm as f32,
)); ));
let mut decorator = genpdf::SimplePageDecorator::new(); let mut decorator = genpdf::SimplePageDecorator::new();
decorator.set_margins(Margins::trbl( decorator.set_margins(Margins::trbl(0.0, 0.0, 0.0, 0.0));
model.margins.top,
model.margins.right,
model.margins.bottom,
model.margins.left,
));
document.set_page_decorator(decorator); document.set_page_decorator(decorator);
let mono_family = inputs let mono_family = inputs
@@ -2249,6 +2273,13 @@ pub(super) fn render_pdf(
} = resources; } = resources;
document.push(PositionedPages::new( document.push(PositionedPages::new(
pages, pages,
Margins::trbl(
model.margins.top,
model.margins.right,
model.margins.bottom,
model.margins.left,
),
model.margins.left,
cjk_family, cjk_family,
mono_family, mono_family,
sans_family, sans_family,
@@ -2474,6 +2505,7 @@ pub(super) fn render_pdf(
caption, caption,
alignments, alignments,
rules, rules,
..
} => { } => {
if let Some(caption) = caption { if let Some(caption) = caption {
document.push( document.push(
@@ -2505,6 +2537,7 @@ pub(super) fn render_pdf(
path, path,
options, options,
caption, caption,
..
} => { } => {
let image_path = PathBuf::from(&path); let image_path = PathBuf::from(&path);
let image_path = if image_path.is_absolute() { let image_path = if image_path.is_absolute() {
+254
View File
@@ -176,6 +176,7 @@ fn page_block_keys(model: &DocumentModel, source_dir: &Path) -> Option<Vec<PageB
caption, caption,
alignments, alignments,
rules, rules,
..
} => Some(PageBlockKey::Table { } => Some(PageBlockKey::Table {
rows: rows rows: rows
.iter() .iter()
@@ -196,6 +197,7 @@ fn page_block_keys(model: &DocumentModel, source_dir: &Path) -> Option<Vec<PageB
path, path,
options, options,
caption, caption,
placement,
} => { } => {
let image_path = resolved_image_path(source_dir, path); let image_path = resolved_image_path(source_dir, path);
let bytes = fs::read(&image_path).ok()?; let bytes = fs::read(&image_path).ok()?;
@@ -205,6 +207,7 @@ fn page_block_keys(model: &DocumentModel, source_dir: &Path) -> Option<Vec<PageB
path: image_path, path: image_path,
options: options.clone(), options: options.clone(),
caption: caption.as_deref().map(normalize_page_runs), caption: caption.as_deref().map(normalize_page_runs),
placement: placement.clone(),
fingerprint: hasher.finish(), fingerprint: hasher.finish(),
}) })
} }
@@ -1335,6 +1338,7 @@ pub(super) fn build_page_break_plan(
caption, caption,
alignments, alignments,
rules, rules,
..
} => { } => {
pre_display_size = None; pre_display_size = None;
let mut line_index = 0; let mut line_index = 0;
@@ -1408,6 +1412,7 @@ pub(super) fn build_page_break_plan(
path, path,
options, options,
caption, caption,
..
} => { } => {
pre_display_size = None; pre_display_size = None;
let Some(figure) = layout_figure( let Some(figure) = layout_figure(
@@ -1540,6 +1545,12 @@ pub(super) fn build_page_break_plan(
text_font_fingerprint: metrics.fingerprint, text_font_fingerprint: metrics.fingerprint,
math_font_fingerprint: math_metrics.fingerprint, math_font_fingerprint: math_metrics.fingerprint,
math_layout_font_fingerprint: math_layout.font_fingerprint, math_layout_font_fingerprint: math_layout.font_fingerprint,
page_style_fingerprint: {
let mut hasher = DefaultHasher::new();
model.page_style.hash(&mut hasher);
model.page_style_overrides.hash(&mut hasher);
hasher.finish()
},
}; };
let blocks = page_block_keys(model, source_dir)?; let blocks = page_block_keys(model, source_dir)?;
let breaks = if model.show_title { let breaks = if model.show_title {
@@ -1934,6 +1945,7 @@ pub(super) fn build_positioned_pages(
let page_goal = scaled_points(content_height_mm * PDF_POINTS_PER_INCH / 25.4).0 as i64; let page_goal = scaled_points(content_height_mm * PDF_POINTS_PER_INCH / 25.4).0 as i64;
let mut pages = vec![PositionedPage::default()]; let mut pages = vec![PositionedPage::default()];
let mut block_end_pages: HashMap<usize, usize> = HashMap::new(); let mut block_end_pages: HashMap<usize, usize> = HashMap::new();
let mut block_start_pages: HashMap<usize, usize> = HashMap::new();
let mut cursor = 0_i64; let mut cursor = 0_i64;
let mut has_previous_block = false; let mut has_previous_block = false;
let mut pending_gap = 0_i64; let mut pending_gap = 0_i64;
@@ -1998,6 +2010,9 @@ pub(super) fn build_positioned_pages(
} }
for (block_index, block) in model.blocks.iter().enumerate() { for (block_index, block) in model.blocks.iter().enumerate() {
block_start_pages
.entry(block_index)
.or_insert_with(|| pages.len().saturating_sub(1));
match block { match block {
Block::Paragraph(runs) | Block::Heading { runs, .. } => { Block::Paragraph(runs) | Block::Heading { runs, .. } => {
let (font_size, is_heading) = match block { let (font_size, is_heading) = match block {
@@ -2420,6 +2435,7 @@ pub(super) fn build_positioned_pages(
caption, caption,
alignments, alignments,
rules, rules,
..
} => { } => {
pre_display_size = None; pre_display_size = None;
let mut line_index = 0; let mut line_index = 0;
@@ -2562,6 +2578,7 @@ pub(super) fn build_positioned_pages(
path, path,
options, options,
caption, caption,
placement,
} => { } => {
pre_display_size = None; pre_display_size = None;
let Some(figure) = layout_figure( let Some(figure) = layout_figure(
@@ -2591,6 +2608,27 @@ pub(super) fn build_positioned_pages(
line: 0, line: 0,
}; };
let block_gap = if has_previous_block { pending_gap } else { 0 }; let block_gap = if has_previous_block { pending_gap } else { 0 };
let bottom_float = placement.contains('b')
&& !placement.contains('h')
&& !placement.contains('t')
&& cursor > 0
&& cursor
.saturating_add(block_gap)
.saturating_add(figure_height)
<= page_goal;
if bottom_float {
let y = page_goal.saturating_sub(figure_height);
pages
.last_mut()
.expect("the page list starts with one page")
.items
.push(PositionedPageItem::Image {
anchor,
element: figure,
y,
});
cursor = page_goal;
} else {
position_box( position_box(
&mut pages, &mut pages,
&mut cursor, &mut cursor,
@@ -2613,6 +2651,7 @@ pub(super) fn build_positioned_pages(
y: cursor, y: cursor,
}); });
cursor = cursor.saturating_add(figure_height); cursor = cursor.saturating_add(figure_height);
}
pending_gap = paragraph_gap + (normal_line_height as f64 * 0.15).round() as i64; pending_gap = paragraph_gap + (normal_line_height as f64 * 0.15).round() as i64;
has_previous_block = true; has_previous_block = true;
} }
@@ -2750,6 +2789,10 @@ pub(super) fn build_positioned_pages(
} }
Block::Penalty(_) => {} Block::Penalty(_) => {}
Block::PageBreak => { Block::PageBreak => {
if pages.last().is_some_and(|page| !page.items.is_empty()) {
pages.push(PositionedPage::default());
cursor = 0;
}
pending_gap = 0; pending_gap = 0;
has_previous_block = false; has_previous_block = false;
pre_display_size = None; pre_display_size = None;
@@ -2773,9 +2816,220 @@ pub(super) fn build_positioned_pages(
cache, cache,
); );
pages.retain(|page| !page.items.is_empty()); pages.retain(|page| !page.items.is_empty());
append_page_decorations(
model,
&mut pages,
&block_start_pages,
content_width_mm,
metrics,
font_cache,
cjk_family,
mono_family,
sans_family,
math_metrics,
math_layout,
cache,
);
Some(pages) Some(pages)
} }
fn decoration_slot_runs(decoration: &PageDecoration, position: PageDecorationPosition) -> &[Run] {
match position {
PageDecorationPosition::Left => &decoration.left,
PageDecorationPosition::Center => &decoration.center,
PageDecorationPosition::Right => &decoration.right,
}
}
fn resolved_page_number_runs(runs: &[Run], page_number: usize) -> Vec<Run> {
let number = page_number.to_string();
runs.iter()
.map(|run| {
let mut run = run.clone();
if run.text.contains(PAGE_NUMBER_MARKER) {
run.text = run.text.replace(PAGE_NUMBER_MARKER, &number);
}
run
})
.collect()
}
#[allow(clippy::too_many_arguments)]
fn effective_page_style_kind(
model: &DocumentModel,
page_index: usize,
page_count: usize,
block_start_pages: &HashMap<usize, usize>,
) -> PageStyleKind {
let mut kind = model.page_style.kind;
for override_ in &model.page_style_overrides {
let page = block_start_pages
.get(&override_.anchor)
.copied()
.unwrap_or_else(|| page_count.saturating_sub(1));
if page == page_index {
kind = override_.kind;
}
}
kind
}
fn append_page_decorations(
model: &DocumentModel,
pages: &mut [PositionedPage],
block_start_pages: &HashMap<usize, usize>,
content_width_mm: f64,
metrics: &BoxFontMetrics,
font_cache: &fonts::FontCache,
cjk_family: Option<FontFamily<fonts::Font>>,
mono_family: Option<FontFamily<fonts::Font>>,
sans_family: Option<FontFamily<fonts::Font>>,
math_metrics: &math_font::MathFontMetrics,
math_layout: &MathLayoutEnvironment,
cache: &mut ParagraphLayoutCache,
) {
let page_count = pages.len();
for (index, page) in pages.iter_mut().enumerate() {
let page_number = index + 1;
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(
page,
&runs,
page_number,
false,
PageDecorationPosition::Center,
content_width_mm,
model.page.height_mm,
metrics,
font_cache,
cjk_family,
mono_family,
sans_family,
math_metrics,
math_layout,
cache,
);
continue;
}
for is_header in [false, true] {
let decoration = if is_header {
&model.page_style.header
} else {
&model.page_style.footer
};
for position in [
PageDecorationPosition::Left,
PageDecorationPosition::Center,
PageDecorationPosition::Right,
] {
let runs = decoration_slot_runs(decoration, position);
if runs.is_empty() {
continue;
}
append_decoration(
page,
runs,
page_number,
is_header,
position,
content_width_mm,
model.page.height_mm,
metrics,
font_cache,
cjk_family,
mono_family,
sans_family,
math_metrics,
math_layout,
cache,
);
}
}
}
}
#[allow(clippy::too_many_arguments)]
fn append_decoration(
page: &mut PositionedPage,
runs: &[Run],
page_number: usize,
is_header: bool,
position: PageDecorationPosition,
content_width_mm: f64,
page_height_mm: f64,
metrics: &BoxFontMetrics,
font_cache: &fonts::FontCache,
cjk_family: Option<FontFamily<fonts::Font>>,
mono_family: Option<FontFamily<fonts::Font>>,
sans_family: Option<FontFamily<fonts::Font>>,
math_metrics: &math_font::MathFontMetrics,
math_layout: &MathLayoutEnvironment,
cache: &mut ParagraphLayoutCache,
) {
let runs = resolved_page_number_runs(runs, page_number);
let lines = measure_positioned_lines(
&runs,
9,
content_width_mm,
metrics,
font_cache,
cjk_family,
mono_family,
sans_family,
math_metrics,
math_layout,
cache,
);
if lines.is_empty() {
return;
}
let body_width = millimeters_to_scaled(content_width_mm);
let page_height = millimeters_to_scaled(page_height_mm);
let top_skip = i64::from(scaled_points(ARTICLE_11PT_TOPSKIP_PT).0);
let total_height: i64 = lines.iter().map(|line| line.height).sum();
let mut y = if is_header {
(top_skip / 2).max(0)
} else {
(page_height - millimeters_to_scaled(12.0) - total_height).max(0)
};
for (line_index, line) in lines.into_iter().enumerate() {
let width = match &line.content {
PositionedLineContent::Text { line, font_size } => {
let text_line = text_layout::TextLine::new(
line,
cjk_family,
mono_family,
sans_family,
*font_size,
);
millimeters_to_scaled(text_line.natural_width_mm(font_cache))
}
PositionedLineContent::InlineMath(_) => 0,
};
let x = match position {
PageDecorationPosition::Left => 0,
PageDecorationPosition::Center => (body_width - width) / 2,
PageDecorationPosition::Right => body_width - width,
};
page.items.push(PositionedPageItem::Line(PositionedLine {
anchor: PageAnchor {
block: usize::MAX,
line: page_number.saturating_mul(1024).saturating_add(line_index),
},
content: line.content,
y,
x,
centered: false,
}));
y = y.saturating_add(line.height);
}
}
#[allow(clippy::too_many_arguments)] #[allow(clippy::too_many_arguments)]
fn append_vertical_text( fn append_vertical_text(
nodes: &mut Vec<VerticalNode>, nodes: &mut Vec<VerticalNode>,
+160
View File
@@ -1687,6 +1687,138 @@ fn page_break_primitive(
execute_layout_primitive(LayoutPrimitive::PageBreak, token, input) execute_layout_primitive(LayoutPrimitive::PageBreak, token, input)
} }
fn page_style_primitive(
token: token::Token,
input: &mut vm::ExecutionInput<CompilerState>,
) -> texlang::prelude::Result<()> {
let content = read_unexpanded_argument(input, token, "expects a page style name")?;
let name = simple_token_text(strip_braced_tokens(&content)).to_ascii_lowercase();
let kind = match name.trim() {
"empty" => texrra_core::document::PageStyleKind::Empty,
"fancy" => texrra_core::document::PageStyleKind::Fancy,
_ => texrra_core::document::PageStyleKind::Plain,
};
write_event(input, token, FrontendEventKind::PageStyle(kind));
Ok(())
}
fn this_page_style_primitive(
token: token::Token,
input: &mut vm::ExecutionInput<CompilerState>,
) -> texlang::prelude::Result<()> {
let content = read_unexpanded_argument(input, token, "expects a page style name")?;
let name = simple_token_text(strip_braced_tokens(&content)).to_ascii_lowercase();
let kind = match name.trim() {
"empty" => texrra_core::document::PageStyleKind::Empty,
"fancy" => texrra_core::document::PageStyleKind::Fancy,
_ => texrra_core::document::PageStyleKind::Plain,
};
write_event(input, token, FrontendEventKind::ThisPageStyle(kind));
Ok(())
}
fn fancy_decoration_primitive(
token: token::Token,
input: &mut vm::ExecutionInput<CompilerState>,
header: bool,
) -> texlang::prelude::Result<()> {
let position = read_optional_bracketed_argument(input, token, "decoration position")?
.map(|tokens| simple_token_text(&tokens))
.and_then(|text| text.chars().find(|character| !character.is_whitespace()));
let position = match position {
Some('L') | Some('l') => texrra_core::document::PageDecorationPosition::Left,
Some('R') | Some('r') => texrra_core::document::PageDecorationPosition::Right,
_ => texrra_core::document::PageDecorationPosition::Center,
};
let content = read_unexpanded_argument(input, token, "expects decoration content")?;
let inner = strip_braced_tokens(&content).to_vec();
if inner.is_empty() {
write_event(
input,
token,
FrontendEventKind::PageDecorationClear { header },
);
return Ok(());
}
write_event(
input,
token,
FrontendEventKind::PageDecorationStart { header, position },
);
let trace_key = token.trace_key();
let mut expansion = inner;
expansion.push(control_sequence_token(
input,
"texrrapagedecorationend",
trace_key,
));
input
.as_mut()
.expansions_mut()
.extend(expansion.into_iter().rev());
Ok(())
}
fn fancy_head_primitive(
token: token::Token,
input: &mut vm::ExecutionInput<CompilerState>,
) -> texlang::prelude::Result<()> {
fancy_decoration_primitive(token, input, true)
}
fn fancy_foot_primitive(
token: token::Token,
input: &mut vm::ExecutionInput<CompilerState>,
) -> texlang::prelude::Result<()> {
fancy_decoration_primitive(token, input, false)
}
fn fancy_hf_primitive(
token: token::Token,
input: &mut vm::ExecutionInput<CompilerState>,
) -> texlang::prelude::Result<()> {
write_event(
input,
token,
FrontendEventKind::PageDecorationClear { header: true },
);
write_event(
input,
token,
FrontendEventKind::PageDecorationClear { header: false },
);
Ok(())
}
fn page_decoration_end_primitive(
token: token::Token,
input: &mut vm::ExecutionInput<CompilerState>,
) -> texlang::prelude::Result<()> {
write_event(input, token, FrontendEventKind::PageDecorationEnd);
Ok(())
}
fn page_number_primitive(
token: token::Token,
input: &mut vm::ExecutionInput<CompilerState>,
) -> texlang::prelude::Result<()> {
write_event(input, token, FrontendEventKind::PageNumber);
Ok(())
}
fn simple_token_text(tokens: &[token::Token]) -> String {
let mut text = String::new();
for token in tokens {
match token.value() {
token::Value::Letter(character)
| token::Value::Other(character)
| token::Value::Space(character) => text.push(character),
_ => {}
}
}
text
}
fn scan_engine_dimension( fn scan_engine_dimension(
input: &mut vm::ExecutionInput<CompilerState>, input: &mut vm::ExecutionInput<CompilerState>,
) -> texlang::prelude::Result<common::Scaled> { ) -> texlang::prelude::Result<common::Scaled> {
@@ -6572,6 +6704,34 @@ fn built_in_commands() -> HashMap<&'static str, texlang::command::BuiltIn<Compil
texlang::command::BuiltIn::new_execution(page_break_primitive) texlang::command::BuiltIn::new_execution(page_break_primitive)
.with_tag(layout_primitive_tag(LayoutPrimitive::PageBreak)), .with_tag(layout_primitive_tag(LayoutPrimitive::PageBreak)),
); );
built_ins.insert(
"pagestyle",
texlang::command::BuiltIn::new_execution(page_style_primitive),
);
built_ins.insert(
"thispagestyle",
texlang::command::BuiltIn::new_execution(this_page_style_primitive),
);
built_ins.insert(
"fancyhead",
texlang::command::BuiltIn::new_execution(fancy_head_primitive),
);
built_ins.insert(
"fancyfoot",
texlang::command::BuiltIn::new_execution(fancy_foot_primitive),
);
built_ins.insert(
"fancyhf",
texlang::command::BuiltIn::new_execution(fancy_hf_primitive),
);
built_ins.insert(
"texrrapagedecorationend",
texlang::command::BuiltIn::new_execution(page_decoration_end_primitive),
);
built_ins.insert(
"thepage",
texlang::command::BuiltIn::new_execution(page_number_primitive),
);
built_ins.insert( built_ins.insert(
"kern", "kern",
texlang::command::BuiltIn::new_execution(kern_primitive) texlang::command::BuiltIn::new_execution(kern_primitive)
+22
View File
@@ -284,6 +284,28 @@ impl TextLine {
self self
} }
/// Natural (unjustified) width of the line in millimetres, for centering
/// and right-aligning decorations whose box may be wider than the text.
pub(super) fn natural_width_mm(&self, fonts: &fonts::FontCache) -> f64 {
let natural_space = Style::new()
.with_font_size(self.font_size)
.str_width(fonts, " ");
let mut x = Mm::from(0.0);
for item in &self.items {
match item {
TextLineItem::Text(span) => {
x += span.style.str_width(fonts, &span.text);
}
TextLineItem::Glue(_) => x += natural_space,
TextLineItem::Kern(width) => x += *width,
TextLineItem::Rule { width, .. } => x += *width,
TextLineItem::Frame { width, .. } => x += *width,
}
}
let width: printpdf::Mm = x.into();
width.0
}
pub(super) fn layout_spans(&self, fonts: &fonts::FontCache) -> TextLineLayout { pub(super) fn layout_spans(&self, fonts: &fonts::FontCache) -> TextLineLayout {
let mut spans = Vec::with_capacity(self.items.len()); let mut spans = Vec::with_capacity(self.items.len());
let mut rules = Vec::new(); let mut rules = Vec::new();
+167
View File
@@ -280,6 +280,84 @@ C\hfill D\hfill E
assert!(e > 150.0, "last hfill did not reach the right edge: {e}"); assert!(e > 150.0, "last hfill did not reach the right edge: {e}");
} }
#[test]
fn figure_placement_and_newpage_split_pages() {
let image = format!("{}/examples/plot.png", env!("CARGO_MANIFEST_DIR"));
let template = r#"\documentclass{article}
\begin{document}
Before text.
\begin{figure}[PLACE]
\includegraphics[width=3cm]{IMAGE}
\caption{Float caption.}
\end{figure}
After text.
\end{document}
"#;
let compile = |placement: &str| {
let source = template
.replace("PLACE", placement)
.replace("IMAGE", &image);
fresh_preview(&source, "float.tex")
};
let top = compile("t");
assert_eq!(top["status"], "ok", "{}", top["message"]);
assert_eq!(pages(&top).len(), 2, "[t] should move the figure to page 2");
assert!(
!page_svg(&top, 0).contains("<image"),
"[t] figure on page 1"
);
assert!(page_svg(&top, 1).contains("<image"), "[t] figure missing");
let here = compile("h");
assert_eq!(here["status"], "ok", "{}", here["message"]);
assert_eq!(pages(&here).len(), 1, "[h] should stay in flow");
assert!(page_svg(&here, 0).contains("<image"), "[h] figure missing");
let float_page = compile("p");
assert_eq!(float_page["status"], "ok", "{}", float_page["message"]);
assert_eq!(pages(&float_page).len(), 3, "[p] should use its own page");
assert!(
page_svg(&float_page, 1).contains("<image"),
"[p] figure page missing"
);
let bottom = compile("b");
assert_eq!(bottom["status"], "ok", "{}", bottom["message"]);
assert_eq!(pages(&bottom).len(), 2, "[b] should end the page");
let bottom_svg = page_svg(&bottom, 0);
assert!(bottom_svg.contains("<image"), "[b] figure missing");
let image_y = bottom_svg
.split("<image")
.nth(1)
.and_then(|rest| rest.split("y=\"").nth(1))
.and_then(|rest| rest.split('"').next())
.and_then(|value| value.parse::<f64>().ok())
.unwrap_or_else(|| panic!("[b] image has no y coordinate: {bottom_svg}"));
assert!(
image_y > 200.0,
"[b] figure was not pushed to the bottom: {image_y}"
);
assert!(page_svg(&bottom, 1).contains("After"), "[b] following text");
let newpage = r#"\documentclass{article}
\begin{document}
First page.
\newpage
Second page.
\end{document}
"#;
let value = fresh_preview(newpage, "newpage.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
assert_eq!(pages(&value).len(), 2, "\\newpage page count");
assert!(page_svg(&value, 0).contains("First"), "first page text");
assert!(page_svg(&value, 1).contains("Second"), "second page text");
}
#[test] #[test]
fn sans_family_selects_the_sans_face() { fn sans_family_selects_the_sans_face() {
let source = r#"\documentclass{article} let source = r#"\documentclass{article}
@@ -515,3 +593,92 @@ Body text.
"title footnote is not at the page bottom: {note}" "title footnote is not at the page bottom: {note}"
); );
} }
#[test]
fn page_style_decorates_headers_and_footers() {
let source = r#"\documentclass{article}
\pagestyle{fancy}
\fancyhead[L]{Left head}
\fancyhead[C]{Middle head}
\fancyhead[R]{Right head}
\fancyfoot[C]{Foot \thepage}
\begin{document}
Body text.
\end{document}
"#;
let value = fresh_preview(source, "pagestyle.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
for text in ["Left", "Middle", "Right", "Foot"] {
assert!(
svg.contains(&format!(">{text}</text>")),
"missing decoration `{text}`: {svg}"
);
}
assert!(
text_x(&svg, "Left") < 1.0,
"left header is not at the left margin"
);
assert!(
text_x(&svg, "Right") > 140.0,
"right header is not at the right edge"
);
assert!(
text_y(&svg, "Left") < 15.0,
"header is not near the top of the page"
);
assert!(
text_y(&svg, "Foot") > 275.0,
"footer is not near the bottom of the page"
);
}
#[test]
fn thispagestyle_empty_suppresses_one_page_decorations() {
let source = r#"\documentclass{article}
\pagestyle{fancy}
\fancyhead[L]{Left head}
\fancyfoot[C]{Foot \thepage}
\begin{document}
First page.\thispagestyle{empty}
\newpage
Second page.
\end{document}
"#;
let value = fresh_preview(source, "thispagestyle.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
assert_eq!(pages(&value).len(), 2, "page count");
let first = page_svg(&value, 0);
assert!(
!first.contains(">Left</text>"),
"page 1 header was not suppressed: {first}"
);
assert!(
!first.contains(">Foot</text>"),
"page 1 footer was not suppressed: {first}"
);
let second = page_svg(&value, 1);
assert!(
second.contains(">Left</text>"),
"page 2 header missing: {second}"
);
assert!(
second.contains(">Foot</text>"),
"page 2 footer missing: {second}"
);
assert!(
second.contains(">2</text>"),
"page 2 number missing: {second}"
);
}
#[test]
fn default_plain_style_prints_a_page_number() {
let value = fresh_preview(include_str!("../examples/hello.tex"), "hello.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
assert!(
text_y(&svg, "1") > 275.0,
"default page number is not in the footer"
);
}