10768 lines
384 KiB
Rust
Executable File
10768 lines
384 KiB
Rust
Executable File
//! Route-D preview endpoints: a small, independent TeX-style page pipeline.
|
||
//!
|
||
//! These endpoints are intentionally separate from the v1 `DocumentModel`
|
||
//! preview. They demonstrate checkpointed, page-hashed output from the route-D
|
||
//! core. The v1 preview remains the default and the fallback.
|
||
|
||
use std::cell::RefCell;
|
||
use std::collections::HashMap;
|
||
use std::fmt::Write as _;
|
||
use std::sync::{Mutex, OnceLock};
|
||
|
||
use texrra_tex_core::cmr10::Cmr10Metrics;
|
||
use texrra_tex_core::math::{AlignedRow, MathAtom, parse_math, split_math_lines};
|
||
use texrra_tex_core::paragraph::HorizontalItem;
|
||
use texrra_tex_core::pdf::{
|
||
PageOrigin, PdfMetadata, PdfOutlineEntry, display_lists_to_pdf_with_cm_type1_and_metadata,
|
||
};
|
||
pub use texrra_tex_core::render::RasterImage;
|
||
use texrra_tex_core::render::{DisplayItem, DisplayList, FontFace};
|
||
use texrra_tex_core::{
|
||
Document, Engine, FloatPlacement, InsertionClass, ParagraphFont, ParagraphStyle, Unit,
|
||
VerticalItem,
|
||
};
|
||
|
||
const SCALE: i64 = 65_536;
|
||
|
||
thread_local! {
|
||
static ROUTE_D_SESSION: RefCell<Option<(Document, Engine)>> = const { RefCell::new(None) };
|
||
}
|
||
|
||
struct ProjectSession {
|
||
paragraphs: Vec<SourceParagraph>,
|
||
geometry: PageGeometry,
|
||
engine: Engine,
|
||
}
|
||
|
||
fn project_sessions() -> &'static Mutex<HashMap<String, ProjectSession>> {
|
||
static SESSIONS: OnceLock<Mutex<HashMap<String, ProjectSession>>> = OnceLock::new();
|
||
SESSIONS.get_or_init(|| Mutex::new(HashMap::new()))
|
||
}
|
||
|
||
fn latex_body(source: &str) -> &str {
|
||
let body = source
|
||
.split_once("\\begin{document}")
|
||
.map_or(source, |(_, body)| body);
|
||
body.split("\\end{document}").next().unwrap_or(body)
|
||
}
|
||
|
||
/// Project-scoped route-D preview. Reuses the previous engine when the
|
||
/// paragraph list is unchanged and applies each changed paragraph through
|
||
/// `Engine::edit`, starting from the earliest changed paragraph. Structural
|
||
/// edits fall back to a full layout. The v1 project preview remains the default.
|
||
#[allow(dead_code)] // Kept as the no-image entry point for callers and tests.
|
||
pub fn project_preview_json(project_id: &str, source: &str) -> Result<String, String> {
|
||
project_preview_json_with_images(project_id, source, &HashMap::new())
|
||
}
|
||
|
||
/// Project preview with project images decoded into raster data.
|
||
pub fn project_preview_json_with_images(
|
||
project_id: &str,
|
||
source: &str,
|
||
images: &HashMap<String, RasterImage>,
|
||
) -> Result<String, String> {
|
||
let (body, mut geometry) = geometry_and_body(source);
|
||
geometry.images = images.clone();
|
||
let body = resolve_page_references(body, &geometry);
|
||
let paragraphs = paragraphs_with_geometry(
|
||
&body,
|
||
&geometry.theorem_definitions,
|
||
geometry_counter(&geometry, "equation"),
|
||
&geometry,
|
||
)?;
|
||
let mut document = build_document(¶graphs, &geometry);
|
||
apply_geometry(&mut document, &geometry);
|
||
let mut sessions = project_sessions()
|
||
.lock()
|
||
.map_err(|_| "route-D session lock".to_string())?;
|
||
let previous = sessions.remove(project_id);
|
||
let (engine, changed, recomputed) = match previous {
|
||
Some(mut session) => {
|
||
if session.paragraphs == paragraphs && session.geometry == geometry {
|
||
(session.engine, Vec::new(), 0)
|
||
} else if session.geometry == geometry
|
||
&& session
|
||
.paragraphs
|
||
.iter()
|
||
.all(|paragraph| paragraph.footnotes.is_empty())
|
||
&& paragraphs
|
||
.iter()
|
||
.all(|paragraph| paragraph.footnotes.is_empty())
|
||
{
|
||
let prefix = session
|
||
.paragraphs
|
||
.iter()
|
||
.zip(¶graphs)
|
||
.take_while(|(a, b)| a == b)
|
||
.count();
|
||
if prefix > 0 && prefix < session.paragraphs.len() && prefix < paragraphs.len() {
|
||
session.engine.relayout_from(&document, prefix);
|
||
let changed = session.engine.changed_pages().to_vec();
|
||
let recomputed = session.engine.recomputed_pages();
|
||
(session.engine, changed, recomputed)
|
||
} else {
|
||
let engine = layout_document(&document);
|
||
let changed: Vec<usize> = (0..engine.pages().len()).collect();
|
||
let recomputed = changed.len();
|
||
(engine, changed, recomputed)
|
||
}
|
||
} else {
|
||
let engine = layout_document(&document);
|
||
let changed: Vec<usize> = (0..engine.pages().len()).collect();
|
||
let recomputed = changed.len();
|
||
(engine, changed, recomputed)
|
||
}
|
||
}
|
||
_ => {
|
||
let engine = layout_document(&document);
|
||
let changed: Vec<usize> = (0..engine.pages().len()).collect();
|
||
let recomputed = changed.len();
|
||
(engine, changed, recomputed)
|
||
}
|
||
};
|
||
let mut warnings = source_warnings(source);
|
||
warnings.extend(document_warnings(&document));
|
||
let json = render_json(
|
||
&document,
|
||
&engine,
|
||
Some((&changed, recomputed)),
|
||
&geometry,
|
||
&warnings,
|
||
);
|
||
sessions.insert(
|
||
project_id.to_string(),
|
||
ProjectSession {
|
||
paragraphs,
|
||
geometry,
|
||
engine,
|
||
},
|
||
);
|
||
Ok(json)
|
||
}
|
||
|
||
/// Page geometry pulled out of the source preamble.
|
||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||
struct PageGeometry {
|
||
origin: PageOrigin,
|
||
paper_width: Option<i64>,
|
||
paper_height: Option<i64>,
|
||
vsize: Option<i64>,
|
||
textheight: Option<i64>,
|
||
/// `\textwidth` / `\hsize` / `\linewidth`, in scaled points.
|
||
line_width: Option<i64>,
|
||
par_indent: Option<i64>,
|
||
par_skip: Option<i64>,
|
||
par_skip_stretch: Option<i64>,
|
||
par_skip_shrink: Option<i64>,
|
||
baseline_skip: Option<i64>,
|
||
/// `\linespread` factor in thousandths.
|
||
linespread: Option<i64>,
|
||
/// `\tabcolsep` on each side of a tabular column.
|
||
tab_col_sep: Option<i64>,
|
||
/// `\itemsep` between list items, as width/stretch/shrink.
|
||
item_sep: Option<(i64, i64, i64)>,
|
||
/// `\topsep` above a list, as width/stretch/shrink.
|
||
top_sep: Option<(i64, i64, i64)>,
|
||
/// `\partopsep` added to `\topsep` when the list starts a paragraph.
|
||
part_op_sep: Option<(i64, i64, i64)>,
|
||
/// `\arraystretch` factor in thousandths.
|
||
array_stretch: Option<i64>,
|
||
/// `\\figurename` used as the caption prefix.
|
||
figure_name: Option<String>,
|
||
/// `\\tablename` used as the caption prefix.
|
||
table_name: Option<String>,
|
||
/// `\\abstractname` heading text.
|
||
abstract_name: Option<String>,
|
||
/// `\\refname` heading for the bibliography.
|
||
ref_name: Option<String>,
|
||
/// `\\contentsname` heading for the table of contents.
|
||
contents_name: Option<String>,
|
||
/// `\\listfigurename` heading for the list of figures.
|
||
list_figure_name: Option<String>,
|
||
/// `\\listtablename` heading for the list of tables.
|
||
list_table_name: Option<String>,
|
||
/// `\\setcounter` assignments keyed by counter name.
|
||
counters: Vec<(String, u32)>,
|
||
/// Named lengths declared with `\newlength` and their current values.
|
||
lengths: Vec<(String, i64)>,
|
||
/// `\pagenumbering` style used for the printed page numbers.
|
||
page_numbering: Option<String>,
|
||
/// Zero-based page counter offset set with `\setcounter{page}`.
|
||
page_start: u32,
|
||
/// `\pagestyle{empty}` suppresses the printed page number.
|
||
suppress_page_numbers: bool,
|
||
/// `\thispagestyle{empty}` suppresses the number on the first page.
|
||
suppress_first_page_number: bool,
|
||
left_skip: Option<i64>,
|
||
right_skip: Option<i64>,
|
||
tolerance: Option<i64>,
|
||
pretolerance: Option<i64>,
|
||
looseness: Option<i64>,
|
||
emergency_stretch: Option<i64>,
|
||
hang_indent: Option<i64>,
|
||
hang_after: Option<i64>,
|
||
french_spacing: Option<bool>,
|
||
space_skip: Option<(i64, i64, i64)>,
|
||
xspace_skip: Option<(i64, i64, i64)>,
|
||
hyphenation_exceptions: Vec<String>,
|
||
par_shape: Vec<(i64, i64)>,
|
||
lineskip: Option<i64>,
|
||
lineskiplimit: Option<i64>,
|
||
par_fillskip: Option<(i64, i64, bool)>,
|
||
top_skip: Option<i64>,
|
||
max_depth: Option<i64>,
|
||
split_top_skip: Option<i64>,
|
||
split_max_depth: Option<i64>,
|
||
hyphen_penalty: Option<i64>,
|
||
ex_hyphen_penalty: Option<i64>,
|
||
double_hyphen_demerits: Option<i64>,
|
||
final_hyphen_demerits: Option<i64>,
|
||
line_penalty: Option<i64>,
|
||
adj_demerits: Option<i64>,
|
||
space_factor_codes: Vec<(char, i64)>,
|
||
/// Base font size from `\documentclass[11pt]`-style options.
|
||
base_font_size: Option<i64>,
|
||
/// Captured `tabular` environments: (column spec, halign source).
|
||
tabular: Vec<(String, String, Option<i64>)>,
|
||
/// `\title{...}` captured from the preamble.
|
||
title: Option<String>,
|
||
/// `\author{...}` captured from the preamble.
|
||
author: Option<String>,
|
||
/// `\date{...}` captured from the preamble.
|
||
date: Option<String>,
|
||
pdf_title: Option<String>,
|
||
pdf_author: Option<String>,
|
||
pdf_subject: Option<String>,
|
||
pdf_keywords: Option<String>,
|
||
/// `thebibliography` entries: label key and entry text, in order.
|
||
bibliography: Vec<(String, String)>,
|
||
/// `\newtheorem` definitions from the preamble.
|
||
theorem_definitions: Vec<TheoremDefinition>,
|
||
/// `\newcommand` definitions from the preamble.
|
||
macros: Vec<MacroDefinition>,
|
||
environments: Vec<EnvironmentDefinition>,
|
||
/// `\newif` boolean flags declared in the preamble.
|
||
conditionals: Vec<ConditionalDefinition>,
|
||
/// Decoded images keyed by `\includegraphics` path.
|
||
images: HashMap<String, RasterImage>,
|
||
/// Directories searched for `\includegraphics` paths.
|
||
graphics_paths: Vec<String>,
|
||
/// `\setcounter{secnumdepth}`; article defaults to 3.
|
||
secnumdepth: Option<u32>,
|
||
/// `\setcounter{tocdepth}`; article defaults to 3.
|
||
tocdepth: Option<u32>,
|
||
}
|
||
|
||
/// A `\newtheorem` declaration: display name, shared counter and section scope.
|
||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||
struct TheoremDefinition {
|
||
name: String,
|
||
display: String,
|
||
shared: Option<String>,
|
||
within: Option<String>,
|
||
starred: bool,
|
||
}
|
||
|
||
/// A user macro captured from `\newcommand` or `\def`.
|
||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||
struct MacroDefinition {
|
||
name: String,
|
||
args: u8,
|
||
default: Option<String>,
|
||
body: String,
|
||
}
|
||
|
||
/// A `\newenvironment` definition expanded textually in the body.
|
||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||
struct EnvironmentDefinition {
|
||
name: String,
|
||
args: u8,
|
||
begin: String,
|
||
end: String,
|
||
}
|
||
|
||
/// A `\newif` boolean flag and its current value.
|
||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||
struct ConditionalDefinition {
|
||
name: String,
|
||
value: bool,
|
||
}
|
||
|
||
/// Consume a braced group; the returned count includes the closing brace.
|
||
fn take_group_after_open(text: &str) -> Option<(String, usize)> {
|
||
let mut depth = 0_i32;
|
||
for (offset, character) in text.char_indices() {
|
||
match character {
|
||
'{' => depth += 1,
|
||
'}' if depth == 0 => {
|
||
return Some((text[..offset].to_string(), offset + 1));
|
||
}
|
||
'}' => depth -= 1,
|
||
_ => {}
|
||
}
|
||
}
|
||
None
|
||
}
|
||
|
||
/// Parse `\newcommand{\name}[n]{body}` (and renew/provide variants).
|
||
fn environment_definition(line: &str) -> Option<EnvironmentDefinition> {
|
||
let rest = line
|
||
.strip_prefix("\\newenvironment")
|
||
.or_else(|| line.strip_prefix("\\renewenvironment"))?;
|
||
let rest = rest.trim_start();
|
||
let rest = rest.strip_prefix('*').unwrap_or(rest).trim_start();
|
||
let (name, consumed) = braced_group(rest)?;
|
||
let mut rest = rest[consumed..].trim_start();
|
||
let mut args = 0_u8;
|
||
if let Some(after_bracket) = rest.strip_prefix('[') {
|
||
let close = after_bracket.find(']')?;
|
||
args = after_bracket[..close].trim().parse().ok()?;
|
||
rest = after_bracket[close + 1..].trim_start();
|
||
}
|
||
if rest.starts_with('[') {
|
||
return None;
|
||
}
|
||
let (begin, consumed) = braced_group(rest)?;
|
||
let rest = rest[consumed..].trim_start();
|
||
let (end, _) = braced_group(rest)?;
|
||
let name = name.trim().to_string();
|
||
if name.is_empty() {
|
||
return None;
|
||
}
|
||
Some(EnvironmentDefinition {
|
||
name,
|
||
args,
|
||
begin: begin.to_string(),
|
||
end: end.to_string(),
|
||
})
|
||
}
|
||
|
||
fn control_sequence(text: &str) -> Option<(String, usize)> {
|
||
let after_slash = text.strip_prefix('\\')?;
|
||
let first = after_slash.chars().next()?;
|
||
let length = if first.is_ascii_alphabetic() {
|
||
after_slash
|
||
.find(|character: char| !character.is_ascii_alphabetic())
|
||
.unwrap_or(after_slash.len())
|
||
} else {
|
||
first.len_utf8()
|
||
};
|
||
Some((format!("\\{}", &after_slash[..length]), length + 1))
|
||
}
|
||
|
||
fn definition_argument_count(params: &str) -> Option<u8> {
|
||
let mut count = 0_u8;
|
||
let mut characters = params.chars().peekable();
|
||
while let Some(character) = characters.next() {
|
||
if character.is_whitespace() {
|
||
continue;
|
||
}
|
||
if character != '#' {
|
||
return None;
|
||
}
|
||
let digit = characters.next()?.to_digit(10)?;
|
||
if digit == 0 || digit > 9 {
|
||
return None;
|
||
}
|
||
count = count.max(digit as u8);
|
||
}
|
||
Some(count)
|
||
}
|
||
|
||
fn macro_alias(line: &str) -> Option<(String, String)> {
|
||
let rest = line.strip_prefix("\\let")?.trim_start();
|
||
let (name, consumed) = control_sequence(rest)?;
|
||
let rest = rest[consumed..].trim_start();
|
||
let rest = rest.strip_prefix('=').unwrap_or(rest).trim_start();
|
||
let (target, _) = control_sequence(rest)?;
|
||
Some((name, target))
|
||
}
|
||
|
||
fn macro_definition(line: &str) -> Option<MacroDefinition> {
|
||
if let Some(rest) = line.strip_prefix("\\def") {
|
||
let rest = rest.trim_start();
|
||
let (name, consumed) = control_sequence(rest)?;
|
||
let rest = &rest[consumed..];
|
||
let open = rest.find('{')?;
|
||
let args = definition_argument_count(&rest[..open])?;
|
||
let (body, _) = take_group_after_open(&rest[open + 1..])?;
|
||
return Some(MacroDefinition {
|
||
name,
|
||
args,
|
||
default: None,
|
||
body,
|
||
});
|
||
}
|
||
let rest = line
|
||
.strip_prefix("\\newcommand")
|
||
.or_else(|| line.strip_prefix("\\renewcommand"))
|
||
.or_else(|| line.strip_prefix("\\providecommand"))?;
|
||
let rest = rest.trim_start();
|
||
let rest = rest.strip_prefix('*').unwrap_or(rest).trim_start();
|
||
let (name, rest) = if let Some(after_open) = rest.strip_prefix('{') {
|
||
let close = after_open.find('}')?;
|
||
(
|
||
after_open[..close].trim().to_string(),
|
||
&after_open[close + 1..],
|
||
)
|
||
} else {
|
||
let after_slash = rest.strip_prefix('\\')?;
|
||
let length = after_slash
|
||
.find(|character: char| !character.is_ascii_alphabetic())
|
||
.unwrap_or(after_slash.len());
|
||
(
|
||
format!("\\{}", &after_slash[..length]),
|
||
&after_slash[length..],
|
||
)
|
||
};
|
||
if name.is_empty() {
|
||
return None;
|
||
}
|
||
let mut rest = rest.trim_start();
|
||
let mut args = 0_u8;
|
||
if let Some(after_bracket) = rest.strip_prefix('[') {
|
||
let close = after_bracket.find(']')?;
|
||
args = after_bracket[..close].trim().parse().ok()?;
|
||
rest = &after_bracket[close + 1..];
|
||
}
|
||
let mut rest = rest.trim_start();
|
||
let mut default = None;
|
||
if let Some(after_bracket) = rest.strip_prefix('[') {
|
||
let close = after_bracket.find(']')?;
|
||
default = Some(after_bracket[..close].to_string());
|
||
rest = &after_bracket[close + 1..];
|
||
}
|
||
let rest = rest.trim_start();
|
||
let body = rest.strip_prefix('{')?;
|
||
let (body, _) = take_group_after_open(body)?;
|
||
Some(MacroDefinition {
|
||
name,
|
||
args,
|
||
default,
|
||
body,
|
||
})
|
||
}
|
||
|
||
/// Replace `#1`..`#9` in a macro body with its arguments.
|
||
fn substitute_macro_args(body: &str, args: &[String]) -> String {
|
||
let mut output = String::with_capacity(body.len());
|
||
let mut characters = body.chars().peekable();
|
||
while let Some(character) = characters.next() {
|
||
if character == '#' {
|
||
if let Some(next) = characters.peek().copied() {
|
||
if let Some(index) = next.to_digit(10) {
|
||
if index >= 1 && (index as usize) <= args.len() {
|
||
output.push_str(&args[index as usize - 1]);
|
||
characters.next();
|
||
continue;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
output.push(character);
|
||
}
|
||
output
|
||
}
|
||
|
||
/// Collect `count` braced arguments starting at `text`; the count is bytes
|
||
/// consumed including leading whitespace and braces.
|
||
fn macro_arguments(text: &str, count: u8) -> Option<(Vec<String>, usize)> {
|
||
let mut args = Vec::new();
|
||
let mut consumed = 0_usize;
|
||
let mut cursor = text;
|
||
for _ in 0..count {
|
||
let trimmed = cursor.trim_start();
|
||
consumed += cursor.len() - trimmed.len();
|
||
cursor = trimmed;
|
||
let after_open = cursor.strip_prefix('{')?;
|
||
let (argument, used) = take_group_after_open(after_open)?;
|
||
args.push(argument);
|
||
consumed += 1 + used;
|
||
cursor = &after_open[used..];
|
||
}
|
||
Some((args, consumed))
|
||
}
|
||
|
||
/// Expand user macros in a single pass, repeating until nothing changes.
|
||
fn expand_links(source: &str) -> String {
|
||
let mut output = Vec::new();
|
||
let mut verbatim = false;
|
||
for line in source.lines() {
|
||
let trimmed = line.trim();
|
||
if trimmed.starts_with("\\begin{verbatim}") {
|
||
verbatim = true;
|
||
output.push(line.to_string());
|
||
continue;
|
||
}
|
||
if trimmed.starts_with("\\end{verbatim}") {
|
||
verbatim = false;
|
||
output.push(line.to_string());
|
||
continue;
|
||
}
|
||
if verbatim {
|
||
output.push(line.to_string());
|
||
continue;
|
||
}
|
||
output.push(expand_links_line(line));
|
||
}
|
||
output.join("\n")
|
||
}
|
||
|
||
fn expand_links_line(line: &str) -> String {
|
||
let mut output = String::new();
|
||
let mut rest = line;
|
||
loop {
|
||
// `\href` survives to the paragraph builder so it can become a link annotation.
|
||
let href: Option<usize> = None;
|
||
let url = rest.find("\\url");
|
||
let choice = match (href, url) {
|
||
(Some(left), Some(right)) if left <= right => Some((left, "\\href")),
|
||
(Some(left), None) => Some((left, "\\href")),
|
||
(_, Some(right)) => Some((right, "\\url")),
|
||
_ => None,
|
||
};
|
||
let Some((position, command)) = choice else {
|
||
output.push_str(rest);
|
||
break;
|
||
};
|
||
output.push_str(&rest[..position]);
|
||
let after = &rest[position + command.len()..];
|
||
if command == "\\href" {
|
||
let Some((_url, used)) = braced_group(after) else {
|
||
output.push_str(command);
|
||
rest = after;
|
||
continue;
|
||
};
|
||
let remainder = &after[used..];
|
||
let Some((text, used_text)) = braced_group(remainder) else {
|
||
output.push_str(command);
|
||
rest = after;
|
||
continue;
|
||
};
|
||
output.push_str(&text);
|
||
rest = &remainder[used_text..];
|
||
} else {
|
||
let Some((target, used)) = braced_group(after) else {
|
||
output.push_str(command);
|
||
rest = after;
|
||
continue;
|
||
};
|
||
output.push_str("\\texttt{");
|
||
output.push_str(&target);
|
||
output.push('}');
|
||
rest = &after[used..];
|
||
}
|
||
}
|
||
output
|
||
}
|
||
|
||
fn expand_macros(source: &str, macros: &[MacroDefinition]) -> String {
|
||
if macros.is_empty() {
|
||
return source.to_string();
|
||
}
|
||
let mut text = source.to_string();
|
||
for _ in 0..8 {
|
||
let mut output = String::with_capacity(text.len());
|
||
let mut index = 0;
|
||
let mut changed = false;
|
||
while index < text.len() {
|
||
let rest = &text[index..];
|
||
if let Some(after_slash) = rest.strip_prefix('\\') {
|
||
let length = after_slash
|
||
.find(|character: char| !character.is_ascii_alphabetic())
|
||
.unwrap_or(after_slash.len());
|
||
if length > 0 {
|
||
let name = format!("\\{}", &after_slash[..length]);
|
||
if let Some(definition) = macros.iter().find(|macro_| macro_.name == name) {
|
||
let tail = &after_slash[length..];
|
||
let mut args = Vec::new();
|
||
let mut consumed = 0_usize;
|
||
let mut supplied_default = false;
|
||
if let Some(default) = &definition.default {
|
||
let trimmed = tail.trim_start();
|
||
let spaces = tail.len() - trimmed.len();
|
||
if let Some(after_bracket) = trimmed.strip_prefix('[') {
|
||
if let Some(close) = after_bracket.find(']') {
|
||
args.push(after_bracket[..close].to_string());
|
||
consumed = spaces + 1 + close + 1;
|
||
supplied_default = true;
|
||
}
|
||
}
|
||
if !supplied_default {
|
||
args.push(default.clone());
|
||
}
|
||
}
|
||
let required = definition.args.saturating_sub(args.len() as u8);
|
||
if let Some((rest_args, used)) =
|
||
macro_arguments(&tail[consumed..], required)
|
||
{
|
||
args.extend(rest_args);
|
||
output.push_str(&substitute_macro_args(&definition.body, &args));
|
||
index += 1 + length + consumed + used;
|
||
changed = true;
|
||
continue;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
let character = rest.chars().next().expect("non-empty tail");
|
||
output.push(character);
|
||
index += character.len_utf8();
|
||
}
|
||
text = output;
|
||
if !changed {
|
||
break;
|
||
}
|
||
}
|
||
text
|
||
}
|
||
|
||
/// Find the matching `\end{name}` for an already-opened environment and
|
||
/// return the body plus the bytes consumed through the closing command.
|
||
fn environment_body(text: &str, name: &str) -> Option<(String, usize)> {
|
||
let begin = format!("\\begin{{{}}}", name);
|
||
let end = format!("\\end{{{}}}", name);
|
||
let mut depth = 1_usize;
|
||
let mut cursor = 0_usize;
|
||
while cursor < text.len() {
|
||
let next_begin = text[cursor..].find(&begin).map(|offset| cursor + offset);
|
||
let next_end = text[cursor..].find(&end).map(|offset| cursor + offset);
|
||
match (next_begin, next_end) {
|
||
(Some(begin_at), Some(end_at)) if begin_at < end_at => {
|
||
depth += 1;
|
||
cursor = begin_at + begin.len();
|
||
}
|
||
(_, Some(end_at)) => {
|
||
depth -= 1;
|
||
if depth == 0 {
|
||
return Some((text[..end_at].to_string(), end_at + end.len()));
|
||
}
|
||
cursor = end_at + end.len();
|
||
}
|
||
(Some(begin_at), None) => {
|
||
depth += 1;
|
||
cursor = begin_at + begin.len();
|
||
}
|
||
(None, None) => return None,
|
||
}
|
||
}
|
||
None
|
||
}
|
||
|
||
fn expand_environments(source: &str, definitions: &[EnvironmentDefinition]) -> String {
|
||
if definitions.is_empty() {
|
||
return source.to_string();
|
||
}
|
||
let mut text = source.to_string();
|
||
for _ in 0..8 {
|
||
let mut output = String::with_capacity(text.len());
|
||
let mut index = 0_usize;
|
||
let mut changed = false;
|
||
while index < text.len() {
|
||
let rest = &text[index..];
|
||
if let Some(after) = rest.strip_prefix("\\begin{")
|
||
&& let Some(close) = after.find('}')
|
||
{
|
||
let name = &after[..close];
|
||
if let Some(definition) = definitions
|
||
.iter()
|
||
.find(|definition| definition.name == name)
|
||
{
|
||
let after_begin = &after[close + 1..];
|
||
if let Some((args, consumed)) = macro_arguments(after_begin, definition.args) {
|
||
let content_start = index + "\\begin{".len() + close + 1 + consumed;
|
||
if let Some((inner, end_len)) =
|
||
environment_body(&text[content_start..], name)
|
||
{
|
||
let expanded_inner = expand_environments(&inner, definitions);
|
||
output.push_str(&substitute_macro_args(&definition.begin, &args));
|
||
output.push_str(&expanded_inner);
|
||
output.push_str(&substitute_macro_args(&definition.end, &args));
|
||
index = content_start + end_len;
|
||
changed = true;
|
||
continue;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
let character = rest.chars().next().expect("non-empty tail");
|
||
output.push(character);
|
||
index += character.len_utf8();
|
||
}
|
||
text = output;
|
||
if !changed {
|
||
break;
|
||
}
|
||
}
|
||
text
|
||
}
|
||
|
||
fn newtheorem_definition(line: &str) -> Option<TheoremDefinition> {
|
||
let rest = line.strip_prefix("\\newtheorem")?;
|
||
let (starred, rest) = match rest.strip_prefix('*') {
|
||
Some(rest) => (true, rest),
|
||
None => (false, rest),
|
||
};
|
||
let rest = rest.trim_start();
|
||
let (name, consumed) = braced_group(rest)?;
|
||
let mut rest = rest[consumed..].trim_start();
|
||
let mut shared = None;
|
||
if let Some(tail) = rest.strip_prefix('[') {
|
||
let (counter, tail) = tail.split_once(']')?;
|
||
shared = Some(counter.trim().to_string());
|
||
rest = tail.trim_start();
|
||
}
|
||
let (display, consumed) = braced_group(rest)?;
|
||
let rest = rest[consumed..].trim_start();
|
||
let within = rest
|
||
.strip_prefix('[')
|
||
.and_then(|tail| tail.split_once(']'))
|
||
.map(|(counter, _)| counter.trim().to_string());
|
||
let name = name.trim();
|
||
let display = display.trim();
|
||
if name.is_empty() || display.is_empty() {
|
||
return None;
|
||
}
|
||
Some(TheoremDefinition {
|
||
name: name.to_string(),
|
||
display: display.to_string(),
|
||
shared,
|
||
within,
|
||
starred,
|
||
})
|
||
}
|
||
|
||
/// Pull `\hoffset`/`\voffset`/`\paperwidth`/`\paperheight`/`\vsize`/
|
||
/// `\textheight` assignments out of the source and return the remaining body.
|
||
/// Each command takes a TeX dimension. LaTeX resets `\vsize` from
|
||
/// `\textheight` at every page, so `\textheight` wins when both appear.
|
||
/// Read the base font size from a class option list such as
|
||
/// `\documentclass[11pt,a4paper]{article}`.
|
||
fn document_class_size(line: &str) -> Option<i64> {
|
||
let rest = line.strip_prefix("\\documentclass")?.trim_start();
|
||
let rest = rest.strip_prefix('[')?;
|
||
let end = rest.find(']')?;
|
||
for option in rest[..end].split(',') {
|
||
match option.trim() {
|
||
"10pt" => return Some(10 * SCALE),
|
||
"11pt" => return Some(11 * SCALE),
|
||
"12pt" => return Some(12 * SCALE),
|
||
_ => {}
|
||
}
|
||
}
|
||
None
|
||
}
|
||
|
||
/// LaTeX's article class sets `\baselineskip` from the base size.
|
||
fn class_baselineskip(font_size: i64) -> i64 {
|
||
if font_size >= 12 * 65_536 {
|
||
14 * 65_536 + 32_768
|
||
} else if font_size >= 11 * 65_536 {
|
||
13 * 65_536 + 39_322
|
||
} else {
|
||
12 * 65_536
|
||
}
|
||
}
|
||
|
||
/// A `\linespread`-style factor in thousandths, clamped to a sane range.
|
||
fn spread_percent(argument: &str) -> Option<i64> {
|
||
let factor: f64 = argument.trim().parse().ok()?;
|
||
if !factor.is_finite() {
|
||
return None;
|
||
}
|
||
Some(((factor * 1000.0).round() as i64).clamp(250, 5000))
|
||
}
|
||
|
||
/// `\linespread{factor}` in thousandths.
|
||
fn linespread_assignment(line: &str) -> Option<i64> {
|
||
let rest = line.strip_prefix("\\linespread")?;
|
||
let (argument, _) = braced_group(rest.trim_start())?;
|
||
spread_percent(argument)
|
||
}
|
||
|
||
/// `\renewcommand{\name}{text}` / `\def\name{text}` for class labels.
|
||
fn renewcommand_text(line: &str, command: &str) -> Option<String> {
|
||
let braced = format!("\\renewcommand{{\\{command}}}");
|
||
let defined = format!("\\def\\{command}");
|
||
let rest = line
|
||
.strip_prefix(&braced)
|
||
.or_else(|| line.strip_prefix(&defined))?;
|
||
let (argument, _) = braced_group(rest.trim_start())?;
|
||
Some(argument.trim().to_string())
|
||
}
|
||
|
||
/// `\renewcommand{\arraystretch}{factor}` in thousandths.
|
||
fn arraystretch_assignment(line: &str) -> Option<i64> {
|
||
let rest = line
|
||
.strip_prefix("\\renewcommand{\\arraystretch}")
|
||
.or_else(|| line.strip_prefix("\\def\\arraystretch"))?;
|
||
let (argument, _) = braced_group(rest.trim_start())?;
|
||
spread_percent(argument)
|
||
}
|
||
|
||
/// `\renewcommand{\baselinestretch}{factor}` in thousandths.
|
||
fn baselinestretch_assignment(line: &str) -> Option<i64> {
|
||
let rest = line
|
||
.strip_prefix("\\renewcommand{\\baselinestretch}")
|
||
.or_else(|| line.strip_prefix("\\def\\baselinestretch"))?;
|
||
let (argument, _) = braced_group(rest.trim_start())?;
|
||
spread_percent(argument)
|
||
}
|
||
|
||
/// Extract the option string of `\usepackage[opts]{geometry}` or `\geometry{opts}`.
|
||
fn geometry_package_options(line: &str) -> Option<String> {
|
||
if let Some(rest) = line.strip_prefix("\\geometry") {
|
||
let (options, _) = braced(rest.trim_start())?;
|
||
return Some(options.to_string());
|
||
}
|
||
let rest = line.strip_prefix("\\usepackage")?;
|
||
let rest = rest.trim_start().strip_prefix('[')?;
|
||
let (options, rest) = rest.split_once(']')?;
|
||
let rest = rest.trim_start().strip_prefix('{')?;
|
||
let (packages, _) = rest.split_once('}')?;
|
||
if packages.split(',').any(|name| name.trim() == "geometry") {
|
||
Some(options.to_string())
|
||
} else {
|
||
None
|
||
}
|
||
}
|
||
|
||
/// Apply the subset of the `geometry` package that route-D can honour.
|
||
fn apply_geometry_package(geometry: &mut PageGeometry, options: &str) {
|
||
let paper_width = geometry.paper_width.unwrap_or(612 * SCALE);
|
||
let paper_height = geometry.paper_height.unwrap_or(792 * SCALE);
|
||
let mut left = None;
|
||
let mut right = None;
|
||
let mut top = None;
|
||
let mut bottom = None;
|
||
for option in options.split(',') {
|
||
let Some((key, value)) = option.split_once('=') else {
|
||
continue;
|
||
};
|
||
let Some(value) = parse_dimension(value.trim()) else {
|
||
continue;
|
||
};
|
||
match key.trim() {
|
||
"margin" => {
|
||
left = Some(value);
|
||
right = Some(value);
|
||
top = Some(value);
|
||
bottom = Some(value);
|
||
}
|
||
"hmargin" => {
|
||
left = Some(value);
|
||
right = Some(value);
|
||
}
|
||
"vmargin" => {
|
||
top = Some(value);
|
||
bottom = Some(value);
|
||
}
|
||
"left" => left = Some(value),
|
||
"right" => right = Some(value),
|
||
"top" => top = Some(value),
|
||
"bottom" => bottom = Some(value),
|
||
"textwidth" => geometry.line_width = Some(value),
|
||
"textheight" => geometry.textheight = Some(value),
|
||
_ => {}
|
||
}
|
||
}
|
||
if left.is_some() || right.is_some() || top.is_some() || bottom.is_some() {
|
||
let left = left.unwrap_or(0);
|
||
let right = right.unwrap_or(0);
|
||
let top = top.unwrap_or(0);
|
||
let bottom = bottom.unwrap_or(0);
|
||
geometry.line_width = Some(paper_width - left - right);
|
||
geometry.textheight = Some(paper_height - top - bottom);
|
||
}
|
||
}
|
||
|
||
/// Read the braced argument of a command that occupies a whole line.
|
||
fn braced_value(line: &str, command: &str) -> Option<String> {
|
||
let rest = line.strip_prefix(command)?.trim_start();
|
||
let (value, _) = braced(rest)?;
|
||
Some(value.trim().to_string())
|
||
}
|
||
|
||
fn newif_definition(line: &str) -> Option<String> {
|
||
let rest = line.strip_prefix("\\newif")?.trim_start();
|
||
let (command, _) = control_sequence(rest)?;
|
||
let name = command.strip_prefix("\\if")?;
|
||
if name.is_empty() {
|
||
None
|
||
} else {
|
||
Some(name.to_string())
|
||
}
|
||
}
|
||
|
||
fn conditional_assignment(
|
||
line: &str,
|
||
flags: &[ConditionalDefinition],
|
||
) -> Option<(String, bool, usize)> {
|
||
let (command, consumed) = control_sequence(line)?;
|
||
let command = command.strip_prefix('\\')?;
|
||
let (name, value) = if let Some(name) = command.strip_suffix("true") {
|
||
(name, true)
|
||
} else {
|
||
(command.strip_suffix("false")?, false)
|
||
};
|
||
if flags.iter().any(|flag| flag.name == name) {
|
||
Some((name.to_string(), value, consumed))
|
||
} else {
|
||
None
|
||
}
|
||
}
|
||
|
||
fn conditional_at(
|
||
text: &str,
|
||
index: usize,
|
||
flags: &[ConditionalDefinition],
|
||
) -> Option<(bool, usize)> {
|
||
let (command, consumed) = control_sequence(text.get(index..)?)?;
|
||
let word = command.strip_prefix('\\')?;
|
||
if word == "iftrue" {
|
||
return Some((true, consumed));
|
||
}
|
||
if word == "iffalse" {
|
||
return Some((false, consumed));
|
||
}
|
||
let name = word.strip_prefix("if")?;
|
||
let flag = flags.iter().find(|flag| flag.name == name)?;
|
||
Some((flag.value, consumed))
|
||
}
|
||
|
||
fn conditional_end(text: &str, start: usize) -> Option<(Option<usize>, usize)> {
|
||
let mut index = start;
|
||
let mut depth = 0_usize;
|
||
let mut else_at = None;
|
||
while let Some(offset) = text[index..].find('\\') {
|
||
let position = index + offset;
|
||
let Some((command, consumed)) = control_sequence(&text[position..]) else {
|
||
index = position + 1;
|
||
continue;
|
||
};
|
||
let word = command.trim_start_matches('\\');
|
||
if word.starts_with("if") && word.len() > 2 {
|
||
depth += 1;
|
||
} else if word == "fi" {
|
||
if depth == 0 {
|
||
return Some((else_at, position));
|
||
}
|
||
depth -= 1;
|
||
} else if word == "else" && depth == 0 && else_at.is_none() {
|
||
else_at = Some(position);
|
||
}
|
||
index = position + consumed;
|
||
}
|
||
None
|
||
}
|
||
|
||
fn expand_conditionals(source: &str, flags: &mut [ConditionalDefinition]) -> String {
|
||
expand_conditionals_at(source, flags, 0)
|
||
}
|
||
|
||
fn expand_conditionals_at(
|
||
source: &str,
|
||
flags: &mut [ConditionalDefinition],
|
||
depth: usize,
|
||
) -> String {
|
||
if depth > 8 {
|
||
return source.to_string();
|
||
}
|
||
let mut output = String::new();
|
||
let mut index = 0;
|
||
while let Some(offset) = source[index..].find('\\') {
|
||
let position = index + offset;
|
||
output.push_str(&source[index..position]);
|
||
if let Some((name, value, consumed)) = conditional_assignment(&source[position..], flags) {
|
||
if let Some(flag) = flags.iter_mut().find(|flag| flag.name == name) {
|
||
flag.value = value;
|
||
}
|
||
index = position + consumed;
|
||
continue;
|
||
}
|
||
if let Some((value, consumed)) = conditional_at(source, position, flags) {
|
||
let body_start = position + consumed;
|
||
if let Some((else_at, fi_at)) = conditional_end(source, body_start) {
|
||
let (chosen, after) = match else_at {
|
||
Some(else_at) => {
|
||
if value {
|
||
(&source[body_start..else_at], fi_at + 3)
|
||
} else {
|
||
(&source[else_at + 5..fi_at], fi_at + 3)
|
||
}
|
||
}
|
||
None => {
|
||
let chosen = if value {
|
||
&source[body_start..fi_at]
|
||
} else {
|
||
""
|
||
};
|
||
(chosen, fi_at + 3)
|
||
}
|
||
};
|
||
output.push_str(&expand_conditionals_at(chosen, flags, depth + 1));
|
||
index = after;
|
||
continue;
|
||
}
|
||
}
|
||
output.push_str(&source[position..position + 1]);
|
||
index = position + 1;
|
||
}
|
||
output.push_str(&source[index..]);
|
||
output
|
||
}
|
||
|
||
fn any_counter_assignment(line: &str) -> Option<(String, u32)> {
|
||
let rest = line.strip_prefix("\\setcounter")?.trim_start();
|
||
let rest = rest.strip_prefix('{')?;
|
||
let close = rest.find('}')?;
|
||
let name = rest[..close].trim().to_string();
|
||
let rest = rest[close + 1..].trim_start();
|
||
let rest = rest.strip_prefix('{')?;
|
||
let close = rest.find('}')?;
|
||
let value = rest[..close].trim().parse().ok()?;
|
||
Some((name, value))
|
||
}
|
||
|
||
fn add_counter_assignment(line: &str) -> Option<(String, i64)> {
|
||
let rest = line.strip_prefix("\\addtocounter")?.trim_start();
|
||
let rest = rest.strip_prefix('{')?;
|
||
let close = rest.find('}')?;
|
||
let name = rest[..close].trim().to_string();
|
||
let rest = rest[close + 1..].trim_start();
|
||
let rest = rest.strip_prefix('{')?;
|
||
let close = rest.find('}')?;
|
||
let value = rest[..close].trim().parse().ok()?;
|
||
Some((name, value))
|
||
}
|
||
|
||
fn new_counter_definition(line: &str) -> Option<String> {
|
||
let rest = line.strip_prefix("\\newcounter")?.trim_start();
|
||
let rest = rest.strip_prefix('{')?;
|
||
let close = rest.find('}')?;
|
||
let name = rest[..close]
|
||
.trim()
|
||
.strip_prefix('\\')
|
||
.unwrap_or(rest[..close].trim());
|
||
(!name.is_empty()).then_some(name.to_string())
|
||
}
|
||
|
||
fn geometry_counter(geometry: &PageGeometry, name: &str) -> u32 {
|
||
geometry
|
||
.counters
|
||
.iter()
|
||
.rev()
|
||
.find(|(counter, _)| counter == name)
|
||
.map(|(_, value)| *value)
|
||
.unwrap_or(0)
|
||
}
|
||
|
||
fn hypersetup_values(line: &str) -> Vec<(String, String)> {
|
||
let Some(rest) = line.strip_prefix("\\hypersetup") else {
|
||
return Vec::new();
|
||
};
|
||
let Some((body, _)) = braced_group(rest.trim_start()) else {
|
||
return Vec::new();
|
||
};
|
||
let mut values = Vec::new();
|
||
let mut depth = 0_usize;
|
||
let mut entry = String::new();
|
||
for character in body.chars() {
|
||
match character {
|
||
'{' => {
|
||
depth += 1;
|
||
entry.push(character);
|
||
}
|
||
'}' => {
|
||
depth = depth.saturating_sub(1);
|
||
entry.push(character);
|
||
}
|
||
',' if depth == 0 => {
|
||
values.push(entry.trim().to_string());
|
||
entry = String::new();
|
||
}
|
||
_ => entry.push(character),
|
||
}
|
||
}
|
||
values.push(entry.trim().to_string());
|
||
values
|
||
.into_iter()
|
||
.filter_map(|entry| {
|
||
let (key, value) = entry.split_once('=')?;
|
||
let value = value.trim();
|
||
let value = value
|
||
.strip_prefix('{')
|
||
.and_then(|inner| inner.strip_suffix('}'))
|
||
.unwrap_or(value)
|
||
.trim()
|
||
.to_string();
|
||
Some((key.trim().to_string(), value))
|
||
})
|
||
.collect()
|
||
}
|
||
|
||
/// Expands `\multirow{n}{width}{text}` cells to their text. The span is not
|
||
/// vertical-centre, so the text stays on its first row; the command itself
|
||
/// must not leak into the table.
|
||
fn expand_multirow(source: &str) -> String {
|
||
let mut rest = source;
|
||
let mut out = String::new();
|
||
while let Some(index) = rest.find(r"\multirow") {
|
||
out.push_str(&rest[..index]);
|
||
let after = rest[index + r"\multirow".len()..].trim_start();
|
||
let after = if let Some(inner) = after.strip_prefix('[') {
|
||
match inner.find(']') {
|
||
Some(end) => inner[end + 1..].trim_start(),
|
||
None => {
|
||
out.push_str(&rest[index..]);
|
||
return out;
|
||
}
|
||
}
|
||
} else {
|
||
after
|
||
};
|
||
let mut cursor = after;
|
||
let mut pieces = Vec::new();
|
||
for _ in 0..3 {
|
||
let Some((body, consumed)) = braced_group(cursor) else {
|
||
out.push_str(&rest[index..]);
|
||
return out;
|
||
};
|
||
pieces.push(body.trim().to_string());
|
||
cursor = &cursor[consumed..];
|
||
}
|
||
out.push_str(&pieces[2]);
|
||
rest = cursor;
|
||
}
|
||
out.push_str(rest);
|
||
out
|
||
}
|
||
|
||
fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
|
||
let mut geometry = PageGeometry::default();
|
||
let mut body = String::new();
|
||
let mut tabular: Option<(String, String, &'static str, Option<i64>)> = None;
|
||
for line in source.lines() {
|
||
let trimmed = line.trim();
|
||
if let Some((_, text, environment, _)) = tabular.as_mut() {
|
||
if trimmed == format!("\\end{{{environment}}}") {
|
||
let (template, text, _, target) = tabular.take().unwrap();
|
||
geometry
|
||
.tabular
|
||
.push((template, expand_multirow(&text), target));
|
||
} else {
|
||
if !text.is_empty() {
|
||
text.push('\n');
|
||
}
|
||
text.push_str(trimmed);
|
||
}
|
||
continue;
|
||
}
|
||
let mut table_environment = None;
|
||
for environment in ["tabular", "longtable", "tabularx", "tabularx"] {
|
||
let begin = format!("\\begin{{{environment}}}");
|
||
if let Some(rest) = trimmed.strip_prefix(&begin) {
|
||
table_environment = Some((environment, rest));
|
||
break;
|
||
}
|
||
}
|
||
if let Some((environment, rest)) = table_environment {
|
||
let rest = rest.trim_start();
|
||
let rest = match rest
|
||
.strip_prefix('[')
|
||
.and_then(|after| after.split_once(']'))
|
||
{
|
||
Some((_, tail)) => tail.trim_start(),
|
||
None => rest,
|
||
};
|
||
let (rest, target) = if environment == "tabularx" {
|
||
let Some((width, after)) = braced(rest) else {
|
||
continue;
|
||
};
|
||
match parse_dimension(width) {
|
||
Some(width) => (after.trim_start(), Some(width)),
|
||
None => continue,
|
||
}
|
||
} else {
|
||
(rest, None)
|
||
};
|
||
if let Some((template, _)) = braced(rest) {
|
||
if !body.ends_with('\n') {
|
||
body.push('\n');
|
||
}
|
||
body.push_str(&format!("\\texrratable{{{}}}\n", geometry.tabular.len()));
|
||
tabular = Some((template.to_string(), String::new(), environment, target));
|
||
}
|
||
continue;
|
||
}
|
||
if trimmed.starts_with("\\newenvironment") || trimmed.starts_with("\\renewenvironment") {
|
||
if let Some(definition) = environment_definition(trimmed) {
|
||
geometry.environments.push(definition);
|
||
}
|
||
continue;
|
||
}
|
||
if let Some(name) = newif_definition(trimmed) {
|
||
geometry
|
||
.conditionals
|
||
.push(ConditionalDefinition { name, value: false });
|
||
continue;
|
||
}
|
||
if let Some((name, value, _)) = conditional_assignment(trimmed, &geometry.conditionals) {
|
||
if let Some(flag) = geometry
|
||
.conditionals
|
||
.iter_mut()
|
||
.find(|flag| flag.name == name)
|
||
{
|
||
flag.value = value;
|
||
}
|
||
continue;
|
||
}
|
||
if let Some(name) = new_counter_definition(trimmed) {
|
||
if !geometry.counters.iter().any(|(known, _)| known == &name) {
|
||
geometry.counters.push((name, 0));
|
||
}
|
||
continue;
|
||
}
|
||
if let Some((name, delta)) = add_counter_assignment(trimmed) {
|
||
if name == "page" {
|
||
geometry.page_start =
|
||
(geometry.page_start as i64 + delta).clamp(0, u32::MAX as i64) as u32;
|
||
} else {
|
||
let current = geometry_counter(&geometry, &name) as i64;
|
||
let updated = (current + delta).clamp(0, u32::MAX as i64) as u32;
|
||
geometry.counters.push((name, updated));
|
||
}
|
||
continue;
|
||
}
|
||
if let Some((name, value)) = any_counter_assignment(trimmed) {
|
||
if name == "page" {
|
||
geometry.page_start = value.saturating_sub(1);
|
||
}
|
||
match name.as_str() {
|
||
"secnumdepth" => geometry.secnumdepth = Some(value),
|
||
"tocdepth" => geometry.tocdepth = Some(value),
|
||
_ => geometry.counters.push((name, value)),
|
||
}
|
||
continue;
|
||
}
|
||
if let Some(spread) = baselinestretch_assignment(trimmed) {
|
||
geometry.linespread = Some(spread);
|
||
continue;
|
||
}
|
||
if let Some(spread) = arraystretch_assignment(trimmed) {
|
||
geometry.array_stretch = Some(spread);
|
||
continue;
|
||
}
|
||
if let Some(name) = renewcommand_text(trimmed, "figurename") {
|
||
geometry.figure_name = Some(name);
|
||
continue;
|
||
}
|
||
if let Some(name) = renewcommand_text(trimmed, "tablename") {
|
||
geometry.table_name = Some(name);
|
||
continue;
|
||
}
|
||
if let Some(name) = renewcommand_text(trimmed, "abstractname") {
|
||
geometry.abstract_name = Some(name);
|
||
continue;
|
||
}
|
||
if let Some(name) = renewcommand_text(trimmed, "refname") {
|
||
geometry.ref_name = Some(name);
|
||
continue;
|
||
}
|
||
if let Some(name) = renewcommand_text(trimmed, "contentsname") {
|
||
geometry.contents_name = Some(name);
|
||
continue;
|
||
}
|
||
if let Some(name) = renewcommand_text(trimmed, "listfigurename") {
|
||
geometry.list_figure_name = Some(name);
|
||
continue;
|
||
}
|
||
if let Some(name) = renewcommand_text(trimmed, "listtablename") {
|
||
geometry.list_table_name = Some(name);
|
||
continue;
|
||
}
|
||
if let Some(rest) = trimmed.strip_prefix("\\DeclareMathOperator") {
|
||
let mut rest = rest.trim_start();
|
||
let mut starred = false;
|
||
if let Some(after) = rest.strip_prefix('*') {
|
||
starred = true;
|
||
rest = after.trim_start();
|
||
}
|
||
if let Some((command, tail)) = braced(rest) {
|
||
if let Some((body, _)) = braced(tail.trim_start()) {
|
||
let name = command.trim().trim_start_matches('\\').to_string();
|
||
let operator = if starred {
|
||
format!("\\operatorname*{{{}}}", body.trim())
|
||
} else {
|
||
format!("\\operatorname{{{}}}", body.trim())
|
||
};
|
||
geometry.macros.push(MacroDefinition {
|
||
name,
|
||
args: 0,
|
||
default: None,
|
||
body: operator,
|
||
});
|
||
}
|
||
}
|
||
continue;
|
||
}
|
||
if trimmed.starts_with("\\newcommand")
|
||
|| trimmed.starts_with("\\renewcommand")
|
||
|| trimmed.starts_with("\\providecommand")
|
||
|| trimmed.starts_with("\\def")
|
||
{
|
||
if let Some(definition) = macro_definition(trimmed) {
|
||
geometry.macros.push(definition);
|
||
}
|
||
continue;
|
||
}
|
||
if trimmed.starts_with(r"\bibliographystyle") || trimmed.starts_with(r"\bibliography{") {
|
||
let rest = trimmed
|
||
.strip_prefix(r"\bibliographystyle")
|
||
.or_else(|| trimmed.strip_prefix(r"\bibliography"));
|
||
if let Some(rest) = rest
|
||
&& braced_group(rest.trim_start()).is_some()
|
||
{
|
||
continue;
|
||
}
|
||
}
|
||
if let Some((name, target)) = macro_alias(trimmed) {
|
||
let definition = geometry
|
||
.macros
|
||
.iter()
|
||
.find(|definition| definition.name == target)
|
||
.cloned()
|
||
.unwrap_or(MacroDefinition {
|
||
name: name.clone(),
|
||
args: 0,
|
||
default: None,
|
||
body: String::new(),
|
||
});
|
||
geometry.macros.push(MacroDefinition {
|
||
name,
|
||
args: definition.args,
|
||
default: definition.default,
|
||
body: definition.body,
|
||
});
|
||
continue;
|
||
}
|
||
if trimmed == "\\listoffigures" {
|
||
body.push_str("\\texrralof\n\n");
|
||
continue;
|
||
}
|
||
if trimmed == "\\listoftables" {
|
||
body.push_str("\\texrralot\n\n");
|
||
continue;
|
||
}
|
||
if trimmed == "\\tableofcontents" {
|
||
body.push_str("\\texrratoc\n\n");
|
||
continue;
|
||
}
|
||
if trimmed.starts_with("\\newtheorem") {
|
||
if let Some(definition) = newtheorem_definition(trimmed) {
|
||
geometry.theorem_definitions.push(definition);
|
||
}
|
||
continue;
|
||
}
|
||
if trimmed.starts_with("\\graphicspath") {
|
||
geometry
|
||
.graphics_paths
|
||
.extend(graphics_path_groups(trimmed));
|
||
continue;
|
||
}
|
||
if trimmed.starts_with("\\hypersetup") {
|
||
for (key, value) in hypersetup_values(trimmed) {
|
||
match key.as_str() {
|
||
"pdftitle" => geometry.pdf_title = Some(value),
|
||
"pdfauthor" => geometry.pdf_author = Some(value),
|
||
"pdfsubject" => geometry.pdf_subject = Some(value),
|
||
"pdfkeywords" => geometry.pdf_keywords = Some(value),
|
||
_ => {}
|
||
}
|
||
}
|
||
continue;
|
||
}
|
||
if let Some(value) = braced_value(trimmed, "\\title") {
|
||
geometry.title = Some(value);
|
||
continue;
|
||
}
|
||
if let Some(value) = braced_value(trimmed, "\\author") {
|
||
geometry.author = Some(value);
|
||
continue;
|
||
}
|
||
if let Some(value) = braced_value(trimmed, "\\date") {
|
||
geometry.date = Some(value);
|
||
continue;
|
||
}
|
||
if let Some(options) = geometry_package_options(trimmed) {
|
||
apply_geometry_package(&mut geometry, &options);
|
||
continue;
|
||
}
|
||
if trimmed.starts_with("\\documentclass") {
|
||
geometry.base_font_size = document_class_size(trimmed);
|
||
continue;
|
||
}
|
||
if let Some(spread) = linespread_assignment(trimmed) {
|
||
geometry.linespread = Some(spread);
|
||
continue;
|
||
}
|
||
if let Some(value) = dimension_assignment(trimmed, "hoffset") {
|
||
geometry.origin.h_offset = value;
|
||
} else if let Some(value) = dimension_assignment(trimmed, "voffset") {
|
||
geometry.origin.v_offset = value;
|
||
} else if let Some(value) = dimension_assignment(trimmed, "paperwidth") {
|
||
geometry.paper_width = Some(value);
|
||
} else if let Some(value) = dimension_assignment(trimmed, "paperheight") {
|
||
geometry.paper_height = Some(value);
|
||
} else if let Some(value) = dimension_assignment(trimmed, "vsize") {
|
||
geometry.vsize = Some(value);
|
||
} else if let Some(value) = dimension_assignment(trimmed, "textheight") {
|
||
geometry.textheight = Some(value);
|
||
} else if let Some(value) = dimension_assignment(trimmed, "textwidth") {
|
||
geometry.line_width = Some(value);
|
||
} else if let Some(value) = dimension_assignment(trimmed, "hsize") {
|
||
geometry.line_width = Some(value);
|
||
} else if let Some(value) = dimension_assignment(trimmed, "linewidth") {
|
||
geometry.line_width = Some(value);
|
||
} else if let Some((width, stretch, shrink)) = setlength_glue(trimmed, "parskip") {
|
||
geometry.par_skip = Some(width);
|
||
geometry.par_skip_stretch = Some(stretch);
|
||
geometry.par_skip_shrink = Some(shrink);
|
||
} else if let Some(spacing) = setlength_glue(trimmed, "itemsep") {
|
||
geometry.item_sep = Some(spacing);
|
||
} else if let Some(spacing) = setlength_glue(trimmed, "topsep") {
|
||
geometry.top_sep = Some(spacing);
|
||
} else if let Some(spacing) = setlength_glue(trimmed, "partopsep") {
|
||
geometry.part_op_sep = Some(spacing);
|
||
} else if let Some((name, raw)) = addtolength_assignment(trimmed) {
|
||
if let Some(delta) = length_value(&geometry, &raw)
|
||
&& let Some((_, current)) = geometry
|
||
.lengths
|
||
.iter_mut()
|
||
.rev()
|
||
.find(|(known, _)| known == &name)
|
||
{
|
||
*current = current.saturating_add(delta);
|
||
}
|
||
} else if let Some((name, raw)) = setlength_assignment(trimmed) {
|
||
if let Some(value) = length_value(&geometry, &raw) {
|
||
match name.as_str() {
|
||
"textwidth" | "hsize" | "linewidth" => geometry.line_width = Some(value),
|
||
"parindent" => geometry.par_indent = Some(value),
|
||
"baselineskip" => geometry.baseline_skip = Some(value),
|
||
"textheight" => geometry.textheight = Some(value),
|
||
"vsize" => geometry.vsize = Some(value),
|
||
"leftskip" => geometry.left_skip = Some(value),
|
||
"rightskip" => geometry.right_skip = Some(value),
|
||
"emergencystretch" => geometry.emergency_stretch = Some(value),
|
||
"hangindent" => geometry.hang_indent = Some(value),
|
||
"lineskip" => geometry.lineskip = Some(value),
|
||
"lineskiplimit" => geometry.lineskiplimit = Some(value),
|
||
"topskip" => geometry.top_skip = Some(value),
|
||
"maxdepth" => geometry.max_depth = Some(value),
|
||
"splittopskip" => geometry.split_top_skip = Some(value),
|
||
"splitmaxdepth" => geometry.split_max_depth = Some(value),
|
||
"tabcolsep" => geometry.tab_col_sep = Some(value),
|
||
_ => {
|
||
geometry.lengths.retain(|(known, _)| known != &name);
|
||
geometry.lengths.push((name, value));
|
||
}
|
||
}
|
||
}
|
||
} else if let Some(rest) = trimmed.strip_prefix("\\pagenumbering") {
|
||
if let Some(rest) = rest.trim_start().strip_prefix('{')
|
||
&& let Some((name, _)) = rest.split_once('}')
|
||
{
|
||
geometry.page_numbering = Some(name.trim().to_string());
|
||
geometry.page_start = 0;
|
||
}
|
||
} else if let Some(rest) = trimmed.strip_prefix("\\pagestyle") {
|
||
if rest.trim_start().starts_with("{empty}") {
|
||
geometry.suppress_page_numbers = true;
|
||
}
|
||
} else if let Some(rest) = trimmed.strip_prefix("\\thispagestyle") {
|
||
if rest.trim_start().starts_with("{empty}") {
|
||
geometry.suppress_first_page_number = true;
|
||
}
|
||
} else if let Some(name) = trimmed.strip_prefix("\\newlength") {
|
||
if let Some(name) = name.trim_start().strip_prefix('{')
|
||
&& let Some((name, _)) = name.split_once('}')
|
||
{
|
||
let name = name.trim().strip_prefix('\\').unwrap_or(name.trim());
|
||
geometry.lengths.retain(|(known, _)| known != name);
|
||
geometry.lengths.push((name.to_string(), 0));
|
||
}
|
||
} else if let Some(value) = dimension_assignment(trimmed, "parindent") {
|
||
geometry.par_indent = Some(value);
|
||
} else if let Some((width, stretch, shrink)) = glue_assignment(trimmed, "parskip") {
|
||
geometry.par_skip = Some(width);
|
||
geometry.par_skip_stretch = Some(stretch);
|
||
geometry.par_skip_shrink = Some(shrink);
|
||
} else if let Some(spacing) = glue_assignment(trimmed, "itemsep") {
|
||
geometry.item_sep = Some(spacing);
|
||
} else if let Some(spacing) = glue_assignment(trimmed, "topsep") {
|
||
geometry.top_sep = Some(spacing);
|
||
} else if let Some(spacing) = glue_assignment(trimmed, "partopsep") {
|
||
geometry.part_op_sep = Some(spacing);
|
||
} else if let Some(value) = dimension_assignment(trimmed, "baselineskip") {
|
||
geometry.baseline_skip = Some(value);
|
||
} else if let Some(value) = dimension_assignment(trimmed, "tabcolsep") {
|
||
geometry.tab_col_sep = Some(value);
|
||
} else if let Some(value) = dimension_assignment(trimmed, "leftskip") {
|
||
geometry.left_skip = Some(value);
|
||
} else if let Some(value) = dimension_assignment(trimmed, "rightskip") {
|
||
geometry.right_skip = Some(value);
|
||
} else if let Some(value) = dimension_assignment(trimmed, "emergencystretch") {
|
||
geometry.emergency_stretch = Some(value);
|
||
} else if let Some(value) = integer_assignment(trimmed, "tolerance") {
|
||
geometry.tolerance = Some(value);
|
||
} else if let Some(value) = integer_assignment(trimmed, "pretolerance") {
|
||
geometry.pretolerance = Some(value);
|
||
} else if let Some(value) = signed_integer_assignment(trimmed, "looseness") {
|
||
geometry.looseness = Some(value.clamp(-9, 9));
|
||
} else if let Some(value) = dimension_assignment(trimmed, "hangindent") {
|
||
geometry.hang_indent = Some(value);
|
||
} else if let Some(value) = integer_assignment(trimmed, "hangafter") {
|
||
geometry.hang_after = Some(value);
|
||
} else if let Some(value) = glue_assignment(trimmed, "spaceskip") {
|
||
geometry.space_skip = Some(value);
|
||
} else if let Some(value) = glue_assignment(trimmed, "xspaceskip") {
|
||
geometry.xspace_skip = Some(value);
|
||
} else if let Some(value) = dimension_assignment(trimmed, "lineskip") {
|
||
geometry.lineskip = Some(value);
|
||
} else if let Some(value) = dimension_assignment(trimmed, "lineskiplimit") {
|
||
geometry.lineskiplimit = Some(value);
|
||
} else if let Some((character, value)) = sfcode_assignment(trimmed) {
|
||
geometry.space_factor_codes.push((character, value));
|
||
} else if let Some(value) = integer_assignment(trimmed, "hyphenpenalty") {
|
||
geometry.hyphen_penalty = Some(value);
|
||
} else if let Some(value) = integer_assignment(trimmed, "exhyphenpenalty") {
|
||
geometry.ex_hyphen_penalty = Some(value);
|
||
} else if let Some(value) = integer_assignment(trimmed, "doublehyphendemerits") {
|
||
geometry.double_hyphen_demerits = Some(value);
|
||
} else if let Some(value) = integer_assignment(trimmed, "finalhyphendemerits") {
|
||
geometry.final_hyphen_demerits = Some(value);
|
||
} else if let Some(value) = integer_assignment(trimmed, "linepenalty") {
|
||
geometry.line_penalty = Some(value);
|
||
} else if let Some(value) = integer_assignment(trimmed, "adjdemerits") {
|
||
geometry.adj_demerits = Some(value);
|
||
} else if let Some(value) = dimension_assignment(trimmed, "topskip") {
|
||
geometry.top_skip = Some(value);
|
||
} else if let Some(value) = dimension_assignment(trimmed, "maxdepth") {
|
||
geometry.max_depth = Some(value);
|
||
} else if let Some(value) = dimension_assignment(trimmed, "splittopskip") {
|
||
geometry.split_top_skip = Some(value);
|
||
} else if let Some(value) = dimension_assignment(trimmed, "splitmaxdepth") {
|
||
geometry.split_max_depth = Some(value);
|
||
} else if let Some(value) = parfillskip_assignment(trimmed) {
|
||
geometry.par_fillskip = Some(value);
|
||
} else if let Some(value) = parshape_assignment(trimmed) {
|
||
geometry.par_shape = value;
|
||
} else if let Some(value) = braced_argument(trimmed, "\\hyphenation") {
|
||
geometry
|
||
.hyphenation_exceptions
|
||
.extend(value.split_whitespace().map(str::to_string));
|
||
} else if trimmed == "\\frenchspacing" {
|
||
geometry.french_spacing = Some(true);
|
||
} else if trimmed == "\\nonfrenchspacing" {
|
||
geometry.french_spacing = Some(false);
|
||
} else {
|
||
body.push_str(line);
|
||
body.push('\n');
|
||
}
|
||
}
|
||
if let Some((template, text, _, target)) = tabular {
|
||
geometry
|
||
.tabular
|
||
.push((template, expand_multirow(&text), target));
|
||
}
|
||
(body, geometry)
|
||
}
|
||
|
||
fn braced(text: &str) -> Option<(&str, &str)> {
|
||
let mut depth = 0_i32;
|
||
for (index, character) in text.char_indices() {
|
||
match character {
|
||
'{' => depth += 1,
|
||
'}' => {
|
||
depth -= 1;
|
||
if depth == 0 {
|
||
return Some((&text[1..index], &text[index + 1..]));
|
||
}
|
||
}
|
||
_ => {}
|
||
}
|
||
}
|
||
None
|
||
}
|
||
|
||
/// Build a captured `tabular` unit with the document's `\tabcolsep`.
|
||
|
||
/// Replace `X` columns of a `tabularx` template with paragraph columns that
|
||
/// share the leftover width, so the table fills its declared target.
|
||
fn expand_tabular_template(template: &str, source: &str, target: Option<i64>) -> String {
|
||
let Some(target) = target else {
|
||
return template.to_string();
|
||
};
|
||
if !template.contains('X') {
|
||
return template.to_string();
|
||
}
|
||
let probe_template: String = template
|
||
.chars()
|
||
.map(|character| if character == 'X' { 'l' } else { character })
|
||
.collect();
|
||
let probe = Unit::halign_from_source_with_template_and_tabskips(
|
||
0,
|
||
&engine_template(&probe_template),
|
||
source,
|
||
6,
|
||
Vec::new(),
|
||
);
|
||
let Some(VerticalItem::Halign(halign)) = probe.items.first() else {
|
||
return template.to_string();
|
||
};
|
||
let mut flags = Vec::new();
|
||
let characters: Vec<char> = template.chars().collect();
|
||
let mut index = 0;
|
||
while index < characters.len() {
|
||
match characters[index] {
|
||
'l' | 'c' | 'r' => {
|
||
flags.push(false);
|
||
index += 1;
|
||
}
|
||
'X' => {
|
||
flags.push(true);
|
||
index += 1;
|
||
}
|
||
'p' | 'm' | 'b' => {
|
||
flags.push(false);
|
||
index += 1;
|
||
if characters.get(index) == Some(&'{') {
|
||
let mut depth = 0_i32;
|
||
while index < characters.len() {
|
||
let inner = characters[index];
|
||
index += 1;
|
||
match inner {
|
||
'{' => depth += 1,
|
||
'}' => {
|
||
depth -= 1;
|
||
if depth == 0 {
|
||
break;
|
||
}
|
||
}
|
||
_ => {}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
_ => index += 1,
|
||
}
|
||
}
|
||
let x_count = flags.iter().filter(|expand| **expand).count();
|
||
if x_count == 0 {
|
||
return template.to_string();
|
||
}
|
||
let gaps = halign.column_widths.len().saturating_sub(1) as i64;
|
||
let fixed: i64 = halign
|
||
.column_widths
|
||
.iter()
|
||
.zip(flags.iter())
|
||
.filter(|(_, expand)| !**expand)
|
||
.map(|(width, _)| *width)
|
||
.sum();
|
||
let share = ((target - fixed - gaps * 6 * SCALE) / x_count as i64).max(SCALE);
|
||
let share = format!("p{{{:.4}pt}}", share as f64 / SCALE as f64);
|
||
let mut out = String::new();
|
||
let mut index = 0;
|
||
while index < characters.len() {
|
||
let character = characters[index];
|
||
match character {
|
||
'X' => {
|
||
out.push_str(&share);
|
||
index += 1;
|
||
}
|
||
'p' | 'm' | 'b' => {
|
||
out.push('p');
|
||
index += 1;
|
||
if characters.get(index) == Some(&'{') {
|
||
let mut depth = 0_i32;
|
||
while index < characters.len() {
|
||
let inner = characters[index];
|
||
out.push(inner);
|
||
index += 1;
|
||
match inner {
|
||
'{' => depth += 1,
|
||
'}' => {
|
||
depth -= 1;
|
||
if depth == 0 {
|
||
break;
|
||
}
|
||
}
|
||
_ => {}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
_ => {
|
||
out.push(character);
|
||
index += 1;
|
||
}
|
||
}
|
||
}
|
||
out
|
||
}
|
||
|
||
fn tabular_unit(
|
||
geometry: &PageGeometry,
|
||
id: u64,
|
||
template: &str,
|
||
source: &str,
|
||
target: Option<i64>,
|
||
) -> Unit {
|
||
let template = expand_tabular_template(template, source, target);
|
||
let mut unit = Unit::halign_from_source_with_template_and_tabskips(
|
||
id,
|
||
&engine_template(&template),
|
||
source,
|
||
6,
|
||
Vec::new(),
|
||
);
|
||
let separator = geometry.tab_col_sep.unwrap_or(6 * SCALE);
|
||
let stretch = geometry.array_stretch.unwrap_or(1000);
|
||
if separator != 6 * SCALE || stretch != 1000 {
|
||
if let Some(VerticalItem::Halign(halign)) = unit.items.first_mut() {
|
||
if separator != 6 * SCALE {
|
||
let gaps = halign.column_widths.len().saturating_sub(1);
|
||
halign.column_skips = vec![separator; gaps];
|
||
halign.width = halign.column_widths.iter().sum::<i64>() + separator * gaps as i64;
|
||
}
|
||
if stretch != 1000 {
|
||
halign.line_height = halign.line_height.saturating_mul(stretch) / 1000;
|
||
halign.height = (0..halign.rows.len())
|
||
.map(|index| halign.row_height(index) + halign.row_gap(index))
|
||
.sum();
|
||
}
|
||
}
|
||
}
|
||
unit
|
||
}
|
||
|
||
fn engine_template(spec: &str) -> String {
|
||
let mut out = String::new();
|
||
let mut characters = spec.chars().peekable();
|
||
while let Some(character) = characters.next() {
|
||
match character {
|
||
'l' | 'c' | 'r' => out.push(character),
|
||
'p' | 'm' | 'b' => {
|
||
out.push('p');
|
||
if characters.peek() == Some(&'{') {
|
||
let mut depth = 0_i32;
|
||
for inner in characters.by_ref() {
|
||
out.push(inner);
|
||
match inner {
|
||
'{' => depth += 1,
|
||
'}' => {
|
||
depth -= 1;
|
||
if depth == 0 {
|
||
break;
|
||
}
|
||
}
|
||
_ => {}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
'|' => out.push('|'),
|
||
'*' => {
|
||
if characters.peek() != Some(&'{') {
|
||
continue;
|
||
}
|
||
characters.next();
|
||
let mut count = String::new();
|
||
while let Some(&digit) = characters.peek() {
|
||
characters.next();
|
||
if digit == '}' {
|
||
break;
|
||
}
|
||
if digit.is_ascii_digit() {
|
||
count.push(digit);
|
||
}
|
||
}
|
||
let Some(count) = count.parse::<usize>().ok() else {
|
||
continue;
|
||
};
|
||
if characters.peek() != Some(&'{') {
|
||
continue;
|
||
}
|
||
let mut inner = String::new();
|
||
let mut depth = 1_u32;
|
||
for character in characters.by_ref() {
|
||
match character {
|
||
'{' => {
|
||
depth += 1;
|
||
inner.push(character);
|
||
}
|
||
'}' => {
|
||
depth -= 1;
|
||
if depth == 0 {
|
||
break;
|
||
}
|
||
inner.push(character);
|
||
}
|
||
_ => inner.push(character),
|
||
}
|
||
}
|
||
out.push_str(&engine_template(&inner).repeat(count.min(20)));
|
||
}
|
||
' ' | '\t' => {}
|
||
'@' | '!' | '>' | '<' => {
|
||
if characters.peek() == Some(&'{') {
|
||
let mut depth = 0_i32;
|
||
for inner in characters.by_ref() {
|
||
match inner {
|
||
'{' => depth += 1,
|
||
'}' => {
|
||
depth -= 1;
|
||
if depth == 0 {
|
||
break;
|
||
}
|
||
}
|
||
_ => {}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
_ => {}
|
||
}
|
||
}
|
||
if out.is_empty() { "l".to_string() } else { out }
|
||
}
|
||
|
||
fn table_reference(text: &str) -> Option<usize> {
|
||
text.trim()
|
||
.strip_prefix("\\texrratable{")?
|
||
.strip_suffix('}')?
|
||
.parse()
|
||
.ok()
|
||
}
|
||
|
||
/// Strip geometry assignments from the whole source (preamble included) and
|
||
/// return the LaTeX body with them removed.
|
||
fn geometry_and_body(source: &str) -> (String, PageGeometry) {
|
||
let (stripped, mut geometry) = strip_page_geometry(source);
|
||
// Removed assignments can leave blank lines at the edges; they are not
|
||
// paragraphs of their own.
|
||
let mut body = latex_body(&stripped).trim_matches('\n').to_string();
|
||
geometry.bibliography = extract_bibliography(&mut body);
|
||
body = expand_environments(&body, &geometry.environments);
|
||
body = expand_macros(&body, &geometry.macros);
|
||
body = expand_links(&body);
|
||
body = expand_conditionals(&body, &mut geometry.conditionals);
|
||
let today = today_string();
|
||
body = expand_today(&body, &today);
|
||
(body, geometry)
|
||
}
|
||
|
||
/// Remove a `thebibliography` environment from the body and return its
|
||
/// `\bibitem{key}` entries in order.
|
||
fn extract_bibliography(body: &mut String) -> Vec<(String, String)> {
|
||
let begin = r"\begin{thebibliography}";
|
||
let end = r"\end{thebibliography}";
|
||
let Some(start) = body.find(begin) else {
|
||
return Vec::new();
|
||
};
|
||
let after_begin = start + begin.len();
|
||
let Some(offset) = body[after_begin..].find(end) else {
|
||
return Vec::new();
|
||
};
|
||
let inner_start = body[after_begin..]
|
||
.find('}')
|
||
.map_or(after_begin, |close| after_begin + close + 1);
|
||
let inner = body[inner_start..after_begin + offset].to_string();
|
||
body.replace_range(start..after_begin + offset + end.len(), "");
|
||
let mut entries = Vec::new();
|
||
let mut rest = inner.as_str();
|
||
while let Some(index) = rest.find(r"\bibitem") {
|
||
let after = rest[index + r"\bibitem".len()..].trim_start();
|
||
let after = match after.strip_prefix('[') {
|
||
Some(label) => match label.split_once(']') {
|
||
Some((_, tail)) => tail.trim_start(),
|
||
None => after,
|
||
},
|
||
None => after,
|
||
};
|
||
let Some((key, consumed)) = braced_group(after) else {
|
||
break;
|
||
};
|
||
let tail = &after[consumed..];
|
||
let next = tail.find(r"\bibitem").unwrap_or(tail.len());
|
||
entries.push((key.trim().to_string(), tail[..next].trim().to_string()));
|
||
rest = &tail[next..];
|
||
}
|
||
entries
|
||
}
|
||
|
||
/// Replace `\cite{...}` with `[n]`/`[n, m]` from the bibliography order.
|
||
/// Remove `\nocite{...}` commands; citations are resolved from the written
|
||
/// `thebibliography` block and there is no BibTeX pass to extend it.
|
||
fn strip_nocite(text: &str) -> String {
|
||
let mut out = String::with_capacity(text.len());
|
||
let mut rest = text;
|
||
while let Some(index) = rest.find(r"\nocite") {
|
||
out.push_str(&rest[..index]);
|
||
let after = rest[index + r"\nocite".len()..].trim_start();
|
||
let Some((_, consumed)) = braced_group(after) else {
|
||
out.push_str(&rest[index..]);
|
||
return out;
|
||
};
|
||
rest = &after[consumed..];
|
||
}
|
||
out.push_str(rest);
|
||
out
|
||
}
|
||
|
||
fn resolve_citations(paragraphs: &mut [SourceParagraph], bibliography: &[(String, String)]) {
|
||
let keys: Vec<&str> = bibliography.iter().map(|(key, _)| key.as_str()).collect();
|
||
for paragraph in paragraphs {
|
||
paragraph.text = strip_nocite(¶graph.text);
|
||
let mut text = String::with_capacity(paragraph.text.len());
|
||
let mut rest = paragraph.text.as_str();
|
||
while let Some(index) = rest.find(r"\cite") {
|
||
text.push_str(&rest[..index]);
|
||
let command =
|
||
if rest[index..].starts_with(r"\citep") || rest[index..].starts_with(r"\citet") {
|
||
&rest[index..index + 6]
|
||
} else {
|
||
&rest[index..index + 5]
|
||
};
|
||
let mut after = rest[index + command.len()..].trim_start();
|
||
// `\cite[p.~3]{key}` drops the optional note but keeps the number.
|
||
while let Some(note) = after.strip_prefix('[') {
|
||
let Some(end) = note.find(']') else {
|
||
break;
|
||
};
|
||
after = note[end + 1..].trim_start();
|
||
}
|
||
let Some((body, consumed)) = braced_group(after) else {
|
||
text.push_str(&rest[index..]);
|
||
rest = "";
|
||
break;
|
||
};
|
||
let numbers: Vec<String> = body
|
||
.split(',')
|
||
.map(|key| {
|
||
keys.iter()
|
||
.position(|candidate| *candidate == key.trim())
|
||
.map_or_else(|| "?".to_string(), |position| (position + 1).to_string())
|
||
})
|
||
.collect();
|
||
let _ = write!(text, "[{}]", numbers.join(", "));
|
||
rest = &after[consumed..];
|
||
}
|
||
text.push_str(rest);
|
||
paragraph.text = text;
|
||
}
|
||
}
|
||
|
||
fn apply_geometry(document: &mut Document, geometry: &PageGeometry) {
|
||
document.h_offset = geometry.origin.h_offset;
|
||
document.v_offset = geometry.origin.v_offset;
|
||
if let Some(width) = geometry.paper_width {
|
||
document.paper_width = width;
|
||
}
|
||
if let Some(height) = geometry.paper_height {
|
||
document.paper_height = height;
|
||
}
|
||
if let Some(height) = geometry.textheight.or(geometry.vsize) {
|
||
document.page_goal = height;
|
||
}
|
||
if let Some(skip) = geometry.par_skip {
|
||
document.par_skip = skip;
|
||
}
|
||
if let Some(stretch) = geometry.par_skip_stretch {
|
||
document.par_skip_stretch = stretch;
|
||
}
|
||
if let Some(shrink) = geometry.par_skip_shrink {
|
||
document.par_skip_shrink = shrink;
|
||
}
|
||
if let Some(skip) = geometry.top_skip {
|
||
document.top_skip = skip;
|
||
}
|
||
if let Some(depth) = geometry.max_depth {
|
||
document.max_depth = depth;
|
||
}
|
||
if let Some(skip) = geometry.split_top_skip {
|
||
document.split_top_skip = skip;
|
||
}
|
||
if let Some(depth) = geometry.split_max_depth {
|
||
document.split_max_depth = depth;
|
||
}
|
||
}
|
||
|
||
/// Read a `\parfillskip` glue assignment, preserving the `1fil` order.
|
||
fn parfillskip_assignment(line: &str) -> Option<(i64, i64, bool)> {
|
||
let rest = line.strip_prefix("\\parfillskip")?.trim_start();
|
||
let rest = rest.strip_prefix('=')?.trim();
|
||
let (width, rest) = split_glue_part(rest)?;
|
||
let mut stretch = 0_i64;
|
||
let mut fil = false;
|
||
let rest = rest.trim_start();
|
||
let rest = if let Some(rest) = rest.strip_prefix("plus") {
|
||
let rest = rest.trim_start();
|
||
if let Some(rest) = rest.strip_prefix("1fil") {
|
||
fil = true;
|
||
rest
|
||
} else {
|
||
let (value, rest) = split_glue_part(rest)?;
|
||
stretch = value;
|
||
rest
|
||
}
|
||
} else {
|
||
rest
|
||
};
|
||
let _ = rest;
|
||
Some((width, stretch, fil))
|
||
}
|
||
|
||
/// Read a `\parshape` specification such as `\parshape=2 0pt 100pt 20pt 80pt`.
|
||
fn parshape_assignment(line: &str) -> Option<Vec<(i64, i64)>> {
|
||
let rest = line.strip_prefix("\\parshape")?.trim_start();
|
||
let rest = rest.strip_prefix('=').unwrap_or(rest).trim();
|
||
let mut parts = rest.split_whitespace();
|
||
let count: usize = parts.next()?.parse().ok()?;
|
||
let mut shape = Vec::with_capacity(count);
|
||
for _ in 0..count {
|
||
let indent = parse_dimension(parts.next()?)?;
|
||
let width = parse_dimension(parts.next()?)?;
|
||
shape.push((indent, width));
|
||
}
|
||
Some(shape)
|
||
}
|
||
|
||
/// Read a braced argument such as `\hyphenation{hy-phen-a-tion}`.
|
||
fn braced_argument<'a>(line: &'a str, command: &str) -> Option<&'a str> {
|
||
let rest = line.strip_prefix(command)?.trim_start();
|
||
let rest = rest.strip_prefix('{')?;
|
||
let mut depth = 1_usize;
|
||
for (index, character) in rest.char_indices() {
|
||
match character {
|
||
'{' => depth += 1,
|
||
'}' => {
|
||
depth -= 1;
|
||
if depth == 0 {
|
||
return Some(&rest[..index]);
|
||
}
|
||
}
|
||
_ => {}
|
||
}
|
||
}
|
||
None
|
||
}
|
||
|
||
/// Read a `\sfcode` assignment such as ``\sfcode`x=2000`` or `\sfcode46=1000`.
|
||
fn sfcode_assignment(line: &str) -> Option<(char, i64)> {
|
||
let rest = line.strip_prefix("\\sfcode")?;
|
||
let rest = rest.trim_start();
|
||
let rest = rest.strip_prefix('=').unwrap_or(rest).trim_start();
|
||
let (character, rest) = if let Some(rest) = rest.strip_prefix('`') {
|
||
let rest = rest.strip_prefix('\\').unwrap_or(rest);
|
||
let mut characters = rest.chars();
|
||
let character = characters.next()?;
|
||
(character, characters.as_str())
|
||
} else {
|
||
let end = rest
|
||
.find(|character: char| !character.is_ascii_digit())
|
||
.unwrap_or(rest.len());
|
||
let code: u32 = rest[..end].parse().ok()?;
|
||
(char::from_u32(code)?, &rest[end..])
|
||
};
|
||
let rest = rest.trim_start().strip_prefix('=')?;
|
||
Some((character, rest.trim().parse().ok()?))
|
||
}
|
||
|
||
/// Read a plain integer assignment such as `\tolerance=1000`.
|
||
fn glue_assignment(line: &str, name: &str) -> Option<(i64, i64, i64)> {
|
||
let rest = line.strip_prefix('\\')?;
|
||
let rest = rest.strip_prefix(name)?;
|
||
let rest = rest.trim_start().strip_prefix('=')?;
|
||
let rest = rest.trim();
|
||
let (width, rest) = split_glue_part(rest)?;
|
||
let (stretch, rest) = match rest.trim_start().strip_prefix("plus") {
|
||
Some(rest) => split_glue_part(rest.trim_start())?,
|
||
None => (0, rest),
|
||
};
|
||
let shrink = match rest.trim_start().strip_prefix("minus") {
|
||
Some(rest) => split_glue_part(rest.trim_start())?.0,
|
||
None => 0,
|
||
};
|
||
Some((width, stretch, shrink))
|
||
}
|
||
|
||
fn split_glue_part(text: &str) -> Option<(i64, &str)> {
|
||
let end = text
|
||
.find(|character: char| {
|
||
!(character.is_ascii_digit() || character == '.' || character == '-')
|
||
})
|
||
.unwrap_or(text.len());
|
||
let number: f64 = text[..end].parse().ok()?;
|
||
let unit_text = &text[end..];
|
||
let (unit, rest) = ["pt", "bp", "in", "cm", "mm", "pc"]
|
||
.iter()
|
||
.find_map(|unit| unit_text.strip_prefix(unit).map(|rest| (*unit, rest)))?;
|
||
let factor = match unit {
|
||
"pt" => 65_536.0,
|
||
"bp" => 65_782.0,
|
||
"in" => 4_736_286.0,
|
||
"cm" => 1_864_680.0,
|
||
"mm" => 186_468.0,
|
||
_ => 786_432.0,
|
||
};
|
||
Some(((number * factor).round() as i64, rest))
|
||
}
|
||
|
||
fn integer_assignment(line: &str, name: &str) -> Option<i64> {
|
||
let rest = line.strip_prefix('\\')?;
|
||
let rest = rest.strip_prefix(name)?;
|
||
let rest = rest.trim_start().strip_prefix('=')?;
|
||
rest.trim()
|
||
.parse::<i64>()
|
||
.ok()
|
||
.map(|value| value.clamp(0, 10_000))
|
||
}
|
||
|
||
/// Read a signed integer assignment such as `\\looseness=-1`.
|
||
fn signed_integer_assignment(line: &str, name: &str) -> Option<i64> {
|
||
let rest = line.strip_prefix('\\')?;
|
||
let rest = rest.strip_prefix(name)?;
|
||
let rest = rest.trim_start().strip_prefix('=')?;
|
||
rest.trim().parse::<i64>().ok()
|
||
}
|
||
|
||
fn dimension_assignment(line: &str, name: &str) -> Option<i64> {
|
||
let rest = line.strip_prefix('\\')?;
|
||
let rest = rest.strip_prefix(name)?;
|
||
let rest = rest.trim_start().strip_prefix('=')?;
|
||
parse_dimension(rest.trim())
|
||
}
|
||
|
||
/// Read a LaTeX `\setlength{\parskip}{<glue>}` assignment.
|
||
fn setlength_glue(line: &str, name: &str) -> Option<(i64, i64, i64)> {
|
||
let rest = line.strip_prefix("\\setlength")?;
|
||
let rest = rest.trim_start().strip_prefix('{')?;
|
||
let (target, rest) = rest.split_once('}')?;
|
||
if target.trim() != format!("\\{name}") {
|
||
return None;
|
||
}
|
||
let rest = rest.trim_start().strip_prefix('{')?;
|
||
let (value, _) = rest.split_once('}')?;
|
||
let (width, rest) = split_glue_part(value.trim())?;
|
||
let mut stretch = 0_i64;
|
||
let mut shrink = 0_i64;
|
||
let rest = rest.trim_start();
|
||
let rest = if let Some(rest) = rest.strip_prefix("plus") {
|
||
let (value, rest) = split_glue_part(rest.trim_start())?;
|
||
stretch = value;
|
||
rest
|
||
} else {
|
||
rest
|
||
};
|
||
let rest = rest.trim_start();
|
||
let _ = if let Some(rest) = rest.strip_prefix("minus") {
|
||
let (value, _) = split_glue_part(rest.trim_start())?;
|
||
shrink = value;
|
||
};
|
||
Some((width, stretch, shrink))
|
||
}
|
||
|
||
/// Read a LaTeX `\setlength{\name}{<dimension>}` assignment.
|
||
fn addtolength_assignment(line: &str) -> Option<(String, String)> {
|
||
let rest = line.strip_prefix("\\addtolength")?;
|
||
let rest = rest.trim_start().strip_prefix('{')?;
|
||
let (target, rest) = rest.split_once('}')?;
|
||
let name = target.trim().strip_prefix('\\')?;
|
||
let rest = rest.trim_start().strip_prefix('{')?;
|
||
let (value, _) = rest.split_once('}')?;
|
||
Some((name.to_string(), value.trim().to_string()))
|
||
}
|
||
|
||
fn setlength_assignment(line: &str) -> Option<(String, String)> {
|
||
let rest = line.strip_prefix("\\setlength")?;
|
||
let rest = rest.trim_start().strip_prefix('{')?;
|
||
let (target, rest) = rest.split_once('}')?;
|
||
let name = target.trim().strip_prefix('\\')?;
|
||
let rest = rest.trim_start().strip_prefix('{')?;
|
||
let (value, _) = rest.split_once('}')?;
|
||
Some((name.to_string(), value.trim().to_string()))
|
||
}
|
||
|
||
/// Resolve a dimension literal or a length declared with `\\newlength`.
|
||
fn length_value(geometry: &PageGeometry, value: &str) -> Option<i64> {
|
||
if let Some(value) = parse_dimension(value.trim()) {
|
||
return Some(value);
|
||
}
|
||
let name = value.trim().strip_prefix('\\')?;
|
||
geometry
|
||
.lengths
|
||
.iter()
|
||
.rev()
|
||
.find(|(known, _)| known == name)
|
||
.map(|(_, value)| *value)
|
||
}
|
||
|
||
fn parse_dimension(text: &str) -> Option<i64> {
|
||
let end = text
|
||
.find(|character: char| {
|
||
!(character.is_ascii_digit() || character == '.' || character == '-')
|
||
})
|
||
.unwrap_or(text.len());
|
||
let number: f64 = text[..end].parse().ok()?;
|
||
let factor = match text[end..].trim() {
|
||
"pt" => 1.0,
|
||
"bp" => 72.27 / 72.0,
|
||
"in" => 72.27,
|
||
"cm" => 72.27 / 2.54,
|
||
"mm" => 72.27 / 25.4,
|
||
"pc" => 12.0,
|
||
"dd" => 1238.0 / 1157.0,
|
||
"cc" => 12.0 * 1238.0 / 1157.0,
|
||
"sp" => 1.0 / 65_536.0,
|
||
// The document class default is 10pt, so `em`/`ex` follow it.
|
||
"em" => 10.0,
|
||
"ex" => 5.0,
|
||
_ => return None,
|
||
};
|
||
Some((number * factor * 65_536.0).round() as i64)
|
||
}
|
||
|
||
/// Lay a document out with the TeX page builder, falling back to the
|
||
/// scrolling builder for material the paged builder cannot express.
|
||
fn layout_document(document: &Document) -> Engine {
|
||
Engine::layout_paged(document).unwrap_or_else(|| Engine::layout(document))
|
||
}
|
||
|
||
/// Resolve `\pageref{label}` to the formatted page number of the heading
|
||
/// that carries the label, using a probe layout followed by the real one.
|
||
fn page_refs_for(body: &str, geometry: &PageGeometry) -> HashMap<String, String> {
|
||
let mut pages = HashMap::new();
|
||
let probe = apply_page_refs(body, &HashMap::new());
|
||
let paragraphs = match paragraphs_with_geometry(
|
||
&probe,
|
||
&geometry.theorem_definitions,
|
||
geometry_counter(geometry, "equation"),
|
||
geometry,
|
||
) {
|
||
Ok(paragraphs) => paragraphs,
|
||
Err(_) => return pages,
|
||
};
|
||
let mut label_units = HashMap::new();
|
||
let mut document =
|
||
build_document_with_labels(¶graphs, geometry, &mut label_units, &mut Vec::new());
|
||
apply_geometry(&mut document, geometry);
|
||
let engine = layout_document(&document);
|
||
let mut unit_page = HashMap::new();
|
||
for (index, page) in engine.pages().iter().enumerate() {
|
||
for (unit, _) in &page.sources {
|
||
unit_page.entry(*unit).or_insert(index);
|
||
}
|
||
}
|
||
let style = geometry.page_numbering.as_deref().unwrap_or("arabic");
|
||
for (label, unit) in label_units {
|
||
if let Some(page) = unit_page.get(&unit) {
|
||
pages.insert(label, page_number_text(*page, style, geometry.page_start));
|
||
}
|
||
}
|
||
pages
|
||
}
|
||
|
||
fn apply_page_refs(body: &str, pages: &HashMap<String, String>) -> String {
|
||
let mut result = String::with_capacity(body.len());
|
||
let mut rest = body;
|
||
while let Some(position) = rest.find("\\pageref{") {
|
||
result.push_str(&rest[..position]);
|
||
let after = &rest[position + "\\pageref{".len()..];
|
||
let Some(close) = after.find('}') else {
|
||
result.push_str(&rest[position..]);
|
||
return result;
|
||
};
|
||
let key = &after[..close];
|
||
result.push_str(pages.get(key).map(String::as_str).unwrap_or("??"));
|
||
rest = &after[close + 1..];
|
||
}
|
||
result.push_str(rest);
|
||
result
|
||
}
|
||
|
||
fn resolve_page_references(body: String, geometry: &PageGeometry) -> String {
|
||
if !body.contains("\\pageref") {
|
||
return body;
|
||
}
|
||
let pages = page_refs_for(&body, geometry);
|
||
apply_page_refs(&body, &pages)
|
||
}
|
||
|
||
/// Build a JSON preview from blank-line-separated plain-text paragraphs.
|
||
pub fn preview_json(source: &str) -> Result<String, String> {
|
||
let (body, geometry) = geometry_and_body(source);
|
||
let body = resolve_page_references(body, &geometry);
|
||
let paragraphs = paragraphs_with_geometry(
|
||
&body,
|
||
&geometry.theorem_definitions,
|
||
geometry_counter(&geometry, "equation"),
|
||
&geometry,
|
||
)?;
|
||
let mut document = build_document(¶graphs, &geometry);
|
||
apply_geometry(&mut document, &geometry);
|
||
let engine = layout_document(&document);
|
||
let mut warnings = source_warnings(source);
|
||
warnings.extend(document_warnings(&document));
|
||
let json = render_json(&document, &engine, None, &geometry, &warnings);
|
||
// Keep the layout so a following `/edit` request can diff against it and
|
||
// reuse page checkpoints instead of starting from a no-op document.
|
||
ROUTE_D_SESSION.with(|slot| {
|
||
*slot.borrow_mut() = Some((document, engine));
|
||
});
|
||
Ok(json)
|
||
}
|
||
|
||
/// Render the same checkpointed document as a route-D PDF.
|
||
pub fn pdf_bytes(source: &str) -> Result<Vec<u8>, String> {
|
||
pdf_bytes_with_images(source, &HashMap::new())
|
||
}
|
||
|
||
/// Render a route-D PDF with decoded project images.
|
||
pub fn pdf_bytes_with_images(
|
||
source: &str,
|
||
images: &HashMap<String, RasterImage>,
|
||
) -> Result<Vec<u8>, String> {
|
||
let (body, mut geometry) = geometry_and_body(source);
|
||
geometry.images = images.clone();
|
||
let body = resolve_page_references(body, &geometry);
|
||
let paragraphs = paragraphs_with_geometry(
|
||
&body,
|
||
&geometry.theorem_definitions,
|
||
geometry_counter(&geometry, "equation"),
|
||
&geometry,
|
||
)?;
|
||
let mut outline_units = Vec::new();
|
||
let mut document = build_document_with_labels(
|
||
¶graphs,
|
||
&geometry,
|
||
&mut HashMap::new(),
|
||
&mut outline_units,
|
||
);
|
||
apply_geometry(&mut document, &geometry);
|
||
let engine = layout_document(&document);
|
||
let mut page_of: HashMap<u64, usize> = HashMap::new();
|
||
for (index, page) in engine.pages().iter().enumerate() {
|
||
for (unit, _) in &page.sources {
|
||
page_of.entry(*unit).or_insert(index);
|
||
}
|
||
}
|
||
let outline: Vec<PdfOutlineEntry> = outline_units
|
||
.iter()
|
||
.filter_map(|(title, level, unit)| {
|
||
page_of.get(unit).map(|page| PdfOutlineEntry {
|
||
title: title.clone(),
|
||
page: *page,
|
||
level: *level,
|
||
})
|
||
})
|
||
.collect();
|
||
let mut pages: Vec<_> = engine
|
||
.pages()
|
||
.iter()
|
||
.map(|page| {
|
||
let mut list =
|
||
page.display_list_with_layout(document.page_goal, document.text_float_sep);
|
||
list.width = list.width.max(document.paper_width);
|
||
list.height = list.height.max(document.paper_height);
|
||
list
|
||
})
|
||
.collect();
|
||
if !geometry.suppress_page_numbers {
|
||
let style = geometry.page_numbering.as_deref().unwrap_or("arabic");
|
||
stamp_page_numbers(
|
||
&mut pages,
|
||
document.page_goal,
|
||
document.paper_width,
|
||
document.paper_height,
|
||
style,
|
||
geometry.page_start,
|
||
geometry.suppress_first_page_number,
|
||
);
|
||
}
|
||
let metadata = PdfMetadata {
|
||
title: geometry
|
||
.pdf_title
|
||
.clone()
|
||
.or_else(|| geometry.title.clone()),
|
||
author: geometry
|
||
.pdf_author
|
||
.clone()
|
||
.or_else(|| geometry.author.clone()),
|
||
subject: geometry.pdf_subject.clone(),
|
||
keywords: geometry.pdf_keywords.clone(),
|
||
outline,
|
||
};
|
||
Ok(display_lists_to_pdf_with_cm_type1_and_metadata(
|
||
&pages,
|
||
document.paper_width,
|
||
document.paper_height,
|
||
geometry.origin,
|
||
&metadata,
|
||
))
|
||
}
|
||
|
||
/// Apply one paragraph edit to the last route-D document and report page
|
||
/// checkpoints that were reused versus rebuilt.
|
||
pub fn edit_json(source: &str, unit: usize) -> Result<String, String> {
|
||
let (body, geometry) = geometry_and_body(source);
|
||
let body = resolve_page_references(body, &geometry);
|
||
let paragraphs = paragraphs_with_geometry(
|
||
&body,
|
||
&geometry.theorem_definitions,
|
||
geometry_counter(&geometry, "equation"),
|
||
&geometry,
|
||
)?;
|
||
if unit >= paragraphs.len() {
|
||
return Err(format!(
|
||
"unit {unit} is out of range for {} paragraphs",
|
||
paragraphs.len()
|
||
));
|
||
}
|
||
let next = build_document(¶graphs, &geometry);
|
||
ROUTE_D_SESSION.with(|slot| {
|
||
let mut slot = slot.borrow_mut();
|
||
let (_, mut engine) = match slot.take() {
|
||
Some(session) => session,
|
||
None => {
|
||
let engine = layout_document(&next);
|
||
(next.clone(), engine)
|
||
}
|
||
};
|
||
let paragraph = ¶graphs[unit];
|
||
match inline_runs(¶graph.text, paragraph.font) {
|
||
Some(runs) => {
|
||
engine.edit_runs(&next, unit as u64, paragraph.text.clone(), runs);
|
||
}
|
||
None => engine.edit(&next, unit as u64, paragraph.text.clone()),
|
||
}
|
||
let changed = engine.changed_pages().to_vec();
|
||
let recomputed = engine.recomputed_pages();
|
||
let mut warnings = source_warnings(source);
|
||
warnings.extend(document_warnings(&next));
|
||
let json = render_json(
|
||
&next,
|
||
&engine,
|
||
Some((&changed, recomputed)),
|
||
&geometry,
|
||
&warnings,
|
||
);
|
||
*slot = Some((next, engine));
|
||
Ok(json)
|
||
})
|
||
}
|
||
|
||
#[derive(Clone, PartialEq, Eq)]
|
||
struct SourceParagraph {
|
||
text: String,
|
||
/// TeX `\newpage` before this paragraph.
|
||
page_break: bool,
|
||
centered: bool,
|
||
right_aligned: bool,
|
||
font: ParagraphFont,
|
||
line_height: i64,
|
||
math: bool,
|
||
left_skip: i64,
|
||
space_before: i64,
|
||
space_stretch: i64,
|
||
space_shrink: i64,
|
||
/// Number of the equation environment this block came from.
|
||
equation_number: Option<u32>,
|
||
equation_tag: Option<String>,
|
||
/// Rows of an `align`/`gather` environment.
|
||
equation_rows: Vec<EquationRow>,
|
||
/// Whether the rows are centred (`gather`) rather than column-aligned.
|
||
align_centered: bool,
|
||
/// Sectioning level: 1 for `\section`, 2 for `\subsection`, 3 for
|
||
/// `\subsubsection`.
|
||
heading_level: Option<u8>,
|
||
/// Starred headings are unnumbered and do not advance the counters.
|
||
heading_starred: bool,
|
||
/// The section number assigned by the numbering pass.
|
||
heading_number: Option<String>,
|
||
heading_short: Option<String>,
|
||
/// Footnote bodies extracted from this paragraph, with their numbers.
|
||
footnotes: Vec<(u32, String)>,
|
||
font_size: Option<i64>,
|
||
/// A `figure` environment carried as a float unit.
|
||
float: Option<FloatSpec>,
|
||
/// A theorem-like environment heading.
|
||
theorem: Option<TheoremSpec>,
|
||
/// Nesting depth when this paragraph is a list item.
|
||
list_depth: Option<u8>,
|
||
/// Width of the generated list label, in points.
|
||
list_label: i64,
|
||
/// Extra right margin in points, used by quotation blocks.
|
||
right_skip: i64,
|
||
/// Overrides the paragraph measure inside a `minipage` environment.
|
||
width: Option<i64>,
|
||
/// A `multline` display: rows share one equation number.
|
||
multline: bool,
|
||
}
|
||
|
||
/// The kind of a LaTeX float environment.
|
||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||
enum FloatKind {
|
||
Figure,
|
||
Table,
|
||
}
|
||
|
||
impl FloatKind {
|
||
fn caption_prefix<'a>(self, figure_name: &'a str, table_name: &'a str) -> &'a str {
|
||
match self {
|
||
FloatKind::Figure => figure_name,
|
||
FloatKind::Table => table_name,
|
||
}
|
||
}
|
||
}
|
||
|
||
/// A theorem-like environment: numbering state and label targets.
|
||
#[derive(Clone, PartialEq, Eq)]
|
||
struct TheoremSpec {
|
||
name: String,
|
||
display: String,
|
||
title: Option<String>,
|
||
starred: bool,
|
||
number: Option<String>,
|
||
labels: Vec<String>,
|
||
}
|
||
|
||
/// A width or height requested by `\includegraphics`.
|
||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||
enum ImageLength {
|
||
Absolute(i64),
|
||
TextWidthPercent(i64),
|
||
TextHeightPercent(i64),
|
||
}
|
||
|
||
impl ImageLength {
|
||
fn resolve(self, line_width: i64, text_height: i64) -> i64 {
|
||
match self {
|
||
ImageLength::Absolute(value) => value,
|
||
ImageLength::TextWidthPercent(percent) => line_width.saturating_mul(percent) / 100,
|
||
ImageLength::TextHeightPercent(percent) => text_height.saturating_mul(percent) / 100,
|
||
}
|
||
}
|
||
}
|
||
|
||
/// A `figure` or `table` environment: placement, graphics size and caption.
|
||
#[derive(Clone, PartialEq, Eq)]
|
||
struct FloatSpec {
|
||
kind: FloatKind,
|
||
placement: FloatPlacement,
|
||
width: Option<ImageLength>,
|
||
height: Option<ImageLength>,
|
||
/// `scale=...` percentage of the image's natural size.
|
||
scale: Option<i64>,
|
||
/// `keepaspectratio` when both width and height are requested.
|
||
keep_aspectratio: bool,
|
||
caption: Option<String>,
|
||
/// The optional `[short]` caption used by float lists.
|
||
caption_short: Option<String>,
|
||
/// Numbered float-list entry derived from the short caption.
|
||
list_caption: Option<String>,
|
||
caption_starred: bool,
|
||
/// `\includegraphics` path for a figure.
|
||
image: Option<String>,
|
||
/// Index into `PageGeometry::tabular` for a captured table body.
|
||
table: Option<usize>,
|
||
}
|
||
|
||
/// One row of an `align`/`gather` environment.
|
||
#[derive(Clone, PartialEq, Eq)]
|
||
struct EquationRow {
|
||
text: String,
|
||
number: Option<u32>,
|
||
tag: Option<String>,
|
||
}
|
||
|
||
/// Recognise an explicit vertical skip command standing alone between
|
||
/// paragraphs.
|
||
fn vertical_skip(text: &str) -> Option<(i64, i64, i64)> {
|
||
match text.trim() {
|
||
"\\smallskip" => Some((3 * SCALE, SCALE, SCALE)),
|
||
"\\medskip" => Some((6 * SCALE, 2 * SCALE, 2 * SCALE)),
|
||
"\\bigskip" => Some((12 * SCALE, 4 * SCALE, 4 * SCALE)),
|
||
other => {
|
||
if let Some(rest) = other.strip_prefix("\\vskip") {
|
||
return skip_glue(rest.trim_start());
|
||
}
|
||
let rest = other.strip_prefix("\\vspace")?.trim_start();
|
||
let rest = rest.strip_prefix('*').map(str::trim_start).unwrap_or(rest);
|
||
let (argument, _) = braced_group(rest)?;
|
||
skip_glue(&argument)
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Parse `\vskip` glue: a width with optional `plus` and `minus` parts.
|
||
fn skip_glue(rest: &str) -> Option<(i64, i64, i64)> {
|
||
let mut width = None;
|
||
let mut stretch = 0_i64;
|
||
let mut shrink = 0_i64;
|
||
let mut mode = 0_u8;
|
||
for token in rest.split_whitespace() {
|
||
match token {
|
||
"plus" => mode = 1,
|
||
"minus" => mode = 2,
|
||
_ => {
|
||
let value = parse_dimension(token)?;
|
||
match mode {
|
||
0 => width = Some(value),
|
||
1 => stretch = value,
|
||
_ => shrink = value,
|
||
}
|
||
}
|
||
}
|
||
}
|
||
Some((width?, stretch, shrink))
|
||
}
|
||
|
||
/// Expand `\input{...}` and `\include{...}` from project files.
|
||
///
|
||
/// The reader returns the file contents for a path, or `None` when the file
|
||
/// is unknown; unknown directives stay in the source so the preview still
|
||
/// renders them as text. Recursion is capped to avoid include cycles.
|
||
pub fn expand_inputs<F>(source: &str, read: F) -> String
|
||
where
|
||
F: Fn(&str) -> Option<String>,
|
||
{
|
||
expand_inputs_at(source, &read, 0)
|
||
}
|
||
|
||
fn expand_inputs_at<F>(source: &str, read: &F, depth: usize) -> String
|
||
where
|
||
F: Fn(&str) -> Option<String>,
|
||
{
|
||
const COMMANDS: [&str; 2] = ["\\input{", "\\include{"];
|
||
let mut expanded = String::new();
|
||
let mut rest = source;
|
||
loop {
|
||
let next = COMMANDS
|
||
.iter()
|
||
.filter_map(|command| rest.find(command).map(|index| (index, *command)))
|
||
.min_by_key(|(index, _)| *index);
|
||
let Some((index, command)) = next else {
|
||
expanded.push_str(rest);
|
||
break;
|
||
};
|
||
expanded.push_str(&rest[..index]);
|
||
let after = &rest[index + command.len()..];
|
||
let Some(close) = after.find('}') else {
|
||
expanded.push_str(rest);
|
||
break;
|
||
};
|
||
let name = after[..close].trim();
|
||
let directive = &rest[index..index + command.len() + close + 1];
|
||
match read(name) {
|
||
Some(text) if depth < 8 => {
|
||
expanded.push_str(&expand_inputs_at(&text, read, depth + 1));
|
||
}
|
||
_ => expanded.push_str(directive),
|
||
}
|
||
rest = &after[close + 1..];
|
||
}
|
||
expanded
|
||
}
|
||
|
||
#[cfg_attr(not(test), allow(dead_code))]
|
||
fn paragraphs(source: &str) -> Result<Vec<SourceParagraph>, String> {
|
||
paragraphs_with_definitions(source, &[])
|
||
}
|
||
|
||
fn paragraphs_with_definitions(
|
||
source: &str,
|
||
definitions: &[TheoremDefinition],
|
||
) -> Result<Vec<SourceParagraph>, String> {
|
||
paragraphs_with_counters(source, definitions, 0)
|
||
}
|
||
|
||
fn paragraphs_with_counters(
|
||
source: &str,
|
||
definitions: &[TheoremDefinition],
|
||
equation_start: u32,
|
||
) -> Result<Vec<SourceParagraph>, String> {
|
||
paragraphs_with_spacing(
|
||
source,
|
||
definitions,
|
||
equation_start,
|
||
ListSpacing::article(&PageGeometry::default()),
|
||
)
|
||
}
|
||
|
||
fn paragraphs_with_geometry(
|
||
source: &str,
|
||
definitions: &[TheoremDefinition],
|
||
equation_start: u32,
|
||
geometry: &PageGeometry,
|
||
) -> Result<Vec<SourceParagraph>, String> {
|
||
paragraphs_with_spacing(
|
||
source,
|
||
definitions,
|
||
equation_start,
|
||
ListSpacing::article(geometry),
|
||
)
|
||
}
|
||
|
||
/// Blank-line splitter that keeps environments which may contain blank lines
|
||
/// (quotation, quote, verse, abstract) in one chunk.
|
||
fn split_display_chunks(source: &str) -> Vec<&str> {
|
||
const OPENINGS: [&str; 5] = [
|
||
"\\begin{quotation}",
|
||
"\\begin{quote}",
|
||
"\\begin{verse}",
|
||
"\\begin{abstract}",
|
||
"\\begin{minipage}",
|
||
];
|
||
fn depth(text: &str) -> i64 {
|
||
let mut depth = 0;
|
||
for opening in OPENINGS {
|
||
let closing = opening.replacen("\\begin", "\\end", 1);
|
||
depth += text.matches(opening).count() as i64;
|
||
depth -= text.matches(&closing).count() as i64;
|
||
}
|
||
depth
|
||
}
|
||
let mut chunks = Vec::new();
|
||
let mut start = 0;
|
||
let bytes = source.as_bytes();
|
||
let mut index = 0;
|
||
while index + 1 < bytes.len() {
|
||
if bytes[index] == b'\n' && bytes[index + 1] == b'\n' {
|
||
let chunk = &source[start..index];
|
||
if depth(chunk) <= 0 {
|
||
chunks.push(chunk);
|
||
start = index + 2;
|
||
}
|
||
index += 2;
|
||
} else {
|
||
index += 1;
|
||
}
|
||
}
|
||
if start < source.len() {
|
||
chunks.push(&source[start..]);
|
||
}
|
||
chunks
|
||
}
|
||
|
||
fn paragraphs_with_spacing(
|
||
source: &str,
|
||
definitions: &[TheoremDefinition],
|
||
equation_start: u32,
|
||
spacing: ListSpacing,
|
||
) -> Result<Vec<SourceParagraph>, String> {
|
||
let paragraphs: Vec<&str> = split_display_chunks(source)
|
||
.into_iter()
|
||
.map(str::trim)
|
||
.filter(|paragraph| !paragraph.is_empty())
|
||
.collect();
|
||
if paragraphs.is_empty() {
|
||
return Err("route-D preview needs at least one paragraph".to_string());
|
||
}
|
||
let mut result = Vec::new();
|
||
let mut pending = (0_i64, 0_i64, 0_i64);
|
||
let mut pending_break = false;
|
||
for chunk in paragraphs {
|
||
if let Some(index) = table_reference(chunk) {
|
||
result.push(SourceParagraph {
|
||
width: None,
|
||
multline: false,
|
||
list_depth: None,
|
||
list_label: 0,
|
||
right_skip: 0,
|
||
text: format!("\\texrratable{{{index}}}"),
|
||
font: ParagraphFont::Roman,
|
||
line_height: 12,
|
||
math: false,
|
||
left_skip: 0,
|
||
centered: false,
|
||
right_aligned: false,
|
||
space_before: pending.0,
|
||
space_stretch: pending.1,
|
||
space_shrink: pending.2,
|
||
page_break: pending_break,
|
||
equation_number: None,
|
||
equation_tag: None,
|
||
equation_rows: Vec::new(),
|
||
align_centered: false,
|
||
heading_level: None,
|
||
heading_starred: false,
|
||
heading_number: None,
|
||
heading_short: None,
|
||
footnotes: Vec::new(),
|
||
theorem: None,
|
||
float: None,
|
||
font_size: None,
|
||
});
|
||
pending = (0, 0, 0);
|
||
pending_break = false;
|
||
continue;
|
||
}
|
||
if chunk == "\\newpage" || chunk == "\\clearpage" {
|
||
pending_break = true;
|
||
continue;
|
||
}
|
||
if let Some(skip) = vertical_skip(chunk) {
|
||
pending.0 += skip.0;
|
||
pending.1 += skip.1;
|
||
pending.2 += skip.2;
|
||
continue;
|
||
}
|
||
let mut blocks = parse_blocks_raw(chunk, definitions, spacing);
|
||
if let Some(first) = blocks.first_mut() {
|
||
first.space_before += pending.0;
|
||
first.space_stretch += pending.1;
|
||
first.space_shrink += pending.2;
|
||
first.page_break = pending_break;
|
||
pending_break = false;
|
||
pending = (0, 0, 0);
|
||
}
|
||
result.extend(blocks);
|
||
}
|
||
resolve_equation_numbers(&mut result, equation_start);
|
||
Ok(result)
|
||
}
|
||
|
||
fn command_body<'a>(text: &'a str, command: &str) -> Option<&'a str> {
|
||
let rest = text.strip_prefix(command)?.trim_start();
|
||
let rest = rest.strip_prefix('{')?.strip_suffix('}')?;
|
||
Some(rest.trim())
|
||
}
|
||
|
||
/// Assign equation numbers in source order and substitute label references.
|
||
fn resolve_equation_numbers(blocks: &mut [SourceParagraph], equation_start: u32) {
|
||
let mut number = equation_start;
|
||
let mut labels: Vec<(String, String)> = Vec::new();
|
||
for block in blocks.iter_mut() {
|
||
if !block.math {
|
||
continue;
|
||
}
|
||
if !block.equation_rows.is_empty() {
|
||
for row in block.equation_rows.iter_mut() {
|
||
if let Some(tag) = take_braced_argument(&mut row.text, "\\tag") {
|
||
row.tag = Some(tag);
|
||
row.number = None;
|
||
}
|
||
if row.text.contains("\\notag") || row.text.contains("\\nonumber") {
|
||
row.number = None;
|
||
}
|
||
row.text = row.text.replace("\\notag", "").replace("\\nonumber", "");
|
||
let mut value = row.tag.clone();
|
||
if row.number.is_some() {
|
||
number += 1;
|
||
row.number = Some(number);
|
||
value = Some(number.to_string());
|
||
}
|
||
if let Some(value) = value {
|
||
for label in take_labels(&mut row.text) {
|
||
labels.push((label, value.clone()));
|
||
}
|
||
}
|
||
}
|
||
continue;
|
||
}
|
||
if let Some(tag) = take_braced_argument(&mut block.text, "\\tag") {
|
||
block.equation_tag = Some(tag);
|
||
block.equation_number = None;
|
||
}
|
||
if block.text.contains("\\notag") || block.text.contains("\\nonumber") {
|
||
block.equation_number = None;
|
||
}
|
||
block.text = block.text.replace("\\notag", "").replace("\\nonumber", "");
|
||
if block.equation_number.is_none() || block.equation_tag.is_some() {
|
||
continue;
|
||
}
|
||
number += 1;
|
||
block.equation_number = Some(number);
|
||
for label in take_labels(&mut block.text) {
|
||
labels.push((label, number.to_string()));
|
||
}
|
||
}
|
||
for block in blocks.iter_mut() {
|
||
for (label, value) in labels.iter() {
|
||
let eqref = format!("\\eqref{{{label}}}");
|
||
let reference = format!("\\ref{{{label}}}");
|
||
block.text = block
|
||
.text
|
||
.replace(&eqref, &format!("({value})"))
|
||
.replace(&reference, value);
|
||
for row in block.equation_rows.iter_mut() {
|
||
row.text = row
|
||
.text
|
||
.replace(&eqref, &format!("({value})"))
|
||
.replace(&reference, value);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
fn take_labels(text: &mut String) -> Vec<String> {
|
||
let mut labels = Vec::new();
|
||
loop {
|
||
let Some(start) = text.find("\\label{") else {
|
||
break;
|
||
};
|
||
let Some(end) = text[start..].find('}') else {
|
||
break;
|
||
};
|
||
let label = text[start + 7..start + end].trim().to_string();
|
||
labels.push(label);
|
||
text.replace_range(start..start + end + 1, "");
|
||
}
|
||
labels
|
||
}
|
||
|
||
/// Parse a `figure` environment into a single float block.
|
||
fn float_block(raw: &str) -> Option<SourceParagraph> {
|
||
let trimmed = raw.trim();
|
||
let (kind, inner) = if let Some(inner) = trimmed
|
||
.strip_prefix("\\begin{figure}")
|
||
.and_then(|rest| rest.strip_suffix("\\end{figure}"))
|
||
{
|
||
(FloatKind::Figure, inner)
|
||
} else if let Some(inner) = trimmed
|
||
.strip_prefix("\\begin{table}")
|
||
.and_then(|rest| rest.strip_suffix("\\end{table}"))
|
||
{
|
||
(FloatKind::Table, inner)
|
||
} else {
|
||
return None;
|
||
};
|
||
let inner = inner.trim();
|
||
let (placement, inner) = match inner.strip_prefix('[') {
|
||
Some(rest) => {
|
||
let end = rest.find(']')?;
|
||
(figure_placement(&rest[..end]), rest[end + 1..].trim_start())
|
||
}
|
||
None => (FloatPlacement::Top, inner),
|
||
};
|
||
let (mut caption, caption_starred, caption_short) = match figure_caption(inner) {
|
||
Some((text, starred, short)) => (Some(text), starred, short),
|
||
None => (None, false, None),
|
||
};
|
||
let labels = figure_labels(inner);
|
||
if !labels.is_empty() && !caption_starred {
|
||
let mut text = caption.unwrap_or_default();
|
||
for label in labels {
|
||
let _ = write!(text, "\\label{{{label}}}");
|
||
}
|
||
caption = Some(text);
|
||
}
|
||
let (width, height, image, scale, keep_aspectratio) =
|
||
figure_graphic(inner).unwrap_or((None, None, None, None, false));
|
||
let table = embedded_table(inner);
|
||
Some(SourceParagraph {
|
||
width: None,
|
||
multline: false,
|
||
list_depth: None,
|
||
list_label: 0,
|
||
right_skip: 0,
|
||
text: String::new(),
|
||
font: ParagraphFont::Roman,
|
||
line_height: 12,
|
||
math: false,
|
||
left_skip: 0,
|
||
centered: false,
|
||
right_aligned: false,
|
||
space_before: 8 * SCALE,
|
||
space_stretch: 2 * SCALE,
|
||
space_shrink: 0,
|
||
page_break: false,
|
||
equation_number: None,
|
||
equation_tag: None,
|
||
equation_rows: Vec::new(),
|
||
align_centered: false,
|
||
heading_level: None,
|
||
heading_starred: false,
|
||
heading_number: None,
|
||
heading_short: None,
|
||
footnotes: Vec::new(),
|
||
theorem: None,
|
||
font_size: None,
|
||
float: Some(FloatSpec {
|
||
kind,
|
||
placement,
|
||
width,
|
||
height,
|
||
scale,
|
||
keep_aspectratio,
|
||
caption,
|
||
caption_short,
|
||
list_caption: None,
|
||
caption_starred,
|
||
image,
|
||
table,
|
||
}),
|
||
})
|
||
}
|
||
|
||
/// Find the index of a captured `tabular` placeholder inside a table float.
|
||
fn embedded_table(inner: &str) -> Option<usize> {
|
||
let index = inner.find("\\texrratable{")?;
|
||
let after = &inner[index + "\\texrratable{".len()..];
|
||
let end = after.find('}')?;
|
||
after[..end].trim().parse().ok()
|
||
}
|
||
|
||
fn figure_placement(spec: &str) -> FloatPlacement {
|
||
if spec.chars().any(|option| matches!(option, 'h' | 'H')) {
|
||
return FloatPlacement::Here;
|
||
}
|
||
if spec.contains('t') {
|
||
return FloatPlacement::Top;
|
||
}
|
||
if spec.contains('b') {
|
||
return FloatPlacement::Bottom;
|
||
}
|
||
FloatPlacement::Top
|
||
}
|
||
|
||
fn figure_caption(inner: &str) -> Option<(String, bool, Option<String>)> {
|
||
let index = inner.find("\\caption")?;
|
||
let after = inner[index + "\\caption".len()..].trim_start();
|
||
let (after, starred) = match after.strip_prefix('*') {
|
||
Some(rest) => (rest.trim_start(), true),
|
||
None => (after, false),
|
||
};
|
||
let (after, short) = match after.strip_prefix('[') {
|
||
Some(short) => match short.find(']') {
|
||
Some(end) => (
|
||
short[end + 1..].trim_start(),
|
||
Some(short[..end].trim().to_string()),
|
||
),
|
||
None => (after, None),
|
||
},
|
||
None => (after, None),
|
||
};
|
||
let (body, _) = braced_group(after)?;
|
||
Some((body.trim().to_string(), starred, short))
|
||
}
|
||
|
||
fn figure_labels(inner: &str) -> Vec<String> {
|
||
let mut labels = Vec::new();
|
||
let mut rest = inner;
|
||
while let Some(index) = rest.find("\\label") {
|
||
let after = rest[index + "\\label".len()..].trim_start();
|
||
let Some((label, consumed)) = braced_group(after) else {
|
||
break;
|
||
};
|
||
labels.push(label.trim().to_string());
|
||
rest = &after[consumed..];
|
||
}
|
||
labels
|
||
}
|
||
|
||
/// Read the path and placeholder dimensions from an `\includegraphics`.
|
||
fn figure_graphic(
|
||
inner: &str,
|
||
) -> Option<(
|
||
Option<ImageLength>,
|
||
Option<ImageLength>,
|
||
Option<String>,
|
||
Option<i64>,
|
||
bool,
|
||
)> {
|
||
let index = inner.find("\\includegraphics")?;
|
||
let after = inner[index + "\\includegraphics".len()..].trim_start();
|
||
let (options, after) = match after.strip_prefix('[') {
|
||
Some(rest) => {
|
||
let end = rest.find(']')?;
|
||
(&rest[..end], rest[end + 1..].trim_start())
|
||
}
|
||
None => ("", after),
|
||
};
|
||
let (path, _) = braced_group(after)?;
|
||
let mut width = None;
|
||
let mut height = None;
|
||
let mut scale = None;
|
||
let mut keep_aspectratio = false;
|
||
for part in options.split(',') {
|
||
let part = part.trim();
|
||
if let Some(value) = part.strip_prefix("width=") {
|
||
width = parse_image_length(value.trim());
|
||
} else if let Some(value) = part.strip_prefix("height=") {
|
||
height = parse_image_length(value.trim());
|
||
} else if let Some(value) = part.strip_prefix("scale=") {
|
||
scale = value
|
||
.trim()
|
||
.parse::<f64>()
|
||
.ok()
|
||
.map(|factor| (factor * 100.0).round().max(1.0) as i64);
|
||
} else if part == "keepaspectratio" {
|
||
keep_aspectratio = true;
|
||
}
|
||
}
|
||
let path = path.trim();
|
||
Some((
|
||
width,
|
||
height,
|
||
(!path.is_empty()).then(|| path.to_string()),
|
||
scale,
|
||
keep_aspectratio,
|
||
))
|
||
}
|
||
|
||
/// Parse `width=`/`height=` values: dimensions, fractions of the measure, or
|
||
/// fractions of the text height.
|
||
fn parse_image_length(value: &str) -> Option<ImageLength> {
|
||
if let Some(dimension) = parse_dimension(value) {
|
||
return Some(ImageLength::Absolute(dimension));
|
||
}
|
||
for (suffix, height) in [
|
||
("\\textwidth", false),
|
||
("\\linewidth", false),
|
||
("\\hsize", false),
|
||
("\\textheight", true),
|
||
("\\vsize", true),
|
||
] {
|
||
if let Some(factor) = value.strip_suffix(suffix) {
|
||
let factor = factor.trim().parse::<f64>().ok()?;
|
||
let percent = (factor * 100.0).round() as i64;
|
||
return Some(if height {
|
||
ImageLength::TextHeightPercent(percent)
|
||
} else {
|
||
ImageLength::TextWidthPercent(percent)
|
||
});
|
||
}
|
||
}
|
||
None
|
||
}
|
||
|
||
/// Directories declared by `\graphicspath{{figures/}{plots/}}`.
|
||
pub fn graphics_paths(source: &str) -> Vec<String> {
|
||
let mut paths = Vec::new();
|
||
for line in source.lines() {
|
||
let trimmed = line.trim();
|
||
if trimmed.starts_with("\\graphicspath") {
|
||
paths.extend(graphics_path_groups(trimmed));
|
||
}
|
||
}
|
||
paths
|
||
}
|
||
|
||
fn graphics_path_groups(line: &str) -> Vec<String> {
|
||
let Some((argument, _)) = braced_group(line.trim_start_matches("\\graphicspath").trim_start())
|
||
else {
|
||
return Vec::new();
|
||
};
|
||
let mut groups = Vec::new();
|
||
let mut rest = argument;
|
||
loop {
|
||
rest = rest.trim_start();
|
||
if rest.is_empty() {
|
||
break;
|
||
}
|
||
let Some((path, consumed)) = braced_group(rest) else {
|
||
break;
|
||
};
|
||
let path = path.trim();
|
||
if path.is_empty() {
|
||
break;
|
||
}
|
||
let mut path = path.to_string();
|
||
if !path.ends_with('/') {
|
||
path.push('/');
|
||
}
|
||
groups.push(path);
|
||
rest = &rest[consumed..];
|
||
}
|
||
groups
|
||
}
|
||
|
||
/// Every distinct `\includegraphics` path in a source file.
|
||
pub fn image_paths(source: &str) -> Vec<String> {
|
||
let mut paths: Vec<String> = Vec::new();
|
||
let mut rest = source;
|
||
while let Some(index) = rest.find("\\includegraphics") {
|
||
let after = rest[index + "\\includegraphics".len()..].trim_start();
|
||
let after = match after.strip_prefix('[') {
|
||
Some(options) => match options.find(']') {
|
||
Some(end) => options[end + 1..].trim_start(),
|
||
None => break,
|
||
},
|
||
None => after,
|
||
};
|
||
let Some((path, consumed)) = braced_group(after) else {
|
||
break;
|
||
};
|
||
let path = path.trim();
|
||
if !path.is_empty() && !paths.iter().any(|existing| existing == path) {
|
||
paths.push(path.to_string());
|
||
}
|
||
rest = &after[consumed..];
|
||
}
|
||
paths
|
||
}
|
||
|
||
const THEOREM_ENVIRONMENTS: [&str; 8] = [
|
||
"theorem",
|
||
"lemma",
|
||
"corollary",
|
||
"proposition",
|
||
"definition",
|
||
"example",
|
||
"remark",
|
||
"proof",
|
||
];
|
||
|
||
fn environment_label(name: &str) -> String {
|
||
let mut characters = name.chars();
|
||
match characters.next() {
|
||
Some(first) => first.to_uppercase().collect::<String>() + characters.as_str(),
|
||
None => String::new(),
|
||
}
|
||
}
|
||
|
||
/// A `theorem`-like environment: a bold heading plus an indented statement.
|
||
fn theorem_block(raw: &str, definitions: &[TheoremDefinition]) -> Option<Vec<SourceParagraph>> {
|
||
let trimmed = raw.trim();
|
||
let definition = definitions.iter().find(|definition| {
|
||
trimmed.starts_with(&format!("\\begin{{{}}}", definition.name))
|
||
|| trimmed.starts_with(&format!("\\begin{{{}*}}", definition.name))
|
||
});
|
||
let (name, display, starred_definition) = match definition {
|
||
Some(definition) => (
|
||
definition.name.clone(),
|
||
definition.display.clone(),
|
||
definition.starred,
|
||
),
|
||
None => {
|
||
let (name, starred) = THEOREM_ENVIRONMENTS.iter().find_map(|name| {
|
||
if trimmed.starts_with(&format!("\\begin{{{name}}}")) {
|
||
Some((*name, false))
|
||
} else if trimmed.starts_with(&format!("\\begin{{{name}*}}")) {
|
||
Some((*name, true))
|
||
} else {
|
||
None
|
||
}
|
||
})?;
|
||
(name.to_string(), environment_label(name), starred)
|
||
}
|
||
};
|
||
let (begin, end, starred_marker) = if trimmed.starts_with(&format!("\\begin{{{name}*}}")) {
|
||
(
|
||
format!("\\begin{{{name}*}}"),
|
||
format!("\\end{{{name}*}}"),
|
||
true,
|
||
)
|
||
} else {
|
||
(
|
||
format!("\\begin{{{name}}}"),
|
||
format!("\\end{{{name}}}"),
|
||
false,
|
||
)
|
||
};
|
||
let starred = starred_definition || starred_marker;
|
||
let body = trimmed.strip_prefix(&begin)?.strip_suffix(&end)?.trim();
|
||
let (title, body) = match body.strip_prefix('[') {
|
||
Some(rest) => {
|
||
let close = rest.find(']')?;
|
||
(
|
||
Some(rest[..close].trim().to_string()),
|
||
rest[close + 1..].trim(),
|
||
)
|
||
}
|
||
None => (None, body),
|
||
};
|
||
let mut body = body.to_string();
|
||
let labels = take_labels(&mut body);
|
||
body = body.trim().to_string();
|
||
if body.is_empty() {
|
||
return None;
|
||
}
|
||
let heading_text = match (name.as_str(), title.as_deref()) {
|
||
("proof", Some(title)) => format!("{title}."),
|
||
_ => format!("{display}."),
|
||
};
|
||
let theorem_title = if name == "proof" { None } else { title.clone() };
|
||
let heading = SourceParagraph {
|
||
width: None,
|
||
multline: false,
|
||
list_depth: None,
|
||
list_label: 0,
|
||
right_skip: 0,
|
||
text: heading_text,
|
||
font: ParagraphFont::Bold,
|
||
line_height: 14,
|
||
math: false,
|
||
left_skip: 0,
|
||
centered: false,
|
||
right_aligned: false,
|
||
space_before: 12 * SCALE,
|
||
space_stretch: 2 * SCALE,
|
||
space_shrink: 0,
|
||
page_break: false,
|
||
equation_number: None,
|
||
equation_tag: None,
|
||
equation_rows: Vec::new(),
|
||
align_centered: false,
|
||
heading_level: None,
|
||
heading_starred: false,
|
||
heading_number: None,
|
||
heading_short: None,
|
||
footnotes: Vec::new(),
|
||
theorem: Some(TheoremSpec {
|
||
name: name.clone(),
|
||
display,
|
||
title: theorem_title,
|
||
starred,
|
||
number: None,
|
||
labels,
|
||
}),
|
||
font_size: None,
|
||
float: None,
|
||
};
|
||
let italic = matches!(
|
||
name.as_str(),
|
||
"theorem" | "lemma" | "corollary" | "proposition" | "proof"
|
||
);
|
||
let statement = SourceParagraph {
|
||
width: None,
|
||
multline: false,
|
||
list_depth: None,
|
||
list_label: 0,
|
||
right_skip: 0,
|
||
text: body,
|
||
font: if italic {
|
||
ParagraphFont::Italic
|
||
} else {
|
||
ParagraphFont::Roman
|
||
},
|
||
line_height: 12,
|
||
math: false,
|
||
left_skip: 0,
|
||
centered: false,
|
||
right_aligned: false,
|
||
space_before: 4 * SCALE,
|
||
space_stretch: 0,
|
||
space_shrink: 0,
|
||
page_break: false,
|
||
equation_number: None,
|
||
equation_tag: None,
|
||
equation_rows: Vec::new(),
|
||
align_centered: false,
|
||
heading_level: None,
|
||
heading_starred: false,
|
||
heading_number: None,
|
||
heading_short: None,
|
||
footnotes: Vec::new(),
|
||
theorem: None,
|
||
font_size: None,
|
||
float: None,
|
||
};
|
||
Some(vec![heading, statement])
|
||
}
|
||
|
||
/// Recognise a list environment chunk and return its kind and body.
|
||
fn list_environment(raw: &str) -> Option<(&'static str, &str)> {
|
||
for environment in ["itemize", "enumerate", "description"] {
|
||
let begin = format!("\\begin{{{environment}}}");
|
||
let end = format!("\\end{{{environment}}}");
|
||
if let Some(body) = raw
|
||
.trim()
|
||
.strip_prefix(&begin)
|
||
.and_then(|text| text.strip_suffix(&end))
|
||
{
|
||
return Some((environment, body));
|
||
}
|
||
}
|
||
None
|
||
}
|
||
|
||
/// Split a list body at top-level `\\item` commands, keeping nested lists
|
||
/// inside the item that contains them.
|
||
fn split_list_items(body: &str) -> Vec<&str> {
|
||
let bytes = body.as_bytes();
|
||
let mut items = Vec::new();
|
||
let mut start = None;
|
||
let mut environment_depth = 0_usize;
|
||
let mut brace_depth = 0_usize;
|
||
let mut index = 0;
|
||
while index < bytes.len() {
|
||
match bytes[index] {
|
||
b'{' => {
|
||
brace_depth += 1;
|
||
index += 1;
|
||
continue;
|
||
}
|
||
b'}' => {
|
||
brace_depth = brace_depth.saturating_sub(1);
|
||
index += 1;
|
||
continue;
|
||
}
|
||
b'\\' => {
|
||
let rest = &body[index..];
|
||
if rest.starts_with("\\begin{") {
|
||
environment_depth += 1;
|
||
index += "\\begin{".len();
|
||
continue;
|
||
}
|
||
if rest.starts_with("\\end{") {
|
||
environment_depth = environment_depth.saturating_sub(1);
|
||
index += "\\end{".len();
|
||
continue;
|
||
}
|
||
if environment_depth == 0 && brace_depth == 0 && rest.starts_with("\\item") {
|
||
let after = index + "\\item".len();
|
||
let boundary = rest["\\item".len()..]
|
||
.chars()
|
||
.next()
|
||
.is_none_or(|character| !character.is_ascii_alphabetic());
|
||
if boundary {
|
||
if let Some(previous) = start {
|
||
items.push(&body[previous..index]);
|
||
}
|
||
start = Some(after);
|
||
index = after;
|
||
continue;
|
||
}
|
||
}
|
||
}
|
||
_ => {}
|
||
}
|
||
index += 1;
|
||
}
|
||
if let Some(previous) = start {
|
||
items.push(&body[previous..]);
|
||
}
|
||
items
|
||
}
|
||
|
||
/// Split item text into the part before a nested list, the nested list itself
|
||
/// and the continuation after it.
|
||
fn split_nested_list(text: &str) -> (String, Option<String>, String) {
|
||
let candidates = [
|
||
"\\begin{itemize}",
|
||
"\\begin{enumerate}",
|
||
"\\begin{description}",
|
||
];
|
||
let Some((start, environment)) = candidates
|
||
.iter()
|
||
.filter_map(|begin| {
|
||
let environment = begin.trim_start_matches("\\begin{").trim_end_matches('}');
|
||
text.find(begin).map(|index| (index, environment))
|
||
})
|
||
.min_by_key(|(index, _)| *index)
|
||
else {
|
||
return (text.to_string(), None, String::new());
|
||
};
|
||
let begin = format!("\\begin{{{environment}}}");
|
||
let end = format!("\\end{{{environment}}}");
|
||
let after_begin = start + begin.len();
|
||
let mut depth = 1_usize;
|
||
let mut cursor = after_begin;
|
||
while depth > 0 {
|
||
let next_begin = text[cursor..].find(&begin).map(|offset| cursor + offset);
|
||
let next_end = text[cursor..].find(&end).map(|offset| cursor + offset);
|
||
match (next_begin, next_end) {
|
||
(Some(begin_index), Some(end_index)) if begin_index < end_index => {
|
||
depth += 1;
|
||
cursor = begin_index + begin.len();
|
||
}
|
||
(_, Some(end_index)) => {
|
||
depth -= 1;
|
||
cursor = end_index + end.len();
|
||
}
|
||
(_, None) => return (text.to_string(), None, String::new()),
|
||
}
|
||
}
|
||
(
|
||
text[..start].to_string(),
|
||
Some(text[start..cursor].to_string()),
|
||
text[cursor..].to_string(),
|
||
)
|
||
}
|
||
|
||
fn alphabetic_label(mut number: u32, upper: bool) -> String {
|
||
let mut label = String::new();
|
||
while number > 0 {
|
||
let digit = ((number - 1) % 26) as u8;
|
||
label.insert(0, (b'a' + digit) as char);
|
||
number = (number - 1) / 26;
|
||
}
|
||
if upper {
|
||
label.to_ascii_uppercase()
|
||
} else {
|
||
label
|
||
}
|
||
}
|
||
|
||
fn roman_label(number: u32) -> String {
|
||
const VALUES: [(u32, &str); 13] = [
|
||
(1000, "m"),
|
||
(900, "cm"),
|
||
(500, "d"),
|
||
(400, "cd"),
|
||
(100, "c"),
|
||
(90, "xc"),
|
||
(50, "l"),
|
||
(40, "xl"),
|
||
(10, "x"),
|
||
(9, "ix"),
|
||
(5, "v"),
|
||
(4, "iv"),
|
||
(1, "i"),
|
||
];
|
||
let mut value = number;
|
||
let mut label = String::new();
|
||
for (amount, glyph) in VALUES {
|
||
while value >= amount {
|
||
label.push_str(glyph);
|
||
value -= amount;
|
||
}
|
||
}
|
||
if label.is_empty() {
|
||
number.to_string()
|
||
} else {
|
||
label
|
||
}
|
||
}
|
||
|
||
fn enumerate_label(number: u32, depth: usize) -> String {
|
||
match depth % 4 {
|
||
1 => format!("({}) ", alphabetic_label(number, false)),
|
||
2 => format!("{}. ", roman_label(number)),
|
||
3 => format!("{}. ", alphabetic_label(number, true)),
|
||
_ => format!("{number}. "),
|
||
}
|
||
}
|
||
|
||
fn bullet_label(depth: usize) -> &'static str {
|
||
match depth % 3 {
|
||
1 => "– ",
|
||
2 => "* ",
|
||
_ => "• ",
|
||
}
|
||
}
|
||
|
||
/// Vertical glue around list items, in points as [width, stretch, shrink].
|
||
///
|
||
/// The four entries follow TeX's `\@listi` through `\@listiv` values from the
|
||
/// article size files: `(topsep, itemsep, partopsep)` for each nesting depth.
|
||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||
struct ListSpacing {
|
||
levels: [((i64, i64, i64), (i64, i64, i64), (i64, i64, i64)); 4],
|
||
}
|
||
|
||
impl ListSpacing {
|
||
fn article(geometry: &PageGeometry) -> Self {
|
||
let base = geometry.base_font_size.unwrap_or(10 * SCALE);
|
||
let mut levels = match base / SCALE {
|
||
12 => [
|
||
((10, 4, 6), (5, 2, 1), (3, 2, 2)),
|
||
((5, 2, 1), (2, 2, 1), (3, 2, 2)),
|
||
((2, 1, 1), (2, 1, 1), (1, 0, 1)),
|
||
((2, 1, 1), (2, 1, 1), (1, 0, 1)),
|
||
],
|
||
11 => [
|
||
((9, 3, 5), (5, 2, 1), (3, 1, 1)),
|
||
((5, 2, 1), (2, 1, 1), (3, 1, 1)),
|
||
((2, 1, 1), (2, 1, 1), (1, 0, 1)),
|
||
((2, 1, 1), (2, 1, 1), (1, 0, 1)),
|
||
],
|
||
_ => [
|
||
((8, 2, 4), (4, 2, 1), (2, 1, 1)),
|
||
((4, 2, 1), (2, 1, 1), (2, 1, 1)),
|
||
((2, 1, 1), (2, 1, 1), (1, 0, 1)),
|
||
((2, 1, 1), (2, 1, 1), (1, 0, 1)),
|
||
],
|
||
};
|
||
let points = |value: (i64, i64, i64)| (value.0 / SCALE, value.1 / SCALE, value.2 / SCALE);
|
||
if let Some(top) = geometry.top_sep {
|
||
for level in &mut levels {
|
||
level.0 = points(top);
|
||
}
|
||
}
|
||
if let Some(item) = geometry.item_sep {
|
||
for level in &mut levels {
|
||
level.1 = points(item);
|
||
}
|
||
}
|
||
if let Some(partop) = geometry.part_op_sep {
|
||
for level in &mut levels {
|
||
level.2 = points(partop);
|
||
}
|
||
}
|
||
Self { levels }
|
||
}
|
||
|
||
fn first(&self, depth: usize) -> Option<(i64, i64, i64)> {
|
||
let (top, partop) = {
|
||
let (top, _, partop) = self.levels[depth.min(3)];
|
||
(top, partop)
|
||
};
|
||
Some((top.0 + partop.0, top.1 + partop.1, top.2 + partop.2))
|
||
}
|
||
|
||
fn item(&self, depth: usize) -> Option<(i64, i64, i64)> {
|
||
Some(self.levels[depth.min(3)].1)
|
||
}
|
||
}
|
||
|
||
fn list_label_width(label: &str) -> i64 {
|
||
let metrics = Cmr10Metrics::Roman;
|
||
let total: i64 = label
|
||
.chars()
|
||
.map(|character| match character {
|
||
' ' => metrics.space(),
|
||
_ => metrics.width(character),
|
||
})
|
||
.sum();
|
||
((total + SCALE - 1) / SCALE).max(1)
|
||
}
|
||
|
||
fn list_paragraph(
|
||
text: String,
|
||
depth: usize,
|
||
space: Option<(i64, i64, i64)>,
|
||
label_width: i64,
|
||
) -> SourceParagraph {
|
||
let (before, stretch, shrink) = space.unwrap_or((0, 0, 0));
|
||
SourceParagraph {
|
||
width: None,
|
||
multline: false,
|
||
text,
|
||
font: ParagraphFont::Roman,
|
||
line_height: 12,
|
||
math: false,
|
||
left_skip: 12 * (depth as i64 + 1),
|
||
centered: false,
|
||
right_aligned: false,
|
||
space_before: before,
|
||
space_stretch: stretch,
|
||
space_shrink: shrink,
|
||
page_break: false,
|
||
equation_number: None,
|
||
equation_tag: None,
|
||
equation_rows: Vec::new(),
|
||
align_centered: false,
|
||
heading_level: None,
|
||
heading_starred: false,
|
||
heading_number: None,
|
||
heading_short: None,
|
||
footnotes: Vec::new(),
|
||
theorem: None,
|
||
float: None,
|
||
font_size: None,
|
||
list_depth: Some(depth as u8),
|
||
list_label: label_width,
|
||
right_skip: 0,
|
||
}
|
||
}
|
||
|
||
/// Lay out a list environment, recursing into lists nested in its items.
|
||
fn verbatim_blocks(raw: &str) -> Option<Vec<SourceParagraph>> {
|
||
let trimmed = raw.trim();
|
||
let inner = trimmed
|
||
.strip_prefix("\\begin{verbatim}")?
|
||
.strip_suffix("\\end{verbatim}")?;
|
||
let inner = inner.strip_prefix('\n').unwrap_or(inner);
|
||
let mut blocks = Vec::new();
|
||
for (index, line) in inner.lines().enumerate() {
|
||
let text = line.trim_end();
|
||
blocks.push(SourceParagraph {
|
||
width: None,
|
||
multline: false,
|
||
list_depth: None,
|
||
list_label: 0,
|
||
right_skip: 0,
|
||
text: text.to_string(),
|
||
page_break: false,
|
||
centered: false,
|
||
right_aligned: false,
|
||
font: ParagraphFont::Mono,
|
||
line_height: 10,
|
||
math: false,
|
||
left_skip: 12,
|
||
space_before: if index == 0 { 6 * SCALE } else { 0 },
|
||
space_stretch: 0,
|
||
space_shrink: 0,
|
||
equation_number: None,
|
||
equation_tag: None,
|
||
equation_rows: Vec::new(),
|
||
align_centered: false,
|
||
heading_level: None,
|
||
heading_starred: false,
|
||
heading_number: None,
|
||
heading_short: None,
|
||
font_size: None,
|
||
footnotes: Vec::new(),
|
||
float: None,
|
||
theorem: None,
|
||
});
|
||
}
|
||
Some(blocks)
|
||
}
|
||
|
||
fn list_blocks(
|
||
raw: &str,
|
||
depth: usize,
|
||
_definitions: &[TheoremDefinition],
|
||
spacing: ListSpacing,
|
||
) -> Option<Vec<SourceParagraph>> {
|
||
let (environment, body) = list_environment(raw)?;
|
||
let mut blocks = Vec::new();
|
||
let mut placed = false;
|
||
let mut number = 0_u32;
|
||
if environment == "enumerate" {
|
||
let counters = ["enumi", "enumii", "enumiii", "enumiv"];
|
||
let counter = counters[depth.min(counters.len() - 1)];
|
||
let marker = format!("\\setcounter{{{counter}}}{{");
|
||
if let Some(position) = body.find(&marker)
|
||
&& position < body.find("\\item").unwrap_or(usize::MAX)
|
||
{
|
||
let after = &body[position + marker.len()..];
|
||
if let Some((value, _)) = after.split_once('}')
|
||
&& let Ok(start) = value.trim().parse::<u32>()
|
||
{
|
||
number = start;
|
||
}
|
||
}
|
||
}
|
||
for item in split_list_items(body) {
|
||
let item = item.trim();
|
||
if item.is_empty() {
|
||
continue;
|
||
}
|
||
let (custom_label, item) = if environment == "description" {
|
||
(None, item)
|
||
} else {
|
||
match item.strip_prefix('[').and_then(|text| text.split_once(']')) {
|
||
Some((label, rest)) => (Some(label.trim().to_string()), rest.trim_start()),
|
||
None => (None, item),
|
||
}
|
||
};
|
||
let (label, rest) = match environment {
|
||
"description" => {
|
||
let (term, rest) = item
|
||
.strip_prefix('[')
|
||
.and_then(|text| text.split_once(']'))
|
||
.map(|(term, rest)| (term.trim(), rest.trim()))
|
||
.unwrap_or(("", item));
|
||
if term.is_empty() {
|
||
(String::new(), rest)
|
||
} else {
|
||
(format!("\\textbf{{{term}}} — "), rest)
|
||
}
|
||
}
|
||
"enumerate" => {
|
||
number += 1;
|
||
let label = custom_label
|
||
.as_deref()
|
||
.filter(|label| !label.is_empty())
|
||
.map(|label| format!("{label} "))
|
||
.unwrap_or_else(|| enumerate_label(number, depth));
|
||
(label, item)
|
||
}
|
||
_ => {
|
||
let label = custom_label
|
||
.as_deref()
|
||
.filter(|label| !label.is_empty())
|
||
.map(|label| format!("{label} "))
|
||
.unwrap_or_else(|| bullet_label(depth).to_string());
|
||
(label, item)
|
||
}
|
||
};
|
||
let (before, nested, after) = split_nested_list(rest);
|
||
if !before.trim().is_empty() {
|
||
let space = if placed {
|
||
spacing.item(depth)
|
||
} else {
|
||
spacing.first(depth)
|
||
};
|
||
placed = true;
|
||
blocks.push(list_paragraph(
|
||
format!("{label}{}", before.trim()),
|
||
depth,
|
||
space,
|
||
list_label_width(&label),
|
||
));
|
||
}
|
||
if let Some(nested) = nested {
|
||
if let Some(nested_blocks) = list_blocks(&nested, depth + 1, _definitions, spacing) {
|
||
blocks.extend(nested_blocks);
|
||
}
|
||
}
|
||
if !after.trim().is_empty() {
|
||
blocks.push(list_paragraph(
|
||
after.trim().to_string(),
|
||
depth,
|
||
None,
|
||
list_label_width(&label),
|
||
));
|
||
}
|
||
}
|
||
if blocks.is_empty() {
|
||
None
|
||
} else {
|
||
Some(blocks)
|
||
}
|
||
}
|
||
|
||
fn standalone_graphic(raw: &str) -> Option<SourceParagraph> {
|
||
let trimmed = raw.trim();
|
||
let rest = trimmed.strip_prefix("\\includegraphics")?;
|
||
let mut rest = rest.trim_start();
|
||
if let Some(options) = rest.strip_prefix('[') {
|
||
let close = options.find(']')?;
|
||
rest = options[close + 1..].trim_start();
|
||
}
|
||
let (_path, consumed) = braced_group(rest)?;
|
||
if !rest[consumed..].trim().is_empty() {
|
||
return None;
|
||
}
|
||
let (width, height, image, scale, keep_aspectratio) = figure_graphic(trimmed)?;
|
||
Some(SourceParagraph {
|
||
width: None,
|
||
multline: false,
|
||
list_depth: None,
|
||
list_label: 0,
|
||
right_skip: 0,
|
||
text: String::new(),
|
||
font: ParagraphFont::Roman,
|
||
line_height: 12,
|
||
math: false,
|
||
left_skip: 0,
|
||
centered: false,
|
||
right_aligned: false,
|
||
space_before: 8 * SCALE,
|
||
space_stretch: 2 * SCALE,
|
||
space_shrink: 0,
|
||
page_break: false,
|
||
equation_number: None,
|
||
equation_tag: None,
|
||
equation_rows: Vec::new(),
|
||
align_centered: false,
|
||
heading_level: None,
|
||
heading_starred: false,
|
||
heading_number: None,
|
||
heading_short: None,
|
||
footnotes: Vec::new(),
|
||
theorem: None,
|
||
font_size: None,
|
||
float: Some(FloatSpec {
|
||
kind: FloatKind::Figure,
|
||
placement: FloatPlacement::Here,
|
||
width,
|
||
height,
|
||
scale,
|
||
keep_aspectratio,
|
||
caption: None,
|
||
caption_short: None,
|
||
list_caption: None,
|
||
caption_starred: false,
|
||
image,
|
||
table: None,
|
||
}),
|
||
})
|
||
}
|
||
|
||
fn verse_block(raw: &str) -> Option<Vec<SourceParagraph>> {
|
||
let body = raw
|
||
.trim()
|
||
.strip_prefix("\\begin{verse}")?
|
||
.strip_suffix("\\end{verse}")?;
|
||
let mut blocks = Vec::new();
|
||
for line in body.split("\\\\") {
|
||
let text = line.trim();
|
||
if text.is_empty() {
|
||
continue;
|
||
}
|
||
let mut block = parse_paragraph(text);
|
||
block.left_skip = 20;
|
||
blocks.push(block);
|
||
}
|
||
if blocks.is_empty() {
|
||
None
|
||
} else {
|
||
Some(blocks)
|
||
}
|
||
}
|
||
|
||
fn rule_block(raw: &str) -> Option<SourceParagraph> {
|
||
let rest = raw.trim().strip_prefix("\\rule")?;
|
||
let mut rest = rest.trim_start();
|
||
if rest.starts_with('[') {
|
||
let close = rest.find(']')?;
|
||
rest = rest[close + 1..].trim_start();
|
||
}
|
||
let (width, consumed) = braced_group(rest)?;
|
||
let width = parse_dimension(width.trim())?;
|
||
rest = rest[consumed..].trim_start();
|
||
let (height, consumed) = braced_group(rest)?;
|
||
let height = parse_dimension(height.trim())?;
|
||
if !rest[consumed..].trim().is_empty() {
|
||
return None;
|
||
}
|
||
let mut block = parse_paragraph("");
|
||
block.float = Some(FloatSpec {
|
||
kind: FloatKind::Figure,
|
||
placement: FloatPlacement::Here,
|
||
width: Some(ImageLength::Absolute(width)),
|
||
height: Some(ImageLength::Absolute(height)),
|
||
scale: None,
|
||
keep_aspectratio: false,
|
||
caption: None,
|
||
caption_short: None,
|
||
list_caption: None,
|
||
caption_starred: false,
|
||
image: None,
|
||
table: None,
|
||
});
|
||
block.space_before = 6 * SCALE;
|
||
block.space_stretch = 0;
|
||
block.space_shrink = 0;
|
||
Some(block)
|
||
}
|
||
|
||
fn minipage_blocks(
|
||
raw: &str,
|
||
definitions: &[TheoremDefinition],
|
||
spacing: ListSpacing,
|
||
) -> Option<Vec<SourceParagraph>> {
|
||
let body = raw
|
||
.trim()
|
||
.strip_prefix("\\begin{minipage}")?
|
||
.strip_suffix("\\end{minipage}")?;
|
||
let mut rest = body.trim_start();
|
||
if let Some(after) = rest.strip_prefix('[') {
|
||
let close = after.find(']')?;
|
||
rest = after[close + 1..].trim_start();
|
||
}
|
||
let (width, consumed) = braced_group(rest)?;
|
||
let width = parse_dimension(width.trim())?;
|
||
let content = rest[consumed..].trim();
|
||
if content.is_empty() {
|
||
return None;
|
||
}
|
||
let mut blocks = Vec::new();
|
||
for chunk in split_display_chunks(content) {
|
||
if chunk.trim().is_empty() {
|
||
continue;
|
||
}
|
||
let mut parsed = parse_blocks_raw(chunk, definitions, spacing);
|
||
for block in &mut parsed {
|
||
block.width = Some(width);
|
||
block.space_before = 0;
|
||
block.space_stretch = 0;
|
||
block.space_shrink = 0;
|
||
}
|
||
blocks.extend(parsed);
|
||
}
|
||
(!blocks.is_empty()).then_some(blocks)
|
||
}
|
||
|
||
fn parse_blocks_raw(
|
||
raw: &str,
|
||
definitions: &[TheoremDefinition],
|
||
spacing: ListSpacing,
|
||
) -> Vec<SourceParagraph> {
|
||
if let Some(block) = float_block(raw) {
|
||
return vec![block];
|
||
}
|
||
if let Some(block) = standalone_graphic(raw) {
|
||
return vec![block];
|
||
}
|
||
if let Some(block) = rule_block(raw) {
|
||
return vec![block];
|
||
}
|
||
if let Some(blocks) = minipage_blocks(raw, definitions, spacing) {
|
||
return blocks;
|
||
}
|
||
if let Some(blocks) = theorem_block(raw, definitions) {
|
||
return blocks;
|
||
}
|
||
if let Some(body) = raw
|
||
.trim()
|
||
.strip_prefix("\\begin{abstract}")
|
||
.and_then(|rest| rest.strip_suffix("\\end{abstract}"))
|
||
{
|
||
let heading = SourceParagraph {
|
||
width: None,
|
||
multline: false,
|
||
list_depth: None,
|
||
list_label: 0,
|
||
right_skip: 0,
|
||
text: "Abstract".to_string(),
|
||
font: ParagraphFont::Bold,
|
||
line_height: 12,
|
||
math: false,
|
||
left_skip: 0,
|
||
centered: true,
|
||
right_aligned: false,
|
||
space_before: 12 * SCALE,
|
||
space_stretch: 0,
|
||
space_shrink: 0,
|
||
page_break: false,
|
||
equation_number: None,
|
||
equation_tag: None,
|
||
equation_rows: Vec::new(),
|
||
align_centered: false,
|
||
heading_level: None,
|
||
heading_starred: false,
|
||
heading_number: None,
|
||
heading_short: None,
|
||
footnotes: Vec::new(),
|
||
theorem: None,
|
||
float: None,
|
||
font_size: Some((12.0 * SCALE as f64) as i64),
|
||
};
|
||
let body = SourceParagraph {
|
||
width: None,
|
||
multline: false,
|
||
list_depth: None,
|
||
list_label: 0,
|
||
right_skip: 0,
|
||
text: body.trim().to_string(),
|
||
font: ParagraphFont::Roman,
|
||
line_height: 12,
|
||
math: false,
|
||
left_skip: 0,
|
||
centered: false,
|
||
right_aligned: false,
|
||
space_before: 6 * SCALE,
|
||
space_stretch: 0,
|
||
space_shrink: 0,
|
||
page_break: false,
|
||
equation_number: None,
|
||
equation_tag: None,
|
||
equation_rows: Vec::new(),
|
||
align_centered: false,
|
||
heading_level: None,
|
||
heading_starred: false,
|
||
heading_number: None,
|
||
heading_short: None,
|
||
footnotes: Vec::new(),
|
||
theorem: None,
|
||
float: None,
|
||
font_size: Some((9.0 * SCALE as f64) as i64),
|
||
};
|
||
if body.text.is_empty() {
|
||
return vec![heading];
|
||
}
|
||
return vec![heading, body];
|
||
}
|
||
for (environment, centered, right_aligned) in [
|
||
("center", true, false),
|
||
("flushleft", false, false),
|
||
("flushright", false, true),
|
||
] {
|
||
let begin = format!("\\begin{{{environment}}}");
|
||
let finish = format!("\\end{{{environment}}}");
|
||
let Some(body) = raw
|
||
.strip_prefix(&begin)
|
||
.and_then(|text| text.strip_suffix(&finish))
|
||
else {
|
||
continue;
|
||
};
|
||
let body = body.trim();
|
||
if body.is_empty() {
|
||
continue;
|
||
}
|
||
let mut blocks = parse_blocks_raw(body, definitions, spacing);
|
||
for block in &mut blocks {
|
||
block.centered = centered;
|
||
block.right_aligned = right_aligned;
|
||
}
|
||
if !blocks.is_empty() {
|
||
return blocks;
|
||
}
|
||
continue;
|
||
}
|
||
if let Some(blocks) = verbatim_blocks(raw) {
|
||
return blocks;
|
||
}
|
||
if let Some(blocks) = list_blocks(raw, 0, definitions, spacing) {
|
||
return blocks;
|
||
}
|
||
if let Some(blocks) = verse_block(raw) {
|
||
return blocks;
|
||
}
|
||
if let Some(body) = raw
|
||
.strip_prefix("\\begin{quotation}")
|
||
.and_then(|text| text.strip_suffix("\\end{quotation}"))
|
||
{
|
||
let mut blocks = Vec::new();
|
||
for paragraph in body.trim().split("\n\n") {
|
||
let text = paragraph.trim();
|
||
if text.is_empty() {
|
||
continue;
|
||
}
|
||
let mut nested = parse_blocks_raw(text, definitions, spacing);
|
||
for block in &mut nested {
|
||
block.left_skip += 20;
|
||
block.right_skip += 20;
|
||
}
|
||
blocks.extend(nested);
|
||
}
|
||
if !blocks.is_empty() {
|
||
return blocks;
|
||
}
|
||
}
|
||
if let Some(body) = raw
|
||
.strip_prefix("\\begin{quote}")
|
||
.and_then(|text| text.strip_suffix("\\end{quote}"))
|
||
{
|
||
let text = body.trim();
|
||
if !text.is_empty() {
|
||
return vec![SourceParagraph {
|
||
width: None,
|
||
multline: false,
|
||
list_depth: None,
|
||
list_label: 0,
|
||
text: text.to_string(),
|
||
font: ParagraphFont::Roman,
|
||
line_height: 12,
|
||
math: false,
|
||
left_skip: 20,
|
||
right_skip: 20,
|
||
centered: false,
|
||
right_aligned: false,
|
||
space_before: 0,
|
||
space_stretch: 0,
|
||
space_shrink: 0,
|
||
page_break: false,
|
||
equation_number: None,
|
||
equation_tag: None,
|
||
equation_rows: Vec::new(),
|
||
align_centered: false,
|
||
heading_level: None,
|
||
heading_starred: false,
|
||
heading_number: None,
|
||
heading_short: None,
|
||
footnotes: Vec::new(),
|
||
theorem: None,
|
||
float: None,
|
||
font_size: None,
|
||
}];
|
||
}
|
||
}
|
||
vec![parse_paragraph(raw)]
|
||
}
|
||
|
||
/// Map a small, general LaTeX subset onto route-D paragraph faces. This is not
|
||
/// a full LaTeX reader; it exists so the live endpoint can show headings and
|
||
/// emphasis while the semantic layer is built out.
|
||
fn take_braced_argument(text: &mut String, command: &str) -> Option<String> {
|
||
let start = text.find(command)?;
|
||
let after = start + command.len();
|
||
if !text[after..].starts_with('{') {
|
||
return None;
|
||
}
|
||
let mut depth = 0_usize;
|
||
for (offset, character) in text[after..].char_indices() {
|
||
match character {
|
||
'{' => depth += 1,
|
||
'}' => {
|
||
depth -= 1;
|
||
if depth == 0 {
|
||
let inner = text[after + 1..after + offset].to_string();
|
||
text.replace_range(start..after + offset + 1, "");
|
||
return Some(inner);
|
||
}
|
||
}
|
||
_ => {}
|
||
}
|
||
}
|
||
None
|
||
}
|
||
|
||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||
enum Family {
|
||
Roman,
|
||
Sans,
|
||
Mono,
|
||
}
|
||
|
||
/// Paragraph-level NFSS declarations: family, series and shape prefixes such
|
||
/// as `{\sffamily\bfseries ...}` are folded into the built-in faces.
|
||
fn nfss_family_name(name: &str) -> Family {
|
||
let lower = name.to_ascii_lowercase();
|
||
if lower.starts_with("cmss") || lower.starts_with("lmss") || lower.starts_with("phv") {
|
||
Family::Sans
|
||
} else if lower.starts_with("cmtt") || lower.starts_with("lmtt") || lower.starts_with("pcr") {
|
||
Family::Mono
|
||
} else {
|
||
Family::Roman
|
||
}
|
||
}
|
||
|
||
fn nfss_braced<'a>(text: &'a str, command: &str) -> Option<(String, &'a str)> {
|
||
let rest = text.strip_prefix(command)?;
|
||
let rest = rest.trim_start().strip_prefix('{')?;
|
||
let end = rest.find('}')?;
|
||
Some((rest[..end].to_string(), rest[end + 1..].trim_start()))
|
||
}
|
||
|
||
fn nfss_declaration<'a>(text: &'a str, command: &str) -> Option<&'a str> {
|
||
let rest = text.strip_prefix(command)?;
|
||
if rest
|
||
.chars()
|
||
.next()
|
||
.is_some_and(|character| character.is_ascii_alphabetic())
|
||
{
|
||
return None;
|
||
}
|
||
Some(rest)
|
||
}
|
||
|
||
/// TeX size commands with the article-class 10pt point size values.
|
||
const SIZE_COMMANDS: [(&str, f64); 10] = [
|
||
("\\tiny", 5.0),
|
||
("\\scriptsize", 7.0),
|
||
("\\footnotesize", 8.0),
|
||
("\\small", 9.0),
|
||
("\\normalsize", 10.0),
|
||
("\\large", 12.0),
|
||
("\\Large", 14.4),
|
||
("\\LARGE", 17.28),
|
||
("\\huge", 20.74),
|
||
("\\Huge", 24.88),
|
||
];
|
||
|
||
/// Scan a size declaration such as `\large` or
|
||
/// `\fontsize{14pt}{18pt}\selectfont`, returning the size and the rest.
|
||
fn font_size_command(rest: &str) -> Option<(i64, &str)> {
|
||
for (command, points) in SIZE_COMMANDS {
|
||
if let Some(after) = nfss_declaration(rest, command) {
|
||
return Some(((points * 65_536.0).round() as i64, after));
|
||
}
|
||
}
|
||
let after = rest.strip_prefix("\\fontsize")?;
|
||
if after
|
||
.chars()
|
||
.next()
|
||
.is_some_and(|character| character.is_ascii_alphabetic())
|
||
{
|
||
return None;
|
||
}
|
||
let after = after.trim_start();
|
||
let (size_text, length) = braced_group(after)?;
|
||
let size = parse_dimension(size_text.trim())?;
|
||
let after = after[length..].trim_start();
|
||
let (_, length) = braced_group(after)?;
|
||
let mut after = after[length..].trim_start();
|
||
if let Some(rest) = after.strip_prefix("\\selectfont") {
|
||
after = rest;
|
||
}
|
||
Some((size, after))
|
||
}
|
||
|
||
fn nfss_font_with_size(
|
||
raw: &str,
|
||
base: ParagraphFont,
|
||
) -> Option<(ParagraphFont, Option<i64>, String)> {
|
||
let (mut family, mut bold, mut italic) = match base {
|
||
ParagraphFont::Roman => (Family::Roman, false, false),
|
||
ParagraphFont::Bold => (Family::Roman, true, false),
|
||
ParagraphFont::Italic => (Family::Roman, false, true),
|
||
ParagraphFont::BoldItalic => (Family::Roman, true, true),
|
||
ParagraphFont::Mono => (Family::Mono, false, false),
|
||
ParagraphFont::Sans => (Family::Sans, false, false),
|
||
ParagraphFont::SansBold => (Family::Sans, true, false),
|
||
ParagraphFont::SansItalic => (Family::Sans, false, true),
|
||
ParagraphFont::SmallCaps => (Family::Roman, false, false),
|
||
ParagraphFont::Slanted => (Family::Roman, false, false),
|
||
ParagraphFont::BoldSlanted => (Family::Roman, true, false),
|
||
ParagraphFont::MonoItalic => (Family::Mono, false, true),
|
||
};
|
||
let mut small_caps = base == ParagraphFont::SmallCaps;
|
||
let mut slanted = matches!(base, ParagraphFont::Slanted | ParagraphFont::BoldSlanted);
|
||
let mut font_size: Option<i64> = None;
|
||
let mut text = raw.trim_start();
|
||
let mut consumed = false;
|
||
loop {
|
||
if let Some((size, rest)) = font_size_command(text) {
|
||
font_size = Some(size);
|
||
text = rest;
|
||
} else if let Some((name, rest)) = nfss_braced(text, "\\fontfamily") {
|
||
family = nfss_family_name(&name);
|
||
text = rest;
|
||
} else if let Some((name, rest)) = nfss_braced(text, "\\fontseries") {
|
||
bold = name.contains('b')
|
||
|| name.contains("bx")
|
||
|| name.contains('s') && name.contains('b');
|
||
text = rest;
|
||
} else if let Some((name, rest)) = nfss_braced(text, "\\fontshape") {
|
||
italic = name == "it";
|
||
slanted = name == "sl";
|
||
small_caps = name == "sc";
|
||
text = rest;
|
||
} else if let Some(rest) = nfss_braced(text, "\\fontencoding").map(|(_, rest)| rest) {
|
||
text = rest;
|
||
} else if let Some(rest) = nfss_declaration(text, "\\normalfont") {
|
||
family = Family::Roman;
|
||
bold = false;
|
||
italic = false;
|
||
slanted = false;
|
||
small_caps = false;
|
||
text = rest;
|
||
} else if let Some(rest) = nfss_declaration(text, "\\em") {
|
||
if italic || slanted {
|
||
italic = false;
|
||
slanted = false;
|
||
} else {
|
||
italic = true;
|
||
slanted = false;
|
||
small_caps = false;
|
||
}
|
||
text = rest;
|
||
} else if let Some(rest) = nfss_declaration(text, "\\rm") {
|
||
family = Family::Roman;
|
||
text = rest;
|
||
} else if let Some(rest) = nfss_declaration(text, "\\sf") {
|
||
family = Family::Sans;
|
||
text = rest;
|
||
} else if let Some(rest) = nfss_declaration(text, "\\tt") {
|
||
family = Family::Mono;
|
||
text = rest;
|
||
} else if let Some(rest) = nfss_declaration(text, "\\bf") {
|
||
bold = true;
|
||
text = rest;
|
||
} else if let Some(rest) = nfss_declaration(text, "\\md") {
|
||
bold = false;
|
||
text = rest;
|
||
} else if let Some(rest) = nfss_declaration(text, "\\it") {
|
||
italic = true;
|
||
slanted = false;
|
||
small_caps = false;
|
||
text = rest;
|
||
} else if let Some(rest) = nfss_declaration(text, "\\sl") {
|
||
italic = false;
|
||
slanted = true;
|
||
small_caps = false;
|
||
text = rest;
|
||
} else if let Some(rest) = nfss_declaration(text, "\\up") {
|
||
italic = false;
|
||
slanted = false;
|
||
small_caps = false;
|
||
text = rest;
|
||
} else if let Some(rest) = nfss_declaration(text, "\\sc") {
|
||
small_caps = true;
|
||
italic = false;
|
||
slanted = false;
|
||
text = rest;
|
||
} else if let Some(rest) = nfss_declaration(text, "\\rmfamily") {
|
||
family = Family::Roman;
|
||
text = rest;
|
||
} else if let Some(rest) = nfss_declaration(text, "\\sffamily") {
|
||
family = Family::Sans;
|
||
text = rest;
|
||
} else if let Some(rest) = nfss_declaration(text, "\\ttfamily") {
|
||
family = Family::Mono;
|
||
text = rest;
|
||
} else if let Some(rest) = nfss_declaration(text, "\\bfseries") {
|
||
bold = true;
|
||
text = rest;
|
||
} else if let Some(rest) = nfss_declaration(text, "\\mdseries") {
|
||
bold = false;
|
||
text = rest;
|
||
} else if let Some(rest) = nfss_declaration(text, "\\itshape") {
|
||
italic = true;
|
||
slanted = false;
|
||
small_caps = false;
|
||
text = rest;
|
||
} else if let Some(rest) = nfss_declaration(text, "\\slshape") {
|
||
italic = false;
|
||
slanted = true;
|
||
small_caps = false;
|
||
text = rest;
|
||
} else if let Some(rest) = nfss_declaration(text, "\\upshape") {
|
||
italic = false;
|
||
slanted = false;
|
||
small_caps = false;
|
||
text = rest;
|
||
} else if let Some(rest) = nfss_declaration(text, "\\scshape") {
|
||
small_caps = true;
|
||
italic = false;
|
||
slanted = false;
|
||
text = rest;
|
||
} else if let Some(rest) = nfss_declaration(text, "\\selectfont") {
|
||
text = rest;
|
||
} else {
|
||
break;
|
||
}
|
||
consumed = true;
|
||
text = text.trim_start();
|
||
}
|
||
if !consumed {
|
||
return None;
|
||
}
|
||
let font = match family {
|
||
Family::Mono => {
|
||
if italic || slanted {
|
||
ParagraphFont::MonoItalic
|
||
} else {
|
||
ParagraphFont::Mono
|
||
}
|
||
}
|
||
Family::Sans => {
|
||
if bold {
|
||
ParagraphFont::SansBold
|
||
} else if italic || slanted {
|
||
ParagraphFont::SansItalic
|
||
} else {
|
||
ParagraphFont::Sans
|
||
}
|
||
}
|
||
Family::Roman => {
|
||
if italic {
|
||
if bold {
|
||
ParagraphFont::BoldItalic
|
||
} else {
|
||
ParagraphFont::Italic
|
||
}
|
||
} else if slanted {
|
||
if bold {
|
||
ParagraphFont::BoldSlanted
|
||
} else {
|
||
ParagraphFont::Slanted
|
||
}
|
||
} else if bold {
|
||
ParagraphFont::Bold
|
||
} else if small_caps {
|
||
ParagraphFont::SmallCaps
|
||
} else {
|
||
ParagraphFont::Roman
|
||
}
|
||
}
|
||
};
|
||
Some((font, font_size, text.to_string()))
|
||
}
|
||
|
||
/// Split a paragraph containing inline style commands into styled runs.
|
||
///
|
||
/// Handles `\textbf{...}`-style wrappers, declaration groups such as
|
||
/// `{\bfseries ...}` and arbitrary nesting of both, including braces inside a
|
||
/// group. Plain text inherits the surrounding face.
|
||
/// Find the closing delimiter of an inline formula.
|
||
fn math_end(text: &str, closing: &str) -> Option<usize> {
|
||
if closing == "$" {
|
||
let bytes = text.as_bytes();
|
||
let mut index = 0;
|
||
while index < bytes.len() {
|
||
match bytes[index] {
|
||
b'\\' => index += 2,
|
||
b'$' => return Some(index),
|
||
_ => index += 1,
|
||
}
|
||
}
|
||
None
|
||
} else {
|
||
text.find(closing)
|
||
}
|
||
}
|
||
|
||
/// Split text into literal pieces and `$...$` / `\(...\)` formulas.
|
||
fn split_inline_math(text: &str) -> Vec<(bool, String)> {
|
||
let mut pieces = Vec::new();
|
||
let mut literal = String::new();
|
||
let mut index = 0;
|
||
while index < text.len() {
|
||
let rest = &text[index..];
|
||
if rest.starts_with("$$") {
|
||
literal.push_str("$$");
|
||
index += 2;
|
||
continue;
|
||
}
|
||
let opener = if rest.starts_with("\\begin{math}") {
|
||
Some(("\\begin{math}".len(), "\\end{math}"))
|
||
} else if rest.starts_with("\\(") {
|
||
Some((2, "\\)"))
|
||
} else if rest.starts_with('$') {
|
||
Some((1, "$"))
|
||
} else {
|
||
None
|
||
};
|
||
if let Some((open_len, closing)) = opener {
|
||
let after = &rest[open_len..];
|
||
if let Some(end) = math_end(after, closing) {
|
||
if !literal.is_empty() {
|
||
pieces.push((false, std::mem::take(&mut literal)));
|
||
}
|
||
pieces.push((true, after[..end].to_string()));
|
||
index += open_len + end + closing.len();
|
||
continue;
|
||
}
|
||
}
|
||
let character = rest.chars().next().expect("non-empty tail");
|
||
if rest.starts_with('\\') {
|
||
literal.push(character);
|
||
if let Some(next) = rest[character.len_utf8()..].chars().next() {
|
||
literal.push(next);
|
||
index += character.len_utf8() + next.len_utf8();
|
||
continue;
|
||
}
|
||
}
|
||
literal.push(character);
|
||
index += character.len_utf8();
|
||
}
|
||
if !literal.is_empty() {
|
||
pieces.push((false, literal));
|
||
}
|
||
pieces
|
||
}
|
||
|
||
/// Build mixed text/math segments when the paragraph contains inline math.
|
||
///
|
||
/// Math metrics are measured at 10pt, so sized paragraphs keep the literal
|
||
/// delimiters until per-size math layout exists.
|
||
enum HrefPart {
|
||
Plain(String),
|
||
Link(String, String),
|
||
}
|
||
|
||
fn split_hrefs(text: &str) -> Vec<HrefPart> {
|
||
let mut parts = Vec::new();
|
||
let mut rest = text;
|
||
while let Some(position) = rest.find("\\href") {
|
||
if position > 0 {
|
||
parts.push(HrefPart::Plain(rest[..position].to_string()));
|
||
}
|
||
let after = &rest[position + "\\href".len()..];
|
||
let Some((url, used)) = braced_group(after) else {
|
||
parts.push(HrefPart::Plain(rest[position..].to_string()));
|
||
return parts;
|
||
};
|
||
let remainder = &after[used..];
|
||
let Some((label, used_label)) = braced_group(remainder) else {
|
||
parts.push(HrefPart::Plain(rest[position..].to_string()));
|
||
return parts;
|
||
};
|
||
parts.push(HrefPart::Link(url.trim().to_string(), label.to_string()));
|
||
rest = &remainder[used_label..];
|
||
}
|
||
if !rest.is_empty() {
|
||
parts.push(HrefPart::Plain(rest.to_string()));
|
||
}
|
||
parts
|
||
}
|
||
|
||
fn strip_hrefs(text: &str) -> String {
|
||
let mut output = String::new();
|
||
for part in split_hrefs(text) {
|
||
match part {
|
||
HrefPart::Plain(piece) | HrefPart::Link(_, piece) => output.push_str(&piece),
|
||
}
|
||
}
|
||
output
|
||
}
|
||
|
||
fn named_color(name: &str) -> Option<[u8; 3]> {
|
||
match name.trim().to_ascii_lowercase().as_str() {
|
||
"black" => Some([0, 0, 0]),
|
||
"white" => Some([255, 255, 255]),
|
||
"red" => Some([255, 0, 0]),
|
||
"green" => Some([0, 128, 0]),
|
||
"blue" => Some([0, 0, 255]),
|
||
"cyan" => Some([0, 255, 255]),
|
||
"magenta" => Some([255, 0, 255]),
|
||
"yellow" => Some([255, 255, 0]),
|
||
"gray" | "grey" => Some([128, 128, 128]),
|
||
"darkgray" | "darkgrey" => Some([64, 64, 64]),
|
||
"lightgray" | "lightgrey" => Some([192, 192, 192]),
|
||
"brown" => Some([165, 42, 42]),
|
||
"lime" => Some([0, 255, 0]),
|
||
"olive" => Some([128, 128, 0]),
|
||
"orange" => Some([255, 165, 0]),
|
||
"pink" => Some([255, 192, 203]),
|
||
"purple" => Some([128, 0, 128]),
|
||
"teal" => Some([0, 128, 128]),
|
||
"violet" => Some([238, 130, 238]),
|
||
_ => None,
|
||
}
|
||
}
|
||
|
||
/// Splits `\textcolor{name}{text}` runs out of a paragraph piece.
|
||
fn split_textcolor(text: &str) -> Vec<(Option<[u8; 3]>, String)> {
|
||
let mut out = Vec::new();
|
||
let mut rest = text;
|
||
let mut plain = String::new();
|
||
while let Some(index) = rest.find("\\textcolor") {
|
||
plain.push_str(&rest[..index]);
|
||
let after = rest[index + "\\textcolor".len()..].trim_start();
|
||
let Some(after) = after.strip_prefix('{') else {
|
||
plain.push_str(&rest[index..]);
|
||
rest = "";
|
||
break;
|
||
};
|
||
let Some(close) = after.find('}') else {
|
||
plain.push_str(&rest[index..]);
|
||
rest = "";
|
||
break;
|
||
};
|
||
let name = &after[..close];
|
||
let after_name = after[close + 1..].trim_start();
|
||
let Some(body) = after_name.strip_prefix('{') else {
|
||
plain.push_str(&rest[index..]);
|
||
rest = "";
|
||
break;
|
||
};
|
||
let mut depth = 1_usize;
|
||
let mut end = None;
|
||
for (offset, character) in body.char_indices() {
|
||
match character {
|
||
'{' => depth += 1,
|
||
'}' => {
|
||
depth -= 1;
|
||
if depth == 0 {
|
||
end = Some(offset);
|
||
break;
|
||
}
|
||
}
|
||
_ => {}
|
||
}
|
||
}
|
||
let Some(end) = end else {
|
||
plain.push_str(&rest[index..]);
|
||
rest = "";
|
||
break;
|
||
};
|
||
match named_color(name) {
|
||
Some(color) => {
|
||
if !plain.is_empty() {
|
||
out.push((None, std::mem::take(&mut plain)));
|
||
}
|
||
out.push((Some(color), body[..end].to_string()));
|
||
}
|
||
None => plain.push_str(&rest[index..index + 1]),
|
||
}
|
||
rest = &body[end + 1..];
|
||
}
|
||
plain.push_str(rest);
|
||
if !plain.is_empty() {
|
||
out.push((None, plain));
|
||
}
|
||
if out.is_empty() {
|
||
out.push((None, text.to_string()));
|
||
}
|
||
out
|
||
}
|
||
|
||
fn inline_math_segments(
|
||
text: &str,
|
||
base: ParagraphFont,
|
||
style: &ParagraphStyle,
|
||
) -> Option<Vec<texrra_tex_core::paragraph::InlineSegment>> {
|
||
if style.font_size != 655_360 {
|
||
return None;
|
||
}
|
||
let mut segments = Vec::new();
|
||
let mut found_math = false;
|
||
let mut found_link = false;
|
||
let mut found_size = false;
|
||
let mut found_color = false;
|
||
for part in split_hrefs(text) {
|
||
match part {
|
||
HrefPart::Plain(piece) => {
|
||
for (color, chunk) in split_textcolor(&piece) {
|
||
let runs = inline_styled_runs(&chunk, base)
|
||
.unwrap_or_else(|| vec![(base, style.font_size, 0, chunk.clone())]);
|
||
for (font, size, raise, run_text) in runs {
|
||
for (is_math, piece) in split_inline_math(&run_text) {
|
||
if is_math {
|
||
found_math = true;
|
||
segments.push(texrra_tex_core::paragraph::InlineSegment::Math(
|
||
parse_math(&piece),
|
||
));
|
||
} else if !piece.is_empty() {
|
||
if let Some(rgb) = color {
|
||
found_color = true;
|
||
segments.push(
|
||
texrra_tex_core::paragraph::InlineSegment::Color(
|
||
font, size, raise, rgb, piece,
|
||
),
|
||
);
|
||
} else if raise != 0 {
|
||
found_size = true;
|
||
segments.push(
|
||
texrra_tex_core::paragraph::InlineSegment::Script(
|
||
font, size, raise, piece,
|
||
),
|
||
);
|
||
} else if size == 655_360 {
|
||
segments.push(texrra_tex_core::paragraph::InlineSegment::Text(
|
||
font, piece,
|
||
));
|
||
} else {
|
||
found_size = true;
|
||
segments.push(
|
||
texrra_tex_core::paragraph::InlineSegment::SizedText(
|
||
font, size, piece,
|
||
),
|
||
);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
HrefPart::Link(url, label) => {
|
||
found_link = true;
|
||
let runs = inline_runs(&label, base).unwrap_or_else(|| vec![(base, label.clone())]);
|
||
for (font, text) in runs {
|
||
segments.push(texrra_tex_core::paragraph::InlineSegment::Link {
|
||
font,
|
||
url: url.clone(),
|
||
text,
|
||
});
|
||
}
|
||
}
|
||
}
|
||
}
|
||
(found_math || found_link || found_size || found_color).then_some(segments)
|
||
}
|
||
|
||
fn inline_runs(text: &str, base: ParagraphFont) -> Option<Vec<(ParagraphFont, String)>> {
|
||
Some(
|
||
inline_sized_runs(text, base)?
|
||
.into_iter()
|
||
.map(|(font, _, text)| (font, text))
|
||
.collect(),
|
||
)
|
||
}
|
||
|
||
fn inline_styled_runs(
|
||
text: &str,
|
||
base: ParagraphFont,
|
||
) -> Option<Vec<(ParagraphFont, i64, i64, String)>> {
|
||
let mut runs = Vec::new();
|
||
let mut found = false;
|
||
parse_runs(text, base, 655_360, 0, &mut runs, &mut found);
|
||
if !found {
|
||
return None;
|
||
}
|
||
Some(runs)
|
||
}
|
||
|
||
fn inline_sized_runs(text: &str, base: ParagraphFont) -> Option<Vec<(ParagraphFont, i64, String)>> {
|
||
Some(
|
||
inline_styled_runs(text, base)?
|
||
.into_iter()
|
||
.map(|(font, size, _, text)| (font, size, text))
|
||
.collect(),
|
||
)
|
||
}
|
||
|
||
fn push_run(
|
||
runs: &mut Vec<(ParagraphFont, i64, i64, String)>,
|
||
font: ParagraphFont,
|
||
size: i64,
|
||
raise: i64,
|
||
text: &str,
|
||
) {
|
||
if text.is_empty() {
|
||
return;
|
||
}
|
||
if let Some((last_font, last_size, last_raise, last_text)) = runs.last_mut()
|
||
&& *last_font == font
|
||
&& *last_size == size
|
||
&& *last_raise == raise
|
||
{
|
||
last_text.push_str(text);
|
||
return;
|
||
}
|
||
runs.push((font, size, raise, text.to_string()));
|
||
}
|
||
|
||
/// Match a balanced `{...}` at the start of `rest`, returning its contents and
|
||
/// the number of bytes consumed (including both braces).
|
||
fn braced_group(rest: &str) -> Option<(&str, usize)> {
|
||
if !rest.starts_with('{') {
|
||
return None;
|
||
}
|
||
let mut depth = 0usize;
|
||
for (offset, character) in rest.char_indices() {
|
||
match character {
|
||
'{' => depth += 1,
|
||
'}' => {
|
||
depth -= 1;
|
||
if depth == 0 {
|
||
return Some((&rest[1..offset], offset + 1));
|
||
}
|
||
}
|
||
_ => {}
|
||
}
|
||
}
|
||
None
|
||
}
|
||
|
||
const INLINE_COMMANDS: [&str; 11] = [
|
||
"\\textbf",
|
||
"\\emph",
|
||
"\\textit",
|
||
"\\textsl",
|
||
"\\texttt",
|
||
"\\textsf",
|
||
"\\textmd",
|
||
"\\textnormal",
|
||
"\\textup",
|
||
"\\textrm",
|
||
"\\textsc",
|
||
];
|
||
/// Match a styled wrapper command at the start of `rest`, composing its face
|
||
/// with the surrounding one (`\\emph` toggles italic inside a bold run, etc.).
|
||
fn inline_wrapper(rest: &str, base: ParagraphFont) -> Option<(ParagraphFont, &str, usize)> {
|
||
for command in INLINE_COMMANDS {
|
||
let Some(after) = rest.strip_prefix(command) else {
|
||
continue;
|
||
};
|
||
if let Some((inner, length)) = braced_group(after) {
|
||
let font = match command {
|
||
"\\textbf" => base.bolded(),
|
||
"\\emph" => base.emphasized(),
|
||
"\\textit" => base.italicized(),
|
||
"\\textsl" => base.slanted(),
|
||
"\\texttt" => ParagraphFont::Mono,
|
||
"\\textsf" => base.sans_family(),
|
||
"\\textmd" => base.medium(),
|
||
"\\textup" => base.upright(),
|
||
"\\textrm" => base.roman_family(),
|
||
"\\textsc" => base.small_caps(),
|
||
"\\textnormal" => ParagraphFont::Roman,
|
||
_ => base,
|
||
};
|
||
return Some((font, inner, command.len() + length));
|
||
}
|
||
}
|
||
None
|
||
}
|
||
|
||
fn verb_run(rest: &str) -> Option<(String, usize)> {
|
||
let after = rest.strip_prefix("\\verb")?;
|
||
let after = after.strip_prefix('*').unwrap_or(after);
|
||
let (start, delimiter) = after.char_indices().next()?;
|
||
if delimiter.is_ascii_alphanumeric() || delimiter.is_whitespace() || delimiter == '\\' {
|
||
return None;
|
||
}
|
||
let body_start = start + delimiter.len_utf8();
|
||
let end = after[body_start..].find(delimiter)?;
|
||
let prefix = rest.len() - after.len();
|
||
Some((
|
||
after[body_start..body_start + end].to_string(),
|
||
prefix + body_start + end + delimiter.len_utf8(),
|
||
))
|
||
}
|
||
|
||
/// Recognise a text command that stands for a printable character.
|
||
/// Recognize `\MakeUppercase`/`\MakeLowercase` and their TeX spellings.
|
||
fn case_run(rest: &str) -> Option<(String, usize)> {
|
||
for (command, upper) in [
|
||
("\\MakeUppercase", true),
|
||
("\\MakeLowercase", false),
|
||
("\\uppercase", true),
|
||
("\\lowercase", false),
|
||
] {
|
||
let Some(after) = rest.strip_prefix(command) else {
|
||
continue;
|
||
};
|
||
let Some(after) = after.strip_prefix('{') else {
|
||
continue;
|
||
};
|
||
let mut depth = 1_usize;
|
||
for (offset, character) in after.char_indices() {
|
||
match character {
|
||
'{' => depth += 1,
|
||
'}' => {
|
||
depth -= 1;
|
||
if depth == 0 {
|
||
let inner = &after[..offset];
|
||
let changed = if upper {
|
||
inner.to_uppercase()
|
||
} else {
|
||
inner.to_lowercase()
|
||
};
|
||
return Some((changed, command.len() + 1 + offset + 1));
|
||
}
|
||
}
|
||
_ => {}
|
||
}
|
||
}
|
||
}
|
||
None
|
||
}
|
||
|
||
fn text_symbol(rest: &str) -> Option<(&'static str, usize)> {
|
||
const SYMBOLS: &[(&str, &str)] = &[
|
||
("\\textthreequarters", "\u{be}"),
|
||
("\\textonequarter", "\u{bc}"),
|
||
("\\textonehalf", "\u{bd}"),
|
||
("\\textperthousand", "\u{2030}"),
|
||
("\\textregistered", "\u{ae}"),
|
||
("\\texttrademark", "\u{2122}"),
|
||
("\\textparagraph", "\u{b6}"),
|
||
("\\textsection", "\u{a7}"),
|
||
("\\textsterling", "\u{a3}"),
|
||
("\\textdegree", "\u{b0}"),
|
||
("\\textcurrency", "\u{a4}"),
|
||
("\\texteuro", "\u{20ac}"),
|
||
("\\textyen", "\u{a5}"),
|
||
("\\textcent", "\u{a2}"),
|
||
("\\textmu", "\u{b5}"),
|
||
("\\textbackslash", "\\"),
|
||
("\\textasciitilde", "~"),
|
||
("\\textasciicircum", "^"),
|
||
("\\textquotedblleft", "\u{201c}"),
|
||
("\\textquotedblright", "\u{201d}"),
|
||
("\\textquoteleft", "\u{2018}"),
|
||
("\\textquoteright", "\u{2019}"),
|
||
("\\textemdash", "\u{2014}"),
|
||
("\\textendash", "\u{2013}"),
|
||
("\\textgreater", ">"),
|
||
("\\textbullet", "\u{2022}"),
|
||
("\\textless", "<"),
|
||
("\\copyright", "\u{a9}"),
|
||
("\\LaTeXe", "LaTeX2e"),
|
||
("\\LaTeX", "LaTeX"),
|
||
("\\pounds", "\u{a3}"),
|
||
("\\textbar", "|"),
|
||
("\\ldots", "\u{2026}"),
|
||
("\\dots", "\u{2026}"),
|
||
("\\TeX", "TeX"),
|
||
("\\SS", "SS"),
|
||
("\\AE", "\u{c6}"),
|
||
("\\OE", "\u{152}"),
|
||
("\\AA", "\u{c5}"),
|
||
("\\DH", "\u{d0}"),
|
||
("\\TH", "\u{de}"),
|
||
("\\NG", "\u{14a}"),
|
||
("\\ae", "\u{e6}"),
|
||
("\\oe", "\u{153}"),
|
||
("\\aa", "\u{e5}"),
|
||
("\\dh", "\u{f0}"),
|
||
("\\th", "\u{fe}"),
|
||
("\\ng", "\u{14b}"),
|
||
("\\ss", "\u{df}"),
|
||
("\\oe", "\u{153}"),
|
||
("\\o", "\u{f8}"),
|
||
("\\O", "\u{d8}"),
|
||
("\\l", "\u{142}"),
|
||
("\\L", "\u{141}"),
|
||
("\\i", "\u{131}"),
|
||
("\\j", "\u{237}"),
|
||
("\\S", "\u{a7}"),
|
||
("\\P", "\u{b6}"),
|
||
];
|
||
for (command, replacement) in SYMBOLS {
|
||
let Some(after) = rest.strip_prefix(command) else {
|
||
continue;
|
||
};
|
||
if after
|
||
.chars()
|
||
.next()
|
||
.map_or(true, |character| !character.is_ascii_alphabetic())
|
||
{
|
||
// TeX swallows the spaces that follow a control word.
|
||
let trimmed = after.trim_start_matches([' ', '\t', '\n']);
|
||
let skipped = after.len() - trimmed.len();
|
||
return Some((replacement, command.len() + skipped));
|
||
}
|
||
}
|
||
None
|
||
}
|
||
|
||
/// Return the precomposed letter for a base letter and a TeX accent command.
|
||
fn compose_accent(base: char, accent: char) -> Option<char> {
|
||
let (bases, composed) = match accent {
|
||
'\'' => ("aeiouycAEIOUYCnsz", "áéíóúýćÁÉÍÓÚÝńśź"),
|
||
'`' => ("aeiouAEIOU", "àèìòùÀÈÌÒÙ"),
|
||
'^' => ("aeiouAEIOU", "âêîôûÂÊÎÔÛ"),
|
||
'"' => ("aeiouyAEIOUY", "äëïöüÿÄËÏÖÜŸ"),
|
||
'~' => ("anoANO", "ãñõÃÑÕ"),
|
||
'c' => ("cC", "çÇ"),
|
||
'r' => ("aA", "åÅ"),
|
||
'v' => ("cszerndtlCSZERNDTL", "čšžěřňȊŽĚŘŇĎŤĽ"),
|
||
'=' => ("aeiouAEIOU", "āēīōūĀĒĪŌŪ"),
|
||
'u' => ("aeiouAEIOU", "ăĕĭŏŭĂĔĬŎŬ"),
|
||
'.' => ("czCZ", "ċżĊŻ"),
|
||
'H' => ("oOuU", "őűŐŰ"),
|
||
_ => return None,
|
||
};
|
||
let index = bases.chars().position(|candidate| candidate == base)?;
|
||
composed.chars().nth(index)
|
||
}
|
||
|
||
/// The combining mark used when no precomposed letter exists.
|
||
fn accent_mark(accent: char) -> Option<char> {
|
||
Some(match accent {
|
||
'\'' => '\u{301}',
|
||
'`' => '\u{300}',
|
||
'^' => '\u{302}',
|
||
'"' => '\u{308}',
|
||
'~' => '\u{303}',
|
||
'c' => '\u{327}',
|
||
'r' => '\u{30a}',
|
||
'v' => '\u{30c}',
|
||
'=' => '\u{304}',
|
||
'u' => '\u{306}',
|
||
'.' => '\u{307}',
|
||
'H' => '\u{30b}',
|
||
_ => return None,
|
||
})
|
||
}
|
||
|
||
/// Recognize a TeX accent command such as `caf\'e` or `na\"{i}ve`.
|
||
fn accent_run(rest: &str) -> Option<(String, usize)> {
|
||
let mut characters = rest.char_indices();
|
||
let (_, backslash) = characters.next()?;
|
||
if backslash != '\\' {
|
||
return None;
|
||
}
|
||
let (accent_offset, accent) = characters.next()?;
|
||
let word_accent = accent.is_ascii_alphabetic();
|
||
if word_accent && !matches!(accent, 'c' | 'v' | 'u' | 'r' | 'H') {
|
||
return None;
|
||
}
|
||
if accent_mark(accent).is_none() {
|
||
return None;
|
||
}
|
||
let mut after_start = accent_offset + accent.len_utf8();
|
||
let after = &rest[after_start..];
|
||
let (after, spaced) = if word_accent {
|
||
let trimmed = after.trim_start_matches([' ', '\t', '\n']);
|
||
after_start += after.len() - trimmed.len();
|
||
(trimmed, trimmed.len() != after.len())
|
||
} else {
|
||
(after, false)
|
||
};
|
||
let (base, extra) = if let Some((group, length)) = braced_group(after) {
|
||
let mut group = group.trim().chars();
|
||
let base = group.next()?;
|
||
if group.next().is_some() {
|
||
return None;
|
||
}
|
||
(base, length)
|
||
} else {
|
||
if word_accent && !spaced {
|
||
return None;
|
||
}
|
||
let base = after.chars().next()?;
|
||
if base.is_whitespace() || base == '{' {
|
||
return None;
|
||
}
|
||
(base, base.len_utf8())
|
||
};
|
||
let text = match compose_accent(base, accent) {
|
||
Some(composed) => composed.to_string(),
|
||
None => format!("{base}{}", accent_mark(accent)?),
|
||
};
|
||
Some((text, after_start + extra))
|
||
}
|
||
|
||
/// Recognize `\textsuperscript{...}` and `\textsubscript{...}`.
|
||
fn script_run(rest: &str) -> Option<(bool, &str, usize)> {
|
||
for (command, superscript) in [("\\textsuperscript", true), ("\\textsubscript", false)] {
|
||
let Some(after) = rest.strip_prefix(command) else {
|
||
continue;
|
||
};
|
||
let skipped = after.len() - after.trim_start().len();
|
||
let after = after.trim_start();
|
||
let (inner, length) = braced_group(after)?;
|
||
return Some((superscript, inner, command.len() + skipped + length));
|
||
}
|
||
None
|
||
}
|
||
|
||
fn parse_runs(
|
||
text: &str,
|
||
font: ParagraphFont,
|
||
size: i64,
|
||
raise: i64,
|
||
runs: &mut Vec<(ParagraphFont, i64, i64, String)>,
|
||
found: &mut bool,
|
||
) {
|
||
let mut index = 0;
|
||
while index < text.len() {
|
||
let rest = &text[index..];
|
||
if let Some((body, length)) = verb_run(rest) {
|
||
*found = true;
|
||
push_run(runs, ParagraphFont::Mono, size, raise, &body);
|
||
index += length;
|
||
continue;
|
||
}
|
||
if let Some((superscript, inner, length)) = script_run(rest) {
|
||
*found = true;
|
||
let script_size = (size * 7 / 10).max(1);
|
||
let shift = size * 2 / 5;
|
||
let script_raise = if superscript {
|
||
raise + shift
|
||
} else {
|
||
raise - shift
|
||
};
|
||
parse_runs(inner, font, script_size, script_raise, runs, found);
|
||
index += length;
|
||
continue;
|
||
}
|
||
if let Some((declared, declared_size, body)) = nfss_font_with_size(rest, font) {
|
||
*found = true;
|
||
parse_runs(
|
||
&body,
|
||
declared,
|
||
declared_size.unwrap_or(size),
|
||
raise,
|
||
runs,
|
||
found,
|
||
);
|
||
return;
|
||
}
|
||
if let Some((inner, length)) = braced_group(rest) {
|
||
let (inner_font, inner_size, inner_text) = match nfss_font_with_size(inner, font) {
|
||
Some((declared, declared_size, body)) => {
|
||
(declared, declared_size.unwrap_or(size), body)
|
||
}
|
||
None => (font, size, inner.to_string()),
|
||
};
|
||
if nfss_font_with_size(inner, font).is_some() {
|
||
*found = true;
|
||
}
|
||
parse_runs(&inner_text, inner_font, inner_size, raise, runs, found);
|
||
index += length;
|
||
continue;
|
||
}
|
||
if let Some((wrapper_font, inner, length)) = inline_wrapper(rest, font) {
|
||
*found = true;
|
||
parse_runs(inner, wrapper_font, size, raise, runs, found);
|
||
index += length;
|
||
continue;
|
||
}
|
||
if let Some((accent, length)) = accent_run(rest) {
|
||
*found = true;
|
||
push_run(runs, font, size, raise, &accent);
|
||
index += length;
|
||
continue;
|
||
}
|
||
if let Some((changed, length)) = case_run(rest) {
|
||
*found = true;
|
||
push_run(runs, font, size, raise, &changed);
|
||
index += length;
|
||
continue;
|
||
}
|
||
if let Some((symbol, length)) = text_symbol(rest) {
|
||
*found = true;
|
||
push_run(runs, font, size, raise, symbol);
|
||
index += length;
|
||
continue;
|
||
}
|
||
if rest.starts_with('\\') {
|
||
let step = rest
|
||
.char_indices()
|
||
.skip(1)
|
||
.find(|(_, character)| !character.is_ascii_alphabetic())
|
||
.map(|(offset, _)| offset.max(1))
|
||
.unwrap_or(rest.len());
|
||
push_run(runs, font, size, raise, &rest[..step]);
|
||
index += step;
|
||
continue;
|
||
}
|
||
let step = rest
|
||
.char_indices()
|
||
.skip(1)
|
||
.find(|(_, character)| *character == '{' || *character == '\\')
|
||
.map(|(offset, _)| offset)
|
||
.unwrap_or(rest.len());
|
||
push_run(runs, font, size, raise, &rest[..step]);
|
||
index += step;
|
||
}
|
||
}
|
||
|
||
/// Recognize a `\section`-family command: level, starred, and title.
|
||
fn heading_command(raw: &str) -> Option<(u8, bool, String, Option<String>)> {
|
||
let raw = raw.trim();
|
||
for (command, level) in [
|
||
("\\section", 1u8),
|
||
("\\subsection", 2),
|
||
("\\subsubsection", 3),
|
||
("\\paragraph", 4),
|
||
("\\subparagraph", 5),
|
||
] {
|
||
let Some(rest) = raw.strip_prefix(command) else {
|
||
continue;
|
||
};
|
||
let (rest, starred) = match rest.strip_prefix('*') {
|
||
Some(rest) => (rest, true),
|
||
None => (rest, false),
|
||
};
|
||
let rest = rest.trim_start();
|
||
// Keep the optional short title for the table of contents.
|
||
let (rest, short) = match rest.strip_prefix('[') {
|
||
Some(after) => match after.split_once(']') {
|
||
Some((short, rest)) => (rest.trim_start(), Some(short.trim().to_string())),
|
||
None => (rest, None),
|
||
},
|
||
None => (rest, None),
|
||
};
|
||
let (body, _) = braced_group(rest)?;
|
||
return Some((level, starred, body.trim().to_string(), short));
|
||
}
|
||
None
|
||
}
|
||
|
||
/// Rows of an amsmath `split` environment, used inside one numbered equation.
|
||
fn split_body_rows(text: &str) -> Option<Vec<String>> {
|
||
let inner = text
|
||
.trim()
|
||
.strip_prefix("\\begin{split}")?
|
||
.strip_suffix("\\end{split}")?;
|
||
Some(
|
||
inner
|
||
.split("\\\\")
|
||
.map(str::trim)
|
||
.filter(|row| !row.is_empty())
|
||
.map(str::to_string)
|
||
.collect(),
|
||
)
|
||
}
|
||
|
||
fn parse_paragraph(raw: &str) -> SourceParagraph {
|
||
if let Some(inner) = raw
|
||
.strip_prefix("\\begin{displaymath}")
|
||
.and_then(|text| text.strip_suffix("\\end{displaymath}"))
|
||
{
|
||
return parse_paragraph(&format!("$$\n{}\n$$", inner));
|
||
}
|
||
for (environment, starred) in [("multline", false), ("multline*", true)] {
|
||
let begin = format!("\\begin{{{environment}}}");
|
||
let finish = format!("\\end{{{environment}}}");
|
||
let Some(inner) = raw
|
||
.strip_prefix(&begin)
|
||
.and_then(|text| text.strip_suffix(&finish))
|
||
else {
|
||
continue;
|
||
};
|
||
let lines: Vec<&str> = inner
|
||
.split("\\\\")
|
||
.map(str::trim)
|
||
.filter(|row| !row.is_empty())
|
||
.collect();
|
||
let rows: Vec<EquationRow> = lines
|
||
.iter()
|
||
.enumerate()
|
||
.map(|(index, row)| EquationRow {
|
||
text: row.to_string(),
|
||
number: if !starred && index + 1 == lines.len() {
|
||
Some(0)
|
||
} else {
|
||
None
|
||
},
|
||
tag: None,
|
||
})
|
||
.collect();
|
||
let mut block = parse_paragraph(inner.trim());
|
||
block.equation_rows = rows;
|
||
block.multline = true;
|
||
block.align_centered = false;
|
||
block.math = true;
|
||
return block;
|
||
}
|
||
for (environment, starred) in [("alignat", false), ("alignat*", true)] {
|
||
let begin = format!("\\begin{{{environment}}}");
|
||
let finish = format!("\\end{{{environment}}}");
|
||
let Some(rest) = raw.strip_prefix(&begin) else {
|
||
continue;
|
||
};
|
||
let rest = rest.trim_start();
|
||
let rest = if let Some(after) = rest.strip_prefix('{') {
|
||
let Some(close) = after.find('}') else {
|
||
continue;
|
||
};
|
||
&after[close + 1..]
|
||
} else {
|
||
rest
|
||
};
|
||
let Some(inner) = rest.strip_suffix(&finish) else {
|
||
continue;
|
||
};
|
||
let rows: Vec<EquationRow> = inner
|
||
.split("\\\\")
|
||
.map(str::trim)
|
||
.filter(|row| !row.is_empty())
|
||
.map(|row| EquationRow {
|
||
text: row.to_string(),
|
||
number: if starred { None } else { Some(0) },
|
||
tag: None,
|
||
})
|
||
.collect();
|
||
let mut block = parse_paragraph(inner.trim());
|
||
block.equation_rows = rows;
|
||
block.align_centered = false;
|
||
block.math = true;
|
||
return block;
|
||
}
|
||
for (environment, starred, centered) in [
|
||
("align", false, false),
|
||
("align*", true, false),
|
||
("gather", false, true),
|
||
("gather*", true, true),
|
||
] {
|
||
let begin = format!("\\begin{{{environment}}}");
|
||
let finish = format!("\\end{{{environment}}}");
|
||
if let Some(inner) = raw
|
||
.strip_prefix(&begin)
|
||
.and_then(|text| text.strip_suffix(&finish))
|
||
{
|
||
let rows: Vec<EquationRow> = inner
|
||
.split("\\\\")
|
||
.map(str::trim)
|
||
.filter(|row| !row.is_empty())
|
||
.map(|row| EquationRow {
|
||
text: row.to_string(),
|
||
number: if starred { None } else { Some(0) },
|
||
tag: None,
|
||
})
|
||
.collect();
|
||
return SourceParagraph {
|
||
width: None,
|
||
multline: false,
|
||
list_depth: None,
|
||
list_label: 0,
|
||
right_skip: 0,
|
||
text: inner.trim().to_string(),
|
||
font: ParagraphFont::Roman,
|
||
line_height: 12,
|
||
math: true,
|
||
left_skip: 0,
|
||
centered: false,
|
||
right_aligned: false,
|
||
space_before: 0,
|
||
space_stretch: 0,
|
||
space_shrink: 0,
|
||
page_break: false,
|
||
equation_number: None,
|
||
equation_tag: None,
|
||
equation_rows: rows,
|
||
align_centered: centered,
|
||
heading_level: None,
|
||
heading_starred: false,
|
||
heading_number: None,
|
||
heading_short: None,
|
||
footnotes: Vec::new(),
|
||
theorem: None,
|
||
float: None,
|
||
font_size: None,
|
||
};
|
||
}
|
||
}
|
||
if let Some((font, font_size, body)) = nfss_font_with_size(raw, ParagraphFont::Roman) {
|
||
return SourceParagraph {
|
||
width: None,
|
||
multline: false,
|
||
list_depth: None,
|
||
list_label: 0,
|
||
right_skip: 0,
|
||
text: body,
|
||
font,
|
||
font_size,
|
||
line_height: 12,
|
||
math: false,
|
||
left_skip: 0,
|
||
centered: false,
|
||
right_aligned: false,
|
||
space_before: 0,
|
||
space_stretch: 0,
|
||
space_shrink: 0,
|
||
page_break: false,
|
||
equation_number: None,
|
||
equation_tag: None,
|
||
equation_rows: Vec::new(),
|
||
align_centered: false,
|
||
heading_level: None,
|
||
heading_starred: false,
|
||
heading_number: None,
|
||
heading_short: None,
|
||
footnotes: Vec::new(),
|
||
theorem: None,
|
||
float: None,
|
||
};
|
||
}
|
||
if let Some(inner) = raw
|
||
.strip_prefix("\\begin{equation}")
|
||
.and_then(|text| text.strip_suffix("\\end{equation}"))
|
||
{
|
||
return SourceParagraph {
|
||
width: None,
|
||
multline: false,
|
||
list_depth: None,
|
||
list_label: 0,
|
||
right_skip: 0,
|
||
text: inner.trim().to_string(),
|
||
font: ParagraphFont::Roman,
|
||
line_height: 12,
|
||
math: true,
|
||
left_skip: 0,
|
||
centered: false,
|
||
right_aligned: false,
|
||
space_before: 0,
|
||
space_stretch: 0,
|
||
space_shrink: 0,
|
||
page_break: false,
|
||
equation_number: Some(0),
|
||
equation_tag: None,
|
||
equation_rows: Vec::new(),
|
||
align_centered: false,
|
||
heading_level: None,
|
||
heading_starred: false,
|
||
heading_number: None,
|
||
heading_short: None,
|
||
footnotes: Vec::new(),
|
||
theorem: None,
|
||
float: None,
|
||
font_size: None,
|
||
};
|
||
}
|
||
if let Some(inner) = raw
|
||
.strip_prefix("\\begin{equation*}")
|
||
.and_then(|text| text.strip_suffix("\\end{equation*}"))
|
||
{
|
||
return SourceParagraph {
|
||
width: None,
|
||
multline: false,
|
||
list_depth: None,
|
||
list_label: 0,
|
||
right_skip: 0,
|
||
text: inner.trim().to_string(),
|
||
font: ParagraphFont::Roman,
|
||
line_height: 12,
|
||
math: true,
|
||
left_skip: 0,
|
||
centered: false,
|
||
right_aligned: false,
|
||
space_before: 0,
|
||
space_stretch: 0,
|
||
space_shrink: 0,
|
||
page_break: false,
|
||
equation_number: None,
|
||
equation_tag: None,
|
||
equation_rows: Vec::new(),
|
||
align_centered: false,
|
||
heading_level: None,
|
||
heading_starred: false,
|
||
heading_number: None,
|
||
heading_short: None,
|
||
footnotes: Vec::new(),
|
||
theorem: None,
|
||
float: None,
|
||
font_size: None,
|
||
};
|
||
}
|
||
if let Some(math) = raw
|
||
.strip_prefix("$$")
|
||
.and_then(|text| text.strip_suffix("$$"))
|
||
.or_else(|| {
|
||
raw.strip_prefix("\\[")
|
||
.and_then(|text| text.strip_suffix("\\]"))
|
||
})
|
||
{
|
||
return SourceParagraph {
|
||
width: None,
|
||
multline: false,
|
||
list_depth: None,
|
||
list_label: 0,
|
||
right_skip: 0,
|
||
text: math.trim().to_string(),
|
||
font: ParagraphFont::Roman,
|
||
line_height: 12,
|
||
math: true,
|
||
left_skip: 0,
|
||
centered: false,
|
||
right_aligned: false,
|
||
space_before: 0,
|
||
space_stretch: 0,
|
||
space_shrink: 0,
|
||
page_break: false,
|
||
equation_number: None,
|
||
equation_tag: None,
|
||
equation_rows: Vec::new(),
|
||
align_centered: false,
|
||
heading_level: None,
|
||
heading_starred: false,
|
||
heading_number: None,
|
||
heading_short: None,
|
||
footnotes: Vec::new(),
|
||
theorem: None,
|
||
float: None,
|
||
font_size: None,
|
||
};
|
||
}
|
||
if let Some((level, starred, title, short)) = heading_command(raw) {
|
||
return SourceParagraph {
|
||
width: None,
|
||
multline: false,
|
||
list_depth: None,
|
||
list_label: 0,
|
||
right_skip: 0,
|
||
text: title,
|
||
font: ParagraphFont::Bold,
|
||
line_height: if level == 1 {
|
||
18
|
||
} else if level <= 3 {
|
||
14
|
||
} else {
|
||
12
|
||
},
|
||
math: false,
|
||
left_skip: 0,
|
||
centered: false,
|
||
right_aligned: false,
|
||
space_before: match level {
|
||
1 => 12 * SCALE,
|
||
2 => 10 * SCALE,
|
||
3 => 8 * SCALE,
|
||
4 => 6 * SCALE,
|
||
_ => 4 * SCALE,
|
||
},
|
||
space_stretch: 4 * SCALE,
|
||
space_shrink: SCALE,
|
||
page_break: false,
|
||
equation_number: None,
|
||
equation_tag: None,
|
||
equation_rows: Vec::new(),
|
||
align_centered: false,
|
||
heading_level: Some(level),
|
||
heading_starred: starred,
|
||
heading_number: None,
|
||
heading_short: short,
|
||
footnotes: Vec::new(),
|
||
theorem: None,
|
||
float: None,
|
||
font_size: None,
|
||
};
|
||
}
|
||
let candidates = [
|
||
("\\textbf", ParagraphFont::Bold, 12),
|
||
("\\textbf", ParagraphFont::Bold, 12),
|
||
("\\emph", ParagraphFont::Italic, 12),
|
||
("\\texttt", ParagraphFont::Mono, 12),
|
||
("\\textsf", ParagraphFont::Sans, 12),
|
||
];
|
||
for (command, font, line_height) in candidates {
|
||
if let Some(text) = command_body(raw, command) {
|
||
return SourceParagraph {
|
||
width: None,
|
||
multline: false,
|
||
list_depth: None,
|
||
list_label: 0,
|
||
right_skip: 0,
|
||
text: text.to_string(),
|
||
font,
|
||
line_height,
|
||
math: false,
|
||
left_skip: 0,
|
||
centered: false,
|
||
right_aligned: false,
|
||
space_before: 0,
|
||
space_stretch: 0,
|
||
space_shrink: 0,
|
||
page_break: false,
|
||
equation_number: None,
|
||
equation_tag: None,
|
||
equation_rows: Vec::new(),
|
||
align_centered: false,
|
||
heading_level: None,
|
||
heading_starred: false,
|
||
heading_number: None,
|
||
heading_short: None,
|
||
footnotes: Vec::new(),
|
||
theorem: None,
|
||
float: None,
|
||
font_size: None,
|
||
};
|
||
}
|
||
}
|
||
SourceParagraph {
|
||
width: None,
|
||
multline: false,
|
||
list_depth: None,
|
||
list_label: 0,
|
||
right_skip: 0,
|
||
text: raw.to_string(),
|
||
font: ParagraphFont::Roman,
|
||
line_height: 12,
|
||
math: false,
|
||
left_skip: 0,
|
||
centered: false,
|
||
right_aligned: false,
|
||
space_before: 0,
|
||
space_stretch: 0,
|
||
space_shrink: 0,
|
||
page_break: false,
|
||
equation_number: None,
|
||
equation_tag: None,
|
||
equation_rows: Vec::new(),
|
||
align_centered: false,
|
||
heading_level: None,
|
||
heading_starred: false,
|
||
heading_number: None,
|
||
heading_short: None,
|
||
footnotes: Vec::new(),
|
||
theorem: None,
|
||
float: None,
|
||
font_size: None,
|
||
}
|
||
}
|
||
|
||
/// Wrap a row cell with empty Ord atoms so relation spacing shows up at the
|
||
/// column boundaries, the way amsmath aligns relation columns.
|
||
fn aligned_cell(source: &str) -> MathAtom {
|
||
let mut atoms = vec![MathAtom::Row(Vec::new())];
|
||
match parse_math(source.trim()) {
|
||
MathAtom::Row(inner) => atoms.extend(inner),
|
||
other => atoms.push(other),
|
||
}
|
||
atoms.push(MathAtom::Row(Vec::new()));
|
||
MathAtom::Row(atoms)
|
||
}
|
||
|
||
/// The article class title size for a base size.
|
||
fn title_size(base_font_size: i64) -> f64 {
|
||
match base_font_size / SCALE {
|
||
12 => 24.88,
|
||
11 => 20.74,
|
||
_ => 17.28,
|
||
}
|
||
}
|
||
|
||
/// The article class `\large` size for a base size.
|
||
fn title_large_size(base_font_size: i64) -> f64 {
|
||
match base_font_size / SCALE {
|
||
12 => 14.4,
|
||
_ => 12.0,
|
||
}
|
||
}
|
||
|
||
/// Remove `\thanks{...}` groups and join multiple authors set with `\and`.
|
||
/// Rewrite `\thanks{...}` notes as footnotes so they become page insertions
|
||
/// instead of disappearing with the title block.
|
||
fn thanks_to_footnotes(text: &str) -> String {
|
||
let mut out = String::new();
|
||
let mut rest = text;
|
||
loop {
|
||
let Some(index) = rest.find("\\thanks") else {
|
||
out.push_str(rest);
|
||
break;
|
||
};
|
||
out.push_str(&rest[..index]);
|
||
let after = &rest[index + "\\thanks".len()..];
|
||
let trimmed = after.trim_start();
|
||
let Some((inner, consumed)) = braced_group(trimmed) else {
|
||
out.push_str("\\thanks");
|
||
rest = after;
|
||
continue;
|
||
};
|
||
out.push_str("\\footnote{");
|
||
out.push_str(&inner);
|
||
out.push('}');
|
||
rest = &trimmed[consumed..];
|
||
}
|
||
out
|
||
}
|
||
|
||
/// The LaTeX `\today` date in article form. Route-D has no time zone
|
||
/// database, so the date comes from the UTC Unix clock.
|
||
fn today_string() -> String {
|
||
const MONTHS: [&str; 12] = [
|
||
"January",
|
||
"February",
|
||
"March",
|
||
"April",
|
||
"May",
|
||
"June",
|
||
"July",
|
||
"August",
|
||
"September",
|
||
"October",
|
||
"November",
|
||
"December",
|
||
];
|
||
let days = std::time::SystemTime::now()
|
||
.duration_since(std::time::UNIX_EPOCH)
|
||
.map(|duration| (duration.as_secs() / 86_400) as i64)
|
||
.unwrap_or(0);
|
||
let (year, month, day) = civil_from_days(days);
|
||
format!("{} {}, {}", MONTHS[(month - 1) as usize], day, year)
|
||
}
|
||
|
||
fn civil_from_days(days: i64) -> (i64, u32, u32) {
|
||
let z = days + 719_468;
|
||
let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
|
||
let day_of_era = z - era * 146_097;
|
||
let year_of_era =
|
||
(day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
|
||
let year = year_of_era + era * 400;
|
||
let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
|
||
let month_index = (5 * day_of_year + 2) / 153;
|
||
let day = day_of_year - (153 * month_index + 2) / 5 + 1;
|
||
let month = if month_index < 10 {
|
||
month_index + 3
|
||
} else {
|
||
month_index - 9
|
||
};
|
||
(
|
||
if month <= 2 { year + 1 } else { year },
|
||
month as u32,
|
||
day as u32,
|
||
)
|
||
}
|
||
|
||
fn expand_today(text: &str, today: &str) -> String {
|
||
text.replace("\\today", today)
|
||
}
|
||
|
||
fn clean_title_value(text: &str) -> String {
|
||
let mut out = String::new();
|
||
let mut rest = text;
|
||
loop {
|
||
let Some(index) = rest.find("\\thanks") else {
|
||
out.push_str(rest);
|
||
break;
|
||
};
|
||
out.push_str(&rest[..index]);
|
||
let after = rest[index + "\\thanks".len()..].trim_start();
|
||
let Some(group) = after.strip_prefix('{') else {
|
||
out.push_str("\\thanks");
|
||
rest = &rest[index + "\\thanks".len()..];
|
||
continue;
|
||
};
|
||
let mut depth = 1usize;
|
||
let mut end = None;
|
||
for (offset, character) in group.char_indices() {
|
||
match character {
|
||
'{' => depth += 1,
|
||
'}' => {
|
||
depth -= 1;
|
||
if depth == 0 {
|
||
end = Some(offset + 1);
|
||
break;
|
||
}
|
||
}
|
||
_ => {}
|
||
}
|
||
}
|
||
match end {
|
||
Some(end) => rest = &group[end..],
|
||
None => {
|
||
out.push_str("\\thanks");
|
||
rest = &rest[index + "\\thanks".len()..];
|
||
}
|
||
}
|
||
}
|
||
let joined = out.replace("\\and", ", ");
|
||
let mut normalized = joined.split_whitespace().collect::<Vec<_>>().join(" ");
|
||
normalized = normalized.replace(" ,", ",");
|
||
normalized.trim().to_string()
|
||
}
|
||
|
||
fn title_block(text: String, size: f64, space_before: i64) -> SourceParagraph {
|
||
SourceParagraph {
|
||
width: None,
|
||
multline: false,
|
||
list_depth: None,
|
||
list_label: 0,
|
||
right_skip: 0,
|
||
text,
|
||
font: ParagraphFont::Roman,
|
||
line_height: 12,
|
||
math: false,
|
||
left_skip: 0,
|
||
centered: true,
|
||
right_aligned: false,
|
||
space_before,
|
||
space_stretch: 0,
|
||
space_shrink: 0,
|
||
page_break: false,
|
||
equation_number: None,
|
||
equation_tag: None,
|
||
equation_rows: Vec::new(),
|
||
align_centered: false,
|
||
heading_level: None,
|
||
heading_starred: false,
|
||
heading_number: None,
|
||
heading_short: None,
|
||
footnotes: Vec::new(),
|
||
theorem: None,
|
||
float: None,
|
||
font_size: Some((size * SCALE as f64) as i64),
|
||
}
|
||
}
|
||
|
||
/// Expand `\maketitle` into the centered title block that article.cls sets.
|
||
/// Rename the bold `Abstract` heading emitted for the abstract environment.
|
||
fn rename_abstract_heading(paragraphs: &mut [SourceParagraph], name: &str) {
|
||
for paragraph in paragraphs {
|
||
if paragraph.font == ParagraphFont::Bold
|
||
&& !paragraph.math
|
||
&& paragraph.heading_level.is_none()
|
||
&& paragraph.text.trim() == "Abstract"
|
||
{
|
||
paragraph.text = name.to_string();
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
|
||
fn expand_maketitle(blocks: &[SourceParagraph], geometry: &PageGeometry) -> Vec<SourceParagraph> {
|
||
if !blocks
|
||
.iter()
|
||
.any(|block| block.text.trim() == "\\maketitle")
|
||
{
|
||
return blocks.to_vec();
|
||
}
|
||
let base = geometry.base_font_size.unwrap_or(10 * SCALE);
|
||
let today = today_string();
|
||
let mut result = Vec::new();
|
||
for block in blocks {
|
||
if block.text.trim() != "\\maketitle" {
|
||
result.push(block.clone());
|
||
continue;
|
||
}
|
||
if let Some(title) = geometry.title.as_deref().filter(|title| !title.is_empty()) {
|
||
let mut paragraph = title_block(
|
||
clean_title_value(&expand_today(&thanks_to_footnotes(title), &today)),
|
||
title_size(base),
|
||
block.space_before,
|
||
);
|
||
paragraph.page_break = block.page_break;
|
||
result.push(paragraph);
|
||
}
|
||
let author_space = block.space_before + 12 * SCALE;
|
||
if let Some(author) = geometry
|
||
.author
|
||
.as_deref()
|
||
.filter(|author| !author.is_empty())
|
||
{
|
||
result.push(title_block(
|
||
clean_title_value(&expand_today(&thanks_to_footnotes(author), &today)),
|
||
title_large_size(base),
|
||
author_space,
|
||
));
|
||
}
|
||
let date = match geometry.date.as_deref() {
|
||
Some(date) if date.trim().is_empty() => None,
|
||
Some(date) => Some(expand_today(date, &today)),
|
||
None => Some(today.clone()),
|
||
};
|
||
if let Some(date) = date {
|
||
result.push(title_block(
|
||
clean_title_value(&thanks_to_footnotes(&date)),
|
||
title_large_size(base),
|
||
12 * SCALE,
|
||
));
|
||
}
|
||
}
|
||
result
|
||
}
|
||
|
||
/// Advance the section counters and prefix each numbered heading with its
|
||
/// number. Labels inside a heading (or on their own line after it) resolve to
|
||
/// that number, and label-only blocks are removed.
|
||
fn number_sections(
|
||
blocks: &mut Vec<SourceParagraph>,
|
||
secnumdepth: u32,
|
||
section_start: u32,
|
||
) -> Vec<(String, String)> {
|
||
let mut counters = [section_start, 0u32, 0, 0, 0];
|
||
let mut appendix = false;
|
||
let mut labels = Vec::new();
|
||
let mut last_number: Option<String> = None;
|
||
let mut index = 0;
|
||
while index < blocks.len() {
|
||
if blocks[index].text.trim() == "\\appendix" {
|
||
appendix = true;
|
||
counters = [0; 5];
|
||
blocks.remove(index);
|
||
continue;
|
||
}
|
||
let level = blocks[index].heading_level;
|
||
let block_labels = take_labels(&mut blocks[index].text);
|
||
if level.is_none() {
|
||
if !block_labels.is_empty() && blocks[index].text.trim().is_empty() {
|
||
let value = last_number.clone().unwrap_or_else(|| "??".to_string());
|
||
for label in block_labels {
|
||
labels.push((label, value.clone()));
|
||
}
|
||
blocks.remove(index);
|
||
continue;
|
||
}
|
||
let value = last_number.clone().unwrap_or_else(|| "??".to_string());
|
||
for label in block_labels {
|
||
labels.push((label, value.clone()));
|
||
}
|
||
index += 1;
|
||
continue;
|
||
}
|
||
let level = level.unwrap();
|
||
if blocks[index].heading_starred {
|
||
let value = last_number.clone().unwrap_or_else(|| "??".to_string());
|
||
for label in block_labels {
|
||
labels.push((label, value.clone()));
|
||
}
|
||
index += 1;
|
||
continue;
|
||
}
|
||
let counter = level as usize - 1;
|
||
counters[counter] += 1;
|
||
for deeper in counters.iter_mut().skip(counter + 1) {
|
||
*deeper = 0;
|
||
}
|
||
let first = if appendix {
|
||
appendix_letter(counters[0])
|
||
} else {
|
||
counters[0].to_string()
|
||
};
|
||
let number = if level == 1 {
|
||
first
|
||
} else {
|
||
let mut parts = vec![first];
|
||
for depth in 1..level as usize {
|
||
parts.push(counters[depth].to_string());
|
||
}
|
||
parts.join(".")
|
||
};
|
||
if level as u32 > secnumdepth {
|
||
let value = last_number.clone().unwrap_or_else(|| "??".to_string());
|
||
for label in block_labels {
|
||
labels.push((label, value.clone()));
|
||
}
|
||
index += 1;
|
||
continue;
|
||
}
|
||
blocks[index].heading_number = Some(number.clone());
|
||
last_number = Some(number.clone());
|
||
for label in block_labels {
|
||
labels.push((label, number.clone()));
|
||
}
|
||
let title = blocks[index].text.trim().to_string();
|
||
blocks[index].text = format!("{number} {title}");
|
||
index += 1;
|
||
}
|
||
labels
|
||
}
|
||
|
||
/// The letter used for an appendix section counter.
|
||
fn appendix_letter(value: u32) -> String {
|
||
match value {
|
||
0 => "0".to_string(),
|
||
1..=26 => char::from(b'A' + value as u8 - 1).to_string(),
|
||
_ => value.to_string(),
|
||
}
|
||
}
|
||
|
||
/// Replace section references and turn unresolved `\ref`/`\eqref` into `??`.
|
||
fn resolve_section_refs(blocks: &mut [SourceParagraph], labels: &[(String, String)]) {
|
||
for block in blocks {
|
||
for (label, value) in labels {
|
||
block.text = block.text.replace(&format!("\\ref{{{label}}}"), value);
|
||
block.text = block.text.replace(&format!("\\eqref{{{label}}}"), value);
|
||
}
|
||
for command in ["\\ref", "\\eqref"] {
|
||
loop {
|
||
let prefix = format!("{command}{{");
|
||
let Some(start) = block.text.find(&prefix) else {
|
||
break;
|
||
};
|
||
let Some(end) = block.text[start..].find('}') else {
|
||
break;
|
||
};
|
||
block.text.replace_range(start..start + end + 1, "??");
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Heading size relative to the base size: article's `\Large`, `\large`
|
||
/// and `\normalsize`.
|
||
fn heading_font_size(level: u8, base: i64) -> i64 {
|
||
let percent = match level {
|
||
1 => 144,
|
||
2 => 120,
|
||
_ => 100,
|
||
};
|
||
base.saturating_mul(percent) / 100
|
||
}
|
||
|
||
/// Pull `\footnote{...}` bodies out of a paragraph, leaving a numbered
|
||
/// reference in the running text. Footnote numbers run across the document.
|
||
fn number_footnotes(paragraphs: &mut [SourceParagraph]) {
|
||
let mut number = 0u32;
|
||
for paragraph in paragraphs {
|
||
let source = paragraph.text.clone();
|
||
let mut text = String::with_capacity(source.len());
|
||
let mut rest = source.as_str();
|
||
while let Some(index) = rest.find("\\footnote") {
|
||
text.push_str(&rest[..index]);
|
||
let after = rest[index + "\\footnote".len()..].trim_start();
|
||
let Some((body, consumed)) = braced_group(after) else {
|
||
text.push_str(&rest[index..]);
|
||
rest = "";
|
||
break;
|
||
};
|
||
number += 1;
|
||
let _ = write!(text, " ({number})");
|
||
paragraph.footnotes.push((number, body.trim().to_string()));
|
||
rest = &after[consumed..];
|
||
}
|
||
text.push_str(rest);
|
||
paragraph.text = text;
|
||
}
|
||
}
|
||
|
||
/// Number theorem-like headings and return their label targets.
|
||
fn number_theorems(
|
||
paragraphs: &mut [SourceParagraph],
|
||
definitions: &[TheoremDefinition],
|
||
starts: &[(String, u32)],
|
||
) -> Vec<(String, String)> {
|
||
let mut counters: Vec<(String, u32)> = Vec::new();
|
||
let mut labels = Vec::new();
|
||
let mut section: Option<String> = None;
|
||
for paragraph in paragraphs {
|
||
if paragraph.heading_level.is_some() {
|
||
section = paragraph.heading_number.clone();
|
||
}
|
||
let Some(theorem) = paragraph.theorem.as_mut() else {
|
||
continue;
|
||
};
|
||
let definition = definitions
|
||
.iter()
|
||
.find(|definition| definition.name == theorem.name);
|
||
if !theorem.starred && theorem.name != "proof" {
|
||
let counter = definition
|
||
.and_then(|definition| definition.shared.clone())
|
||
.unwrap_or_else(|| theorem.name.clone());
|
||
let value = match counters.iter_mut().find(|(name, _)| *name == counter) {
|
||
Some((_, count)) => {
|
||
*count += 1;
|
||
*count
|
||
}
|
||
None => {
|
||
let start = starts
|
||
.iter()
|
||
.filter(|(name, _)| *name == counter)
|
||
.last()
|
||
.map(|(_, value)| *value)
|
||
.unwrap_or(0);
|
||
counters.push((counter, start + 1));
|
||
start + 1
|
||
}
|
||
};
|
||
let within_section =
|
||
definition.and_then(|definition| definition.within.as_deref()) == Some("section");
|
||
theorem.number = Some(if within_section {
|
||
match §ion {
|
||
Some(section) => format!("{section}.{value}"),
|
||
None => value.to_string(),
|
||
}
|
||
} else {
|
||
value.to_string()
|
||
});
|
||
}
|
||
let display = theorem.display.clone();
|
||
let number = theorem
|
||
.number
|
||
.as_ref()
|
||
.map(|number| format!(" {number}"))
|
||
.unwrap_or_default();
|
||
let title = theorem
|
||
.title
|
||
.as_ref()
|
||
.map(|title| format!(" ({title})"))
|
||
.unwrap_or_default();
|
||
paragraph.text = format!("{display}{number}{title}.");
|
||
let number = theorem.number.clone();
|
||
if let Some(number) = number {
|
||
for label in theorem.labels.drain(..) {
|
||
labels.push((label, number.clone()));
|
||
}
|
||
} else {
|
||
theorem.labels.clear();
|
||
}
|
||
}
|
||
labels
|
||
}
|
||
|
||
/// Number float captions and return their label targets.
|
||
fn number_floats(
|
||
paragraphs: &mut [SourceParagraph],
|
||
figure_name: &str,
|
||
table_name: &str,
|
||
figure_start: u32,
|
||
table_start: u32,
|
||
) -> Vec<(String, String)> {
|
||
let mut figures = figure_start;
|
||
let mut tables = table_start;
|
||
let mut labels = Vec::new();
|
||
for paragraph in paragraphs {
|
||
let Some(spec) = paragraph.float.as_mut() else {
|
||
continue;
|
||
};
|
||
let Some(caption) = spec.caption.as_mut() else {
|
||
continue;
|
||
};
|
||
let found = take_labels(caption);
|
||
if spec.caption_starred {
|
||
*caption = caption.trim().to_string();
|
||
continue;
|
||
}
|
||
let number = match spec.kind {
|
||
FloatKind::Figure => {
|
||
figures += 1;
|
||
figures
|
||
}
|
||
FloatKind::Table => {
|
||
tables += 1;
|
||
tables
|
||
}
|
||
};
|
||
let prefix = spec.kind.caption_prefix(figure_name, table_name);
|
||
*caption = format!("{prefix} {number}: {}", caption.trim());
|
||
if let Some(short) = &spec.caption_short {
|
||
spec.list_caption = Some(format!("{prefix} {number}: {short}"));
|
||
}
|
||
for label in found {
|
||
labels.push((label, number.to_string()));
|
||
}
|
||
}
|
||
labels
|
||
}
|
||
|
||
/// Append `thebibliography` entries as numbered paragraphs.
|
||
fn bibliography_heading(text: &str) -> SourceParagraph {
|
||
SourceParagraph {
|
||
width: None,
|
||
multline: false,
|
||
list_depth: None,
|
||
list_label: 0,
|
||
right_skip: 0,
|
||
text: text.to_string(),
|
||
page_break: false,
|
||
centered: false,
|
||
right_aligned: false,
|
||
font: ParagraphFont::Bold,
|
||
line_height: 14,
|
||
math: false,
|
||
left_skip: 0,
|
||
space_before: 12 * SCALE,
|
||
space_stretch: 2 * SCALE,
|
||
space_shrink: 0,
|
||
equation_number: None,
|
||
equation_tag: None,
|
||
equation_rows: Vec::new(),
|
||
align_centered: false,
|
||
heading_level: None,
|
||
heading_starred: false,
|
||
heading_number: None,
|
||
heading_short: None,
|
||
footnotes: Vec::new(),
|
||
theorem: None,
|
||
float: None,
|
||
font_size: None,
|
||
}
|
||
}
|
||
|
||
fn append_bibliography(
|
||
paragraphs: &mut Vec<SourceParagraph>,
|
||
bibliography: &[(String, String)],
|
||
heading: &str,
|
||
) {
|
||
if bibliography.is_empty() {
|
||
return;
|
||
}
|
||
paragraphs.push(bibliography_heading(heading));
|
||
for (index, (_, entry)) in bibliography.iter().enumerate() {
|
||
paragraphs.push(SourceParagraph {
|
||
width: None,
|
||
multline: false,
|
||
list_depth: None,
|
||
list_label: 0,
|
||
right_skip: 0,
|
||
text: format!("[{}] {entry}", index + 1),
|
||
page_break: false,
|
||
centered: false,
|
||
right_aligned: false,
|
||
font: ParagraphFont::Roman,
|
||
line_height: 12,
|
||
math: false,
|
||
left_skip: 0,
|
||
space_before: if index == 0 { 4 * SCALE } else { 4 * SCALE },
|
||
space_stretch: 2 * SCALE,
|
||
space_shrink: 0,
|
||
equation_number: None,
|
||
equation_tag: None,
|
||
equation_rows: Vec::new(),
|
||
align_centered: false,
|
||
heading_level: None,
|
||
heading_starred: false,
|
||
heading_number: None,
|
||
heading_short: None,
|
||
footnotes: Vec::new(),
|
||
theorem: None,
|
||
float: None,
|
||
font_size: None,
|
||
});
|
||
}
|
||
}
|
||
|
||
fn expand_toc(paragraphs: &mut Vec<SourceParagraph>, tocdepth: u32, contents_name: &str) {
|
||
let entries: Vec<(u8, String, String)> = paragraphs
|
||
.iter()
|
||
.filter(|paragraph| {
|
||
paragraph
|
||
.heading_level
|
||
.is_some_and(|level| level as u32 <= tocdepth)
|
||
&& !paragraph.heading_starred
|
||
&& paragraph.heading_number.is_some()
|
||
})
|
||
.map(|paragraph| {
|
||
let number = paragraph.heading_number.clone().unwrap_or_default();
|
||
let text = match (¶graph.heading_short, ¶graph.heading_number) {
|
||
(Some(short), Some(number)) => format!("{number} {short}"),
|
||
_ => paragraph.text.clone(),
|
||
};
|
||
(paragraph.heading_level.unwrap_or(1), number, text)
|
||
})
|
||
.collect();
|
||
let Some(position) = paragraphs
|
||
.iter()
|
||
.position(|paragraph| paragraph.text.trim() == "\\texrratoc")
|
||
else {
|
||
return;
|
||
};
|
||
let space_before = paragraphs[position].space_before;
|
||
let mut toc = Vec::with_capacity(entries.len() + 1);
|
||
if entries.is_empty() {
|
||
paragraphs.remove(position);
|
||
return;
|
||
}
|
||
let mut heading = bibliography_heading(contents_name);
|
||
heading.space_before = space_before;
|
||
toc.push(heading);
|
||
for (level, number, text) in entries.iter() {
|
||
toc.push(SourceParagraph {
|
||
width: None,
|
||
multline: false,
|
||
list_depth: None,
|
||
list_label: 0,
|
||
right_skip: 0,
|
||
text: format!("\\texrratocpage{{{number}}} {text}"),
|
||
page_break: false,
|
||
centered: false,
|
||
right_aligned: false,
|
||
font: ParagraphFont::Roman,
|
||
line_height: 12,
|
||
math: false,
|
||
left_skip: 12 * (level.saturating_sub(1) as i64),
|
||
space_before: 2 * SCALE,
|
||
space_stretch: 0,
|
||
space_shrink: 0,
|
||
equation_number: None,
|
||
equation_tag: None,
|
||
equation_rows: Vec::new(),
|
||
align_centered: false,
|
||
heading_level: None,
|
||
heading_starred: false,
|
||
heading_number: None,
|
||
heading_short: None,
|
||
font_size: None,
|
||
footnotes: Vec::new(),
|
||
float: None,
|
||
theorem: None,
|
||
});
|
||
}
|
||
paragraphs.splice(position..=position, toc);
|
||
}
|
||
|
||
fn expand_float_lists(
|
||
paragraphs: &mut Vec<SourceParagraph>,
|
||
figure_heading: &str,
|
||
table_heading: &str,
|
||
) {
|
||
let figures: Vec<(String, String)> = paragraphs
|
||
.iter()
|
||
.filter_map(|paragraph| match ¶graph.float {
|
||
Some(spec) if spec.kind == FloatKind::Figure => {
|
||
let caption = spec.list_caption.clone().or_else(|| spec.caption.clone())?;
|
||
let prefix = caption
|
||
.split_once(':')
|
||
.map_or("Figure", |(prefix, _)| prefix);
|
||
Some((prefix.trim().to_string(), caption))
|
||
}
|
||
_ => None,
|
||
})
|
||
.collect();
|
||
let tables: Vec<(String, String)> = paragraphs
|
||
.iter()
|
||
.filter_map(|paragraph| match ¶graph.float {
|
||
Some(spec) if spec.kind == FloatKind::Table => {
|
||
let caption = spec.list_caption.clone().or_else(|| spec.caption.clone())?;
|
||
let prefix = caption
|
||
.split_once(':')
|
||
.map_or("Table", |(prefix, _)| prefix);
|
||
Some((prefix.trim().to_string(), caption))
|
||
}
|
||
_ => None,
|
||
})
|
||
.collect();
|
||
for (marker, heading, entries) in [
|
||
("\\texrralof", figure_heading, figures),
|
||
("\\texrralot", table_heading, tables),
|
||
] {
|
||
let Some(position) = paragraphs
|
||
.iter()
|
||
.position(|paragraph| paragraph.text.trim() == marker)
|
||
else {
|
||
continue;
|
||
};
|
||
let space_before = paragraphs[position].space_before;
|
||
if entries.is_empty() {
|
||
paragraphs.remove(position);
|
||
continue;
|
||
}
|
||
let mut list = Vec::with_capacity(entries.len() + 1);
|
||
let mut heading = bibliography_heading(heading);
|
||
heading.space_before = space_before;
|
||
list.push(heading);
|
||
for (prefix, text) in entries.iter() {
|
||
list.push(SourceParagraph {
|
||
width: None,
|
||
multline: false,
|
||
list_depth: None,
|
||
list_label: 0,
|
||
right_skip: 0,
|
||
text: format!("\\texrrafloatpage{{{prefix}}} {text}"),
|
||
page_break: false,
|
||
centered: false,
|
||
right_aligned: false,
|
||
font: ParagraphFont::Roman,
|
||
line_height: 12,
|
||
math: false,
|
||
left_skip: 0,
|
||
space_before: 2 * SCALE,
|
||
space_stretch: 0,
|
||
space_shrink: 0,
|
||
equation_number: None,
|
||
equation_tag: None,
|
||
equation_rows: Vec::new(),
|
||
align_centered: false,
|
||
heading_level: None,
|
||
heading_starred: false,
|
||
heading_number: None,
|
||
heading_short: None,
|
||
font_size: None,
|
||
footnotes: Vec::new(),
|
||
float: None,
|
||
theorem: None,
|
||
});
|
||
}
|
||
paragraphs.splice(position..=position, list);
|
||
}
|
||
}
|
||
|
||
fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Document {
|
||
build_document_with_labels(paragraphs, geometry, &mut HashMap::new(), &mut Vec::new())
|
||
}
|
||
|
||
fn build_document_with_labels(
|
||
paragraphs: &[SourceParagraph],
|
||
geometry: &PageGeometry,
|
||
label_units: &mut HashMap<String, u64>,
|
||
outline_units: &mut Vec<(String, u8, u64)>,
|
||
) -> Document {
|
||
let mut paragraphs = expand_maketitle(paragraphs, geometry);
|
||
if let Some(name) = geometry.abstract_name.as_deref() {
|
||
rename_abstract_heading(&mut paragraphs, name);
|
||
}
|
||
let section_labels = number_sections(
|
||
&mut paragraphs,
|
||
geometry.secnumdepth.unwrap_or(3),
|
||
geometry_counter(geometry, "section"),
|
||
);
|
||
let label_numbers = section_labels.clone();
|
||
expand_toc(
|
||
&mut paragraphs,
|
||
geometry.tocdepth.unwrap_or(3),
|
||
geometry.contents_name.as_deref().unwrap_or("Contents"),
|
||
);
|
||
let mut references = section_labels;
|
||
references.extend(number_theorems(
|
||
&mut paragraphs,
|
||
&geometry.theorem_definitions,
|
||
&geometry.counters,
|
||
));
|
||
references.extend(number_floats(
|
||
&mut paragraphs,
|
||
geometry.figure_name.as_deref().unwrap_or("Figure"),
|
||
geometry.table_name.as_deref().unwrap_or("Table"),
|
||
geometry_counter(geometry, "figure"),
|
||
geometry_counter(geometry, "table"),
|
||
));
|
||
expand_float_lists(
|
||
&mut paragraphs,
|
||
geometry
|
||
.list_figure_name
|
||
.as_deref()
|
||
.unwrap_or("List of Figures"),
|
||
geometry
|
||
.list_table_name
|
||
.as_deref()
|
||
.unwrap_or("List of Tables"),
|
||
);
|
||
resolve_section_refs(&mut paragraphs, &references);
|
||
number_footnotes(&mut paragraphs);
|
||
resolve_citations(&mut paragraphs, &geometry.bibliography);
|
||
append_bibliography(
|
||
&mut paragraphs,
|
||
&geometry.bibliography,
|
||
geometry.ref_name.as_deref().unwrap_or("References"),
|
||
);
|
||
// Table-of-contents entries carry an invisible marker naming the heading
|
||
// whose page number they show; resolve it once the units exist.
|
||
let mut toc_targets: Vec<(usize, String)> = Vec::new();
|
||
let mut float_targets: Vec<(usize, String)> = Vec::new();
|
||
for (index, paragraph) in paragraphs.iter_mut().enumerate() {
|
||
if let Some(rest) = paragraph.text.trim_start().strip_prefix("\\texrratocpage{") {
|
||
if let Some((number, tail)) = rest.split_once('}') {
|
||
let number = number.trim().to_string();
|
||
paragraph.text = tail.trim_start().to_string();
|
||
toc_targets.push((index, number));
|
||
}
|
||
} else if let Some(rest) = paragraph
|
||
.text
|
||
.trim_start()
|
||
.strip_prefix("\\texrrafloatpage{")
|
||
{
|
||
if let Some((number, tail)) = rest.split_once('}') {
|
||
let number = number.trim().to_string();
|
||
paragraph.text = tail.trim_start().to_string();
|
||
float_targets.push((index, number));
|
||
}
|
||
}
|
||
}
|
||
let line_width = geometry.line_width.unwrap_or(480 * SCALE);
|
||
let base_units: Vec<Unit> = paragraphs
|
||
.iter()
|
||
.enumerate()
|
||
.map(|(index, paragraph)| {
|
||
if let Some(spec) = ¶graph.float {
|
||
let width = line_width;
|
||
let mut content = Vec::new();
|
||
let caption_unit = spec.caption.as_ref().map(|caption| {
|
||
let style = ParagraphStyle {
|
||
line_width: width,
|
||
centered: true,
|
||
par_indent: 0,
|
||
font_size: 9 * SCALE,
|
||
baselineskip: 11 * SCALE,
|
||
line_height: 11 * SCALE,
|
||
..ParagraphStyle::default()
|
||
};
|
||
Unit::paragraph_with_style_and_face(
|
||
index as u64,
|
||
caption.clone(),
|
||
style,
|
||
ParagraphFont::Roman,
|
||
)
|
||
});
|
||
if spec.kind == FloatKind::Table {
|
||
if let Some(caption) = &caption_unit {
|
||
content.extend(caption.items.clone());
|
||
}
|
||
}
|
||
let text_height = geometry
|
||
.textheight
|
||
.or(geometry.vsize)
|
||
.unwrap_or(550 * SCALE);
|
||
let resolve = |length: &ImageLength| length.resolve(width, text_height);
|
||
let mut placed_image = false;
|
||
if let Some(path) = &spec.image {
|
||
if let Some(image) = geometry.images.get(path) {
|
||
// Images have no intrinsic TeX resolution, so treat one
|
||
// pixel as one point at 100%.
|
||
let natural_width = (image.width as i64).max(1) * SCALE;
|
||
let natural_height = (image.height as i64).max(1) * SCALE;
|
||
let scale = spec.scale.unwrap_or(100).max(1);
|
||
let mut image_width = spec
|
||
.width
|
||
.as_ref()
|
||
.map(resolve)
|
||
.unwrap_or(natural_width.saturating_mul(scale) / 100);
|
||
let mut image_height =
|
||
spec.height.as_ref().map(resolve).unwrap_or_else(|| {
|
||
if spec.width.is_some() || spec.scale.is_some() {
|
||
(image_width * natural_height / natural_width).max(1)
|
||
} else {
|
||
natural_height.saturating_mul(scale) / 100
|
||
}
|
||
});
|
||
if spec.keep_aspectratio && spec.width.is_some() && spec.height.is_some() {
|
||
let scale = (image_width as f64 / natural_width as f64)
|
||
.min(image_height as f64 / natural_height as f64);
|
||
image_width = (natural_width as f64 * scale).round() as i64;
|
||
image_height = (natural_height as f64 * scale).round() as i64;
|
||
}
|
||
content.push(VerticalItem::Image {
|
||
width: image_width.max(1),
|
||
height: image_height.max(1),
|
||
image: image.clone(),
|
||
});
|
||
placed_image = true;
|
||
}
|
||
}
|
||
if !placed_image && (spec.height.is_some() || spec.width.is_some()) {
|
||
let rule_width = spec.width.as_ref().map(resolve).unwrap_or(width);
|
||
let rule_height = spec.height.as_ref().map(resolve).unwrap_or(rule_width / 2);
|
||
content.push(VerticalItem::Rule {
|
||
width: rule_width,
|
||
height: rule_height,
|
||
});
|
||
}
|
||
if let Some(table) = spec.table {
|
||
if let Some((template, source, target)) = geometry.tabular.get(table) {
|
||
let table_unit =
|
||
tabular_unit(&geometry, index as u64, template, source, *target);
|
||
content.extend(table_unit.items);
|
||
}
|
||
}
|
||
if spec.kind == FloatKind::Figure {
|
||
if let Some(caption) = &caption_unit {
|
||
content.extend(caption.items.clone());
|
||
}
|
||
}
|
||
let mut unit =
|
||
Unit::float_with_content(index as u64, spec.placement, width, 0, content);
|
||
unit.space_before = paragraph.space_before;
|
||
unit.space_stretch = paragraph.space_stretch;
|
||
unit.space_shrink = paragraph.space_shrink;
|
||
return unit;
|
||
}
|
||
if let Some(table) = table_reference(¶graph.text) {
|
||
if let Some((template, source, target)) = geometry.tabular.get(table) {
|
||
let mut unit = tabular_unit(&geometry, index as u64, template, source, *target);
|
||
unit.space_before = paragraph.space_before;
|
||
unit.space_stretch = paragraph.space_stretch;
|
||
unit.space_shrink = paragraph.space_shrink;
|
||
return unit;
|
||
}
|
||
}
|
||
if paragraph.math {
|
||
let font = Cmr10Metrics::Math;
|
||
let atom = if paragraph.multline {
|
||
let rows: Vec<MathAtom> = paragraph
|
||
.equation_rows
|
||
.iter()
|
||
.map(|row| parse_math(&row.text))
|
||
.collect();
|
||
let tag = paragraph.equation_rows.last().and_then(|row| {
|
||
row.tag
|
||
.clone()
|
||
.or_else(|| row.number.map(|number| format!("({number})")))
|
||
});
|
||
MathAtom::Multline { rows, tag }
|
||
} else if let Some(split_rows) = split_body_rows(¶graph.text) {
|
||
let rows: Vec<AlignedRow> = split_rows
|
||
.iter()
|
||
.map(|row| {
|
||
let cells: Vec<MathAtom> = row.split('&').map(aligned_cell).collect();
|
||
AlignedRow::new(cells, None)
|
||
})
|
||
.collect();
|
||
MathAtom::Aligned {
|
||
rows,
|
||
centered: false,
|
||
}
|
||
} else if paragraph.equation_rows.is_empty() {
|
||
parse_math(¶graph.text)
|
||
} else {
|
||
let rows: Vec<AlignedRow> = paragraph
|
||
.equation_rows
|
||
.iter()
|
||
.map(|row| {
|
||
let cells: Vec<MathAtom> = if paragraph.align_centered {
|
||
vec![aligned_cell(&row.text)]
|
||
} else {
|
||
row.text.split('&').map(aligned_cell).collect()
|
||
};
|
||
let tag = row
|
||
.tag
|
||
.clone()
|
||
.or_else(|| row.number.map(|number| format!("({number})")));
|
||
AlignedRow::new(cells, tag)
|
||
})
|
||
.collect();
|
||
MathAtom::Aligned {
|
||
rows,
|
||
centered: paragraph.align_centered,
|
||
}
|
||
};
|
||
let tag = paragraph.equation_tag.clone().or_else(|| {
|
||
paragraph
|
||
.equation_number
|
||
.map(|number| format!("({number})"))
|
||
});
|
||
let atom = match tag {
|
||
Some(tag) => MathAtom::Tagged {
|
||
body: Box::new(atom),
|
||
tag,
|
||
},
|
||
None => atom,
|
||
};
|
||
let lines = split_math_lines(&atom, &font, line_width);
|
||
let mut unit = Unit::math_lines(index as u64, &lines, &font);
|
||
unit.space_before = paragraph.space_before;
|
||
unit.space_stretch = paragraph.space_stretch;
|
||
unit.space_shrink = paragraph.space_shrink;
|
||
return unit;
|
||
}
|
||
let mut text = paragraph.text.clone();
|
||
let no_indent = text.trim_start().starts_with("\\noindent");
|
||
if no_indent {
|
||
text = text
|
||
.trim_start()
|
||
.trim_start_matches("\\noindent")
|
||
.trim_start()
|
||
.to_string();
|
||
}
|
||
let class_size = paragraph
|
||
.font_size
|
||
.or(geometry.base_font_size)
|
||
.unwrap_or(655_360);
|
||
let base_font_size = match paragraph.heading_level {
|
||
Some(level) => heading_font_size(level, class_size),
|
||
None => class_size,
|
||
};
|
||
let baselineskip = geometry
|
||
.baseline_skip
|
||
.unwrap_or_else(|| class_baselineskip(base_font_size));
|
||
let baselineskip = geometry
|
||
.linespread
|
||
.map(|spread| baselineskip.saturating_mul(spread) / 1000)
|
||
.unwrap_or(baselineskip);
|
||
let (left_skip, par_indent) = match paragraph.list_depth {
|
||
Some(_) => {
|
||
let indent = paragraph.left_skip * SCALE + geometry.left_skip.unwrap_or(0);
|
||
let hang = (paragraph.list_label + 5) * SCALE;
|
||
(indent + hang, -hang)
|
||
}
|
||
None => (
|
||
paragraph.left_skip * SCALE + geometry.left_skip.unwrap_or(0),
|
||
if no_indent {
|
||
0
|
||
} else {
|
||
geometry.par_indent.unwrap_or(0)
|
||
},
|
||
),
|
||
};
|
||
let style = ParagraphStyle {
|
||
line_width: paragraph.width.unwrap_or(line_width),
|
||
left_skip,
|
||
centered: paragraph.centered,
|
||
right_aligned: paragraph.right_aligned,
|
||
looseness: geometry.looseness.unwrap_or(0),
|
||
ragged_right: false,
|
||
right_skip: geometry.right_skip.unwrap_or(0) + paragraph.right_skip * SCALE,
|
||
hang_indent: geometry.hang_indent.unwrap_or(0),
|
||
hang_after: geometry.hang_after.unwrap_or(1) as i32,
|
||
par_shape: geometry.par_shape.clone(),
|
||
par_fillskip: geometry
|
||
.par_fillskip
|
||
.map(|(width, _, _)| width)
|
||
.unwrap_or(0),
|
||
par_fillskip_stretch: geometry
|
||
.par_fillskip
|
||
.map(|(_, stretch, _)| stretch)
|
||
.unwrap_or(0),
|
||
par_fillskip_fil: geometry.par_fillskip.map(|(_, _, fil)| fil).unwrap_or(true),
|
||
frenchspacing: geometry.french_spacing.unwrap_or(false),
|
||
space_factor_codes: geometry.space_factor_codes.clone(),
|
||
baselineskip,
|
||
lineskip: geometry.lineskip.unwrap_or(65536),
|
||
lineskiplimit: geometry.lineskiplimit.unwrap_or(0),
|
||
par_indent,
|
||
emergencystretch: geometry.emergency_stretch.unwrap_or(0),
|
||
pretolerance: geometry.pretolerance.unwrap_or(100),
|
||
tolerance: geometry.tolerance.unwrap_or(200),
|
||
hyphen_penalty: geometry.hyphen_penalty.unwrap_or(50),
|
||
ex_hyphen_penalty: geometry.ex_hyphen_penalty.unwrap_or(50),
|
||
double_hyphen_demerits: geometry.double_hyphen_demerits.unwrap_or(10_000),
|
||
final_hyphen_demerits: geometry.final_hyphen_demerits.unwrap_or(5_000),
|
||
line_penalty: geometry.line_penalty.unwrap_or(10),
|
||
adj_demerits: geometry.adj_demerits.unwrap_or(10_000),
|
||
hyphenation_exceptions: geometry.hyphenation_exceptions.clone(),
|
||
line_height: if paragraph.heading_level.is_some() {
|
||
base_font_size * 13 / 10
|
||
} else if paragraph.line_height == 12 {
|
||
baselineskip
|
||
} else {
|
||
paragraph.line_height * SCALE
|
||
},
|
||
font_size: base_font_size,
|
||
char_width: 10 * SCALE,
|
||
space_width: 4 * SCALE,
|
||
space_stretch: 6 * SCALE,
|
||
space_shrink: 2 * SCALE,
|
||
space_skip: geometry.space_skip,
|
||
xspace_skip: geometry.xspace_skip,
|
||
};
|
||
let plain = strip_hrefs(&text);
|
||
let mut unit = match inline_math_segments(&text, paragraph.font, &style) {
|
||
Some(segments) => Unit::paragraph_with_style_and_segments(
|
||
index as u64,
|
||
text.clone(),
|
||
style.clone(),
|
||
segments,
|
||
),
|
||
None => match inline_runs(&plain, paragraph.font) {
|
||
Some(runs) => Unit::paragraph_with_style_and_runs(
|
||
index as u64,
|
||
plain.clone(),
|
||
style,
|
||
runs,
|
||
),
|
||
None => Unit::paragraph_with_style_and_face(
|
||
index as u64,
|
||
plain,
|
||
style,
|
||
paragraph.font,
|
||
),
|
||
},
|
||
};
|
||
unit.space_before = paragraph.space_before;
|
||
unit.space_stretch = paragraph.space_stretch;
|
||
unit.space_shrink = paragraph.space_shrink;
|
||
unit
|
||
})
|
||
.collect();
|
||
// Footnotes follow their anchor paragraph as insertion units, so the page
|
||
// builder reserves room for them on the page that mentions them.
|
||
let mut units: Vec<Unit> = Vec::with_capacity(base_units.len());
|
||
let mut unit_for_paragraph = Vec::with_capacity(paragraphs.len());
|
||
let mut footnote_count = 0usize;
|
||
for (paragraph, unit) in paragraphs.iter().zip(base_units) {
|
||
unit_for_paragraph.push(units.len());
|
||
units.push(unit);
|
||
for (number, body) in ¶graph.footnotes {
|
||
footnote_count += 1;
|
||
let style = ParagraphStyle {
|
||
line_width,
|
||
font_size: 9 * SCALE,
|
||
par_indent: 0,
|
||
baselineskip: 11 * SCALE,
|
||
line_height: 11 * SCALE,
|
||
..ParagraphStyle::default()
|
||
};
|
||
let id = 1_000_000 + *number as u64;
|
||
let footnote = match inline_runs(body, ParagraphFont::Roman) {
|
||
Some(runs) => Unit::paragraph_with_style_and_runs(id, body.clone(), style, runs),
|
||
None => Unit::paragraph_with_style_and_face(
|
||
id,
|
||
body.clone(),
|
||
style,
|
||
ParagraphFont::Roman,
|
||
),
|
||
};
|
||
let height = footnote
|
||
.items
|
||
.iter()
|
||
.map(|item| match item {
|
||
VerticalItem::Paragraph(paragraph) => paragraph.height + paragraph.depth,
|
||
_ => 0,
|
||
})
|
||
.sum::<i64>();
|
||
units.push(Unit::insertion(id, 0, height, footnote.items));
|
||
}
|
||
}
|
||
for (index, number) in toc_targets {
|
||
let Some(target) = paragraphs
|
||
.iter()
|
||
.position(|paragraph| paragraph.heading_number.as_deref() == Some(number.as_str()))
|
||
else {
|
||
continue;
|
||
};
|
||
if let (Some(entry), Some(target)) = (
|
||
units.get_mut(unit_for_paragraph[index]),
|
||
unit_for_paragraph.get(target).copied(),
|
||
) {
|
||
entry.toc_target = Some(target as u64);
|
||
}
|
||
}
|
||
for (index, prefix) in float_targets {
|
||
let Some(target) = paragraphs.iter().position(|paragraph| {
|
||
paragraph
|
||
.float
|
||
.as_ref()
|
||
.and_then(|spec| spec.caption.as_deref())
|
||
.is_some_and(|caption| {
|
||
caption
|
||
.strip_prefix(&prefix)
|
||
.is_some_and(|rest| rest.starts_with(':'))
|
||
})
|
||
}) else {
|
||
continue;
|
||
};
|
||
if let (Some(entry), Some(target)) = (
|
||
units.get_mut(unit_for_paragraph[index]),
|
||
unit_for_paragraph.get(target).copied(),
|
||
) {
|
||
entry.toc_target = Some(target as u64);
|
||
}
|
||
}
|
||
let mut unit_by_number: HashMap<String, u64> = HashMap::new();
|
||
for (index, paragraph) in paragraphs.iter().enumerate() {
|
||
if let Some(number) = ¶graph.heading_number {
|
||
unit_by_number.insert(number.clone(), unit_for_paragraph[index] as u64);
|
||
}
|
||
}
|
||
for (label, number) in &label_numbers {
|
||
if let Some(unit) = unit_by_number.get(number) {
|
||
label_units.insert(label.clone(), *unit);
|
||
}
|
||
}
|
||
for (index, paragraph) in paragraphs.iter().enumerate() {
|
||
if let (Some(level), Some(_)) = (paragraph.heading_level, paragraph.heading_number.as_ref())
|
||
{
|
||
outline_units.push((
|
||
paragraph.text.clone(),
|
||
level,
|
||
unit_for_paragraph[index] as u64,
|
||
));
|
||
}
|
||
}
|
||
let mut document = Document::new(700 * SCALE, units);
|
||
if footnote_count > 0 {
|
||
document.insertion_classes.push(InsertionClass {
|
||
number: 0,
|
||
fraction_percent: 100,
|
||
max_height: None,
|
||
skip: Some(12 * SCALE),
|
||
multiplier: 1000,
|
||
});
|
||
document.insertion_skip = 12 * SCALE;
|
||
}
|
||
// LaTeX sets \maxdepth=.5\topskip; sources may override it later.
|
||
document.max_depth = 5 * SCALE;
|
||
document.text_width = line_width;
|
||
document.page_breaks = paragraphs
|
||
.iter()
|
||
.enumerate()
|
||
.filter(|(_, paragraph)| paragraph.page_break)
|
||
.map(|(index, _)| unit_for_paragraph[index])
|
||
.collect();
|
||
document
|
||
}
|
||
|
||
fn roman_page_number(mut number: usize, upper: bool) -> String {
|
||
const VALUES: [(usize, &str); 13] = [
|
||
(1000, "m"),
|
||
(900, "cm"),
|
||
(500, "d"),
|
||
(400, "cd"),
|
||
(100, "c"),
|
||
(90, "xc"),
|
||
(50, "l"),
|
||
(40, "xl"),
|
||
(10, "x"),
|
||
(9, "ix"),
|
||
(5, "v"),
|
||
(4, "iv"),
|
||
(1, "i"),
|
||
];
|
||
let mut text = String::new();
|
||
for (value, letters) in VALUES {
|
||
while number >= value {
|
||
text.push_str(letters);
|
||
number -= value;
|
||
}
|
||
}
|
||
if upper { text.to_uppercase() } else { text }
|
||
}
|
||
|
||
fn alphabetic_page_number(mut number: usize, upper: bool) -> String {
|
||
let mut letters = Vec::new();
|
||
while number > 0 {
|
||
let remainder = (number - 1) % 26;
|
||
letters.push(b'a' + remainder as u8);
|
||
number = (number - 1) / 26;
|
||
}
|
||
letters.reverse();
|
||
let text = String::from_utf8(letters).unwrap_or_default();
|
||
if upper { text.to_uppercase() } else { text }
|
||
}
|
||
|
||
fn page_number_text(index: usize, style: &str, start: u32) -> String {
|
||
let number = index + 1 + start as usize;
|
||
match style {
|
||
"roman" => roman_page_number(number, false),
|
||
"Roman" => roman_page_number(number, true),
|
||
"alph" => alphabetic_page_number(number, false),
|
||
"Alph" => alphabetic_page_number(number, true),
|
||
_ => number.to_string(),
|
||
}
|
||
}
|
||
|
||
/// Paint the LaTeX page number centred in the footer of every page.
|
||
fn stamp_page_numbers(
|
||
lists: &mut [DisplayList],
|
||
page_goal: i64,
|
||
paper_width: i64,
|
||
paper_height: i64,
|
||
style: &str,
|
||
start: u32,
|
||
skip_first: bool,
|
||
) {
|
||
let size = 10 * SCALE;
|
||
let baseline = (page_goal + 36 * SCALE).min(paper_height - 24 * SCALE);
|
||
for (index, list) in lists.iter_mut().enumerate() {
|
||
if skip_first && index == 0 {
|
||
continue;
|
||
}
|
||
let text = page_number_text(index, style, start);
|
||
let width: i64 = text
|
||
.chars()
|
||
.map(|character| Cmr10Metrics::Roman.width(character))
|
||
.sum();
|
||
let x = ((paper_width - width) / 2).max(0);
|
||
list.push(DisplayItem::Text {
|
||
x,
|
||
y: baseline,
|
||
size,
|
||
text,
|
||
font: FontFace::Roman,
|
||
});
|
||
}
|
||
}
|
||
|
||
/// Fill in table-of-contents page numbers from a laid-out engine. Returns
|
||
/// true when at least one entry changed and the document needs re-layout.
|
||
fn text_width_roman(text: &str) -> i64 {
|
||
let metrics = Cmr10Metrics::Roman;
|
||
text.chars()
|
||
.map(|character| match character {
|
||
' ' => metrics.space(),
|
||
_ => metrics.width(character),
|
||
})
|
||
.sum()
|
||
}
|
||
|
||
/// Fill the space between entry text and page number with dot leaders.
|
||
fn toc_leader(head: &str, number: &str, measure: i64) -> Option<String> {
|
||
let metrics = Cmr10Metrics::Roman;
|
||
let head_width = text_width_roman(head);
|
||
let number_width = text_width_roman(number);
|
||
let dot = metrics.width('.');
|
||
let space = metrics.space();
|
||
if dot <= 0 || measure <= 0 {
|
||
return None;
|
||
}
|
||
let room = measure - head_width - number_width - 2 * space;
|
||
let count = room / dot;
|
||
if count < 4 {
|
||
return None;
|
||
}
|
||
Some(format!("{head} {} {number}", ".".repeat(count as usize)))
|
||
}
|
||
|
||
fn stamp_toc_pages(document: &mut Document, engine: &Engine, geometry: &PageGeometry) -> bool {
|
||
let mut page_of = std::collections::HashMap::new();
|
||
for (index, page) in engine.pages().iter().enumerate() {
|
||
for (unit, _) in &page.sources {
|
||
page_of.entry(*unit).or_insert(index);
|
||
}
|
||
}
|
||
let numbering = geometry.page_numbering.as_deref().unwrap_or("arabic");
|
||
let updates: Vec<(u64, String)> = document
|
||
.units
|
||
.iter()
|
||
.filter(|unit| unit.toc_target.is_some() && !unit.toc_stamped)
|
||
.filter_map(|unit| {
|
||
let target = unit.toc_target?;
|
||
let page = page_of.get(&target)?;
|
||
let page_number = page_number_text(*page, numbering, geometry.page_start);
|
||
let measure = unit
|
||
.paragraph_style
|
||
.as_ref()
|
||
.map(|style| {
|
||
(style.line_width - style.left_skip - style.right_skip - style.par_indent)
|
||
.max(1)
|
||
})
|
||
.unwrap_or(0);
|
||
let source = toc_leader(unit.source.trim_end(), &page_number, measure)
|
||
.unwrap_or_else(|| format!("{} \\hfill {}", unit.source.trim_end(), page_number));
|
||
Some((unit.id, source))
|
||
})
|
||
.collect();
|
||
let mut changed = false;
|
||
for (id, source) in updates {
|
||
let Some(index) = document.units.iter().position(|unit| unit.id == id) else {
|
||
continue;
|
||
};
|
||
let Some(style) = document.units[index].paragraph_style.clone() else {
|
||
continue;
|
||
};
|
||
let font = document.units[index]
|
||
.items
|
||
.iter()
|
||
.find_map(|item| match item {
|
||
VerticalItem::Paragraph(paragraph) => Some(paragraph.font),
|
||
_ => None,
|
||
})
|
||
.unwrap_or(ParagraphFont::Roman);
|
||
let previous = &document.units[index];
|
||
let mut replacement = Unit::paragraph_with_style_and_face(id, source, style, font);
|
||
replacement.space_before = previous.space_before;
|
||
replacement.space_stretch = previous.space_stretch;
|
||
replacement.space_shrink = previous.space_shrink;
|
||
replacement.toc_target = previous.toc_target;
|
||
replacement.toc_stamped = true;
|
||
document.units[index] = replacement;
|
||
changed = true;
|
||
}
|
||
changed
|
||
}
|
||
|
||
/// Environments route-D knows how to lay out (starred variants are normalised).
|
||
const SUPPORTED_ENVIRONMENTS: &[&str] = &[
|
||
"document",
|
||
"itemize",
|
||
"enumerate",
|
||
"description",
|
||
"quote",
|
||
"quotation",
|
||
"verse",
|
||
"abstract",
|
||
"figure",
|
||
"table",
|
||
"center",
|
||
"flushleft",
|
||
"flushright",
|
||
"minipage",
|
||
"verbatim",
|
||
"tabular",
|
||
"longtable",
|
||
"tabularx",
|
||
"displaymath",
|
||
"math",
|
||
"equation",
|
||
"align",
|
||
"gather",
|
||
"cases",
|
||
"split",
|
||
"alignat",
|
||
"multline",
|
||
"matrix",
|
||
"pmatrix",
|
||
"bmatrix",
|
||
"Bmatrix",
|
||
"vmatrix",
|
||
"Vmatrix",
|
||
"array",
|
||
"thebibliography",
|
||
"theorem",
|
||
"lemma",
|
||
"corollary",
|
||
"proposition",
|
||
"definition",
|
||
"example",
|
||
"remark",
|
||
"proof",
|
||
];
|
||
|
||
/// Report environments that route-D would otherwise leave as literal text.
|
||
fn source_warnings(source: &str) -> Vec<String> {
|
||
let mut warnings = Vec::new();
|
||
let mut rest = source;
|
||
while let Some(index) = rest.find("\\begin{") {
|
||
let after = &rest[index + "\\begin{".len()..];
|
||
let Some(close) = after.find('}') else {
|
||
break;
|
||
};
|
||
let name = after[..close].trim();
|
||
let normalized = name.trim_end_matches('*');
|
||
if !SUPPORTED_ENVIRONMENTS.contains(&normalized) {
|
||
let message = format!("unsupported environment `{name}`");
|
||
if !warnings.contains(&message) {
|
||
warnings.push(message);
|
||
}
|
||
}
|
||
rest = &after[close + 1..];
|
||
}
|
||
warnings
|
||
}
|
||
|
||
/// Report control words that survived layout as literal backslash glyphs.
|
||
fn document_warnings(document: &Document) -> Vec<String> {
|
||
let mut warnings = Vec::new();
|
||
for unit in &document.units {
|
||
for item in &unit.items {
|
||
let VerticalItem::Paragraph(paragraph) = item else {
|
||
continue;
|
||
};
|
||
for line in ¶graph.lines {
|
||
let mut index = 0;
|
||
while index < line.len() {
|
||
if let HorizontalItem::Box(box_) = &line[index] {
|
||
if box_.character == Some('\\') {
|
||
let mut name = String::new();
|
||
let mut next = index + 1;
|
||
while let Some(HorizontalItem::Box(next_box)) = line.get(next) {
|
||
match next_box.character {
|
||
Some(character) if character.is_ascii_alphabetic() => {
|
||
name.push(character);
|
||
next += 1;
|
||
}
|
||
_ => break,
|
||
}
|
||
}
|
||
let message = if name.is_empty() {
|
||
"unsupported command near a backslash".to_string()
|
||
} else {
|
||
format!("unsupported command `\\{name}`")
|
||
};
|
||
if !warnings.contains(&message) {
|
||
warnings.push(message);
|
||
}
|
||
}
|
||
}
|
||
index += 1;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
warnings.truncate(20);
|
||
warnings
|
||
}
|
||
|
||
fn render_json(
|
||
document: &Document,
|
||
engine: &Engine,
|
||
edit: Option<(&[usize], usize)>,
|
||
geometry: &PageGeometry,
|
||
warnings: &[String],
|
||
) -> String {
|
||
let mut document = document.clone();
|
||
let relaid = if stamp_toc_pages(&mut document, engine, geometry) {
|
||
Some(layout_document(&document))
|
||
} else {
|
||
None
|
||
};
|
||
let engine = relaid.as_ref().unwrap_or(engine);
|
||
let document = &document;
|
||
let mut json = String::new();
|
||
let page_width_mm = document.paper_width as f64 / SCALE as f64 * 25.4 / 72.0;
|
||
let page_height_mm = document.paper_height as f64 / SCALE as f64 * 25.4 / 72.0;
|
||
let page_height_pt = document.paper_height as f64 / SCALE as f64;
|
||
let _ = write!(
|
||
json,
|
||
"{{\"status\":\"ok\",\"pageWidthMm\":{page_width_mm:.2},\"pageHeightMm\":{page_height_mm:.2},\"pages\":["
|
||
);
|
||
let mut lists: Vec<DisplayList> = engine
|
||
.pages()
|
||
.iter()
|
||
.map(|page| {
|
||
let mut list =
|
||
page.display_list_with_layout(document.page_goal, document.text_float_sep);
|
||
list.width = list.width.max(document.paper_width);
|
||
list.height = list.height.max(document.paper_height);
|
||
list
|
||
})
|
||
.collect();
|
||
if !geometry.suppress_page_numbers {
|
||
let style = geometry.page_numbering.as_deref().unwrap_or("arabic");
|
||
stamp_page_numbers(
|
||
&mut lists,
|
||
document.page_goal,
|
||
document.paper_width,
|
||
document.paper_height,
|
||
style,
|
||
geometry.page_start,
|
||
geometry.suppress_first_page_number,
|
||
);
|
||
}
|
||
for (index, (page, mut list)) in engine.pages().iter().zip(lists).enumerate() {
|
||
list.place(document.h_offset, document.v_offset);
|
||
if index > 0 {
|
||
json.push(',');
|
||
}
|
||
let _ = write!(
|
||
json,
|
||
"{{\"index\":{index},\"hash\":\"{:016x}\",\"svg\":\"{}\"}}",
|
||
page.hash,
|
||
escape_json(&list.to_svg())
|
||
);
|
||
}
|
||
let _ = write!(json, "],\"pageCount\":{}", engine.pages().len());
|
||
if let Some((changed, recomputed)) = edit {
|
||
let _ = write!(
|
||
json,
|
||
",\"changedPages\":{:?},\"recomputedPages\":{recomputed}",
|
||
changed
|
||
);
|
||
}
|
||
let _ = write!(json, ",\"warnings\":[");
|
||
for (index, warning) in warnings.iter().enumerate() {
|
||
if index > 0 {
|
||
json.push(',');
|
||
}
|
||
let _ = write!(json, "\"{}\"", escape_json(warning));
|
||
}
|
||
json.push(']');
|
||
let _ = write!(json, ",\"pageHeightPt\":{page_height_pt:.0}}}");
|
||
json
|
||
}
|
||
|
||
fn escape_json(value: &str) -> String {
|
||
let mut escaped = String::with_capacity(value.len());
|
||
for character in value.chars() {
|
||
match character {
|
||
'"' => escaped.push_str("\\\""),
|
||
'\\' => escaped.push_str("\\\\"),
|
||
'\n' => escaped.push_str("\\n"),
|
||
'\r' => escaped.push_str("\\r"),
|
||
'\t' => escaped.push_str("\\t"),
|
||
character if character < '\u{20}' => {
|
||
let _ = write!(escaped, "\\u{:04x}", character as u32);
|
||
}
|
||
character => escaped.push(character),
|
||
}
|
||
}
|
||
escaped
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
|
||
#[test]
|
||
fn display_math_is_split_to_the_measure() {
|
||
let mut formula = String::from("$$");
|
||
for index in 0..80 {
|
||
if index > 0 {
|
||
formula.push_str(" + ");
|
||
}
|
||
formula.push('x');
|
||
}
|
||
formula.push_str(" = z$$");
|
||
let (body, geometry) = geometry_and_body(&formula);
|
||
let paragraphs = paragraphs(&body).unwrap();
|
||
let document = build_document(¶graphs, &geometry);
|
||
assert!(
|
||
document.units[0].items.len() > 1,
|
||
"items={}",
|
||
document.units[0].items.len()
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn size_commands_set_the_paragraph_font_size() {
|
||
let (body, geometry) = geometry_and_body("\\large Big text");
|
||
let paragraphs = paragraphs(&body).unwrap();
|
||
let document = build_document(¶graphs, &geometry);
|
||
let unit = &document.units[0];
|
||
assert_eq!(unit.paragraph_style.as_ref().unwrap().font_size, 12 * SCALE);
|
||
assert_eq!(unit.source, "Big text");
|
||
}
|
||
|
||
#[test]
|
||
fn fontsize_sets_the_exact_paragraph_size() {
|
||
let (body, geometry) = geometry_and_body("\\fontsize{20pt}{24pt}\\selectfont Huge text");
|
||
let paragraphs = paragraphs(&body).unwrap();
|
||
let document = build_document(¶graphs, &geometry);
|
||
let unit = &document.units[0];
|
||
assert_eq!(unit.paragraph_style.as_ref().unwrap().font_size, 20 * SCALE);
|
||
assert_eq!(unit.source, "Huge text");
|
||
}
|
||
|
||
#[test]
|
||
fn arraystretch_scales_tabular_rows() {
|
||
let source = "\\renewcommand{\\arraystretch}{2}\n\n\\begin{tabular}{ll}\nA & B \\\\\nC & D\n\\end{tabular}";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
assert_eq!(geometry.array_stretch, Some(2000));
|
||
let blocks =
|
||
paragraphs_with_definitions(&body, &geometry.theorem_definitions).expect("paragraphs");
|
||
let document = build_document(&blocks, &geometry);
|
||
let halign = document
|
||
.units
|
||
.iter()
|
||
.flat_map(|unit| &unit.items)
|
||
.find_map(|item| match item {
|
||
VerticalItem::Halign(halign) => Some(halign),
|
||
_ => None,
|
||
})
|
||
.expect("tabular halign");
|
||
assert_eq!(halign.line_height, 24 * SCALE);
|
||
assert_eq!(halign.height, 48 * SCALE);
|
||
}
|
||
|
||
#[test]
|
||
fn abstract_names_follow_renewcommand() {
|
||
let source = "\\renewcommand{\\abstractname}{Zusammenfassung}\n\n\\begin{abstract}\nBody text.\n\\end{abstract}";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
assert_eq!(geometry.abstract_name.as_deref(), Some("Zusammenfassung"));
|
||
assert!(!body.contains("abstractname"));
|
||
let paragraphs =
|
||
paragraphs_with_definitions(&body, &geometry.theorem_definitions).expect("paragraphs");
|
||
let document = build_document(¶graphs, &geometry);
|
||
assert!(
|
||
document
|
||
.units
|
||
.iter()
|
||
.any(|unit| unit.source.contains("Zusammenfassung"))
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn float_names_follow_renewcommand() {
|
||
let source =
|
||
"\\renewcommand{\\figurename}{Fig.}\n\n\\begin{figure}\n\\caption{A}\n\\end{figure}";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
assert_eq!(geometry.figure_name.as_deref(), Some("Fig."));
|
||
assert!(!body.contains("figurename"));
|
||
let mut blocks =
|
||
paragraphs_with_definitions(&body, &geometry.theorem_definitions).expect("paragraphs");
|
||
number_floats(
|
||
&mut blocks,
|
||
geometry.figure_name.as_deref().unwrap_or("Figure"),
|
||
geometry.table_name.as_deref().unwrap_or("Table"),
|
||
0,
|
||
0,
|
||
);
|
||
let caption = blocks[0]
|
||
.float
|
||
.as_ref()
|
||
.and_then(|spec| spec.caption.as_deref());
|
||
assert_eq!(caption, Some("Fig. 1: A"));
|
||
|
||
let source =
|
||
"\\renewcommand{\\tablename}{Tab.}\n\n\\begin{table}\n\\caption{B}\n\\end{table}";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
assert_eq!(geometry.table_name.as_deref(), Some("Tab."));
|
||
let mut blocks =
|
||
paragraphs_with_definitions(&body, &geometry.theorem_definitions).expect("paragraphs");
|
||
number_floats(
|
||
&mut blocks,
|
||
geometry.figure_name.as_deref().unwrap_or("Figure"),
|
||
geometry.table_name.as_deref().unwrap_or("Table"),
|
||
0,
|
||
0,
|
||
);
|
||
let caption = blocks[0]
|
||
.float
|
||
.as_ref()
|
||
.and_then(|spec| spec.caption.as_deref());
|
||
assert_eq!(caption, Some("Tab. 1: B"));
|
||
}
|
||
|
||
#[test]
|
||
fn tabcolsep_sets_tabular_column_glue() {
|
||
let source = "\\tabcolsep=20pt\n\n\\begin{tabular}{ll}\nA & B \\\\\nC & D\n\\end{tabular}";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
assert_eq!(geometry.tab_col_sep, Some(20 * SCALE));
|
||
assert!(!body.contains("tabcolsep"));
|
||
let blocks =
|
||
paragraphs_with_definitions(&body, &geometry.theorem_definitions).expect("paragraphs");
|
||
let document = build_document(&blocks, &geometry);
|
||
let halign = document
|
||
.units
|
||
.iter()
|
||
.flat_map(|unit| &unit.items)
|
||
.find_map(|item| match item {
|
||
VerticalItem::Halign(halign) => Some(halign),
|
||
_ => None,
|
||
})
|
||
.expect("tabular halign");
|
||
assert_eq!(halign.column_skips, vec![20 * SCALE]);
|
||
let columns: i64 = halign.column_widths.iter().sum();
|
||
assert_eq!(halign.width, columns + 20 * SCALE);
|
||
|
||
let (_, default) = geometry_and_body("\\begin{tabular}{ll}\nA & B\n\\end{tabular}");
|
||
assert_eq!(default.tab_col_sep, None);
|
||
let blocks = paragraphs_with_definitions("\\texrratable{0}", &default.theorem_definitions)
|
||
.expect("paragraphs");
|
||
let document = build_document(&blocks, &default);
|
||
let halign = document
|
||
.units
|
||
.iter()
|
||
.flat_map(|unit| &unit.items)
|
||
.find_map(|item| match item {
|
||
VerticalItem::Halign(halign) => Some(halign),
|
||
_ => None,
|
||
})
|
||
.expect("tabular halign");
|
||
assert!(halign.column_skips.is_empty());
|
||
let columns: i64 = halign.column_widths.iter().sum();
|
||
assert_eq!(halign.width, columns + 6 * SCALE);
|
||
}
|
||
|
||
#[test]
|
||
fn linespread_scales_the_class_baseline() {
|
||
let source = "\\documentclass{article}\n\\linespread{1.5}\n\nBody text.";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
assert_eq!(geometry.linespread, Some(1500));
|
||
assert!(!body.contains("linespread"));
|
||
let blocks =
|
||
paragraphs_with_definitions(&body, &geometry.theorem_definitions).expect("paragraphs");
|
||
let document = build_document(&blocks, &geometry);
|
||
let style = document.units[0]
|
||
.paragraph_style
|
||
.clone()
|
||
.expect("paragraph style");
|
||
assert_eq!(style.baselineskip, 18 * SCALE);
|
||
|
||
let (_, clamped) = geometry_and_body("\\linespread{9}\n\nBody text.");
|
||
assert_eq!(clamped.linespread, Some(5000));
|
||
|
||
let (_, renamed) =
|
||
geometry_and_body("\\renewcommand{\\baselinestretch}{1.25}\n\nBody text.");
|
||
assert_eq!(renamed.linespread, Some(1250));
|
||
}
|
||
|
||
#[test]
|
||
fn documentclass_size_options_set_the_base_size() {
|
||
let source =
|
||
"\\documentclass[12pt]{article}\n\\begin{document}\n\nPlain text\n\n\\end{document}";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
assert_eq!(geometry.base_font_size, Some(12 * SCALE));
|
||
let paragraphs = paragraphs(&body).unwrap();
|
||
let document = build_document(¶graphs, &geometry);
|
||
let style = document.units[0].paragraph_style.as_ref().unwrap();
|
||
assert_eq!(style.font_size, 12 * SCALE);
|
||
assert_eq!(style.baselineskip, 14 * 65_536 + 32_768);
|
||
}
|
||
|
||
#[test]
|
||
fn explicit_size_commands_override_the_class_size() {
|
||
let source = "\\documentclass[12pt]{article}\n\\begin{document}\n\n\\small Small text\n\n\\end{document}";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
let paragraphs = paragraphs(&body).unwrap();
|
||
let document = build_document(¶graphs, &geometry);
|
||
let style = document.units[0].paragraph_style.as_ref().unwrap();
|
||
assert_eq!(style.font_size, 9 * SCALE);
|
||
}
|
||
|
||
#[test]
|
||
fn documentclass_defaults_to_ten_point() {
|
||
let source = "\\documentclass{article}\n\\begin{document}\n\nPlain text\n\n\\end{document}";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
let paragraphs = paragraphs(&body).unwrap();
|
||
let document = build_document(¶graphs, &geometry);
|
||
let style = document.units[0].paragraph_style.as_ref().unwrap();
|
||
assert_eq!(style.font_size, 10 * SCALE);
|
||
assert_eq!(style.baselineskip, 12 * 65_536);
|
||
}
|
||
|
||
#[test]
|
||
fn engine_template_keeps_paragraph_columns() {
|
||
assert_eq!(engine_template("{|l|c|p{3cm}|}"), "|l|c|p{3cm}|");
|
||
assert_eq!(engine_template("|p{2cm}|r|"), "|p{2cm}|r|");
|
||
assert_eq!(engine_template("*{3}{c}"), "ccc");
|
||
assert_eq!(engine_template("|*{3}{c|}"), "|c|c|c|");
|
||
assert_eq!(engine_template("*{2}{p{2cm}}"), "p{2cm}p{2cm}");
|
||
assert_eq!(engine_template(""), "l");
|
||
}
|
||
|
||
fn multi_page_source() -> String {
|
||
let mut source = String::from("\\documentclass{article}\n\\begin{document}\n\n");
|
||
for index in 0..36 {
|
||
source.push_str(&format!("Paragraph {index:02} "));
|
||
for _ in 0..4 {
|
||
source.push_str(
|
||
"lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor. ",
|
||
);
|
||
}
|
||
source.push_str("\n\n");
|
||
}
|
||
source.push_str("\\end{document}\n");
|
||
source
|
||
}
|
||
|
||
#[test]
|
||
fn multi_paragraph_edits_reuse_earlier_pages() {
|
||
let source = multi_page_source();
|
||
let first = project_preview_json("route-d-multi-edit", &source).expect("first preview");
|
||
let first: serde_json::Value = serde_json::from_str(&first).expect("first JSON");
|
||
let page_count = first["pageCount"].as_u64().expect("page count");
|
||
assert!(
|
||
page_count >= 2,
|
||
"expected a multi-page preview, got {page_count}"
|
||
);
|
||
|
||
let edited = source
|
||
.replace("Paragraph 30 ", "Paragraph 30 changed ")
|
||
.replace("Paragraph 33 ", "Paragraph 33 changed ");
|
||
let second = project_preview_json("route-d-multi-edit", &edited).expect("edited preview");
|
||
let second: serde_json::Value = serde_json::from_str(&second).expect("edited JSON");
|
||
assert!(
|
||
second["changedPages"]
|
||
.as_array()
|
||
.is_some_and(|pages| !pages.is_empty())
|
||
);
|
||
let recomputed = second["recomputedPages"].as_u64().expect("recomputed");
|
||
assert!(recomputed < page_count, "changed pages should be a subset");
|
||
}
|
||
|
||
#[test]
|
||
fn structural_edit_keeps_pages_before_the_inserted_paragraph() {
|
||
let source = multi_page_source();
|
||
let first =
|
||
project_preview_json("route-d-structural-edit", &source).expect("first preview");
|
||
let first: serde_json::Value = serde_json::from_str(&first).expect("first JSON");
|
||
let first_hash = first["pages"][0]["hash"].as_str().expect("first hash");
|
||
|
||
let inserted = source.replacen(
|
||
"Paragraph 21 ",
|
||
"Paragraph inserted before twenty-one with enough words to make a line.\n\nParagraph 21 ",
|
||
1,
|
||
);
|
||
let second =
|
||
project_preview_json("route-d-structural-edit", &inserted).expect("inserted preview");
|
||
let second: serde_json::Value = serde_json::from_str(&second).expect("second JSON");
|
||
assert_eq!(
|
||
second["pages"][0]["hash"].as_str().expect("second hash"),
|
||
first_hash
|
||
);
|
||
let page_count = second["pageCount"].as_u64().expect("page count");
|
||
assert!(
|
||
second["changedPages"]
|
||
.as_array()
|
||
.is_some_and(|pages| !pages.is_empty())
|
||
);
|
||
assert!(
|
||
second["recomputedPages"].as_u64().expect("recomputed") < page_count,
|
||
"the unchanged prefix should not be recomputed"
|
||
);
|
||
}
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod source_tests {
|
||
use super::*;
|
||
|
||
#[test]
|
||
fn footnotes_become_page_insertions() {
|
||
let blocks = paragraphs("Body\\footnote{Note} tail").unwrap();
|
||
let document = build_document(&blocks, &PageGeometry::default());
|
||
assert_eq!(document.units.len(), 2);
|
||
assert_eq!(document.units[0].source, "Body (1) tail");
|
||
let Some(VerticalItem::Insertion(insertion)) = document.units[1].items.first() else {
|
||
panic!("expected an insertion unit");
|
||
};
|
||
assert_eq!(insertion.class, 0);
|
||
assert!(insertion.height > 0);
|
||
assert_eq!(document.insertion_classes.len(), 1);
|
||
let engine = Engine::layout_paged(&document).expect("paged layout");
|
||
assert_eq!(engine.pages().len(), 1);
|
||
assert_eq!(engine.pages()[0].insertions.len(), 1);
|
||
let list =
|
||
engine.pages()[0].display_list_with_layout(document.page_goal, document.text_float_sep);
|
||
assert!(list.items.iter().any(|item| {
|
||
matches!(item, texrra_tex_core::DisplayItem::Text { text, .. } if text == "N")
|
||
}));
|
||
}
|
||
|
||
#[test]
|
||
fn float_placement_options_follow_the_spec() {
|
||
for (spec, placement) in [
|
||
("[htbp]", FloatPlacement::Here),
|
||
("[!t]", FloatPlacement::Top),
|
||
("[b]", FloatPlacement::Bottom),
|
||
("[H]", FloatPlacement::Here),
|
||
("[]", FloatPlacement::Top),
|
||
] {
|
||
let source = format!("\\begin{{figure}}{}\n\\caption{{A}}\n\\end{{figure}}", spec);
|
||
let blocks = paragraphs(&source).expect("paragraphs");
|
||
assert_eq!(
|
||
blocks[0].float.as_ref().expect("float").placement,
|
||
placement,
|
||
"spec {spec}"
|
||
);
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn figures_become_float_units() {
|
||
let source = "\\begin{figure}[h]\n\\caption{A caption}\\label{fig:a}\n\\end{figure}";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
let blocks = paragraphs(&body).unwrap();
|
||
let document = build_document(&blocks, &geometry);
|
||
assert_eq!(document.units.len(), 1);
|
||
let Some(VerticalItem::Float(float)) = document.units[0].items.first() else {
|
||
panic!("expected a float unit");
|
||
};
|
||
assert_eq!(float.placement, FloatPlacement::Here);
|
||
let mut caption = String::new();
|
||
for item in &float.content {
|
||
if let VerticalItem::Paragraph(paragraph) = item {
|
||
for line in ¶graph.lines {
|
||
for item in line {
|
||
match item {
|
||
texrra_tex_core::paragraph::HorizontalItem::Box(box_) => {
|
||
if let Some(character) = box_.character {
|
||
caption.push(character);
|
||
}
|
||
}
|
||
texrra_tex_core::paragraph::HorizontalItem::Glue { width, .. } => {
|
||
if *width > 0 {
|
||
caption.push(' ');
|
||
}
|
||
}
|
||
_ => {}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
assert_eq!(caption, "Figure 1: A caption");
|
||
}
|
||
|
||
#[test]
|
||
fn figure_labels_resolve_references() {
|
||
let source = "See \\ref{fig:a}.\n\n\\begin{figure}\n\\caption{Caption}\n\\label{fig:a}\n\\end{figure}";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
let blocks = paragraphs(&body).unwrap();
|
||
let document = build_document(&blocks, &geometry);
|
||
assert_eq!(document.units[0].source, "See 1.");
|
||
}
|
||
|
||
#[test]
|
||
fn standalone_graphics_place_image_items() {
|
||
let source = "\\includegraphics[width=100pt]{pixel.bmp}";
|
||
let blocks = paragraphs(source).expect("paragraphs");
|
||
let (_, mut geometry) = geometry_and_body(source);
|
||
geometry.images.insert(
|
||
"pixel.bmp".to_string(),
|
||
RasterImage {
|
||
width: 2,
|
||
height: 2,
|
||
rgb: vec![0; 12],
|
||
},
|
||
);
|
||
let document = build_document(&blocks, &geometry);
|
||
let image = document
|
||
.units
|
||
.iter()
|
||
.flat_map(|unit| unit.items.iter())
|
||
.find_map(|item| match item {
|
||
VerticalItem::Float(float) => {
|
||
float.content.iter().find_map(|content| match content {
|
||
VerticalItem::Image { width, height, .. } => Some((*width, *height)),
|
||
_ => None,
|
||
})
|
||
}
|
||
_ => None,
|
||
})
|
||
.expect("image item inside the graphic float");
|
||
assert_eq!(image.0, 100 * SCALE);
|
||
assert_eq!(image.1, 100 * SCALE);
|
||
}
|
||
|
||
#[test]
|
||
fn standalone_graphics_become_in_text_floats() {
|
||
let blocks = paragraphs("\\includegraphics[width=100pt]{pixel.bmp}").expect("paragraphs");
|
||
assert_eq!(blocks.len(), 1);
|
||
let spec = blocks[0].float.as_ref().expect("graphic float");
|
||
assert_eq!(spec.placement, FloatPlacement::Here);
|
||
assert_eq!(spec.image.as_deref(), Some("pixel.bmp"));
|
||
assert_eq!(spec.width, Some(ImageLength::Absolute(100 * SCALE)));
|
||
assert!(spec.caption.is_none());
|
||
}
|
||
|
||
#[test]
|
||
fn figure_graphics_place_decoded_images() {
|
||
let blocks = paragraphs(
|
||
"\\begin{figure}[t]\n\\includegraphics[width=120pt]{plot.png}\n\\caption{Plot}\n\\end{figure}",
|
||
)
|
||
.expect("paragraphs");
|
||
let mut geometry = PageGeometry::default();
|
||
geometry.images.insert(
|
||
"plot.png".to_string(),
|
||
RasterImage {
|
||
width: 200,
|
||
height: 100,
|
||
rgb: vec![7; 200 * 100 * 3],
|
||
},
|
||
);
|
||
let document = build_document(&blocks, &geometry);
|
||
let image = document
|
||
.units
|
||
.iter()
|
||
.flat_map(|unit| &unit.items)
|
||
.find_map(|item| match item {
|
||
VerticalItem::Float(float) => {
|
||
float.content.iter().find_map(|content| match content {
|
||
VerticalItem::Image {
|
||
width,
|
||
height,
|
||
image,
|
||
} => Some((*width, *height, image.clone())),
|
||
_ => None,
|
||
})
|
||
}
|
||
_ => None,
|
||
})
|
||
.expect("decoded image in the float");
|
||
assert_eq!(image.0, 120 * SCALE);
|
||
assert_eq!(image.1, 60 * SCALE);
|
||
assert_eq!(image.2.width, 200);
|
||
assert_eq!(image.2.rgb.len(), 200 * 100 * 3);
|
||
}
|
||
|
||
#[test]
|
||
fn graphics_options_size_the_image() {
|
||
let mut geometry = PageGeometry::default();
|
||
geometry.line_width = Some(480 * SCALE);
|
||
geometry.textheight = Some(600 * SCALE);
|
||
geometry.images.insert(
|
||
"plot.png".to_string(),
|
||
RasterImage {
|
||
width: 200,
|
||
height: 100,
|
||
rgb: vec![9; 200 * 100 * 3],
|
||
},
|
||
);
|
||
let cases = [
|
||
("width=0.5\\textwidth", (240 * SCALE, 120 * SCALE)),
|
||
(
|
||
"width=100pt,height=100pt,keepaspectratio",
|
||
(100 * SCALE, 50 * SCALE),
|
||
),
|
||
("scale=0.5", (100 * SCALE, 50 * SCALE)),
|
||
("", (200 * SCALE, 100 * SCALE)),
|
||
];
|
||
for (options, expected) in cases {
|
||
let source = format!(
|
||
"\\begin{{figure}}[t]\n\\includegraphics[{options}]{{plot.png}}\n\\end{{figure}}"
|
||
);
|
||
let blocks = paragraphs(&source).expect("paragraphs");
|
||
let document = build_document(&blocks, &geometry);
|
||
let image = document
|
||
.units
|
||
.iter()
|
||
.flat_map(|unit| &unit.items)
|
||
.find_map(|item| match item {
|
||
VerticalItem::Float(float) => {
|
||
float.content.iter().find_map(|content| match content {
|
||
VerticalItem::Image { width, height, .. } => Some((*width, *height)),
|
||
_ => None,
|
||
})
|
||
}
|
||
_ => None,
|
||
})
|
||
.expect("image in the float");
|
||
assert_eq!(image, expected, "options: {options}");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn noindent_starts_the_paragraph_flush() {
|
||
let blocks = paragraphs("\\noindent Alpha\n\nBeta").expect("paragraphs");
|
||
let mut geometry = PageGeometry::default();
|
||
geometry.par_indent = Some(20 * SCALE);
|
||
let document = build_document(&blocks, &geometry);
|
||
assert_eq!(document.units[0].source, "Alpha");
|
||
assert_eq!(
|
||
document.units[0]
|
||
.paragraph_style
|
||
.as_ref()
|
||
.map(|style| style.par_indent),
|
||
Some(0)
|
||
);
|
||
assert_eq!(
|
||
document.units[1]
|
||
.paragraph_style
|
||
.as_ref()
|
||
.map(|style| style.par_indent),
|
||
Some(20 * SCALE)
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn page_numbers_are_centered_in_previews() {
|
||
let json = preview_json("Alpha").expect("preview");
|
||
assert!(json.contains(">1</text>"), "got {json}");
|
||
|
||
let roman = preview_json("\\pagenumbering{roman}\n\nAlpha").expect("roman preview");
|
||
assert!(roman.contains(">i</text>"), "got {roman}");
|
||
|
||
let empty = preview_json("\\pagestyle{empty}\n\nAlpha").expect("pagestyle preview");
|
||
assert!(!empty.contains(">1</text>"), "got {empty}");
|
||
|
||
let first = preview_json("\\thispagestyle{empty}\n\nAlpha\n\n\\newpage\n\nBeta")
|
||
.expect("thispagestyle preview");
|
||
assert!(!first.contains(">1</text>"), "got {first}");
|
||
assert!(first.contains(">2</text>"), "got {first}");
|
||
}
|
||
|
||
#[test]
|
||
fn minipage_paragraphs_use_their_declared_width() {
|
||
let source = "\\begin{minipage}{120pt}\nAlpha beta.\n\nGamma delta.\n\\end{minipage}";
|
||
let blocks = paragraphs(source).expect("paragraphs");
|
||
assert_eq!(blocks.len(), 2);
|
||
assert_eq!(blocks[0].text, "Alpha beta.");
|
||
assert_eq!(blocks[1].text, "Gamma delta.");
|
||
assert_eq!(blocks[0].width, Some(120 * SCALE));
|
||
let document = build_document(&blocks, &PageGeometry::default());
|
||
let style = document.units[0]
|
||
.paragraph_style
|
||
.as_ref()
|
||
.expect("paragraph style");
|
||
assert_eq!(style.line_width, 120 * SCALE);
|
||
}
|
||
|
||
#[test]
|
||
fn addtocounter_offsets_the_printed_page_number() {
|
||
let offset = preview_json("\\setcounter{page}{5}\n\n\\addtocounter{page}{2}\n\nAlpha")
|
||
.expect("preview");
|
||
assert!(offset.contains(">7</text>"), "{offset}");
|
||
}
|
||
|
||
#[test]
|
||
fn newcounter_definitions_stay_out_of_the_body() {
|
||
let (body, geometry) =
|
||
geometry_and_body("\\newcounter{steps}\n\n\\setcounter{steps}{4}\n\nBody.");
|
||
assert_eq!(body.trim(), "Body.");
|
||
assert_eq!(geometry_counter(&geometry, "steps"), 4);
|
||
}
|
||
|
||
#[test]
|
||
fn multline_rows_share_one_number() {
|
||
let json = preview_json("\\begin{multline}a + b \\\\ c + d \\\\ e\\end{multline}")
|
||
.expect("multline preview");
|
||
assert!(json.contains(">1</text>"), "{json}");
|
||
assert!(json.contains(">e</text>"), "{json}");
|
||
assert!(!json.contains("multline"), "{json}");
|
||
}
|
||
|
||
#[test]
|
||
fn split_inside_equation_numbers_once() {
|
||
let json = preview_json(
|
||
"\\begin{equation}\\begin{split}\na &= b \\\\\nc &= d\n\\end{split}\\end{equation}",
|
||
)
|
||
.expect("split preview");
|
||
assert!(json.contains(">1</text>"), "{json}");
|
||
assert!(json.contains(">(</text>"), "{json}");
|
||
assert!(json.contains(">a</text>"), "{json}");
|
||
assert!(!json.contains("split"), "{json}");
|
||
}
|
||
|
||
#[test]
|
||
fn alignat_rows_are_numbered() {
|
||
let json = preview_json(
|
||
"\\begin{alignat}{2}\na &= b & c &= d \\\\\ne &= f & g &= h\n\\end{alignat}",
|
||
)
|
||
.expect("alignat preview");
|
||
assert!(json.contains(">1</text>"), "{json}");
|
||
assert!(json.contains(">2</text>"), "{json}");
|
||
assert!(!json.contains("alignat"), "{json}");
|
||
}
|
||
|
||
#[test]
|
||
fn operator_names_and_declared_operators_render() {
|
||
let source = r"\DeclareMathOperator{\Tr}{Tr}
|
||
|
||
Body $\operatorname{rank}(A)$ and $\Tr(B)$.";
|
||
let json = preview_json(source).expect("preview");
|
||
assert!(json.contains(">r</text>"));
|
||
assert!(!json.contains("operatorname"));
|
||
assert!(!json.contains("DeclareMathOperator"));
|
||
}
|
||
|
||
#[test]
|
||
fn substack_scripts_paint_their_rows() {
|
||
let json = preview_json("\\[\\sum_{\\substack{i=1 \\\\ j=2}} x\\]").expect("preview");
|
||
assert!(json.contains(">i</text>"));
|
||
assert!(json.contains(">j</text>"));
|
||
assert!(!json.contains("substack"));
|
||
}
|
||
|
||
#[test]
|
||
fn matrix_environments_paint_their_delimiters() {
|
||
let json = preview_json("\\[\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}\\]")
|
||
.expect("matrix preview");
|
||
assert!(json.contains(">[</text>"), "{json}");
|
||
assert!(json.contains(">]</text>"), "{json}");
|
||
assert!(json.contains(">a</text>"), "{json}");
|
||
assert!(!json.contains("unsupported environment"), "{json}");
|
||
}
|
||
|
||
#[test]
|
||
fn cases_environments_paint_rows_and_a_brace() {
|
||
let json = preview_json("\\[\\begin{cases} x & x>0 \\\\ 0 & \\text{else} \\end{cases}\\]")
|
||
.expect("cases preview");
|
||
assert!(json.contains(">{</text>"), "{json}");
|
||
assert!(json.contains(">x</text>"), "{json}");
|
||
assert!(!json.contains("unsupported environment `cases`"), "{json}");
|
||
}
|
||
|
||
#[test]
|
||
fn preview_warnings_flag_unsupported_environments() {
|
||
let source = r"\begin{document}
|
||
\begin{align}
|
||
a &= b
|
||
\end{align}
|
||
|
||
\[\begin{eqnarray}
|
||
x = 1 \\
|
||
y = 2
|
||
\end{eqnarray}\]
|
||
|
||
\begin{wrapfigure}{r}{4cm}
|
||
a & b
|
||
\end{wrapfigure}
|
||
\end{document}";
|
||
let json = preview_json(source).expect("preview");
|
||
assert!(
|
||
json.contains("unsupported environment `eqnarray`"),
|
||
"{json}"
|
||
);
|
||
assert!(
|
||
json.contains("unsupported environment `wrapfigure`"),
|
||
"{json}"
|
||
);
|
||
assert!(!json.contains("unsupported environment `align`"), "{json}");
|
||
let plain = preview_json("Alpha").expect("plain preview");
|
||
assert!(plain.contains("\"warnings\":[]"), "{plain}");
|
||
}
|
||
|
||
#[test]
|
||
fn preview_warnings_flag_leaked_commands() {
|
||
let json = preview_json(r"See \unknownthing and \textcolor{red}{red}.").expect("preview");
|
||
assert!(
|
||
json.contains(r"unsupported command `\\unknownthing`"),
|
||
"{json}"
|
||
);
|
||
assert!(
|
||
!json.contains(r"unsupported command `\\textcolor`"),
|
||
"{json}"
|
||
);
|
||
assert!(json.contains("#ff0000"), "{json}");
|
||
}
|
||
|
||
#[test]
|
||
fn headings_become_pdf_bookmarks() {
|
||
let pdf = pdf_bytes(
|
||
"\\section{One}\n\n\\subsection{Sub}\n\n\\newpage\n\n\\section{Two}\n\nSecond.",
|
||
)
|
||
.expect("pdf");
|
||
let text = String::from_utf8_lossy(&pdf);
|
||
assert!(text.contains("/Type /Outlines"));
|
||
assert!(text.contains("/Title (1 One)"));
|
||
assert!(text.contains("/Title (1.1 Sub)"));
|
||
assert!(text.contains("/Title (2 Two)"));
|
||
assert!(text.contains("/Count 3"));
|
||
}
|
||
|
||
#[test]
|
||
fn hypersetup_writes_the_pdf_info_dictionary() {
|
||
let pdf =
|
||
pdf_bytes("\\hypersetup{pdftitle={My Title},pdfauthor={Ada}}\n\nBody.").expect("pdf");
|
||
let text = String::from_utf8_lossy(&pdf);
|
||
assert!(text.contains("/Title (My Title)"));
|
||
assert!(text.contains("/Author (Ada)"));
|
||
}
|
||
|
||
#[test]
|
||
fn pageref_reports_the_page_of_its_heading() {
|
||
let source = "\\pagestyle{empty}\n\n\\section{One}\n\nFirst page.\n\n\\newpage\n\n\\section{Two}\\label{sec:two}\n\nSee page \\pageref{sec:two}.";
|
||
let json = preview_json(source).expect("preview");
|
||
assert!(
|
||
json.contains(">2</text>"),
|
||
"expected the second page number"
|
||
);
|
||
assert!(
|
||
!json.contains("pageref"),
|
||
"the command must not leak: {json}"
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn unknown_pagerefs_print_question_marks() {
|
||
let json =
|
||
preview_json("\\pagestyle{empty}\n\nSee page \\pageref{missing}.").expect("preview");
|
||
assert!(json.contains(">?</text>"));
|
||
assert!(!json.contains("pageref"));
|
||
}
|
||
|
||
#[test]
|
||
fn page_numbers_follow_the_page_counter() {
|
||
let offset = preview_json("\\setcounter{page}{5}\n\nAlpha\n\n\\newpage\n\nBeta")
|
||
.expect("offset preview");
|
||
assert!(offset.contains(">5</text>"), "got {offset}");
|
||
assert!(offset.contains(">6</text>"), "got {offset}");
|
||
|
||
let reset = preview_json("\\setcounter{page}{5}\n\n\\pagenumbering{roman}\n\nAlpha")
|
||
.expect("reset preview");
|
||
assert!(reset.contains(">i</text>"), "got {reset}");
|
||
|
||
let later = preview_json("\\pagenumbering{roman}\n\n\\setcounter{page}{5}\n\nAlpha")
|
||
.expect("later preview");
|
||
assert!(later.contains(">v</text>"), "got {later}");
|
||
}
|
||
|
||
#[test]
|
||
fn page_numbers_survive_pdf_extraction() {
|
||
use std::process::Command;
|
||
|
||
if Command::new("pdftotext")
|
||
.arg("-v")
|
||
.stdout(std::process::Stdio::null())
|
||
.stderr(std::process::Stdio::null())
|
||
.status()
|
||
.is_err()
|
||
{
|
||
return;
|
||
}
|
||
let pdf = pdf_bytes("Alpha").expect("pdf");
|
||
let path =
|
||
std::env::temp_dir().join(format!("texrra-page-number-{}.pdf", std::process::id()));
|
||
std::fs::write(&path, &pdf).expect("write pdf");
|
||
let output = Command::new("pdftotext")
|
||
.arg(&path)
|
||
.arg("-")
|
||
.output()
|
||
.expect("pdftotext");
|
||
let _ = std::fs::remove_file(&path);
|
||
let text = String::from_utf8_lossy(&output.stdout);
|
||
assert!(text.contains("Alpha"), "got {text:?}");
|
||
assert!(text.contains('1'), "got {text:?}");
|
||
}
|
||
|
||
#[test]
|
||
fn greek_text_paints_in_previews() {
|
||
let json =
|
||
preview_json("\u{3b1}\u{3b2}\u{3b3} \u{3bc}\u{3ad}\u{3b3}\u{3b1}").expect("preview");
|
||
assert!(json.contains(">\u{3b1}</text>"), "got {json}");
|
||
assert!(!json.contains(">?</text>"));
|
||
}
|
||
|
||
#[test]
|
||
fn addtolength_updates_named_lengths() {
|
||
let source = "\\newlength{\\gutter}\n\\setlength{\\gutter}{6pt}\n\\addtolength{\\gutter}{2pt}\n\\setlength{\\parindent}{\\gutter}\n\nText.";
|
||
let (_, geometry) = geometry_and_body(source);
|
||
assert_eq!(geometry.par_indent, Some(8 * 65_536));
|
||
}
|
||
|
||
#[test]
|
||
fn named_lengths_feed_setlength() {
|
||
let source = "\\newlength{\\indent}\n\\setlength{\\indent}{2em}\n\\setlength{\\parindent}{\\indent}\n\\setlength{\\textwidth}{\\indent}\n\nText.";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
assert_eq!(geometry.par_indent, Some(1_310_720));
|
||
assert_eq!(geometry.line_width, Some(1_310_720));
|
||
assert_eq!(
|
||
geometry
|
||
.lengths
|
||
.iter()
|
||
.find(|(name, _)| name == "indent")
|
||
.map(|(_, value)| *value),
|
||
Some(1_310_720)
|
||
);
|
||
assert!(!body.contains("newlength"));
|
||
}
|
||
|
||
#[test]
|
||
fn graphics_paths_are_read_from_the_preamble() {
|
||
let (body, geometry) = geometry_and_body(
|
||
"\\graphicspath{{figures/}{plots}}\n\\begin{figure}[t]\n\\includegraphics{x}\n\\end{figure}",
|
||
);
|
||
assert_eq!(geometry.graphics_paths, vec!["figures/", "plots/"]);
|
||
assert!(!body.contains("graphicspath"));
|
||
assert_eq!(graphics_paths("\\graphicspath{{a/}}"), vec!["a/"]);
|
||
}
|
||
|
||
#[test]
|
||
fn figure_graphics_reserve_a_placeholder() {
|
||
let source = "\\begin{figure}[b]\n\\includegraphics[width=200pt]{plot.pdf}\\caption{Plot}\n\\end{figure}";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
let blocks = paragraphs(&body).unwrap();
|
||
let document = build_document(&blocks, &geometry);
|
||
let Some(VerticalItem::Float(float)) = document.units[0].items.first() else {
|
||
panic!("expected a float unit");
|
||
};
|
||
assert_eq!(float.placement, FloatPlacement::Bottom);
|
||
let Some(VerticalItem::Rule { width, height }) = float.content.first() else {
|
||
panic!("expected a graphics rule");
|
||
};
|
||
assert_eq!(*width, 200 * SCALE);
|
||
assert_eq!(*height, 100 * SCALE);
|
||
}
|
||
|
||
#[test]
|
||
fn table_captions_sit_above_their_tabular() {
|
||
let source = "\\begin{table}[t]\n\\caption{Numbers}\n\\begin{tabular}{ll}\na & b \\\\\n\\end{tabular}\n\\end{table}";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
let blocks = paragraphs(&body).expect("blocks");
|
||
assert_eq!(blocks.len(), 1);
|
||
let document = build_document(&blocks, &geometry);
|
||
let VerticalItem::Float(float) = &document.units[0].items[0] else {
|
||
panic!("expected a float");
|
||
};
|
||
let caption = match &float.content[0] {
|
||
VerticalItem::Paragraph(paragraph) => paragraph,
|
||
other => panic!("expected the caption first, got {other:?}"),
|
||
};
|
||
let text: String = caption
|
||
.lines
|
||
.iter()
|
||
.flatten()
|
||
.map(|item| match item {
|
||
texrra_tex_core::paragraph::HorizontalItem::Box(character) => {
|
||
character.character.unwrap_or(' ')
|
||
}
|
||
texrra_tex_core::paragraph::HorizontalItem::Glue { width, .. } if *width > 0 => ' ',
|
||
_ => '\0',
|
||
})
|
||
.filter(|character| *character != '\0')
|
||
.collect();
|
||
assert_eq!(text, "Table 1: Numbers");
|
||
assert!(matches!(float.content[1], VerticalItem::Halign(_)));
|
||
}
|
||
|
||
#[test]
|
||
fn starred_captions_stay_unnumbered() {
|
||
let source = "\\begin{figure}[t]\n\\caption*{Note}\n\\end{figure}\n\n\\begin{figure}[t]\n\\caption{Numbered}\n\\end{figure}";
|
||
let (body, _) = geometry_and_body(source);
|
||
let mut blocks = paragraphs(&body).expect("blocks");
|
||
assert_eq!(blocks.len(), 2);
|
||
number_floats(&mut blocks, "Figure", "Table", 0, 0);
|
||
let first = blocks[0].float.as_ref().expect("first float");
|
||
assert_eq!(first.caption.as_deref(), Some("Note"));
|
||
let second = blocks[1].float.as_ref().expect("second float");
|
||
assert_eq!(second.caption.as_deref(), Some("Figure 1: Numbered"));
|
||
}
|
||
|
||
#[test]
|
||
fn tabular_cline_draws_partial_rules() {
|
||
let source = r"\begin{tabular}{ll}
|
||
A & B \\
|
||
\cline{2-2}
|
||
C & D \\
|
||
\end{tabular}";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
let blocks = paragraphs(&body).unwrap();
|
||
let document = build_document(&blocks, &geometry);
|
||
let Some(VerticalItem::Halign(halign)) = document.units[0].items.first() else {
|
||
panic!("expected halign");
|
||
};
|
||
assert_eq!(halign.rows.len(), 2);
|
||
assert_eq!(halign.rules.len(), 1);
|
||
assert_eq!(halign.rules[0].start, 1);
|
||
assert_eq!(halign.rules[0].end, 1);
|
||
}
|
||
|
||
#[test]
|
||
fn tabular_multicolumn_cells_span_columns() {
|
||
let source = r"\begin{tabular}{|l|c|}
|
||
\multicolumn{2}{|c|}{Merged} \\
|
||
A & B \\
|
||
\end{tabular}";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
let blocks = paragraphs(&body).unwrap();
|
||
let document = build_document(&blocks, &geometry);
|
||
let Some(VerticalItem::Halign(halign)) = document.units[0].items.first() else {
|
||
panic!("expected halign");
|
||
};
|
||
assert_eq!(halign.rows[0].cells.len(), 1);
|
||
assert_eq!(halign.rows[0].cells[0].text, "Merged");
|
||
assert_eq!(halign.rows[0].cells[0].span, 2);
|
||
assert_eq!(
|
||
halign.rows[0].cells[0].alignment,
|
||
texrra_tex_core::CellAlignment::Center
|
||
);
|
||
assert_eq!(halign.rows[1].cells.len(), 2);
|
||
}
|
||
|
||
#[test]
|
||
fn table_floats_carry_their_tabular() {
|
||
let source = r"\begin{table}[t]
|
||
\caption{Numbers}\label{tab:a}
|
||
\begin{tabular}{|l|c|}
|
||
A & 1 \\
|
||
B & 2 \\
|
||
\end{tabular}
|
||
\end{table}
|
||
|
||
See \ref{tab:a}.";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
let blocks = paragraphs(&body).unwrap();
|
||
let document = build_document(&blocks, &geometry);
|
||
assert_eq!(document.units.len(), 2);
|
||
let Some(VerticalItem::Float(float)) = document.units[0].items.first() else {
|
||
panic!("expected a table float");
|
||
};
|
||
assert!(
|
||
float
|
||
.content
|
||
.iter()
|
||
.any(|item| matches!(item, VerticalItem::Halign(_)))
|
||
);
|
||
let mut caption = String::new();
|
||
for item in &float.content {
|
||
if let VerticalItem::Paragraph(paragraph) = item {
|
||
for line in ¶graph.lines {
|
||
for item in line {
|
||
match item {
|
||
texrra_tex_core::paragraph::HorizontalItem::Box(box_) => {
|
||
if let Some(character) = box_.character {
|
||
caption.push(character);
|
||
}
|
||
}
|
||
texrra_tex_core::paragraph::HorizontalItem::Glue { width, .. } => {
|
||
if *width > 0 {
|
||
caption.push(' ');
|
||
}
|
||
}
|
||
_ => {}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
assert_eq!(caption, "Table 1: Numbers");
|
||
assert_eq!(document.units[1].source, "See 1.");
|
||
}
|
||
|
||
#[test]
|
||
fn figure_and_table_labels_count_independently() {
|
||
let source = r"\begin{figure}[h]
|
||
\caption{Shape}\label{fig:a}
|
||
\end{figure}
|
||
|
||
\begin{table}[h]
|
||
\caption{Data}\label{tab:b}
|
||
\end{table}
|
||
|
||
See \ref{fig:a} and \ref{tab:b}.";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
let blocks = paragraphs(&body).unwrap();
|
||
let document = build_document(&blocks, &geometry);
|
||
assert_eq!(document.units[2].source, "See 1 and 1.");
|
||
}
|
||
|
||
#[test]
|
||
fn links_keep_their_text_and_style_urls() {
|
||
let (body, _) = geometry_and_body(
|
||
"See \\href{https://example.com}{Example} and \\url{https://x.test/a_b}.",
|
||
);
|
||
assert!(
|
||
body.contains(r"\href{https://example.com}{Example}")
|
||
&& body.contains(r"\texttt{https://x.test/a_b}."),
|
||
"{body}"
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn verbatim_links_stay_literal() {
|
||
let (body, _) = geometry_and_body("\\begin{verbatim}\n\\url{https://x}\n\\end{verbatim}");
|
||
assert!(body.contains("\\url{https://x}"), "{body}");
|
||
}
|
||
|
||
#[test]
|
||
fn verbatim_lines_stay_monospaced() {
|
||
let source = "\\begin{verbatim}\nlet x = 1;\nreturn x;\n\\end{verbatim}";
|
||
let blocks = paragraphs(source).expect("blocks");
|
||
assert_eq!(blocks.len(), 2);
|
||
assert_eq!(blocks[0].text, "let x = 1;");
|
||
assert_eq!(blocks[1].text, "return x;");
|
||
assert_eq!(blocks[0].font, ParagraphFont::Mono);
|
||
assert_eq!(blocks[0].left_skip, 12);
|
||
assert_eq!(blocks[0].space_before, 6 * SCALE);
|
||
assert_eq!(blocks[1].space_before, 0);
|
||
}
|
||
|
||
#[test]
|
||
fn today_expands_to_the_current_date() {
|
||
let (body, _geometry) = geometry_and_body("Body \\today.");
|
||
assert_eq!(body.trim(), format!("Body {}.", today_string()));
|
||
let date = today_string();
|
||
assert!(date.chars().any(|character| character.is_ascii_digit()));
|
||
assert!(date.contains(','));
|
||
}
|
||
|
||
#[test]
|
||
fn maketitle_defaults_to_today_when_no_date_is_set() {
|
||
let (body, geometry) = geometry_and_body("\\maketitle");
|
||
let blocks = paragraphs(&body).expect("paragraphs");
|
||
let document = build_document(&blocks, &geometry);
|
||
let today = today_string();
|
||
assert!(document.units.iter().any(|unit| unit.source == today));
|
||
}
|
||
|
||
#[test]
|
||
fn explicit_empty_date_suppresses_the_title_date() {
|
||
let (body, geometry) = geometry_and_body("\\date{}\n\\maketitle");
|
||
let blocks = paragraphs(&body).expect("paragraphs");
|
||
let document = build_document(&blocks, &geometry);
|
||
let today = today_string();
|
||
assert!(document.units.iter().all(|unit| unit.source != today));
|
||
}
|
||
|
||
#[test]
|
||
fn list_items_take_article_separations() {
|
||
let blocks =
|
||
paragraphs("\\begin{itemize}\n\\item One\n\\item Two\n\\end{itemize}").expect("blocks");
|
||
assert_eq!(blocks[0].space_before, 10, "article topsep plus partopsep");
|
||
assert_eq!(blocks[0].space_stretch, 3);
|
||
assert_eq!(blocks[0].space_shrink, 5);
|
||
assert_eq!(blocks[1].space_before, 4, "article itemsep at 10pt");
|
||
assert_eq!(blocks[1].space_stretch, 2);
|
||
assert_eq!(blocks[1].space_shrink, 1);
|
||
}
|
||
|
||
#[test]
|
||
fn list_separations_follow_setlength() {
|
||
let source = "\\setlength{\\topsep}{3pt plus 1pt minus 2pt}\n\\setlength{\\itemsep}{6pt plus 2pt minus 1pt}\n\n\\begin{enumerate}\n\\item One\n\\item Two\n\\end{enumerate}";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
let blocks = paragraphs_with_geometry(&body, &[], 0, &geometry).expect("blocks");
|
||
assert_eq!(blocks[0].space_before, 5, "topsep plus partopsep");
|
||
assert_eq!(blocks[0].space_stretch, 2);
|
||
assert_eq!(blocks[0].space_shrink, 3);
|
||
assert_eq!(blocks[1].space_before, 6);
|
||
assert_eq!(blocks[1].space_stretch, 2);
|
||
assert_eq!(blocks[1].space_shrink, 1);
|
||
}
|
||
|
||
#[test]
|
||
fn list_separations_follow_the_class_size() {
|
||
let source = "\\documentclass[12pt]{article}\n\\begin{document}\n\n\\begin{itemize}\n\\item One\n\\item Two\n\\end{itemize}\n\n\\end{document}";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
let blocks = paragraphs_with_geometry(&body, &[], 0, &geometry).expect("blocks");
|
||
assert_eq!(blocks[0].space_before, 13, "12pt topsep plus partopsep");
|
||
assert_eq!(blocks[1].space_before, 5, "12pt itemsep");
|
||
}
|
||
|
||
#[test]
|
||
fn tabular_star_specs_repeat_columns() {
|
||
let source = "\\begin{tabular}{*{3}{c}}\na & b & c\n\\end{tabular}";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
let blocks = paragraphs_with_geometry(&body, &[], 0, &geometry).expect("blocks");
|
||
let document = build_document(&blocks, &geometry);
|
||
let halign = document
|
||
.units
|
||
.iter()
|
||
.find_map(|unit| match &unit.items[0] {
|
||
VerticalItem::Halign(halign) => Some(halign),
|
||
_ => None,
|
||
})
|
||
.expect("halign");
|
||
assert_eq!(halign.column_widths.len(), 3);
|
||
assert_eq!(halign.rows.len(), 1);
|
||
assert_eq!(halign.rows[0].cells.len(), 3);
|
||
}
|
||
|
||
#[test]
|
||
fn tabular_optional_position_is_ignored() {
|
||
let (body, geometry) = geometry_and_body("\\begin{tabular}[t]{ll}\nA & B\n\\end{tabular}");
|
||
assert_eq!(geometry.tabular.len(), 1);
|
||
assert_eq!(geometry.tabular[0].0, "ll");
|
||
assert!(body.contains("texrratable"), "missing placeholder: {body}");
|
||
assert!(!body.contains("tabular"), "environment leaked: {body}");
|
||
}
|
||
|
||
#[test]
|
||
fn multirow_cells_keep_their_text() {
|
||
let source =
|
||
"\\begin{tabular}{ll}\n\\multirow{2}{*}{Both} & a \\\\\n & b\n\\end{tabular}\n\nTail.";
|
||
let (_, geometry) = geometry_and_body(source);
|
||
assert_eq!(geometry.tabular.len(), 1);
|
||
let (_, text, _) = &geometry.tabular[0];
|
||
assert!(text.contains("Both & a"), "{text}");
|
||
assert!(!text.contains("multirow"));
|
||
let json = preview_json(source).expect("preview");
|
||
assert!(json.contains(">Both</text>"));
|
||
assert!(!json.contains("multirow"));
|
||
}
|
||
|
||
#[test]
|
||
fn tabularx_fills_its_target_width() {
|
||
let source =
|
||
"\\begin{tabularx}{200pt}{lX}\na & alpha beta gamma \\\\\nb & delta\n\\end{tabularx}";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
assert_eq!(geometry.tabular.len(), 1);
|
||
let template = &geometry.tabular[0].0;
|
||
assert_eq!(template, "lX");
|
||
assert!(geometry.tabular[0].2.is_some(), "target width missing");
|
||
assert!(body.contains("\\texrratable{0}"));
|
||
let blocks = paragraphs_with_geometry(
|
||
&body,
|
||
&PageGeometry::default().theorem_definitions,
|
||
0,
|
||
&geometry,
|
||
)
|
||
.expect("paragraphs");
|
||
let document = build_document(&blocks, &geometry);
|
||
let halign = document
|
||
.units
|
||
.iter()
|
||
.find_map(|unit| {
|
||
unit.items.iter().find_map(|item| match item {
|
||
VerticalItem::Halign(halign) => Some(halign.clone()),
|
||
_ => None,
|
||
})
|
||
})
|
||
.expect("halign");
|
||
assert_eq!(halign.column_widths.len(), 2);
|
||
assert!(halign.column_widths[1] > halign.column_widths[0]);
|
||
let width = halign.width;
|
||
assert!(
|
||
(width - 200 * SCALE).abs() <= 2 * SCALE,
|
||
"width {width} not near 200pt"
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn longtable_captures_its_body() {
|
||
let (body, geometry) =
|
||
geometry_and_body("\\begin{longtable}{ll}\na & b \\\\\n\\end{longtable}\n\nBody.");
|
||
assert_eq!(geometry.tabular.len(), 1);
|
||
assert_eq!(geometry.tabular[0].0, "ll");
|
||
assert!(geometry.tabular[0].1.contains("a & b"));
|
||
assert!(body.contains("\\texrratable{0}"));
|
||
assert!(!body.contains("longtable"));
|
||
}
|
||
|
||
#[test]
|
||
fn rule_paragraphs_become_rule_boxes() {
|
||
let blocks = paragraphs("\\rule{20pt}{5pt}").expect("rule");
|
||
assert_eq!(blocks.len(), 1);
|
||
let spec = blocks[0].float.as_ref().expect("rule float");
|
||
assert_eq!(spec.width, Some(ImageLength::Absolute(20 * SCALE)));
|
||
assert_eq!(spec.height, Some(ImageLength::Absolute(5 * SCALE)));
|
||
assert!(spec.caption.is_none());
|
||
|
||
let document = build_document(&blocks, &PageGeometry::default());
|
||
let Some(VerticalItem::Float(float)) = document.units[0].items.first() else {
|
||
panic!("expected float rule unit");
|
||
};
|
||
assert!(matches!(
|
||
float.content.first(),
|
||
Some(VerticalItem::Rule { width, height }) if *width == 20 * SCALE && *height == 5 * SCALE
|
||
));
|
||
}
|
||
|
||
#[test]
|
||
fn centered_environments_parse_their_body() {
|
||
let blocks =
|
||
paragraphs("\\begin{center}\n\\rule{20pt}{5pt}\n\\end{center}").expect("center");
|
||
assert_eq!(blocks.len(), 1);
|
||
assert!(blocks[0].float.is_some());
|
||
}
|
||
|
||
#[test]
|
||
fn quotation_parses_nested_lists() {
|
||
let blocks = paragraphs(
|
||
"\\begin{quotation}\n\\begin{itemize}\n\\item a\n\\item b\n\\end{itemize}\n\\end{quotation}",
|
||
)
|
||
.expect("quotation");
|
||
assert_eq!(blocks.len(), 2);
|
||
assert_eq!(blocks[0].left_skip, 32);
|
||
assert_eq!(blocks[1].left_skip, 32);
|
||
}
|
||
|
||
#[test]
|
||
fn verse_keeps_its_line_breaks() {
|
||
let blocks =
|
||
paragraphs("\\begin{verse}\nline one \\\\\nline two\n\\end{verse}").expect("verse");
|
||
assert_eq!(blocks.len(), 2);
|
||
assert_eq!(blocks[0].text, "line one");
|
||
assert_eq!(blocks[0].left_skip, 20);
|
||
assert_eq!(blocks[1].text, "line two");
|
||
assert_eq!(blocks[1].left_skip, 20);
|
||
}
|
||
|
||
#[test]
|
||
fn quotation_indents_both_margins() {
|
||
let source = "\\begin{quotation}\nOne paragraph.\n\nTwo paragraph.\n\\end{quotation}";
|
||
let blocks = paragraphs(source).expect("paragraphs");
|
||
assert_eq!(blocks.len(), 2);
|
||
assert!(
|
||
blocks
|
||
.iter()
|
||
.all(|block| block.left_skip == 20 && block.right_skip == 20)
|
||
);
|
||
assert!(blocks[0].text.starts_with("One"));
|
||
assert!(blocks[1].text.starts_with("Two"));
|
||
}
|
||
|
||
#[test]
|
||
fn quotation_narrows_the_measure() {
|
||
let long = "alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron pi rho sigma tau upsilon phi chi psi omega";
|
||
let plain = paragraphs(long).expect("paragraphs");
|
||
let indented = paragraphs(&format!("\\begin{{quotation}}\n{long}\n\\end{{quotation}}"))
|
||
.expect("paragraphs");
|
||
let geometry = PageGeometry {
|
||
line_width: Some(200 * SCALE),
|
||
..PageGeometry::default()
|
||
};
|
||
let plain_document = build_document(&plain, &geometry);
|
||
let quote_document = build_document(&indented, &geometry);
|
||
let lines = |document: &Document| {
|
||
document.units[0]
|
||
.items
|
||
.iter()
|
||
.find_map(|item| match item {
|
||
VerticalItem::Paragraph(paragraph) => Some(paragraph.lines.len()),
|
||
_ => None,
|
||
})
|
||
.expect("paragraph")
|
||
};
|
||
assert!(lines("e_document) > lines(&plain_document));
|
||
assert_eq!(
|
||
quote_document.units[0]
|
||
.paragraph_style
|
||
.as_ref()
|
||
.expect("style")
|
||
.right_skip,
|
||
20 * SCALE
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn list_items_hang_their_continuation_lines() {
|
||
let source = "\\begin{itemize}\n\\item alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron\n\\end{itemize}";
|
||
let blocks = paragraphs(source).expect("paragraphs");
|
||
assert_eq!(blocks[0].list_depth, Some(0));
|
||
let geometry = PageGeometry {
|
||
line_width: Some(140 * SCALE),
|
||
..PageGeometry::default()
|
||
};
|
||
let document = build_document(&blocks, &geometry);
|
||
let paragraph = document.units[0]
|
||
.items
|
||
.iter()
|
||
.find_map(|item| match item {
|
||
VerticalItem::Paragraph(paragraph) => Some(paragraph),
|
||
_ => None,
|
||
})
|
||
.expect("list paragraph");
|
||
assert!(paragraph.lines.len() > 1, "the item must wrap");
|
||
let hang = (blocks[0].list_label + 5) * SCALE;
|
||
assert_eq!(paragraph.left_skip, 12 * SCALE + hang);
|
||
assert_eq!(paragraph.line_indents[0], -hang);
|
||
assert_eq!(paragraph.line_indents[1], 0);
|
||
}
|
||
|
||
#[test]
|
||
fn nested_lists_use_the_second_level_skips() {
|
||
let source = "\\begin{itemize}\n\\item Outer\n\\begin{itemize}\n\\item Inner\n\\item More\n\\end{itemize}\n\\item Next\n\\end{itemize}";
|
||
let blocks = paragraphs(source).expect("blocks");
|
||
let spaces: Vec<i64> = blocks.iter().map(|block| block.space_before).collect();
|
||
assert_eq!(spaces, vec![10, 6, 2, 4]);
|
||
}
|
||
|
||
#[test]
|
||
fn enumerate_honours_setcounter_in_its_preamble() {
|
||
let blocks = paragraphs(
|
||
"\\begin{enumerate}\n\\setcounter{enumi}{4}\n\\item Fifth\n\\item Sixth\n\\end{enumerate}",
|
||
)
|
||
.expect("paragraphs");
|
||
assert_eq!(blocks.len(), 2);
|
||
assert_eq!(blocks[0].text, "5. Fifth");
|
||
assert_eq!(blocks[1].text, "6. Sixth");
|
||
}
|
||
|
||
#[test]
|
||
fn nested_itemize_indents_and_relabels() {
|
||
let source = "\\begin{itemize}\n\\item Outer\n\\begin{itemize}\n\\item Inner\n\\end{itemize}\n\\end{itemize}";
|
||
let blocks = paragraphs(source).unwrap();
|
||
assert_eq!(
|
||
blocks.len(),
|
||
2,
|
||
"{:?}",
|
||
blocks.iter().map(|b| &b.text).collect::<Vec<_>>()
|
||
);
|
||
assert_eq!(blocks[0].text, "• Outer");
|
||
assert_eq!(blocks[0].left_skip, 12);
|
||
assert_eq!(blocks[1].text, "– Inner");
|
||
assert_eq!(blocks[1].left_skip, 24);
|
||
}
|
||
|
||
#[test]
|
||
fn nested_enumerate_uses_letter_labels() {
|
||
let source = "\\begin{enumerate}\n\\item First\n\\begin{enumerate}\n\\item Alpha\n\\item Beta\n\\end{enumerate}\n\\item Second\n\\end{enumerate}";
|
||
let blocks = paragraphs(source).unwrap();
|
||
let texts: Vec<&str> = blocks.iter().map(|block| block.text.as_str()).collect();
|
||
assert_eq!(texts, ["1. First", "(a) Alpha", "(b) Beta", "2. Second"]);
|
||
let skips: Vec<i64> = blocks.iter().map(|block| block.left_skip).collect();
|
||
assert_eq!(skips, [12, 24, 24, 12]);
|
||
}
|
||
|
||
#[test]
|
||
fn item_labels_override_generated_markers() {
|
||
let blocks = paragraphs(
|
||
"\\begin{itemize}\n\\item[--] Dash\n\\item Next\n\\end{itemize}\n\n\\begin{enumerate}\n\\item[(iv)] Fourth\n\\end{enumerate}",
|
||
)
|
||
.expect("paragraphs");
|
||
assert_eq!(blocks[0].text, "-- Dash");
|
||
assert_eq!(blocks[1].text, "• Next");
|
||
assert_eq!(blocks[2].text, "(iv) Fourth");
|
||
}
|
||
|
||
#[test]
|
||
fn description_items_keep_their_terms() {
|
||
let source = "\\begin{description}\n\\item[Term] Definition\n\\end{description}";
|
||
let blocks = paragraphs(source).unwrap();
|
||
assert_eq!(blocks.len(), 1);
|
||
assert_eq!(blocks[0].text, "\\textbf{Term} — Definition");
|
||
assert_eq!(blocks[0].left_skip, 12);
|
||
}
|
||
|
||
#[test]
|
||
fn description_terms_are_bold() {
|
||
let json =
|
||
preview_json("\\begin{description}\n\\item[Term] Definition\n\\end{description}")
|
||
.expect("preview");
|
||
assert!(json.contains(r#"font-weight=\"bold\""#), "{json}");
|
||
assert!(json.contains(">T</text>"), "{json}");
|
||
}
|
||
|
||
#[test]
|
||
fn newif_definitions_default_to_false() {
|
||
let source = "\\newif\\ifdraft\n\\ifdraft Draft\\else Final\\fi";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
assert_eq!(geometry.conditionals.len(), 1);
|
||
assert_eq!(geometry.conditionals[0].name, "draft");
|
||
assert!(!geometry.conditionals[0].value);
|
||
assert_eq!(body.trim(), "Final");
|
||
}
|
||
|
||
#[test]
|
||
fn conditional_assignments_select_the_true_branch() {
|
||
let source = "\\newif\\ifdraft\n\\drafttrue\n\n\\ifdraft Draft\\else Final\\fi";
|
||
let (body, _) = geometry_and_body(source);
|
||
assert_eq!(body.trim(), "Draft");
|
||
}
|
||
|
||
#[test]
|
||
fn conditional_assignments_in_the_body_take_effect() {
|
||
let source =
|
||
"\\newif\\ifdraft\n\nA\\ifdraft X\\else Y\\fi B\\drafttrue C\\ifdraft Z\\else W\\fi D";
|
||
let (body, _) = geometry_and_body(source);
|
||
assert_eq!(body.trim(), "A Y B C Z D");
|
||
}
|
||
|
||
#[test]
|
||
fn nested_conditionals_pick_the_inner_branch() {
|
||
let source =
|
||
"\\newif\\ifdraft\n\\drafttrue\n\n\\ifdraft A\\ifdraft B\\else C\\fi\\else D\\fi";
|
||
let (body, _) = geometry_and_body(source);
|
||
assert_eq!(body.trim(), "A B");
|
||
}
|
||
|
||
#[test]
|
||
fn unknown_conditionals_stay_literal() {
|
||
let source = "\\ifxyz A\\fi";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
assert!(geometry.conditionals.is_empty());
|
||
assert_eq!(body.trim(), "\\ifxyz A\\fi");
|
||
}
|
||
|
||
#[test]
|
||
fn macros_can_introduce_conditionals() {
|
||
let source = "\\newif\\ifdraft\n\\drafttrue\n\\newcommand{\\pick}{\\ifdraft D\\else F\\fi}\n\n\\pick";
|
||
let (body, _) = geometry_and_body(source);
|
||
assert_eq!(body.trim(), "D");
|
||
}
|
||
|
||
#[test]
|
||
fn iftrue_and_iffalse_select_without_declarations() {
|
||
let source = "\\iftrue Yes\\else No\\fi and\\iffalse A\\else B\\fi";
|
||
let (body, _) = geometry_and_body(source);
|
||
assert_eq!(body.trim(), "Yes and B");
|
||
}
|
||
|
||
#[test]
|
||
fn newenvironment_wraps_its_body() {
|
||
let source = "\\newenvironment{note}{\\textbf{Note: }}{}\n\n\\begin{note}body\\end{note}.";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
assert_eq!(geometry.environments.len(), 1);
|
||
assert_eq!(body.trim(), "\\textbf{Note: }body.");
|
||
}
|
||
|
||
#[test]
|
||
fn environment_arguments_reach_begin_and_end_codes() {
|
||
let source = "\\newenvironment{pair}[1]{(#1)}{!}\n\n\\begin{pair}{A}body\\end{pair}";
|
||
let (body, _) = geometry_and_body(source);
|
||
assert_eq!(body.trim(), "(A)body!");
|
||
}
|
||
|
||
#[test]
|
||
fn nested_environments_expand_recursively() {
|
||
let source =
|
||
"\\newenvironment{box}{(}{)}\n\n\\begin{box}a\\begin{box}b\\end{box}c\\end{box}";
|
||
let (body, _) = geometry_and_body(source);
|
||
assert_eq!(body.trim(), "(a(b)c)");
|
||
}
|
||
|
||
#[test]
|
||
fn environment_codes_expand_macros() {
|
||
let source = "\\def\\x{A}\n\\newenvironment{e}{[\\x]}{}\n\n\\begin{e}body\\end{e}";
|
||
let (body, _) = geometry_and_body(source);
|
||
assert_eq!(body.trim(), "[A]body");
|
||
}
|
||
|
||
#[test]
|
||
fn undefined_environments_stay_literal() {
|
||
let source = "\\begin{figure}x\\end{figure}";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
assert!(geometry.environments.is_empty());
|
||
assert_eq!(body.trim(), "\\begin{figure}x\\end{figure}");
|
||
}
|
||
|
||
#[test]
|
||
fn newcommand_definitions_expand_in_the_body() {
|
||
let source = "\\newcommand{\\R}{\\mathbb{R}}\n\\newcommand{\\pair}[2]{(#1,#2)}\n\n$\\R$ and $\\pair{x}{y}$";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
assert_eq!(geometry.macros.len(), 2);
|
||
assert!(!body.contains("\\newcommand"));
|
||
assert!(body.contains("\\mathbb{R}"));
|
||
assert!(body.contains("(x,y)"));
|
||
}
|
||
|
||
#[test]
|
||
fn def_definitions_expand_in_the_body() {
|
||
let (body, geometry) = geometry_and_body("\\def\\half{1/2}\n\nA \\half here.");
|
||
assert_eq!(geometry.macros.len(), 1);
|
||
assert_eq!(body.trim(), "A 1/2 here.");
|
||
}
|
||
|
||
#[test]
|
||
fn def_arguments_are_substituted() {
|
||
let (body, geometry) =
|
||
geometry_and_body("\\def\\pair#1#2{(#1, #2)}\n\nA \\pair{a}{b} pair.");
|
||
assert_eq!(geometry.macros[0].args, 2);
|
||
assert_eq!(body.trim(), "A (a, b) pair.");
|
||
}
|
||
|
||
#[test]
|
||
fn let_aliases_copy_definitions() {
|
||
let (body, geometry) = geometry_and_body("\\def\\x{A}\n\\let\\y=\\x\n\n\\y b.");
|
||
assert_eq!(geometry.macros.len(), 2);
|
||
assert_eq!(body.trim(), "A b.");
|
||
}
|
||
|
||
#[test]
|
||
fn let_to_unknown_sequence_stays_quiet() {
|
||
let (body, _) = geometry_and_body("\\let\\z=\\missing\n\na\\z b");
|
||
assert_eq!(body.trim(), "a b");
|
||
}
|
||
|
||
#[test]
|
||
fn macro_arguments_substitute_in_order() {
|
||
let definition =
|
||
macro_definition("\\newcommand{\\vect}[2]{\\mathbf{#2}^{#1}}").expect("definition");
|
||
assert_eq!(definition.args, 2);
|
||
assert_eq!(
|
||
expand_macros("\\vect{2}{x}", std::slice::from_ref(&definition)),
|
||
"\\mathbf{x}^{2}"
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn optional_macro_arguments_use_defaults() {
|
||
let definition =
|
||
macro_definition("\\newcommand{\\vect}[2][x]{(#1,#2)}").expect("definition");
|
||
assert_eq!(definition.default.as_deref(), Some("x"));
|
||
assert_eq!(
|
||
expand_macros("\\vect{y}", std::slice::from_ref(&definition)),
|
||
"(x,y)"
|
||
);
|
||
assert_eq!(
|
||
expand_macros("\\vect[z]{w}", std::slice::from_ref(&definition)),
|
||
"(z,w)"
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn macros_expand_nested_and_stop_on_recursion() {
|
||
let definitions = vec![
|
||
MacroDefinition {
|
||
name: "\\a".into(),
|
||
args: 0,
|
||
default: None,
|
||
body: "\\b".into(),
|
||
},
|
||
MacroDefinition {
|
||
name: "\\b".into(),
|
||
args: 0,
|
||
default: None,
|
||
body: "B".into(),
|
||
},
|
||
];
|
||
assert_eq!(expand_macros("\\a", &definitions), "B");
|
||
let recursive = vec![MacroDefinition {
|
||
name: "\\loop".into(),
|
||
args: 0,
|
||
default: None,
|
||
body: "\\loop".into(),
|
||
}];
|
||
assert_eq!(expand_macros("\\loop", &recursive), "\\loop");
|
||
assert_eq!(expand_macros("\\missing", &definitions), "\\missing");
|
||
}
|
||
|
||
#[test]
|
||
fn newcommand_optional_arguments_expand() {
|
||
let source = "\\newcommand{\\half}[1][2]{1/#1}\n\nA \\half.\n\nB \\half[4].";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
assert_eq!(geometry.macros[0].default.as_deref(), Some("2"));
|
||
let paragraphs =
|
||
paragraphs_with_definitions(&body, &geometry.theorem_definitions).expect("blocks");
|
||
assert_eq!(paragraphs[0].text, "A 1/2.");
|
||
assert_eq!(paragraphs[1].text, "B 1/4.");
|
||
}
|
||
|
||
#[test]
|
||
fn macros_expand_in_previews() {
|
||
let json = preview_json("\\newcommand{\\name}{Ada}\n\nHello \\name.").expect("preview");
|
||
assert!(json.contains(">A</text>"));
|
||
assert!(json.contains(">d</text>"));
|
||
}
|
||
|
||
#[test]
|
||
fn newtheorem_definitions_are_captured() {
|
||
let source = "\\newtheorem{claim}[theorem]{Claim}\n\\newtheorem*{note}{Note}\n\\newtheorem{observation}{Observation}[section]\n\nBody.";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
assert_eq!(geometry.theorem_definitions.len(), 3);
|
||
assert_eq!(geometry.theorem_definitions[0].name, "claim");
|
||
assert_eq!(geometry.theorem_definitions[0].display, "Claim");
|
||
assert_eq!(
|
||
geometry.theorem_definitions[0].shared.as_deref(),
|
||
Some("theorem")
|
||
);
|
||
assert!(geometry.theorem_definitions[1].starred);
|
||
assert_eq!(
|
||
geometry.theorem_definitions[2].within.as_deref(),
|
||
Some("section")
|
||
);
|
||
assert!(!body.contains("newtheorem"), "{body}");
|
||
}
|
||
|
||
#[test]
|
||
fn custom_theorems_share_counters_and_sections() {
|
||
let source = "\\newtheorem{claim}[theorem]{Claim}\n\\newtheorem{observation}{Observation}[section]\n\n\\section{One}\n\n\\begin{theorem}\nA theorem.\n\\end{theorem}\n\n\\begin{claim}\nA claim.\n\\end{claim}\n\n\\begin{observation}\n\\label{obs:a}An observation.\n\\end{observation}\n\nSee \\ref{obs:a}.";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
let blocks = paragraphs_with_definitions(&body, &geometry.theorem_definitions).unwrap();
|
||
let document = build_document(&blocks, &geometry);
|
||
let sources: Vec<&str> = document
|
||
.units
|
||
.iter()
|
||
.map(|unit| unit.source.as_str())
|
||
.collect();
|
||
assert!(sources.contains(&"1 One"), "{sources:?}");
|
||
assert!(sources.contains(&"Theorem 1."), "{sources:?}");
|
||
assert!(sources.contains(&"Claim 2."), "{sources:?}");
|
||
assert!(sources.contains(&"Observation 1.1."), "{sources:?}");
|
||
assert!(sources.contains(&"See 1.1."), "{sources:?}");
|
||
}
|
||
|
||
#[test]
|
||
fn starred_newtheorem_stays_unnumbered() {
|
||
let source = "\\newtheorem*{aside}{Aside}\n\n\\begin{aside}\nA remark.\n\\end{aside}";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
let blocks = paragraphs_with_definitions(&body, &geometry.theorem_definitions).unwrap();
|
||
let document = build_document(&blocks, &geometry);
|
||
assert_eq!(document.units[0].source, "Aside.");
|
||
assert_eq!(document.units[1].source, "A remark.");
|
||
}
|
||
|
||
#[test]
|
||
fn theorem_environments_number_and_label() {
|
||
let source = r"\begin{theorem}\label{thm:a}
|
||
Every group has an identity.
|
||
\end{theorem}
|
||
|
||
\begin{lemma}
|
||
A lemma follows.
|
||
\end{lemma}
|
||
|
||
See \ref{thm:a}.";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
let blocks = paragraphs(&body).unwrap();
|
||
let document = build_document(&blocks, &geometry);
|
||
assert_eq!(document.units.len(), 5);
|
||
assert_eq!(document.units[0].source, "Theorem 1.");
|
||
assert_eq!(document.units[1].source, "Every group has an identity.");
|
||
assert!(matches!(
|
||
document.units[1].items.first(),
|
||
Some(VerticalItem::Paragraph(paragraph)) if paragraph.font == ParagraphFont::Italic
|
||
));
|
||
assert_eq!(document.units[2].source, "Lemma 1.");
|
||
assert_eq!(document.units[4].source, "See 1.");
|
||
}
|
||
|
||
#[test]
|
||
fn theorem_titles_are_appended_to_the_heading() {
|
||
let source = r"\begin{theorem}[Main result]
|
||
Body.
|
||
\end{theorem}";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
let blocks = paragraphs(&body).unwrap();
|
||
let document = build_document(&blocks, &geometry);
|
||
assert_eq!(document.units[0].source, "Theorem 1 (Main result).");
|
||
}
|
||
|
||
#[test]
|
||
fn proof_headings_use_their_optional_title() {
|
||
let source = "\\begin{proof}[Proof of the claim]\nBecause it follows.\n\\end{proof}";
|
||
let blocks = paragraphs(&source).expect("paragraphs");
|
||
assert_eq!(blocks.len(), 2);
|
||
assert_eq!(blocks[0].text, "Proof of the claim.");
|
||
assert_eq!(blocks[1].font, ParagraphFont::Italic);
|
||
}
|
||
|
||
#[test]
|
||
fn proof_is_unnumbered_and_definitions_stay_roman() {
|
||
let source = r"\begin{proof}
|
||
It follows.
|
||
\end{proof}
|
||
|
||
\begin{definition}
|
||
A definition.
|
||
\end{definition}";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
let blocks = paragraphs(&body).unwrap();
|
||
let document = build_document(&blocks, &geometry);
|
||
assert_eq!(document.units[0].source, "Proof.");
|
||
assert!(matches!(
|
||
document.units[1].items.first(),
|
||
Some(VerticalItem::Paragraph(paragraph)) if paragraph.font == ParagraphFont::Italic
|
||
));
|
||
assert_eq!(document.units[2].source, "Definition 1.");
|
||
assert!(matches!(
|
||
document.units[3].items.first(),
|
||
Some(VerticalItem::Paragraph(paragraph)) if paragraph.font == ParagraphFont::Roman
|
||
));
|
||
}
|
||
|
||
#[test]
|
||
fn table_of_contents_starts_with_contents_heading() {
|
||
let source = "\\tableofcontents\n\n\\section{Intro}\n\nText.";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
let paragraphs =
|
||
paragraphs_with_definitions(&body, &geometry.theorem_definitions).expect("blocks");
|
||
let document = build_document(¶graphs, &geometry);
|
||
let names: Vec<&str> = document
|
||
.units
|
||
.iter()
|
||
.map(|unit| unit.source.as_str())
|
||
.collect();
|
||
assert_eq!(names[0], "Contents");
|
||
assert_eq!(names[1], "1 Intro");
|
||
assert_eq!(
|
||
document
|
||
.units
|
||
.iter()
|
||
.filter(|unit| unit.source == "Contents")
|
||
.count(),
|
||
1
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn short_titles_appear_in_the_table_of_contents() {
|
||
let source = "\\tableofcontents\n\n\\section[Short]{A much longer title}\n\nText.";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
let paragraphs =
|
||
paragraphs_with_definitions(&body, &geometry.theorem_definitions).expect("blocks");
|
||
let document = build_document(¶graphs, &geometry);
|
||
let names: Vec<&str> = document
|
||
.units
|
||
.iter()
|
||
.map(|unit| unit.source.as_str())
|
||
.collect();
|
||
assert!(names.contains(&"1 Short"), "{names:?}");
|
||
assert_eq!(
|
||
names
|
||
.iter()
|
||
.filter(|name| **name == "1 A much longer title")
|
||
.count(),
|
||
1,
|
||
"{names:?}"
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn contents_names_follow_renewcommand() {
|
||
let source = "\\renewcommand{\\contentsname}{Inhalt}\n\n\\tableofcontents\n\n\\section{Intro}\n\nText.";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
assert_eq!(geometry.contents_name.as_deref(), Some("Inhalt"));
|
||
let paragraphs =
|
||
paragraphs_with_definitions(&body, &geometry.theorem_definitions).expect("blocks");
|
||
let document = build_document(¶graphs, &geometry);
|
||
assert_eq!(document.units[0].source, "Inhalt");
|
||
}
|
||
|
||
#[test]
|
||
fn bibliography_starts_with_references_heading() {
|
||
let source = "See \\cite{alpha}.\n\n\\begin{thebibliography}{9}\n\\bibitem{alpha} Alpha entry.\n\\end{thebibliography}";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
let paragraphs =
|
||
paragraphs_with_definitions(&body, &geometry.theorem_definitions).expect("blocks");
|
||
let document = build_document(¶graphs, &geometry);
|
||
let names: Vec<&str> = document
|
||
.units
|
||
.iter()
|
||
.map(|unit| unit.source.as_str())
|
||
.collect();
|
||
let heading = names.iter().position(|name| *name == "References");
|
||
let entry = names.iter().position(|name| *name == "[1] Alpha entry.");
|
||
assert!(heading.is_some(), "{names:?}");
|
||
assert!(entry.is_some(), "{names:?}");
|
||
assert!(heading < entry, "{names:?}");
|
||
}
|
||
|
||
#[test]
|
||
fn reference_names_follow_renewcommand() {
|
||
let source = "\\renewcommand{\\refname}{Literatur}\n\nSee \\cite{alpha}.\n\n\\begin{thebibliography}{9}\n\\bibitem{alpha} Alpha entry.\n\\end{thebibliography}";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
assert_eq!(geometry.ref_name.as_deref(), Some("Literatur"));
|
||
let paragraphs =
|
||
paragraphs_with_definitions(&body, &geometry.theorem_definitions).expect("blocks");
|
||
let document = build_document(¶graphs, &geometry);
|
||
assert!(document.units.iter().any(|unit| unit.source == "Literatur"));
|
||
assert!(
|
||
!document
|
||
.units
|
||
.iter()
|
||
.any(|unit| unit.source == "References")
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn bibliography_entries_resolve_citations() {
|
||
let source = "See \\cite{alpha} and \\cite{alpha,beta}.\n\n\\begin{thebibliography}{9}\n\\bibitem{alpha} Alpha entry.\n\\bibitem{beta} Beta entry.\n\\end{thebibliography}";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
assert_eq!(geometry.bibliography.len(), 2);
|
||
let blocks = paragraphs(&body).unwrap();
|
||
let document = build_document(&blocks, &geometry);
|
||
let sources: Vec<&str> = document
|
||
.units
|
||
.iter()
|
||
.map(|unit| unit.source.as_str())
|
||
.collect();
|
||
assert!(sources.contains(&"See [1] and [1, 2]."), "{sources:?}");
|
||
assert!(sources.contains(&"[1] Alpha entry."), "{sources:?}");
|
||
assert!(sources.contains(&"[2] Beta entry."), "{sources:?}");
|
||
}
|
||
|
||
#[test]
|
||
fn missing_citations_print_a_question_mark() {
|
||
let blocks = paragraphs("See \\cite{missing}.").unwrap();
|
||
let document = build_document(&blocks, &PageGeometry::default());
|
||
assert_eq!(document.units[0].source, "See [?].");
|
||
}
|
||
|
||
#[test]
|
||
fn citation_notes_and_nocite_are_dropped() {
|
||
let source = "See \\citep[p.~3]{alpha} and \\citet{alpha}.\\nocite{beta}\n\n\\begin{thebibliography}{9}\n\\bibitem{alpha} Alpha entry.\n\\bibitem{beta} Beta entry.\n\\end{thebibliography}";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
let blocks = paragraphs(&body).unwrap();
|
||
let document = build_document(&blocks, &geometry);
|
||
let sources: Vec<&str> = document
|
||
.units
|
||
.iter()
|
||
.map(|unit| unit.source.as_str())
|
||
.collect();
|
||
assert_eq!(sources[0], "See [1] and [1].");
|
||
assert!(sources.contains(&"[1] Alpha entry."), "{sources:?}");
|
||
assert!(sources.contains(&"[2] Beta entry."), "{sources:?}");
|
||
}
|
||
|
||
#[test]
|
||
fn bibliography_commands_stay_out_of_the_body() {
|
||
let source = "\\bibliographystyle{plain}\n\\bibliography{refs}\n\nBody.";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
assert!(!body.contains("bibliograph"), "{body:?}");
|
||
let blocks = paragraphs(&body).unwrap();
|
||
assert_eq!(blocks.len(), 1);
|
||
assert_eq!(blocks[0].text, "Body.");
|
||
let document = build_document(&blocks, &geometry);
|
||
assert_eq!(document.units.len(), 1);
|
||
}
|
||
|
||
#[test]
|
||
fn footnotes_number_across_paragraphs() {
|
||
let blocks = paragraphs("One\\footnote{A}\n\nTwo\\footnote{B}").unwrap();
|
||
let document = build_document(&blocks, &PageGeometry::default());
|
||
assert_eq!(document.units[0].source, "One (1)");
|
||
assert_eq!(document.units[2].source, "Two (2)");
|
||
assert_eq!(document.units.len(), 4);
|
||
}
|
||
|
||
#[test]
|
||
fn reads_hang_registers_from_the_preamble() {
|
||
let (body, geometry) = geometry_and_body(
|
||
"\\hangindent=20pt\n\\hangafter=1\n\\tolerance=1000\n\\pretolerance=50\n\\looseness=-1\n\\spaceskip=6pt plus 1pt minus 0.5pt\n\\frenchspacing\n\nword word",
|
||
);
|
||
assert_eq!(geometry.hang_indent, Some(20 * 65_536));
|
||
assert_eq!(geometry.hang_after, Some(1));
|
||
let pt = 65_536;
|
||
assert_eq!(geometry.tolerance, Some(1000));
|
||
assert_eq!(geometry.pretolerance, Some(50));
|
||
assert_eq!(geometry.looseness, Some(-1));
|
||
assert_eq!(geometry.space_skip, Some((6 * pt, pt, pt / 2)));
|
||
assert_eq!(geometry.french_spacing, Some(true));
|
||
let paragraphs = paragraphs(&body).expect("paragraphs");
|
||
assert_eq!(paragraphs.len(), 1, "{body:?}");
|
||
let document = build_document(¶graphs, &geometry);
|
||
let style = document.units[0].paragraph_style.clone().expect("style");
|
||
assert_eq!(style.hang_indent, 20 * 65_536);
|
||
assert_eq!(style.hang_after, 1);
|
||
assert_eq!(style.tolerance, 1000);
|
||
assert_eq!(style.pretolerance, 50);
|
||
assert_eq!(style.looseness, -1);
|
||
assert_eq!(style.space_skip, Some((6 * pt, pt, pt / 2)));
|
||
assert!(style.frenchspacing);
|
||
}
|
||
#[test]
|
||
fn geometry_reads_hyphenation_exceptions() {
|
||
let source = "\\documentclass{article}\n\\hyphenation{zzz-zzz alpha-beta}\n\\begin{document}\n\nzzzzzz\n\n\\end{document}\n";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
assert_eq!(
|
||
geometry.hyphenation_exceptions,
|
||
vec!["zzz-zzz".to_string(), "alpha-beta".to_string()]
|
||
);
|
||
assert!(!body.contains("hyphenation"));
|
||
let paragraphs = paragraphs(&body).expect("paragraphs");
|
||
let document = build_document(¶graphs, &geometry);
|
||
let style = document.units[0]
|
||
.paragraph_style
|
||
.clone()
|
||
.expect("paragraph style");
|
||
assert_eq!(
|
||
style.hyphenation_exceptions,
|
||
geometry.hyphenation_exceptions
|
||
);
|
||
}
|
||
#[test]
|
||
fn geometry_reads_parshape() {
|
||
let source = "\\documentclass{article}\n\\parshape=2 0pt 100pt 20pt 80pt\n\\begin{document}\n\nSome words here.\n\n\\end{document}\n";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
assert_eq!(
|
||
geometry.par_shape,
|
||
vec![(0, 100 * SCALE), (20 * SCALE, 80 * SCALE)]
|
||
);
|
||
assert!(!body.contains("parshape"));
|
||
let paragraphs = paragraphs(&body).expect("paragraphs");
|
||
let document = build_document(¶graphs, &geometry);
|
||
let style = document.units[0]
|
||
.paragraph_style
|
||
.clone()
|
||
.expect("paragraph style");
|
||
assert_eq!(style.par_shape, geometry.par_shape);
|
||
}
|
||
#[test]
|
||
fn geometry_reads_parfillskip_and_lineskip() {
|
||
let source = "\\documentclass{article}\n\\parfillskip=0pt plus 1fil\n\\lineskip=2pt\n\\lineskiplimit=3pt\n\\begin{document}\n\nSome words here.\n\n\\end{document}\n";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
assert_eq!(geometry.par_fillskip, Some((0, 0, true)));
|
||
assert_eq!(geometry.lineskip, Some(2 * SCALE));
|
||
assert_eq!(geometry.lineskiplimit, Some(3 * SCALE));
|
||
assert!(!body.contains("parfillskip"));
|
||
let paragraphs = paragraphs(&body).expect("paragraphs");
|
||
let document = build_document(¶graphs, &geometry);
|
||
let style = document.units[0]
|
||
.paragraph_style
|
||
.clone()
|
||
.expect("paragraph style");
|
||
assert_eq!(style.par_fillskip, 0);
|
||
assert!(style.par_fillskip_fil);
|
||
assert_eq!(style.lineskip, 2 * SCALE);
|
||
assert_eq!(style.lineskiplimit, 3 * SCALE);
|
||
}
|
||
#[test]
|
||
fn geometry_reads_stretchy_parskip() {
|
||
let source = "\\documentclass{article}\n\\parskip=2pt plus 5pt minus 1pt\n\\begin{document}\n\nSome words here.\n\n\\end{document}\n";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
assert!(!body.contains("parskip"));
|
||
assert_eq!(geometry.par_skip, Some(2 * 65_536));
|
||
assert_eq!(geometry.par_skip_stretch, Some(5 * 65_536));
|
||
assert_eq!(geometry.par_skip_shrink, Some(65_536));
|
||
}
|
||
|
||
#[test]
|
||
fn geometry_reads_page_skip_registers() {
|
||
let source = "\\documentclass{article}\n\\topskip=10pt\n\\maxdepth=5pt\n\\splittopskip=3pt\n\\begin{document}\n\nSome words here.\n\n\\end{document}\n";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
assert_eq!(geometry.top_skip, Some(10 * SCALE));
|
||
assert_eq!(geometry.max_depth, Some(5 * SCALE));
|
||
assert_eq!(geometry.split_top_skip, Some(3 * SCALE));
|
||
assert!(!body.contains("topskip"));
|
||
let paragraphs = paragraphs(&body).expect("paragraphs");
|
||
let mut document = build_document(¶graphs, &geometry);
|
||
apply_geometry(&mut document, &geometry);
|
||
assert_eq!(document.top_skip, 10 * SCALE);
|
||
assert_eq!(document.max_depth, 5 * SCALE);
|
||
assert_eq!(document.split_top_skip, 3 * SCALE);
|
||
}
|
||
#[test]
|
||
fn geometry_reads_demerit_registers() {
|
||
let source = "\\documentclass{article}\n\\hyphenpenalty=77\n\\exhyphenpenalty=88\n\\doublehyphendemerits=1234\n\\finalhyphendemerits=4321\n\\linepenalty=20\n\\adjdemerits=999\n\\begin{document}\n\nSome words here.\n\n\\end{document}\n";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
assert_eq!(geometry.hyphen_penalty, Some(77));
|
||
assert_eq!(geometry.ex_hyphen_penalty, Some(88));
|
||
assert_eq!(geometry.double_hyphen_demerits, Some(1234));
|
||
assert_eq!(geometry.final_hyphen_demerits, Some(4321));
|
||
assert_eq!(geometry.line_penalty, Some(20));
|
||
assert_eq!(geometry.adj_demerits, Some(999));
|
||
assert!(!body.contains("hyphenpenalty"));
|
||
let paragraphs = paragraphs(&body).expect("paragraphs");
|
||
let document = build_document(¶graphs, &geometry);
|
||
let style = document.units[0]
|
||
.paragraph_style
|
||
.clone()
|
||
.expect("paragraph style");
|
||
assert_eq!(style.hyphen_penalty, 77);
|
||
assert_eq!(style.ex_hyphen_penalty, 88);
|
||
assert_eq!(style.double_hyphen_demerits, 1234);
|
||
assert_eq!(style.final_hyphen_demerits, 4321);
|
||
assert_eq!(style.line_penalty, 20);
|
||
assert_eq!(style.adj_demerits, 999);
|
||
}
|
||
#[test]
|
||
fn geometry_reads_sfcode_assignments() {
|
||
let source = "\\documentclass{article}\n\\sfcode61=1000\n\\sfcode`x=2000\n\\begin{document}\n\nSome words here.\n\n\\end{document}\n";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
assert_eq!(geometry.space_factor_codes, vec![('=', 1000), ('x', 2000)]);
|
||
assert!(!body.contains("sfcode"));
|
||
let paragraphs = paragraphs(&body).expect("paragraphs");
|
||
let document = build_document(¶graphs, &geometry);
|
||
let style = document.units[0]
|
||
.paragraph_style
|
||
.clone()
|
||
.expect("paragraph style");
|
||
assert_eq!(style.space_factor_codes, geometry.space_factor_codes);
|
||
}
|
||
#[test]
|
||
fn preview_pages_honour_page_offsets() {
|
||
let plain = preview_json("Hello route D").expect("plain preview");
|
||
let shifted =
|
||
preview_json("\\hoffset=10pt\n\\voffset=5pt\nHello route D").expect("shifted");
|
||
fn first_text_position(json: &str) -> (f64, f64) {
|
||
let value: serde_json::Value = serde_json::from_str(json).expect("JSON");
|
||
let svg = value["pages"][0]["svg"].as_str().expect("svg");
|
||
let start = svg.find("<text").expect("text element");
|
||
let rest = &svg[start..];
|
||
let x_start = rest.find("x=\"").expect("x") + 3;
|
||
let x_end = rest[x_start..].find('"').expect("x end") + x_start;
|
||
let y_start = rest.find("y=\"").expect("y") + 3;
|
||
let y_end = rest[y_start..].find('"').expect("y end") + y_start;
|
||
(
|
||
rest[x_start..x_end].parse().expect("x value"),
|
||
rest[y_start..y_end].parse().expect("y value"),
|
||
)
|
||
}
|
||
let (plain_x, plain_y) = first_text_position(&plain);
|
||
let (shifted_x, shifted_y) = first_text_position(&shifted);
|
||
assert!(
|
||
(shifted_x - plain_x - 10.0).abs() < 1.0,
|
||
"x shift {} from {}",
|
||
shifted_x,
|
||
plain_x
|
||
);
|
||
assert!(
|
||
(shifted_y - plain_y - 5.0).abs() < 1.0,
|
||
"y shift {} from {}",
|
||
shifted_y,
|
||
plain_y
|
||
);
|
||
}
|
||
#[test]
|
||
fn float_lists_follow_their_captions() {
|
||
let source = "\\listoffigures\n\n\\listoftables\n\n\\begin{figure}\n\\caption{Plot}\\label{fig:p}\n\\end{figure}\n\n\\begin{table}\n\\begin{tabular}{l}\nA\n\\end{tabular}\n\\caption{Numbers}\\label{tab:t}\n\\end{table}\n\nBody.";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
let paragraphs =
|
||
paragraphs_with_definitions(&body, &geometry.theorem_definitions).expect("blocks");
|
||
let document = build_document(¶graphs, &geometry);
|
||
let sources: Vec<&str> = document
|
||
.units
|
||
.iter()
|
||
.map(|unit| unit.source.as_str())
|
||
.collect();
|
||
assert_eq!(
|
||
sources
|
||
.iter()
|
||
.filter(|source| **source == "Figure 1: Plot")
|
||
.count(),
|
||
1,
|
||
"{sources:?}"
|
||
);
|
||
assert_eq!(
|
||
sources
|
||
.iter()
|
||
.filter(|source| **source == "Table 1: Numbers")
|
||
.count(),
|
||
1,
|
||
"{sources:?}"
|
||
);
|
||
assert_eq!(sources.len(), 7, "{sources:?}");
|
||
assert!(!sources.iter().any(|source| source.contains("texrralof")));
|
||
assert!(!sources.iter().any(|source| source.contains("texrralot")));
|
||
assert_eq!(document.units[0].source, "List of Figures");
|
||
assert_eq!(document.units[1].source, "Figure 1: Plot");
|
||
assert_eq!(document.units[2].source, "List of Tables");
|
||
assert_eq!(document.units[3].source, "Table 1: Numbers");
|
||
}
|
||
|
||
#[test]
|
||
fn setcounter_offsets_figures_and_tables() {
|
||
let source = "\\setcounter{figure}{5}\n\n\\setcounter{table}{2}\n\n\\begin{figure}\n\\caption{A}\n\\end{figure}\n\n\\begin{table}\n\\caption{B}\n\\end{table}";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
let mut blocks =
|
||
paragraphs_with_definitions(&body, &geometry.theorem_definitions).expect("blocks");
|
||
number_floats(
|
||
&mut blocks,
|
||
"Figure",
|
||
"Table",
|
||
geometry_counter(&geometry, "figure"),
|
||
geometry_counter(&geometry, "table"),
|
||
);
|
||
let captions: Vec<&str> = blocks
|
||
.iter()
|
||
.filter_map(|block| block.float.as_ref()?.caption.as_deref())
|
||
.collect();
|
||
assert!(captions.contains(&"Figure 6: A"), "{captions:?}");
|
||
assert!(captions.contains(&"Table 3: B"), "{captions:?}");
|
||
}
|
||
#[test]
|
||
fn setcounter_offsets_section_numbers() {
|
||
let source = "\\setcounter{section}{4}\n\n\\section{Intro}\n\nText.";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
assert_eq!(geometry_counter(&geometry, "section"), 4);
|
||
let paragraphs =
|
||
paragraphs_with_definitions(&body, &geometry.theorem_definitions).expect("blocks");
|
||
let document = build_document(¶graphs, &geometry);
|
||
assert_eq!(document.units[0].source, "5 Intro");
|
||
}
|
||
|
||
#[test]
|
||
fn setcounter_offsets_theorem_numbers() {
|
||
let source = "\\setcounter{theorem}{4}\n\n\\begin{theorem}\nClaim.\n\\end{theorem}";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
assert_eq!(geometry_counter(&geometry, "theorem"), 4);
|
||
let paragraphs =
|
||
paragraphs_with_definitions(&body, &geometry.theorem_definitions).expect("blocks");
|
||
let document = build_document(¶graphs, &geometry);
|
||
assert_eq!(document.units[0].source, "Theorem 5.");
|
||
}
|
||
|
||
#[test]
|
||
fn setcounter_offsets_equation_numbers() {
|
||
let source = "\\setcounter{equation}{2}\n\n\\begin{equation}\nx = 1\n\\end{equation}";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
assert_eq!(geometry_counter(&geometry, "equation"), 2);
|
||
let paragraphs = paragraphs_with_counters(
|
||
&body,
|
||
&geometry.theorem_definitions,
|
||
geometry_counter(&geometry, "equation"),
|
||
)
|
||
.expect("blocks");
|
||
assert_eq!(paragraphs[0].equation_number, Some(3));
|
||
}
|
||
|
||
#[test]
|
||
fn short_captions_follow_into_float_lists() {
|
||
let source = "\\listoffigures\n\n\\begin{figure}\n\\caption[Short caption]{A long caption}\n\\end{figure}";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
assert!(body.contains("figure"));
|
||
let blocks = paragraphs(&body).expect("paragraphs");
|
||
let document = build_document(&blocks, &geometry);
|
||
let texts: Vec<String> = document
|
||
.units
|
||
.iter()
|
||
.map(|unit| unit.source.clone())
|
||
.collect();
|
||
assert!(texts.iter().any(|text| text == "List of Figures"));
|
||
assert!(texts.iter().any(|text| text == "Figure 1: Short caption"));
|
||
let spec = blocks
|
||
.iter()
|
||
.find_map(|block| block.float.as_ref())
|
||
.expect("float");
|
||
assert_eq!(spec.caption.as_deref(), Some("A long caption"));
|
||
assert_eq!(spec.caption_short.as_deref(), Some("Short caption"));
|
||
}
|
||
|
||
#[test]
|
||
fn float_list_names_follow_renewcommand() {
|
||
let source = "\\renewcommand{\\listfigurename}{Abbildungen}\n\n\\renewcommand{\\listtablename}{Tabellen}\n\n\\listoffigures\n\n\\begin{figure}\n\\caption{Plot}\n\\end{figure}\n\n\\listoftables\n\n\\begin{table}\n\\begin{tabular}{l}\nA\n\\end{tabular}\n\\caption{Numbers}\n\\end{table}";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
assert_eq!(geometry.list_figure_name.as_deref(), Some("Abbildungen"));
|
||
assert_eq!(geometry.list_table_name.as_deref(), Some("Tabellen"));
|
||
let paragraphs =
|
||
paragraphs_with_definitions(&body, &geometry.theorem_definitions).expect("blocks");
|
||
let document = build_document(¶graphs, &geometry);
|
||
let names: Vec<&str> = document
|
||
.units
|
||
.iter()
|
||
.map(|unit| unit.source.as_str())
|
||
.collect();
|
||
assert!(names.contains(&"Abbildungen"), "{names:?}");
|
||
assert!(names.contains(&"Tabellen"), "{names:?}");
|
||
assert!(!names.contains(&"List of Figures"), "{names:?}");
|
||
assert!(!names.contains(&"List of Tables"), "{names:?}");
|
||
}
|
||
#[test]
|
||
fn secnumdepth_stops_numbering_deep_headings() {
|
||
let (body, geometry) =
|
||
geometry_and_body("\\setcounter{secnumdepth}{1}\n\n\\section{A}\n\n\\subsection{B}");
|
||
assert_eq!(geometry.secnumdepth, Some(1));
|
||
let mut blocks = paragraphs_with_definitions(&body, &[]).expect("paragraphs");
|
||
number_sections(&mut blocks, 1, 0);
|
||
assert_eq!(blocks[0].text, "1 A");
|
||
assert_eq!(blocks[0].heading_number.as_deref(), Some("1"));
|
||
assert_eq!(blocks[1].text, "B");
|
||
assert_eq!(blocks[1].heading_number, None);
|
||
}
|
||
|
||
#[test]
|
||
fn tocdepth_limits_the_table_of_contents() {
|
||
let source =
|
||
"\\tableofcontents\n\n\\setcounter{tocdepth}{1}\n\n\\section{A}\n\n\\subsection{B}";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
assert_eq!(geometry.tocdepth, Some(1));
|
||
let mut blocks = paragraphs_with_definitions(&body, &[]).expect("paragraphs");
|
||
number_sections(&mut blocks, 3, 0);
|
||
expand_toc(&mut blocks, 1, "Contents");
|
||
let section = blocks
|
||
.iter()
|
||
.filter(|block| block.text == "1 A" || block.text.ends_with(" 1 A"))
|
||
.count();
|
||
let subsection = blocks.iter().filter(|block| block.text == "1.1 B").count();
|
||
assert_eq!(section, 2, "heading plus one TOC line");
|
||
assert_eq!(subsection, 1, "heading only; no TOC line");
|
||
}
|
||
|
||
#[test]
|
||
fn paragraph_headings_number_to_five_levels() {
|
||
let source = "\\section{A}\n\n\\paragraph{P}\n\n\\subparagraph{S}\n\n\\subsection{B}\n\n\\paragraph{Q}";
|
||
let mut blocks = paragraphs(source).expect("paragraphs");
|
||
// Article's default secnumdepth is 3; the five-level counters are
|
||
// reachable by raising it, which LaTeX classes do for reports.
|
||
number_sections(&mut blocks, 5, 0);
|
||
let numbers: Vec<&str> = blocks
|
||
.iter()
|
||
.filter(|block| block.heading_level.is_some())
|
||
.map(|block| block.text.as_str())
|
||
.collect();
|
||
assert_eq!(
|
||
numbers,
|
||
["1 A", "1.0.0.1 P", "1.0.0.1.1 S", "1.1 B", "1.1.0.1 Q"]
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn table_of_contents_stops_at_subsubsections() {
|
||
let source = "\\tableofcontents\n\n\\section{A}\n\n\\paragraph{P}";
|
||
let mut blocks = paragraphs(source).expect("paragraphs");
|
||
number_sections(&mut blocks, 3, 0);
|
||
expand_toc(&mut blocks, 3, "Contents");
|
||
let paragraph_entries = blocks
|
||
.iter()
|
||
.filter(|block| block.text.trim() == "P")
|
||
.count();
|
||
assert_eq!(paragraph_entries, 1);
|
||
assert!(
|
||
blocks
|
||
.iter()
|
||
.all(|block| block.text.trim() != "\\texrratoc")
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn table_of_contents_entries_gain_page_numbers() {
|
||
let source = "\\tableofcontents\n\n\\section{One}\n\nFirst body paragraph.\n\n\\newpage\n\n\\section{Two}\n\nSecond body paragraph.";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
let paragraphs = paragraphs(&body).expect("paragraphs");
|
||
let mut document = build_document(¶graphs, &geometry);
|
||
apply_geometry(&mut document, &geometry);
|
||
let engine = layout_document(&document);
|
||
assert!(stamp_toc_pages(&mut document, &engine, &geometry));
|
||
let entries: Vec<&Unit> = document
|
||
.units
|
||
.iter()
|
||
.filter(|unit| unit.toc_target.is_some())
|
||
.collect();
|
||
assert_eq!(entries.len(), 2, "{entries:?}");
|
||
assert!(
|
||
entries[0].source.contains("..") && entries[0].source.ends_with(" 1"),
|
||
"{}",
|
||
entries[0].source
|
||
);
|
||
assert!(
|
||
entries[1].source.contains("..") && entries[1].source.ends_with(" 2"),
|
||
"{}",
|
||
entries[1].source
|
||
);
|
||
assert!(!stamp_toc_pages(&mut document, &engine, &geometry));
|
||
}
|
||
|
||
#[test]
|
||
fn toc_leaders_fill_the_measure() {
|
||
let measure = 300 * SCALE;
|
||
let leader = toc_leader("1 Intro", "1", measure).expect("leader");
|
||
assert!(leader.starts_with("1 Intro "), "{leader}");
|
||
assert!(leader.ends_with(" 1"), "{leader}");
|
||
assert!(leader.contains(".."), "{leader}");
|
||
let width = text_width_roman(&leader);
|
||
assert!(width <= measure, "leader overflows: {width} > {measure}");
|
||
let dot = Cmr10Metrics::Roman.width('.');
|
||
assert!(
|
||
measure - width < dot + SCALE / 2,
|
||
"short by {}",
|
||
measure - width
|
||
);
|
||
assert!(toc_leader("1 Intro", "1", 10 * SCALE).is_none());
|
||
}
|
||
|
||
#[test]
|
||
fn float_lists_gain_page_numbers() {
|
||
let source = "\\listoffigures\n\n\\newpage\n\n\\begin{figure}[t]\n\\caption{Picture}\n\\end{figure}\n\nBody.";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
let paragraphs =
|
||
paragraphs_with_definitions(&body, &geometry.theorem_definitions).expect("blocks");
|
||
let mut document = build_document(¶graphs, &geometry);
|
||
apply_geometry(&mut document, &geometry);
|
||
let engine = layout_document(&document);
|
||
assert!(stamp_toc_pages(&mut document, &engine, &geometry));
|
||
let entries: Vec<&Unit> = document
|
||
.units
|
||
.iter()
|
||
.filter(|unit| unit.toc_target.is_some())
|
||
.collect();
|
||
assert_eq!(entries.len(), 1, "{entries:?}");
|
||
assert!(
|
||
entries[0].source.contains("..") && entries[0].source.ends_with(" 2"),
|
||
"{}",
|
||
entries[0].source
|
||
);
|
||
assert!(!stamp_toc_pages(&mut document, &engine, &geometry));
|
||
}
|
||
|
||
#[test]
|
||
fn table_of_contents_lists_numbered_headings() {
|
||
let source = "\\tableofcontents\n\n\\section{Intro}\n\nText.\n\n\\subsection{Sub}\n\nMore.\n\n\\section*{Notes}\n\nEnd.";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
let paragraphs =
|
||
paragraphs_with_definitions(&body, &geometry.theorem_definitions).expect("blocks");
|
||
let document = build_document(¶graphs, &geometry);
|
||
let sources: Vec<&str> = document
|
||
.units
|
||
.iter()
|
||
.map(|unit| unit.source.as_str())
|
||
.collect();
|
||
assert_eq!(
|
||
sources
|
||
.iter()
|
||
.filter(|source| **source == "1 Intro")
|
||
.count(),
|
||
2,
|
||
"{sources:?}"
|
||
);
|
||
assert_eq!(
|
||
sources
|
||
.iter()
|
||
.filter(|source| **source == "1.1 Sub")
|
||
.count(),
|
||
2,
|
||
"{sources:?}"
|
||
);
|
||
assert_eq!(
|
||
sources.iter().filter(|source| **source == "Notes").count(),
|
||
1,
|
||
"{sources:?}"
|
||
);
|
||
assert!(!sources.iter().any(|source| source.contains("texrratoc")));
|
||
assert_eq!(document.units[0].source, "Contents");
|
||
assert_eq!(document.units[1].source, "1 Intro");
|
||
assert_eq!(document.units[2].source, "1.1 Sub");
|
||
assert_eq!(
|
||
document.units[2]
|
||
.paragraph_style
|
||
.as_ref()
|
||
.unwrap()
|
||
.left_skip,
|
||
12 * 65_536
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn input_directives_expand_from_the_reader() {
|
||
let source = "Before \\input{section} after \\input{nested}";
|
||
let expanded = expand_inputs(source, |name| match name {
|
||
"section" => Some("Included.".to_string()),
|
||
"nested" => Some("\\input{deep}".to_string()),
|
||
"deep" => Some("Deep.".to_string()),
|
||
_ => None,
|
||
});
|
||
assert_eq!(expanded, "Before Included. after Deep.");
|
||
assert_eq!(
|
||
expand_inputs("\\input{missing}", |_| None),
|
||
"\\input{missing}"
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn vspace_between_paragraphs_sets_vertical_glue() {
|
||
let source = "A.\n\n\\vspace{7pt plus 1pt minus 2pt}\n\nB.\n\n\\vspace*{2mm}\n\nC.";
|
||
let blocks = paragraphs(source).expect("paragraphs");
|
||
assert_eq!(blocks[1].space_before, 7 * SCALE);
|
||
assert_eq!(blocks[1].space_stretch, SCALE);
|
||
assert_eq!(blocks[1].space_shrink, 2 * SCALE);
|
||
assert!((blocks[2].space_before - 2 * 186_468).abs() <= 1);
|
||
assert!(!blocks.iter().any(|block| block.text.contains("vspace")));
|
||
}
|
||
|
||
#[test]
|
||
fn paragraphs_read_vertical_skip_commands() {
|
||
let source = "Alpha.\n\n\\medskip\n\nBeta.\n\n\\bigskip\n\nGamma.\n\n\\vskip 5pt plus 2pt minus 1pt\n\nDelta.";
|
||
let parsed = paragraphs(source).expect("paragraphs");
|
||
assert_eq!(parsed.len(), 4);
|
||
assert_eq!(parsed[0].space_before, 0);
|
||
assert_eq!(parsed[1].space_before, 6 * SCALE);
|
||
assert_eq!(parsed[1].space_stretch, 2 * SCALE);
|
||
assert_eq!(parsed[1].space_shrink, 2 * SCALE);
|
||
assert_eq!(parsed[2].space_before, 12 * SCALE);
|
||
assert_eq!(parsed[2].space_stretch, 4 * SCALE);
|
||
assert_eq!(parsed[2].space_shrink, 4 * SCALE);
|
||
assert_eq!(parsed[3].space_before, 5 * SCALE);
|
||
assert_eq!(parsed[3].space_stretch, 2 * SCALE);
|
||
assert_eq!(parsed[3].space_shrink, SCALE);
|
||
assert!(
|
||
!parsed
|
||
.iter()
|
||
.any(|paragraph| paragraph.text.contains("skip"))
|
||
);
|
||
let document = build_document(&parsed, &PageGeometry::default());
|
||
assert_eq!(document.units[1].space_before, 6 * SCALE);
|
||
assert_eq!(document.units[1].space_stretch, 2 * SCALE);
|
||
assert_eq!(document.units[1].space_shrink, 2 * SCALE);
|
||
assert_eq!(document.units[2].space_before, 12 * SCALE);
|
||
assert_eq!(document.units[3].space_before, 5 * SCALE);
|
||
assert_eq!(document.units[3].space_stretch, 2 * SCALE);
|
||
assert_eq!(document.units[3].space_shrink, SCALE);
|
||
}
|
||
#[test]
|
||
fn inline_math_becomes_math_boxes() {
|
||
let blocks = paragraphs("Value $x^2$ tail.").expect("paragraphs");
|
||
let document = build_document(&blocks, &PageGeometry::default());
|
||
let paragraph = match &document.units[0].items[0] {
|
||
VerticalItem::Paragraph(paragraph) => paragraph,
|
||
_ => panic!("expected a paragraph unit"),
|
||
};
|
||
let math = paragraph
|
||
.lines
|
||
.iter()
|
||
.flatten()
|
||
.find_map(|item| match item {
|
||
texrra_tex_core::paragraph::HorizontalItem::Box(box_) if box_.math.is_some() => {
|
||
Some(box_)
|
||
}
|
||
_ => None,
|
||
})
|
||
.expect("inline math box");
|
||
assert!(math.character.is_none());
|
||
assert!(math.width > 0);
|
||
assert_eq!(document.units[0].source, "Value $x^2$ tail.");
|
||
}
|
||
|
||
#[test]
|
||
fn inline_verb_paints_typewriter_text() {
|
||
let json = preview_json("A \\verb|x&y| b.").expect("preview");
|
||
assert!(json.contains(">x</text>"), "verb body is painted");
|
||
assert!(json.contains("monospace"), "verb body uses the mono face");
|
||
assert!(!json.contains("verb|"), "verb syntax is consumed");
|
||
}
|
||
|
||
#[test]
|
||
fn inline_math_paints_italic_glyphs() {
|
||
let json = preview_json("Value $x^2$ tail.").expect("preview");
|
||
assert!(
|
||
json.contains("font-style=") && json.contains("italic"),
|
||
"math letters use the italic face"
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn size_commands_split_sized_runs() {
|
||
let runs = inline_sized_runs("plain \\large large text", ParagraphFont::Roman)
|
||
.expect("sized runs");
|
||
assert_eq!(
|
||
runs,
|
||
vec![
|
||
(ParagraphFont::Roman, 655_360, "plain ".to_string()),
|
||
(ParagraphFont::Roman, 786_432, "large text".to_string()),
|
||
]
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn inline_size_commands_paint_bigger_glyphs() {
|
||
let json = preview_json("Body \\large Big.").expect("preview");
|
||
assert!(json.contains("12.000"), "{json}");
|
||
assert!(json.contains("10.000"), "{json}");
|
||
assert!(!json.contains("\\large"), "{json}");
|
||
}
|
||
|
||
#[test]
|
||
fn href_creates_link_boxes() {
|
||
let source = "Visit \\href{https://example.com}{the site} now.";
|
||
let blocks = paragraphs(source).expect("paragraphs");
|
||
let document = build_document(&blocks, &PageGeometry::default());
|
||
let mut linked = 0;
|
||
let mut backslashes = 0;
|
||
for unit in &document.units {
|
||
for item in &unit.items {
|
||
let VerticalItem::Paragraph(paragraph) = item else {
|
||
continue;
|
||
};
|
||
for line in ¶graph.lines {
|
||
for item in line {
|
||
let texrra_tex_core::paragraph::HorizontalItem::Box(box_) = item else {
|
||
continue;
|
||
};
|
||
if box_.link.as_deref() == Some("https://example.com") {
|
||
linked += 1;
|
||
}
|
||
if box_.character == Some('\\') {
|
||
backslashes += 1;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
assert!(linked > 0);
|
||
assert_eq!(backslashes, 0);
|
||
}
|
||
|
||
#[test]
|
||
fn sized_paragraphs_strip_href_commands() {
|
||
let source = "\\Large Visit \\href{https://example.com}{the site}.";
|
||
let blocks = paragraphs(source).expect("paragraphs");
|
||
let document = build_document(&blocks, &PageGeometry::default());
|
||
let mut linked = 0;
|
||
let mut backslashes = 0;
|
||
for unit in &document.units {
|
||
for item in &unit.items {
|
||
let VerticalItem::Paragraph(paragraph) = item else {
|
||
continue;
|
||
};
|
||
for line in ¶graph.lines {
|
||
for item in line {
|
||
let texrra_tex_core::paragraph::HorizontalItem::Box(box_) = item else {
|
||
continue;
|
||
};
|
||
if box_.link.is_some() {
|
||
linked += 1;
|
||
}
|
||
if box_.character == Some('\\') {
|
||
backslashes += 1;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
assert_eq!(linked, 0);
|
||
assert_eq!(backslashes, 0);
|
||
}
|
||
|
||
#[test]
|
||
fn inline_math_inside_styled_runs_keeps_both_faces() {
|
||
let blocks = paragraphs("\\textbf{Value $x$}").expect("paragraphs");
|
||
let document = build_document(&blocks, &PageGeometry::default());
|
||
let paragraph = match &document.units[0].items[0] {
|
||
VerticalItem::Paragraph(paragraph) => paragraph,
|
||
_ => panic!("expected a paragraph unit"),
|
||
};
|
||
let boxes: Vec<_> = paragraph
|
||
.lines
|
||
.iter()
|
||
.flatten()
|
||
.filter_map(|item| match item {
|
||
texrra_tex_core::paragraph::HorizontalItem::Box(box_) => Some(box_),
|
||
_ => None,
|
||
})
|
||
.collect();
|
||
assert!(
|
||
boxes.iter().any(|box_| box_.math.is_some()),
|
||
"the math run keeps its math box"
|
||
);
|
||
assert!(
|
||
boxes
|
||
.iter()
|
||
.any(|box_| box_.font == Some(ParagraphFont::Bold) && box_.math.is_none()),
|
||
"the surrounding text keeps its bold face"
|
||
);
|
||
assert!(
|
||
boxes.iter().all(|box_| box_.character != Some('$')),
|
||
"math delimiters are consumed"
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn displaymath_environment_becomes_a_math_block() {
|
||
let blocks =
|
||
paragraphs("\\begin{displaymath}\nx = 1\n\\end{displaymath}").expect("paragraphs");
|
||
assert_eq!(blocks.len(), 1);
|
||
assert!(blocks[0].math);
|
||
assert_eq!(blocks[0].text, "x = 1");
|
||
assert_eq!(blocks[0].equation_number, None);
|
||
}
|
||
|
||
#[test]
|
||
fn math_environment_becomes_inline_math() {
|
||
let svg = preview_json("Body \\begin{math}x\\end{math}.").expect("preview");
|
||
assert!(
|
||
svg.contains("font-style=\\\"italic\\\""),
|
||
"missing math: {svg}"
|
||
);
|
||
assert!(!svg.contains("begin{math}"), "environment leaked: {svg}");
|
||
}
|
||
|
||
#[test]
|
||
fn inline_math_stays_literal_in_sized_paragraphs() {
|
||
let blocks = paragraphs("\\large Value $x$ tail.").expect("paragraphs");
|
||
let document = build_document(&blocks, &PageGeometry::default());
|
||
let paragraph = match &document.units[0].items[0] {
|
||
VerticalItem::Paragraph(paragraph) => paragraph,
|
||
_ => panic!("expected a paragraph unit"),
|
||
};
|
||
let boxes: Vec<_> = paragraph
|
||
.lines
|
||
.iter()
|
||
.flatten()
|
||
.filter_map(|item| match item {
|
||
texrra_tex_core::paragraph::HorizontalItem::Box(box_) => Some(box_),
|
||
_ => None,
|
||
})
|
||
.collect();
|
||
assert!(boxes.iter().all(|box_| box_.math.is_none()));
|
||
assert!(boxes.iter().any(|box_| box_.character == Some('$')));
|
||
}
|
||
|
||
#[test]
|
||
fn textcolor_paints_red_glyphs() {
|
||
let source = "Body \\textcolor{red}{red} word.";
|
||
let json = preview_json(source).expect("preview");
|
||
assert!(json.contains(r##"fill=\"#ff0000\""##), "{json}");
|
||
assert!(!json.contains("textcolor"));
|
||
let pdf = pdf_bytes(source).expect("pdf");
|
||
let text = String::from_utf8_lossy(&pdf);
|
||
assert!(text.contains("1.000 0.000 0.000 rg"), "{text}");
|
||
assert!(!text.contains("textcolor"));
|
||
}
|
||
|
||
#[test]
|
||
fn text_width_sets_the_paragraph_measure() {
|
||
let long =
|
||
"A paragraph with enough words to wrap across several lines in a narrow measure.";
|
||
let line_count = |source: &str| {
|
||
let (body, geometry) = geometry_and_body(source);
|
||
let parsed = paragraphs(&body).expect("paragraphs");
|
||
let document = build_document(&parsed, &geometry);
|
||
let engine = texrra_tex_core::Engine::layout(&document);
|
||
let mut ys: Vec<i64> = Vec::new();
|
||
for page in engine.pages() {
|
||
let list = page.display_list();
|
||
ys.extend(list.items.iter().filter_map(|item| match item {
|
||
texrra_tex_core::render::DisplayItem::Text { y, .. } => Some(*y),
|
||
_ => None,
|
||
}));
|
||
}
|
||
ys.sort_unstable();
|
||
ys.dedup();
|
||
ys.len()
|
||
};
|
||
let wide = line_count(long);
|
||
let narrow = line_count(&format!("\\textwidth=240pt\n\n{long}"));
|
||
assert!(wide >= 1, "the wide measure should paint at least one line");
|
||
assert!(
|
||
narrow > wide,
|
||
"narrow measure should wrap into more lines: {narrow} vs {wide}"
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn setlength_and_hsize_set_the_measure() {
|
||
let (_, textwidth) = geometry_and_body("\\setlength{\\textwidth}{300pt}\n\nA paragraph.");
|
||
assert_eq!(textwidth.line_width, Some(300 * SCALE));
|
||
let (_, hsize) = geometry_and_body("\\hsize=360pt\n\nA paragraph.");
|
||
assert_eq!(hsize.line_width, Some(360 * SCALE));
|
||
let (_, lengths) = geometry_and_body(
|
||
"\\setlength{\\parindent}{20pt}\n\n\\setlength{\\textheight}{500pt}\n\nA paragraph.",
|
||
);
|
||
assert_eq!(lengths.line_width, None);
|
||
assert_eq!(lengths.par_indent, Some(20 * SCALE));
|
||
assert_eq!(lengths.textheight, Some(500 * SCALE));
|
||
let (_, glue) =
|
||
geometry_and_body("\\setlength{\\parskip}{6pt plus 2pt minus 1pt}\n\nA paragraph.");
|
||
assert_eq!(glue.par_skip, Some(6 * SCALE));
|
||
assert_eq!(glue.par_skip_stretch, Some(2 * SCALE));
|
||
assert_eq!(glue.par_skip_shrink, Some(SCALE));
|
||
}
|
||
|
||
#[test]
|
||
fn headings_are_numbered_and_starred_headings_are_not() {
|
||
let source = "\\section{One}\n\n\\subsection{Two}\n\n\\section*{Star}\n\n\\section{Three}";
|
||
let mut blocks = paragraphs(source).expect("blocks");
|
||
number_sections(&mut blocks, 3, 0);
|
||
assert_eq!(blocks[0].text, "1 One");
|
||
assert_eq!(blocks[1].text, "1.1 Two");
|
||
assert_eq!(blocks[2].text, "Star");
|
||
assert_eq!(blocks[3].text, "2 Three");
|
||
assert_eq!(blocks[1].heading_number.as_deref(), Some("1.1"));
|
||
assert_eq!(blocks[2].heading_number, None);
|
||
}
|
||
|
||
#[test]
|
||
fn abstract_environment_expands_into_a_heading_and_body() {
|
||
let blocks =
|
||
paragraphs("\\begin{abstract}\nShort summary.\n\\end{abstract}").expect("blocks");
|
||
assert_eq!(blocks.len(), 2);
|
||
assert_eq!(blocks[0].text, "Abstract");
|
||
assert!(blocks[0].centered);
|
||
assert_eq!(blocks[1].text, "Short summary.");
|
||
assert_eq!(blocks[1].font_size, Some((9.0 * SCALE as f64) as i64));
|
||
}
|
||
|
||
#[test]
|
||
fn section_labels_resolve_from_their_headings() {
|
||
let source = "\\section{Intro\\label{sec:intro}}\n\nSee \\ref{sec:intro}.";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
let blocks = paragraphs(&body).expect("blocks");
|
||
let document = build_document(&blocks, &geometry);
|
||
assert_eq!(document.units[0].source, "1 Intro");
|
||
assert_eq!(document.units[1].source, "See 1.");
|
||
}
|
||
|
||
#[test]
|
||
fn appendix_switches_to_letter_numbering() {
|
||
let source = "\\section{Intro}\n\n\\appendix\n\n\\section{Extra}\n\n\\subsection{Detail}";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
let blocks = paragraphs(&body).expect("blocks");
|
||
let document = build_document(&blocks, &geometry);
|
||
assert_eq!(document.units[0].source, "1 Intro");
|
||
assert_eq!(document.units[1].source, "A Extra");
|
||
assert_eq!(document.units[2].source, "A.1 Detail");
|
||
}
|
||
|
||
#[test]
|
||
fn standalone_labels_attach_to_the_previous_heading() {
|
||
let source = "\\section{A}\n\n\\subsection{B}\n\n\\label{sec:b}\n\nSee \\ref{sec:b} and \\ref{missing}.";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
let blocks = paragraphs(&body).expect("blocks");
|
||
let document = build_document(&blocks, &geometry);
|
||
assert_eq!(document.units.len(), 3);
|
||
assert_eq!(document.units[1].source, "1.1 B");
|
||
assert_eq!(document.units[2].source, "See 1.1 and ??.");
|
||
}
|
||
|
||
#[test]
|
||
fn headings_add_vertical_space_and_allow_short_titles() {
|
||
let blocks = paragraphs("\\section[Short]{Long title}").expect("blocks");
|
||
assert_eq!(blocks[0].text, "Long title");
|
||
assert!(blocks[0].space_before >= 12 * SCALE);
|
||
}
|
||
|
||
#[test]
|
||
fn heading_sizes_are_painted() {
|
||
let json = preview_json("\\section{Intro}\n\nBody").expect("preview");
|
||
assert!(json.contains("font-size=\\\"14.400\\\""), "{json}");
|
||
}
|
||
|
||
#[test]
|
||
fn heading_sizes_follow_the_class_base() {
|
||
let source = "\\section{One}\n\nBody";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
let blocks = paragraphs(&body).expect("blocks");
|
||
let document = build_document(&blocks, &geometry);
|
||
let style = document.units[0]
|
||
.paragraph_style
|
||
.clone()
|
||
.expect("heading style");
|
||
assert_eq!(style.font_size, 655_360 * 144 / 100);
|
||
assert!(style.line_height > style.font_size);
|
||
}
|
||
|
||
#[test]
|
||
fn maketitle_expands_title_author_and_date() {
|
||
let source = "\\title{Paper}\n\\author{Ada}\n\\date{2024}\n\n\\maketitle\n\nBody";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
assert_eq!(geometry.title.as_deref(), Some("Paper"));
|
||
assert_eq!(geometry.author.as_deref(), Some("Ada"));
|
||
let blocks = paragraphs(&body).expect("blocks");
|
||
let expanded = expand_maketitle(&blocks, &geometry);
|
||
assert_eq!(expanded.len(), 4);
|
||
assert_eq!(expanded[0].text, "Paper");
|
||
assert!(expanded[0].centered);
|
||
assert_eq!(expanded[0].font_size, Some((17.28 * SCALE as f64) as i64));
|
||
assert_eq!(expanded[1].text, "Ada");
|
||
assert_eq!(expanded[1].font_size, Some((12.0 * SCALE as f64) as i64));
|
||
assert_eq!(expanded[2].text, "2024");
|
||
assert_eq!(expanded[3].text, "Body");
|
||
assert!(!expanded[3].centered);
|
||
}
|
||
|
||
#[test]
|
||
fn maketitle_joins_authors_and_turns_thanks_into_footnotes() {
|
||
let source = "\\title{Paper}\n\\author{A \\and B \\thanks{Support}}\n\n\\maketitle\n\nBody";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
let blocks = paragraphs(&body).expect("blocks");
|
||
let expanded = expand_maketitle(&blocks, &geometry);
|
||
assert_eq!(expanded[1].text, "A, B \\footnote{Support}");
|
||
assert!(!expanded[1].text.contains("thanks"));
|
||
}
|
||
|
||
#[test]
|
||
fn title_thanks_becomes_a_page_footnote() {
|
||
let source = "\\title{Paper}\n\\author{Ada\\thanks{Funded}}\n\n\\maketitle\n\nBody";
|
||
let (body, geometry) = geometry_and_body(source);
|
||
let blocks = paragraphs(&body).expect("blocks");
|
||
let document = build_document(&blocks, &geometry);
|
||
let author = document
|
||
.units
|
||
.iter()
|
||
.find(|unit| unit.source.starts_with("Ada"))
|
||
.expect("author unit");
|
||
assert_eq!(author.source, "Ada (1)");
|
||
let insertion = document
|
||
.units
|
||
.iter()
|
||
.find_map(|unit| {
|
||
unit.items.iter().find_map(|item| match item {
|
||
VerticalItem::Insertion(insertion) => Some(insertion),
|
||
_ => None,
|
||
})
|
||
})
|
||
.expect("footnote insertion");
|
||
let text: String = insertion
|
||
.items
|
||
.iter()
|
||
.find_map(|item| match item {
|
||
VerticalItem::Paragraph(paragraph) => Some(
|
||
paragraph
|
||
.lines
|
||
.iter()
|
||
.flatten()
|
||
.filter_map(|item| match item {
|
||
texrra_tex_core::paragraph::HorizontalItem::Box(character) => {
|
||
character.character
|
||
}
|
||
_ => None,
|
||
})
|
||
.collect::<String>(),
|
||
),
|
||
_ => None,
|
||
})
|
||
.expect("footnote paragraph");
|
||
assert_eq!(text, "Funded");
|
||
}
|
||
|
||
#[test]
|
||
fn maketitle_paints_its_title_block() {
|
||
let source = "\\title{Paper}\n\\author{Ada}\n\n\\maketitle\n\nBody";
|
||
let json = preview_json(source).expect("preview");
|
||
assert!(json.contains("font-size=\\\"17.280\\\""), "{json}");
|
||
assert!(json.contains("font-size=\\\"12.000\\\""), "{json}");
|
||
assert!(json.contains(">B</text>"), "{json}");
|
||
}
|
||
|
||
#[test]
|
||
fn alignment_environments_set_the_block_alignment() {
|
||
let blocks = paragraphs("\\begin{center}\nCentered\n\\end{center}").expect("blocks");
|
||
assert!(blocks[0].centered);
|
||
assert!(!blocks[0].right_aligned);
|
||
let blocks = paragraphs("\\begin{flushright}\nRight\n\\end{flushright}").expect("blocks");
|
||
assert!(blocks[0].right_aligned);
|
||
assert!(!blocks[0].centered);
|
||
let blocks = paragraphs("\\begin{flushleft}\nLeft\n\\end{flushleft}").expect("blocks");
|
||
assert!(!blocks[0].centered);
|
||
assert!(!blocks[0].right_aligned);
|
||
}
|
||
|
||
#[test]
|
||
fn centered_blocks_paint_centred_lines() {
|
||
let wide = "\\begin{center}\nshort\n\\end{center}";
|
||
let blocks = paragraphs(wide).expect("blocks");
|
||
let document = build_document(&blocks, &PageGeometry::default());
|
||
let engine = texrra_tex_core::Engine::layout_paged(&document).expect("layout");
|
||
let page = &engine.pages()[0];
|
||
let x = page
|
||
.display_list()
|
||
.items
|
||
.into_iter()
|
||
.find_map(|item| match item {
|
||
texrra_tex_core::DisplayItem::Text { x, text, .. } if text == "s" => Some(x),
|
||
_ => None,
|
||
})
|
||
.expect("text");
|
||
assert!(x > 0, "centred text starts at {x}");
|
||
}
|
||
|
||
#[test]
|
||
fn geometry_package_sets_margins() {
|
||
let (_, geometry) = geometry_and_body("\\usepackage[margin=1in]{geometry}\n\nA paragraph.");
|
||
let width = geometry.line_width.expect("width");
|
||
let height = geometry.textheight.expect("height");
|
||
assert!((width - 468 * SCALE).abs() <= 2 * SCALE, "width {width}");
|
||
assert!((height - 648 * SCALE).abs() <= 2 * SCALE, "height {height}");
|
||
let (_, command) = geometry_and_body("\\geometry{left=1in,right=2in}\n\nA paragraph.");
|
||
let left_right = command.line_width.expect("left/right width");
|
||
assert!(
|
||
(left_right - 396 * SCALE).abs() <= 2 * SCALE,
|
||
"left/right width {left_right}"
|
||
);
|
||
let (_, explicit) = geometry_and_body(
|
||
"\\usepackage[margin=1in]{geometry}\n\\textwidth=300pt\n\nA paragraph.",
|
||
);
|
||
assert_eq!(explicit.line_width, Some(300 * SCALE));
|
||
}
|
||
|
||
#[test]
|
||
fn newpage_starts_a_new_page() {
|
||
let source = "Alpha beta gamma delta.\n\n\\newpage\n\nEpsilon zeta eta theta.";
|
||
let parsed = paragraphs(source).expect("paragraphs");
|
||
assert_eq!(parsed.len(), 2);
|
||
assert!(!parsed[0].page_break);
|
||
assert!(parsed[1].page_break);
|
||
let document = build_document(&parsed, &PageGeometry::default());
|
||
assert_eq!(document.page_breaks, vec![1]);
|
||
let engine = layout_document(&document);
|
||
assert_eq!(engine.pages().len(), 2);
|
||
assert!(engine.pages()[0].items.len() >= 1);
|
||
}
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod equation_tests {
|
||
use super::*;
|
||
|
||
#[test]
|
||
fn equations_are_numbered_and_labels_resolved() {
|
||
let source = r"\begin{equation}
|
||
x^2 + y^2
|
||
\label{eq:sum}
|
||
\end{equation}
|
||
|
||
See \eqref{eq:sum} and \ref{eq:sum}.
|
||
|
||
\begin{equation*}
|
||
z
|
||
\end{equation*}
|
||
|
||
\begin{equation}
|
||
a + b
|
||
\end{equation}";
|
||
let blocks = paragraphs(source).expect("paragraphs");
|
||
let numbers: Vec<u32> = blocks
|
||
.iter()
|
||
.filter_map(|block| block.equation_number)
|
||
.collect();
|
||
assert_eq!(numbers, vec![1, 2], "equation numbering");
|
||
let reference = blocks
|
||
.iter()
|
||
.find(|block| block.text.starts_with("See"))
|
||
.expect("reference paragraph");
|
||
assert_eq!(reference.text, "See (1) and 1.");
|
||
assert!(
|
||
!blocks.iter().any(|block| block.text.contains("\\label")),
|
||
"labels are stripped from equation bodies"
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn equation_tags_override_and_suppress_numbers() {
|
||
let source = r"\begin{equation}
|
||
a
|
||
\end{equation}
|
||
|
||
\begin{equation}
|
||
b
|
||
\tag{B}
|
||
\end{equation}
|
||
|
||
\begin{equation}
|
||
c
|
||
\notag
|
||
\end{equation}
|
||
|
||
\begin{equation}
|
||
d
|
||
\end{equation}";
|
||
let blocks = paragraphs(source).expect("paragraphs");
|
||
let tags: Vec<(Option<u32>, Option<String>)> = blocks
|
||
.iter()
|
||
.filter(|block| block.math)
|
||
.map(|block| (block.equation_number, block.equation_tag.clone()))
|
||
.collect();
|
||
assert_eq!(
|
||
tags,
|
||
vec![
|
||
(Some(1), None),
|
||
(None, Some("B".to_string())),
|
||
(None, None),
|
||
(Some(2), None)
|
||
]
|
||
);
|
||
assert!(
|
||
!blocks
|
||
.iter()
|
||
.any(|block| block.text.contains("\\tag") || block.text.contains("\\notag")),
|
||
"tagging commands are stripped from the formula"
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn align_rows_are_numbered_and_tagged() {
|
||
let source = r"\begin{align}
|
||
a &= b \\
|
||
c &= d \tag{C} \\
|
||
e &= f \notag \\
|
||
g &= h
|
||
\end{align}";
|
||
let blocks = paragraphs(source).expect("paragraphs");
|
||
assert_eq!(blocks.len(), 1);
|
||
let rows = &blocks[0].equation_rows;
|
||
assert_eq!(rows.len(), 4);
|
||
let numbers: Vec<Option<u32>> = rows.iter().map(|row| row.number).collect();
|
||
assert_eq!(numbers, vec![Some(1), None, None, Some(2)]);
|
||
assert_eq!(rows[1].tag.as_deref(), Some("C"));
|
||
assert!(rows[0].text.contains('&'), "cells keep their separator");
|
||
assert!(
|
||
rows.iter()
|
||
.all(|row| !row.text.contains("\\tag") && !row.text.contains("\\notag")),
|
||
"tag commands are stripped from the rows"
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn align_labels_resolve_from_their_rows() {
|
||
let source = r"\begin{align}
|
||
a &= b \label{eq:a} \\
|
||
c &= d
|
||
\end{align}
|
||
|
||
See \eqref{eq:a}.";
|
||
let blocks = paragraphs(source).expect("paragraphs");
|
||
assert_eq!(blocks[0].equation_rows[0].number, Some(1));
|
||
let reference = blocks
|
||
.iter()
|
||
.find(|block| block.text.starts_with("See"))
|
||
.expect("reference paragraph");
|
||
assert_eq!(reference.text, "See (1).");
|
||
assert!(
|
||
!blocks[0].equation_rows[0].text.contains("\\label"),
|
||
"labels are stripped from aligned rows"
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn gather_centres_its_single_cells() {
|
||
let source = r"\begin{gather*}
|
||
x \\
|
||
y
|
||
\end{gather*}";
|
||
let blocks = paragraphs(source).expect("paragraphs");
|
||
assert!(blocks[0].align_centered);
|
||
assert_eq!(blocks[0].equation_rows.len(), 2);
|
||
assert!(
|
||
blocks[0]
|
||
.equation_rows
|
||
.iter()
|
||
.all(|row| !row.text.contains('&') && row.number.is_none())
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn align_displays_draw_each_row_with_its_number() {
|
||
let source = r"\begin{align}
|
||
a &= b \\
|
||
c &= d
|
||
\end{align}";
|
||
let json = preview_json(source).expect("preview");
|
||
assert!(json.contains(">1</text>"), "first row number: {json}");
|
||
assert!(json.contains(">2</text>"), "second row number: {json}");
|
||
assert!(json.contains(">=</text>"), "relation glyph");
|
||
}
|
||
|
||
#[test]
|
||
fn numbered_equation_renders_its_tag() {
|
||
let json = preview_json("\\begin{equation}\nx^2\n\\end{equation}").expect("preview");
|
||
assert!(json.contains(">x</text>"), "formula glyphs in SVG: {json}");
|
||
assert!(json.contains(">(</text>"), "open tag parenthesis");
|
||
assert!(json.contains(">1</text>"), "equation number");
|
||
assert!(json.contains(">)</text>"), "close tag parenthesis");
|
||
}
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod nfss_tests {
|
||
use super::*;
|
||
|
||
fn paragraph_font(raw: &str) -> ParagraphFont {
|
||
paragraphs(raw).expect("paragraphs")[0].font
|
||
}
|
||
|
||
#[test]
|
||
fn declarations_select_built_in_faces() {
|
||
assert_eq!(paragraph_font("\\sffamily Sans text"), ParagraphFont::Sans);
|
||
assert_eq!(
|
||
paragraph_font("\\sffamily\\bfseries Sans text"),
|
||
ParagraphFont::SansBold
|
||
);
|
||
assert_eq!(
|
||
paragraph_font("\\sffamily\\itshape Sans text"),
|
||
ParagraphFont::SansItalic
|
||
);
|
||
assert_eq!(
|
||
paragraph_font("\\scshape Small text"),
|
||
ParagraphFont::SmallCaps
|
||
);
|
||
assert_eq!(
|
||
paragraph_font("\\sffamily\\scshape Small text"),
|
||
ParagraphFont::Sans
|
||
);
|
||
assert_eq!(
|
||
paragraph_font("\\bfseries\\scshape Small text"),
|
||
ParagraphFont::Bold
|
||
);
|
||
assert_eq!(
|
||
paragraph_font("\\scshape\\itshape Small text"),
|
||
ParagraphFont::Italic
|
||
);
|
||
assert_eq!(
|
||
paragraph_font("\\itshape\\scshape Small text"),
|
||
ParagraphFont::SmallCaps
|
||
);
|
||
assert_eq!(paragraph_font("\\ttfamily Mono text"), ParagraphFont::Mono);
|
||
assert_eq!(paragraph_font("\\bfseries Bold text"), ParagraphFont::Bold);
|
||
assert_eq!(
|
||
paragraph_font("\\itshape Italic text"),
|
||
ParagraphFont::Italic
|
||
);
|
||
assert_eq!(
|
||
paragraph_font("\\sffamily\\bfseries Bold sans"),
|
||
ParagraphFont::SansBold
|
||
);
|
||
assert_eq!(
|
||
paragraph_font("\\rmfamily\\mdseries\\upshape Roman"),
|
||
ParagraphFont::Roman
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn declarations_do_not_leak_into_the_text() {
|
||
let blocks = paragraphs("\\sffamily\\bfseries Fancy text").expect("paragraphs");
|
||
assert_eq!(blocks[0].text, "Fancy text");
|
||
}
|
||
|
||
#[test]
|
||
fn nfss_commands_configure_the_face() {
|
||
assert_eq!(
|
||
paragraph_font("\\fontfamily{cmss}\\selectfont Sans"),
|
||
ParagraphFont::Sans
|
||
);
|
||
assert_eq!(
|
||
paragraph_font("\\fontseries{bx}\\selectfont Bold"),
|
||
ParagraphFont::Bold
|
||
);
|
||
assert_eq!(
|
||
paragraph_font("\\fontshape{it}\\selectfont Italic"),
|
||
ParagraphFont::Italic
|
||
);
|
||
assert_eq!(
|
||
paragraph_font("\\fontencoding{T1}\\selectfont Roman"),
|
||
ParagraphFont::Roman
|
||
);
|
||
assert_eq!(paragraph_font("\\normalfont Reset"), ParagraphFont::Roman);
|
||
}
|
||
|
||
#[test]
|
||
fn slanted_and_italic_shapes_stay_distinct() {
|
||
assert_eq!(paragraph_font("\\slshape slanted"), ParagraphFont::Slanted);
|
||
assert_eq!(paragraph_font("\\itshape italic"), ParagraphFont::Italic);
|
||
assert_eq!(
|
||
paragraph_font("\\bfseries\\slshape bold slanted"),
|
||
ParagraphFont::BoldSlanted
|
||
);
|
||
assert_eq!(
|
||
paragraph_font("\\ttfamily\\itshape tt italic"),
|
||
ParagraphFont::MonoItalic
|
||
);
|
||
assert_eq!(
|
||
paragraph_font("\\slshape\\itshape italic"),
|
||
ParagraphFont::Italic
|
||
);
|
||
assert_eq!(
|
||
paragraph_font("\\ttfamily\\slshape tt slanted"),
|
||
ParagraphFont::MonoItalic
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn legacy_declarations_stay_bounded() {
|
||
assert_eq!(paragraph_font("\\tt Legacy mono"), ParagraphFont::Mono);
|
||
assert_eq!(paragraph_font("\\bf Legacy bold"), ParagraphFont::Bold);
|
||
let blocks = paragraphs("\\item bullet").expect("paragraphs");
|
||
assert_eq!(blocks[0].text, "\\item bullet");
|
||
}
|
||
|
||
#[test]
|
||
fn texttt_and_textsf_select_faces() {
|
||
assert_eq!(paragraph_font("\\texttt{code}"), ParagraphFont::Mono);
|
||
assert_eq!(paragraph_font("\\textsf{sans}"), ParagraphFont::Sans);
|
||
assert_eq!(paragraph_font("\\texttt{code words}"), ParagraphFont::Mono);
|
||
}
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod inline_tests {
|
||
use super::*;
|
||
|
||
#[test]
|
||
fn text_symbols_render_as_characters() {
|
||
let runs = inline_runs("\\LaTeX{} and \\ldots", ParagraphFont::Roman).expect("runs");
|
||
let text: String = runs.into_iter().map(|(_, text)| text).collect();
|
||
assert_eq!(text, "LaTeX and \u{2026}");
|
||
assert!(inline_runs("\\LaTeX{}", ParagraphFont::Roman).is_some());
|
||
}
|
||
|
||
#[test]
|
||
fn case_commands_paint_uppercase_text() {
|
||
let svg = preview_json("\\MakeUppercase{quiet}.").expect("preview");
|
||
assert!(svg.contains(">Q</text>"), "missing uppercase: {svg}");
|
||
assert!(!svg.contains("MakeUppercase"), "command leaked: {svg}");
|
||
}
|
||
|
||
#[test]
|
||
fn letter_commands_paint_unicode_glyphs() {
|
||
let svg = preview_json("Stra\\ss e").expect("preview");
|
||
assert!(svg.contains(">ß</text>"), "missing sharp s: {svg}");
|
||
assert!(!svg.contains("\\ss"), "command leaked: {svg}");
|
||
}
|
||
|
||
#[test]
|
||
fn text_superscript_paints_smaller_and_higher() {
|
||
let svg = preview_json("E = mc\\textsuperscript{2}").expect("preview");
|
||
assert!(
|
||
svg.contains("font-size=\\\"7.000\\\""),
|
||
"missing script size: {svg}"
|
||
);
|
||
assert!(svg.contains(">2</text>"), "missing script glyph: {svg}");
|
||
assert!(!svg.contains("textsuperscript"), "command leaked: {svg}");
|
||
}
|
||
|
||
#[test]
|
||
fn accent_commands_paint_precomposed_glyphs() {
|
||
let svg = preview_json("Caf\\'e au lait.").expect("preview");
|
||
assert!(svg.contains(">é</text>"), "missing composed glyph: {svg}");
|
||
assert!(!svg.contains(">'</text>"), "accent leaked as text: {svg}");
|
||
}
|
||
|
||
#[test]
|
||
fn text_symbols_paint_in_previews() {
|
||
let json = preview_json("\\LaTeX{} \\S1").expect("preview");
|
||
assert!(json.contains(">L</text>"));
|
||
assert!(json.contains(">\u{a7}</text>"));
|
||
assert!(!json.contains("LaTeX{}"));
|
||
}
|
||
|
||
#[test]
|
||
fn case_commands_transform_their_argument() {
|
||
assert_eq!(
|
||
inline_runs("\\MakeUppercase{Straße}", ParagraphFont::Roman),
|
||
Some(vec![(ParagraphFont::Roman, "STRASSE".to_string())])
|
||
);
|
||
assert_eq!(
|
||
inline_runs("\\MakeLowercase{ÀÉ}", ParagraphFont::Roman),
|
||
Some(vec![(ParagraphFont::Roman, "àé".to_string())])
|
||
);
|
||
assert_eq!(
|
||
inline_runs("\\uppercase{abc} tail", ParagraphFont::Roman),
|
||
Some(vec![(ParagraphFont::Roman, "ABC tail".to_string())])
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn letter_and_symbol_commands_render_unicode() {
|
||
assert_eq!(
|
||
inline_runs("Stra\\ss e", ParagraphFont::Roman),
|
||
Some(vec![(ParagraphFont::Roman, "Straße".to_string())])
|
||
);
|
||
assert_eq!(
|
||
inline_runs("\\ae\\oe\\aa", ParagraphFont::Roman),
|
||
Some(vec![(ParagraphFont::Roman, "æœå".to_string())])
|
||
);
|
||
assert_eq!(
|
||
inline_runs("\\o\\l\\dh\\th", ParagraphFont::Roman),
|
||
Some(vec![(ParagraphFont::Roman, "øłðþ".to_string())])
|
||
);
|
||
assert_eq!(inline_runs("\\in and \\only", ParagraphFont::Roman), None);
|
||
}
|
||
|
||
#[test]
|
||
fn text_superscripts_and_subscripts_split_sized_runs() {
|
||
assert_eq!(
|
||
inline_styled_runs("x\\textsuperscript{2}", ParagraphFont::Roman),
|
||
Some(vec![
|
||
(ParagraphFont::Roman, 655_360, 0, "x".to_string()),
|
||
(ParagraphFont::Roman, 458_752, 262_144, "2".to_string()),
|
||
])
|
||
);
|
||
assert_eq!(
|
||
inline_styled_runs("x\\textsubscript{i}", ParagraphFont::Roman),
|
||
Some(vec![
|
||
(ParagraphFont::Roman, 655_360, 0, "x".to_string()),
|
||
(ParagraphFont::Roman, 458_752, -262_144, "i".to_string()),
|
||
])
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn accent_commands_compose_characters() {
|
||
assert_eq!(
|
||
inline_runs("caf\\'e", ParagraphFont::Roman),
|
||
Some(vec![(ParagraphFont::Roman, "café".to_string())])
|
||
);
|
||
assert_eq!(
|
||
inline_runs("na\\\"ive", ParagraphFont::Roman),
|
||
Some(vec![(ParagraphFont::Roman, "naïve".to_string())])
|
||
);
|
||
assert_eq!(
|
||
inline_runs("\\c{c}a", ParagraphFont::Roman),
|
||
Some(vec![(ParagraphFont::Roman, "ça".to_string())])
|
||
);
|
||
assert_eq!(
|
||
inline_runs("\\'q", ParagraphFont::Roman),
|
||
Some(vec![(ParagraphFont::Roman, "q\u{301}".to_string())])
|
||
);
|
||
assert_eq!(
|
||
inline_runs("\\vspace and \\cup", ParagraphFont::Roman),
|
||
None
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn verb_spans_render_monospaced() {
|
||
let runs = inline_runs("a \\verb|x&y| b", ParagraphFont::Roman).expect("runs");
|
||
assert_eq!(
|
||
runs,
|
||
vec![
|
||
(ParagraphFont::Roman, "a ".to_string()),
|
||
(ParagraphFont::Mono, "x&y".to_string()),
|
||
(ParagraphFont::Roman, " b".to_string()),
|
||
]
|
||
);
|
||
let star = inline_runs("\\verb*!a_b!", ParagraphFont::Roman).expect("runs");
|
||
assert_eq!(star, vec![(ParagraphFont::Mono, "a_b".to_string())]);
|
||
}
|
||
|
||
#[test]
|
||
fn inline_commands_split_runs() {
|
||
let runs = inline_runs("Plain \\textbf{bold} tail", ParagraphFont::Roman).expect("runs");
|
||
assert_eq!(
|
||
runs,
|
||
vec![
|
||
(ParagraphFont::Roman, "Plain ".to_string()),
|
||
(ParagraphFont::Bold, "bold".to_string()),
|
||
(ParagraphFont::Roman, " tail".to_string()),
|
||
]
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn textsl_selects_the_slanted_shape() {
|
||
let runs = inline_runs("\\textsl{slanted}", ParagraphFont::Roman).expect("runs");
|
||
assert_eq!(runs[0], (ParagraphFont::Slanted, "slanted".to_string()));
|
||
let runs = inline_runs("\\textbf{\\textsl{slanted}}", ParagraphFont::Roman).expect("runs");
|
||
assert_eq!(runs[0], (ParagraphFont::BoldSlanted, "slanted".to_string()));
|
||
}
|
||
|
||
#[test]
|
||
fn textsc_composes_with_the_surrounding_face() {
|
||
let runs = inline_runs("\\textsc{small}", ParagraphFont::Roman).expect("runs");
|
||
assert_eq!(runs[0], (ParagraphFont::SmallCaps, "small".to_string()));
|
||
let runs = inline_runs("\\textbf{\\textsc{small}}", ParagraphFont::Roman).expect("runs");
|
||
assert_eq!(runs[0], (ParagraphFont::Bold, "small".to_string()));
|
||
}
|
||
|
||
#[test]
|
||
fn textsf_inside_bold_stays_bold() {
|
||
let runs = inline_runs("\\textbf{a \\textsf{b}}", ParagraphFont::Roman).expect("runs");
|
||
assert_eq!(runs[1], (ParagraphFont::SansBold, "b".to_string()));
|
||
}
|
||
|
||
#[test]
|
||
fn plain_paragraphs_have_no_runs() {
|
||
assert!(inline_runs("no commands here", ParagraphFont::Sans).is_none());
|
||
}
|
||
|
||
#[test]
|
||
fn base_font_fills_plain_segments() {
|
||
let runs = inline_runs("\\texttt{code} and text", ParagraphFont::Sans).expect("runs");
|
||
assert_eq!(runs[0], (ParagraphFont::Mono, "code".to_string()));
|
||
assert_eq!(runs[1], (ParagraphFont::Sans, " and text".to_string()));
|
||
}
|
||
|
||
#[test]
|
||
fn declarations_switch_the_following_text() {
|
||
let runs = inline_runs("plain \\bfseries bold", ParagraphFont::Roman).expect("runs");
|
||
assert_eq!(
|
||
runs,
|
||
vec![
|
||
(ParagraphFont::Roman, "plain ".to_string()),
|
||
(ParagraphFont::Bold, "bold".to_string()),
|
||
]
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn mid_paragraph_declarations_stay_inside_their_group() {
|
||
let runs = inline_runs("a {\\bfseries b} c", ParagraphFont::Roman).expect("runs");
|
||
assert_eq!(
|
||
runs,
|
||
vec![
|
||
(ParagraphFont::Roman, "a ".to_string()),
|
||
(ParagraphFont::Bold, "b".to_string()),
|
||
(ParagraphFont::Roman, " c".to_string()),
|
||
]
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn em_toggles_emphasis() {
|
||
let runs = inline_runs("a \\em b", ParagraphFont::Roman).expect("runs");
|
||
assert_eq!(runs[0], (ParagraphFont::Roman, "a ".to_string()));
|
||
assert_eq!(runs[1].0, ParagraphFont::Italic);
|
||
assert_eq!(runs[1].1, "b");
|
||
let runs = inline_runs("a {\\bfseries b \\em c}", ParagraphFont::Roman).expect("runs");
|
||
assert!(
|
||
runs.iter()
|
||
.any(|(font, _)| *font == ParagraphFont::BoldItalic)
|
||
);
|
||
assert!(inline_runs("\\emph{x}", ParagraphFont::Roman).is_some());
|
||
}
|
||
|
||
#[test]
|
||
fn declaration_groups_switch_the_face() {
|
||
let runs = inline_runs("{\\bfseries bold} normal", ParagraphFont::Roman).expect("runs");
|
||
assert_eq!(
|
||
runs,
|
||
vec![
|
||
(ParagraphFont::Bold, "bold".to_string()),
|
||
(ParagraphFont::Roman, " normal".to_string()),
|
||
]
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn nested_groups_recurse() {
|
||
let runs = inline_runs(
|
||
"{\\bfseries bold \\textit{italic} bold} plain",
|
||
ParagraphFont::Roman,
|
||
)
|
||
.expect("runs");
|
||
assert_eq!(
|
||
runs,
|
||
vec![
|
||
(ParagraphFont::Bold, "bold ".to_string()),
|
||
(ParagraphFont::BoldItalic, "italic".to_string()),
|
||
(ParagraphFont::Bold, " bold".to_string()),
|
||
(ParagraphFont::Roman, " plain".to_string()),
|
||
]
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn emph_inside_bold_is_bold_italic() {
|
||
let runs = inline_runs(
|
||
"{\\bfseries bold \\emph{bold italic} bold}",
|
||
ParagraphFont::Roman,
|
||
)
|
||
.expect("runs");
|
||
assert_eq!(
|
||
runs,
|
||
vec![
|
||
(ParagraphFont::Bold, "bold ".to_string()),
|
||
(ParagraphFont::BoldItalic, "bold italic".to_string()),
|
||
(ParagraphFont::Bold, " bold".to_string()),
|
||
]
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn emph_inside_italic_returns_upright() {
|
||
let runs = inline_runs("{\\itshape it \\emph{up} it}", ParagraphFont::Roman).expect("runs");
|
||
assert_eq!(
|
||
runs,
|
||
vec![
|
||
(ParagraphFont::Italic, "it ".to_string()),
|
||
(ParagraphFont::Roman, "up".to_string()),
|
||
(ParagraphFont::Italic, " it".to_string()),
|
||
]
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn textmd_inside_bold_drops_weight() {
|
||
let runs =
|
||
inline_runs("\\textbf{a \\textmd{plain} b}", ParagraphFont::Roman).expect("runs");
|
||
assert_eq!(
|
||
runs,
|
||
vec![
|
||
(ParagraphFont::Bold, "a ".to_string()),
|
||
(ParagraphFont::Roman, "plain".to_string()),
|
||
(ParagraphFont::Bold, " b".to_string()),
|
||
]
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn wrapper_groups_keep_nested_braces() {
|
||
let runs = inline_runs("\\textbf{a {b} c}", ParagraphFont::Roman).expect("runs");
|
||
assert_eq!(runs, vec![(ParagraphFont::Bold, "a b c".to_string())]);
|
||
}
|
||
|
||
#[test]
|
||
fn styled_runs_paint_with_their_face() {
|
||
let document = Document::new(
|
||
550 * 65_536,
|
||
vec![Unit::paragraph_with_style_and_runs(
|
||
1,
|
||
"plain bold",
|
||
ParagraphStyle::default(),
|
||
vec![
|
||
(ParagraphFont::Roman, "plain ".to_string()),
|
||
(ParagraphFont::Bold, "bold".to_string()),
|
||
],
|
||
)],
|
||
);
|
||
let engine = Engine::layout_paged(&document).expect("pages");
|
||
let list = engine.pages()[0].display_list_with_goal(document.page_goal);
|
||
assert!(list.items.iter().any(|item| matches!(
|
||
item,
|
||
texrra_tex_core::render::DisplayItem::Text {
|
||
font: texrra_tex_core::render::FontFace::Bold,
|
||
..
|
||
}
|
||
)));
|
||
}
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod edit_tests {
|
||
use super::*;
|
||
|
||
#[test]
|
||
fn paragraph_edits_keep_inline_runs() {
|
||
let _ = preview_json("plain start").expect("preview");
|
||
let json = edit_json("\\textbf{bold} start", 0).expect("edit");
|
||
assert!(json.contains(r#"font-weight=\"bold\""#), "{json}");
|
||
}
|
||
}
|