Honor \catcode`\@ assignments

Class files often set the @ catcode directly instead of calling
\makeatletter. Recognise \catcode assignments in the canonicalisation pass for
the @ target: the target may be written with a backtick, bare, or as a code
point, the value must be numeric (11 letter, 12 other) or \active, and the
assignment is consumed and updates the same state \makeatletter toggles.
Assignments for other characters are left untouched so nothing is silently
dropped.

A preview test sets \catcode`\@=11, defines and uses \@foo, and checks "bar"
with no warnings and no leaked assignment.
This commit is contained in:
gloamxun committed 2026-10-27 00:46:15 +08:00
1 parent b056b11ba9
commit 34d54d91a4
3 files changed
+102 -5

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
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
prefer route-D with a v1 fallback). 996 workspace tests are green and no oracle
prefer route-D with a v1 fallback). 997 workspace tests are green and no oracle
fixture is ignored. Preview JSON also carries a `warnings` array naming
environments route-D cannot lay out and control words that survived layout, so
unsupported source is reported instead of being silently typeset.
+5 -3
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.
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 996 tests (437 route-D unit, 369 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 997 tests (437 route-D unit, 370 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
@@ -544,8 +544,10 @@ are:
the body expand their bodies (including `\csname`) when read, while a plain
`\def` stays lazy. A runtime `\def` also parses its parameter text, so a
body-embedded `\def\foo#1{...}` (undelimited or delimited) expands with its
arguments instead of leaking. There is still no catcode table beyond `@` and no token
stream, so class code that relies on those semantics degrades.
arguments instead of leaking. A `\catcode` assignment is recognised for `@`
(backtick, bare or code-point target, values 11/12), so class files that set
the catcode directly instead of using `\makeatletter` work; catcodes for any
other character are still unmodelled, and there is no token stream.
- **Boxes**: `\sbox`/`\savebox` content and `\mbox`/`\hbox`/`\makebox`
bodies are inserted as one unbreakable inline box (interword spaces become
fixed-width boxes), so `\usebox` no longer reflows across lines. Savebox
+96 -1
View File
@@ -5286,7 +5286,70 @@ fn is_internal_at_command(name: &str) -> bool {
.is_some_and(|rest| INTERNAL_AT_COMMANDS.contains(&rest))
}
/// Model the one catcode the engine understands: `@` is a letter only between
/// Parse the `\catcode` target and value that follow the command, supporting
/// the backtick form (`\catcode`\@=11`), a bare character, or a code point.
fn catcode_assignment(characters: &[char], start: usize) -> Option<(char, i64, usize)> {
let mut index = start;
let skip_space = |index: &mut usize| {
while *index < characters.len() && characters[*index].is_whitespace() {
*index += 1;
}
};
skip_space(&mut index);
if index < characters.len() && characters[index] == '`' {
index += 1;
}
if index >= characters.len() {
return None;
}
let target = if characters[index] == '\\' {
let character = *characters.get(index + 1)?;
index += 2;
character
} else if characters[index].is_ascii_digit() {
let mut value = 0_i64;
while index < characters.len() && characters[index].is_ascii_digit() {
value = value * 10 + characters[index].to_digit(10)? as i64;
index += 1;
}
char::from_u32(u32::try_from(value).ok()?)?
} else {
let character = characters[index];
index += 1;
character
};
skip_space(&mut index);
if index >= characters.len() || characters[index] != '=' {
return None;
}
index += 1;
skip_space(&mut index);
if index >= characters.len() {
return None;
}
if characters[index].is_ascii_digit() {
let mut value = 0_i64;
while index < characters.len() && characters[index].is_ascii_digit() {
value = value * 10 + characters[index].to_digit(10)? as i64;
index += 1;
}
return Some((target, value, index));
}
// `\active` and friends are not modelled; consume the word and treat the
// target as active (13).
let mut word = String::new();
while index < characters.len() && characters[index].is_ascii_alphabetic() {
word.push(characters[index]);
index += 1;
}
if word == "active" {
Some((target, 13, index))
} else {
None
}
}
/// Model the catcode the engine understands: `@` is a letter only between
/// `\makeatletter` and `\makeatother`, and grouping restores the state. User
/// command names containing `@` are rewritten with a private-use placeholder
/// so later scanners still see one control word; route-D's own `\@...` names
@@ -5394,6 +5457,15 @@ fn canonicalize_at_catcodes(source: &str) -> String {
index = end;
continue;
}
"catcode" => {
if let Some((target, value, next)) = catcode_assignment(&characters, end) {
if target == '@' {
at_letter = value == 11;
index = next;
continue;
}
}
}
_ => {}
}
out.push('\\');
@@ -15410,6 +15482,29 @@ A definition.
assert!(!text.contains("makeatletter"), "{text}");
}
#[test]
fn catcode_assignments_toggle_at_letter() {
let source = "\\documentclass{article}\n\\begin{document}\n\n\\catcode`\\@=11\n\\def\\@foo{bar}\n\\@foo\n\n\\end{document}\n";
let json = preview_json(source).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("bar"), "{text}");
assert!(!text.contains("catcode"), "{text}");
assert!(!text.contains("@foo"), "{text}");
}
#[test]
fn runtime_definitions_accept_parameters() {
let source = "\\documentclass{article}\n\\begin{document}\n\n\\def\\add#1{[#1]}\\def\\pair#1,#2{(#1|#2)}\n\n\\add{x} and \\pair a,b\n\n\\end{document}\n";