Files
texrra-engine/src/route_d.rs
T
gloamxun 1a74ece3ba Accept baselinestretch as the linespread factor
LaTeX classes often set leading through \renewcommand{\baselinestretch}
instead of \linespread. Both forms, including \def\baselinestretch, now
feed the same factor and scale the class baseline.
2026-10-25 00:11:49 +08:00

7209 lines
257 KiB
Rust
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! 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::pdf::{PageOrigin, display_lists_to_pdf_with_cm_type1};
pub use texrra_tex_core::render::RasterImage;
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 paragraphs = paragraphs_with_definitions(&body, &geometry.theorem_definitions)?;
let mut document = build_document(&paragraphs, &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(&paragraphs)
.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 json = render_json(&document, &engine, Some((&changed, recomputed)));
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>,
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)>,
/// `\title{...}` captured from the preamble.
title: Option<String>,
/// `\author{...}` captured from the preamble.
author: Option<String>,
/// `\date{...}` captured from the preamble.
date: 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,
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, 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 rest = rest.trim_start();
if rest.starts_with('[') {
// Optional arguments are not supported yet.
return None;
}
let body = rest.strip_prefix('{')?;
let (body, _) = take_group_after_open(body)?;
Some(MacroDefinition { name, args, 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 Some((args, consumed)) =
macro_arguments(&after_slash[length..], definition.args)
{
output.push_str(&substitute_macro_args(&definition.body, &args));
index += 1 + length + consumed;
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{\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 counter_assignment(line: &str, name: &str) -> Option<u32> {
let rest = line.strip_prefix("\\setcounter")?.trim_start();
let rest = rest.strip_prefix('{')?;
let close = rest.find('}')?;
if rest[..close].trim() != name {
return None;
}
let rest = rest[close + 1..].trim_start();
let rest = rest.strip_prefix('{')?;
let close = rest.find('}')?;
rest[..close].trim().parse().ok()
}
fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
let mut geometry = PageGeometry::default();
let mut body = String::new();
let mut tabular: Option<(String, String)> = None;
for line in source.lines() {
let trimmed = line.trim();
if let Some((_, text)) = tabular.as_mut() {
if trimmed == "\\end{tabular}" {
let (template, text) = tabular.take().unwrap();
geometry.tabular.push((template, text));
} else {
if !text.is_empty() {
text.push('\n');
}
text.push_str(trimmed);
}
continue;
}
if let Some(rest) = trimmed.strip_prefix("\\begin{tabular}") {
if let Some((template, _)) = braced(rest.trim_start()) {
if !body.ends_with('\n') {
body.push('\n');
}
body.push_str(&format!("\\texrratable{{{}}}\n", geometry.tabular.len()));
tabular = Some((template.to_string(), String::new()));
}
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(depth) = counter_assignment(trimmed, "secnumdepth") {
geometry.secnumdepth = Some(depth);
continue;
}
if let Some(depth) = counter_assignment(trimmed, "tocdepth") {
geometry.tocdepth = Some(depth);
continue;
}
if let Some(spread) = baselinestretch_assignment(trimmed) {
geometry.linespread = Some(spread);
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 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,
body: String::new(),
});
geometry.macros.push(MacroDefinition {
name,
args: definition.args,
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 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((name, value)) = setlength_assignment(trimmed) {
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),
_ => {}
}
} 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(value) = dimension_assignment(trimmed, "baselineskip") {
geometry.baseline_skip = 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)) = tabular {
geometry.tabular.push((template, text));
}
(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
}
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;
}
}
_ => {}
}
}
}
}
'|' | ' ' | '\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.
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 {
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 after = rest[index + r"\cite".len()..].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 setlength_assignment(line: &str) -> Option<(String, i64)> {
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('}')?;
parse_dimension(value.trim()).map(|value| (name.to_string(), 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,
_ => 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))
}
/// 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 paragraphs = paragraphs_with_definitions(&body, &geometry.theorem_definitions)?;
let mut document = build_document(&paragraphs, &geometry);
apply_geometry(&mut document, &geometry);
let engine = layout_document(&document);
let json = render_json(&document, &engine, None);
// 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 paragraphs = paragraphs_with_definitions(&body, &geometry.theorem_definitions)?;
let mut document = build_document(&paragraphs, &geometry);
apply_geometry(&mut document, &geometry);
let engine = layout_document(&document);
let 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();
Ok(display_lists_to_pdf_with_cm_type1(
&pages,
document.paper_width,
document.paper_height,
geometry.origin,
))
}
/// 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 paragraphs = paragraphs_with_definitions(&body, &geometry.theorem_definitions)?;
if unit >= paragraphs.len() {
return Err(format!(
"unit {unit} is out of range for {} paragraphs",
paragraphs.len()
));
}
let next = build_document(&paragraphs, &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 = &paragraphs[unit];
match inline_runs(&paragraph.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 json = render_json(&next, &engine, Some((&changed, recomputed)));
*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>,
/// 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>,
}
/// The kind of a LaTeX float environment.
#[derive(Clone, Copy, PartialEq, Eq)]
enum FloatKind {
Figure,
Table,
}
impl FloatKind {
fn caption_prefix(self) -> &'static str {
match self {
FloatKind::Figure => "Figure",
FloatKind::Table => "Table",
}
}
}
/// 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>,
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> {
let paragraphs: Vec<&str> = source
.split("\n\n")
.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 {
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,
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);
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);
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]) {
let mut number = 0;
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) = match figure_caption(inner) {
Some((text, starred)) => (Some(text), starred),
None => (None, false),
};
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 {
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,
footnotes: Vec::new(),
theorem: None,
font_size: None,
float: Some(FloatSpec {
kind,
placement,
width,
height,
scale,
keep_aspectratio,
caption,
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 {
for option in spec.chars() {
match option {
'b' => return FloatPlacement::Bottom,
'h' => return FloatPlacement::Here,
't' => return FloatPlacement::Top,
_ => {}
}
}
FloatPlacement::Top
}
fn figure_caption(inner: &str) -> Option<(String, bool)> {
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 = match after.strip_prefix('[') {
Some(short) => match short.find(']') {
Some(end) => short[end + 1..].trim_start(),
None => after,
},
None => after,
};
let (body, _) = braced_group(after)?;
Some((body.trim().to_string(), starred))
}
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 = SourceParagraph {
text: format!("{display}."),
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,
footnotes: Vec::new(),
theorem: Some(TheoremSpec {
name: name.clone(),
display,
title,
starred,
number: None,
labels,
}),
font_size: None,
float: None,
};
let italic = matches!(
name.as_str(),
"theorem" | "lemma" | "corollary" | "proposition" | "proof"
);
let statement = SourceParagraph {
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,
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 => "* ",
_ => "• ",
}
}
fn list_paragraph(text: String, depth: usize) -> SourceParagraph {
SourceParagraph {
text,
font: ParagraphFont::Roman,
line_height: 12,
math: false,
left_skip: 12 * (depth as i64 + 1),
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,
footnotes: Vec::new(),
theorem: None,
float: None,
font_size: None,
}
}
/// 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 {
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,
font_size: None,
footnotes: Vec::new(),
float: None,
theorem: None,
});
}
Some(blocks)
}
fn list_blocks(
raw: &str,
depth: usize,
_definitions: &[TheoremDefinition],
) -> Option<Vec<SourceParagraph>> {
let (environment, body) = list_environment(raw)?;
let mut blocks = Vec::new();
let mut number = 0_u32;
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!("{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() {
blocks.push(list_paragraph(format!("{label}{}", before.trim()), depth));
}
if let Some(nested) = nested {
if let Some(nested_blocks) = list_blocks(&nested, depth + 1, _definitions) {
blocks.extend(nested_blocks);
}
}
if !after.trim().is_empty() {
blocks.push(list_paragraph(after.trim().to_string(), depth));
}
}
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 {
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,
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_starred: false,
image,
table: None,
}),
})
}
fn parse_blocks_raw(raw: &str, definitions: &[TheoremDefinition]) -> 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(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 {
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,
footnotes: Vec::new(),
theorem: None,
float: None,
font_size: Some((12.0 * SCALE as f64) as i64),
};
let body = SourceParagraph {
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,
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 block = parse_paragraph(body);
block.centered = centered;
block.right_aligned = right_aligned;
return vec![block];
}
if let Some(blocks) = verbatim_blocks(raw) {
return blocks;
}
if let Some(blocks) = list_blocks(raw, 0, definitions) {
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 {
text: text.to_string(),
font: ParagraphFont::Roman,
line_height: 12,
math: false,
left_skip: 12,
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,
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))
}
#[cfg_attr(not(test), allow(dead_code))]
fn nfss_font(raw: &str, base: ParagraphFont) -> Option<(ParagraphFont, String)> {
nfss_font_with_size(raw, base).map(|(font, _, body)| (font, body))
}
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("\\(") {
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 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;
for part in split_hrefs(text) {
match part {
HrefPart::Plain(piece) => {
let runs = inline_sized_runs(&piece, base)
.unwrap_or_else(|| vec![(base, style.font_size, piece.clone())]);
for (font, size, 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 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).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_sized_runs(text: &str, base: ParagraphFont) -> Option<Vec<(ParagraphFont, i64, String)>> {
let mut runs = Vec::new();
let mut found = false;
parse_runs(text, base, 655_360, &mut runs, &mut found);
if !found {
return None;
}
Some(runs)
}
fn push_run(
runs: &mut Vec<(ParagraphFont, i64, String)>,
font: ParagraphFont,
size: i64,
text: &str,
) {
if text.is_empty() {
return;
}
if let Some((last_font, last_size, last_text)) = runs.last_mut()
&& *last_font == font
&& *last_size == size
{
last_text.push_str(text);
return;
}
runs.push((font, size, 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(),
))
}
fn parse_runs(
text: &str,
font: ParagraphFont,
size: i64,
runs: &mut Vec<(ParagraphFont, 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, &body);
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), 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, runs, found);
index += length;
continue;
}
if let Some((wrapper_font, inner, length)) = inline_wrapper(rest, font) {
*found = true;
parse_runs(inner, wrapper_font, size, runs, found);
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, &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, &rest[..step]);
index += step;
}
}
/// Recognize a `\section`-family command: level, starred, and title.
fn heading_command(raw: &str) -> Option<(u8, bool, 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();
// Discard the optional short title: `\section[Short]{Long}`.
let rest = match rest.strip_prefix('[') {
Some(short) => match short.split_once(']') {
Some((_, rest)) => rest.trim_start(),
None => rest,
},
None => rest,
};
let (body, _) = braced_group(rest)?;
return Some((level, starred, body.trim().to_string()));
}
None
}
fn parse_paragraph(raw: &str) -> SourceParagraph {
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 {
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,
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 {
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,
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 {
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,
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 {
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,
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 {
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,
footnotes: Vec::new(),
theorem: None,
float: None,
font_size: None,
};
}
if let Some((level, starred, title)) = heading_command(raw) {
return SourceParagraph {
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,
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 {
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,
footnotes: Vec::new(),
theorem: None,
float: None,
font_size: None,
};
}
}
SourceParagraph {
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,
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 {
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,
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.
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) -> Vec<(String, String)> {
let mut counters = [0u32; 5];
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],
) -> 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 => {
counters.push((counter, 1));
1
}
};
let within_section =
definition.and_then(|definition| definition.within.as_deref()) == Some("section");
theorem.number = Some(if within_section {
match &section {
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]) -> Vec<(String, String)> {
let mut figures = 0u32;
let mut tables = 0u32;
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
}
};
*caption = format!(
"{} {number}: {}",
spec.kind.caption_prefix(),
caption.trim()
);
for label in found {
labels.push((label, number.to_string()));
}
}
labels
}
/// Append `thebibliography` entries as numbered paragraphs.
fn append_bibliography(paragraphs: &mut Vec<SourceParagraph>, bibliography: &[(String, String)]) {
for (index, (_, entry)) in bibliography.iter().enumerate() {
paragraphs.push(SourceParagraph {
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 { 12 * 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,
footnotes: Vec::new(),
theorem: None,
float: None,
font_size: None,
});
}
}
fn expand_toc(paragraphs: &mut Vec<SourceParagraph>, tocdepth: u32) {
let entries: Vec<(u8, 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| (paragraph.heading_level.unwrap_or(1), paragraph.text.clone()))
.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());
for (index, (level, text)) in entries.iter().enumerate() {
toc.push(SourceParagraph {
text: text.clone(),
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: if index == 0 { space_before } else { 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,
font_size: None,
footnotes: Vec::new(),
float: None,
theorem: None,
});
}
paragraphs.splice(position..=position, toc);
}
fn expand_float_lists(paragraphs: &mut Vec<SourceParagraph>) {
let figures: Vec<String> = paragraphs
.iter()
.filter_map(|paragraph| match &paragraph.float {
Some(spec) if spec.kind == FloatKind::Figure => spec.caption.clone(),
_ => None,
})
.collect();
let tables: Vec<String> = paragraphs
.iter()
.filter_map(|paragraph| match &paragraph.float {
Some(spec) if spec.kind == FloatKind::Table => spec.caption.clone(),
_ => None,
})
.collect();
for (marker, entries) in [("\\texrralof", figures), ("\\texrralot", tables)] {
let Some(position) = paragraphs
.iter()
.position(|paragraph| paragraph.text.trim() == marker)
else {
continue;
};
let space_before = paragraphs[position].space_before;
let mut list = Vec::with_capacity(entries.len());
for (index, text) in entries.iter().enumerate() {
list.push(SourceParagraph {
text: text.clone(),
page_break: false,
centered: false,
right_aligned: false,
font: ParagraphFont::Roman,
line_height: 12,
math: false,
left_skip: 0,
space_before: if index == 0 { space_before } else { 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,
font_size: None,
footnotes: Vec::new(),
float: None,
theorem: None,
});
}
paragraphs.splice(position..=position, list);
}
}
fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Document {
let mut paragraphs = expand_maketitle(paragraphs, geometry);
let section_labels = number_sections(&mut paragraphs, geometry.secnumdepth.unwrap_or(3));
expand_toc(&mut paragraphs, geometry.tocdepth.unwrap_or(3));
let mut references = section_labels;
references.extend(number_theorems(
&mut paragraphs,
&geometry.theorem_definitions,
));
references.extend(number_floats(&mut paragraphs));
expand_float_lists(&mut paragraphs);
resolve_section_refs(&mut paragraphs, &references);
number_footnotes(&mut paragraphs);
resolve_citations(&mut paragraphs, &geometry.bibliography);
append_bibliography(&mut paragraphs, &geometry.bibliography);
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) = &paragraph.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)) = geometry.tabular.get(table) {
let table_unit = Unit::halign_from_source_with_template_and_tabskips(
index as u64,
&engine_template(template),
source,
6 * SCALE,
Vec::new(),
);
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(&paragraph.text) {
if let Some((template, source)) = geometry.tabular.get(table) {
let mut unit = Unit::halign_from_source_with_template_and_tabskips(
index as u64,
&engine_template(template),
source,
6 * SCALE,
Vec::new(),
);
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.equation_rows.is_empty() {
parse_math(&paragraph.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 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 style = ParagraphStyle {
line_width,
left_skip: paragraph.left_skip * SCALE + geometry.left_skip.unwrap_or(0),
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),
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: geometry.par_indent.unwrap_or(0),
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(&paragraph.text);
let mut unit = match inline_math_segments(&paragraph.text, paragraph.font, &style) {
Some(segments) => Unit::paragraph_with_style_and_segments(
index as u64,
paragraph.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 &paragraph.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));
}
}
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 render_json(document: &Document, engine: &Engine, edit: Option<(&[usize], usize)>) -> String {
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\":["
);
for (index, page) in engine.pages().iter().enumerate() {
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.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, ",\"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(&paragraphs, &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(&paragraphs, &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(&paragraphs, &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 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(&paragraphs, &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(&paragraphs, &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(&paragraphs, &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}|}"), "lcp{3cm}");
assert_eq!(engine_template("|p{2cm}|r|"), "p{2cm}r");
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 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 &paragraph.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 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);
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 &paragraph.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 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, "Term — Definition");
assert_eq!(blocks[0].left_skip, 12);
}
#[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 macros_expand_nested_and_stop_on_recursion() {
let definitions = vec![
MacroDefinition {
name: "\\a".into(),
args: 0,
body: "\\b".into(),
},
MacroDefinition {
name: "\\b".into(),
args: 0,
body: "B".into(),
},
];
assert_eq!(expand_macros("\\a", &definitions), "B");
let recursive = vec![MacroDefinition {
name: "\\loop".into(),
args: 0,
body: "\\loop".into(),
}];
assert_eq!(expand_macros("\\loop", &recursive), "\\loop");
assert_eq!(expand_macros("\\missing", &definitions), "\\missing");
}
#[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_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 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 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(&paragraphs, &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(&paragraphs, &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(&paragraphs, &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(&paragraphs, &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(&paragraphs, &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(&paragraphs, &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(&paragraphs, &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(&paragraphs, &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(), 5, "{sources:?}");
assert!(!sources.iter().any(|source| source.contains("texrralof")));
assert!(!sources.iter().any(|source| source.contains("texrralot")));
assert_eq!(document.units[0].source, "Figure 1: Plot");
assert_eq!(document.units[1].source, "Table 1: Numbers");
}
#[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);
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);
expand_toc(&mut blocks, 1);
let section = blocks.iter().filter(|block| block.text == "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);
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);
expand_toc(&mut blocks, 3);
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_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(&paragraphs, &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, "1 Intro");
assert_eq!(document.units[1].source, "1.1 Sub");
assert_eq!(
document.units[1]
.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 &paragraph.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 &paragraph.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 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 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);
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 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}");
}
}