From 466abd4ce6c31002597af5b570ef9a77ffcd768a Mon Sep 17 00:00:00 2001 From: GloamXun Date: Tue, 20 Oct 2026 01:08:37 +0800 Subject: [PATCH] Build structured journal front matter for sn-jnl --- README.md | 7 + crates/texrra-core/src/document.rs | 34 +++ crates/texrra-core/src/document_parser.rs | 109 ++++++++- crates/texrra-core/src/expanded.rs | 16 ++ docs/ROADMAP.md | 6 +- docs/STATUS.md | 5 +- src/rust_typeset/frontend.rs | 2 - src/rust_typeset/pdf/layout.rs | 257 ++++++++++++++++++++++ src/rust_typeset/texlang_adapter.rs | 216 ++++++++++++++++++ tests/typeset.rs | 39 +++- 10 files changed, 684 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 0111036..f770f8d 100644 --- a/README.md +++ b/README.md @@ -323,6 +323,13 @@ 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. +Journal classes that distribute front matter through commands such as +`\author`, `\affil`, `\abstract`, and `\keywords` are captured as structured +metadata. The `sn-jnl` class then renders a journal title block: centered title, +numbered author lines with affiliation marks, affiliation list, e-mail line, +abstract, and keywords. Class-internal `\maketitle` layout is still not +executed; the engine builds the block from the captured metadata. + When a document loads `arxiv.sty`, the engine switches to a native preprint title style: top/bottom title rules, small-caps title with inline emphasis preserved (e.g. the italic `arxiv` in the class example), `\undertitle`, diff --git a/crates/texrra-core/src/document.rs b/crates/texrra-core/src/document.rs index c6c6e61..fefa999 100644 --- a/crates/texrra-core/src/document.rs +++ b/crates/texrra-core/src/document.rs @@ -63,6 +63,25 @@ pub enum TitleStyle { Article, /// Preprint-style title block with rules, an undertitle, and author columns. Preprint, + /// Journal-style title block: title, author/affiliation columns, abstract, + /// and keywords. + Journal, +} + +/// One author block in a structured front matter. +#[derive(Clone, Default, PartialEq, Eq)] +pub struct AuthorBlock { + pub runs: Vec, + /// One-based affiliation indices attached to this author. + pub affiliations: Vec, + pub email: Option, +} + +/// One numbered affiliation in a structured front matter. +#[derive(Clone, Default, PartialEq, Eq)] +pub struct Affiliation { + pub index: usize, + pub runs: Vec, } #[derive(Clone, Debug, Default, PartialEq, Eq)] @@ -88,6 +107,16 @@ pub struct DocumentModel { pub title_style: TitleStyle, /// Optional line printed under the title rules, e.g. "A Preprint". pub undertitle: Option, + /// Short title from `\title[short]{long}`. + pub short_title: Option, + /// Structured author blocks from `\author` / `\affil` / `\email`. + pub authors: Vec, + /// Numbered affiliations from `\affil[n]{...}`. + pub affiliations: Vec, + /// Body of `\abstract{...}` captured for journal title blocks. + pub abstract_runs: Vec, + /// Body of `\keywords{...}` captured for journal title blocks. + pub keywords: Vec, pub page: PageSize, pub parindent: common::Scaled, /// Base font size selected by the document class (10, 11, or 12pt). @@ -120,6 +149,11 @@ impl Default for DocumentModel { date: String::new(), title_style: TitleStyle::default(), undertitle: None, + short_title: None, + authors: Vec::new(), + affiliations: Vec::new(), + abstract_runs: Vec::new(), + keywords: Vec::new(), 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 6486a39..64c4d91 100644 --- a/crates/texrra-core/src/document_parser.rs +++ b/crates/texrra-core/src/document_parser.rs @@ -478,6 +478,12 @@ struct Parser { pending_table_caption: Option>, caption_capture: Option>, metadata_capture: Option<(expanded::MetadataField, Vec)>, + author_affiliations: Vec, + pending_author_email: Option, + email_capture: Option>, + affiliation_capture: Option<(usize, Vec)>, + abstract_capture: Option>, + keywords_capture: Option>, framed_box: Option>, box_frame: bool, box_width: Option, @@ -590,6 +596,12 @@ impl Parser { pending_table_caption: None, caption_capture: None, metadata_capture: None, + author_affiliations: Vec::new(), + pending_author_email: None, + email_capture: None, + affiliation_capture: None, + abstract_capture: None, + keywords_capture: None, framed_box: None, box_frame: true, box_width: None, @@ -787,7 +799,16 @@ impl Parser { self.document.title = value; self.document.title_runs = runs; } - expanded::MetadataField::Author => self.document.author = value, + expanded::MetadataField::Author => { + self.document.author = value; + let affiliations = std::mem::take(&mut self.author_affiliations); + let email = self.pending_author_email.take(); + self.document.authors.push(crate::document::AuthorBlock { + runs, + affiliations, + email, + }); + } expanded::MetadataField::Date => self.document.date = value, } } @@ -1006,6 +1027,9 @@ impl Parser { self.finish_metadata(*field); } expanded::FrontendEventKind::PackageLoaded(package) => { + if package == "sn-jnl" { + self.document.title_style = TitleStyle::Journal; + } if package == "arxiv" { self.document.title_style = TitleStyle::Preprint; self.document.author_year_citations = true; @@ -1030,6 +1054,60 @@ impl Parser { self.append_text("\u{F7001}"); } } + expanded::FrontendEventKind::MetadataShortTitle(short) => { + self.document.short_title = Some(short.clone()); + } + expanded::FrontendEventKind::AuthorAffiliations(indices) => { + self.author_affiliations = indices.clone(); + } + expanded::FrontendEventKind::MetadataEmailStart => { + self.email_capture = Some(Vec::new()); + } + expanded::FrontendEventKind::MetadataEmailEnd => { + if let Some(mut runs) = self.email_capture.take() { + trim_run_end(&mut runs); + let email = runs.iter().map(|run| run.text.as_str()).collect::(); + self.pending_author_email = Some(email); + } + } + expanded::FrontendEventKind::AffiliationStart(index) => { + if self.document.title_style == TitleStyle::Article { + self.document.title_style = TitleStyle::Journal; + } + self.affiliation_capture = Some((*index, Vec::new())); + } + expanded::FrontendEventKind::AffiliationEnd => { + if let Some((index, mut runs)) = self.affiliation_capture.take() { + trim_run_end(&mut runs); + self.document + .affiliations + .push(crate::document::Affiliation { index, runs }); + } + } + expanded::FrontendEventKind::AbstractStart => { + if self.document.title_style == TitleStyle::Article { + self.document.title_style = TitleStyle::Journal; + } + self.abstract_capture = Some(Vec::new()); + } + expanded::FrontendEventKind::AbstractEnd => { + if let Some(mut runs) = self.abstract_capture.take() { + trim_run_end(&mut runs); + self.document.abstract_runs = runs; + } + } + expanded::FrontendEventKind::KeywordsStart => { + if self.document.title_style == TitleStyle::Article { + self.document.title_style = TitleStyle::Journal; + } + self.keywords_capture = Some(Vec::new()); + } + expanded::FrontendEventKind::KeywordsEnd => { + if let Some(mut runs) = self.keywords_capture.take() { + trim_run_end(&mut runs); + self.document.keywords = runs; + } + } expanded::FrontendEventKind::Geometry(settings) => { apply_class_font_size(&mut self.document, settings); apply_geometry(&mut self.document, settings); @@ -1749,6 +1827,31 @@ impl Parser { .expect("page decoration capture was checked") .2; } + if self.email_capture.is_some() { + return self + .email_capture + .as_mut() + .expect("email capture was checked"); + } + if self.affiliation_capture.is_some() { + return &mut self + .affiliation_capture + .as_mut() + .expect("affiliation capture was checked") + .1; + } + if self.abstract_capture.is_some() { + return self + .abstract_capture + .as_mut() + .expect("abstract capture was checked"); + } + if self.keywords_capture.is_some() { + return self + .keywords_capture + .as_mut() + .expect("keywords capture was checked"); + } if self.footnote_capture.is_some() { return self .footnote_capture @@ -1764,6 +1867,10 @@ impl Parser { && self.centered.is_none() && self.framed_box.is_none() && self.metadata_capture.is_none() + && self.email_capture.is_none() + && self.affiliation_capture.is_none() + && self.abstract_capture.is_none() + && self.keywords_capture.is_none() && self.page_decoration_capture.is_none() && self.caption_capture.is_none() && self.heading.is_none() diff --git a/crates/texrra-core/src/expanded.rs b/crates/texrra-core/src/expanded.rs index 6d34a8a..f8f1a97 100644 --- a/crates/texrra-core/src/expanded.rs +++ b/crates/texrra-core/src/expanded.rs @@ -277,6 +277,22 @@ pub enum FrontendEventKind { PackageLoaded(String), /// A separator between author blocks (LaTeX's \And). MetadataSeparator, + /// Short title from the optional argument of `\title[short]{long}`. + MetadataShortTitle(String), + /// Affiliation indices from the optional argument of `\author[1,2]{...}`. + AuthorAffiliations(Vec), + /// Start of an `\affil[n]{...}` body. + AffiliationStart(usize), + AffiliationEnd, + /// Start/end of an `\abstract{...}` body captured for the title block. + AbstractStart, + AbstractEnd, + /// Start/end of a `\keywords{...}` body. + KeywordsStart, + KeywordsEnd, + /// Start/end of the e-mail address inside an author block. + MetadataEmailStart, + MetadataEmailEnd, ParagraphAlignment(crate::document::ParagraphAlignment), TableOfContents, ListOfFigures, diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 36d8401..d536db1 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -37,8 +37,10 @@ captions with the insertion area reserved on the caption page. - 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). + first page style. Loading `sn-jnl` selects a structured journal title block + with numbered authors, affiliations, e-mail, abstract, and keywords. + Remaining work: two-column body layout (`iicol`), exact journal title + spacing, and class-specific author grids. ## 3. True vertical boxes (partial) diff --git a/docs/STATUS.md b/docs/STATUS.md index 611af8e..d14788e 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -57,6 +57,9 @@ the source changes; the SVG preview is refreshed per page. `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. + Loading `sn-jnl` selects a structured journal title style built from + `\author`/`\affil`/`\abstract`/`\keywords` metadata: centered title, + numbered authors and affiliations, e-mail line, abstract, and keywords. 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. @@ -126,7 +129,7 @@ See `docs/ROADMAP.md` for concrete implementation plans. 0.29 MB and `pdffonts` reports only embedded CID TrueType faces); this avoids viewer-dependent glyph substitution. Tables use natural column widths and centered rules; preview and PDF share the same table line coordinates. -- `cargo fmt --check` passes; `cargo test --offline` (71 tests: 67 compiler +- `cargo fmt --check` passes; `cargo test --offline` (72 tests: 68 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 ce5c038..37a896f 100644 --- a/src/rust_typeset/frontend.rs +++ b/src/rust_typeset/frontend.rs @@ -19,8 +19,6 @@ const PRELUDE: &str = r#" \def\geometry#1{\texrrageometry{#1}} \def\begin#1{\texrrabegin{#1}} \def\end#1{\texrraend{#1}} -\def\title#1{\texrrametadatastart{title}#1\texrrametadataend{title}} -\def\author#1{\texrrametadatastart{author}#1\texrrametadataend{author}} \def\date#1{\texrrametadatastart{date}#1\texrrametadataend{date}} \def\@title{\texrrametadatatitle} \def\@author{\texrrametadataauthor} diff --git a/src/rust_typeset/pdf/layout.rs b/src/rust_typeset/pdf/layout.rs index 2139a64..75e6ff9 100644 --- a/src/rust_typeset/pdf/layout.rs +++ b/src/rust_typeset/pdf/layout.rs @@ -1794,6 +1794,263 @@ pub(super) fn build_positioned_pages( } } } + TitleStyle::Journal => { + let title_runs: Vec = if model.title_runs.is_empty() { + if model.title.is_empty() { + Vec::new() + } else { + vec![Run::plain(model.title.clone())] + } + } else { + model.title_runs.clone() + }; + let mut styled_title = title_runs; + for run in &mut styled_title { + run.bold = true; + } + for line in measure_positioned_lines( + &styled_title, + base_font_size + 5, + 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 superscript = |number: usize| -> String { + number + .to_string() + .chars() + .map(|digit| match digit { + '0' => '⁰', + '1' => '¹', + '2' => '²', + '3' => '³', + '4' => '⁴', + '5' => '⁵', + '6' => '⁶', + '7' => '⁷', + '8' => '⁸', + '9' => '⁹', + other => other, + }) + .collect() + }; + let mut author_emails = Vec::new(); + for author in &model.authors { + let mut runs = author.runs.clone(); + if !author.affiliations.is_empty() { + let marks = author + .affiliations + .iter() + .map(|index| superscript(*index)) + .collect::(); + runs.push(Run::plain(marks)); + } + for line in measure_positioned_lines( + &runs, + 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, + ); + } + if let Some(email) = &author.email { + author_emails.push(email.clone()); + } + } + + for affiliation in &model.affiliations { + let mut runs = vec![Run::plain(format!("{} ", superscript(affiliation.index)))]; + runs.extend(affiliation.runs.clone()); + for line in measure_positioned_lines( + &runs, + base_font_size.saturating_sub(1).max(1), + 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, + ); + } + } + + if !author_emails.is_empty() { + let email_runs = + vec![Run::plain(format!("E-mail: {}", author_emails.join("; ")))]; + for line in measure_positioned_lines( + &email_runs, + base_font_size.saturating_sub(1).max(1), + 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, + ); + } + } + + if !model.abstract_runs.is_empty() { + let mut heading = Run::plain("Abstract".to_string()); + heading.bold = true; + for line in measure_positioned_lines( + std::slice::from_ref(&heading), + 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, + ); + } + let inset_mm = 15.0_f64.min(content_width_mm / 4.0); + let abstract_width = (content_width_mm - 2.0 * inset_mm).max(20.0); + for line in measure_positioned_lines( + &model.abstract_runs, + base_font_size, + abstract_width, + 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, + millimeters_to_scaled(inset_mm), + false, + ); + } + } + + if !model.keywords.is_empty() { + let mut runs = vec![Run::plain("Keywords: ".to_string())]; + let mut keyword_run = Run::plain(String::new()); + keyword_run.bold = true; + runs.push(keyword_run); + runs.extend(model.keywords.clone()); + for line in measure_positioned_lines( + &runs, + base_font_size.saturating_sub(1).max(1), + 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, + millimeters_to_scaled(15.0_f64.min(content_width_mm / 4.0)), + false, + ); + } + } + } TitleStyle::Preprint => { let rule_width = millimeters_to_scaled(content_width_mm); let rule_height = i64::from(scaled_points(2.0).0).max(1); diff --git a/src/rust_typeset/texlang_adapter.rs b/src/rust_typeset/texlang_adapter.rs index 6776298..569f8c4 100644 --- a/src/rust_typeset/texlang_adapter.rs +++ b/src/rust_typeset/texlang_adapter.rs @@ -2172,6 +2172,129 @@ fn make_title_primitive( Ok(()) } +fn token_list_text(tokens: &[token::Token]) -> String { + tokens.iter().filter_map(|token| token.char()).collect() +} + +fn parse_affiliation_indices(value: &str) -> Vec { + value + .split([',', ' ']) + .filter_map(|part| part.trim().parse::().ok()) + .collect() +} + +fn push_frontmatter_content( + input: &mut vm::ExecutionInput, + token: token::Token, + command: &'static str, + content: Vec, +) { + let trace_key = token.trace_key(); + let mut expansion = strip_braced_tokens(&content).to_vec(); + expansion.push(control_sequence_token(input, command, trace_key)); + input + .as_mut() + .expansions_mut() + .extend(expansion.into_iter().rev()); +} + +fn title_frontmatter_primitive( + token: token::Token, + input: &mut vm::ExecutionInput, +) -> texlang::prelude::Result<()> { + if let Some(short) = read_optional_bracketed_argument(input, token, "short title")? { + write_event( + input, + token, + FrontendEventKind::MetadataShortTitle(token_list_text(&short).trim().to_string()), + ); + } + let content = read_unexpanded_argument(input, token, "expects a title")?; + write_event( + input, + token, + FrontendEventKind::MetadataStart(MetadataField::Title), + ); + push_frontmatter_content(input, token, "texrratitleend", content); + Ok(()) +} + +fn author_frontmatter_primitive( + token: token::Token, + input: &mut vm::ExecutionInput, +) -> texlang::prelude::Result<()> { + if let Some(next) = input.unexpanded().next()? { + if !matches!(next.value(), token::Value::Other('*')) { + input.unexpanded().back(next); + } + } + if let Some(indices) = read_optional_bracketed_argument(input, token, "author affiliation")? { + write_event( + input, + token, + FrontendEventKind::AuthorAffiliations(parse_affiliation_indices(&token_list_text( + &indices, + ))), + ); + } + let content = read_unexpanded_argument(input, token, "expects an author")?; + write_event( + input, + token, + FrontendEventKind::MetadataStart(MetadataField::Author), + ); + push_frontmatter_content(input, token, "texrraauthorend", content); + Ok(()) +} + +fn affiliation_frontmatter_primitive( + token: token::Token, + input: &mut vm::ExecutionInput, +) -> texlang::prelude::Result<()> { + if let Some(next) = input.unexpanded().next()? { + if !matches!(next.value(), token::Value::Other('*')) { + input.unexpanded().back(next); + } + } + let index = read_optional_bracketed_argument(input, token, "affiliation number")? + .and_then(|tokens| token_list_text(&tokens).trim().parse::().ok()) + .unwrap_or(1); + let content = read_unexpanded_argument(input, token, "expects an affiliation")?; + write_event(input, token, FrontendEventKind::AffiliationStart(index)); + push_frontmatter_content(input, token, "texrraaffiliationend", content); + Ok(()) +} + +fn abstract_frontmatter_primitive( + token: token::Token, + input: &mut vm::ExecutionInput, +) -> texlang::prelude::Result<()> { + let content = read_unexpanded_argument(input, token, "expects an abstract")?; + write_event(input, token, FrontendEventKind::AbstractStart); + push_frontmatter_content(input, token, "texrraabstractend", content); + Ok(()) +} + +fn keywords_frontmatter_primitive( + token: token::Token, + input: &mut vm::ExecutionInput, +) -> texlang::prelude::Result<()> { + let content = read_unexpanded_argument(input, token, "expects keywords")?; + write_event(input, token, FrontendEventKind::KeywordsStart); + push_frontmatter_content(input, token, "texrrakeywordsend", content); + Ok(()) +} + +fn email_frontmatter_primitive( + token: token::Token, + input: &mut vm::ExecutionInput, +) -> texlang::prelude::Result<()> { + let content = read_unexpanded_argument(input, token, "expects an e-mail address")?; + write_event(input, token, FrontendEventKind::MetadataEmailStart); + push_frontmatter_content(input, token, "texrraemailend", content); + Ok(()) +} + fn metadata_field_argument( token: token::Token, input: &mut vm::ExecutionInput, @@ -2869,6 +2992,12 @@ fn engine_managed_command(name: &EngineCommandName) -> bool { matches!( name.as_str(), "maketitle" + | "title" + | "author" + | "affil" + | "abstract" + | "keywords" + | "email" | "section" | "subsection" | "subsubsection" @@ -4289,6 +4418,19 @@ fn define_tex_macro( }; let macro_name = engine_command_name(name, input.vm().cs_name_interner()); + if matches!( + ¯o_name, + EngineCommandName::ControlSequence(name) + if matches!( + name.as_str(), + "title" | "author" | "affil" | "abstract" | "keywords" | "email" + ) + ) { + // The front matter is owned by the engine's semantic model. Document + // classes routinely replace these commands with box-level storage + // macros that the renderer cannot read, so keep the engine definitions. + return Ok(()); + } let global = matches!( scope, texcraft_stdext::collections::groupingmap::Scope::Global @@ -7681,6 +7823,80 @@ fn built_in_commands() -> HashMap<&'static str, texlang::command::BuiltInA<", + ">Journal<", + ">Alice<", + ">Bob<", + ">Department<", + ">Abstract<", + ">Keywords:<", + ">abstract<", + ">body<", + ] { + assert!( + svg.contains(needle), + "missing {needle:?} in title block: {svg}" + ); + } +}