558 lines
16 KiB
Rust
558 lines
16 KiB
Rust
use std::{
|
|
collections::{HashMap, HashSet},
|
|
path::PathBuf,
|
|
};
|
|
|
|
use crate::{TeXGlue, math_expr::MathExpr, source::SourceLocation};
|
|
|
|
/// Physical page dimensions in millimetres.
|
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
pub struct PageSize {
|
|
pub width_mm: f64,
|
|
pub height_mm: f64,
|
|
}
|
|
|
|
impl PageSize {
|
|
pub const A4: Self = Self {
|
|
width_mm: 210.0,
|
|
height_mm: 297.0,
|
|
};
|
|
pub const A5: Self = Self {
|
|
width_mm: 148.0,
|
|
height_mm: 210.0,
|
|
};
|
|
pub const B5: Self = Self {
|
|
width_mm: 176.0,
|
|
height_mm: 250.0,
|
|
};
|
|
/// US letter, 8.5 by 11 inches.
|
|
pub const LETTER: Self = Self {
|
|
width_mm: 215.9,
|
|
height_mm: 279.4,
|
|
};
|
|
/// US legal, 8.5 by 14 inches.
|
|
pub const LEGAL: Self = Self {
|
|
width_mm: 215.9,
|
|
height_mm: 355.6,
|
|
};
|
|
/// US executive, 7.25 by 10.5 inches.
|
|
pub const EXECUTIVE: Self = Self {
|
|
width_mm: 184.15,
|
|
height_mm: 266.7,
|
|
};
|
|
|
|
pub fn landscape(self) -> Self {
|
|
Self {
|
|
width_mm: self.height_mm,
|
|
height_mm: self.width_mm,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Default for PageSize {
|
|
fn default() -> Self {
|
|
Self::A4
|
|
}
|
|
}
|
|
|
|
/// Layout style for the document title block.
|
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
|
pub enum TitleStyle {
|
|
/// The generic article title: title, author, date, no rules.
|
|
#[default]
|
|
Article,
|
|
/// Preprint-style title block with rules, an undertitle, and author columns.
|
|
Preprint,
|
|
/// Journal-style title block: title, author/affiliation columns, abstract,
|
|
/// and keywords.
|
|
Journal,
|
|
}
|
|
|
|
/// One author block in a structured front matter.
|
|
#[derive(Clone, Default, PartialEq, Eq)]
|
|
pub struct AuthorBlock {
|
|
pub runs: Vec<Run>,
|
|
/// One-based affiliation indices attached to this author.
|
|
pub affiliations: Vec<usize>,
|
|
pub email: Option<String>,
|
|
/// Author marked with `*` (corresponding author).
|
|
pub corresponding: bool,
|
|
}
|
|
|
|
/// One numbered affiliation in a structured front matter.
|
|
#[derive(Clone, Default, PartialEq, Eq)]
|
|
pub struct Affiliation {
|
|
pub index: usize,
|
|
pub runs: Vec<Run>,
|
|
}
|
|
|
|
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
|
pub struct CitationMetadata {
|
|
pub author: String,
|
|
pub year: String,
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub struct Footnote {
|
|
pub number: u32,
|
|
pub runs: Vec<Run>,
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub struct DocumentModel {
|
|
pub title: String,
|
|
/// Rich title runs, preserving inline emphases such as .
|
|
pub title_runs: Vec<Run>,
|
|
pub author: String,
|
|
pub date: String,
|
|
/// Style selected by the document's class/package layer.
|
|
pub title_style: TitleStyle,
|
|
/// Optional line printed under the title rules, e.g. "A Preprint".
|
|
pub undertitle: Option<String>,
|
|
/// Short title from `\title[short]{long}`.
|
|
pub short_title: Option<String>,
|
|
/// Structured author blocks from `\author` / `\affil` / `\email`.
|
|
pub authors: Vec<AuthorBlock>,
|
|
/// Numbered affiliations from `\affil[n]{...}`.
|
|
pub affiliations: Vec<Affiliation>,
|
|
/// Body of `\abstract{...}` captured for journal title blocks.
|
|
pub abstract_runs: Vec<Run>,
|
|
/// Body of `\keywords{...}` captured for journal title blocks.
|
|
pub keywords: Vec<Run>,
|
|
pub page: PageSize,
|
|
pub parindent: common::Scaled,
|
|
/// Base font size selected by the document class (10, 11, or 12pt).
|
|
/// Number of text columns (1 for article, 2 for `iicol`/`twocolumn`).
|
|
pub columns: u8,
|
|
pub base_font_size: u8,
|
|
pub margins: PageMargins,
|
|
pub show_title: bool,
|
|
pub blocks: Vec<Block>,
|
|
pub block_sources: Vec<Option<SourceLocation>>,
|
|
pub labels: HashMap<String, String>,
|
|
pub citations: HashMap<String, usize>,
|
|
pub citation_metadata: HashMap<String, CitationMetadata>,
|
|
/// Display text -> hyperlink URL for `\href` annotations.
|
|
pub link_targets: HashMap<String, String>,
|
|
pub orcid_urls: Vec<String>,
|
|
/// Bibliography keys in the order their metadata was declared. Needed to
|
|
/// assign natbib-style year suffixes (2014a, 2014b, ...) deterministically.
|
|
pub bibliography_order: Vec<String>,
|
|
pub author_year_citations: bool,
|
|
pub footnotes: Vec<Footnote>,
|
|
pub page_style: PageStyle,
|
|
pub page_style_overrides: Vec<PageStyleOverride>,
|
|
}
|
|
|
|
impl Default for DocumentModel {
|
|
fn default() -> Self {
|
|
Self {
|
|
title: String::new(),
|
|
title_runs: Vec::new(),
|
|
author: String::new(),
|
|
date: String::new(),
|
|
title_style: TitleStyle::default(),
|
|
undertitle: None,
|
|
short_title: None,
|
|
authors: Vec::new(),
|
|
affiliations: Vec::new(),
|
|
abstract_runs: Vec::new(),
|
|
keywords: Vec::new(),
|
|
page: PageSize::default(),
|
|
// article's default \parindent for 10/11pt text.
|
|
parindent: common::Scaled(17 * 65_536),
|
|
columns: 1,
|
|
base_font_size: 10,
|
|
margins: PageMargins::default(),
|
|
show_title: false,
|
|
blocks: Vec::new(),
|
|
block_sources: Vec::new(),
|
|
labels: HashMap::new(),
|
|
citations: HashMap::new(),
|
|
citation_metadata: HashMap::new(),
|
|
link_targets: HashMap::new(),
|
|
orcid_urls: Vec::new(),
|
|
bibliography_order: Vec::new(),
|
|
author_year_citations: false,
|
|
footnotes: Vec::new(),
|
|
page_style: PageStyle::default(),
|
|
page_style_overrides: Vec::new(),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Page style selected by `\pagestyle`.
|
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
|
pub enum PageStyleKind {
|
|
Empty,
|
|
/// LaTeX's default: a centered page number in the footer.
|
|
#[default]
|
|
Plain,
|
|
/// fancyhdr-style header/footer declared with `\fancyhead`/`\fancyfoot`.
|
|
Fancy,
|
|
}
|
|
|
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
|
pub enum PageDecorationPosition {
|
|
#[default]
|
|
Center,
|
|
Left,
|
|
Right,
|
|
}
|
|
|
|
/// Header or footer runs for one edge of the page.
|
|
#[derive(Clone, Default, PartialEq, Eq, Hash)]
|
|
pub struct PageDecoration {
|
|
pub left: Vec<Run>,
|
|
pub center: Vec<Run>,
|
|
pub right: Vec<Run>,
|
|
}
|
|
|
|
impl PageDecoration {
|
|
pub fn slot_mut(&mut self, position: PageDecorationPosition) -> &mut Vec<Run> {
|
|
match position {
|
|
PageDecorationPosition::Left => &mut self.left,
|
|
PageDecorationPosition::Center => &mut self.center,
|
|
PageDecorationPosition::Right => &mut self.right,
|
|
}
|
|
}
|
|
|
|
pub fn is_empty(&self) -> bool {
|
|
self.left.is_empty() && self.center.is_empty() && self.right.is_empty()
|
|
}
|
|
|
|
pub fn clear(&mut self) {
|
|
self.left.clear();
|
|
self.center.clear();
|
|
self.right.clear();
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Default, PartialEq, Eq, Hash)]
|
|
pub struct PageStyle {
|
|
pub kind: PageStyleKind,
|
|
pub header: PageDecoration,
|
|
pub footer: PageDecoration,
|
|
}
|
|
|
|
/// A `\thispagestyle` override, anchored at the block it was issued before.
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
|
pub struct PageStyleOverride {
|
|
pub anchor: usize,
|
|
pub kind: PageStyleKind,
|
|
}
|
|
|
|
/// Marker character used by `\thepage` inside header/footer runs; the page
|
|
/// renderer substitutes the concrete page number before measuring and painting.
|
|
/// Private-use marker for a dotted leader in generated contents lines.
|
|
/// Private-use marker toggling hyperlink paint for the following glyphs.
|
|
pub const LINK_START_MARKER: char = '\u{F3000}';
|
|
pub const LINK_END_MARKER: char = '\u{F3001}';
|
|
|
|
pub const CONTENTS_LEADER_MARKER: char = '\u{F6000}';
|
|
|
|
pub const PAGE_NUMBER_MARKER: char = '\u{F5000}';
|
|
|
|
pub fn page_number_marker_text() -> String {
|
|
PAGE_NUMBER_MARKER.to_string()
|
|
}
|
|
|
|
pub struct ParsedDocument(pub DocumentModel);
|
|
|
|
#[derive(Clone)]
|
|
pub struct PageMargins {
|
|
pub top: f64,
|
|
pub right: f64,
|
|
pub bottom: f64,
|
|
pub left: f64,
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
|
pub struct EquationNumber {
|
|
pub text: String,
|
|
pub parenthesized: bool,
|
|
}
|
|
|
|
impl Default for PageMargins {
|
|
fn default() -> Self {
|
|
Self {
|
|
top: 25.0,
|
|
right: 25.0,
|
|
bottom: 25.0,
|
|
left: 25.0,
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub enum Block {
|
|
Paragraph(Vec<Run>),
|
|
Heading {
|
|
level: u8,
|
|
runs: Vec<Run>,
|
|
},
|
|
List(ListBlock),
|
|
Table {
|
|
rows: Vec<Vec<Vec<Run>>>,
|
|
caption: Option<Vec<Run>>,
|
|
alignments: Vec<ColumnAlignment>,
|
|
rules: Vec<TableRule>,
|
|
/// Per-cell span and alignment metadata, parallel to `rows`.
|
|
cell_styles: Vec<Vec<TableCellStyle>>,
|
|
/// Float placement hints from `[htbp]`.
|
|
placement: String,
|
|
},
|
|
Image {
|
|
path: String,
|
|
options: String,
|
|
caption: Option<Vec<Run>>,
|
|
/// Float placement hints from `[htbp]`.
|
|
placement: String,
|
|
},
|
|
Bibliography(Vec<(String, Vec<Run>)>),
|
|
/// A box such as `\fbox{...}` (framed) or `\parbox{width}{...}`.
|
|
FramedBox {
|
|
runs: Vec<Run>,
|
|
frame: bool,
|
|
width: Option<common::Scaled>,
|
|
},
|
|
/// Center-aligned content produced by the `center` environment.
|
|
Centered {
|
|
runs: Vec<Run>,
|
|
},
|
|
/// A horizontal rule such as `\hrule` (full width when `width` is None).
|
|
HorizontalRule {
|
|
height: common::Scaled,
|
|
width: Option<common::Scaled>,
|
|
},
|
|
Math {
|
|
expression: MathExpr,
|
|
equation_numbers: Vec<Option<EquationNumber>>,
|
|
},
|
|
VerticalKern(common::Scaled),
|
|
VerticalGlue(TeXGlue),
|
|
Penalty(i32),
|
|
PageBreak,
|
|
}
|
|
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
|
pub enum ColumnAlignment {
|
|
Left,
|
|
Center,
|
|
Right,
|
|
}
|
|
|
|
/// Per-cell table metadata: a multicolumn span and an optional local alignment.
|
|
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
|
|
pub struct TableCellStyle {
|
|
pub colspan: usize,
|
|
pub alignment: Option<ColumnAlignment>,
|
|
}
|
|
|
|
/// A horizontal table rule. `end_column` is exclusive; `usize::MAX` means the
|
|
/// rule spans every column.
|
|
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
|
pub struct TableRule {
|
|
pub row: usize,
|
|
pub start_column: usize,
|
|
pub end_column: usize,
|
|
pub trim_left: bool,
|
|
pub trim_right: bool,
|
|
}
|
|
|
|
impl TableRule {
|
|
pub fn full(row: usize) -> Self {
|
|
Self {
|
|
row,
|
|
start_column: 0,
|
|
end_column: usize::MAX,
|
|
trim_left: false,
|
|
trim_right: false,
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, PartialEq, Eq, Hash)]
|
|
pub struct ListBlock {
|
|
pub ordered: bool,
|
|
pub items: Vec<ListItem>,
|
|
}
|
|
|
|
#[derive(Clone, PartialEq, Eq, Hash)]
|
|
pub struct ListItem {
|
|
pub runs: Vec<Run>,
|
|
pub nested: Vec<ListBlock>,
|
|
pub vertical_glue_after: Vec<TeXGlue>,
|
|
}
|
|
|
|
#[derive(Clone, PartialEq, Eq, Hash)]
|
|
pub enum UnresolvedReference {
|
|
Label(String),
|
|
Citation(Vec<String>),
|
|
/// A textual citation such as natbib's `\citet`, rendered as
|
|
/// `Author (year)` instead of a parenthetical citation.
|
|
TextualCitation(Vec<String>),
|
|
/// A table-of-contents/list page number for the block with this index.
|
|
/// The target is resolved to a page number during page layout.
|
|
TocPage(usize),
|
|
}
|
|
|
|
/// Horizontal alignment of a fixed-width inline box.
|
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
|
pub enum InlineBoxAlign {
|
|
#[default]
|
|
Left,
|
|
Center,
|
|
Right,
|
|
}
|
|
|
|
/// An unbreakable inline box such as `\mbox{...}`, `\makebox{...}`,
|
|
/// `\raisebox{...}`, or `\fbox{...}`.
|
|
#[derive(Clone, PartialEq, Eq, Hash)]
|
|
pub struct InlineBox {
|
|
pub runs: Vec<Run>,
|
|
/// Fixed width from `\makebox[width]{...}`, if any.
|
|
pub width: Option<common::Scaled>,
|
|
pub align: InlineBoxAlign,
|
|
/// Vertical lift from `\raisebox{lift}{...}`.
|
|
pub raise: common::Scaled,
|
|
/// Draw a frame around the box (`\fbox`).
|
|
pub frame: bool,
|
|
}
|
|
|
|
/// A filled rectangle produced by `\rule`.
|
|
#[derive(Clone, PartialEq, Eq, Hash)]
|
|
pub struct RuleBox {
|
|
pub width: common::Scaled,
|
|
/// Distance from the baseline to the bottom edge of the ink.
|
|
///
|
|
/// A positive raise leaves a gap between the baseline and the rule; a
|
|
/// negative raise moves the rule below the baseline.
|
|
pub raise: common::Scaled,
|
|
/// Thickness of the rule.
|
|
pub height: common::Scaled,
|
|
/// Optional fill colour; means the regular black rule.
|
|
pub color: Option<[u8; 3]>,
|
|
pub image: Option<String>,
|
|
}
|
|
|
|
/// Paragraph-level alignment requested by `\raggedright` or `\raggedleft`.
|
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
|
pub enum ParagraphAlignment {
|
|
#[default]
|
|
Justified,
|
|
RaggedRight,
|
|
RaggedLeft,
|
|
Centered,
|
|
Quote,
|
|
}
|
|
|
|
#[derive(Clone, PartialEq, Eq, Hash)]
|
|
pub struct Run {
|
|
pub text: String,
|
|
pub math: Option<MathExpr>,
|
|
pub kern: Option<common::Scaled>,
|
|
pub glue: Option<TeXGlue>,
|
|
pub penalty: Option<i32>,
|
|
pub rule: Option<RuleBox>,
|
|
pub box_run: Option<InlineBox>,
|
|
pub y_offset: Option<common::Scaled>,
|
|
pub footnote_number: Option<u32>,
|
|
pub unresolved_reference: Option<UnresolvedReference>,
|
|
pub bold: bool,
|
|
pub italic: bool,
|
|
pub monospace: bool,
|
|
pub sans: bool,
|
|
pub small_caps: bool,
|
|
/// Hyperlink text (rendered in the hyperref link colour).
|
|
pub link: bool,
|
|
/// True for the synthetic kern that carries paragraph indentation.
|
|
pub paragraph_indent: bool,
|
|
/// Alignment declaration active when this run started its paragraph.
|
|
pub alignment: Option<ParagraphAlignment>,
|
|
}
|
|
|
|
impl Run {
|
|
pub fn plain(text: String) -> Self {
|
|
Self {
|
|
text,
|
|
math: None,
|
|
kern: None,
|
|
glue: None,
|
|
penalty: None,
|
|
rule: None,
|
|
box_run: None,
|
|
y_offset: None,
|
|
footnote_number: None,
|
|
unresolved_reference: None,
|
|
bold: false,
|
|
italic: false,
|
|
monospace: false,
|
|
sans: false,
|
|
small_caps: false,
|
|
link: false,
|
|
paragraph_indent: false,
|
|
alignment: None,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl DocumentModel {
|
|
pub fn math_font_files(&self) -> HashSet<PathBuf> {
|
|
fn collect_runs(runs: &[Run], files: &mut HashSet<PathBuf>) {
|
|
for run in runs {
|
|
if let Some(expression) = &run.math {
|
|
expression.collect_math_font_files(files);
|
|
}
|
|
}
|
|
}
|
|
|
|
fn collect_list(list: &ListBlock, files: &mut HashSet<PathBuf>) {
|
|
for item in &list.items {
|
|
collect_runs(&item.runs, files);
|
|
for nested in &item.nested {
|
|
collect_list(nested, files);
|
|
}
|
|
}
|
|
}
|
|
|
|
let mut files = HashSet::new();
|
|
for block in &self.blocks {
|
|
match block {
|
|
Block::Paragraph(runs) | Block::Heading { runs, .. } => {
|
|
collect_runs(runs, &mut files);
|
|
}
|
|
Block::List(list) => collect_list(list, &mut files),
|
|
Block::Table { rows, caption, .. } => {
|
|
for cell in rows.iter().flatten() {
|
|
collect_runs(cell, &mut files);
|
|
}
|
|
if let Some(caption) = caption {
|
|
collect_runs(caption, &mut files);
|
|
}
|
|
}
|
|
Block::Image { caption, .. } => {
|
|
if let Some(caption) = caption {
|
|
collect_runs(caption, &mut files);
|
|
}
|
|
}
|
|
Block::FramedBox { runs, .. } | Block::Centered { runs } => {
|
|
collect_runs(runs, &mut files);
|
|
}
|
|
Block::Bibliography(items) => {
|
|
for (_, runs) in items {
|
|
collect_runs(runs, &mut files);
|
|
}
|
|
}
|
|
Block::Math { expression, .. } => expression.collect_math_font_files(&mut files),
|
|
Block::HorizontalRule { .. }
|
|
| Block::VerticalKern(_)
|
|
| Block::VerticalGlue(_)
|
|
| Block::Penalty(_)
|
|
| Block::PageBreak => {}
|
|
}
|
|
}
|
|
files
|
|
}
|
|
}
|