Capture inline definitions and @ control words

The line-based capture treated any line that began with a definition command as
a definition and dropped the rest of the line, so
\makeatletter\def\@foo{bar}\makeatother\@foo lost everything after the body.
Only consume such a line when the definition actually ends it; otherwise leave
it for a new inline pass that captures simple \def\name{body} forms anywhere in
running text.

\makeatletter/\makeatother are stripped as no-ops and the macro expander now
scans @ as a letter, matching control_sequence, so \@foo expands to its body.

A test defines \@foo and \greet in one body line and checks the previewed text
"bar and Hello." with no warnings. Group scoping, catcode state and a token
stream remain open.
This commit is contained in:
gloamxun committed 2026-10-27 00:02:54 +08:00
1 parent def93b6cf5
commit 7547c0abc4
3 files changed
+160 -8

No files matched your search

+152 -3
View File
@@ -763,7 +763,7 @@ fn expand_links_line(line: &str) -> String {
fn expand_macro_at(text: &str, macros: &[MacroDefinition]) -> Option<(String, usize)> {
let after_slash = text.strip_prefix('\\')?;
let length = after_slash
.find(|character: char| !character.is_ascii_alphabetic())
.find(|character: char| !character.is_ascii_alphabetic() && character != '@')
.unwrap_or(after_slash.len());
if length == 0 {
return None;
@@ -2477,7 +2477,11 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
geometry.head_rule_width = Some(width);
continue;
}
if let Some(definition) = macro_definition(definition_line) {
// Only consume the line when the definition ends it; otherwise
// inline capture handles a definition embedded in running text.
if let Some(definition) = macro_definition(definition_line)
&& definition_consumes_line(definition_line)
{
let provided = definition_line.trim_start().starts_with("\\providecommand");
if !provided
|| !geometry
@@ -2487,8 +2491,8 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
{
geometry.macros.push(definition);
}
continue;
}
continue;
}
if trimmed.starts_with(r"\bibliographystyle") || trimmed.starts_with(r"\bibliography{") {
let rest = trimmed
@@ -4644,6 +4648,122 @@ fn capture_body_registers(
}
}
/// Capture simple `\def\name{body}` definitions that appear in running body
/// text (not at the start of a line). Parameterised forms stay with the
/// line-based capture until the token engine models grouping.
fn capture_inline_definitions(body: &mut String, macros: &mut Vec<MacroDefinition>) {
let mut out = String::new();
let mut rest = body.as_str();
let mut changed = false;
while let Some(position) = rest.find("\\def") {
let after = &rest[position + "\\def".len()..];
let boundary = after
.chars()
.next()
.is_none_or(|character| !character.is_ascii_alphabetic());
if !boundary {
out.push_str(&rest[..position + "\\def".len()]);
rest = after;
continue;
}
let trimmed = after.trim_start();
let Some((name, used)) = control_sequence(trimmed) else {
out.push_str(&rest[..position + "\\def".len()]);
rest = after;
continue;
};
let after_name = trimmed[used..].trim_start();
if !after_name.starts_with('{') {
out.push_str(&rest[..position + "\\def".len()]);
rest = after;
continue;
}
let Some((content, body_used)) = braced_group(after_name) else {
out.push_str(&rest[..position + "\\def".len()]);
rest = after;
continue;
};
out.push_str(&rest[..position]);
let name = format!("\\{}", name.trim_start_matches('\\'));
if let Some(existing) = macros.iter_mut().find(|m| m.name == name) {
existing.body = content.to_string();
existing.params = None;
existing.args = 0;
} else {
macros.push(MacroDefinition {
name,
args: 0,
default: None,
params: None,
body: content.to_string(),
});
}
rest = &after_name[body_used..];
changed = true;
}
out.push_str(rest);
if changed {
*body = out;
}
}
/// Whether a definition command consumes its whole line (ignoring trailing
/// whitespace). Embedded definitions are left for the inline pass.
fn definition_consumes_line(line: &str) -> bool {
let line = line.trim();
let Some((command, used)) = control_sequence(line) else {
return false;
};
let rest = &line[used..];
match command.as_str() {
"\\def" | "\\gdef" | "\\edef" | "\\xdef" => {
let trimmed = rest.trim_start();
let Some((_name, name_used)) = control_sequence(trimmed) else {
return false;
};
let after_name = &trimmed[name_used..];
let Some(brace) = after_name.find('{') else {
return false;
};
let Some((_body, body_used)) = braced_group(&after_name[brace..]) else {
return false;
};
after_name[brace + body_used..].trim().is_empty()
}
"\\newcommand" | "\\renewcommand" | "\\DeclareRobustCommand" | "\\providecommand" => {
let mut rest = rest.trim_start();
if let Some(stripped) = rest.strip_prefix('*') {
rest = stripped.trim_start();
}
let after_name = if let Some(stripped) = rest.strip_prefix('{') {
let Some(close) = stripped.find('}') else {
return false;
};
&stripped[close + 1..]
} else {
let Some((_name, name_used)) = control_sequence(rest) else {
return false;
};
&rest[name_used..]
};
let mut rest = after_name.trim_start();
for _ in 0..2 {
if let Some(stripped) = rest.strip_prefix('[') {
let Some((_option, tail)) = stripped.split_once(']') else {
return false;
};
rest = tail.trim_start();
}
}
let Some((_body, body_used)) = braced_group(rest) else {
return false;
};
rest[body_used..].trim().is_empty()
}
_ => false,
}
}
fn capture_body_definitions(
body: &mut String,
macros: &mut Vec<MacroDefinition>,
@@ -4918,6 +5038,10 @@ fn geometry_and_body(source: &str) -> (String, PageGeometry) {
&mut geometry.theorem_definitions,
&mut geometry.environments,
);
capture_inline_definitions(&mut body, &mut geometry.macros);
body = body
.replace("\\makeatletter", "")
.replace("\\makeatother", "");
body = expand_environments(&body, &geometry.environments);
body = expand_keywords(&body);
body = drop_bibliography_commands(&body);
@@ -14668,6 +14792,31 @@ A definition.
assert!(!text.contains('?'), "{text}");
}
#[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";
let json = preview_json(source).expect("preview");
let value: serde_json::Value = serde_json::from_str(&json).expect("JSON");
assert_eq!(value["status"], "ok");
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("bar"), "{text}");
assert!(text.contains("Hello"), "{text}");
assert!(!text.contains("def"), "{text}");
assert!(!text.contains("makeatletter"), "{text}");
}
#[test]
fn nested_tables_keep_the_outer_structure() {
let source = r"\begin{tabular}{ll}