mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-27 07:04:48 +00:00
Add craft-latex: LaTeX documents read and written, on craft-flow
WordCraft's crates/formats/src/latex (07f97737) with its 21 tests, moved onto craft-flow and craft-wordmodel; bytes are decoded by craft-mime's detect. The LaTeX parts of WordCraft's cross-format tests (nesting, column specs, labels, no TeX commands from the document, the fuzz and round-trip properties) come along as tests/hostile.rs. The ligature test builds its three-font paragraph as a flow instead of reading HTML.
This commit is contained in:
Generated
+11
@@ -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"
|
||||
|
||||
@@ -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" }
|
||||
|
||||
@@ -199,6 +199,7 @@ craft-<name> = { git = "https://github.com/storytold/craft-libs", rev = "<commit
|
||||
- [`craft-audio`](crates/audio/README.md): audio file I/O and codecs (WAV, AIFF, FLAC, AAC, Opus,
|
||||
AC-3/E-AC-3, MP1/MP2, MP3 encoding), streaming and seeking, and packet decoding for any demuxer. See its
|
||||
README for formats and features.
|
||||
- [`craft-latex`](crates/latex/README.md): LaTeX documents read (the everyday subset) and written (a standalone article), to and from the craft-flow model.
|
||||
- [`craft-markdown`](crates/markdown/README.md): Markdown read and written (a CommonMark subset with GitHub tables and strikethrough), to and from the craft-flow model.
|
||||
- [`craft-media`](crates/media/README.md): bit-level I/O (`bitstream`), clean-room MP4/MOV
|
||||
(`isobmff`), Matroska/WebM (`matroska`) and MXF (`mxf`) demuxers and muxers, Ogg (`ogg`), AVI (`avi`) and
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
[package]
|
||||
name = "craft-latex"
|
||||
description = "LaTeX documents read and written: the everyday subset (sections, lists, tables, math, formatting, links) to and from the craft-flow model, and a standalone article that compiles with any TeX distribution."
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-flow = { workspace = true }
|
||||
# Text that names no encoding: BOM, UTF-16, UTF-8, else the legacy encoding it looks like.
|
||||
craft-mime = { workspace = true, features = ["detect"] }
|
||||
craft-wordmodel = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
craft-markdown = { workspace = true }
|
||||
|
||||
proptest = { workspace = true }
|
||||
@@ -0,0 +1,37 @@
|
||||
# craft-latex
|
||||
|
||||
LaTeX documents, read and written, to and from the [craft-flow](../flow/README.md) model and a
|
||||
craft-wordmodel `Document`.
|
||||
|
||||
- **Write** (`export`): a standalone LaTeX 2ε `article` that compiles with pdfLaTeX, XeLaTeX or
|
||||
LuaLaTeX using only packages every distribution ships (`fontenc`, `ulem`, `xcolor`, `multirow`,
|
||||
`amsmath`, `hyperref`): unnumbered sectioning commands, `itemize`/`enumerate`, `tabular` with the
|
||||
column widths, equations `$…$` / `\[…\]`, character formatting, links and bookmarks. Pictures
|
||||
become their alternative text. Nothing the document says is written as a TeX command.
|
||||
- **Read** (`import`, `parse` for the flow): the everyday subset documents are written in: the
|
||||
preamble's `\title`/`\author`, sectioning, paragraphs, lists, `quote`, `center`/`flush…`,
|
||||
verbatim-like environments, `tabular` with `\multicolumn`/`\multirow`, inline and display math
|
||||
(kept as equations), text formatting commands and declarations, colours, links, labels, accents,
|
||||
special characters and ligatures. It is not a TeX engine: macros are not expanded. Unknown
|
||||
commands are dropped with their braced arguments kept as text; layout commands are dropped
|
||||
with their arguments. Bytes that name no encoding are decoded by `craft_mime::detect`.
|
||||
|
||||
```rust
|
||||
let doc = craft_latex::import(br"\section*{Intro} Some \textbf{bold} text and $x^2$.");
|
||||
assert!(doc.plain_text(Default::default()).starts_with("Intro\nSome bold text and"));
|
||||
let tex = craft_latex::export(&doc);
|
||||
assert!(tex.contains(r"\section*{Intro}") && tex.contains(r"\textbf{bold}") && tex.contains("$x^2$"));
|
||||
```
|
||||
|
||||
Input is hostile: nesting, column specs, labels and the source size (`MAX_SOURCE`) are bounded,
|
||||
and the work is linear.
|
||||
|
||||
## Math
|
||||
|
||||
`latex_to_linear` and `linear_to_latex` convert the math of a document to and from the linear
|
||||
format equations are kept in, as text, keeping the source's spacing. craft-math converts the same
|
||||
two syntaxes through its equation tree. These are two converters for one pair of syntaxes, and
|
||||
which one documents should use is an open question; this crate keeps WordCraft's choice.
|
||||
|
||||
Moved from WordCraft (`crates/formats/src/latex`, `07f97737`) with its tests and the LaTeX parts
|
||||
of its cross-format tests.
|
||||
@@ -316,7 +316,7 @@ impl Writer {
|
||||
Some(target) => 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<f32> = 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.
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
+21
-17
@@ -1,5 +1,5 @@
|
||||
use super::*;
|
||||
use crate::model::FBlock;
|
||||
use craft_flow::FBlock;
|
||||
|
||||
fn paras(src: &str) -> Vec<Para> {
|
||||
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(
|
||||
"<p><span style=\"font-family:Arial\">a-</span><span style=\"font-family:Georgia\">-b '</span><span style=\"font-family:Arial\">'x</span></p>",
|
||||
);
|
||||
// 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));
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ fn named_color(name: &str) -> Option<Rgb> {
|
||||
pub(super) fn parse_color(model: Option<&str>, spec: &str) -> Option<Rgb> {
|
||||
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<u8> = spec.split(',').filter_map(|x| x.trim().parse::<f32>().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<f32> {
|
||||
/// Column widths of a `tabular` column spec, when every column has one (`p{3cm}`).
|
||||
pub(super) fn spec_widths(spec: &str) -> (usize, Vec<f32>) {
|
||||
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<f32>) {
|
||||
let max_cols = wordcraft_doc::table::MAX_COLS;
|
||||
let max_cols = craft_wordmodel::table::MAX_COLS;
|
||||
let chars: Vec<char> = spec.chars().collect();
|
||||
let braces = closers(&chars, '{', '}');
|
||||
let mut cols = 0usize;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user