Render arxiv-style preprint title blocks

This commit is contained in:
gloamxun committed 2026-10-19 15:23:13 +08:00
1 parent 8d5cbc69ba
commit 4991bdfcfc
12 files changed
+559 -77

No files matched your search

+19 -4
View File
@@ -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<PreprocessOutput
})
}
fn current_date_utc() -> 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 {
+1
View File
@@ -913,6 +913,7 @@ struct InlineMathLine {
pre_display_size: Option<Mm>,
}
#[derive(Clone)]
pub(super) struct InlineMathLineElement {
line: InlineMathLine,
alignment: Alignment,
+1
View File
@@ -65,6 +65,7 @@ struct PageBreakPlan {
breaks: HashSet<PageAnchor>,
}
#[derive(Clone)]
enum PositionedLineContent {
Text {
line: text_layout::LineBox,
+400 -46
View File
@@ -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<PositionedPage>,
deferred: &mut Vec<DeferredFloat>,
cursor: &mut i64,
page_breaks: &HashSet<PageAnchor>,
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<PositionedPage>,
deferred: &mut Vec<DeferredFloat>,
cursor: &mut i64,
page_breaks: &HashSet<PageAnchor>,
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<FontFamily<fonts::Font>>,
mono_family: Option<FontFamily<fonts::Font>>,
sans_family: Option<FontFamily<fonts::Font>>,
) -> 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::<Vec<_>>()
})
.filter(|lines| !lines.is_empty())
.collect::<Vec<_>>();
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<FontFamily<fonts::Font>>,
mono_family: Option<FontFamily<fonts::Font>>,
sans_family: Option<FontFamily<fonts::Font>>,
_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)
+22
View File
@@ -2130,6 +2130,14 @@ fn metadata_value_primitive(
Ok(())
}
fn metadata_separator_primitive(
token: token::Token,
input: &mut vm::ExecutionInput<CompilerState>,
) -> texlang::prelude::Result<()> {
write_event(input, token, FrontendEventKind::MetadataSeparator);
Ok(())
}
fn metadata_start_primitive(
token: token::Token,
input: &mut vm::ExecutionInput<CompilerState>,
@@ -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<Compil
metadata_value_primitive(MetadataField::Date, token, input)
}),
);
built_ins.insert(
"texrraauthorseparator",
texlang::command::BuiltIn::new_execution(metadata_separator_primitive),
);
built_ins.insert(
"texrrametadatastart",
texlang::command::BuiltIn::new_execution(metadata_start_primitive),