Run let/chardef and keep group definitions local
Runtime expansion only understood \def/\gdef. Add \let\alias=\target (a macro
body that expands to the target) and \chardef\name=<code> (a one-character
body), both honoring the current scope, so class-style aliases work and can be
shadowed inside a group.
Line-based capture also still pulled a definition line out of a group and made
it global. Track brace depth across body lines and only capture at depth zero,
and restrict strip_page_geometry's definition capture to the preamble before
\begin{document}; body lines now reach runtime expansion where the scope stack
applies.
Tests preview a group-local \def on its own line as "twoone" and
\let/\chardef as "HiandA".
This commit is contained in:
1 parent
d1b66af251
commit
9aa743b601
3 files changed
+145
-13
No files matched your search
+138
-9
@@ -768,6 +768,87 @@ fn upsert_macro(table: &mut Vec<MacroDefinition>, definition: MacroDefinition) {
|
||||
}
|
||||
}
|
||||
|
||||
fn brace_depth_delta(line: &str) -> i32 {
|
||||
let mut depth = 0_i32;
|
||||
let mut escaped = false;
|
||||
for character in line.chars() {
|
||||
if escaped {
|
||||
escaped = false;
|
||||
continue;
|
||||
}
|
||||
match character {
|
||||
'\\' => escaped = true,
|
||||
'{' => depth += 1,
|
||||
'}' => depth -= 1,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
depth
|
||||
}
|
||||
|
||||
/// Runtime `\let\alias=\target` and `\chardef\name=<code>` definitions.
|
||||
fn runtime_plain_definition(text: &str) -> Option<(MacroDefinition, usize)> {
|
||||
let (command, used) = control_sequence(text)?;
|
||||
let rest = &text[used..];
|
||||
let trimmed = rest.trim_start();
|
||||
let skipped = rest.len() - trimmed.len();
|
||||
let (name, name_used) = control_sequence(trimmed)?;
|
||||
let after_name = trimmed[name_used..].trim_start();
|
||||
let name_gap = trimmed[name_used..].len() - after_name.len();
|
||||
match command.as_str() {
|
||||
"\\let" => {
|
||||
let after = after_name
|
||||
.strip_prefix('=')
|
||||
.map(str::trim_start)
|
||||
.unwrap_or(after_name);
|
||||
let eq_skipped = after_name.len() - after.len();
|
||||
let (target, target_used) = if let Some((target, target_used)) = control_sequence(after)
|
||||
{
|
||||
(target, target_used)
|
||||
} else {
|
||||
let character = after.chars().next()?;
|
||||
(character.to_string(), character.len_utf8())
|
||||
};
|
||||
Some((
|
||||
MacroDefinition {
|
||||
name: format!("\\{}", name.trim_start_matches('\\')),
|
||||
args: 0,
|
||||
default: None,
|
||||
params: None,
|
||||
body: target,
|
||||
},
|
||||
used + skipped + name_used + name_gap + eq_skipped + target_used,
|
||||
))
|
||||
}
|
||||
"\\chardef" => {
|
||||
let after = after_name
|
||||
.strip_prefix('=')
|
||||
.map(str::trim_start)
|
||||
.unwrap_or(after_name);
|
||||
let eq_skipped = after_name.len() - after.len();
|
||||
let digits: String = after
|
||||
.chars()
|
||||
.take_while(|character| character.is_ascii_digit())
|
||||
.collect();
|
||||
if digits.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let value: u32 = digits.parse().ok()?;
|
||||
Some((
|
||||
MacroDefinition {
|
||||
name: format!("\\{}", name.trim_start_matches('\\')),
|
||||
args: 0,
|
||||
default: None,
|
||||
params: None,
|
||||
body: char::from_u32(value)?.to_string(),
|
||||
},
|
||||
used + skipped + name_used + name_gap + eq_skipped + digits.len(),
|
||||
))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse a simple runtime `\def\name{body}` / `\gdef\name{body}` and return
|
||||
/// the definition, bytes consumed and whether it is global.
|
||||
fn runtime_definition(text: &str) -> Option<(MacroDefinition, usize, bool)> {
|
||||
@@ -1283,6 +1364,16 @@ fn expand_macros(source: &str, macros: &[MacroDefinition]) -> String {
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
if let Some((definition, used)) = runtime_plain_definition(rest) {
|
||||
if scopes.is_empty() {
|
||||
upsert_macro(&mut runtime, definition);
|
||||
} else if let Some(scope) = scopes.last_mut() {
|
||||
upsert_macro(scope, definition);
|
||||
}
|
||||
index += used;
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
if rest.starts_with(r"\begingroup") {
|
||||
scopes.push(Vec::new());
|
||||
index += r"\begingroup".len();
|
||||
@@ -2231,8 +2322,12 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
|
||||
let mut geometry = PageGeometry::default();
|
||||
let mut body = String::new();
|
||||
let mut tabular: Option<(String, String, &'static str, Option<i64>, usize)> = None;
|
||||
let mut in_document = false;
|
||||
for line in source.lines() {
|
||||
let trimmed = line.trim();
|
||||
if trimmed.contains("\\begin{document}") {
|
||||
in_document = true;
|
||||
}
|
||||
if let Some((_, text, environment, _, depth)) = tabular.as_mut() {
|
||||
let end = format!("\\end{{{environment}}}");
|
||||
let closed = trimmed.strip_suffix(&end);
|
||||
@@ -2553,12 +2648,13 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
|
||||
|| rest.chars().next().is_some_and(char::is_whitespace)
|
||||
})
|
||||
};
|
||||
if is_macro_command("\\newcommand")
|
||||
|| is_macro_command("\\renewcommand")
|
||||
|| is_macro_command("\\DeclareRobustCommand")
|
||||
|| is_macro_command("\\providecommand")
|
||||
|| is_macro_command("\\def")
|
||||
|| is_macro_command("\\gdef")
|
||||
if !in_document
|
||||
&& (is_macro_command("\\newcommand")
|
||||
|| is_macro_command("\\renewcommand")
|
||||
|| is_macro_command("\\DeclareRobustCommand")
|
||||
|| is_macro_command("\\providecommand")
|
||||
|| is_macro_command("\\def")
|
||||
|| is_macro_command("\\gdef"))
|
||||
{
|
||||
if is_macro_command("\\renewcommand")
|
||||
&& let Some(width) = renewcommand_length(definition_line, "headrulewidth")
|
||||
@@ -4803,7 +4899,13 @@ fn capture_body_definitions(
|
||||
) {
|
||||
let mut kept = String::new();
|
||||
let mut changed = false;
|
||||
let mut depth = 0_i32;
|
||||
let mut depths = Vec::new();
|
||||
for line in body.lines() {
|
||||
depths.push(depth);
|
||||
depth += brace_depth_delta(line);
|
||||
}
|
||||
for (line, depth) in body.lines().zip(depths) {
|
||||
let trimmed = line.trim_start();
|
||||
let definition_line = strip_definition_prefixes(trimmed);
|
||||
if trimmed.starts_with("\\newenvironment") || trimmed.starts_with("\\renewenvironment") {
|
||||
@@ -4831,19 +4933,24 @@ fn capture_body_definitions(
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
if let Some(definition) = macro_definition(definition_line)
|
||||
if depth == 0
|
||||
&& let Some(definition) = macro_definition(definition_line)
|
||||
&& definition_consumes_line(definition_line)
|
||||
{
|
||||
macros.push(definition);
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
if let Some(definition) = char_definition(definition_line) {
|
||||
if depth == 0
|
||||
&& let Some(definition) = char_definition(definition_line)
|
||||
{
|
||||
macros.push(definition);
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
if let Some((name, target)) = macro_alias(definition_line) {
|
||||
if depth == 0
|
||||
&& let Some((name, target)) = macro_alias(definition_line)
|
||||
{
|
||||
let source = macros
|
||||
.iter()
|
||||
.find(|definition| definition.name == target)
|
||||
@@ -14884,6 +14991,28 @@ A definition.
|
||||
assert!(grouped.contains("twoone"), "{grouped}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_lines_and_runtime_aliases() {
|
||||
let text_of = |source: &str| -> String {
|
||||
let json = preview_json(source).expect("preview");
|
||||
let value: serde_json::Value = serde_json::from_str(&json).expect("JSON");
|
||||
let svg = value["pages"][0]["svg"].as_str().expect("svg");
|
||||
svg.split('>')
|
||||
.filter_map(|piece| piece.split('<').next())
|
||||
.collect::<String>()
|
||||
.split_whitespace()
|
||||
.collect()
|
||||
};
|
||||
let grouped = text_of(
|
||||
"\\documentclass{article}\n\\begin{document}\n\n\\def\\a{one}\n{\n\\def\\a{two}\n\\a\n}\n\\a\n\n\\end{document}\n",
|
||||
);
|
||||
assert!(grouped.contains("twoone"), "{grouped}");
|
||||
let aliased = text_of(
|
||||
"\\documentclass{article}\n\\begin{document}\n\n\\def\\b{Hi}\\let\\c=\\b\\c and \\chardef\\d=65\\d\n\n\\end{document}\n",
|
||||
);
|
||||
assert!(aliased.contains("HiandA"), "{aliased}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_definitions_and_makeatletter_expand() {
|
||||
let source = "\\documentclass{article}\n\\begin{document}\n\n\\makeatletter\\def\\@foo{bar}\\makeatother\\@foo and \\def\\greet{Hello}\\greet.\n\n\\end{document}\n";
|
||||
|
||||
Reference in new issue
Block a user