diff --git a/Cargo.lock b/Cargo.lock index 86c5f004f2..f96e565e7e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1283,6 +1283,17 @@ dependencies = [ "zip", ] +[[package]] +name = "craft-latex" +version = "0.1.0" +dependencies = [ + "craft-flow", + "craft-markdown", + "craft-mime", + "craft-wordmodel", + "proptest", +] + [[package]] name = "craft-lottie" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index be4be55776..222e28ad0a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -66,6 +66,7 @@ craft-assuan = { path = "crates/assuan" } craft-kra = { path = "crates/kra" } craft-audio = { path = "crates/audio" } # No default features, so craft-audio's `encode` builds craft-media without `isobmff`. +craft-latex = { path = "crates/latex" } craft-markdown = { path = "crates/markdown" } craft-media = { path = "crates/media", default-features = false } craft-media-testkit = { path = "crates/media-testkit" } diff --git a/README.md b/README.md index 9b469bb1fd..36b86257ee 100644 --- a/README.md +++ b/README.md @@ -199,6 +199,7 @@ craft- = { git = "https://github.com/storytold/craft-libs", rev = " format!("\\hyperlink{{{}}}{{{s}}}", escape_url(target)), // A script, `file:`, UNC or other non-web target becomes plain text: a `\href` // compiles to a PDF `/URI` action the reader would otherwise follow on click. - None if wordcraft_doc::link::is_safe_href(l) => format!("\\href{{{}}}{{{s}}}", escape_url(l)), + None if craft_wordmodel::link::is_safe_href(l) => format!("\\href{{{}}}{{{s}}}", escape_url(l)), None => s, }; } @@ -324,7 +324,7 @@ impl Writer { } pub(super) fn table(&mut self, t: &FTable) { - let cols = t.cols().clamp(1, wordcraft_doc::table::MAX_COLS); + let cols = t.cols().clamp(1, craft_wordmodel::table::MAX_COLS); let widths: Vec = if t.widths.len() == cols && t.widths.iter().all(|w| w.is_finite() && *w > 1.0) { let total: f32 = t.widths.iter().sum(); // Scale a table wider than the page to fit. diff --git a/crates/latex/src/lib.rs b/crates/latex/src/lib.rs index 488decce0e..9a4c6bcba5 100644 --- a/crates/latex/src/lib.rs +++ b/crates/latex/src/lib.rs @@ -1,3 +1,4 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] //! LaTeX (`.tex`) import and export. //! //! **Export** writes a standalone LaTeX 2ε `article` that compiles with pdfLaTeX, XeLaTeX or @@ -18,8 +19,12 @@ //! Like the other text formats, the parser is lenient and never panics on hostile input: group and //! environment nesting is depth-limited and the input size is capped. -use crate::model::{self, Cell, FBlock, FTable, Flow, Fmt, Inline, Kind, ListInfo, Para}; -use wordcraft_doc::{Align, Document, Rgb}; +#[cfg(doctest)] +#[doc = include_str!("../README.md")] +struct ReadmeExamples; + +use craft_flow::{self as model, Cell, FBlock, FTable, Flow, Fmt, Inline, Kind, ListInfo, Para}; +use craft_wordmodel::{Align, Document, Rgb}; mod export; mod lex; diff --git a/crates/latex/src/parser.rs b/crates/latex/src/parser.rs index cd5e63507b..1ff739fa9c 100644 --- a/crates/latex/src/parser.rs +++ b/crates/latex/src/parser.rs @@ -11,7 +11,7 @@ use super::{Align, Document, FBlock, Flow, Fmt, Inline, Kind, ListInfo, Para, mo /// Import a LaTeX source file. pub fn import(bytes: &[u8]) -> Document { model::begin_import(); - let mut d = model::to_doc(&parse(&crate::txt::decode(bytes.get(..MAX_SOURCE).unwrap_or(bytes)))); + let mut d = model::to_doc(&parse(&craft_mime::detect::decode(bytes.get(..MAX_SOURCE).unwrap_or(bytes)))); d.ensure_nonempty(); d } diff --git a/crates/latex/src/table.rs b/crates/latex/src/table.rs index f02c20cda6..c6bc981d0f 100644 --- a/crates/latex/src/table.rs +++ b/crates/latex/src/table.rs @@ -88,7 +88,7 @@ pub(super) fn table(toks: &[Tok], spec: &str, depth: usize) -> FTable { } _ => {} } - if rows.len() >= wordcraft_doc::table::MAX_ROWS { + if rows.len() >= craft_wordmodel::table::MAX_ROWS { break; } } @@ -106,7 +106,7 @@ pub(super) fn table(toks: &[Tok], spec: &str, depth: usize) -> FTable { let mut g = 0usize; // A document row keeps MAX_COLS cells; the rest would only widen `covering`, which is // walked once per row. - for cell_toks in r.into_iter().take(wordcraft_doc::table::MAX_COLS) { + for cell_toks in r.into_iter().take(craft_wordmodel::table::MAX_COLS) { let mut cell = Cell::default(); let mut content = trim_cell(cell_toks); // `\multicolumn{n}{spec}{content}`, `\multirow{n}{width}{content}`. Each wrapper diff --git a/crates/latex/src/tests.rs b/crates/latex/src/tests.rs index 3097eaea1f..aabe04ab01 100644 --- a/crates/latex/src/tests.rs +++ b/crates/latex/src/tests.rs @@ -1,5 +1,5 @@ use super::*; -use crate::model::FBlock; +use craft_flow::FBlock; fn paras(src: &str) -> Vec { parse(src).blocks.into_iter().filter_map(|b| if let FBlock::Para(p) = b { Some(p) } else { None }).collect() @@ -33,11 +33,11 @@ fn spec_widths_repeats_are_bounded() { assert_eq!(spec_widths("*{2}{*{2}{l}}").0, 4); let deep = format!("{}l{}", "*{1}{".repeat(MAX_NEST + 5), "}".repeat(MAX_NEST + 5)); let (cols, widths) = spec_widths(&deep); - assert!(cols <= wordcraft_doc::table::MAX_COLS && widths.is_empty()); + assert!(cols <= craft_wordmodel::table::MAX_COLS && widths.is_empty()); let wide = format!("{}p{{1cm}}{}", "*{64}{".repeat(30), "}".repeat(30)); let (cols, widths) = spec_widths(&wide); - assert_eq!(cols, wordcraft_doc::table::MAX_COLS); - assert!(widths.len() <= wordcraft_doc::table::MAX_COLS); + assert_eq!(cols, craft_wordmodel::table::MAX_COLS); + assert!(widths.len() <= craft_wordmodel::table::MAX_COLS); } #[test] @@ -281,26 +281,26 @@ fn math_conversions() { #[test] fn equations_survive_a_round_trip() { let mut d = Document::new(); - let mut p = wordcraft_doc::Paragraph::with_text("Area ", Default::default()); + let mut p = craft_wordmodel::Paragraph::with_text("Area ", Default::default()); let n = p.len(); p.insert_object( n, - wordcraft_doc::para::InlineObject::Equation { linear: "π r^2".into(), display: false, math: Default::default() }, + craft_wordmodel::para::InlineObject::Equation { linear: "π r^2".into(), display: false, math: Default::default() }, &Default::default(), ) .unwrap(); - d.body = vec![wordcraft_doc::para_block(p)]; + d.body = vec![craft_wordmodel::para_block(p)]; let tex = export(&d); assert!(tex.contains("$\\pi r^2$") && tex.contains("\\usepackage{amsmath}"), "{tex}"); let back = import(tex.as_bytes()); - let wordcraft_doc::Block::Para(bp) = &*back.body[0] else { panic!() }; + let craft_wordmodel::Block::Para(bp) = &*back.body[0] else { panic!() }; assert!( - bp.objects.iter().any(|o| matches!(o, wordcraft_doc::para::InlineObject::Equation { linear, .. } if linear == "π r^2")), + bp.objects.iter().any(|o| matches!(o, craft_wordmodel::para::InlineObject::Equation { linear, .. } if linear == "π r^2")), "{:?}", bp.objects ); // Formats without equations keep the text. - let md = crate::markdown::export(&d); + let md = craft_markdown::export(&d); assert!(md.contains("π r^2"), "{md}"); } @@ -308,7 +308,7 @@ fn equations_survive_a_round_trip() { fn leading_brackets_stay_text() { // `\item [x]` and `\\ [1]` would read the bracket as an optional argument. assert_eq!(escape_text("[x] a\n [1] b [c]"), "{[}x] a\\\\\n {[}1] b [c]"); - let doc = crate::markdown::import("- [x] done"); + let doc = craft_markdown::import("- [x] done"); let back = import(export(&doc).as_bytes()); assert_eq!(back.plain_text(Default::default()), "[x] done"); } @@ -384,8 +384,8 @@ fn exported_borderless_tables_omit_rules() { #[test] fn table_borders_and_borderless_round_trip() { + use craft_wordmodel::{Block, CharProps, Paragraph, Table, para_block}; use std::sync::Arc; - use wordcraft_doc::{Block, CharProps, Paragraph, Table, para_block}; // 1. Borderless table. let mut doc = Document::new(); @@ -426,7 +426,7 @@ fn verbatim_end_is_kept_out_after_control_characters_go() { // the code line closed the environment and the rest ran as TeX. let mut d = Document::new(); let line = "\\end{verb\u{E}atim}\\input{/etc/passwd}"; - d.body = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text(line, Default::default()).styled(model::CODE_STYLE))]; + d.body = vec![craft_wordmodel::para_block(craft_wordmodel::Paragraph::with_text(line, Default::default()).styled(model::CODE_STYLE))]; let out = export(&d); assert_eq!(out.matches("\\end{verbatim}").count(), 1, "{out}"); assert!(out.contains("\\end {verbatim}\\input"), "{out}"); @@ -452,9 +452,13 @@ fn nested_multicolumn_wrappers_are_bounded() { #[test] fn ligature_characters_split_across_runs_stay_apart() { - let d = crate::html::import( - "

a--b ''x

", - ); + // Three runs in different fonts (as HTML with font-family spans gives them). + let font = |f: &str| Fmt { font: Some(f.into()), ..Default::default() }; + let mut p = Para::default(); + p.push_text("a-", &font("Arial")); + p.push_text("-b '", &font("Georgia")); + p.push_text("'x", &font("Arial")); + let d = model::to_doc(&Flow { blocks: vec![FBlock::Para(p)], ..Default::default() }); let tex = export(&d); assert!(tex.contains("a-{}-b '{}'x"), "{tex}"); let back = import(tex.as_bytes()); @@ -468,6 +472,6 @@ fn a_tabular_row_keeps_the_cells_a_table_row_holds() { let wide = vec!["\\multicolumn{63}{c}{x}"; 5000].join("&"); let toks = tokenize(&format!("{wide}\\\\ a & b \\\\")); let t = table::table(&toks, "", 0); - assert_eq!(t.rows.first().map(Vec::len), Some(wordcraft_doc::table::MAX_COLS)); + assert_eq!(t.rows.first().map(Vec::len), Some(craft_wordmodel::table::MAX_COLS)); assert_eq!(t.rows.get(1).map(Vec::len), Some(2)); } diff --git a/crates/latex/src/units.rs b/crates/latex/src/units.rs index c327cbdc88..b4186a3a26 100644 --- a/crates/latex/src/units.rs +++ b/crates/latex/src/units.rs @@ -50,7 +50,7 @@ fn named_color(name: &str) -> Option { pub(super) fn parse_color(model: Option<&str>, spec: &str) -> Option { let spec = spec.trim(); match model.map(str::trim) { - Some("HTML") => crate::model::parse_color(&format!("#{spec}")), + Some("HTML") => craft_flow::parse_color(&format!("#{spec}")), Some("RGB") => { let v: Vec = spec.split(',').filter_map(|x| x.trim().parse::().ok()).map(|x| x.clamp(0.0, 255.0) as u8).collect(); match v.as_slice() { @@ -109,14 +109,14 @@ pub(super) fn length_pt(s: &str) -> Option { /// Column widths of a `tabular` column spec, when every column has one (`p{3cm}`). pub(super) fn spec_widths(spec: &str) -> (usize, Vec) { let (cols, widths) = spec_widths_at(spec, 0); - (cols.min(wordcraft_doc::table::MAX_COLS), if widths.len() == cols { widths } else { Vec::new() }) + (cols.min(craft_wordmodel::table::MAX_COLS), if widths.len() == cols { widths } else { Vec::new() }) } /// [`spec_widths`] at nesting `depth` of `*{n}{…}` repeats. The column count saturates and the -/// widths stop growing past [`wordcraft_doc::table::MAX_COLS`], so nested repeats can't overflow +/// widths stop growing past [`craft_wordmodel::table::MAX_COLS`], so nested repeats can't overflow /// or exhaust memory; the returned widths are empty unless every column has one. fn spec_widths_at(spec: &str, depth: usize) -> (usize, Vec) { - let max_cols = wordcraft_doc::table::MAX_COLS; + let max_cols = craft_wordmodel::table::MAX_COLS; let chars: Vec = spec.chars().collect(); let braces = closers(&chars, '{', '}'); let mut cols = 0usize; diff --git a/crates/latex/tests/hostile.rs b/crates/latex/tests/hostile.rs new file mode 100644 index 0000000000..1ccb424990 --- /dev/null +++ b/crates/latex/tests/hostile.rs @@ -0,0 +1,89 @@ +//! Hostile and generated input, from WordCraft's cross-format tests (`crates/formats/src/tests.rs`): +//! nesting, column specs and labels are bounded and linear, the export carries no TeX commands +//! from the document, and text survives a round trip. + +use craft_latex::{export, import, linear_to_latex}; +use craft_wordmodel::Document; +use std::time::{Duration, Instant}; + +fn text(tex: &str) -> String { + import(tex.as_bytes()).plain_text(Default::default()) +} + +#[test] +fn deep_nesting_is_bounded() { + assert!(text(&("{\\textbf{".repeat(50_000) + "x")).contains('x')); + assert!(text(&("\\begin{itemize}\\item ".repeat(10_000) + "deep")).contains("deep")); + let _ = import(("\\begin{tabular}{l}".repeat(2_000) + "cell").as_bytes()); + let _ = import(format!("${}x{}$", "\\frac{".repeat(10_000), "}".repeat(10_000)).as_bytes()); + // `*{n}{…}` column specs nested 100k deep, and repeats multiplying past what a table holds. + assert!(text(&format!("\\begin{{tabular}}{{{}l{}}}x\\end{{tabular}}", "*{1}{".repeat(100_000), "}".repeat(100_000))).contains('x')); + assert!(text(&format!("\\begin{{tabular}}{{{}p{{1cm}}{}}}x\\end{{tabular}}", "*{64}{".repeat(30), "}".repeat(30))).contains('x')); + // An equation of unmatched `(` and one nested 100k deep convert in linear time. + let started = Instant::now(); + assert_eq!(linear_to_latex(&"(".repeat(200_000)).len(), 200_000); + let nested = format!("{}x{}", "(".repeat(100_000), ")".repeat(100_000)); + assert_eq!(linear_to_latex(&nested).len(), 200_001); + assert!(started.elapsed() < Duration::from_secs(10), "{:?}", started.elapsed()); + assert_eq!(linear_to_latex("(a)/(b)"), "\\frac{a}{b}"); + assert_eq!(linear_to_latex("((a)/(b))/(c)"), "\\frac{\\frac{a}{b}}{c}"); + // `\begin{` never closed. + let started = Instant::now(); + let _ = import("\\begin{".repeat(300_000).as_bytes()); + assert!(started.elapsed() < Duration::from_secs(10), "{:?}", started.elapsed()); +} + +/// What a document says in an equation or a bookmark name is not written to the exported file as +/// TeX commands: compiling the export must not read files or run programs the document names. +#[test] +fn latex_export_carries_no_commands_from_the_document() { + let tex = linear_to_latex("\\input secret.txt \\immediate\\write18\\bgroup id\\egroup \\csname x\\endcsname"); + for cmd in ["\\input", "\\immediate", "\\write", "\\bgroup", "\\egroup", "\\csname", "\\endcsname"] { + assert!(!tex.contains(cmd), "{cmd} in {tex}"); + } + assert!(tex.contains("\\backslash input"), "{tex}"); + for linear in ["a^^5cinput secret.txt ", "a^^^^5cinput", "x^(^^5cinput)", "^^5cinput"] { + assert!(!linear_to_latex(linear).contains("^^"), "{linear}"); + } + let deep = format!("{}^^5cinput x{}", "x^(".repeat(40), ")".repeat(40)); + assert!(!linear_to_latex(&deep).contains("^^")); + assert_eq!(linear_to_latex("\\alpha+\\sin x+\\mathbb R"), "\\alpha+\\sin x+\\mathbb R"); + assert_eq!(linear_to_latex("x^2^3"), "x^2^3"); + let d = import("Text $\\input secret.txt $ and \\hypertarget{^^5cinput secret.txt ^^5c}{here}.".as_bytes()); + let out = export(&d); + assert!(!out.contains("\\input") && !out.contains("^^"), "{out}"); +} + +#[test] +fn latex_labels_in_a_row_are_read_in_linear_time() { + let started = Instant::now(); + for src in ["\\label{a} ".repeat(100_000) + "x", "\\label{a}".repeat(100_000) + "x", "\\hypertarget{a}{} ".repeat(100_000)] { + assert!(import(src.as_bytes()).body.len() <= 2); + } + assert!(started.elapsed() < Duration::from_secs(10), "{:?}", started.elapsed()); + let d = import("\\label{one}First \\label{two}second \\label{three}third.".as_bytes()); + let p = d.para_at(&craft_wordmodel::Pos::body(0, 0)).unwrap(); + let names: Vec<&str> = p + .objects + .iter() + .filter_map(|o| if let craft_wordmodel::InlineObject::BookmarkStart { name } = o { Some(name.as_str()) } else { None }) + .collect(); + assert_eq!(names, ["one", "two", "three"]); + assert_eq!(d.plain_text(craft_wordmodel::StoryRef::Body).replace('\u{FFFC}', ""), "First second third."); +} + +proptest::proptest! { + #[test] + fn fuzz_latex(s in "(\\\\(begin|end)\\{(itemize|tabular|verbatim|quote|center|x)\\}|\\\\[a-zA-Z]{1,8}\\*?|\\\\[^a-zA-Z]|[{}\\[\\]$&%~^_#]|\n\n|[a-z ]){0,150}") { + let d = import(s.as_bytes()); + let _ = export(&d); + } + + #[test] + fn latex_text_round_trips(words in proptest::collection::vec("[a-zA-Z0-9{}$&%#_~^\\\\<>|`'.!-]{1,8}", 1..8)) { + let text = words.join(" "); + let tex = export(&Document::from_text(&text)); + let got = import(tex.as_bytes()).plain_text(Default::default()); + proptest::prop_assert_eq!(got.trim(), text.trim(), "tex: {}", tex); + } +}