Print macro bodies with meaning

\meaning<token> was unsupported. Expansion now reads the following token and
prints its meaning literally: for a known macro, "macro:" plus its parameter
text (or #1..#n from the argument count) and "->" plus the stored body; for an
undefined control sequence, \relax; for a character, "the character <c>". The
text goes through the same private-use escaping as \string so later passes
cannot re-tokenise it.

A preview test defines \greet#1 and prints \meaning\greet plus
\meaning\missing, checking "macro:#1->Hello #1" and "\relax" with no warnings.
This commit is contained in:
gloamxun committed 2026-10-27 01:18:49 +08:00
1 parent 47dcdfec47
commit d791e3a0f2
3 files changed
+77 -7

No files matched your search

+72 -4
View File
@@ -805,11 +805,51 @@ fn string_token(text: &str) -> Option<(String, usize)> {
return None;
}
let (token, used) = next_token(after)?;
let escaped = token
.replace('\\', "\u{E023}")
Some((escape_literal(&token), "\\string".len() + used))
}
fn escape_literal(text: &str) -> String {
text.replace('\\', "\u{E023}")
.replace('{', "\u{E024}")
.replace('}', "\u{E025}");
Some((escaped, "\\string".len() + used))
.replace('}', "\u{E025}")
}
/// `\meaning<token>` prints the macro body (or a primitive stand-in) literally.
fn meaning_token(
text: &str,
runtime: &[MacroDefinition],
scopes: &[Vec<MacroDefinition>],
) -> Option<(String, usize)> {
let after = text.strip_prefix("\\meaning")?;
if after
.chars()
.next()
.is_some_and(|character| character.is_ascii_alphabetic())
{
return None;
}
let (token, used) = next_token(after)?;
let meaning = if token.starts_with('\\') {
let definition = scopes
.iter()
.rev()
.find_map(|scope| scope.iter().rev().find(|known| known.name == token))
.or_else(|| runtime.iter().find(|known| known.name == token));
match definition {
Some(definition) => {
let params = definition.params.clone().unwrap_or_else(|| {
(1..=definition.args)
.map(|index| format!("#{index}"))
.collect()
});
format!("macro:{}->{}", params, definition.body)
}
None => "\\relax".to_string(),
}
} else {
format!("the character {}", token)
};
Some((escape_literal(&meaning), "\\meaning".len() + used))
}
fn toks_register(text: &str) -> Option<(String, usize)> {
@@ -1698,6 +1738,12 @@ fn expand_macros_mut(
changed = true;
continue;
}
if let Some((text, used)) = meaning_token(rest, &runtime, &scopes) {
output.push_str(&text);
index += used;
changed = true;
continue;
}
if let Some((content, used)) = newtoks_declaration(rest) {
if !tokens.iter().any(|(key, _)| key == &content) {
tokens.push((content, String::new()));
@@ -16027,6 +16073,28 @@ A definition.
assert!(!text.contains("makeatletter"), "{text}");
}
#[test]
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 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("macro:#1-&gt;Hello#1"), "{text}");
assert!(text.contains("\\relax"), "{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";