Queue aftergroup tokens until the group closes

\aftergroup was unsupported, so class-style deferred setup leaked. Expansion
now keeps a parallel stack of pending token lists: '{' and \begingroup push an
empty list, '}' and \endgroup pop it and append its tokens after the group (the
closing brace is emitted first, then the pending tokens with the command-end
marker so a control word cannot merge with the following text).
\aftergroup<token> queues one token and \aftergroup{...} queues the group body.

A test defines a group-local \a while queueing \aftergroup\a, then checks that
the queued \a runs after the group restores A, giving "AA and !X" with no
warnings.
This commit is contained in:
gloamxun committed 2026-10-27 00:59:19 +08:00
1 parent 9d10def2f5
commit 24d5390d25
3 files changed
+79 -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). 999 workspace tests are green and no oracle
prefer route-D with a v1 fallback). 1000 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.
+6 -4
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 999 tests (437 route-D unit, 372 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 1000 tests (437 route-D unit, 373 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
@@ -551,9 +551,11 @@ are:
`\csname ... \endcsname` (also inside ordinary macro bodies) expands its
contents and resolves the named macro, yielding nothing when undefined.
`\futurelet\alias\command <token>` binds the looked-ahead token to the
alias without consuming it; conditionals are evaluated after macro expansion
with their operand tokens protected from expansion, then before register
expansion.
alias without consuming it, and `\aftergroup<token>` (or
`\aftergroup{...}`) queues its token until the enclosing `{}` or
`\begingroup` closes, then injects it after the group. 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`
bodies are inserted as one unbreakable inline box (interword spaces become
fixed-width boxes), so `\usebox` no longer reflows across lines. Savebox
+72
View File
@@ -793,6 +793,29 @@ fn brace_depth_delta(line: &str) -> i32 {
depth
}
/// Parse `\aftergroup<token>` (or `\aftergroup{...}`) into the text that should
/// run once the current group closes.
fn aftergroup_tokens(text: &str) -> Option<(String, usize)> {
let after = text.strip_prefix("\\aftergroup")?;
if after
.chars()
.next()
.is_some_and(|character| character.is_ascii_alphabetic())
{
return None;
}
let (token, used) = next_token(after)?;
if token == "{" {
let brace_start = used - 1;
let (content, group_used) = braced_group(&after[brace_start..])?;
return Some((
content.to_string(),
"\\aftergroup".len() + brace_start + group_used,
));
}
Some((token, "\\aftergroup".len() + used))
}
/// Copy a conditional command together with the operand tokens it inspects,
/// so macro expansion cannot consume them before the conditional is evaluated.
fn protected_conditional_prefix(text: &str) -> Option<(String, usize)> {
@@ -1510,6 +1533,7 @@ fn expand_macros_mut(source: &str, macros: &mut Vec<MacroDefinition>) -> String
let mut index = 0;
let mut changed = false;
let mut scopes: Vec<Vec<MacroDefinition>> = Vec::new();
let mut after_groups: Vec<Vec<String>> = Vec::new();
while index < text.len() {
let rest = &text[index..];
if let Some((prefix, used)) = protected_conditional_prefix(rest) {
@@ -1538,6 +1562,16 @@ fn expand_macros_mut(source: &str, macros: &mut Vec<MacroDefinition>) -> String
changed = true;
continue;
}
if let Some((tokens, used)) = aftergroup_tokens(rest) {
if let Some(pending) = after_groups.last_mut() {
pending.push(tokens);
} else {
output.push_str(&tokens);
}
index += used;
changed = true;
continue;
}
if let Some((alias, target, command_start)) = futurelet_lookahead(rest) {
let definition = MacroDefinition {
name: alias,
@@ -1571,12 +1605,19 @@ fn expand_macros_mut(source: &str, macros: &mut Vec<MacroDefinition>) -> String
}
if rest.starts_with(r"\begingroup") {
scopes.push(Vec::new());
after_groups.push(Vec::new());
index += r"\begingroup".len();
changed = true;
continue;
}
if rest.starts_with(r"\endgroup") {
scopes.pop();
if let Some(tokens) = after_groups.pop() {
for tokens in tokens {
output.push_str(&tokens);
output.push('\u{E022}');
}
}
index += r"\endgroup".len();
changed = true;
continue;
@@ -1658,10 +1699,19 @@ fn expand_macros_mut(source: &str, macros: &mut Vec<MacroDefinition>) -> String
let character = rest.chars().next().expect("non-empty tail");
if character == '{' {
scopes.push(Vec::new());
after_groups.push(Vec::new());
} else if character == '}' {
scopes.pop();
}
output.push(character);
if character == '}' {
if let Some(tokens) = after_groups.pop() {
for tokens in tokens {
output.push_str(&tokens);
output.push('\u{E022}');
}
}
}
index += character.len_utf8();
}
text = output;
@@ -15669,6 +15719,28 @@ A definition.
assert!(!text.contains("makeatletter"), "{text}");
}
#[test]
fn aftergroup_runs_tokens_at_group_end() {
let source = "\\documentclass{article}\n\\begin{document}\n\n\\def\\a{A}{\\def\\a{B}\\aftergroup\\a}\\a and {\\aftergroup{!}}X\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("AAand!X"), "{text}");
assert!(!text.contains("aftergroup"), "{text}");
}
#[test]
fn futurelet_peeks_without_consuming() {
let source = "\\documentclass{article}\n\\begin{document}\n\n\\def\\shownext{[\\next]}\\futurelet\\next\\shownext x\n\n\\def\\yes{Y}\\def\\no{N}\\def\\pick{\\futurelet\\next\\pickii}\\def\\pickii{\\ifx\\next x\\yes\\else\\no\\fi}\n\n\\pick x\n\n\\end{document}\n";