diff --git a/crates/math/src/latex_text.rs b/crates/math/src/latex_text.rs index 0565ac9a9..64e7709b7 100644 --- a/crates/math/src/latex_text.rs +++ b/crates/math/src/latex_text.rs @@ -237,6 +237,9 @@ fn linear_to_latex_at(linear: &str, depth: usize) -> String { let parens = closers(&chars, '(', ')'); let brackets = closers(&chars, '〖', '〗'); let mut o = String::new(); + // Where the output ended after the last plain letter written below: while it still ends + // there, its trailing letters are plain text, not a control word, and needn't be scanned. + let mut plain_end = usize::MAX; let mut i = 0; let sub = |s: &str| if depth < MAX_NEST { linear_to_latex_at(s, depth + 1) } else { escape_math_text(s) }; while let Some(&c) = chars.get(i) { @@ -337,10 +340,15 @@ fn linear_to_latex_at(linear: &str, depth: usize) -> String { // A letter after a control word would extend it. The lookahead above only sees // the next input character, so a character dropped in between (an unmatched // `〖` or `〗`, a control character) would join `\in` and `put` into `\input`. - if c.is_ascii_alphabetic() && ends_with_control_word(&o) { + // Scanning only when other output came since the last plain letter keeps a long + // run of letters linear. + if c.is_ascii_alphabetic() && o.len() != plain_end && ends_with_control_word(&o) { o.push(' '); } o.push(c); + if c.is_ascii_alphabetic() { + plain_end = o.len(); + } } }, } @@ -664,5 +672,9 @@ mod tests { // A command followed by a letter directly is still separated, and grouping still works. assert_eq!(linear_to_latex("∈x"), "\\in x"); assert_eq!(linear_to_latex("〖a+b〗^2"), "{a+b}^2"); + // The check stays linear: a long run of letters, plain or after a command, is one pass. + let letters = "a".repeat(400_000); + assert_eq!(linear_to_latex(&letters).len(), 400_000); + assert_eq!(linear_to_latex(&format!("∈〗{letters}")), format!("\\in {letters}")); } }