Files
texrra-engine/crates/texrra-core/src/document_parser.rs
T

2641 lines
93 KiB
Rust

use std::collections::{HashMap, VecDeque};
use crate::{
TeXGlue, TeXGlueOrder,
document::{
Block, ColumnAlignment, DocumentModel, EquationNumber, InlineBox, InlineBoxAlign,
ListBlock, ListItem, PageMargins, PageSize, PageStyleKind, PageStyleOverride,
ParagraphAlignment, ParsedDocument, RuleBox, Run, TableCellStyle, TableRule, TitleStyle,
UnresolvedReference,
},
expanded,
math_expr::*,
source::SourceLocation,
};
#[derive(Default)]
struct ListBuilder {
ordered: bool,
items: Vec<ListItem>,
current: Vec<Run>,
nested: Vec<ListBlock>,
vertical_glue_after: Vec<TeXGlue>,
has_current_item: bool,
}
impl ListBuilder {
fn finish_current_item(&mut self) {
trim_run_end(&mut self.current);
if self.has_current_item
|| !self.current.is_empty()
|| !self.nested.is_empty()
|| !self.vertical_glue_after.is_empty()
{
self.items.push(ListItem {
runs: std::mem::take(&mut self.current),
nested: std::mem::take(&mut self.nested),
vertical_glue_after: std::mem::take(&mut self.vertical_glue_after),
});
}
self.has_current_item = false;
}
}
#[derive(Default)]
struct TableBuilder {
rows: Vec<Vec<Vec<Run>>>,
row: Vec<Vec<Run>>,
cell: Vec<Run>,
caption: Option<Vec<Run>>,
alignments: Vec<ColumnAlignment>,
rules: Vec<TableRule>,
cell_styles: Vec<Vec<TableCellStyle>>,
row_styles: Vec<TableCellStyle>,
pending_cell_style: Option<TableCellStyle>,
}
#[derive(Default)]
struct BibliographyBuilder {
items: Vec<(String, Vec<Run>)>,
current: Option<(String, Vec<Run>)>,
}
struct HeadingBuilder {
level: u8,
runs: Vec<Run>,
source: Option<SourceLocation>,
}
#[derive(Default)]
pub struct ParagraphParseCache {
entries: HashMap<String, Vec<Run>>,
insertion_order: VecDeque<String>,
rich_entries: HashMap<RichParagraphCacheKey, Vec<Run>>,
rich_insertion_order: VecDeque<RichParagraphCacheKey>,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct RichParagraphCacheKey {
items: Vec<RichParagraphItemKey>,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct RichParagraphItemKey {
position: usize,
end_position: usize,
kind: expanded::ExpandedItemKind,
math_code: Option<u16>,
math_family: Option<i32>,
delimiter_settings: Option<MathDelimiterSettings>,
math_fonts: MathFontFamilies,
math_line_break_penalties: MathLineBreakPenalties,
}
struct RichParagraphCandidate {
end_index: usize,
key: RichParagraphCacheKey,
source: SourceLocation,
end_source: SourceLocation,
block_index: usize,
math_expressions: Vec<MathExpr>,
}
impl ParagraphParseCache {
fn parse(&mut self, source: &str) -> Vec<Run> {
if let Some(runs) = self.entries.get(source) {
return runs.clone();
}
let normalized = normalize_whitespace(source);
let text = normalized.trim().to_string();
let runs = if text.is_empty() {
Vec::new()
} else {
vec![Run::plain(text)]
};
const CAPACITY: usize = 2048;
if !self.entries.contains_key(source) {
if self.entries.len() == CAPACITY
&& let Some(oldest) = self.insertion_order.pop_front()
{
self.entries.remove(&oldest);
}
self.insertion_order.push_back(source.to_string());
}
self.entries.insert(source.to_string(), runs.clone());
runs
}
fn get_rich(
&mut self,
key: &RichParagraphCacheKey,
math_expressions: &[MathExpr],
) -> Option<Vec<Run>> {
let mut runs = self.rich_entries.get(key)?.clone();
let mut math_expressions = math_expressions.iter();
for run in &mut runs {
if let Some(expression) = &mut run.math {
*expression = math_expressions.next()?.clone();
}
}
if math_expressions.next().is_some() {
return None;
}
if let Some(index) = self
.rich_insertion_order
.iter()
.position(|cached| cached == key)
{
let key = self
.rich_insertion_order
.remove(index)
.expect("rich paragraph cache index was found");
self.rich_insertion_order.push_back(key);
}
Some(runs)
}
fn insert_rich(&mut self, key: RichParagraphCacheKey, runs: Vec<Run>) {
const CAPACITY: usize = 256;
if let Some(index) = self
.rich_insertion_order
.iter()
.position(|cached| cached == &key)
{
self.rich_insertion_order.remove(index);
} else if self.rich_entries.len() == CAPACITY
&& let Some(oldest) = self.rich_insertion_order.pop_front()
{
self.rich_entries.remove(&oldest);
}
self.rich_insertion_order.push_back(key.clone());
self.rich_entries.insert(key, runs);
}
}
fn append_token_text(item: &expanded::ExpandedItem, output: &mut String) {
let expanded::ExpandedItemKind::Token(value) = &item.kind else {
return;
};
if let Some(character) = value.character() {
output.push(character);
} else if let expanded::ExpandedTokenValue::ControlSequence(name) = value {
output.push('\\');
output.push_str(name);
}
}
fn rich_item_key(item: &expanded::ExpandedItem, paragraph_start: usize) -> RichParagraphItemKey {
let kind = match &item.kind {
expanded::ExpandedItemKind::Event(expanded::FrontendEventKind::InlineMath(expression)) => {
expanded::ExpandedItemKind::Event(expanded::FrontendEventKind::InlineMath(
expression.without_source(),
))
}
kind => kind.clone(),
};
RichParagraphItemKey {
position: item.position - paragraph_start,
end_position: item.end_position - paragraph_start,
kind,
math_code: item.math_code,
math_family: item.math_family,
delimiter_settings: item.delimiter_settings,
math_fonts: std::sync::Arc::clone(&item.math_fonts),
math_line_break_penalties: item.math_line_break_penalties,
}
}
fn rich_math_expressions(items: &[expanded::ExpandedItem]) -> Vec<MathExpr> {
items
.iter()
.filter_map(|item| match &item.kind {
expanded::ExpandedItemKind::Event(expanded::FrontendEventKind::InlineMath(
expression,
)) if !expression.plain_text().is_empty() => Some(expression.clone()),
_ => None,
})
.collect()
}
fn rich_paragraph_candidate(
expanded: &expanded::ExpandedTokenStream,
start_index: usize,
block_index: usize,
) -> Option<RichParagraphCandidate> {
use expanded::{ExpandedItemKind, ExpandedTokenValue, FrontendEventKind as Event};
let mut group_depth = 0usize;
let mut has_content = false;
let mut has_rich_event = false;
let mut source = None;
for (index, item) in expanded.items.iter().enumerate().skip(start_index) {
match &item.kind {
ExpandedItemKind::Token(ExpandedTokenValue::ControlSequence(_)) => return None,
ExpandedItemKind::Token(_) => {
has_content = true;
source.get_or_insert_with(|| item.location.clone());
}
ExpandedItemKind::Event(kind) => match kind {
Event::ParagraphBreak => {
if group_depth != 0 || !has_content || !has_rich_event {
return None;
}
let items = &expanded.items[start_index..=index];
let paragraph_start = items.first()?.position;
return Some(RichParagraphCandidate {
end_index: index + 1,
key: RichParagraphCacheKey {
items: items
.iter()
.map(|item| rich_item_key(item, paragraph_start))
.collect(),
},
source: source?,
end_source: item.location.clone(),
block_index,
math_expressions: rich_math_expressions(items),
});
}
Event::GroupStart => group_depth += 1,
Event::GroupEnd => {
group_depth = group_depth.checked_sub(1)?;
}
Event::InlineMath(_)
| Event::Reference(_)
| Event::Citation(_)
| Event::LiteralAmpersand
| Event::LiteralCharacter(_)
| Event::LineBreak
| Event::MathCell
| Event::MathSpace(_)
| Event::RowBreak => {
has_content = true;
has_rich_event = true;
source.get_or_insert_with(|| item.location.clone());
}
_ => return None,
},
}
}
if group_depth != 0 || !has_content || !has_rich_event {
return None;
}
let items = &expanded.items[start_index..];
let paragraph_start = items.first()?.position;
let end_source = expanded.items.last()?.location.clone();
Some(RichParagraphCandidate {
end_index: expanded.items.len(),
key: RichParagraphCacheKey {
items: items
.iter()
.map(|item| rich_item_key(item, paragraph_start))
.collect(),
},
source: source?,
end_source,
block_index,
math_expressions: rich_math_expressions(items),
})
}
fn consume_environment_preamble(
expanded: &expanded::ExpandedTokenStream,
start_index: usize,
environment: &str,
) -> (usize, Option<String>) {
use expanded::{ExpandedItemKind, ExpandedTokenValue, FrontendEventKind as Event};
let mut argument_start = start_index;
while let Some(item) = expanded.items.get(argument_start) {
if matches!(
&item.kind,
ExpandedItemKind::Token(ExpandedTokenValue::Space(character))
if character.is_whitespace()
) {
argument_start += 1;
} else {
break;
}
}
if environment == "thebibliography" {
let Some(ExpandedItemKind::Event(Event::GroupStart)) =
expanded.items.get(argument_start).map(|item| &item.kind)
else {
return (start_index, None);
};
let mut depth = 0usize;
for (index, item) in expanded.items.iter().enumerate().skip(argument_start) {
match &item.kind {
ExpandedItemKind::Event(Event::GroupStart) => depth += 1,
ExpandedItemKind::Event(Event::GroupEnd) => {
depth -= 1;
if depth == 0 {
return (index + 1, None);
}
}
_ => {}
}
}
return (start_index, None);
}
if !matches!(environment, "figure" | "table")
|| expanded
.items
.get(argument_start)
.and_then(|item| match &item.kind {
ExpandedItemKind::Token(value) => value.character(),
ExpandedItemKind::Event(_) => None,
})
!= Some('[')
{
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,
ExpandedItemKind::Event(Event::GroupEnd) => {
group_depth = group_depth.saturating_sub(1);
}
ExpandedItemKind::Token(value) if group_depth == 0 => match value.character() {
Some('[') => bracket_depth += 1,
Some(']') => {
bracket_depth = bracket_depth.saturating_sub(1);
if bracket_depth == 0 {
return (index + 1, Some(placement));
}
}
Some(character) if bracket_depth == 1 => placement.push(character),
_ => {}
},
_ => {}
}
}
(start_index, None)
}
struct MinipageBuilder {
runs: Vec<Run>,
width: Option<common::Scaled>,
}
/// Marker characters used by placeholders for generated contents lists.
const CONTENTS_TOC_MARKER: char = '\u{F6200}';
const CONTENTS_FIGURES_MARKER: char = '\u{F6201}';
const CONTENTS_TABLES_MARKER: char = '\u{F6202}';
#[derive(Clone, Copy, PartialEq, Eq)]
enum ContentsKind {
TableOfContents,
ListOfFigures,
ListOfTables,
}
struct ContentsEntry {
runs: Vec<Run>,
target: usize,
}
struct InlineBoxSpec {
runs: Vec<Run>,
width: Option<common::Scaled>,
align: InlineBoxAlign,
raise: common::Scaled,
frame: bool,
}
fn contents_kind(block: &Block) -> Option<ContentsKind> {
let Block::Paragraph(runs) = block else {
return None;
};
if runs.len() != 1 {
return None;
}
match runs[0].text.chars().next() {
Some(character) if character == CONTENTS_TOC_MARKER => Some(ContentsKind::TableOfContents),
Some(character) if character == CONTENTS_FIGURES_MARKER => {
Some(ContentsKind::ListOfFigures)
}
Some(character) if character == CONTENTS_TABLES_MARKER => Some(ContentsKind::ListOfTables),
_ => None,
}
}
fn contents_line_runs(title: &[Run], target: usize) -> Vec<Run> {
let mut runs = title.to_vec();
trim_run_end(&mut runs);
runs.push(Run::plain(
crate::document::CONTENTS_LEADER_MARKER.to_string(),
));
let mut filler = Run::plain(String::new());
filler.glue = Some(TeXGlue {
width: common::Scaled::ZERO,
stretch: common::Scaled(65536),
stretch_order: TeXGlueOrder::Fil,
shrink: common::Scaled::ZERO,
shrink_order: TeXGlueOrder::Normal,
});
runs.push(filler);
let mut page = Run::plain("00".to_string());
page.unresolved_reference = Some(UnresolvedReference::TocPage(target));
runs.push(page);
runs
}
struct Parser {
document: DocumentModel,
paragraph: Vec<Run>,
heading: Option<HeadingBuilder>,
lists: Vec<ListBuilder>,
table: Option<TableBuilder>,
bibliography: Option<BibliographyBuilder>,
bold: bool,
italic: bool,
monospace: bool,
sans: bool,
small_caps: bool,
text_style_stack: Vec<(expanded::TextStyle, bool, bool, bool, bool, bool)>,
style_declarations: Vec<(usize, expanded::TextStyle)>,
group_depth: usize,
section_numbers: [u32; 4],
has_chapters: bool,
equation_number: u32,
figure_number: u32,
table_number: u32,
current_reference: String,
figure_active: bool,
figure_image: Option<usize>,
table_active: bool,
current_table_block: Option<usize>,
pending_table_caption: Option<Vec<Run>>,
caption_capture: Option<Vec<Run>>,
metadata_capture: Option<(expanded::MetadataField, Vec<Run>)>,
framed_box: Option<Vec<Run>>,
box_frame: bool,
box_width: Option<common::Scaled>,
inline_boxes: Vec<InlineBoxSpec>,
minipage: Option<MinipageBuilder>,
footnote_capture: Option<Vec<Run>>,
vbox_stack: Vec<(Vec<Block>, Vec<Option<SourceLocation>>)>,
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>,
paragraph_indent: Option<common::Scaled>,
suppress_indent: bool,
paragraph_alignment: ParagraphAlignment,
alignment_saves: Vec<ParagraphAlignment>,
in_abstract: bool,
}
fn apply_bibliography_year_suffixes(document: &DocumentModel, items: &mut [(String, Vec<Run>)]) {
for (key, runs) in items {
let Some(metadata) = document.citation_metadata.get(key) else {
continue;
};
if metadata.year.len() != 5 {
continue;
}
let base = &metadata.year[..4];
let suffix = &metadata.year[4..];
if let Some(run) = runs
.iter_mut()
.rev()
.find(|run| run.text.contains(base) && !run.text.contains(&metadata.year))
{
run.text = run.text.replacen(base, &format!("{base}{suffix}"), 1);
}
}
}
fn assign_citation_year_suffixes(document: &mut DocumentModel) {
let mut groups: HashMap<(String, String), Vec<String>> = HashMap::new();
for key in &document.bibliography_order {
let Some(metadata) = document.citation_metadata.get(key) else {
continue;
};
if metadata.author.is_empty() || metadata.year.is_empty() {
continue;
}
groups
.entry((metadata.author.clone(), metadata.year.clone()))
.or_default()
.push(key.clone());
}
for keys in groups.into_values() {
if keys.len() < 2 {
continue;
}
for (index, key) in keys.into_iter().enumerate() {
let Some(metadata) = document.citation_metadata.get_mut(&key) else {
continue;
};
if metadata.year.len() == 4 {
let letter = char::from(b'a' + (index as u8).min(25));
metadata.year.push(letter);
}
}
}
}
impl Parser {
fn new() -> Self {
Self {
document: DocumentModel::default(),
paragraph: Vec::new(),
heading: None,
lists: Vec::new(),
table: None,
bibliography: None,
bold: false,
italic: false,
monospace: false,
sans: false,
small_caps: false,
text_style_stack: Vec::new(),
style_declarations: Vec::new(),
group_depth: 0,
section_numbers: [0; 4],
has_chapters: false,
equation_number: 0,
figure_number: 0,
table_number: 0,
current_reference: String::new(),
figure_active: false,
figure_image: None,
table_active: false,
current_table_block: None,
pending_table_caption: None,
caption_capture: None,
metadata_capture: None,
framed_box: None,
box_frame: true,
box_width: None,
inline_boxes: Vec::new(),
minipage: None,
footnote_capture: None,
vbox_stack: Vec::new(),
footnote_counter: 0,
page_decoration_capture: None,
float_placement: String::new(),
table_placement: String::new(),
centered: None,
current_source: None,
paragraph_source: None,
paragraph_indent: None,
suppress_indent: false,
paragraph_alignment: ParagraphAlignment::Justified,
alignment_saves: Vec::new(),
in_abstract: false,
}
}
fn parse(
mut self,
expanded: &expanded::ExpandedTokenStream,
paragraph_cache: &mut ParagraphParseCache,
) -> ParsedDocument {
let mut pending_text = String::new();
let mut pending_source = None;
let mut item_index = 0;
let mut rich_candidate = None;
let mut cache_scan_pending = true;
while let Some(item) = expanded.items.get(item_index) {
if cache_scan_pending
&& rich_candidate.is_none()
&& pending_text.is_empty()
&& self.can_reuse_plain_paragraph()
{
cache_scan_pending = false;
if let Some(candidate) =
rich_paragraph_candidate(expanded, item_index, self.document.blocks.len())
{
if let Some(mut runs) =
paragraph_cache.get_rich(&candidate.key, &candidate.math_expressions)
{
self.begin_paragraph_if_needed();
let indent = self.paragraph_indent.take().unwrap_or(common::Scaled::ZERO);
prepend_paragraph_indent(&mut runs, indent);
self.push_block_at(Block::Paragraph(runs), Some(candidate.source));
self.current_source = Some(candidate.end_source);
item_index = candidate.end_index;
cache_scan_pending = true;
continue;
}
rich_candidate = Some(candidate);
}
}
match &item.kind {
expanded::ExpandedItemKind::Token(_) => {
if pending_text.is_empty() {
pending_source = Some(item.location.clone());
}
append_token_text(item, &mut pending_text);
item_index += 1;
}
expanded::ExpandedItemKind::Event(kind) => {
let paragraph_break =
matches!(kind, expanded::FrontendEventKind::ParagraphBreak);
if !pending_text.is_empty() {
self.current_source = pending_source.take();
if paragraph_break && self.can_reuse_plain_paragraph() {
let mut runs = paragraph_cache.parse(&pending_text);
if !runs.is_empty() {
self.begin_paragraph_if_needed();
let indent =
self.paragraph_indent.take().unwrap_or(common::Scaled::ZERO);
prepend_paragraph_indent(&mut runs, indent);
self.push_block_at(
Block::Paragraph(runs),
self.current_source.clone(),
);
}
} else {
self.append_text(&pending_text);
}
pending_text.clear();
}
self.current_source = Some(item.location.clone());
let event = expanded::FrontendEvent {
position: item.position,
kind: kind.clone(),
location: item.location.clone(),
math_line_break_penalties: item.math_line_break_penalties,
};
self.handle_frontend_event(&event);
item_index += 1;
if let expanded::FrontendEventKind::BeginEnvironment {
name: environment, ..
} = kind
{
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 {
if rich_candidate
.as_ref()
.is_some_and(|candidate| candidate.end_index == item_index)
{
let candidate = rich_candidate
.take()
.expect("rich paragraph candidate was checked");
if let Some(Block::Paragraph(runs)) =
self.document.blocks.get(candidate.block_index)
{
let mut cached = runs.clone();
strip_paragraph_indent(&mut cached);
paragraph_cache.insert_rich(candidate.key, cached);
}
}
cache_scan_pending = true;
} else if pending_text.is_empty() && self.can_reuse_plain_paragraph() {
cache_scan_pending = true;
}
}
}
}
if !pending_text.is_empty() {
self.current_source = pending_source;
self.append_text(&pending_text);
}
self.finish_heading();
self.finish_minipage();
self.flush_paragraph();
if let Some(candidate) = rich_candidate
&& candidate.end_index == expanded.items.len()
&& let Some(Block::Paragraph(runs)) = self.document.blocks.get(candidate.block_index)
{
let mut cached = runs.clone();
strip_paragraph_indent(&mut cached);
paragraph_cache.insert_rich(candidate.key, cached);
}
while !self.lists.is_empty() {
self.finish_list();
}
self.finish_table();
self.finish_bibliography();
self.finalize_contents();
ParsedDocument(self.document)
}
fn can_reuse_plain_paragraph(&self) -> bool {
self.paragraph.is_empty()
&& self.heading.is_none()
&& self.lists.is_empty()
&& self.table.is_none()
&& self.bibliography.is_none()
&& !self.figure_active
&& !self.table_active
&& self.caption_capture.is_none()
&& self.metadata_capture.is_none()
&& self.framed_box.is_none()
&& self.centered.is_none()
&& self.inline_boxes.is_empty()
&& self.minipage.is_none()
&& self.footnote_capture.is_none()
&& !self.bold
&& !self.italic
&& !self.monospace
&& !self.sans
&& self.text_style_stack.is_empty()
}
fn finish_metadata(&mut self, field: expanded::MetadataField) {
let Some((active_field, runs)) = self.metadata_capture.take() else {
return;
};
if active_field != field {
self.metadata_capture = Some((active_field, runs));
return;
}
let value = runs.iter().map(|run| run.text.clone()).collect::<String>();
match field {
expanded::MetadataField::Title => {
self.document.title = value;
self.document.title_runs = runs;
}
expanded::MetadataField::Author => self.document.author = value,
expanded::MetadataField::Date => self.document.date = value,
}
}
fn begin_style(&mut self, style: expanded::TextStyle) {
self.text_style_stack.push((
style,
self.bold,
self.italic,
self.monospace,
self.sans,
self.small_caps,
));
match style {
expanded::TextStyle::Bold => self.bold = true,
expanded::TextStyle::Italic => self.italic = true,
expanded::TextStyle::Monospace => self.monospace = true,
expanded::TextStyle::Sans => self.sans = true,
expanded::TextStyle::SmallCaps => self.small_caps = true,
expanded::TextStyle::Normal => {
self.bold = false;
self.italic = false;
self.monospace = false;
self.sans = false;
self.small_caps = false;
}
}
}
fn end_style(&mut self, style: expanded::TextStyle) {
if self
.text_style_stack
.last()
.is_some_and(|(active_style, _, _, _, _, _)| *active_style == style)
&& let Some((_, bold, italic, monospace, sans, small_caps)) =
self.text_style_stack.pop()
{
self.bold = bold;
self.italic = italic;
self.monospace = monospace;
self.sans = sans;
self.small_caps = small_caps;
}
}
fn handle_frontend_event(&mut self, event: &expanded::FrontendEvent) {
self.current_source = Some(event.location.clone());
match &event.kind {
expanded::FrontendEventKind::ParagraphBreak => self.paragraph_break(),
expanded::FrontendEventKind::PageBreak => {
self.flush_paragraph();
self.push_block(Block::PageBreak);
}
expanded::FrontendEventKind::Kern(width) => self.append_kern(*width),
expanded::FrontendEventKind::Rule {
width,
raise,
height,
} => self.append_rule(*width, *raise, *height),
expanded::FrontendEventKind::HorizontalGlue(glue) => self.append_glue(*glue),
expanded::FrontendEventKind::VerticalGlue(glue) => self.append_vertical_glue(*glue),
expanded::FrontendEventKind::Penalty(penalty) => self.append_penalty(*penalty),
expanded::FrontendEventKind::MakeTitle => {
self.flush_paragraph();
self.document.show_title = true;
self.suppress_indent = true;
}
expanded::FrontendEventKind::FootnoteStart => {
self.footnote_capture = Some(Vec::new());
}
expanded::FrontendEventKind::FootnoteEnd => {
if let Some(mut runs) = self.footnote_capture.take() {
trim_run_end(&mut runs);
self.footnote_counter += 1;
let number = self.footnote_counter;
self.document
.footnotes
.push(crate::document::Footnote { number, runs });
let bold = self.bold;
let italic = self.italic;
let monospace = self.monospace;
let sans = self.sans;
let small_caps = self.small_caps;
let marker = Run {
text: superscript_number(number),
math: None,
kern: None,
glue: None,
penalty: None,
rule: None,
box_run: None,
y_offset: None,
footnote_number: Some(number),
unresolved_reference: None,
bold,
italic,
monospace,
sans,
small_caps,
paragraph_indent: false,
alignment: None,
};
self.target_runs().push(marker);
}
}
expanded::FrontendEventKind::InlineBoxStart {
width,
align,
raise,
frame,
} => {
self.inline_boxes.push(InlineBoxSpec {
runs: Vec::new(),
width: *width,
align: *align,
raise: *raise,
frame: *frame,
});
}
expanded::FrontendEventKind::InlineBoxEnd => {
if let Some(mut spec) = self.inline_boxes.pop() {
trim_run_end(&mut spec.runs);
let run = Run {
text: String::new(),
math: None,
kern: None,
glue: None,
penalty: None,
rule: None,
box_run: Some(InlineBox {
runs: spec.runs,
width: spec.width,
align: spec.align,
raise: spec.raise,
frame: spec.frame,
}),
unresolved_reference: None,
bold: false,
italic: false,
monospace: false,
paragraph_indent: false,
alignment: None,
sans: false,
small_caps: false,
y_offset: None,
footnote_number: None,
};
self.target_runs().push(run);
}
}
expanded::FrontendEventKind::FramedBoxStart => {
self.flush_paragraph();
self.box_frame = true;
self.box_width = None;
if self.framed_box.is_none() {
self.framed_box = Some(Vec::new());
}
}
expanded::FrontendEventKind::VBoxStart => {
self.flush_paragraph();
let blocks = std::mem::take(&mut self.document.blocks);
let sources = std::mem::take(&mut self.document.block_sources);
self.vbox_stack.push((blocks, sources));
}
expanded::FrontendEventKind::VBoxEnd => {
self.flush_paragraph();
let Some((blocks, sources)) = self.vbox_stack.pop() else {
return;
};
let inner_blocks = std::mem::replace(&mut self.document.blocks, blocks);
let inner_sources = std::mem::replace(&mut self.document.block_sources, sources);
self.document.blocks.extend(inner_blocks);
self.document.block_sources.extend(inner_sources);
}
expanded::FrontendEventKind::ParboxStart { width } => {
self.flush_paragraph();
self.box_frame = false;
self.box_width = Some(*width);
if self.framed_box.is_none() {
self.framed_box = Some(Vec::new());
}
}
expanded::FrontendEventKind::HorizontalRule { height, width } => {
self.flush_paragraph();
self.push_block(Block::HorizontalRule {
height: *height,
width: *width,
});
}
expanded::FrontendEventKind::FramedBoxEnd => {
if let Some(mut runs) = self.framed_box.take() {
trim_run_end(&mut runs);
let frame = self.box_frame;
let width = self.box_width.take();
self.push_block(Block::FramedBox { runs, frame, width });
}
}
expanded::FrontendEventKind::MetadataValue(field) => {
let value = match field {
expanded::MetadataField::Title => self.document.title.clone(),
expanded::MetadataField::Author => self.document.author.clone(),
expanded::MetadataField::Date => self.document.date.clone(),
};
self.append_text(&value);
}
expanded::FrontendEventKind::MetadataStart(field) => {
self.metadata_capture = Some((*field, Vec::new()));
}
expanded::FrontendEventKind::MetadataEnd(field) => {
self.finish_metadata(*field);
}
expanded::FrontendEventKind::PackageLoaded(package) => {
if package == "arxiv" {
self.document.title_style = TitleStyle::Preprint;
self.document.author_year_citations = true;
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);
}
expanded::FrontendEventKind::TextStyleStart(style) => self.begin_style(*style),
expanded::FrontendEventKind::TextStyleEnd(style) => self.end_style(*style),
expanded::FrontendEventKind::TextStyleDeclare(style) => {
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::TableOfContents => {
self.push_contents_placeholder(CONTENTS_TOC_MARKER);
}
expanded::FrontendEventKind::ListOfFigures => {
self.push_contents_placeholder(CONTENTS_FIGURES_MARKER);
}
expanded::FrontendEventKind::ListOfTables => {
self.push_contents_placeholder(CONTENTS_TABLES_MARKER);
}
expanded::FrontendEventKind::ParagraphAlignment(alignment) => {
self.paragraph_alignment = *alignment;
}
expanded::FrontendEventKind::GroupStart => {
self.group_depth += 1;
self.alignment_saves.push(self.paragraph_alignment);
}
expanded::FrontendEventKind::GroupEnd => {
let depth = self.group_depth;
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 = self.group_depth.saturating_sub(1);
self.paragraph_alignment = self
.alignment_saves
.pop()
.unwrap_or(ParagraphAlignment::Justified);
}
expanded::FrontendEventKind::LiteralAmpersand
| expanded::FrontendEventKind::MathCell => self.append_literal_ampersand(),
expanded::FrontendEventKind::LiteralCharacter(character) => {
self.append_text(&character.to_string())
}
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(" ");
}
}
expanded::FrontendEventKind::ListItem => self.start_list_item(),
expanded::FrontendEventKind::TableCell => self.finish_table_cell(),
expanded::FrontendEventKind::TableCellSpan { colspan, alignment } => {
if let Some(table) = &mut self.table {
table.pending_cell_style = Some(TableCellStyle {
colspan: (*colspan).max(1),
alignment: *alignment,
});
}
}
expanded::FrontendEventKind::TableRule => {
if let Some(table) = &mut self.table {
table.rules.push(TableRule::full(table.rows.len()));
}
}
expanded::FrontendEventKind::TableRuleRange {
start_column,
end_column,
trim_left,
trim_right,
} => {
if let Some(table) = &mut self.table {
table.rules.push(TableRule {
row: table.rows.len(),
start_column: *start_column,
end_column: *end_column,
trim_left: *trim_left,
trim_right: *trim_right,
});
}
}
expanded::FrontendEventKind::DisplayMath {
expression,
environment,
rows,
} => {
self.flush_paragraph();
let number_rows = matches!(
environment.as_deref(),
Some(
"equation"
| "align"
| "alignat"
| "flalign"
| "eqnarray"
| "gather"
| "multline"
)
);
let mut equation_numbers = Vec::with_capacity(rows.len());
for row in rows {
let number = if let Some(tag) = &row.equation_tag {
Some(EquationNumber {
text: tag.text.clone(),
parenthesized: !tag.starred,
})
} else if number_rows && !row.suppress_number {
self.equation_number += 1;
Some(EquationNumber {
text: self.equation_number.to_string(),
parenthesized: true,
})
} else {
None
};
let reference = number
.as_ref()
.map(|number| number.text.clone())
.unwrap_or_else(|| "?".to_string());
for key in &row.labels {
self.document.labels.insert(key.clone(), reference.clone());
}
if number.is_some() {
self.current_reference = reference;
}
equation_numbers.push(number);
}
if equation_numbers.iter().all(Option::is_none) {
self.current_reference.clear();
}
if !expression.plain_text().is_empty() {
self.push_block_at(
Block::Math {
expression: expression.clone(),
equation_numbers,
},
Some(event.location.clone()),
);
}
}
expanded::FrontendEventKind::InlineMath(expression) => {
self.append_math_expression(expression.clone());
}
expanded::FrontendEventKind::MathSpace(_) => self.append_text(" "),
expanded::FrontendEventKind::DisplayMathStart
| expanded::FrontendEventKind::DisplayMathEnd(_)
| expanded::FrontendEventKind::SuppressEquationNumber
| expanded::FrontendEventKind::EquationTag(_)
| expanded::FrontendEventKind::InlineMathStart
| expanded::FrontendEventKind::InlineMathEnd(_)
| expanded::FrontendEventKind::MathFractionStart { .. }
| expanded::FrontendEventKind::MathFractionSeparator
| expanded::FrontendEventKind::MathFractionEnd
| expanded::FrontendEventKind::MathInfixFraction(..)
| expanded::FrontendEventKind::MathCharacter { .. }
| expanded::FrontendEventKind::MathUnicodeCharacter { .. }
| expanded::FrontendEventKind::MathUnicodeDelimiter { .. }
| expanded::FrontendEventKind::MathStyleChange(_)
| expanded::FrontendEventKind::MathChoiceStart
| expanded::FrontendEventKind::MathChoiceBranch(_)
| expanded::FrontendEventKind::MathChoiceEnd
| expanded::FrontendEventKind::MathLimitMode(_)
| expanded::FrontendEventKind::MathAccentStart { .. }
| expanded::FrontendEventKind::MathAccentEnd
| expanded::FrontendEventKind::MathFontStart(_)
| expanded::FrontendEventKind::MathFontEnd
| expanded::FrontendEventKind::MathPhantomStart(_)
| expanded::FrontendEventKind::MathPhantomEnd
| expanded::FrontendEventKind::MathOperatorStart
| expanded::FrontendEventKind::MathOperatorEnd
| expanded::FrontendEventKind::MathClassStart(_)
| expanded::FrontendEventKind::MathClassEnd
| expanded::FrontendEventKind::MathRootStart { .. }
| expanded::FrontendEventKind::MathRootSeparator
| expanded::FrontendEventKind::MathRootEnd
| expanded::FrontendEventKind::MathDelimiterStart { .. }
| expanded::FrontendEventKind::MathDelimiterMiddle { .. }
| expanded::FrontendEventKind::MathDelimiterEnd { .. }
| expanded::FrontendEventKind::MathManualDelimiter { .. } => {}
expanded::FrontendEventKind::EnvironmentArgument(argument) => {
if self.table.is_some() {
self.set_table_alignments(argument);
}
if let Some(minipage) = &mut self.minipage
&& minipage.width.is_none()
{
minipage.width = parse_dimension(argument.trim()).map(|width_mm| {
common::Scaled((width_mm / 25.4 * 72.0_f64 * 65_536.0).round() as i32)
});
}
}
expanded::FrontendEventKind::BeginEnvironment {
name: environment, ..
} => self.handle_environment(true, environment),
expanded::FrontendEventKind::EndEnvironment { name, .. } => {
self.handle_environment(false, name)
}
expanded::FrontendEventKind::HeadingStart { level, numbered } => {
self.start_heading(*level, *numbered)
}
expanded::FrontendEventKind::HeadingEnd => self.finish_heading(),
expanded::FrontendEventKind::Parindent(width) => {
self.document.parindent = *width;
}
expanded::FrontendEventKind::NoIndent => {
if self.paragraph.is_empty() {
self.suppress_indent = true;
}
}
expanded::FrontendEventKind::CaptionStart => {
self.flush_paragraph();
self.caption_capture = Some(Vec::new());
}
expanded::FrontendEventKind::CaptionEnd => {
if let Some(caption) = self.caption_capture.take() {
self.handle_caption(caption);
}
}
expanded::FrontendEventKind::Label(key) => {
let reference = if self.current_reference.is_empty() {
"?".to_string()
} else {
self.current_reference.clone()
};
self.document.labels.insert(key.clone(), reference);
}
expanded::FrontendEventKind::Reference(key) => {
self.append_reference(UnresolvedReference::Label(key.clone()))
}
expanded::FrontendEventKind::Citation(keys) => {
let (keys, textual) = match keys.strip_prefix("@text:") {
Some(keys) => (keys, true),
None => (keys.as_str(), false),
};
let keys = keys.split(',').map(str::trim).map(str::to_string).collect();
self.append_reference(if textual {
UnresolvedReference::TextualCitation(keys)
} else {
UnresolvedReference::Citation(keys)
})
}
expanded::FrontendEventKind::BibliographyItem(key) => {
self.start_bibliography_item(key.clone())
}
expanded::FrontendEventKind::BibliographyMetadata { key, author, year } => {
if !self.document.bibliography_order.contains(key) {
self.document.bibliography_order.push(key.clone());
}
self.document.citation_metadata.insert(
key.clone(),
crate::document::CitationMetadata {
author: author.clone(),
year: year.clone(),
},
);
}
expanded::FrontendEventKind::IncludeGraphics { options, path } => {
self.add_image(path.clone(), options.clone())
}
}
}
fn append_math_expression(&mut self, expression: MathExpr) {
let text = expression.plain_text();
if text.is_empty() {
return;
}
if self.paragraph.is_empty()
&& self.heading.is_none()
&& self.table.is_none()
&& self.lists.is_empty()
{
self.paragraph_source = self.current_source.clone();
}
let bold = self.bold;
self.target_runs().push(Run {
text,
math: Some(expression),
kern: None,
glue: None,
penalty: None,
rule: None,
box_run: None,
unresolved_reference: None,
bold,
italic: true,
monospace: false,
paragraph_indent: false,
alignment: None,
sans: false,
small_caps: false,
y_offset: None,
footnote_number: None,
});
}
fn start_heading(&mut self, level: u8, numbered: bool) {
self.flush_paragraph();
self.finish_heading();
let level = level.min(3);
if level == 0 {
self.has_chapters = true;
if !self.document.blocks.is_empty() {
self.push_block(Block::PageBreak);
}
}
let runs = if numbered {
let number = self.next_section_number(level);
self.current_reference = number.clone();
vec![Run::plain(format!("{number} "))]
} else {
self.current_reference.clear();
Vec::new()
};
self.heading = Some(HeadingBuilder {
level,
runs,
source: self.current_source.clone(),
});
}
fn finish_minipage(&mut self) {
let Some(mut minipage) = self.minipage.take() else {
return;
};
trim_run_end(&mut minipage.runs);
if minipage.runs.is_empty() {
return;
}
let width = minipage
.width
.unwrap_or_else(|| common::Scaled((160.0 / 25.4 * 72.0_f64 * 65_536.0).round() as i32));
self.push_block(Block::FramedBox {
runs: minipage.runs,
frame: false,
width: Some(width),
});
}
fn finish_heading(&mut self) {
if let Some(mut heading) = self.heading.take() {
trim_run_end(&mut heading.runs);
self.push_block_at(
Block::Heading {
level: heading.level,
runs: heading.runs,
},
heading.source,
);
self.suppress_indent = true;
}
}
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;
}
if !text.is_empty()
&& self.paragraph.is_empty()
&& self.heading.is_none()
&& self.table.is_none()
&& self.lists.is_empty()
&& self.metadata_capture.is_none()
{
self.paragraph_source = self.current_source.clone();
}
let bold = self.bold;
let italic = self.italic;
let monospace = self.monospace;
let sans = self.sans;
let small_caps = self.small_caps;
if self.table.is_some() {
let mut pieces = text.split('&').peekable();
while let Some(piece) = pieces.next() {
append_run(
self.target_runs(),
normalize_whitespace(piece),
bold,
italic,
monospace,
sans,
small_caps,
);
if pieces.peek().is_some() {
self.finish_table_cell();
}
}
} else {
append_run(
self.target_runs(),
normalize_whitespace(text),
bold,
italic,
monospace,
sans,
small_caps,
);
}
let alignment = self.paragraph_alignment;
if alignment != ParagraphAlignment::Justified
&& let Some(run) = self.target_runs().last_mut()
{
run.alignment = Some(alignment);
}
}
fn append_kern(&mut self, width: common::Scaled) {
let in_vertical_mode = self.paragraph.is_empty()
&& self.heading.is_none()
&& self.lists.is_empty()
&& self.table.is_none()
&& self.bibliography.is_none()
&& self.caption_capture.is_none()
&& self.metadata_capture.is_none()
&& self.framed_box.is_none()
&& self.centered.is_none()
&& self.inline_boxes.is_empty()
&& !self.figure_active;
if in_vertical_mode {
self.push_block(Block::VerticalKern(width));
return;
}
let bold = self.bold;
let italic = self.italic;
let monospace = self.monospace;
self.target_runs().push(Run {
text: String::new(),
math: None,
kern: Some(width),
glue: None,
penalty: None,
rule: None,
box_run: None,
unresolved_reference: None,
bold,
italic,
monospace,
paragraph_indent: false,
alignment: None,
sans: false,
small_caps: false,
y_offset: None,
footnote_number: None,
});
}
fn append_rule(
&mut self,
width: common::Scaled,
raise: common::Scaled,
height: common::Scaled,
) {
let bold = self.bold;
let italic = self.italic;
let monospace = self.monospace;
self.target_runs().push(Run {
text: String::new(),
math: None,
kern: None,
glue: None,
penalty: None,
rule: Some(RuleBox {
width,
raise,
height,
}),
box_run: None,
unresolved_reference: None,
bold,
italic,
monospace,
paragraph_indent: false,
alignment: None,
sans: false,
small_caps: false,
y_offset: None,
footnote_number: None,
});
}
fn append_glue(&mut self, glue: TeXGlue) {
if self.paragraph.is_empty()
&& self.heading.is_none()
&& self.lists.is_empty()
&& self.table.is_none()
&& self.bibliography.is_none()
&& self.caption_capture.is_none()
&& self.metadata_capture.is_none()
&& self.framed_box.is_none()
&& self.centered.is_none()
&& self.inline_boxes.is_empty()
{
self.paragraph_source = self.current_source.clone();
}
let bold = self.bold;
let italic = self.italic;
let monospace = self.monospace;
self.target_runs().push(Run {
text: String::new(),
math: None,
kern: None,
glue: Some(glue),
penalty: None,
rule: None,
box_run: None,
unresolved_reference: None,
bold,
italic,
monospace,
paragraph_indent: false,
alignment: None,
sans: false,
small_caps: false,
y_offset: None,
footnote_number: None,
});
}
fn append_vertical_glue(&mut self, glue: TeXGlue) {
if let Some(list) = self.lists.last_mut() {
list.vertical_glue_after.push(glue);
return;
}
self.flush_paragraph();
self.push_block(Block::VerticalGlue(glue));
}
fn append_penalty(&mut self, penalty: i32) {
let in_vertical_mode = self.paragraph.is_empty()
&& self.heading.is_none()
&& self.lists.is_empty()
&& self.table.is_none()
&& self.bibliography.is_none()
&& self.caption_capture.is_none()
&& self.metadata_capture.is_none()
&& self.framed_box.is_none()
&& self.centered.is_none()
&& self.inline_boxes.is_empty();
if in_vertical_mode {
self.push_block(Block::Penalty(penalty));
return;
}
let bold = self.bold;
let italic = self.italic;
let monospace = self.monospace;
self.target_runs().push(Run {
text: String::new(),
math: None,
kern: None,
glue: None,
penalty: Some(penalty),
rule: None,
box_run: None,
unresolved_reference: None,
bold,
italic,
monospace,
paragraph_indent: false,
alignment: None,
sans: false,
small_caps: false,
y_offset: None,
footnote_number: None,
});
}
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
.as_mut()
.expect("footnote capture was checked");
}
self.target_runs_without_footnote()
}
fn target_runs_without_footnote(&mut self) -> &mut Vec<Run> {
let paragraph_target = self.inline_boxes.is_empty()
&& self.minipage.is_none()
&& 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()
&& self.lists.is_empty()
&& !self
.bibliography
.as_ref()
.is_some_and(|bibliography| bibliography.current.is_some());
if paragraph_target {
self.begin_paragraph_if_needed();
}
if let Some(spec) = self.inline_boxes.last_mut() {
&mut spec.runs
} else if let Some(minipage) = &mut self.minipage {
&mut minipage.runs
} else if let Some(runs) = &mut self.centered {
runs
} else if let Some(runs) = &mut self.framed_box {
runs
} else if let Some((_, metadata)) = &mut self.metadata_capture {
metadata
} else if let Some(caption) = &mut self.caption_capture {
caption
} else if let Some(heading) = &mut self.heading {
&mut heading.runs
} else if let Some(table) = &mut self.table {
&mut table.cell
} else if let Some(bibliography) = &mut self.bibliography {
if let Some((_, runs)) = &mut bibliography.current {
runs
} else {
&mut self.paragraph
}
} else if let Some(list) = self.lists.last_mut() {
&mut list.current
} else {
&mut self.paragraph
}
}
fn begin_paragraph_if_needed(&mut self) {
if !self.paragraph.is_empty() {
return;
}
// Empty appends (for example whitespace-only tokens or macro-definition
// text in the prelude) must not freeze the indentation of the paragraph
// that eventually receives the first real run. Re-evaluate until a run
// actually lands in the paragraph.
self.paragraph_indent = Some(if self.suppress_indent {
common::Scaled::ZERO
} else {
self.document.parindent
});
self.suppress_indent = false;
self.paragraph_source = self.current_source.clone();
}
fn append_literal_ampersand(&mut self) {
let bold = self.bold;
let italic = self.italic;
let monospace = self.monospace;
let sans = self.sans;
let small_caps = self.small_caps;
append_run(
self.target_runs(),
"&".to_string(),
bold,
italic,
monospace,
sans,
small_caps,
);
}
fn append_reference(&mut self, reference: UnresolvedReference) {
if self.paragraph.is_empty()
&& self.heading.is_none()
&& self.table.is_none()
&& self.lists.is_empty()
&& self.bibliography.is_none()
&& self.caption_capture.is_none()
&& self.metadata_capture.is_none()
&& self.framed_box.is_none()
&& self.centered.is_none()
&& self.inline_boxes.is_empty()
{
self.paragraph_source = self.current_source.clone();
}
let bold = self.bold;
let italic = self.italic;
let monospace = self.monospace;
self.target_runs().push(Run {
text: String::new(),
math: None,
kern: None,
glue: None,
penalty: None,
rule: None,
box_run: None,
unresolved_reference: Some(reference),
bold,
italic,
monospace,
paragraph_indent: false,
alignment: None,
sans: false,
small_caps: false,
y_offset: None,
footnote_number: None,
});
}
fn paragraph_break(&mut self) {
if self.footnote_capture.is_some() || self.minipage.is_some() {
self.append_text(" ");
} else if !self.lists.is_empty() || self.table.is_some() {
self.append_text(" ");
} else {
self.flush_paragraph();
}
}
fn push_contents_placeholder(&mut self, marker: char) {
self.flush_paragraph();
self.push_block(Block::Paragraph(vec![Run::plain(marker.to_string())]));
}
fn finalize_contents(&mut self) {
let mut toc_entries = Vec::new();
let mut figure_entries = Vec::new();
let mut table_entries = Vec::new();
for (index, block) in self.document.blocks.iter().enumerate() {
match block {
Block::Heading { level, runs } if *level <= 3 => {
let numbered = runs.first().is_some_and(|run| {
run.text
.chars()
.next()
.is_some_and(|character| character.is_ascii_digit())
});
if numbered {
toc_entries.push(ContentsEntry {
runs: runs.clone(),
target: index,
});
}
}
Block::Image {
caption: Some(caption),
..
} => figure_entries.push(ContentsEntry {
runs: caption.clone(),
target: index,
}),
Block::Table {
caption: Some(caption),
..
} => table_entries.push(ContentsEntry {
runs: caption.clone(),
target: index,
}),
_ => {}
}
}
let has_placeholders = self
.document
.blocks
.iter()
.any(|block| contents_kind(block).is_some());
if !has_placeholders {
return;
}
let blocks = std::mem::take(&mut self.document.blocks);
let sources = std::mem::take(&mut self.document.block_sources);
let mut output_index = Vec::with_capacity(blocks.len());
let mut next = 0;
for block in &blocks {
output_index.push(next);
next += match contents_kind(block) {
Some(ContentsKind::TableOfContents) => 1 + toc_entries.len(),
Some(ContentsKind::ListOfFigures) => 1 + figure_entries.len(),
Some(ContentsKind::ListOfTables) => 1 + table_entries.len(),
None => 1,
};
}
let mut expanded_blocks = Vec::with_capacity(next);
let mut expanded_sources = Vec::with_capacity(next);
for (index, block) in blocks.into_iter().enumerate() {
if let Some(kind) = contents_kind(&block) {
let source = sources.get(index).cloned().flatten();
let (title, entries) = match kind {
ContentsKind::TableOfContents => ("Contents", &toc_entries),
ContentsKind::ListOfFigures => ("List of Figures", &figure_entries),
ContentsKind::ListOfTables => ("List of Tables", &table_entries),
};
let mut title_runs = vec![Run::plain(title.to_string())];
title_runs[0].bold = true;
expanded_blocks.push(Block::Paragraph(title_runs));
expanded_sources.push(source.clone());
for entry in entries {
let target = output_index[entry.target];
expanded_blocks.push(Block::Paragraph(contents_line_runs(&entry.runs, target)));
expanded_sources.push(source.clone());
}
} else {
expanded_blocks.push(block);
expanded_sources.push(sources.get(index).cloned().flatten());
}
}
self.document.blocks = expanded_blocks;
self.document.block_sources = expanded_sources;
}
fn flush_paragraph(&mut self) {
trim_run_end(&mut self.paragraph);
let indent = self.paragraph_indent.take().unwrap_or(common::Scaled::ZERO);
if !self.paragraph.is_empty() {
let mut runs = std::mem::take(&mut self.paragraph);
if self.paragraph_alignment != ParagraphAlignment::Justified
&& let Some(first) = runs.first_mut()
{
first.alignment = Some(self.paragraph_alignment);
} else if self.in_abstract
&& runs.first().is_some_and(|run| run.alignment.is_none())
&& let Some(first) = runs.first_mut()
{
first.alignment = Some(ParagraphAlignment::Quote);
}
prepend_paragraph_indent(&mut runs, indent);
let source = self.paragraph_source.take();
self.push_block_at(Block::Paragraph(runs), source);
} else {
self.paragraph_source = None;
}
}
fn push_block(&mut self, block: Block) {
self.push_block_at(block, self.current_source.clone());
}
fn push_block_at(&mut self, block: Block, source: Option<SourceLocation>) {
self.document.blocks.push(block);
self.document.block_sources.push(source);
}
fn start_list_item(&mut self) {
if self.lists.is_empty() {
self.flush_paragraph();
self.lists.push(ListBuilder::default());
}
if let Some(list) = self.lists.last_mut() {
list.finish_current_item();
list.has_current_item = true;
}
}
fn handle_environment(&mut self, begin: bool, environment: &str) {
match (begin, environment) {
(true, "itemize") | (true, "enumerate") => {
self.flush_paragraph();
if let Some(parent) = self.lists.last_mut() {
parent.has_current_item = true;
}
self.lists.push(ListBuilder {
ordered: environment == "enumerate",
..ListBuilder::default()
});
}
(false, "itemize") | (false, "enumerate") => {
self.flush_paragraph();
self.finish_list();
}
(true, "tabular") => {
self.flush_paragraph();
self.finish_list();
self.table = Some(TableBuilder {
caption: self.pending_table_caption.take(),
..TableBuilder::default()
});
if !self.table_active {
self.table_number += 1;
self.current_reference = self.table_number.to_string();
}
}
(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;
self.current_reference = self.figure_number.to_string();
}
(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;
self.table_number += 1;
self.current_reference = self.table_number.to_string();
}
(false, "table") => {
self.flush_paragraph();
self.table_active = false;
self.current_table_block = None;
}
(true, "abstract") => {
self.flush_paragraph();
let mut heading = Run::plain("Abstract".to_string());
heading.bold = true;
heading.small_caps = true;
self.push_block(Block::Centered {
runs: vec![heading],
});
self.in_abstract = true;
}
(false, "abstract") => {
self.flush_paragraph();
self.in_abstract = false;
}
(true, "raggedright") => {
self.flush_paragraph();
self.alignment_saves.push(self.paragraph_alignment);
self.paragraph_alignment = ParagraphAlignment::RaggedRight;
}
(false, "raggedright") => {
self.flush_paragraph();
self.paragraph_alignment = self
.alignment_saves
.pop()
.unwrap_or(ParagraphAlignment::Justified);
}
(true, "raggedleft") => {
self.flush_paragraph();
self.alignment_saves.push(self.paragraph_alignment);
self.paragraph_alignment = ParagraphAlignment::RaggedLeft;
}
(false, "raggedleft") => {
self.flush_paragraph();
self.paragraph_alignment = self
.alignment_saves
.pop()
.unwrap_or(ParagraphAlignment::Justified);
}
(true, "center") => {
self.flush_paragraph();
if self.centered.is_none() {
self.centered = Some(Vec::new());
}
}
(false, "center") => {
if let Some(mut runs) = self.centered.take() {
trim_run_end(&mut runs);
self.push_block(Block::Centered { runs });
}
}
(true, "minipage") => {
self.flush_paragraph();
self.minipage = Some(MinipageBuilder {
runs: Vec::new(),
width: None,
});
}
(false, "minipage") => self.finish_minipage(),
(true, "thebibliography") => {
self.flush_paragraph();
self.bibliography = Some(BibliographyBuilder::default());
}
(false, "thebibliography") => self.finish_bibliography(),
_ => {}
}
}
fn next_section_number(&mut self, level: u8) -> String {
let index = usize::from(level.min(3));
self.section_numbers[index] += 1;
self.section_numbers[index + 1..].fill(0);
if level == 0 {
self.has_chapters = true;
return self.section_numbers[0].to_string();
}
let start = if self.has_chapters && self.section_numbers[0] > 0 {
0
} else {
1
};
self.section_numbers[start..=index]
.iter()
.map(u32::to_string)
.collect::<Vec<_>>()
.join(".")
}
fn add_image(&mut self, path: String, options: String) {
if self.metadata_capture.is_some() {
// Title metadata is stored as plain text, so inline images (such as
// ORCID icons inside \author) are dropped here.
return;
}
self.flush_paragraph();
if !self.figure_active {
self.figure_number += 1;
}
self.current_reference = self.figure_number.to_string();
if self.figure_active && 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);
}
}
fn handle_caption(&mut self, caption: Vec<Run>) {
self.flush_paragraph();
if self.figure_active {
self.current_reference = self.figure_number.to_string();
let caption = caption_with_prefix(format!("Figure {}: ", self.figure_number), caption);
if let Some(index) = self.figure_image
&& let Some(Block::Image {
caption: image_caption,
..
}) = self.document.blocks.get_mut(index)
{
*image_caption = Some(caption);
return;
}
self.push_block(Block::Paragraph(caption));
return;
}
if let Some(table) = &mut self.table {
self.current_reference = self.table_number.to_string();
table.caption = Some(caption_with_prefix(
format!("Table {}: ", self.table_number),
caption,
));
return;
}
if self.table_active {
self.current_reference = self.table_number.to_string();
let caption = caption_with_prefix(format!("Table {}: ", self.table_number), caption);
if let Some(index) = self.current_table_block
&& let Some(Block::Table {
caption: table_caption,
..
}) = self.document.blocks.get_mut(index)
{
*table_caption = Some(caption);
} else {
self.pending_table_caption = Some(caption);
}
} else {
self.push_block(Block::Paragraph(caption));
}
}
fn finish_table_cell(&mut self) {
if let Some(table) = &mut self.table {
trim_run_end(&mut table.cell);
let style = table.pending_cell_style.take().unwrap_or_default();
table.row_styles.push(style);
table.row.push(std::mem::take(&mut table.cell));
}
}
fn finish_table_row(&mut self) {
self.finish_table_cell();
if let Some(table) = &mut self.table
&& !table.row.is_empty()
{
table.rows.push(std::mem::take(&mut table.row));
table
.cell_styles
.push(std::mem::take(&mut table.row_styles));
}
}
fn finish_table(&mut self) {
self.finish_table_row();
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('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 {
rows: table.rows,
caption,
alignments: table.alignments,
rules: table.rules,
cell_styles: table.cell_styles,
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);
}
}
}
fn start_bibliography_item(&mut self, key: String) {
self.flush_paragraph();
self.finish_bibliography_item();
if let Some(bibliography) = &mut self.bibliography {
let number = bibliography.items.len() + 1;
self.document.citations.insert(key.clone(), number);
self.current_reference = number.to_string();
bibliography.current = Some((key, Vec::new()));
}
}
fn finish_bibliography_item(&mut self) {
if let Some(bibliography) = &mut self.bibliography
&& let Some((key, mut runs)) = bibliography.current.take()
{
trim_run_end(&mut runs);
bibliography.items.push((key, runs));
}
}
fn finish_bibliography(&mut self) {
self.finish_bibliography_item();
assign_citation_year_suffixes(&mut self.document);
if let Some(mut bibliography) = self.bibliography.take()
&& !bibliography.items.is_empty()
{
apply_bibliography_year_suffixes(&self.document, &mut bibliography.items);
self.push_block(Block::Bibliography(bibliography.items));
}
}
fn finish_list(&mut self) {
if let Some(mut list) = self.lists.pop() {
list.finish_current_item();
if !list.items.is_empty() {
let block = ListBlock {
ordered: list.ordered,
items: list.items,
};
if let Some(parent) = self.lists.last_mut() {
parent.has_current_item = true;
parent.nested.push(block);
} else {
self.push_block(Block::List(block));
}
}
}
}
fn set_table_alignments(&mut self, specification: &str) {
let Some(table) = &mut self.table else {
return;
};
let mut chars = specification.chars().peekable();
while let Some(character) = chars.next() {
match character {
'l' => table.alignments.push(ColumnAlignment::Left),
'c' => table.alignments.push(ColumnAlignment::Center),
'r' => table.alignments.push(ColumnAlignment::Right),
'p' | 'm' | 'b' => {
if chars.peek() == Some(&'{') {
chars.next();
for nested in chars.by_ref() {
if nested == '}' {
break;
}
}
}
table.alignments.push(ColumnAlignment::Left);
}
_ => {}
}
}
}
}
pub fn parse_document(
source: &expanded::ExpandedTokenStream,
paragraph_cache: &mut ParagraphParseCache,
) -> ParsedDocument {
Parser::new().parse(source, paragraph_cache)
}
fn indent_run(indent: common::Scaled) -> Run {
Run {
text: String::new(),
math: None,
kern: Some(indent),
glue: None,
penalty: None,
rule: None,
box_run: None,
unresolved_reference: None,
bold: false,
italic: false,
monospace: false,
sans: false,
small_caps: false,
y_offset: None,
footnote_number: None,
paragraph_indent: true,
alignment: None,
}
}
fn prepend_paragraph_indent(runs: &mut Vec<Run>, indent: common::Scaled) {
if indent.0 > 0 {
runs.insert(0, indent_run(indent));
}
}
fn strip_paragraph_indent(runs: &mut Vec<Run>) {
if runs.first().is_some_and(|run| run.paragraph_indent) {
runs.remove(0);
}
}
fn superscript_number(number: u32) -> String {
number
.to_string()
.chars()
.map(|digit| match digit {
'0' => '⁰',
'1' => '¹',
'2' => '²',
'3' => '³',
'4' => '⁴',
'5' => '⁵',
'6' => '⁶',
'7' => '⁷',
'8' => '⁸',
'9' => '⁹',
other => other,
})
.collect()
}
fn append_run(
runs: &mut Vec<Run>,
mut text: String,
bold: bool,
italic: bool,
monospace: bool,
sans: bool,
small_caps: bool,
) {
if text.is_empty() {
return;
}
if runs.is_empty() || runs.last().is_some_and(|run| run.text.ends_with(' ')) {
text = text.trim_start().to_string();
}
if text.is_empty() {
return;
}
if let Some(last) = runs.last_mut()
&& last.math.is_none()
&& last.kern.is_none()
&& last.glue.is_none()
&& last.penalty.is_none()
&& last.rule.is_none()
&& last.box_run.is_none()
&& last.unresolved_reference.is_none()
&& last.bold == bold
&& last.italic == italic
&& last.monospace == monospace
&& last.sans == sans
&& last.small_caps == small_caps
{
last.text.push_str(&text);
return;
}
runs.push(Run {
text,
math: None,
kern: None,
glue: None,
penalty: None,
rule: None,
box_run: None,
unresolved_reference: None,
bold,
italic,
monospace,
sans,
small_caps,
paragraph_indent: false,
alignment: None,
y_offset: None,
footnote_number: None,
});
}
fn trim_run_end(runs: &mut Vec<Run>) {
if let Some(last) = runs.last_mut() {
last.text = last.text.trim_end().to_string();
if last.text.is_empty()
&& last.kern.is_none()
&& last.glue.is_none()
&& last.penalty.is_none()
&& last.rule.is_none()
&& last.box_run.is_none()
&& last.unresolved_reference.is_none()
{
runs.pop();
}
}
}
fn normalize_whitespace(text: &str) -> String {
let mut output = String::with_capacity(text.len());
let mut previous_whitespace = false;
for character in text.chars() {
if character.is_whitespace() {
if !previous_whitespace {
output.push(' ');
}
previous_whitespace = true;
} else {
output.push(character);
previous_whitespace = false;
}
}
output
}
fn apply_geometry(document: &mut DocumentModel, settings: &str) {
apply_geometry_settings(&mut document.page, &mut document.margins, settings);
}
/// Apply article-class base font size options (10pt, 11pt, 12pt).
fn apply_class_font_size(document: &mut DocumentModel, settings: &str) {
for setting in settings.split(',').map(str::trim) {
let size = match setting {
"10pt" => 10,
"11pt" => 11,
"12pt" => 12,
_ => continue,
};
document.base_font_size = size;
let indent = if size == 11 { 17 } else { 15 };
document.parindent = common::Scaled(indent * 65_536);
}
}
/// 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(',') {
let setting = setting.trim();
if setting.is_empty() {
continue;
}
let (key, value) = match setting.split_once('=') {
Some((key, value)) => (key.trim(), Some(value.trim())),
None => (setting, None),
};
match key {
"a4paper" => *page = PageSize::A4,
"a5paper" => *page = PageSize::A5,
"b5paper" => *page = PageSize::B5,
"letterpaper" => *page = PageSize::LETTER,
"legalpaper" => *page = PageSize::LEGAL,
"executivepaper" => *page = PageSize::EXECUTIVE,
"landscape" => *page = page.landscape(),
"paperwidth" => {
if let Some(value) = value.and_then(parse_dimension) {
page.width_mm = value;
}
}
"paperheight" => {
if let Some(value) = value.and_then(parse_dimension) {
page.height_mm = value;
}
}
_ => {}
}
}
for setting in settings.split(',') {
let Some((key, value)) = setting.split_once('=') else {
continue;
};
let Some(value) = parse_dimension(value.trim()) else {
continue;
};
match key.trim() {
"margin" => {
*margins = PageMargins {
top: value,
right: value,
bottom: value,
left: value,
};
}
"top" | "tmargin" => margins.top = value,
"right" | "rmargin" => margins.right = value,
"bottom" | "bmargin" => margins.bottom = value,
"left" | "lmargin" => margins.left = value,
"hmargin" => {
margins.left = value;
margins.right = value;
}
"vmargin" => {
margins.top = value;
margins.bottom = value;
}
_ => {}
}
}
// Text-block dimensions are resolved after explicit margins so that top
// influences the computed bottom margin in the same settings list.
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;
};
let Some(value) = parse_dimension(value.trim()) else {
continue;
};
match key.trim() {
"textwidth" => {
let side = ((page_width - value) / 2.0).max(0.0);
margins.left = side;
margins.right = side;
}
"textheight" => {
margins.bottom = (page_height - margins.top - value).max(0.0);
}
_ => {}
}
}
}
pub fn parse_dimension(value: &str) -> Option<f64> {
let split = value
.find(|character: char| {
!(character.is_ascii_digit() || character == '.' || character == '-')
})
.unwrap_or(value.len());
let number = value[..split].parse::<f64>().ok()?;
let multiplier = match value[split..].trim() {
"mm" => 1.0,
"cm" => 10.0,
"in" => 25.4,
"pt" => 25.4 / 72.27,
"bp" => 25.4 / 72.0,
"" => return None,
_ => return None,
};
(number.is_finite() && number > 0.0).then_some(number * multiplier)
}
fn caption_with_prefix(prefix: String, caption: Vec<Run>) -> Vec<Run> {
let mut runs = Vec::with_capacity(caption.len() + 1);
runs.push(Run::plain(prefix));
runs.extend(caption);
runs
}