croft-software 0.2.82

VSCode-style TUI written in Rust
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
//! SGR span parsing for the rendered ANSI log view (#257).
//!
//! A log file is a stream transcript, not a screen: it has unbounded line
//! width and no cursor. So this parses SGR (colour/attribute) sequences into
//! styled spans over the *stripped* text and discards every other escape —
//! cursor movement, OSC, scroll regions — rather than interpreting them.
//! Driving a real terminal grid instead would impose a fixed width the file
//! does not have.
//!
//! Colours stay symbolic ([`AnsiColor::Indexed`] for the low 16) so the
//! active theme's palette resolves them at paint time and a theme switch
//! recolours the view without reparsing.

/// A colour named by an SGR sequence.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AnsiColor {
    /// One of the 16 base slots, resolved through the theme's ANSI palette.
    /// Kept symbolic so a theme switch recolours without a reparse.
    Indexed(u8),
    /// A 256-colour cube / greyscale entry (SGR 38;5;n) outside the low 16.
    Palette256(u8),
    /// A 24-bit colour (SGR 38;2;r;g;b).
    Rgb(u8, u8, u8),
}

/// The style in force for a run of characters.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct AnsiStyle {
    pub fg: Option<AnsiColor>,
    pub bg: Option<AnsiColor>,
    pub bold: bool,
    pub dim: bool,
    pub italic: bool,
    pub underline: bool,
    /// SGR 7. Swapping fg/bg is left to the painter, which knows the
    /// theme's default pair to swap against.
    pub inverse: bool,
    /// SGR 9, cleared by 29.
    pub strikeout: bool,
}

impl AnsiStyle {
    fn reset(&mut self) {
        *self = Self::default();
    }
}

/// A run of characters sharing one style. `start`/`end` are byte offsets into
/// the STRIPPED line text, so a caller can slice the visible string directly.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AnsiSpan {
    pub start: usize,
    pub end: usize,
    pub style: AnsiStyle,
}

/// One parsed line: the escape-free text plus the spans that colour it.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct AnsiLine {
    pub text: String,
    pub spans: Vec<AnsiSpan>,
}

impl AnsiLine {
    /// A line with no escapes in it: its text in the default style.
    pub fn plain(text: impl Into<String>) -> Self {
        let text = text.into();
        let spans = if text.is_empty() {
            Vec::new()
        } else {
            vec![AnsiSpan {
                start: 0,
                end: text.len(),
                style: AnsiStyle::default(),
            }]
        };
        Self { text, spans }
    }

    /// Put `lead` in front of the line, in the default style, moving the
    /// spans along with the text they colour.
    pub fn prefix(&mut self, lead: &str) {
        if lead.is_empty() {
            return;
        }
        let n = lead.len();
        for span in &mut self.spans {
            span.start += n;
            span.end += n;
        }
        self.spans.insert(
            0,
            AnsiSpan {
                start: 0,
                end: n,
                style: AnsiStyle::default(),
            },
        );
        self.text.insert_str(0, lead);
    }
}

/// The parser state one output stream carries between its chunks: the SGR
/// state left in force, an escape sequence cut off mid-chunk, and the line
/// the stream is in the middle of. Each debug session keeps its own, one per
/// output category (#1501), since two programs' output is two streams, not
/// one terminal: a shared one let one session's cut `ESC[3` swallow the next
/// session's first letter, and its unreset colour paint the other's text.
///
/// A chunk is not a line (#932): `print("i =", i)` can reach a debug adapter
/// as `i =` and ` 0\n`, and an empty `print()` as a lone `\n`. A line ends at
/// its newline, blank or not, and the text after the last one stays open
/// until a later chunk ends it.
#[derive(Clone, Debug, Default)]
pub struct AnsiStream {
    style: AnsiStyle,
    cut: String,
    open: AnsiLine,
    /// A carriage return came after the open line's text: the next visible
    /// text replaces the line rather than extending it, as a progress bar's
    /// redraw does in a terminal. `\r\n` still just ends the line.
    rewind: bool,
}

/// How long an open line may grow before it is ended anyway: a program that
/// prints a dot per step and never a newline must not grow one line, and
/// the copy of it each chunk updates, without bound.
const OPEN_LINE_CAP: usize = 64 * 1024;

/// How long an escape sequence a chunk ends inside of may be held back
/// waiting for its end: an OSC with no terminator (an `ESC ]` in binary
/// output, say) would otherwise be kept, and rescanned on every chunk,
/// without bound. Past it the held bytes are dropped, as a terminal
/// swallows an escape it never sees the end of.
const ESCAPE_CAP: usize = 64 * 1024;

impl AnsiStream {
    /// Parse the next chunk and return the lines it ends, blank ones
    /// included. Text after its last newline joins the open line,
    /// [`open_line`](Self::open_line), and an escape sequence the chunk ends
    /// in the middle of waits for the next one.
    pub fn feed(&mut self, text: &str) -> Vec<AnsiLine> {
        let mut raw = std::mem::take(&mut self.cut);
        raw.push_str(text);
        let whole = raw.len() - unfinished_escape_len(&raw);
        self.cut = if raw.len() - whole > ESCAPE_CAP {
            String::new()
        } else {
            raw[whole..].to_string()
        };
        let mut ended = Vec::new();
        let mut rest = &raw[..whole];
        loop {
            let stop = rest.find(['\n', '\r']);
            self.append(&rest[..stop.unwrap_or(rest.len())]);
            let Some(at) = stop else { break };
            if rest.as_bytes()[at] == b'\n' {
                ended.push(std::mem::take(&mut self.open));
                self.rewind = false;
            } else {
                self.rewind = true;
            }
            rest = &rest[at + 1..];
        }
        if self.open.text.len() >= OPEN_LINE_CAP {
            ended.push(std::mem::take(&mut self.open));
            self.rewind = false;
        }
        ended
    }

    /// The line the stream is in the middle of, as it reads so far, or
    /// `None` when the last chunk ended at a newline.
    pub fn open_line(&self) -> Option<&AnsiLine> {
        (!self.open.text.is_empty()).then_some(&self.open)
    }

    /// End the stream: its open line, if it has one, as a finished line.
    pub fn finish(&mut self) -> Option<AnsiLine> {
        self.rewind = false;
        let line = std::mem::take(&mut self.open);
        (!line.text.is_empty()).then_some(line)
    }

    /// Add one piece of text with no line break in it to the open line.
    fn append(&mut self, raw: &str) {
        let piece = parse_line(raw, &mut self.style);
        if piece.text.is_empty() {
            return;
        }
        if std::mem::take(&mut self.rewind) {
            self.open = AnsiLine::default();
        }
        let offset = self.open.text.len();
        self.open.text.push_str(&piece.text);
        for span in piece.spans {
            match self.open.spans.last_mut() {
                Some(last) if last.end == offset + span.start && last.style == span.style => {
                    last.end = offset + span.end;
                }
                _ => self.open.spans.push(AnsiSpan {
                    start: offset + span.start,
                    end: offset + span.end,
                    style: span.style,
                }),
            }
        }
    }
}

/// How many bytes at the end of `raw` are an escape sequence that has not
/// finished yet: a stream cut mid-sequence (a debug adapter's output event,
/// #1501) holds these back until the next chunk completes them, where
/// [`parse_line`] would drop a truncated CSI and print a lone ESC. Only the
/// last line counts, since a newline ends any line the parser reads.
pub fn unfinished_escape_len(raw: &str) -> usize {
    let line = raw.rfind('\n').map(|i| i + 1).unwrap_or(0);
    let bytes = &raw.as_bytes()[line..];
    let Some(esc) = bytes.iter().rposition(|&b| b == 0x1b) else {
        return 0;
    };
    let tail = &bytes[esc..];
    let unfinished = match tail.get(1) {
        None => true,
        Some(b'[') => !tail[2..].iter().any(|b| (0x40..=0x7e).contains(b)),
        Some(b']' | b'P' | b'X' | b'^' | b'_') => !tail[2..].contains(&0x07),
        Some(b'(' | b')' | b'*' | b'+' | b'#') => tail.len() < 3,
        Some(_) => false,
    };
    if unfinished { tail.len() } else { 0 }
}

/// Parse one line, carrying `style` in and out so colours persist across
/// lines the way a terminal does (a log that sets red on one line and resets
/// three lines later paints all three red).
pub fn parse_line(raw: &str, style: &mut AnsiStyle) -> AnsiLine {
    let mut out = AnsiLine::default();
    parse_into(raw, style, &mut out);
    out
}

/// [`parse_line`] into a caller-owned line, so a bulk scan can reuse one
/// allocation instead of building a `String` and a span `Vec` per line.
///
/// There is ONE implementation of the stripping rules on purpose: a second
/// "just strip the escapes" copy would be the cheap thing to write and would
/// drift from this one the first time a sequence is handled differently, and
/// the two are compared by everything that trusts `text` (find, copy,
/// `path:line` scanning) to describe the same characters.
pub fn parse_into(raw: &str, style: &mut AnsiStyle, out: &mut AnsiLine) {
    out.text.clear();
    out.spans.clear();
    let mut run_start = 0usize;
    let mut run_style = *style;
    let bytes = raw.as_bytes();
    let mut i = 0usize;

    let close_run = |out: &mut AnsiLine, end: usize, start: usize, st: AnsiStyle| {
        if end > start {
            out.spans.push(AnsiSpan {
                start,
                end,
                style: st,
            });
        }
    };

    while i < bytes.len() {
        if bytes[i] != 0x1b {
            // Copy through to the next ESC in one go; `raw` is valid UTF-8 and
            // ESC never appears inside a multi-byte sequence, so slicing at an
            // ESC boundary is always a char boundary.
            let next = bytes[i..].iter().position(|&b| b == 0x1b);
            let end = next.map(|n| i + n).unwrap_or(bytes.len());
            out.text.push_str(&raw[i..end]);
            i = end;
            continue;
        }
        // An ESC at end-of-line has no sequence to close it: emit it as text
        // rather than swallowing a byte the file really contains.
        let Some(&next) = bytes.get(i + 1) else {
            out.text.push('\u{1b}');
            i += 1;
            continue;
        };
        match next {
            b'[' => {
                // CSI: params until a byte in 0x40..=0x7e ends it.
                let mut j = i + 2;
                while j < bytes.len() && !(0x40..=0x7e).contains(&bytes[j]) {
                    j += 1;
                }
                if j >= bytes.len() {
                    // Truncated sequence (the file ends mid-escape): drop it.
                    i = bytes.len();
                    continue;
                }
                if bytes[j] == b'm' {
                    let params = &raw[i + 2..j];
                    let end = out.text.len();
                    close_run(out, end, run_start, run_style);
                    apply_sgr(params, style);
                    run_start = end;
                    run_style = *style;
                }
                // Every other CSI final byte (cursor movement, erase, …) is
                // dropped: a transcript has no cursor to move.
                i = j + 1;
            }
            b']' => {
                // OSC: ends at BEL or ST (ESC \). Dropped entirely — a title
                // or hyperlink has no meaning in a static buffer.
                let mut j = i + 2;
                while j < bytes.len() {
                    if bytes[j] == 0x07 {
                        j += 1;
                        break;
                    }
                    if bytes[j] == 0x1b && bytes.get(j + 1) == Some(&b'\\') {
                        j += 2;
                        break;
                    }
                    j += 1;
                }
                i = j;
            }
            // Three-byte forms: charset selection (`ESC ( B`) and friends.
            b'(' | b')' | b'*' | b'+' | b'#' => i = next_boundary(raw, i + 3),
            // DCS / SOS / PM / APC carry a payload terminated like OSC, so
            // scanning to ST/BEL is the only way not to leak it as text.
            b'P' | b'X' | b'^' | b'_' => {
                let mut j = i + 2;
                while j < bytes.len() {
                    if bytes[j] == 0x07 {
                        j += 1;
                        break;
                    }
                    if bytes[j] == 0x1b && bytes.get(j + 1) == Some(&b'\\') {
                        j += 2;
                        break;
                    }
                    j += 1;
                }
                i = j;
            }
            // A two-byte escape is `ESC` + one ASCII final byte (RI, NEL,
            // DECSC…). If the byte after ESC is NOT ASCII, this is not an
            // escape at all — it is a stray ESC in the text before a real
            // character. Dropping just the ESC keeps the character, where
            // advancing two bytes would swallow it (and, before the boundary
            // guard, could land mid-character and panic on the next slice).
            _ if next.is_ascii() => i += 2,
            _ => {
                out.text.push('\u{1b}');
                i += 1;
            }
        }
    }
    let end = out.text.len();
    close_run(out, end, run_start, run_style);
}

/// The next char boundary at or after `i`, clamped to the string's length.
/// Escape-consuming arms advance by a fixed byte count, which can land inside
/// a multi-byte character when a file carries a stray ESC before UTF-8 text;
/// slicing there panics.
fn next_boundary(s: &str, i: usize) -> usize {
    let mut i = i.min(s.len());
    while i < s.len() && !s.is_char_boundary(i) {
        i += 1;
    }
    i
}

/// Apply one SGR parameter string to `style`. Unknown parameters are ignored
/// rather than aborting the sequence, matching what terminals do.
fn apply_sgr(params: &str, style: &mut AnsiStyle) {
    // A bare `ESC[m` means reset, same as `ESC[0m`.
    if params.is_empty() {
        style.reset();
        return;
    }
    let parts: Vec<&str> = params.split(';').collect();
    let mut k = 0usize;
    while k < parts.len() {
        // An empty parameter is a zero (`ESC[;31m` is reset then red).
        let n: u16 = if parts[k].is_empty() {
            0
        } else {
            match parts[k].parse() {
                Ok(v) => v,
                Err(_) => {
                    k += 1;
                    continue;
                }
            }
        };
        match n {
            0 => style.reset(),
            1 => style.bold = true,
            2 => style.dim = true,
            3 => style.italic = true,
            4 => style.underline = true,
            7 => style.inverse = true,
            9 => style.strikeout = true,
            22 => {
                style.bold = false;
                style.dim = false;
            }
            23 => style.italic = false,
            24 => style.underline = false,
            27 => style.inverse = false,
            29 => style.strikeout = false,
            30..=37 => style.fg = Some(AnsiColor::Indexed((n - 30) as u8)),
            39 => style.fg = None,
            40..=47 => style.bg = Some(AnsiColor::Indexed((n - 40) as u8)),
            49 => style.bg = None,
            // Bright aliases occupy palette slots 8..15.
            90..=97 => style.fg = Some(AnsiColor::Indexed((n - 90 + 8) as u8)),
            100..=107 => style.bg = Some(AnsiColor::Indexed((n - 100 + 8) as u8)),
            38 | 48 => {
                let (colour, consumed) = extended_color(&parts[k + 1..]);
                if let Some(c) = colour {
                    if n == 38 {
                        style.fg = Some(c);
                    } else {
                        style.bg = Some(c);
                    }
                }
                k += consumed;
            }
            _ => {}
        }
        k += 1;
    }
}

/// Parse the tail of a `38`/`48` sequence: `5;n` (palette) or `2;r;g;b`
/// (truecolor). Returns the colour and how many extra parameters it ate, so a
/// malformed sequence consumes what it can instead of desynchronising the
/// rest of the parameter list.
fn extended_color(rest: &[&str]) -> (Option<AnsiColor>, usize) {
    let num = |s: &str| s.parse::<u16>().ok();
    match rest.first().and_then(|s| num(s)) {
        Some(5) => match rest.get(1).and_then(|s| num(s)) {
            Some(v) if v < 256 => {
                let v = v as u8;
                // The low 16 stay symbolic so the theme palette owns them.
                let c = if v < 16 {
                    AnsiColor::Indexed(v)
                } else {
                    AnsiColor::Palette256(v)
                };
                (Some(c), 2)
            }
            _ => (None, 1),
        },
        Some(2) => {
            let r = rest.get(1).and_then(|s| num(s));
            let g = rest.get(2).and_then(|s| num(s));
            let b = rest.get(3).and_then(|s| num(s));
            match (r, g, b) {
                (Some(r), Some(g), Some(b)) if r < 256 && g < 256 && b < 256 => {
                    (Some(AnsiColor::Rgb(r as u8, g as u8, b as u8)), 4)
                }
                _ => (None, 1),
            }
        }
        _ => (None, 0),
    }
}

/// Whether `sample` looks like ANSI-coloured output: an SGR sequence in the
/// sniffed prefix. Deliberately narrower than "contains ESC" — a file full of
/// cursor movement is a terminal recording, not a colour log, and rendering
/// it as if the escapes were decoration would mislead.
pub fn looks_like_ansi(sample: &str) -> bool {
    let b = sample.as_bytes();
    for i in 0..b.len() {
        if b[i] != 0x1b || b.get(i + 1) != Some(&b'[') {
            continue;
        }
        let mut j = i + 2;
        while j < b.len() && !(0x40..=0x7e).contains(&b[j]) {
            j += 1;
        }
        if b.get(j) == Some(&b'm') {
            return true;
        }
    }
    false
}

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

    /// SGR 9 and 29 round-trip like the other attributes: a pane's
    /// struck-through cells come back struck through in the rendered log.
    #[test]
    fn strikeout_is_set_by_9_and_cleared_by_29() {
        let mut style = AnsiStyle::default();
        let line = parse_line("\x1b[9mgone\x1b[29m kept", &mut style);
        assert_eq!(line.text, "gone kept");
        let gone = line
            .spans
            .iter()
            .find(|s| s.start == 0)
            .expect("a span for the struck run");
        assert!(
            gone.style.strikeout,
            "SGR 9 sets strikeout: {:?}",
            line.spans
        );
        let kept = line.spans.iter().find(|s| s.start >= 4);
        assert!(
            kept.is_none_or(|s| !s.style.strikeout),
            "SGR 29 clears it: {:?}",
            line.spans
        );
    }

    fn parse(raw: &str) -> AnsiLine {
        let mut st = AnsiStyle::default();
        parse_line(raw, &mut st)
    }

    #[test]
    fn plain_text_yields_one_unstyled_span() {
        let l = parse("hello");
        assert_eq!(l.text, "hello");
        assert_eq!(l.spans.len(), 1);
        assert_eq!(l.spans[0].style, AnsiStyle::default());
    }

    #[test]
    fn basic_colors_map_to_palette_slots_and_text_is_stripped() {
        let l = parse("\u{1b}[31mred\u{1b}[0m plain");
        assert_eq!(l.text, "red plain", "escapes never reach the text");
        assert_eq!(l.spans[0].style.fg, Some(AnsiColor::Indexed(1)));
        assert_eq!(&l.text[l.spans[0].start..l.spans[0].end], "red");
        assert_eq!(l.spans[1].style, AnsiStyle::default());
    }

    #[test]
    fn bright_aliases_land_in_the_upper_palette_half() {
        let l = parse("\u{1b}[91mbright\u{1b}[0m");
        assert_eq!(l.spans[0].style.fg, Some(AnsiColor::Indexed(9)));
        let l = parse("\u{1b}[103mbg\u{1b}[0m");
        assert_eq!(l.spans[0].style.bg, Some(AnsiColor::Indexed(11)));
    }

    #[test]
    fn palette_and_truecolor_parse_with_their_parameters_consumed() {
        let l = parse("\u{1b}[38;5;208morange\u{1b}[0m");
        assert_eq!(l.spans[0].style.fg, Some(AnsiColor::Palette256(208)));
        let l = parse("\u{1b}[38;2;10;20;30mrgb\u{1b}[0m");
        assert_eq!(l.spans[0].style.fg, Some(AnsiColor::Rgb(10, 20, 30)));
        // The low 16 stay symbolic even when spelled the 256-colour way, so
        // the theme palette still owns them.
        let l = parse("\u{1b}[38;5;3myellow\u{1b}[0m");
        assert_eq!(l.spans[0].style.fg, Some(AnsiColor::Indexed(3)));
    }

    #[test]
    fn a_truecolor_sequence_does_not_swallow_following_attributes() {
        // The r;g;b parameters must be consumed, or the `1` below would be
        // read as a colour component and bold would be lost.
        let l = parse("\u{1b}[38;2;1;2;3;1mx\u{1b}[0m");
        assert_eq!(l.spans[0].style.fg, Some(AnsiColor::Rgb(1, 2, 3)));
        assert!(l.spans[0].style.bold, "the trailing 1 is still bold");
    }

    #[test]
    fn attributes_set_and_clear_independently() {
        let l = parse("\u{1b}[1;3;4ma\u{1b}[23mb\u{1b}[24mc\u{1b}[22md");
        assert!(l.spans[0].style.bold && l.spans[0].style.italic && l.spans[0].style.underline);
        assert!(!l.spans[1].style.italic && l.spans[1].style.underline);
        assert!(!l.spans[2].style.underline && l.spans[2].style.bold);
        assert!(!l.spans[3].style.bold);
    }

    #[test]
    fn non_sgr_escapes_are_stripped_not_rendered() {
        // Cursor movement, erase-line, and OSC titles carry no meaning in a
        // static buffer; none of them may leak into the text.
        let l = parse("\u{1b}[2Ka\u{1b}[10;20Hb\u{1b}]0;title\u{7}c");
        assert_eq!(l.text, "abc");
        let l = parse("\u{1b}]8;;https://example.com\u{1b}\\link\u{1b}]8;;\u{1b}\\");
        assert_eq!(l.text, "link", "OSC-8 hyperlinks strip to their label");
    }

    #[test]
    fn style_carries_across_lines_like_a_terminal() {
        let mut st = AnsiStyle::default();
        let a = parse_line("\u{1b}[31mred starts", &mut st);
        let b = parse_line("still red", &mut st);
        assert_eq!(a.spans[0].style.fg, Some(AnsiColor::Indexed(1)));
        assert_eq!(
            b.spans[0].style.fg,
            Some(AnsiColor::Indexed(1)),
            "no reset means the next line stays red"
        );
        let c = parse_line("\u{1b}[0mplain", &mut st);
        assert_eq!(c.spans[0].style.fg, None);
    }

    #[test]
    fn malformed_and_truncated_sequences_do_not_panic_or_eat_text() {
        assert_eq!(parse("\u{1b}[999999999999m x").text, " x");
        assert_eq!(parse("\u{1b}[38;5mtruncated").text, "truncated");
        assert_eq!(parse("\u{1b}[38;2;1;2mshort").text, "short");
        // A trailing ESC is real content, not the start of a sequence.
        assert_eq!(parse("tail\u{1b}").text, "tail\u{1b}");
        // Unterminated CSI at EOF: dropped, and nothing after it exists.
        assert_eq!(parse("head\u{1b}[31").text, "head");
    }

    #[test]
    fn multibyte_text_survives_slicing_at_escape_boundaries() {
        let l = parse("héllo \u{1b}[31mwörld 🙂\u{1b}[0m ok");
        assert_eq!(l.text, "héllo wörld 🙂 ok");
        // Spans are byte offsets into the stripped text, so slicing them must
        // land on char boundaries.
        for s in &l.spans {
            assert!(l.text.is_char_boundary(s.start) && l.text.is_char_boundary(s.end));
        }
        assert_eq!(&l.text[l.spans[1].start..l.spans[1].end], "wörld 🙂");
    }

    #[test]
    fn bare_and_empty_sgr_parameters_reset() {
        let mut st = AnsiStyle {
            bold: true,
            fg: Some(AnsiColor::Indexed(2)),
            ..Default::default()
        };
        parse_line("\u{1b}[mx", &mut st);
        assert_eq!(st, AnsiStyle::default(), "ESC[m is a reset");
        let l = parse("\u{1b}[1m\u{1b}[;31mx");
        assert_eq!(
            l.spans.last().unwrap().style.fg,
            Some(AnsiColor::Indexed(1))
        );
        assert!(
            !l.spans.last().unwrap().style.bold,
            "the empty parameter reset bold before red applied"
        );
    }

    #[test]
    fn sniffing_requires_an_sgr_sequence_not_just_an_escape() {
        assert!(looks_like_ansi("plain \u{1b}[31mred"));
        assert!(looks_like_ansi("\u{1b}[1;32mok"));
        assert!(
            !looks_like_ansi("\u{1b}[2J\u{1b}[10;1H"),
            "a screen recording is not a colour log"
        );
        assert!(!looks_like_ansi("no escapes here"));
        assert!(!looks_like_ansi("\u{1b}[31"), "truncated is not a match");
    }

    #[test]
    fn an_escape_before_a_multibyte_char_does_not_panic() {
        // The two-byte-escape arm advanced past ESC + one byte
        // unconditionally, landing inside a multi-byte character and
        // panicking on the next slice.
        // ESC before a non-ASCII byte is not an escape sequence at all, so
        // the ESC is kept as content (same rule as a trailing ESC) and the
        // character survives — the old code swallowed it, or panicked.
        assert_eq!(parse("\u{1b}\u{e9} tail").text, "\u{1b}\u{e9} tail");
        assert_eq!(parse("\u{1b}\u{1F642} tail").text, "\u{1b}\u{1F642} tail");
        // A real two-byte escape still disappears.
        assert_eq!(parse("\u{1b}7saved").text, "saved");
    }

    /// #1501: a debug adapter cuts output anywhere, so the console holds back
    /// a sequence the chunk ends inside of, and only that.
    #[test]
    fn an_unfinished_escape_at_the_end_is_measured() {
        assert_eq!(unfinished_escape_len("ok \u{1b}[3"), 3);
        assert_eq!(unfinished_escape_len("ok \u{1b}["), 2);
        assert_eq!(unfinished_escape_len("ok \u{1b}"), 1);
        assert_eq!(unfinished_escape_len("\u{1b}]0;title"), 9);
        assert_eq!(unfinished_escape_len("a\n\u{1b}[1;3"), 5);
    }

    #[test]
    fn a_finished_escape_or_plain_text_holds_nothing_back() {
        assert_eq!(unfinished_escape_len(""), 0);
        assert_eq!(unfinished_escape_len("plain [31m text"), 0);
        assert_eq!(unfinished_escape_len("\u{1b}[31mred\u{1b}[0m"), 0);
        assert_eq!(unfinished_escape_len("\u{1b}]0;title\u{7}after"), 0);
        assert_eq!(unfinished_escape_len("\u{1b}]8;;x\u{1b}\\"), 0);
        // A newline ends the line the cut sequence was on.
        assert_eq!(unfinished_escape_len("\u{1b}[3\nnext"), 0);
    }

    fn texts(lines: &[AnsiLine]) -> Vec<&str> {
        lines.iter().map(|l| l.text.as_str()).collect()
    }

    /// #932: a debug adapter's output event is a chunk, not a line. A line
    /// cut between two chunks is one line, and an empty `print()` is a blank
    /// line rather than nothing.
    #[test]
    fn a_stream_ends_lines_at_newlines_not_at_chunks() {
        let mut stream = AnsiStream::default();
        assert_eq!(texts(&stream.feed("print: i =")), Vec::<&str>::new());
        assert_eq!(stream.open_line().unwrap().text, "print: i =");
        let mut lines = stream.feed(" 0\n");
        assert_eq!(stream.open_line(), None);
        for chunk in ["\n", "Section 2\n"] {
            lines.extend(stream.feed(chunk));
        }
        assert_eq!(texts(&lines), ["print: i = 0", "", "Section 2"]);
        assert_eq!(texts(&stream.feed("a\n\nb\r\nc")), ["a", "", "b"]);
        assert_eq!(stream.finish().unwrap().text, "c");
        assert_eq!(stream.finish(), None);
    }

    /// #932: a carriage return rewrites the open line, so a progress bar
    /// redraws in place, while `\r\n` only ends it.
    #[test]
    fn a_carriage_return_rewrites_the_open_line() {
        let mut stream = AnsiStream::default();
        stream.feed("\r 10%|#");
        stream.feed("\r 50%|#####");
        assert_eq!(stream.open_line().unwrap().text, " 50%|#####");
        stream.feed("\r");
        assert_eq!(
            stream.open_line().unwrap().text,
            " 50%|#####",
            "a bare \\r keeps the line until new text replaces it"
        );
        assert_eq!(
            texts(&stream.feed("100%|##########\n")),
            ["100%|##########"]
        );
        assert_eq!(texts(&stream.feed("done\r")), Vec::<&str>::new());
        assert_eq!(texts(&stream.feed("\n")), ["done"]);
    }

    /// A colour carries across the chunks of one line, its runs joined.
    #[test]
    fn an_open_line_keeps_its_colour_across_chunks() {
        let mut stream = AnsiStream::default();
        stream.feed("\u{1b}[31mred");
        let line = stream.feed(" still\u{1b}[0m plain\n").remove(0);
        assert_eq!(line.text, "red still plain");
        assert_eq!(line.spans.len(), 2, "{:?}", line.spans);
        assert_eq!(
            (line.spans[0].end, line.spans[0].style.fg),
            (9, Some(AnsiColor::Indexed(1)))
        );
        assert_eq!(line.spans[1].style.fg, None);
    }

    /// A line that never ends is ended at the cap, so it cannot grow
    /// without bound.
    #[test]
    fn an_open_line_is_ended_at_the_cap() {
        let mut stream = AnsiStream::default();
        let mut ended = Vec::new();
        for _ in 0..OPEN_LINE_CAP {
            ended.extend(stream.feed("."));
        }
        assert_eq!(ended.len(), 1);
        assert_eq!(ended[0].text.len(), OPEN_LINE_CAP);
        assert_eq!(ended[0].spans.len(), 1, "one run, not one per dot");
        assert_eq!(stream.open_line(), None);
    }

    /// An escape that never ends (an OSC with no terminator) is held back
    /// only up to its cap and then dropped, so it cannot grow without bound,
    /// and the output after it still comes through.
    #[test]
    fn an_unfinished_escape_is_dropped_at_its_cap() {
        let mut stream = AnsiStream::default();
        stream.feed("\u{1b}]0;");
        let chunk = "x".repeat(1024);
        for _ in 0..ESCAPE_CAP / chunk.len() + 2 {
            stream.feed(&chunk);
            assert!(
                stream.cut.len() <= ESCAPE_CAP,
                "{} held back",
                stream.cut.len()
            );
        }
        let ended = stream.feed("done\n");
        assert!(ended.last().unwrap().text.ends_with("done"));
    }

    #[test]
    fn a_prefix_moves_the_spans_with_their_text() {
        let mut style = AnsiStyle::default();
        let mut line = parse_line("\u{1b}[31mred\u{1b}[0m done", &mut style);
        line.prefix("[A] ");
        assert_eq!(line.text, "[A] red done");
        let red: Vec<&str> = line
            .spans
            .iter()
            .filter(|s| s.style.fg == Some(AnsiColor::Indexed(1)))
            .map(|s| &line.text[s.start..s.end])
            .collect();
        assert_eq!(red, vec!["red"]);
        assert_eq!(line.spans[0].style, AnsiStyle::default());
        assert_eq!(AnsiLine::plain("").spans, Vec::new());
        assert_eq!(AnsiLine::plain("x").text, "x");
    }
}