Expand the common LaTeX internal commands

This commit is contained in:
gloamxun committed 2026-10-26 02:14:42 +08:00
1 parent ded738d445
commit 676a6976f8
4 files changed
+145 -9

No files matched your search

+141 -5
View File
@@ -342,9 +342,10 @@ fn environment_definition(line: &str) -> Option<EnvironmentDefinition> {
fn control_sequence(text: &str) -> Option<(String, usize)> {
let after_slash = text.strip_prefix('\\')?;
let first = after_slash.chars().next()?;
let length = if first.is_ascii_alphabetic() {
let letter = |character: char| character.is_ascii_alphabetic() || character == '@';
let length = if letter(first) {
after_slash
.find(|character: char| !character.is_ascii_alphabetic())
.find(|character: char| !letter(character))
.unwrap_or(after_slash.len())
} else {
first.len_utf8()
@@ -638,10 +639,95 @@ fn expand_macro_at(text: &str, macros: &[MacroDefinition]) -> Option<(String, us
Some((expanded, 1 + length + consumed + used))
}
fn expand_macros(source: &str, macros: &[MacroDefinition]) -> String {
if macros.is_empty() {
return source.to_string();
/// Expand the small set of LaTeX internal commands used by class and package
/// files. Returns the replacement text and the bytes consumed.
fn latex_internal_at(rest: &str, macros: &[MacroDefinition]) -> Option<(String, usize)> {
let boundary = |after: &str| {
after
.chars()
.next()
.is_none_or(|character| !(character.is_ascii_alphabetic() || character == '@'))
};
if let Some(after) = rest.strip_prefix("\\@empty") {
if boundary(after) {
return Some((String::new(), "\\@empty".len()));
}
}
if let Some(after) = rest.strip_prefix("\\@nameuse") {
if boundary(after) {
let skipped = after.len() - after.trim_start().len();
let after = after.trim_start();
let (inner, used) = braced_group(after)?;
return Some((
format!("\\{}", inner.trim().trim_start_matches('\\')),
"\\@nameuse".len() + skipped + used,
));
}
}
if let Some(after) = rest.strip_prefix("\\@ifundefined") {
if boundary(after) {
let mut offset = "\\@ifundefined".len();
let mut cursor = after;
let skipped = cursor.len() - cursor.trim_start().len();
offset += skipped;
cursor = cursor.trim_start();
let (name, used) = braced_group(cursor)?;
offset += used;
cursor = &cursor[used..];
let skipped = cursor.len() - cursor.trim_start().len();
offset += skipped;
cursor = cursor.trim_start();
let (true_branch, used) = braced_group(cursor)?;
offset += used;
cursor = &cursor[used..];
let skipped = cursor.len() - cursor.trim_start().len();
offset += skipped;
cursor = cursor.trim_start();
let (false_branch, used) = braced_group(cursor)?;
offset += used;
let name = name.trim();
let full = if name.starts_with('\\') {
name.to_string()
} else {
format!("\\{}", name)
};
let defined = macros.iter().any(|definition| definition.name == full);
let chosen = if defined { false_branch } else { true_branch };
return Some((chosen.to_string(), offset));
}
}
for (command, pick) in [
("\\@firstofone", 0_usize),
("\\@firstoftwo", 0_usize),
("\\@secondoftwo", 1_usize),
] {
if let Some(after) = rest.strip_prefix(command) {
if boundary(after) {
let mut offset = command.len();
let mut cursor = after;
let skipped = cursor.len() - cursor.trim_start().len();
offset += skipped;
cursor = cursor.trim_start();
let (first, used) = braced_group(cursor)?;
offset += used;
if command == "\\@firstofone" {
return Some((first.to_string(), offset));
}
cursor = &cursor[used..];
let skipped = cursor.len() - cursor.trim_start().len();
offset += skipped;
cursor = cursor.trim_start();
let (second, used) = braced_group(cursor)?;
offset += used;
let chosen = if pick == 0 { first } else { second };
return Some((chosen.to_string(), offset));
}
}
}
None
}
fn expand_macros(source: &str, macros: &[MacroDefinition]) -> String {
let mut text = source.to_string();
for _ in 0..8 {
let mut output = String::with_capacity(text.len());
@@ -713,6 +799,12 @@ fn expand_macros(source: &str, macros: &[MacroDefinition]) -> String {
}
}
}
if let Some((expanded, used)) = latex_internal_at(rest, macros) {
output.push_str(&expanded);
index += used;
changed = true;
continue;
}
if let Some((expanded, used)) = expand_macro_at(rest, macros) {
output.push_str(&expanded);
index += used;
@@ -1659,6 +1751,22 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
}
continue;
}
if let Some(rest) = trimmed.strip_prefix("\\@namedef") {
let rest = rest.trim_start();
if let Some((name, used)) = braced_group(rest) {
let rest = rest[used..].trim_start();
if let Some((body, _)) = braced_group(rest) {
let name = name.trim().trim_start_matches('\\');
geometry.macros.push(MacroDefinition {
name: format!("\\{}", name),
args: 0,
default: None,
body: body.to_string(),
});
continue;
}
}
}
if trimmed.starts_with("\\newcommand")
|| trimmed.starts_with("\\renewcommand")
|| trimmed.starts_with("\\providecommand")
@@ -8634,6 +8742,34 @@ a & b
assert_eq!(body.trim(), "yesA");
}
#[test]
fn latex_internal_first_of_two_picks_arguments() {
let (body, _) =
geometry_and_body("\\@firstoftwo{A}{B} \\@secondoftwo{C}{D} \\@firstofone{E}");
assert_eq!(body.trim(), "A D E");
}
#[test]
fn at_namedef_and_nameuse_share_macros() {
let (body, geometry) = geometry_and_body("\\@namedef{inner}{Z}\n\nBody \\@nameuse{inner}.");
assert_eq!(body.trim(), "Body Z.");
assert!(
geometry
.macros
.iter()
.any(|definition| definition.name == "\\inner" && definition.body == "Z"),
"named macro recorded"
);
}
#[test]
fn at_ifundefined_chooses_its_branch() {
let (body, _) = geometry_and_body(
"\\@namedef{known}{}\n\nFirst \\@ifundefined{known}{no}{yes}, second \\@ifundefined{other}{no}{yes}.",
);
assert_eq!(body.trim(), "First yes, second no.");
}
#[test]
fn page_numbers_follow_the_page_counter() {
let offset = preview_json("\\setcounter{page}{5}\n\nAlpha\n\n\\newpage\n\nBeta")