1919 lines
65 KiB
Rust
1919 lines
65 KiB
Rust
use std::collections::{HashMap, VecDeque};
|
|
|
|
use crate::{
|
|
TeXGlue,
|
|
document::{
|
|
Block, ColumnAlignment, DocumentModel, EquationNumber, InlineBox, InlineBoxAlign,
|
|
ListBlock, ListItem, PageMargins, PageSize, ParsedDocument, RuleBox, Run,
|
|
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<usize>,
|
|
}
|
|
|
|
#[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 {
|
|
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;
|
|
};
|
|
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;
|
|
}
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
return start_index;
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
let mut bracket_depth = 0usize;
|
|
let mut group_depth = 0usize;
|
|
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;
|
|
}
|
|
}
|
|
_ => {}
|
|
},
|
|
_ => {}
|
|
}
|
|
}
|
|
start_index
|
|
}
|
|
|
|
struct InlineBoxSpec {
|
|
runs: Vec<Run>,
|
|
width: Option<common::Scaled>,
|
|
align: InlineBoxAlign,
|
|
raise: common::Scaled,
|
|
frame: bool,
|
|
}
|
|
|
|
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; 3],
|
|
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>,
|
|
centered: Option<Vec<Run>>,
|
|
current_source: Option<SourceLocation>,
|
|
paragraph_source: Option<SourceLocation>,
|
|
paragraph_indent: Option<common::Scaled>,
|
|
suppress_indent: bool,
|
|
}
|
|
|
|
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; 3],
|
|
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(),
|
|
centered: None,
|
|
current_source: None,
|
|
paragraph_source: None,
|
|
paragraph_indent: None,
|
|
suppress_indent: 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
|
|
{
|
|
item_index =
|
|
consume_environment_preamble(expanded, item_index, environment);
|
|
}
|
|
|
|
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.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();
|
|
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.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.into_iter().map(|run| run.text).collect::<String>();
|
|
match field {
|
|
expanded::MetadataField::Title => self.document.title = value,
|
|
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::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,
|
|
|
|
sans: false,
|
|
small_caps: false,
|
|
|
|
y_offset: 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::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::MetadataStart(field) => {
|
|
self.metadata_capture = Some((*field, Vec::new()));
|
|
}
|
|
expanded::FrontendEventKind::MetadataEnd(field) => {
|
|
self.finish_metadata(*field);
|
|
}
|
|
expanded::FrontendEventKind::Geometry(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::GroupStart => self.group_depth += 1,
|
|
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);
|
|
}
|
|
expanded::FrontendEventKind::LiteralAmpersand
|
|
| expanded::FrontendEventKind::MathCell => self.append_literal_ampersand(),
|
|
expanded::FrontendEventKind::LiteralCharacter(character) => {
|
|
self.append_text(&character.to_string())
|
|
}
|
|
expanded::FrontendEventKind::LineBreak => self.append_text(" "),
|
|
expanded::FrontendEventKind::RowBreak => {
|
|
if self.table.is_some() {
|
|
self.finish_table_row();
|
|
} else {
|
|
self.append_text(" ");
|
|
}
|
|
}
|
|
expanded::FrontendEventKind::ListItem => self.start_list_item(),
|
|
expanded::FrontendEventKind::TableCell => self.finish_table_cell(),
|
|
expanded::FrontendEventKind::TableRule => {
|
|
if let Some(table) = &mut self.table {
|
|
table.rules.push(table.rows.len());
|
|
}
|
|
}
|
|
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);
|
|
}
|
|
}
|
|
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) => {
|
|
self.append_reference(UnresolvedReference::Citation(
|
|
keys.split(',').map(str::trim).map(str::to_string).collect(),
|
|
))
|
|
}
|
|
expanded::FrontendEventKind::BibliographyItem(key) => {
|
|
self.start_bibliography_item(key.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,
|
|
|
|
sans: false,
|
|
small_caps: false,
|
|
|
|
y_offset: None,
|
|
});
|
|
}
|
|
|
|
fn start_heading(&mut self, level: u8, numbered: bool) {
|
|
self.flush_paragraph();
|
|
self.finish_heading();
|
|
let level = level.clamp(1, 3);
|
|
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_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_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,
|
|
);
|
|
}
|
|
}
|
|
|
|
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,
|
|
|
|
sans: false,
|
|
small_caps: false,
|
|
|
|
y_offset: 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,
|
|
|
|
sans: false,
|
|
small_caps: false,
|
|
|
|
y_offset: 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,
|
|
|
|
sans: false,
|
|
small_caps: false,
|
|
|
|
y_offset: 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,
|
|
|
|
sans: false,
|
|
small_caps: false,
|
|
|
|
y_offset: None,
|
|
});
|
|
}
|
|
|
|
fn target_runs(&mut self) -> &mut Vec<Run> {
|
|
let paragraph_target = self.inline_boxes.is_empty()
|
|
&& self.centered.is_none()
|
|
&& self.framed_box.is_none()
|
|
&& self.metadata_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(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,
|
|
|
|
sans: false,
|
|
small_caps: false,
|
|
|
|
y_offset: None,
|
|
});
|
|
}
|
|
|
|
fn paragraph_break(&mut self) {
|
|
if !self.lists.is_empty() || self.table.is_some() {
|
|
self.append_text(" ");
|
|
} else {
|
|
self.flush_paragraph();
|
|
}
|
|
}
|
|
|
|
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);
|
|
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.figure_active = true;
|
|
self.figure_image = None;
|
|
self.figure_number += 1;
|
|
self.current_reference = self.figure_number.to_string();
|
|
}
|
|
(false, "figure") => {
|
|
self.flush_paragraph();
|
|
self.figure_active = false;
|
|
self.figure_image = None;
|
|
}
|
|
(true, "table") => {
|
|
self.flush_paragraph();
|
|
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, "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, "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.saturating_sub(1).min(2));
|
|
self.section_numbers[index] += 1;
|
|
self.section_numbers[index + 1..].fill(0);
|
|
self.section_numbers[..=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();
|
|
let index = self.document.blocks.len();
|
|
self.push_block(Block::Image {
|
|
path,
|
|
options,
|
|
caption: None,
|
|
});
|
|
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);
|
|
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));
|
|
}
|
|
}
|
|
|
|
fn finish_table(&mut self) {
|
|
self.finish_table_row();
|
|
if let Some(table) = self.table.take()
|
|
&& !table.rows.is_empty()
|
|
{
|
|
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,
|
|
});
|
|
if self.table_active {
|
|
self.current_table_block = Some(index);
|
|
}
|
|
}
|
|
}
|
|
|
|
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();
|
|
if let Some(bibliography) = self.bibliography.take()
|
|
&& !bibliography.items.is_empty()
|
|
{
|
|
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,
|
|
paragraph_indent: true,
|
|
}
|
|
}
|
|
|
|
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 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,
|
|
|
|
y_offset: 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) {
|
|
let page = &mut document.page;
|
|
// 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;
|
|
}
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
|
|
let margins = &mut document.margins;
|
|
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 = document.page.width_mm;
|
|
let page_height = document.page.height_mm;
|
|
let margins = &mut document.margins;
|
|
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
|
|
}
|