Apply the percent catcode when stripping comments

Comments were stripped in a separate pass before canonicalisation, so
\catcode`\%=12 happened too late to make a later percent literal. Move comment
stripping into the canonicalisation pass: it now tracks whether % is a comment
char (default yes), skips to the end of line when it is, and \catcode`\%=12
(or 13) turns that off so later percents reach the text. The source order in
geometry_and_body becomes canonicalise (comments + catcodes) then collapse
definition bodies, and the separate strip_tex_comments call is gone.

A test previews "100% sure" under \catcode`\%=12 and the default commented form
("Hello% hidden" + "world") as "Helloworld" with no warnings.
This commit is contained in:
gloamxun committed 2026-10-27 01:21:10 +08:00
1 parent d791e3a0f2
commit 05e1bd096b
3 files changed
+51 -8

No files matched your search

+1 -1
View File
@@ -49,7 +49,7 @@ floats (`\floatsep`, `\textfloatsep`, `\intextsep`, `\topfraction`,
absolute limits, splitting), marks, Rust output hook, multi-page PDF, and the absolute limits, splitting), marks, Rust output hook, multi-page PDF, and the
route-D service endpoints (`/api/route-d/preview|pdf|edit`, project preview and route-D service endpoints (`/api/route-d/preview|pdf|edit`, project preview and
PDF opt-in with `?engine=route-d`; flat `/preview` and project previews now PDF opt-in with `?engine=route-d`; flat `/preview` and project previews now
prefer route-D with a v1 fallback). 1007 workspace tests are green and no oracle prefer route-D with a v1 fallback). 1008 workspace tests are green and no oracle
fixture is ignored. Preview JSON also carries a `warnings` array naming fixture is ignored. Preview JSON also carries a `warnings` array naming
environments route-D cannot lay out and control words that survived layout, so environments route-D cannot lay out and control words that survived layout, so
unsupported source is reported instead of being silently typeset. unsupported source is reported instead of being silently typeset.
+6 -5
View File
@@ -370,7 +370,7 @@ Math coverage includes fractions/roots, scripts, `\left...\right` with body-scal
Paragraph units carry a `ParagraphFont`; `Unit::paragraph_with_face` and `Unit::paragraph_with_style_and_face` select Roman, bold, italic, mono, or sans. The corresponding Computer Modern TFM (`cmr10`, `cmbx10`, `cmti10`, `cmbxti10`, `cmtt10`, `cmss10`, `cmssbx10`, `cmssi10`, `cmcsc10`) supplies advances, kerns, ligatures, and italic correction for layout, the display list selects the matching face, and the PDF writes Computer Modern Type1 outlines for each built-in face (`cmr10`/`cmbx10`/`cmti10`/`cmbxti10`/`cmtt10`/`cmss10`/`cmssbx10`/`cmssi10`/`cmcsc10`, plus `cmmi10` for mathematical italic letters, `cmsy10` for math symbols and `cmex10` for big operators), falling back to Liberation subsets only for characters the Type1 encodings cannot address; those fallback glyphs keep their Unicode text under PDF extraction, so accented and Greek words round-trip; Type1 faces carry a ToUnicode CMap built from the requested characters, so glyphs whose names are ambiguous in the Adobe Glyph List (capital Omega, which would otherwise extract as U+2126) keep their intended code points. `Engine::edit` preserves the face when reflowing an edited paragraph. Paragraph units carry a `ParagraphFont`; `Unit::paragraph_with_face` and `Unit::paragraph_with_style_and_face` select Roman, bold, italic, mono, or sans. The corresponding Computer Modern TFM (`cmr10`, `cmbx10`, `cmti10`, `cmbxti10`, `cmtt10`, `cmss10`, `cmssbx10`, `cmssi10`, `cmcsc10`) supplies advances, kerns, ligatures, and italic correction for layout, the display list selects the matching face, and the PDF writes Computer Modern Type1 outlines for each built-in face (`cmr10`/`cmbx10`/`cmti10`/`cmbxti10`/`cmtt10`/`cmss10`/`cmssbx10`/`cmssi10`/`cmcsc10`, plus `cmmi10` for mathematical italic letters, `cmsy10` for math symbols and `cmex10` for big operators), falling back to Liberation subsets only for characters the Type1 encodings cannot address; those fallback glyphs keep their Unicode text under PDF extraction, so accented and Greek words round-trip; Type1 faces carry a ToUnicode CMap built from the requested characters, so glyphs whose names are ambiguous in the Adobe Glyph List (capital Omega, which would otherwise extract as U+2126) keep their intended code points. `Engine::edit` preserves the face when reflowing an edited paragraph.
The crate currently has 437 unit tests plus ten route-D integration tests and forty-two oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 1007 tests (437 route-D unit, 380 engine binary unit, 10 route-D integration, 42 oracle, 71 v1 integration, 62 server, 4 engine unit, 1 core unit), with none ignored. The flat `/preview` endpoint and the project preview/PDF endpoints now try route-D first and fall back to v1 on error (`?engine=v1` or `TEXRRA_ENGINE=v1` forces v1; the flat response carries `X-Preview-Engine`, naming the engine used). A geometry-less project now defaults to Letter, matching pdfLaTeX, where the old v1 path used A4. The crate currently has 437 unit tests plus ten route-D integration tests and forty-two oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 1008 tests (437 route-D unit, 381 engine binary unit, 10 route-D integration, 42 oracle, 71 v1 integration, 62 server, 4 engine unit, 1 core unit), with none ignored. The flat `/preview` endpoint and the project preview/PDF endpoints now try route-D first and fall back to v1 on error (`?engine=v1` or `TEXRRA_ENGINE=v1` forces v1; the flat response carries `X-Preview-Engine`, naming the engine used). A geometry-less project now defaults to Letter, matching pdfLaTeX, where the old v1 path used A4.
### M0 incremental demo ### M0 incremental demo
@@ -553,10 +553,11 @@ are:
`\def` stays lazy. A runtime `\def` also parses its parameter text, so a `\def` stays lazy. A runtime `\def` also parses its parameter text, so a
body-embedded `\def\foo#1{...}` (undelimited or delimited) expands with its body-embedded `\def\foo#1{...}` (undelimited or delimited) expands with its
arguments instead of leaking. A `\catcode` assignment is consumed for any arguments instead of leaking. A `\catcode` assignment is consumed for any
target (backtick, bare or code-point form); only `@` (values 11/12) changes target (backtick, bare or code-point form); `@` (values 11/12) and `%`
scanning, so class files that set it directly instead of using (value 12 makes comments literal) are applied, so class files that set them
`\makeatletter` work, while other catcode values are consumed but not applied directly work, while other catcode values are consumed but not applied yet.
yet. There is no token stream. A runtime Comment stripping now lives in the same canonicalisation pass. There is no
token stream. A runtime
`\csname ... \endcsname` (also inside ordinary macro bodies) expands its `\csname ... \endcsname` (also inside ordinary macro bodies) expands its
contents and resolves the named macro, yielding nothing when undefined. contents and resolves the named macro, yielding nothing when undefined.
`\futurelet\alias\command <token>` binds the looked-ahead token to the `\futurelet\alias\command <token>` binds the looked-ahead token to the
+44 -2
View File
@@ -5947,6 +5947,7 @@ fn canonicalize_at_catcodes(source: &str) -> String {
let mut out = String::with_capacity(source.len()); let mut out = String::with_capacity(source.len());
let mut index = 0; let mut index = 0;
let mut at_letter = false; let mut at_letter = false;
let mut percent_comments = true;
let mut saved = Vec::new(); let mut saved = Vec::new();
while index < characters.len() { while index < characters.len() {
let character = characters[index]; let character = characters[index];
@@ -5962,6 +5963,12 @@ fn canonicalize_at_catcodes(source: &str) -> String {
index += 1; index += 1;
continue; continue;
} }
if character == '%' && percent_comments {
while index < characters.len() && characters[index] != '\n' {
index += 1;
}
continue;
}
if character != '\\' { if character != '\\' {
out.push(character); out.push(character);
index += 1; index += 1;
@@ -6051,6 +6058,8 @@ fn canonicalize_at_catcodes(source: &str) -> String {
// assignments are consumed so they do not leak as text. // assignments are consumed so they do not leak as text.
if target == '@' { if target == '@' {
at_letter = value == 11; at_letter = value == 11;
} else if target == '%' {
percent_comments = value != 12 && value != 13;
} }
index = next; index = next;
continue; continue;
@@ -6149,9 +6158,8 @@ fn geometry_and_body_with_images(
// body before `\begin{document}` so its commands are consumed as setup // body before `\begin{document}` so its commands are consumed as setup
// instead of being typeset as text at the top of page one. // instead of being typeset as text at the top of page one.
let source = lift_at_begin_document(source); let source = lift_at_begin_document(source);
let source = collapse_definition_bodies(&source);
let source = strip_tex_comments(&source);
let source = canonicalize_at_catcodes(&source); let source = canonicalize_at_catcodes(&source);
let source = collapse_definition_bodies(&source);
let source = collapse_braced_command(&source, "\\newgeometry"); let source = collapse_braced_command(&source, "\\newgeometry");
// Class files write the title metadata across lines, especially author // Class files write the title metadata across lines, especially author
// blocks with forced line breaks and thanks notes. // blocks with forced line breaks and thanks notes.
@@ -16073,6 +16081,40 @@ A definition.
assert!(!text.contains("makeatletter"), "{text}"); assert!(!text.contains("makeatletter"), "{text}");
} }
#[test]
fn percent_catcode_turns_comments_literal() {
let literal = "\\documentclass{article}\n\\catcode`\\%=12\n\\begin{document}\n\n100% sure\n\n\\end{document}\n";
let json = preview_json(literal).expect("preview");
let value: serde_json::Value = serde_json::from_str(&json).expect("JSON");
assert_eq!(
value["warnings"].as_array().map(Vec::len),
Some(0),
"{}",
value["warnings"]
);
let svg = value["pages"][0]["svg"].as_str().expect("svg");
let text: String = svg
.split('>')
.filter_map(|piece| piece.split('<').next())
.collect::<String>()
.split_whitespace()
.collect();
assert!(text.contains("100%sure"), "{text}");
let commented = "\\documentclass{article}\n\\begin{document}\n\nHello% hidden\nworld\n\n\\end{document}\n";
let json = preview_json(commented).expect("preview");
let value: serde_json::Value = serde_json::from_str(&json).expect("JSON");
let svg = value["pages"][0]["svg"].as_str().expect("svg");
let text: String = svg
.split('>')
.filter_map(|piece| piece.split('<').next())
.collect::<String>()
.split_whitespace()
.collect();
assert!(text.contains("Helloworld"), "{text}");
assert!(!text.contains("hidden"), "{text}");
}
#[test] #[test]
fn meaning_prints_macro_bodies() { fn meaning_prints_macro_bodies() {
let source = "\\documentclass{article}\n\\begin{document}\n\n\\def\\greet#1{Hello #1}\n\n\\meaning\\greet and \\meaning\\missing.\n\n\\end{document}\n"; let source = "\\documentclass{article}\n\\begin{document}\n\n\\def\\greet#1{Hello #1}\n\n\\meaning\\greet and \\meaning\\missing.\n\n\\end{document}\n";