pixel8-console 0.1.0

Pixel8: a PICO-8-like fantasy console for Rust games
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
//! The code editor: 31 columns of Rust in a 4x7 pixel font, with the
//! classic immediate cursor feel. Not an IDE — a place to type games.

use super::history::History;
use crate::{
    shell::{Key, Mods},
    ui::{self, Mouse},
};
use pixel8_runtime::{fb::Framebuffer, font, palette::col};

/// An undo snapshot of the buffer: the lines plus the cursor position, so undo
/// restores where the cursor was as well as the text.
type Snapshot = (Vec<String>, usize, usize);

/// Visible text geometry. The row count is derived from the font's line height
/// so the text never overruns the status bar (the bottom 8 rows of the screen).
const AREA_X: i32 = 1;
const AREA_Y: i32 = 9;
const ROWS: usize = ((120 - AREA_Y) / font::GLYPH_H) as usize;
const COLS: usize = 31;

/// Syntax colors, chosen from the fixed palette.
const C_TEXT: u8 = col::WHITE;
const C_KEYWORD: u8 = col::PINK;
const C_STRING: u8 = col::GREEN;
const C_NUMBER: u8 = col::BLUE;
const C_COMMENT: u8 = col::LAVENDER;
const C_TYPE: u8 = col::YELLOW;
const C_MACRO: u8 = col::ORANGE;
const C_PUNCT: u8 = col::LIGHT_GREY;

const KEYWORDS: &[&str] = &[
    "as", "async", "await", "break", "const", "continue", "crate", "dyn", "else", "enum", "extern",
    "false", "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub",
    "ref", "return", "self", "Self", "static", "struct", "super", "trait", "true", "type",
    "unsafe", "use", "where", "while",
];

pub struct CodeEditor {
    lines: Vec<String>,
    line: usize,
    col: usize,
    pref_col: usize,
    scroll_y: usize,
    scroll_x: usize,
    anchor: Option<(usize, usize)>,
    status: ui::StatusMsg,
    history: History<Snapshot>,
    frame: u64,
}

impl CodeEditor {
    pub fn new() -> Self {
        Self {
            lines: vec![String::new()],
            line: 0,
            col: 0,
            pref_col: 0,
            scroll_y: 0,
            scroll_x: 0,
            anchor: None,
            status: ui::StatusMsg::default(),
            history: History::new(),
            frame: 0,
        }
    }

    /// Load text, keeping the cursor when the text is unchanged (so
    /// switching tabs back and forth doesn't lose your place).
    pub fn set_text(&mut self, text: &str) {
        let new: Vec<String> = if text.is_empty() {
            vec![String::new()]
        } else {
            text.split('\n').map(str::to_string).collect()
        };
        if new != self.lines {
            self.lines = new;
            self.line = 0;
            self.col = 0;
            self.scroll_y = 0;
            self.scroll_x = 0;
            self.anchor = None;
            self.history.clear();
        }
    }

    pub fn text(&self) -> String {
        self.lines.join("\n")
    }

    /// Copy the selection for the system clipboard, or `None` when nothing is
    /// selected.
    pub fn copy(&mut self, code: &str) -> Option<String> {
        self.set_text(code);
        let text = self.selected_text();
        if text.is_empty() {
            return None;
        }
        self.status.set(clip_msg("copied", &text));
        Some(text)
    }

    /// Cut the selection: return it for the clipboard and remove it from `code`.
    pub fn cut(&mut self, code: &mut String) -> Option<String> {
        self.set_text(code);
        let text = self.selected_text();
        if text.is_empty() {
            return None;
        }
        self.push_undo();
        self.delete_selection();
        let snap = self.snapshot();
        self.history.commit(&snap);
        self.scroll_to_cursor();
        *code = self.text();
        self.status.set(clip_msg("cut", &text));
        Some(text)
    }

    /// Insert clipboard `text` at the cursor, replacing any selection.
    pub fn paste_text(&mut self, code: &mut String, text: &str) {
        self.set_text(code);
        if text.is_empty() {
            return;
        }
        self.push_undo();
        self.delete_selection();
        self.insert_str(text);
        let snap = self.snapshot();
        self.history.commit(&snap);
        self.scroll_to_cursor();
        *code = self.text();
        self.status.set(clip_msg("pasted", text));
    }

    /// Set a transient bottom-bar message.
    pub fn set_status(&mut self, msg: String) {
        self.status.set(msg);
    }

    fn clamp_cursor(&mut self) {
        self.line = self.line.min(self.lines.len() - 1);
        self.col = self.col.min(self.lines[self.line].chars().count());
    }

    fn snapshot(&self) -> Snapshot {
        (self.lines.clone(), self.line, self.col)
    }

    /// Open an undo step, snapshotting the buffer before an edit. Idempotent
    /// within a single `key` call, so one keypress is one undo step.
    fn push_undo(&mut self) {
        let snap = self.snapshot();
        self.history.begin(&snap);
    }

    /// Replace the buffer from an undo/redo snapshot.
    fn restore(&mut self, snap: Snapshot) {
        let (lines, line, col) = snap;
        self.lines = lines;
        self.line = line;
        self.col = col;
        self.anchor = None;
        self.clamp_cursor();
    }

    fn byte_idx(s: &str, char_idx: usize) -> usize {
        s.char_indices()
            .nth(char_idx)
            .map(|(i, _)| i)
            .unwrap_or(s.len())
    }

    fn selection(&self) -> Option<((usize, usize), (usize, usize))> {
        let a = self.anchor?;
        let b = (self.line, self.col);
        if a == b {
            return None;
        }
        Some(if a < b { (a, b) } else { (b, a) })
    }

    fn delete_selection(&mut self) -> bool {
        let Some(((l0, c0), (l1, c1))) = self.selection() else {
            return false;
        };
        let head = self.lines[l0][..Self::byte_idx(&self.lines[l0], c0)].to_string();
        let tail = self.lines[l1][Self::byte_idx(&self.lines[l1], c1)..].to_string();
        self.lines.splice(l0..=l1, [head + &tail]);
        self.line = l0;
        self.col = c0;
        self.anchor = None;
        true
    }

    fn selected_text(&self) -> String {
        let Some(((l0, c0), (l1, c1))) = self.selection() else {
            return String::new();
        };
        if l0 == l1 {
            let s = &self.lines[l0];
            return s[Self::byte_idx(s, c0)..Self::byte_idx(s, c1)].to_string();
        }
        let mut out = self.lines[l0][Self::byte_idx(&self.lines[l0], c0)..].to_string();
        for l in &self.lines[l0 + 1..l1] {
            out.push('\n');
            out.push_str(l);
        }
        out.push('\n');
        out.push_str(&self.lines[l1][..Self::byte_idx(&self.lines[l1], c1)]);
        out
    }

    fn insert_str(&mut self, text: &str) {
        for c in text.chars() {
            if c == '\n' {
                let at = Self::byte_idx(&self.lines[self.line], self.col);
                let rest = self.lines[self.line].split_off(at);
                self.lines.insert(self.line + 1, rest);
                self.line += 1;
                self.col = 0;
            } else {
                let at = Self::byte_idx(&self.lines[self.line], self.col);
                self.lines[self.line].insert(at, c);
                self.col += 1;
            }
        }
    }

    fn move_cursor(&mut self, key: Key, mods: Mods) {
        if mods.shift {
            if self.anchor.is_none() {
                self.anchor = Some((self.line, self.col));
            }
        } else {
            self.anchor = None;
        }
        match key {
            Key::Left => {
                if self.col > 0 {
                    self.col -= 1;
                } else if self.line > 0 {
                    self.line -= 1;
                    self.col = self.lines[self.line].chars().count();
                }
                self.pref_col = self.col;
            }
            Key::Right => {
                if self.col < self.lines[self.line].chars().count() {
                    self.col += 1;
                } else if self.line + 1 < self.lines.len() {
                    self.line += 1;
                    self.col = 0;
                }
                self.pref_col = self.col;
            }
            Key::Up => {
                self.line = self.line.saturating_sub(1);
                self.col = self.pref_col;
                self.clamp_cursor();
            }
            Key::Down => {
                self.line = (self.line + 1).min(self.lines.len() - 1);
                self.col = self.pref_col;
                self.clamp_cursor();
            }
            Key::Home => {
                self.col = 0;
                self.pref_col = 0;
            }
            Key::End => {
                self.col = self.lines[self.line].chars().count();
                self.pref_col = self.col;
            }
            Key::PageUp => {
                self.line = self.line.saturating_sub(ROWS);
                self.col = self.pref_col;
                self.clamp_cursor();
            }
            Key::PageDown => {
                self.line = (self.line + ROWS).min(self.lines.len() - 1);
                self.col = self.pref_col;
                self.clamp_cursor();
            }
            _ => {}
        }
    }

    pub fn key(&mut self, key: Key, mods: Mods, code: &mut String) {
        self.set_text(code);
        match key {
            Key::Left
            | Key::Right
            | Key::Up
            | Key::Down
            | Key::Home
            | Key::End
            | Key::PageUp
            | Key::PageDown => self.move_cursor(key, mods),
            Key::Char(c) if mods.ctrl => match c.to_ascii_lowercase() {
                'a' => {
                    self.anchor = Some((0, 0));
                    self.line = self.lines.len() - 1;
                    self.col = self.lines[self.line].chars().count();
                }
                // Ctrl+Z undoes; Ctrl+Shift+Z and Ctrl+Y redo.
                'z' if mods.shift => {
                    let mut snap = self.snapshot();
                    if self.history.redo(&mut snap) {
                        self.restore(snap);
                    }
                }
                'z' => {
                    let mut snap = self.snapshot();
                    if self.history.undo(&mut snap) {
                        self.restore(snap);
                    }
                }
                'y' => {
                    let mut snap = self.snapshot();
                    if self.history.redo(&mut snap) {
                        self.restore(snap);
                    }
                }
                _ => {}
            },
            Key::Char(c) => {
                self.push_undo();
                self.delete_selection();
                let mut buf = [0u8; 4];
                self.insert_str(c.encode_utf8(&mut buf));
                self.pref_col = self.col;
            }
            Key::Tab => {
                self.push_undo();
                self.delete_selection();
                self.insert_str("  ");
            }
            Key::Enter => {
                self.push_undo();
                self.delete_selection();
                // Auto-indent: carry the current line's leading spaces.
                let indent: String = self.lines[self.line]
                    .chars()
                    .take_while(|c| *c == ' ')
                    .take(self.col)
                    .collect();
                self.insert_str(&format!("\n{indent}"));
                self.pref_col = self.col;
            }
            Key::Backspace => {
                self.push_undo();
                if !self.delete_selection() {
                    if self.col > 0 {
                        let at = Self::byte_idx(&self.lines[self.line], self.col - 1);
                        self.lines[self.line].remove(at);
                        self.col -= 1;
                    } else if self.line > 0 {
                        let cur = self.lines.remove(self.line);
                        self.line -= 1;
                        self.col = self.lines[self.line].chars().count();
                        self.lines[self.line].push_str(&cur);
                    }
                }
                self.pref_col = self.col;
            }
            Key::Delete => {
                self.push_undo();
                if !self.delete_selection() {
                    let len = self.lines[self.line].chars().count();
                    if self.col < len {
                        let at = Self::byte_idx(&self.lines[self.line], self.col);
                        self.lines[self.line].remove(at);
                    } else if self.line + 1 < self.lines.len() {
                        let next = self.lines.remove(self.line + 1);
                        self.lines[self.line].push_str(&next);
                    }
                }
            }
            Key::Escape | Key::CaptureLabel | Key::ToggleStats => {}
        }
        // Close the undo step opened by this keypress (a no-op when nothing
        // changed, e.g. cursor motion or an undo/redo that already closed it).
        let snap = self.snapshot();
        self.history.commit(&snap);
        self.scroll_to_cursor();
        *code = self.text();
    }

    fn scroll_to_cursor(&mut self) {
        if self.line < self.scroll_y {
            self.scroll_y = self.line;
        }
        if self.line >= self.scroll_y + ROWS {
            self.scroll_y = self.line - ROWS + 1;
        }
        if self.col < self.scroll_x {
            self.scroll_x = self.col;
        }
        if self.col >= self.scroll_x + COLS {
            self.scroll_x = self.col - COLS + 1;
        }
    }

    pub fn tick(&mut self, mouse: &Mouse, code: &str) {
        self.status.tick();
        self.set_text(code);
        self.frame += 1;
        let in_area = mouse.y >= AREA_Y && mouse.y < AREA_Y + (ROWS as i32) * font::GLYPH_H;
        if (mouse.left_pressed || mouse.left) && in_area {
            let l = (self.scroll_y as i32 + (mouse.y - AREA_Y) / font::GLYPH_H).max(0) as usize;
            let c = (self.scroll_x as i32 + (mouse.x - AREA_X) / 4).max(0) as usize;
            if mouse.left_pressed {
                self.anchor = None;
                self.line = l.min(self.lines.len() - 1);
                self.col = c;
                self.clamp_cursor();
                self.anchor = Some((self.line, self.col));
            } else {
                // Drag-select.
                self.line = l.min(self.lines.len() - 1);
                self.col = c;
                self.clamp_cursor();
            }
            self.pref_col = self.col;
        }
        if !mouse.left {
            if let Some(a) = self.anchor {
                if a == (self.line, self.col) {
                    self.anchor = None;
                }
            }
        }
    }

    pub fn draw(&self, fb: &mut Framebuffer, code: &str) {
        let lines: Vec<&str> = if code.is_empty() {
            vec![""]
        } else {
            code.split('\n').collect()
        };
        fb.rectfill(0, 8, 127, 119, col::BLACK);

        // Block-comment state up to the first visible line.
        let mut in_block = false;
        for l in lines.iter().take(self.scroll_y) {
            in_block = scan_block_state(l, in_block);
        }

        let sel = self.selection();
        for row in 0..ROWS {
            let li = self.scroll_y + row;
            let Some(line) = lines.get(li) else { break };
            let y = AREA_Y + row as i32 * font::GLYPH_H;

            // Selection background.
            if let Some(((l0, c0), (l1, c1))) = sel {
                if li >= l0 && li <= l1 {
                    let len = line.chars().count();
                    let s = if li == l0 { c0 } else { 0 };
                    let e = if li == l1 { c1 } else { len + 1 };
                    let (s, e) = (
                        s.saturating_sub(self.scroll_x),
                        e.saturating_sub(self.scroll_x),
                    );
                    if e > s {
                        fb.rectfill(
                            AREA_X + s as i32 * 4,
                            y - 1,
                            (AREA_X + e as i32 * 4 - 1).min(127),
                            y + font::GLYPH_H - 2,
                            col::DARK_BLUE,
                        );
                    }
                }
            }

            // Highlighted text.
            let spans = highlight(line, &mut in_block);
            for (start, text, color) in spans {
                let vis_start = start as i32 - self.scroll_x as i32;
                for (i, ch) in text.chars().enumerate() {
                    let cx = vis_start + i as i32;
                    if (0..COLS as i32).contains(&cx) {
                        fb.print(ch.encode_utf8(&mut [0u8; 4]), AREA_X + cx * 4, y, color);
                    }
                }
            }
        }

        // Cursor (blinking).
        if (self.frame / 8).is_multiple_of(2) {
            let cy = self.line as i32 - self.scroll_y as i32;
            let cx = self.col as i32 - self.scroll_x as i32;
            if (0..ROWS as i32).contains(&cy) && (0..=COLS as i32).contains(&cx) {
                fb.rectfill(
                    AREA_X + cx * 4,
                    AREA_Y + cy * font::GLYPH_H - 1,
                    AREA_X + cx * 4 + 3,
                    AREA_Y + cy * font::GLYPH_H + font::GLYPH_H - 2,
                    col::RED,
                );
            }
        }

        let info = format!("L{}/{} C{}", self.line + 1, lines.len(), self.col + 1);
        self.status.show(fb, &info);
    }
}

/// A copy/cut/paste message sized to the text: lines when it spans more than
/// one, else characters.
fn clip_msg(verb: &str, text: &str) -> String {
    if text.contains('\n') {
        format!("{verb} {} lines", text.matches('\n').count() + 1)
    } else {
        format!("{verb} {} chars", text.chars().count())
    }
}

/// Track whether a line ends inside a `/* */` block comment.
fn scan_block_state(line: &str, mut in_block: bool) -> bool {
    let b = line.as_bytes();
    let mut i = 0;
    while i + 1 < b.len() {
        if in_block {
            if &b[i..i + 2] == b"*/" {
                in_block = false;
                i += 2;
                continue;
            }
        } else {
            if &b[i..i + 2] == b"//" {
                return in_block;
            }
            if &b[i..i + 2] == b"/*" {
                in_block = true;
                i += 2;
                continue;
            }
        }
        i += 1;
    }
    in_block
}

/// Split a line into colored spans: `(start_col, text, color)`.
fn highlight<'a>(line: &'a str, in_block: &mut bool) -> Vec<(usize, &'a str, u8)> {
    let mut out = Vec::new();
    let chars: Vec<char> = line.chars().collect();
    let n = chars.len();
    let mut i = 0;

    let slice = |a: usize, b: usize| -> &'a str {
        let start = line
            .char_indices()
            .nth(a)
            .map(|(i, _)| i)
            .unwrap_or(line.len());
        let end = line
            .char_indices()
            .nth(b)
            .map(|(i, _)| i)
            .unwrap_or(line.len());
        &line[start..end]
    };

    while i < n {
        // Inside a block comment: eat until */.
        if *in_block {
            let start = i;
            while i < n {
                if chars[i] == '*' && i + 1 < n && chars[i + 1] == '/' {
                    i += 2;
                    *in_block = false;
                    break;
                }
                i += 1;
            }
            out.push((start, slice(start, i), C_COMMENT));
            continue;
        }
        let c = chars[i];
        // Line comment.
        if c == '/' && i + 1 < n && chars[i + 1] == '/' {
            out.push((i, slice(i, n), C_COMMENT));
            break;
        }
        // Block comment start.
        if c == '/' && i + 1 < n && chars[i + 1] == '*' {
            *in_block = true;
            i += 2;
            continue;
        }
        // String literal.
        if c == '"' {
            let start = i;
            i += 1;
            while i < n {
                if chars[i] == '\\' {
                    i += 2;
                    continue;
                }
                if chars[i] == '"' {
                    i += 1;
                    break;
                }
                i += 1;
            }
            let i2 = i.min(n);
            out.push((start, slice(start, i2), C_STRING));
            i = i2;
            continue;
        }
        // Number.
        if c.is_ascii_digit() {
            let start = i;
            while i < n && (chars[i].is_ascii_alphanumeric() || chars[i] == '.' || chars[i] == '_')
            {
                i += 1;
            }
            out.push((start, slice(start, i), C_NUMBER));
            continue;
        }
        // Identifier / keyword / type / macro.
        if c.is_alphabetic() || c == '_' {
            let start = i;
            while i < n && (chars[i].is_alphanumeric() || chars[i] == '_') {
                i += 1;
            }
            let word = slice(start, i);
            let color = if i < n && chars[i] == '!' {
                C_MACRO
            } else if KEYWORDS.contains(&word) {
                C_KEYWORD
            } else if word.chars().next().is_some_and(|c| c.is_uppercase()) {
                C_TYPE
            } else {
                C_TEXT
            };
            out.push((start, word, color));
            continue;
        }
        // Attribute marker.
        if c == '#' {
            out.push((i, slice(i, i + 1), C_MACRO));
            i += 1;
            continue;
        }
        // Whitespace: skip.
        if c == ' ' {
            i += 1;
            continue;
        }
        // Everything else is punctuation.
        let start = i;
        i += 1;
        out.push((start, slice(start, i), C_PUNCT));
    }
    out
}

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

    fn ed_with(text: &str) -> (CodeEditor, String) {
        let mut e = CodeEditor::new();
        e.set_text(text);
        (e, text.to_string())
    }

    #[test]
    fn typing_inserts() {
        let (mut e, mut code) = ed_with("");
        for c in "fn main".chars() {
            e.key(Key::Char(c), Mods::default(), &mut code);
        }
        assert_eq!(code, "fn main");
    }

    #[test]
    fn enter_auto_indents() {
        let (mut e, mut code) = ed_with("  abc");
        e.key(Key::End, Mods::default(), &mut code);
        e.key(Key::Enter, Mods::default(), &mut code);
        assert_eq!(code, "  abc\n  ");
    }

    #[test]
    fn backspace_joins_lines() {
        let (mut e, mut code) = ed_with("ab\ncd");
        e.key(Key::Down, Mods::default(), &mut code);
        e.key(Key::Home, Mods::default(), &mut code);
        e.key(Key::Backspace, Mods::default(), &mut code);
        assert_eq!(code, "abcd");
    }

    #[test]
    fn select_all_cut_paste() {
        let (mut e, mut code) = ed_with("hello\nworld");
        let ctrl = Mods {
            ctrl: true,
            ..Default::default()
        };
        e.key(Key::Char('a'), ctrl, &mut code); // select all
        let cut = e.cut(&mut code).unwrap();
        assert_eq!(cut, "hello\nworld");
        assert_eq!(code, "");
        e.paste_text(&mut code, &cut);
        assert_eq!(code, "hello\nworld");
    }

    #[test]
    fn copy_reports_size() {
        let (mut e, mut code) = ed_with("hello\nworld");
        let ctrl = Mods {
            ctrl: true,
            ..Default::default()
        };
        e.key(Key::Char('a'), ctrl, &mut code); // select all
        assert_eq!(e.copy(&code).unwrap(), "hello\nworld");
        assert_eq!(e.status.current(), Some("copied 2 lines"));
    }

    #[test]
    fn undo_restores() {
        let (mut e, mut code) = ed_with("abc");
        e.key(Key::End, Mods::default(), &mut code);
        e.key(Key::Char('!'), Mods::default(), &mut code);
        assert_eq!(code, "abc!");
        e.key(
            Key::Char('z'),
            Mods {
                ctrl: true,
                ..Default::default()
            },
            &mut code,
        );
        assert_eq!(code, "abc");
    }

    #[test]
    fn redo_reapplies_an_undone_edit() {
        let (mut e, mut code) = ed_with("abc");
        let ctrl = Mods {
            ctrl: true,
            ..Default::default()
        };
        let ctrl_shift = Mods {
            ctrl: true,
            shift: true,
            ..Default::default()
        };
        e.key(Key::End, Mods::default(), &mut code);
        e.key(Key::Char('!'), Mods::default(), &mut code);
        assert_eq!(code, "abc!");
        e.key(Key::Char('z'), ctrl, &mut code); // undo
        assert_eq!(code, "abc");
        // Ctrl+Shift+Z arrives as an uppercase 'Z' from the keyboard layer.
        e.key(Key::Char('Z'), ctrl_shift, &mut code);
        assert_eq!(code, "abc!", "redo reapplies the typed character");
        // A fresh edit clears the redo stack.
        e.key(Key::Char('z'), ctrl, &mut code); // undo back to "abc"
        e.key(Key::Char('?'), Mods::default(), &mut code);
        assert_eq!(code, "abc?");
        e.key(Key::Char('Z'), ctrl_shift, &mut code); // nothing to redo
        assert_eq!(code, "abc?");
    }

    #[test]
    fn highlight_classifies() {
        let mut in_block = false;
        let spans = highlight("let x = \"hi\"; // c", &mut in_block);
        let find = |text: &str| spans.iter().find(|(_, t, _)| *t == text).unwrap().2;
        assert_eq!(find("let"), C_KEYWORD);
        assert_eq!(find("x"), C_TEXT);
        assert_eq!(find("\"hi\""), C_STRING);
        assert_eq!(find("// c"), C_COMMENT);
    }

    #[test]
    fn block_comment_state_tracks() {
        assert!(scan_block_state("a /* b", false));
        assert!(!scan_block_state("b */ c", true));
        assert!(!scan_block_state("// /* not", false));
    }

    #[test]
    fn paste_scrolls_cursor_into_view() {
        let (mut e, mut code) = ed_with("");
        let many: String = (0..50)
            .map(|i| format!("l{i}"))
            .collect::<Vec<_>>()
            .join("\n");
        e.paste_text(&mut code, &many);
        // Cursor ends on the last pasted line; it must be within the visible window.
        assert!(e.line >= e.scroll_y && e.line < e.scroll_y + ROWS);
    }

    #[test]
    fn status_messages_fit_the_bar() {
        use pixel8_runtime::{fb::WIDTH, font::text_width};
        let budget = WIDTH - 2;
        // Realistic large selections: a 7-digit char count and line count both
        // stay well within the bar. Counts are display-only, not stored sizes.
        assert!(text_width(&clip_msg("pasted", &"x\n".repeat(1_000_000))) <= budget);
        assert!(text_width(&clip_msg("copied", &"x".repeat(1_000_000))) <= budget);
    }
}