texplain 0.1.0

Strip LaTeX to plain text with 1:1 line mapping, so prose linters report the source line.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
//! Single-line LaTeX stripping: comment removal, command parsing, whitespace
//! normalisation.
//!
//! This module owns the entire pipeline for converting one line of LaTeX source
//! into plain text.  It is the only module that needs to understand LaTeX
//! syntax (backslash commands, brace groups, `%`-comments, `~` non-breaking
//! spaces, optional `[…]` arguments).

use std::borrow::Cow;
use std::ops::Range;

// ---------------------------------------------------------------------------
// LaTeX accent → Unicode mapping
// ---------------------------------------------------------------------------

/// Map a LaTeX shorthand accent and its base letter to one precomposed
/// character: `(b'"', b'a')` → `ä`, `(b'\'', b'e')` → `é`.
///
/// Returns `None` for any pair the table does not cover. Callers fall back to
/// emitting the base letter alone.
///
/// This is a `const fn` match rather than a lazily-built `HashMap`: the table
/// is fixed at compile time, so hashing it at runtime would buy nothing and
/// cost an allocation plus a `LazyLock` on every lookup path.
#[rustfmt::skip]
const fn accented(accent: u8, base: u8) -> Option<char> {
    Some(match (accent, base) {
        // diaeresis \"
        (b'"', b'a') => 'ä', (b'"', b'e') => 'ë', (b'"', b'i') => 'ï',
        (b'"', b'o') => 'ö', (b'"', b'u') => 'ü', (b'"', b'y') => 'ÿ',
        (b'"', b'A') => 'Ä', (b'"', b'E') => 'Ë', (b'"', b'I') => 'Ï',
        (b'"', b'O') => 'Ö', (b'"', b'U') => 'Ü', (b'"', b'Y') => 'Ÿ',
        // acute \'
        (b'\'', b'a') => 'á', (b'\'', b'e') => 'é', (b'\'', b'i') => 'í',
        (b'\'', b'o') => 'ó', (b'\'', b'u') => 'ú', (b'\'', b'y') => 'ý',
        (b'\'', b'A') => 'Á', (b'\'', b'E') => 'É', (b'\'', b'I') => 'Í',
        (b'\'', b'O') => 'Ó', (b'\'', b'U') => 'Ú', (b'\'', b'Y') => 'Ý',
        // grave \`
        (b'`', b'a') => 'à', (b'`', b'e') => 'è', (b'`', b'i') => 'ì',
        (b'`', b'o') => 'ò', (b'`', b'u') => 'ù',
        (b'`', b'A') => 'À', (b'`', b'E') => 'È', (b'`', b'I') => 'Ì',
        (b'`', b'O') => 'Ò', (b'`', b'U') => 'Ù',
        // circumflex \^
        (b'^', b'a') => 'â', (b'^', b'e') => 'ê', (b'^', b'i') => 'î',
        (b'^', b'o') => 'ô', (b'^', b'u') => 'û',
        (b'^', b'A') => 'Â', (b'^', b'E') => 'Ê', (b'^', b'I') => 'Î',
        (b'^', b'O') => 'Ô', (b'^', b'U') => 'Û',
        // tilde \~
        (b'~', b'a') => 'ã', (b'~', b'n') => 'ñ', (b'~', b'o') => 'õ',
        (b'~', b'A') => 'Ã', (b'~', b'N') => 'Ñ', (b'~', b'O') => 'Õ',
        _ => return None,
    })
}

// ---------------------------------------------------------------------------
// Checked source access
// ---------------------------------------------------------------------------

/// A borrowed source line with checked byte-level accessors.
///
/// The stripper is a hand-written scanner that needs random access by byte
/// offset, which is exactly where `s[i]` and `&s[a..b]` turn a logic slip into
/// a panic.  Every accessor here is total: out-of-range reads yield `None` and
/// out-of-range slices yield `""`.
///
/// Note that [`Self::slice`] returns `&'src str`, not `&str` borrowed from
/// `self`.  The lifetime comes from the source the cursor points at, so slices
/// outlive the cursor and callers are free to move it on.
#[derive(Debug, Clone, Copy)]
struct Source<'src> {
    /// The line being scanned.
    text: &'src str,
}

impl<'src> Source<'src> {
    /// Wrap a line for scanning.
    const fn new(text: &'src str) -> Self {
        Self { text }
    }

    /// Length of the line in bytes.
    const fn len(self) -> usize {
        self.text.len()
    }

    /// The byte at `at`, or `None` past the end.
    fn byte(self, at: usize) -> Option<u8> {
        self.text.as_bytes().get(at).copied()
    }

    /// Is the byte at `at` exactly `byte`?  `false` past the end.
    fn is(self, at: usize, byte: u8) -> bool {
        self.byte(at) == Some(byte)
    }

    /// Does the byte at `at` satisfy `pred`?  `false` past the end.
    fn at_is(self, at: usize, pred: impl FnOnce(u8) -> bool) -> bool {
        self.byte(at).is_some_and(pred)
    }

    /// The text in `range`, or `""` if the range is out of bounds or splits a
    /// UTF-8 character.
    ///
    /// The scanner only ever builds ranges from positions it found by walking
    /// the line, so a miss means a bug: `debug_assert` catches it in tests
    /// while release builds degrade to empty rather than panicking.
    fn slice(self, range: Range<usize>) -> &'src str {
        let found = self.text.get(range.clone());
        debug_assert!(found.is_some(), "slice {range:?} is not a char boundary of {:?}", self.text);
        found.unwrap_or_default()
    }
}

// ---------------------------------------------------------------------------
// Brace matching
// ---------------------------------------------------------------------------

/// Find the index of the closing `}` that matches the opening `{` at `open_pos`.
///
/// Returns `None` if the brace is never closed.  Depth is tracked with
/// `checked_sub`, so a caller pointing `open_pos` at something other than `{`
/// gets `None` rather than an arithmetic overflow.
fn find_matching_brace(src: Source<'_>, open_pos: usize) -> Option<usize> {
    let mut depth: u32 = 0;
    for (i, byte) in src.text.bytes().enumerate().skip(open_pos) {
        match byte {
            b'{' => depth += 1,
            b'}' => {
                depth = depth.checked_sub(1)?;
                if depth == 0 {
                    return Some(i);
                }
            }
            _ => {}
        }
    }
    None
}

// ---------------------------------------------------------------------------
// Public entry point
// ---------------------------------------------------------------------------

/// Strip a single line of LaTeX to plain text.
///
/// 1. Removes trailing comments (from the first unescaped `%` to end of line).
/// 2. Strips all LaTeX commands and braces, recursing into brace groups.
/// 3. Collapses runs of whitespace to a single space and trims.
///
/// This handles one line in isolation. Constructs that span lines (blanked
/// environments, multi-line `\author`/`\title`) need [`crate::strip`].
///
/// Returns [`Cow::Borrowed`] when the line is already plain text, which is the
/// common case in prose-heavy sources. Only lines that actually contain markup
/// or irregular whitespace allocate.
#[must_use]
pub fn strip_line(line: &str) -> Cow<'_, str> {
    if is_already_plain(line) {
        return Cow::Borrowed(line);
    }
    let without_comment = remove_comment(line);
    let stripped = strip_fragment(Source::new(&without_comment));
    Cow::Owned(collapse_whitespace(&stripped))
}

/// Bytes that make a line interesting to the stripper.
///
/// `[` and `]` are included because [`strip_fragment`] drops bracket groups,
/// `$` because it opens math, and `-` is not: hyphens pass through untouched.
const MARKUP_BYTES: &[u8] = b"\\{}%~&[]$";

/// Would stripping this line leave it byte-for-byte unchanged?
///
/// True when the line holds no markup and no whitespace that
/// [`collapse_whitespace`] would rewrite: no leading or trailing whitespace, no
/// runs, every space a plain ASCII space, and no space sitting in front of
/// [`CLINGY_PUNCTUATION`].
///
/// This must stay exactly in step with the transformation it predicts.
/// `borrowed_and_owned_paths_agree` in the test module holds it to that.
fn is_already_plain(line: &str) -> bool {
    if line.bytes().any(|b| MARKUP_BYTES.contains(&b)) {
        return false;
    }
    let mut prev_was_space = false;
    let mut at_start = true;
    for ch in line.chars() {
        if ch.is_whitespace() {
            // Leading whitespace, a run, or any space that is not a plain
            // ASCII one all get rewritten.
            if at_start || prev_was_space || ch != ' ' {
                return false;
            }
            prev_was_space = true;
        } else {
            if prev_was_space && CLINGY_PUNCTUATION.contains(&ch) {
                return false;
            }
            prev_was_space = false;
        }
        at_start = false;
    }
    // A trailing space would be trimmed. An empty line is already plain.
    !prev_was_space
}

// ---------------------------------------------------------------------------
// Comment removal
// ---------------------------------------------------------------------------

/// Remove the trailing `%`-comment from a line.
///
/// Walks ASCII delimiters by byte while leaving multi-byte UTF-8 sequences
/// intact.  Single-character escapes like `\"` skip two bytes so that `\%` is
/// not mistaken for a comment.  Alphabetic commands (`\textbf`) are left
/// intact, because [`strip_fragment`] handles those.
///
/// Borrows when there is no comment to remove, which is most lines.
fn remove_comment(line: &str) -> Cow<'_, str> {
    let src = Source::new(line);
    let mut i = 0;

    while i < src.len() {
        if src.is(i, b'\\') {
            // An escaped non-letter consumes its escapee. `\cmd` does not.
            let escapes_next = src.at_is(i + 1, |b| !b.is_ascii_alphabetic() && b != b'@');
            i += if escapes_next { 2 } else { 1 };
            continue;
        }
        if src.is(i, b'%') {
            return Cow::Borrowed(src.slice(0..i));
        }
        i += 1;
    }

    Cow::Borrowed(line)
}

// ---------------------------------------------------------------------------
// Fragment parser (recursive)
// ---------------------------------------------------------------------------

/// Commands whose mandatory `{…}` argument should be **discarded** rather
/// than kept as prose.
const DROP_ARG_COMMANDS: &[&str] = &[
    "url",
    "href",
    "includegraphics",
    "label",
    "ref",
    "eqref",
    "cite",
    "cref",
    "Cref",
    "autoref",
    "pageref",
    "nameref",
    "bibliographystyle",
    "bibliography",
    "input",
    "include",
    "usepackage",
    "documentclass",
    "begin",
    "end",
    "newcommand",
    "renewcommand",
    "setlength",
    "addtolength",
    "setcounter",
    "newcounter",
    "fnsymbol",
    "arabic",
    "thispagestyle",
    "pagestyle",
    "put",
    "parbox",
    "DeclareGraphicsExtensions",
    "graphicspath",
    "author",
    "IEEEauthorblockN",
    "IEEEauthorblockA",
    "maketitle",
    "thanks",
    // Typesetting hints and indexing: the argument is never prose.
    "hyphenation",
    "index",
    "nocite",
    "markboth",
    "markright",
    "addcontentsline",
    "pagenumbering",
    "hspace",
    "vspace",
    "rule",
    "bibitem",
    // `doc` package: documents a macro name, which is code.
    "DescribeMacro",
    "DescribeEnv",
];

/// Commands that stand for a piece of text, mapped to that text.
///
/// Without these the command vanishes and takes a word out of the sentence:
/// `produced under \LaTeX\ using` became `produced under using`, which reads
/// to a linter as a grammar error that is not in the source.
const TEXT_COMMANDS: &[(&str, &str)] = &[
    ("LaTeX", "LaTeX"),
    ("LaTeXe", "LaTeX2e"),
    ("TeX", "TeX"),
    ("BibTeX", "BibTeX"),
    // The real character, not "...": LaTeX typesets these as a proper
    // ellipsis, and emitting three periods makes a typography rule suggest
    // replacing them with the character the source already produces.
    ("ldots", "…"),
    ("dots", "…"),
    ("textellipsis", "…"),
    ("copyright", "(c)"),
    ("textcopyright", "(c)"),
    ("textregistered", "(R)"),
    ("texttrademark", "(TM)"),
    ("pounds", "GBP"),
    ("euro", "EUR"),
    ("textbackslash", " "),
    ("textbar", "|"),
    ("S", "Section"),
    ("P", "Paragraph"),
    ("dag", "*"),
    ("ddag", "*"),
    ("ss", "ss"),
    ("ae", "ae"),
    ("AE", "AE"),
    ("oe", "oe"),
    ("OE", "OE"),
    ("aa", "a"),
    ("AA", "A"),
    ("o", "o"),
    ("O", "O"),
    ("l", "l"),
    ("L", "L"),
    ("i", "i"),
    ("j", "j"),
];

/// The replacement text for a command that stands for a symbol or word.
fn text_command(name: &str) -> Option<&'static str> {
    TEXT_COMMANDS.iter().find(|(cmd, _)| *cmd == name).map(|(_, text)| *text)
}

/// Sectioning commands whose argument should be kept but followed by a period
/// so that the heading forms its own sentence for the linter.
/// A period is only appended if the text does not already end in punctuation.
const HEADING_COMMANDS: &[&str] = &[
    "section",
    "subsection",
    "subsubsection",
    "paragraph",
    "subparagraph",
    "chapter",
    "caption",
    "title",
];

/// Strip LaTeX commands from a text fragment, recursing into brace groups.
///
/// Returns a string with no backslashes and no braces, only plain text and
/// whitespace.  Called recursively for the content inside `{…}` groups.
fn strip_fragment(src: Source<'_>) -> String {
    let mut out = String::with_capacity(src.len());
    let mut i = 0;

    while i < src.len() {
        let Some(byte) = src.byte(i) else { break };

        if byte == b'\\' {
            // A trailing backslash introduces nothing. Drop it: the output is
            // documented to contain no backslashes. (It used to be emitted,
            // because the bounds check fell through to the literal-byte arm.)
            let Some(next) = src.byte(i + 1) else { break };
            if next.is_ascii_alphabetic() || next == b'@' {
                i = skip_command(src, i, &mut out);
            } else {
                i += 2;
                match next {
                    // line break (`\\`) and escaped space (`\ `) both become a space
                    b'\\' | b' ' => out.push(' '),
                    // accent shortcuts: consume the next letter and map to Unicode
                    b'"' | b'\'' | b'`' | b'^' | b'~' => {
                        let base = resolve_accent_base(src, &mut i);
                        match base.as_bytes().first().and_then(|&b| accented(next, b)) {
                            Some(ch) => {
                                out.push(ch);
                                // if base was multi-char (from a {…} group), append the rest
                                out.push_str(base.get(1..).unwrap_or_default());
                            }
                            None => out.push_str(&base),
                        }
                    }
                    b'%' | b'&' | b'#' | b'$' | b'_' | b'-' | b'.' | b'?' => {
                        out.push(char::from(next));
                    }
                    // math spacing commands (`\,`, `\;`, `\:`, `\!`, `\>`)
                    // collapse to a single space so they do not look like
                    // sentence punctuation to downstream linters.
                    b',' | b';' | b':' | b'!' | b'>' => {
                        out.push(' ');
                    }
                    // `\(…\)` is inline math: part of the sentence, so keep
                    // what the formula reduces to. `\[…\]` is a display block
                    // and is dropped whole.
                    // `\(…\)` and `\[…\]` are math. Not prose, so dropped.
                    // See the `$` arm below for why nothing is put in its place.
                    b'(' | b'[' => {
                        let closer = if next == b'(' { b')' } else { b']' };
                        i = close_paren_math(src, i, closer).map_or_else(|| src.len(), |c| c + 2);
                        out.push(' ');
                    }
                    _ => {}
                }
            }
            continue;
        }

        if byte == b'%' {
            break;
        }

        // `$…$` and `$$…$$` are math. Without this the delimiters themselves
        // land in the output: `$\alpha$` used to strip to a bare `$$`.
        //
        // The formula is dropped rather than reduced to text. Keeping it reads
        // better in isolation, but it feeds notation to rules written for
        // prose: on this thesis, keeping it turned `$-58\,\%$` into a
        // negative-number complaint and `$\{t_1, \ldots, t_N\}$` into two
        // ellipsis complaints. Measured over the same corpus, dropping gave 16
        // alerts, a placeholder token 17 to 19, and keeping the text 21. The
        // extras in each case are artefacts, not findings.
        //
        // The cost is that `word $x$ word` fuses into `word word`, which can
        // read as a repetition that is not in the source. That is one alert in
        // this corpus against five the other way.
        if byte == b'$' {
            let display = src.is(i + 1, b'$');
            let delim = if display { 2 } else { 1 };
            i = close_dollar_math(src, i, display).map_or_else(|| src.len(), |c| c + delim);
            out.push(' ');
            continue;
        }

        if byte == b'[' {
            i = skip_brackets(src, i);
            continue;
        }

        if byte == b'{' {
            if let Some(close) = find_matching_brace(src, i) {
                out.push_str(&strip_fragment(Source::new(src.slice(i + 1..close))));
                i = close + 1;
            } else {
                i += 1;
            }
            continue;
        }

        match byte {
            // Braces carry no text, and a stray closer is simply dropped.
            b'}' => i += 1,
            // Alignment tab and non-breaking space both read as a word break.
            b'&' | b'~' => {
                out.push(' ');
                i += 1;
            }
            // Start of a multi-byte UTF-8 sequence: copy it whole.
            _ if !byte.is_ascii() => {
                let start = i;
                i += 1;
                while src.at_is(i, is_utf8_continuation) {
                    i += 1;
                }
                out.push_str(src.slice(start..i));
            }
            _ => {
                out.push(char::from(byte));
                i += 1;
            }
        }
    }

    out
}

/// Is this byte a UTF-8 continuation byte (`10xxxxxx`)?
const fn is_utf8_continuation(byte: u8) -> bool {
    byte & 0b1100_0000 == 0b1000_0000
}

// ---------------------------------------------------------------------------
// Accent helpers
// ---------------------------------------------------------------------------

/// Read the base letter for a shorthand accent command (`\"`, `\'`, etc.).
///
/// The base is either a single ASCII letter immediately following the accent
/// (`\"a`) or a `{…}` group (`\"{a}`).  Advances `*pos` past the consumed
/// input and returns the base text (stripped if it was a brace group).
///
/// The result borrows from `'src`, not from `pos`: a single letter is a slice
/// of the line, so it stays valid after the cursor moves on.  Only the brace
/// group has to allocate, because its content is rewritten.
fn resolve_accent_base<'src>(src: Source<'src>, pos: &mut usize) -> Cow<'src, str> {
    let Some(byte) = src.byte(*pos) else {
        return Cow::Borrowed("");
    };
    if byte == b'{' {
        if let Some(close) = find_matching_brace(src, *pos) {
            let inner = strip_fragment(Source::new(src.slice(*pos + 1..close)));
            *pos = close + 1;
            return Cow::Owned(inner);
        }
    }
    if byte.is_ascii_alphabetic() {
        let base = src.slice(*pos..*pos + 1);
        *pos += 1;
        return Cow::Borrowed(base);
    }
    Cow::Borrowed("")
}

// ---------------------------------------------------------------------------
// Command / bracket helpers
// ---------------------------------------------------------------------------

/// Advance past a `\command[opt]{arg}` sequence, appending the stripped
/// content of the mandatory `{arg}` (if present) to `out`, unless the
/// command is in [`DROP_ARG_COMMANDS`], in which case the argument is
/// silently discarded.
///
/// Returns the new cursor position after the command and its arguments.
fn skip_command(src: Source<'_>, start: usize, out: &mut String) -> usize {
    let mut j = start + 2;
    while src.at_is(j, |b| b.is_ascii_alphabetic() || b == b'@') {
        j += 1;
    }

    let cmd_name = src.slice(start + 1..j);

    // `\verb` delimits its argument with whatever character follows, not with
    // braces. Left to the brace logic below, `\verb|\institute|` would emit
    // `||`, the delimiters, with the code between them stripped as if it were
    // prose. The content is code, so drop it whole.
    if cmd_name == "verb" {
        let after_star = if src.is(j, b'*') { j + 1 } else { j };
        if let Some(delim) = src.byte(after_star) {
            out.push(' ');
            return skip_delimited(src, after_star + 1, delim);
        }
    }

    // A command that stands for text contributes that text and nothing else.
    if let Some(text) = text_command(cmd_name) {
        out.push_str(text);
        // `\LaTeX{}` is the usual way to keep the following space. Consume the
        // empty group so it does not read as an argument.
        if src.is(j, b'{') && src.is(j + 1, b'}') {
            return j + 2;
        }
        return j;
    }

    let drop = DROP_ARG_COMMANDS.contains(&cmd_name);
    let heading = HEADING_COMMANDS.contains(&cmd_name);

    if src.at_is(j, |b| matches!(b, b'*' | b'^' | b'_')) {
        j += 1;
    }

    if src.is(j, b'[') {
        j = skip_brackets(src, j);
    }

    if src.is(j, b'{') {
        if let Some(close) = find_matching_brace(src, j) {
            if !drop {
                let content = strip_fragment(Source::new(src.slice(j + 1..close)));
                out.push_str(&content);
                if heading && !content.ends_with(['.', '?', '!']) {
                    out.push('.');
                }
            }
            j = close + 1;
            // For drop-argument commands, also consume any further
            // `[opt]` brackets and `{arg}` groups that belong to the same
            // command (e.g. `\newcommand{\Name}[N]{body}` or
            // `\begin{env}[opt]{spec}`). For non-drop commands, only
            // consume directly adjacent `{arg}` groups so multi-argument
            // text macros like `\frac{a}{b}` are not over-eagerly merged.
            if drop {
                loop {
                    while src.is(j, b'[') {
                        j = skip_brackets(src, j);
                    }
                    let Some(close2) =
                        src.is(j, b'{').then(|| find_matching_brace(src, j)).flatten()
                    else {
                        break;
                    };
                    j = close2 + 1;
                }
            } else {
                while let Some(close2) =
                    src.is(j, b'{').then(|| find_matching_brace(src, j)).flatten()
                {
                    j = close2 + 1;
                }
            }
            return j;
        }
    }

    j
}

/// Skip from `start` to just past the next occurrence of `delim`.
///
/// Used for `\verb<delim>…<delim>`, whose argument is delimited by an
/// arbitrary character. Returns the end of the line if `delim` never recurs.
fn skip_delimited(src: Source<'_>, start: usize, delim: u8) -> usize {
    let mut i = start;
    while i < src.len() {
        if src.is(i, delim) {
            return i + 1;
        }
        i += 1;
    }
    src.len()
}

/// Find the `\)` or `\]` closing math whose content starts at `content_start`.
///
/// `content_start` is the byte after the opening `\(` or `\[`, which is where
/// [`strip_fragment`]'s cursor already sits by the time it dispatches on the
/// delimiter. Returns the index of the closer's backslash, or `None` if the
/// math does not close on this line.
fn close_paren_math(src: Source<'_>, content_start: usize, closer: u8) -> Option<usize> {
    let mut i = content_start;
    while i < src.len() {
        if src.is(i, b'\\') && src.is(i + 1, closer) {
            return Some(i);
        }
        i += 1;
    }
    None
}

/// Find the `$` or `$$` closing the math opened at `open`.
///
/// Returns the index of the closing delimiter's first byte, or `None` if it
/// does not close on this line. An escaped `\$` never reaches here:
/// [`strip_fragment`] handles it as a single-character escape first.
fn close_dollar_math(src: Source<'_>, open: usize, display: bool) -> Option<usize> {
    let mut i = open + if display { 2 } else { 1 };

    while i < src.len() {
        // A `\$` inside the formula is an escaped dollar, not the closer.
        if src.is(i, b'\\') {
            i += 2;
            continue;
        }
        if src.is(i, b'$') && (!display || src.is(i + 1, b'$')) {
            return Some(i);
        }
        i += 1;
    }
    None
}

/// Skip a balanced `[…]` group starting at `pos`.  Returns the position
/// immediately after the closing `]`, or the end of the line if unmatched.
fn skip_brackets(src: Source<'_>, pos: usize) -> usize {
    let mut depth: u32 = 1;
    let mut j = pos + 1;
    while depth > 0 {
        let Some(byte) = src.byte(j) else { break };
        match byte {
            b'[' => depth += 1,
            b']' => depth -= 1,
            _ => {}
        }
        j += 1;
    }
    j
}

// ---------------------------------------------------------------------------
// Whitespace normalisation
// ---------------------------------------------------------------------------

/// Punctuation that must not be preceded by a space.
///
/// Dropping a command mid-sentence leaves the space that stood before it:
/// `See Subsection \ref{x}.` becomes `See Subsection .`, which a linter reads
/// as a sentence ending in a floating period. Closing brackets get the same
/// treatment for the same reason.
const CLINGY_PUNCTUATION: [char; 8] = ['.', ',', ';', ':', '!', '?', ')', ']'];

/// Collapse all whitespace runs to a single space, trim, and close up the gap
/// left in front of punctuation by a dropped command.
///
/// [`str::split_whitespace`] already trims and splits on runs, so this needs no
/// regex. The engine that used to do it cost a `LazyLock`, a compile, and a
/// full scan per line.
fn collapse_whitespace(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for word in s.split_whitespace() {
        if !out.is_empty() && !word.starts_with(CLINGY_PUNCTUATION) {
            out.push(' ');
        }
        out.push_str(word);
    }
    out
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    // The scanner takes a checked cursor. These shims let the tests keep
    // reading as plain `&str` in, plain value out. Locally defined items win
    // over the `use super::*` glob, so the names stay the same.

    /// Wrap `text` and strip it as a fragment.
    fn strip_fragment(text: &str) -> String {
        super::strip_fragment(Source::new(text))
    }

    /// Wrap `text` and find the brace matching the one at `open_pos`.
    fn find_matching_brace(text: &str, open_pos: usize) -> Option<usize> {
        super::find_matching_brace(Source::new(text), open_pos)
    }

    /// The always-owned pipeline, ignoring the [`is_already_plain`] fast path.
    fn strip_line_the_long_way(line: &str) -> String {
        let without_comment = remove_comment(line);
        collapse_whitespace(&strip_fragment(&without_comment))
    }

    /// The borrowed fast path must be indistinguishable from doing the work.
    ///
    /// [`is_already_plain`] predicts the result of a transformation it does not
    /// perform, so it can silently drift from it. This pins the two together
    /// over inputs on both sides of every condition the predicate tests.
    #[test]
    fn borrowed_and_owned_paths_agree() {
        let cases = [
            "",
            "plain prose here",
            " leading space",
            "trailing space ",
            "double  space",
            "tab\tseparated",
            "non\u{a0}breaking space",
            "naïve unicode prose",
            "hyphen-joined words",
            "trailing backslash \\",
            r"\textbf{markup}",
            "brace } alone",
            "percent % comment",
            "tilde~space",
            "amp & tab",
            "bracket [opt] group",
        ];
        for case in cases {
            assert_eq!(
                strip_line(case),
                strip_line_the_long_way(case),
                "fast path diverged from the full pipeline on {case:?}"
            );
        }
    }

    /// The fast path must actually fire, or it is dead weight.
    #[test]
    fn plain_lines_are_borrowed() {
        assert!(
            matches!(strip_line("plain prose here"), Cow::Borrowed(_)),
            "a line with no markup must not allocate"
        );
        assert!(
            matches!(strip_line(r"\textbf{markup}"), Cow::Owned(_)),
            "a line with markup must be rewritten"
        );
    }

    // -- constructs that used to leak raw source --

    /// Math is dropped, delimiters and all. See `strip_fragment` for why the
    /// formula is not reduced to text instead.
    #[test]
    fn math_is_dropped() {
        assert_eq!(
            strip_line(r"The symbol $\alpha$ tagged as math."),
            "The symbol tagged as math.",
            "`$…$` must not leave its delimiters behind"
        );
        assert_eq!(strip_line("Set $x = y + 1$ here."), "Set here.", "a formula is not prose");
        assert_eq!(strip_line("before $$a+b$$ after"), "before after", "`$$…$$` is dropped");
        assert_eq!(strip_line(r"before \(a+b\) after"), "before after", r"`\(…\)` is dropped");
        assert_eq!(strip_line(r"before \[a+b\] after"), "before after", r"`\[…\]` is dropped");
    }

    /// Notation must never reach the linter, whatever else happens.
    #[test]
    fn math_notation_does_not_leak() {
        for line in [r"a $-58\,\%$ b", r"a $\{t_1, \ldots, t_N\}$ b", r"a $x^2_i$ b"] {
            let got = strip_line(line);
            assert_eq!(got, "a b", "notation leaked from {line:?} as {got:?}");
        }
    }

    #[test]
    fn escaped_dollar_is_not_math() {
        assert_eq!(
            strip_line(r"costs \$5 and \$6"),
            "costs $5 and $6",
            r"`\$` is a literal dollar, not a math delimiter"
        );
    }

    #[test]
    fn unclosed_math_does_not_eat_the_next_line() {
        // Display math often spans lines, so dropping the rest of this one is
        // correct, and the line itself must still be produced.
        assert_eq!(strip_line("text $unclosed"), "text", "unclosed math ends at the line");
    }

    #[test]
    fn verb_argument_is_dropped() {
        assert_eq!(
            strip_line(r"should be given in \verb|\institute|."),
            "should be given in.",
            "`\\verb` uses an arbitrary delimiter, and its content is code"
        );
        assert_eq!(
            strip_line(r"use \verb+\foo+ here"),
            "use here",
            "the delimiter is whatever follows \\verb"
        );
    }

    #[test]
    fn text_commands_keep_their_word() {
        assert_eq!(
            strip_line(r"produced under \LaTeX\ using"),
            "produced under LaTeX using",
            "a vanished \\LaTeX leaves a hole in the sentence"
        );
        assert_eq!(
            strip_line(r"searched by \LaTeX{}, then"),
            "searched by LaTeX, then",
            "the empty-group spacing idiom is consumed, not read as an argument"
        );
    }

    #[test]
    fn dropped_command_does_not_strand_punctuation() {
        assert_eq!(
            strip_line(r"See Subsection \ref{subsec1}."),
            "See Subsection.",
            "the space left by a dropped command must not precede the period"
        );
        assert_eq!(
            strip_line(r"Example citation, See \cite{lamport94}."),
            "Example citation, See.",
            "same for a dropped citation"
        );
    }

    #[test]
    fn hyphenation_hints_are_dropped() {
        assert_eq!(
            strip_line(r"\hyphenation{op-tical net-works}"),
            "",
            "hyphenation hints are typesetting, not prose"
        );
    }

    // -- strip_line (full pipeline) --

    #[test]
    fn plain_text_unchanged() {
        assert_eq!(strip_line("hello world"), "hello world", "plain text is unchanged");
    }

    #[test]
    fn removes_comment() {
        assert_eq!(strip_line("visible % hidden"), "visible", "trailing comment is removed");
    }

    #[test]
    fn collapses_whitespace() {
        assert_eq!(
            strip_line("  lots   of   space  "),
            "lots of space",
            "whitespace is collapsed and trimmed"
        );
    }

    #[test]
    fn nested_commands() {
        assert_eq!(
            strip_line(r"\textbf{\emph{bold and italic}} and more"),
            "bold and italic and more",
            "nested commands are stripped, prose kept"
        );
    }

    #[test]
    fn escaped_percent() {
        assert_eq!(
            strip_line(r"100\% done"),
            "100% done",
            "escaped percent is kept as literal character"
        );
    }

    // -- strip_fragment --

    #[test]
    fn fragment_plain_text() {
        assert_eq!(
            strip_fragment("hello world"),
            "hello world",
            "plain text passes through unchanged"
        );
    }

    #[test]
    fn fragment_simple_command() {
        assert_eq!(strip_fragment(r"\textbf{bold}"), "bold", "command arg is kept");
    }

    #[test]
    fn fragment_nested_commands() {
        assert_eq!(strip_fragment(r"\textbf{\emph{deep}}"), "deep", "nested commands recurse");
    }

    #[test]
    fn fragment_command_without_braces() {
        assert_eq!(
            strip_fragment(r"\par some text"),
            " some text",
            "command without braces is removed"
        );
    }

    #[test]
    fn fragment_tilde() {
        assert_eq!(strip_fragment("z.~B."), "z. B.", "tilde becomes a regular space");
    }

    #[test]
    fn fragment_percent() {
        assert_eq!(strip_fragment("visible % hidden"), "visible ", "percent stops parsing");
    }

    #[test]
    fn fragment_single_char_escape() {
        assert_eq!(strip_fragment(r#"Universit\"at"#), "Universität", "diaeresis accent resolved");
    }

    #[test]
    fn fragment_accent_acute() {
        assert_eq!(strip_fragment(r"caf\'e"), "café", "acute accent resolved");
    }

    #[test]
    fn fragment_accent_brace_group() {
        assert_eq!(strip_fragment(r#"Universit\"{a}t"#), "Universität", "accent with brace group");
    }

    #[test]
    fn fragment_optional_arg_kept() {
        assert_eq!(
            strip_fragment(r"\textbf[opt]{kept}"),
            "kept",
            "optional arg is skipped, mandatory arg kept for normal commands"
        );
    }

    #[test]
    fn fragment_drop_arg_command() {
        assert_eq!(
            strip_fragment(r"\usepackage[utf8]{inputenc}"),
            "",
            "drop-arg command discards its mandatory argument"
        );
    }

    #[test]
    fn fragment_url_dropped() {
        assert_eq!(strip_fragment(r"\url{https://example.com}"), "", "\\url content is dropped");
    }

    #[test]
    fn fragment_math_spacing() {
        assert_eq!(
            strip_line(r"a \, b \; c \: d \! e \> f"),
            "a b c d e f",
            "math spacing commands collapse to a single space"
        );
    }

    #[test]
    fn fragment_newcommand_with_arity_and_body_dropped() {
        assert_eq!(
            strip_line(r"\newcommand{\DB}[1]{\todo[color=cyan]{David: #1}}"),
            "",
            r"\newcommand body must be dropped even with intervening [N]"
        );
        assert_eq!(
            strip_line(r"prose \newcommand{\foo}[2][def]{body \emph{x}} after"),
            "prose after",
            r"\newcommand with optional default value drops every following arg"
        );
    }

    #[test]
    fn fragment_escaped_punctuation_preserved() {
        assert_eq!(
            strip_line(r"50\% off, item \#42, \$10, file\_name"),
            "50% off, item #42, $10, file_name",
            "escaped sentence punctuation is kept verbatim"
        );
    }

    // -- remove_comment --

    #[test]
    fn comment_basic() {
        assert_eq!(remove_comment("text % comment"), "text ");
    }

    #[test]
    fn comment_escaped_percent() {
        assert_eq!(
            remove_comment(r"100\% of cases"),
            r"100\% of cases",
            r"escaped \% is preserved, strip_fragment handles removal"
        );
    }

    // -- collapse_whitespace --

    #[test]
    fn whitespace_basic() {
        assert_eq!(collapse_whitespace("  a   b  "), "a b");
    }

    // -- find_matching_brace --

    #[test]
    fn brace_simple_pair() {
        assert_eq!(find_matching_brace("{hello}", 0), Some(6), "simple brace pair");
    }

    #[test]
    fn brace_nested_pair() {
        assert_eq!(find_matching_brace("{a{b}c}", 0), Some(6), "nested brace pair");
    }

    #[test]
    fn brace_unmatched() {
        assert_eq!(find_matching_brace("{no close", 0), None, "unmatched opening brace");
    }

    #[test]
    fn brace_mid_string() {
        assert_eq!(
            find_matching_brace("xx{inner}yy", 2),
            Some(8),
            "brace group starting mid-string"
        );
    }

    #[test]
    fn brace_empty_group() {
        assert_eq!(find_matching_brace("{}", 0), Some(1), "empty brace pair");
    }
}