//! Route-D preview endpoints: a small, independent TeX-style page pipeline. //! //! These endpoints are intentionally separate from the v1 `DocumentModel` //! preview. They demonstrate checkpointed, page-hashed output from the route-D //! core. The v1 preview remains the default and the fallback. use std::cell::RefCell; use std::collections::HashMap; use std::fmt::Write as _; use std::sync::{Mutex, OnceLock}; use texrra_tex_core::cmr10::Cmr10Metrics; use texrra_tex_core::math::{AlignedRow, MathAtom, parse_math, split_math_lines}; use texrra_tex_core::paragraph::HorizontalItem; use texrra_tex_core::pdf::{ PageOrigin, PdfMetadata, PdfOutlineEntry, display_lists_to_pdf_with_cm_type1_and_metadata, }; pub use texrra_tex_core::render::RasterImage; use texrra_tex_core::render::{DisplayItem, DisplayList, FontFace}; use texrra_tex_core::{ Document, Engine, FloatPlacement, InsertionClass, ParagraphFont, ParagraphStyle, Unit, VerticalItem, }; const SCALE: i64 = 65_536; thread_local! { static ROUTE_D_SESSION: RefCell> = const { RefCell::new(None) }; } struct ProjectSession { paragraphs: Vec, geometry: PageGeometry, engine: Engine, } fn project_sessions() -> &'static Mutex> { static SESSIONS: OnceLock>> = 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 { 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, ) -> Result { let (body, mut geometry) = geometry_and_body_with_images(source, images); let body = resolve_page_references(body, &geometry); let paragraphs = paragraphs_with_geometry( &body, &geometry.theorem_definitions, geometry_counter(&geometry, "equation"), &geometry, )?; let mut document = build_document(¶graphs, &geometry); apply_geometry(&mut document, &geometry); let mut sessions = project_sessions() .lock() .map_err(|_| "route-D session lock".to_string())?; let previous = sessions.remove(project_id); let (engine, changed, recomputed) = match previous { Some(mut session) => { if session.paragraphs == paragraphs && session.geometry == geometry { (session.engine, Vec::new(), 0) } else if session.geometry == geometry && session .paragraphs .iter() .all(|paragraph| paragraph.footnotes.is_empty()) && paragraphs .iter() .all(|paragraph| paragraph.footnotes.is_empty()) { let prefix = session .paragraphs .iter() .zip(¶graphs) .take_while(|(a, b)| a == b) .count(); if prefix > 0 && prefix < session.paragraphs.len() && prefix < paragraphs.len() { session.engine.relayout_from(&document, prefix); let changed = session.engine.changed_pages().to_vec(); let recomputed = session.engine.recomputed_pages(); (session.engine, changed, recomputed) } else { let engine = layout_document(&document); let changed: Vec = (0..engine.pages().len()).collect(); let recomputed = changed.len(); (engine, changed, recomputed) } } else { let engine = layout_document(&document); let changed: Vec = (0..engine.pages().len()).collect(); let recomputed = changed.len(); (engine, changed, recomputed) } } _ => { let engine = layout_document(&document); let changed: Vec = (0..engine.pages().len()).collect(); let recomputed = changed.len(); (engine, changed, recomputed) } }; let mut warnings = source_warnings(source, &geometry); warnings.extend(document_warnings(&document)); let json = render_json( &document, &engine, Some((&changed, recomputed)), &geometry, &warnings, ); sessions.insert( project_id.to_string(), ProjectSession { paragraphs, geometry, engine, }, ); Ok(json) } /// Page geometry pulled out of the source preamble. #[derive(Clone, Debug, Default, PartialEq, Eq)] struct PageGeometry { origin: PageOrigin, paper_width: Option, paper_height: Option, vsize: Option, textheight: Option, /// `geometry`'s `top`/`bottom`: the page body starts this far below the /// sheet edge, and the footer margin stays clear below it. top_margin: Option, bottom_margin: Option, /// `\textwidth` / `\hsize` / `\linewidth`, in scaled points. line_width: Option, par_indent: Option, par_skip: Option, par_skip_stretch: Option, par_skip_shrink: Option, baseline_skip: Option, /// `\linespread` factor in thousandths. linespread: Option, /// `\tabcolsep` on each side of a tabular column. tab_col_sep: Option, /// Custom column letters declared with `\newcolumntype`. column_types: Vec<(char, String, u8)>, /// `\itemsep` between list items, as width/stretch/shrink. item_sep: Option<(i64, i64, i64)>, /// `\topsep` above a list, as width/stretch/shrink. top_sep: Option<(i64, i64, i64)>, /// `\partopsep` added to `\topsep` when the list starts a paragraph. part_op_sep: Option<(i64, i64, i64)>, /// `\arraystretch` factor in thousandths. array_stretch: Option, /// `\\figurename` used as the caption prefix. figure_name: Option, /// `\\tablename` used as the caption prefix. table_name: Option, /// `\\abstractname` heading text. abstract_name: Option, /// `\\refname` heading for the bibliography. ref_name: Option, /// `\\contentsname` heading for the table of contents. contents_name: Option, /// `\\listfigurename` heading for the list of figures. list_figure_name: Option, /// `\\listtablename` heading for the list of tables. list_table_name: Option, /// `\\setcounter` assignments keyed by counter name. counters: Vec<(String, u32)>, /// Named lengths declared with `\newlength` and their current values. lengths: Vec<(String, i64)>, /// Colors declared with `\definecolor` and their RGB values. colors: Vec<(String, [u8; 3])>, /// Background colour painted behind every page. pub page_color: Option<[u8; 3]>, /// Integer registers declared with `\newcount` and their current values. count_registers: Vec<(String, i64)>, /// Dimension registers declared with `\newdimen`, in scaled points. dimension_registers: Vec<(String, i64)>, /// Glue registers declared with `\newskip` as width, stretch, shrink. skip_registers: Vec<(String, [i64; 3])>, /// TeX scratch count registers 0 through 9. numbered_counts: Vec, /// TeX scratch dimension registers 0 through 9, in scaled points. numbered_dimens: Vec, /// TeX scratch glue registers 0 through 9. numbered_skips: Vec<[i64; 3]>, /// `\pagenumbering` style used for the printed page numbers. page_numbering: Option, /// Zero-based page counter offset set with `\setcounter{page}`. page_start: u32, /// `\pagestyle{empty}` suppresses the printed page number. suppress_page_numbers: bool, /// `\thispagestyle{empty}` suppresses the number on the first page. suppress_first_page_number: bool, /// `\pagestyle{fancy}` turns on the fancyhdr fields below. fancy_pagestyle: bool, /// `\thispagestyle{empty}` suppresses the running head on the first page. suppress_first_page_header: bool, header_left: Option, header_center: Option, header_right: Option, footer_left: Option, footer_center: Option, footer_right: Option, /// `\renewcommand{\headrulewidth}{0.4pt}`. head_rule_width: Option, /// Frozen `\sbox`/`\savebox` metrics: name -> (width, height, depth), sp. savebox_dimensions: Vec<(String, (i64, i64, i64))>, /// Nested `tabular` sources referenced by `\texrranested{index}` tokens. nested_tables: Vec, /// Token registers: `\toks0`/named registers mapped to their text. token_registers: Vec<(String, String)>, head_sep: Option, head_height: Option, foot_skip: Option, left_skip: Option, right_skip: Option, tolerance: Option, pretolerance: Option, looseness: Option, emergency_stretch: Option, hang_indent: Option, hang_after: Option, french_spacing: Option, space_skip: Option<(i64, i64, i64)>, xspace_skip: Option<(i64, i64, i64)>, hyphenation_exceptions: Vec, par_shape: Vec<(i64, i64)>, lineskip: Option, lineskiplimit: Option, par_fillskip: Option<(i64, i64, bool)>, top_skip: Option, max_depth: Option, club_penalty: Option, widow_penalty: Option, /// `\abovedisplayskip` and friends, as width/stretch/shrink. above_display_skip: Option<(i64, i64, i64)>, below_display_skip: Option<(i64, i64, i64)>, above_display_short_skip: Option<(i64, i64, i64)>, below_display_short_skip: Option<(i64, i64, i64)>, split_top_skip: Option, split_max_depth: Option, hyphen_penalty: Option, ex_hyphen_penalty: Option, double_hyphen_demerits: Option, final_hyphen_demerits: Option, line_penalty: Option, adj_demerits: Option, space_factor_codes: Vec<(char, i64)>, /// Base font size from `\documentclass[11pt]`-style options. base_font_size: Option, /// Class name from the document class declaration. document_class: Option, /// Captured `tabular` environments: (column spec, halign source). tabular: Vec<(String, String, Option)>, /// `\title{...}` captured from the preamble. title: Option, /// `\author{...}` captured from the preamble. author: Option, /// `\date{...}` captured from the preamble. date: Option, pdf_title: Option, pdf_author: Option, pdf_subject: Option, pdf_keywords: Option, /// Colour applied to `\href` labels (`xcolor`'s `urlcolor`/`linkcolor`). link_color: Option, /// Border colour requested for URI link annotations. link_border_color: Option, /// `\hypersetup{hidelinks}` drops the annotation border. hide_links: bool, /// `thebibliography` entries: label key and entry text, in order. bibliography: Vec<(String, String)>, /// `\newtheorem` definitions from the preamble. theorem_definitions: Vec, /// `\newcommand` definitions from the preamble. macros: Vec, environments: Vec, /// `\newif` boolean flags declared in the preamble. conditionals: Vec, /// Decoded images keyed by `\includegraphics` path. images: HashMap, /// Directories searched for `\includegraphics` paths. graphics_paths: Vec, /// `\setcounter{secnumdepth}`; article defaults to 3. secnumdepth: Option, /// `\setcounter{tocdepth}`; article defaults to 3. tocdepth: Option, } /// A `\newtheorem` declaration: display name, shared counter and section scope. #[derive(Clone, Debug, PartialEq, Eq)] struct TheoremDefinition { name: String, display: String, shared: Option, within: Option, starred: bool, } /// A user macro captured from `\newcommand` or `\def`. #[derive(Clone, Debug, PartialEq, Eq)] struct MacroDefinition { name: String, args: u8, default: Option, body: String, /// Literal parameter text when the macro uses delimited arguments. params: Option, } /// A `\newenvironment` definition expanded textually in the body. #[derive(Clone, Debug, PartialEq, Eq)] struct EnvironmentDefinition { name: String, args: u8, default: Option, 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 { 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(); } let mut default = None; if let Some(after_bracket) = rest.strip_prefix('[') { let close = after_bracket.find(']')?; default = Some(after_bracket[..close].to_string()); rest = after_bracket[close + 1..].trim_start(); } 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, default, 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 letter = |character: char| { character.is_ascii_alphabetic() || character == '@' || character == '\u{E021}' }; let length = if letter(first) { after_slash .find(|character: char| !letter(character)) .unwrap_or(after_slash.len()) } else { first.len_utf8() }; Some(( format!("\\{}", &after_slash[..length]).replace('\u{E021}', "@"), length + 1, )) } fn definition_argument_count(params: &str) -> Option { 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 parameter_placeholders(params: &str) -> Option { let mut count = 0_u8; let mut characters = params.chars(); while let Some(character) = characters.next() { if character == '#' { let digit = characters.next()?.to_digit(10)?; if digit == 0 { return None; } count = count.max(digit as u8); } else if character == '\\' { return None; } } Some(count) } fn expand_csnames(text: &str) -> String { let mut result = String::with_capacity(text.len()); let mut rest = text; while let Some(index) = rest.find(r"\csname") { result.push_str(&rest[..index]); let after = &rest[index + r"\csname".len()..]; let Some(end) = after.find(r"\endcsname") else { result.push_str(&rest[index..]); return result; }; let name = after[..end].trim(); if name.is_empty() { result.push_str(r"\relax"); } else { result.push('\\'); result.push_str(name); } rest = &after[end + r"\endcsname".len()..]; } result.push_str(rest); result } fn strip_definition_prefixes(line: &str) -> &str { let mut rest = line.trim_start(); if rest.starts_with(r"\protected@") { return rest; } loop { let mut changed = false; for prefix in [r"\long", r"\global", r"\outer", r"\protected"] { if let Some(after) = rest.strip_prefix(prefix) && !after .chars() .next() .is_some_and(|character| character.is_alphabetic()) { rest = after.trim_start(); changed = true; break; } } if !changed { return rest; } } } fn char_definition(line: &str) -> Option { let rest = line.strip_prefix("\\chardef")?; let rest = rest.trim_start(); let (name, used) = control_sequence(rest)?; let rest = rest[used..].trim_start(); let rest = rest.strip_prefix('=')?.trim_start(); let value = if let Some(hex) = rest.strip_prefix('"') { let digits: String = hex.chars().take_while(|c| c.is_ascii_hexdigit()).collect(); u32::from_str_radix(&digits, 16).ok()? } else if let Some(octal) = rest.strip_prefix('\'') { let digits: String = octal .chars() .take_while(|c| ('0'..='7').contains(c)) .collect(); u32::from_str_radix(&digits, 8).ok()? } else if let Some(tail) = rest.strip_prefix('`') { let character = tail.chars().next()?; character as u32 } else { let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect(); digits.parse().ok()? }; let character = char::from_u32(value)?; Some(MacroDefinition { name, args: 0, default: None, body: character.to_string(), params: None, }) } fn edef_definition(line: &str, macros: &[MacroDefinition]) -> Option { let rest = line .strip_prefix(r"\edef") .or_else(|| line.strip_prefix(r"\xdef")) .or_else(|| line.strip_prefix(r"\protected@edef")) .or_else(|| line.strip_prefix(r"\protected@xdef"))? .trim_start(); let (name, consumed) = control_sequence(rest)?; let rest = &rest[consumed..]; let open = rest.find('{')?; let params_text = &rest[..open]; let (args, params) = match definition_argument_count(params_text) { Some(args) => (args, None), None => ( parameter_placeholders(params_text)?, Some(params_text.to_string()), ), }; let (body, _) = take_group_after_open(&rest[open + 1..])?; let mut body = expand_csnames(&body); if args == 0 { body = expand_macros(&body, macros); } Some(MacroDefinition { name, args, default: None, body, params, }) } 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 { if let Some(rest) = line .strip_prefix("\\def") .or_else(|| line.strip_prefix("\\gdef")) { let rest = rest.trim_start(); let (name, consumed) = control_sequence(rest)?; let rest = &rest[consumed..]; let open = rest.find('{')?; let params_text = &rest[..open]; let (args, params) = match definition_argument_count(params_text) { Some(args) => (args, None), None => ( parameter_placeholders(params_text)?, Some(params_text.to_string()), ), }; let (body, _) = take_group_after_open(&rest[open + 1..])?; return Some(MacroDefinition { name, args, default: None, body, params, }); } let rest = line .strip_prefix("\\newcommand") .or_else(|| line.strip_prefix("\\renewcommand")) .or_else(|| line.strip_prefix("\\DeclareRobustCommand")) .or_else(|| line.strip_prefix("\\providecommand"))?; let rest = rest.trim_start(); let rest = rest.strip_prefix('*').unwrap_or(rest).trim_start(); let (name, rest) = if let Some(after_open) = rest.strip_prefix('{') { let close = after_open.find('}')?; ( after_open[..close].trim().to_string(), &after_open[close + 1..], ) } else { let after_slash = rest.strip_prefix('\\')?; let length = after_slash .find(|character: char| !character.is_ascii_alphabetic()) .unwrap_or(after_slash.len()); ( format!("\\{}", &after_slash[..length]), &after_slash[length..], ) }; if name.is_empty() { return None; } let mut rest = rest.trim_start(); let mut args = 0_u8; if let Some(after_bracket) = rest.strip_prefix('[') { let close = after_bracket.find(']')?; args = after_bracket[..close].trim().parse().ok()?; rest = &after_bracket[close + 1..]; } let mut rest = rest.trim_start(); let mut default = None; if let Some(after_bracket) = rest.strip_prefix('[') { let close = after_bracket.find(']')?; default = Some(after_bracket[..close].to_string()); rest = &after_bracket[close + 1..]; } let rest = rest.trim_start(); let body = rest.strip_prefix('{')?; let (body, _) = take_group_after_open(body)?; Some(MacroDefinition { name, args, default, body, params: None, }) } /// 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, 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 = 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.replace('~', "\\textasciitilde{}")); output.push('}'); rest = &after[used..]; } } output } fn upsert_macro(table: &mut Vec, definition: MacroDefinition) { if let Some(existing) = table.iter_mut().find(|known| known.name == definition.name) { *existing = definition; } else { table.push(definition); } } fn brace_depth_delta(line: &str) -> i32 { let mut depth = 0_i32; let mut escaped = false; for character in line.chars() { if escaped { escaped = false; continue; } match character { '\\' => escaped = true, '{' => depth += 1, '}' => depth -= 1, _ => {} } } depth } /// `\string` prints the token's characters without expanding it. fn string_token(text: &str) -> Option<(String, usize)> { let after = text.strip_prefix("\\string")?; if after .chars() .next() .is_some_and(|character| character.is_ascii_alphabetic()) { return None; } let (token, used) = next_token(after)?; Some((escape_literal(&token), "\\string".len() + used)) } fn escape_literal(text: &str) -> String { text.replace('\\', "\u{E023}") .replace('{', "\u{E024}") .replace('}', "\u{E025}") } /// `\meaning` prints the macro body (or a primitive stand-in) literally. fn meaning_token( text: &str, runtime: &[MacroDefinition], scopes: &[Vec], ) -> Option<(String, usize)> { let after = text.strip_prefix("\\meaning")?; if after .chars() .next() .is_some_and(|character| character.is_ascii_alphabetic()) { return None; } let (token, used) = next_token(after)?; let meaning = if token.starts_with('\\') { let definition = scopes .iter() .rev() .find_map(|scope| scope.iter().rev().find(|known| known.name == token)) .or_else(|| runtime.iter().find(|known| known.name == token)); match definition { Some(definition) => { let params = definition.params.clone().unwrap_or_else(|| { (1..=definition.args) .map(|index| format!("#{index}")) .collect() }); format!("macro:{}->{}", params, definition.body) } None => "\\relax".to_string(), } } else { format!("the character {}", token) }; Some((escape_literal(&meaning), "\\meaning".len() + used)) } fn toks_register(text: &str) -> Option<(String, usize)> { let after = text.strip_prefix("\\toks")?; if after .chars() .next() .is_some_and(|character| character.is_ascii_alphabetic()) { return None; } let digits: String = after .chars() .take_while(|character| character.is_ascii_digit()) .collect(); if !digits.is_empty() { return Some((digits.clone(), "\\toks".len() + digits.len())); } let (name, used) = control_sequence(after)?; Some((name, "\\toks".len() + used)) } fn newtoks_declaration(text: &str) -> Option<(String, usize)> { let after = text.strip_prefix("\\newtoks")?; if after .chars() .next() .is_some_and(|character| character.is_ascii_alphabetic()) { return None; } let trimmed = after.trim_start(); let skipped = after.len() - trimmed.len(); let (name, used) = control_sequence(trimmed)?; Some((name, "\\newtoks".len() + skipped + used)) } fn named_toks_assignment( text: &str, tokens: &[(String, String)], ) -> Option<(String, String, usize)> { let (name, name_used) = control_sequence(text)?; if !tokens.iter().any(|(known, _)| known == &name) { return None; } let rest = text[name_used..].trim_start(); let mut used = name_used + (text[name_used..].len() - rest.len()); let rest = rest.strip_prefix('=')?; let value = rest.trim_start(); used += text[used..].len() - value.len(); let (content, group_used) = braced_group(value)?; Some((name, content.to_string(), used + group_used)) } fn toks_assignment(text: &str) -> Option<(String, String, usize)> { let (key, mut used) = toks_register(text)?; let rest = text[used..].trim_start(); used += text[used..].len() - rest.len(); let rest = rest.strip_prefix('=')?; let value = rest.trim_start(); used += text[used..].len() - value.len(); let (content, group_used) = braced_group(value)?; Some((key, content.to_string(), used + group_used)) } fn the_toks(text: &str, tokens: &[(String, String)]) -> Option<(String, usize)> { let after = text.strip_prefix("\\the")?; if after .chars() .next() .is_some_and(|character| character.is_ascii_alphabetic()) { return None; } let trimmed = after.trim_start(); let skipped = after.len() - trimmed.len(); if let Some((key, used)) = toks_register(trimmed) { let content = tokens .iter() .find(|(known, _)| known == &key) .map(|(_, value)| value.clone())?; return Some((content, "\\the".len() + skipped + used)); } let (name, used) = control_sequence(trimmed)?; let content = tokens .iter() .find(|(known, _)| known == &name) .map(|(_, value)| value.clone())?; Some((content, "\\the".len() + skipped + used)) } /// Replace `\scantokens{...}` with the text it re-tokenises; later expansion /// passes then process the content as usual. fn scantokens_body(text: &str) -> Option<(String, usize)> { let after = text.strip_prefix("\\scantokens")?; if after .chars() .next() .is_some_and(|character| character.is_ascii_alphabetic()) { return None; } let trimmed = after.trim_start(); let skipped = after.len() - trimmed.len(); let (content, used) = braced_group(trimmed)?; Some((content.to_string(), "\\scantokens".len() + skipped + used)) } /// Parse `\aftergroup` (or `\aftergroup{...}`) into the text that should /// run once the current group closes. fn aftergroup_tokens(text: &str) -> Option<(String, usize)> { let after = text.strip_prefix("\\aftergroup")?; if after .chars() .next() .is_some_and(|character| character.is_ascii_alphabetic()) { return None; } let (token, used) = next_token(after)?; if token == "{" { let brace_start = used - 1; let (content, group_used) = braced_group(&after[brace_start..])?; return Some(( content.to_string(), "\\aftergroup".len() + brace_start + group_used, )); } Some((token, "\\aftergroup".len() + used)) } /// Copy a conditional command together with the operand tokens it inspects, /// so macro expansion cannot consume them before the conditional is evaluated. fn protected_conditional_prefix(text: &str) -> Option<(String, usize)> { for (command, operands) in [ ("\\ifdefined", 1_usize), ("\\ifx", 2), ("\\ifcat", 2), ("\\if", 2), ] { let Some(after) = text.strip_prefix(command) else { continue; }; if after .chars() .next() .is_some_and(|character| character.is_ascii_alphabetic()) { continue; } let mut consumed = command.len(); for _ in 0..operands { let (_, used) = next_token(&text[consumed..])?; consumed += used; } return Some((text[..consumed].to_string(), consumed)); } None } /// Whether the output currently ends with a conditional control word, where /// splicing a letter directly would merge into a different control word. fn output_ends_with_conditional(output: &str) -> bool { const CONDITIONALS: &[&str] = &[ "ifx", "if", "ifnum", "ifcat", "ifdim", "ifdefined", "ifcsname", "ifhmode", "ifvmode", "ifmmode", "ifvoid", "ifhbox", "ifvbox", "ifeof", "iftrue", "iffalse", "else", "fi", "or", "unless", ]; let bytes = output.as_bytes(); let mut start = bytes.len(); while start > 0 && bytes[start - 1].is_ascii_alphabetic() { start -= 1; } if start == 0 || start == bytes.len() || bytes[start - 1] != b'\\' { return false; } CONDITIONALS.contains(&&output[start..]) } /// Parse `\futurelet\next\command `: return the alias name, the peeked /// token text and the byte offset where the command starts. fn futurelet_lookahead(text: &str) -> Option<(String, String, usize)> { let after = text.strip_prefix("\\futurelet")?; if after .chars() .next() .is_some_and(|character| character.is_ascii_alphabetic()) { return None; } let trimmed = after.trim_start(); let (alias, alias_used) = control_sequence(trimmed)?; let rest = &trimmed[alias_used..]; let command_text = rest.trim_start(); let (_, command_used) = next_token(command_text)?; let target_text = &command_text[command_used..]; let (target, _) = next_token(target_text)?; Some((alias, target, text.len() - command_text.len())) } fn next_token(text: &str) -> Option<(String, usize)> { let trimmed = text.trim_start(); let skipped = text.len() - trimmed.len(); if trimmed.starts_with('\\') { let (name, used) = control_sequence(trimmed)?; Some((name, skipped + used)) } else { let character = trimmed.chars().next()?; Some((character.to_string(), skipped + character.len_utf8())) } } /// Resolve a runtime `\csname ... \endcsname` into the macro it names. fn csname_expansion( text: &str, runtime: &[MacroDefinition], scopes: &[Vec], ) -> Option<(String, usize)> { let after = text.strip_prefix("\\csname")?; if after .chars() .next() .is_some_and(|character| character.is_ascii_alphabetic()) { return None; } let end = after.find("\\endcsname")?; let inner = &after[..end]; let mut table = runtime.to_vec(); for scope in scopes { table.extend(scope.iter().cloned()); } let expanded = expand_macros(inner, &table).trim().to_string(); let consumed = "\\csname".len() + end + "\\endcsname".len(); if expanded.is_empty() { return Some((String::new(), consumed)); } let name = format!("\\{}", expanded.trim_start_matches('\\')); let definition = scopes .iter() .rev() .find_map(|scope| scope.iter().rev().find(|known| known.name == name)) .or_else(|| runtime.iter().find(|known| known.name == name)); let body = definition .filter(|known| known.args == 0 && known.params.is_none()) .map(|known| known.body.clone()) .unwrap_or_default(); Some((body, consumed)) } /// Runtime `\let\alias=\target` and `\chardef\name=` definitions. fn runtime_plain_definition(text: &str) -> Option<(MacroDefinition, usize)> { let (command, used) = control_sequence(text)?; let rest = &text[used..]; let trimmed = rest.trim_start(); let skipped = rest.len() - trimmed.len(); let (name, name_used) = control_sequence(trimmed)?; let after_name = trimmed[name_used..].trim_start(); let name_gap = trimmed[name_used..].len() - after_name.len(); match command.as_str() { "\\let" => { let after = after_name .strip_prefix('=') .map(str::trim_start) .unwrap_or(after_name); let eq_skipped = after_name.len() - after.len(); let (target, target_used) = if let Some((target, target_used)) = control_sequence(after) { (target, target_used) } else { let character = after.chars().next()?; (character.to_string(), character.len_utf8()) }; Some(( MacroDefinition { name: format!("\\{}", name.trim_start_matches('\\')), args: 0, default: None, params: None, body: target, }, used + skipped + name_used + name_gap + eq_skipped + target_used, )) } "\\chardef" => { let after = after_name .strip_prefix('=') .map(str::trim_start) .unwrap_or(after_name); let eq_skipped = after_name.len() - after.len(); let digits: String = after .chars() .take_while(|character| character.is_ascii_digit()) .collect(); if digits.is_empty() { return None; } let value: u32 = digits.parse().ok()?; Some(( MacroDefinition { name: format!("\\{}", name.trim_start_matches('\\')), args: 0, default: None, params: None, body: char::from_u32(value)?.to_string(), }, used + skipped + name_used + name_gap + eq_skipped + digits.len(), )) } _ => None, } } /// Parse a simple runtime `\def\name{body}` / `\gdef\name{body}` and return /// the definition, bytes consumed and whether it is global. fn runtime_definition(text: &str) -> Option<(MacroDefinition, usize, bool)> { let (command, used) = control_sequence(text)?; let global = match command.as_str() { "\\def" => false, "\\gdef" => true, _ => return None, }; let rest = &text[used..]; let trimmed = rest.trim_start(); let skipped = rest.len() - trimmed.len(); let (name, name_used) = control_sequence(trimmed)?; let after_name = trimmed[name_used..].trim_start(); let brace_skipped = trimmed[name_used..].len() - after_name.len(); let open = after_name.find('{')?; let params_text = after_name[..open].trim(); let (args, params) = match definition_argument_count(params_text) { Some(args) => (args, None), None => ( parameter_placeholders(params_text)?, Some(params_text.to_string()), ), }; let (body, body_used) = braced_group(&after_name[open..])?; Some(( MacroDefinition { name: format!("\\{}", name.trim_start_matches('\\')), args, default: None, params, body: body.to_string(), }, used + skipped + name_used + brace_skipped + open + body_used, global, )) } fn expand_macro_at(text: &str, macros: &[MacroDefinition]) -> Option<(String, usize)> { expand_macro_lookup(text, macros, &[]) } fn expand_macro_at_scoped( text: &str, macros: &[MacroDefinition], scopes: &[Vec], ) -> Option<(String, usize)> { expand_macro_lookup(text, macros, scopes) } fn expand_macro_lookup( text: &str, macros: &[MacroDefinition], scopes: &[Vec], ) -> Option<(String, usize)> { let after_slash = text.strip_prefix('\\')?; let length = after_slash .find(|character: char| { !character.is_ascii_alphabetic() && character != '@' && character != '\u{E021}' }) .unwrap_or(after_slash.len()); if length == 0 { return None; } let name = format!("\\{}", &after_slash[..length]).replace('\u{E021}', "@"); let definition = scopes .iter() .rev() .find_map(|scope| scope.iter().rev().find(|macro_| macro_.name == name)) .or_else(|| macros.iter().find(|macro_| macro_.name == name))?; if let Some(params) = &definition.params { return expand_delimited(text, definition, params); } let tail = &after_slash[length..]; let mut args = Vec::new(); let mut consumed = 0_usize; let mut supplied_default = false; if let Some(default) = &definition.default { let trimmed = tail.trim_start(); let spaces = tail.len() - trimmed.len(); if let Some(after_bracket) = trimmed.strip_prefix('[') { if let Some(close) = after_bracket.find(']') { args.push(after_bracket[..close].to_string()); consumed = spaces + 1 + close + 1; supplied_default = true; } } if !supplied_default { args.push(default.clone()); } } let required = definition.args.saturating_sub(args.len() as u8); let (rest_args, used) = macro_arguments(&tail[consumed..], required)?; args.extend(rest_args); let expanded = substitute_macro_args(&definition.body, &args); Some((expanded, 1 + length + consumed + used)) } /// Expand the small set of LaTeX internal commands used by class and package /// files. Returns the replacement text and the bytes consumed. /// Expand a macro whose parameter text contains delimiters. fn expand_delimited( text: &str, definition: &MacroDefinition, params: &str, ) -> Option<(String, usize)> { let after_slash = text.strip_prefix('\\')?; let length = after_slash .find(|character: char| !character.is_ascii_alphabetic()) .unwrap_or(after_slash.len()); let tail = &after_slash[length..]; let mut leading = String::new(); let mut delimiters: Vec = Vec::new(); let mut literal = String::new(); let mut characters = params.chars(); let mut first = true; while let Some(character) = characters.next() { if character == '#' { let digit = characters.next()?.to_digit(10)?; if first { leading = std::mem::take(&mut literal); first = false; } else { delimiters.push(std::mem::take(&mut literal)); } if digit == 0 || digit as u8 != delimiters.len() as u8 + 1 { return None; } } else { literal.push(character); } } delimiters.push(literal); let mut consumed = 1 + length; let mut rest = tail; let trimmed = rest.trim_start(); consumed += rest.len() - trimmed.len(); rest = trimmed; if !leading.is_empty() { rest = rest.strip_prefix(&leading)?; consumed += leading.len(); } let mut args = Vec::new(); for delimiter in &delimiters { if delimiter.is_empty() { let trimmed = rest.trim_start(); consumed += rest.len() - trimmed.len(); rest = trimmed; if let Some(after_open) = rest.strip_prefix('{') { let (argument, used) = take_group_after_open(after_open)?; args.push(argument); consumed += 1 + used; rest = &after_open[used..]; } else { let character = rest.chars().next()?; args.push(character.to_string()); consumed += character.len_utf8(); rest = &rest[character.len_utf8()..]; } } else { let position = rest.find(delimiter)?; let mut argument = rest[..position].to_string(); if argument.starts_with('{') && argument.ends_with('}') { argument = argument[1..argument.len() - 1].to_string(); } args.push(argument); consumed += position + delimiter.len(); rest = &rest[position + delimiter.len()..]; } } let expanded = substitute_macro_args(&definition.body, &args); Some((expanded, consumed)) } fn latex_internal_at(rest: &str, macros: &[MacroDefinition]) -> Option<(String, usize)> { let boundary = |after: &str| { after .chars() .next() .is_none_or(|character| !(character.is_ascii_alphabetic() || character == '@')) }; if let Some(after) = rest.strip_prefix("\\@empty") { if boundary(after) { return Some((String::new(), "\\@empty".len())); } } for (command, count) in [("\\@gobble", 1_usize), ("\\@gobbletwo", 2_usize)] { if let Some(after) = rest.strip_prefix(command) { if boundary(after) { let mut offset = command.len(); let mut cursor = after; for _ in 0..count { let skipped = cursor.len() - cursor.trim_start().len(); offset += skipped; cursor = cursor.trim_start(); let (_, used) = braced_group(cursor)?; offset += used; cursor = &cursor[used..]; } return Some((String::new(), offset)); } } } if let Some(after) = rest.strip_prefix("\\@ifmtarg") { if boundary(after) { let mut offset = "\\@ifmtarg".len(); let mut cursor = after; let mut groups = Vec::new(); for _ in 0..3 { let skipped = cursor.len() - cursor.trim_start().len(); offset += skipped; cursor = cursor.trim_start(); let (group, used) = braced_group(cursor)?; offset += used; cursor = &cursor[used..]; groups.push(group); } let chosen = if groups[0].trim().is_empty() { groups[1] } else { groups[2] }; return Some((chosen.to_string(), offset)); } } if let Some(after) = rest.strip_prefix("\\@nameuse") { if boundary(after) { let skipped = after.len() - after.trim_start().len(); let mut after = after.trim_start(); let (inner, used) = braced_group(after)?; return Some(( format!("\\{}", inner.trim().trim_start_matches('\\')), "\\@nameuse".len() + skipped + used, )); } } if let Some(after) = rest.strip_prefix("\\@ifundefined") { if boundary(after) { let mut offset = "\\@ifundefined".len(); let mut cursor = after; let skipped = cursor.len() - cursor.trim_start().len(); offset += skipped; cursor = cursor.trim_start(); let (name, used) = braced_group(cursor)?; offset += used; cursor = &cursor[used..]; let skipped = cursor.len() - cursor.trim_start().len(); offset += skipped; cursor = cursor.trim_start(); let (true_branch, used) = braced_group(cursor)?; offset += used; cursor = &cursor[used..]; let skipped = cursor.len() - cursor.trim_start().len(); offset += skipped; cursor = cursor.trim_start(); let (false_branch, used) = braced_group(cursor)?; offset += used; let name = name.trim(); let full = if name.starts_with('\\') { name.to_string() } else { format!("\\{}", name) }; let defined = macros.iter().any(|definition| definition.name == full); let chosen = if defined { false_branch } else { true_branch }; return Some((chosen.to_string(), offset)); } } if let Some(after) = rest.strip_prefix("\\@ifpackageloaded") { if boundary(after) { let mut offset = "\\@ifpackageloaded".len(); let mut cursor = after; let skipped = cursor.len() - cursor.trim_start().len(); offset += skipped; cursor = cursor.trim_start(); let (package, used) = braced_group(cursor)?; offset += used; cursor = &cursor[used..]; let skipped = cursor.len() - cursor.trim_start().len(); offset += skipped; cursor = cursor.trim_start(); let (true_branch, used) = braced_group(cursor)?; offset += used; cursor = &cursor[used..]; let skipped = cursor.len() - cursor.trim_start().len(); offset += skipped; cursor = cursor.trim_start(); let (false_branch, used) = braced_group(cursor)?; offset += used; let known = [ "geometry", "hyperref", "graphicx", "amsmath", "xcolor", "booktabs", "longtable", "tabularx", ]; let loaded = known.contains(&package.trim()); let chosen = if loaded { true_branch } else { false_branch }; return Some((chosen.to_string(), offset)); } } if let Some(after) = rest.strip_prefix("\\@ifclassloaded") { if boundary(after) { let mut offset = "\\@ifclassloaded".len(); let mut cursor = after; let skipped = cursor.len() - cursor.trim_start().len(); offset += skipped; cursor = cursor.trim_start(); let (class, used) = braced_group(cursor)?; offset += used; cursor = &cursor[used..]; let skipped = cursor.len() - cursor.trim_start().len(); offset += skipped; cursor = cursor.trim_start(); let (true_branch, used) = braced_group(cursor)?; offset += used; cursor = &cursor[used..]; let skipped = cursor.len() - cursor.trim_start().len(); offset += skipped; cursor = cursor.trim_start(); let (false_branch, used) = braced_group(cursor)?; offset += used; let loaded = matches!(class.trim(), "article" | "report" | "book"); let chosen = if loaded { true_branch } else { false_branch }; return Some((chosen.to_string(), offset)); } } if let Some(after) = rest.strip_prefix("\\@ifdefinable") { if boundary(after) { let mut offset = "\\@ifdefinable".len(); let mut cursor = after.trim_start(); offset += after.len() - cursor.len(); let name = if let Some((name, used)) = braced_group(cursor) { offset += used; cursor = &cursor[used..]; format!("\\{}", name.trim().trim_start_matches('\\')) } else if let Some((command, used)) = control_sequence(cursor) { offset += used; cursor = &cursor[used..]; command } else { return None; }; let skipped = cursor.len() - cursor.trim_start().len(); offset += skipped; cursor = cursor.trim_start(); let (true_branch, used) = braced_group(cursor)?; offset += used; let defined = macros.iter().any(|definition| definition.name == name); let chosen = if defined { "" } else { true_branch }; return Some((chosen.to_string(), offset)); } } for command in ["\\@onlypreamble", "\\@nopreamble"] { if let Some(after) = rest.strip_prefix(command) { if boundary(after) { let mut offset = command.len(); let cursor = after.trim_start(); offset += after.len() - cursor.len(); if let Some((_, used)) = braced_group(cursor) { offset += used; return Some((String::new(), offset)); } if let Some((_, used)) = control_sequence(cursor) { offset += used; return Some((String::new(), offset)); } } } } for (command, pick) in [ ("\\@firstofone", 0_usize), ("\\@firstoftwo", 0_usize), ("\\@secondoftwo", 1_usize), ] { if let Some(after) = rest.strip_prefix(command) { if boundary(after) { let mut offset = command.len(); let mut cursor = after; let skipped = cursor.len() - cursor.trim_start().len(); offset += skipped; cursor = cursor.trim_start(); let (first, used) = braced_group(cursor)?; offset += used; if command == "\\@firstofone" { return Some((first.to_string(), offset)); } cursor = &cursor[used..]; let skipped = cursor.len() - cursor.trim_start().len(); offset += skipped; cursor = cursor.trim_start(); let (second, used) = braced_group(cursor)?; offset += used; let chosen = if pick == 0 { first } else { second }; return Some((chosen.to_string(), offset)); } } } if let Some(after) = rest.strip_prefix("\\@ifstar") { if boundary(after) { let mut offset = "\\@ifstar".len(); let mut cursor = after; let skipped = cursor.len() - cursor.trim_start().len(); offset += skipped; cursor = cursor.trim_start(); let (starred, used) = braced_group(cursor)?; offset += used; cursor = &cursor[used..]; let skipped = cursor.len() - cursor.trim_start().len(); offset += skipped; cursor = cursor.trim_start(); let (plain, used) = braced_group(cursor)?; offset += used; if cursor[used..].starts_with('*') { return Some((starred.to_string(), offset + 1)); } return Some((plain.to_string(), offset)); } } if let Some(after) = rest.strip_prefix("\\@ifnextchar") { if boundary(after) { let mut offset = "\\@ifnextchar".len(); let mut cursor = after; let skipped = cursor.len() - cursor.trim_start().len(); offset += skipped; cursor = cursor.trim_start(); let target = if let Some((command, used)) = control_sequence(cursor) { offset += used; cursor = &cursor[used..]; (true, command) } else { let character = cursor.chars().next()?; offset += character.len_utf8(); cursor = &cursor[character.len_utf8()..]; (false, character.to_string()) }; let skipped = cursor.len() - cursor.trim_start().len(); offset += skipped; cursor = cursor.trim_start(); let (matched, used) = braced_group(cursor)?; offset += used; cursor = &cursor[used..]; let skipped = cursor.len() - cursor.trim_start().len(); offset += skipped; cursor = cursor.trim_start(); let (unmatched, used) = braced_group(cursor)?; offset += used; let mut look = &cursor[used..]; let spaces = look.len() - look.trim_start().len(); look = look.trim_start(); let matches = if let Some((command, _)) = control_sequence(look) { target.0 && command == target.1 } else { !target.0 && look.starts_with(&target.1) }; if matches { return Some((matched.to_string(), offset + spaces)); } return Some((unmatched.to_string(), offset)); } } None } fn expandafter_chain(text: &str, macros: &[MacroDefinition]) -> Option<(String, usize)> { let mut position = 0; let mut output = String::new(); loop { let rest = &text[position..]; let after = rest.strip_prefix(r"\expandafter")?; if after .chars() .next() .is_some_and(|character| character.is_ascii_alphabetic()) { return None; } position += r"\expandafter".len(); let spaces = after.len() - after.trim_start().len(); position += spaces; let trimmed = &text[position..]; let (command, length) = control_sequence(trimmed)?; let definition = macros .iter() .find(|known| known.name == command && known.args == 0 && known.default.is_none())?; output.push_str(&definition.body); position += length; let rest = &text[position..]; position += rest.len() - rest.trim_start().len(); if text[position..].starts_with(r"\expandafter") { continue; } break; } let (expanded, used) = expand_macro_at(&text[position..], macros)?; output.push_str(&expanded); position += used; Some((output, position)) } fn expand_macros(source: &str, macros: &[MacroDefinition]) -> String { let mut table = macros.to_vec(); let mut tokens = Vec::new(); expand_macros_mut(source, &mut table, &mut tokens) } fn expand_macros_mut( source: &str, macros: &mut Vec, tokens: &mut Vec<(String, String)>, ) -> String { let mut text = source.to_string(); let mut runtime: Vec = macros.clone(); for _ in 0..8 { let mut output = String::with_capacity(text.len()); let mut index = 0; let mut changed = false; let mut scopes: Vec> = Vec::new(); let mut after_groups: Vec> = Vec::new(); while index < text.len() { let rest = &text[index..]; if let Some((prefix, used)) = protected_conditional_prefix(rest) { output.push_str(&prefix); index += used; changed = true; continue; } if let Some((definition, used, global)) = runtime_definition(rest) { if global || scopes.is_empty() { upsert_macro(&mut runtime, definition); } else if let Some(scope) = scopes.last_mut() { upsert_macro(scope, definition); } index += used; changed = true; continue; } if let Some((definition, used)) = runtime_plain_definition(rest) { if scopes.is_empty() { upsert_macro(&mut runtime, definition); } else if let Some(scope) = scopes.last_mut() { upsert_macro(scope, definition); } index += used; changed = true; continue; } if let Some((text, used)) = string_token(rest) { output.push_str(&text); index += used; changed = true; continue; } if let Some((text, used)) = meaning_token(rest, &runtime, &scopes) { output.push_str(&text); index += used; changed = true; continue; } if let Some((content, used)) = newtoks_declaration(rest) { if !tokens.iter().any(|(key, _)| key == &content) { tokens.push((content, String::new())); } index += used; changed = true; continue; } if let Some((key, value, used)) = named_toks_assignment(rest, tokens) { if let Some(slot) = tokens.iter_mut().find(|(known, _)| known == &key) { slot.1 = value; } index += used; changed = true; continue; } if let Some((key, value, used)) = toks_assignment(rest) { if let Some(slot) = tokens.iter_mut().find(|(known, _)| known == &key) { slot.1 = value; } else { tokens.push((key, value)); } index += used; changed = true; continue; } if let Some((content, used)) = the_toks(rest, tokens) { output.push('\u{E022}'); output.push_str(&content); index += used; changed = true; continue; } if let Some((content, used)) = scantokens_body(rest) { output.push('\u{E022}'); output.push_str(&content); index += used; changed = true; continue; } if let Some((tokens, used)) = aftergroup_tokens(rest) { if let Some(pending) = after_groups.last_mut() { pending.push(tokens); } else { output.push_str(&tokens); } index += used; changed = true; continue; } if let Some((alias, target, command_start)) = futurelet_lookahead(rest) { let definition = MacroDefinition { name: alias, args: 0, default: None, params: None, body: target, }; if scopes.is_empty() { upsert_macro(&mut runtime, definition); } else if let Some(scope) = scopes.last_mut() { upsert_macro(scope, definition); } index += command_start; changed = true; continue; } if let Some((expanded, used)) = csname_expansion(rest, &runtime, &scopes) { if expanded .chars() .next() .is_some_and(|character| character.is_ascii_alphabetic()) && output_ends_with_conditional(&output) { output.push(' '); } output.push_str(&expanded); index += used; changed = true; continue; } if rest.starts_with(r"\begingroup") { scopes.push(Vec::new()); after_groups.push(Vec::new()); index += r"\begingroup".len(); changed = true; continue; } if rest.starts_with(r"\endgroup") { scopes.pop(); if let Some(tokens) = after_groups.pop() { for tokens in tokens { output.push_str(&tokens); output.push('\u{E022}'); } } index += r"\endgroup".len(); changed = true; continue; } if let Some(after) = rest.strip_prefix(r"\noexpand") { let boundary = after .chars() .next() .is_none_or(|character| !character.is_ascii_alphabetic()); if boundary { let trimmed = after.trim_start(); let skipped = after.len() - trimmed.len(); if trimmed.starts_with('\\') { if let Some((command, used)) = control_sequence(trimmed) { output.push('\u{E000}'); output.push_str(command.trim_start_matches('\\')); index += r"\noexpand".len() + skipped + used; changed = true; continue; } } if let Some(character) = trimmed.chars().next() { output.push('\u{E000}'); output.push(character); index += r"\noexpand".len() + skipped + character.len_utf8(); changed = true; continue; } } } if rest.starts_with(r"\expandafter") { if let Some((expanded, used)) = expandafter_chain(rest, &runtime) { output.push_str(&expanded); index += used; changed = true; continue; } } if let Some((expanded, used)) = latex_internal_at(rest, &runtime) { output.push_str(&expanded); index += used; changed = true; continue; } if let Some((command, used)) = control_sequence(rest) { if matches!( command.as_str(), "\\maketitle" | "\\thanks" | "\\section" | "\\subsection" | "\\subsubsection" | "\\paragraph" | "\\chapter" | "\\part" ) { // The native title block reads \title/\author/\date // directly; expanding a class-file \maketitle definition // would typeset the whole LaTeX machinery instead. output.push_str(&command); index += used; continue; } } if let Some((expanded, used)) = expand_macro_at_scoped(rest, &runtime, &scopes) { if expanded .chars() .next() .is_some_and(|character| character.is_ascii_alphabetic()) && output_ends_with_conditional(&output) { output.push(' '); } output.push_str(&expanded); index += used; changed = true; continue; } let character = rest.chars().next().expect("non-empty tail"); if character == '{' { scopes.push(Vec::new()); after_groups.push(Vec::new()); } else if character == '}' { scopes.pop(); } output.push(character); if character == '}' { if let Some(tokens) = after_groups.pop() { for tokens in tokens { output.push_str(&tokens); output.push('\u{E022}'); } } } index += character.len_utf8(); } text = output; if !changed { break; } } macros.clone_from(&runtime); text.replace('\u{E000}', "\\") } /// 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..]; let mut arguments = Vec::new(); let mut consumed = 0_usize; let mut optional_present = false; if definition.default.is_some() && definition.args > 0 { let trimmed = after_begin.trim_start(); let skipped = after_begin.len() - trimmed.len(); if let Some(inner) = trimmed.strip_prefix('[') { if let Some(end) = inner.find(']') { arguments.push(inner[..end].to_string()); consumed = skipped + end + 2; optional_present = true; } } } let required = if definition.default.is_some() && optional_present { definition.args.saturating_sub(1) } else if definition.default.is_some() { 0 } else { definition.args }; if let Some((mut rest_args, rest_consumed)) = macro_arguments(&after_begin[consumed..], required) { arguments.append(&mut rest_args); consumed += rest_consumed; if !optional_present { if let Some(default) = &definition.default { arguments.insert(0, default.clone()); } } let args = arguments; 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 { 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 { 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 { 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 { let rest = line.strip_prefix("\\linespread")?; let (argument, _) = braced_group(rest.trim_start())?; spread_percent(argument) } /// `\renewcommand{\name}{text}` / `\def\name{text}` for class labels. fn renewcommand_text(line: &str, command: &str) -> Option { let braced = format!("\\renewcommand{{\\{command}}}"); let defined = format!("\\def\\{command}"); let rest = line .strip_prefix(&braced) .or_else(|| line.strip_prefix(&defined))?; let (argument, _) = braced_group(rest.trim_start())?; Some(argument.trim().to_string()) } /// `\renewcommand{\arraystretch}{factor}` in thousandths. fn arraystretch_assignment(line: &str) -> Option { let rest = line .strip_prefix("\\renewcommand{\\arraystretch}") .or_else(|| line.strip_prefix("\\def\\arraystretch"))?; let (argument, _) = braced_group(rest.trim_start())?; spread_percent(argument) } /// `\renewcommand{\baselinestretch}{factor}` in thousandths. fn baselinestretch_assignment(line: &str) -> Option { 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 { if let Some(rest) = line.strip_prefix("\\geometry") { let (options, _) = braced(rest.trim_start())?; return Some(options.to_string()); } if let Some(rest) = line.strip_prefix("\\newgeometry") { 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), _ => {} } } geometry.top_margin = top; geometry.bottom_margin = bottom; let explicit_width = geometry.line_width; let explicit_height = geometry.textheight; 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); // A `textwidth`/`textheight` option is authoritative; the arXiv // template's `\newgeometry{textheight=9in,textwidth=6.5in,top=1in}` // must keep its 9in/6.5in block instead of deriving it from margins. if explicit_width.is_none() { geometry.line_width = Some(paper_width - left - right); } if explicit_height.is_none() { 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 { let rest = line.strip_prefix(command)?.trim_start(); let (value, _) = braced(rest)?; Some(value.trim().to_string()) } fn newif_definition(line: &str) -> Option { 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 } } #[derive(Clone, PartialEq, Eq)] enum ConditionalToken { Control(String), Character(char), } fn conditional_token(text: &str) -> Option<(ConditionalToken, usize)> { let trimmed = text.trim_start(); let skipped = text.len() - trimmed.len(); if trimmed.starts_with('\\') { let (command, used) = control_sequence(trimmed)?; return Some((ConditionalToken::Control(command), skipped + used)); } let character = trimmed.chars().next()?; Some(( ConditionalToken::Character(character), skipped + character.len_utf8(), )) } fn conditional_operand( text: &str, counts: &[(String, i64)], counters: &[(String, u32)], ) -> Option<(i64, usize)> { let trimmed = text.trim_start(); let skipped = text.len() - trimmed.len(); if let Some(rest) = trimmed.strip_prefix("\\value") { let rest = rest.trim_start(); let name = rest.strip_prefix('{')?; let close = name.find('}')?; let key = name[..close].trim(); let value = counters .iter() .rev() .find(|(known, _)| known == key) .map(|(_, value)| i64::from(*value))?; return Some((value, skipped + (trimmed.len() - rest.len()) + close + 2)); } if trimmed.starts_with('\\') { let (command, used) = control_sequence(trimmed)?; let name = command.trim_start_matches('\\'); let value = counts .iter() .rev() .find(|(known, _)| known == name) .map(|(_, value)| *value)?; return Some((value, skipped + used)); } let (value, used) = scan_signed_integer(trimmed)?; Some((value, skipped + used)) } fn conditional_at( text: &str, index: usize, flags: &[ConditionalDefinition], macros: &[MacroDefinition], counts: &[(String, i64)], counters: &[(String, u32)], ) -> 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)); } // Route-D expands macros while building paragraph text, which is // horizontal mode; vertical and math mode are not modelled here. if word == "ifhmode" { return Some((true, consumed)); } if word == "ifvmode" || word == "ifmmode" { return Some((false, consumed)); } if word == "ifdefined" { let after = text.get(index + consumed..)?; let trimmed = after.trim_start(); let skipped = after.len() - trimmed.len(); let (command, command_consumed) = control_sequence(trimmed)?; let defined = macros.iter().any(|definition| definition.name == command); return Some((defined, consumed + skipped + command_consumed)); } if word == "ifnum" { let after = text.get(index + consumed..)?; let (left, left_used) = conditional_operand(after, counts, counters)?; let rest = &after[left_used..]; let trimmed = rest.trim_start(); let skipped = rest.len() - trimmed.len(); let relation = trimmed.chars().next()?; if !matches!(relation, '=' | '<' | '>') { return None; } let (right, right_used) = conditional_operand(&trimmed[1..], counts, counters)?; let value = match relation { '=' => left == right, '<' => left < right, _ => left > right, }; return Some((value, consumed + left_used + skipped + 1 + right_used)); } if word == "ifx" { let after = text.get(index + consumed..)?; let (first, first_used) = conditional_token(after)?; let (second, second_used) = conditional_token(&after[first_used..])?; let value = match (&first, &second) { (ConditionalToken::Character(left), ConditionalToken::Character(right)) => { left == right } (ConditionalToken::Control(left), ConditionalToken::Control(right)) => { match ( macros.iter().find(|definition| &definition.name == left), macros.iter().find(|definition| &definition.name == right), ) { (Some(left), Some(right)) => { left.body == right.body && left.args == right.args && left.default == right.default } (None, None) => left == right, _ => false, } } (ConditionalToken::Control(name), ConditionalToken::Character(character)) | (ConditionalToken::Character(character), ConditionalToken::Control(name)) => macros .iter() .find(|definition| &definition.name == name) .is_some_and(|definition| definition.body == character.to_string()), _ => false, }; return Some((value, consumed + first_used + second_used)); } if word == "ifcat" { let after = text.get(index + consumed..)?; let (first, first_used) = conditional_token(after)?; let (second, second_used) = conditional_token(&after[first_used..])?; let value = category(&first) == category(&second); return Some((value, consumed + first_used + second_used)); } if word == "if" { let after = text.get(index + consumed..)?; let (first, first_used) = conditional_token(after)?; let (second, second_used) = conditional_token(&after[first_used..])?; let value = match (&first, &second) { (ConditionalToken::Character(left), ConditionalToken::Character(right)) => { left == right } _ => false, }; return Some((value, consumed + first_used + second_used)); } if word == "ifodd" { let after = text.get(index + consumed..)?; let (value, used) = conditional_operand(after, counts, counters)?; return Some((value % 2 != 0, consumed + used)); } let name = word.strip_prefix("if")?; let flag = flags.iter().find(|flag| flag.name == name)?; Some((flag.value, consumed)) } fn category(token: &ConditionalToken) -> u8 { match token { ConditionalToken::Control(_) => 16, ConditionalToken::Character(character) => match character { '{' => 1, '}' => 2, '$' => 3, '&' => 4, '#' => 6, '^' => 7, '_' => 8, ' ' => 10, value if value.is_ascii_alphabetic() => 11, value if value.is_ascii_digit() => 12, _ => 13, }, } } fn case_conditional_at( text: &str, index: usize, counts: &[(String, i64)], counters: &[(String, u32)], ) -> Option<(i64, usize)> { let rest = text.get(index..)?; let after = rest.strip_prefix("\\ifcase")?; if after .chars() .next() .is_some_and(|c| c.is_ascii_alphabetic()) { return None; } let (value, used) = conditional_operand(after, counts, counters)?; Some((value, "\\ifcase".len() + used)) } /// Split the body of an `\ifcase` into `\or` branches and the `\else` branch. fn case_branches(source: &str, start: usize) -> Option<(Vec<&str>, Option<&str>, usize)> { let mut branches = Vec::new(); let mut otherwise_start = None; let mut current_start = start; let mut depth = 0_usize; let mut search = start; while let Some(offset) = source[search..].find('\\') { let position = search + offset; let Some((command, consumed)) = control_sequence(&source[position..]) else { search = 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 { if let Some(else_start) = otherwise_start { let _ = else_start; return Some((branches, Some(&source[current_start..position]), position)); } branches.push(&source[current_start..position]); return Some((branches, None, position)); } depth -= 1; } else if depth == 0 && word == "or" { branches.push(&source[current_start..position]); current_start = position + consumed; } else if depth == 0 && word == "else" && otherwise_start.is_none() { branches.push(&source[current_start..position]); current_start = position + consumed; otherwise_start = Some(position); } search = position + consumed; } None } fn conditional_end(text: &str, start: usize) -> Option<(Option, 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], macros: &[MacroDefinition], counts: &[(String, i64)], counters: &[(String, u32)], ) -> String { expand_conditionals_at(source, flags, macros, counts, counters, 0) } fn expand_conditionals_at( source: &str, flags: &mut [ConditionalDefinition], macros: &[MacroDefinition], counts: &[(String, i64)], counters: &[(String, u32)], 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)) = case_conditional_at(source, position, counts, counters) { if let Some((branches, otherwise, fi_at)) = case_branches(source, position + consumed) { let chosen = if value >= 0 { branches.get(value as usize).copied().or(otherwise) } else { otherwise }; output.push_str(&expand_conditionals_at( chosen.unwrap_or("").trim_start(), flags, macros, counts, counters, depth + 1, )); index = fi_at + 3; continue; } } let conditional = if let Some(rest) = source[position..].strip_prefix("\\unless") { let trimmed = rest.trim_start(); if rest.len() == trimmed.len() && trimmed.starts_with(|c: char| c.is_ascii_alphabetic()) { None } else { let skipped = rest.len() - trimmed.len(); conditional_at( source, position + 7 + skipped, flags, macros, counts, counters, ) .map(|(value, consumed)| (!value, 7 + skipped + consumed)) } } else { conditional_at(source, position, flags, macros, counts, counters) }; if let Some((value, consumed)) = conditional { 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) } }; let chosen = chosen.trim_start(); output.push_str(&expand_conditionals_at( chosen, flags, macros, counts, counters, depth + 1, )); index = after; continue; } } output.push_str(&source[position..position + 1]); index = position + 1; } output.push_str(&source[index..]); output } fn any_counter_assignment(line: &str) -> Option<(String, u32)> { let rest = line.strip_prefix("\\setcounter")?.trim_start(); let rest = rest.strip_prefix('{')?; let close = rest.find('}')?; let name = rest[..close].trim().to_string(); let rest = rest[close + 1..].trim_start(); let rest = rest.strip_prefix('{')?; let close = rest.find('}')?; let value = rest[..close].trim().parse().ok()?; Some((name, value)) } fn add_counter_assignment(line: &str) -> Option<(String, i64)> { let rest = line.strip_prefix("\\addtocounter")?.trim_start(); let rest = rest.strip_prefix('{')?; let close = rest.find('}')?; let name = rest[..close].trim().to_string(); let rest = rest[close + 1..].trim_start(); let rest = rest.strip_prefix('{')?; let close = rest.find('}')?; let value = rest[..close].trim().parse().ok()?; Some((name, value)) } fn new_counter_definition(line: &str) -> Option { let rest = line.strip_prefix("\\newcounter")?.trim_start(); let rest = rest.strip_prefix('{')?; let close = rest.find('}')?; let name = rest[..close] .trim() .strip_prefix('\\') .unwrap_or(rest[..close].trim()); (!name.is_empty()).then_some(name.to_string()) } fn geometry_counter(geometry: &PageGeometry, name: &str) -> u32 { geometry .counters .iter() .rev() .find(|(counter, _)| counter == name) .map(|(_, value)| *value) .unwrap_or(0) } fn hypersetup_values(line: &str) -> Vec<(String, String)> { let Some(rest) = line.strip_prefix("\\hypersetup") else { return Vec::new(); }; let Some((body, _)) = braced_group(rest.trim_start()) else { return Vec::new(); }; let mut values = Vec::new(); let mut depth = 0_usize; let mut entry = String::new(); for character in body.chars() { match character { '{' => { depth += 1; entry.push(character); } '}' => { depth = depth.saturating_sub(1); entry.push(character); } ',' if depth == 0 => { values.push(entry.trim().to_string()); entry = String::new(); } _ => entry.push(character), } } values.push(entry.trim().to_string()); values .into_iter() .filter_map(|entry| { let (key, value) = entry.split_once('=')?; let value = value.trim(); let value = value .strip_prefix('{') .and_then(|inner| inner.strip_suffix('}')) .unwrap_or(value) .trim() .to_string(); Some((key.trim().to_string(), value)) }) .collect() } /// Expands `\multirow{n}{width}{text}` cells to their text. The span is not /// vertical-centre, so the text stays on its first row; the command itself /// must not leak into the table. fn expand_multirow(source: &str) -> String { let mut rest = source; let mut out = String::new(); while let Some(index) = rest.find(r"\multirow") { out.push_str(&rest[..index]); let after = rest[index + r"\multirow".len()..].trim_start(); let after = if let Some(inner) = after.strip_prefix('[') { match inner.find(']') { Some(end) => inner[end + 1..].trim_start(), None => { out.push_str(&rest[index..]); return out; } } } else { after }; let mut cursor = after; let mut pieces = Vec::new(); for _ in 0..3 { let Some((body, consumed)) = braced_group(cursor) else { out.push_str(&rest[index..]); return out; }; pieces.push(body.trim().to_string()); cursor = &cursor[consumed..]; } out.push_str(&format!( "\\texrramultirow{{{}}}{{{}}}", pieces[0], pieces[2] )); rest = cursor; } out.push_str(rest); out } /// Map a fontspec family name to one of the engine's NFSS families. fn fontspec_family(name: &str) -> &'static str { let lowered = name.to_ascii_lowercase(); if lowered.contains("mono") || lowered.contains("typewriter") || lowered.contains("courier") { "cmtt" } else if lowered.contains("sans") || lowered.contains("helvetica") || lowered.contains("arial") { "cmss" } else { "cmr" } } fn strip_page_geometry( source: &str, images: &HashMap, ) -> (String, PageGeometry) { // Full-width floats behave like their single-column counterparts here. let source = source .replace("\\begin{figure*}", "\\begin{figure}") .replace("\\end{figure*}", "\\end{figure}") .replace("\\begin{table*}", "\\begin{table}") .replace("\\end{table*}", "\\end{table}"); let mut geometry = PageGeometry::default(); geometry.images = images.clone(); let mut body = String::new(); let mut tabular: Option<(String, String, &'static str, Option, usize)> = None; let mut in_document = false; for line in source.lines() { let trimmed = line.trim(); if trimmed.contains("\\begin{document}") { in_document = true; } if let Some((_, text, environment, _, depth)) = tabular.as_mut() { let end = format!("\\end{{{environment}}}"); let closed = trimmed.strip_suffix(&end); let begins = trimmed.matches("\\begin{tabular").count(); let ends = trimmed.matches("\\end{tabular").count(); if closed.is_some() && *depth == 0 && begins == 0 { if let Some(prefix) = closed { let prefix = prefix.trim(); if !prefix.is_empty() { if !text.is_empty() { text.push('\n'); } text.push_str(prefix); } } let (template, text, _, target, _) = tabular.take().unwrap(); let text = protect_nested_tables(&text, &mut geometry.nested_tables); geometry .tabular .push((template, expand_multirow(&text), target)); } else { if begins > ends { *depth += begins - ends; } else { *depth = depth.saturating_sub(ends - begins); } if !text.is_empty() { text.push('\n'); } text.push_str(trimmed); } continue; } let mut table_environment = None; for environment in ["tabular", "longtable", "tabularx", "tabular*"] { let begin = format!("\\begin{{{environment}}}"); if let Some(rest) = trimmed.strip_prefix(&begin) { table_environment = Some((environment, rest)); break; } } if let Some((environment, rest)) = table_environment { let rest = rest.trim_start(); let rest = match rest .strip_prefix('[') .and_then(|after| after.split_once(']')) { Some((_, tail)) => tail.trim_start(), None => rest, }; let (rest, target) = if environment == "tabularx" || environment == "tabular*" { let Some((width, after)) = braced(rest) else { continue; }; match parse_dimension(width) { Some(width) => (after.trim_start(), Some(width)), None => continue, } } else { (rest, None) }; if let Some((template, _)) = braced(rest) { if !body.ends_with('\n') { body.push('\n'); } body.push_str(&format!("\\texrratable{{{}}}\n", geometry.tabular.len())); tabular = Some((template.to_string(), String::new(), environment, target, 0)); } continue; } if let Some(rest) = trimmed .strip_prefix("\\newfontfamily") .or_else(|| trimmed.strip_prefix("\\renewfontfamily")) { let rest = rest.trim_start(); if let Some((name, used)) = control_sequence(rest) { let mut rest = rest[used..].trim_start(); if let Some(stripped) = rest.strip_prefix('[') && let Some((_options, tail)) = stripped.split_once(']') { rest = tail.trim_start(); } if let Some((font, _)) = braced_group(rest) { geometry.macros.push(MacroDefinition { name, args: 0, default: None, params: None, body: format!("\\fontfamily{{{}}}\\selectfont", fontspec_family(font)), }); } } continue; } if trimmed.starts_with("\\setmainfont") || trimmed.starts_with("\\setsansfont") || trimmed.starts_with("\\setmonofont") { // The engine's Roman/Sans/Mono faces already stand in for the // document's chosen families; consume the declaration. continue; } if trimmed.starts_with("\\newenvironment") || trimmed.starts_with("\\renewenvironment") { if let Some(definition) = environment_definition(trimmed) { geometry.environments.push(definition); } continue; } if trimmed.starts_with("\\allowdisplaybreaks") { continue; } if let Some(rest) = trimmed.strip_prefix("\\newcolumntype") { let rest = rest.trim_start(); let Some((name, used)) = braced_group(rest) else { continue; }; let after = rest[used..].trim_start(); let mut arg_count = 0_u8; let after = if let Some(inner) = after.strip_prefix('[') { if let Some(bracket) = inner.find(']') { arg_count = inner[..bracket].trim().parse().unwrap_or(0); inner[bracket + 1..].trim_start() } else { after } } else { after }; if let Some((spec, _)) = braced_group(after) { if let Some(letter) = name.trim().chars().next() { geometry .column_types .push((letter, spec.trim().to_string(), arg_count)); } } continue; } if trimmed.starts_with("\\newsavebox") || trimmed.starts_with("\\sbox") || trimmed.starts_with("\\savebox") { let base = geometry.base_font_size.unwrap_or(655_360); handle_savebox_line( trimmed, &mut geometry.macros, &mut geometry.savebox_dimensions, base, images, ); continue; } if let Some(rest) = trimmed.strip_prefix("\\newcount") { if let Some((command, _)) = control_sequence(rest.trim_start()) { let name = command.trim_start_matches('\\').to_string(); if !geometry .count_registers .iter() .any(|(known, _)| known == &name) { geometry.count_registers.push((name, 0)); } } continue; } if let Some((command, used)) = control_sequence(trimmed) { let name = command.trim_start_matches('\\'); if let Some(position) = geometry .count_registers .iter() .position(|(known, _)| known == name) { let rest = trimmed[used..].trim_start(); if let Some(value) = rest.strip_prefix('=') { if let Some((assigned, _)) = scan_signed_integer(value) { geometry.count_registers[position].1 = assigned; continue; } } } } if let Some(rest) = trimmed.strip_prefix("\\newdimen") { if let Some((command, _)) = control_sequence(rest.trim_start()) { let name = command.trim_start_matches('\\').to_string(); if !geometry .dimension_registers .iter() .any(|(known, _)| known == &name) { geometry.dimension_registers.push((name, 0)); } } continue; } if let Some(rest) = trimmed.strip_prefix("\\newskip") { if let Some((command, _)) = control_sequence(rest.trim_start()) { let name = command.trim_start_matches('\\').to_string(); if !geometry .skip_registers .iter() .any(|(known, _)| known == &name) { geometry.skip_registers.push((name, [0, 0, 0])); } } continue; } if let Some(name) = newif_definition(trimmed) { geometry .conditionals .push(ConditionalDefinition { name, value: false }); continue; } if let Some((name, value, _)) = conditional_assignment(trimmed, &geometry.conditionals) { if let Some(flag) = geometry .conditionals .iter_mut() .find(|flag| flag.name == name) { flag.value = value; } continue; } if let Some(name) = new_counter_definition(trimmed) { if !geometry.counters.iter().any(|(known, _)| known == &name) { geometry.counters.push((name, 0)); } continue; } if let Some((name, delta)) = add_counter_assignment(trimmed) { if name == "page" { geometry.page_start = (geometry.page_start as i64 + delta).clamp(0, u32::MAX as i64) as u32; } else { let current = geometry_counter(&geometry, &name) as i64; let updated = (current + delta).clamp(0, u32::MAX as i64) as u32; geometry.counters.push((name, updated)); } continue; } if let Some((name, value)) = any_counter_assignment(trimmed) { if name == "page" { geometry.page_start = value.saturating_sub(1); } match name.as_str() { "secnumdepth" => geometry.secnumdepth = Some(value), "tocdepth" => geometry.tocdepth = Some(value), _ => geometry.counters.push((name, value)), } continue; } if let Some(spread) = baselinestretch_assignment(trimmed) { geometry.linespread = Some(spread); continue; } if let Some(spread) = arraystretch_assignment(trimmed) { geometry.array_stretch = Some(spread); continue; } if let Some(name) = renewcommand_text(trimmed, "figurename") { geometry.figure_name = Some(name); continue; } if let Some(name) = renewcommand_text(trimmed, "tablename") { geometry.table_name = Some(name); continue; } if let Some(name) = renewcommand_text(trimmed, "abstractname") { geometry.abstract_name = Some(name); continue; } if let Some(name) = renewcommand_text(trimmed, "refname") { geometry.ref_name = Some(name); continue; } if let Some(name) = renewcommand_text(trimmed, "contentsname") { geometry.contents_name = Some(name); continue; } if let Some(name) = renewcommand_text(trimmed, "listfigurename") { geometry.list_figure_name = Some(name); continue; } if let Some(name) = renewcommand_text(trimmed, "listtablename") { geometry.list_table_name = Some(name); continue; } if let Some(rest) = trimmed.strip_prefix("\\DeclareMathOperator") { let mut rest = rest.trim_start(); let mut starred = false; if rest.starts_with('*') { starred = true; rest = rest[1..].trim_start(); } if let Some((command, tail)) = braced(rest) { if let Some((body, _)) = braced(tail.trim_start()) { let name = command.trim().trim_start_matches('\\').to_string(); let operator = if starred { format!("\\operatorname*{{{}}}", body.trim()) } else { format!("\\operatorname{{{}}}", body.trim()) }; geometry.macros.push(MacroDefinition { name, args: 0, default: None, body: operator, params: None, }); } } continue; } let definition_line = strip_definition_prefixes(trimmed); if !in_document && trimmed.starts_with("\\chardef") { if let Some(definition) = char_definition(trimmed) { geometry.macros.push(definition); } continue; } if !in_document && (definition_line.starts_with(r"\edef") || definition_line.starts_with(r"\xdef") || definition_line.starts_with(r"\protected@edef") || definition_line.starts_with(r"\protected@xdef")) { if let Some(definition) = edef_definition(definition_line, &geometry.macros) { geometry.macros.push(definition); } continue; } if let Some(rest) = trimmed.strip_prefix("\\@namedef") { let rest = rest.trim_start(); if let Some((name, used)) = braced_group(rest) { let rest = rest[used..].trim_start(); if let Some((body, _)) = braced_group(rest) { let name = name.trim().trim_start_matches('\\'); geometry.macros.push(MacroDefinition { name: format!("\\{}", name), args: 0, default: None, body: body.to_string(), params: None, }); continue; } } } let is_macro_command = |command: &str| { definition_line.strip_prefix(command).is_some_and(|rest| { rest.starts_with('{') || rest.starts_with('\\') || rest.chars().next().is_some_and(char::is_whitespace) }) }; if !in_document && (is_macro_command("\\newcommand") || is_macro_command("\\renewcommand") || is_macro_command("\\DeclareRobustCommand") || is_macro_command("\\providecommand") || is_macro_command("\\def") || is_macro_command("\\gdef")) { if is_macro_command("\\renewcommand") && let Some(width) = renewcommand_length(definition_line, "headrulewidth") { geometry.head_rule_width = Some(width); continue; } // Only consume the line when the definition ends it; otherwise // inline capture handles a definition embedded in running text. if let Some(definition) = macro_definition(definition_line) && definition_consumes_line(definition_line) { let provided = definition_line.trim_start().starts_with("\\providecommand"); if !provided || !geometry .macros .iter() .any(|known| known.name == definition.name) { geometry.macros.push(definition); } continue; } } if trimmed.starts_with(r"\bibliographystyle") || trimmed.starts_with(r"\bibliography{") { let rest = trimmed .strip_prefix(r"\bibliographystyle") .or_else(|| trimmed.strip_prefix(r"\bibliography")); if let Some(rest) = rest && braced_group(rest.trim_start()).is_some() { continue; } } if let Some((name, target)) = macro_alias(definition_line) { let definition = geometry .macros .iter() .find(|definition| definition.name == target) .cloned() .unwrap_or(MacroDefinition { name: name.clone(), args: 0, default: None, body: String::new(), params: None, }); geometry.macros.push(MacroDefinition { name, args: definition.args, default: definition.default, body: definition.body, params: None, }); continue; } if trimmed == "\\listoffigures" { body.push_str("\\texrralof\n\n"); continue; } if trimmed == "\\listoftables" { body.push_str("\\texrralot\n\n"); continue; } if trimmed == "\\tableofcontents" { body.push_str("\\texrratoc\n\n"); continue; } if trimmed.starts_with("\\newtheorem") { if let Some(definition) = newtheorem_definition(trimmed) { geometry.theorem_definitions.push(definition); } continue; } if trimmed.starts_with("\\graphicspath") { geometry .graphics_paths .extend(graphics_path_groups(trimmed)); continue; } if trimmed.starts_with("\\pagecolor") { let rest = trimmed .strip_prefix("\\pagecolor") .map(str::trim_start) .unwrap_or(""); if let Some((name, _)) = braced_group(rest) { geometry.page_color = color_spec(name.trim(), &geometry.colors); } continue; } if let Some((name, rgb)) = define_color(trimmed) { geometry.colors.retain(|(known, _)| known != &name); geometry.colors.push((name, rgb)); continue; } if trimmed.starts_with("\\hypersetup") { for (key, value) in hypersetup_values(trimmed) { match key.as_str() { "pdftitle" => geometry.pdf_title = Some(value), "pdfauthor" => geometry.pdf_author = Some(value), "pdfsubject" => geometry.pdf_subject = Some(value), "pdfkeywords" => geometry.pdf_keywords = Some(value), "urlcolor" | "linkcolor" => geometry.link_color = Some(value), "linkbordercolor" | "urlbordercolor" => { geometry.link_border_color = Some(value) } "hidelinks" => geometry.hide_links = true, _ => {} } } 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); let rest = trimmed.trim_start_matches("\\documentclass").trim_start(); let rest = match rest.strip_prefix('[') { Some(after) => after .split_once(']') .map_or(rest, |(_, remainder)| remainder.trim_start()), None => rest, }; if let Some((name, _)) = braced_group(rest) { geometry.document_class = Some(name.trim().to_string()); } continue; } if let Some(spread) = linespread_assignment(trimmed) { geometry.linespread = Some(spread); continue; } if let Some(value) = dimension_assignment(trimmed, "hoffset") { geometry.origin.h_offset = value; } else if let Some(value) = dimension_assignment(trimmed, "voffset") { geometry.origin.v_offset = value; } else if let Some(value) = dimension_assignment(trimmed, "paperwidth") { geometry.paper_width = Some(value); } else if let Some(value) = dimension_assignment(trimmed, "paperheight") { geometry.paper_height = Some(value); } else if let Some(value) = dimension_assignment(trimmed, "vsize") { geometry.vsize = Some(value); } else if let Some(value) = dimension_assignment(trimmed, "textheight") { geometry.textheight = Some(value); } else if let Some(value) = dimension_assignment(trimmed, "textwidth") { geometry.line_width = Some(value); } else if let Some(value) = dimension_assignment(trimmed, "hsize") { geometry.line_width = Some(value); } else if let Some(value) = dimension_assignment(trimmed, "linewidth") { geometry.line_width = Some(value); } else if let Some((width, stretch, shrink)) = setlength_glue(trimmed, "parskip") { geometry.par_skip = Some(width); geometry.par_skip_stretch = Some(stretch); geometry.par_skip_shrink = Some(shrink); } else if let Some(spacing) = setlength_glue(trimmed, "itemsep") { geometry.item_sep = Some(spacing); } else if let Some(spacing) = setlength_glue(trimmed, "topsep") { geometry.top_sep = Some(spacing); } else if let Some(spacing) = setlength_glue(trimmed, "partopsep") { geometry.part_op_sep = Some(spacing); } else if let Some((name, raw)) = addtolength_assignment(trimmed) { if let Some(delta) = length_value(&geometry, &raw) && let Some((_, current)) = geometry .lengths .iter_mut() .rev() .find(|(known, _)| known == &name) { *current = current.saturating_add(delta); } } else if let Some((name, raw)) = setlength_assignment(trimmed) { if let Some(position) = geometry .skip_registers .iter() .position(|(known, _)| known == &name) { if let Some((width, stretch, shrink, _)) = parse_glue(&raw) { geometry.skip_registers[position].1 = [width, stretch, shrink]; } } else if let Some(value) = length_value(&geometry, &raw) { match name.as_str() { "textwidth" | "hsize" | "linewidth" => geometry.line_width = Some(value), "parindent" => geometry.par_indent = Some(value), "baselineskip" => geometry.baseline_skip = Some(value), "textheight" => geometry.textheight = Some(value), "vsize" => geometry.vsize = Some(value), "leftskip" => geometry.left_skip = Some(value), "rightskip" => geometry.right_skip = Some(value), "emergencystretch" => geometry.emergency_stretch = Some(value), "hangindent" => geometry.hang_indent = Some(value), "lineskip" => geometry.lineskip = Some(value), "lineskiplimit" => geometry.lineskiplimit = Some(value), "topskip" => geometry.top_skip = Some(value), "maxdepth" => geometry.max_depth = Some(value), "splittopskip" => geometry.split_top_skip = Some(value), "splitmaxdepth" => geometry.split_max_depth = Some(value), "tabcolsep" => geometry.tab_col_sep = Some(value), _ => { geometry.lengths.retain(|(known, _)| known != &name); geometry.lengths.push((name, value)); } } } } else if let Some(rest) = trimmed.strip_prefix("\\pagenumbering") { if let Some(rest) = rest.trim_start().strip_prefix('{') && let Some((name, _)) = rest.split_once('}') { geometry.page_numbering = Some(name.trim().to_string()); geometry.page_start = 0; } } else if let Some(rest) = trimmed.strip_prefix("\\pagestyle") { if rest.trim_start().starts_with("{fancy}") { geometry.fancy_pagestyle = true; } if rest.trim_start().starts_with("{empty}") { geometry.suppress_page_numbers = true; } } else if let Some(rest) = trimmed.strip_prefix("\\thispagestyle") { if rest.trim_start().starts_with("{empty}") { geometry.suppress_first_page_number = true; geometry.suppress_first_page_header = true; } } else if let Some((positions, text)) = fancy_field(trimmed, "\\fancyhead") { set_fancy_fields(&mut geometry, &positions, &text, FancySlot::Header); } else if let Some((positions, text)) = fancy_field(trimmed, "\\fancyfoot") { set_fancy_fields(&mut geometry, &positions, &text, FancySlot::Footer); } else if let Some(text) = fancy_all(trimmed, "\\fancyhf") { let _ = text; geometry.header_left = None; geometry.header_center = None; geometry.header_right = None; geometry.footer_left = None; geometry.footer_center = None; geometry.footer_right = None; } else if let Some((positions, text)) = fancy_field(trimmed, "\\fancyhf") { set_fancy_fields(&mut geometry, &positions, &text, FancySlot::Header); set_fancy_fields(&mut geometry, &positions, &text, FancySlot::Footer); } else if let Some(text) = braced_value(trimmed, "\\lhead") { geometry.header_left = Some(text); } else if let Some(text) = braced_value(trimmed, "\\chead") { geometry.header_center = Some(text); } else if let Some(text) = braced_value(trimmed, "\\rhead") { geometry.header_right = Some(text); } else if let Some(text) = braced_value(trimmed, "\\lfoot") { geometry.footer_left = Some(text); } else if let Some(text) = braced_value(trimmed, "\\cfoot") { geometry.footer_center = Some(text); } else if let Some(text) = braced_value(trimmed, "\\rfoot") { geometry.footer_right = Some(text); } else if trimmed.starts_with("\\fancyheadoffset") || trimmed.starts_with("\\fancyfootoffset") { continue; } else if let Some(width) = renewcommand_length(trimmed, "headrulewidth") { geometry.head_rule_width = Some(width); } else if let Some(name) = trimmed.strip_prefix("\\newlength") { if let Some(name) = name.trim_start().strip_prefix('{') && let Some((name, _)) = name.split_once('}') { let name = name.trim().strip_prefix('\\').unwrap_or(name.trim()); geometry.lengths.retain(|(known, _)| known != name); geometry.lengths.push((name.to_string(), 0)); } } else if let Some(value) = dimension_assignment(trimmed, "parindent") { geometry.par_indent = Some(value); } else if let Some((width, stretch, shrink)) = glue_assignment(trimmed, "parskip") { geometry.par_skip = Some(width); geometry.par_skip_stretch = Some(stretch); geometry.par_skip_shrink = Some(shrink); } else if let Some(spacing) = glue_assignment(trimmed, "abovedisplayskip") { geometry.above_display_skip = Some(spacing); } else if glue_copy(trimmed, "belowdisplayskip", "abovedisplayskip") { geometry.below_display_skip = geometry.above_display_skip; } else if let Some(spacing) = glue_assignment(trimmed, "belowdisplayskip") { geometry.below_display_skip = Some(spacing); } else if let Some(spacing) = glue_assignment(trimmed, "abovedisplayshortskip") { geometry.above_display_short_skip = Some(spacing); } else if let Some(spacing) = glue_assignment(trimmed, "belowdisplayshortskip") { geometry.below_display_short_skip = Some(spacing); } else if let Some(spacing) = setlength_glue(trimmed, "abovedisplayskip") { geometry.above_display_skip = Some(spacing); } else if let Some(spacing) = setlength_glue(trimmed, "belowdisplayskip") { geometry.below_display_skip = Some(spacing); } else if let Some(spacing) = glue_assignment(trimmed, "itemsep") { geometry.item_sep = Some(spacing); } else if let Some(spacing) = glue_assignment(trimmed, "topsep") { geometry.top_sep = Some(spacing); } else if let Some(spacing) = glue_assignment(trimmed, "partopsep") { geometry.part_op_sep = Some(spacing); } else if let Some(value) = dimension_assignment(trimmed, "baselineskip") { geometry.baseline_skip = Some(value); } else if let Some(value) = dimension_assignment(trimmed, "tabcolsep") { geometry.tab_col_sep = Some(value); } else if let Some(value) = dimension_assignment(trimmed, "leftskip") { geometry.left_skip = Some(value); } else if let Some(value) = dimension_assignment(trimmed, "rightskip") { geometry.right_skip = Some(value); } else if let Some(value) = dimension_assignment(trimmed, "emergencystretch") { geometry.emergency_stretch = Some(value); } else if let Some(value) = integer_assignment(trimmed, "tolerance") { geometry.tolerance = Some(value); } else if let Some(value) = integer_assignment(trimmed, "pretolerance") { geometry.pretolerance = Some(value); } else if let Some(value) = signed_integer_assignment(trimmed, "looseness") { geometry.looseness = Some(value.clamp(-9, 9)); } else if let Some(value) = dimension_assignment(trimmed, "hangindent") { geometry.hang_indent = Some(value); } else if let Some(value) = integer_assignment(trimmed, "hangafter") { geometry.hang_after = Some(value); } else if let Some(value) = glue_assignment(trimmed, "spaceskip") { geometry.space_skip = Some(value); } else if let Some(value) = glue_assignment(trimmed, "xspaceskip") { geometry.xspace_skip = Some(value); } else if let Some(value) = dimension_assignment(trimmed, "lineskip") { geometry.lineskip = Some(value); } else if let Some(value) = dimension_assignment(trimmed, "lineskiplimit") { geometry.lineskiplimit = Some(value); } else if let Some((character, value)) = sfcode_assignment(trimmed) { geometry.space_factor_codes.push((character, value)); } else if let Some(value) = integer_assignment(trimmed, "hyphenpenalty") { geometry.hyphen_penalty = Some(value); } else if let Some(value) = integer_assignment(trimmed, "exhyphenpenalty") { geometry.ex_hyphen_penalty = Some(value); } else if let Some(value) = integer_assignment(trimmed, "doublehyphendemerits") { geometry.double_hyphen_demerits = Some(value); } else if let Some(value) = integer_assignment(trimmed, "finalhyphendemerits") { geometry.final_hyphen_demerits = Some(value); } else if let Some(value) = integer_assignment(trimmed, "linepenalty") { geometry.line_penalty = Some(value); } else if let Some(value) = integer_assignment(trimmed, "adjdemerits") { geometry.adj_demerits = Some(value); } else if let Some(value) = integer_assignment(trimmed, "clubpenalty") { geometry.club_penalty = Some(value); } else if let Some(value) = integer_assignment(trimmed, "widowpenalty") { geometry.widow_penalty = Some(value); } else if let Some(value) = dimension_assignment(trimmed, "topskip") { geometry.top_skip = Some(value); } else if let Some(value) = dimension_assignment(trimmed, "maxdepth") { geometry.max_depth = Some(value); } else if let Some(value) = dimension_assignment(trimmed, "splittopskip") { geometry.split_top_skip = Some(value); } else if let Some(value) = dimension_assignment(trimmed, "splitmaxdepth") { geometry.split_max_depth = Some(value); } else if let Some(value) = parfillskip_assignment(trimmed) { geometry.par_fillskip = Some(value); } else if let Some(value) = parshape_assignment(trimmed) { geometry.par_shape = value; } else if let Some(value) = braced_argument(trimmed, "\\hyphenation") { geometry .hyphenation_exceptions .extend(value.split_whitespace().map(str::to_string)); } else if trimmed == "\\frenchspacing" { geometry.french_spacing = Some(true); } else if trimmed == "\\nonfrenchspacing" { geometry.french_spacing = Some(false); } else { body.push_str(line); body.push('\n'); } } if let Some((template, text, _, target, _)) = tabular { let text = protect_nested_tables(&text, &mut geometry.nested_tables); geometry .tabular .push((template, expand_multirow(&text), target)); } (body, geometry) } fn braced(text: &str) -> Option<(&str, &str)> { let mut depth = 0_i32; for (index, character) in text.char_indices() { match character { '{' => depth += 1, '}' => { depth -= 1; if depth == 0 { return Some((&text[1..index], &text[index + 1..])); } } _ => {} } } None } /// Replace nested `tabular` blocks with `\texrranested{index}` tokens and /// store their sources on the geometry for `tabular_unit` to resolve. fn protect_nested_tables(source: &str, nested_tables: &mut Vec) -> String { let mut out = String::new(); let mut rest = source; while let Some(position) = rest.find("\\begin{tabular") { out.push_str(&rest[..position]); let after = &rest[position..]; let Some(end) = nested_table_end(after) else { out.push_str(after); return out; }; let block = &after[..end]; let index = nested_tables.len(); nested_tables.push(block.to_string()); out.push_str(&format!("\\texrranested{{{index}}}")); rest = &after[end..]; } out.push_str(rest); out } /// Split a full `\begin{tabular}...\end{tabular}` block into its column spec /// and body rows. fn nested_table_parts(block: &str) -> Option<(&str, &str)> { let open_end = block.find('}')?; let environment = block.get("\\begin{".len()..open_end)?; let mut rest = block[open_end + 1..].trim_start(); if let Some(stripped) = rest.strip_prefix('[') && let Some((_, tail)) = stripped.split_once(']') { rest = tail.trim_start(); } if (environment == "tabularx" || environment == "tabular*") && let Some((_, used)) = braced_group(rest) { rest = rest[used..].trim_start(); } let (spec, used) = braced_group(rest)?; let body = &rest[used..]; let body_end = body.rfind("\\end{tabular")?; Some((spec, body[..body_end].trim())) } /// Flatten nested `tabular` environments to a text summary (fallback). #[allow(dead_code)] fn flatten_nested_tables(source: &str) -> String { let mut out = String::new(); let mut rest = source; while let Some(position) = rest.find("\\begin{tabular") { out.push_str(&rest[..position]); let after = &rest[position..]; let Some(end) = nested_table_end(after) else { out.push_str(after); return out; }; let block = &after[..end]; out.push_str(&flatten_nested_block(block)); rest = &after[end..]; } out.push_str(rest); out } /// Return the byte offset just past the matching `\end{tabular}`. fn nested_table_end(text: &str) -> Option { let begin = "\\begin{tabular"; let end = "\\end{tabular}"; let mut depth = 0_i64; let mut cursor = 0; 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; cursor = end_at + end.len(); if depth <= 0 { return Some(cursor); } } (Some(begin_at), None) => { depth += 1; cursor = begin_at + begin.len(); } (None, None) => return None, } } None } fn flatten_nested_block(block: &str) -> String { let Some(open_end) = block.find('}') else { return String::new(); }; let environment = block.get("\\begin{".len()..open_end).unwrap_or(""); let body_end = block.rfind("\\end{tabular").unwrap_or(block.len()); let mut rest = block[open_end + 1..body_end].trim_start(); if let Some(stripped) = rest.strip_prefix('[') && let Some((_, tail)) = stripped.split_once(']') { rest = tail.trim_start(); } if environment == "tabularx" || environment == "tabular*" { if let Some((_, used)) = braced_group(rest) { rest = rest[used..].trim_start(); } } let Some((_spec, used)) = braced_group(rest) else { return String::new(); }; let body = &rest[used..]; let rows: Vec = split_top_level(body, "\\\\") .into_iter() .map(|row| { let row = strip_table_rules(&row); let cells: Vec = split_top_level(&row, "&") .into_iter() .map(|cell| flatten_nested_cell(&cell)) .filter(|cell| !cell.is_empty()) .collect(); cells.join(" ") }) .filter(|row| !row.is_empty()) .collect(); rows.join(" ; ") } fn flatten_nested_cell(cell: &str) -> String { let mut text = cell.to_string(); for command in ["\\multicolumn", "\\multirow"] { while let Some(position) = text.find(command) { let after = &text[position + command.len()..]; let mut rest = after.trim_start(); let mut argument = String::new(); for _ in 0..3 { if let Some((group, used)) = braced_group(rest) { argument = group.to_string(); rest = rest[used..].trim_start(); } else { break; } } if argument.is_empty() { break; } text = format!("{}{}{}", &text[..position], argument, rest); } } let text = flatten_nested_tables(&text); let text = strip_table_rules(&text); let text = scrub_title_metadata(&text); let text = strip_noop_commands(&text); text.split_whitespace().collect::>().join(" ") } fn split_top_level(text: &str, separator: &str) -> Vec { let mut parts = Vec::new(); let mut current = String::new(); let mut depth = 0_i64; let mut chars = text.char_indices().peekable(); while let Some((index, character)) = chars.next() { if character == '{' { depth += 1; } else if character == '}' { depth -= 1; } if depth == 0 && text[index..].starts_with(separator) { parts.push(std::mem::take(&mut current)); for _ in 1..separator.len() { chars.next(); } continue; } current.push(character); } parts.push(current); parts } fn strip_table_rules(text: &str) -> String { let mut out = text.to_string(); for command in [ "\\hline", "\\toprule", "\\midrule", "\\bottomrule", "\\addlinespace", "\\cmidrule", "\\cline", "\\noalign", ] { while let Some(position) = out.find(command) { let after = &out[position + command.len()..]; let mut rest = after.trim_start(); if let Some(inner) = rest.strip_prefix('(') { if let Some(close) = inner.find(')') { rest = inner[close + 1..].trim_start(); } } if let Some(stripped) = rest.strip_prefix('[') && let Some((_, tail)) = stripped.split_once(']') { rest = tail.trim_start(); } if let Some((_, used)) = braced_group(rest) { rest = &rest[used..]; } out = format!("{}{}", &out[..position], rest); } } out } /// Build a captured `tabular` unit with the document's `\tabcolsep`. /// Replace `X` columns of a `tabularx` template with paragraph columns that /// share the leftover width, so the table fills its declared target. fn expand_tabular_template(template: &str, source: &str, target: Option) -> String { let Some(target) = target else { return template.to_string(); }; if !template.contains('X') { return template.to_string(); } let probe_template: String = template .chars() .map(|character| if character == 'X' { 'l' } else { character }) .collect(); let probe = Unit::halign_from_source_with_template_and_tabskips( 0, &engine_template(&probe_template), source, 12, Vec::new(), ); let Some(VerticalItem::Halign(halign)) = probe.items.first() else { return template.to_string(); }; let mut flags = Vec::new(); let characters: Vec = template.chars().collect(); let mut index = 0; while index < characters.len() { match characters[index] { 'l' | 'c' | 'r' => { flags.push(false); index += 1; } 'X' => { flags.push(true); index += 1; } 'p' | 'm' | 'b' => { flags.push(false); index += 1; if characters.get(index) == Some(&'{') { let mut depth = 0_i32; while index < characters.len() { let inner = characters[index]; index += 1; match inner { '{' => depth += 1, '}' => { depth -= 1; if depth == 0 { break; } } _ => {} } } } } _ => index += 1, } } let x_count = flags.iter().filter(|expand| **expand).count(); if x_count == 0 { return template.to_string(); } let gaps = halign.column_widths.len().saturating_sub(1) as i64; let fixed: i64 = halign .column_widths .iter() .zip(flags.iter()) .filter(|(_, expand)| !**expand) .map(|(width, _)| *width) .sum(); let share = ((target - fixed - gaps * 12 * SCALE) / x_count as i64).max(SCALE); let share = format!("p{{{:.4}pt}}", share as f64 / SCALE as f64); let mut out = String::new(); let mut index = 0; while index < characters.len() { let character = characters[index]; match character { 'X' => { out.push_str(&share); index += 1; } 'p' | 'm' | 'b' => { out.push('p'); index += 1; if characters.get(index) == Some(&'{') { let mut depth = 0_i32; while index < characters.len() { let inner = characters[index]; out.push(inner); index += 1; match inner { '{' => depth += 1, '}' => { depth -= 1; if depth == 0 { break; } } _ => {} } } } } _ => { out.push(character); index += 1; } } } out } /// Substitute `\newcolumntype` letters at the top level of a column spec. fn expand_column_types(template: &str, types: &[(char, String, u8)]) -> String { if types.is_empty() { return template.to_string(); } let mut characters = template.chars().peekable(); let mut out = String::new(); let mut depth = 0_usize; while let Some(character) = characters.next() { match character { '{' => { depth += 1; out.push(character); } '}' => { depth = depth.saturating_sub(1); out.push(character); } _ if depth == 0 => { if let Some((_, spec, args)) = types.iter().find(|(letter, _, _)| *letter == character) { let mut spec = spec.clone(); for index in 1..=*args { while characters.peek().is_some_and(|next| next.is_whitespace()) { characters.next(); } if characters.peek() != Some(&'{') { break; } characters.next(); let mut argument = String::new(); let mut nested = 1_usize; while let Some(inner) = characters.next() { match inner { '{' => { nested += 1; argument.push(inner); } '}' => { nested -= 1; if nested == 0 { break; } argument.push(inner); } _ => argument.push(inner), } } spec = spec.replace(&format!("#{index}"), &argument); } out.push_str(&spec); } else { out.push(character); } } _ => out.push(character), } } out } fn tabular_unit( geometry: &PageGeometry, id: u64, template: &str, source: &str, target: Option, ) -> Unit { let separator = geometry.tab_col_sep.unwrap_or(6 * SCALE); let template = expand_column_types(template, &geometry.column_types); let inner_target = target.map(|target| (target - 2 * 6 * SCALE).max(10 * 65_536)); let template = expand_tabular_template(&template, source, inner_target); let mut unit = Unit::halign_from_source_with_template_and_tabskips( id, &engine_template(&template), source, 12, Vec::new(), ); let stretch = geometry.array_stretch.unwrap_or(1000); if separator != 6 * SCALE || stretch != 1000 { if let Some(VerticalItem::Halign(halign)) = unit.items.first_mut() { if separator != 6 * SCALE { let gaps = halign.column_widths.len().saturating_sub(1); halign.column_skips = vec![separator * 2; gaps]; halign.width = halign.column_widths.iter().sum::() + separator * 2 * gaps as i64; } halign.margin = separator; if stretch != 1000 { halign.line_height = halign.line_height.saturating_mul(stretch) / 1000; halign.height = (0..halign.rows.len()) .map(|index| halign.row_height(index) + halign.row_gap(index)) .sum(); } } } if let Some(VerticalItem::Halign(halign)) = unit.items.first_mut() { halign.margin = separator; halign.width += 2 * separator; if let Some(target) = target && halign.column_widths.len() > 1 && halign.width < target { let extra = target - halign.width; if halign.column_skips.is_empty() { halign.width = target; } else { let gaps = halign.column_skips.len() as i64; let per = extra / gaps.max(1); for skip in &mut halign.column_skips { *skip += per; } halign.width += per * gaps; } } } if let Some(VerticalItem::Halign(halign)) = unit.items.first_mut() { resolve_nested_tables(halign, geometry, id); } unit } fn resolve_nested_tables(halign: &mut texrra_tex_core::Halign, geometry: &PageGeometry, id: u64) { let mut placements = Vec::new(); for (row_index, row) in halign.rows.iter().enumerate() { for (cell_index, cell) in row.cells.iter().enumerate() { if let Some(rest) = cell.text.trim().strip_prefix("\\texrranested{") && let Some((index, _)) = rest.split_once('}') && let Ok(index) = index.trim().parse::() { placements.push((row_index, cell_index, index)); } } } for (row, cell, index) in placements { let Some(source) = geometry.nested_tables.get(index).cloned() else { continue; }; let Some((template, body)) = nested_table_parts(&source) else { continue; }; let template = template.to_string(); let body = body.to_string(); let inner = tabular_unit(geometry, id, &template, &body, None); let Some(VerticalItem::Halign(table)) = inner.items.first().cloned() else { continue; }; if let Some(cell) = halign .rows .get_mut(row) .and_then(|line| line.cells.get_mut(cell)) { cell.text.clear(); } halign.nested.push((row, cell, table)); } if !halign.nested.is_empty() { halign.refresh_measurements(); } } fn engine_template(spec: &str) -> String { let mut out = String::new(); let mut characters = spec.chars().peekable(); while let Some(character) = characters.next() { match character { 'l' | 'c' | 'r' => out.push(character), 'p' | 'm' | 'b' => { out.push('p'); if characters.peek() == Some(&'{') { let mut depth = 0_i32; for inner in characters.by_ref() { out.push(inner); match inner { '{' => depth += 1, '}' => { depth -= 1; if depth == 0 { break; } } _ => {} } } } } '|' => out.push('|'), '*' => { if characters.peek() != Some(&'{') { continue; } characters.next(); let mut count = String::new(); while let Some(&digit) = characters.peek() { characters.next(); if digit == '}' { break; } if digit.is_ascii_digit() { count.push(digit); } } let Some(count) = count.parse::().ok() else { continue; }; if characters.peek() != Some(&'{') { continue; } let mut inner = String::new(); let mut depth = 1_u32; for character in characters.by_ref() { match character { '{' => { depth += 1; inner.push(character); } '}' => { depth -= 1; if depth == 0 { break; } inner.push(character); } _ => inner.push(character), } } out.push_str(&engine_template(&inner).repeat(count.min(20))); } ' ' | '\t' => {} '@' | '!' | '>' | '<' => { if characters.peek() == Some(&'{') { let mut depth = 0_i32; for inner in characters.by_ref() { match inner { '{' => depth += 1, '}' => { depth -= 1; if depth == 0 { break; } } _ => {} } } } } _ => {} } } if out.is_empty() { "l".to_string() } else { out } } fn table_reference(text: &str) -> Option { 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. /// Parse an optionally signed decimal integer, returning its value and the /// number of bytes consumed (including leading spaces). fn scan_signed_integer(text: &str) -> Option<(i64, usize)> { let trimmed = text.trim_start(); let skipped = text.len() - trimmed.len(); let mut characters = trimmed.char_indices().peekable(); let mut negative = false; if let Some((_, sign)) = characters.peek().copied() { if sign == '-' || sign == '+' { negative = sign == '-'; characters.next(); } } let mut digits = String::new(); for (offset, character) in characters { if let Some(digit) = character.to_digit(10) { digits.push(char::from_digit(digit, 10).unwrap_or('0')); } else { return if digits.is_empty() { None } else { let value: i64 = digits.parse().ok()?; Some((if negative { -value } else { value }, skipped + offset)) }; } } if digits.is_empty() { return None; } let value: i64 = digits.parse().ok()?; Some(( if negative { -value } else { value }, skipped + trimmed.len(), )) } struct NumericParser<'a> { text: &'a str, position: usize, registers: &'a [(String, i64)], } impl<'a> NumericParser<'a> { fn new(text: &'a str, registers: &'a [(String, i64)]) -> Self { Self { text, position: 0, registers, } } fn skip_space(&mut self) { while let Some(character) = self.text[self.position..].chars().next() { if character.is_whitespace() { self.position += character.len_utf8(); } else { break; } } } fn factor(&mut self) -> Option { self.skip_space(); let rest = &self.text[self.position..]; if rest.starts_with('(') { self.position += 1; let value = self.expression()?; self.skip_space(); self.text[self.position..].strip_prefix(')')?; self.position += 1; return Some(value); } if rest.starts_with('-') { self.position += 1; return Some(self.factor()?.saturating_neg()); } if rest.starts_with('\\') { let (command, used) = control_sequence(rest)?; let name = command.trim_start_matches('\\'); let value = self .registers .iter() .rev() .find(|(known, _)| known == name) .map(|(_, value)| *value)?; self.position += used; return Some(value); } let digits = rest .find(|character: char| !character.is_ascii_digit()) .unwrap_or(rest.len()); if digits == 0 { return None; } let value = rest[..digits].parse().ok()?; self.position += digits; Some(value) } fn term(&mut self) -> Option { let mut value = self.factor()?; loop { self.skip_space(); let rest = &self.text[self.position..]; if rest.starts_with('*') { self.position += 1; value = value.saturating_mul(self.factor()?); } else if rest.starts_with('/') { self.position += 1; let divisor = self.factor()?; value = if divisor == 0 { 0 } else { value / divisor }; } else { break; } } Some(value) } fn expression(&mut self) -> Option { let mut value = self.term()?; loop { self.skip_space(); let rest = &self.text[self.position..]; if rest.starts_with('+') { self.position += 1; value = value.saturating_add(self.term()?); } else if rest.starts_with('-') { self.position += 1; value = value.saturating_sub(self.term()?); } else { break; } } Some(value) } } /// Evaluate `\numexpr`-style arithmetic and return the value plus the bytes /// consumed, including a trailing `\relax` when present. fn numeric_expression(text: &str, registers: &[(String, i64)]) -> Option<(i64, usize)> { let mut parser = NumericParser::new(text, registers); let value = parser.expression()?; let end = parser.position; parser.skip_space(); let rest = &text[parser.position..]; let consumed = rest .strip_prefix("\\relax") .map(|_| parser.position + 6) .unwrap_or(end); Some((value, consumed)) } /// Read a TeX dimension at the start of `text`, returning scaled points and /// the bytes consumed. fn scan_tex_dimension(text: &str) -> Option<(i64, usize)> { let trimmed = text.trim_start(); let skipped = text.len() - trimmed.len(); let mut end = 0_usize; let mut seen_digit = false; for (offset, character) in trimmed.char_indices() { if character.is_ascii_digit() || (character == '.' && seen_digit) { seen_digit = true; end = offset + character.len_utf8(); } else { break; } } if !seen_digit { return None; } while let Some(character) = trimmed[end..].chars().next() { if character.is_ascii_alphabetic() { end += character.len_utf8(); } else { break; } } let value = parse_dimension(&trimmed[..end])?; Some((value, skipped + end)) } /// Format scaled points the way TeX prints a dimension, e.g. `5.0pt`. fn format_dimension(value: i64) -> String { let whole = value.div_euclid(65_536); let fraction = value.rem_euclid(65_536); let digits = format!("{:05}", fraction * 100_000 / 65_536); let digits = digits.trim_end_matches('0'); let digits = if digits.is_empty() { "0" } else { digits }; format!("{}.{}pt", whole, digits) } struct DimensionParser<'a> { text: &'a str, position: usize, registers: &'a [(String, i64)], } impl<'a> DimensionParser<'a> { fn new(text: &'a str, registers: &'a [(String, i64)]) -> Self { Self { text, position: 0, registers, } } fn skip_space(&mut self) { while let Some(character) = self.text[self.position..].chars().next() { if character.is_whitespace() { self.position += character.len_utf8(); } else { break; } } } fn factor(&mut self) -> Option { self.skip_space(); let rest = &self.text[self.position..]; if let Some(after) = rest.strip_prefix('(') { self.position += 1; let value = self.expression()?; self.skip_space(); if !self.text[self.position..].starts_with(')') { return None; } self.position += 1; let _ = after; return Some(value); } if let Some(after) = rest.strip_prefix('-') { self.position += 1; let value = self.factor()?; let _ = after; return Some(-value); } if rest.starts_with('\\') { let (command, length) = control_sequence(rest)?; let name = command.trim_start_matches('\\'); let value = self.registers.iter().find(|(known, _)| known == name)?.1; self.position += length; return Some(value); } let (value, used) = scan_tex_dimension(rest)?; self.position += used; Some(value) } fn term(&mut self) -> Option { let mut value = self.factor()?; loop { self.skip_space(); let rest = &self.text[self.position..]; if let Some(after) = rest.strip_prefix('*') { self.position += 1; let (factor, used) = scan_signed_integer(after)?; self.position += used; value = value.saturating_mul(factor); } else if let Some(after) = rest.strip_prefix('/') { self.position += 1; let (factor, used) = scan_signed_integer(after)?; self.position += used; if factor == 0 { return None; } value /= factor; } else { break; } } Some(value) } fn expression(&mut self) -> Option { let mut value = self.term()?; loop { self.skip_space(); let rest = &self.text[self.position..]; if rest.starts_with('+') { self.position += 1; value = value.saturating_add(self.term()?); } else if rest.starts_with('-') { self.position += 1; value = value.saturating_sub(self.term()?); } else { break; } } Some(value) } } fn dimension_expression(text: &str, registers: &[(String, i64)]) -> Option<(i64, usize)> { let trimmed = text.trim_start(); let skipped = text.len() - trimmed.len(); let rest = trimmed.strip_prefix("\\dimexpr")?; let mut parser = DimensionParser::new(rest, registers); let value = parser.expression()?; parser.skip_space(); let mut consumed = parser.position; if rest[consumed..].starts_with("\\relax") { consumed += "\\relax".len(); } Some((value, skipped + "\\dimexpr".len() + consumed)) } /// Resolve `\newdimen` registers in a body: assignments, `\advance` / /// `\multiply` / `\divide` and `\the` printing. fn format_glue(glue: [i64; 3]) -> String { let mut text = format_dimension(glue[0]); if glue[1] != 0 { text.push_str(" plus "); text.push_str(&format_dimension(glue[1].abs())); } if glue[2] != 0 { text.push_str(" minus "); text.push_str(&format_dimension(glue[2].abs())); } text } /// Parse a dimension with optional `plus`/`minus` parts. fn parse_glue(text: &str) -> Option<(i64, i64, i64, usize)> { let trimmed = text.trim_start(); let (width, used) = scan_tex_dimension(trimmed)?; let mut rest = &trimmed[used..]; let mut stretch = 0; let mut shrink = 0; loop { let probe = rest.trim_start(); if let Some(after) = probe.strip_prefix("plus") { let (value, length) = scan_tex_dimension(after.trim_start())?; stretch = value; rest = &after.trim_start()[length..]; } else if let Some(after) = probe.strip_prefix("minus") { let (value, length) = scan_tex_dimension(after.trim_start())?; shrink = value; rest = &after.trim_start()[length..]; } else { break; } } Some((width, stretch, shrink, text.len() - rest.len())) } struct GlueParser<'a> { text: &'a str, position: usize, registers: &'a [(String, [i64; 3])], } impl<'a> GlueParser<'a> { fn skip_space(&mut self) { while let Some(character) = self.text[self.position..].chars().next() { if character.is_whitespace() { self.position += character.len_utf8(); } else { break; } } } fn dimension(&mut self) -> Option { self.skip_space(); let rest = &self.text[self.position..]; if rest.starts_with('\\') { let (command, length) = control_sequence(rest)?; let name = command.trim_start_matches('\\'); if let Some((_, glue)) = self.registers.iter().find(|(known, _)| known == name) { self.position += length; return Some(glue[0]); } } let mut parser = DimensionParser { text: rest, position: 0, registers: &[], }; let value = parser.expression()?; self.position += parser.position; Some(value) } fn factor(&mut self) -> Option<[i64; 3]> { self.skip_space(); if self.text[self.position..].starts_with('(') { self.position += 1; let value = self.expression()?; self.skip_space(); if !self.text[self.position..].starts_with(')') { return None; } self.position += 1; return Some(value); } let rest = &self.text[self.position..]; if rest.starts_with('\\') { if let Some((command, length)) = control_sequence(rest) { let name = command.trim_start_matches('\\'); if let Some((_, glue)) = self.registers.iter().find(|(known, _)| known == name) { self.position += length; return Some(*glue); } } } let mut parser = DimensionParser { text: rest, position: 0, registers: &[], }; let value = parser.expression()?; self.position += parser.position; Some([value, 0, 0]) } fn term(&mut self) -> Option<[i64; 3]> { let mut glue = self.factor()?; loop { self.skip_space(); let rest = &self.text[self.position..]; if let Some(after) = rest.strip_prefix("plus") { if !after .chars() .next() .is_some_and(|character| character.is_ascii_alphabetic()) { self.position += 4; glue[1] = glue[1].saturating_add(self.dimension()?); continue; } } if let Some(after) = rest.strip_prefix("minus") { if !after .chars() .next() .is_some_and(|character| character.is_ascii_alphabetic()) { self.position += 5; glue[2] = glue[2].saturating_sub(self.dimension()?); continue; } } break; } Some(glue) } fn expression(&mut self) -> Option<[i64; 3]> { let mut value = self.term()?; loop { self.skip_space(); let rest = &self.text[self.position..]; if rest.starts_with('+') { self.position += 1; let right = self.term()?; value[0] = value[0].saturating_add(right[0]); value[1] = value[1].saturating_add(right[1]); value[2] = value[2].saturating_add(right[2]); } else if rest.starts_with('-') { self.position += 1; let right = self.term()?; value[0] = value[0].saturating_sub(right[0]); value[1] = value[1].saturating_sub(right[1]); value[2] = value[2].saturating_sub(right[2]); } else { break; } } Some(value) } } fn glue_expression(text: &str, registers: &[(String, [i64; 3])]) -> Option<([i64; 3], usize)> { let trimmed = text.trim_start(); let body = trimmed.strip_prefix("\\glueexpr")?; if body .chars() .next() .is_some_and(|character| character.is_ascii_alphabetic()) { return None; } let mut parser = GlueParser { text: body, position: 0, registers, }; let value = parser.expression()?; parser.skip_space(); if parser.text[parser.position..].starts_with("\\relax") { parser.position += 6; } Some((value, text.len() - body[parser.position..].len())) } fn expand_skip_registers(body: &str, registers: &mut Vec<(String, [i64; 3])>) -> String { let mut result = String::new(); let mut index = 0; while index < body.len() { let rest = &body[index..]; let Some((command, length)) = control_sequence(rest) else { let character = rest.chars().next().expect("body remainder"); result.push(character); index += character.len_utf8(); continue; }; let name = command.trim_start_matches('\\'); if name == "advance" { let after = rest[length..].trim_start(); if let Some((target, target_length)) = control_sequence(after) { let target_name = target.trim_start_matches('\\'); if let Some(position) = registers.iter().position(|(known, _)| known == target_name) { let raw = after[target_length..].trim_start(); let raw = raw.strip_prefix("by").map(str::trim_start).unwrap_or(raw); if let Some((width, stretch, shrink, used)) = parse_glue(raw) { let slot = &mut registers[position].1; slot[0] = slot[0].saturating_add(width); slot[1] = slot[1].saturating_add(stretch); slot[2] = slot[2].saturating_add(shrink); index = body.len() - raw[used..].len(); continue; } } } result.push_str(&command); index += length; continue; } if let Some(position) = registers.iter().position(|(known, _)| known == name) { let after = &rest[length..]; let trimmed = after.trim_start(); if let Some(value) = trimmed.strip_prefix('=') { if value.trim_start().starts_with("\\glueexpr") { if let Some((glue_value, used)) = glue_expression(value, registers) { registers[position].1 = glue_value; index = body.len() - value[used..].len(); continue; } } if let Some((width, stretch, shrink, used)) = parse_glue(value) { registers[position].1 = [width, stretch, shrink]; index = body.len() - value[used..].len(); continue; } } result.push_str(&command); index += length; continue; } if name == "the" { let after = rest[length..].trim_start(); if after.starts_with("\\glueexpr") { if let Some((value, used)) = glue_expression(after, registers) { result.push_str(&format_glue(value)); index = body.len() - after[used..].len(); continue; } } if let Some((target, target_length)) = control_sequence(after) { let target_name = target.trim_start_matches('\\'); if let Some((_, value)) = registers.iter().find(|(known, _)| known == target_name) { result.push_str(&format_glue(*value)); index = body.len() - after[target_length..].len(); continue; } } } if name == "glueexpr" { if let Some((value, used)) = glue_expression(rest, registers) { result.push_str(&format_glue(value)); index = body.len() - rest[used..].len(); continue; } } result.push_str(&command); index += length; } result } fn expand_dimension_registers(body: &str, registers: &mut Vec<(String, i64)>) -> String { let mut result = String::new(); let mut index = 0; while index < body.len() { let rest = &body[index..]; let Some((command, length)) = control_sequence(rest) else { let character = rest.chars().next().expect("body remainder"); result.push(character); index += character.len_utf8(); continue; }; let name = command.trim_start_matches('\\'); if name == "dimexpr" { if let Some((value, used)) = dimension_expression(rest, registers) { result.push_str(&format_dimension(value)); index += used; continue; } } if matches!(name, "advance" | "multiply" | "divide") { let after = rest[length..].trim_start(); if let Some((target, target_length)) = control_sequence(after) { let target_name = target.trim_start_matches('\\'); if let Some(position) = registers.iter().position(|(known, _)| known == target_name) { let raw = after[target_length..].trim_start(); let raw = raw.strip_prefix("by").map(str::trim_start).unwrap_or(raw); let parsed = scan_tex_dimension(raw) .or_else(|| scan_signed_integer(raw).map(|(value, used)| (value, used))); if let Some((value, used)) = parsed { let slot = &mut registers[position].1; let operand = if raw[..used].chars().any(|c| c.is_ascii_alphabetic()) { value } else { value * 65_536 }; match name { "advance" => *slot = slot.saturating_add(operand), "multiply" => *slot = slot.saturating_mul(value), _ => { if value != 0 { *slot /= value; } } } index = body.len() - raw[used..].len(); continue; } } } result.push_str(&command); index += length; continue; } if let Some(position) = registers.iter().position(|(known, _)| known == name) { let after = &rest[length..]; let trimmed = after.trim_start(); if let Some(value) = trimmed.strip_prefix('=') { if let Some((assigned, used)) = scan_tex_dimension(value) { registers[position].1 = assigned; index = body.len() - value[used..].len(); continue; } } result.push_str(&command); index += length; continue; } if name == "the" { let after = rest[length..].trim_start(); if let Some((target, target_length)) = control_sequence(after) { let target_name = target.trim_start_matches('\\'); if target_name == "dimexpr" { if let Some((value, used)) = dimension_expression(after, registers) { result.push_str(&format_dimension(value)); index = body.len() - after[used..].len(); continue; } } if let Some((_, value)) = registers.iter().find(|(known, _)| known == target_name) { result.push_str(&format_dimension(*value)); index = body.len() - after[target_length..].len(); continue; } } } result.push_str(&command); index += length; } result } /// Resolve `\newcount` registers in a body: assignments, `\advance` / /// `\multiply` / `\divide`, and `\the` / `\number` printing. fn numbered_count(text: &str) -> Option<(usize, usize)> { let rest = text.strip_prefix("\\count")?; let digits: String = rest .chars() .take_while(|character| character.is_ascii_digit()) .collect(); if digits.is_empty() || digits.len() > 3 { return None; } let index: usize = digits.parse().ok()?; if index >= 256 { return None; } Some((index, "\\count".len() + digits.len())) } fn numbered_slot(text: &str, command: &str) -> Option<(usize, usize)> { let rest = text.strip_prefix(command)?; let digits: String = rest .chars() .take_while(|character| character.is_ascii_digit()) .collect(); if digits.is_empty() || digits.len() > 3 { return None; } let index: usize = digits.parse().ok()?; if index >= 256 { return None; } Some((index, command.len() + digits.len())) } fn ensure_count_slot(registers: &mut Vec, index: usize) { if registers.len() <= index { registers.resize(index + 1, 0); } } fn ensure_skip_slot(registers: &mut Vec<[i64; 3]>, index: usize) { if registers.len() <= index { registers.resize(index + 1, [0, 0, 0]); } } fn expand_numbered_dimens(body: &str, registers: &mut Vec) -> String { let mut result = String::new(); let mut index = 0; while index < body.len() { let rest = &body[index..]; let Some((command, length)) = control_sequence(rest) else { let character = rest.chars().next().expect("body remainder"); result.push(character); index += character.len_utf8(); continue; }; let name = command.trim_start_matches('\\'); if name == "dimen" { if let Some((slot, used)) = numbered_slot(rest, "\\dimen") { ensure_count_slot(registers, slot); let trimmed = rest[used..].trim_start(); if let Some(value) = trimmed.strip_prefix('=') { if let Some((dimension, consumed)) = scan_tex_dimension(value) { registers[slot] = dimension; index = body.len() - value[consumed..].len(); continue; } } result.push_str(&command); index += length; continue; } } if matches!(name, "advance" | "multiply" | "divide") { let after = rest[length..].trim_start(); if let Some((slot, used)) = numbered_slot(after, "\\dimen") { ensure_count_slot(registers, slot); let raw = after[used..].trim_start(); let raw = raw.strip_prefix("by").map(str::trim_start).unwrap_or(raw); if let Some((value, consumed)) = scan_tex_dimension(raw) { match name { "advance" => registers[slot] = registers[slot].saturating_add(value), "multiply" => registers[slot] = registers[slot].saturating_mul(value), _ => { if value != 0 { registers[slot] /= value; } } } index = body.len() - raw[consumed..].len(); continue; } } } if name == "the" || name == "number" { let after = rest[length..].trim_start(); if let Some((slot, used)) = numbered_slot(after, "\\dimen") { ensure_count_slot(registers, slot); result.push_str(&format_dimension(registers[slot])); index = body.len() - after[used..].len(); continue; } } result.push_str(&command); index += length; } result } fn expand_numbered_skips(body: &str, registers: &mut Vec<[i64; 3]>) -> String { let mut result = String::new(); let mut index = 0; while index < body.len() { let rest = &body[index..]; let Some((command, length)) = control_sequence(rest) else { let character = rest.chars().next().expect("body remainder"); result.push(character); index += character.len_utf8(); continue; }; let name = command.trim_start_matches('\\'); if name == "skip" { if let Some((slot, used)) = numbered_slot(rest, "\\skip") { ensure_skip_slot(registers, slot); let trimmed = rest[used..].trim_start(); if let Some(value) = trimmed.strip_prefix('=') { if let Some((width, stretch, shrink, consumed)) = parse_glue(value) { registers[slot] = [width, stretch, shrink]; index = body.len() - value[consumed..].len(); continue; } } result.push_str(&command); index += length; continue; } } if name == "advance" { let after = rest[length..].trim_start(); if let Some((slot, used)) = numbered_slot(after, "\\skip") { ensure_skip_slot(registers, slot); let raw = after[used..].trim_start(); let raw = raw.strip_prefix("by").map(str::trim_start).unwrap_or(raw); if let Some((width, stretch, shrink, consumed)) = parse_glue(raw) { let slot = &mut registers[slot]; slot[0] = slot[0].saturating_add(width); slot[1] = slot[1].saturating_add(stretch); slot[2] = slot[2].saturating_add(shrink); index = body.len() - raw[consumed..].len(); continue; } } } if name == "the" { let after = rest[length..].trim_start(); if let Some((slot, used)) = numbered_slot(after, "\\skip") { ensure_skip_slot(registers, slot); result.push_str(&format_glue(registers[slot])); index = body.len() - after[used..].len(); continue; } } result.push_str(&command); index += length; } result } fn expand_numbered_counts(body: &str, registers: &mut Vec) -> String { let mut result = String::new(); let mut index = 0; while index < body.len() { let rest = &body[index..]; let Some((command, length)) = control_sequence(rest) else { let character = rest.chars().next().expect("body remainder"); result.push(character); index += character.len_utf8(); continue; }; let name = command.trim_start_matches('\\'); if name == "count" { if let Some((slot, used)) = numbered_count(rest) { ensure_count_slot(registers, slot); let after = &rest[used..]; let trimmed = after.trim_start(); if let Some(value) = trimmed.strip_prefix('=') { if let Some((number, consumed)) = scan_signed_integer(value) { registers[slot] = number; index = body.len() - value[consumed..].len(); continue; } } result.push_str(&command); index += length; continue; } } if matches!(name, "advance" | "multiply" | "divide") { let after = rest[length..].trim_start(); if let Some((slot, used)) = numbered_count(after) { ensure_count_slot(registers, slot); let raw = after[used..].trim_start(); let raw = raw.strip_prefix("by").map(str::trim_start).unwrap_or(raw); if let Some((number, consumed)) = scan_signed_integer(raw) { match name { "advance" => registers[slot] = registers[slot].saturating_add(number), "multiply" => registers[slot] = registers[slot].saturating_mul(number), _ => { if number != 0 { registers[slot] /= number; } } } index = body.len() - raw[consumed..].len(); continue; } } } if name == "the" || name == "number" { let after = rest[length..].trim_start(); if let Some((slot, used)) = numbered_count(after) { ensure_count_slot(registers, slot); result.push_str(®isters[slot].to_string()); index = body.len() - after[used..].len(); continue; } } result.push_str(&command); index += length; } result } fn roman_numeral(value: i64) -> String { if value <= 0 { return "0".to_string(); } const VALUES: [(i64, &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 number = value; let mut out = String::new(); for (amount, glyph) in VALUES { while number >= amount { out.push_str(glyph); number -= amount; } } out } fn expand_count_registers(body: &str, registers: &mut Vec<(String, i64)>) -> String { let mut result = String::new(); let mut index = 0; while index < body.len() { let rest = &body[index..]; let Some((command, length)) = control_sequence(rest) else { let character = rest.chars().next().expect("body remainder"); result.push(character); index += character.len_utf8(); continue; }; let name = command.trim_start_matches('\\'); if name == "numexpr" { if let Some((value, used)) = numeric_expression(&rest[length..], registers) { result.push_str(&value.to_string()); index += length + used; continue; } } if matches!(name, "advance" | "multiply" | "divide") { let after = rest[length..].trim_start(); if let Some((target, target_length)) = control_sequence(after) { let target_name = target.trim_start_matches('\\'); if let Some(position) = registers.iter().position(|(known, _)| known == target_name) { let rest_value = after[target_length..].trim_start(); let rest_value = rest_value .strip_prefix("by") .map(str::trim_start) .unwrap_or(rest_value); if let Some((value, value_length)) = scan_signed_integer(rest_value) { let slot = &mut registers[position].1; match name { "advance" => *slot = slot.saturating_add(value), "multiply" => *slot = slot.saturating_mul(value), _ => { if value != 0 { *slot /= value; } } } index = body.len() - rest_value[value_length..].len(); continue; } } } result.push_str(&command); index += length; continue; } if let Some(position) = registers.iter().position(|(known, _)| known == name) { let after = &rest[length..]; let trimmed = after.trim_start(); if let Some(value) = trimmed.strip_prefix('=') { if let Some((assigned, assigned_length)) = scan_signed_integer(value) { registers[position].1 = assigned; index = body.len() - value[assigned_length..].len(); continue; } } result.push_str(&command); index += length; continue; } if name == "romannumeral" { let after = rest[length..].trim_start(); if let Some((target, target_length)) = control_sequence(after) { let target_name = target.trim_start_matches('\\'); if let Some((_, value)) = registers.iter().find(|(known, _)| known == target_name) { result.push_str(&roman_numeral(*value)); index = body.len() - after[target_length..].len(); continue; } } result.push_str(&command); index += length; continue; } if name == "the" || name == "number" { let raw_after = &rest[length..]; let skipped = raw_after.len() - raw_after.trim_start().len(); let trimmed_after = raw_after.trim_start(); if let Some(numexpr) = trimmed_after.strip_prefix("\\numexpr") { if let Some((value, used)) = numeric_expression(numexpr, registers) { result.push_str(&value.to_string()); index += length + skipped + "\\numexpr".len() + used; continue; } } let after = rest[length..].trim_start(); if let Some((target, target_length)) = control_sequence(after) { let target_name = target.trim_start_matches('\\'); if let Some((_, value)) = registers.iter().find(|(known, _)| known == target_name) { result.push_str(&value.to_string()); index = body.len() - after[target_length..].len(); continue; } } result.push_str(&command); index += length; continue; } result.push_str(&command); index += length; } result } /// Later definitions replace earlier ones with the same name, matching TeX's /// redefinition semantics for `\def`, `\newcommand` and friends. fn dedupe_macros(macros: &mut Vec) { let mut result: Vec = Vec::new(); for definition in macros.drain(..) { if let Some(position) = result .iter() .position(|known| known.name == definition.name) { result[position] = definition; } else { result.push(definition); } } *macros = result; } /// Replace `\usebox{name}` with stored content and store `\sbox`/`\savebox` bodies. /// Replace `\wd`/`\ht`/`\dp\boxname` with the frozen savebox metrics. fn expand_box_dimensions(body: &str, dimensions: &[(String, (i64, i64, i64))]) -> String { let mut out = body.to_string(); let mut ordered = dimensions.to_vec(); ordered.sort_by_key(|(name, _)| std::cmp::Reverse(name.len())); for (name, (width, height, depth)) in ordered { for (command, value) in [("\\wd", width), ("\\ht", height), ("\\dp", depth)] { let needle = format!("{command}{name}"); if out.contains(&needle) { out = out.replace(&needle, &format!("{:.4}pt", value as f64 / 65536.0)); } } } out } fn expand_saveboxes( body: &str, macros: &mut Vec, dimensions: &mut Vec<(String, (i64, i64, i64))>, base_size: i64, images: &HashMap, ) -> String { let mut out = String::new(); let mut index = 0; while index < body.len() { let rest = &body[index..]; if let Some(after) = rest.strip_prefix("\\usebox") { let after = after.trim_start(); if let Some((name, used)) = braced_group(after) { let name = format!("\\{}", name.trim().trim_start_matches('\\')); if let Some(definition) = macros.iter().find(|m| m.name == name) { out.push('\u{E010}'); out.push_str(&base_size.to_string()); out.push(';'); out.push_str(&definition.body); out.push('\u{E011}'); } index += rest.len() - after.len() + used; continue; } } if rest.starts_with("\\sbox") || rest.starts_with("\\savebox") { let after = rest .strip_prefix("\\sbox") .or_else(|| rest.strip_prefix("\\savebox")) .unwrap_or(""); let after = after.trim_start(); if let Some((name, used)) = braced_group(after) { let body_rest = after[used..].trim_start(); if let Some((content, used_body)) = braced_group(body_rest) { let name = format!("\\{}", name.trim().trim_start_matches('\\')); if let Some(existing) = macros.iter_mut().find(|m| m.name == name) { existing.body = content.to_string(); existing.params = None; } else { macros.push(MacroDefinition { name: name.clone(), args: 0, default: None, params: None, body: content.to_string(), }); } set_savebox_dimensions( dimensions, &name, measure_savebox(content, base_size, images), ); index += rest.len() - body_rest.len() + used_body; continue; } } } let character = rest.chars().next().expect("character"); out.push(character); index += character.len_utf8(); } out } /// Register the content of a `\sbox`/`\savebox` or reserve a `\newsavebox` name. fn handle_savebox_line( line: &str, macros: &mut Vec, dimensions: &mut Vec<(String, (i64, i64, i64))>, base_size: i64, images: &HashMap, ) { let rest = line.trim_start(); if let Some(after) = rest.strip_prefix("\\newsavebox") { let after = after.trim_start(); if let Some((name, _)) = braced_group(after) { let name = format!("\\{}", name.trim().trim_start_matches('\\')); if !macros.iter().any(|m| m.name == name) { macros.push(MacroDefinition { name, args: 0, default: None, params: None, body: String::new(), }); } } return; } let after = rest .strip_prefix("\\sbox") .or_else(|| rest.strip_prefix("\\savebox")); let Some(after) = after else { return }; let after = after.trim_start(); let Some((name, used)) = braced_group(after) else { return; }; let body_rest = after[used..].trim_start(); let Some((body, _)) = braced_group(body_rest) else { return; }; let name = format!("\\{}", name.trim().trim_start_matches('\\')); if let Some(existing) = macros.iter_mut().find(|m| m.name == name) { existing.body = body.to_string(); existing.params = None; } else { macros.push(MacroDefinition { name: name.clone(), args: 0, default: None, params: None, body: body.to_string(), }); } set_savebox_dimensions(dimensions, &name, measure_savebox(body, base_size, images)); } fn set_savebox_dimensions( dimensions: &mut Vec<(String, (i64, i64, i64))>, name: &str, metrics: (i64, i64, i64), ) { if let Some(existing) = dimensions.iter_mut().find(|(known, _)| known == name) { existing.1 = metrics; } else { dimensions.push((name.to_string(), metrics)); } } /// Measure a savebox body with the Roman metrics at `base_size`. /// Measure an `\includegraphics` body from decoded image pixels (72 dpi), /// honouring explicit width/height options. fn graphic_measure(content: &str, images: &HashMap) -> Option<(i64, i64)> { const SP_PER_PIXEL: i64 = 65_782; let index = content.find("\\includegraphics")?; let after = &content[index + "\\includegraphics".len()..]; let trimmed = after.trim_start(); let mut rest = trimmed; let options = if let Some(stripped) = rest.strip_prefix('[') { let (inside, tail) = stripped.split_once(']')?; rest = tail.trim_start(); Some(inside) } else { None }; let (path, _) = braced_group(rest)?; let path = path.trim().trim_matches('"'); let image = images.get(path)?; let natural_width = image.width as i64 * SP_PER_PIXEL; let natural_height = image.height as i64 * SP_PER_PIXEL; let mut width = None; let mut height = None; if let Some(options) = options { for option in options.split(',') { let option = option.trim(); if let Some(value) = option.strip_prefix("width") { if let Some((_, dimension)) = value.split_once('=') { width = parse_dimension(dimension.trim()); } } else if let Some(value) = option.strip_prefix("height") && let Some((_, dimension)) = value.split_once('=') { height = parse_dimension(dimension.trim()); } } } let (width, height) = match (width, height) { (Some(width), Some(height)) => (width, height), (Some(width), None) => ( width, width.saturating_mul(natural_height) / natural_width.max(1), ), (None, Some(height)) => ( height.saturating_mul(natural_width) / natural_height.max(1), height, ), (None, None) => (natural_width, natural_height), }; Some((width, height)) } fn measure_savebox( content: &str, base_size: i64, images: &HashMap, ) -> (i64, i64, i64) { if let Some((width, height)) = graphic_measure(content, images) { return (width, height, 0); } let cleaned = scrub_title_metadata(&strip_box_commands(content)); let metrics = Cmr10Metrics::Roman; let scale = |value: i64| value.saturating_mul(base_size) / 655_360; ( scale(text_width_roman(&cleaned)), scale(metrics.height('M').max(1)), scale(metrics.depth('g').max(0)), ) } /// Capture `\def` lines written in the document body, before macro expansion. /// Reserve `\newcount`/`\newdimen`/`\newskip` registers declared in the body. /// Move the token queued by `\afterassignment` behind the assignment it /// follows, so the normal assignment passes run first. fn apply_afterassignment(body: &str) -> String { let mut text = body.to_string(); loop { let Some(position) = text.find("\\afterassignment") else { break; }; let after = &text[position + "\\afterassignment".len()..]; let Some((token, token_used)) = next_token(after) else { break; }; let rest = &after[token_used..]; let Some(end) = assignment_end(rest) else { break; }; text = format!( "{}{}{}{}", &text[..position], &rest[..end], token, &rest[end..] ); } text } fn assignment_end(text: &str) -> Option { if let Some((_, used, _)) = runtime_definition(text) { return Some(used); } let mut depth = 0_i32; for (index, character) in text.char_indices() { match character { '{' => depth += 1, '}' => depth -= 1, '=' if depth == 0 => { let after = &text[index + 1..]; let (_, used) = next_token(after)?; return Some(index + 1 + used); } _ => {} } } None } fn capture_body_registers( body: &mut String, counts: &mut Vec<(String, i64)>, dimens: &mut Vec<(String, i64)>, skips: &mut Vec<(String, [i64; 3])>, ) { let mut kept = String::new(); let mut changed = false; for line in body.lines() { let trimmed = line.trim_start(); let mut handled = false; if let Some(rest) = trimmed.strip_prefix("\\newcount") { if let Some((command, _)) = control_sequence(rest.trim_start()) { let name = command.trim_start_matches('\\').to_string(); if !counts.iter().any(|(known, _)| known == &name) { counts.push((name, 0)); } handled = true; } } else if let Some(rest) = trimmed.strip_prefix("\\newdimen") { if let Some((command, _)) = control_sequence(rest.trim_start()) { let name = command.trim_start_matches('\\').to_string(); if !dimens.iter().any(|(known, _)| known == &name) { dimens.push((name, 0)); } handled = true; } } else if let Some(rest) = trimmed.strip_prefix("\\newskip") { if let Some((command, _)) = control_sequence(rest.trim_start()) { let name = command.trim_start_matches('\\').to_string(); if !skips.iter().any(|(known, _)| known == &name) { skips.push((name, [0, 0, 0])); } handled = true; } } if handled { changed = true; continue; } kept.push_str(line); kept.push('\n'); } if changed { *body = kept.trim_end_matches('\n').to_string(); } } /// Whether a definition command consumes its whole line (ignoring trailing /// whitespace). Embedded definitions are left for the inline pass. fn definition_consumes_line(line: &str) -> bool { let line = line.trim(); let Some((command, used)) = control_sequence(line) else { return false; }; let rest = &line[used..]; match command.as_str() { "\\def" | "\\gdef" | "\\edef" | "\\xdef" => { let trimmed = rest.trim_start(); let Some((_name, name_used)) = control_sequence(trimmed) else { return false; }; let after_name = &trimmed[name_used..]; let Some(brace) = after_name.find('{') else { return false; }; let Some((_body, body_used)) = braced_group(&after_name[brace..]) else { return false; }; after_name[brace + body_used..].trim().is_empty() } "\\newcommand" | "\\renewcommand" | "\\DeclareRobustCommand" | "\\providecommand" => { let mut rest = rest.trim_start(); if let Some(stripped) = rest.strip_prefix('*') { rest = stripped.trim_start(); } let after_name = if let Some(stripped) = rest.strip_prefix('{') { let Some(close) = stripped.find('}') else { return false; }; &stripped[close + 1..] } else { let Some((_name, name_used)) = control_sequence(rest) else { return false; }; &rest[name_used..] }; let mut rest = after_name.trim_start(); for _ in 0..2 { if let Some(stripped) = rest.strip_prefix('[') { let Some((_option, tail)) = stripped.split_once(']') else { return false; }; rest = tail.trim_start(); } } let Some((_body, body_used)) = braced_group(rest) else { return false; }; rest[body_used..].trim().is_empty() } _ => false, } } fn capture_body_definitions( body: &mut String, macros: &mut Vec, conditionals: &mut Vec, theorems: &mut Vec, environments: &mut Vec, ) { let mut kept = String::new(); let mut changed = false; let mut depth = 0_i32; let mut depths = Vec::new(); for line in body.lines() { depths.push(depth); depth += brace_depth_delta(line); } for (line, depth) in body.lines().zip(depths) { let trimmed = line.trim_start(); let definition_line = strip_definition_prefixes(trimmed); if trimmed.starts_with("\\newenvironment") || trimmed.starts_with("\\renewenvironment") { if let Some(definition) = environment_definition(definition_line) { environments.push(definition); } changed = true; continue; } if let Some(definition) = newtheorem_definition(definition_line) { theorems.push(definition); changed = true; continue; } if trimmed.starts_with("\\newsavebox") { // Only the name is reserved here; the body's \sbox is measured by // expand_saveboxes once the geometry is available. let mut ignored_dimensions = Vec::new(); handle_savebox_line( trimmed, macros, &mut ignored_dimensions, 655_360, &HashMap::new(), ); changed = true; continue; } if let Some(name) = newif_definition(definition_line) { conditionals.push(ConditionalDefinition { name, value: false }); changed = true; continue; } if depth == 0 && let Some(definition) = edef_definition(definition_line, macros) { macros.push(definition); changed = true; continue; } if depth == 0 && let Some(definition) = macro_definition(definition_line) && definition_consumes_line(definition_line) { macros.push(definition); changed = true; continue; } if depth == 0 && let Some(definition) = char_definition(definition_line) { macros.push(definition); changed = true; continue; } if depth == 0 && let Some((name, target)) = macro_alias(definition_line) { let source = macros .iter() .find(|definition| definition.name == target) .cloned(); let definition = source.unwrap_or(MacroDefinition { name: name.clone(), args: 0, default: None, body: String::new(), params: None, }); macros.push(MacroDefinition { name, args: definition.args, default: definition.default, body: definition.body, params: definition.params, }); changed = true; continue; } kept.push_str(line); kept.push('\n'); } if changed { *body = kept.trim_end_matches('\n').to_string(); } } /// Join multi-line `\newcommand`/`\def`/`\newenvironment` definitions into /// one line so the line-oriented preamble parser can capture the whole body. fn collapse_definition_bodies(source: &str) -> String { const COMMANDS: [&str; 9] = [ "\\newcommand", "\\renewcommand", "\\providecommand", "\\def", "\\gdef", "\\edef", "\\xdef", "\\newenvironment", "\\renewenvironment", ]; let starts_definition = |line: &str| { COMMANDS.iter().any(|command| { line.strip_prefix(command) .is_some_and(|rest| !rest.starts_with(|c: char| c.is_ascii_alphabetic())) }) }; let mut out = String::new(); let mut pending: Option = None; let mut depth = 0_i64; for line in source.lines() { if let Some(buffer) = pending.as_mut() { let continues = line.trim_end().ends_with('%'); let code = strip_tex_comment(line); if code.trim().is_empty() { buffer.push_str(" \\par "); } else if continues { buffer.push_str(code.trim()); } else { buffer.push(' '); buffer.push_str(code.trim()); } depth += brace_delta(&code); if depth <= 0 { out.push_str(buffer); out.push('\n'); pending = None; depth = 0; } continue; } let code = strip_tex_comment(line); let trimmed = code.trim_start(); if starts_definition(trimmed) { let delta = brace_delta(&code); if delta > 0 { pending = Some(code.trim_end().to_string()); depth = delta; continue; } } out.push_str(line); out.push('\n'); } if let Some(buffer) = pending { out.push_str(&buffer); out.push('\n'); } out } /// Drop an unescaped `%` comment from the end of a source line. fn strip_tex_comment(line: &str) -> String { let mut out = String::with_capacity(line.len()); let mut escaped = false; for character in line.chars() { if escaped { escaped = false; out.push(character); continue; } if character == '\\' { escaped = true; out.push(character); continue; } if character == '%' { break; } out.push(character); } out } fn brace_delta(text: &str) -> i64 { let mut depth = 0_i64; let mut escaped = false; for character in text.chars() { if escaped { escaped = false; continue; } match character { '\\' => escaped = true, '{' => depth += 1, '}' => depth -= 1, _ => {} } } depth } /// Move `\AtBeginDocument{...}` bodies in front of `\begin{document}`. const INTERNAL_AT_COMMANDS: &[&str] = &[ "empty", "firstofone", "firstoftwo", "secondoftwo", "gobble", "gobbletwo", "ifmtarg", "ifnextchar", "ifstar", "ifundefined", "ifpackageloaded", "ifclassloaded", "ifdefinable", "namedef", "nameuse", "nopreamble", "onlypreamble", "setfontsize", "listi", "listiv", "title", "minus", "plus", ]; const INTERNAL_AT_INFIX: &[&str] = &[ "protected@edef", "protected@xdef", "protected@write", "sixt@@n", "e@ight", "thr@@", "m@ne", "tw@", "p@", "z@", ]; fn is_internal_at_command(name: &str) -> bool { if INTERNAL_AT_INFIX.contains(&name) { return true; } name.strip_prefix('@') .is_some_and(|rest| INTERNAL_AT_COMMANDS.contains(&rest)) } /// Rewrite `\valign{...}` into a transposed `tabular`: each `\cr`-separated /// input line is one column, and the output rows take one entry from each line. fn expand_valign(source: &str) -> String { let mut out = String::new(); let mut rest = source; while let Some(position) = rest.find("\\valign") { out.push_str(&rest[..position]); let after = &rest[position + "\\valign".len()..]; let trimmed = after.trim_start(); let Some((content, used)) = braced_group(trimmed) else { out.push_str(&rest[position..]); return out; }; out.push_str(&render_valign(content)); rest = &trimmed[used..]; } out.push_str(rest); out } fn render_valign(content: &str) -> String { let body = match content.split_once("\\cr") { Some((_preamble, body)) => body, None => content, }; let columns: Vec> = body .split("\\cr") .map(|line| { line.split('&') .map(|cell| cell.trim().to_string()) .collect::>() }) .filter(|cells| cells.iter().any(|cell| !cell.is_empty())) .collect(); if columns.is_empty() { return String::new(); } let height = columns.iter().map(Vec::len).max().unwrap_or(0); let mut out = format!("\\begin{{tabular}}{{{}}}\n", "l".repeat(columns.len())); for row in 0..height { let cells: Vec<&str> = columns .iter() .map(|column| column.get(row).map(String::as_str).unwrap_or("")) .collect(); out.push_str(&cells.join(" & ")); out.push_str(" \\\\\n"); } out.push_str("\\end{tabular}"); out } /// Parse the `\catcode` target and value that follow the command, supporting /// the backtick form (`\catcode`\@=11`), a bare character, or a code point. fn catcode_assignment(characters: &[char], start: usize) -> Option<(char, i64, usize)> { let mut index = start; let skip_space = |index: &mut usize| { while *index < characters.len() && characters[*index].is_whitespace() { *index += 1; } }; skip_space(&mut index); if index < characters.len() && characters[index] == '`' { index += 1; } if index >= characters.len() { return None; } let target = if characters[index] == '\\' { let character = *characters.get(index + 1)?; index += 2; character } else if characters[index].is_ascii_digit() { let mut value = 0_i64; while index < characters.len() && characters[index].is_ascii_digit() { value = value * 10 + characters[index].to_digit(10)? as i64; index += 1; } char::from_u32(u32::try_from(value).ok()?)? } else { let character = characters[index]; index += 1; character }; skip_space(&mut index); if index >= characters.len() || characters[index] != '=' { return None; } index += 1; skip_space(&mut index); if index >= characters.len() { return None; } if characters[index].is_ascii_digit() { let mut value = 0_i64; while index < characters.len() && characters[index].is_ascii_digit() { value = value * 10 + characters[index].to_digit(10)? as i64; index += 1; } return Some((target, value, index)); } // `\active` and friends are not modelled; consume the word and treat the // target as active (13). let mut word = String::new(); while index < characters.len() && characters[index].is_ascii_alphabetic() { word.push(characters[index]); index += 1; } if word == "active" { Some((target, 13, index)) } else { None } } /// Model the catcode the engine understands: `@` is a letter only between /// `\makeatletter` and `\makeatother`, and grouping restores the state. User /// command names containing `@` are rewritten with a private-use placeholder /// so later scanners still see one control word; route-D's own `\@...` names /// stay literal for their handlers. fn canonicalize_at_catcodes(source: &str) -> String { let characters: Vec = source.chars().collect(); let mut out = String::with_capacity(source.len()); let mut index = 0; let mut at_letter = false; let mut percent_comments = true; let mut saved = Vec::new(); while index < characters.len() { let character = characters[index]; if character == '{' { saved.push(at_letter); out.push(character); index += 1; continue; } if character == '}' { at_letter = saved.pop().unwrap_or(false); out.push(character); index += 1; continue; } if character == '%' && percent_comments { while index < characters.len() && characters[index] != '\n' { index += 1; } continue; } if character != '\\' { out.push(character); index += 1; continue; } let start = index + 1; let mut end = start; while end < characters.len() && (characters[end].is_ascii_alphabetic() || (at_letter && characters[end] == '@')) { end += 1; } if !at_letter { let mut matched = false; for name in INTERNAL_AT_INFIX { let candidate: Vec = name.chars().collect(); if characters[start..].starts_with(&candidate) { let next = start + candidate.len(); let boundary = next >= characters.len() || (!characters[next].is_ascii_alphabetic() && characters[next] != '@'); if boundary { out.push('\\'); for character in &candidate { out.push(*character); } index = next; matched = true; break; } } } if matched { continue; } } if end == start { if !at_letter && start < characters.len() && characters[start] == '@' { let mut matched = false; for name in INTERNAL_AT_COMMANDS { let candidate: Vec = std::iter::once('@').chain(name.chars()).collect(); if characters[start..].starts_with(&candidate) { let next = start + candidate.len(); let boundary = next >= characters.len() || (!characters[next].is_ascii_alphabetic() && characters[next] != '@'); if boundary { out.push('\\'); out.extend(candidate.iter()); index = next; matched = true; break; } } } if matched { continue; } out.push('\\'); out.push('@'); out.push('\u{E022}'); index = start + 1; continue; } out.push('\\'); if start < characters.len() { out.push(characters[start]); index = start + 1; } else { index = start; } continue; } let name: String = characters[start..end].iter().collect(); match name.as_str() { "makeatletter" => { at_letter = true; index = end; continue; } "makeatother" => { at_letter = false; index = end; continue; } "catcode" => { if let Some((target, value, next)) = catcode_assignment(&characters, end) { // Only the @ catcode changes scanning; the other // assignments are consumed so they do not leak as text. if target == '@' { at_letter = value == 11; } else if target == '%' { percent_comments = value != 12 && value != 13; } index = next; continue; } } _ => {} } out.push('\\'); if is_internal_at_command(&name) { out.push_str(&name); } else { for character in name.chars() { out.push(if character == '@' { '\u{E021}' } else { character }); } if end < characters.len() && characters[end] == '@' && !at_letter { out.push('\u{E022}'); } } index = end; } out } fn lift_at_begin_document(source: &str) -> String { let mut hooks = String::new(); let mut out = String::new(); let mut rest = source; while let Some(index) = rest.find("\\AtBeginDocument") { out.push_str(&rest[..index]); let after = &rest[index + "\\AtBeginDocument".len()..]; let trimmed = after.trim_start(); let leading = after.len() - trimmed.len(); let Some((content, used)) = braced_group(trimmed) else { out.push_str(&rest[index..]); rest = ""; break; }; if !content.trim().is_empty() { hooks.push_str(content.trim()); hooks.push('\n'); } rest = &after[leading + used..]; } out.push_str(rest); if hooks.trim().is_empty() { return out; } if let Some(position) = out.find("\\begin{document}") { let mut lifted = String::with_capacity(out.len() + hooks.len()); lifted.push_str(&out[..position]); lifted.push_str(&hooks); lifted.push_str(&out[position..]); lifted } else { hooks + &out } } /// Join a multi-line braced argument such as `\newgeometry{ ... }` into one /// line so the line-oriented preamble parser can read it. fn collapse_braced_command(source: &str, command: &str) -> String { let mut out = String::new(); let mut rest = source; while let Some(index) = rest.find(command) { out.push_str(&rest[..index + command.len()]); let after = &rest[index + command.len()..]; let trimmed = after.trim_start(); let leading = after.len() - trimmed.len(); if let Some((content, used)) = braced_group(trimmed) { out.push('{'); out.push_str(&content.replace('\n', " ")); out.push('}'); rest = &after[leading + used..]; } else { rest = after; break; } } out.push_str(rest); out } fn geometry_and_body(source: &str) -> (String, PageGeometry) { geometry_and_body_with_images(source, &HashMap::new()) } fn geometry_and_body_with_images( source: &str, images: &HashMap, ) -> (String, PageGeometry) { // Class files put page setup inside `\AtBeginDocument{...}`; run that // body before `\begin{document}` so its commands are consumed as setup // instead of being typeset as text at the top of page one. let source = lift_at_begin_document(source); let source = expand_valign(&source); let source = canonicalize_at_catcodes(&source); let source = collapse_definition_bodies(&source); let source = collapse_braced_command(&source, "\\newgeometry"); // Class files write the title metadata across lines, especially author // blocks with forced line breaks and thanks notes. let source = collapse_braced_command(&source, "\\title"); let source = collapse_braced_command(&source, "\\author"); let source = collapse_braced_command(&source, "\\date"); let (stripped, mut geometry) = strip_page_geometry(&source, images); dedupe_macros(&mut geometry.macros); // 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 = apply_afterassignment(&body); capture_body_registers( &mut body, &mut geometry.count_registers, &mut geometry.dimension_registers, &mut geometry.skip_registers, ); capture_body_definitions( &mut body, &mut geometry.macros, &mut geometry.conditionals, &mut geometry.theorem_definitions, &mut geometry.environments, ); body = body .replace("\\makeatletter", "") .replace("\\makeatother", ""); body = expand_environments(&body, &geometry.environments); body = expand_keywords(&body); body = drop_bibliography_commands(&body); let savebox_base = geometry.base_font_size.unwrap_or(655_360); body = expand_saveboxes( &body, &mut geometry.macros, &mut geometry.savebox_dimensions, savebox_base, &geometry.images, ); body = expand_box_dimensions(&body, &geometry.savebox_dimensions); dedupe_macros(&mut geometry.macros); let mut macros = geometry.macros.clone(); body = expand_macros_mut(&body, &mut macros, &mut geometry.token_registers); body = expand_conditionals( &body, &mut geometry.conditionals, ¯os, &geometry.count_registers, &geometry.counters, ); let mut numbered_dimens = geometry.numbered_dimens; body = expand_numbered_dimens(&body, &mut numbered_dimens); geometry.numbered_dimens = numbered_dimens; let mut numbered_skips = geometry.numbered_skips; body = expand_numbered_skips(&body, &mut numbered_skips); geometry.numbered_skips = numbered_skips; let mut numbered_counts = geometry.numbered_counts; body = expand_numbered_counts(&body, &mut numbered_counts); geometry.numbered_counts = numbered_counts; let mut count_registers = geometry.count_registers.clone(); body = expand_count_registers(&body, &mut count_registers); geometry.count_registers = count_registers; let mut dimension_registers = geometry.dimension_registers.clone(); body = expand_dimension_registers(&body, &mut dimension_registers); geometry.dimension_registers = dimension_registers; let mut skip_registers = geometry.skip_registers.clone(); body = expand_skip_registers(&body, &mut skip_registers); geometry.skip_registers = skip_registers; body = expand_links(&body); let today = today_string(); body = expand_today(&body, &today); body = expand_lipsum(&body); // Class \maketitle definitions (arXiv, sn-jnl) issue \thispagestyle{empty}. if geometry.fancy_pagestyle && geometry.title.is_some() { geometry.suppress_first_page_header = true; geometry.suppress_first_page_number = true; } (body, geometry) } /// Remove a `thebibliography` environment from the body and return its /// `\bibitem{key}` entries in order. /// Start a new block when a display environment follows text on the same /// chunk, e.g. "The documentation is at\n\begin{center}...". fn split_block_environments(chunk: &str) -> Vec<&str> { const OPENINGS: [&str; 3] = [ "\\begin{center}", "\\begin{flushleft}", "\\begin{flushright}", ]; let mut pieces = Vec::new(); let mut rest = chunk; loop { let next = OPENINGS .iter() .filter_map(|opening| rest.find(opening).map(|position| (position, *opening))) .min_by_key(|(position, _)| *position); match next { Some((position, _)) if position > 0 && !rest[..position].trim().is_empty() => { pieces.push(&rest[..position]); rest = &rest[position..]; } _ => break, } } pieces.push(rest); pieces } /// Remove `%` comments; TeX never typesets them. fn strip_tex_comments(source: &str) -> String { source .lines() .map(strip_tex_comment) .collect::>() .join("\n") } /// `\bibliography{...}` and `\bibliographystyle{...}` need an external .bib /// run that route-D does not implement; dropping them keeps the command from /// reaching layout. An inline `thebibliography` still supplies References. fn drop_bibliography_commands(body: &str) -> String { let mut out = String::new(); let mut rest = body; loop { let next = ["\\bibliographystyle", "\\bibliography"] .iter() .filter_map(|command| rest.find(command).map(|position| (position, *command))) .min_by_key(|(position, _)| *position); let Some((position, command)) = next else { out.push_str(rest); break; }; out.push_str(&rest[..position]); let after = &rest[position + command.len()..]; let trimmed = after.trim_start(); if let Some((_name, used)) = braced_group(trimmed) { rest = &trimmed[used..]; } else { rest = after; } } out } /// Turn `\keywords{...}` into a plain "Keywords: ..." paragraph. Class files /// implement it with \addvspace and \rightskip machinery that route-D does not /// model yet. fn expand_keywords(body: &str) -> String { let mut out = String::with_capacity(body.len()); let mut rest = body; while let Some(index) = rest.find("\\keywords") { out.push_str(&rest[..index]); let after = &rest[index + "\\keywords".len()..]; let trimmed = after.trim_start(); let Some((inner, used)) = braced_group(trimmed) else { out.push_str("\\keywords"); rest = after; continue; }; let words = inner .replace("\\AND", ", ") .replace("\\and", ", ") .split_whitespace() .collect::>() .join(" "); out.push_str("Keywords: "); out.push_str(&words); rest = &trimmed[used..]; } out.push_str(rest); out } /// The first paragraphs of the standard Lorem ipsum filler text, used by /// `\lipsum[n]` in templates. The Latin text is public domain. const LIPSUM_PARAGRAPHS: [&str; 10] = [ "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.", "At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga.", "Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus.", "Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.", "Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae.", "Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur. At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores.", "Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur. Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur.", "Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt.", "Sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.", ]; /// Expand the `lipsum` package's filler command (`\lipsum[n]`, `\lipsum[a-b]`, /// and bare `\lipsum`). fn expand_lipsum(body: &str) -> String { let mut out = String::with_capacity(body.len()); let mut rest = body; while let Some(index) = rest.find("\\lipsum") { out.push_str(&rest[..index]); let after = &rest[index + "\\lipsum".len()..]; let trimmed = after.trim_start(); if let Some(inner) = trimmed.strip_prefix('[') { if let Some((spec, tail)) = inner.split_once(']') { out.push_str(&lipsum_paragraphs(spec)); rest = tail; continue; } } out.push_str(&lipsum_paragraphs("1-10")); rest = trimmed; } out.push_str(rest); out } fn lipsum_paragraphs(spec: &str) -> String { let spec = spec.trim(); let (start, end) = if let Some((start, end)) = spec.split_once('-') { let start = start.trim().parse::().unwrap_or(1); let end = end.trim().parse::().unwrap_or(start); (start, end) } else { let value = spec.parse::().unwrap_or(1); (value, value) }; let start = start.clamp(1, LIPSUM_PARAGRAPHS.len()); let end = end.clamp(start, LIPSUM_PARAGRAPHS.len()); LIPSUM_PARAGRAPHS[start - 1..end].join("\n\n") } fn extract_bibliography(body: &mut String) -> Vec<(String, String)> { let begin = r"\begin{thebibliography}"; let end = r"\end{thebibliography}"; let Some(start) = body.find(begin) else { return Vec::new(); }; let after_begin = start + begin.len(); let Some(offset) = body[after_begin..].find(end) else { return Vec::new(); }; let inner_start = body[after_begin..] .find('}') .map_or(after_begin, |close| after_begin + close + 1); let inner = body[inner_start..after_begin + offset].to_string(); body.replace_range(start..after_begin + offset + end.len(), ""); let mut entries = Vec::new(); let mut rest = inner.as_str(); while let Some(index) = rest.find(r"\bibitem") { let after = rest[index + r"\bibitem".len()..].trim_start(); let after = match after.strip_prefix('[') { Some(label) => match label.split_once(']') { Some((_, tail)) => tail.trim_start(), None => after, }, None => after, }; let Some((key, consumed)) = braced_group(after) else { break; }; let tail = &after[consumed..]; let next = tail.find(r"\bibitem").unwrap_or(tail.len()); entries.push((key.trim().to_string(), tail[..next].trim().to_string())); rest = &tail[next..]; } entries } /// Replace `\cite{...}` with `[n]`/`[n, m]` from the bibliography order. /// Remove `\nocite{...}` commands; citations are resolved from the written /// `thebibliography` block and there is no BibTeX pass to extend it. fn strip_nocite(text: &str) -> String { let mut out = String::with_capacity(text.len()); let mut rest = text; while let Some(index) = rest.find(r"\nocite") { out.push_str(&rest[..index]); let after = rest[index + r"\nocite".len()..].trim_start(); let Some((_, consumed)) = braced_group(after) else { out.push_str(&rest[index..]); return out; }; rest = &after[consumed..]; } out.push_str(rest); out } fn resolve_citations(paragraphs: &mut [SourceParagraph], bibliography: &[(String, String)]) { let keys: Vec<&str> = bibliography.iter().map(|(key, _)| key.as_str()).collect(); for paragraph in paragraphs { paragraph.text = strip_nocite(¶graph.text); let mut text = String::with_capacity(paragraph.text.len()); let mut rest = paragraph.text.as_str(); while let Some(index) = rest.find(r"\cite") { text.push_str(&rest[..index]); let command = if rest[index..].starts_with(r"\citep") || rest[index..].starts_with(r"\citet") { &rest[index..index + 6] } else { &rest[index..index + 5] }; let mut after = rest[index + command.len()..].trim_start(); // `\cite[p.~3]{key}` drops the optional note but keeps the number. while let Some(note) = after.strip_prefix('[') { let Some(end) = note.find(']') else { break; }; after = note[end + 1..].trim_start(); } let Some((body, consumed)) = braced_group(after) else { text.push_str(&rest[index..]); rest = ""; break; }; let numbers: Vec = 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; } } #[derive(Clone, Copy)] enum FancySlot { Header, Footer, } /// Parse `\fancyhead[L]{...}` / `\fancyfoot[CR]{...}` into the position list /// and field text. Without a bracket the field is centred. fn fancy_field(line: &str, command: &str) -> Option<(Vec, String)> { let rest = line.strip_prefix(command)?.trim_start(); let (positions, rest) = if let Some(rest) = rest.strip_prefix('[') { let (inside, tail) = rest.split_once(']')?; ( inside .chars() .filter(|character| matches!(character, 'L' | 'C' | 'R')) .collect::>(), tail.trim_start(), ) } else { (vec!['C'], rest) }; let (text, _) = braced_group(rest)?; Some((positions, text.to_string())) } /// Match a bracketless `\fancyhf{...}` (clear-all form). fn fancy_all(line: &str, command: &str) -> Option { let rest = line.strip_prefix(command)?.trim_start(); if rest.starts_with('[') { return None; } let (text, _) = braced_group(rest)?; Some(text.to_string()) } fn set_fancy_fields(geometry: &mut PageGeometry, positions: &[char], text: &str, slot: FancySlot) { for position in positions { match (slot, position) { (FancySlot::Header, 'L') => geometry.header_left = Some(text.to_string()), (FancySlot::Header, 'C') => geometry.header_center = Some(text.to_string()), (FancySlot::Header, 'R') => geometry.header_right = Some(text.to_string()), (FancySlot::Footer, 'L') => geometry.footer_left = Some(text.to_string()), (FancySlot::Footer, 'C') => geometry.footer_center = Some(text.to_string()), (FancySlot::Footer, 'R') => geometry.footer_right = Some(text.to_string()), _ => {} } } } fn renewcommand_length(line: &str, name: &str) -> Option { let rest = line.strip_prefix("\\renewcommand")?.trim_start(); let (target, used) = braced_group(rest)?; if target.trim() != format!("\\{name}") { return None; } let after = &rest[used..]; let (value, _) = braced_group(after.trim_start())?; parse_dimension(value.trim()) } fn apply_geometry(document: &mut Document, geometry: &PageGeometry) { document.h_offset = geometry.origin.h_offset; // geometry's `top` places the text block below the sheet edge; the // display list and the PDF writer both honour the offset. document.v_offset = geometry.origin.v_offset + geometry.top_margin.unwrap_or(0); 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> { 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(); // TeX accepts both `\parskip=6pt` and `\abovedisplayskip 10pt`; class // files use the space-separated form. let rest = rest.strip_prefix('=').unwrap_or(rest).trim(); let (width, rest) = split_glue_part(rest)?; let rest = rest.trim_start(); let (stretch, rest) = match rest .strip_prefix("plus") .or_else(|| rest.strip_prefix("\\@plus")) { Some(rest) => split_glue_part(rest.trim_start())?, None => (0, rest), }; let rest = rest.trim_start(); let shrink = match rest .strip_prefix("minus") .or_else(|| rest.strip_prefix("\\@minus")) { Some(rest) => split_glue_part(rest.trim_start())?.0, None => 0, }; Some((width, stretch, shrink)) } /// Match a register copy such as `\belowdisplayskip \abovedisplayskip`. fn glue_copy(line: &str, name: &str, source: &str) -> bool { let Some(rest) = line.strip_prefix('\\') else { return false; }; let Some(rest) = rest.strip_prefix(name) else { return false; }; let rest = rest.trim_start(); let rest = rest.strip_prefix('=').unwrap_or(rest).trim(); rest == format!("\\{source}") } fn split_glue_part(text: &str) -> Option<(i64, &str)> { let text = text.trim_start(); // TeX's internal dimension macros: \z@ is 0pt and \p@ is 1pt. if let Some(rest) = text.strip_prefix("\\z@") { return Some((0, rest)); } 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", "\\p@"] .iter() .find_map(|unit| unit_text.strip_prefix(unit).map(|rest| (*unit, rest)))?; let factor = match unit { "pt" | "\\p@" => 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 { let rest = line.strip_prefix('\\')?; let rest = rest.strip_prefix(name)?; let rest = rest.trim_start().strip_prefix('=')?; rest.trim() .parse::() .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 { let rest = line.strip_prefix('\\')?; let rest = rest.strip_prefix(name)?; let rest = rest.trim_start().strip_prefix('=')?; rest.trim().parse::().ok() } fn dimension_assignment(line: &str, name: &str) -> Option { 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}{}` 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}{}` assignment. fn addtolength_assignment(line: &str) -> Option<(String, String)> { let rest = line.strip_prefix("\\addtolength")?; let rest = rest.trim_start().strip_prefix('{')?; let (target, rest) = rest.split_once('}')?; let name = target.trim().strip_prefix('\\')?; let rest = rest.trim_start().strip_prefix('{')?; let (value, _) = rest.split_once('}')?; Some((name.to_string(), value.trim().to_string())) } fn setlength_assignment(line: &str) -> Option<(String, String)> { let rest = line.strip_prefix("\\setlength")?; let rest = rest.trim_start().strip_prefix('{')?; let (target, rest) = rest.split_once('}')?; let name = target.trim().strip_prefix('\\')?; let rest = rest.trim_start().strip_prefix('{')?; let (value, _) = rest.split_once('}')?; Some((name.to_string(), value.trim().to_string())) } /// Resolve a dimension literal or a length declared with `\\newlength`. fn length_value(geometry: &PageGeometry, value: &str) -> Option { if let Some(value) = parse_dimension(value.trim()) { return Some(value); } let name = value.trim().strip_prefix('\\')?; geometry .lengths .iter() .rev() .find(|(known, _)| known == name) .map(|(_, value)| *value) } fn parse_dimension(text: &str) -> Option { let end = text .find(|character: char| { !(character.is_ascii_digit() || character == '.' || character == '-') }) .unwrap_or(text.len()); let number: f64 = text[..end].parse().ok()?; let factor = match text[end..].trim() { "pt" => 1.0, "bp" => 72.27 / 72.0, "in" => 72.27, "cm" => 72.27 / 2.54, "mm" => 72.27 / 25.4, "pc" => 12.0, "dd" => 1238.0 / 1157.0, "cc" => 12.0 * 1238.0 / 1157.0, "sp" => 1.0 / 65_536.0, // The document class default is 10pt, so `em`/`ex` follow it. "em" => 10.0, "ex" => 5.0, _ => return None, }; Some((number * factor * 65_536.0).round() as i64) } /// Lay a document out with the TeX page builder, falling back to the /// scrolling builder for material the paged builder cannot express. fn layout_document(document: &Document) -> Engine { Engine::layout_paged(document).unwrap_or_else(|| Engine::layout(document)) } /// Resolve `\pageref{label}` to the formatted page number of the heading /// that carries the label, using a probe layout followed by the real one. fn page_refs_for(body: &str, geometry: &PageGeometry) -> HashMap { let mut pages = HashMap::new(); let probe = apply_page_refs(body, &HashMap::new()); let paragraphs = match paragraphs_with_geometry( &probe, &geometry.theorem_definitions, geometry_counter(geometry, "equation"), geometry, ) { Ok(paragraphs) => paragraphs, Err(_) => return pages, }; let mut label_units = HashMap::new(); let mut document = build_document_with_labels(¶graphs, geometry, &mut label_units, &mut Vec::new()); apply_geometry(&mut document, geometry); let engine = layout_document(&document); let mut unit_page = HashMap::new(); for (index, page) in engine.pages().iter().enumerate() { for (unit, _) in &page.sources { unit_page.entry(*unit).or_insert(index); } } let style = geometry.page_numbering.as_deref().unwrap_or("arabic"); for (label, unit) in label_units { if let Some(page) = unit_page.get(&unit) { pages.insert(label, page_number_text(*page, style, geometry.page_start)); } } pages } fn apply_page_refs(body: &str, pages: &HashMap) -> String { let mut result = String::with_capacity(body.len()); let mut rest = body; while let Some(position) = rest.find("\\pageref{") { result.push_str(&rest[..position]); let after = &rest[position + "\\pageref{".len()..]; let Some(close) = after.find('}') else { result.push_str(&rest[position..]); return result; }; let key = &after[..close]; result.push_str(pages.get(key).map(String::as_str).unwrap_or("??")); rest = &after[close + 1..]; } result.push_str(rest); result } fn resolve_page_references(body: String, geometry: &PageGeometry) -> String { if !body.contains("\\pageref") { return body; } let pages = page_refs_for(&body, geometry); apply_page_refs(&body, &pages) } /// Build a JSON preview from blank-line-separated plain-text paragraphs. pub fn preview_json(source: &str) -> Result { let (body, geometry) = geometry_and_body(source); let body = resolve_page_references(body, &geometry); let paragraphs = paragraphs_with_geometry( &body, &geometry.theorem_definitions, geometry_counter(&geometry, "equation"), &geometry, )?; let mut document = build_document(¶graphs, &geometry); apply_geometry(&mut document, &geometry); let engine = layout_document(&document); let mut warnings = source_warnings(source, &geometry); warnings.extend(document_warnings(&document)); let json = render_json(&document, &engine, None, &geometry, &warnings); // Keep the layout so a following `/edit` request can diff against it and // reuse page checkpoints instead of starting from a no-op document. ROUTE_D_SESSION.with(|slot| { *slot.borrow_mut() = Some((document, engine)); }); Ok(json) } /// Render the same checkpointed document as a route-D PDF. pub fn pdf_bytes(source: &str) -> Result, 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, ) -> Result, String> { let (body, mut geometry) = geometry_and_body_with_images(source, images); let body = resolve_page_references(body, &geometry); let paragraphs = paragraphs_with_geometry( &body, &geometry.theorem_definitions, geometry_counter(&geometry, "equation"), &geometry, )?; let mut outline_units = Vec::new(); let mut document = build_document_with_labels( ¶graphs, &geometry, &mut HashMap::new(), &mut outline_units, ); apply_geometry(&mut document, &geometry); let engine = layout_document(&document); let mut page_of: HashMap = HashMap::new(); for (index, page) in engine.pages().iter().enumerate() { for (unit, _) in &page.sources { page_of.entry(*unit).or_insert(index); } } let outline: Vec = outline_units .iter() .filter_map(|(title, level, unit)| { page_of.get(unit).map(|page| PdfOutlineEntry { title: title.clone(), page: *page, level: *level, }) }) .collect(); let mut pages: Vec<_> = engine .pages() .iter() .map(|page| { let mut list = page.display_list_with_layout(document.page_goal, document.text_float_sep); list.width = list.width.max(document.paper_width); list.height = list.height.max(document.paper_height); if let Some(color) = geometry.page_color { list.items .insert(0, texrra_tex_core::DisplayItem::Background(color)); } list }) .collect(); if !geometry.suppress_page_numbers { let style = geometry.page_numbering.as_deref().unwrap_or("arabic"); stamp_page_numbers( &mut pages, document.page_goal, document.paper_width, document.paper_height, style, geometry.page_start, geometry.suppress_first_page_number, ); } stamp_running_heads( &mut pages, &geometry, document.page_goal, document.text_width, document.paper_height, ); let metadata = PdfMetadata { title: geometry .pdf_title .clone() .or_else(|| geometry.title.clone()), author: geometry .pdf_author .clone() .or_else(|| geometry.author.clone()), subject: geometry.pdf_subject.clone(), keywords: geometry.pdf_keywords.clone(), outline, link_border: if geometry.hide_links { None } else { geometry .link_border_color .as_deref() .and_then(|name| color_spec(name, &geometry.colors)) }, }; Ok(display_lists_to_pdf_with_cm_type1_and_metadata( &pages, document.paper_width, document.paper_height, geometry.origin, &metadata, )) } /// Apply one paragraph edit to the last route-D document and report page /// checkpoints that were reused versus rebuilt. pub fn edit_json(source: &str, unit: usize) -> Result { let (body, geometry) = geometry_and_body(source); let body = resolve_page_references(body, &geometry); let paragraphs = paragraphs_with_geometry( &body, &geometry.theorem_definitions, geometry_counter(&geometry, "equation"), &geometry, )?; if unit >= paragraphs.len() { return Err(format!( "unit {unit} is out of range for {} paragraphs", paragraphs.len() )); } let next = build_document(¶graphs, &geometry); ROUTE_D_SESSION.with(|slot| { let mut slot = slot.borrow_mut(); let (_, mut engine) = match slot.take() { Some(session) => session, None => { let engine = layout_document(&next); (next.clone(), engine) } }; let paragraph = ¶graphs[unit]; match inline_runs(¶graph.text, paragraph.font) { Some(runs) => { engine.edit_runs(&next, unit as u64, paragraph.text.clone(), runs); } None => engine.edit(&next, unit as u64, paragraph.text.clone()), } let changed = engine.changed_pages().to_vec(); let recomputed = engine.recomputed_pages(); let mut warnings = source_warnings(source, &geometry); warnings.extend(document_warnings(&next)); let json = render_json( &next, &engine, Some((&changed, recomputed)), &geometry, &warnings, ); *slot = Some((next, engine)); Ok(json) }) } #[derive(Clone, PartialEq, Eq)] struct SourceParagraph { text: String, /// TeX `\newpage` before this paragraph. page_break: bool, centered: bool, right_aligned: bool, font: ParagraphFont, line_height: i64, math: bool, left_skip: i64, space_before: i64, space_stretch: i64, space_shrink: i64, /// Number of the equation environment this block came from. equation_number: Option, equation_tag: Option, /// Rows of an `align`/`gather` environment. equation_rows: Vec, /// 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, /// Starred headings are unnumbered and do not advance the counters. heading_starred: bool, /// The section number assigned by the numbering pass. heading_number: Option, heading_short: Option, /// Footnote bodies extracted from this paragraph, with their numbers. footnotes: Vec<(u32, String)>, font_size: Option, /// A `figure` environment carried as a float unit. float: Option, /// A theorem-like environment heading. theorem: Option, /// Nesting depth when this paragraph is a list item. list_depth: Option, /// Width of the generated list label, in points. list_label: i64, /// Extra right margin in points, used by quotation blocks. right_skip: i64, /// Overrides the paragraph measure inside a `minipage` environment. width: Option, /// A `multline` display: rows share one equation number. multline: bool, } /// The kind of a LaTeX float environment. #[derive(Clone, Copy, PartialEq, Eq)] enum FloatKind { Figure, Table, } impl FloatKind { fn caption_prefix<'a>(self, figure_name: &'a str, table_name: &'a str) -> &'a str { match self { FloatKind::Figure => figure_name, FloatKind::Table => table_name, } } } /// A theorem-like environment: numbering state and label targets. #[derive(Clone, PartialEq, Eq)] struct TheoremSpec { name: String, display: String, title: Option, starred: bool, number: Option, labels: Vec, } /// 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, height: Option, /// `scale=...` percentage of the image's natural size. scale: Option, /// `keepaspectratio` when both width and height are requested. keep_aspectratio: bool, caption: Option, /// The optional `[short]` caption used by float lists. caption_short: Option, /// Numbered float-list entry derived from the short caption. list_caption: Option, caption_starred: bool, /// `\includegraphics` path for a figure. image: Option, /// Index into `PageGeometry::tabular` for a captured table body. table: Option, } /// One row of an `align`/`gather` environment. #[derive(Clone, PartialEq, Eq)] struct EquationRow { text: String, number: Option, tag: Option, } /// 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(source: &str, read: F) -> String where F: Fn(&str) -> Option, { expand_inputs_at(source, &read, 0) } fn expand_inputs_at(source: &str, read: &F, depth: usize) -> String where F: Fn(&str) -> Option, { 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, String> { paragraphs_with_definitions(source, &[]) } fn paragraphs_with_definitions( source: &str, definitions: &[TheoremDefinition], ) -> Result, String> { paragraphs_with_counters(source, definitions, 0) } fn paragraphs_with_counters( source: &str, definitions: &[TheoremDefinition], equation_start: u32, ) -> Result, String> { paragraphs_with_spacing( source, definitions, equation_start, ListSpacing::article(&PageGeometry::default()), ) } fn paragraphs_with_geometry( source: &str, definitions: &[TheoremDefinition], equation_start: u32, geometry: &PageGeometry, ) -> Result, String> { paragraphs_with_spacing( source, definitions, equation_start, ListSpacing::article(geometry), ) } /// Blank-line splitter that keeps environments which may contain blank lines /// (quotation, quote, verse, abstract) in one chunk. fn split_display_chunks(source: &str) -> Vec<&str> { const OPENINGS: [&str; 5] = [ "\\begin{quotation}", "\\begin{quote}", "\\begin{verse}", "\\begin{abstract}", "\\begin{minipage}", ]; fn depth(text: &str) -> i64 { let mut depth = 0; for opening in OPENINGS { let closing = opening.replacen("\\begin", "\\end", 1); depth += text.matches(opening).count() as i64; depth -= text.matches(&closing).count() as i64; } depth } let mut chunks = Vec::new(); let mut start = 0; let bytes = source.as_bytes(); let mut index = 0; while index + 1 < bytes.len() { if bytes[index] == b'\n' && bytes[index + 1] == b'\n' { let chunk = &source[start..index]; if depth(chunk) <= 0 { chunks.push(chunk); start = index + 2; } index += 2; } else { index += 1; } } if start < source.len() { chunks.push(&source[start..]); } chunks } fn paragraphs_with_spacing( source: &str, definitions: &[TheoremDefinition], equation_start: u32, spacing: ListSpacing, ) -> Result, String> { let mut paragraphs: Vec<&str> = Vec::new(); for chunk in split_display_chunks(source) { for piece in split_block_environments(chunk) { let piece = piece.trim(); if !piece.is_empty() { paragraphs.push(piece); } } } if paragraphs.is_empty() { return Err("route-D preview needs at least one paragraph".to_string()); } let mut result = Vec::new(); let mut pending = (0_i64, 0_i64, 0_i64); let mut pending_break = false; for chunk in paragraphs { if let Some(index) = table_reference(chunk) { result.push(SourceParagraph { width: None, multline: false, list_depth: None, list_label: 0, right_skip: 0, text: format!("\\texrratable{{{index}}}"), font: ParagraphFont::Roman, line_height: 12, math: false, left_skip: 0, centered: false, right_aligned: false, space_before: pending.0, space_stretch: pending.1, space_shrink: pending.2, page_break: pending_break, equation_number: None, equation_tag: None, equation_rows: Vec::new(), align_centered: false, heading_level: None, heading_starred: false, heading_number: None, heading_short: None, footnotes: Vec::new(), theorem: None, float: None, font_size: None, }); pending = (0, 0, 0); pending_break = false; continue; } if chunk == "\\newpage" || chunk == "\\clearpage" { pending_break = true; continue; } if let Some(skip) = vertical_skip(chunk) { pending.0 += skip.0; pending.1 += skip.1; pending.2 += skip.2; continue; } let mut blocks = parse_blocks_raw(chunk, definitions, spacing); if let Some(first) = blocks.first_mut() { first.space_before += pending.0; first.space_stretch += pending.1; first.space_shrink += pending.2; first.page_break = pending_break; pending_break = false; pending = (0, 0, 0); } result.extend(blocks); } resolve_equation_numbers(&mut result, equation_start); Ok(result) } fn command_body<'a>(text: &'a str, command: &str) -> Option<&'a str> { let rest = text.strip_prefix(command)?.trim_start(); let rest = rest.strip_prefix('{')?.strip_suffix('}')?; Some(rest.trim()) } /// Assign equation numbers in source order and substitute label references. fn resolve_equation_numbers(blocks: &mut [SourceParagraph], equation_start: u32) { let mut number = equation_start; let mut labels: Vec<(String, String)> = Vec::new(); for block in blocks.iter_mut() { if !block.math { continue; } if !block.equation_rows.is_empty() { for row in block.equation_rows.iter_mut() { if let Some(tag) = take_braced_argument(&mut row.text, "\\tag") { row.tag = Some(tag); row.number = None; } if row.text.contains("\\notag") || row.text.contains("\\nonumber") { row.number = None; } row.text = row.text.replace("\\notag", "").replace("\\nonumber", ""); let mut value = row.tag.clone(); if row.number.is_some() { number += 1; row.number = Some(number); value = Some(number.to_string()); } if let Some(value) = value { for label in take_labels(&mut row.text) { labels.push((label, value.clone())); } } } continue; } if let Some(tag) = take_braced_argument(&mut block.text, "\\tag") { block.equation_tag = Some(tag); block.equation_number = None; } if block.text.contains("\\notag") || block.text.contains("\\nonumber") { block.equation_number = None; } block.text = block.text.replace("\\notag", "").replace("\\nonumber", ""); if block.equation_number.is_none() || block.equation_tag.is_some() { continue; } number += 1; block.equation_number = Some(number); for label in take_labels(&mut block.text) { labels.push((label, number.to_string())); } } for block in blocks.iter_mut() { for (label, value) in labels.iter() { let eqref = format!("\\eqref{{{label}}}"); let reference = format!("\\ref{{{label}}}"); block.text = block .text .replace(&eqref, &format!("({value})")) .replace(&reference, value); for row in block.equation_rows.iter_mut() { row.text = row .text .replace(&eqref, &format!("({value})")) .replace(&reference, value); } } } } fn take_labels(text: &mut String) -> Vec { 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 standalone `\captionof{kind}{caption}` as a here-float caption. fn caption_of_block(raw: &str) -> Option { let trimmed = raw.trim(); let rest = trimmed.strip_prefix("\\captionof")?.trim_start(); let rest = rest.strip_prefix('{')?; let kind_end = rest.find('}')?; let kind = rest[..kind_end].trim(); if kind != "figure" && kind != "table" { return None; } let after = rest[kind_end + 1..].trim_start(); let after = after.strip_prefix('{')?; let mut depth = 0_usize; let mut end = None; for (offset, character) in after.char_indices() { match character { '{' => depth += 1, '}' => { if depth == 0 { end = Some(offset); break; } depth -= 1; } _ => {} } } let caption = &after[..end?]; let synthetic = format!("\\begin{{{kind}}}[h]\n\\caption{{{caption}}}\n\\end{{{kind}}}"); float_block(&synthetic) } /// Parse a `figure` environment into a single float block. fn float_block(raw: &str) -> Option { let trimmed = raw.trim(); let (kind, inner) = if let Some(inner) = trimmed .strip_prefix("\\begin{figure}") .and_then(|rest| rest.strip_suffix("\\end{figure}")) { (FloatKind::Figure, inner) } else if let Some(inner) = trimmed .strip_prefix("\\begin{table}") .and_then(|rest| rest.strip_suffix("\\end{table}")) { (FloatKind::Table, inner) } else { return None; }; let inner = inner.trim(); let (placement, inner) = match inner.strip_prefix('[') { Some(rest) => { let end = rest.find(']')?; (figure_placement(&rest[..end]), rest[end + 1..].trim_start()) } None => (FloatPlacement::Top, inner), }; let (mut caption, caption_starred, caption_short) = match figure_caption(inner) { Some((text, starred, short)) => (Some(text), starred, short), None => (None, false, None), }; let labels = figure_labels(inner); if !labels.is_empty() && !caption_starred { let mut text = caption.unwrap_or_default(); for label in labels { let _ = write!(text, "\\label{{{label}}}"); } caption = Some(text); } let (width, height, image, scale, keep_aspectratio) = figure_graphic(inner).unwrap_or((None, None, None, None, false)); let table = embedded_table(inner); Some(SourceParagraph { width: None, multline: false, list_depth: None, list_label: 0, right_skip: 0, text: String::new(), font: ParagraphFont::Roman, line_height: 12, math: false, left_skip: 0, centered: false, right_aligned: false, space_before: 8 * SCALE, space_stretch: 2 * SCALE, space_shrink: 0, page_break: false, equation_number: None, equation_tag: None, equation_rows: Vec::new(), align_centered: false, heading_level: None, heading_starred: false, heading_number: None, heading_short: None, footnotes: Vec::new(), theorem: None, font_size: None, float: Some(FloatSpec { kind, placement, width, height, scale, keep_aspectratio, caption, caption_short, list_caption: None, caption_starred, image, table, }), }) } /// Find the index of a captured `tabular` placeholder inside a table float. fn embedded_table(inner: &str) -> Option { let index = inner.find("\\texrratable{")?; let after = &inner[index + "\\texrratable{".len()..]; let end = after.find('}')?; after[..end].trim().parse().ok() } fn figure_placement(spec: &str) -> FloatPlacement { if spec.chars().any(|option| matches!(option, 'h' | 'H')) { return FloatPlacement::Here; } if spec.contains('t') { return FloatPlacement::Top; } if spec.contains('b') { return FloatPlacement::Bottom; } FloatPlacement::Top } fn figure_caption(inner: &str) -> Option<(String, bool, Option)> { let index = inner.find("\\caption")?; let after = inner[index + "\\caption".len()..].trim_start(); let (after, starred) = match after.strip_prefix('*') { Some(rest) => (rest.trim_start(), true), None => (after, false), }; let (after, short) = match after.strip_prefix('[') { Some(short) => match short.find(']') { Some(end) => ( short[end + 1..].trim_start(), Some(short[..end].trim().to_string()), ), None => (after, None), }, None => (after, None), }; let (body, _) = braced_group(after)?; Some((body.trim().to_string(), starred, short)) } fn figure_labels(inner: &str) -> Vec { 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, Option, Option, Option, 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::() .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 { 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::().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 { 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 { 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 { let mut paths: Vec = 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::() + 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> { let trimmed = raw.trim(); let definition = definitions.iter().find(|definition| { trimmed.starts_with(&format!("\\begin{{{}}}", definition.name)) || trimmed.starts_with(&format!("\\begin{{{}*}}", definition.name)) }); let (name, display, starred_definition) = match definition { Some(definition) => ( definition.name.clone(), definition.display.clone(), definition.starred, ), None => { let (name, starred) = THEOREM_ENVIRONMENTS.iter().find_map(|name| { if trimmed.starts_with(&format!("\\begin{{{name}}}")) { Some((*name, false)) } else if trimmed.starts_with(&format!("\\begin{{{name}*}}")) { Some((*name, true)) } else { None } })?; (name.to_string(), environment_label(name), starred) } }; let (begin, end, starred_marker) = if trimmed.starts_with(&format!("\\begin{{{name}*}}")) { ( format!("\\begin{{{name}*}}"), format!("\\end{{{name}*}}"), true, ) } else { ( format!("\\begin{{{name}}}"), format!("\\end{{{name}}}"), false, ) }; let starred = starred_definition || starred_marker; let body = trimmed.strip_prefix(&begin)?.strip_suffix(&end)?.trim(); let (title, body) = match body.strip_prefix('[') { Some(rest) => { let close = rest.find(']')?; ( Some(rest[..close].trim().to_string()), rest[close + 1..].trim(), ) } None => (None, body), }; let mut body = body.to_string(); let labels = take_labels(&mut body); body = body.trim().to_string(); if body.is_empty() { return None; } let heading_text = match (name.as_str(), title.as_deref()) { ("proof", Some(title)) => format!("{title}."), _ => format!("{display}."), }; let theorem_title = if name == "proof" { None } else { title.clone() }; let heading = SourceParagraph { width: None, multline: false, list_depth: None, list_label: 0, right_skip: 0, text: heading_text, font: ParagraphFont::Bold, line_height: 14, math: false, left_skip: 0, centered: false, right_aligned: false, space_before: 12 * SCALE, space_stretch: 2 * SCALE, space_shrink: 0, page_break: false, equation_number: None, equation_tag: None, equation_rows: Vec::new(), align_centered: false, heading_level: None, heading_starred: false, heading_number: None, heading_short: None, footnotes: Vec::new(), theorem: Some(TheoremSpec { name: name.clone(), display, title: theorem_title, starred, number: None, labels, }), font_size: None, float: None, }; let italic = matches!( name.as_str(), "theorem" | "lemma" | "corollary" | "proposition" | "proof" ); let statement = SourceParagraph { width: None, multline: false, list_depth: None, list_label: 0, right_skip: 0, text: body, font: if italic { ParagraphFont::Italic } else { ParagraphFont::Roman }, line_height: 12, math: false, left_skip: 0, centered: false, right_aligned: false, space_before: 4 * SCALE, space_stretch: 0, space_shrink: 0, page_break: false, equation_number: None, equation_tag: None, equation_rows: Vec::new(), align_centered: false, heading_level: None, heading_starred: false, heading_number: None, heading_short: None, footnotes: Vec::new(), theorem: None, font_size: None, float: None, }; Some(vec![heading, statement]) } /// Recognise a list environment chunk and return its kind and body. fn list_environment(raw: &str) -> Option<(&'static str, &str)> { for environment in ["itemize", "enumerate", "description"] { let begin = format!("\\begin{{{environment}}}"); let end = format!("\\end{{{environment}}}"); if let Some(body) = raw .trim() .strip_prefix(&begin) .and_then(|text| text.strip_suffix(&end)) { return Some((environment, body)); } } None } /// Split a list body at top-level `\\item` commands, keeping nested lists /// inside the item that contains them. fn split_list_items(body: &str) -> Vec<&str> { let bytes = body.as_bytes(); let mut items = Vec::new(); let mut start = None; let mut environment_depth = 0_usize; let mut brace_depth = 0_usize; let mut index = 0; while index < bytes.len() { match bytes[index] { b'{' => { brace_depth += 1; index += 1; continue; } b'}' => { brace_depth = brace_depth.saturating_sub(1); index += 1; continue; } b'\\' => { let rest = &body[index..]; if rest.starts_with("\\begin{") { environment_depth += 1; index += "\\begin{".len(); continue; } if rest.starts_with("\\end{") { environment_depth = environment_depth.saturating_sub(1); index += "\\end{".len(); continue; } if environment_depth == 0 && brace_depth == 0 && rest.starts_with("\\item") { let after = index + "\\item".len(); let boundary = rest["\\item".len()..] .chars() .next() .is_none_or(|character| !character.is_ascii_alphabetic()); if boundary { if let Some(previous) = start { items.push(&body[previous..index]); } start = Some(after); index = after; continue; } } } _ => {} } index += 1; } if let Some(previous) = start { items.push(&body[previous..]); } items } /// Split item text into the part before a nested list, the nested list itself /// and the continuation after it. fn split_nested_list(text: &str) -> (String, Option, String) { let candidates = [ "\\begin{itemize}", "\\begin{enumerate}", "\\begin{description}", ]; let Some((start, environment)) = candidates .iter() .filter_map(|begin| { let environment = begin.trim_start_matches("\\begin{").trim_end_matches('}'); text.find(begin).map(|index| (index, environment)) }) .min_by_key(|(index, _)| *index) else { return (text.to_string(), None, String::new()); }; let begin = format!("\\begin{{{environment}}}"); let end = format!("\\end{{{environment}}}"); let after_begin = start + begin.len(); let mut depth = 1_usize; let mut cursor = after_begin; while depth > 0 { let next_begin = text[cursor..].find(&begin).map(|offset| cursor + offset); let next_end = text[cursor..].find(&end).map(|offset| cursor + offset); match (next_begin, next_end) { (Some(begin_index), Some(end_index)) if begin_index < end_index => { depth += 1; cursor = begin_index + begin.len(); } (_, Some(end_index)) => { depth -= 1; cursor = end_index + end.len(); } (_, None) => return (text.to_string(), None, String::new()), } } ( text[..start].to_string(), Some(text[start..cursor].to_string()), text[cursor..].to_string(), ) } fn alphabetic_label(mut number: u32, upper: bool) -> String { let mut label = String::new(); while number > 0 { let digit = ((number - 1) % 26) as u8; label.insert(0, (b'a' + digit) as char); number = (number - 1) / 26; } if upper { label.to_ascii_uppercase() } else { label } } fn roman_label(number: u32) -> String { const VALUES: [(u32, &str); 13] = [ (1000, "m"), (900, "cm"), (500, "d"), (400, "cd"), (100, "c"), (90, "xc"), (50, "l"), (40, "xl"), (10, "x"), (9, "ix"), (5, "v"), (4, "iv"), (1, "i"), ]; let mut value = number; let mut label = String::new(); for (amount, glyph) in VALUES { while value >= amount { label.push_str(glyph); value -= amount; } } if label.is_empty() { number.to_string() } else { label } } fn enumerate_label(number: u32, depth: usize) -> String { match depth % 4 { 1 => format!("({}) ", alphabetic_label(number, false)), 2 => format!("{}. ", roman_label(number)), 3 => format!("{}. ", alphabetic_label(number, true)), _ => format!("{number}. "), } } fn bullet_label(depth: usize) -> &'static str { match depth % 3 { 1 => "– ", 2 => "* ", _ => "• ", } } /// Vertical glue around list items, in points as [width, stretch, shrink]. /// /// The four entries follow TeX's `\@listi` through `\@listiv` values from the /// article size files: `(topsep, itemsep, partopsep)` for each nesting depth. #[derive(Clone, Copy, Debug, PartialEq, Eq)] struct ListSpacing { levels: [((i64, i64, i64), (i64, i64, i64), (i64, i64, i64)); 4], } impl ListSpacing { fn article(geometry: &PageGeometry) -> Self { let base = geometry.base_font_size.unwrap_or(10 * SCALE); let mut levels = match base / SCALE { 12 => [ ((10, 4, 6), (5, 2, 1), (3, 2, 2)), ((5, 2, 1), (2, 2, 1), (3, 2, 2)), ((2, 1, 1), (2, 1, 1), (1, 0, 1)), ((2, 1, 1), (2, 1, 1), (1, 0, 1)), ], 11 => [ ((9, 3, 5), (5, 2, 1), (3, 1, 1)), ((5, 2, 1), (2, 1, 1), (3, 1, 1)), ((2, 1, 1), (2, 1, 1), (1, 0, 1)), ((2, 1, 1), (2, 1, 1), (1, 0, 1)), ], _ => [ ((8, 2, 4), (4, 2, 1), (2, 1, 1)), ((4, 2, 1), (2, 1, 1), (2, 1, 1)), ((2, 1, 1), (2, 1, 1), (1, 0, 1)), ((2, 1, 1), (2, 1, 1), (1, 0, 1)), ], }; let points = |value: (i64, i64, i64)| (value.0 / SCALE, value.1 / SCALE, value.2 / SCALE); if let Some(top) = geometry.top_sep { for level in &mut levels { level.0 = points(top); } } if let Some(item) = geometry.item_sep { for level in &mut levels { level.1 = points(item); } } if let Some(partop) = geometry.part_op_sep { for level in &mut levels { level.2 = points(partop); } } Self { levels } } fn first(&self, depth: usize) -> Option<(i64, i64, i64)> { let (top, partop) = { let (top, _, partop) = self.levels[depth.min(3)]; (top, partop) }; Some((top.0 + partop.0, top.1 + partop.1, top.2 + partop.2)) } fn item(&self, depth: usize) -> Option<(i64, i64, i64)> { Some(self.levels[depth.min(3)].1) } } fn list_label_width(label: &str) -> i64 { let metrics = Cmr10Metrics::Roman; let total: i64 = label .chars() .map(|character| match character { ' ' => metrics.space(), _ => metrics.width(character), }) .sum(); ((total + SCALE - 1) / SCALE).max(1) } fn list_paragraph( text: String, depth: usize, space: Option<(i64, i64, i64)>, label_width: i64, ) -> SourceParagraph { let (before, stretch, shrink) = space.unwrap_or((0, 0, 0)); SourceParagraph { width: None, multline: false, text, font: ParagraphFont::Roman, line_height: 12, math: false, left_skip: 12 * (depth as i64 + 1), centered: false, right_aligned: false, space_before: before, space_stretch: stretch, space_shrink: shrink, page_break: false, equation_number: None, equation_tag: None, equation_rows: Vec::new(), align_centered: false, heading_level: None, heading_starred: false, heading_number: None, heading_short: None, footnotes: Vec::new(), theorem: None, float: None, font_size: None, list_depth: Some(depth as u8), list_label: label_width, right_skip: 0, } } /// Lay out a list environment, recursing into lists nested in its items. fn verbatim_blocks(raw: &str) -> Option> { let trimmed = raw.trim(); let inner = trimmed .strip_prefix("\\begin{verbatim}")? .strip_suffix("\\end{verbatim}")?; let inner = inner.strip_prefix('\n').unwrap_or(inner); let mut blocks = Vec::new(); for (index, line) in inner.lines().enumerate() { let text = line.trim_end(); blocks.push(SourceParagraph { width: None, multline: false, list_depth: None, list_label: 0, right_skip: 0, text: text.to_string(), page_break: false, centered: false, right_aligned: false, font: ParagraphFont::Mono, line_height: 10, math: false, left_skip: 12, space_before: if index == 0 { 6 * SCALE } else { 0 }, space_stretch: 0, space_shrink: 0, equation_number: None, equation_tag: None, equation_rows: Vec::new(), align_centered: false, heading_level: None, heading_starred: false, heading_number: None, heading_short: None, font_size: None, footnotes: Vec::new(), float: None, theorem: None, }); } Some(blocks) } fn list_blocks( raw: &str, depth: usize, _definitions: &[TheoremDefinition], spacing: ListSpacing, ) -> Option> { let (environment, body) = list_environment(raw)?; let mut blocks = Vec::new(); let mut placed = false; let mut number = 0_u32; if environment == "enumerate" { let counters = ["enumi", "enumii", "enumiii", "enumiv"]; let counter = counters[depth.min(counters.len() - 1)]; let marker = format!("\\setcounter{{{counter}}}{{"); if let Some(position) = body.find(&marker) && position < body.find("\\item").unwrap_or(usize::MAX) { let after = &body[position + marker.len()..]; if let Some((value, _)) = after.split_once('}') && let Ok(start) = value.trim().parse::() { number = start; } } } for item in split_list_items(body) { let item = item.trim(); if item.is_empty() { continue; } let (custom_label, item) = if environment == "description" { (None, item) } else { match item.strip_prefix('[').and_then(|text| text.split_once(']')) { Some((label, rest)) => (Some(label.trim().to_string()), rest.trim_start()), None => (None, item), } }; let (label, rest) = match environment { "description" => { let (term, rest) = item .strip_prefix('[') .and_then(|text| text.split_once(']')) .map(|(term, rest)| (term.trim(), rest.trim())) .unwrap_or(("", item)); if term.is_empty() { (String::new(), rest) } else { (format!("\\textbf{{{term}}} — "), rest) } } "enumerate" => { number += 1; let label = custom_label .as_deref() .filter(|label| !label.is_empty()) .map(|label| format!("{label} ")) .unwrap_or_else(|| enumerate_label(number, depth)); (label, item) } _ => { let label = custom_label .as_deref() .filter(|label| !label.is_empty()) .map(|label| format!("{label} ")) .unwrap_or_else(|| bullet_label(depth).to_string()); (label, item) } }; let (before, nested, after) = split_nested_list(rest); if !before.trim().is_empty() { let space = if placed { spacing.item(depth) } else { spacing.first(depth) }; placed = true; blocks.push(list_paragraph( format!("{label}{}", before.trim()), depth, space, list_label_width(&label), )); } if let Some(nested) = nested { if let Some(nested_blocks) = list_blocks(&nested, depth + 1, _definitions, spacing) { blocks.extend(nested_blocks); } } if !after.trim().is_empty() { blocks.push(list_paragraph( after.trim().to_string(), depth, None, list_label_width(&label), )); } } if blocks.is_empty() { None } else { Some(blocks) } } fn standalone_graphic(raw: &str) -> Option { let trimmed = raw.trim(); let rest = trimmed.strip_prefix("\\includegraphics")?; let mut rest = rest.trim_start(); if let Some(options) = rest.strip_prefix('[') { let close = options.find(']')?; rest = options[close + 1..].trim_start(); } let (_path, consumed) = braced_group(rest)?; if !rest[consumed..].trim().is_empty() { return None; } let (width, height, image, scale, keep_aspectratio) = figure_graphic(trimmed)?; Some(SourceParagraph { width: None, multline: false, list_depth: None, list_label: 0, right_skip: 0, text: String::new(), font: ParagraphFont::Roman, line_height: 12, math: false, left_skip: 0, centered: false, right_aligned: false, space_before: 8 * SCALE, space_stretch: 2 * SCALE, space_shrink: 0, page_break: false, equation_number: None, equation_tag: None, equation_rows: Vec::new(), align_centered: false, heading_level: None, heading_starred: false, heading_number: None, heading_short: None, footnotes: Vec::new(), theorem: None, font_size: None, float: Some(FloatSpec { kind: FloatKind::Figure, placement: FloatPlacement::Here, width, height, scale, keep_aspectratio, caption: None, caption_short: None, list_caption: None, caption_starred: false, image, table: None, }), }) } fn verse_block(raw: &str) -> Option> { let body = raw .trim() .strip_prefix("\\begin{verse}")? .strip_suffix("\\end{verse}")?; let mut blocks = Vec::new(); for line in body.split("\\\\") { let text = line.trim(); if text.is_empty() { continue; } let mut block = parse_paragraph(text); block.left_skip = 20; blocks.push(block); } if blocks.is_empty() { None } else { Some(blocks) } } fn rule_block(raw: &str) -> Option { let rest = raw.trim().strip_prefix("\\rule")?; let mut rest = rest.trim_start(); if rest.starts_with('[') { let close = rest.find(']')?; rest = rest[close + 1..].trim_start(); } let (width, consumed) = braced_group(rest)?; let width = parse_dimension(width.trim())?; rest = rest[consumed..].trim_start(); let (height, consumed) = braced_group(rest)?; let height = parse_dimension(height.trim())?; if !rest[consumed..].trim().is_empty() { return None; } let mut block = parse_paragraph(""); block.float = Some(FloatSpec { kind: FloatKind::Figure, placement: FloatPlacement::Here, width: Some(ImageLength::Absolute(width)), height: Some(ImageLength::Absolute(height)), scale: None, keep_aspectratio: false, caption: None, caption_short: None, list_caption: None, caption_starred: false, image: None, table: None, }); block.space_before = 6 * SCALE; block.space_stretch = 0; block.space_shrink = 0; Some(block) } fn minipage_blocks( raw: &str, definitions: &[TheoremDefinition], spacing: ListSpacing, ) -> Option> { let body = raw .trim() .strip_prefix("\\begin{minipage}")? .strip_suffix("\\end{minipage}")?; let mut rest = body.trim_start(); if let Some(after) = rest.strip_prefix('[') { let close = after.find(']')?; rest = after[close + 1..].trim_start(); } let (width, consumed) = braced_group(rest)?; let width = parse_dimension(width.trim())?; let content = rest[consumed..].trim(); if content.is_empty() { return None; } let mut blocks = Vec::new(); for chunk in split_display_chunks(content) { if chunk.trim().is_empty() { continue; } let mut parsed = parse_blocks_raw(chunk, definitions, spacing); for block in &mut parsed { block.width = Some(width); block.space_before = 0; block.space_stretch = 0; block.space_shrink = 0; } blocks.extend(parsed); } (!blocks.is_empty()).then_some(blocks) } fn parse_blocks_raw( raw: &str, definitions: &[TheoremDefinition], spacing: ListSpacing, ) -> Vec { if let Some(block) = float_block(raw) { return vec![block]; } if let Some(block) = caption_of_block(raw) { return vec![block]; } if let Some(block) = standalone_graphic(raw) { return vec![block]; } if let Some(block) = rule_block(raw) { return vec![block]; } if let Some(blocks) = minipage_blocks(raw, definitions, spacing) { return blocks; } if let Some(blocks) = theorem_block(raw, definitions) { return blocks; } if let Some(body) = raw .trim() .strip_prefix("\\begin{abstract}") .and_then(|rest| rest.strip_suffix("\\end{abstract}")) { let heading = SourceParagraph { width: None, multline: false, list_depth: None, list_label: 0, right_skip: 0, text: "Abstract".to_string(), font: ParagraphFont::Bold, line_height: 12, math: false, left_skip: 0, centered: true, right_aligned: false, space_before: 12 * SCALE, space_stretch: 0, space_shrink: 0, page_break: false, equation_number: None, equation_tag: None, equation_rows: Vec::new(), align_centered: false, heading_level: None, heading_starred: false, heading_number: None, heading_short: None, footnotes: Vec::new(), theorem: None, float: None, font_size: Some((12.0 * SCALE as f64) as i64), }; let body = SourceParagraph { width: None, multline: false, list_depth: None, list_label: 0, right_skip: 0, text: body.trim().to_string(), font: ParagraphFont::Roman, line_height: 12, math: false, left_skip: 0, centered: false, right_aligned: false, space_before: 6 * SCALE, space_stretch: 0, space_shrink: 0, page_break: false, equation_number: None, equation_tag: None, equation_rows: Vec::new(), align_centered: false, heading_level: None, heading_starred: false, heading_number: None, heading_short: None, footnotes: Vec::new(), theorem: None, float: None, font_size: Some((9.0 * SCALE as f64) as i64), }; if body.text.is_empty() { return vec![heading]; } return vec![heading, body]; } for (environment, centered, right_aligned) in [ ("center", true, false), ("flushleft", false, false), ("flushright", false, true), ] { let begin = format!("\\begin{{{environment}}}"); let finish = format!("\\end{{{environment}}}"); let Some(body) = raw .strip_prefix(&begin) .and_then(|text| text.strip_suffix(&finish)) else { continue; }; let body = body.trim(); if body.is_empty() { continue; } let mut blocks = parse_blocks_raw(body, definitions, spacing); for block in &mut blocks { block.centered = centered; block.right_aligned = right_aligned; } if !blocks.is_empty() { return blocks; } continue; } if let Some(blocks) = verbatim_blocks(raw) { return blocks; } if let Some(blocks) = list_blocks(raw, 0, definitions, spacing) { return blocks; } if let Some(blocks) = verse_block(raw) { return blocks; } if let Some(body) = raw .strip_prefix("\\begin{quotation}") .and_then(|text| text.strip_suffix("\\end{quotation}")) { let mut blocks = Vec::new(); for paragraph in body.trim().split("\n\n") { let text = paragraph.trim(); if text.is_empty() { continue; } let mut nested = parse_blocks_raw(text, definitions, spacing); for block in &mut nested { block.left_skip += 20; block.right_skip += 20; } blocks.extend(nested); } if !blocks.is_empty() { return blocks; } } if let Some(body) = raw .strip_prefix("\\begin{quote}") .and_then(|text| text.strip_suffix("\\end{quote}")) { let text = body.trim(); if !text.is_empty() { return vec![SourceParagraph { width: None, multline: false, list_depth: None, list_label: 0, text: text.to_string(), font: ParagraphFont::Roman, line_height: 12, math: false, left_skip: 20, right_skip: 20, centered: false, right_aligned: false, space_before: 0, space_stretch: 0, space_shrink: 0, page_break: false, equation_number: None, equation_tag: None, equation_rows: Vec::new(), align_centered: false, heading_level: None, heading_starred: false, heading_number: None, heading_short: None, footnotes: Vec::new(), theorem: None, float: None, font_size: None, }]; } } vec![parse_paragraph(raw)] } /// Map a small, general LaTeX subset onto route-D paragraph faces. This is not /// a full LaTeX reader; it exists so the live endpoint can show headings and /// emphasis while the semantic layer is built out. fn take_braced_argument(text: &mut String, command: &str) -> Option { let start = text.find(command)?; let after = start + command.len(); if !text[after..].starts_with('{') { return None; } let mut depth = 0_usize; for (offset, character) in text[after..].char_indices() { match character { '{' => depth += 1, '}' => { depth -= 1; if depth == 0 { let inner = text[after + 1..after + offset].to_string(); text.replace_range(start..after + offset + 1, ""); return Some(inner); } } _ => {} } } None } #[derive(Clone, Copy, PartialEq, Eq)] enum Family { Roman, Sans, Mono, } /// Paragraph-level NFSS declarations: family, series and shape prefixes such /// as `{\sffamily\bfseries ...}` are folded into the built-in faces. fn nfss_family_name(name: &str) -> Family { let lower = name.to_ascii_lowercase(); if lower.starts_with("cmss") || lower.starts_with("lmss") || lower.starts_with("phv") { Family::Sans } else if lower.starts_with("cmtt") || lower.starts_with("lmtt") || lower.starts_with("pcr") { Family::Mono } else { Family::Roman } } fn nfss_braced<'a>(text: &'a str, command: &str) -> Option<(String, &'a str)> { let rest = text.strip_prefix(command)?; let rest = rest.trim_start().strip_prefix('{')?; let end = rest.find('}')?; Some((rest[..end].to_string(), rest[end + 1..].trim_start())) } fn nfss_declaration<'a>(text: &'a str, command: &str) -> Option<&'a str> { let rest = text.strip_prefix(command)?; if rest .chars() .next() .is_some_and(|character| character.is_ascii_alphabetic()) { return None; } Some(rest) } /// TeX size commands with the article-class 10pt point size values. const SIZE_COMMANDS: [(&str, f64); 10] = [ ("\\tiny", 5.0), ("\\scriptsize", 7.0), ("\\footnotesize", 8.0), ("\\small", 9.0), ("\\normalsize", 10.0), ("\\large", 12.0), ("\\Large", 14.4), ("\\LARGE", 17.28), ("\\huge", 20.74), ("\\Huge", 24.88), ]; /// Scan a size declaration such as `\large` or /// `\fontsize{14pt}{18pt}\selectfont`, returning the size and the rest. fn font_size_command(rest: &str) -> Option<(i64, &str)> { for (command, points) in SIZE_COMMANDS { if let Some(after) = nfss_declaration(rest, command) { return Some(((points * 65_536.0).round() as i64, after)); } } let after = rest.strip_prefix("\\fontsize")?; if after .chars() .next() .is_some_and(|character| character.is_ascii_alphabetic()) { return None; } let after = after.trim_start(); let (size_text, length) = braced_group(after)?; let size = parse_dimension(size_text.trim())?; let after = after[length..].trim_start(); let (_, length) = braced_group(after)?; let mut after = after[length..].trim_start(); if let Some(rest) = after.strip_prefix("\\selectfont") { after = rest; } Some((size, after)) } fn nfss_font_with_size( raw: &str, base: ParagraphFont, ) -> Option<(ParagraphFont, Option, 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 = 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 { if closing == "$" { let bytes = text.as_bytes(); let mut index = 0; while index < bytes.len() { match bytes[index] { b'\\' => index += 2, b'$' => return Some(index), _ => index += 1, } } None } else { text.find(closing) } } /// Split text into literal pieces and `$...$` / `\(...\)` formulas. fn split_inline_math(text: &str) -> Vec<(bool, String)> { let mut pieces = Vec::new(); let mut literal = String::new(); let mut index = 0; while index < text.len() { let rest = &text[index..]; if rest.starts_with("$$") { literal.push_str("$$"); index += 2; continue; } let opener = if rest.starts_with("\\begin{math}") { Some(("\\begin{math}".len(), "\\end{math}")) } else if rest.starts_with("\\(") { Some((2, "\\)")) } else if rest.starts_with('$') { Some((1, "$")) } else { None }; if let Some((open_len, closing)) = opener { let after = &rest[open_len..]; if let Some(end) = math_end(after, closing) { if !literal.is_empty() { pieces.push((false, std::mem::take(&mut literal))); } pieces.push((true, after[..end].to_string())); index += open_len + end + closing.len(); continue; } } let character = rest.chars().next().expect("non-empty tail"); if rest.starts_with('\\') { literal.push(character); if let Some(next) = rest[character.len_utf8()..].chars().next() { literal.push(next); index += character.len_utf8() + next.len_utf8(); continue; } } literal.push(character); index += character.len_utf8(); } if !literal.is_empty() { pieces.push((false, literal)); } pieces } /// Build mixed text/math segments when the paragraph contains inline math. /// /// Math metrics are measured at 10pt, so sized paragraphs keep the literal /// delimiters until per-size math layout exists. enum HrefPart { Plain(String), Link(String, String), } fn split_hrefs(text: &str) -> Vec { 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 color_byte(value: f64) -> u8 { (value.clamp(0.0, 1.0) * 255.0).round() as u8 } fn color_int(value: &str) -> Option { let parsed = value.trim().parse::().ok()?; Some(parsed.clamp(0, 255) as u8) } fn hex_pair(text: &str) -> Option { u8::from_str_radix(text, 16).ok() } fn define_color(line: &str) -> Option<(String, [u8; 3])> { let rest = line.trim_start().strip_prefix("\\definecolor")?; let rest = rest.trim_start(); let (name, used) = braced_group(rest)?; let rest = rest[used..].trim_start(); let (model, used) = braced_group(rest)?; let rest = rest[used..].trim_start(); let (spec, _) = braced_group(rest)?; let rgb = match model.trim() { "rgb" => { let parts: Vec = spec .split(',') .map(|part| part.trim().parse::().ok()) .collect::>>()?; if parts.len() != 3 { return None; } [ color_byte(parts[0]), color_byte(parts[1]), color_byte(parts[2]), ] } "RGB" => { let parts: Vec<&str> = spec.split(',').collect(); if parts.len() != 3 { return None; } [ color_int(parts[0])?, color_int(parts[1])?, color_int(parts[2])?, ] } "gray" => { let level = color_byte(spec.trim().parse::().ok()?); [level, level, level] } "HTML" => { let digits = spec.trim(); if digits.len() != 6 { return None; } [ hex_pair(&digits[0..2])?, hex_pair(&digits[2..4])?, hex_pair(&digits[4..6])?, ] } "cmyk" => { let parts: Vec = spec .split(',') .map(|part| part.trim().parse::().ok()) .collect::>>()?; if parts.len() != 4 { return None; } let k = parts[3].clamp(0.0, 1.0); [ color_byte((1.0 - parts[0].clamp(0.0, 1.0)) * (1.0 - k)), color_byte((1.0 - parts[1].clamp(0.0, 1.0)) * (1.0 - k)), color_byte((1.0 - parts[2].clamp(0.0, 1.0)) * (1.0 - k)), ] } _ => return None, }; Some((name.trim().to_string(), rgb)) } fn color_spec(spec: &str, custom: &[(String, [u8; 3])]) -> Option<[u8; 3]> { let parts: Vec<&str> = spec.split('!').collect(); if parts.len() == 1 { return named_color(spec.trim(), custom); } if parts.len() > 3 { return None; } let first = named_color(parts[0].trim(), custom)?; let percent: u8 = parts[1].trim().parse().ok()?; let second = if parts.len() == 3 { named_color(parts[2].trim(), custom)? } else { [255, 255, 255] }; let first_weight = percent.min(100) as u32; let second_weight = 100 - first_weight; let mix = |left: u8, right: u8| { ((left as u32 * first_weight + right as u32 * second_weight + 50) / 100) as u8 }; Some([ mix(first[0], second[0]), mix(first[1], second[1]), mix(first[2], second[2]), ]) } fn named_color(name: &str, custom: &[(String, [u8; 3])]) -> Option<[u8; 3]> { if let Some((_, rgb)) = custom.iter().rev().find(|(known, _)| known == name) { return Some(*rgb); } match name.trim().to_ascii_lowercase().as_str() { "black" => Some([0, 0, 0]), "white" => Some([255, 255, 255]), "red" => Some([255, 0, 0]), "green" => Some([0, 128, 0]), "blue" => Some([0, 0, 255]), "cyan" => Some([0, 255, 255]), "magenta" => Some([255, 0, 255]), "yellow" => Some([255, 255, 0]), "gray" | "grey" => Some([128, 128, 128]), "darkgray" | "darkgrey" => Some([64, 64, 64]), "lightgray" | "lightgrey" => Some([192, 192, 192]), "brown" => Some([165, 42, 42]), "lime" => Some([0, 255, 0]), "olive" => Some([128, 128, 0]), "orange" => Some([255, 165, 0]), "pink" => Some([255, 192, 203]), "purple" => Some([128, 0, 128]), "teal" => Some([0, 128, 128]), "violet" => Some([238, 130, 238]), _ => None, } } /// Splits `\textcolor{name}{text}` runs out of a paragraph piece. fn take_braced_group(text: &str) -> Option<(String, &str)> { let text = text.trim_start(); let body = text.strip_prefix('{')?; let mut depth = 1_usize; for (offset, character) in body.char_indices() { match character { '{' => depth += 1, '}' => { depth -= 1; if depth == 0 { return Some((body[..offset].to_string(), &body[offset + 1..])); } } _ => {} } } None } fn split_color_runs( text: &str, custom: &[(String, [u8; 3])], ) -> Vec<(Option<[u8; 3]>, bool, Option<[u8; 3]>, String)> { let mut out = Vec::new(); let mut rest = text; let mut plain = String::new(); loop { let next = rest .find("\\textcolor") .map(|index| (index, "\\textcolor")) .into_iter() .chain(rest.find("\\colorbox").map(|index| (index, "\\colorbox"))) .chain(rest.find("\\fcolorbox").map(|index| (index, "\\fcolorbox"))) .chain(rest.find("\\fbox").map(|index| (index, "\\fbox"))) .min_by_key(|(index, _)| *index); let Some((index, command)) = next else { break; }; plain.push_str(&rest[..index]); let after_command = &rest[index + command.len()..]; let Some((first, after_first)) = take_braced_group(after_command) else { plain.push_str(&rest[index..]); rest = ""; break; }; let (color, background, frame, body_source) = match command { "\\textcolor" => match color_spec(&first, custom) { Some(color) => (Some(color), false, None, after_first), None => { plain.push_str(&rest[index..=index]); rest = &rest[index + 1..]; continue; } }, "\\fbox" => (None, false, Some([0, 0, 0]), after_command), "\\colorbox" => match color_spec(&first, custom) { Some(color) => (Some(color), true, None, after_first), None => { plain.push_str(&rest[index..=index]); rest = &rest[index + 1..]; continue; } }, _ => { let Some(frame) = color_spec(&first, custom) else { plain.push_str(&rest[index..=index]); rest = &rest[index + 1..]; continue; }; let Some((background_name, after_background)) = take_braced_group(after_first) else { plain.push_str(&rest[index..]); rest = ""; break; }; let Some(background) = color_spec(&background_name, custom) else { plain.push_str(&rest[index..=index]); rest = &rest[index + 1..]; continue; }; (Some(background), true, Some(frame), after_background) } }; let Some((body, after_body)) = take_braced_group(body_source) else { plain.push_str(&rest[index..]); rest = ""; break; }; if !plain.is_empty() { out.push((None, false, None, std::mem::take(&mut plain))); } out.push((color, background, frame, body)); rest = after_body; } plain.push_str(rest); if !plain.is_empty() { out.push((None, false, None, plain)); } if out.is_empty() { out.push((None, false, None, text.to_string())); } out } fn expand_character_commands(text: &str) -> String { let mut out = String::new(); let mut index = 0; while index < text.len() { let rest = &text[index..]; if let Some(after) = rest.strip_prefix("\\char") { let digits: String = after.chars().take_while(|c| c.is_ascii_digit()).collect(); if !digits.is_empty() { if let Ok(value) = digits.parse::() { if let Some(character) = char::from_u32(value) { out.push(character); index += "\\char".len() + digits.len(); continue; } } } } if let Some(after) = rest.strip_prefix("\\symbol{") { if let Some(close) = after.find('}') { if let Ok(value) = after[..close].trim().parse::() { if let Some(character) = char::from_u32(value) { out.push(character); index += "\\symbol{".len() + close + 1; continue; } } } } let character = rest.chars().next().expect("remainder"); out.push(character); index += character.len_utf8(); } out } /// Drop grouping braces outside math mode; `\{`/`\}` stay literal. Command /// arguments that matter have already been consumed by this stage. fn strip_group_braces(text: &str) -> String { let mut out = String::with_capacity(text.len()); let mut math = false; let mut chars = text.chars().peekable(); while let Some(character) = chars.next() { if character == '$' { math = !math; out.push(character); continue; } if math { out.push(character); continue; } if character == '\\' { if let Some(&next) = chars.peek() { if next == '{' || next == '}' { out.push(next); chars.next(); continue; } } out.push(character); continue; } if character == '{' || character == '}' { continue; } out.push(character); } out.replace('\u{E022}', "") } fn strip_noop_commands(text: &str) -> String { let text = text.replace('\u{E022}', ""); const COMMANDS: [&str; 17] = [ "\\displaybreak", "\\protect", "\\relax", "\\ignorespaces", "\\unskip", "\\nobreak", "\\allowbreak", "\\sloppy", "\\fussy", "\\phantomsection", "\\leavevmode", "\\strut", "\\mathstrut", "\\linebreak", "\\nolinebreak", "\\pagebreak", "\\nopagebreak", ]; let mut out = String::new(); let mut index = 0; while index < text.len() { let rest = &text[index..]; let mut matched = None; if rest.starts_with('\\') { for command in COMMANDS { if let Some(after) = rest.strip_prefix(command) { if !after .chars() .next() .is_some_and(|c| c.is_ascii_alphabetic()) { matched = Some(command.len()); break; } } } } if let Some(length) = matched { index += length; if let Some(after) = text[index..].trim_start().strip_prefix('[') { if let Some(close) = after.find(']') { index = text.len() - after.len() + close + 1; } } continue; } if rest.starts_with("\\-") { index += 2; continue; } let Some(character) = rest.chars().next() else { break; }; out.push(character); index += character.len_utf8(); } out } /// Remove vertical spacing commands that survived into running text; the /// standalone forms already became vertical glue items earlier. fn strip_inline_spacing(text: &str) -> String { let mut out = String::new(); let mut rest = text; while !rest.is_empty() { if let Some(after) = rest.strip_prefix("\\vspace") { let mut after = after.trim_start(); if let Some(stripped) = after.strip_prefix('*') { after = stripped.trim_start(); } if let Some((_, used)) = braced_group(after) { rest = &after[used..]; continue; } } let mut matched = false; for command in ["\\smallskip", "\\medskip", "\\bigskip", "\\samepage"] { if let Some(after) = rest.strip_prefix(command) && !after .chars() .next() .is_some_and(|character| character.is_ascii_alphabetic()) { rest = after; matched = true; break; } } if matched { continue; } let character = rest.chars().next().expect("text remainder"); out.push(character); rest = &rest[character.len_utf8()..]; } out } fn strip_box_commands(text: &str) -> String { let mut out = String::new(); let mut rest = text; loop { let matches: Vec<(&str, usize)> = ["\\mbox{", "\\hbox{", "\\makebox[", "\\underline{"] .iter() .filter_map(|command| rest.find(command).map(|index| (*command, index))) .collect(); let Some((command, index)) = matches.into_iter().min_by_key(|(_, index)| *index) else { out.push_str(rest); return out; }; out.push_str(&rest[..index]); let mut after = &rest[index + command.len()..]; if command == "\\makebox[" { let Some(close) = after.find(']') else { out.push_str(&rest[index..]); return out; }; after = &after[close + 1..]; let mut after = after.trim_start(); if let Some(stripped) = after.strip_prefix('[') { if let Some(close) = stripped.find(']') { after = &stripped[close + 1..]; } else { out.push_str(&rest[index..]); return out; } } let mut after = after.trim_start(); while let Some(stripped) = after.strip_prefix('[') { let Some(close) = stripped.find(']') else { out.push_str(&rest[index..]); return out; }; after = &stripped[close + 1..]; after = after.trim_start(); } if let Some(stripped) = after.strip_prefix('{') { let Some(close) = stripped.find('}') else { out.push_str(&rest[index..]); return out; }; out.push('\u{E010}'); out.push_str("0;"); out.push_str(&strip_box_commands(&stripped[..close])); out.push('\u{E011}'); after = &stripped[close + 1..]; rest = after; continue; } out.push_str(&rest[index..]); return out; } let mut depth = 1_usize; let mut end = None; for (offset, character) in after.char_indices() { match character { '{' => depth += 1, '}' => { depth -= 1; if depth == 0 { end = Some(offset); break; } } _ => {} } } let Some(end) = end else { out.push_str(&rest[index..]); return out; }; if command == "\\underline{" { out.push_str(&strip_box_commands(&after[..end])); } else { out.push('\u{E010}'); out.push_str("0;"); out.push_str(&strip_box_commands(&after[..end])); out.push('\u{E011}'); } rest = &after[end + 1..]; } } fn expand_ensuremath_plain(text: &str) -> String { let mut out = String::new(); let mut rest = text; while let Some(index) = rest.find("\\ensuremath{") { out.push_str(&rest[..index]); let after_open = &rest[index + "\\ensuremath{".len()..]; let mut depth = 1_usize; let mut end = None; for (offset, character) in after_open.char_indices() { match character { '{' => depth += 1, '}' => { depth -= 1; if depth == 0 { end = Some(offset); break; } } _ => {} } } let Some(end) = end else { out.push_str(&rest[index..]); return out; }; out.push('$'); out.push_str(&after_open[..end]); out.push('$'); rest = &after_open[end + 1..]; } out.push_str(rest); out } fn replace_spacing_commands(text: &str) -> String { let mut out = text.to_string(); for (command, replacement) in [ ("\\enspace", "\\hspace{0.5em}"), ("\\thinspace", "\\hspace{0.16667em}"), ("\\medspace", "\\hspace{0.22222em}"), ("\\thickspace", "\\hspace{0.27778em}"), ("\\qquad", "\\hspace{2em}"), ("\\quad", "\\hspace{1em}"), ("\\;", "\\hspace{0.27778em}"), ("\\:", "\\hspace{0.22222em}"), ("\\,", "\\hspace{0.16667em}"), ] { out = out.replace(command, replacement); } out } fn expand_math_spaces(text: &str) -> String { let parts: Vec<&str> = text.split('$').collect(); let mut out = String::new(); for (index, part) in parts.iter().enumerate() { if index > 0 { out.push('$'); } if index % 2 == 0 { out.push_str(&replace_spacing_commands(part)); } else { out.push_str(part); } } out } fn expand_hspace_plain(text: &str) -> String { let mut out = String::new(); let mut rest = text; while let Some(index) = rest.find("\\hspace") { out.push_str(&rest[..index]); let after_command = &rest[index + "\\hspace".len()..]; let after_star = after_command .trim_start() .strip_prefix('*') .unwrap_or(after_command); let Some((body, used)) = braced_group(after_star.trim_start()) else { out.push_str(&rest[index..]); return out; }; out.push_str("$\\hspace{"); out.push_str(body); out.push_str("}$"); rest = &after_star.trim_start()[used..]; } out.push_str(rest); out } fn expand_hspace(text: &str) -> String { let mut out = String::new(); let mut rest = text; let mut math_mode = false; while !rest.is_empty() { if math_mode { if let Some(position) = rest.find('$') { out.push_str(&rest[..=position]); rest = &rest[position + 1..]; math_mode = false; } else { out.push_str(rest); break; } } else if let Some(position) = rest.find('$') { out.push_str(&expand_hspace_plain(&rest[..position])); out.push('$'); rest = &rest[position + 1..]; math_mode = true; } else { out.push_str(&expand_hspace_plain(rest)); break; } } out } /// Expand `\\ensuremath{...}` outside math mode into an inline math run. fn expand_ensuremath(text: &str) -> String { let mut out = String::new(); let mut rest = text; let mut math_mode = false; while !rest.is_empty() { if math_mode { if let Some(position) = rest.find('$') { out.push_str(&rest[..=position]); rest = &rest[position + 1..]; math_mode = false; } else { out.push_str(rest); break; } } else if let Some(position) = rest.find('$') { out.push_str(&expand_ensuremath_plain(&rest[..position])); out.push('$'); rest = &rest[position + 1..]; math_mode = true; } else { out.push_str(&expand_ensuremath_plain(rest)); break; } } out } /// Split text at the private-use markers that wrap `\mbox`/`\usebox` /// material: `true` means a no-break region, `false` plain text. fn split_no_break(text: &str) -> Vec<(bool, i64, String)> { let mut chunks = Vec::new(); let mut rest = text; while let Some(open) = rest.find('\u{E010}') { if open > 0 { chunks.push((false, 0, rest[..open].to_string())); } let after = &rest[open + '\u{E010}'.len_utf8()..]; if let Some(close) = after.find('\u{E011}') { let inner = &after[..close]; let (size, content) = match inner.split_once(';') { Some((digits, content)) => { (digits.parse::().unwrap_or(0), content.to_string()) } None => (0, inner.to_string()), }; chunks.push((true, size, content)); rest = &after[close + '\u{E011}'.len_utf8()..]; } else { chunks.push((false, 0, after.to_string())); return chunks; } } if !rest.is_empty() { chunks.push((false, 0, rest.to_string())); } chunks } fn inline_segments_with_boxes( text: &str, base: ParagraphFont, style: &ParagraphStyle, custom: &[(String, [u8; 3])], link_color: Option<[u8; 3]>, ) -> Option> { use texrra_tex_core::paragraph::InlineSegment; if !text.contains('\u{E010}') { return inline_math_segments(text, base, style, custom, link_color); } let mut segments = Vec::new(); for (is_box, size, piece) in split_no_break(text) { if piece.trim().is_empty() { continue; } let plain = piece.replace('~', " "); if is_box { let runs = inline_runs(&plain, base).unwrap_or_else(|| vec![(base, plain.clone())]); for (font, run) in runs { segments.push(InlineSegment::NoBreak(font, size, run)); } } else if let Some(found) = inline_math_segments(&plain, base, style, custom, link_color) { segments.extend(found); } else { let runs = inline_runs(&plain, base).unwrap_or_else(|| vec![(base, plain.clone())]); for (font, run) in runs { segments.push(InlineSegment::Text(font, run)); } } } (!segments.is_empty()).then_some(segments) } fn inline_math_segments( text: &str, base: ParagraphFont, style: &ParagraphStyle, custom: &[(String, [u8; 3])], link_color: Option<[u8; 3]>, ) -> Option> { let mut segments = Vec::new(); let mut found_math = false; let mut found_link = false; let mut found_size = false; let mut found_color = false; for part in split_hrefs(text) { match part { HrefPart::Plain(piece) => { for (color, background, frame, chunk) in split_color_runs(&piece, custom) { let chunk = chunk.replace('~', " "); let runs = inline_styled_runs(&chunk, base) .unwrap_or_else(|| vec![(base, style.font_size, 0, chunk.clone())]); for (font, size, raise, run_text) in runs { for (is_math, piece) in split_inline_math(&run_text) { if is_math { found_math = true; segments.push(texrra_tex_core::paragraph::InlineSegment::Math( parse_math(&piece), )); } else if !piece.is_empty() { let piece = strip_group_braces(&piece); if piece.is_empty() { continue; } if background || frame.is_some() { found_color = true; segments.push( texrra_tex_core::paragraph::InlineSegment::ColorBox( font, size, raise, color, frame, piece, ), ); } else if let Some(rgb) = color { found_color = true; segments.push( texrra_tex_core::paragraph::InlineSegment::Color( font, size, raise, rgb, piece, ), ); } else if raise != 0 { found_size = true; segments.push( texrra_tex_core::paragraph::InlineSegment::Script( font, size, raise, piece, ), ); } else if size == 655_360 { segments.push(texrra_tex_core::paragraph::InlineSegment::Text( font, piece, )); } else { found_size = true; segments.push( texrra_tex_core::paragraph::InlineSegment::SizedText( font, size, piece, ), ); } } } } } } HrefPart::Link(url, label) => { found_link = true; let runs = inline_runs(&label, base).unwrap_or_else(|| vec![(base, label.clone())]); for (font, text) in runs { segments.push(texrra_tex_core::paragraph::InlineSegment::Link { font, url: url.clone(), text: strip_group_braces(&text), color: link_color, }); } } } } // Math metrics are laid out at 10pt, so a paragraph that mixes math with // another base size keeps its literal delimiters instead of painting the // formula at the wrong size. Colour, link and sized runs are safe at any // base size. if found_math && style.font_size != 655_360 { return None; } (found_math || found_link || found_size || found_color).then_some(segments) } fn inline_runs(text: &str, base: ParagraphFont) -> Option> { Some( inline_sized_runs(text, base)? .into_iter() .map(|(font, _, text)| (font, strip_group_braces(&text))) .collect(), ) } fn inline_styled_runs( text: &str, base: ParagraphFont, ) -> Option> { let mut runs = Vec::new(); let mut found = false; parse_runs(text, base, 655_360, 0, &mut runs, &mut found); if !found { return None; } Some(runs) } fn inline_sized_runs(text: &str, base: ParagraphFont) -> Option> { Some( inline_styled_runs(text, base)? .into_iter() .map(|(font, size, _, text)| (font, size, text)) .collect(), ) } fn push_run( runs: &mut Vec<(ParagraphFont, i64, i64, String)>, font: ParagraphFont, size: i64, raise: i64, text: &str, ) { if text.is_empty() { return; } if let Some((last_font, last_size, last_raise, last_text)) = runs.last_mut() && *last_font == font && *last_size == size && *last_raise == raise { last_text.push_str(text); return; } runs.push((font, size, raise, text.to_string())); } /// Match a balanced `{...}` at the start of `rest`, returning its contents and /// the number of bytes consumed (including both braces). fn braced_group(rest: &str) -> Option<(&str, usize)> { if !rest.starts_with('{') { return None; } let mut depth = 0usize; for (offset, character) in rest.char_indices() { match character { '{' => depth += 1, '}' => { depth -= 1; if depth == 0 { return Some((&rest[1..offset], offset + 1)); } } _ => {} } } None } const INLINE_COMMANDS: [&str; 11] = [ "\\textbf", "\\emph", "\\textit", "\\textsl", "\\texttt", "\\textsf", "\\textmd", "\\textnormal", "\\textup", "\\textrm", "\\textsc", ]; /// Match a styled wrapper command at the start of `rest`, composing its face /// with the surrounding one (`\\emph` toggles italic inside a bold run, etc.). fn inline_wrapper(rest: &str, base: ParagraphFont) -> Option<(ParagraphFont, &str, usize)> { for command in INLINE_COMMANDS { let Some(after) = rest.strip_prefix(command) else { continue; }; if let Some((inner, length)) = braced_group(after) { let font = match command { "\\textbf" => base.bolded(), "\\emph" => base.emphasized(), "\\textit" => base.italicized(), "\\textsl" => base.slanted(), "\\texttt" => ParagraphFont::Mono, "\\textsf" => base.sans_family(), "\\textmd" => base.medium(), "\\textup" => base.upright(), "\\textrm" => base.roman_family(), "\\textsc" => base.small_caps(), "\\textnormal" => ParagraphFont::Roman, _ => base, }; return Some((font, inner, command.len() + length)); } } None } fn verb_run(rest: &str) -> Option<(String, usize)> { let after = rest.strip_prefix("\\verb")?; let after = after.strip_prefix('*').unwrap_or(after); let (start, delimiter) = after.char_indices().next()?; if delimiter.is_ascii_alphanumeric() || delimiter.is_whitespace() || delimiter == '\\' { return None; } let body_start = start + delimiter.len_utf8(); let end = after[body_start..].find(delimiter)?; let prefix = rest.len() - after.len(); Some(( after[body_start..body_start + end].to_string(), prefix + body_start + end + delimiter.len_utf8(), )) } /// Recognise a text command that stands for a printable character. /// Recognize `\MakeUppercase`/`\MakeLowercase` and their TeX spellings. fn case_run(rest: &str) -> Option<(String, usize)> { for (command, upper) in [ ("\\MakeUppercase", true), ("\\MakeLowercase", false), ("\\uppercase", true), ("\\lowercase", false), ] { let Some(after) = rest.strip_prefix(command) else { continue; }; let Some(after) = after.strip_prefix('{') else { continue; }; let mut depth = 1_usize; for (offset, character) in after.char_indices() { match character { '{' => depth += 1, '}' => { depth -= 1; if depth == 0 { let inner = &after[..offset]; let changed = if upper { inner.to_uppercase() } else { inner.to_lowercase() }; return Some((changed, command.len() + 1 + offset + 1)); } } _ => {} } } } None } fn text_symbol(rest: &str) -> Option<(&'static str, usize)> { const SYMBOLS: &[(&str, &str)] = &[ ("\\textthreequarters", "\u{be}"), ("\\textonequarter", "\u{bc}"), ("\\textonehalf", "\u{bd}"), ("\\textperthousand", "\u{2030}"), ("\\textregistered", "\u{ae}"), ("\\guillemotleft", "\u{ab}"), ("\\guillemotright", "\u{bb}"), ("\\guilsinglleft", "\u{2039}"), ("\\guilsinglright", "\u{203a}"), ("\\texttrademark", "\u{2122}"), ("\\textparagraph", "\u{b6}"), ("\\textsection", "\u{a7}"), ("\\textsterling", "\u{a3}"), ("\\textdegree", "\u{b0}"), ("\\textcurrency", "\u{a4}"), ("\\texteuro", "\u{20ac}"), ("\\textyen", "\u{a5}"), ("\\textcent", "\u{a2}"), ("\\textmu", "\u{b5}"), ("\\textquotedbl", "\\\""), ("\\textquotesingle", "'"), ("\\textunderscore", "_"), ("\\textbraceleft", "{"), ("\\textbraceright", "}"), ("\\textasciigrave", "`"), ("\\textpm", "\u{b1}"), ("\\textminus", "\u{2212}"), ("\\texttimes", "\u{d7}"), ("\\textdiv", "\u{f7}"), ("\\textperiodcentered", "\u{b7}"), ("\\textsection", "\u{a7}"), ("\\textparagraph", "\u{b6}"), ("\\textdagger", "\u{2020}"), ("\\textdaggerdbl", "\u{2021}"), ("\\dag", "\u{2020}"), ("\\ddag", "\u{2021}"), ("\\checkmark", "\u{2713}"), ("\\textbackslash", "\\"), ("\\textasciitilde", "~"), ("\\textasciicircum", "^"), ("\\textquotedblleft", "\u{201c}"), ("\\textquotedblright", "\u{201d}"), ("\\textquoteleft", "\u{2018}"), ("\\textquoteright", "\u{2019}"), ("\\textemdash", "\u{2014}"), ("\\textendash", "\u{2013}"), ("\\textgreater", ">"), ("\\textbullet", "\u{2022}"), ("\\textless", "<"), ("\\copyright", "\u{a9}"), ("\\LaTeXe", "LaTeX2e"), ("\\LaTeX", "LaTeX"), ("\\pounds", "\u{a3}"), ("\\textbar", "|"), ("\\ldots", "\u{2026}"), ("\\dots", "\u{2026}"), ("\\TeX", "TeX"), ("\\SS", "SS"), ("\\AE", "\u{c6}"), ("\\OE", "\u{152}"), ("\\AA", "\u{c5}"), ("\\DH", "\u{d0}"), ("\\TH", "\u{de}"), ("\\NG", "\u{14a}"), ("\\ae", "\u{e6}"), ("\\oe", "\u{153}"), ("\\aa", "\u{e5}"), ("\\dh", "\u{f0}"), ("\\th", "\u{fe}"), ("\\ng", "\u{14b}"), ("\\ss", "\u{df}"), ("\\oe", "\u{153}"), ("\\o", "\u{f8}"), ("\\O", "\u{d8}"), ("\\l", "\u{142}"), ("\\L", "\u{141}"), ("\\i", "\u{131}"), ("\\j", "\u{237}"), ("\\S", "\u{a7}"), ("\\P", "\u{b6}"), ]; for (command, replacement) in SYMBOLS { let Some(after) = rest.strip_prefix(command) else { continue; }; if after .chars() .next() .map_or(true, |character| !character.is_ascii_alphabetic()) { // TeX swallows the spaces that follow a control word. let trimmed = after.trim_start_matches([' ', '\t', '\n']); let skipped = after.len() - trimmed.len(); return Some((replacement, command.len() + skipped)); } } None } /// Return the precomposed letter for a base letter and a TeX accent command. fn compose_accent(base: char, accent: char) -> Option { let (bases, composed) = match accent { '\'' => ("aeiouycAEIOUYCnsz", "áéíóúýćÁÉÍÓÚÝńśź"), '`' => ("aeiouAEIOU", "àèìòùÀÈÌÒÙ"), '^' => ("aeiouAEIOU", "âêîôûÂÊÎÔÛ"), '"' => ("aeiouyAEIOUY", "äëïöüÿÄËÏÖÜŸ"), '~' => ("anoANO", "ãñõÃÑÕ"), 'c' => ("cC", "çÇ"), 'r' => ("aA", "åÅ"), 'v' => ("cszerndtlCSZERNDTL", "čšžěřňȊŽĚŘŇĎŤĽ"), '=' => ("aeiouAEIOU", "āēīōūĀĒĪŌŪ"), 'u' => ("aeiouAEIOU", "ăĕĭŏŭĂĔĬŎŬ"), '.' => ("czCZ", "ċżĊŻ"), 'H' => ("oOuU", "őűŐŰ"), _ => return None, }; let index = bases.chars().position(|candidate| candidate == base)?; composed.chars().nth(index) } /// The combining mark used when no precomposed letter exists. fn accent_mark(accent: char) -> Option { Some(match accent { '\'' => '\u{301}', '`' => '\u{300}', '^' => '\u{302}', '"' => '\u{308}', '~' => '\u{303}', 'c' => '\u{327}', 'r' => '\u{30a}', 'v' => '\u{30c}', '=' => '\u{304}', 'u' => '\u{306}', '.' => '\u{307}', 'H' => '\u{30b}', _ => return None, }) } /// Recognize a TeX accent command such as `caf\'e` or `na\"{i}ve`. fn accent_run(rest: &str) -> Option<(String, usize)> { let mut characters = rest.char_indices(); let (_, backslash) = characters.next()?; if backslash != '\\' { return None; } let (accent_offset, accent) = characters.next()?; let word_accent = accent.is_ascii_alphabetic(); if word_accent && !matches!(accent, 'c' | 'v' | 'u' | 'r' | 'H') { return None; } if accent_mark(accent).is_none() { return None; } let mut after_start = accent_offset + accent.len_utf8(); let after = &rest[after_start..]; let (after, spaced) = if word_accent { let trimmed = after.trim_start_matches([' ', '\t', '\n']); after_start += after.len() - trimmed.len(); (trimmed, trimmed.len() != after.len()) } else { (after, false) }; let (base, extra) = if let Some((group, length)) = braced_group(after) { let mut group = group.trim().chars(); let base = group.next()?; if group.next().is_some() { return None; } (base, length) } else { if word_accent && !spaced { return None; } let base = after.chars().next()?; if base.is_whitespace() || base == '{' { return None; } (base, base.len_utf8()) }; let text = match compose_accent(base, accent) { Some(composed) => composed.to_string(), None => format!("{base}{}", accent_mark(accent)?), }; Some((text, after_start + extra)) } /// Recognize `\textsuperscript{...}` and `\textsubscript{...}`. fn script_run(rest: &str) -> Option<(bool, &str, usize)> { for (command, superscript) in [("\\textsuperscript", true), ("\\textsubscript", false)] { let Some(after) = rest.strip_prefix(command) else { continue; }; let skipped = after.len() - after.trim_start().len(); let after = after.trim_start(); let (inner, length) = braced_group(after)?; return Some((superscript, inner, command.len() + skipped + length)); } None } fn parse_runs( text: &str, font: ParagraphFont, size: i64, raise: i64, runs: &mut Vec<(ParagraphFont, i64, i64, String)>, found: &mut bool, ) { let mut index = 0; while index < text.len() { let rest = &text[index..]; if let Some((body, length)) = verb_run(rest) { *found = true; push_run(runs, ParagraphFont::Mono, size, raise, &body); index += length; continue; } if let Some((superscript, inner, length)) = script_run(rest) { *found = true; let script_size = (size * 7 / 10).max(1); let shift = size * 2 / 5; let script_raise = if superscript { raise + shift } else { raise - shift }; parse_runs(inner, font, script_size, script_raise, runs, found); index += length; continue; } if let Some((declared, declared_size, body)) = nfss_font_with_size(rest, font) { *found = true; parse_runs( &body, declared, declared_size.unwrap_or(size), raise, runs, found, ); return; } if let Some((inner, length)) = braced_group(rest) { let (inner_font, inner_size, inner_text) = match nfss_font_with_size(inner, font) { Some((declared, declared_size, body)) => { (declared, declared_size.unwrap_or(size), body) } None => (font, size, inner.to_string()), }; if nfss_font_with_size(inner, font).is_some() { *found = true; } parse_runs(&inner_text, inner_font, inner_size, raise, runs, found); index += length; continue; } if let Some((wrapper_font, inner, length)) = inline_wrapper(rest, font) { *found = true; parse_runs(inner, wrapper_font, size, raise, runs, found); index += length; continue; } if let Some((accent, length)) = accent_run(rest) { *found = true; push_run(runs, font, size, raise, &accent); index += length; continue; } if let Some((changed, length)) = case_run(rest) { *found = true; push_run(runs, font, size, raise, &changed); index += length; continue; } if let Some((symbol, length)) = text_symbol(rest) { *found = true; push_run(runs, font, size, raise, symbol); index += length; continue; } if rest.starts_with('\\') { let step = rest .char_indices() .skip(1) .find(|(_, character)| !character.is_ascii_alphabetic()) .map(|(offset, _)| offset.max(1)) .unwrap_or(rest.len()); push_run(runs, font, size, raise, &rest[..step]); index += step; continue; } let step = rest .char_indices() .skip(1) .find(|(_, character)| *character == '{' || *character == '\\') .map(|(offset, _)| offset) .unwrap_or(rest.len()); push_run(runs, font, size, raise, &rest[..step]); index += step; } } /// Recognize a `\section`-family command: level, starred, and title. fn heading_command(raw: &str) -> Option<(u8, bool, String, Option)> { let raw = raw.trim(); for (command, level) in [ ("\\chapter", 0u8), ("\\section", 1u8), ("\\subsection", 2), ("\\subsubsection", 3), ("\\paragraph", 4), ("\\subparagraph", 5), ] { let Some(rest) = raw.strip_prefix(command) else { continue; }; let (rest, starred) = match rest.strip_prefix('*') { Some(rest) => (rest, true), None => (rest, false), }; let rest = rest.trim_start(); // Keep the optional short title for the table of contents. let (rest, short) = match rest.strip_prefix('[') { Some(after) => match after.split_once(']') { Some((short, rest)) => (rest.trim_start(), Some(short.trim().to_string())), None => (rest, None), }, None => (rest, None), }; let (body, _) = braced_group(rest)?; return Some((level, starred, body.trim().to_string(), short)); } None } /// Rows of an amsmath `split` environment, used inside one numbered equation. fn split_body_rows(text: &str) -> Option> { let inner = text .trim() .strip_prefix("\\begin{split}")? .strip_suffix("\\end{split}")?; Some( inner .split("\\\\") .map(str::trim) .filter(|row| !row.is_empty()) .map(str::to_string) .collect(), ) } fn parse_paragraph(raw: &str) -> SourceParagraph { if let Some(inner) = raw .strip_prefix("\\begin{displaymath}") .and_then(|text| text.strip_suffix("\\end{displaymath}")) { return parse_paragraph(&format!("$$\n{}\n$$", inner)); } for (environment, starred) in [("multline", false), ("multline*", true)] { let begin = format!("\\begin{{{environment}}}"); let finish = format!("\\end{{{environment}}}"); let Some(inner) = raw .strip_prefix(&begin) .and_then(|text| text.strip_suffix(&finish)) else { continue; }; let lines: Vec<&str> = inner .split("\\\\") .map(str::trim) .filter(|row| !row.is_empty()) .collect(); let rows: Vec = lines .iter() .enumerate() .map(|(index, row)| EquationRow { text: row.to_string(), number: if !starred && index + 1 == lines.len() { Some(0) } else { None }, tag: None, }) .collect(); let mut block = parse_paragraph(inner.trim()); block.equation_rows = rows; block.multline = true; block.align_centered = false; block.math = true; return block; } for (environment, starred) in [("alignat", false), ("alignat*", true)] { let begin = format!("\\begin{{{environment}}}"); let finish = format!("\\end{{{environment}}}"); let Some(rest) = raw.strip_prefix(&begin) else { continue; }; let rest = rest.trim_start(); let rest = if let Some(after) = rest.strip_prefix('{') { let Some(close) = after.find('}') else { continue; }; &after[close + 1..] } else { rest }; let Some(inner) = rest.strip_suffix(&finish) else { continue; }; let rows: Vec = inner .split("\\\\") .map(str::trim) .filter(|row| !row.is_empty()) .map(|row| EquationRow { text: row.to_string(), number: if starred { None } else { Some(0) }, tag: None, }) .collect(); let mut block = parse_paragraph(inner.trim()); block.equation_rows = rows; block.align_centered = false; block.math = true; return block; } for (environment, starred, centered) in [ ("align", false, false), ("align*", true, false), ("gather", false, true), ("gather*", true, true), ] { let begin = format!("\\begin{{{environment}}}"); let finish = format!("\\end{{{environment}}}"); if let Some(inner) = raw .strip_prefix(&begin) .and_then(|text| text.strip_suffix(&finish)) { let rows: Vec = inner .split("\\\\") .map(str::trim) .filter(|row| !row.is_empty()) .map(|row| EquationRow { text: row.to_string(), number: if starred { None } else { Some(0) }, tag: None, }) .collect(); return SourceParagraph { width: None, multline: false, list_depth: None, list_label: 0, right_skip: 0, text: inner.trim().to_string(), font: ParagraphFont::Roman, line_height: 12, math: true, left_skip: 0, centered: false, right_aligned: false, space_before: 0, space_stretch: 0, space_shrink: 0, page_break: false, equation_number: None, equation_tag: None, equation_rows: rows, align_centered: centered, heading_level: None, heading_starred: false, heading_number: None, heading_short: None, footnotes: Vec::new(), theorem: None, float: None, font_size: None, }; } } if let Some((font, font_size, body)) = nfss_font_with_size(raw, ParagraphFont::Roman) { return SourceParagraph { width: None, multline: false, list_depth: None, list_label: 0, right_skip: 0, text: body, font, font_size, line_height: 12, math: false, left_skip: 0, centered: false, right_aligned: false, space_before: 0, space_stretch: 0, space_shrink: 0, page_break: false, equation_number: None, equation_tag: None, equation_rows: Vec::new(), align_centered: false, heading_level: None, heading_starred: false, heading_number: None, heading_short: None, footnotes: Vec::new(), theorem: None, float: None, }; } if let Some(inner) = raw .strip_prefix("\\begin{equation}") .and_then(|text| text.strip_suffix("\\end{equation}")) { return SourceParagraph { width: None, multline: false, list_depth: None, list_label: 0, right_skip: 0, text: inner.trim().to_string(), font: ParagraphFont::Roman, line_height: 12, math: true, left_skip: 0, centered: false, right_aligned: false, space_before: 0, space_stretch: 0, space_shrink: 0, page_break: false, equation_number: Some(0), equation_tag: None, equation_rows: Vec::new(), align_centered: false, heading_level: None, heading_starred: false, heading_number: None, heading_short: None, footnotes: Vec::new(), theorem: None, float: None, font_size: None, }; } if let Some(inner) = raw .strip_prefix("\\begin{equation*}") .and_then(|text| text.strip_suffix("\\end{equation*}")) { return SourceParagraph { width: None, multline: false, list_depth: None, list_label: 0, right_skip: 0, text: inner.trim().to_string(), font: ParagraphFont::Roman, line_height: 12, math: true, left_skip: 0, centered: false, right_aligned: false, space_before: 0, space_stretch: 0, space_shrink: 0, page_break: false, equation_number: None, equation_tag: None, equation_rows: Vec::new(), align_centered: false, heading_level: None, heading_starred: false, heading_number: None, heading_short: None, footnotes: Vec::new(), theorem: None, float: None, font_size: None, }; } if let Some(math) = raw .strip_prefix("$$") .and_then(|text| text.strip_suffix("$$")) .or_else(|| { raw.strip_prefix("\\[") .and_then(|text| text.strip_suffix("\\]")) }) { return SourceParagraph { width: None, multline: false, list_depth: None, list_label: 0, right_skip: 0, text: math.trim().to_string(), font: ParagraphFont::Roman, line_height: 12, math: true, left_skip: 0, centered: false, right_aligned: false, space_before: 0, space_stretch: 0, space_shrink: 0, page_break: false, equation_number: None, equation_tag: None, equation_rows: Vec::new(), align_centered: false, heading_level: None, heading_starred: false, heading_number: None, heading_short: None, footnotes: Vec::new(), theorem: None, float: None, font_size: None, }; } if let Some((level, starred, title, short)) = heading_command(raw) { return SourceParagraph { width: None, multline: false, list_depth: None, list_label: 0, right_skip: 0, text: title, font: ParagraphFont::Bold, line_height: if level == 0 { 24 } else 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 { 0 => 24 * SCALE, 1 => 12 * SCALE, 2 => 10 * SCALE, 3 => 8 * SCALE, 4 => 6 * SCALE, _ => 4 * SCALE, }, space_stretch: 4 * SCALE, space_shrink: SCALE, page_break: false, equation_number: None, equation_tag: None, equation_rows: Vec::new(), align_centered: false, heading_level: Some(level), heading_starred: starred, heading_number: None, heading_short: short, footnotes: Vec::new(), theorem: None, float: None, font_size: None, }; } let candidates = [ ("\\textbf", ParagraphFont::Bold, 12), ("\\textbf", ParagraphFont::Bold, 12), ("\\emph", ParagraphFont::Italic, 12), ("\\texttt", ParagraphFont::Mono, 12), ("\\textsf", ParagraphFont::Sans, 12), ]; for (command, font, line_height) in candidates { if let Some(text) = command_body(raw, command) { return SourceParagraph { width: None, multline: false, list_depth: None, list_label: 0, right_skip: 0, text: text.to_string(), font, line_height, math: false, left_skip: 0, centered: false, right_aligned: false, space_before: 0, space_stretch: 0, space_shrink: 0, page_break: false, equation_number: None, equation_tag: None, equation_rows: Vec::new(), align_centered: false, heading_level: None, heading_starred: false, heading_number: None, heading_short: None, footnotes: Vec::new(), theorem: None, float: None, font_size: None, }; } } SourceParagraph { width: None, multline: false, list_depth: None, list_label: 0, right_skip: 0, text: raw.to_string(), font: ParagraphFont::Roman, line_height: 12, math: false, left_skip: 0, centered: false, right_aligned: false, space_before: 0, space_stretch: 0, space_shrink: 0, page_break: false, equation_number: None, equation_tag: None, equation_rows: Vec::new(), align_centered: false, heading_level: None, heading_starred: false, heading_number: None, heading_short: None, footnotes: Vec::new(), theorem: None, float: None, font_size: None, } } /// Wrap a row cell with empty Ord atoms so relation spacing shows up at the /// column boundaries, the way amsmath aligns relation columns. fn aligned_cell(source: &str) -> MathAtom { let mut atoms = vec![MathAtom::Row(Vec::new())]; match parse_math(source.trim()) { MathAtom::Row(inner) => atoms.extend(inner), other => atoms.push(other), } atoms.push(MathAtom::Row(Vec::new())); MathAtom::Row(atoms) } /// The article class title size for a base size. fn title_size(base_font_size: i64) -> f64 { match base_font_size / SCALE { 12 => 24.88, 11 => 20.74, _ => 17.28, } } /// The article class `\large` size for a base size. fn title_large_size(base_font_size: i64) -> f64 { match base_font_size / SCALE { 12 => 14.4, _ => 12.0, } } /// Remove `\thanks{...}` groups and join multiple authors set with `\and`. /// Rewrite `\thanks{...}` notes as footnotes so they become page insertions /// instead of disappearing with the title block. fn thanks_to_footnotes(text: &str) -> String { let mut out = String::new(); let mut rest = text; loop { let Some(index) = rest.find("\\thanks") else { out.push_str(rest); break; }; out.push_str(&rest[..index]); let after = &rest[index + "\\thanks".len()..]; let trimmed = after.trim_start(); let Some((inner, consumed)) = braced_group(trimmed) else { out.push_str("\\thanks"); rest = after; continue; }; out.push_str("\\footnote{"); out.push_str(&inner); out.push('}'); rest = &trimmed[consumed..]; } out } /// The LaTeX `\today` date in article form. Route-D has no time zone /// database, so the date comes from the UTC Unix clock. fn today_string() -> String { const MONTHS: [&str; 12] = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", ]; let days = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|duration| (duration.as_secs() / 86_400) as i64) .unwrap_or(0); let (year, month, day) = civil_from_days(days); format!("{} {}, {}", MONTHS[(month - 1) as usize], day, year) } fn civil_from_days(days: i64) -> (i64, u32, u32) { let z = days + 719_468; let era = if z >= 0 { z } else { z - 146_096 } / 146_097; let day_of_era = z - era * 146_097; let year_of_era = (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365; let year = year_of_era + era * 400; let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100); let month_index = (5 * day_of_year + 2) / 153; let day = day_of_year - (153 * month_index + 2) / 5 + 1; let month = if month_index < 10 { month_index + 3 } else { month_index - 9 }; ( if month <= 2 { year + 1 } else { year }, month as u32, day as u32, ) } fn expand_today(text: &str, today: &str) -> String { text.replace("\\today", today) } fn clean_title_value(text: &str) -> String { let mut out = String::new(); let mut rest = text; loop { let Some(index) = rest.find("\\thanks") else { out.push_str(rest); break; }; out.push_str(&rest[..index]); let after = rest[index + "\\thanks".len()..].trim_start(); let Some(group) = after.strip_prefix('{') else { out.push_str("\\thanks"); rest = &rest[index + "\\thanks".len()..]; continue; }; let mut depth = 1usize; let mut end = None; for (offset, character) in group.char_indices() { match character { '{' => depth += 1, '}' => { depth -= 1; if depth == 0 { end = Some(offset + 1); break; } } _ => {} } } match end { Some(end) => rest = &group[end..], None => { out.push_str("\\thanks"); rest = &rest[index + "\\thanks".len()..]; } } } let joined = out.replace("\\and", ", "); let mut normalized = joined.split_whitespace().collect::>().join(" "); normalized = normalized.replace(" ,", ","); normalized = scrub_title_metadata(&normalized); normalized.trim().to_string() } /// Strip author/title metadata commands that have no text of their own. fn scrub_title_metadata(text: &str) -> String { let text = href_to_label(text); let mut text = text; for command in [ "\\emph", "\\textit", "\\textbf", "\\textsc", "\\textsf", "\\textrm", "\\textup", "\\texttt", "\\textmd", "\\textnormal", "\\url", "\\mbox", ] { text = replace_command_group(&text, command); } for command in ["\\includegraphics", "\\hspace", "\\vspace", "\\rule"] { text = drop_command_group(&text, command); } for declaration in [ "\\scshape", "\\footnotesize", "\\small", "\\normalsize", "\\bfseries", "\\itshape", "\\centering", "\\relax", ] { text = text.replace(declaration, ""); } text.replace("\\\\", " ") .replace("\\AND", ", ") .replace("\\And", ", ") .replace("\\and", ", ") } /// `\href{url}{label}` keeps the visible label. fn href_to_label(text: &str) -> String { let mut out = String::new(); let mut rest = text; while let Some(index) = rest.find("\\href") { out.push_str(&rest[..index]); let after = &rest[index + "\\href".len()..]; let trimmed = after.trim_start(); let Some((_url, used)) = braced_group(trimmed) else { rest = after; continue; }; let tail = trimmed[used..].trim_start(); if let Some((label, label_used)) = braced_group(tail) { out.push_str(&label); rest = &tail[label_used..]; } else { rest = tail; } } out.push_str(rest); out } /// `\command{body}` becomes `body`. fn replace_command_group(text: &str, command: &str) -> String { let mut out = String::new(); let mut rest = text; while let Some(index) = rest.find(command) { let after = &rest[index + command.len()..]; if after.starts_with(|character: char| character.is_ascii_alphabetic()) { out.push_str(&rest[..index + command.len()]); rest = after; continue; } out.push_str(&rest[..index]); let trimmed = after.trim_start(); if let Some((body, used)) = braced_group(trimmed) { out.push_str(&body); rest = &trimmed[used..]; } else { rest = after; } } out.push_str(rest); out } /// Drop `\command[options]{body}`. fn drop_command_group(text: &str, command: &str) -> String { let mut out = String::new(); let mut rest = text; while let Some(index) = rest.find(command) { let after = &rest[index + command.len()..]; if after.starts_with(|character: char| character.is_ascii_alphabetic()) { out.push_str(&rest[..index + command.len()]); rest = after; continue; } out.push_str(&rest[..index]); let mut trimmed = after.trim_start(); if let Some(options) = trimmed.strip_prefix('[') && let Some((_options, tail)) = options.split_once(']') { trimmed = tail.trim_start(); } if let Some((_body, used)) = braced_group(trimmed) { rest = &trimmed[used..]; } else { rest = after; } } out.push_str(rest); out } fn title_block(text: String, size: f64, space_before: i64) -> SourceParagraph { SourceParagraph { width: None, multline: false, list_depth: None, list_label: 0, right_skip: 0, text, font: ParagraphFont::Roman, line_height: 12, math: false, left_skip: 0, centered: true, right_aligned: false, space_before, space_stretch: 0, space_shrink: 0, page_break: false, equation_number: None, equation_tag: None, equation_rows: Vec::new(), align_centered: false, heading_level: None, heading_starred: false, heading_number: None, heading_short: None, footnotes: Vec::new(), theorem: None, float: None, font_size: Some((size * SCALE as f64) as i64), } } /// Expand `\maketitle` into the centered title block that article.cls sets. /// Rename the bold `Abstract` heading emitted for the abstract environment. fn rename_abstract_heading(paragraphs: &mut [SourceParagraph], name: &str) { for paragraph in paragraphs { if paragraph.font == ParagraphFont::Bold && !paragraph.math && paragraph.heading_level.is_none() && paragraph.text.trim() == "Abstract" { paragraph.text = name.to_string(); break; } } } fn expand_maketitle(blocks: &[SourceParagraph], geometry: &PageGeometry) -> Vec { 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, secnumdepth: u32, section_start: u32, chaptered: bool, ) -> Vec<(String, String)> { let mut counters = [section_start, 0u32, 0, 0, 0]; let mut chapter = 0u32; let mut chapter_number: Option = None; let mut appendix = false; let mut labels = Vec::new(); let mut last_number: Option = None; let mut index = 0; while index < blocks.len() { if blocks[index].text.trim() == "\\appendix" { appendix = true; counters = [0; 5]; chapter = 0; chapter_number = None; 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; } if level == 0 { chapter += 1; counters = [0; 5]; let number = if appendix { appendix_letter(chapter) } else { chapter.to_string() }; chapter_number = Some(number.clone()); 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; 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 = match (chaptered, chapter_number.as_ref()) { (true, Some(chapter)) => { let mut parts = vec![chapter.clone()]; for depth in 0..level as usize { parts.push(counters[depth].to_string()); } parts.join(".") } _ if level == 1 => first, _ => { 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 { 0 => 200, 1 => 144, 2 => 120, _ => 100, }; base.saturating_mul(percent) / 100 } /// Pull `\footnote{...}` bodies out of a paragraph, leaving a numbered /// reference in the running text. Footnote numbers run across the document. fn number_footnotes(paragraphs: &mut [SourceParagraph]) { let mut number = 0u32; for paragraph in paragraphs { let source = paragraph.text.clone(); let mut text = String::with_capacity(source.len()); let mut rest = source.as_str(); while let Some(index) = rest.find("\\footnote") { text.push_str(&rest[..index]); let after = rest[index + "\\footnote".len()..].trim_start(); let Some((body, consumed)) = braced_group(after) else { text.push_str(&rest[index..]); rest = ""; break; }; number += 1; let _ = write!(text, " ({number})"); paragraph.footnotes.push((number, body.trim().to_string())); rest = &after[consumed..]; } text.push_str(rest); paragraph.text = text; } } /// Number theorem-like headings and return their label targets. fn number_theorems( paragraphs: &mut [SourceParagraph], definitions: &[TheoremDefinition], starts: &[(String, u32)], ) -> Vec<(String, String)> { let mut counters: Vec<(String, u32)> = Vec::new(); let mut labels = Vec::new(); let mut section: Option = None; for paragraph in paragraphs { if paragraph.heading_level.is_some() { section = paragraph.heading_number.clone(); } let Some(theorem) = paragraph.theorem.as_mut() else { continue; }; let definition = definitions .iter() .find(|definition| definition.name == theorem.name); if !theorem.starred && theorem.name != "proof" { let counter = definition .and_then(|definition| definition.shared.clone()) .unwrap_or_else(|| theorem.name.clone()); let value = match counters.iter_mut().find(|(name, _)| *name == counter) { Some((_, count)) => { *count += 1; *count } None => { let start = starts .iter() .filter(|(name, _)| *name == counter) .last() .map(|(_, value)| *value) .unwrap_or(0); counters.push((counter, start + 1)); start + 1 } }; let within_section = definition.and_then(|definition| definition.within.as_deref()) == Some("section"); theorem.number = Some(if within_section { match §ion { Some(section) => format!("{section}.{value}"), None => value.to_string(), } } else { value.to_string() }); } let display = theorem.display.clone(); let number = theorem .number .as_ref() .map(|number| format!(" {number}")) .unwrap_or_default(); let title = theorem .title .as_ref() .map(|title| format!(" ({title})")) .unwrap_or_default(); paragraph.text = format!("{display}{number}{title}."); let number = theorem.number.clone(); if let Some(number) = number { for label in theorem.labels.drain(..) { labels.push((label, number.clone())); } } else { theorem.labels.clear(); } } labels } /// Number float captions and return their label targets. fn number_floats( paragraphs: &mut [SourceParagraph], figure_name: &str, table_name: &str, figure_start: u32, table_start: u32, ) -> Vec<(String, String)> { let mut figures = figure_start; let mut tables = table_start; let mut labels = Vec::new(); for paragraph in paragraphs { let Some(spec) = paragraph.float.as_mut() else { continue; }; let Some(caption) = spec.caption.as_mut() else { continue; }; let found = take_labels(caption); if spec.caption_starred { *caption = caption.trim().to_string(); continue; } let number = match spec.kind { FloatKind::Figure => { figures += 1; figures } FloatKind::Table => { tables += 1; tables } }; let prefix = spec.kind.caption_prefix(figure_name, table_name); *caption = format!("{prefix} {number}: {}", caption.trim()); if let Some(short) = &spec.caption_short { spec.list_caption = Some(format!("{prefix} {number}: {short}")); } for label in found { labels.push((label, number.to_string())); } } labels } /// Append `thebibliography` entries as numbered paragraphs. fn bibliography_heading(text: &str) -> SourceParagraph { SourceParagraph { width: None, multline: false, list_depth: None, list_label: 0, right_skip: 0, text: text.to_string(), page_break: false, centered: false, right_aligned: false, font: ParagraphFont::Bold, line_height: 14, math: false, left_skip: 0, space_before: 12 * SCALE, space_stretch: 2 * SCALE, space_shrink: 0, equation_number: None, equation_tag: None, equation_rows: Vec::new(), align_centered: false, heading_level: None, heading_starred: false, heading_number: None, heading_short: None, footnotes: Vec::new(), theorem: None, float: None, font_size: None, } } fn append_bibliography( paragraphs: &mut Vec, bibliography: &[(String, String)], heading: &str, ) { if bibliography.is_empty() { return; } paragraphs.push(bibliography_heading(heading)); for (index, (_, entry)) in bibliography.iter().enumerate() { paragraphs.push(SourceParagraph { width: None, multline: false, list_depth: None, list_label: 0, right_skip: 0, text: format!("[{}] {entry}", index + 1), page_break: false, centered: false, right_aligned: false, font: ParagraphFont::Roman, line_height: 12, math: false, left_skip: 0, space_before: if index == 0 { 4 * SCALE } else { 4 * SCALE }, space_stretch: 2 * SCALE, space_shrink: 0, equation_number: None, equation_tag: None, equation_rows: Vec::new(), align_centered: false, heading_level: None, heading_starred: false, heading_number: None, heading_short: None, footnotes: Vec::new(), theorem: None, float: None, font_size: None, }); } } fn expand_toc( paragraphs: &mut Vec, tocdepth: u32, contents_name: &str, chaptered: bool, ) { let entries: Vec<(u8, String, String)> = paragraphs .iter() .filter(|paragraph| { paragraph .heading_level .is_some_and(|level| level as u32 <= tocdepth) && !paragraph.heading_starred && paragraph.heading_number.is_some() }) .map(|paragraph| { let number = paragraph.heading_number.clone().unwrap_or_default(); let text = match (¶graph.heading_short, ¶graph.heading_number) { (Some(short), Some(number)) => format!("{number} {short}"), _ => paragraph.text.clone(), }; (paragraph.heading_level.unwrap_or(1), number, text) }) .collect(); let Some(position) = paragraphs .iter() .position(|paragraph| paragraph.text.trim() == "\\texrratoc") else { return; }; let space_before = paragraphs[position].space_before; let mut toc = Vec::with_capacity(entries.len() + 1); if entries.is_empty() { paragraphs.remove(position); return; } let mut heading = bibliography_heading(contents_name); heading.space_before = space_before; toc.push(heading); for (level, number, text) in entries.iter() { toc.push(SourceParagraph { width: None, multline: false, list_depth: None, list_label: 0, right_skip: 0, text: format!("\\texrratocpage{{{number}}} {text}"), page_break: false, centered: false, right_aligned: false, font: ParagraphFont::Roman, line_height: 12, math: false, left_skip: if chaptered { 12 * (*level as i64) } else { 12 * (level.saturating_sub(1) as i64) }, space_before: 2 * SCALE, space_stretch: 0, space_shrink: 0, equation_number: None, equation_tag: None, equation_rows: Vec::new(), align_centered: false, heading_level: None, heading_starred: false, heading_number: None, heading_short: None, font_size: None, footnotes: Vec::new(), float: None, theorem: None, }); } paragraphs.splice(position..=position, toc); } fn expand_float_lists( paragraphs: &mut Vec, figure_heading: &str, table_heading: &str, ) { let figures: Vec<(String, String)> = paragraphs .iter() .filter_map(|paragraph| match ¶graph.float { Some(spec) if spec.kind == FloatKind::Figure => { let caption = spec.list_caption.clone().or_else(|| spec.caption.clone())?; let prefix = caption .split_once(':') .map_or("Figure", |(prefix, _)| prefix); Some((prefix.trim().to_string(), caption)) } _ => None, }) .collect(); let tables: Vec<(String, String)> = paragraphs .iter() .filter_map(|paragraph| match ¶graph.float { Some(spec) if spec.kind == FloatKind::Table => { let caption = spec.list_caption.clone().or_else(|| spec.caption.clone())?; let prefix = caption .split_once(':') .map_or("Table", |(prefix, _)| prefix); Some((prefix.trim().to_string(), caption)) } _ => None, }) .collect(); for (marker, heading, entries) in [ ("\\texrralof", figure_heading, figures), ("\\texrralot", table_heading, tables), ] { let Some(position) = paragraphs .iter() .position(|paragraph| paragraph.text.trim() == marker) else { continue; }; let space_before = paragraphs[position].space_before; if entries.is_empty() { paragraphs.remove(position); continue; } let mut list = Vec::with_capacity(entries.len() + 1); let mut heading = bibliography_heading(heading); heading.space_before = space_before; list.push(heading); for (prefix, text) in entries.iter() { list.push(SourceParagraph { width: None, multline: false, list_depth: None, list_label: 0, right_skip: 0, text: format!("\\texrrafloatpage{{{prefix}}} {text}"), page_break: false, centered: false, right_aligned: false, font: ParagraphFont::Roman, line_height: 12, math: false, left_skip: 0, space_before: 2 * SCALE, space_stretch: 0, space_shrink: 0, equation_number: None, equation_tag: None, equation_rows: Vec::new(), align_centered: false, heading_level: None, heading_starred: false, heading_number: None, heading_short: None, font_size: None, footnotes: Vec::new(), float: None, theorem: None, }); } paragraphs.splice(position..=position, list); } } /// Parse a leading `\color{name}` switch and return the name plus the rest. fn color_switch(text: &str) -> Option<(String, String)> { let trimmed = text.trim_start(); let rest = trimmed.strip_prefix("\\color")?; let rest = rest.trim_start(); if rest.starts_with('{') { let (name, used) = braced_group(rest)?; let after = rest[used..] .trim_start_matches([' ', '\t', '\n']) .to_string(); return Some((name.trim().to_string(), after)); } None } /// LaTeX's article-class display skips for 10pt, 11pt and 12pt. fn display_skip_defaults(base_font_size: i64) -> ((i64, i64, i64), (i64, i64, i64)) { const PT: i64 = 65_536; if base_font_size >= 12 * PT { ((12 * PT, 3 * PT, 7 * PT), (12 * PT, 3 * PT, 7 * PT)) } else if base_font_size >= 11 * PT { ((11 * PT, 3 * PT, 6 * PT), (11 * PT, 3 * PT, 6 * PT)) } else { ((10 * PT, 2 * PT, 5 * PT), (10 * PT, 2 * PT, 5 * PT)) } } fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Document { build_document_with_labels(paragraphs, geometry, &mut HashMap::new(), &mut Vec::new()) } fn build_document_with_labels( paragraphs: &[SourceParagraph], geometry: &PageGeometry, label_units: &mut HashMap, outline_units: &mut Vec<(String, u8, u64)>, ) -> Document { let mut paragraphs = expand_maketitle(paragraphs, geometry); if let Some(name) = geometry.abstract_name.as_deref() { rename_abstract_heading(&mut paragraphs, name); } let chaptered = geometry .document_class .as_deref() .is_some_and(|name| matches!(name, "report" | "book")); let section_labels = number_sections( &mut paragraphs, geometry.secnumdepth.unwrap_or(3), geometry_counter(geometry, "section"), chaptered, ); let label_numbers = section_labels.clone(); expand_toc( &mut paragraphs, geometry.tocdepth.unwrap_or(3), geometry.contents_name.as_deref().unwrap_or("Contents"), chaptered, ); let mut references = section_labels; references.extend(number_theorems( &mut paragraphs, &geometry.theorem_definitions, &geometry.counters, )); references.extend(number_floats( &mut paragraphs, geometry.figure_name.as_deref().unwrap_or("Figure"), geometry.table_name.as_deref().unwrap_or("Table"), geometry_counter(geometry, "figure"), geometry_counter(geometry, "table"), )); expand_float_lists( &mut paragraphs, geometry .list_figure_name .as_deref() .unwrap_or("List of Figures"), geometry .list_table_name .as_deref() .unwrap_or("List of Tables"), ); resolve_section_refs(&mut paragraphs, &references); number_footnotes(&mut paragraphs); resolve_citations(&mut paragraphs, &geometry.bibliography); append_bibliography( &mut paragraphs, &geometry.bibliography, geometry.ref_name.as_deref().unwrap_or("References"), ); // Table-of-contents entries carry an invisible marker naming the heading // whose page number they show; resolve it once the units exist. let mut toc_targets: Vec<(usize, String)> = Vec::new(); let mut float_targets: Vec<(usize, String)> = Vec::new(); for (index, paragraph) in paragraphs.iter_mut().enumerate() { if let Some(rest) = paragraph.text.trim_start().strip_prefix("\\texrratocpage{") { if let Some((number, tail)) = rest.split_once('}') { let number = number.trim().to_string(); paragraph.text = tail.trim_start().to_string(); toc_targets.push((index, number)); } } else if let Some(rest) = paragraph .text .trim_start() .strip_prefix("\\texrrafloatpage{") { if let Some((number, tail)) = rest.split_once('}') { let number = number.trim().to_string(); paragraph.text = tail.trim_start().to_string(); float_targets.push((index, number)); } } } let line_width = geometry.line_width.unwrap_or(480 * SCALE); let mut base_units: Vec = paragraphs .iter() .enumerate() .map(|(index, paragraph)| { if let Some(spec) = ¶graph.float { let width = line_width; let mut content = Vec::new(); let caption_unit = spec.caption.as_ref().map(|caption| { let style = ParagraphStyle { line_width: width, centered: true, par_indent: 0, font_size: 9 * SCALE, baselineskip: 11 * SCALE, line_height: 11 * SCALE, ..ParagraphStyle::default() }; Unit::paragraph_with_style_and_face( index as u64, caption.clone(), style, ParagraphFont::Roman, ) }); if spec.kind == FloatKind::Table { if let Some(caption) = &caption_unit { content.extend(caption.items.clone()); } } let text_height = geometry .textheight .or(geometry.vsize) .unwrap_or(550 * SCALE); let resolve = |length: &ImageLength| length.resolve(width, text_height); let mut placed_image = false; if let Some(path) = &spec.image { if let Some(image) = geometry.images.get(path) { // Images have no intrinsic TeX resolution, so treat one // pixel as one point at 100%. let natural_width = (image.width as i64).max(1) * SCALE; let natural_height = (image.height as i64).max(1) * SCALE; let scale = spec.scale.unwrap_or(100).max(1); let mut image_width = spec .width .as_ref() .map(resolve) .unwrap_or(natural_width.saturating_mul(scale) / 100); let mut image_height = spec.height.as_ref().map(resolve).unwrap_or_else(|| { if spec.width.is_some() || spec.scale.is_some() { (image_width * natural_height / natural_width).max(1) } else { natural_height.saturating_mul(scale) / 100 } }); if spec.keep_aspectratio && spec.width.is_some() && spec.height.is_some() { let scale = (image_width as f64 / natural_width as f64) .min(image_height as f64 / natural_height as f64); image_width = (natural_width as f64 * scale).round() as i64; image_height = (natural_height as f64 * scale).round() as i64; } content.push(VerticalItem::Image { width: image_width.max(1), height: image_height.max(1), image: image.clone(), }); placed_image = true; } } if !placed_image && (spec.height.is_some() || spec.width.is_some()) { let rule_width = spec.width.as_ref().map(resolve).unwrap_or(width); let rule_height = spec.height.as_ref().map(resolve).unwrap_or(rule_width / 2); content.push(VerticalItem::Rule { width: rule_width, height: rule_height, }); } if let Some(table) = spec.table { if let Some((template, source, target)) = geometry.tabular.get(table) { let table_unit = tabular_unit(&geometry, index as u64, template, source, *target); content.extend(table_unit.items); } } if spec.kind == FloatKind::Figure { if let Some(caption) = &caption_unit { content.extend(caption.items.clone()); } } let mut unit = Unit::float_with_content(index as u64, spec.placement, width, 0, content); unit.space_before = paragraph.space_before; unit.space_stretch = paragraph.space_stretch; unit.space_shrink = paragraph.space_shrink; return unit; } if let Some(table) = table_reference(¶graph.text) { if let Some((template, source, target)) = geometry.tabular.get(table) { let mut unit = tabular_unit(&geometry, index as u64, template, source, *target); unit.space_before = paragraph.space_before; unit.space_stretch = paragraph.space_stretch; unit.space_shrink = paragraph.space_shrink; return unit; } } if paragraph.math { let font = Cmr10Metrics::Math; let atom = if paragraph.multline { let rows: Vec = paragraph .equation_rows .iter() .map(|row| parse_math(&row.text)) .collect(); let tag = paragraph.equation_rows.last().and_then(|row| { row.tag .clone() .or_else(|| row.number.map(|number| format!("({number})"))) }); MathAtom::Multline { rows, tag } } else if let Some(split_rows) = split_body_rows(¶graph.text) { let rows: Vec = split_rows .iter() .map(|row| { let cells: Vec = row.split('&').map(aligned_cell).collect(); AlignedRow::new(cells, None) }) .collect(); MathAtom::Aligned { rows, centered: false, } } else if paragraph.equation_rows.is_empty() { parse_math(¶graph.text) } else { let rows: Vec = paragraph .equation_rows .iter() .map(|row| { let cells: Vec = if paragraph.align_centered { vec![aligned_cell(&row.text)] } else { row.text.split('&').map(aligned_cell).collect() }; let tag = row .tag .clone() .or_else(|| row.number.map(|number| format!("({number})"))); AlignedRow::new(cells, tag) }) .collect(); MathAtom::Aligned { rows, centered: paragraph.align_centered, } }; let tag = paragraph.equation_tag.clone().or_else(|| { paragraph .equation_number .map(|number| format!("({number})")) }); let atom = match tag { Some(tag) => MathAtom::Tagged { body: Box::new(atom), tag, }, None => atom, }; let lines = split_math_lines(&atom, &font, line_width); let mut unit = Unit::math_lines(index as u64, &lines, &font); unit.space_before = paragraph.space_before; unit.space_stretch = paragraph.space_stretch; unit.space_shrink = paragraph.space_shrink; return unit; } let mut text = paragraph.text.clone(); let no_indent = text.trim_start().starts_with("\\noindent"); if no_indent { text = text .trim_start() .trim_start_matches("\\noindent") .trim_start() .to_string(); } text = strip_noop_commands(&text); text = strip_inline_spacing(&text); text = expand_character_commands(&text); let mut centered = paragraph.centered; let mut right_aligned = paragraph.right_aligned; let mut ragged = false; if let Some(rest) = text.trim_start().strip_prefix("\\raggedright") { ragged = true; text = rest.trim_start().to_string(); } if let Some(rest) = text.trim_start().strip_prefix("\\leftline") { if let Some((body, used)) = braced_group(rest.trim_start()) { text = format!("{}{}", body, &rest.trim_start()[used..]); } } if let Some(rest) = text.trim_start().strip_prefix("\\centerline") { if let Some((body, used)) = braced_group(rest.trim_start()) { centered = true; text = format!("{}{}", body, &rest.trim_start()[used..]); } if let Some(rest) = text.trim_start().strip_prefix("\\rightline") { if let Some((body, used)) = braced_group(rest.trim_start()) { right_aligned = true; text = format!("{}{}", body, &rest.trim_start()[used..]); } } } let trimmed = text.trim_start(); if let Some(rest) = trimmed.strip_prefix("\\centering") { centered = true; text = rest.trim_start().to_string(); } else if let Some(rest) = trimmed.strip_prefix("\\raggedleft") { right_aligned = true; text = rest.trim_start().to_string(); } text = strip_box_commands(&text); text = expand_math_spaces(&text); text = expand_ensuremath(&text); text = expand_hspace(&text); if let Some((color, rest)) = color_switch(&text) { text = format!("\\textcolor{{{color}}}{{{rest}}}"); } let class_size = paragraph .font_size .or(geometry.base_font_size) .unwrap_or(655_360); let base_font_size = match paragraph.heading_level { Some(level) => heading_font_size(level, class_size), None => class_size, }; let baselineskip = geometry .baseline_skip .unwrap_or_else(|| class_baselineskip(base_font_size)); let baselineskip = geometry .linespread .map(|spread| baselineskip.saturating_mul(spread) / 1000) .unwrap_or(baselineskip); let (left_skip, par_indent) = match paragraph.list_depth { Some(_) => { let indent = paragraph.left_skip * SCALE + geometry.left_skip.unwrap_or(0); let hang = (paragraph.list_label + 5) * SCALE; (indent + hang, -hang) } None => ( paragraph.left_skip * SCALE + geometry.left_skip.unwrap_or(0), if no_indent { 0 } else { geometry.par_indent.unwrap_or(0) }, ), }; let style = ParagraphStyle { line_width: paragraph.width.unwrap_or(line_width), left_skip, centered, right_aligned, looseness: geometry.looseness.unwrap_or(0), ragged_right: ragged, right_skip: geometry.right_skip.unwrap_or(0) + paragraph.right_skip * SCALE, hang_indent: geometry.hang_indent.unwrap_or(0), hang_after: geometry.hang_after.unwrap_or(1) as i32, par_shape: geometry.par_shape.clone(), par_fillskip: geometry .par_fillskip .map(|(width, _, _)| width) .unwrap_or(0), par_fillskip_stretch: geometry .par_fillskip .map(|(_, stretch, _)| stretch) .unwrap_or(0), par_fillskip_fil: geometry.par_fillskip.map(|(_, _, fil)| fil).unwrap_or(true), frenchspacing: geometry.french_spacing.unwrap_or(false), space_factor_codes: geometry.space_factor_codes.clone(), baselineskip, lineskip: geometry.lineskip.unwrap_or(65536), lineskiplimit: geometry.lineskiplimit.unwrap_or(0), par_indent, emergencystretch: geometry.emergency_stretch.unwrap_or(0), pretolerance: geometry.pretolerance.unwrap_or(100), tolerance: geometry.tolerance.unwrap_or(200), hyphen_penalty: geometry.hyphen_penalty.unwrap_or(50), ex_hyphen_penalty: geometry.ex_hyphen_penalty.unwrap_or(50), double_hyphen_demerits: geometry.double_hyphen_demerits.unwrap_or(10_000), final_hyphen_demerits: geometry.final_hyphen_demerits.unwrap_or(5_000), line_penalty: geometry.line_penalty.unwrap_or(10), adj_demerits: geometry.adj_demerits.unwrap_or(10_000), hyphenation_exceptions: geometry.hyphenation_exceptions.clone(), line_height: if paragraph.heading_level.is_some() { base_font_size * 13 / 10 } else if paragraph.line_height == 12 { baselineskip } else { paragraph.line_height * SCALE }, font_size: base_font_size, char_width: 10 * SCALE, space_width: 4 * SCALE, space_stretch: 6 * SCALE, space_shrink: 2 * SCALE, space_skip: geometry.space_skip, xspace_skip: geometry.xspace_skip, }; let plain = strip_hrefs(&text).replace('~', " "); let mut unit = match inline_segments_with_boxes( &text, paragraph.font, &style, &geometry.colors, geometry .link_color .as_deref() .and_then(|name| color_spec(name, &geometry.colors)), ) { Some(segments) => Unit::paragraph_with_style_and_segments( index as u64, text.clone(), style.clone(), segments, ), None => match inline_runs(&plain, paragraph.font) { Some(runs) => Unit::paragraph_with_style_and_runs( index as u64, plain.clone(), style, runs, ), None => Unit::paragraph_with_style_and_face( index as u64, strip_group_braces(&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 (default_above_display, default_below_display) = display_skip_defaults(geometry.base_font_size.unwrap_or(655_360)); let above_display = geometry.above_display_skip.unwrap_or(default_above_display); let below_display = geometry.below_display_skip.unwrap_or(default_below_display); for index in 0..base_units.len().min(paragraphs.len()) { if paragraphs[index].math { base_units[index].space_before += above_display.0; base_units[index].space_stretch += above_display.1; base_units[index].space_shrink += above_display.2; } if index > 0 && paragraphs[index - 1].math { base_units[index].space_before += below_display.0; base_units[index].space_stretch += below_display.1; base_units[index].space_shrink += below_display.2; } } let mut units: Vec = Vec::with_capacity(base_units.len()); let mut unit_for_paragraph = Vec::with_capacity(paragraphs.len()); let mut footnote_count = 0usize; for (paragraph, unit) in paragraphs.iter().zip(base_units) { unit_for_paragraph.push(units.len()); units.push(unit); for (number, body) in ¶graph.footnotes { footnote_count += 1; let style = ParagraphStyle { line_width, font_size: 9 * SCALE, par_indent: 0, baselineskip: 11 * SCALE, line_height: 11 * SCALE, ..ParagraphStyle::default() }; let id = 1_000_000 + *number as u64; let footnote = match inline_runs(body, ParagraphFont::Roman) { Some(runs) => Unit::paragraph_with_style_and_runs(id, body.clone(), style, runs), None => Unit::paragraph_with_style_and_face( id, body.clone(), style, ParagraphFont::Roman, ), }; let height = footnote .items .iter() .map(|item| match item { VerticalItem::Paragraph(paragraph) => paragraph.height + paragraph.depth, _ => 0, }) .sum::(); units.push(Unit::insertion(id, 0, height, footnote.items)); } } for (index, number) in toc_targets { let Some(target) = paragraphs .iter() .position(|paragraph| paragraph.heading_number.as_deref() == Some(number.as_str())) else { continue; }; if let (Some(entry), Some(target)) = ( units.get_mut(unit_for_paragraph[index]), unit_for_paragraph.get(target).copied(), ) { entry.toc_target = Some(target as u64); } } for (index, prefix) in float_targets { let Some(target) = paragraphs.iter().position(|paragraph| { paragraph .float .as_ref() .and_then(|spec| spec.caption.as_deref()) .is_some_and(|caption| { caption .strip_prefix(&prefix) .is_some_and(|rest| rest.starts_with(':')) }) }) else { continue; }; if let (Some(entry), Some(target)) = ( units.get_mut(unit_for_paragraph[index]), unit_for_paragraph.get(target).copied(), ) { entry.toc_target = Some(target as u64); } } let mut unit_by_number: HashMap = HashMap::new(); for (index, paragraph) in paragraphs.iter().enumerate() { if let Some(number) = ¶graph.heading_number { unit_by_number.insert(number.clone(), unit_for_paragraph[index] as u64); } } for (label, number) in &label_numbers { if let Some(unit) = unit_by_number.get(number) { label_units.insert(label.clone(), *unit); } } let figure_name = geometry.figure_name.as_deref().unwrap_or("Figure"); let table_name = geometry.table_name.as_deref().unwrap_or("Table"); for (label, number) in &references { if label_units.contains_key(label) { continue; } let figure_caption = format!("{figure_name} {number}:"); let table_caption = format!("{table_name} {number}:"); if let Some(index) = paragraphs.iter().position(|paragraph| { paragraph .float .as_ref() .and_then(|spec| spec.caption.as_deref()) .is_some_and(|caption| { caption.starts_with(&figure_caption) || caption.starts_with(&table_caption) }) }) { label_units.insert(label.clone(), unit_for_paragraph[index] as u64); continue; } if let Some(index) = paragraphs.iter().position(|paragraph| { paragraph .equation_number .map(|value| value.to_string()) .as_deref() == Some(number.as_str()) }) { label_units.insert(label.clone(), unit_for_paragraph[index] as u64); } } for (index, paragraph) in paragraphs.iter().enumerate() { if let (Some(level), Some(_)) = (paragraph.heading_level, paragraph.heading_number.as_ref()) { outline_units.push(( paragraph.text.clone(), level, unit_for_paragraph[index] as u64, )); } } let mut document = Document::new(700 * SCALE, units); if footnote_count > 0 { document.insertion_classes.push(InsertionClass { number: 0, fraction_percent: 100, max_height: None, skip: Some(12 * SCALE), multiplier: 1000, }); document.insertion_skip = 12 * SCALE; } // LaTeX sets \maxdepth=.5\topskip; sources may override it later. document.max_depth = 5 * SCALE; document.club_penalty = geometry.club_penalty.unwrap_or(150); document.widow_penalty = geometry.widow_penalty.unwrap_or(150); document.text_width = line_width; document.page_breaks = paragraphs .iter() .enumerate() .filter(|(_, paragraph)| paragraph.page_break) .map(|(index, _)| unit_for_paragraph[index]) .collect(); document } fn roman_page_number(mut number: usize, upper: bool) -> String { const VALUES: [(usize, &str); 13] = [ (1000, "m"), (900, "cm"), (500, "d"), (400, "cd"), (100, "c"), (90, "xc"), (50, "l"), (40, "xl"), (10, "x"), (9, "ix"), (5, "v"), (4, "iv"), (1, "i"), ]; let mut text = String::new(); for (value, letters) in VALUES { while number >= value { text.push_str(letters); number -= value; } } if upper { text.to_uppercase() } else { text } } fn alphabetic_page_number(mut number: usize, upper: bool) -> String { let mut letters = Vec::new(); while number > 0 { let remainder = (number - 1) % 26; letters.push(b'a' + remainder as u8); number = (number - 1) / 26; } letters.reverse(); let text = String::from_utf8(letters).unwrap_or_default(); if upper { text.to_uppercase() } else { text } } fn page_number_text(index: usize, style: &str, start: u32) -> String { let number = index + 1 + start as usize; match style { "roman" => roman_page_number(number, false), "Roman" => roman_page_number(number, true), "alph" => alphabetic_page_number(number, false), "Alph" => alphabetic_page_number(number, true), _ => number.to_string(), } } /// Paint the LaTeX page number centred in the footer of every page. /// Draw fancyhdr's running header/footer fields on every page. Positions are /// content-relative: the header sits above the first baseline and the footer /// below the page goal, so the PDF writer's page origin shifts both correctly. fn stamp_running_heads( lists: &mut [DisplayList], geometry: &PageGeometry, page_goal: i64, text_width: i64, paper_height: i64, ) { if !geometry.fancy_pagestyle || geometry.suppress_page_numbers { return; } let head_sep = geometry.head_sep.unwrap_or(25 * SCALE); let foot_skip = geometry.foot_skip.unwrap_or(30 * SCALE); let header_baseline = -head_sep; let footer_baseline = (page_goal + foot_skip).min(paper_height - 12 * SCALE); let rule_width = geometry.head_rule_width.unwrap_or(0); let style = geometry.page_numbering.as_deref().unwrap_or("arabic"); for (index, list) in lists.iter_mut().enumerate() { if index == 0 && geometry.suppress_first_page_header { continue; } let number = page_number_text(index, style, geometry.page_start); let fields = [ (&geometry.header_left, header_baseline, 0_usize), (&geometry.header_center, header_baseline, 1), (&geometry.header_right, header_baseline, 2), (&geometry.footer_left, footer_baseline, 0), (&geometry.footer_center, footer_baseline, 1), (&geometry.footer_right, footer_baseline, 2), ]; for (field, baseline, position) in fields { let Some(field) = field else { continue; }; let text = running_head_text(field, geometry, &number); if text.is_empty() { continue; } let width = text_width_roman(&text); let x = match position { 0 => 0, 1 => ((text_width - width) / 2).max(0), _ => (text_width - width).max(0), }; list.push(DisplayItem::Text { x, y: baseline, size: 9 * SCALE, text, font: FontFace::Roman, }); } if rule_width > 0 { list.push(DisplayItem::Rule { x: 0, y: header_baseline + 4 * SCALE, width: text_width, height: rule_width, }); } } } fn running_head_text(field: &str, geometry: &PageGeometry, page_number: &str) -> String { // Remove size/shape declarations before expanding macros: the class // redefines \footnotesize in terms of itself, and expanding it would // repeat \@setfontsize internals on every pass. let mut field = field.to_string(); for declaration in [ "\\scshape", "\\footnotesize", "\\small", "\\normalsize", "\\large", "\\Large", "\\LARGE", "\\huge", "\\Huge", "\\bfseries", "\\itshape", "\\slshape", "\\upshape", "\\ttfamily", "\\sffamily", "\\rmfamily", "\\mdseries", "\\centering", "\\relax", ] { field = field.replace(declaration, ""); } let mut text = expand_macros(&field, &geometry.macros); text = text.replace("\\thepage", page_number); if let Some(title) = geometry.title.as_deref() { text = text.replace("\\@title", title); text = text.replace("\\shorttitle", title); text = text.replace("\\headeright", "A Preprint"); } scrub_title_metadata(&text) } fn stamp_page_numbers( lists: &mut [DisplayList], page_goal: i64, paper_width: i64, paper_height: i64, style: &str, start: u32, skip_first: bool, ) { let size = 10 * SCALE; let baseline = (page_goal + 36 * SCALE).min(paper_height - 24 * SCALE); for (index, list) in lists.iter_mut().enumerate() { if skip_first && index == 0 { continue; } let text = page_number_text(index, style, start); let width: i64 = text .chars() .map(|character| Cmr10Metrics::Roman.width(character)) .sum(); let x = ((paper_width - width) / 2).max(0); list.push(DisplayItem::Text { x, y: baseline, size, text, font: FontFace::Roman, }); } } /// Fill in table-of-contents page numbers from a laid-out engine. Returns /// true when at least one entry changed and the document needs re-layout. fn text_width_roman(text: &str) -> i64 { let metrics = Cmr10Metrics::Roman; text.chars() .map(|character| match character { ' ' => metrics.space(), _ => metrics.width(character), }) .sum() } /// Fill the space between entry text and page number with dot leaders. fn toc_leader(head: &str, number: &str, measure: i64) -> Option { let metrics = Cmr10Metrics::Roman; let head_width = text_width_roman(head); let number_width = text_width_roman(number); let dot = metrics.width('.'); let space = metrics.space(); if dot <= 0 || measure <= 0 { return None; } let room = measure - head_width - number_width - 2 * space; let count = room / dot; if count < 4 { return None; } Some(format!("{head} {} {number}", ".".repeat(count as usize))) } fn stamp_toc_pages(document: &mut Document, engine: &Engine, geometry: &PageGeometry) -> bool { let mut page_of = std::collections::HashMap::new(); for (index, page) in engine.pages().iter().enumerate() { for (unit, _) in &page.sources { page_of.entry(*unit).or_insert(index); } } let numbering = geometry.page_numbering.as_deref().unwrap_or("arabic"); let updates: Vec<(u64, String)> = document .units .iter() .filter(|unit| unit.toc_target.is_some() && !unit.toc_stamped) .filter_map(|unit| { let target = unit.toc_target?; let page = page_of.get(&target)?; let page_number = page_number_text(*page, numbering, geometry.page_start); let measure = unit .paragraph_style .as_ref() .map(|style| { (style.line_width - style.left_skip - style.right_skip - style.par_indent) .max(1) }) .unwrap_or(0); let source = toc_leader(unit.source.trim_end(), &page_number, measure) .unwrap_or_else(|| format!("{} \\hfill {}", unit.source.trim_end(), page_number)); Some((unit.id, source)) }) .collect(); let mut changed = false; for (id, source) in updates { let Some(index) = document.units.iter().position(|unit| unit.id == id) else { continue; }; let Some(style) = document.units[index].paragraph_style.clone() else { continue; }; let font = document.units[index] .items .iter() .find_map(|item| match item { VerticalItem::Paragraph(paragraph) => Some(paragraph.font), _ => None, }) .unwrap_or(ParagraphFont::Roman); let previous = &document.units[index]; let mut replacement = Unit::paragraph_with_style_and_face(id, source, style, font); replacement.space_before = previous.space_before; replacement.space_stretch = previous.space_stretch; replacement.space_shrink = previous.space_shrink; replacement.toc_target = previous.toc_target; replacement.toc_stamped = true; document.units[index] = replacement; changed = true; } changed } /// Environments route-D knows how to lay out (starred variants are normalised). const SUPPORTED_ENVIRONMENTS: &[&str] = &[ "document", "itemize", "enumerate", "description", "quote", "quotation", "verse", "abstract", "figure", "figure*", "table", "table*", "center", "flushleft", "flushright", "minipage", "verbatim", "tabular", "longtable", "tabularx", "tabular*", "displaymath", "math", "equation", "align", "gather", "cases", "split", "alignat", "multline", "matrix", "pmatrix", "bmatrix", "Bmatrix", "vmatrix", "Vmatrix", "array", "thebibliography", "theorem", "lemma", "corollary", "proposition", "definition", "example", "remark", "proof", ]; /// Report environments that route-D would otherwise leave as literal text. fn source_warnings(source: &str, geometry: &PageGeometry) -> Vec { let mut warnings = Vec::new(); let mut rest = source; while let Some(index) = rest.find("\\begin{") { let after = &rest[index + "\\begin{".len()..]; let Some(close) = after.find('}') else { break; }; let name = after[..close].trim(); let normalized = name.trim_end_matches('*'); let declared = geometry .theorem_definitions .iter() .any(|definition| definition.name == normalized) || geometry .environments .iter() .any(|definition| definition.name == normalized); if !SUPPORTED_ENVIRONMENTS.contains(&normalized) && !declared { let message = format!("unsupported environment `{name}`"); if !warnings.contains(&message) { warnings.push(message); } } rest = &after[close + 1..]; } warnings } /// Report control words that survived layout as literal backslash glyphs. fn document_warnings(document: &Document) -> Vec { let mut warnings = Vec::new(); for unit in &document.units { for item in &unit.items { let VerticalItem::Paragraph(paragraph) = item else { continue; }; for line in ¶graph.lines { let mut index = 0; while index < line.len() { if let HorizontalItem::Box(box_) = &line[index] { if box_.character == Some('\\') { let mut name = String::new(); let mut next = index + 1; while let Some(HorizontalItem::Box(next_box)) = line.get(next) { match next_box.character { Some(character) if character.is_ascii_alphabetic() => { name.push(character); next += 1; } _ => break, } } let message = if name.is_empty() { "unsupported command near a backslash".to_string() } else { format!("unsupported command `\\{name}`") }; if !warnings.contains(&message) { warnings.push(message); } } } index += 1; } } } } warnings.truncate(20); warnings } fn render_json( document: &Document, engine: &Engine, edit: Option<(&[usize], usize)>, geometry: &PageGeometry, warnings: &[String], ) -> String { let mut document = document.clone(); let relaid = if stamp_toc_pages(&mut document, engine, geometry) { Some(layout_document(&document)) } else { None }; let engine = relaid.as_ref().unwrap_or(engine); let document = &document; let mut json = String::new(); let page_width_mm = document.paper_width as f64 / SCALE as f64 * 25.4 / 72.0; let page_height_mm = document.paper_height as f64 / SCALE as f64 * 25.4 / 72.0; let page_height_pt = document.paper_height as f64 / SCALE as f64; let _ = write!( json, "{{\"status\":\"ok\",\"pageWidthMm\":{page_width_mm:.2},\"pageHeightMm\":{page_height_mm:.2},\"pages\":[" ); let mut lists: Vec = 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); if let Some(color) = geometry.page_color { list.items .insert(0, texrra_tex_core::DisplayItem::Background(color)); } list }) .collect(); if !geometry.hide_links && let Some(color) = geometry .link_border_color .as_deref() .and_then(|name| color_spec(name, &geometry.colors)) { for list in &mut lists { let frames: Vec = list .items .iter() .filter_map(|item| match item { texrra_tex_core::DisplayItem::Link { x, y, width, height, .. } => Some(texrra_tex_core::DisplayItem::Frame { x: *x, y: *y, width: *width, height: *height, color, thickness: 26_214, }), _ => None, }) .collect(); list.items.extend(frames); } } if !geometry.suppress_page_numbers { let style = geometry.page_numbering.as_deref().unwrap_or("arabic"); stamp_page_numbers( &mut lists, document.page_goal, document.paper_width, document.paper_height, style, geometry.page_start, geometry.suppress_first_page_number, ); } stamp_running_heads( &mut lists, geometry, document.page_goal, document.text_width, document.paper_height, ); for (index, (page, mut list)) in engine.pages().iter().zip(lists).enumerate() { list.place(document.h_offset, document.v_offset); if index > 0 { json.push(','); } let _ = write!( json, "{{\"index\":{index},\"hash\":\"{:016x}\",\"svg\":\"{}\"}}", page.hash, escape_json(&list.to_svg()) ); } let _ = write!(json, "],\"pageCount\":{}", engine.pages().len()); if let Some((changed, recomputed)) = edit { let _ = write!( json, ",\"changedPages\":{:?},\"recomputedPages\":{recomputed}", changed ); } let _ = write!(json, ",\"warnings\":["); for (index, warning) in warnings.iter().enumerate() { if index > 0 { json.push(','); } let _ = write!(json, "\"{}\"", escape_json(warning)); } json.push(']'); let _ = write!(json, ",\"pageHeightPt\":{page_height_pt:.0}}}"); json } fn escape_json(value: &str) -> String { let mut escaped = String::with_capacity(value.len()); for character in value.chars() { match character { '"' => escaped.push_str("\\\""), '\\' => escaped.push_str("\\\\"), '\n' => escaped.push_str("\\n"), '\r' => escaped.push_str("\\r"), '\t' => escaped.push_str("\\t"), character if character < '\u{20}' => { let _ = write!(escaped, "\\u{:04x}", character as u32); } character => escaped.push(character), } } escaped } #[cfg(test)] mod tests { use super::*; /// Drop the internal no-break markers (and their size prefix) that /// `\usebox`/`\mbox` insert. fn visible(text: &str) -> String { let mut out = String::new(); let mut rest = text; while let Some(open) = rest.find('\u{E010}') { out.push_str(&rest[..open]); let after = &rest[open + '\u{E010}'.len_utf8()..]; let content = match after.find(';') { Some(semi) if after[..semi].chars().all(|c| c.is_ascii_digit()) => { &after[semi + 1..] } _ => after, }; let close = content.find('\u{E011}').unwrap_or(content.len()); out.push_str(&content[..close]); rest = content[close..] .strip_prefix('\u{E011}') .unwrap_or(&content[close..]); } out.push_str(rest); out } #[test] fn display_math_is_split_to_the_measure() { let mut formula = String::from("$$"); for index in 0..80 { if index > 0 { formula.push_str(" + "); } formula.push('x'); } formula.push_str(" = z$$"); let (body, geometry) = geometry_and_body(&formula); let paragraphs = paragraphs(&body).unwrap(); let document = build_document(¶graphs, &geometry); assert!( document.units[0].items.len() > 1, "items={}", document.units[0].items.len() ); } #[test] fn size_commands_set_the_paragraph_font_size() { let (body, geometry) = geometry_and_body("\\large Big text"); let paragraphs = paragraphs(&body).unwrap(); let document = build_document(¶graphs, &geometry); let unit = &document.units[0]; assert_eq!(unit.paragraph_style.as_ref().unwrap().font_size, 12 * SCALE); assert_eq!(unit.source, "Big text"); } #[test] fn fontsize_sets_the_exact_paragraph_size() { let (body, geometry) = geometry_and_body("\\fontsize{20pt}{24pt}\\selectfont Huge text"); let paragraphs = paragraphs(&body).unwrap(); let document = build_document(¶graphs, &geometry); let unit = &document.units[0]; assert_eq!(unit.paragraph_style.as_ref().unwrap().font_size, 20 * SCALE); assert_eq!(unit.source, "Huge text"); } #[test] fn arraystretch_scales_tabular_rows() { let source = "\\renewcommand{\\arraystretch}{2}\n\n\\begin{tabular}{ll}\nA & B \\\\\nC & D\n\\end{tabular}"; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry.array_stretch, Some(2000)); let blocks = paragraphs_with_definitions(&body, &geometry.theorem_definitions).expect("paragraphs"); let document = build_document(&blocks, &geometry); let halign = document .units .iter() .flat_map(|unit| &unit.items) .find_map(|item| match item { VerticalItem::Halign(halign) => Some(halign), _ => None, }) .expect("tabular halign"); assert_eq!(halign.line_height, 24 * SCALE); assert_eq!(halign.height, 48 * SCALE); } #[test] fn abstract_names_follow_renewcommand() { let source = "\\renewcommand{\\abstractname}{Zusammenfassung}\n\n\\begin{abstract}\nBody text.\n\\end{abstract}"; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry.abstract_name.as_deref(), Some("Zusammenfassung")); assert!(!body.contains("abstractname")); let paragraphs = paragraphs_with_definitions(&body, &geometry.theorem_definitions).expect("paragraphs"); let document = build_document(¶graphs, &geometry); assert!( document .units .iter() .any(|unit| unit.source.contains("Zusammenfassung")) ); } #[test] fn float_names_follow_renewcommand() { let source = "\\renewcommand{\\figurename}{Fig.}\n\n\\begin{figure}\n\\caption{A}\n\\end{figure}"; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry.figure_name.as_deref(), Some("Fig.")); assert!(!body.contains("figurename")); let mut blocks = paragraphs_with_definitions(&body, &geometry.theorem_definitions).expect("paragraphs"); number_floats( &mut blocks, geometry.figure_name.as_deref().unwrap_or("Figure"), geometry.table_name.as_deref().unwrap_or("Table"), 0, 0, ); let caption = blocks[0] .float .as_ref() .and_then(|spec| spec.caption.as_deref()); assert_eq!(caption, Some("Fig. 1: A")); let source = "\\renewcommand{\\tablename}{Tab.}\n\n\\begin{table}\n\\caption{B}\n\\end{table}"; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry.table_name.as_deref(), Some("Tab.")); let mut blocks = paragraphs_with_definitions(&body, &geometry.theorem_definitions).expect("paragraphs"); number_floats( &mut blocks, geometry.figure_name.as_deref().unwrap_or("Figure"), geometry.table_name.as_deref().unwrap_or("Table"), 0, 0, ); let caption = blocks[0] .float .as_ref() .and_then(|spec| spec.caption.as_deref()); assert_eq!(caption, Some("Tab. 1: B")); } #[test] fn tables_reserve_outer_tabcolsep_margins() { let source = "\\begin{tabular}{ll}\nA & B \\\\\nC & D\n\\end{tabular}"; let (body, geometry) = geometry_and_body(source); let blocks = paragraphs(&body).expect("paragraphs"); let document = build_document(&blocks, &geometry); let halign = document .units .iter() .flat_map(|unit| &unit.items) .find_map(|item| match item { VerticalItem::Halign(halign) => Some(halign), _ => None, }) .expect("tabular halign"); assert_eq!(halign.margin, 6 * SCALE); assert_eq!(halign.cell_box(0, 0).expect("first cell").0, 6 * SCALE); assert_eq!( halign.width, halign.column_widths.iter().sum::() + 24 * SCALE ); } #[test] fn tabcolsep_sets_tabular_column_glue() { let source = "\\tabcolsep=20pt\n\n\\begin{tabular}{ll}\nA & B \\\\\nC & D\n\\end{tabular}"; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry.tab_col_sep, Some(20 * SCALE)); assert!(!body.contains("tabcolsep")); let blocks = paragraphs_with_definitions(&body, &geometry.theorem_definitions).expect("paragraphs"); let document = build_document(&blocks, &geometry); let halign = document .units .iter() .flat_map(|unit| &unit.items) .find_map(|item| match item { VerticalItem::Halign(halign) => Some(halign), _ => None, }) .expect("tabular halign"); assert_eq!(halign.column_skips, vec![40 * SCALE]); let columns: i64 = halign.column_widths.iter().sum(); assert_eq!(halign.width, columns + 80 * SCALE); let (_, default) = geometry_and_body("\\begin{tabular}{ll}\nA & B\n\\end{tabular}"); assert_eq!(default.tab_col_sep, None); let blocks = paragraphs_with_definitions("\\texrratable{0}", &default.theorem_definitions) .expect("paragraphs"); let document = build_document(&blocks, &default); let halign = document .units .iter() .flat_map(|unit| &unit.items) .find_map(|item| match item { VerticalItem::Halign(halign) => Some(halign), _ => None, }) .expect("tabular halign"); assert!(halign.column_skips.is_empty()); let columns: i64 = halign.column_widths.iter().sum(); assert_eq!(halign.width, columns + 24 * SCALE); } #[test] fn linespread_scales_the_class_baseline() { let source = "\\documentclass{article}\n\\linespread{1.5}\n\nBody text."; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry.linespread, Some(1500)); assert!(!body.contains("linespread")); let blocks = paragraphs_with_definitions(&body, &geometry.theorem_definitions).expect("paragraphs"); let document = build_document(&blocks, &geometry); let style = document.units[0] .paragraph_style .clone() .expect("paragraph style"); assert_eq!(style.baselineskip, 18 * SCALE); let (_, clamped) = geometry_and_body("\\linespread{9}\n\nBody text."); assert_eq!(clamped.linespread, Some(5000)); let (_, renamed) = geometry_and_body("\\renewcommand{\\baselinestretch}{1.25}\n\nBody text."); assert_eq!(renamed.linespread, Some(1250)); } #[test] fn documentclass_size_options_set_the_base_size() { let source = "\\documentclass[12pt]{article}\n\\begin{document}\n\nPlain text\n\n\\end{document}"; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry.base_font_size, Some(12 * SCALE)); let paragraphs = paragraphs(&body).unwrap(); let document = build_document(¶graphs, &geometry); let style = document.units[0].paragraph_style.as_ref().unwrap(); assert_eq!(style.font_size, 12 * SCALE); assert_eq!(style.baselineskip, 14 * 65_536 + 32_768); } #[test] fn explicit_size_commands_override_the_class_size() { let source = "\\documentclass[12pt]{article}\n\\begin{document}\n\n\\small Small text\n\n\\end{document}"; let (body, geometry) = geometry_and_body(source); let paragraphs = paragraphs(&body).unwrap(); let document = build_document(¶graphs, &geometry); let style = document.units[0].paragraph_style.as_ref().unwrap(); assert_eq!(style.font_size, 9 * SCALE); } #[test] fn documentclass_defaults_to_ten_point() { let source = "\\documentclass{article}\n\\begin{document}\n\nPlain text\n\n\\end{document}"; let (body, geometry) = geometry_and_body(source); let paragraphs = paragraphs(&body).unwrap(); let document = build_document(¶graphs, &geometry); let style = document.units[0].paragraph_style.as_ref().unwrap(); assert_eq!(style.font_size, 10 * SCALE); assert_eq!(style.baselineskip, 12 * 65_536); } #[test] fn engine_template_keeps_paragraph_columns() { assert_eq!(engine_template("{|l|c|p{3cm}|}"), "|l|c|p{3cm}|"); assert_eq!(engine_template("|p{2cm}|r|"), "|p{2cm}|r|"); assert_eq!(engine_template("*{3}{c}"), "ccc"); assert_eq!(engine_template("|*{3}{c|}"), "|c|c|c|"); assert_eq!(engine_template("*{2}{p{2cm}}"), "p{2cm}p{2cm}"); assert_eq!(engine_template(""), "l"); } fn multi_page_source() -> String { let mut source = String::from("\\documentclass{article}\n\\begin{document}\n\n"); for index in 0..36 { source.push_str(&format!("Paragraph {index:02} ")); for _ in 0..4 { source.push_str( "lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor. ", ); } source.push_str("\n\n"); } source.push_str("\\end{document}\n"); source } #[test] fn multi_paragraph_edits_reuse_earlier_pages() { let source = multi_page_source(); let first = project_preview_json("route-d-multi-edit", &source).expect("first preview"); let first: serde_json::Value = serde_json::from_str(&first).expect("first JSON"); let page_count = first["pageCount"].as_u64().expect("page count"); assert!( page_count >= 2, "expected a multi-page preview, got {page_count}" ); let edited = source .replace("Paragraph 30 ", "Paragraph 30 changed ") .replace("Paragraph 33 ", "Paragraph 33 changed "); let second = project_preview_json("route-d-multi-edit", &edited).expect("edited preview"); let second: serde_json::Value = serde_json::from_str(&second).expect("edited JSON"); assert!( second["changedPages"] .as_array() .is_some_and(|pages| !pages.is_empty()) ); let recomputed = second["recomputedPages"].as_u64().expect("recomputed"); assert!(recomputed < page_count, "changed pages should be a subset"); } #[test] fn structural_edit_keeps_pages_before_the_inserted_paragraph() { let source = multi_page_source(); let first = project_preview_json("route-d-structural-edit", &source).expect("first preview"); let first: serde_json::Value = serde_json::from_str(&first).expect("first JSON"); let first_hash = first["pages"][0]["hash"].as_str().expect("first hash"); let inserted = source.replacen( "Paragraph 21 ", "Paragraph inserted before twenty-one with enough words to make a line.\n\nParagraph 21 ", 1, ); let second = project_preview_json("route-d-structural-edit", &inserted).expect("inserted preview"); let second: serde_json::Value = serde_json::from_str(&second).expect("second JSON"); assert_eq!( second["pages"][0]["hash"].as_str().expect("second hash"), first_hash ); let page_count = second["pageCount"].as_u64().expect("page count"); assert!( second["changedPages"] .as_array() .is_some_and(|pages| !pages.is_empty()) ); assert!( second["recomputedPages"].as_u64().expect("recomputed") < page_count, "the unchanged prefix should not be recomputed" ); } } #[cfg(test)] mod source_tests { use super::*; /// Drop the internal no-break markers (and their size prefix) that /// `\usebox`/`\mbox` insert. fn visible(text: &str) -> String { let mut out = String::new(); let mut rest = text; while let Some(open) = rest.find('\u{E010}') { out.push_str(&rest[..open]); let after = &rest[open + '\u{E010}'.len_utf8()..]; let content = match after.find(';') { Some(semi) if after[..semi].chars().all(|c| c.is_ascii_digit()) => { &after[semi + 1..] } _ => after, }; let close = content.find('\u{E011}').unwrap_or(content.len()); out.push_str(&content[..close]); rest = content[close..] .strip_prefix('\u{E011}') .unwrap_or(&content[close..]); } out.push_str(rest); out } #[test] fn footnotes_become_page_insertions() { let blocks = paragraphs("Body\\footnote{Note} tail").unwrap(); let document = build_document(&blocks, &PageGeometry::default()); assert_eq!(document.units.len(), 2); assert_eq!(document.units[0].source, "Body (1) tail"); let Some(VerticalItem::Insertion(insertion)) = document.units[1].items.first() else { panic!("expected an insertion unit"); }; assert_eq!(insertion.class, 0); assert!(insertion.height > 0); assert_eq!(document.insertion_classes.len(), 1); let engine = Engine::layout_paged(&document).expect("paged layout"); assert_eq!(engine.pages().len(), 1); assert_eq!(engine.pages()[0].insertions.len(), 1); let list = engine.pages()[0].display_list_with_layout(document.page_goal, document.text_float_sep); assert!(list.items.iter().any(|item| { matches!(item, texrra_tex_core::DisplayItem::Text { text, .. } if text == "N") })); } #[test] fn float_placement_options_follow_the_spec() { for (spec, placement) in [ ("[htbp]", FloatPlacement::Here), ("[!t]", FloatPlacement::Top), ("[b]", FloatPlacement::Bottom), ("[H]", FloatPlacement::Here), ("[]", FloatPlacement::Top), ] { let source = format!("\\begin{{figure}}{}\n\\caption{{A}}\n\\end{{figure}}", spec); let blocks = paragraphs(&source).expect("paragraphs"); assert_eq!( blocks[0].float.as_ref().expect("float").placement, placement, "spec {spec}" ); } } #[test] fn figures_become_float_units() { let source = "\\begin{figure}[h]\n\\caption{A caption}\\label{fig:a}\n\\end{figure}"; let (body, geometry) = geometry_and_body(source); let blocks = paragraphs(&body).unwrap(); let document = build_document(&blocks, &geometry); assert_eq!(document.units.len(), 1); let Some(VerticalItem::Float(float)) = document.units[0].items.first() else { panic!("expected a float unit"); }; assert_eq!(float.placement, FloatPlacement::Here); let mut caption = String::new(); for item in &float.content { if let VerticalItem::Paragraph(paragraph) = item { for line in ¶graph.lines { for item in line { match item { texrra_tex_core::paragraph::HorizontalItem::Box(box_) => { if let Some(character) = box_.character { caption.push(character); } } texrra_tex_core::paragraph::HorizontalItem::Glue { width, .. } => { if *width > 0 { caption.push(' '); } } _ => {} } } } } } assert_eq!(caption, "Figure 1: A caption"); } #[test] fn figure_labels_resolve_references() { let source = "See \\ref{fig:a}.\n\n\\begin{figure}\n\\caption{Caption}\n\\label{fig:a}\n\\end{figure}"; let (body, geometry) = geometry_and_body(source); let blocks = paragraphs(&body).unwrap(); let document = build_document(&blocks, &geometry); assert_eq!(document.units[0].source, "See 1."); } #[test] fn standalone_graphics_place_image_items() { let source = "\\includegraphics[width=100pt]{pixel.bmp}"; let blocks = paragraphs(source).expect("paragraphs"); let (_, mut geometry) = geometry_and_body(source); geometry.images.insert( "pixel.bmp".to_string(), RasterImage { width: 2, height: 2, rgb: vec![0; 12], }, ); let document = build_document(&blocks, &geometry); let image = document .units .iter() .flat_map(|unit| unit.items.iter()) .find_map(|item| match item { VerticalItem::Float(float) => { float.content.iter().find_map(|content| match content { VerticalItem::Image { width, height, .. } => Some((*width, *height)), _ => None, }) } _ => None, }) .expect("image item inside the graphic float"); assert_eq!(image.0, 100 * SCALE); assert_eq!(image.1, 100 * SCALE); } #[test] fn standalone_graphics_become_in_text_floats() { let blocks = paragraphs("\\includegraphics[width=100pt]{pixel.bmp}").expect("paragraphs"); assert_eq!(blocks.len(), 1); let spec = blocks[0].float.as_ref().expect("graphic float"); assert_eq!(spec.placement, FloatPlacement::Here); assert_eq!(spec.image.as_deref(), Some("pixel.bmp")); assert_eq!(spec.width, Some(ImageLength::Absolute(100 * SCALE))); assert!(spec.caption.is_none()); } #[test] fn figure_graphics_place_decoded_images() { let blocks = paragraphs( "\\begin{figure}[t]\n\\includegraphics[width=120pt]{plot.png}\n\\caption{Plot}\n\\end{figure}", ) .expect("paragraphs"); let mut geometry = PageGeometry::default(); geometry.images.insert( "plot.png".to_string(), RasterImage { width: 200, height: 100, rgb: vec![7; 200 * 100 * 3], }, ); let document = build_document(&blocks, &geometry); let image = document .units .iter() .flat_map(|unit| &unit.items) .find_map(|item| match item { VerticalItem::Float(float) => { float.content.iter().find_map(|content| match content { VerticalItem::Image { width, height, image, } => Some((*width, *height, image.clone())), _ => None, }) } _ => None, }) .expect("decoded image in the float"); assert_eq!(image.0, 120 * SCALE); assert_eq!(image.1, 60 * SCALE); assert_eq!(image.2.width, 200); assert_eq!(image.2.rgb.len(), 200 * 100 * 3); } #[test] fn graphics_options_size_the_image() { let mut geometry = PageGeometry::default(); geometry.line_width = Some(480 * SCALE); geometry.textheight = Some(600 * SCALE); geometry.images.insert( "plot.png".to_string(), RasterImage { width: 200, height: 100, rgb: vec![9; 200 * 100 * 3], }, ); let cases = [ ("width=0.5\\textwidth", (240 * SCALE, 120 * SCALE)), ( "width=100pt,height=100pt,keepaspectratio", (100 * SCALE, 50 * SCALE), ), ("scale=0.5", (100 * SCALE, 50 * SCALE)), ("", (200 * SCALE, 100 * SCALE)), ]; for (options, expected) in cases { let source = format!( "\\begin{{figure}}[t]\n\\includegraphics[{options}]{{plot.png}}\n\\end{{figure}}" ); let blocks = paragraphs(&source).expect("paragraphs"); let document = build_document(&blocks, &geometry); let image = document .units .iter() .flat_map(|unit| &unit.items) .find_map(|item| match item { VerticalItem::Float(float) => { float.content.iter().find_map(|content| match content { VerticalItem::Image { width, height, .. } => Some((*width, *height)), _ => None, }) } _ => None, }) .expect("image in the float"); assert_eq!(image, expected, "options: {options}"); } } #[test] fn noindent_starts_the_paragraph_flush() { let blocks = paragraphs("\\noindent Alpha\n\nBeta").expect("paragraphs"); let mut geometry = PageGeometry::default(); geometry.par_indent = Some(20 * SCALE); let document = build_document(&blocks, &geometry); assert_eq!(document.units[0].source, "Alpha"); assert_eq!( document.units[0] .paragraph_style .as_ref() .map(|style| style.par_indent), Some(0) ); assert_eq!( document.units[1] .paragraph_style .as_ref() .map(|style| style.par_indent), Some(20 * SCALE) ); } #[test] fn page_numbers_are_centered_in_previews() { let json = preview_json("Alpha").expect("preview"); assert!(json.contains(">1"), "got {json}"); let roman = preview_json("\\pagenumbering{roman}\n\nAlpha").expect("roman preview"); assert!(roman.contains(">i"), "got {roman}"); let empty = preview_json("\\pagestyle{empty}\n\nAlpha").expect("pagestyle preview"); assert!(!empty.contains(">1"), "got {empty}"); let first = preview_json("\\thispagestyle{empty}\n\nAlpha\n\n\\newpage\n\nBeta") .expect("thispagestyle preview"); assert!(!first.contains(">1"), "got {first}"); assert!(first.contains(">2"), "got {first}"); } #[test] fn minipage_paragraphs_use_their_declared_width() { let source = "\\begin{minipage}{120pt}\nAlpha beta.\n\nGamma delta.\n\\end{minipage}"; let blocks = paragraphs(source).expect("paragraphs"); assert_eq!(blocks.len(), 2); assert_eq!(blocks[0].text, "Alpha beta."); assert_eq!(blocks[1].text, "Gamma delta."); assert_eq!(blocks[0].width, Some(120 * SCALE)); let document = build_document(&blocks, &PageGeometry::default()); let style = document.units[0] .paragraph_style .as_ref() .expect("paragraph style"); assert_eq!(style.line_width, 120 * SCALE); } #[test] fn addtocounter_offsets_the_printed_page_number() { let offset = preview_json("\\setcounter{page}{5}\n\n\\addtocounter{page}{2}\n\nAlpha") .expect("preview"); assert!(offset.contains(">7"), "{offset}"); } #[test] fn newcounter_definitions_stay_out_of_the_body() { let (body, geometry) = geometry_and_body("\\newcounter{steps}\n\n\\setcounter{steps}{4}\n\nBody."); assert_eq!(body.trim(), "Body."); assert_eq!(geometry_counter(&geometry, "steps"), 4); } #[test] fn multline_rows_share_one_number() { let json = preview_json("\\begin{multline}a + b \\\\ c + d \\\\ e\\end{multline}") .expect("multline preview"); assert!(json.contains(">1"), "{json}"); assert!(json.contains(">e"), "{json}"); assert!(!json.contains("multline"), "{json}"); } #[test] fn split_inside_equation_numbers_once() { let json = preview_json( "\\begin{equation}\\begin{split}\na &= b \\\\\nc &= d\n\\end{split}\\end{equation}", ) .expect("split preview"); assert!(json.contains(">1"), "{json}"); assert!(json.contains(">("), "{json}"); assert!(json.contains(">a"), "{json}"); assert!(!json.contains("split"), "{json}"); } #[test] fn alignat_rows_are_numbered() { let json = preview_json( "\\begin{alignat}{2}\na &= b & c &= d \\\\\ne &= f & g &= h\n\\end{alignat}", ) .expect("alignat preview"); assert!(json.contains(">1"), "{json}"); assert!(json.contains(">2"), "{json}"); assert!(!json.contains("alignat"), "{json}"); } #[test] fn operator_names_and_declared_operators_render() { let source = r"\DeclareMathOperator{\Tr}{Tr} Body $\operatorname{rank}(A)$ and $\Tr(B)$."; let json = preview_json(source).expect("preview"); assert!(json.contains(">r")); assert!(!json.contains("operatorname")); assert!(!json.contains("DeclareMathOperator")); } #[test] fn substack_scripts_paint_their_rows() { let json = preview_json("\\[\\sum_{\\substack{i=1 \\\\ j=2}} x\\]").expect("preview"); assert!(json.contains(">i")); assert!(json.contains(">j")); assert!(!json.contains("substack")); } #[test] fn matrix_environments_paint_their_delimiters() { let json = preview_json("\\[\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}\\]") .expect("matrix preview"); assert!(json.contains(">["), "{json}"); assert!(json.contains(">]"), "{json}"); assert!(json.contains(">a"), "{json}"); assert!(!json.contains("unsupported environment"), "{json}"); } #[test] fn cases_environments_paint_rows_and_a_brace() { let json = preview_json("\\[\\begin{cases} x & x>0 \\\\ 0 & \\text{else} \\end{cases}\\]") .expect("cases preview"); assert!(json.contains(">{"), "{json}"); assert!(json.contains(">x"), "{json}"); assert!(!json.contains("unsupported environment `cases`"), "{json}"); } #[test] fn preview_warnings_flag_unsupported_environments() { let source = r"\begin{document} \begin{align} a &= b \end{align} \[\begin{eqnarray} x = 1 \\ y = 2 \end{eqnarray}\] \begin{wrapfigure}{r}{4cm} a & b \end{wrapfigure} \end{document}"; let json = preview_json(source).expect("preview"); assert!( json.contains("unsupported environment `eqnarray`"), "{json}" ); assert!( json.contains("unsupported environment `wrapfigure`"), "{json}" ); assert!(!json.contains("unsupported environment `align`"), "{json}"); let plain = preview_json("Alpha").expect("plain preview"); assert!(plain.contains("\"warnings\":[]"), "{plain}"); } #[test] fn preview_warnings_flag_leaked_commands() { let json = preview_json(r"See \unknownthing and \textcolor{red}{red}.").expect("preview"); assert!( json.contains(r"unsupported command `\\unknownthing`"), "{json}" ); assert!( !json.contains(r"unsupported command `\\textcolor`"), "{json}" ); assert!(json.contains("#ff0000"), "{json}"); } #[test] fn headings_become_pdf_bookmarks() { let pdf = pdf_bytes( "\\section{One}\n\n\\subsection{Sub}\n\n\\newpage\n\n\\section{Two}\n\nSecond.", ) .expect("pdf"); let text = String::from_utf8_lossy(&pdf); assert!(text.contains("/Type /Outlines")); assert!(text.contains("/Title (1 One)")); assert!(text.contains("/Title (1.1 Sub)")); assert!(text.contains("/Title (2 Two)")); assert!(text.contains("/Count 3")); } #[test] fn hypersetup_writes_the_pdf_info_dictionary() { let pdf = pdf_bytes("\\hypersetup{pdftitle={My Title},pdfauthor={Ada}}\n\nBody.").expect("pdf"); let text = String::from_utf8_lossy(&pdf); assert!(text.contains("/Title (My Title)")); assert!(text.contains("/Author (Ada)")); } #[test] fn pageref_reports_the_page_of_its_heading() { let source = "\\pagestyle{empty}\n\n\\section{One}\n\nFirst page.\n\n\\newpage\n\n\\section{Two}\\label{sec:two}\n\nSee page \\pageref{sec:two}."; let json = preview_json(source).expect("preview"); assert!( json.contains(">2"), "expected the second page number" ); assert!( !json.contains("pageref"), "the command must not leak: {json}" ); } #[test] fn pageref_reports_the_page_of_a_float() { let source = "\\pagestyle{empty}\n\n\\begin{figure}[h]\n\\rule{10pt}{10pt}\n\\caption{Cap}\n\\label{fig:a}\n\\end{figure}\n\n\\newpage\n\nSee page \\pageref{fig:a}."; let json = preview_json(source).expect("preview"); assert!(!json.contains("??"), "unresolved pageref: {json}"); assert!(!json.contains("pageref")); } #[test] fn unknown_pagerefs_print_question_marks() { let json = preview_json("\\pagestyle{empty}\n\nSee page \\pageref{missing}.").expect("preview"); assert!(json.contains(">?")); assert!(!json.contains("pageref")); } #[test] fn edef_expands_at_definition_time() { let (body, geometry) = geometry_and_body("\\def\\a{A}\n\\edef\\b{\\a B}\n\\def\\a{C}\n\nBody \\b."); assert_eq!(body, "Body A B."); assert_eq!( geometry.macros.len(), 2, "the later def replaces the earlier one" ); } #[test] fn csname_resolves_at_expansion_time() { let (body, _) = geometry_and_body("\\def\\foo{Z}\n\\edef\\cs{\\csname foo\\endcsname}\n\n\\cs."); assert_eq!(body, "Z."); } #[test] fn xdef_is_an_edef_alias() { let (body, _) = geometry_and_body("\\def\\x{1}\n\\xdef\\y{\\x}\n\\def\\x{2}\n\n\\y"); assert_eq!(body, "1"); } #[test] fn expandafter_chains_through_several_prefixes() { let (body, _) = geometry_and_body( "\\def\\a{1}\n\\def\\b{2}\n\\def\\c{3}\n\n\\expandafter\\a\\expandafter\\b\\c", ); assert_eq!(body, "123"); } #[test] fn expandafter_expands_the_following_token_first() { let (body, _) = geometry_and_body("\\def\\x{y}\n\\def\\y{Z}\n\n\\expandafter\\x\\y"); assert_eq!(body, "yZ"); } #[test] fn expandafter_concatenates_zero_argument_expansions() { let (body, _) = geometry_and_body("\\def\\a{1}\n\\def\\b{2}\n\n\\expandafter\\a\\b"); assert_eq!(body, "12"); } #[test] fn ifdefined_checks_declared_macros() { let (body, _) = geometry_and_body( "\\def\\known{} \\ifdefined\\known yes\\else no\\fi and \\ifdefined\\missing yes\\else no\\fi", ); assert_eq!(body, "yes and no"); } #[test] fn numbered_dimension_registers_track_values() { let source = "\\dimen0=3pt\n\\advance\\dimen0 by 2pt\n\nWidth \\the\\dimen0."; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry.numbered_dimens[0], 327_680); assert!(body.contains("Width 5.0pt."), "{body:?}"); } #[test] fn numbered_skip_registers_keep_their_components() { let source = "\\skip0=2pt plus 1pt\n\\advance\\skip0 by 1pt minus 1pt\n\nGap \\the\\skip0."; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry.numbered_skips[0], [196_608, 65_536, 65_536]); assert!( body.contains("Gap 3.0pt plus 1.0pt minus 1.0pt."), "{body:?}" ); } #[test] fn numbered_registers_accept_multi_digit_slots() { let source = "\\count12=7\n\\dimen42=3pt\n\\skip100=2pt plus 1pt\n\nA \\the\\count12 B \\the\\dimen42 C \\the\\skip100."; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry.numbered_counts[12], 7); assert_eq!(geometry.numbered_dimens[42], 196_608); assert_eq!(geometry.numbered_skips[100], [131_072, 65_536, 0]); assert!(body.contains("A 7 B 3.0pt C 2.0pt plus 1.0pt."), "{body:?}"); } #[test] fn numbered_count_registers_track_arithmetic() { let source = "\\count0=5\n\\advance\\count0 by 2\n\\multiply\\count0 by 3\n\\divide\\count0 by 2\n\nSteps \\the\\count0."; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry.numbered_counts[0], 10); assert!(body.contains("Steps 10."), "{body:?}"); } #[test] fn numbered_count_registers_print_with_number() { let source = "\\count2=7\n\nValue \\number\\count2."; let (body, _geometry) = geometry_and_body(source); assert!(body.contains("Value 7."), "{body:?}"); } #[test] fn count_registers_track_integer_arithmetic() { let source = "\\newcount\\steps\n\\steps=5\n\\advance\\steps by 2\n\\multiply\\steps by 3\n\\divide\\steps by 2\n\nSteps \\the\\steps."; let (body, geometry) = geometry_and_body(source); assert_eq!(body.trim(), "Steps 10."); assert!(!body.contains("newcount")); assert_eq!( geometry.count_registers, vec![("steps".to_string(), 10)], "register value" ); } #[test] fn count_registers_accept_negative_values() { let source = "\\newcount\\depth\n\\depth=-4\n\\advance\\depth by 1\n\nDepth \\number\\depth."; let (body, geometry) = geometry_and_body(source); assert_eq!(body.trim(), "Depth -3."); assert_eq!(geometry.count_registers, vec![("depth".to_string(), -3)]); } #[test] fn ifnum_compares_literal_integers() { let source = "\\ifnum 2 < 3 smaller\\else bigger\\fi and \\ifnum 3=2 no\\else yes\\fi"; let (body, _) = geometry_and_body(source); assert_eq!(body.trim(), "smaller and yes"); } #[test] fn ifnum_reads_count_registers() { let source = "\\newcount\\a\n\\a=3\n\n\\ifnum\\a=3 yes\\else no\\fi"; let (body, _) = geometry_and_body(source); assert_eq!(body.trim(), "yes"); } #[test] fn ifnum_reads_latex_counters() { let source = "\\setcounter{section}{2}\n\n\\ifnum\\value{section}=2 two\\else other\\fi"; let (body, _) = geometry_and_body(source); assert_eq!(body.trim(), "two"); } #[test] fn if_compares_character_codes() { let same = "\\if a a same\\else diff\\fi"; let (body, _) = geometry_and_body(same); assert_eq!(body.trim(), "same"); let different = "\\if a b same\\else diff\\fi"; let (body, _) = geometry_and_body(different); assert_eq!(body.trim(), "diff"); } #[test] fn ifodd_tests_integer_parity() { let odd = "\\ifodd 3 odd\\else even\\fi"; let (body, _) = geometry_and_body(odd); assert_eq!(body.trim(), "odd"); let even = "\\ifodd 2 odd\\else even\\fi"; let (body, _) = geometry_and_body(even); assert_eq!(body.trim(), "even"); } #[test] fn unless_inverts_the_next_conditional() { let undefined = "\\unless\\ifdefined\\missing yes\\else no\\fi"; let (body, _) = geometry_and_body(undefined); assert_eq!(body.trim(), "yes"); let true_num = "\\unless\\ifnum 1=1 yes\\else no\\fi"; let (body, _) = geometry_and_body(true_num); assert_eq!(body.trim(), "no"); } #[test] fn chardef_defines_character_commands() { let source = concat!( r"\chardef\letter=65", "\n", r#"\chardef\quote="22"#, "\n\n", r"\letter\quote" ); let (body, geometry) = geometry_and_body(source); assert_eq!(body.trim(), "A\""); assert_eq!(geometry.macros.len(), 2); } #[test] fn compatibility_report_document_is_warning_free() { let source = r#"\documentclass{article} \newcommand{\vect}[1]{\mathbf{#1}} \newtheorem{claim}{Claim} \newenvironment{note}{\begin{quote}}{\end{quote}} \definecolor{accent}{HTML}{336699} \begin{document} \tableofcontents \listoffigures \section{Intro}\label{sec:intro} Text with $\vect{x}$, \textcolor{accent}{accent} and \fcolorbox{red}{yellow}{box}. \begin{claim}\label{cl:one} A claim. \end{claim} \begin{note} Quoted note. \end{note} \begin{itemize} \item First \begin{enumerate} \item Nested \end{enumerate} \end{itemize} \begin{center} Centred. \end{center} \begin{figure}[t] \rule{80pt}{30pt} \caption{A figure}\label{fig:one} \end{figure} \begin{table}[h] \begin{tabularx}{250pt}{lX} A & wide cell text \\ \end{tabularx} \caption{A table}\label{tab:one} \end{table} See \ref{sec:intro}, \ref{fig:one}, \pageref{tab:one}. \appendix \section{Extra}\label{sec:extra} Appendix text. \begin{thebibliography}{1} \bibitem{k} Entry. \end{thebibliography} \end{document} "#; let json = preview_json(source).expect("preview"); assert!(json.contains("\"warnings\":[]"), "warnings: {}", json); assert!(json.contains(">Q")); assert!( json.contains("stroke=") && json.contains("#ff0000"), "frame missing" ); } #[test] fn compatibility_report_class_document_is_warning_free() { let source = r#"\documentclass{report} \usepackage[margin=1in]{geometry} \tableofcontents \chapter{Start} Report body with \footnote{A note.} and $x^2 = 4$. \section{Detail} \begin{equation} a = b \end{equation} \chapter{Next} More text. "#; let preview = preview_json(source).expect("preview"); assert!(preview.contains("\"warnings\":[]"), "warnings: {preview}"); assert!(preview.contains(">C"), "contents heading"); assert!(preview.contains(">1"), "chapter number"); assert!(!preview.contains("chapter"), "chapter leaked"); } #[test] fn compatibility_geometry_document_is_warning_free() { let source = r#"\documentclass{article} \usepackage[margin=1in]{geometry} \linespread{1.15} \hypersetup{pdftitle={Doc},urlcolor=blue,linkbordercolor=red} \begin{document} \setcounter{page}{3} \section{One}\label{sec:one} A footnote\footnote{Note.} and a link \href{https://example.com}{Example} plus \url{https://example.com/a_b}. \begin{quotation} Quoted paragraph with $a^2+b^2=c^2$ math. \end{quotation} \begin{tabular}{lc} \hline A & B \\ \hline \end{tabular} \begin{figure}[b] \rule{60pt}{20pt} \caption{Bottom figure} \end{figure} \newpage Second page. \end{document} "#; let json = preview_json(source).expect("preview"); assert!(json.contains("\"warnings\":[]"), "warnings: {}", json); assert!(json.contains(">E")); assert!( json.contains("fill=") && json.contains("#0000ff"), "link colour missing" ); assert!( json.contains("stroke=") && json.contains("#ff0000"), "link border missing" ); } #[test] fn compatibility_sample_document_is_warning_free() { let source = concat!( "\\documentclass{article}\n", "\\title{A Sample}\n", "\\author{Ada}\n", "\\begin{document}\n", "\\maketitle\n\n", "\\begin{abstract}\nShort abstract.\n\\end{abstract}\n\n", "\\tableofcontents\n\n", "\\section{One}\n\\label{sec:one}\n\n", "Some \\textbf{bold} text with $x^2$ math.\n\n", "\\begin{equation}\n a = b\n\\end{equation}\n\n", "\\begin{figure}[t]\n\\rule{100pt}{40pt}\n\\caption{Cap}\n\\label{fig:a}\n\\end{figure}\n\n", "\\begin{table}[h]\n\\begin{tabular}{lc}\n\\hline A & B \\\\\n\\hline\\end{tabular}\n\\caption{Tab}\n\\end{table}\n\n", "A note\\footnote{Note text.} and see \\ref{sec:one} on page \\pageref{fig:a}.\n\n", "\\begin{thebibliography}{1}\n\\bibitem{a} Entry.\n\\end{thebibliography}\n", "\\end{document}\n" ); let json = preview_json(source).expect("preview"); assert!(json.contains("\"warnings\":[]"), "warnings: {}", json); assert!(json.contains(">O")); assert!(json.contains(">C")); assert!(!json.contains("??"), "unresolved references: {}", json); } #[test] fn ifcat_compares_character_categories() { let letters = "\\ifcat a b same\\else diff\\fi"; let (body, _) = geometry_and_body(letters); assert_eq!(body.trim(), "same"); let digit = "\\ifcat a 1 same\\else diff\\fi"; let (body, _) = geometry_and_body(digit); assert_eq!(body.trim(), "diff"); let controls = "\\ifcat\\a\\b same\\else diff\\fi"; let (body, _) = geometry_and_body(controls); assert_eq!(body.trim(), "same"); } #[test] fn ifx_compares_macro_meaning() { let same = "\\def\\x{A}\n\\def\\y{A}\n\n\\ifx\\x\\y same\\else diff\\fi"; let (body, _) = geometry_and_body(same); assert_eq!(body.trim(), "same"); let different = "\\def\\x{A}\n\\def\\y{B}\n\n\\ifx\\x\\y same\\else diff\\fi"; let (body, _) = geometry_and_body(different); assert_eq!(body.trim(), "diff"); } #[test] fn noexpand_keeps_a_token_for_later_expansion() { let protected = "\\def\\a{A}\n\\edef\\b{\\noexpand\\a}\n\\def\\a{C}\n\n\\b"; let (body, _) = geometry_and_body(protected); assert_eq!(body.trim(), "C", "noexpand store should expand at use time"); let expanded = "\\def\\a{A}\n\\edef\\b{\\a}\n\\def\\a{C}\n\n\\b"; let (body, _) = geometry_and_body(expanded); assert_eq!(body.trim(), "A", "plain edef should capture the old body"); } #[test] fn noexpand_keeps_a_character_literal() { let source = "\\def\\x{A}\n\\edef\\y{\\noexpand\\x}\n\\def\\x{B}\n\n\\y"; let (body, _) = geometry_and_body(source); assert_eq!(body.trim(), "B"); } #[test] fn ifcase_selects_the_numbered_branch() { let (body, _) = geometry_and_body("\\ifcase 2 zero\\or one\\or two\\else other\\fi"); assert_eq!(body.trim(), "two"); } #[test] fn ifcase_falls_back_to_else() { let (body, _) = geometry_and_body("\\ifcase 5 zero\\or one\\else other\\fi"); assert_eq!(body.trim(), "other"); } #[test] fn ifcase_reads_count_registers() { let (body, _) = geometry_and_body("\\newcount\\k\n\\k=1\n\n\\ifcase\\k zero\\or one\\fi"); assert_eq!(body.trim(), "one"); } #[test] fn ifcase_handles_nested_conditionals() { let (body, _) = geometry_and_body("\\ifcase 0 yes\\iftrue A\\else B\\fi\\or no\\fi"); assert_eq!(body.trim(), "yesA"); } #[test] fn latex_internal_first_of_two_picks_arguments() { let (body, _) = geometry_and_body("\\@firstoftwo{A}{B} \\@secondoftwo{C}{D} \\@firstofone{E}"); assert_eq!(body.trim(), "A D E"); } #[test] fn at_namedef_and_nameuse_share_macros() { let (body, geometry) = geometry_and_body("\\@namedef{inner}{Z}\n\nBody \\@nameuse{inner}."); assert_eq!(body.trim(), "Body Z."); assert!( geometry .macros .iter() .any(|definition| definition.name == "\\inner" && definition.body == "Z"), "named macro recorded" ); } #[test] fn at_ifundefined_chooses_its_branch() { let (body, _) = geometry_and_body( "\\@namedef{known}{}\n\nFirst \\@ifundefined{known}{no}{yes}, second \\@ifundefined{other}{no}{yes}.", ); assert_eq!(body.trim(), "First yes, second no."); } #[test] fn numexpr_evaluates_arithmetic() { let (body, _) = geometry_and_body("\\the\\numexpr 2+3*4\\relax and \\the\\numexpr (2+3)*4\\relax"); assert_eq!(body.trim(), "14 and 20"); } #[test] fn numexpr_reads_count_registers() { let (body, _) = geometry_and_body("\\newcount\\a\n\\a=5\n\n\\the\\numexpr\\a*2+1\\relax"); assert_eq!(body.trim(), "11"); } #[test] fn numexpr_prints_without_the() { let (body, _) = geometry_and_body("Width \\numexpr 10-3\\relax."); assert_eq!(body.trim(), "Width 7."); } #[test] fn skip_registers_track_glue_arithmetic() { let (body, geometry) = geometry_and_body( "\\newskip\\gap\n\\gap=2pt plus 1pt\n\\advance\\gap by 3pt minus 1pt\n\nGap \\the\\gap.", ); assert_eq!(body.trim(), "Gap 5.0pt plus 1.0pt minus 1.0pt."); assert_eq!( geometry.skip_registers, vec![("gap".to_string(), [327_680, 65_536, 65_536])] ); } #[test] fn glue_expressions_combine_components() { let source = "\\newskip\\gap\n\\gap=\\glueexpr 2pt plus 1pt minus 1pt\\relax\n\nGap \\the\\glueexpr \\gap + 1pt\\relax."; let (_body, geometry) = geometry_and_body(source); let (_, glue) = geometry .skip_registers .iter() .find(|(name, _)| name == "gap") .expect("gap register"); assert_eq!(*glue, [131_072, 65_536, -65_536]); assert!( _body.contains("Gap 3.0pt plus 1.0pt minus 1.0pt."), "{_body:?}" ); } #[test] fn glue_expressions_parenthesise_components() { let (body, geometry) = geometry_and_body( "\\newskip\\gap\n\\gap=\\glueexpr (2pt plus 1pt minus 1pt) + 3pt\\relax\n\nGap \\the\\gap.", ); let (_, glue) = geometry .skip_registers .iter() .find(|(name, _)| name == "gap") .expect("gap register"); assert_eq!(*glue, [327_680, 65_536, -65_536]); assert!( body.contains("Gap 5.0pt plus 1.0pt minus 1.0pt."), "{body:?}" ); } #[test] fn declare_robust_command_defines_a_macro() { let (body, geometry) = geometry_and_body("\\DeclareRobustCommand{\\hello}{Hi}\n\n\\hello there."); assert!(body.contains("Hi there."), "{body:?}"); assert!(geometry.macros.iter().any(|m| m.name == "\\hello")); } #[test] fn providecommand_keeps_an_existing_definition() { let (body, _) = geometry_and_body("\\newcommand{\\a}{A}\n\\providecommand{\\a}{B}\n\n\\a."); assert!(body.contains("A."), "{body:?}"); let (body, _) = geometry_and_body("\\providecommand{\\b}{B}\n\n\\b."); assert!(body.contains("B."), "{body:?}"); } #[test] fn setlength_assigns_skip_registers() { let (body, geometry) = geometry_and_body( "\\newskip\\gap\n\\setlength{\\gap}{10pt plus 2pt minus 3pt}\n\nGap \\the\\gap.", ); assert_eq!(body, "Gap 10.0pt plus 2.0pt minus 3.0pt."); assert_eq!(geometry.skip_registers[0].1, [655_360, 131_072, 196_608]); } #[test] fn dimension_expressions_evaluate() { let (body, geometry) = geometry_and_body( "\\newdimen\\gap\n\\gap=2pt\n\nGap \\the\\dimexpr \\gap + 3pt\\relax.\n\nTwice \\dimexpr 3pt * 2\\relax.", ); assert!(body.contains("Gap 5.0pt."), "{body}"); assert!(body.contains("Twice 6.0pt."), "{body}"); assert_eq!( geometry.dimension_registers, vec![("gap".to_string(), 2 * 65_536)] ); } #[test] fn dimension_registers_advance() { let (body, _) = geometry_and_body( "\\newdimen\\gap\n\\gap=5pt\n\\advance\\gap by 2pt\n\nGap \\the\\gap.", ); assert_eq!(body.trim(), "Gap 7.0pt."); } #[test] fn dimension_registers_scale() { let (body, _) = geometry_and_body( "\\newdimen\\gap\n\\gap=2.5pt\n\\multiply\\gap by 2\n\nGap \\the\\gap.", ); assert_eq!(body.trim(), "Gap 5.0pt."); } #[test] fn dimension_registers_divide() { let (body, _) = geometry_and_body("\\newdimen\\gap\n\\gap=9pt\n\\divide\\gap by 2\n\nGap \\the\\gap."); assert_eq!(body.trim(), "Gap 4.5pt."); } #[test] fn textcolor_mixes_named_colors() { let json = preview_json("\\textcolor{red!50!blue}{Purple} \\textcolor{red!25}{Tint}") .expect("preview"); assert!(json.contains(r##"fill=\"#800080\""##), "{json}"); assert!(json.contains(r##"fill=\"#ffbfbf\""##), "{json}"); } #[test] fn definecolor_models_produce_rgb_values() { assert_eq!( define_color("\\definecolor{red}{rgb}{1,0,0}"), Some(("red".to_string(), [255, 0, 0])) ); assert_eq!( define_color("\\definecolor{accent}{HTML}{336699}"), Some(("accent".to_string(), [0x33, 0x66, 0x99])) ); assert_eq!( define_color("\\definecolor{grey}{gray}{0.5}"), Some(("grey".to_string(), [128, 128, 128])) ); assert_eq!( define_color("\\definecolor{ink}{cmyk}{0,0,0,1}"), Some(("ink".to_string(), [0, 0, 0])) ); } #[test] fn definecolor_colors_are_used_by_textcolor() { let json = preview_json("\\definecolor{accent}{HTML}{336699}\n\n\\textcolor{accent}{Deep}") .expect("preview"); assert!(json.contains(r##"fill=\"#336699\""##), "{json}"); assert!(!json.contains("definecolor"), "{json}"); } #[test] fn color_switch_paints_the_rest_of_the_paragraph() { let json = preview_json("\\color{blue} Blue text.").expect("preview"); assert!(json.contains(r##"fill=\"#0000ff\""##), "{json}"); assert!(!json.contains("color{"), "{json}"); } #[test] fn at_ifstar_consumes_a_star() { let (body, _) = geometry_and_body("\\def\\cmd{\\@ifstar{starred}{plain}}\n\nA \\cmd* B \\cmd C."); assert!(body.contains("A starred B plain C."), "{body}"); } #[test] fn at_ifnextchar_chooses_by_lookahead() { let (body, _) = geometry_and_body("\\def\\opt{\\@ifnextchar[{[}{no}}\n\n\\opt[x] and \\opt y."); assert!(body.contains("[[x] and no y."), "{body}"); } #[test] fn gobble_commands_drop_arguments() { let (body, _) = geometry_and_body( "\\def\\gob{\\@gobble}\n\\def\\gobtwo{\\@gobbletwo}\n\nA \\gob{X} \\gobtwo{Y}{Z} B", ); assert!(!body.contains('X'), "{body}"); assert!(!body.contains('Y'), "{body}"); assert!(!body.contains('Z'), "{body}"); assert!(body.contains('A') && body.contains('B'), "{body}"); } #[test] fn ifmtarg_checks_for_an_empty_argument() { let (body, _) = geometry_and_body( "\\def\\ifempty{\\@ifmtarg}\n\n\\ifempty{}{empty}{not} \\ifempty{x}{empty}{not}", ); assert!(body.starts_with("empty not"), "{body}"); } #[test] fn definition_prefixes_are_transparent() { let (body, geometry) = geometry_and_body( "\\long\\def\\a{A}\n\\global\\def\\b{B}\n\\gdef\\c{C}\n\\protected@edef\\d{\\a\\b}\n\n\\a \\b \\c \\d", ); assert_eq!(body, "A B C AB"); assert_eq!(geometry.macros.len(), 4); assert!(!body.contains("long")); } #[test] fn global_let_copies_a_definition() { let (body, _) = geometry_and_body("\\def\\x{X}\n\\global\\let\\y=\\x\n\n\\y"); assert_eq!(body, "X"); } #[test] fn hypersetup_link_borders_draw_svg_frames() { let json = preview_json( "\\documentclass{article}\n\\usepackage{hyperref}\n\\hypersetup{urlbordercolor=red}\n\n\\begin{document}\nSee \\href{https://example.com}{Link}.\n\\end{document}", ) .expect("preview"); assert!(json.contains(r##"stroke=\"#ff0000\""##), "{json}"); let plain = preview_json( "\\documentclass{article}\n\\usepackage{hyperref}\n\n\\begin{document}\nSee \\href{https://example.com}{Link}.\n\\end{document}", ) .expect("preview"); assert!(!plain.contains("stroke="), "{plain}"); } #[test] fn page_numbers_follow_the_page_counter() { let offset = preview_json("\\setcounter{page}{5}\n\nAlpha\n\n\\newpage\n\nBeta") .expect("offset preview"); assert!(offset.contains(">5"), "got {offset}"); assert!(offset.contains(">6"), "got {offset}"); let reset = preview_json("\\setcounter{page}{5}\n\n\\pagenumbering{roman}\n\nAlpha") .expect("reset preview"); assert!(reset.contains(">i"), "got {reset}"); let later = preview_json("\\pagenumbering{roman}\n\n\\setcounter{page}{5}\n\nAlpha") .expect("later preview"); assert!(later.contains(">v"), "got {later}"); } #[test] fn page_numbers_survive_pdf_extraction() { use std::process::Command; if Command::new("pdftotext") .arg("-v") .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::null()) .status() .is_err() { return; } let pdf = pdf_bytes("Alpha").expect("pdf"); let path = std::env::temp_dir().join(format!("texrra-page-number-{}.pdf", std::process::id())); std::fs::write(&path, &pdf).expect("write pdf"); let output = Command::new("pdftotext") .arg(&path) .arg("-") .output() .expect("pdftotext"); let _ = std::fs::remove_file(&path); let text = String::from_utf8_lossy(&output.stdout); assert!(text.contains("Alpha"), "got {text:?}"); assert!(text.contains('1'), "got {text:?}"); } #[test] fn greek_text_paints_in_previews() { let json = preview_json("\u{3b1}\u{3b2}\u{3b3} \u{3bc}\u{3ad}\u{3b3}\u{3b1}").expect("preview"); assert!(json.contains(">\u{3b1}"), "got {json}"); assert!(!json.contains(">?")); } #[test] fn addtolength_updates_named_lengths() { let source = "\\newlength{\\gutter}\n\\setlength{\\gutter}{6pt}\n\\addtolength{\\gutter}{2pt}\n\\setlength{\\parindent}{\\gutter}\n\nText."; let (_, geometry) = geometry_and_body(source); assert_eq!(geometry.par_indent, Some(8 * 65_536)); } #[test] fn named_lengths_feed_setlength() { let source = "\\newlength{\\indent}\n\\setlength{\\indent}{2em}\n\\setlength{\\parindent}{\\indent}\n\\setlength{\\textwidth}{\\indent}\n\nText."; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry.par_indent, Some(1_310_720)); assert_eq!(geometry.line_width, Some(1_310_720)); assert_eq!( geometry .lengths .iter() .find(|(name, _)| name == "indent") .map(|(_, value)| *value), Some(1_310_720) ); assert!(!body.contains("newlength")); } #[test] fn graphics_paths_are_read_from_the_preamble() { let (body, geometry) = geometry_and_body( "\\graphicspath{{figures/}{plots}}\n\\begin{figure}[t]\n\\includegraphics{x}\n\\end{figure}", ); assert_eq!(geometry.graphics_paths, vec!["figures/", "plots/"]); assert!(!body.contains("graphicspath")); assert_eq!(graphics_paths("\\graphicspath{{a/}}"), vec!["a/"]); } #[test] fn figure_graphics_reserve_a_placeholder() { let source = "\\begin{figure}[b]\n\\includegraphics[width=200pt]{plot.pdf}\\caption{Plot}\n\\end{figure}"; let (body, geometry) = geometry_and_body(source); let blocks = paragraphs(&body).unwrap(); let document = build_document(&blocks, &geometry); let Some(VerticalItem::Float(float)) = document.units[0].items.first() else { panic!("expected a float unit"); }; assert_eq!(float.placement, FloatPlacement::Bottom); let Some(VerticalItem::Rule { width, height }) = float.content.first() else { panic!("expected a graphics rule"); }; assert_eq!(*width, 200 * SCALE); assert_eq!(*height, 100 * SCALE); } #[test] fn table_captions_sit_above_their_tabular() { let source = "\\begin{table}[t]\n\\caption{Numbers}\n\\begin{tabular}{ll}\na & b \\\\\n\\end{tabular}\n\\end{table}"; let (body, geometry) = geometry_and_body(source); let blocks = paragraphs(&body).expect("blocks"); assert_eq!(blocks.len(), 1); let document = build_document(&blocks, &geometry); let VerticalItem::Float(float) = &document.units[0].items[0] else { panic!("expected a float"); }; let caption = match &float.content[0] { VerticalItem::Paragraph(paragraph) => paragraph, other => panic!("expected the caption first, got {other:?}"), }; let text: String = caption .lines .iter() .flatten() .map(|item| match item { texrra_tex_core::paragraph::HorizontalItem::Box(character) => { character.character.unwrap_or(' ') } texrra_tex_core::paragraph::HorizontalItem::Glue { width, .. } if *width > 0 => ' ', _ => '\0', }) .filter(|character| *character != '\0') .collect(); assert_eq!(text, "Table 1: Numbers"); assert!(matches!(float.content[1], VerticalItem::Halign(_))); } #[test] fn starred_captions_stay_unnumbered() { let source = "\\begin{figure}[t]\n\\caption*{Note}\n\\end{figure}\n\n\\begin{figure}[t]\n\\caption{Numbered}\n\\end{figure}"; let (body, _) = geometry_and_body(source); let mut blocks = paragraphs(&body).expect("blocks"); assert_eq!(blocks.len(), 2); number_floats(&mut blocks, "Figure", "Table", 0, 0); let first = blocks[0].float.as_ref().expect("first float"); assert_eq!(first.caption.as_deref(), Some("Note")); let second = blocks[1].float.as_ref().expect("second float"); assert_eq!(second.caption.as_deref(), Some("Figure 1: Numbered")); } #[test] fn tabular_cline_draws_partial_rules() { let source = r"\begin{tabular}{ll} A & B \\ \cline{2-2} C & D \\ \end{tabular}"; let (body, geometry) = geometry_and_body(source); let blocks = paragraphs(&body).unwrap(); let document = build_document(&blocks, &geometry); let Some(VerticalItem::Halign(halign)) = document.units[0].items.first() else { panic!("expected halign"); }; assert_eq!(halign.rows.len(), 2); assert_eq!(halign.rules.len(), 1); assert_eq!(halign.rules[0].start, 1); assert_eq!(halign.rules[0].end, 1); } #[test] fn tabular_multicolumn_cells_span_columns() { let source = r"\begin{tabular}{|l|c|} \multicolumn{2}{|c|}{Merged} \\ A & B \\ \end{tabular}"; let (body, geometry) = geometry_and_body(source); let blocks = paragraphs(&body).unwrap(); let document = build_document(&blocks, &geometry); let Some(VerticalItem::Halign(halign)) = document.units[0].items.first() else { panic!("expected halign"); }; assert_eq!(halign.rows[0].cells.len(), 1); assert_eq!(halign.rows[0].cells[0].text, "Merged"); assert_eq!(halign.rows[0].cells[0].span, 2); assert_eq!( halign.rows[0].cells[0].alignment, texrra_tex_core::CellAlignment::Center ); assert_eq!(halign.rows[1].cells.len(), 2); } #[test] fn table_floats_carry_their_tabular() { let source = r"\begin{table}[t] \caption{Numbers}\label{tab:a} \begin{tabular}{|l|c|} A & 1 \\ B & 2 \\ \end{tabular} \end{table} See \ref{tab:a}."; let (body, geometry) = geometry_and_body(source); let blocks = paragraphs(&body).unwrap(); let document = build_document(&blocks, &geometry); assert_eq!(document.units.len(), 2); let Some(VerticalItem::Float(float)) = document.units[0].items.first() else { panic!("expected a table float"); }; assert!( float .content .iter() .any(|item| matches!(item, VerticalItem::Halign(_))) ); let mut caption = String::new(); for item in &float.content { if let VerticalItem::Paragraph(paragraph) = item { for line in ¶graph.lines { for item in line { match item { texrra_tex_core::paragraph::HorizontalItem::Box(box_) => { if let Some(character) = box_.character { caption.push(character); } } texrra_tex_core::paragraph::HorizontalItem::Glue { width, .. } => { if *width > 0 { caption.push(' '); } } _ => {} } } } } } assert_eq!(caption, "Table 1: Numbers"); assert_eq!(document.units[1].source, "See 1."); } #[test] fn figure_and_table_labels_count_independently() { let source = r"\begin{figure}[h] \caption{Shape}\label{fig:a} \end{figure} \begin{table}[h] \caption{Data}\label{tab:b} \end{table} See \ref{fig:a} and \ref{tab:b}."; let (body, geometry) = geometry_and_body(source); let blocks = paragraphs(&body).unwrap(); let document = build_document(&blocks, &geometry); assert_eq!(document.units[2].source, "See 1 and 1."); } #[test] fn links_keep_their_text_and_style_urls() { let (body, _) = geometry_and_body( "See \\href{https://example.com}{Example} and \\url{https://x.test/a_b}.", ); assert!( body.contains(r"\href{https://example.com}{Example}") && body.contains(r"\texttt{https://x.test/a_b}."), "{body}" ); } #[test] fn verbatim_links_stay_literal() { let (body, _) = geometry_and_body("\\begin{verbatim}\n\\url{https://x}\n\\end{verbatim}"); assert!(body.contains("\\url{https://x}"), "{body}"); } #[test] fn verbatim_lines_stay_monospaced() { let source = "\\begin{verbatim}\nlet x = 1;\nreturn x;\n\\end{verbatim}"; let blocks = paragraphs(source).expect("blocks"); assert_eq!(blocks.len(), 2); assert_eq!(blocks[0].text, "let x = 1;"); assert_eq!(blocks[1].text, "return x;"); assert_eq!(blocks[0].font, ParagraphFont::Mono); assert_eq!(blocks[0].left_skip, 12); assert_eq!(blocks[0].space_before, 6 * SCALE); assert_eq!(blocks[1].space_before, 0); } #[test] fn today_expands_to_the_current_date() { let (body, _geometry) = geometry_and_body("Body \\today."); assert_eq!(body.trim(), format!("Body {}.", today_string())); let date = today_string(); assert!(date.chars().any(|character| character.is_ascii_digit())); assert!(date.contains(',')); } #[test] fn maketitle_defaults_to_today_when_no_date_is_set() { let (body, geometry) = geometry_and_body("\\maketitle"); let blocks = paragraphs(&body).expect("paragraphs"); let document = build_document(&blocks, &geometry); let today = today_string(); assert!(document.units.iter().any(|unit| unit.source == today)); } #[test] fn explicit_empty_date_suppresses_the_title_date() { let (body, geometry) = geometry_and_body("\\date{}\n\\maketitle"); let blocks = paragraphs(&body).expect("paragraphs"); let document = build_document(&blocks, &geometry); let today = today_string(); assert!(document.units.iter().all(|unit| unit.source != today)); } #[test] fn list_items_take_article_separations() { let blocks = paragraphs("\\begin{itemize}\n\\item One\n\\item Two\n\\end{itemize}").expect("blocks"); assert_eq!(blocks[0].space_before, 10, "article topsep plus partopsep"); assert_eq!(blocks[0].space_stretch, 3); assert_eq!(blocks[0].space_shrink, 5); assert_eq!(blocks[1].space_before, 4, "article itemsep at 10pt"); assert_eq!(blocks[1].space_stretch, 2); assert_eq!(blocks[1].space_shrink, 1); } #[test] fn list_separations_follow_setlength() { let source = "\\setlength{\\topsep}{3pt plus 1pt minus 2pt}\n\\setlength{\\itemsep}{6pt plus 2pt minus 1pt}\n\n\\begin{enumerate}\n\\item One\n\\item Two\n\\end{enumerate}"; let (body, geometry) = geometry_and_body(source); let blocks = paragraphs_with_geometry(&body, &[], 0, &geometry).expect("blocks"); assert_eq!(blocks[0].space_before, 5, "topsep plus partopsep"); assert_eq!(blocks[0].space_stretch, 2); assert_eq!(blocks[0].space_shrink, 3); assert_eq!(blocks[1].space_before, 6); assert_eq!(blocks[1].space_stretch, 2); assert_eq!(blocks[1].space_shrink, 1); } #[test] fn list_separations_follow_the_class_size() { let source = "\\documentclass[12pt]{article}\n\\begin{document}\n\n\\begin{itemize}\n\\item One\n\\item Two\n\\end{itemize}\n\n\\end{document}"; let (body, geometry) = geometry_and_body(source); let blocks = paragraphs_with_geometry(&body, &[], 0, &geometry).expect("blocks"); assert_eq!(blocks[0].space_before, 13, "12pt topsep plus partopsep"); assert_eq!(blocks[1].space_before, 5, "12pt itemsep"); } #[test] fn tabular_star_specs_repeat_columns() { let source = "\\begin{tabular}{*{3}{c}}\na & b & c\n\\end{tabular}"; let (body, geometry) = geometry_and_body(source); let blocks = paragraphs_with_geometry(&body, &[], 0, &geometry).expect("blocks"); let document = build_document(&blocks, &geometry); let halign = document .units .iter() .find_map(|unit| match &unit.items[0] { VerticalItem::Halign(halign) => Some(halign), _ => None, }) .expect("halign"); assert_eq!(halign.column_widths.len(), 3); assert_eq!(halign.rows.len(), 1); assert_eq!(halign.rows[0].cells.len(), 3); } #[test] fn tabular_optional_position_is_ignored() { let (body, geometry) = geometry_and_body("\\begin{tabular}[t]{ll}\nA & B\n\\end{tabular}"); assert_eq!(geometry.tabular.len(), 1); assert_eq!(geometry.tabular[0].0, "ll"); assert!(body.contains("texrratable"), "missing placeholder: {body}"); assert!(!body.contains("tabular"), "environment leaked: {body}"); } #[test] fn starred_floats_behave_like_normal_floats() { let source = "\\begin{figure*}[t]\n\\rule{10pt}{10pt}\n\\caption{Wide}\n\\label{fig:wide}\n\\end{figure*}\n\nSee Figure~\\ref{fig:wide}."; let (_, geometry) = geometry_and_body(source); assert_eq!(geometry.tabular.len(), 0); let json = preview_json(source).expect("preview"); assert!(json.contains("\"warnings\":[]"), "warnings: {json}"); assert!(!json.contains("figure*")); assert!(json.contains(">W")); } #[test] fn multirow_cells_keep_their_text() { let source = "\\begin{tabular}{ll}\n\\multirow{2}{*}{Both} & a \\\\\n & b\n\\end{tabular}\n\nTail."; let (_, geometry) = geometry_and_body(source); assert_eq!(geometry.tabular.len(), 1); let (_, text, _) = &geometry.tabular[0]; assert!(text.contains("texrramultirow{2}{Both}"), "{text}"); assert!(!text.contains("\\multirow")); let json = preview_json(source).expect("preview"); assert!(json.contains(">Both")); assert!(!json.contains("multirow")); } #[test] fn captionof_creates_a_numbered_caption() { let source = "\\captionof{figure}{Standalone}\\label{cap:x}\n\nSee Figure~\\ref{cap:x}."; let json = preview_json(source).expect("preview"); assert!(json.contains("\"warnings\":[]"), "warnings: {json}"); assert!(!json.contains("captionof")); assert!(!json.contains("??"), "unresolved reference: {json}"); assert!(json.contains(">S")); } #[test] fn newcolumntype_accepts_arguments() { let source = "\\newcolumntype{C}[1]{>{\\centering}p{#1}}\n\n\\begin{tabular}{C{20mm}l}\nalpha beta & right \\\\\n\\end{tabular}"; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry.column_types.len(), 1); assert_eq!(geometry.column_types[0].2, 1); assert!(!body.contains("newcolumntype")); let json = preview_json(source).expect("preview"); assert!(json.contains("\"warnings\":[]"), "warnings: {json}"); assert!(!json.contains("#1")); } #[test] fn tabular_star_stretches_to_its_width() { let source = "\\begin{tabular*}{200pt}{ll}\na & b \\\\\n\\end{tabular*}"; let (body, geometry) = geometry_and_body(source); let blocks = paragraphs(&body).expect("paragraphs"); let document = build_document(&blocks, &geometry); let halign = document .units .iter() .flat_map(|unit| &unit.items) .find_map(|item| match item { VerticalItem::Halign(halign) => Some(halign), _ => None, }) .expect("tabular halign"); assert_eq!(halign.column_widths.len(), 2); assert!( (halign.width - 200 * SCALE).abs() < 2 * SCALE, "width {}", halign.width ); } #[test] fn tabular_star_renders_its_table() { let source = "\\begin{tabular*}{200pt}{ll}\na & b \\\\\n\\end{tabular*}"; let (_, geometry) = geometry_and_body(source); assert_eq!(geometry.tabular.len(), 1); let json = preview_json(source).expect("preview"); assert!(json.contains("\"warnings\":[]"), "warnings: {json}"); assert!(!json.contains("tabular*")); } #[test] fn newcolumntype_expands_in_templates() { let source = "\\newcolumntype{L}{>{\\centering}p{20mm}}\n\n\\begin{tabular}{Ll}\nalpha beta & right \\\\\n\\end{tabular}"; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry.column_types.len(), 1); assert!(!body.contains("newcolumntype")); let json = preview_json(source).expect("preview"); assert!(json.contains("\"warnings\":[]"), "warnings: {json}"); assert!(!json.contains("centering")); } #[test] fn array_column_modifiers_stay_out_of_the_text() { let source = "\\begin{tabular}{>{\\centering}p{20mm}l}\nalpha beta & right \\\\\n\\end{tabular}"; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry.tabular.len(), 1); let json = preview_json(source).expect("preview"); assert!(json.contains("\"warnings\":[]"), "warnings: {json}"); assert!(!json.contains("centering")); assert!(!body.contains("centering")); } #[test] fn tabularx_fills_its_target_width() { let source = "\\begin{tabularx}{200pt}{lX}\na & alpha beta gamma \\\\\nb & delta\n\\end{tabularx}"; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry.tabular.len(), 1); let template = &geometry.tabular[0].0; assert_eq!(template, "lX"); assert!(geometry.tabular[0].2.is_some(), "target width missing"); assert!(body.contains("\\texrratable{0}")); let blocks = paragraphs_with_geometry( &body, &PageGeometry::default().theorem_definitions, 0, &geometry, ) .expect("paragraphs"); let document = build_document(&blocks, &geometry); let halign = document .units .iter() .find_map(|unit| { unit.items.iter().find_map(|item| match item { VerticalItem::Halign(halign) => Some(halign.clone()), _ => None, }) }) .expect("halign"); assert_eq!(halign.column_widths.len(), 2); assert!(halign.column_widths[1] > halign.column_widths[0]); let width = halign.width; assert!( (width - 200 * SCALE).abs() <= 2 * SCALE, "width {width} not near 200pt" ); } #[test] fn longtable_captures_its_body() { let (body, geometry) = geometry_and_body("\\begin{longtable}{ll}\na & b \\\\\n\\end{longtable}\n\nBody."); assert_eq!(geometry.tabular.len(), 1); assert_eq!(geometry.tabular[0].0, "ll"); assert!(geometry.tabular[0].1.contains("a & b")); assert!(body.contains("\\texrratable{0}")); assert!(!body.contains("longtable")); } #[test] fn rule_paragraphs_become_rule_boxes() { let blocks = paragraphs("\\rule{20pt}{5pt}").expect("rule"); assert_eq!(blocks.len(), 1); let spec = blocks[0].float.as_ref().expect("rule float"); assert_eq!(spec.width, Some(ImageLength::Absolute(20 * SCALE))); assert_eq!(spec.height, Some(ImageLength::Absolute(5 * SCALE))); assert!(spec.caption.is_none()); let document = build_document(&blocks, &PageGeometry::default()); let Some(VerticalItem::Float(float)) = document.units[0].items.first() else { panic!("expected float rule unit"); }; assert!(matches!( float.content.first(), Some(VerticalItem::Rule { width, height }) if *width == 20 * SCALE && *height == 5 * SCALE )); } #[test] fn centered_environments_parse_their_body() { let blocks = paragraphs("\\begin{center}\n\\rule{20pt}{5pt}\n\\end{center}").expect("center"); assert_eq!(blocks.len(), 1); assert!(blocks[0].float.is_some()); } #[test] fn quotation_parses_nested_lists() { let blocks = paragraphs( "\\begin{quotation}\n\\begin{itemize}\n\\item a\n\\item b\n\\end{itemize}\n\\end{quotation}", ) .expect("quotation"); assert_eq!(blocks.len(), 2); assert_eq!(blocks[0].left_skip, 32); assert_eq!(blocks[1].left_skip, 32); } #[test] fn verse_keeps_its_line_breaks() { let blocks = paragraphs("\\begin{verse}\nline one \\\\\nline two\n\\end{verse}").expect("verse"); assert_eq!(blocks.len(), 2); assert_eq!(blocks[0].text, "line one"); assert_eq!(blocks[0].left_skip, 20); assert_eq!(blocks[1].text, "line two"); assert_eq!(blocks[1].left_skip, 20); } #[test] fn quotation_indents_both_margins() { let source = "\\begin{quotation}\nOne paragraph.\n\nTwo paragraph.\n\\end{quotation}"; let blocks = paragraphs(source).expect("paragraphs"); assert_eq!(blocks.len(), 2); assert!( blocks .iter() .all(|block| block.left_skip == 20 && block.right_skip == 20) ); assert!(blocks[0].text.starts_with("One")); assert!(blocks[1].text.starts_with("Two")); } #[test] fn quotation_narrows_the_measure() { let long = "alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron pi rho sigma tau upsilon phi chi psi omega"; let plain = paragraphs(long).expect("paragraphs"); let indented = paragraphs(&format!("\\begin{{quotation}}\n{long}\n\\end{{quotation}}")) .expect("paragraphs"); let geometry = PageGeometry { line_width: Some(200 * SCALE), ..PageGeometry::default() }; let plain_document = build_document(&plain, &geometry); let quote_document = build_document(&indented, &geometry); let lines = |document: &Document| { document.units[0] .items .iter() .find_map(|item| match item { VerticalItem::Paragraph(paragraph) => Some(paragraph.lines.len()), _ => None, }) .expect("paragraph") }; assert!(lines("e_document) > lines(&plain_document)); assert_eq!( quote_document.units[0] .paragraph_style .as_ref() .expect("style") .right_skip, 20 * SCALE ); } #[test] fn list_items_hang_their_continuation_lines() { let source = "\\begin{itemize}\n\\item alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron\n\\end{itemize}"; let blocks = paragraphs(source).expect("paragraphs"); assert_eq!(blocks[0].list_depth, Some(0)); let geometry = PageGeometry { line_width: Some(140 * SCALE), ..PageGeometry::default() }; let document = build_document(&blocks, &geometry); let paragraph = document.units[0] .items .iter() .find_map(|item| match item { VerticalItem::Paragraph(paragraph) => Some(paragraph), _ => None, }) .expect("list paragraph"); assert!(paragraph.lines.len() > 1, "the item must wrap"); let hang = (blocks[0].list_label + 5) * SCALE; assert_eq!(paragraph.left_skip, 12 * SCALE + hang); assert_eq!(paragraph.line_indents[0], -hang); assert_eq!(paragraph.line_indents[1], 0); } #[test] fn nested_lists_use_the_second_level_skips() { let source = "\\begin{itemize}\n\\item Outer\n\\begin{itemize}\n\\item Inner\n\\item More\n\\end{itemize}\n\\item Next\n\\end{itemize}"; let blocks = paragraphs(source).expect("blocks"); let spaces: Vec = blocks.iter().map(|block| block.space_before).collect(); assert_eq!(spaces, vec![10, 6, 2, 4]); } #[test] fn enumerate_honours_setcounter_in_its_preamble() { let blocks = paragraphs( "\\begin{enumerate}\n\\setcounter{enumi}{4}\n\\item Fifth\n\\item Sixth\n\\end{enumerate}", ) .expect("paragraphs"); assert_eq!(blocks.len(), 2); assert_eq!(blocks[0].text, "5. Fifth"); assert_eq!(blocks[1].text, "6. Sixth"); } #[test] fn nested_itemize_indents_and_relabels() { let source = "\\begin{itemize}\n\\item Outer\n\\begin{itemize}\n\\item Inner\n\\end{itemize}\n\\end{itemize}"; let blocks = paragraphs(source).unwrap(); assert_eq!( blocks.len(), 2, "{:?}", blocks.iter().map(|b| &b.text).collect::>() ); 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 = blocks.iter().map(|block| block.left_skip).collect(); assert_eq!(skips, [12, 24, 24, 12]); } #[test] fn item_labels_override_generated_markers() { let blocks = paragraphs( "\\begin{itemize}\n\\item[--] Dash\n\\item Next\n\\end{itemize}\n\n\\begin{enumerate}\n\\item[(iv)] Fourth\n\\end{enumerate}", ) .expect("paragraphs"); assert_eq!(blocks[0].text, "-- Dash"); assert_eq!(blocks[1].text, "• Next"); assert_eq!(blocks[2].text, "(iv) Fourth"); } #[test] fn description_items_keep_their_terms() { let source = "\\begin{description}\n\\item[Term] Definition\n\\end{description}"; let blocks = paragraphs(source).unwrap(); assert_eq!(blocks.len(), 1); assert_eq!(blocks[0].text, "\\textbf{Term} — Definition"); assert_eq!(blocks[0].left_skip, 12); } #[test] fn description_terms_are_bold() { let json = preview_json("\\begin{description}\n\\item[Term] Definition\n\\end{description}") .expect("preview"); assert!(json.contains(r#"font-weight=\"bold\""#), "{json}"); assert!(json.contains(">T"), "{json}"); } #[test] fn newif_definitions_default_to_false() { let source = "\\newif\\ifdraft\n\\ifdraft Draft\\else Final\\fi"; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry.conditionals.len(), 1); assert_eq!(geometry.conditionals[0].name, "draft"); assert!(!geometry.conditionals[0].value); assert_eq!(body.trim(), "Final"); } #[test] fn conditional_assignments_select_the_true_branch() { let source = "\\newif\\ifdraft\n\\drafttrue\n\n\\ifdraft Draft\\else Final\\fi"; let (body, _) = geometry_and_body(source); assert_eq!(body.trim(), "Draft"); } #[test] fn conditional_assignments_in_the_body_take_effect() { let source = "\\newif\\ifdraft\n\nA\\ifdraft X\\else Y\\fi B\\drafttrue C\\ifdraft Z\\else W\\fi D"; let (body, _) = geometry_and_body(source); assert_eq!(body.trim(), "AY B CZ 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(), "AB"); } #[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 andB"); } #[test] fn display_break_hints_are_dropped() { let source = "\\allowdisplaybreaks[2]\n\nText \\displaybreak[1] here."; let json = preview_json(source).expect("preview"); assert!(json.contains("\"warnings\":[]"), "warnings: {json}"); assert!(!json.contains("displaybreak")); assert!(!json.contains("allowdisplaybreaks")); } #[test] fn preamble_only_guards_leave_no_text() { let source = "\\@onlypreamble\\foo\\@nopreamble\\bar Text"; let (body, _) = geometry_and_body(source); assert_eq!(body.trim(), "Text"); } #[test] fn ifdefinable_runs_its_branch_for_undefined_commands() { let source = "\\def\\known{X}\n\n\\@ifdefinable\\known{defined}\\@ifdefinable\\other{defined}"; let (body, _) = geometry_and_body(source); assert_eq!(body.trim(), "defined"); } #[test] fn ifclassloaded_selects_supported_classes() { let source = "\\@ifclassloaded{article}{article}{other} \ \\@ifclassloaded{beamer}{beamer}{other}"; let (body, _) = geometry_and_body(source); assert_eq!(body.trim(), "article other"); } #[test] fn ifpackageloaded_selects_known_packages() { let source = "\\@ifpackageloaded{hyperref}{loaded}{missing} \ \\@ifpackageloaded{nosuchpackage}{loaded}{missing}"; let (body, _) = geometry_and_body(source); assert_eq!(body.trim(), "loaded missing"); } #[test] fn body_chardef_defines_a_character() { let source = "\\chardef\\letter=65\n\n\\letter b."; let (body, geometry) = geometry_and_body(source); assert_eq!(body.trim(), "A b."); assert!( geometry .macros .iter() .any(|definition| definition.name == "\\letter") ); } #[test] fn body_let_aliases_expand() { let source = "\\def\\x{A}\n\\let\\y=\\x\n\n\\y b."; let (body, _) = geometry_and_body(source); assert_eq!(body.trim(), "A b."); } #[test] fn body_newif_defines_a_conditional() { let source = "\\newif\\ifdraft\n\\ifdraft Draft\\else Final\\fi"; let (body, _geometry) = geometry_and_body(source); assert_eq!(body.trim(), "Final"); } #[test] fn body_count_declarations_are_reserved() { let source = "\\newcount\\total\n\\total=3\n\nValue \\the\\total."; let (body, _geometry) = geometry_and_body(source); assert_eq!(body.trim(), "Value 3."); } #[test] fn body_newsavebox_declarations_are_reserved() { let source = "\\newsavebox{\\boxa}\n\\sbox{\\boxa}{Stored}\n\nFirst \\usebox{\\boxa}."; let (body, _geometry) = geometry_and_body(source); assert_eq!(visible(body.trim()), "First Stored."); } #[test] fn body_theorem_definitions_are_reserved() { let source = "\\newtheorem{claim}{Claim}\n\n\\begin{claim}Body.\\end{claim}"; let json = preview_json(source).expect("preview"); assert!(json.contains("\"warnings\":[]"), "warnings: {json}"); assert!(!json.contains("newtheorem")); } #[test] fn body_environment_definitions_are_reserved() { let source = "\\newenvironment{note}{Note: }{!}\n\n\\begin{note}Body.\\end{note}"; let (body, _geometry) = geometry_and_body(source); assert_eq!(body.trim(), "Note: Body.!"); let json = preview_json(source).expect("preview"); assert!(json.contains("\"warnings\":[]"), "warnings: {json}"); assert!(!json.contains("newenvironment")); } #[test] fn body_definitions_expand_later_in_the_document() { let source = "\\def\\greet{Hello}\n\n\\greet world."; let (body, geometry) = geometry_and_body(source); assert_eq!(body.trim(), "Hello world."); assert!( geometry .macros .iter() .any(|definition| definition.name == "\\greet") ); } #[test] fn newenvironment_optional_arguments_use_their_default() { let definition = environment_definition("\\newenvironment{note}[1][Default]{(#1)}{!}") .expect("definition"); assert_eq!(definition.args, 1); assert_eq!(definition.default.as_deref(), Some("Default")); let source = "\\newenvironment{note}[1][Default]{(#1)}{!}\n\n\\begin{note}body\\end{note}"; let (body, _) = geometry_and_body(source); assert_eq!(body.trim(), "(Default)body!"); let explicit = "\\newenvironment{note}[1][Default]{(#1)}{!}\n\n\\begin{note}[X]body\\end{note}"; let (body, _) = geometry_and_body(explicit); assert_eq!(body.trim(), "(X)body!"); } #[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 delimited_macro_arguments_parse() { let source = concat!(r"\def\pair#1,#2{(#1|#2)}", "\n\n", r"Body \pair a,b."); let (body, geometry) = geometry_and_body(source); assert_eq!(body.trim(), "Body (a|b)."); assert_eq!(geometry.macros[0].params.as_deref(), Some("#1,#2")); } #[test] fn delimited_arguments_accept_braced_groups() { let source = concat!( r"\def\swap#1/#2{(#2/#1)}", "\n\n", r"\swap {left right}/{right side}." ); let (body, _) = geometry_and_body(source); assert!(body.contains("(right side/left right)."), "{body:?}"); } #[test] fn delimited_arguments_allow_a_leading_literal() { let source = concat!(r"\def\angle<#1>{<#1>}", "\n\n", r"\angle."); let (body, _) = geometry_and_body(source); assert!(body.contains("."), "{body:?}"); } #[test] fn newcommand_definitions_expand_in_the_body() { let source = "\\newcommand{\\R}{\\mathbb{R}}\n\\newcommand{\\pair}[2]{(#1,#2)}\n\n$\\R$ and $\\pair{x}{y}$"; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry.macros.len(), 2); assert!(!body.contains("\\newcommand")); assert!(body.contains("\\mathbb{R}")); assert!(body.contains("(x,y)")); } #[test] fn def_definitions_expand_in_the_body() { let (body, geometry) = geometry_and_body("\\def\\half{1/2}\n\nA \\half here."); assert_eq!(geometry.macros.len(), 1); assert_eq!(body.trim(), "A 1/2 here."); } #[test] fn def_arguments_are_substituted() { let (body, geometry) = geometry_and_body("\\def\\pair#1#2{(#1, #2)}\n\nA \\pair{a}{b} pair."); assert_eq!(geometry.macros[0].args, 2); assert_eq!(body.trim(), "A (a, b) pair."); } #[test] fn let_aliases_copy_definitions() { let (body, geometry) = geometry_and_body("\\def\\x{A}\n\\let\\y=\\x\n\n\\y b."); assert_eq!(geometry.macros.len(), 2); assert_eq!(body.trim(), "A b."); } #[test] fn let_to_unknown_sequence_stays_quiet() { let (body, _) = geometry_and_body("\\let\\z=\\missing\n\na\\z b"); assert_eq!(body.trim(), "a b"); } #[test] fn macro_arguments_substitute_in_order() { let definition = macro_definition("\\newcommand{\\vect}[2]{\\mathbf{#2}^{#1}}").expect("definition"); assert_eq!(definition.args, 2); assert_eq!( expand_macros("\\vect{2}{x}", std::slice::from_ref(&definition)), "\\mathbf{x}^{2}" ); } #[test] fn optional_macro_arguments_use_defaults() { let definition = macro_definition("\\newcommand{\\vect}[2][x]{(#1,#2)}").expect("definition"); assert_eq!(definition.default.as_deref(), Some("x")); assert_eq!( expand_macros("\\vect{y}", std::slice::from_ref(&definition)), "(x,y)" ); assert_eq!( expand_macros("\\vect[z]{w}", std::slice::from_ref(&definition)), "(z,w)" ); } #[test] fn macros_expand_nested_and_stop_on_recursion() { let definitions = vec![ MacroDefinition { name: "\\a".into(), args: 0, default: None, body: "\\b".into(), params: None, }, MacroDefinition { name: "\\b".into(), args: 0, default: None, body: "B".into(), params: None, }, ]; assert_eq!(expand_macros("\\a", &definitions), "B"); let recursive = vec![MacroDefinition { name: "\\loop".into(), args: 0, default: None, body: "\\loop".into(), params: None, }]; assert_eq!(expand_macros("\\loop", &recursive), "\\loop"); assert_eq!(expand_macros("\\missing", &definitions), "\\missing"); } #[test] fn newcommand_optional_arguments_expand() { let source = "\\newcommand{\\half}[1][2]{1/#1}\n\nA \\half.\n\nB \\half[4]."; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry.macros[0].default.as_deref(), Some("2")); let paragraphs = paragraphs_with_definitions(&body, &geometry.theorem_definitions).expect("blocks"); assert_eq!(paragraphs[0].text, "A 1/2."); assert_eq!(paragraphs[1].text, "B 1/4."); } #[test] fn macros_expand_in_previews() { let json = preview_json("\\newcommand{\\name}{Ada}\n\nHello \\name.").expect("preview"); assert!(json.contains(">A")); assert!(json.contains(">d")); } #[test] fn newtheorem_definitions_are_captured() { let source = "\\newtheorem{claim}[theorem]{Claim}\n\\newtheorem*{note}{Note}\n\\newtheorem{observation}{Observation}[section]\n\nBody."; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry.theorem_definitions.len(), 3); assert_eq!(geometry.theorem_definitions[0].name, "claim"); assert_eq!(geometry.theorem_definitions[0].display, "Claim"); assert_eq!( geometry.theorem_definitions[0].shared.as_deref(), Some("theorem") ); assert!(geometry.theorem_definitions[1].starred); assert_eq!( geometry.theorem_definitions[2].within.as_deref(), Some("section") ); assert!(!body.contains("newtheorem"), "{body}"); } #[test] fn custom_theorems_share_counters_and_sections() { let source = "\\newtheorem{claim}[theorem]{Claim}\n\\newtheorem{observation}{Observation}[section]\n\n\\section{One}\n\n\\begin{theorem}\nA theorem.\n\\end{theorem}\n\n\\begin{claim}\nA claim.\n\\end{claim}\n\n\\begin{observation}\n\\label{obs:a}An observation.\n\\end{observation}\n\nSee \\ref{obs:a}."; let (body, geometry) = geometry_and_body(source); let blocks = paragraphs_with_definitions(&body, &geometry.theorem_definitions).unwrap(); let document = build_document(&blocks, &geometry); let sources: Vec<&str> = document .units .iter() .map(|unit| unit.source.as_str()) .collect(); assert!(sources.contains(&"1 One"), "{sources:?}"); assert!(sources.contains(&"Theorem 1."), "{sources:?}"); assert!(sources.contains(&"Claim 2."), "{sources:?}"); assert!(sources.contains(&"Observation 1.1."), "{sources:?}"); assert!(sources.contains(&"See 1.1."), "{sources:?}"); } #[test] fn starred_newtheorem_stays_unnumbered() { let source = "\\newtheorem*{aside}{Aside}\n\n\\begin{aside}\nA remark.\n\\end{aside}"; let (body, geometry) = geometry_and_body(source); let blocks = paragraphs_with_definitions(&body, &geometry.theorem_definitions).unwrap(); let document = build_document(&blocks, &geometry); assert_eq!(document.units[0].source, "Aside."); assert_eq!(document.units[1].source, "A remark."); } #[test] fn theorem_environments_number_and_label() { let source = r"\begin{theorem}\label{thm:a} Every group has an identity. \end{theorem} \begin{lemma} A lemma follows. \end{lemma} See \ref{thm:a}."; let (body, geometry) = geometry_and_body(source); let blocks = paragraphs(&body).unwrap(); let document = build_document(&blocks, &geometry); assert_eq!(document.units.len(), 5); assert_eq!(document.units[0].source, "Theorem 1."); assert_eq!(document.units[1].source, "Every group has an identity."); assert!(matches!( document.units[1].items.first(), Some(VerticalItem::Paragraph(paragraph)) if paragraph.font == ParagraphFont::Italic )); assert_eq!(document.units[2].source, "Lemma 1."); assert_eq!(document.units[4].source, "See 1."); } #[test] fn theorem_titles_are_appended_to_the_heading() { let source = r"\begin{theorem}[Main result] Body. \end{theorem}"; let (body, geometry) = geometry_and_body(source); let blocks = paragraphs(&body).unwrap(); let document = build_document(&blocks, &geometry); assert_eq!(document.units[0].source, "Theorem 1 (Main result)."); } #[test] fn proof_headings_use_their_optional_title() { let source = "\\begin{proof}[Proof of the claim]\nBecause it follows.\n\\end{proof}"; let blocks = paragraphs(&source).expect("paragraphs"); assert_eq!(blocks.len(), 2); assert_eq!(blocks[0].text, "Proof of the claim."); assert_eq!(blocks[1].font, ParagraphFont::Italic); } #[test] fn proof_is_unnumbered_and_definitions_stay_roman() { let source = r"\begin{proof} It follows. \end{proof} \begin{definition} A definition. \end{definition}"; let (body, geometry) = geometry_and_body(source); let blocks = paragraphs(&body).unwrap(); let document = build_document(&blocks, &geometry); assert_eq!(document.units[0].source, "Proof."); assert!(matches!( document.units[1].items.first(), Some(VerticalItem::Paragraph(paragraph)) if paragraph.font == ParagraphFont::Italic )); assert_eq!(document.units[2].source, "Definition 1."); assert!(matches!( document.units[3].items.first(), Some(VerticalItem::Paragraph(paragraph)) if paragraph.font == ParagraphFont::Roman )); } #[test] fn table_of_contents_starts_with_contents_heading() { let source = "\\tableofcontents\n\n\\section{Intro}\n\nText."; let (body, geometry) = geometry_and_body(source); let paragraphs = paragraphs_with_definitions(&body, &geometry.theorem_definitions).expect("blocks"); let document = build_document(¶graphs, &geometry); let names: Vec<&str> = document .units .iter() .map(|unit| unit.source.as_str()) .collect(); assert_eq!(names[0], "Contents"); assert_eq!(names[1], "1 Intro"); assert_eq!( document .units .iter() .filter(|unit| unit.source == "Contents") .count(), 1 ); } #[test] fn short_titles_appear_in_the_table_of_contents() { let source = "\\tableofcontents\n\n\\section[Short]{A much longer title}\n\nText."; let (body, geometry) = geometry_and_body(source); let paragraphs = paragraphs_with_definitions(&body, &geometry.theorem_definitions).expect("blocks"); let document = build_document(¶graphs, &geometry); let names: Vec<&str> = document .units .iter() .map(|unit| unit.source.as_str()) .collect(); assert!(names.contains(&"1 Short"), "{names:?}"); assert_eq!( names .iter() .filter(|name| **name == "1 A much longer title") .count(), 1, "{names:?}" ); } #[test] fn contents_names_follow_renewcommand() { let source = "\\renewcommand{\\contentsname}{Inhalt}\n\n\\tableofcontents\n\n\\section{Intro}\n\nText."; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry.contents_name.as_deref(), Some("Inhalt")); let paragraphs = paragraphs_with_definitions(&body, &geometry.theorem_definitions).expect("blocks"); let document = build_document(¶graphs, &geometry); assert_eq!(document.units[0].source, "Inhalt"); } #[test] fn bibliography_starts_with_references_heading() { let source = "See \\cite{alpha}.\n\n\\begin{thebibliography}{9}\n\\bibitem{alpha} Alpha entry.\n\\end{thebibliography}"; let (body, geometry) = geometry_and_body(source); let paragraphs = paragraphs_with_definitions(&body, &geometry.theorem_definitions).expect("blocks"); let document = build_document(¶graphs, &geometry); let names: Vec<&str> = document .units .iter() .map(|unit| unit.source.as_str()) .collect(); let heading = names.iter().position(|name| *name == "References"); let entry = names.iter().position(|name| *name == "[1] Alpha entry."); assert!(heading.is_some(), "{names:?}"); assert!(entry.is_some(), "{names:?}"); assert!(heading < entry, "{names:?}"); } #[test] fn reference_names_follow_renewcommand() { let source = "\\renewcommand{\\refname}{Literatur}\n\nSee \\cite{alpha}.\n\n\\begin{thebibliography}{9}\n\\bibitem{alpha} Alpha entry.\n\\end{thebibliography}"; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry.ref_name.as_deref(), Some("Literatur")); let paragraphs = paragraphs_with_definitions(&body, &geometry.theorem_definitions).expect("blocks"); let document = build_document(¶graphs, &geometry); assert!(document.units.iter().any(|unit| unit.source == "Literatur")); assert!( !document .units .iter() .any(|unit| unit.source == "References") ); } #[test] fn bibliography_entries_resolve_citations() { let source = "See \\cite{alpha} and \\cite{alpha,beta}.\n\n\\begin{thebibliography}{9}\n\\bibitem{alpha} Alpha entry.\n\\bibitem{beta} Beta entry.\n\\end{thebibliography}"; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry.bibliography.len(), 2); let blocks = paragraphs(&body).unwrap(); let document = build_document(&blocks, &geometry); let sources: Vec<&str> = document .units .iter() .map(|unit| unit.source.as_str()) .collect(); assert!(sources.contains(&"See [1] and [1, 2]."), "{sources:?}"); assert!(sources.contains(&"[1] Alpha entry."), "{sources:?}"); assert!(sources.contains(&"[2] Beta entry."), "{sources:?}"); } #[test] fn missing_citations_print_a_question_mark() { let blocks = paragraphs("See \\cite{missing}.").unwrap(); let document = build_document(&blocks, &PageGeometry::default()); assert_eq!(document.units[0].source, "See [?]."); } #[test] fn citation_notes_and_nocite_are_dropped() { let source = "See \\citep[p.~3]{alpha} and \\citet{alpha}.\\nocite{beta}\n\n\\begin{thebibliography}{9}\n\\bibitem{alpha} Alpha entry.\n\\bibitem{beta} Beta entry.\n\\end{thebibliography}"; let (body, geometry) = geometry_and_body(source); let blocks = paragraphs(&body).unwrap(); let document = build_document(&blocks, &geometry); let sources: Vec<&str> = document .units .iter() .map(|unit| unit.source.as_str()) .collect(); assert_eq!(sources[0], "See [1] and [1]."); assert!(sources.contains(&"[1] Alpha entry."), "{sources:?}"); assert!(sources.contains(&"[2] Beta entry."), "{sources:?}"); } #[test] fn bibliography_commands_stay_out_of_the_body() { let source = "\\bibliographystyle{plain}\n\\bibliography{refs}\n\nBody."; let (body, geometry) = geometry_and_body(source); assert!(!body.contains("bibliograph"), "{body:?}"); let blocks = paragraphs(&body).unwrap(); assert_eq!(blocks.len(), 1); assert_eq!(blocks[0].text, "Body."); let document = build_document(&blocks, &geometry); assert_eq!(document.units.len(), 1); } #[test] fn footnotes_number_across_paragraphs() { let blocks = paragraphs("One\\footnote{A}\n\nTwo\\footnote{B}").unwrap(); let document = build_document(&blocks, &PageGeometry::default()); assert_eq!(document.units[0].source, "One (1)"); assert_eq!(document.units[2].source, "Two (2)"); assert_eq!(document.units.len(), 4); } #[test] fn reads_hang_registers_from_the_preamble() { let (body, geometry) = geometry_and_body( "\\hangindent=20pt\n\\hangafter=1\n\\tolerance=1000\n\\pretolerance=50\n\\looseness=-1\n\\spaceskip=6pt plus 1pt minus 0.5pt\n\\frenchspacing\n\nword word", ); assert_eq!(geometry.hang_indent, Some(20 * 65_536)); assert_eq!(geometry.hang_after, Some(1)); let pt = 65_536; assert_eq!(geometry.tolerance, Some(1000)); assert_eq!(geometry.pretolerance, Some(50)); assert_eq!(geometry.looseness, Some(-1)); assert_eq!(geometry.space_skip, Some((6 * pt, pt, pt / 2))); assert_eq!(geometry.french_spacing, Some(true)); let paragraphs = paragraphs(&body).expect("paragraphs"); assert_eq!(paragraphs.len(), 1, "{body:?}"); let document = build_document(¶graphs, &geometry); let style = document.units[0].paragraph_style.clone().expect("style"); assert_eq!(style.hang_indent, 20 * 65_536); assert_eq!(style.hang_after, 1); assert_eq!(style.tolerance, 1000); assert_eq!(style.pretolerance, 50); assert_eq!(style.looseness, -1); assert_eq!(style.space_skip, Some((6 * pt, pt, pt / 2))); assert!(style.frenchspacing); } #[test] fn geometry_reads_hyphenation_exceptions() { let source = "\\documentclass{article}\n\\hyphenation{zzz-zzz alpha-beta}\n\\begin{document}\n\nzzzzzz\n\n\\end{document}\n"; let (body, geometry) = geometry_and_body(source); assert_eq!( geometry.hyphenation_exceptions, vec!["zzz-zzz".to_string(), "alpha-beta".to_string()] ); assert!(!body.contains("hyphenation")); let paragraphs = paragraphs(&body).expect("paragraphs"); let document = build_document(¶graphs, &geometry); let style = document.units[0] .paragraph_style .clone() .expect("paragraph style"); assert_eq!( style.hyphenation_exceptions, geometry.hyphenation_exceptions ); } #[test] fn geometry_reads_parshape() { let source = "\\documentclass{article}\n\\parshape=2 0pt 100pt 20pt 80pt\n\\begin{document}\n\nSome words here.\n\n\\end{document}\n"; let (body, geometry) = geometry_and_body(source); assert_eq!( geometry.par_shape, vec![(0, 100 * SCALE), (20 * SCALE, 80 * SCALE)] ); assert!(!body.contains("parshape")); let paragraphs = paragraphs(&body).expect("paragraphs"); let document = build_document(¶graphs, &geometry); let style = document.units[0] .paragraph_style .clone() .expect("paragraph style"); assert_eq!(style.par_shape, geometry.par_shape); } #[test] fn geometry_reads_parfillskip_and_lineskip() { let source = "\\documentclass{article}\n\\parfillskip=0pt plus 1fil\n\\lineskip=2pt\n\\lineskiplimit=3pt\n\\begin{document}\n\nSome words here.\n\n\\end{document}\n"; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry.par_fillskip, Some((0, 0, true))); assert_eq!(geometry.lineskip, Some(2 * SCALE)); assert_eq!(geometry.lineskiplimit, Some(3 * SCALE)); assert!(!body.contains("parfillskip")); let paragraphs = paragraphs(&body).expect("paragraphs"); let document = build_document(¶graphs, &geometry); let style = document.units[0] .paragraph_style .clone() .expect("paragraph style"); assert_eq!(style.par_fillskip, 0); assert!(style.par_fillskip_fil); assert_eq!(style.lineskip, 2 * SCALE); assert_eq!(style.lineskiplimit, 3 * SCALE); } #[test] fn geometry_reads_stretchy_parskip() { let source = "\\documentclass{article}\n\\parskip=2pt plus 5pt minus 1pt\n\\begin{document}\n\nSome words here.\n\n\\end{document}\n"; let (body, geometry) = geometry_and_body(source); assert!(!body.contains("parskip")); assert_eq!(geometry.par_skip, Some(2 * 65_536)); assert_eq!(geometry.par_skip_stretch, Some(5 * 65_536)); assert_eq!(geometry.par_skip_shrink, Some(65_536)); } #[test] fn geometry_reads_page_skip_registers() { let source = "\\documentclass{article}\n\\topskip=10pt\n\\maxdepth=5pt\n\\splittopskip=3pt\n\\begin{document}\n\nSome words here.\n\n\\end{document}\n"; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry.top_skip, Some(10 * SCALE)); assert_eq!(geometry.max_depth, Some(5 * SCALE)); assert_eq!(geometry.split_top_skip, Some(3 * SCALE)); assert!(!body.contains("topskip")); let paragraphs = paragraphs(&body).expect("paragraphs"); let mut document = build_document(¶graphs, &geometry); apply_geometry(&mut document, &geometry); assert_eq!(document.top_skip, 10 * SCALE); assert_eq!(document.max_depth, 5 * SCALE); assert_eq!(document.split_top_skip, 3 * SCALE); } #[test] fn geometry_reads_club_and_widow_penalties() { let source = "\\documentclass{article}\n\\clubpenalty=77\n\\widowpenalty=88\n\\begin{document}\n\nSome words here.\n\n\\end{document}\n"; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry.club_penalty, Some(77)); assert_eq!(geometry.widow_penalty, Some(88)); assert!(!body.contains("clubpenalty")); let paragraphs = paragraphs(&body).expect("paragraphs"); let document = build_document(¶graphs, &geometry); assert_eq!(document.club_penalty, 77); assert_eq!(document.widow_penalty, 88); } #[test] fn math_greek_letters_render() { let source = "\\documentclass{article}\\begin{document}\n\n$\\alpha + \\beta = \\gamma$\n\n\\end{document}\n"; let json = preview_json(source).expect("preview"); let value: serde_json::Value = serde_json::from_str(&json).expect("JSON"); let svg = value["pages"][0]["svg"].as_str().expect("svg"); let text: String = svg .split('>') .filter_map(|piece| piece.split('<').next()) .collect::() .split_whitespace() .collect(); assert!(text.contains('α'), "{text}"); assert!(text.contains('β'), "{text}"); assert!(text.contains('γ'), "{text}"); assert!(!text.contains('?'), "{text}"); } #[test] fn group_definitions_are_local() { let text_of = |source: &str| -> String { let json = preview_json(source).expect("preview"); let value: serde_json::Value = serde_json::from_str(&json).expect("JSON"); let svg = value["pages"][0]["svg"].as_str().expect("svg"); svg.split('>') .filter_map(|piece| piece.split('<').next()) .collect::() .split_whitespace() .collect() }; let braced = text_of( "\\documentclass{article}\n\\begin{document}\n\n\\def\\a{one}{\\def\\a{two}\\a}\\a\n\n\\end{document}\n", ); assert!(braced.contains("twoone"), "{braced}"); let grouped = text_of( "\\documentclass{article}\n\\begin{document}\n\n\\def\\a{one}\\begingroup\\def\\a{two}\\a\\endgroup\\a\n\n\\end{document}\n", ); assert!(grouped.contains("twoone"), "{grouped}"); } #[test] fn edef_in_body_expands_at_definition_time() { let source = "\\documentclass{article}\n\\begin{document}\n\n\\def\\a{one}\n\\edef\\b{\\a}\n\\def\\a{two}\n\n\\b and \\a\n\n\\end{document}\n"; let json = preview_json(source).expect("preview"); let value: serde_json::Value = serde_json::from_str(&json).expect("JSON"); let svg = value["pages"][0]["svg"].as_str().expect("svg"); let text: String = svg .split('>') .filter_map(|piece| piece.split('<').next()) .collect::() .split_whitespace() .collect(); assert!(text.contains("oneandtwo"), "{text}"); assert_eq!(value["warnings"].as_array().map(Vec::len), Some(0)); } #[test] fn at_is_a_letter_only_inside_makeatletter() { let text_of = |body: &str| -> String { let source = format!( "\\documentclass{{article}}\n\\begin{{document}}\n\n{body}\n\n\\end{{document}}\n" ); let json = preview_json(&source).expect("preview"); let value: serde_json::Value = serde_json::from_str(&json).expect("JSON"); let svg = value["pages"][0]["svg"].as_str().expect("svg"); svg.split('>') .filter_map(|piece| piece.split('<').next()) .collect::() .split_whitespace() .collect() }; assert!(text_of("\\makeatletter\\def\\@foo{bar}\\@foo\\makeatother").contains("bar")); let split = text_of("\\def\\foo{Hi}\\foo@bar"); assert!(split.contains("Hi@bar"), "{split}"); assert!(text_of("\\@ifundefined{missing}{Yes}{No}").contains("Yes")); assert!( text_of("\\makeatletter{\\makeatother}\\def\\@x{Y}\\@x\\makeatother").contains('Y') ); } #[test] fn group_lines_and_runtime_aliases() { let text_of = |source: &str| -> String { let json = preview_json(source).expect("preview"); let value: serde_json::Value = serde_json::from_str(&json).expect("JSON"); let svg = value["pages"][0]["svg"].as_str().expect("svg"); svg.split('>') .filter_map(|piece| piece.split('<').next()) .collect::() .split_whitespace() .collect() }; let grouped = text_of( "\\documentclass{article}\n\\begin{document}\n\n\\def\\a{one}\n{\n\\def\\a{two}\n\\a\n}\n\\a\n\n\\end{document}\n", ); assert!(grouped.contains("twoone"), "{grouped}"); let aliased = text_of( "\\documentclass{article}\n\\begin{document}\n\n\\def\\b{Hi}\\let\\c=\\b\\c and \\chardef\\d=65\\d\n\n\\end{document}\n", ); assert!(aliased.contains("HiandA"), "{aliased}"); } #[test] fn inline_definitions_and_makeatletter_expand() { let source = "\\documentclass{article}\n\\begin{document}\n\n\\makeatletter\\def\\@foo{bar}\\@foo and \\def\\greet{Hello}\\greet.\\makeatother\n\n\\end{document}\n"; let json = preview_json(source).expect("preview"); let value: serde_json::Value = serde_json::from_str(&json).expect("JSON"); assert_eq!(value["status"], "ok"); assert_eq!( value["warnings"].as_array().map(Vec::len), Some(0), "{}", value["warnings"] ); let svg = value["pages"][0]["svg"].as_str().expect("svg"); let text: String = svg .split('>') .filter_map(|piece| piece.split('<').next()) .collect::() .split_whitespace() .collect(); assert!(text.contains("bar"), "{text}"); assert!(text.contains("Hello"), "{text}"); assert!(!text.contains("def"), "{text}"); assert!(!text.contains("makeatletter"), "{text}"); } #[test] fn inline_spacing_and_guillemets_are_clean() { let source = "\\documentclass{article}\n\\begin{document}\n\nA\\vspace*{6pt}B \\smallskip C\\bigskip D\\samepage \\guillemotleft x\\guillemotright\n\n\\end{document}\n"; let json = preview_json(source).expect("preview"); let value: serde_json::Value = serde_json::from_str(&json).expect("JSON"); assert_eq!( value["warnings"].as_array().map(Vec::len), Some(0), "{}", value["warnings"] ); let svg = value["pages"][0]["svg"].as_str().expect("svg"); let text: String = svg .split('>') .filter_map(|piece| piece.split('<').next()) .collect::() .split_whitespace() .collect(); assert!(text.contains("ABCD"), "{text}"); assert!(text.contains("«x»"), "{text}"); } #[test] fn valign_transposes_into_a_table() { let source = "\\valign{\\cr a & b & c \\cr d & e & f \\cr}"; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry.tabular.len(), 1); let blocks = paragraphs(&body).expect("paragraphs"); let document = build_document(&blocks, &geometry); let halign = document .units .iter() .find_map(|unit| { unit.items.iter().find_map(|item| match item { VerticalItem::Halign(halign) => Some(halign), _ => None, }) }) .expect("halign"); assert_eq!(halign.column_widths.len(), 2); assert_eq!(halign.rows.len(), 3); let row0: Vec<&str> = halign.rows[0] .cells .iter() .map(|cell| cell.text.as_str()) .collect(); let row2: Vec<&str> = halign.rows[2] .cells .iter() .map(|cell| cell.text.as_str()) .collect(); assert_eq!(row0, vec!["a", "d"]); assert_eq!(row2, vec!["c", "f"]); } #[test] fn percent_catcode_turns_comments_literal() { let literal = "\\documentclass{article}\n\\catcode`\\%=12\n\\begin{document}\n\n100% sure\n\n\\end{document}\n"; let json = preview_json(literal).expect("preview"); let value: serde_json::Value = serde_json::from_str(&json).expect("JSON"); assert_eq!( value["warnings"].as_array().map(Vec::len), Some(0), "{}", value["warnings"] ); let svg = value["pages"][0]["svg"].as_str().expect("svg"); let text: String = svg .split('>') .filter_map(|piece| piece.split('<').next()) .collect::() .split_whitespace() .collect(); assert!(text.contains("100%sure"), "{text}"); let commented = "\\documentclass{article}\n\\begin{document}\n\nHello% hidden\nworld\n\n\\end{document}\n"; let json = preview_json(commented).expect("preview"); let value: serde_json::Value = serde_json::from_str(&json).expect("JSON"); let svg = value["pages"][0]["svg"].as_str().expect("svg"); let text: String = svg .split('>') .filter_map(|piece| piece.split('<').next()) .collect::() .split_whitespace() .collect(); assert!(text.contains("Helloworld"), "{text}"); assert!(!text.contains("hidden"), "{text}"); } #[test] fn meaning_prints_macro_bodies() { let source = "\\documentclass{article}\n\\begin{document}\n\n\\def\\greet#1{Hello #1}\n\n\\meaning\\greet and \\meaning\\missing.\n\n\\end{document}\n"; let json = preview_json(source).expect("preview"); let value: serde_json::Value = serde_json::from_str(&json).expect("JSON"); assert_eq!( value["warnings"].as_array().map(Vec::len), Some(0), "{}", value["warnings"] ); let svg = value["pages"][0]["svg"].as_str().expect("svg"); let text: String = svg .split('>') .filter_map(|piece| piece.split('<').next()) .collect::() .split_whitespace() .collect(); assert!(text.contains("macro:#1->Hello#1"), "{text}"); assert!(text.contains("\\relax"), "{text}"); } #[test] fn string_prints_tokens_literally() { let source = "\\documentclass{article}\n\\begin{document}\n\n\\def\\foo{bar}\n\n\\string\\foo and \\string{ and \\string}.\n\n\\end{document}\n"; let json = preview_json(source).expect("preview"); let value: serde_json::Value = serde_json::from_str(&json).expect("JSON"); assert_eq!( value["warnings"].as_array().map(Vec::len), Some(0), "{}", value["warnings"] ); let svg = value["pages"][0]["svg"].as_str().expect("svg"); let text: String = svg .split('>') .filter_map(|piece| piece.split('<').next()) .collect::() .split_whitespace() .collect(); assert!(text.contains("\\fooand{and}."), "{text}"); assert!(!text.contains("bar"), "{text}"); } #[test] fn image_saveboxes_measure_the_image() { let mut images = HashMap::new(); images.insert( "plot.png".to_string(), RasterImage { width: 100, height: 50, rgb: vec![0; 100 * 50 * 3], }, ); let source = "\\newsavebox{\\logo}\n\\sbox{\\logo}{\\includegraphics{plot.png}}\n\nX\\hspace{\\wd\\logo}Y"; let (_body, geometry) = geometry_and_body_with_images(source, &images); let (_, (width, height, depth)) = geometry .savebox_dimensions .iter() .find(|(name, _)| name == "\\logo") .expect("savebox dimensions"); assert_eq!(*width, 100 * 65_782); assert_eq!(*height, 50 * 65_782); assert_eq!(*depth, 0); } #[test] fn token_registers_store_and_expand() { let source = "\\documentclass{article}\n\\begin{document}\n\n\\newtoks\\greet\n\\greet={Hello}\n\\toks0={A}\n\n\\the\\greet and \\the\\toks0 B\n\n\\end{document}\n"; let json = preview_json(source).expect("preview"); let value: serde_json::Value = serde_json::from_str(&json).expect("JSON"); assert_eq!( value["warnings"].as_array().map(Vec::len), Some(0), "{}", value["warnings"] ); let svg = value["pages"][0]["svg"].as_str().expect("svg"); let text: String = svg .split('>') .filter_map(|piece| piece.split('<').next()) .collect::() .split_whitespace() .collect(); assert!(text.contains("HelloandAB"), "{text}"); assert!(!text.contains("toks"), "{text}"); } #[test] fn scantokens_reprocesses_its_content() { let source = "\\documentclass{article}\n\\begin{document}\n\n\\def\\greet{Hello}\\scantokens{\\greet world}.\n\n\\end{document}\n"; let json = preview_json(source).expect("preview"); let value: serde_json::Value = serde_json::from_str(&json).expect("JSON"); assert_eq!( value["warnings"].as_array().map(Vec::len), Some(0), "{}", value["warnings"] ); let svg = value["pages"][0]["svg"].as_str().expect("svg"); let text: String = svg .split('>') .filter_map(|piece| piece.split('<').next()) .collect::() .split_whitespace() .collect(); assert!(text.contains("Helloworld."), "{text}"); assert!(!text.contains("scantokens"), "{text}"); } #[test] fn other_catcode_assignments_are_consumed() { let source = "\\documentclass{article}\n\\begin{document}\n\n\\catcode`\\#=12\n\\catcode`\\_=12\n\n#hash and a_b.\n\n\\end{document}\n"; let json = preview_json(source).expect("preview"); let value: serde_json::Value = serde_json::from_str(&json).expect("JSON"); assert_eq!( value["warnings"].as_array().map(Vec::len), Some(0), "{}", value["warnings"] ); let svg = value["pages"][0]["svg"].as_str().expect("svg"); let text: String = svg .split('>') .filter_map(|piece| piece.split('<').next()) .collect::() .split_whitespace() .collect(); assert!(text.contains("#hash"), "{text}"); assert!(text.contains("a_b."), "{text}"); assert!(!text.contains("catcode"), "{text}"); } #[test] fn afterassignment_runs_after_the_assignment() { let source = "\\documentclass{article}\n\\begin{document}\n\n\\newcount\\a\n\\def\\hello{H}\n\\afterassignment\\hello\\a=5\n\nText.\n\n\\end{document}\n"; let json = preview_json(source).expect("preview"); let value: serde_json::Value = serde_json::from_str(&json).expect("JSON"); assert_eq!( value["warnings"].as_array().map(Vec::len), Some(0), "{}", value["warnings"] ); let svg = value["pages"][0]["svg"].as_str().expect("svg"); let text: String = svg .split('>') .filter_map(|piece| piece.split('<').next()) .collect::() .split_whitespace() .collect(); assert!(text.contains('H'), "{text}"); assert!(text.contains("Text."), "{text}"); assert!(!text.contains("afterassignment"), "{text}"); } #[test] fn aftergroup_runs_tokens_at_group_end() { let source = "\\documentclass{article}\n\\begin{document}\n\n\\def\\a{A}{\\def\\a{B}\\aftergroup\\a}\\a and {\\aftergroup{!}}X\n\n\\end{document}\n"; let json = preview_json(source).expect("preview"); let value: serde_json::Value = serde_json::from_str(&json).expect("JSON"); assert_eq!( value["warnings"].as_array().map(Vec::len), Some(0), "{}", value["warnings"] ); let svg = value["pages"][0]["svg"].as_str().expect("svg"); let text: String = svg .split('>') .filter_map(|piece| piece.split('<').next()) .collect::() .split_whitespace() .collect(); assert!(text.contains("AAand!X"), "{text}"); assert!(!text.contains("aftergroup"), "{text}"); } #[test] fn futurelet_peeks_without_consuming() { let source = "\\documentclass{article}\n\\begin{document}\n\n\\def\\shownext{[\\next]}\\futurelet\\next\\shownext x\n\n\\def\\yes{Y}\\def\\no{N}\\def\\pick{\\futurelet\\next\\pickii}\\def\\pickii{\\ifx\\next x\\yes\\else\\no\\fi}\n\n\\pick x\n\n\\end{document}\n"; let json = preview_json(source).expect("preview"); let value: serde_json::Value = serde_json::from_str(&json).expect("JSON"); assert_eq!( value["warnings"].as_array().map(Vec::len), Some(0), "{}", value["warnings"] ); let svg = value["pages"][0]["svg"].as_str().expect("svg"); let text: String = svg .split('>') .filter_map(|piece| piece.split('<').next()) .collect::() .split_whitespace() .collect(); assert!(text.contains("[x]"), "{text}"); assert!(text.contains("Y"), "{text}"); assert!(!text.contains("futurelet"), "{text}"); } #[test] fn runtime_csname_resolves_macros() { let source = "\\documentclass{article}\n\\begin{document}\n\n\\def\\foo{Z}\n\\def\\a{\\csname foo\\endcsname}\n\n\\a and \\csname foo\\endcsname and \\csname missing\\endcsname.\n\n\\end{document}\n"; let json = preview_json(source).expect("preview"); let value: serde_json::Value = serde_json::from_str(&json).expect("JSON"); assert_eq!( value["warnings"].as_array().map(Vec::len), Some(0), "{}", value["warnings"] ); let svg = value["pages"][0]["svg"].as_str().expect("svg"); let text: String = svg .split('>') .filter_map(|piece| piece.split('<').next()) .collect::() .split_whitespace() .collect(); assert!(text.contains("ZandZand."), "{text}"); assert!(!text.contains("csname"), "{text}"); } #[test] fn catcode_assignments_toggle_at_letter() { let source = "\\documentclass{article}\n\\begin{document}\n\n\\catcode`\\@=11\n\\def\\@foo{bar}\n\\@foo\n\n\\end{document}\n"; let json = preview_json(source).expect("preview"); let value: serde_json::Value = serde_json::from_str(&json).expect("JSON"); assert_eq!( value["warnings"].as_array().map(Vec::len), Some(0), "{}", value["warnings"] ); let svg = value["pages"][0]["svg"].as_str().expect("svg"); let text: String = svg .split('>') .filter_map(|piece| piece.split('<').next()) .collect::() .split_whitespace() .collect(); assert!(text.contains("bar"), "{text}"); assert!(!text.contains("catcode"), "{text}"); assert!(!text.contains("@foo"), "{text}"); } #[test] fn runtime_definitions_accept_parameters() { let source = "\\documentclass{article}\n\\begin{document}\n\n\\def\\add#1{[#1]}\\def\\pair#1,#2{(#1|#2)}\n\n\\add{x} and \\pair a,b\n\n\\end{document}\n"; let json = preview_json(source).expect("preview"); let value: serde_json::Value = serde_json::from_str(&json).expect("JSON"); assert_eq!( value["warnings"].as_array().map(Vec::len), Some(0), "{}", value["warnings"] ); let svg = value["pages"][0]["svg"].as_str().expect("svg"); let text: String = svg .split('>') .filter_map(|piece| piece.split('<').next()) .collect::() .split_whitespace() .collect(); assert!(text.contains("[x]"), "{text}"); assert!(text.contains("(a|b)"), "{text}"); } #[test] fn fontspec_families_map_to_engine_faces() { let source = "\\documentclass{article}\n\\usepackage{fontspec}\n\\setmainfont{Liberation Serif}\n\\setsansfont{Liberation Sans}\n\\newfontfamily\\headingfont[Ligatures=TeX]{Liberation Sans}\n\\begin{document}\n\n\\headingfont Sans words.\n\n\\end{document}\n"; let json = preview_json(source).expect("preview"); let value: serde_json::Value = serde_json::from_str(&json).expect("JSON"); assert_eq!( value["warnings"].as_array().map(Vec::len), Some(0), "{}", value["warnings"] ); let svg = value["pages"][0]["svg"].as_str().expect("svg"); assert!(svg.contains("sans-serif"), "{svg}"); assert!(svg.contains(">S"), "{svg}"); assert!(!svg.contains("newfontfamily"), "{svg}"); assert!(!svg.contains("setmainfont"), "{svg}"); } #[test] fn nested_tables_keep_the_outer_structure() { let source = r"\begin{tabular}{ll} outer & \begin{tabular}{cc}a & b\\ c & d\end{tabular} \\ left & right \\ \end{tabular}"; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry.tabular.len(), 1, "outer table captured once"); assert_eq!(geometry.nested_tables.len(), 1, "nested table stored once"); let (template, text, _) = &geometry.tabular[0]; assert_eq!(template, "ll"); assert!(text.contains("\\texrranested{0}"), "{text}"); assert!(!text.contains("begin{tabular}"), "{text}"); let blocks = paragraphs(&body).expect("paragraphs"); let document = build_document(&blocks, &geometry); let halign = document .units .iter() .find_map(|unit| { unit.items.iter().find_map(|item| match item { VerticalItem::Halign(halign) => Some(halign), _ => None, }) }) .expect("halign"); assert_eq!(halign.column_widths.len(), 2); assert_eq!(halign.rows.len(), 2); assert_eq!(halign.nested.len(), 1, "nested table attached"); let (row, cell, table) = &halign.nested[0]; assert_eq!((*row, *cell), (0, 1)); assert_eq!(table.rows.len(), 2); assert_eq!(table.column_widths.len(), 2); assert!(halign.rows[0].cells[1].text.is_empty()); let cells: String = table .rows .iter() .flat_map(|row| row.cells.iter().map(|cell| cell.text.clone())) .collect(); assert!(cells.contains('a') && cells.contains('d'), "{cells}"); let document_source = format!( "\\documentclass{{article}}\n\\begin{{document}}\n\n{source}\n\nAfter.\n\n\\end{{document}}\n" ); let json = preview_json(&document_source).expect("preview"); let value: serde_json::Value = serde_json::from_str(&json).expect("JSON"); let svg = value["pages"][0]["svg"].as_str().expect("svg"); assert!(svg.contains("a") && svg.contains("d"), "{svg}"); } #[test] fn savebox_dimensions_are_frozen_and_readable() { let source = "\\newsavebox{\\b}\n\\sbox{\\b}{abc}\n\nX\\hspace{\\wd\\b}Y"; let (body, geometry) = geometry_and_body(source); let (_, (width, height, depth)) = geometry .savebox_dimensions .iter() .find(|(name, _)| name == "\\b") .expect("savebox dimensions"); assert!(*width > 0, "width {width}"); assert!(*height > 0, "height {height}"); assert!(*depth >= 0, "depth {depth}"); assert!(!body.contains("\\wd"), "{body}"); assert!(body.contains("pt"), "dimension not expanded: {body}"); } #[test] fn mbox_and_usebox_stay_on_one_line() { let measure = |source: &str| { let (body, mut geometry) = geometry_and_body(source); geometry.line_width = Some(60 * SCALE); let blocks = paragraphs(&body).expect("paragraphs"); let document = build_document(&blocks, &geometry); let paragraph = document.units[0] .items .iter() .find_map(|item| match item { VerticalItem::Paragraph(paragraph) => Some(paragraph), _ => None, }) .expect("paragraph"); paragraph.lines.len() }; assert_eq!( measure("\\mbox{alpha beta gamma}"), 1, "mbox must not break" ); assert_eq!( measure("\\newsavebox{\\b}\n\\sbox{\\b}{alpha beta gamma}\n\n\\usebox{\\b}"), 1, "usebox content must not break" ); } #[test] fn inline_colours_and_links_work_at_twelve_point() { let source = "\\documentclass[12pt]{article}\n\\begin{document}\n\nA \\textcolor{red}{red word} and a \\href{https://example.com}{link} and x\\textsuperscript{2}.\n\n\\end{document}\n"; let json = preview_json(source).expect("preview"); let value: serde_json::Value = serde_json::from_str(&json).expect("JSON"); assert_eq!(value["status"], "ok"); let svg = value["pages"][0]["svg"].as_str().expect("svg"); let text: String = svg .split('>') .filter_map(|piece| piece.split('<').next()) .collect::() .split_whitespace() .collect(); assert!(!text.contains("textcolor"), "colour command leaked: {text}"); assert!(!text.contains("href"), "link command leaked: {text}"); assert!(text.contains("redword"), "coloured text missing: {text}"); assert!(text.contains("link"), "link label missing: {text}"); assert!( value["warnings"].as_array().is_some_and(Vec::is_empty), "{}", value["warnings"] ); } #[test] fn display_math_uses_article_display_skips() { let source = "\\documentclass{article}\n\\begin{document}\n\nBefore.\n\n\\[ x \\]\n\nAfter.\n\n\\end{document}\n"; let (body, geometry) = geometry_and_body(source); let paragraphs = paragraphs(&body).expect("paragraphs"); let document = build_document(¶graphs, &geometry); let math_index = document .units .iter() .position(|unit| { unit.items .iter() .any(|item| matches!(item, VerticalItem::Math { .. })) }) .expect("display math unit"); let math = &document.units[math_index]; assert_eq!(math.space_before, 10 * SCALE); assert_eq!(math.space_stretch, 2 * SCALE); assert_eq!(math.space_shrink, 5 * SCALE); let after = &document.units[math_index + 1]; assert_eq!(after.space_before, 10 * SCALE); assert_eq!(after.space_stretch, 2 * SCALE); assert_eq!(after.space_shrink, 5 * SCALE); } #[test] fn block_environment_after_text_starts_a_new_block() { let blocks = paragraphs("The link is at\n\\begin{center}\nCentered\n\\end{center}\n") .expect("blocks"); assert_eq!(blocks.len(), 2); assert_eq!(blocks[0].text.trim(), "The link is at"); assert!( blocks[1].centered, "center environment must center its block" ); } #[test] fn comments_and_external_bibliography_commands_are_dropped() { let source = "\\documentclass{article}\n\\begin{document}\n\nVisible text. % \\newblock hidden\n\n\\bibliographystyle{plain}\n\\bibliography{references}\n\\end{document}\n"; let (body, _) = geometry_and_body(source); assert!(!body.contains("newblock"), "{body}"); assert!(!body.contains("bibliography"), "{body}"); assert!(body.contains("Visible text."), "{body}"); } #[test] fn arxiv_template_previews_without_warnings() { let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")); let template = std::fs::read_to_string(root.join("fixtures/arxiv-template/template.tex")) .expect("template"); let sty = std::fs::read_to_string(root.join("fixtures/arxiv-template/arxiv.sty")).expect("sty"); let assembled = template.replace("\\usepackage{arxiv}", &sty); let json = preview_json(&assembled).expect("preview"); let value: serde_json::Value = serde_json::from_str(&json).expect("JSON"); assert_eq!(value["status"], "ok"); assert_eq!( value["warnings"].as_array().map(Vec::len), Some(0), "{}", value["warnings"] ); assert!( value["pageCount"].as_u64().unwrap_or(0) >= 2, "expected at least two pages" ); let pages = value["pages"].as_array().expect("pages"); let first = pages[0]["svg"].as_str().expect("first svg"); let second = pages[1]["svg"].as_str().expect("second svg"); assert!( !first.contains("A Preprint"), "title page must be empty style" ); assert!(second.contains("A Preprint"), "right header missing"); assert!(second.contains("arXiv Template"), "centre header missing"); } #[test] fn fancyhdr_fields_are_parsed() { let source = "\\documentclass{article}\n\\pagestyle{fancy}\n\\fancyhf{}\n\\rhead{\\scshape \\footnotesize \\headeright}\n\\chead{\\shorttitle}\n\\lfoot{Left}\n\\cfoot{\\thepage}\n\\renewcommand{\\headrulewidth}{0.4pt}\n\\begin{document}\n\nHello.\n\n\\end{document}\n"; let (_body, geometry) = geometry_and_body(source); assert!(geometry.fancy_pagestyle); assert_eq!( geometry.header_right.as_deref(), Some("\\scshape \\footnotesize \\headeright") ); assert_eq!(geometry.header_center.as_deref(), Some("\\shorttitle")); assert_eq!(geometry.footer_left.as_deref(), Some("Left")); assert_eq!(geometry.footer_center.as_deref(), Some("\\thepage")); assert_eq!(geometry.head_rule_width, parse_dimension("0.4pt")); } fn svg_texts(json: &str) -> Vec<(String, f64, f64)> { let value: serde_json::Value = serde_json::from_str(json).expect("JSON"); let mut found = Vec::new(); for page in value["pages"].as_array().expect("pages") { let svg = page["svg"].as_str().expect("svg"); let mut rest = svg; while let Some(start) = rest.find("').expect("tag end"); let close = tag_end + rest[tag_end..].find("").expect("close"); let tag = &rest[start..=tag_end]; let text = rest[tag_end + 1..close].to_string(); let attr = |name: &str| -> f64 { let needle = format!("{name}=\""); let at = tag.find(&needle).expect("attr") + needle.len(); let end = tag[at..].find('"').expect("attr end") + at; tag[at..end].parse().expect("numeric") }; found.push((text, attr("x"), attr("y"))); rest = &rest[close + "".len()..]; } } found } #[test] fn fancy_headers_and_footers_are_painted() { let source = "\\documentclass{article}\n\\usepackage[top=1in,textheight=9in]{geometry}\n\\pagestyle{fancy}\n\\fancyhf{}\n\\rhead{Preprint}\n\\cfoot{Page \\thepage}\n\\begin{document}\n\nHello.\n\n\\end{document}\n"; let json = preview_json(source).expect("preview"); let texts = svg_texts(&json); let head = texts .iter() .find(|(text, _, _)| text == "Preprint") .expect("header"); let inch = parse_dimension("1in").unwrap() as f64 / SCALE as f64; assert!( (head.2 - (inch - 25.0)).abs() < 0.5, "header baseline at {}pt", head.2 ); assert!(head.1 > 400.0, "right header should be right-aligned"); let footer = texts .iter() .find(|(text, _, _)| text == "Page 1") .expect("footer page number"); assert!( (footer.2 - (inch + 9.0 * 72.27 + 30.0)).abs() < 1.0, "footer baseline at {}pt", footer.2 ); } #[test] fn geometry_reads_vertical_margins() { let source = "\\documentclass{article}\n\\usepackage[top=1in,bottom=1.5in,left=1in,right=1in]{geometry}\n\\begin{document}\n\nText.\n\n\\end{document}\n"; let (_body, geometry) = geometry_and_body(source); assert_eq!(geometry.top_margin, parse_dimension("1in")); assert_eq!(geometry.bottom_margin, parse_dimension("1.5in")); assert_eq!( geometry.textheight, Some(792 * SCALE - parse_dimension("1in").unwrap() - parse_dimension("1.5in").unwrap()) ); } #[test] fn geometry_top_margin_offsets_the_page_body() { let first_y = |json: &str| -> f64 { let value: serde_json::Value = serde_json::from_str(json).expect("JSON"); let svg = value["pages"][0]["svg"].as_str().expect("svg"); let index = svg.find("y=\"").expect("text y"); let rest = &svg[index + 3..]; let end = rest.find('"').expect("y end"); rest[..end].parse().expect("numeric y") }; let plain = preview_json("Hello").expect("plain preview"); let shifted = preview_json("\\usepackage[top=1in]{geometry}\n\nHello").expect("shifted preview"); let delta = first_y(&shifted) - first_y(&plain); let inch = parse_dimension("1in").unwrap() as f64 / SCALE as f64; assert!( (delta - inch).abs() < 0.2, "top margin shifted text by {delta}pt, expected {inch}pt" ); } #[test] fn lipsum_expands_to_filler_paragraphs() { let source = "\\documentclass{article}\n\\begin{document}\n\n\\lipsum[1]\n\n\\lipsum[2-3]\n\n\\lipsum\n\n\\end{document}\n"; let (body, _) = geometry_and_body(source); assert!(!body.contains("\\lipsum"), "{body}"); assert!(body.contains("Lorem ipsum"), "{body}"); let blocks = paragraphs(&body).expect("paragraphs"); assert!(blocks.len() >= 4, "{} blocks", blocks.len()); } #[test] fn multiline_macro_definitions_do_not_leak_into_the_body() { let source = "\\documentclass{article}\n\\newcommand{\\kw}[1]{%\n \\textbf{#1}%\n}\n\\def\\and{\\ifhmode\n\\fi}\n\\begin{document}\n\nSee \\kw{Hi} and \\and there.\n\n\\end{document}\n"; let (body, _) = geometry_and_body(source); assert!(!body.contains("newcommand"), "{body}"); assert!(!body.contains("ifhmode"), "{body}"); assert!(body.contains("Hi"), "{body}"); } #[test] fn arxiv_class_preamble_does_not_reach_the_body() { let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")); let template = std::fs::read_to_string(root.join("fixtures/arxiv-template/template.tex")) .expect("template"); let sty = std::fs::read_to_string(root.join("fixtures/arxiv-template/arxiv.sty")).expect("sty"); let assembled = template.replace("\\usepackage{arxiv}", &sty); let (body, _) = geometry_and_body(&assembled); for needle in ["NeedsTeXFormat", "fancyhf", "ifhmode"] { assert!(!body.contains(needle), "`{needle}` leaked into the body"); } assert!( body.contains("Introduction"), "body lost the document text: {}", body.chars().take(200).collect::() ); } #[test] fn at_begin_document_newgeometry_sets_the_text_block() { let source = "\\documentclass{article}\n\\usepackage{geometry}\n\\AtBeginDocument{\n \\newgeometry{\n textheight=9in,\n textwidth=6.5in,\n top=1in,\n headheight=14pt,\n headsep=25pt,\n footskip=30pt\n }\n}\n\\begin{document}\n\nSome words here.\n\n\\end{document}\n"; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry.line_width, parse_dimension("6.5in")); assert_eq!(geometry.textheight, parse_dimension("9in")); assert!(!body.contains("newgeometry")); assert!(!body.contains("AtBeginDocument")); let paragraphs = paragraphs(&body).expect("paragraphs"); let document = build_document(¶graphs, &geometry); assert_eq!(document.text_width, parse_dimension("6.5in").unwrap()); } #[test] fn at_begin_document_setup_does_not_leak_into_text() { let source = "\\documentclass{article}\n\\AtBeginDocument{\\newgeometry{textwidth=200pt}}\n\\begin{document}\n\nHello world.\n\n\\end{document}\n"; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry.line_width, Some(200 * SCALE)); assert!(!body.contains("AtBeginDocument")); assert!(!body.contains("newgeometry")); let warnings = source_warnings(source, &geometry); assert!( !warnings .iter() .any(|warning| warning.contains("newgeometry")), "{warnings:?}" ); } #[test] fn display_skips_accept_class_file_spelling() { let source = "\\documentclass{article}\n\\abovedisplayskip 7\\p@ \\@plus 2\\p@ \\@minus 5\\p@\n\\abovedisplayshortskip \\z@ \\@plus 3\\p@\n\\belowdisplayskip \\abovedisplayskip\n\\belowdisplayshortskip 4\\p@ \\@plus 3\\p@ \\@minus 3\\p@\n\\begin{document}\n\nBefore.\n\n\\[ x \\]\n\nAfter.\n\n\\end{document}\n"; let (_body, geometry) = geometry_and_body(source); assert_eq!( geometry.above_display_skip, Some((7 * SCALE, 2 * SCALE, 5 * SCALE)) ); assert_eq!(geometry.above_display_short_skip, Some((0, 3 * SCALE, 0))); assert_eq!( geometry.below_display_skip, Some((7 * SCALE, 2 * SCALE, 5 * SCALE)) ); assert_eq!( geometry.below_display_short_skip, Some((4 * SCALE, 3 * SCALE, 3 * SCALE)) ); } #[test] fn display_skip_registers_override_the_class_defaults() { let source = "\\documentclass{article}\n\\abovedisplayskip=30pt plus 1pt minus 2pt\n\\belowdisplayskip=40pt plus 3pt minus 4pt\n\\abovedisplayshortskip=1pt plus 2pt\n\\belowdisplayshortskip=3pt minus 1pt\n\\begin{document}\n\nBefore.\n\n\\[ x \\]\n\nAfter.\n\n\\end{document}\n"; let (body, geometry) = geometry_and_body(source); assert_eq!( geometry.above_display_skip, Some((30 * SCALE, SCALE, 2 * SCALE)) ); assert_eq!( geometry.below_display_skip, Some((40 * SCALE, 3 * SCALE, 4 * SCALE)) ); assert_eq!( geometry.above_display_short_skip, Some((SCALE, 2 * SCALE, 0)) ); assert_eq!( geometry.below_display_short_skip, Some((3 * SCALE, 0, SCALE)) ); let paragraphs = paragraphs(&body).expect("paragraphs"); let document = build_document(¶graphs, &geometry); let math_index = document .units .iter() .position(|unit| { unit.items .iter() .any(|item| matches!(item, VerticalItem::Math { .. })) }) .expect("display math unit"); let math = &document.units[math_index]; assert_eq!( (math.space_before, math.space_stretch, math.space_shrink), (30 * SCALE, SCALE, 2 * SCALE) ); let after = &document.units[math_index + 1]; assert_eq!( (after.space_before, after.space_stretch, after.space_shrink), (40 * SCALE, 3 * SCALE, 4 * SCALE) ); } #[test] fn geometry_reads_demerit_registers() { let source = "\\documentclass{article}\n\\hyphenpenalty=77\n\\exhyphenpenalty=88\n\\doublehyphendemerits=1234\n\\finalhyphendemerits=4321\n\\linepenalty=20\n\\adjdemerits=999\n\\begin{document}\n\nSome words here.\n\n\\end{document}\n"; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry.hyphen_penalty, Some(77)); assert_eq!(geometry.ex_hyphen_penalty, Some(88)); assert_eq!(geometry.double_hyphen_demerits, Some(1234)); assert_eq!(geometry.final_hyphen_demerits, Some(4321)); assert_eq!(geometry.line_penalty, Some(20)); assert_eq!(geometry.adj_demerits, Some(999)); assert!(!body.contains("hyphenpenalty")); let paragraphs = paragraphs(&body).expect("paragraphs"); let document = build_document(¶graphs, &geometry); let style = document.units[0] .paragraph_style .clone() .expect("paragraph style"); assert_eq!(style.hyphen_penalty, 77); assert_eq!(style.ex_hyphen_penalty, 88); assert_eq!(style.double_hyphen_demerits, 1234); assert_eq!(style.final_hyphen_demerits, 4321); assert_eq!(style.line_penalty, 20); assert_eq!(style.adj_demerits, 999); } #[test] fn geometry_reads_sfcode_assignments() { let source = "\\documentclass{article}\n\\sfcode61=1000\n\\sfcode`x=2000\n\\begin{document}\n\nSome words here.\n\n\\end{document}\n"; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry.space_factor_codes, vec![('=', 1000), ('x', 2000)]); assert!(!body.contains("sfcode")); let paragraphs = paragraphs(&body).expect("paragraphs"); let document = build_document(¶graphs, &geometry); let style = document.units[0] .paragraph_style .clone() .expect("paragraph style"); assert_eq!(style.space_factor_codes, geometry.space_factor_codes); } #[test] fn preview_pages_honour_page_offsets() { let plain = preview_json("Hello route D").expect("plain preview"); let shifted = preview_json("\\hoffset=10pt\n\\voffset=5pt\nHello route D").expect("shifted"); fn first_text_position(json: &str) -> (f64, f64) { let value: serde_json::Value = serde_json::from_str(json).expect("JSON"); let svg = value["pages"][0]["svg"].as_str().expect("svg"); let start = svg.find(" = document .units .iter() .map(|unit| unit.source.as_str()) .collect(); assert_eq!( sources .iter() .filter(|source| **source == "Figure 1: Plot") .count(), 1, "{sources:?}" ); assert_eq!( sources .iter() .filter(|source| **source == "Table 1: Numbers") .count(), 1, "{sources:?}" ); assert_eq!(sources.len(), 7, "{sources:?}"); assert!(!sources.iter().any(|source| source.contains("texrralof"))); assert!(!sources.iter().any(|source| source.contains("texrralot"))); assert_eq!(document.units[0].source, "List of Figures"); assert_eq!(document.units[1].source, "Figure 1: Plot"); assert_eq!(document.units[2].source, "List of Tables"); assert_eq!(document.units[3].source, "Table 1: Numbers"); } #[test] fn setcounter_offsets_figures_and_tables() { let source = "\\setcounter{figure}{5}\n\n\\setcounter{table}{2}\n\n\\begin{figure}\n\\caption{A}\n\\end{figure}\n\n\\begin{table}\n\\caption{B}\n\\end{table}"; let (body, geometry) = geometry_and_body(source); let mut blocks = paragraphs_with_definitions(&body, &geometry.theorem_definitions).expect("blocks"); number_floats( &mut blocks, "Figure", "Table", geometry_counter(&geometry, "figure"), geometry_counter(&geometry, "table"), ); let captions: Vec<&str> = blocks .iter() .filter_map(|block| block.float.as_ref()?.caption.as_deref()) .collect(); assert!(captions.contains(&"Figure 6: A"), "{captions:?}"); assert!(captions.contains(&"Table 3: B"), "{captions:?}"); } #[test] fn setcounter_offsets_section_numbers() { let source = "\\setcounter{section}{4}\n\n\\section{Intro}\n\nText."; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry_counter(&geometry, "section"), 4); let paragraphs = paragraphs_with_definitions(&body, &geometry.theorem_definitions).expect("blocks"); let document = build_document(¶graphs, &geometry); assert_eq!(document.units[0].source, "5 Intro"); } #[test] fn setcounter_offsets_theorem_numbers() { let source = "\\setcounter{theorem}{4}\n\n\\begin{theorem}\nClaim.\n\\end{theorem}"; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry_counter(&geometry, "theorem"), 4); let paragraphs = paragraphs_with_definitions(&body, &geometry.theorem_definitions).expect("blocks"); let document = build_document(¶graphs, &geometry); assert_eq!(document.units[0].source, "Theorem 5."); } #[test] fn setcounter_offsets_equation_numbers() { let source = "\\setcounter{equation}{2}\n\n\\begin{equation}\nx = 1\n\\end{equation}"; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry_counter(&geometry, "equation"), 2); let paragraphs = paragraphs_with_counters( &body, &geometry.theorem_definitions, geometry_counter(&geometry, "equation"), ) .expect("blocks"); assert_eq!(paragraphs[0].equation_number, Some(3)); } #[test] fn short_captions_follow_into_float_lists() { let source = "\\listoffigures\n\n\\begin{figure}\n\\caption[Short caption]{A long caption}\n\\end{figure}"; let (body, geometry) = geometry_and_body(source); assert!(body.contains("figure")); let blocks = paragraphs(&body).expect("paragraphs"); let document = build_document(&blocks, &geometry); let texts: Vec = document .units .iter() .map(|unit| unit.source.clone()) .collect(); assert!(texts.iter().any(|text| text == "List of Figures")); assert!(texts.iter().any(|text| text == "Figure 1: Short caption")); let spec = blocks .iter() .find_map(|block| block.float.as_ref()) .expect("float"); assert_eq!(spec.caption.as_deref(), Some("A long caption")); assert_eq!(spec.caption_short.as_deref(), Some("Short caption")); } #[test] fn float_list_names_follow_renewcommand() { let source = "\\renewcommand{\\listfigurename}{Abbildungen}\n\n\\renewcommand{\\listtablename}{Tabellen}\n\n\\listoffigures\n\n\\begin{figure}\n\\caption{Plot}\n\\end{figure}\n\n\\listoftables\n\n\\begin{table}\n\\begin{tabular}{l}\nA\n\\end{tabular}\n\\caption{Numbers}\n\\end{table}"; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry.list_figure_name.as_deref(), Some("Abbildungen")); assert_eq!(geometry.list_table_name.as_deref(), Some("Tabellen")); let paragraphs = paragraphs_with_definitions(&body, &geometry.theorem_definitions).expect("blocks"); let document = build_document(¶graphs, &geometry); let names: Vec<&str> = document .units .iter() .map(|unit| unit.source.as_str()) .collect(); assert!(names.contains(&"Abbildungen"), "{names:?}"); assert!(names.contains(&"Tabellen"), "{names:?}"); assert!(!names.contains(&"List of Figures"), "{names:?}"); assert!(!names.contains(&"List of Tables"), "{names:?}"); } #[test] fn secnumdepth_stops_numbering_deep_headings() { let (body, geometry) = geometry_and_body("\\setcounter{secnumdepth}{1}\n\n\\section{A}\n\n\\subsection{B}"); assert_eq!(geometry.secnumdepth, Some(1)); let mut blocks = paragraphs_with_definitions(&body, &[]).expect("paragraphs"); number_sections(&mut blocks, 1, 0, false); assert_eq!(blocks[0].text, "1 A"); assert_eq!(blocks[0].heading_number.as_deref(), Some("1")); assert_eq!(blocks[1].text, "B"); assert_eq!(blocks[1].heading_number, None); } #[test] fn tocdepth_limits_the_table_of_contents() { let source = "\\tableofcontents\n\n\\setcounter{tocdepth}{1}\n\n\\section{A}\n\n\\subsection{B}"; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry.tocdepth, Some(1)); let mut blocks = paragraphs_with_definitions(&body, &[]).expect("paragraphs"); number_sections(&mut blocks, 3, 0, false); expand_toc(&mut blocks, 1, "Contents", false); let section = blocks .iter() .filter(|block| block.text == "1 A" || block.text.ends_with(" 1 A")) .count(); let subsection = blocks.iter().filter(|block| block.text == "1.1 B").count(); assert_eq!(section, 2, "heading plus one TOC line"); assert_eq!(subsection, 1, "heading only; no TOC line"); } #[test] fn report_chapters_number_their_sections() { let source = "\\documentclass{report}\n\\begin{document}\n\n\\chapter{One}\n\nText.\n\n\\section{Sub}\n\nMore.\n\\end{document}"; let (body, geometry) = geometry_and_body(source); let mut blocks = paragraphs(&body).expect("paragraphs"); number_sections(&mut blocks, 3, 0, true); let numbers: Vec<_> = blocks .iter() .filter_map(|block| block.heading_number.clone()) .collect(); assert_eq!(numbers, ["1", "1.1"]); let headings: Vec<_> = blocks .iter() .filter(|block| block.heading_level.is_some()) .map(|block| block.text.clone()) .collect(); assert_eq!(headings, ["1 One", "1.1 Sub"]); assert_eq!(geometry.document_class.as_deref(), Some("report")); } #[test] fn report_appendix_letters_chapters() { let source = "\\documentclass{book}\n\\begin{document}\n\n\\chapter{One}\n\nText.\n\n\\appendix\n\n\\chapter{Extra}\n\nMore.\n\\end{document}"; let (body, _geometry) = geometry_and_body(source); let mut blocks = paragraphs(&body).expect("paragraphs"); number_sections(&mut blocks, 3, 0, true); let numbers: Vec<_> = blocks .iter() .filter_map(|block| block.heading_number.clone()) .collect(); assert_eq!(numbers, ["1", "A"]); } #[test] fn paragraph_headings_number_to_five_levels() { let source = "\\section{A}\n\n\\paragraph{P}\n\n\\subparagraph{S}\n\n\\subsection{B}\n\n\\paragraph{Q}"; let mut blocks = paragraphs(source).expect("paragraphs"); // Article's default secnumdepth is 3; the five-level counters are // reachable by raising it, which LaTeX classes do for reports. number_sections(&mut blocks, 5, 0, false); let numbers: Vec<&str> = blocks .iter() .filter(|block| block.heading_level.is_some()) .map(|block| block.text.as_str()) .collect(); assert_eq!( numbers, ["1 A", "1.0.0.1 P", "1.0.0.1.1 S", "1.1 B", "1.1.0.1 Q"] ); } #[test] fn table_of_contents_stops_at_subsubsections() { let source = "\\tableofcontents\n\n\\section{A}\n\n\\paragraph{P}"; let mut blocks = paragraphs(source).expect("paragraphs"); number_sections(&mut blocks, 3, 0, false); expand_toc(&mut blocks, 3, "Contents", false); let paragraph_entries = blocks .iter() .filter(|block| block.text.trim() == "P") .count(); assert_eq!(paragraph_entries, 1); assert!( blocks .iter() .all(|block| block.text.trim() != "\\texrratoc") ); } #[test] fn table_of_contents_entries_gain_page_numbers() { let source = "\\tableofcontents\n\n\\section{One}\n\nFirst body paragraph.\n\n\\newpage\n\n\\section{Two}\n\nSecond body paragraph."; let (body, geometry) = geometry_and_body(source); let paragraphs = paragraphs(&body).expect("paragraphs"); let mut document = build_document(¶graphs, &geometry); apply_geometry(&mut document, &geometry); let engine = layout_document(&document); assert!(stamp_toc_pages(&mut document, &engine, &geometry)); let entries: Vec<&Unit> = document .units .iter() .filter(|unit| unit.toc_target.is_some()) .collect(); assert_eq!(entries.len(), 2, "{entries:?}"); assert!( entries[0].source.contains("..") && entries[0].source.ends_with(" 1"), "{}", entries[0].source ); assert!( entries[1].source.contains("..") && entries[1].source.ends_with(" 2"), "{}", entries[1].source ); assert!(!stamp_toc_pages(&mut document, &engine, &geometry)); } #[test] fn toc_leaders_fill_the_measure() { let measure = 300 * SCALE; let leader = toc_leader("1 Intro", "1", measure).expect("leader"); assert!(leader.starts_with("1 Intro "), "{leader}"); assert!(leader.ends_with(" 1"), "{leader}"); assert!(leader.contains(".."), "{leader}"); let width = text_width_roman(&leader); assert!(width <= measure, "leader overflows: {width} > {measure}"); let dot = Cmr10Metrics::Roman.width('.'); assert!( measure - width < dot + SCALE / 2, "short by {}", measure - width ); assert!(toc_leader("1 Intro", "1", 10 * SCALE).is_none()); } #[test] fn float_lists_gain_page_numbers() { let source = "\\listoffigures\n\n\\newpage\n\n\\begin{figure}[t]\n\\caption{Picture}\n\\end{figure}\n\nBody."; let (body, geometry) = geometry_and_body(source); let paragraphs = paragraphs_with_definitions(&body, &geometry.theorem_definitions).expect("blocks"); let mut document = build_document(¶graphs, &geometry); apply_geometry(&mut document, &geometry); let engine = layout_document(&document); assert!(stamp_toc_pages(&mut document, &engine, &geometry)); let entries: Vec<&Unit> = document .units .iter() .filter(|unit| unit.toc_target.is_some()) .collect(); assert_eq!(entries.len(), 1, "{entries:?}"); assert!( entries[0].source.contains("..") && entries[0].source.ends_with(" 2"), "{}", entries[0].source ); assert!(!stamp_toc_pages(&mut document, &engine, &geometry)); } #[test] fn table_of_contents_lists_numbered_headings() { let source = "\\tableofcontents\n\n\\section{Intro}\n\nText.\n\n\\subsection{Sub}\n\nMore.\n\n\\section*{Notes}\n\nEnd."; let (body, geometry) = geometry_and_body(source); let paragraphs = paragraphs_with_definitions(&body, &geometry.theorem_definitions).expect("blocks"); let document = build_document(¶graphs, &geometry); let sources: Vec<&str> = document .units .iter() .map(|unit| unit.source.as_str()) .collect(); assert_eq!( sources .iter() .filter(|source| **source == "1 Intro") .count(), 2, "{sources:?}" ); assert_eq!( sources .iter() .filter(|source| **source == "1.1 Sub") .count(), 2, "{sources:?}" ); assert_eq!( sources.iter().filter(|source| **source == "Notes").count(), 1, "{sources:?}" ); assert!(!sources.iter().any(|source| source.contains("texrratoc"))); assert_eq!(document.units[0].source, "Contents"); assert_eq!(document.units[1].source, "1 Intro"); assert_eq!(document.units[2].source, "1.1 Sub"); assert_eq!( document.units[2] .paragraph_style .as_ref() .unwrap() .left_skip, 12 * 65_536 ); } #[test] fn input_directives_expand_from_the_reader() { let source = "Before \\input{section} after \\input{nested}"; let expanded = expand_inputs(source, |name| match name { "section" => Some("Included.".to_string()), "nested" => Some("\\input{deep}".to_string()), "deep" => Some("Deep.".to_string()), _ => None, }); assert_eq!(expanded, "Before Included. after Deep."); assert_eq!( expand_inputs("\\input{missing}", |_| None), "\\input{missing}" ); } #[test] fn vspace_between_paragraphs_sets_vertical_glue() { let source = "A.\n\n\\vspace{7pt plus 1pt minus 2pt}\n\nB.\n\n\\vspace*{2mm}\n\nC."; let blocks = paragraphs(source).expect("paragraphs"); assert_eq!(blocks[1].space_before, 7 * SCALE); assert_eq!(blocks[1].space_stretch, SCALE); assert_eq!(blocks[1].space_shrink, 2 * SCALE); assert!((blocks[2].space_before - 2 * 186_468).abs() <= 1); assert!(!blocks.iter().any(|block| block.text.contains("vspace"))); } #[test] fn paragraphs_read_vertical_skip_commands() { let source = "Alpha.\n\n\\medskip\n\nBeta.\n\n\\bigskip\n\nGamma.\n\n\\vskip 5pt plus 2pt minus 1pt\n\nDelta."; let parsed = paragraphs(source).expect("paragraphs"); assert_eq!(parsed.len(), 4); assert_eq!(parsed[0].space_before, 0); assert_eq!(parsed[1].space_before, 6 * SCALE); assert_eq!(parsed[1].space_stretch, 2 * SCALE); assert_eq!(parsed[1].space_shrink, 2 * SCALE); assert_eq!(parsed[2].space_before, 12 * SCALE); assert_eq!(parsed[2].space_stretch, 4 * SCALE); assert_eq!(parsed[2].space_shrink, 4 * SCALE); assert_eq!(parsed[3].space_before, 5 * SCALE); assert_eq!(parsed[3].space_stretch, 2 * SCALE); assert_eq!(parsed[3].space_shrink, SCALE); assert!( !parsed .iter() .any(|paragraph| paragraph.text.contains("skip")) ); let document = build_document(&parsed, &PageGeometry::default()); assert_eq!(document.units[1].space_before, 6 * SCALE); assert_eq!(document.units[1].space_stretch, 2 * SCALE); assert_eq!(document.units[1].space_shrink, 2 * SCALE); assert_eq!(document.units[2].space_before, 12 * SCALE); assert_eq!(document.units[3].space_before, 5 * SCALE); assert_eq!(document.units[3].space_stretch, 2 * SCALE); assert_eq!(document.units[3].space_shrink, SCALE); } #[test] fn inline_math_becomes_math_boxes() { let blocks = paragraphs("Value $x^2$ tail.").expect("paragraphs"); let document = build_document(&blocks, &PageGeometry::default()); let paragraph = match &document.units[0].items[0] { VerticalItem::Paragraph(paragraph) => paragraph, _ => panic!("expected a paragraph unit"), }; let math = paragraph .lines .iter() .flatten() .find_map(|item| match item { texrra_tex_core::paragraph::HorizontalItem::Box(box_) if box_.math.is_some() => { Some(box_) } _ => None, }) .expect("inline math box"); assert!(math.character.is_none()); assert!(math.width > 0); assert_eq!(document.units[0].source, "Value $x^2$ tail."); } #[test] fn inline_verb_paints_typewriter_text() { let json = preview_json("A \\verb|x&y| b.").expect("preview"); assert!(json.contains(">x"), "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 hypersetup_link_border_colors_annotations() { let pdf = pdf_bytes( "\\hypersetup{linkbordercolor=red}\n\nVisit \\href{https://example.com}{Example}.", ) .expect("pdf"); let pdf = String::from_utf8_lossy(&pdf); assert!(pdf.contains("/Border [0 0 1]"), "{pdf}"); assert!(pdf.contains("/C [1.000 0.000 0.000]"), "{pdf}"); let plain = pdf_bytes("Visit \\href{https://example.com}{Example}.").expect("pdf"); let plain = String::from_utf8_lossy(&plain); assert!(plain.contains("/Border [0 0 0]"), "{plain}"); assert!(!plain.contains("/C [1.000"), "{plain}"); } #[test] fn hypersetup_urlcolor_paints_links() { let json = preview_json( "\\hypersetup{urlcolor=red}\n\nVisit \\href{https://example.com}{Example}.", ) .expect("preview"); assert!(json.contains(r##"fill=\"#ff0000\""##), "{json}"); assert!(json.contains(">E"), "{json}"); } #[test] fn href_creates_link_boxes() { let source = "Visit \\href{https://example.com}{the site} now."; let blocks = paragraphs(source).expect("paragraphs"); let document = build_document(&blocks, &PageGeometry::default()); let mut linked = 0; let mut backslashes = 0; for unit in &document.units { for item in &unit.items { let VerticalItem::Paragraph(paragraph) = item else { continue; }; for line in ¶graph.lines { for item in line { let texrra_tex_core::paragraph::HorizontalItem::Box(box_) = item else { continue; }; if box_.link.as_deref() == Some("https://example.com") { linked += 1; } if box_.character == Some('\\') { backslashes += 1; } } } } } assert!(linked > 0); assert_eq!(backslashes, 0); } #[test] fn sized_paragraphs_link_href_commands() { let source = "\\Large Visit \\href{https://example.com}{the site}."; let blocks = paragraphs(source).expect("paragraphs"); let document = build_document(&blocks, &PageGeometry::default()); let mut linked = 0; let mut backslashes = 0; for unit in &document.units { for item in &unit.items { let VerticalItem::Paragraph(paragraph) = item else { continue; }; for line in ¶graph.lines { for item in line { let texrra_tex_core::paragraph::HorizontalItem::Box(box_) = item else { continue; }; if box_.link.is_some() { linked += 1; } if box_.character == Some('\\') { backslashes += 1; } } } } } assert!(linked > 0, "sized runs must keep their link"); assert_eq!(backslashes, 0, "href delimiters leaked"); } #[test] fn inline_math_inside_styled_runs_keeps_both_faces() { let blocks = paragraphs("\\textbf{Value $x$}").expect("paragraphs"); let document = build_document(&blocks, &PageGeometry::default()); let paragraph = match &document.units[0].items[0] { VerticalItem::Paragraph(paragraph) => paragraph, _ => panic!("expected a paragraph unit"), }; let boxes: Vec<_> = paragraph .lines .iter() .flatten() .filter_map(|item| match item { texrra_tex_core::paragraph::HorizontalItem::Box(box_) => Some(box_), _ => None, }) .collect(); assert!( boxes.iter().any(|box_| box_.math.is_some()), "the math run keeps its math box" ); assert!( boxes .iter() .any(|box_| box_.font == Some(ParagraphFont::Bold) && box_.math.is_none()), "the surrounding text keeps its bold face" ); assert!( boxes.iter().all(|box_| box_.character != Some('$')), "math delimiters are consumed" ); } #[test] fn displaymath_environment_becomes_a_math_block() { let blocks = paragraphs("\\begin{displaymath}\nx = 1\n\\end{displaymath}").expect("paragraphs"); assert_eq!(blocks.len(), 1); assert!(blocks[0].math); assert_eq!(blocks[0].text, "x = 1"); assert_eq!(blocks[0].equation_number, None); } #[test] fn math_environment_becomes_inline_math() { let svg = preview_json("Body \\begin{math}x\\end{math}.").expect("preview"); assert!( svg.contains("font-style=\\\"italic\\\""), "missing math: {svg}" ); assert!(!svg.contains("begin{math}"), "environment leaked: {svg}"); } #[test] fn inline_math_stays_literal_in_sized_paragraphs() { let blocks = paragraphs("\\large Value $x$ tail.").expect("paragraphs"); let document = build_document(&blocks, &PageGeometry::default()); let paragraph = match &document.units[0].items[0] { VerticalItem::Paragraph(paragraph) => paragraph, _ => panic!("expected a paragraph unit"), }; let boxes: Vec<_> = paragraph .lines .iter() .flatten() .filter_map(|item| match item { texrra_tex_core::paragraph::HorizontalItem::Box(box_) => Some(box_), _ => None, }) .collect(); assert!(boxes.iter().all(|box_| box_.math.is_none())); assert!(boxes.iter().any(|box_| box_.character == Some('$'))); } #[test] fn pagecolor_fills_the_page_background() { let json = preview_json("\\pagecolor{yellow}\n\nBody.").expect("preview"); assert!(json.contains(r##"fill=\"#ffff00\""##), "{json}"); assert!(!json.contains("pagecolor")); let pdf = pdf_bytes("\\pagecolor{yellow}\n\nBody.").expect("pdf"); let text = String::from_utf8_lossy(&pdf); assert!(text.contains("1.000 1.000 0.000 rg"), "{text}"); } #[test] fn fcolorbox_paints_a_frame_and_background() { let source = "Body \\fcolorbox{red}{lime}{Framed} word."; let json = preview_json(source).expect("preview"); assert!(json.contains(r##"stroke=\"#ff0000\""##), "{json}"); assert!(json.contains(r##"fill=\"#00ff00\""##), "{json}"); assert!(!json.contains("fcolorbox"), "{json}"); let pdf = pdf_bytes(source).expect("pdf"); let text = String::from_utf8_lossy(&pdf); assert!(text.contains("1.000 0.000 0.000 RG"), "{text}"); assert!(text.contains("0.000 1.000 0.000 rg"), "{text}"); } #[test] fn color_runs_recognise_fbox() { let runs = split_color_runs(r"\fbox{Boxed}", &[]); assert_eq!(runs.len(), 1); assert!(runs[0].2 == Some([0, 0, 0]), "{runs:?}"); assert_eq!(runs[0].3, "Boxed"); } #[test] fn saveboxes_reuse_their_content() { let source = "\\newsavebox{\\boxa}\n\\sbox{\\boxa}{Stored}\n\nFirst \\usebox{\\boxa}."; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry.macros.len(), 1); let blocks = paragraphs(&body).expect("paragraphs"); assert_eq!(visible(&blocks[0].text), "First Stored."); } #[test] fn saveboxes_defined_in_the_body_work() { let units = paragraphs("\\sbox{\\boxb}{In body}\n\nSee \\usebox{\\boxb}.").expect("paragraphs"); let _ = units; let (body, _geometry) = geometry_and_body("\\sbox{\\boxb}{In body}\n\nSee \\usebox{\\boxb}."); let blocks = paragraphs(&body).expect("paragraphs"); assert_eq!(visible(&blocks[0].text), "See In body."); } #[test] fn struts_leave_no_text_behind() { let text = strip_noop_commands(r"A\strut B \mathstrut C"); assert_eq!(text, "A B C"); } #[test] fn character_commands_print_their_codepoints() { let blocks = paragraphs("A\\char66 C and \\symbol{68}.").expect("paragraphs"); let document = build_document(&blocks, &PageGeometry::default()); assert_eq!(document.units[0].source, "AB C and D."); } #[test] fn leftline_keeps_its_argument_flush_left() { let blocks = paragraphs("\\leftline{Short.}").expect("paragraphs"); let document = build_document(&blocks, &PageGeometry::default()); assert_eq!(document.units[0].source, "Short."); let style = document.units[0].paragraph_style.clone().expect("style"); assert!(!style.centered && !style.right_aligned); } #[test] fn rightline_flushes_its_argument_right() { let blocks = paragraphs("\\rightline{Short.}").expect("paragraphs"); let document = build_document(&blocks, &PageGeometry::default()); let engine = Engine::layout(&document); let x = engine .pages() .iter() .flat_map(|page| page.display_list().items) .find_map(|item| match item { texrra_tex_core::render::DisplayItem::Text { text, x, .. } if text == "S" => { Some(x) } _ => None, }) .expect("S glyph"); assert!(x > 300, "right-flushed text starts at {}", x); } #[test] fn centerline_centres_its_argument() { let blocks = paragraphs("\\centerline{Short.}").expect("paragraphs"); let document = build_document(&blocks, &PageGeometry::default()); let engine = Engine::layout(&document); let x = engine .pages() .iter() .flat_map(|page| page.display_list().items) .find_map(|item| match item { texrra_tex_core::render::DisplayItem::Text { text, x, .. } if text == "S" => { Some(x) } _ => None, }) .expect("S glyph"); assert!(x > 0, "centerline text starts at {}", x); } #[test] fn raggedright_declaration_keeps_lines_short() { let blocks = paragraphs("\\raggedright A line of text.").expect("paragraphs"); let document = build_document(&blocks, &PageGeometry::default()); let style = document.units[0].paragraph_style.clone().expect("style"); assert!(style.ragged_right); assert_eq!(document.units[0].source, "A line of text."); } #[test] fn centering_declaration_centres_the_block() { let blocks = paragraphs("\\centering Short.").expect("paragraphs"); let document = build_document(&blocks, &PageGeometry::default()); let engine = Engine::layout(&document); let x = engine .pages() .iter() .flat_map(|page| page.display_list().items) .find_map(|item| match item { texrra_tex_core::render::DisplayItem::Text { text, x, .. } if text == "S" => { Some(x) } _ => None, }) .expect("S glyph"); assert!(x > 0, "centred text starts at {}", x); } #[test] fn romannumeral_prints_a_register() { let (body, _geometry) = geometry_and_body("\\newcount\\a\n\\a=4\n\nValue \\romannumeral\\a."); let blocks = paragraphs(&body).expect("paragraphs"); assert_eq!(blocks[0].text, "Value iv."); } #[test] fn named_spaces_reach_the_layout() { let blocks = paragraphs("A\\enspace B").expect("paragraphs"); let document = build_document(&blocks, &PageGeometry::default()); let engine = Engine::layout(&document); let mut positions = Vec::new(); let mut leaked = false; for page in engine.pages() { for item in page.display_list().items { if let texrra_tex_core::render::DisplayItem::Text { text, x, .. } = item { if text == "e" { leaked = true; } if text == "A" || text == "B" { positions.push((text, x)); } } } } let a = positions.iter().find(|(text, _)| text == "A").expect("A").1; let b = positions.iter().find(|(text, _)| text == "B").expect("B").1; assert!(b - a > 400_000, "gap {}", b - a); assert!(!leaked); } #[test] fn quad_commands_become_text_spaces() { let blocks = paragraphs("A\\quad B").expect("paragraphs"); let document = build_document(&blocks, &PageGeometry::default()); let engine = Engine::layout(&document); let mut positions = Vec::new(); for page in engine.pages() { for item in page.display_list().items { if let texrra_tex_core::render::DisplayItem::Text { text, x, .. } = item { if text == "A" || text == "B" { positions.push((text, x)); } } } } let a = positions.iter().find(|(text, _)| text == "A").expect("A").1; let b = positions.iter().find(|(text, _)| text == "B").expect("B").1; assert!(b - a > 700_000, "gap {}", b - a); let leaked = document.units[0].items.iter().any(|item| match item { texrra_tex_core::VerticalItem::Paragraph(paragraph) => { paragraph.lines.iter().flatten().any(|item| { matches!( item, texrra_tex_core::paragraph::HorizontalItem::Box(b) if b.character == Some('q') ) }) } _ => false, }); assert!(!leaked); } #[test] fn hspace_keeps_its_math_width() { let blocks = paragraphs("A \\hspace{2em} B").expect("paragraphs"); let document = build_document(&blocks, &PageGeometry::default()); let engine = Engine::layout(&document); let mut positions = Vec::new(); for page in engine.pages() { for item in page.display_list().items { if let texrra_tex_core::render::DisplayItem::Text { text, x, .. } = item { if text == "A" || text == "B" { positions.push((text, x)); } } } } let a = positions.iter().find(|(text, _)| text == "A").expect("A").1; let b = positions.iter().find(|(text, _)| text == "B").expect("B").1; assert!(b - a > 1_200_000, "gap {}", b - a); } #[test] fn checkmark_expands_in_text() { let preview = preview_json("Done \\checkmark").expect("preview"); assert!(!preview.contains("checkmark")); assert!(preview.contains("\"warnings\":[]"), "warnings: {preview}"); } #[test] fn punctuation_symbols_expand() { let preview = preview_json("\\textpm \\textminus \\texttimes \\textdiv \\textsection \\textdagger") .expect("preview"); assert!(!preview.contains("textpm")); assert!(!preview.contains("textdagger")); assert!(preview.contains("\"warnings\":[]"), "warnings: {preview}"); } #[test] fn more_text_symbols_expand() { let preview = preview_json( "A \\textquotesingle{} \\textunderscore{} \\textbraceleft{} \\textbraceright{} B", ) .expect("preview"); assert!(preview.contains(">'")); assert!(preview.contains(">_")); assert!(!preview.contains("textquotesingle")); assert!(!preview.contains("textbraceleft")); } #[test] fn break_hints_and_discretionary_hyphens_vanish() { let text = strip_noop_commands("First\\linebreak[4] Second \\- co\\-op."); assert_eq!(text, "First Second coop."); } #[test] fn noop_commands_are_dropped() { let preview = preview_json("A \\protect B \\relax C \\ignorespaces D \\phantomsection E.") .expect("preview"); assert!(preview.contains(">A")); assert!(preview.contains(">E")); assert!(!preview.contains("protect")); assert!(preview.contains("\"warnings\":[]")); } #[test] fn underline_keeps_its_text() { let text = strip_box_commands("A \\underline{B} C"); assert_eq!(text, "A B C"); let preview = preview_json("A \\underline{B} C").expect("preview"); assert!(preview.contains(">B")); assert!(!preview.contains("underline")); } #[test] fn box_commands_keep_their_text() { let preview = preview_json("A \\mbox{B C} \\makebox[2cm][l]{D} \\hbox{E}.").expect("preview"); assert!(preview.contains(">B")); assert!(preview.contains(">E")); assert!(!preview.contains("mbox")); assert!(!preview.contains("makebox")); } #[test] fn ensuremath_makes_inline_math() { let preview = preview_json("A \\ensuremath{x^2} B").expect("preview"); assert!(preview.contains("font-style=\\\"italic\\\"")); assert!(!preview.contains("ensuremath")); } #[test] fn tildes_make_spaces() { let json = preview_json("Figure~1.").expect("preview"); assert!(!json.contains(">~"), "{json}"); assert!(json.contains(">F"), "{json}"); } #[test] fn url_tildes_stay_literal() { let json = preview_json(r"\url{https://x.test/a~b}").expect("preview"); assert!(json.contains(">~"), "{json}"); } #[test] fn fbox_draws_a_frame_without_a_background() { let json = preview_json(r"\fbox{Boxed}").expect("preview"); assert!( json.contains("stroke=") && json.contains("#000000"), "{json}" ); assert!(json.contains(">B"), "{json}"); assert!(!json.contains("fbox"), "{json}"); } #[test] fn colorbox_paints_a_background_rectangle() { let source = "Body \\colorbox{lime}{Boxed} word."; let json = preview_json(source).expect("preview"); assert!(json.contains(r##"fill=\"#00ff00\""##), "{json}"); assert!(json.contains(r##" = Vec::new(); for page in engine.pages() { let list = page.display_list(); ys.extend(list.items.iter().filter_map(|item| match item { texrra_tex_core::render::DisplayItem::Text { y, .. } => Some(*y), _ => None, })); } ys.sort_unstable(); ys.dedup(); ys.len() }; let wide = line_count(long); let narrow = line_count(&format!("\\textwidth=240pt\n\n{long}")); assert!(wide >= 1, "the wide measure should paint at least one line"); assert!( narrow > wide, "narrow measure should wrap into more lines: {narrow} vs {wide}" ); } #[test] fn setlength_and_hsize_set_the_measure() { let (_, textwidth) = geometry_and_body("\\setlength{\\textwidth}{300pt}\n\nA paragraph."); assert_eq!(textwidth.line_width, Some(300 * SCALE)); let (_, hsize) = geometry_and_body("\\hsize=360pt\n\nA paragraph."); assert_eq!(hsize.line_width, Some(360 * SCALE)); let (_, lengths) = geometry_and_body( "\\setlength{\\parindent}{20pt}\n\n\\setlength{\\textheight}{500pt}\n\nA paragraph.", ); assert_eq!(lengths.line_width, None); assert_eq!(lengths.par_indent, Some(20 * SCALE)); assert_eq!(lengths.textheight, Some(500 * SCALE)); let (_, glue) = geometry_and_body("\\setlength{\\parskip}{6pt plus 2pt minus 1pt}\n\nA paragraph."); assert_eq!(glue.par_skip, Some(6 * SCALE)); assert_eq!(glue.par_skip_stretch, Some(2 * SCALE)); assert_eq!(glue.par_skip_shrink, Some(SCALE)); } #[test] fn headings_are_numbered_and_starred_headings_are_not() { let source = "\\section{One}\n\n\\subsection{Two}\n\n\\section*{Star}\n\n\\section{Three}"; let mut blocks = paragraphs(source).expect("blocks"); number_sections(&mut blocks, 3, 0, false); 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::(), ), _ => 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"), "{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 = 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, Option)> = 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> = 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"), "first row number: {json}"); assert!(json.contains(">2"), "second row number: {json}"); assert!(json.contains(">="), "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"), "formula glyphs in SVG: {json}"); assert!(json.contains(">("), "open tag parenthesis"); assert!(json.contains(">1"), "equation number"); assert!(json.contains(">)"), "close tag parenthesis"); } } #[cfg(test)] mod nfss_tests { use super::*; fn paragraph_font(raw: &str) -> ParagraphFont { paragraphs(raw).expect("paragraphs")[0].font } #[test] fn declarations_select_built_in_faces() { assert_eq!(paragraph_font("\\sffamily Sans text"), ParagraphFont::Sans); assert_eq!( paragraph_font("\\sffamily\\bfseries Sans text"), ParagraphFont::SansBold ); assert_eq!( paragraph_font("\\sffamily\\itshape Sans text"), ParagraphFont::SansItalic ); assert_eq!( paragraph_font("\\scshape Small text"), ParagraphFont::SmallCaps ); assert_eq!( paragraph_font("\\sffamily\\scshape Small text"), ParagraphFont::Sans ); assert_eq!( paragraph_font("\\bfseries\\scshape Small text"), ParagraphFont::Bold ); assert_eq!( paragraph_font("\\scshape\\itshape Small text"), ParagraphFont::Italic ); assert_eq!( paragraph_font("\\itshape\\scshape Small text"), ParagraphFont::SmallCaps ); assert_eq!(paragraph_font("\\ttfamily Mono text"), ParagraphFont::Mono); assert_eq!(paragraph_font("\\bfseries Bold text"), ParagraphFont::Bold); assert_eq!( paragraph_font("\\itshape Italic text"), ParagraphFont::Italic ); assert_eq!( paragraph_font("\\sffamily\\bfseries Bold sans"), ParagraphFont::SansBold ); assert_eq!( paragraph_font("\\rmfamily\\mdseries\\upshape Roman"), ParagraphFont::Roman ); } #[test] fn declarations_do_not_leak_into_the_text() { let blocks = paragraphs("\\sffamily\\bfseries Fancy text").expect("paragraphs"); assert_eq!(blocks[0].text, "Fancy text"); } #[test] fn nfss_commands_configure_the_face() { assert_eq!( paragraph_font("\\fontfamily{cmss}\\selectfont Sans"), ParagraphFont::Sans ); assert_eq!( paragraph_font("\\fontseries{bx}\\selectfont Bold"), ParagraphFont::Bold ); assert_eq!( paragraph_font("\\fontshape{it}\\selectfont Italic"), ParagraphFont::Italic ); assert_eq!( paragraph_font("\\fontencoding{T1}\\selectfont Roman"), ParagraphFont::Roman ); assert_eq!(paragraph_font("\\normalfont Reset"), ParagraphFont::Roman); } #[test] fn slanted_and_italic_shapes_stay_distinct() { assert_eq!(paragraph_font("\\slshape slanted"), ParagraphFont::Slanted); assert_eq!(paragraph_font("\\itshape italic"), ParagraphFont::Italic); assert_eq!( paragraph_font("\\bfseries\\slshape bold slanted"), ParagraphFont::BoldSlanted ); assert_eq!( paragraph_font("\\ttfamily\\itshape tt italic"), ParagraphFont::MonoItalic ); assert_eq!( paragraph_font("\\slshape\\itshape italic"), ParagraphFont::Italic ); assert_eq!( paragraph_font("\\ttfamily\\slshape tt slanted"), ParagraphFont::MonoItalic ); } #[test] fn legacy_declarations_stay_bounded() { assert_eq!(paragraph_font("\\tt Legacy mono"), ParagraphFont::Mono); assert_eq!(paragraph_font("\\bf Legacy bold"), ParagraphFont::Bold); let blocks = paragraphs("\\item bullet").expect("paragraphs"); assert_eq!(blocks[0].text, "\\item bullet"); } #[test] fn texttt_and_textsf_select_faces() { assert_eq!(paragraph_font("\\texttt{code}"), ParagraphFont::Mono); assert_eq!(paragraph_font("\\textsf{sans}"), ParagraphFont::Sans); assert_eq!(paragraph_font("\\texttt{code words}"), ParagraphFont::Mono); } } #[cfg(test)] mod inline_tests { use super::*; #[test] fn text_symbols_render_as_characters() { let runs = inline_runs("\\LaTeX{} and \\ldots", ParagraphFont::Roman).expect("runs"); let text: String = runs.into_iter().map(|(_, text)| text).collect(); assert_eq!(text, "LaTeX and \u{2026}"); assert!(inline_runs("\\LaTeX{}", ParagraphFont::Roman).is_some()); } #[test] fn case_commands_paint_uppercase_text() { let svg = preview_json("\\MakeUppercase{quiet}.").expect("preview"); assert!(svg.contains(">Q"), "missing uppercase: {svg}"); assert!(!svg.contains("MakeUppercase"), "command leaked: {svg}"); } #[test] fn letter_commands_paint_unicode_glyphs() { let svg = preview_json("Stra\\ss e").expect("preview"); assert!(svg.contains(">ß"), "missing sharp s: {svg}"); assert!(!svg.contains("\\ss"), "command leaked: {svg}"); } #[test] fn text_superscript_paints_smaller_and_higher() { let svg = preview_json("E = mc\\textsuperscript{2}").expect("preview"); assert!( svg.contains("font-size=\\\"7.000\\\""), "missing script size: {svg}" ); assert!(svg.contains(">2"), "missing script glyph: {svg}"); assert!(!svg.contains("textsuperscript"), "command leaked: {svg}"); } #[test] fn accent_commands_paint_precomposed_glyphs() { let svg = preview_json("Caf\\'e au lait.").expect("preview"); assert!(svg.contains(">é"), "missing composed glyph: {svg}"); assert!(!svg.contains(">'"), "accent leaked as text: {svg}"); } #[test] fn text_symbols_paint_in_previews() { let json = preview_json("\\LaTeX{} \\S1").expect("preview"); assert!(json.contains(">L")); assert!(json.contains(">\u{a7}")); assert!(!json.contains("LaTeX{}")); } #[test] fn case_commands_transform_their_argument() { assert_eq!( inline_runs("\\MakeUppercase{Straße}", ParagraphFont::Roman), Some(vec![(ParagraphFont::Roman, "STRASSE".to_string())]) ); assert_eq!( inline_runs("\\MakeLowercase{ÀÉ}", ParagraphFont::Roman), Some(vec![(ParagraphFont::Roman, "àé".to_string())]) ); assert_eq!( inline_runs("\\uppercase{abc} tail", ParagraphFont::Roman), Some(vec![(ParagraphFont::Roman, "ABC tail".to_string())]) ); } #[test] fn letter_and_symbol_commands_render_unicode() { assert_eq!( inline_runs("Stra\\ss e", ParagraphFont::Roman), Some(vec![(ParagraphFont::Roman, "Straße".to_string())]) ); assert_eq!( inline_runs("\\ae\\oe\\aa", ParagraphFont::Roman), Some(vec![(ParagraphFont::Roman, "æœå".to_string())]) ); assert_eq!( inline_runs("\\o\\l\\dh\\th", ParagraphFont::Roman), Some(vec![(ParagraphFont::Roman, "øłðþ".to_string())]) ); assert_eq!(inline_runs("\\in and \\only", ParagraphFont::Roman), None); } #[test] fn text_superscripts_and_subscripts_split_sized_runs() { assert_eq!( inline_styled_runs("x\\textsuperscript{2}", ParagraphFont::Roman), Some(vec![ (ParagraphFont::Roman, 655_360, 0, "x".to_string()), (ParagraphFont::Roman, 458_752, 262_144, "2".to_string()), ]) ); assert_eq!( inline_styled_runs("x\\textsubscript{i}", ParagraphFont::Roman), Some(vec![ (ParagraphFont::Roman, 655_360, 0, "x".to_string()), (ParagraphFont::Roman, 458_752, -262_144, "i".to_string()), ]) ); } #[test] fn accent_commands_compose_characters() { assert_eq!( inline_runs("caf\\'e", ParagraphFont::Roman), Some(vec![(ParagraphFont::Roman, "café".to_string())]) ); assert_eq!( inline_runs("na\\\"ive", ParagraphFont::Roman), Some(vec![(ParagraphFont::Roman, "naïve".to_string())]) ); assert_eq!( inline_runs("\\c{c}a", ParagraphFont::Roman), Some(vec![(ParagraphFont::Roman, "ça".to_string())]) ); assert_eq!( inline_runs("\\'q", ParagraphFont::Roman), Some(vec![(ParagraphFont::Roman, "q\u{301}".to_string())]) ); assert_eq!( inline_runs("\\vspace and \\cup", ParagraphFont::Roman), None ); } #[test] fn verb_spans_render_monospaced() { let runs = inline_runs("a \\verb|x&y| b", ParagraphFont::Roman).expect("runs"); assert_eq!( runs, vec![ (ParagraphFont::Roman, "a ".to_string()), (ParagraphFont::Mono, "x&y".to_string()), (ParagraphFont::Roman, " b".to_string()), ] ); let star = inline_runs("\\verb*!a_b!", ParagraphFont::Roman).expect("runs"); assert_eq!(star, vec![(ParagraphFont::Mono, "a_b".to_string())]); } #[test] fn inline_commands_split_runs() { let runs = inline_runs("Plain \\textbf{bold} tail", ParagraphFont::Roman).expect("runs"); assert_eq!( runs, vec![ (ParagraphFont::Roman, "Plain ".to_string()), (ParagraphFont::Bold, "bold".to_string()), (ParagraphFont::Roman, " tail".to_string()), ] ); } #[test] fn textsl_selects_the_slanted_shape() { let runs = inline_runs("\\textsl{slanted}", ParagraphFont::Roman).expect("runs"); assert_eq!(runs[0], (ParagraphFont::Slanted, "slanted".to_string())); let runs = inline_runs("\\textbf{\\textsl{slanted}}", ParagraphFont::Roman).expect("runs"); assert_eq!(runs[0], (ParagraphFont::BoldSlanted, "slanted".to_string())); } #[test] fn textsc_composes_with_the_surrounding_face() { let runs = inline_runs("\\textsc{small}", ParagraphFont::Roman).expect("runs"); assert_eq!(runs[0], (ParagraphFont::SmallCaps, "small".to_string())); let runs = inline_runs("\\textbf{\\textsc{small}}", ParagraphFont::Roman).expect("runs"); assert_eq!(runs[0], (ParagraphFont::Bold, "small".to_string())); } #[test] fn textsf_inside_bold_stays_bold() { let runs = inline_runs("\\textbf{a \\textsf{b}}", ParagraphFont::Roman).expect("runs"); assert_eq!(runs[1], (ParagraphFont::SansBold, "b".to_string())); } #[test] fn plain_paragraphs_have_no_runs() { assert!(inline_runs("no commands here", ParagraphFont::Sans).is_none()); } #[test] fn base_font_fills_plain_segments() { let runs = inline_runs("\\texttt{code} and text", ParagraphFont::Sans).expect("runs"); assert_eq!(runs[0], (ParagraphFont::Mono, "code".to_string())); assert_eq!(runs[1], (ParagraphFont::Sans, " and text".to_string())); } #[test] fn declarations_switch_the_following_text() { let runs = inline_runs("plain \\bfseries bold", ParagraphFont::Roman).expect("runs"); assert_eq!( runs, vec![ (ParagraphFont::Roman, "plain ".to_string()), (ParagraphFont::Bold, "bold".to_string()), ] ); } #[test] fn mid_paragraph_declarations_stay_inside_their_group() { let runs = inline_runs("a {\\bfseries b} c", ParagraphFont::Roman).expect("runs"); assert_eq!( runs, vec![ (ParagraphFont::Roman, "a ".to_string()), (ParagraphFont::Bold, "b".to_string()), (ParagraphFont::Roman, " c".to_string()), ] ); } #[test] fn em_toggles_emphasis() { let runs = inline_runs("a \\em b", ParagraphFont::Roman).expect("runs"); assert_eq!(runs[0], (ParagraphFont::Roman, "a ".to_string())); assert_eq!(runs[1].0, ParagraphFont::Italic); assert_eq!(runs[1].1, "b"); let runs = inline_runs("a {\\bfseries b \\em c}", ParagraphFont::Roman).expect("runs"); assert!( runs.iter() .any(|(font, _)| *font == ParagraphFont::BoldItalic) ); assert!(inline_runs("\\emph{x}", ParagraphFont::Roman).is_some()); } #[test] fn declaration_groups_switch_the_face() { let runs = inline_runs("{\\bfseries bold} normal", ParagraphFont::Roman).expect("runs"); assert_eq!( runs, vec![ (ParagraphFont::Bold, "bold".to_string()), (ParagraphFont::Roman, " normal".to_string()), ] ); } #[test] fn nested_groups_recurse() { let runs = inline_runs( "{\\bfseries bold \\textit{italic} bold} plain", ParagraphFont::Roman, ) .expect("runs"); assert_eq!( runs, vec![ (ParagraphFont::Bold, "bold ".to_string()), (ParagraphFont::BoldItalic, "italic".to_string()), (ParagraphFont::Bold, " bold".to_string()), (ParagraphFont::Roman, " plain".to_string()), ] ); } #[test] fn emph_inside_bold_is_bold_italic() { let runs = inline_runs( "{\\bfseries bold \\emph{bold italic} bold}", ParagraphFont::Roman, ) .expect("runs"); assert_eq!( runs, vec![ (ParagraphFont::Bold, "bold ".to_string()), (ParagraphFont::BoldItalic, "bold italic".to_string()), (ParagraphFont::Bold, " bold".to_string()), ] ); } #[test] fn emph_inside_italic_returns_upright() { let runs = inline_runs("{\\itshape it \\emph{up} it}", ParagraphFont::Roman).expect("runs"); assert_eq!( runs, vec![ (ParagraphFont::Italic, "it ".to_string()), (ParagraphFont::Roman, "up".to_string()), (ParagraphFont::Italic, " it".to_string()), ] ); } #[test] fn textmd_inside_bold_drops_weight() { let runs = inline_runs("\\textbf{a \\textmd{plain} b}", ParagraphFont::Roman).expect("runs"); assert_eq!( runs, vec![ (ParagraphFont::Bold, "a ".to_string()), (ParagraphFont::Roman, "plain".to_string()), (ParagraphFont::Bold, " b".to_string()), ] ); } #[test] fn wrapper_groups_keep_nested_braces() { let runs = inline_runs("\\textbf{a {b} c}", ParagraphFont::Roman).expect("runs"); assert_eq!(runs, vec![(ParagraphFont::Bold, "a b c".to_string())]); } #[test] fn styled_runs_paint_with_their_face() { let document = Document::new( 550 * 65_536, vec![Unit::paragraph_with_style_and_runs( 1, "plain bold", ParagraphStyle::default(), vec![ (ParagraphFont::Roman, "plain ".to_string()), (ParagraphFont::Bold, "bold".to_string()), ], )], ); let engine = Engine::layout_paged(&document).expect("pages"); let list = engine.pages()[0].display_list_with_goal(document.page_goal); assert!(list.items.iter().any(|item| matches!( item, texrra_tex_core::render::DisplayItem::Text { font: texrra_tex_core::render::FontFace::Bold, .. } ))); } } #[cfg(test)] mod edit_tests { use super::*; #[test] fn paragraph_edits_keep_inline_runs() { let _ = preview_json("plain start").expect("preview"); let json = edit_json("\\textbf{bold} start", 0).expect("edit"); assert!(json.contains(r#"font-weight=\"bold\""#), "{json}"); } }