Print tokens literally with string

\string<token> was unsupported, so documenting a control sequence expanded it
instead of printing it. The expand loop now reads the following token and emits
its characters without expansion; backslash and braces are replaced by
private-use placeholders that the renderer maps back to the real characters, so
the printed text cannot be re-tokenised and expanded by a later pass.

A preview test defines \foo, prints \string\foo, \string{ and \string}, and
checks the literal "\foo and { and }." with no expansion of \foo and no
warnings.
This commit is contained in:
gloamxun committed 2026-10-27 01:16:30 +08:00
1 parent 57424015de
commit 47dcdfec47
4 files changed
+54 -3

No files matched your search

+3
View File
@@ -392,6 +392,9 @@ fn is_math_letter(character: char) -> bool {
fn character_text(character: char) -> String { fn character_text(character: char) -> String {
match character { match character {
'\u{E023}' => "\\".to_owned(),
'\u{E024}' => "{".to_owned(),
'\u{E025}' => "}".to_owned(),
'\u{FB00}' => "ff".to_owned(), '\u{FB00}' => "ff".to_owned(),
'\u{FB01}' => "fi".to_owned(), '\u{FB01}' => "fi".to_owned(),
'\u{FB02}' => "fl".to_owned(), '\u{FB02}' => "fl".to_owned(),
+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). 1005 workspace tests are green and no oracle prefer route-D with a v1 fallback). 1006 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.
+4 -2
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 1005 tests (437 route-D unit, 378 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 1006 tests (437 route-D unit, 379 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
@@ -568,7 +568,9 @@ are:
`\scantokens{...}` replaces itself with the group text so later passes `\scantokens{...}` replaces itself with the group text so later passes
re-tokenise and expand it again. Token registers work in the common forms: re-tokenise and expand it again. Token registers work in the common forms:
`\newtoks\name`, `\name={...}`, `\toks0={...}` and `\the\toks0` / `\newtoks\name`, `\name={...}`, `\toks0={...}` and `\the\toks0` /
`\the\name` store and splice the register text. `\the\name` store and splice the register text. `\string<token>` prints the
token without expanding it, with backslash/braces carried through private-use
placeholders so they render but never re-tokenise.
Conditionals are evaluated after macro expansion with their operand tokens Conditionals are evaluated after macro expansion with their operand tokens
protected from expansion, then before register expansion. protected from expansion, then before register expansion.
- **Boxes**: `\sbox`/`\savebox` content and `\mbox`/`\hbox`/`\makebox` - **Boxes**: `\sbox`/`\savebox` content and `\mbox`/`\hbox`/`\makebox`
+46
View File
@@ -794,6 +794,24 @@ fn brace_depth_delta(line: &str) -> i32 {
depth depth
} }
/// `\string<token>` prints the token's characters without expanding it.
fn string_token(text: &str) -> Option<(String, usize)> {
let after = text.strip_prefix("\\string")?;
if after
.chars()
.next()
.is_some_and(|character| character.is_ascii_alphabetic())
{
return None;
}
let (token, used) = next_token(after)?;
let escaped = token
.replace('\\', "\u{E023}")
.replace('{', "\u{E024}")
.replace('}', "\u{E025}");
Some((escaped, "\\string".len() + used))
}
fn toks_register(text: &str) -> Option<(String, usize)> { fn toks_register(text: &str) -> Option<(String, usize)> {
let after = text.strip_prefix("\\toks")?; let after = text.strip_prefix("\\toks")?;
if after if after
@@ -1674,6 +1692,12 @@ fn expand_macros_mut(
changed = true; changed = true;
continue; continue;
} }
if let Some((text, used)) = string_token(rest) {
output.push_str(&text);
index += used;
changed = true;
continue;
}
if let Some((content, used)) = newtoks_declaration(rest) { if let Some((content, used)) = newtoks_declaration(rest) {
if !tokens.iter().any(|(key, _)| key == &content) { if !tokens.iter().any(|(key, _)| key == &content) {
tokens.push((content, String::new())); tokens.push((content, String::new()));
@@ -16003,6 +16027,28 @@ A definition.
assert!(!text.contains("makeatletter"), "{text}"); assert!(!text.contains("makeatletter"), "{text}");
} }
#[test]
fn string_prints_tokens_literally() {
let source = "\\documentclass{article}\n\\begin{document}\n\n\\def\\foo{bar}\n\n\\string\\foo and \\string{ and \\string}.\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("\\fooand{and}."), "{text}");
assert!(!text.contains("bar"), "{text}");
}
#[test] #[test]
fn image_saveboxes_measure_the_image() { fn image_saveboxes_measure_the_image() {
let mut images = HashMap::new(); let mut images = HashMap::new();