Files
texrra-engine/tests/typeset.rs
T

1552 lines
48 KiB
Rust

//! Compiler-session regression tests.
//!
//! These tests drive the same public `CompilerSession` API used by the HTTP
//! server, so they cover parsing, layout, SVG serialization, and PDF painting
//! without network or process setup.
use std::path::PathBuf;
use serde_json::Value;
use texrra_engine::rust_typeset::CompilerSession;
fn preview(session: &mut CompilerSession, source: &str, file_name: &str) -> Value {
let json = session
.preview_json(source, file_name)
.unwrap_or_else(|error| panic!("preview failed for {file_name}: {error}"));
serde_json::from_str(&json).unwrap_or_else(|error| panic!("invalid preview JSON: {error}"))
}
fn fresh_preview(source: &str, file_name: &str) -> Value {
preview(&mut CompilerSession::default(), source, file_name)
}
fn pages(value: &Value) -> &Vec<Value> {
value["pages"]
.as_array()
.unwrap_or_else(|| panic!("preview has no pages array: {value}"))
}
fn number(value: &Value, key: &str) -> f64 {
value[key]
.as_f64()
.unwrap_or_else(|| panic!("preview has no numeric {key}: {value}"))
}
fn page_svg(value: &Value, index: usize) -> String {
pages(value)[index]["svg"]
.as_str()
.unwrap_or_else(|| panic!("page {index} has no SVG"))
.to_string()
}
#[test]
fn examples_compile_to_one_a4_page() {
let examples = [
("hello.tex", include_str!("../examples/hello.tex")),
("boxes.tex", include_str!("../examples/boxes.tex")),
("compat.tex", include_str!("../examples/compat.tex")),
];
for (name, source) in examples {
let value = fresh_preview(source, name);
assert_eq!(value["status"], "ok", "{name}: {value}");
assert_eq!(pages(&value).len(), 1, "{name} page count");
assert!(
(number(&value, "pageWidthMm") - 210.0).abs() < 0.1,
"{name} width"
);
assert!(
(number(&value, "pageHeightMm") - 297.0).abs() < 0.1,
"{name} height"
);
if name == "compat.tex" {
let svg = page_svg(&value, 0);
assert!(
svg.contains("fill=\"#008000\">iD</text>"),
"compat example lost the ORCID badge"
);
assert!(
svg.contains(">example</text>"),
"compat example lost the link text"
);
}
}
}
#[test]
fn hello_compiles_to_pdf() {
let source = include_str!("../examples/hello.tex");
let pdf = CompilerSession::default()
.compile(source, "hello.tex")
.expect("hello PDF");
assert!(pdf.starts_with(b"%PDF-"), "missing PDF header");
assert!(
pdf.len() > 10_000,
"suspiciously small PDF: {} bytes",
pdf.len()
);
}
#[test]
fn arxiv_fixture_is_three_letter_pages() {
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("fixtures")
.join("arxiv-template")
.join("template.tex");
let source = std::fs::read_to_string(&path).expect("read arXiv fixture");
let file_name = path.to_string_lossy().to_string();
let value = fresh_preview(&source, &file_name);
assert_eq!(value["status"], "ok", "{}", value["message"]);
assert_eq!(pages(&value).len(), 3, "arXiv page count");
assert!(
(number(&value, "pageWidthMm") - 215.9).abs() < 0.1,
"Letter width"
);
assert!(
(number(&value, "pageHeightMm") - 279.4).abs() < 0.1,
"Letter height"
);
let first_page = page_svg(&value, 0);
assert!(first_page.contains("REPRINT"), "missing undertitle");
assert!(first_page.contains("Hippocampus"), "missing author column");
assert!(first_page.contains("October"), "missing date");
let note_y = text_y(&first_page, "Use");
assert!(
note_y > 200.0,
"title footnote should be painted in the page-bottom insertion area: {note_y}"
);
assert!(
first_page.contains(">See</text>"),
"first page should keep the closing section-2 line"
);
let see_y = text_y(&first_page, "See");
assert!(
note_y - see_y > 3.0,
"body must stay above the title footnote: see {see_y}, note {note_y}"
);
let third_page = page_svg(&value, 2);
let entry_x = text_x(&third_page, "Geor");
let continuation_x = text_x(&third_page, "Recognition");
assert!(
continuation_x - entry_x > 3.0,
"bibliography continuation lines should be indented: {entry_x} vs {continuation_x}"
);
}
#[test]
fn arxiv_title_block_uses_rules_and_small_caps() {
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("fixtures")
.join("arxiv-template")
.join("template.tex");
let source = std::fs::read_to_string(&path).expect("read arXiv fixture");
let value = fresh_preview(&source, &path.to_string_lossy());
assert_eq!(value["status"], "ok", "{}", value["message"]);
let first_page = page_svg(&value, 0);
let rule_count = first_page.matches("<rect").count();
assert!(rule_count >= 2, "title rules missing: {rule_count}");
assert!(
first_page.contains("font-size=\"4.9389\""),
"small-caps title glyphs missing"
);
assert!(
first_page.contains("font-style=\"italic\">arxiv</text>"),
"italic emph{{arxiv}} title run missing"
);
assert!(
first_page.contains("fill=\"#A6CE39\""),
"ORCID vector badge missing"
);
assert!(
first_page.contains(">iD</text>"),
"ORCID badge label missing"
);
}
#[test]
fn starred_headings_are_unnumbered() {
let source = r#"\documentclass{article}
\begin{document}
\section*{Starred Heading}
\section{Numbered Heading}
\end{document}
"#;
let value = fresh_preview(source, "headings.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
assert!(!svg.contains("1 *"), "starred heading was numbered: {svg}");
assert!(svg.contains("Star"), "starred heading text missing");
assert!(svg.contains("Number"), "numbered heading text missing");
}
#[test]
fn box_and_rule_material_paints_rectangles() {
let source = r#"\documentclass{article}
\begin{document}
\fbox{\rule{10mm}{5mm}}
\hrule width 20mm height 2pt
\end{document}
"#;
let value = fresh_preview(source, "rectangles.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
// Page background, fbox frame, the 10mm black rule, and the 20mm hrule.
assert!(
svg.matches("<rect").count() >= 4,
"expected four rectangles: {svg}"
);
assert!(
svg.contains("stroke=\"#000000\""),
"fbox frame is not stroked"
);
assert!(svg.contains("width=\"10."), "10mm rule missing");
assert!(svg.contains("width=\"20."), "20mm hrule missing");
}
#[test]
fn undefined_commands_report_an_error() {
let source = r#"\documentclass{article}
\begin{document}
\notacommand
\end{document}
"#;
let error = CompilerSession::default()
.preview_json(source, "bad.tex")
.expect_err("undefined command should fail");
assert!(
error.contains("undefined control sequence"),
"unexpected error: {error}"
);
}
#[test]
fn repeated_previews_reuse_stable_page_hashes() {
let mut session = CompilerSession::default();
let first_source = r#"\documentclass{article}
\begin{document}
First document.
\end{document}
"#;
let second_source = r#"\documentclass{article}
\begin{document}
Second document.
\end{document}
"#;
let first = preview(&mut session, first_source, "cache.tex");
let second = preview(&mut session, second_source, "cache.tex");
let again = preview(&mut session, first_source, "cache.tex");
assert_eq!(first["status"], "ok");
assert_eq!(second["status"], "ok");
assert_eq!(again["status"], "ok");
assert_eq!(first["pages"], again["pages"], "cache returned stale pages");
assert_ne!(
first["pages"][0]["hash"], second["pages"][0]["hash"],
"different sources produced the same page hash"
);
}
fn text_x(svg: &str, needle: &str) -> f64 {
let closing = format!("{needle}</text>");
let index = svg
.find(&closing)
.unwrap_or_else(|| panic!("missing text element containing `{needle}`"));
let start = svg[..index]
.rfind("<text ")
.unwrap_or_else(|| panic!("no text element before `{needle}`"));
let tag = &svg[start..index];
tag.split("x=\"")
.nth(1)
.and_then(|rest| rest.split('"').next())
.and_then(|value| value.parse::<f64>().ok())
.unwrap_or_else(|| panic!("text element for `{needle}` has no x coordinate"))
}
fn first_black_rect_width(svg: &str) -> f64 {
for fragment in svg.split("<rect ").skip(1) {
let tag = fragment.split('>').next().unwrap_or(fragment);
if !tag.contains("fill=\"#000000\"") {
continue;
}
let value = tag
.split("width=\"")
.nth(1)
.and_then(|rest| rest.split('"').next())
.and_then(|value| value.parse::<f64>().ok());
if let Some(width) = value {
return width;
}
}
panic!("no filled rectangle in SVG: {svg}");
}
fn max_black_rect_height(svg: &str) -> f64 {
let mut maximum: Option<f64> = None;
for fragment in svg.split("<rect ").skip(1) {
let tag = fragment.split('>').next().unwrap_or(fragment);
if !tag.contains("fill=\"#000000\"") {
continue;
}
let value = tag
.split("height=\"")
.nth(1)
.and_then(|rest| rest.split('"').next())
.and_then(|value| value.parse::<f64>().ok());
if let Some(height) = value {
maximum = Some(maximum.map_or(height, |current| current.max(height)));
}
}
maximum.unwrap_or_else(|| panic!("no filled rectangle in SVG: {svg}"))
}
#[test]
fn paragraph_indent_tracks_setlength_groups_and_noindent() {
let source = r#"\documentclass{article}
\begin{document}
\parindent=0pt
First paragraph.
\setlength{\parindent}{10mm}
Second paragraph.
{\setlength{\parindent}{0pt}
Third paragraph.
}
Fourth paragraph.
\addtolength{\parindent}{5mm}
Fifth paragraph.
\noindent
Noindent paragraph.
\end{document}
"#;
let value = fresh_preview(source, "parindent.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
let first = text_x(&svg, "First");
let second = text_x(&svg, "Second");
let third = text_x(&svg, "Third");
let fourth = text_x(&svg, "Fourth");
let fifth = text_x(&svg, "Fifth");
let noindent = text_x(&svg, "Noindent");
assert!(
first.abs() < 0.1,
"first paragraph should not be indented: {first}"
);
assert!((second - 10.0).abs() < 0.25, "second indent: {second}");
assert!(third.abs() < 0.1, "grouped zero indent leaked: {third}");
assert!(
(fourth - 10.0).abs() < 0.25,
"group restore failed: {fourth}"
);
assert!((fifth - 15.0).abs() < 0.25, "addtolength failed: {fifth}");
assert!(noindent.abs() < 0.1, "noindent ignored: {noindent}");
}
#[test]
fn default_parindent_is_seventeen_points() {
let source = r#"\documentclass{article}
\begin{document}
Default indent.
\end{document}
"#;
let value = fresh_preview(source, "default-parindent.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
let x = text_x(&svg, "Default");
// 17pt is 5.98mm.
assert!((x - 5.98).abs() < 0.15, "default parindent: {x}");
}
#[test]
fn hfill_fills_the_remaining_line() {
let source = r#"\documentclass{article}
\begin{document}
\setlength{\parindent}{0pt}
A\hfill B
C\hfill D\hfill E
\end{document}
"#;
let value = fresh_preview(source, "hfill.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
let a = text_x(&svg, "A");
let b = text_x(&svg, "B");
let c = text_x(&svg, "C");
let d = text_x(&svg, "D");
let e = text_x(&svg, "E");
assert!(a.abs() < 0.1, "A should stay at the left margin: {a}");
assert!(b > 150.0, "single hfill did not reach the right edge: {b}");
assert!(c.abs() < 0.1, "C should stay at the left margin: {c}");
assert!(d > 70.0 && d < 100.0, "middle hfill is not centered: {d}");
assert!(e > 150.0, "last hfill did not reach the right edge: {e}");
}
#[test]
fn figure_placement_and_newpage_split_pages() {
let image = format!("{}/examples/plot.png", env!("CARGO_MANIFEST_DIR"));
let template = r#"\documentclass{article}
\begin{document}
Before text.
\begin{figure}[PLACE]
\includegraphics[width=3cm]{IMAGE}
\caption{Float caption.}
\end{figure}
After text.
\end{document}
"#;
let compile = |placement: &str| {
let source = template
.replace("PLACE", placement)
.replace("IMAGE", &image);
fresh_preview(&source, "float.tex")
};
let top = compile("t");
assert_eq!(top["status"], "ok", "{}", top["message"]);
assert_eq!(pages(&top).len(), 2, "[t] should move the figure to page 2");
assert!(
!page_svg(&top, 0).contains("<image"),
"[t] figure on page 1"
);
assert!(page_svg(&top, 1).contains("<image"), "[t] figure missing");
assert!(
page_svg(&top, 0).contains("After"),
"[t] text after the float should fill page 1: {}",
page_svg(&top, 0)
);
let top_image_y = page_svg(&top, 1)
.split("<image")
.nth(1)
.and_then(|rest| rest.split("y=\"").nth(1))
.and_then(|rest| rest.split("\"").next())
.and_then(|value| value.parse::<f64>().ok())
.unwrap_or_else(|| panic!("[t] image has no y coordinate: {}", page_svg(&top, 1)));
assert!(
top_image_y < 30.0,
"[t] figure was not placed at the top of page 2: {top_image_y}"
);
let here = compile("h");
assert_eq!(here["status"], "ok", "{}", here["message"]);
assert_eq!(pages(&here).len(), 1, "[h] should stay in flow");
assert!(page_svg(&here, 0).contains("<image"), "[h] figure missing");
let float_page = compile("p");
assert_eq!(float_page["status"], "ok", "{}", float_page["message"]);
assert_eq!(pages(&float_page).len(), 3, "[p] should use its own page");
assert!(
page_svg(&float_page, 1).contains("<image"),
"[p] figure page missing"
);
let bottom = compile("b");
assert_eq!(bottom["status"], "ok", "{}", bottom["message"]);
assert_eq!(pages(&bottom).len(), 2, "[b] should end the page");
let bottom_svg = page_svg(&bottom, 0);
assert!(bottom_svg.contains("<image"), "[b] figure missing");
let image_y = bottom_svg
.split("<image")
.nth(1)
.and_then(|rest| rest.split("y=\"").nth(1))
.and_then(|rest| rest.split('"').next())
.and_then(|value| value.parse::<f64>().ok())
.unwrap_or_else(|| panic!("[b] image has no y coordinate: {bottom_svg}"));
assert!(
image_y > 200.0,
"[b] figure was not pushed to the bottom: {image_y}"
);
assert!(page_svg(&bottom, 1).contains("After"), "[b] following text");
let newpage = r#"\documentclass{article}
\begin{document}
First page.
\newpage
Second page.
\end{document}
"#;
let value = fresh_preview(newpage, "newpage.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
assert_eq!(pages(&value).len(), 2, "\\newpage page count");
assert!(page_svg(&value, 0).contains("First"), "first page text");
assert!(page_svg(&value, 1).contains("Second"), "second page text");
}
#[test]
fn sans_family_selects_the_sans_face() {
let source = r#"\documentclass{article}
\begin{document}
\setlength{\parindent}{0pt}
Serif text.
{\sffamily Sans family text.}
\textsf{Textsf sans} and {\sffamily\bfseries bold sans}.
\end{document}
"#;
let value = fresh_preview(source, "sans.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
assert!(
svg.contains("font-family=\"TexrraSans\""),
"sans face missing"
);
assert!(
svg.contains("font-family=\"TexrraSerif\""),
"serif face missing"
);
assert!(svg.contains(">Sans</text>"), "sans text missing");
assert!(svg.contains("extsf"), "textsf text missing");
assert!(
svg.contains("font-family=\"TexrraSans\" font-size=\"3.5278\" font-weight=\"700\""),
"bold sans face missing"
);
}
#[test]
fn small_caps_uses_reduced_uppercase_glyphs() {
let source = r#"\documentclass{article}
\begin{document}
\setlength{\parindent}{0pt}
\textsc{Small Caps} and {\scshape mixed Case}.
\end{document}
"#;
let value = fresh_preview(source, "smallcaps.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
assert!(
svg.contains(">MALL</text>"),
"lowercase letters were not uppercased"
);
assert!(!svg.contains("mall"), "small caps leaked lowercase glyphs");
assert!(
svg.contains("font-size=\"2.8222\""),
"small caps were not reduced to 80%"
);
assert!(
svg.contains("font-size=\"3.5278\""),
"full-size capitals should remain full-size"
);
}
#[test]
fn preprint_metadata_spacing_matches_reference() {
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("fixtures")
.join("arxiv-template")
.join("template.tex");
let source = std::fs::read_to_string(&path).expect("read arXiv fixture");
let value = fresh_preview(&source, &path.to_string_lossy());
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
let title = text_y(&svg, "STYLE");
let author = text_y_contains(&svg, "Hippocampus");
let date = text_y(&svg, "October");
// Measured against the XeLaTeX reference PDF (1 pt = 0.3528 mm).
assert!(
(author - title - 25.1).abs() < 1.0,
"title-to-author gap: {}",
author - title
);
assert!(
(date - author - 29.4).abs() < 1.0,
"author-to-date gap: {}",
date - author
);
}
fn text_y_contains(svg: &str, needle: &str) -> f64 {
let index = svg
.find(needle)
.unwrap_or_else(|| panic!("missing text element containing `{needle}`"));
let start = svg[..index]
.rfind("<text ")
.unwrap_or_else(|| panic!("no text element before `{needle}`"));
let tag = &svg[start..index];
tag.split("y=\"")
.nth(1)
.and_then(|rest| rest.split('\"').next())
.and_then(|value| value.parse::<f64>().ok())
.unwrap_or_else(|| panic!("text element for `{needle}` has no y coordinate"))
}
fn text_y(svg: &str, needle: &str) -> f64 {
let closing = format!("{needle}</text>");
let index = svg
.find(&closing)
.unwrap_or_else(|| panic!("missing text element containing `{needle}`"));
let start = svg[..index]
.rfind("<text ")
.unwrap_or_else(|| panic!("no text element before `{needle}`"));
let tag = &svg[start..index];
tag.split("y=\"")
.nth(1)
.and_then(|rest| rest.split('"').next())
.and_then(|value| value.parse::<f64>().ok())
.unwrap_or_else(|| panic!("text element for `{needle}` has no y coordinate"))
}
#[test]
fn raisebox_lifts_content_inline() {
let source = r#"\documentclass{article}
\begin{document}
\setlength{\parindent}{0pt}
A\raisebox{4pt}{raised}B
\end{document}
"#;
let value = fresh_preview(source, "raisebox.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
let baseline = text_y(&svg, "A");
let raised = text_y(&svg, "raised");
let lift = baseline - raised;
// 4pt = 1.411mm.
assert!((lift - 1.411).abs() < 0.15, "raisebox lift: {lift}");
}
#[test]
fn makebox_honours_width_and_alignment() {
let source = r#"\documentclass{article}
\begin{document}
\setlength{\parindent}{0pt}
X\makebox[20mm][c]{mid}Y
\makebox[40mm][l]{L}\makebox[40mm][r]{R}
\end{document}
"#;
let value = fresh_preview(source, "makebox.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
let x = text_x(&svg, "X");
let mid = text_x(&svg, "mid");
let y = text_x(&svg, "Y");
assert!(
mid > x + 7.0,
"centered box content did not move right: {mid}"
);
assert!(mid < y - 4.0, "centered box content overflowed: {mid}");
assert!(
(y - x - 22.8).abs() < 0.5,
"fixed box width not honoured: {}",
y - x
);
let left = text_x(&svg, "L");
let right = text_x(&svg, "R");
assert!(
right > left + 70.0,
"right-aligned box did not fill width: {right}"
);
}
#[test]
fn inline_fbox_draws_a_frame_around_content() {
let source = r#"\documentclass{article}
\begin{document}
\setlength{\parindent}{0pt}
A\fbox{B}C
\end{document}
"#;
let value = fresh_preview(source, "inline-fbox.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
assert!(
svg.contains("fill=\"none\" stroke=\"#000000\""),
"inline fbox frame is missing"
);
assert!(svg.contains(">B</text>"), "inline fbox content is missing");
assert!(
svg.contains(">A</text>") && svg.contains(">C</text>"),
"text around fbox missing"
);
}
#[test]
fn minipage_wraps_to_requested_width_and_vbox_wraps() {
let source = r#"\documentclass{article}
\begin{document}
\begin{minipage}[t]{50mm}
This is a minipage with enough text to wrap across several lines and demonstrate that it is block-wide.
\end{minipage}
\vbox{A vbox wraps at text width with \textbf{bold} content.}
\end{document}
"#;
let value = fresh_preview(source, "minipage.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
assert!(svg.contains(">minipage</text>"), "minipage content missing");
assert!(
svg.contains(">block-wide.</text>"),
"wrapped minipage tail missing"
);
let first = text_y(&svg, "This");
let wrapped = text_y(&svg, "block-wide.");
assert!(
wrapped > first + 3.0,
"minipage did not wrap: {first} -> {wrapped}"
);
for word in ["This", "text", "block-wide."] {
assert!(
text_x(&svg, word) < 50.0,
"minipage content escaped its 50mm width: {word}"
);
}
assert!(svg.contains(">vbox</text>"), "vbox content missing");
assert!(svg.contains(">bold</text>"), "vbox styled content missing");
}
#[test]
fn footnotes_are_placed_at_the_page_bottom() {
let source = r#"\documentclass{article}
\begin{document}
First paragraph.\footnote{This is a footnote.}
Second paragraph.\footnote{Another note.}
Third paragraph.
\end{document}
"#;
let value = fresh_preview(source, "footnotes.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
assert!(svg.contains("¹"), "footnote marker missing");
assert!(svg.contains("²"), "second footnote marker missing");
let body = text_y(&svg, "First");
let note = text_y(&svg, "This");
assert!(
note > body + 150.0,
"footnote is not at the page bottom: {note}"
);
assert!(
text_x(&svg, "This") > 7.5 && text_x(&svg, "This") < 11.0,
"footnote indent missing"
);
assert!(
svg.contains("fill=\"#000000\"/>"),
"footnote separator rule missing"
);
}
#[test]
fn thanks_creates_a_title_footnote() {
let source = r#"\documentclass{article}
\title{A Title\thanks{Thanks to the test suite.}}
\author{Author\thanks{Author affiliation.}}
\begin{document}
\maketitle
Body text.
\end{document}
"#;
let value = fresh_preview(source, "thanks.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
assert!(svg.contains("¹"), "title thanks marker missing");
assert!(svg.contains("²"), "author thanks marker missing");
let note = text_y(&svg, "Thanks");
assert!(
note > 200.0,
"title footnote is not at the page bottom: {note}"
);
}
#[test]
fn page_style_decorates_headers_and_footers() {
let source = r#"\documentclass{article}
\pagestyle{fancy}
\fancyhead[L]{Left head}
\fancyhead[C]{Middle head}
\fancyhead[R]{Right head}
\fancyfoot[C]{Foot \thepage}
\begin{document}
Body text.
\end{document}
"#;
let value = fresh_preview(source, "pagestyle.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
for text in ["Left", "Middle", "Right", "Foot"] {
assert!(
svg.contains(&format!(">{text}</text>")),
"missing decoration `{text}`: {svg}"
);
}
assert!(
text_x(&svg, "Left") < 1.0,
"left header is not at the left margin"
);
assert!(
text_x(&svg, "Right") > 140.0,
"right header is not at the right edge"
);
assert!(
text_y(&svg, "Left") < 25.0,
"header is not near the top of the page"
);
assert!(
text_y(&svg, "Foot") > 250.0,
"footer is not near the bottom of the page"
);
}
#[test]
fn thispagestyle_empty_suppresses_one_page_decorations() {
let source = r#"\documentclass{article}
\pagestyle{fancy}
\fancyhead[L]{Left head}
\fancyfoot[C]{Foot \thepage}
\begin{document}
First page.\thispagestyle{empty}
\newpage
Second page.
\end{document}
"#;
let value = fresh_preview(source, "thispagestyle.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
assert_eq!(pages(&value).len(), 2, "page count");
let first = page_svg(&value, 0);
assert!(
!first.contains(">Left</text>"),
"page 1 header was not suppressed: {first}"
);
assert!(
!first.contains(">Foot</text>"),
"page 1 footer was not suppressed: {first}"
);
let second = page_svg(&value, 1);
assert!(
second.contains(">Left</text>"),
"page 2 header missing: {second}"
);
assert!(
second.contains(">Foot</text>"),
"page 2 footer missing: {second}"
);
assert!(
second.contains(">2</text>"),
"page 2 number missing: {second}"
);
}
#[test]
fn default_plain_style_prints_a_page_number() {
let value = fresh_preview(include_str!("../examples/hello.tex"), "hello.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
assert!(
text_y(&svg, "1") > 250.0,
"default page number is not in the footer"
);
}
#[test]
fn geometry_updates_text_width_and_text_height() {
let source = r#"\documentclass{article}
\geometry{textwidth=100mm,textheight=200mm}
\begin{document}
\noindent\rule{\textwidth}{2pt}
\noindent\rule{2pt}{\textheight}
\end{document}
"#;
let value = fresh_preview(source, "geometry-lengths.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
let width = first_black_rect_width(&svg);
assert!(
(width - 100.0).abs() < 1.0,
"textwidth did not follow geometry: {width}"
);
let height = max_black_rect_height(&svg);
assert!(
(height - 200.0).abs() < 1.0,
"textheight did not follow geometry: {height}"
);
}
#[test]
fn letter_paper_updates_text_width_length() {
let source = r#"\documentclass[letterpaper]{article}
\begin{document}
\noindent\rule{\textwidth}{2pt}
\end{document}
"#;
let value = fresh_preview(source, "letter-lengths.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let width = first_black_rect_width(&page_svg(&value, 0));
assert!(
(width - 165.9).abs() < 1.0,
"letter textwidth is wrong: {width}"
);
}
#[test]
fn document_class_font_size_scales_body_and_headings() {
for (option, body_size, heading_size) in [
("10pt", "3.5278", "4.9389"),
("11pt", "3.8806", "4.9389"),
("12pt", "4.2333", "5.9972"),
] {
let source = format!(
r"\documentclass[{option}]{{article}}
\begin{{document}}
\section{{Heading}}
Body text.
\end{{document}}
"
);
let value = fresh_preview(&source, "fontsize.tex");
assert_eq!(value["status"], "ok", "{option}: {}", value["message"]);
let svg = page_svg(&value, 0);
assert!(
svg.contains(&format!("font-size=\"{body_size}\" font-weight=\"400\"")),
"{option}: body size {body_size} missing"
);
assert!(
svg.contains(&format!("font-size=\"{heading_size}\" font-weight=\"700\"")),
"{option}: heading size {heading_size} missing"
);
}
}
#[test]
fn top_table_moves_to_the_next_page_and_text_flows() {
let source = r#"\documentclass{article}
\begin{document}
Before table.
\begin{table}[t]
\caption{Top table}
\begin{tabular}{ll}
Alpha & Beta \\
Gamma & Delta \\
\end{tabular}
\end{table}
After table.
\end{document}
"#;
let value = fresh_preview(source, "table-float.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
assert_eq!(pages(&value).len(), 2, "top table should start a new page");
assert!(
!page_svg(&value, 0).contains("Top"),
"table caption should not stay on page 1: {}",
page_svg(&value, 0)
);
assert!(
page_svg(&value, 0).contains("After"),
"text after the table should fill page 1"
);
let second = page_svg(&value, 1);
assert!(
second.contains(">op</text>"),
"table caption missing from page 2: {second}"
);
assert!(
second.contains(">Alpha</text>"),
"table body missing from page 2: {second}"
);
}
#[test]
fn bottom_table_sits_at_the_page_bottom() {
let source = r#"\documentclass{article}
\begin{document}
Before table.
\begin{table}[b]
\caption{Bottom table}
\begin{tabular}{ll}
Alpha & Beta \\
Gamma & Delta \\
\end{tabular}
\end{table}
After table.
\end{document}
"#;
let value = fresh_preview(source, "table-bottom.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
assert_eq!(pages(&value).len(), 2, "bottom table should end page 1");
let first = page_svg(&value, 0);
assert!(first.contains(">Alpha</text>"), "bottom table missing");
let alpha_y = text_y(&first, "Alpha");
assert!(
alpha_y > 220.0,
"bottom table was not pushed to the page bottom: {alpha_y}"
);
assert!(
page_svg(&value, 1).contains("After"),
"text after a bottom table should continue on the next page"
);
}
#[test]
fn table_of_contents_lists_numbered_sections_and_pages() {
let source = r"\documentclass{article}
\begin{document}
\tableofcontents
\section{Alpha section}
Alpha paragraph.
\newpage
\section{Beta section}
Beta paragraph.
\end{document}";
let value = fresh_preview(source, "contents.tex");
assert_eq!(value["status"], "ok", "{value}");
assert_eq!(pages(&value).len(), 2, "{value}");
let svg = page_svg(&value, 0);
assert!(svg.contains(">Contents</text>"), "missing contents heading");
assert!(svg.contains(">Alpha</text>"), "missing first entry");
assert!(svg.contains(">Beta</text>"), "missing second entry");
assert!(svg.contains(">1</text>"), "missing first page number");
assert!(svg.contains(">2</text>"), "missing second page number");
assert!(svg.contains(". . ."), "missing dotted leader: {svg}");
}
#[test]
fn list_of_tables_lists_captions_and_pages() {
let source = r"\documentclass{article}
\begin{document}
\listoftables
\begin{table}[h]
\caption{First table}
\begin{tabular}{ll}
A & B \\
\end{tabular}
\end{table}
\end{document}";
let value = fresh_preview(source, "lot.tex");
assert_eq!(value["status"], "ok", "{value}");
let svg = page_svg(&value, 0);
assert!(svg.contains(">List</text>"), "missing list heading");
assert!(svg.contains(">of</text>"), "missing tables heading word");
assert!(svg.contains(">ables</text>"), "missing tables word");
assert!(svg.contains(">First</text>"), "missing caption entry");
assert!(svg.contains(">1</text>"), "missing page number");
}
#[test]
fn list_of_figures_lists_captions_and_pages() {
let source = r"\documentclass{article}
\begin{document}
\listoffigures
\begin{figure}[h]
\includegraphics[width=20mm]{examples/plot.png}
\caption{First figure}
\end{figure}
\end{document}";
let value = fresh_preview(source, "lof.tex");
assert_eq!(value["status"], "ok", "{value}");
let svg = page_svg(&value, 0);
assert!(svg.contains(">List</text>"), "missing list heading");
assert!(svg.contains(">of</text>"), "missing figures heading word");
assert!(svg.contains(">First</text>"), "missing caption entry");
}
#[test]
fn rules_are_native_pdf_rectangles() {
let source = r"\documentclass{article}
\begin{document}
Before.
\rule{40mm}{5mm}
\fbox{Framed box}
After.
\end{document}";
let pdf = CompilerSession::default()
.compile(source, "rules.tex")
.expect("rule PDF");
assert!(pdf.starts_with(b"%PDF-"));
let text = String::from_utf8_lossy(&pdf);
assert!(
!text.contains("/Subtype /Image"),
"rules should not be painted as image XObjects"
);
}
#[test]
fn ascii_documents_use_base14_fonts_without_embedding() {
let source = r"\documentclass{article}
\begin{document}
Plain text that only needs the standard Times encoding.
\end{document}";
let pdf = CompilerSession::default()
.compile(source, "base14.tex")
.expect("base14 PDF");
let text = String::from_utf8_lossy(&pdf);
assert!(
text.contains("Times-Roman"),
"expected a Base-14 Times face"
);
assert!(
!text.contains("FontFile2"),
"ASCII text should not embed a TrueType program"
);
}
#[test]
fn arxiv_table_rules_follow_a_narrow_centered_table() {
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("fixtures")
.join("arxiv-template")
.join("template.tex");
let source = std::fs::read_to_string(&path).expect("read arXiv fixture");
let file_name = path.to_string_lossy().to_string();
let value = fresh_preview(&source, &file_name);
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 2);
let mut table_rules = Vec::new();
for fragment in svg.split("<line ").skip(1) {
let tag = fragment.split('>').next().unwrap_or(fragment);
let x1 = tag
.split("x1=\"")
.nth(1)
.and_then(|rest| rest.split('"').next())
.and_then(|value| value.parse::<f64>().ok());
let x2 = tag
.split("x2=\"")
.nth(1)
.and_then(|rest| rest.split('"').next())
.and_then(|value| value.parse::<f64>().ok());
if let (Some(x1), Some(x2)) = (x1, x2) {
let width = x2 - x1;
if x1 > 20.0 && width > 40.0 && width < 140.0 {
table_rules.push((x1, width));
}
}
}
assert!(
table_rules.len() >= 4,
"expected the table's top/mid/bottom rules, got {table_rules:?}"
);
assert!(
table_rules
.iter()
.all(|(x, width)| *x > 20.0 && *width < 140.0),
"table rules should be centered and narrower than the text block: {table_rules:?}"
);
let widest = table_rules
.iter()
.map(|(_, width)| *width)
.fold(0.0_f64, f64::max);
assert!(
(60.5..62.5).contains(&widest),
"natural-width table should match the reference width (~61.2mm), got {widest:.2}mm"
);
}
#[test]
fn multicolumn_and_cmidrule_render_spans() {
let source = r"\documentclass{article}
\begin{document}
\begin{tabular}{lll}
\toprule
\multicolumn{2}{c}{Part} \\
\cmidrule(r){1-2}
Name & Description & Size ($\mu$m) \\
\midrule
Dendrite & Input terminal & 100 \\
\bottomrule
\end{tabular}
\end{document}";
let value = fresh_preview(source, "multicolumn.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
let mut rules = Vec::new();
for fragment in svg.split("<line ").skip(1) {
let tag = fragment.split('>').next().unwrap_or(fragment);
let read = |name: &str| {
tag.split(&format!("{name}=\""))
.nth(1)
.and_then(|rest| rest.split('"').next())
.and_then(|value| value.parse::<f64>().ok())
};
if let (Some(x1), Some(x2), Some(y1), Some(y2)) =
(read("x1"), read("x2"), read("y1"), read("y2"))
&& x2 > x1 + 10.0
&& (y1 - y2).abs() < 0.01
{
rules.push((x1, x2, y1));
}
}
assert_eq!(rules.len(), 4, "expected four table rules, got {rules:?}");
let full = rules
.iter()
.max_by(|left, right| (left.1 - left.0).total_cmp(&(right.1 - right.0)))
.copied()
.expect("full-width rule");
let short = rules
.iter()
.find(|(x1, x2, _)| *x2 - *x1 < (full.1 - full.0) * 0.9)
.copied()
.expect("partial cmidrule");
assert!(
(short.0 - full.0).abs() < 1.0,
"partial rule should start at the first column: {short:?}"
);
assert!(
short.1 < full.1 - 5.0,
"partial rule extends across the whole table: {short:?}"
);
let mut part_x = None;
for fragment in svg.split("<text ").skip(1) {
let tag = fragment.split('>').next().unwrap_or(fragment);
if fragment.contains(">Part</text>") {
part_x = tag
.split("x=\"")
.nth(1)
.and_then(|rest| rest.split('"').next())
.and_then(|value| value.parse::<f64>().ok());
}
}
let part_x = part_x.expect("Part text in SVG");
assert!(
part_x < full.0 + (full.1 - full.0) / 2.0,
"multicolumn text should be centered over the first two columns, Part x={part_x}, rule={full:?}"
);
}
#[test]
fn abstract_environment_gets_an_unumbered_heading() {
let source = r"\documentclass{article}
\begin{document}
\begin{abstract}
This is the abstract body.
\end{abstract}
\section{Introduction}
Body.
\end{document}";
let preview = CompilerSession::default()
.preview_json(source, "abstract.tex")
.expect("abstract preview");
let value: serde_json::Value = serde_json::from_str(&preview).expect("preview JSON");
let svg = value["pages"][0]["svg"].as_str().expect("svg");
assert!(
svg.contains(">BSTRACT</text>"),
"missing abstract heading: {svg}"
);
assert!(
svg.contains(">1</text>"),
"section numbering changed: {svg}"
);
}
#[test]
fn ragged_alignment_declarations_are_honoured() {
let prefix = r"\documentclass{article}
\usepackage[margin=6.5cm]{geometry}
\begin{document}
";
let ragged_source = format!(
"{prefix}{{\\raggedleft Right}}\n\n{{\\raggedright alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu}}\n\\end{{document}}"
);
let justified_source = format!(
"{prefix}alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu\n\\end{{document}}"
);
let ragged = fresh_preview(&ragged_source, "ragged.tex");
let justified = fresh_preview(&justified_source, "justified.tex");
let ragged_svg = page_svg(&ragged, 0);
let justified_svg = page_svg(&justified, 0);
assert!(
text_x(&ragged_svg, "Right") > 30.0,
"raggedleft did not move to the right margin: {ragged_svg}"
);
let ragged_beta = text_x(&ragged_svg, "beta");
let justified_beta = text_x(&justified_svg, "beta");
assert!(
ragged_beta + 0.2 < justified_beta,
"raggedright still justified the line: ragged={ragged_beta}, justified={justified_beta}\nRAGGED={ragged_svg}\nJUSTIFIED={justified_svg}"
);
}
#[test]
fn centering_declaration_centers_a_paragraph() {
let prefix = r"\documentclass{article}
\usepackage[margin=6.5cm]{geometry}
\begin{document}
";
let centered_source =
format!("{prefix}{{\\centering alpha beta}}\n\nplain paragraph\n\\end{{document}}");
let left_source = format!("{prefix}alpha beta\n\nplain paragraph\n\\end{{document}}");
let centered = fresh_preview(&centered_source, "centered.tex");
let left = fresh_preview(&left_source, "left.tex");
let centered_svg = page_svg(&centered, 0);
let left_svg = page_svg(&left, 0);
let centered_alpha = text_x(&centered_svg, "alpha");
let left_alpha = text_x(&left_svg, "alpha");
assert!(
centered_alpha > left_alpha + 10.0,
"centering did not move the line: centered={centered_alpha}, left={left_alpha}\n{centered_svg}"
);
let plain_alpha = text_x(&centered_svg, "plain");
let left_plain = text_x(&left_svg, "plain");
assert!(
(plain_alpha - left_plain).abs() < 0.5,
"centering leaked into the following paragraph: centered={plain_alpha}, left={left_plain}"
);
}
#[test]
fn chapter_headings_number_sections_and_enter_contents() {
let source = r#"\documentclass{book}
\begin{document}
\tableofcontents
\chapter{First Chapter}
\section{Alpha}
\subsection{Beta}
\chapter{Second Chapter}
\section{Gamma}
\end{document}
"#;
let value = fresh_preview(source, "chapters.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
assert!(
pages(&value).len() >= 2,
"chapters did not start on a new page: {value}"
);
let svg = (0..pages(&value).len())
.map(|index| page_svg(&value, index))
.collect::<Vec<_>>()
.join("");
for needle in [
"Contents", "First", "Chapter", "Alpha", "Beta", "Gamma", "1.1", "1.1.1", "2.1",
] {
assert!(svg.contains(needle), "chapter numbering is missing : {svg}");
}
assert!(
!svg.contains("0.1"),
"section was numbered under chapter zero: {svg}"
);
}
#[test]
fn custom_maketitle_replaces_the_engine_title_block() {
let source = r#"\documentclass{article}
\title{Custom title}
\author{Engine author}
\renewcommand{\maketitle}{\begin{center}\@title\end{center}}
\begin{document}
\maketitle
Body text.
\end{document}
"#;
let value = fresh_preview(source, "custom-title.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
assert!(svg.contains("Custom"), "custom title missing: {svg}");
assert!(
!svg.contains("Engine title"),
"engine title block was not replaced: {svg}"
);
assert!(svg.contains("Body"), "body text missing: {svg}");
}
#[test]
fn vbox_captures_vertical_material() {
let source = r#"\documentclass{article}
\begin{document}
Before.
\vbox{%
\hrule width 40mm height 2pt
\vskip 4pt
\hrule width 20mm height 2pt
}
After.
\end{document}
"#;
let value = fresh_preview(source, "vbox.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
assert_eq!(
svg.matches("fill=\"#000000\"/>").count(),
2,
"expected two rules in vbox: {svg}"
);
assert!(svg.contains("width=\"40.15"), "wide rule missing: {svg}");
assert!(svg.contains("width=\"20.07"), "narrow rule missing: {svg}");
assert!(svg.contains(">Before.</text>"), "text before vbox missing");
assert!(svg.contains(">After</text>"), "text after vbox missing");
}
#[test]
fn page_decorations_expand_declarations_at_document_start() {
let source = r#"\documentclass{article}
\usepackage{fancyhdr}
\pagestyle{fancy}
\fancyhf{}
\chead{\shorttitle}
\def\shorttitle{First title}
\def\shorttitle{Renewed title}
\begin{document}
First page.
\newpage
Second page.
\end{document}
"#;
let value = fresh_preview(source, "header-declarations.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
assert_eq!(pages(&value).len(), 2, "expected two pages: {value}");
let second = page_svg(&value, 1);
assert!(
second.contains(">Renewed</text>"),
"header did not see the renewed shorttitle: {second}"
);
assert!(
!second.contains(">First</text>"),
"header was expanded too early: {second}"
);
}
#[test]
fn abstract_body_is_indented_like_a_quote() {
let source = r#"\documentclass{article}
\begin{document}
\begin{abstract}
Alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu.
\end{abstract}
Body text after the abstract.
\end{document}
"#;
let value = fresh_preview(source, "abstract-quote.tex");
assert_eq!(value["status"], "ok", "{}", value["message"]);
let svg = page_svg(&value, 0);
let abstract_x = text_x(&svg, "Alpha");
let body_x = text_x(&svg, "Body");
assert!(
abstract_x > 9.0,
"abstract body was not inset: x={abstract_x}"
);
assert!(
body_x + 3.0 < abstract_x,
"abstract inset did not differ from body: abstract={abstract_x}, body={body_x}"
);
}
#[test]
fn natbib_citations_use_author_year() {
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("fixtures")
.join("arxiv-template")
.join("template.tex");
let source = std::fs::read_to_string(&path).expect("read arXiv fixture");
let value = fresh_preview(&source, &path.to_string_lossy());
assert_eq!(value["status"], "ok", "{}", value["message"]);
let second = page_svg(&value, 1);
assert!(
second.contains(">Kour</text>") && second.contains(">Saabne,</text>"),
"author-year citation missing: {second}"
);
assert!(
!second.contains(">[1, 3]</text>"),
"numeric citation was not replaced: {second}"
);
assert!(
second.contains("2014a") && second.contains("2014b"),
"duplicate author-year citations should get a/b suffixes: {second}"
);
let third = page_svg(&value, 2);
let george = third.find("Geor").expect("bibliography given name missing");
let kour = third
.find(">Kour</text>")
.expect("bibliography family name missing");
assert!(
george < kour,
"bibliography should render given name before family name: {third}"
);
assert!(
!third.contains(">[1]</text>"),
"author-year bibliography should omit numeric labels: {third}"
);
assert!(
third.contains("2014a") && third.contains("2014b"),
"bibliography years should carry a/b suffixes: {third}"
);
}
fn text_has_fill(svg: &str, word: &str, fill: &str) -> bool {
let needle = format!(">{word}</text>");
let Some(end) = svg.find(&needle) else {
return false;
};
let start = svg[..end].rfind("<text").expect("text element not found");
svg[start..end].contains(fill)
}
#[test]
fn hyperlink_colour_survives_line_breaks() {
let source = r"\documentclass{article}
\usepackage[margin=6.5cm]{geometry}
\begin{document}
\href{https://example.com/a}{alpha beta gamma delta epsilon zeta eta theta iota kappa}
\end{document}";
let value = fresh_preview(source, "hyperlink-wrap.tex");
assert_eq!(value["status"], "ok", "{value}");
let svg = page_svg(&value, 0);
for word in ["alpha", "gamma", "kappa"] {
assert!(
text_has_fill(&svg, word, "fill=\"#008000\""),
"hyperlink word {word} lost its green colour"
);
}
}
#[test]
fn href_text_is_painted_with_the_link_colour() {
let source = r"\documentclass{article}
\begin{document}
See \href{https://example.com}{the example site} for details.
\end{document}";
let value = fresh_preview(source, "href.tex");
assert_eq!(value["status"], "ok", "{value}");
let svg = page_svg(&value, 0);
assert!(svg.contains("fill=\"#008000\""), "{svg}");
assert!(svg.contains(">example</text>"), "{svg}");
}
#[test]
fn orcidlink_renders_a_green_badge_without_printing_the_url() {
let source = r"\documentclass{article}
\begin{document}
\orcidlink{0000-0002-1825-0097}
\end{document}";
let value = fresh_preview(source, "orcidlink.tex");
assert_eq!(value["status"], "ok", "{value}");
let svg = page_svg(&value, 0);
assert!(svg.contains("fill=\"#008000\">iD</text>"), "{svg}");
assert!(
!svg.contains("orcid.org"),
"URL leaked into the document: {svg}"
);
}
#[test]
fn caption_footnotes_follow_the_figure_page() {
let source = r"\documentclass{article}
\usepackage{graphicx}
\begin{document}
Before.\newpage
\begin{figure}[h]
\includegraphics[width=0.5\textwidth]{examples/plot.png}
\caption{A caption with a footnote\footnote{Caption footnote text.}}
\end{figure}
After text.
\end{document}";
let value = fresh_preview(source, "caption-footnote.tex");
assert_eq!(value["status"], "ok", "{value}");
let pages = pages(&value);
assert!(pages.len() >= 2, "expected a new page before the figure");
assert!(
!page_svg(&value, 0).contains(">Caption</text>"),
"caption footnote leaked onto the first page"
);
assert!(
page_svg(&value, 1).contains(">Caption</text>"),
"caption footnote should be painted on the figure page"
);
}