Add expanded, unexpanded and detokenize

Three expansion primitives class files use were unsupported. \expanded{...}
runs the argument through the current macro table and scopes immediately;
\unexpanded{...} passes the text through unchanged (normal typesetting
semantics; the edef freeze is not modelled); \detokenize{...} prints the text
literally through the same private-use escaping as \string.

A preview test expands \a, passes \a through unexpanded and detokenizes it,
checking "Hi and Hi and \\a." with no warnings.
This commit is contained in:
gloamxun committed 2026-10-27 01:41:52 +08:00
1 parent 28aed153fe
commit 8bdeffa646
3 files changed
+64 -4

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). 1014 workspace tests are green and no oracle
prefer route-D with a v1 fallback). 1015 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 1014 tests (437 route-D unit, 386 engine binary unit, 10 route-D integration, 42 oracle, 71 v1 integration, 63 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 1015 tests (437 route-D unit, 386 engine binary unit, 10 route-D integration, 42 oracle, 71 v1 integration, 63 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
@@ -520,7 +520,7 @@ deliberately open rather than approximated:
## Limits and remaining gaps
The suite currently stands at 1014 passing tests, with the workspace clean.
The suite currently stands at 1015 passing tests, with the workspace clean.
Route-D serves both flat `/preview` and project preview/PDF requests by default
(automatic v1 fallback; `?engine=v1` or `TEXRRA_ENGINE=v1` opts out). The
objective's areas are implemented to the limits below; complex-script shaping is
@@ -576,7 +576,9 @@ are:
token without expanding it, with backslash/braces carried through private-use
placeholders so they render but never re-tokenise. `\meaning<token>` prints
`macro:<params>-><body>` for a macro (or `\relax` for an undefined control
sequence) with the same literal escaping.
sequence) with the same literal escaping. `\expanded{...}` expands its
argument immediately, `\unexpanded{...}` passes the text through, and
`\detokenize{...}` prints it literally.
Conditionals are evaluated after macro expansion with their operand tokens
protected from expansion, then before register expansion.
- **Boxes**: `\sbox`/`\savebox` content and `\mbox`/`\hbox`/`\makebox`
+58
View File
@@ -794,6 +794,21 @@ fn brace_depth_delta(line: &str) -> i32 {
depth
}
fn command_argument(text: &str, command: &str) -> Option<(String, usize)> {
let after = text.strip_prefix(command)?;
if after
.chars()
.next()
.is_some_and(|character| character.is_ascii_alphabetic())
{
return None;
}
let trimmed = after.trim_start();
let skipped = after.len() - trimmed.len();
let (body, used) = braced_group(trimmed)?;
Some((body.to_string(), command.len() + skipped + used))
}
/// `\string<token>` prints the token's characters without expanding it.
fn string_token(text: &str) -> Option<(String, usize)> {
let after = text.strip_prefix("\\string")?;
@@ -1732,6 +1747,28 @@ fn expand_macros_mut(
changed = true;
continue;
}
if let Some((body, used)) = command_argument(rest, "\\expanded") {
let mut table = runtime.clone();
for scope in &scopes {
table.extend(scope.iter().cloned());
}
output.push_str(&expand_macros(&body, &table));
index += used;
changed = true;
continue;
}
if let Some((body, used)) = command_argument(rest, "\\unexpanded") {
output.push_str(&body);
index += used;
changed = true;
continue;
}
if let Some((body, used)) = command_argument(rest, "\\detokenize") {
output.push_str(&escape_literal(&body));
index += used;
changed = true;
continue;
}
if let Some((text, used)) = string_token(rest) {
output.push_str(&text);
index += used;
@@ -16268,6 +16305,27 @@ A definition.
assert!(!text.contains("makeatletter"), "{text}");
}
#[test]
fn expanded_unexpanded_and_detokenize_work() {
let source = "\\documentclass{article}\n\\begin{document}\n\n\\def\\a{Hi}\\expanded{\\a} and \\unexpanded{\\a} and \\detokenize{\\a}.\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("HiandHiand\\a."), "{text}");
}
#[test]
fn parbox_orcid_and_hrule_are_handled() {
let source = "\\documentclass{article}\n\\begin{document}\n\n\\parbox{60mm}{Parbox words} and \\orcidlink{0000-0002-1825-0097}.\n\n\\hrule\n\nAfter.\n\n\\end{document}\n";