Choose branches with @ifstar and @ifnextchar

This commit is contained in:
gloamxun committed 2026-10-26 02:46:15 +08:00
1 parent 7e3877df98
commit 352c44a9b1
4 files changed
+81 -4

No files matched your search

+77
View File
@@ -734,6 +734,69 @@ fn latex_internal_at(rest: &str, macros: &[MacroDefinition]) -> Option<(String,
}
}
}
if let Some(after) = rest.strip_prefix("\\@ifstar") {
if boundary(after) {
let mut offset = "\\@ifstar".len();
let mut cursor = after;
let skipped = cursor.len() - cursor.trim_start().len();
offset += skipped;
cursor = cursor.trim_start();
let (starred, used) = braced_group(cursor)?;
offset += used;
cursor = &cursor[used..];
let skipped = cursor.len() - cursor.trim_start().len();
offset += skipped;
cursor = cursor.trim_start();
let (plain, used) = braced_group(cursor)?;
offset += used;
if cursor[used..].starts_with('*') {
return Some((starred.to_string(), offset + 1));
}
return Some((plain.to_string(), offset));
}
}
if let Some(after) = rest.strip_prefix("\\@ifnextchar") {
if boundary(after) {
let mut offset = "\\@ifnextchar".len();
let mut cursor = after;
let skipped = cursor.len() - cursor.trim_start().len();
offset += skipped;
cursor = cursor.trim_start();
let target = if let Some((command, used)) = control_sequence(cursor) {
offset += used;
cursor = &cursor[used..];
(true, command)
} else {
let character = cursor.chars().next()?;
offset += character.len_utf8();
cursor = &cursor[character.len_utf8()..];
(false, character.to_string())
};
let skipped = cursor.len() - cursor.trim_start().len();
offset += skipped;
cursor = cursor.trim_start();
let (matched, used) = braced_group(cursor)?;
offset += used;
cursor = &cursor[used..];
let skipped = cursor.len() - cursor.trim_start().len();
offset += skipped;
cursor = cursor.trim_start();
let (unmatched, used) = braced_group(cursor)?;
offset += used;
let mut look = &cursor[used..];
let spaces = look.len() - look.trim_start().len();
look = look.trim_start();
let matches = if let Some((command, _)) = control_sequence(look) {
target.0 && command == target.1
} else {
!target.0 && look.starts_with(&target.1)
};
if matches {
return Some((matched.to_string(), offset + spaces));
}
return Some((unmatched.to_string(), offset));
}
}
None
}
@@ -9595,6 +9658,20 @@ a & b
assert!(!json.contains("color{"), "{json}");
}
#[test]
fn at_ifstar_consumes_a_star() {
let (body, _) =
geometry_and_body("\\def\\cmd{\\@ifstar{starred}{plain}}\n\nA \\cmd* B \\cmd C.");
assert!(body.contains("A starred B plain C."), "{body}");
}
#[test]
fn at_ifnextchar_chooses_by_lookahead() {
let (body, _) =
geometry_and_body("\\def\\opt{\\@ifnextchar[{[}{no}}\n\n\\opt[x] and \\opt y.");
assert!(body.contains("[[x] and no y."), "{body}");
}
#[test]
fn page_numbers_follow_the_page_counter() {
let offset = preview_json("\\setcounter{page}{5}\n\nAlpha\n\n\\newpage\n\nBeta")