From 4991bdfcfc494cff7871f62904ded00976b220c8 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Mon, 19 Oct 2026 15:23:13 +0800 Subject: [PATCH] Render arxiv-style preprint title blocks --- README.md | 24 +- crates/texrra-core/src/document.rs | 16 + crates/texrra-core/src/document_parser.rs | 49 ++- crates/texrra-core/src/expanded.rs | 4 + docs/ROADMAP.md | 15 +- docs/STATUS.md | 13 +- src/rust_typeset/frontend.rs | 23 +- src/rust_typeset/math_layout.rs | 1 + src/rust_typeset/pdf.rs | 1 + src/rust_typeset/pdf/layout.rs | 446 +++++++++++++++++++--- src/rust_typeset/texlang_adapter.rs | 22 ++ tests/typeset.rs | 22 ++ 12 files changed, 559 insertions(+), 77 deletions(-) diff --git a/README.md b/README.md index 9a2f5b8..748c0b0 100644 --- a/README.md +++ b/README.md @@ -316,15 +316,19 @@ Base font-size class options `10pt`, `11pt`, and `12pt` now set the body size and propagate through headings, title material, lists, tables, block boxes, footnotes, and the default paragraph indent. The article default is `10pt`, matching LaTeX. -A document-level `\renewcommand{\maketitle}` replaces the engine title block; -class and package files that replace `\maketitle` are ignored so template -title code cannot break the native layout. In particular, the arXiv style -file defines its own box-level `\maketitle`/`\@maketitle` (title rules, -`\undertitle`, author tabular); that block is not executed, so arXiv PDFs use -the native title layout without those pieces. Known gaps for full document -classes: `\parbox`/`\minipage` are block-level rather than inline, and -`\vbox`/`\vtop` capture vertical material but do not form an independent -natural-width box with its own baseline. +A document-level `\renewcommand{\maketitle}` replaces the engine title block. +When a document loads `arxiv.sty`, the engine switches to a native preprint +title style: top/bottom title rules, small-caps title and `\undertitle`, +two-column author blocks with affiliations and monospaced e-mail addresses, +a long date, and `\thispagestyle{empty}` on the first page. Class and package +files that replace `\maketitle` itself are still ignored, so box-level +template code cannot break the native layout. Ordinary text is now placed on +a TeX baseline grid (1.2em line height, 0.8em ascent) instead of the fallback +TrueType font's larger ascent/descent, which matches LaTeX line spacing and +page breaks. Known gaps for full document classes: `\parbox`/`\minipage` are +block-level rather than inline, and `\vbox`/`\vtop` capture vertical +material but do not form an independent natural-width box with its own +baseline. `\footnote{...}` captures its content, emits a superscript marker, reserves space on the page where the paragraph ends, and paints the notes with a @@ -502,7 +506,7 @@ advisory breaks, starred `\vspace`/`\hspace`, `center`, `\hrule`, `\fbox`, | Notes/floats | footnotes with page-bottom insertion area, title/author `\thanks`, figure `[htbp]` placement (deferred top floats, bottom/page/here), table `[t]`/`[b]`/`[p]` placement | table float-page queues, `\textfraction` | | Contents | `\tableofcontents`, `\listoffigures`, `\listoftables` generated from numbered headings and captions, dotted leaders, page numbers resolved after pagination | per-chapter book/report contents | | Pages | A4/Letter/... page sizes, margins/geometry, automatic pagination, `\newpage`, `\pagebreak`, plain/fancy page styles, `\thispagestyle`, fancyhdr L/C/R headers and footers | — | -| Classes/packages | built-in + local classes, option protocol, local package options, base font sizes 10/11/12pt, chapter headings and numbering, chapter page breaks, document-level custom `\maketitle` | class-specific formatting beyond chapter breaks | +| Classes/packages | built-in + local classes, option protocol, local package options, base font sizes 10/11/12pt, chapter headings and numbering, chapter page breaks, document-level custom `\maketitle`, native arxiv-style preprint title blocks (rules, `\undertitle`, author columns, long date) | class-specific formatting beyond chapter breaks | | Live preview | incremental paragraph cache, page-hash diffing, SVG refresh | — | The compatibility layer also covers spacing macros, text symbols/letters, style diff --git a/crates/texrra-core/src/document.rs b/crates/texrra-core/src/document.rs index 4dbacc0..d665e31 100644 --- a/crates/texrra-core/src/document.rs +++ b/crates/texrra-core/src/document.rs @@ -55,6 +55,16 @@ impl Default for PageSize { } } +/// Layout style for the document title block. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum TitleStyle { + /// The generic article title: title, author, date, no rules. + #[default] + Article, + /// Preprint-style title block with rules, an undertitle, and author columns. + Preprint, +} + #[derive(Clone)] pub struct Footnote { pub number: u32, @@ -66,6 +76,10 @@ pub struct DocumentModel { pub title: String, pub author: String, pub date: String, + /// Style selected by the document's class/package layer. + pub title_style: TitleStyle, + /// Optional line printed under the title rules, e.g. "A Preprint". + pub undertitle: Option, pub page: PageSize, pub parindent: common::Scaled, /// Base font size selected by the document class (10, 11, or 12pt). @@ -87,6 +101,8 @@ impl Default for DocumentModel { title: String::new(), author: String::new(), date: String::new(), + title_style: TitleStyle::default(), + undertitle: None, page: PageSize::default(), // article's default \parindent for 10/11pt text. parindent: common::Scaled(17 * 65_536), diff --git a/crates/texrra-core/src/document_parser.rs b/crates/texrra-core/src/document_parser.rs index 3a1e6cc..782f10e 100644 --- a/crates/texrra-core/src/document_parser.rs +++ b/crates/texrra-core/src/document_parser.rs @@ -4,8 +4,8 @@ use crate::{ TeXGlue, TeXGlueOrder, document::{ Block, ColumnAlignment, DocumentModel, EquationNumber, InlineBox, InlineBoxAlign, - ListBlock, ListItem, PageMargins, PageSize, PageStyleOverride, ParagraphAlignment, - ParsedDocument, RuleBox, Run, UnresolvedReference, + ListBlock, ListItem, PageMargins, PageSize, PageStyleKind, PageStyleOverride, + ParagraphAlignment, ParsedDocument, RuleBox, Run, TitleStyle, UnresolvedReference, }, expanded, math_expr::*, @@ -942,6 +942,30 @@ impl Parser { expanded::FrontendEventKind::MetadataEnd(field) => { self.finish_metadata(*field); } + expanded::FrontendEventKind::PackageLoaded(package) => { + if package == "arxiv" { + self.document.title_style = TitleStyle::Preprint; + if self.document.undertitle.is_none() { + self.document.undertitle = Some("A Preprint".to_string()); + } + if !self + .document + .page_style_overrides + .iter() + .any(|override_| override_.anchor == 0) + { + self.document.page_style_overrides.push(PageStyleOverride { + anchor: 0, + kind: PageStyleKind::Empty, + }); + } + } + } + expanded::FrontendEventKind::MetadataSeparator => { + if self.metadata_capture.is_some() { + self.append_text("\u{F7001}"); + } + } expanded::FrontendEventKind::Geometry(settings) => { apply_class_font_size(&mut self.document, settings); apply_geometry(&mut self.document, settings); @@ -1067,10 +1091,18 @@ impl Parser { expanded::FrontendEventKind::LiteralCharacter(character) => { self.append_text(&character.to_string()) } - expanded::FrontendEventKind::LineBreak => self.append_text(" "), + expanded::FrontendEventKind::LineBreak => { + if self.metadata_capture.is_some() { + self.append_metadata_line_break(); + } else { + self.append_text(" "); + } + } expanded::FrontendEventKind::RowBreak => { if self.table.is_some() { self.finish_table_row(); + } else if self.metadata_capture.is_some() { + self.append_metadata_line_break(); } else { self.append_text(" "); } @@ -1339,6 +1371,17 @@ impl Parser { } } + fn append_metadata_line_break(&mut self) { + let Some((_, runs)) = &mut self.metadata_capture else { + return; + }; + if let Some(last) = runs.last_mut() { + last.text.push('\n'); + } else { + runs.push(Run::plain("\n".to_string())); + } + } + fn append_text(&mut self, text: &str) { if normalize_whitespace(text).is_empty() { return; diff --git a/crates/texrra-core/src/expanded.rs b/crates/texrra-core/src/expanded.rs index d58b94b..8bcdd0c 100644 --- a/crates/texrra-core/src/expanded.rs +++ b/crates/texrra-core/src/expanded.rs @@ -248,6 +248,10 @@ pub enum FrontendEventKind { header: bool, }, PageNumber, + /// A package or class was loaded from a local file. + PackageLoaded(String), + /// A separator between author blocks (LaTeX's \And). + MetadataSeparator, ParagraphAlignment(crate::document::ParagraphAlignment), TableOfContents, ListOfFigures, diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 7db50ff..50b6eab 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -25,16 +25,13 @@ planner remains). work: queue table float-page placements, tune `\textfraction`/`\topfraction`, and support more than a one-page lookahead. -## 2. Class title blocks +## 2. Class title blocks (implemented for arXiv-style preprints) -- A document-level `\renewcommand{\maketitle}` already works. Class/package - title code is still ignored; the arXiv style replaces both `\maketitle` and - `\@maketitle` with box-level TeX (title rules, `\undertitle`, author - tabular, `\thispagestyle{empty}`). Supporting it generally requires running - style-origin layout commands or modelling their semantic pieces (title, - subtitle, author blocks, affiliations, date, abstract heading) as data. -- Until then, arXiv PDFs use the native title block and page 1 uses `plain` - (no fancy header) but still shows the page number. +- A document-level `\renewcommand{\maketitle}` works, and loading `arxiv.sty` + switches to a native preprint title block: title rules, small-caps title, + `\undertitle`, two-column author/affiliation blocks, long date, and an empty + first page style. Remaining work is class-specific variation beyond this + style (for example other journal templates with different author grids). ## 3. True vertical boxes (partial) diff --git a/docs/STATUS.md b/docs/STATUS.md index 8bd7b19..142e7f8 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -50,10 +50,13 @@ the source changes; the SVG preview is refreshed per page. headings, title material, lists, tables, block boxes, footnotes, and the default paragraph indent (10/12pt use 15pt; 11pt uses 17pt). - Title blocks: a document-level `\renewcommand{\maketitle}` replaces the - engine title layout and can use `\@title`/`\@author`/`\@date`; class and - package replacements are ignored so template title code keeps using the - native layout. The arXiv style's box-level `\maketitle`/`\@maketitle` - (title rules, `\undertitle`, author tabular) is therefore not applied. + engine title layout and can use `\@title`/`\@author`/`\@date`. Loading + `arxiv.sty` selects a native preprint title style (rules, small-caps title, + `\undertitle`, two-column author/affiliation blocks, long date, empty first + page style), so arXiv PDFs no longer fall back to the plain article title. + Class/package replacements of `\maketitle` itself remain ignored. +- Line spacing: ordinary text lines use a TeX baseline grid (1.2em height, + 0.8em ascent); boxes/rules keep their measured vertical metrics. - Classes/packages: built-in classes, local `.cls`/`.sty`, paper options, `\DeclareOption`/`\ProcessOptions`/`\ExecuteOptions`/option passing. - Compatibility: spacing macros (quad/qquad/thin/en/med/thick, `\vspace*`, @@ -87,7 +90,7 @@ See `docs/ROADMAP.md` for concrete implementation plans. - `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 --offline` (41 tests: 37 compiler +- `cargo fmt --check` passes; `cargo test --offline` (42 tests: 38 compiler integration tests + 4 server tests) covers the three examples, the arXiv fixture, figure/table floats (top and bottom), newpage, page styles and `\thispagestyle`, SVG/PDF output, project API, static frontend assets, path traversal, the legacy diff --git a/src/rust_typeset/frontend.rs b/src/rust_typeset/frontend.rs index 61299bb..d5e00dc 100644 --- a/src/rust_typeset/frontend.rs +++ b/src/rust_typeset/frontend.rs @@ -450,8 +450,8 @@ const PRELUDE: &str = r#" \def\dots{...} \def\textellipsis{...} \def\and{ } -\def\And{ } -\def\AND{ } +\def\And{\texrraauthorseparator} +\def\AND{\texrraauthorseparator} \def\ifhmode{\iftrue} \def\paragraph#1{\par\texrraheadingstart{3}#1\texrraheadingend\par} \def\subparagraph#1{\par\texrraheadingstart{3}#1\texrraheadingend\par} @@ -645,7 +645,7 @@ fn preprocess_latex(source: &str, source_path: &Path) -> Result String { +pub(crate) fn current_date_utc() -> String { let days = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap_or_default() @@ -666,7 +666,22 @@ fn current_date_utc() -> String { let day = day_of_year - (153 * month_part + 2) / 5 + 1; let month = month_part + if month_part < 10 { 3 } else { -9 }; year += i64::from(month <= 2); - format!("{year:04}-{month:02}-{day:02}") + const MONTHS: [&str; 12] = [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December", + ]; + let month_name = MONTHS[(month.clamp(1, 12) - 1) as usize]; + format!("{month_name} {day}, {year}") } pub(super) fn can_cache_frontend_snapshot(source: &str) -> bool { diff --git a/src/rust_typeset/math_layout.rs b/src/rust_typeset/math_layout.rs index cbe73c7..e441c90 100644 --- a/src/rust_typeset/math_layout.rs +++ b/src/rust_typeset/math_layout.rs @@ -913,6 +913,7 @@ struct InlineMathLine { pre_display_size: Option, } +#[derive(Clone)] pub(super) struct InlineMathLineElement { line: InlineMathLine, alignment: Alignment, diff --git a/src/rust_typeset/pdf.rs b/src/rust_typeset/pdf.rs index 8c7a900..dd4ca0a 100644 --- a/src/rust_typeset/pdf.rs +++ b/src/rust_typeset/pdf.rs @@ -65,6 +65,7 @@ struct PageBreakPlan { breaks: HashSet, } +#[derive(Clone)] enum PositionedLineContent { Text { line: text_layout::LineBox, diff --git a/src/rust_typeset/pdf/layout.rs b/src/rust_typeset/pdf/layout.rs index 90658dc..b9eb6c0 100644 --- a/src/rust_typeset/pdf/layout.rs +++ b/src/rust_typeset/pdf/layout.rs @@ -1,5 +1,5 @@ use super::*; -use texrra_core::document::{ParagraphAlignment, UnresolvedReference}; +use texrra_core::document::{ParagraphAlignment, TitleStyle, UnresolvedReference}; const ARTICLE_11PT_LIST_TOPSEP_PT: f64 = 9.0; const ARTICLE_11PT_LIST_TOPSEP_STRETCH_PT: f64 = 3.0; @@ -1331,6 +1331,125 @@ fn resolve_toc_page_numbers( changed.then_some(resolved) } +#[allow(clippy::too_many_arguments)] +fn push_title_line( + pages: &mut Vec, + deferred: &mut Vec, + cursor: &mut i64, + page_breaks: &HashSet, + page_goal: i64, + top_skip: i64, + max_depth: i64, + line: MeasuredLine, + x: i64, + centered: bool, +) { + let anchor = PageAnchor { + block: usize::MAX, + line: line.line_index, + }; + position_box( + pages, + deferred, + cursor, + page_breaks, + anchor, + line.height, + line.ascent, + line.leading_before, + page_goal, + top_skip, + max_depth, + ); + let y = *cursor; + pages + .last_mut() + .expect("the page list starts with one page") + .items + .push(PositionedPageItem::Line(PositionedLine { + anchor, + content: line.content, + y, + x, + centered, + ragged: false, + })); + *cursor = cursor.saturating_add(line.height); +} + +#[allow(clippy::too_many_arguments)] +fn push_title_rule( + pages: &mut Vec, + deferred: &mut Vec, + cursor: &mut i64, + page_breaks: &HashSet, + page_goal: i64, + top_skip: i64, + max_depth: i64, + width: i64, + height: i64, +) { + let anchor = PageAnchor { + block: usize::MAX, + line: 0, + }; + position_box( + pages, + deferred, + cursor, + page_breaks, + anchor, + height, + height, + 0, + page_goal, + top_skip, + max_depth, + ); + let line = text_layout::LineBox { + width: common::Scaled(width as i32), + items: vec![text_layout::LineItem::Rule { + width: common::Scaled(width as i32), + raise: common::Scaled::ZERO, + height: common::Scaled(height as i32), + y_offset: common::Scaled::ZERO, + }], + pre_display_size: None, + }; + pages + .last_mut() + .expect("the page list starts with one page") + .items + .push(PositionedPageItem::Line(PositionedLine { + anchor, + content: PositionedLineContent::Text { + line, + font_size: 10, + }, + y: *cursor, + x: 0, + centered: false, + ragged: false, + })); + *cursor = cursor.saturating_add(height); +} + +fn title_line_natural_width( + content: &PositionedLineContent, + font_cache: &fonts::FontCache, + cjk_family: Option>, + mono_family: Option>, + sans_family: Option>, +) -> f64 { + match content { + PositionedLineContent::Text { line, font_size } => { + text_layout::TextLine::new(line, cjk_family, mono_family, sans_family, *font_size) + .natural_width_mm(font_cache) + } + PositionedLineContent::InlineMath(_) => 0.0, + } +} + pub(super) fn build_positioned_pages( model: &DocumentModel, source_dir: &Path, @@ -1369,59 +1488,279 @@ pub(super) fn build_positioned_pages( let mut pre_display_size = None; if model.show_title { - for (text, font_size, bold) in [ - (&model.title, base_font_size + 9, true), - (&model.author, base_font_size + 1, false), - (&model.date, base_font_size, false), - ] { - if text.is_empty() { - continue; + match model.title_style { + TitleStyle::Article => { + for (text, font_size, bold) in [ + (&model.title, base_font_size + 9, true), + (&model.author, base_font_size + 1, false), + (&model.date, base_font_size, false), + ] { + if text.is_empty() { + continue; + } + let mut run = Run::plain(text.clone()); + run.bold = bold; + for line in measure_positioned_lines( + &[run], + font_size, + content_width_mm, + metrics, + font_cache, + cjk_family, + mono_family, + sans_family, + math_metrics, + math_layout, + cache, + ) { + push_title_line( + &mut pages, + &mut deferred, + &mut cursor, + page_breaks, + page_goal, + top_skip, + max_depth, + line, + 0, + true, + ); + } + } } - let mut run = Run::plain(text.clone()); - run.bold = bold; - for line in measure_positioned_lines( - &[run], - font_size, - content_width_mm, - metrics, - font_cache, - cjk_family, - mono_family, - sans_family, - math_metrics, - math_layout, - cache, - ) { - let anchor = PageAnchor { - block: usize::MAX, - line: line.line_index, - }; - position_box( + TitleStyle::Preprint => { + let rule_width = millimeters_to_scaled(content_width_mm); + let rule_height = i64::from(scaled_points(2.0).0).max(1); + let mut title_run = Run::plain(model.title.clone()); + title_run.bold = true; + title_run.small_caps = true; + push_title_rule( &mut pages, &mut deferred, &mut cursor, page_breaks, - anchor, - line.height, - line.ascent, - line.leading_before, page_goal, top_skip, max_depth, + rule_width, + rule_height, ); - pages - .last_mut() - .expect("the page list starts with one page") - .items - .push(PositionedPageItem::Line(PositionedLine { - anchor, - content: line.content, - y: cursor, - x: 0, - centered: true, - ragged: false, - })); - cursor = cursor.saturating_add(line.height); + cursor = cursor.saturating_add(millimeters_to_scaled(6.35)); + for line in measure_positioned_lines( + &[title_run], + base_font_size + 7, + content_width_mm, + metrics, + font_cache, + cjk_family, + mono_family, + sans_family, + math_metrics, + math_layout, + cache, + ) { + push_title_line( + &mut pages, + &mut deferred, + &mut cursor, + page_breaks, + page_goal, + top_skip, + max_depth, + line, + 0, + true, + ); + } + cursor = cursor.saturating_add(millimeters_to_scaled(1.0)); + push_title_rule( + &mut pages, + &mut deferred, + &mut cursor, + page_breaks, + page_goal, + top_skip, + max_depth, + rule_width, + rule_height, + ); + cursor = cursor.saturating_add(millimeters_to_scaled(2.29)); + let undertitle = model.undertitle.clone().unwrap_or_default(); + if !undertitle.is_empty() { + let mut run = Run::plain(undertitle); + run.small_caps = true; + for line in measure_positioned_lines( + &[run], + base_font_size + 2, + content_width_mm, + metrics, + font_cache, + cjk_family, + mono_family, + sans_family, + math_metrics, + math_layout, + cache, + ) { + push_title_line( + &mut pages, + &mut deferred, + &mut cursor, + page_breaks, + page_goal, + top_skip, + max_depth, + line, + 0, + true, + ); + } + } + cursor = cursor.saturating_add(millimeters_to_scaled(2.54)); + let blocks = model + .author + .split('\u{F7001}') + .map(|block| { + block + .split('\n') + .map(str::trim) + .filter(|line| !line.is_empty()) + .map(str::to_string) + .collect::>() + }) + .filter(|lines| !lines.is_empty()) + .collect::>(); + if !blocks.is_empty() { + let column_count = blocks.len(); + let column_width = content_width_mm / column_count as f64; + let mut measured_blocks = Vec::with_capacity(column_count); + for lines in &blocks { + let mut measured_lines = Vec::with_capacity(lines.len()); + for (index, text) in lines.iter().enumerate() { + let mut run = Run::plain(text.clone()); + if index == 0 { + run.bold = true; + } + if text.contains('@') && !text.contains(' ') { + run.monospace = true; + } + if let Some(line) = measure_positioned_lines( + &[run], + base_font_size, + column_width - 2.0, + metrics, + font_cache, + cjk_family, + mono_family, + sans_family, + math_metrics, + math_layout, + cache, + ) + .into_iter() + .next() + { + measured_lines.push(line); + } + } + measured_blocks.push(measured_lines); + } + let row_count = measured_blocks.iter().map(Vec::len).max().unwrap_or(0); + for row in 0..row_count { + let mut row_height = 0; + let mut row_ascent = 0; + for block in &measured_blocks { + if let Some(line) = block.get(row) { + row_height = row_height.max(line.height); + row_ascent = row_ascent.max(line.ascent); + } + } + if row_height == 0 { + continue; + } + let anchor = PageAnchor { + block: usize::MAX, + line: 0, + }; + position_box( + &mut pages, + &mut deferred, + &mut cursor, + page_breaks, + anchor, + row_height, + row_ascent, + 0, + page_goal, + top_skip, + max_depth, + ); + let y = cursor; + for (column, block) in measured_blocks.iter().enumerate() { + let Some(line) = block.get(row) else { + continue; + }; + let natural_width = title_line_natural_width( + &line.content, + font_cache, + cjk_family, + mono_family, + sans_family, + ); + let column_start = column as f64 * column_width; + let x = millimeters_to_scaled( + column_start + (column_width - natural_width).max(0.0) / 2.0, + ); + pages + .last_mut() + .expect("the page list starts with one page") + .items + .push(PositionedPageItem::Line(PositionedLine { + anchor, + content: line.content.clone(), + y, + x, + centered: false, + ragged: false, + })); + } + cursor = cursor.saturating_add(row_height); + } + } + cursor = cursor.saturating_add(millimeters_to_scaled(6.0)); + let date = if model.date.is_empty() { + crate::rust_typeset::frontend::current_date_utc() + } else { + model.date.clone() + }; + if !date.is_empty() { + for line in measure_positioned_lines( + &[Run::plain(date)], + base_font_size, + content_width_mm, + metrics, + font_cache, + cjk_family, + mono_family, + sans_family, + math_metrics, + math_layout, + cache, + ) { + push_title_line( + &mut pages, + &mut deferred, + &mut cursor, + page_breaks, + page_goal, + top_skip, + max_depth, + line, + 0, + true, + ); + } + } } } cursor = cursor.saturating_add(normal_line_height); @@ -2654,11 +2993,18 @@ pub(super) fn text_line_metrics_scaled( cjk_family: Option>, mono_family: Option>, sans_family: Option>, - _font_size: u8, + font_size: u8, ) -> (i64, i64) { let mut ascent_mm = Mm::from(0.0); let mut descent_mm = Mm::from(0.0); + let mut has_box_material = false; for item in &line.items { + if matches!( + item, + text_layout::LineItem::Frame { .. } | text_layout::LineItem::Rule { .. } + ) { + has_box_material = true; + } if let text_layout::LineItem::Frame { ascent, depth, @@ -2737,6 +3083,14 @@ pub(super) fn text_line_metrics_scaled( descent_mm = descent_mm .max((style.line_height(font_cache) - glyph_height - y_offset).max(Mm::from(0.0))); } + if !has_box_material { + // TeX places ordinary text on a baseline grid: 10pt text uses 12pt + // baseline distance, rather than the much larger line box advertised + // by the fallback TrueType font's ascent/descent. + let grid_height = i64::from(scaled_points(f64::from(font_size) * 1.2).0); + let grid_ascent = i64::from(scaled_points(f64::from(font_size) * 0.8).0); + return (grid_ascent, grid_height.saturating_sub(grid_ascent)); + } let ascent = i64::from(scaled_points(f64::from(ascent_mm) * PDF_POINTS_PER_INCH / 25.4).0); let height = i64::from(scaled_points(f64::from(ascent_mm + descent_mm) * PDF_POINTS_PER_INCH / 25.4).0) diff --git a/src/rust_typeset/texlang_adapter.rs b/src/rust_typeset/texlang_adapter.rs index 5186670..bf375cb 100644 --- a/src/rust_typeset/texlang_adapter.rs +++ b/src/rust_typeset/texlang_adapter.rs @@ -2130,6 +2130,14 @@ fn metadata_value_primitive( Ok(()) } +fn metadata_separator_primitive( + token: token::Token, + input: &mut vm::ExecutionInput, +) -> texlang::prelude::Result<()> { + write_event(input, token, FrontendEventKind::MetadataSeparator); + Ok(()) +} + fn metadata_start_primitive( token: token::Token, input: &mut vm::ExecutionInput, @@ -4275,6 +4283,11 @@ fn load_document_class( )) })?; input.state_mut().loaded_styles.insert(path.clone()); + write_event( + input, + token, + FrontendEventKind::PackageLoaded(class.clone()), + ); SourceDependency::record( &mut input.state_mut().dependencies.borrow_mut(), &path, @@ -4565,6 +4578,11 @@ fn use_package( )) })?; input.state_mut().loaded_styles.insert(path.clone()); + write_event( + input, + token, + FrontendEventKind::PackageLoaded(package.clone()), + ); SourceDependency::record( &mut input.state_mut().dependencies.borrow_mut(), &path, @@ -6985,6 +7003,10 @@ fn built_in_commands() -> HashMap<&'static str, texlang::command::BuiltIn= 2, "title rules missing: {rule_count}"); + assert!( + first_page.contains("font-size=\"4.9389\""), + "small-caps title glyphs missing" + ); } #[test]