Honour explicit limits and nolimits on operators

This commit is contained in:
gloamxun committed 2026-10-26 00:48:52 +08:00
1 parent 29d363d47a
commit e926bc9eb3
4 files changed
+55 -6

No files matched your search

+50 -1
View File
@@ -1318,13 +1318,37 @@ fn is_right_command(chars: &[char], index: usize) -> bool {
&& chars.get(index + 5) == Some(&'t')
}
fn limits_override(chars: &[char], index: usize) -> Option<(bool, usize)> {
let mut cursor = index;
while cursor < chars.len() && (chars[cursor] == '\u{0}' || chars[cursor].is_whitespace()) {
cursor += 1;
}
let rest = chars.get(cursor..)?;
for (word, forced) in [("\\limits", true), ("\\nolimits", false)] {
let letters: Vec<char> = word.chars().collect();
if rest.starts_with(&letters)
&& !rest
.get(letters.len())
.is_some_and(|character| character.is_ascii_alphabetic())
{
return Some((forced, cursor + letters.len()));
}
}
None
}
fn parse_limits(chars: &[char], next: usize, base: MathAtom) -> (MathAtom, usize) {
let mut after = next;
let mut forced = None;
while let Some((value, end)) = limits_override(chars, after) {
forced = Some(value);
after = end;
}
let mut sub = None;
let mut sup = None;
loop {
let mut cursor = after;
while cursor < chars.len() && chars[cursor].is_whitespace() {
while cursor < chars.len() && (chars[cursor].is_whitespace() || chars[cursor] == '\u{0}') {
cursor += 1;
}
match chars.get(cursor) {
@@ -1343,6 +1367,15 @@ fn parse_limits(chars: &[char], next: usize, base: MathAtom) -> (MathAtom, usize
}
if sub.is_none() && sup.is_none() {
(base, after)
} else if forced == Some(false) {
(
MathAtom::Script {
base: Box::new(base),
sub,
sup,
},
after,
)
} else {
(
MathAtom::Limits {
@@ -2971,6 +3004,22 @@ mod tests {
assert!(limited.depth > plain.depth);
}
#[test]
fn nolimits_moves_scripts_beside_the_operator() {
let font = Cmr10Metrics::default();
let stacked = layout_math(&parse_math(r"\sum_{i}^{n}"), &font);
let beside = layout_math(&parse_math(r"\sum\nolimits_{i}^{n}"), &font);
assert!(beside.width > stacked.width);
assert!(beside.height < stacked.height);
let MathAtom::Row(atoms) = parse_math(r"\int\limits_{0}^{1}") else {
panic!("expected a row");
};
assert!(matches!(&atoms[0], MathAtom::Limits { .. }));
let MathAtom::Row(nolimits) = parse_math(r"\sum\nolimits_{i}") else {
panic!("expected a row");
};
assert!(matches!(&nolimits[0], MathAtom::Script { .. }));
}
#[test]
fn starred_operatorname_takes_limits_below() {
let font = Cmr10Metrics::default();
let plain = layout_math(&parse_math(r"\operatorname*{argmax}"), &font);