Expand parameterized runtime definitions

runtime_definition only accepted \def\name{body}: if the first token after the
name was not '{' it gave up, leaving a body-embedded \def\foo#1{...} to leak as
text. Parse the parameter text before the body with the same helpers the line
capture uses: definition_argument_count for undelimited #1..#n, otherwise
parameter_placeholders plus the raw parameter text for delimited forms. The
returned MacroDefinition carries args/params, so expand_macro_lookup collects
the arguments during expansion.

A preview test defines \add#1 and \pair#1,#2 mid-body and checks "[x]" and
"(a|b)" with no warnings.
This commit is contained in:
gloamxun committed 2026-10-27 00:43:51 +08:00
1 parent 619eb19f72
commit b056b11ba9
3 files changed
+40 -10

No files matched your search

+35 -7
View File
@@ -871,19 +871,25 @@ fn runtime_definition(text: &str) -> Option<(MacroDefinition, usize, bool)> {
let (name, name_used) = control_sequence(trimmed)?;
let after_name = trimmed[name_used..].trim_start();
let brace_skipped = trimmed[name_used..].len() - after_name.len();
if !after_name.starts_with('{') {
return None;
}
let (body, body_used) = braced_group(after_name)?;
let open = after_name.find('{')?;
let params_text = after_name[..open].trim();
let (args, params) = match definition_argument_count(params_text) {
Some(args) => (args, None),
None => (
parameter_placeholders(params_text)?,
Some(params_text.to_string()),
),
};
let (body, body_used) = braced_group(&after_name[open..])?;
Some((
MacroDefinition {
name: format!("\\{}", name.trim_start_matches('\\')),
args: 0,
args,
default: None,
params: None,
params,
body: body.to_string(),
},
used + skipped + name_used + brace_skipped + body_used,
used + skipped + name_used + brace_skipped + open + body_used,
global,
))
}
@@ -15404,6 +15410,28 @@ A definition.
assert!(!text.contains("makeatletter"), "{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";
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("[x]"), "{text}");
assert!(text.contains("(a|b)"), "{text}");
}
#[test]
fn fontspec_families_map_to_engine_faces() {
let source = "\\documentclass{article}\n\\usepackage{fontspec}\n\\setmainfont{Liberation Serif}\n\\setsansfont{Liberation Sans}\n\\newfontfamily\\headingfont[Ligatures=TeX]{Liberation Sans}\n\\begin{document}\n\n\\headingfont Sans words.\n\n\\end{document}\n";