Report unsupported environments and leaked commands

This commit is contained in:
gloamxun committed 2026-10-26 00:31:43 +08:00
1 parent c9a074b1fe
commit a28e8926c7
4 files changed
+177 -10

No files matched your search

+168 -3
View File
@@ -11,6 +11,7 @@ use std::sync::{Mutex, OnceLock};
use texrra_tex_core::cmr10::Cmr10Metrics;
use texrra_tex_core::math::{AlignedRow, MathAtom, parse_math, split_math_lines};
use texrra_tex_core::paragraph::HorizontalItem;
use texrra_tex_core::pdf::{PageOrigin, display_lists_to_pdf_with_cm_type1};
pub use texrra_tex_core::render::RasterImage;
use texrra_tex_core::render::{DisplayItem, DisplayList, FontFace};
@@ -116,7 +117,15 @@ pub fn project_preview_json_with_images(
(engine, changed, recomputed)
}
};
let json = render_json(&document, &engine, Some((&changed, recomputed)), &geometry);
let mut warnings = source_warnings(source);
warnings.extend(document_warnings(&document));
let json = render_json(
&document,
&engine,
Some((&changed, recomputed)),
&geometry,
&warnings,
);
sessions.insert(
project_id.to_string(),
ProjectSession {
@@ -1981,7 +1990,9 @@ pub fn preview_json(source: &str) -> Result<String, String> {
let mut document = build_document(&paragraphs, &geometry);
apply_geometry(&mut document, &geometry);
let engine = layout_document(&document);
let json = render_json(&document, &engine, None, &geometry);
let mut warnings = source_warnings(source);
warnings.extend(document_warnings(&document));
let json = render_json(&document, &engine, None, &geometry, &warnings);
// 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| {
@@ -2077,7 +2088,15 @@ pub fn edit_json(source: &str, unit: usize) -> Result<String, String> {
}
let changed = engine.changed_pages().to_vec();
let recomputed = engine.recomputed_pages();
let json = render_json(&next, &engine, Some((&changed, recomputed)), &geometry);
let mut warnings = source_warnings(source);
warnings.extend(document_warnings(&next));
let json = render_json(
&next,
&engine,
Some((&changed, recomputed)),
&geometry,
&warnings,
);
*slot = Some((next, engine));
Ok(json)
})
@@ -6380,11 +6399,112 @@ fn stamp_toc_pages(document: &mut Document, engine: &Engine, geometry: &PageGeom
changed
}
/// Environments route-D knows how to lay out (starred variants are normalised).
const SUPPORTED_ENVIRONMENTS: &[&str] = &[
"document",
"itemize",
"enumerate",
"description",
"quote",
"quotation",
"verse",
"abstract",
"figure",
"table",
"center",
"flushleft",
"flushright",
"minipage",
"verbatim",
"tabular",
"longtable",
"displaymath",
"math",
"equation",
"align",
"gather",
"thebibliography",
"theorem",
"lemma",
"corollary",
"proposition",
"definition",
"example",
"remark",
"proof",
];
/// Report environments that route-D would otherwise leave as literal text.
fn source_warnings(source: &str) -> Vec<String> {
let mut warnings = Vec::new();
let mut rest = source;
while let Some(index) = rest.find("\\begin{") {
let after = &rest[index + "\\begin{".len()..];
let Some(close) = after.find('}') else {
break;
};
let name = after[..close].trim();
let normalized = name.trim_end_matches('*');
if !SUPPORTED_ENVIRONMENTS.contains(&normalized) {
let message = format!("unsupported environment `{name}`");
if !warnings.contains(&message) {
warnings.push(message);
}
}
rest = &after[close + 1..];
}
warnings
}
/// Report control words that survived layout as literal backslash glyphs.
fn document_warnings(document: &Document) -> Vec<String> {
let mut warnings = Vec::new();
for unit in &document.units {
for item in &unit.items {
let VerticalItem::Paragraph(paragraph) = item else {
continue;
};
for line in &paragraph.lines {
let mut index = 0;
while index < line.len() {
if let HorizontalItem::Box(box_) = &line[index] {
if box_.character == Some('\\') {
let mut name = String::new();
let mut next = index + 1;
while let Some(HorizontalItem::Box(next_box)) = line.get(next) {
match next_box.character {
Some(character) if character.is_ascii_alphabetic() => {
name.push(character);
next += 1;
}
_ => break,
}
}
let message = if name.is_empty() {
"unsupported command near a backslash".to_string()
} else {
format!("unsupported command `\\{name}`")
};
if !warnings.contains(&message) {
warnings.push(message);
}
}
}
index += 1;
}
}
}
}
warnings.truncate(20);
warnings
}
fn render_json(
document: &Document,
engine: &Engine,
edit: Option<(&[usize], usize)>,
geometry: &PageGeometry,
warnings: &[String],
) -> String {
let mut document = document.clone();
let relaid = if stamp_toc_pages(&mut document, engine, geometry) {
@@ -6445,6 +6565,14 @@ fn render_json(
changed
);
}
let _ = write!(json, ",\"warnings\":[");
for (index, warning) in warnings.iter().enumerate() {
if index > 0 {
json.push(',');
}
let _ = write!(json, "\"{}\"", escape_json(warning));
}
json.push(']');
let _ = write!(json, ",\"pageHeightPt\":{page_height_pt:.0}}}");
json
}
@@ -7062,6 +7190,43 @@ mod source_tests {
assert_eq!(geometry_counter(&geometry, "steps"), 4);
}
#[test]
fn preview_warnings_flag_unsupported_environments() {
let source = r"\begin{document}
\begin{align}
a &= b
\end{align}
\[\begin{cases}
x & x > 0 \\
0 & \text{otherwise}
\end{cases}\]
\begin{tabularx}{\textwidth}{lX}
a & b
\end{tabularx}
\end{document}";
let json = preview_json(source).expect("preview");
assert!(json.contains("unsupported environment `cases`"), "{json}");
assert!(
json.contains("unsupported environment `tabularx`"),
"{json}"
);
assert!(!json.contains("unsupported environment `align`"), "{json}");
let plain = preview_json("Alpha").expect("plain preview");
assert!(plain.contains("\"warnings\":[]"), "{plain}");
}
#[test]
fn preview_warnings_flag_leaked_commands() {
let json = preview_json(r"See \pageref{sec} and \textcolor{red}{red}.").expect("preview");
assert!(json.contains(r"unsupported command `\\pageref`"), "{json}");
assert!(
json.contains(r"unsupported command `\\textcolor`"),
"{json}"
);
}
#[test]
fn page_numbers_follow_the_page_counter() {
let offset = preview_json("\\setcounter{page}{5}\n\nAlpha\n\n\\newpage\n\nBeta")