//! Route-D preview endpoints: a small, independent TeX-style page pipeline. //! //! These endpoints are intentionally separate from the v1 `DocumentModel` //! preview. They demonstrate checkpointed, page-hashed output from the route-D //! core. The v1 preview remains the default and the fallback. use std::cell::RefCell; use std::collections::HashMap; use std::fmt::Write as _; use std::sync::{Mutex, OnceLock}; use texrra_tex_core::cmr10::Cmr10Metrics; use texrra_tex_core::math::{AlignedRow, MathAtom, parse_math, split_math_lines}; use texrra_tex_core::pdf::{PageOrigin, display_lists_to_pdf_with_cm_type1}; use texrra_tex_core::{Document, Engine, ParagraphFont, ParagraphStyle, Unit}; 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. pub fn project_preview_json(project_id: &str, source: &str) -> Result { let (body, geometry) = geometry_and_body(source); let paragraphs = paragraphs(&body)?; 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 { 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 json = render_json(&document, &engine, Some((&changed, recomputed))); sessions.insert( project_id.to_string(), ProjectSession { paragraphs, geometry, engine, }, ); Ok(json) } /// Page geometry pulled out of the source preamble. #[derive(Clone, Debug, Default, PartialEq, Eq)] struct PageGeometry { origin: PageOrigin, paper_width: Option, paper_height: Option, vsize: Option, textheight: Option, par_indent: Option, par_skip: Option, par_skip_stretch: Option, par_skip_shrink: Option, baseline_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, 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)>, /// Captured `tabular` environments: (column spec, halign source). tabular: Vec<(String, String)>, } /// 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. fn strip_page_geometry(source: &str) -> (String, PageGeometry) { let mut geometry = PageGeometry::default(); let mut body = String::new(); let mut tabular: Option<(String, String)> = None; for line in source.lines() { let trimmed = line.trim(); if let Some((_, text)) = tabular.as_mut() { if trimmed == "\\end{tabular}" { let (template, text) = tabular.take().unwrap(); geometry.tabular.push((template, text)); } else { if !text.is_empty() { text.push('\n'); } text.push_str(trimmed); } continue; } if let Some(rest) = trimmed.strip_prefix("\\begin{tabular}") { if let Some((template, _)) = braced(rest.trim_start()) { body.push_str(&format!( "\n\n\\texrratable{{{}}}\n\n", geometry.tabular.len() )); tabular = Some((template.to_string(), String::new())); } 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, "parindent") { geometry.par_indent = Some(value); } else if let Some((width, stretch, shrink)) = glue_assignment(trimmed, "parskip") { geometry.par_skip = Some(width); geometry.par_skip_stretch = Some(stretch); geometry.par_skip_shrink = Some(shrink); } else if let Some(value) = dimension_assignment(trimmed, "baselineskip") { geometry.baseline_skip = Some(value); } else if let Some(value) = dimension_assignment(trimmed, "leftskip") { geometry.left_skip = Some(value); } else if let Some(value) = dimension_assignment(trimmed, "rightskip") { geometry.right_skip = Some(value); } else if let Some(value) = dimension_assignment(trimmed, "emergencystretch") { geometry.emergency_stretch = Some(value); } else if let Some(value) = integer_assignment(trimmed, "tolerance") { geometry.tolerance = Some(value); } else if let Some(value) = integer_assignment(trimmed, "pretolerance") { geometry.pretolerance = Some(value); } else if let Some(value) = signed_integer_assignment(trimmed, "looseness") { geometry.looseness = Some(value.clamp(-9, 9)); } else if let Some(value) = dimension_assignment(trimmed, "hangindent") { geometry.hang_indent = Some(value); } else if let Some(value) = integer_assignment(trimmed, "hangafter") { geometry.hang_after = Some(value); } else if let Some(value) = glue_assignment(trimmed, "spaceskip") { geometry.space_skip = Some(value); } else if let Some(value) = glue_assignment(trimmed, "xspaceskip") { geometry.xspace_skip = Some(value); } else if let Some(value) = dimension_assignment(trimmed, "lineskip") { geometry.lineskip = Some(value); } else if let Some(value) = dimension_assignment(trimmed, "lineskiplimit") { geometry.lineskiplimit = Some(value); } else if let Some((character, value)) = sfcode_assignment(trimmed) { geometry.space_factor_codes.push((character, value)); } else if let Some(value) = integer_assignment(trimmed, "hyphenpenalty") { geometry.hyphen_penalty = Some(value); } else if let Some(value) = integer_assignment(trimmed, "exhyphenpenalty") { geometry.ex_hyphen_penalty = Some(value); } else if let Some(value) = integer_assignment(trimmed, "doublehyphendemerits") { geometry.double_hyphen_demerits = Some(value); } else if let Some(value) = integer_assignment(trimmed, "finalhyphendemerits") { geometry.final_hyphen_demerits = Some(value); } else if let Some(value) = integer_assignment(trimmed, "linepenalty") { geometry.line_penalty = Some(value); } else if let Some(value) = integer_assignment(trimmed, "adjdemerits") { geometry.adj_demerits = Some(value); } else if let Some(value) = dimension_assignment(trimmed, "topskip") { geometry.top_skip = Some(value); } else if let Some(value) = dimension_assignment(trimmed, "maxdepth") { geometry.max_depth = Some(value); } else if let Some(value) = dimension_assignment(trimmed, "splittopskip") { geometry.split_top_skip = Some(value); } else if let Some(value) = dimension_assignment(trimmed, "splitmaxdepth") { geometry.split_max_depth = Some(value); } else if let Some(value) = parfillskip_assignment(trimmed) { geometry.par_fillskip = Some(value); } else if let Some(value) = parshape_assignment(trimmed) { geometry.par_shape = value; } else if let Some(value) = braced_argument(trimmed, "\\hyphenation") { geometry .hyphenation_exceptions .extend(value.split_whitespace().map(str::to_string)); } else if trimmed == "\\frenchspacing" { geometry.french_spacing = Some(true); } else if trimmed == "\\nonfrenchspacing" { geometry.french_spacing = Some(false); } else { body.push_str(line); body.push('\n'); } } if let Some((template, text)) = tabular { geometry.tabular.push((template, text)); } (body, geometry) } fn braced(text: &str) -> Option<(&str, &str)> { let mut depth = 0_i32; for (index, character) in text.char_indices() { match character { '{' => depth += 1, '}' => { depth -= 1; if depth == 0 { return Some((&text[1..index], &text[index + 1..])); } } _ => {} } } None } fn engine_template(spec: &str) -> String { let mut out = String::new(); let mut characters = spec.chars().peekable(); while let Some(character) = characters.next() { match character { 'l' | 'c' | 'r' => out.push(character), 'p' | 'm' | 'b' => { out.push('p'); if characters.peek() == Some(&'{') { let mut depth = 0_i32; for inner in characters.by_ref() { out.push(inner); match inner { '{' => depth += 1, '}' => { depth -= 1; if depth == 0 { break; } } _ => {} } } } } '|' | ' ' | '\t' => {} '@' | '!' | '>' | '<' | '*' => { if characters.peek() == Some(&'{') { let mut depth = 0_i32; for inner in characters.by_ref() { match inner { '{' => depth += 1, '}' => { depth -= 1; if depth == 0 { break; } } _ => {} } } } } _ => {} } } if out.is_empty() { "l".to_string() } else { out } } fn table_reference(text: &str) -> Option { text.trim() .strip_prefix("\\texrratable{")? .strip_suffix('}')? .parse() .ok() } /// Strip geometry assignments from the whole source (preamble included) and /// return the LaTeX body with them removed. fn geometry_and_body(source: &str) -> (String, PageGeometry) { let (stripped, geometry) = strip_page_geometry(source); // Removed assignments can leave blank lines at the edges; they are not // paragraphs of their own. let body = latex_body(&stripped).trim_matches('\n').to_string(); (body, geometry) } fn apply_geometry(document: &mut Document, geometry: &PageGeometry) { document.h_offset = geometry.origin.h_offset; document.v_offset = geometry.origin.v_offset; if let Some(width) = geometry.paper_width { document.paper_width = width; } if let Some(height) = geometry.paper_height { document.paper_height = height; } if let Some(height) = geometry.textheight.or(geometry.vsize) { document.page_goal = height; } if let Some(skip) = geometry.par_skip { document.par_skip = skip; } if let Some(stretch) = geometry.par_skip_stretch { document.par_skip_stretch = stretch; } if let Some(shrink) = geometry.par_skip_shrink { document.par_skip_shrink = shrink; } if let Some(skip) = geometry.top_skip { document.top_skip = skip; } if let Some(depth) = geometry.max_depth { document.max_depth = depth; } if let Some(skip) = geometry.split_top_skip { document.split_top_skip = skip; } if let Some(depth) = geometry.split_max_depth { document.split_max_depth = depth; } } /// Read a `\parfillskip` glue assignment, preserving the `1fil` order. fn parfillskip_assignment(line: &str) -> Option<(i64, i64, bool)> { let rest = line.strip_prefix("\\parfillskip")?.trim_start(); let rest = rest.strip_prefix('=')?.trim(); let (width, rest) = split_glue_part(rest)?; let mut stretch = 0_i64; let mut fil = false; let rest = rest.trim_start(); let rest = if let Some(rest) = rest.strip_prefix("plus") { let rest = rest.trim_start(); if let Some(rest) = rest.strip_prefix("1fil") { fil = true; rest } else { let (value, rest) = split_glue_part(rest)?; stretch = value; rest } } else { rest }; let _ = rest; Some((width, stretch, fil)) } /// Read a `\parshape` specification such as `\parshape=2 0pt 100pt 20pt 80pt`. fn parshape_assignment(line: &str) -> Option> { let rest = line.strip_prefix("\\parshape")?.trim_start(); let rest = rest.strip_prefix('=').unwrap_or(rest).trim(); let mut parts = rest.split_whitespace(); let count: usize = parts.next()?.parse().ok()?; let mut shape = Vec::with_capacity(count); for _ in 0..count { let indent = parse_dimension(parts.next()?)?; let width = parse_dimension(parts.next()?)?; shape.push((indent, width)); } Some(shape) } /// Read a braced argument such as `\hyphenation{hy-phen-a-tion}`. fn braced_argument<'a>(line: &'a str, command: &str) -> Option<&'a str> { let rest = line.strip_prefix(command)?.trim_start(); let rest = rest.strip_prefix('{')?; let mut depth = 1_usize; for (index, character) in rest.char_indices() { match character { '{' => depth += 1, '}' => { depth -= 1; if depth == 0 { return Some(&rest[..index]); } } _ => {} } } None } /// Read a `\sfcode` assignment such as ``\sfcode`x=2000`` or `\sfcode46=1000`. fn sfcode_assignment(line: &str) -> Option<(char, i64)> { let rest = line.strip_prefix("\\sfcode")?; let rest = rest.trim_start(); let rest = rest.strip_prefix('=').unwrap_or(rest).trim_start(); let (character, rest) = if let Some(rest) = rest.strip_prefix('`') { let rest = rest.strip_prefix('\\').unwrap_or(rest); let mut characters = rest.chars(); let character = characters.next()?; (character, characters.as_str()) } else { let end = rest .find(|character: char| !character.is_ascii_digit()) .unwrap_or(rest.len()); let code: u32 = rest[..end].parse().ok()?; (char::from_u32(code)?, &rest[end..]) }; let rest = rest.trim_start().strip_prefix('=')?; Some((character, rest.trim().parse().ok()?)) } /// Read a plain integer assignment such as `\tolerance=1000`. fn glue_assignment(line: &str, name: &str) -> Option<(i64, i64, i64)> { let rest = line.strip_prefix('\\')?; let rest = rest.strip_prefix(name)?; let rest = rest.trim_start().strip_prefix('=')?; let rest = rest.trim(); let (width, rest) = split_glue_part(rest)?; let (stretch, rest) = match rest.trim_start().strip_prefix("plus") { Some(rest) => split_glue_part(rest.trim_start())?, None => (0, rest), }; let shrink = match rest.trim_start().strip_prefix("minus") { Some(rest) => split_glue_part(rest.trim_start())?.0, None => 0, }; Some((width, stretch, shrink)) } fn split_glue_part(text: &str) -> Option<(i64, &str)> { let end = text .find(|character: char| { !(character.is_ascii_digit() || character == '.' || character == '-') }) .unwrap_or(text.len()); let number: f64 = text[..end].parse().ok()?; let unit_text = &text[end..]; let (unit, rest) = ["pt", "bp", "in", "cm", "mm", "pc"] .iter() .find_map(|unit| unit_text.strip_prefix(unit).map(|rest| (*unit, rest)))?; let factor = match unit { "pt" => 65_536.0, "bp" => 65_782.0, "in" => 4_736_286.0, "cm" => 1_864_680.0, "mm" => 186_468.0, _ => 786_432.0, }; Some(((number * factor).round() as i64, rest)) } fn integer_assignment(line: &str, name: &str) -> Option { 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()) } 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, _ => return None, }; Some((number * factor * 65_536.0).round() as i64) } /// Lay a document out with the TeX page builder, falling back to the /// scrolling builder for material the paged builder cannot express. fn layout_document(document: &Document) -> Engine { Engine::layout_paged(document).unwrap_or_else(|| Engine::layout(document)) } /// Build a JSON preview from blank-line-separated plain-text paragraphs. pub fn preview_json(source: &str) -> Result { let (body, geometry) = geometry_and_body(source); let paragraphs = paragraphs(&body)?; let mut document = build_document(¶graphs, &geometry); apply_geometry(&mut document, &geometry); let engine = layout_document(&document); let json = render_json(&document, &engine, None); // Keep the layout so a following `/edit` request can diff against it and // reuse page checkpoints instead of starting from a no-op document. ROUTE_D_SESSION.with(|slot| { *slot.borrow_mut() = Some((document, engine)); }); Ok(json) } /// Render the same checkpointed document as a route-D PDF. pub fn pdf_bytes(source: &str) -> Result, String> { let (body, geometry) = geometry_and_body(source); let paragraphs = paragraphs(&body)?; let mut document = build_document(¶graphs, &geometry); apply_geometry(&mut document, &geometry); let engine = layout_document(&document); let pages: Vec<_> = engine .pages() .iter() .map(|page| { let mut list = page.display_list_with_layout(document.page_goal, document.text_float_sep); list.width = list.width.max(document.paper_width); list.height = list.height.max(document.paper_height); list }) .collect(); Ok(display_lists_to_pdf_with_cm_type1( &pages, document.paper_width, document.paper_height, geometry.origin, )) } /// Apply one paragraph edit to the last route-D document and report page /// checkpoints that were reused versus rebuilt. pub fn edit_json(source: &str, unit: usize) -> Result { let (body, geometry) = geometry_and_body(source); let paragraphs = paragraphs(&body)?; 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 json = render_json(&next, &engine, Some((&changed, recomputed))); *slot = Some((next, engine)); Ok(json) }) } #[derive(Clone, PartialEq, Eq)] struct SourceParagraph { text: String, /// TeX `\newpage` before this paragraph. page_break: bool, centered: bool, right_aligned: bool, font: ParagraphFont, line_height: i64, math: bool, left_skip: i64, space_before: i64, space_stretch: i64, space_shrink: i64, /// Number of the equation environment this block came from. equation_number: Option, 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, font_size: 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 => other .strip_prefix("\\vskip") .and_then(|rest| skip_glue(rest.trim_start())), } } /// 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)) } fn paragraphs(source: &str) -> Result, String> { let paragraphs: Vec<&str> = source .split("\n\n") .map(str::trim) .filter(|paragraph| !paragraph.is_empty()) .collect(); if paragraphs.is_empty() { return Err("route-D preview needs at least one paragraph".to_string()); } let mut result = Vec::new(); let mut pending = (0_i64, 0_i64, 0_i64); let mut pending_break = false; for chunk in paragraphs { if let Some(index) = table_reference(chunk) { result.push(SourceParagraph { text: format!("\\texrratable{{{index}}}"), font: ParagraphFont::Roman, line_height: 12, math: false, left_skip: 0, centered: false, right_aligned: false, space_before: pending.0, space_stretch: pending.1, space_shrink: pending.2, page_break: pending_break, equation_number: None, equation_tag: None, equation_rows: Vec::new(), align_centered: false, 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); if let Some(first) = blocks.first_mut() { first.space_before += pending.0; first.space_stretch += pending.1; first.space_shrink += pending.2; first.page_break = pending_break; pending_break = false; pending = (0, 0, 0); } result.extend(blocks); } resolve_equation_numbers(&mut result); Ok(result) } fn command_body<'a>(text: &'a str, command: &str) -> Option<&'a str> { let rest = text.strip_prefix(command)?.trim_start(); let rest = rest.strip_prefix('{')?.strip_suffix('}')?; Some(rest.trim()) } /// Assign equation numbers in source order and substitute label references. fn resolve_equation_numbers(blocks: &mut [SourceParagraph]) { let mut number = 0; let mut labels: Vec<(String, String)> = Vec::new(); for block in blocks.iter_mut() { if !block.math { continue; } if !block.equation_rows.is_empty() { for row in block.equation_rows.iter_mut() { if let Some(tag) = take_braced_argument(&mut row.text, "\\tag") { row.tag = Some(tag); row.number = None; } if row.text.contains("\\notag") || row.text.contains("\\nonumber") { row.number = None; } row.text = row.text.replace("\\notag", "").replace("\\nonumber", ""); let mut value = row.tag.clone(); if row.number.is_some() { number += 1; row.number = Some(number); value = Some(number.to_string()); } if let Some(value) = value { for label in take_labels(&mut row.text) { labels.push((label, value.clone())); } } } continue; } if let Some(tag) = take_braced_argument(&mut block.text, "\\tag") { block.equation_tag = Some(tag); block.equation_number = None; } if block.text.contains("\\notag") || block.text.contains("\\nonumber") { block.equation_number = None; } block.text = block.text.replace("\\notag", "").replace("\\nonumber", ""); if block.equation_number.is_none() || block.equation_tag.is_some() { continue; } number += 1; block.equation_number = Some(number); for label in take_labels(&mut block.text) { labels.push((label, number.to_string())); } } for block in blocks.iter_mut() { for (label, value) in labels.iter() { let eqref = format!("\\eqref{{{label}}}"); let reference = format!("\\ref{{{label}}}"); block.text = block .text .replace(&eqref, &format!("({value})")) .replace(&reference, value); for row in block.equation_rows.iter_mut() { row.text = row .text .replace(&eqref, &format!("({value})")) .replace(&reference, value); } } } } fn take_labels(text: &mut String) -> Vec { 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 } fn parse_blocks_raw(raw: &str) -> Vec { for (environment, numbered) in [("itemize", false), ("enumerate", 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 mut number = 0; let items: Vec = body .split("\\item") .map(str::trim) .filter(|item| !item.is_empty()) .map(|item| { number += 1; let prefix = if numbered { format!("{number}. ") } else { "• ".to_string() }; SourceParagraph { text: format!("{prefix}{item}"), font: ParagraphFont::Roman, line_height: 12, math: false, left_skip: 12, centered: false, right_aligned: false, space_before: 0, space_stretch: 0, space_shrink: 0, page_break: false, equation_number: None, equation_tag: None, equation_rows: Vec::new(), align_centered: false, font_size: None, } }) .collect(); if !items.is_empty() { return items; } } if let Some(body) = raw .strip_prefix("\\begin{quote}") .and_then(|text| text.strip_suffix("\\end{quote}")) { let text = body.trim(); if !text.is_empty() { return vec![SourceParagraph { text: text.to_string(), font: ParagraphFont::Roman, line_height: 12, math: false, left_skip: 12, centered: false, right_aligned: false, space_before: 0, space_stretch: 0, space_shrink: 0, page_break: false, equation_number: None, equation_tag: None, equation_rows: Vec::new(), align_centered: false, font_size: None, }]; } } if let Some(body) = raw .strip_prefix("\\begin{description}") .and_then(|text| text.strip_suffix("\\end{description}")) { let items: Vec = body .split("\\item") .map(str::trim) .filter(|item| !item.is_empty()) .map(|item| { let (term, rest) = item .strip_prefix('[') .and_then(|text| text.split_once(']')) .map(|(term, rest)| (term.trim(), rest.trim())) .unwrap_or(("", item)); let text = if term.is_empty() { rest.to_string() } else { format!("{term} — {rest}") }; SourceParagraph { text, font: ParagraphFont::Roman, line_height: 12, math: false, left_skip: 12, centered: false, right_aligned: false, space_before: 0, space_stretch: 0, space_shrink: 0, page_break: false, equation_number: None, equation_tag: None, equation_rows: Vec::new(), align_centered: false, font_size: None, } }) .collect(); if !items.is_empty() { return items; } } 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(raw: &str, base: ParagraphFont) -> Option<(ParagraphFont, String)> { nfss_font_with_size(raw, base).map(|(font, _, body)| (font, body)) } fn nfss_font_with_size( raw: &str, base: ParagraphFont, ) -> Option<(ParagraphFont, Option, 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. fn inline_runs(text: &str, base: ParagraphFont) -> Option> { let mut runs = Vec::new(); let mut found = false; parse_runs(text, base, &mut runs, &mut found); if !found { return None; } Some(runs) } fn push_run(runs: &mut Vec<(ParagraphFont, String)>, font: ParagraphFont, text: &str) { if text.is_empty() { return; } if let Some((last_font, last_text)) = runs.last_mut() && *last_font == font { last_text.push_str(text); return; } runs.push((font, 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 parse_runs( text: &str, font: ParagraphFont, runs: &mut Vec<(ParagraphFont, String)>, found: &mut bool, ) { let mut index = 0; while index < text.len() { let rest = &text[index..]; if let Some((declared, body)) = nfss_font(rest, font) { *found = true; parse_runs(&body, declared, runs, found); return; } if let Some((inner, length)) = braced_group(rest) { let (inner_font, inner_text) = match nfss_font(inner, font) { Some((declared, body)) => (declared, body), None => (font, inner.to_string()), }; if nfss_font(inner, font).is_some() { *found = true; } parse_runs(&inner_text, inner_font, runs, found); index += length; continue; } if let Some((wrapper_font, inner, length)) = inline_wrapper(rest, font) { *found = true; parse_runs(inner, wrapper_font, runs, found); index += length; continue; } if rest.starts_with('\\') { let step = rest .char_indices() .skip(1) .find(|(_, character)| !character.is_ascii_alphabetic()) .map(|(offset, _)| offset.max(1)) .unwrap_or(rest.len()); push_run(runs, font, &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, &rest[..step]); index += step; } } fn parse_paragraph(raw: &str) -> SourceParagraph { for (environment, starred, centered) in [ ("align", false, false), ("align*", true, false), ("gather", false, true), ("gather*", true, true), ] { let begin = format!("\\begin{{{environment}}}"); let finish = format!("\\end{{{environment}}}"); if let Some(inner) = raw .strip_prefix(&begin) .and_then(|text| text.strip_suffix(&finish)) { let rows: Vec = inner .split("\\\\") .map(str::trim) .filter(|row| !row.is_empty()) .map(|row| EquationRow { text: row.to_string(), number: if starred { None } else { Some(0) }, tag: None, }) .collect(); return SourceParagraph { text: inner.trim().to_string(), font: ParagraphFont::Roman, line_height: 12, math: true, left_skip: 0, centered: false, right_aligned: false, space_before: 0, space_stretch: 0, space_shrink: 0, page_break: false, equation_number: None, equation_tag: None, equation_rows: rows, align_centered: centered, font_size: None, }; } } if let Some((font, font_size, body)) = nfss_font_with_size(raw, ParagraphFont::Roman) { return SourceParagraph { text: body, font, font_size, line_height: 12, math: false, left_skip: 0, centered: false, right_aligned: false, space_before: 0, space_stretch: 0, space_shrink: 0, page_break: false, equation_number: None, equation_tag: None, equation_rows: Vec::new(), align_centered: false, }; } if let Some(inner) = raw .strip_prefix("\\begin{equation}") .and_then(|text| text.strip_suffix("\\end{equation}")) { return SourceParagraph { text: inner.trim().to_string(), font: ParagraphFont::Roman, line_height: 12, math: true, left_skip: 0, centered: false, right_aligned: false, space_before: 0, space_stretch: 0, space_shrink: 0, page_break: false, equation_number: Some(0), equation_tag: None, equation_rows: Vec::new(), align_centered: false, font_size: None, }; } if let Some(inner) = raw .strip_prefix("\\begin{equation*}") .and_then(|text| text.strip_suffix("\\end{equation*}")) { return SourceParagraph { text: inner.trim().to_string(), font: ParagraphFont::Roman, line_height: 12, math: true, left_skip: 0, centered: false, right_aligned: false, space_before: 0, space_stretch: 0, space_shrink: 0, page_break: false, equation_number: None, equation_tag: None, equation_rows: Vec::new(), align_centered: false, font_size: None, }; } if let Some(math) = raw .strip_prefix("$$") .and_then(|text| text.strip_suffix("$$")) .or_else(|| { raw.strip_prefix("\\[") .and_then(|text| text.strip_suffix("\\]")) }) { return SourceParagraph { text: math.trim().to_string(), font: ParagraphFont::Roman, line_height: 12, math: true, left_skip: 0, centered: false, right_aligned: false, space_before: 0, space_stretch: 0, space_shrink: 0, page_break: false, equation_number: None, equation_tag: None, equation_rows: Vec::new(), align_centered: false, font_size: None, }; } let candidates = [ ("\\section", ParagraphFont::Bold, 18), ("\\textbf", ParagraphFont::Bold, 12), ("\\emph", ParagraphFont::Italic, 12), ("\\texttt", ParagraphFont::Mono, 12), ("\\textsf", ParagraphFont::Sans, 12), ]; for (command, font, line_height) in candidates { if let Some(text) = command_body(raw, command) { return SourceParagraph { text: text.to_string(), font, line_height, math: false, left_skip: 0, centered: false, right_aligned: false, space_before: 0, space_stretch: 0, space_shrink: 0, page_break: false, equation_number: None, equation_tag: None, equation_rows: Vec::new(), align_centered: false, font_size: None, }; } } SourceParagraph { text: raw.to_string(), font: ParagraphFont::Roman, line_height: 12, math: false, left_skip: 0, centered: false, right_aligned: false, space_before: 0, space_stretch: 0, space_shrink: 0, page_break: false, equation_number: None, equation_tag: None, equation_rows: Vec::new(), align_centered: false, 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) } fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Document { let units = paragraphs .iter() .enumerate() .map(|(index, paragraph)| { if let Some(table) = table_reference(¶graph.text) { if let Some((template, source)) = geometry.tabular.get(table) { let mut unit = Unit::halign_from_source_with_template_and_tabskips( index as u64, &engine_template(template), source, 6 * SCALE, Vec::new(), ); unit.space_before = paragraph.space_before; unit.space_stretch = paragraph.space_stretch; unit.space_shrink = paragraph.space_shrink; return unit; } } if paragraph.math { let font = Cmr10Metrics::Math; let atom = if paragraph.equation_rows.is_empty() { parse_math(¶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, 480 * SCALE); 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 style = ParagraphStyle { line_width: 480 * SCALE, left_skip: paragraph.left_skip * SCALE + geometry.left_skip.unwrap_or(0), centered: paragraph.centered, right_aligned: paragraph.right_aligned, looseness: geometry.looseness.unwrap_or(0), ragged_right: false, right_skip: geometry.right_skip.unwrap_or(0), hang_indent: geometry.hang_indent.unwrap_or(0), hang_after: geometry.hang_after.unwrap_or(1) as i32, par_shape: geometry.par_shape.clone(), par_fillskip: geometry .par_fillskip .map(|(width, _, _)| width) .unwrap_or(0), par_fillskip_stretch: geometry .par_fillskip .map(|(_, stretch, _)| stretch) .unwrap_or(0), par_fillskip_fil: geometry.par_fillskip.map(|(_, _, fil)| fil).unwrap_or(true), frenchspacing: geometry.french_spacing.unwrap_or(false), space_factor_codes: geometry.space_factor_codes.clone(), baselineskip: geometry.baseline_skip.unwrap_or(12 * 65536), lineskip: geometry.lineskip.unwrap_or(65536), lineskiplimit: geometry.lineskiplimit.unwrap_or(0), par_indent: geometry.par_indent.unwrap_or(0), emergencystretch: geometry.emergency_stretch.unwrap_or(0), pretolerance: geometry.pretolerance.unwrap_or(100), tolerance: geometry.tolerance.unwrap_or(200), hyphen_penalty: geometry.hyphen_penalty.unwrap_or(50), ex_hyphen_penalty: geometry.ex_hyphen_penalty.unwrap_or(50), double_hyphen_demerits: geometry.double_hyphen_demerits.unwrap_or(10_000), final_hyphen_demerits: geometry.final_hyphen_demerits.unwrap_or(5_000), line_penalty: geometry.line_penalty.unwrap_or(10), adj_demerits: geometry.adj_demerits.unwrap_or(10_000), hyphenation_exceptions: geometry.hyphenation_exceptions.clone(), line_height: if paragraph.line_height == 12 { geometry.baseline_skip.unwrap_or(12 * 65536) } else { paragraph.line_height * SCALE }, font_size: paragraph.font_size.unwrap_or(655_360), 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 mut unit = match inline_runs(¶graph.text, paragraph.font) { Some(runs) => Unit::paragraph_with_style_and_runs( index as u64, paragraph.text.clone(), style, runs, ), None => Unit::paragraph_with_style_and_face( index as u64, paragraph.text.clone(), style, paragraph.font, ), }; unit.space_before = paragraph.space_before; unit.space_stretch = paragraph.space_stretch; unit.space_shrink = paragraph.space_shrink; unit }) .collect(); let mut document = Document::new(700 * SCALE, units); // LaTeX sets \maxdepth=.5\topskip; sources may override it later. document.max_depth = 5 * SCALE; document.text_width = 480 * SCALE; document.page_breaks = paragraphs .iter() .enumerate() .filter(|(_, paragraph)| paragraph.page_break) .map(|(index, _)| index) .collect(); document } fn render_json(document: &Document, engine: &Engine, edit: Option<(&[usize], usize)>) -> String { let mut json = String::new(); let page_width_mm = document.paper_width as f64 / SCALE as f64 * 25.4 / 72.0; let page_height_mm = document.paper_height as f64 / SCALE as f64 * 25.4 / 72.0; let page_height_pt = document.paper_height as f64 / SCALE as f64; let _ = write!( json, "{{\"status\":\"ok\",\"pageWidthMm\":{page_width_mm:.2},\"pageHeightMm\":{page_height_mm:.2},\"pages\":[" ); for (index, page) in engine.pages().iter().enumerate() { let mut list = page.display_list_with_layout(document.page_goal, document.text_float_sep); list.width = list.width.max(document.paper_width); list.height = list.height.max(document.paper_height); list.place(document.h_offset, document.v_offset); if index > 0 { json.push(','); } let _ = write!( json, "{{\"index\":{index},\"hash\":\"{:016x}\",\"svg\":\"{}\"}}", page.hash, escape_json(&list.to_svg()) ); } let _ = write!(json, "],\"pageCount\":{}", engine.pages().len()); if let Some((changed, recomputed)) = edit { let _ = write!( json, ",\"changedPages\":{:?},\"recomputedPages\":{recomputed}", changed ); } let _ = write!(json, ",\"pageHeightPt\":{page_height_pt:.0}}}"); json } fn escape_json(value: &str) -> String { let mut escaped = String::with_capacity(value.len()); for character in value.chars() { match character { '"' => escaped.push_str("\\\""), '\\' => escaped.push_str("\\\\"), '\n' => escaped.push_str("\\n"), '\r' => escaped.push_str("\\r"), '\t' => escaped.push_str("\\t"), character if character < '\u{20}' => { let _ = write!(escaped, "\\u{:04x}", character as u32); } character => escaped.push(character), } } escaped } #[cfg(test)] mod tests { use super::*; #[test] fn display_math_is_split_to_the_measure() { let mut formula = String::from("$$"); for index in 0..80 { if index > 0 { formula.push_str(" + "); } formula.push('x'); } formula.push_str(" = z$$"); let (body, geometry) = geometry_and_body(&formula); let paragraphs = paragraphs(&body).unwrap(); let document = build_document(¶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 engine_template_keeps_paragraph_columns() { assert_eq!(engine_template("{|l|c|p{3cm}|}"), "lcp{3cm}"); assert_eq!(engine_template("|p{2cm}|r|"), "p{2cm}r"); assert_eq!(engine_template(""), "l"); } fn multi_page_source() -> String { let mut source = String::from("\\documentclass{article}\n\\begin{document}\n\n"); for index in 0..36 { source.push_str(&format!("Paragraph {index:02} ")); for _ in 0..4 { source.push_str( "lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor. ", ); } source.push_str("\n\n"); } source.push_str("\\end{document}\n"); source } #[test] fn multi_paragraph_edits_reuse_earlier_pages() { let source = multi_page_source(); let first = project_preview_json("route-d-multi-edit", &source).expect("first preview"); let first: serde_json::Value = serde_json::from_str(&first).expect("first JSON"); let page_count = first["pageCount"].as_u64().expect("page count"); assert!( page_count >= 2, "expected a multi-page preview, got {page_count}" ); let edited = source .replace("Paragraph 30 ", "Paragraph 30 changed ") .replace("Paragraph 33 ", "Paragraph 33 changed "); let second = project_preview_json("route-d-multi-edit", &edited).expect("edited preview"); let second: serde_json::Value = serde_json::from_str(&second).expect("edited JSON"); assert!( second["changedPages"] .as_array() .is_some_and(|pages| !pages.is_empty()) ); let recomputed = second["recomputedPages"].as_u64().expect("recomputed"); assert!(recomputed < page_count, "changed pages should be a subset"); } #[test] fn structural_edit_keeps_pages_before_the_inserted_paragraph() { let source = multi_page_source(); let first = project_preview_json("route-d-structural-edit", &source).expect("first preview"); let first: serde_json::Value = serde_json::from_str(&first).expect("first JSON"); let first_hash = first["pages"][0]["hash"].as_str().expect("first hash"); let inserted = source.replacen( "Paragraph 21 ", "Paragraph inserted before twenty-one with enough words to make a line.\n\nParagraph 21 ", 1, ); let second = project_preview_json("route-d-structural-edit", &inserted).expect("inserted preview"); let second: serde_json::Value = serde_json::from_str(&second).expect("second JSON"); assert_eq!( second["pages"][0]["hash"].as_str().expect("second hash"), first_hash ); let page_count = second["pageCount"].as_u64().expect("page count"); assert!( second["changedPages"] .as_array() .is_some_and(|pages| !pages.is_empty()) ); assert!( second["recomputedPages"].as_u64().expect("recomputed") < page_count, "the unchanged prefix should not be recomputed" ); } } #[cfg(test)] mod source_tests { use super::*; #[test] fn reads_hang_registers_from_the_preamble() { let (body, geometry) = geometry_and_body( "\\hangindent=20pt\n\\hangafter=1\n\\tolerance=1000\n\\pretolerance=50\n\\looseness=-1\n\\spaceskip=6pt plus 1pt minus 0.5pt\n\\frenchspacing\n\nword word", ); assert_eq!(geometry.hang_indent, Some(20 * 65_536)); assert_eq!(geometry.hang_after, Some(1)); let pt = 65_536; assert_eq!(geometry.tolerance, Some(1000)); assert_eq!(geometry.pretolerance, Some(50)); assert_eq!(geometry.looseness, Some(-1)); assert_eq!(geometry.space_skip, Some((6 * pt, pt, pt / 2))); assert_eq!(geometry.french_spacing, Some(true)); let paragraphs = paragraphs(&body).expect("paragraphs"); assert_eq!(paragraphs.len(), 1, "{body:?}"); let document = build_document(¶graphs, &geometry); let style = document.units[0].paragraph_style.clone().expect("style"); assert_eq!(style.hang_indent, 20 * 65_536); assert_eq!(style.hang_after, 1); assert_eq!(style.tolerance, 1000); assert_eq!(style.pretolerance, 50); assert_eq!(style.looseness, -1); assert_eq!(style.space_skip, Some((6 * pt, pt, pt / 2))); assert!(style.frenchspacing); } #[test] fn geometry_reads_hyphenation_exceptions() { let source = "\\documentclass{article}\n\\hyphenation{zzz-zzz alpha-beta}\n\\begin{document}\n\nzzzzzz\n\n\\end{document}\n"; let (body, geometry) = geometry_and_body(source); assert_eq!( geometry.hyphenation_exceptions, vec!["zzz-zzz".to_string(), "alpha-beta".to_string()] ); assert!(!body.contains("hyphenation")); let paragraphs = paragraphs(&body).expect("paragraphs"); let document = build_document(¶graphs, &geometry); let style = document.units[0] .paragraph_style .clone() .expect("paragraph style"); assert_eq!( style.hyphenation_exceptions, geometry.hyphenation_exceptions ); } #[test] fn geometry_reads_parshape() { let source = "\\documentclass{article}\n\\parshape=2 0pt 100pt 20pt 80pt\n\\begin{document}\n\nSome words here.\n\n\\end{document}\n"; let (body, geometry) = geometry_and_body(source); assert_eq!( geometry.par_shape, vec![(0, 100 * SCALE), (20 * SCALE, 80 * SCALE)] ); assert!(!body.contains("parshape")); let paragraphs = paragraphs(&body).expect("paragraphs"); let document = build_document(¶graphs, &geometry); let style = document.units[0] .paragraph_style .clone() .expect("paragraph style"); assert_eq!(style.par_shape, geometry.par_shape); } #[test] fn geometry_reads_parfillskip_and_lineskip() { let source = "\\documentclass{article}\n\\parfillskip=0pt plus 1fil\n\\lineskip=2pt\n\\lineskiplimit=3pt\n\\begin{document}\n\nSome words here.\n\n\\end{document}\n"; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry.par_fillskip, Some((0, 0, true))); assert_eq!(geometry.lineskip, Some(2 * SCALE)); assert_eq!(geometry.lineskiplimit, Some(3 * SCALE)); assert!(!body.contains("parfillskip")); let paragraphs = paragraphs(&body).expect("paragraphs"); let document = build_document(¶graphs, &geometry); let style = document.units[0] .paragraph_style .clone() .expect("paragraph style"); assert_eq!(style.par_fillskip, 0); assert!(style.par_fillskip_fil); assert_eq!(style.lineskip, 2 * SCALE); assert_eq!(style.lineskiplimit, 3 * SCALE); } #[test] fn geometry_reads_stretchy_parskip() { let source = "\\documentclass{article}\n\\parskip=2pt plus 5pt minus 1pt\n\\begin{document}\n\nSome words here.\n\n\\end{document}\n"; let (body, geometry) = geometry_and_body(source); assert!(!body.contains("parskip")); assert_eq!(geometry.par_skip, Some(2 * 65_536)); assert_eq!(geometry.par_skip_stretch, Some(5 * 65_536)); assert_eq!(geometry.par_skip_shrink, Some(65_536)); } #[test] fn geometry_reads_page_skip_registers() { let source = "\\documentclass{article}\n\\topskip=10pt\n\\maxdepth=5pt\n\\splittopskip=3pt\n\\begin{document}\n\nSome words here.\n\n\\end{document}\n"; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry.top_skip, Some(10 * SCALE)); assert_eq!(geometry.max_depth, Some(5 * SCALE)); assert_eq!(geometry.split_top_skip, Some(3 * SCALE)); assert!(!body.contains("topskip")); let paragraphs = paragraphs(&body).expect("paragraphs"); let mut document = build_document(¶graphs, &geometry); apply_geometry(&mut document, &geometry); assert_eq!(document.top_skip, 10 * SCALE); assert_eq!(document.max_depth, 5 * SCALE); assert_eq!(document.split_top_skip, 3 * SCALE); } #[test] fn geometry_reads_demerit_registers() { let source = "\\documentclass{article}\n\\hyphenpenalty=77\n\\exhyphenpenalty=88\n\\doublehyphendemerits=1234\n\\finalhyphendemerits=4321\n\\linepenalty=20\n\\adjdemerits=999\n\\begin{document}\n\nSome words here.\n\n\\end{document}\n"; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry.hyphen_penalty, Some(77)); assert_eq!(geometry.ex_hyphen_penalty, Some(88)); assert_eq!(geometry.double_hyphen_demerits, Some(1234)); assert_eq!(geometry.final_hyphen_demerits, Some(4321)); assert_eq!(geometry.line_penalty, Some(20)); assert_eq!(geometry.adj_demerits, Some(999)); assert!(!body.contains("hyphenpenalty")); let paragraphs = paragraphs(&body).expect("paragraphs"); let document = build_document(¶graphs, &geometry); let style = document.units[0] .paragraph_style .clone() .expect("paragraph style"); assert_eq!(style.hyphen_penalty, 77); assert_eq!(style.ex_hyphen_penalty, 88); assert_eq!(style.double_hyphen_demerits, 1234); assert_eq!(style.final_hyphen_demerits, 4321); assert_eq!(style.line_penalty, 20); assert_eq!(style.adj_demerits, 999); } #[test] fn geometry_reads_sfcode_assignments() { let source = "\\documentclass{article}\n\\sfcode61=1000\n\\sfcode`x=2000\n\\begin{document}\n\nSome words here.\n\n\\end{document}\n"; let (body, geometry) = geometry_and_body(source); assert_eq!(geometry.space_factor_codes, vec![('=', 1000), ('x', 2000)]); assert!(!body.contains("sfcode")); let paragraphs = paragraphs(&body).expect("paragraphs"); let document = build_document(¶graphs, &geometry); let style = document.units[0] .paragraph_style .clone() .expect("paragraph style"); assert_eq!(style.space_factor_codes, geometry.space_factor_codes); } #[test] fn preview_pages_honour_page_offsets() { let plain = preview_json("Hello route D").expect("plain preview"); let shifted = preview_json("\\hoffset=10pt\n\\voffset=5pt\nHello route D").expect("shifted"); fn first_text_position(json: &str) -> (f64, f64) { let value: serde_json::Value = serde_json::from_str(json).expect("JSON"); let svg = value["pages"][0]["svg"].as_str().expect("svg"); let start = svg.find("= 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 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}"); } }