2 Commits
Author SHA1 Message Date
gloamxun 269433abdb Track textwidth and textheight from page geometry 2026-10-19 13:46:25 +08:00
gloamxun ed1da06685 Add float placement and page headers/footers 2026-10-19 13:41:29 +08:00
16 changed files with 1119 additions and 110 deletions

No files matched your search

Generated
+1
View File
@@ -950,6 +950,7 @@ dependencies = [
"genpdf",
"hyphenate",
"image",
"printpdf",
"rmp-serde",
"rusttype",
"serde",
+1
View File
@@ -18,6 +18,7 @@ texrra-core = { path = "crates/texrra-core", features = ["serde"] }
flate2 = "1.1"
hyphenate = { path = "vendor/hyphenate" }
genpdf = { version = "0.2.0", features = ["images"] }
printpdf = "0.3.4"
image = { version = "0.23.12", default-features = false, features = ["png", "jpeg", "bmp"] }
common = { git = "https://github.com/jamespfennell/texcraft", rev = "c1dbf5dfe3a480daf73972c394ac8231e0c6ebd0", features = ["serde"] }
boxworks = { git = "https://github.com/jamespfennell/texcraft", rev = "c1dbf5dfe3a480daf73972c394ac8231e0c6ebd0" }
+18 -4
View File
@@ -165,13 +165,27 @@ options/`\geometry{...}` settings, including `paperwidth`, `paperheight`,
`textheight` sizes it below the current top margin. The chosen page size drives
the PDF pages, the positioned layout, and the SVG preview.
`\textwidth`, `\textheight`, `\linewidth`, and `\columnwidth` are live named
length registers: they start at the A4 text block and are updated by
`\documentclass` paper options, `\geometry`, and `\newgeometry`, so
`\parbox{\textwidth}`, `\rule{\textwidth}{...}`, and
`\includegraphics[width=0.5\textwidth]` all follow the current page setup.
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`,
`amsmath`, `amssymb`, `amsfonts`, `booktabs`, `hyperref`, `cite`, `natbib`,
`inputenc`, `fontenc`, `url`, `nicefrac`, `microtype`, `cleveref`, `lipsum`,
`doi`, `authblk`, and `fancyhdr`. Their commands are approximated where they
affect text (`\url` becomes breakable monospace, `\nicefrac`, `\cref`,
`\doi`, `\lipsum`, `\verb`), and are no-ops where they only affect the PDF
back end (`\hypersetup`, `\fancyhf`, `\microtypesetup`).
`\doi`, `\lipsum`, `\verb`); `\hypersetup` and `\microtypesetup` remain
PDF-backend no-ops, while fancyhdr's page decorations are painted natively.
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
@@ -464,8 +478,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 |
| 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` |
| Notes/floats | footnotes with page-bottom insertion area, title/author `\thanks` | figure/table floats |
| Pages | A4/Letter/... page sizes, margins/geometry, automatic pagination, `\newpage`, `\pagebreak` | headers/footers (`fancyhdr`), unified planner/renderer |
| 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`, 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) |
| 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 citations: HashMap<String, usize>,
pub footnotes: Vec<Footnote>,
pub page_style: PageStyle,
pub page_style_overrides: Vec<PageStyleOverride>,
}
impl Default for DocumentModel {
@@ -93,10 +95,81 @@ impl Default for DocumentModel {
labels: HashMap::new(),
citations: HashMap::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);
#[derive(Clone)]
@@ -137,11 +210,15 @@ pub enum Block {
caption: Option<Vec<Run>>,
alignments: Vec<ColumnAlignment>,
rules: Vec<usize>,
/// Float placement hints from `[htbp]`.
placement: String,
},
Image {
path: String,
options: String,
caption: Option<Vec<Run>>,
/// Float placement hints from `[htbp]`.
placement: String,
},
Bibliography(Vec<(String, Vec<Run>)>),
/// A box such as `\fbox{...}` (framed) or `\parbox{width}{...}`.
+158 -15
View File
@@ -4,8 +4,8 @@ use crate::{
TeXGlue,
document::{
Block, ColumnAlignment, DocumentModel, EquationNumber, InlineBox, InlineBoxAlign,
ListBlock, ListItem, PageMargins, PageSize, ParsedDocument, RuleBox, Run,
UnresolvedReference,
ListBlock, ListItem, PageMargins, PageSize, PageStyleOverride, ParsedDocument, RuleBox,
Run, UnresolvedReference,
},
expanded,
math_expr::*,
@@ -300,7 +300,7 @@ fn consume_environment_preamble(
expanded: &expanded::ExpandedTokenStream,
start_index: usize,
environment: &str,
) -> usize {
) -> (usize, Option<String>) {
use expanded::{ExpandedItemKind, ExpandedTokenValue, FrontendEventKind as Event};
let mut argument_start = start_index;
@@ -320,7 +320,7 @@ fn consume_environment_preamble(
let Some(ExpandedItemKind::Event(Event::GroupStart)) =
expanded.items.get(argument_start).map(|item| &item.kind)
else {
return start_index;
return (start_index, None);
};
let mut depth = 0usize;
for (index, item) in expanded.items.iter().enumerate().skip(argument_start) {
@@ -329,13 +329,13 @@ fn consume_environment_preamble(
ExpandedItemKind::Event(Event::GroupEnd) => {
depth -= 1;
if depth == 0 {
return index + 1;
return (index + 1, None);
}
}
_ => {}
}
}
return start_index;
return (start_index, None);
}
if !matches!(environment, "figure" | "table")
@@ -348,11 +348,12 @@ fn consume_environment_preamble(
})
!= Some('[')
{
return start_index;
return (start_index, None);
}
let mut bracket_depth = 0usize;
let mut group_depth = 0usize;
let mut placement = String::new();
for (index, item) in expanded.items.iter().enumerate().skip(argument_start) {
match &item.kind {
ExpandedItemKind::Event(Event::GroupStart) => group_depth += 1,
@@ -364,15 +365,16 @@ fn consume_environment_preamble(
Some(']') => {
bracket_depth = bracket_depth.saturating_sub(1);
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 {
@@ -422,6 +424,19 @@ struct Parser {
minipage: Option<MinipageBuilder>,
footnote_capture: Option<Vec<Run>>,
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>>,
current_source: Option<SourceLocation>,
paragraph_source: Option<SourceLocation>,
@@ -465,6 +480,9 @@ impl Parser {
minipage: None,
footnote_capture: None,
footnote_counter: 0,
page_decoration_capture: None,
float_placement: String::new(),
table_placement: String::new(),
centered: None,
current_source: None,
paragraph_source: None,
@@ -553,8 +571,16 @@ impl Parser {
name: environment, ..
} = kind
{
item_index =
let (next_index, placement) =
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 {
@@ -835,6 +861,83 @@ impl Parser {
self.begin_style(*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::GroupEnd => {
let depth = self.group_depth;
@@ -1342,6 +1445,13 @@ impl Parser {
}
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() {
return self
.footnote_capture
@@ -1357,6 +1467,7 @@ impl Parser {
&& self.centered.is_none()
&& self.framed_box.is_none()
&& self.metadata_capture.is_none()
&& self.page_decoration_capture.is_none()
&& self.caption_capture.is_none()
&& self.heading.is_none()
&& self.table.is_none()
@@ -1546,6 +1657,7 @@ impl Parser {
(false, "tabular") => self.finish_table(),
(true, "figure") => {
self.flush_paragraph();
self.float_placement = String::new();
self.figure_active = true;
self.figure_image = None;
self.figure_number += 1;
@@ -1553,11 +1665,18 @@ impl Parser {
}
(false, "figure") => {
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_image = None;
}
(true, "table") => {
self.flush_paragraph();
self.table_placement = String::new();
self.table_active = true;
self.current_table_block = None;
self.pending_table_caption = None;
@@ -1620,11 +1739,19 @@ impl Parser {
self.figure_number += 1;
}
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();
self.push_block(Block::Image {
path,
options,
caption: None,
placement: self.float_placement.clone(),
});
if self.figure_active {
self.figure_image = Some(index);
@@ -1695,6 +1822,12 @@ impl Parser {
if let Some(table) = self.table.take()
&& !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 caption = table.caption.or_else(|| self.pending_table_caption.take());
self.push_block(Block::Table {
@@ -1702,10 +1835,14 @@ impl Parser {
caption,
alignments: table.alignments,
rules: table.rules,
placement: self.table_placement.clone(),
});
if self.table_active {
self.current_table_block = Some(index);
}
if !self.table_placement.is_empty() && self.table_placement.contains('p') {
self.push_block(Block::PageBreak);
}
}
}
@@ -1934,7 +2071,15 @@ fn normalize_whitespace(text: &str) -> String {
}
fn apply_geometry(document: &mut DocumentModel, settings: &str) {
let page = &mut document.page;
apply_geometry_settings(&mut document.page, &mut document.margins, settings);
}
/// Apply comma-separated `geometry` settings to a page size and margins.
///
/// This is shared by the document parser and by the frontend's live length
/// tracker, so `\textwidth`/`\textheight` expanded during macro processing
/// match the layout that the parser will produce.
pub fn apply_geometry_settings(page: &mut PageSize, margins: &mut PageMargins, settings: &str) {
// Paper size first: explicit margins in the same list must be measured
// against the final page dimensions.
for setting in settings.split(',') {
@@ -1968,7 +2113,6 @@ fn apply_geometry(document: &mut DocumentModel, settings: &str) {
}
}
let margins = &mut document.margins;
for setting in settings.split(',') {
let Some((key, value)) = setting.split_once('=') else {
continue;
@@ -2003,9 +2147,8 @@ fn apply_geometry(document: &mut DocumentModel, settings: &str) {
// Text-block dimensions are resolved after explicit margins so that top
// influences the computed bottom margin in the same settings list.
let page_width = document.page.width_mm;
let page_height = document.page.height_mm;
let margins = &mut document.margins;
let page_width = page.width_mm;
let page_height = page.height_mm;
for setting in settings.split(',') {
let Some((key, value)) = setting.split_once('=') else {
continue;
+11
View File
@@ -234,6 +234,17 @@ pub enum FrontendEventKind {
Reference(String),
Citation(String),
BibliographyItem(String),
PageStyle(crate::document::PageStyleKind),
ThisPageStyle(crate::document::PageStyleKind),
PageDecorationStart {
header: bool,
position: crate::document::PageDecorationPosition,
},
PageDecorationEnd,
PageDecorationClear {
header: bool,
},
PageNumber,
GroupStart,
GroupEnd,
}
+24 -18
View File
@@ -5,26 +5,32 @@ are still missing. Each item names the files/functions to touch.
Completed: paragraph indentation (`\parindent`) and `\hfill`/`\hfil`; sans
family and true scaled small caps; inline box geometry (`\fbox`, `\makebox`,
`\raisebox`), `\minipage`, `\vbox`/`\vtop` block approximations, and
footnotes/`\thanks` (see `docs/STATUS.md`).
`\raisebox`), `\minipage`, `\vbox`/`\vtop` block approximations;
footnotes/`\thanks`; figure/table `[htbp]` placement approximations; page
styles (plain/fancy, `\thispagestyle`, fancyhdr headers/footers, `\thepage`);
and geometry-aware `\textwidth`/`\textheight` named length registers.
## 1. Floats
- 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
## 1. Unified pagination
- Extract the current duplicated planner (`build_page_break_plan`) and renderer
(`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
final painting.
final painting. This is the prerequisite for a true deferred float queue.
## 2. Base font size
- 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.
+17 -10
View File
@@ -23,7 +23,13 @@ the source changes; the SVG preview is refreshed per page.
centering, first-line `\parindent` (17pt default, group-scoped, `\setlength`/
`\addtolength`/`\noindent` aware), and `\hfill`/`\hfil` infinite glue.
- Pages: A4/A5/B5/Letter/Legal/Executive, landscape, geometry margins and
text block, automatic pagination, `\newpage`/`\pagebreak`.
text block, geometry-aware `\textwidth`/`\textheight`/`\linewidth`/
`\columnwidth` (as live named length registers), 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,
superscript markers, and title/author `\thanks`.
- Classes/packages: built-in classes, local `.cls`/`.sty`, paper options,
@@ -42,23 +48,24 @@ See `docs/ROADMAP.md` for concrete implementation plans.
- Boxes: `\parbox`/`\minipage` are block-level; `\vbox`/`\vtop` map to a
full-width block rather than true nested VBox material.
- Pages: no floats, no headers/footers (fancyhdr commands are accepted as
no-ops), planner and renderer are separate.
- Pages: float placement is immediate rather than a deferred float queue
(no `\textfraction` tuning, no reordering around later text); planner and
renderer are still separate.
- Notes: footnotes inside captions, floats, or arbitrary boxes are not
collected; the insertion area currently follows the page where the paragraph
ends rather than the exact reference line.
- Lengths: `\textwidth`/`\textheight`/`\linewidth`/`\columnwidth` are fixed
A4-content defaults, not geometry-aware.
- Miscellaneous: `\tableofcontents`/list commands are no-ops; base font-size
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
- `examples/hello.tex`, `examples/boxes.tex`, `examples/compat.tex` compile to
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
examples, the arXiv fixture, SVG/PDF output, project API, static frontend
assets, path traversal, the legacy `/texrra` endpoint, and page-hash cache
stability.
- `cargo fmt --check` passes; `cargo test --offline` (28 tests: 24 compiler
integration tests + 4 server tests) covers the three examples, the arXiv
fixture, floats/newpage, page styles and `\thispagestyle`, SVG/PDF output,
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).
+3 -1
View File
@@ -33,7 +33,7 @@ use document::{
MathDelimiterSettings, MathExpr, MathFontFamilies, MathFontSelection, MathFontStyle,
MathFractionDelimiters, MathFractionStyle, MathInfixFractionKind, MathLimitMode,
MathLineBreakPenalties, MathMuGlue, MathPhantomKind, MathRowSpacing, MathSpacingSettings,
RuleBox, Run,
PAGE_NUMBER_MARKER, PageDecoration, PageDecorationPosition, PageStyleKind, RuleBox, Run,
};
use parser::parse_dimension;
@@ -444,6 +444,7 @@ fn render_html_document(
caption,
alignments,
rules,
..
} => {
html.push_str(&format!(
"<table class=\"texrra-table\"{source_attributes}>"
@@ -482,6 +483,7 @@ fn render_html_document(
path,
options,
caption,
..
} => {
let image_path = PathBuf::from(&path);
let image_path = if image_path.is_absolute() {
+2 -1
View File
@@ -1,4 +1,5 @@
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::*;
+10 -14
View File
@@ -327,8 +327,10 @@ const PRELUDE: &str = r#"
\def\medskip{\vskip6pt}
\def\smallskip{\vskip3pt}
\def\bigskip{\vskip12pt}
\def\textwidth{160mm}
\def\textheight{247mm}
\skipdef\textwidth=126
\textwidth=160mm\relax
\skipdef\textheight=127
\textheight=247mm\relax
\def\linewidth{\textwidth}
\def\columnwidth{\textwidth}
\def\smallbreak{\smallskip}
@@ -350,21 +352,15 @@ const PRELUDE: &str = r#"
\def~{ }
\def\AtBeginDocument#1{#1}
\def\newgeometry#1{\texrrageometry{#1}}
\def\fancyhf{}
\def\fancyheadoffset#1{}
\def\fancyhead#1{}
\def\fancyfoot#1{}
\def\lhead#1{}
\def\chead#1{}
\def\rhead#1{}
\def\lfoot#1{}
\def\cfoot#1{}
\def\rfoot#1{}
\def\lhead#1{\fancyhead[L]{#1}}
\def\chead#1{\fancyhead[C]{#1}}
\def\rhead#1{\fancyhead[R]{#1}}
\def\lfoot#1{\fancyfoot[L]{#1}}
\def\cfoot#1{\fancyfoot[C]{#1}}
\def\rfoot#1{\fancyfoot[R]{#1}}
\def\headrulewidth{0.4pt}
\def\footrulewidth{0pt}
\def\pagestyle#1{}
\def\thispagestyle#1{}
\def\thepage{1}
\def\hypersetup#1{}
\def\microtypesetup#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::{
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},
is_cjk, math_font, math_layout, parse_dimension, prohibits_cjk_line_break, text_layout,
};
@@ -76,6 +77,7 @@ enum PageBlockKey {
path: PathBuf,
options: String,
caption: Option<Vec<Run>>,
placement: String,
fingerprint: u64,
},
Bibliography(Vec<(String, Vec<Run>)>),
@@ -108,6 +110,7 @@ struct PageLayoutConfig {
text_font_fingerprint: u64,
math_font_fingerprint: u64,
math_layout_font_fingerprint: u64,
page_style_fingerprint: u64,
}
struct PageLayoutSnapshot {
@@ -490,6 +493,8 @@ impl PositionedCentered {
struct PositionedPages {
pages: Vec<PositionedPage>,
content_margins: Margins,
left_margin_mm: f64,
next_page: usize,
cjk_family: Option<FontFamily<fonts::Font>>,
mono_family: Option<FontFamily<fonts::Font>>,
@@ -499,12 +504,16 @@ struct PositionedPages {
impl PositionedPages {
fn new(
pages: Vec<PositionedPage>,
content_margins: Margins,
left_margin_mm: f64,
cjk_family: Option<FontFamily<fonts::Font>>,
mono_family: Option<FontFamily<fonts::Font>>,
sans_family: Option<FontFamily<fonts::Font>>,
) -> Self {
Self {
pages,
content_margins,
left_margin_mm,
next_page: 0,
cjk_family,
mono_family,
@@ -526,6 +535,9 @@ impl Element for PositionedPages {
let page_index = self.next_page;
self.next_page += 1;
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;
for item in &mut page.items {
@@ -540,8 +552,20 @@ impl Element for PositionedPages {
let (result, y) = match item {
PositionedPageItem::Line(planned_line) => {
let y = scaled_units_to_mm(planned_line.y);
let mut line_area = area.clone();
line_area.add_offset(Position::new(scaled_units_to_mm(planned_line.x), y));
let is_decoration = planned_line.anchor.block == usize::MAX;
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 {
PositionedLineContent::Text { line, font_size } => {
let text_line = text_layout::TextLine::new(
@@ -568,13 +592,13 @@ impl Element for PositionedPages {
element, style, 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));
(element.render(context, math_area, *style)?, y)
}
PositionedPageItem::Table { element, 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));
(
element.render(
@@ -590,7 +614,7 @@ impl Element for PositionedPages {
}
PositionedPageItem::Image { element, 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));
(
element.render(
@@ -606,7 +630,7 @@ impl Element for PositionedPages {
}
PositionedPageItem::FramedBox { element, 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));
(
element.render(
@@ -622,7 +646,7 @@ impl Element for PositionedPages {
}
PositionedPageItem::Centered { element, 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));
(
element.render(
@@ -642,7 +666,12 @@ impl Element for PositionedPages {
format!(
"Rust page layout placed a {kind} outside its page frame (page {}, y {y:.2}mm, area {:.2}mm)",
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,
));
@@ -2066,12 +2095,7 @@ impl RenderResources {
model.page.height_mm as f32,
));
let mut decorator = genpdf::SimplePageDecorator::new();
decorator.set_margins(Margins::trbl(
model.margins.top,
model.margins.right,
model.margins.bottom,
model.margins.left,
));
decorator.set_margins(Margins::trbl(0.0, 0.0, 0.0, 0.0));
document.set_page_decorator(decorator);
let mono_family = inputs
@@ -2249,6 +2273,13 @@ pub(super) fn render_pdf(
} = resources;
document.push(PositionedPages::new(
pages,
Margins::trbl(
model.margins.top,
model.margins.right,
model.margins.bottom,
model.margins.left,
),
model.margins.left,
cjk_family,
mono_family,
sans_family,
@@ -2474,6 +2505,7 @@ pub(super) fn render_pdf(
caption,
alignments,
rules,
..
} => {
if let Some(caption) = caption {
document.push(
@@ -2505,6 +2537,7 @@ pub(super) fn render_pdf(
path,
options,
caption,
..
} => {
let image_path = PathBuf::from(&path);
let image_path = if image_path.is_absolute() {
+275 -21
View File
@@ -176,6 +176,7 @@ fn page_block_keys(model: &DocumentModel, source_dir: &Path) -> Option<Vec<PageB
caption,
alignments,
rules,
..
} => Some(PageBlockKey::Table {
rows: rows
.iter()
@@ -196,6 +197,7 @@ fn page_block_keys(model: &DocumentModel, source_dir: &Path) -> Option<Vec<PageB
path,
options,
caption,
placement,
} => {
let image_path = resolved_image_path(source_dir, path);
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,
options: options.clone(),
caption: caption.as_deref().map(normalize_page_runs),
placement: placement.clone(),
fingerprint: hasher.finish(),
})
}
@@ -1335,6 +1338,7 @@ pub(super) fn build_page_break_plan(
caption,
alignments,
rules,
..
} => {
pre_display_size = None;
let mut line_index = 0;
@@ -1408,6 +1412,7 @@ pub(super) fn build_page_break_plan(
path,
options,
caption,
..
} => {
pre_display_size = None;
let Some(figure) = layout_figure(
@@ -1540,6 +1545,12 @@ pub(super) fn build_page_break_plan(
text_font_fingerprint: metrics.fingerprint,
math_font_fingerprint: math_metrics.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 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 mut pages = vec![PositionedPage::default()];
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 has_previous_block = false;
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() {
block_start_pages
.entry(block_index)
.or_insert_with(|| pages.len().saturating_sub(1));
match block {
Block::Paragraph(runs) | Block::Heading { runs, .. } => {
let (font_size, is_heading) = match block {
@@ -2420,6 +2435,7 @@ pub(super) fn build_positioned_pages(
caption,
alignments,
rules,
..
} => {
pre_display_size = None;
let mut line_index = 0;
@@ -2562,6 +2578,7 @@ pub(super) fn build_positioned_pages(
path,
options,
caption,
placement,
} => {
pre_display_size = None;
let Some(figure) = layout_figure(
@@ -2591,28 +2608,50 @@ pub(super) fn build_positioned_pages(
line: 0,
};
let block_gap = if has_previous_block { pending_gap } else { 0 };
position_box(
&mut pages,
&mut cursor,
page_breaks,
anchor,
figure_height,
figure_height,
block_gap,
page_goal,
top_skip,
max_depth,
);
pages
.last_mut()
.expect("the page list starts with one page")
.items
.push(PositionedPageItem::Image {
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(
&mut pages,
&mut cursor,
page_breaks,
anchor,
element: figure,
y: cursor,
});
cursor = cursor.saturating_add(figure_height);
figure_height,
figure_height,
block_gap,
page_goal,
top_skip,
max_depth,
);
pages
.last_mut()
.expect("the page list starts with one page")
.items
.push(PositionedPageItem::Image {
anchor,
element: figure,
y: cursor,
});
cursor = cursor.saturating_add(figure_height);
}
pending_gap = paragraph_gap + (normal_line_height as f64 * 0.15).round() as i64;
has_previous_block = true;
}
@@ -2750,6 +2789,10 @@ pub(super) fn build_positioned_pages(
}
Block::Penalty(_) => {}
Block::PageBreak => {
if pages.last().is_some_and(|page| !page.items.is_empty()) {
pages.push(PositionedPage::default());
cursor = 0;
}
pending_gap = 0;
has_previous_block = false;
pre_display_size = None;
@@ -2773,9 +2816,220 @@ pub(super) fn build_positioned_pages(
cache,
);
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)
}
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)]
fn append_vertical_text(
nodes: &mut Vec<VerticalNode>,
+208 -11
View File
@@ -56,6 +56,9 @@ const DEFAULT_JOT: common::Scaled = common::Scaled(3 * 65_536);
/// Index of the `\parindent` skip register defined by the compatibility prelude.
const PARINDENT_REGISTER_INDEX: usize = 100;
/// Indices of the geometry-aware `\textwidth`/`\textheight` skip registers.
const TEXTWIDTH_REGISTER_INDEX: usize = 126;
const TEXTHEIGHT_REGISTER_INDEX: usize = 127;
static PARAGRAPH_BREAK_TAG: texlang::command::StaticTag = texlang::command::StaticTag::new();
static LINE_BREAK_TAG: texlang::command::StaticTag = texlang::command::StaticTag::new();
@@ -515,6 +518,11 @@ struct CompilerState {
edef_tokens: Option<VecDeque<token::Token>>,
#[serde(skip)]
dependencies: Rc<RefCell<Vec<SourceDependency>>>,
/// Live page geometry used by `\textwidth`/`\textheight` expansion.
#[serde(skip)]
geometry_page: texrra_core::document::PageSize,
#[serde(skip)]
geometry_margins: texrra_core::document::PageMargins,
}
struct TexlangInputTrace {
@@ -1687,6 +1695,138 @@ fn page_break_primitive(
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(
input: &mut vm::ExecutionInput<CompilerState>,
) -> texlang::prelude::Result<common::Scaled> {
@@ -4002,11 +4142,9 @@ fn load_document_class(
merged_options.extend(split_options(&text));
}
if !merged_options.is_empty() {
write_event(
input,
token,
FrontendEventKind::Geometry(merged_options.join(",")),
);
let settings = merged_options.join(",");
note_geometry_settings(input, &settings);
write_event(input, token, FrontendEventKind::Geometry(settings));
}
let class_file = format!("{class}.cls");
@@ -4297,11 +4435,9 @@ fn use_package(
if is_builtin_package(package) {
if package == "geometry" && !merged_options.is_empty() {
write_event(
input,
token,
FrontendEventKind::Geometry(merged_options.join(",")),
);
let settings = merged_options.join(",");
note_geometry_settings(input, &settings);
write_event(input, token, FrontendEventKind::Geometry(settings));
}
queue_package_continuation(input, token, command_name, options.as_deref(), remaining);
return Ok(());
@@ -5945,7 +6081,40 @@ fn geometry_primitive(
token: token::Token,
input: &mut vm::ExecutionInput<CompilerState>,
) -> texlang::prelude::Result<()> {
argument_event_primitive(token, input, FrontendEventKind::Geometry)
let settings = read_scanned_token_list(input)?
.into_iter()
.filter_map(|token| token.char())
.collect::<String>()
.trim()
.to_string();
note_geometry_settings(input, &settings);
write_event(input, token, FrontendEventKind::Geometry(settings));
Ok(())
}
fn note_geometry_settings(input: &mut vm::ExecutionInput<CompilerState>, settings: &str) {
let state = input.state_mut();
texrra_core::document_parser::apply_geometry_settings(
&mut state.geometry_page,
&mut state.geometry_margins,
settings,
);
let width =
(state.geometry_page.width_mm - state.geometry_margins.left - state.geometry_margins.right)
.max(0.0);
let height = (state.geometry_page.height_mm
- state.geometry_margins.top
- state.geometry_margins.bottom)
.max(0.0);
set_geometry_register(state, TEXTWIDTH_REGISTER_INDEX, width);
set_geometry_register(state, TEXTHEIGHT_REGISTER_INDEX, height);
}
fn set_geometry_register(state: &mut CompilerState, index: usize, millimetres: f64) {
let register = state.engine.skip_registers.get_index_mut_ref(index);
register.width = common::Scaled((millimetres * 72.27 / 25.4 * 65_536.0).round() as i32);
register.stretch = common::Scaled::ZERO;
register.shrink = common::Scaled::ZERO;
}
fn text_style_argument(
@@ -6572,6 +6741,34 @@ fn built_in_commands() -> HashMap<&'static str, texlang::command::BuiltIn<Compil
texlang::command::BuiltIn::new_execution(page_break_primitive)
.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(
"kern",
texlang::command::BuiltIn::new_execution(kern_primitive)
+22
View File
@@ -284,6 +284,28 @@ impl TextLine {
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 {
let mut spans = Vec::with_capacity(self.items.len());
let mut rules = Vec::new();
+244
View File
@@ -194,6 +194,43 @@ fn text_x(svg: &str, needle: &str) -> f64 {
.unwrap_or_else(|| panic!("text element for `{needle}` has no x coordinate"))
}
fn first_black_rect_width(svg: &str) -> f64 {
for fragment in svg.split("<rect ").skip(1) {
let tag = fragment.split('>').next().unwrap_or(fragment);
if !tag.contains("fill=\"#000000\"") {
continue;
}
let value = tag
.split("width=\"")
.nth(1)
.and_then(|rest| rest.split('"').next())
.and_then(|value| value.parse::<f64>().ok());
if let Some(width) = value {
return width;
}
}
panic!("no filled rectangle in SVG: {svg}");
}
fn max_black_rect_height(svg: &str) -> f64 {
let mut maximum: Option<f64> = None;
for fragment in svg.split("<rect ").skip(1) {
let tag = fragment.split('>').next().unwrap_or(fragment);
if !tag.contains("fill=\"#000000\"") {
continue;
}
let value = tag
.split("height=\"")
.nth(1)
.and_then(|rest| rest.split('"').next())
.and_then(|value| value.parse::<f64>().ok());
if let Some(height) = value {
maximum = Some(maximum.map_or(height, |current| current.max(height)));
}
}
maximum.unwrap_or_else(|| panic!("no filled rectangle in SVG: {svg}"))
}
#[test]
fn paragraph_indent_tracks_setlength_groups_and_noindent() {
let source = r#"\documentclass{article}
@@ -280,6 +317,84 @@ C\hfill D\hfill 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]
fn sans_family_selects_the_sans_face() {
let source = r#"\documentclass{article}
@@ -515,3 +630,132 @@ Body text.
"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"
);
}
#[test]
fn geometry_updates_text_width_and_text_height() {
let source = r#"\documentclass{article}
\geometry{textwidth=100mm,textheight=200mm}
\begin{document}
\noindent\rule{\textwidth}{2pt}
\noindent\rule{2pt}{\textheight}
\end{document}
"#;
let value = fresh_preview(source, "geometry-lengths.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
let width = first_black_rect_width(&svg);
assert!(
(width - 100.0).abs() < 1.0,
"textwidth did not follow geometry: {width}"
);
let height = max_black_rect_height(&svg);
assert!(
(height - 200.0).abs() < 1.0,
"textheight did not follow geometry: {height}"
);
}
#[test]
fn letter_paper_updates_text_width_length() {
let source = r#"\documentclass[letterpaper]{article}
\begin{document}
\noindent\rule{\textwidth}{2pt}
\end{document}
"#;
let value = fresh_preview(source, "letter-lengths.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let width = first_black_rect_width(&page_svg(&value, 0));
assert!(
(width - 165.9).abs() < 1.0,
"letter textwidth is wrong: {width}"
);
}