//! 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::parse_math; use texrra_tex_core::pdf::{PageOrigin, display_lists_to_pdf_with_paper}; 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 = Engine::layout(&document); let changed: Vec = (0..engine.pages().len()).collect(); let recomputed = changed.len(); (engine, changed, recomputed) } } else { let engine = Engine::layout(&document); let changed: Vec = (0..engine.pages().len()).collect(); let recomputed = changed.len(); (engine, changed, recomputed) } } _ => { let engine = Engine::layout(&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, 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, } /// 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(); for line in source.lines() { let trimmed = line.trim(); 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(value) = dimension_assignment(trimmed, "parskip") { geometry.par_skip = Some(value); } 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(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) = 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'); } } (body, geometry) } /// 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(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; } } /// 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 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) } /// 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 = Engine::layout(&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 = Engine::layout(&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_paper( &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 = Engine::layout(&next); (next.clone(), engine) } }; engine.edit(&next, unit as u64, paragraphs[unit].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, centered: bool, right_aligned: bool, font: ParagraphFont, line_height: i64, math: bool, left_skip: i64, } 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()); } Ok(paragraphs.into_iter().flat_map(parse_blocks).collect()) } 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()) } fn parse_blocks(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, } }) .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, }]; } } 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, } }) .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 parse_paragraph(raw: &str) -> SourceParagraph { 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, }; } let candidates = [ ("\\section", ParagraphFont::Bold, 18), ("\\textbf", ParagraphFont::Bold, 12), ("\\emph", ParagraphFont::Italic, 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, }; } } SourceParagraph { text: raw.to_string(), font: ParagraphFont::Roman, line_height: 12, math: false, left_skip: 0, centered: false, right_aligned: false, } } fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Document { let units = paragraphs .iter() .enumerate() .map(|(index, paragraph)| { if paragraph.math { return Unit::math( index as u64, parse_math(¶graph.text), &Cmr10Metrics::default(), ); } 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: Vec::new(), 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: 50, ex_hyphen_penalty: 50, double_hyphen_demerits: 10_000, final_hyphen_demerits: 5_000, line_penalty: 10, adj_demerits: 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 }, 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, }; Unit::paragraph_with_style_and_face( index as u64, paragraph.text.clone(), style, paragraph.font, ) }) .collect(); Document::new(700 * SCALE, units) } 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); 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::*; 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_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); } }