paperos 0.2.0

A programmable editor built on the Runact actor runtime
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
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
use super::basic_input::InputExtension;
use super::message_sink::MessageSink;
use super::vi_input::{EditorMode, ViInputExtension};
use crate::core::{BufferMessage, CommandHandler, EditorRuntime, Extension};
use crate::extensions::keymap_registry::{Context, Key, KeymapRegistry, Layer};
use crate::extensions::lua_ext::LuaExtension;
use crate::extensions::panel_registry::PanelRegistry;
use crate::extensions::theme::Theme;
use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyModifiers};
use crossterm::execute;
use crossterm::terminal::{
    disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
};
use ratatui::backend::CrosstermBackend;
use ratatui::layout::{Constraint, Direction, Layout};
use ratatui::style::{Color, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Paragraph, Wrap};
use ratatui::Terminal;
use runact::{ActorId, Runtime};
use std::any::Any;
use std::io;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, RwLock};

/// Shared scroll state between RenderExtension and scroll command handlers.
/// Fields are PRIVATE. Mutation happens ONLY through scroll commands.
#[derive(Clone)]
pub struct ScrollState {
    row: Arc<AtomicUsize>,
    col: Arc<AtomicUsize>,
    viewport_rows: Arc<AtomicUsize>,
    viewport_cols: Arc<AtomicUsize>,
}

impl ScrollState {
    pub fn new() -> Self {
        Self {
            row: Arc::new(AtomicUsize::new(0)),
            col: Arc::new(AtomicUsize::new(0)),
            viewport_rows: Arc::new(AtomicUsize::new(0)),
            viewport_cols: Arc::new(AtomicUsize::new(0)),
        }
    }

    pub fn row(&self) -> usize {
        self.row.load(Ordering::Relaxed)
    }

    pub fn col(&self) -> usize {
        self.col.load(Ordering::Relaxed)
    }

    pub fn viewport_rows(&self) -> usize {
        self.viewport_rows.load(Ordering::Relaxed)
    }

    pub fn viewport_cols(&self) -> usize {
        self.viewport_cols.load(Ordering::Relaxed)
    }

    pub fn set_viewport(&self, rows: usize, cols: usize) {
        self.viewport_rows.store(rows, Ordering::Relaxed);
        self.viewport_cols.store(cols, Ordering::Relaxed);
    }

    pub fn scroll_up(&self, step: usize) {
        self.row.fetch_sub(step, Ordering::Relaxed);
    }

    pub fn scroll_down(&self, step: usize) {
        self.row.fetch_add(step, Ordering::Relaxed);
    }

    pub fn scroll_left(&self, step: usize) {
        self.col.fetch_sub(step, Ordering::Relaxed);
    }

    pub fn scroll_right(&self, step: usize) {
        self.col.fetch_add(step, Ordering::Relaxed);
    }

    pub fn ensure_cursor_visible(&self, cursor_row: usize, cursor_col: usize) {
        let rows = self.viewport_rows();
        let cols = self.viewport_cols();
        let scroll_row = self.row();

        if cursor_row < scroll_row {
            self.row.store(cursor_row, Ordering::Relaxed);
        } else if cursor_row >= scroll_row + rows {
            self.row
                .store(cursor_row.saturating_sub(rows - 1), Ordering::Relaxed);
        }

        let scroll_col = self.col();
        if cursor_col < scroll_col {
            self.col.store(cursor_col, Ordering::Relaxed);
        } else if cursor_col >= scroll_col + cols {
            self.col
                .store(cursor_col.saturating_sub(cols - 1), Ordering::Relaxed);
        }
    }
}

impl Default for ScrollState {
    fn default() -> Self {
        Self::new()
    }
}

/// Scroll command: moves the viewport up/down by half or full page.
pub struct ScrollCommand {
    scroll: ScrollState,
    direction: i64,
    full_page: bool,
}

impl ScrollCommand {
    pub fn new(scroll: ScrollState, direction: i64, full_page: bool) -> Self {
        Self {
            scroll,
            direction,
            full_page,
        }
    }
}

impl CommandHandler for ScrollCommand {
    fn handle(
        &mut self,
        _args: &[String],
        runtime: &Runtime,
        buffer: Option<ActorId>,
    ) -> Result<Option<String>, Box<dyn std::error::Error>> {
        let visible = self.scroll.viewport_rows() as i64;
        let step = if self.full_page {
            visible
        } else {
            (visible / 2).max(1)
        };
        let step = (step * self.direction).unsigned_abs() as usize;

        if self.direction > 0 {
            self.scroll.scroll_down(step);
        } else {
            self.scroll.scroll_up(step);
        }

        for _ in 0..step {
            if let Some(buf) = buffer {
                let _ = runtime.send(buf, BufferMessage::MoveDown);
            }
        }

        Ok(None)
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
        self
    }
}

/// Horizontal scroll command: moves the viewport left/right.
pub struct HScrollCommand {
    scroll: ScrollState,
    direction: i64,
}

impl HScrollCommand {
    pub fn new(scroll: ScrollState, direction: i64) -> Self {
        Self { scroll, direction }
    }
}

impl CommandHandler for HScrollCommand {
    fn handle(
        &mut self,
        _args: &[String],
        _runtime: &Runtime,
        _buffer: Option<ActorId>,
    ) -> Result<Option<String>, Box<dyn std::error::Error>> {
        if self.direction > 0 {
            self.scroll.scroll_right(1);
        } else {
            self.scroll.scroll_left(1);
        }
        Ok(None)
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
        self
    }
}

pub struct RenderExtension {
    /// Current render target. Interior-mutable so the event loop (which
    /// holds &self) can follow the BufferManager's active buffer.
    buffer: std::sync::Mutex<Option<ActorId>>,
    input: Option<Arc<RwLock<InputExtension>>>,
    vi_input: Option<Arc<RwLock<ViInputExtension>>>,
    /// Terminal extension — when the editor is in Terminal mode, the
    /// terminal panel's grid is drawn instead of the plain-lines view.
    terminal: Option<Arc<RwLock<crate::extensions::terminal::TerminalExtension>>>,
    /// Shared active-buffer handle (BufferManager). When it changes, the
    /// render extension re-targets it — buffer switching without restart.
    active_buffer_handle: Option<Arc<RwLock<Option<ActorId>>>>,
    message_sink: MessageSink,
    scroll: ScrollState,
    show_line_numbers: bool,
    /// UI theme — every color the renderer uses (see Theme::default).
    theme: Theme,
    #[allow(dead_code)]
    quit_requested: Arc<std::sync::atomic::AtomicBool>,
    panels: Option<Arc<RwLock<PanelRegistry>>>,
    /// Central keymap registry — resolves keys to commands based on
    /// context (mode + buffer kind) and an ordered layer stack.
    keymap_registry: KeymapRegistry,
}

impl Extension for RenderExtension {
    fn name(&self) -> &str {
        "render"
    }

    fn init(&mut self, _runtime: &mut Runtime) -> Result<(), Box<dyn std::error::Error>> {
        Ok(())
    }

    fn shutdown(&mut self, _runtime: &mut Runtime) -> Result<(), Box<dyn std::error::Error>> {
        Ok(())
    }

    fn on_key(&mut self, _ch: char) -> Result<(), Box<dyn std::error::Error>> {
        Ok(())
    }

    fn on_render(&mut self, _runtime: &Runtime) -> Result<(), Box<dyn std::error::Error>> {
        Ok(())
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }
}

impl Default for RenderExtension {
    fn default() -> Self {
        Self::new()
    }
}

impl RenderExtension {
    pub fn new() -> Self {
        Self {
            buffer: std::sync::Mutex::new(None),
            input: None,
            vi_input: None,
            terminal: None,
            active_buffer_handle: None,
            message_sink: MessageSink::default(),
            scroll: ScrollState::new(),
            show_line_numbers: true,
            theme: Theme::default(),
            quit_requested: Arc::new(std::sync::atomic::AtomicBool::new(false)),
            panels: None,
            keymap_registry: Self::default_registry(),
        }
    }

    /// Toggle the line-number gutter (ui.line_numbers config option).
    pub fn set_show_line_numbers(&mut self, show: bool) {
        self.show_line_numbers = show;
    }

    /// Set the UI theme (paper.theme.set config entries).
    pub fn set_theme(&mut self, theme: Theme) {
        self.theme = theme;
    }

    /// Build a registry with the global layer (M-x → command-mode).
    /// Input extensions add their own default layers via `register_layers`.
    /// Scroll keys come from InputExtension::global_bindings — same as main.rs.
    fn default_registry() -> KeymapRegistry {
        let mut reg = KeymapRegistry::new();
        let mut global = Layer::new("global-defaults", 15, Some(Context::new("*")));
        global.bind(Key::parse("M-x").unwrap(), "command-mode");
        // Scroll keys — sourced from InputExtension::global_bindings
        for (key_spec, cmd) in InputExtension::new().global_bindings() {
            if let Some(k) = Key::parse(key_spec) {
                global.bind(k, cmd);
            }
        }
        reg.register(global);
        reg
    }

    pub fn set_message_sink(&mut self, sink: MessageSink) {
        self.message_sink = sink;
    }
    #[allow(dead_code)]
    pub fn echo_line(&self, runtime: &Runtime) -> String {
        if let Some(ref panels) = self.panels {
            if let Ok(panels) = panels.read() {
                let lines = panels.get_lines(runtime, "echo");
                if !lines.is_empty() {
                    return lines.last().cloned().unwrap_or_default();
                }
            }
        }
        self.message_sink.last().unwrap_or_default()
    }

    pub fn set_buffer(&mut self, buffer: ActorId) {
        *self.buffer.lock().unwrap() = Some(buffer);
    }

    pub fn set_input(&mut self, input: Arc<RwLock<InputExtension>>) {
        self.input = Some(input);
    }

    pub fn set_vi_input(&mut self, vi_input: Arc<RwLock<ViInputExtension>>) {
        self.vi_input = Some(vi_input);
    }

    /// Wire the shared active-buffer handle (BufferManager). Each frame,
    /// if the active buffer changed, self.buffer follows it.
    pub fn set_active_buffer_handle(&mut self, handle: Arc<RwLock<Option<ActorId>>>) {
        self.active_buffer_handle = Some(handle);
    }

    /// Wire the terminal extension (grid rendering in Terminal mode).
    pub fn set_terminal(
        &mut self,
        terminal: Arc<RwLock<crate::extensions::terminal::TerminalExtension>>,
    ) {
        self.terminal = Some(terminal);
    }

    /// Inject a pre-built keymap registry (with default layers + user
    /// remaps from Lua config). If not called, `new()` provides an empty
    /// registry and the basic_input fallback handles keys.
    pub fn set_keymap_registry(&mut self, reg: KeymapRegistry) {
        self.keymap_registry = reg;
    }

    #[allow(dead_code)]
    pub fn set_panels(&mut self, panels: Arc<RwLock<PanelRegistry>>) {
        self.panels = Some(panels);
    }

    #[allow(dead_code)]
    pub fn command_buffer_display(&self) -> String {
        if let Some(ref panels) = self.panels {
            if let Ok(panels) = panels.read() {
                if panels.minibuffer_active() {
                    return format!("M-x {}", panels.minibuffer_content());
                }
            }
        }
        String::new()
    }

    pub fn set_viewport(&self, rows: usize, cols: usize) {
        self.scroll.set_viewport(rows.max(1), cols.max(1));
    }

    pub fn scroll_row(&self) -> usize {
        self.scroll.row()
    }

    pub fn scroll_col(&self) -> usize {
        self.scroll.col()
    }

    pub fn clamp_scroll(&self, line_count: usize, max_line_len: usize) {
        let rows = self.scroll.viewport_rows();
        let cols = self.scroll.viewport_cols();
        let max_scroll_row = line_count.saturating_sub(rows);
        let sr = self.scroll.row().min(max_scroll_row);
        self.scroll.row.store(sr, Ordering::Relaxed);
        let max_scroll_col = max_line_len.saturating_sub(cols);
        let sc = self.scroll.col().min(max_scroll_col);
        self.scroll.col.store(sc, Ordering::Relaxed);
    }

    pub fn ensure_cursor_visible(&self, cursor_row: usize, cursor_col: usize) {
        self.scroll.ensure_cursor_visible(cursor_row, cursor_col);
    }

    pub fn scroll_state(&self) -> ScrollState {
        self.scroll.clone()
    }

    /// Shared quit flag — set to `true` by the QuitCommand handler so the
    /// event loop can check it each iteration and break cleanly.
    pub fn quit_flag(&self) -> Arc<std::sync::atomic::AtomicBool> {
        Arc::clone(&self.quit_requested)
    }

    pub fn run_event_loop(
        &self,
        editor_runtime: &mut EditorRuntime,
        buffer: Option<ActorId>,
    ) -> io::Result<()> {
        enable_raw_mode()?;
        let mut stdout = io::stdout();
        execute!(
            stdout,
            EnterAlternateScreen,
            crossterm::event::EnableMouseCapture
        )?;
        let backend = CrosstermBackend::new(stdout);
        let mut terminal = Terminal::new(backend)?;

        loop {
            // Follow the active buffer: BufferManager may have switched it
            // (next-buffer / prev-buffer / switch-buffer / M-n / M-p).
            if let Some(ref handle) = self.active_buffer_handle {
                if let Ok(active) = handle.read() {
                    if let Some(id) = *active {
                        if let Ok(mut cur) = self.buffer.lock() {
                            if *cur != Some(id) {
                                *cur = Some(id);
                            }
                        }
                    }
                }
            }
            terminal.draw(|f| {
                self.render(f, editor_runtime.runtime());
            })?;

            // Drain the Lua command queue (paper.cmd / paper.open /
            // paper.save) — commands are messages, run through the real
            // command registry. Panel writes (paper.panel.write) deliver
            // to their named buffers. Due timers (paper.after) fire their
            // Lua callbacks first — their queued side effects (paper.cmd
            // etc.) are drained in the same tick, below.
            if let Some(ext) = editor_runtime.extension::<LuaExtension>() {
                ext.due_timers(std::time::Instant::now());
            }
            // Keep the terminal panel buffer mirroring the live grid.
            if let Some(ref term) = self.terminal {
                if let Ok(ext) = term.read() {
                    ext.sync_projection(editor_runtime.runtime());
                }
            }
            let (pending_cmds, panel_writes) =
                if let Some(ext) = editor_runtime.extension::<LuaExtension>() {
                    let cmds: Vec<String> = ext.cmd_queue().lock().unwrap().drain(..).collect();
                    let writes: Vec<(String, String)> = ext
                        .pending_panel_writes()
                        .lock()
                        .unwrap()
                        .drain(..)
                        .collect();
                    (cmds, writes)
                } else {
                    (Vec::new(), Vec::new())
                };
            for cmd in pending_cmds {
                match editor_runtime.run_command(&cmd, buffer) {
                    Ok(Some(output)) => self.echo_output(editor_runtime, output),
                    Ok(None) => {}
                    Err(e) => self.echo_output(editor_runtime, format!("{cmd}: {e}")),
                }
            }
            if !panel_writes.is_empty() {
                if let Some(panels) = self.panels.clone() {
                    if let Ok(reg) = panels.read() {
                        for (name, text) in panel_writes {
                            if let Err(e) = reg.send(
                                editor_runtime.runtime(),
                                &name,
                                crate::core::BufferMessage::Echo(text),
                            ) {
                                self.echo_output(
                                    editor_runtime,
                                    format!("panel.write({name}): {e}"),
                                );
                            }
                        }
                    }
                }
            }

            if event::poll(std::time::Duration::from_millis(50))? {
                let ev = event::read()?;
                if let Event::Mouse(mouse) = &ev {
                    self.handle_mouse(*mouse, editor_runtime.runtime());
                }
                if let Event::Key(key) = ev {
                    // Ctrl-q is the universal quit — always intercepted at
                    // the event loop level (not a user-rebindable command).
                    if key.code == KeyCode::Char('q') && key.modifiers == KeyModifiers::CONTROL {
                        break;
                    }
                    // Terminal mode: keys encode to PTY bytes (the terminal
                    // extension consumes them). Escape hatches (M-x, Esc,
                    // buffer switching) are NOT consumed — they fall
                    // through to the normal keymap path.
                    let consumed = if let Some(ref term) = self.terminal {
                        if let Ok(ext) = term.read() {
                            ext.handle_key(key, editor_runtime.runtime())
                        } else {
                            false
                        }
                    } else {
                        false
                    };
                    if !consumed {
                        self.handle_key(key, editor_runtime, buffer);
                    }
                    // Check if the quit flag was set by a `:q` / `:quit` command.
                    if self
                        .quit_requested
                        .load(std::sync::atomic::Ordering::Relaxed)
                    {
                        break;
                    }
                    if let Some(buf) = buffer {
                        if let Ok(handle) = editor_runtime
                            .runtime()
                            .request(buf, BufferMessage::GetCursorPosition)
                        {
                            if let Ok(reply) =
                                handle.recv_timeout(std::time::Duration::from_millis(100))
                            {
                                if let Ok(pos) = reply.downcast::<(usize, usize)>() {
                                    let (row, col) = *pos;
                                    self.ensure_cursor_visible(row, col);
                                }
                            }
                        }
                    }
                }
            }
        }

        disable_raw_mode()?;
        execute!(
            terminal.backend_mut(),
            crossterm::event::DisableMouseCapture,
            LeaveAlternateScreen
        )?;
        Ok(())
    }

    pub fn handle_key(
        &self,
        key: KeyEvent,
        editor_runtime: &mut EditorRuntime,
        buffer: Option<ActorId>,
    ) {
        // 1. If minibuffer is active, accumulate key presses
        let minibuffer_active = if let Some(ref panels) = self.panels {
            if let Ok(panels) = panels.read() {
                panels.minibuffer_active()
            } else {
                false
            }
        } else {
            false
        };

        if minibuffer_active {
            if let Some(ref panels) = self.panels {
                if let Ok(mut panels) = panels.write() {
                    match key.code {
                        KeyCode::Enter => {
                            let cmd = panels.minibuffer_content().to_string();
                            // Don't clear yet — we may need to keep minibuffer
                            // active for multi-line command output (e.g. "commands").
                            if cmd.is_empty() {
                                panels.minibuffer_clear();
                                panels.set_minibuffer_active(false);
                            } else {
                                // Clear stale echo output before running —
                                // a successful command must not leave an old
                                // error on the echo line.
                                panels.echo_clear(editor_runtime.runtime());
                                self.message_sink.clear();
                                match editor_runtime.run_command(&cmd, buffer) {
                                    Ok(Some(output)) => {
                                        // Multi-line output: show as scrollable
                                        // candidate list in the minibuffer.
                                        if output.contains('\n') {
                                            let lines: Vec<String> =
                                                output.lines().map(|s| s.to_string()).collect();
                                            panels.set_candidates(lines);
                                            // Keep minibuffer active to browse.
                                            // Clear the typed text.
                                            panels.minibuffer_clear();
                                        } else {
                                            // Single-line output → echo line.
                                            panels.echo(editor_runtime.runtime(), output.clone());
                                            self.message_sink.push(output);
                                            // Deactivate minibuffer after echo.
                                            panels.set_minibuffer_active(false);
                                        }
                                    }
                                    Ok(None) => {
                                        // No output — success silently.
                                        panels.minibuffer_clear();
                                        panels.set_minibuffer_active(false);
                                    }
                                    Err(e) => {
                                        panels.echo(editor_runtime.runtime(), e.to_string());
                                        self.message_sink.push(e.to_string());
                                        panels.minibuffer_clear();
                                        panels.set_minibuffer_active(false);
                                    }
                                }
                            }
                        }
                        KeyCode::Backspace => {
                            panels.minibuffer_backspace();
                            // Re-compute candidates after backspace
                            let partial = panels.minibuffer_content().to_string();
                            update_candidates(&mut panels, editor_runtime, &partial);
                        }
                        KeyCode::Esc => {
                            panels.minibuffer_clear();
                            panels.set_minibuffer_active(false);
                        }
                        // Ctrl-n / Ctrl-p: scroll candidate list
                        KeyCode::Char('n') if key.modifiers == KeyModifiers::CONTROL => {
                            panels.scroll_candidates(1);
                        }
                        KeyCode::Char('p') if key.modifiers == KeyModifiers::CONTROL => {
                            panels.scroll_candidates(-1);
                        }
                        KeyCode::Char(ch) if !ch.is_control() => {
                            panels.minibuffer_push(ch);
                            // Update command candidates based on what's typed.
                            let partial = panels.minibuffer_content().to_string();
                            update_candidates(&mut panels, editor_runtime, &partial);
                        }
                        _ => {}
                    }
                }
            }
            return;
        }

        // 2. All non-minibuffer keys go through the central KeymapRegistry.
        // Context = the current editor mode.
        let ctx = self.build_context();
        if let Some(key) = crate::extensions::keymap_convert::crossterm_to_key(key) {
            if let Some(resolution) = self.keymap_registry.resolve(key, &ctx) {
                // command-mode is a UI-level key (opens the minibuffer) rather
                // than a registered command — intercept it here.
                if resolution.command == "command-mode" {
                    if let Some(ref panels) = self.panels {
                        if let Ok(mut panels) = panels.write() {
                            panels.set_minibuffer_active(true);
                        }
                    }
                    return;
                }

                // All other commands (including mode switches) run through
                // the command system.
                match editor_runtime.run_command(&resolution.command, buffer) {
                    Ok(Some(output)) => {
                        self.echo_output(editor_runtime, output);
                    }
                    Ok(None) => {}
                    Err(e) => {
                        self.message_sink.push(e.to_string());
                    }
                }
                return;
            }
        }

        // 3. No binding resolved — in Terminal mode, Esc exits to Normal
        // (vi_input's Terminal arm handles , but the live path never
        // calls it — route the mode flip here).
        if key.code == KeyCode::Esc && self.get_mode() == EditorMode::Terminal {
            if let Some(ref vi) = self.vi_input {
                if let Ok(mut vi_guard) = vi.write() {
                    vi_guard.handle_char_key('\x1b');
                }
            }
            return;
        }

        // 4. No binding resolved — in Basic/Insert mode, fall back to
        // printable char insertion. In vi Normal/Visual mode, unbound keys
        // do not insert — they're operator prefixes or unhandled.
        let mode = self.get_mode();
        if mode == EditorMode::Basic || mode == EditorMode::Insert {
            if let Some(ref input) = self.input {
                if let Some(cmd) = {
                    if let Ok(mut input_guard) = input.write() {
                        input_guard.handle_key(&key)
                    } else {
                        None
                    }
                } {
                    match editor_runtime.run_command(&cmd, buffer) {
                        Ok(Some(output)) => {
                            self.echo_output(editor_runtime, output);
                        }
                        Ok(None) => {}
                        Err(e) => {
                            self.message_sink.push(e.to_string());
                        }
                    }
                }
            }
        }
    }

    /// Mouse handling. In Terminal mode, the wheel scrolls the terminal
    /// viewport (3 rows per notch, standard terminal feel).
    /// (Public test alias: handle_mouse_for_test.)
    #[allow(dead_code)]
    pub fn handle_mouse_for_test(&self, mouse: crossterm::event::MouseEvent, runtime: &Runtime) {
        self.handle_mouse(mouse, runtime)
    }

    fn handle_mouse(&self, mouse: crossterm::event::MouseEvent, _runtime: &Runtime) {
        use crossterm::event::MouseEventKind;
        if self.get_mode() != EditorMode::Terminal {
            return;
        }
        let Some(ref term) = self.terminal else {
            return;
        };
        let Ok(ext) = term.read() else {
            return;
        };
        match mouse.kind {
            MouseEventKind::ScrollUp => ext.scroll_viewport(3),
            MouseEventKind::ScrollDown => ext.scroll_viewport(-3),
            _ => {}
        }
    }

    /// Echo command output to the echo panel + message sink.
    fn echo_output(&self, runtime: &EditorRuntime, output: String) {
        if let Some(ref panels) = self.panels {
            if let Ok(panels) = panels.read() {
                panels.echo(runtime.runtime(), output.clone());
            }
        }
        self.message_sink.push(output);
    }

    /// Build the resolution context: the current editor mode.
    fn build_context(&self) -> Context {
        let mode = match self.get_mode() {
            EditorMode::Basic => "basic",
            EditorMode::Normal => "normal",
            EditorMode::Insert => "insert",
            EditorMode::Command => "command",
            EditorMode::Search => "search",
            EditorMode::Terminal => "terminal",
        };

        Context::new(mode)
    }
    fn render(&self, f: &mut ratatui::Frame, runtime: &Runtime) {
        let content = self.get_buffer_content(runtime);
        let (cursor_row, cursor_col) = self.get_cursor_position(runtime);
        let mode = self.get_mode();
        let file_name = self.get_file_name(runtime);
        let modified = self.is_modified(runtime);

        // Terminal mode: the terminal panel is claimed by the terminal
        // extension — it draws its grid into the editor area; the
        // statusbar below still uses the buffer-backed path.
        if mode == EditorMode::Terminal {
            if let Some(ref term) = self.terminal {
                if let Ok(ext) = term.read() {
                    // Echo/minibuffer row — same visibility rule as the
                    // normal path so M-x is visible in Terminal mode.
                    let echo_active = self.echo_active(runtime);
                    let area = f.area();
                    let vertical = Layout::default()
                        .direction(Direction::Vertical)
                        .constraints(if echo_active {
                            vec![
                                Constraint::Min(1),
                                Constraint::Length(self.echo_height()),
                                Constraint::Length(1),
                            ]
                        } else {
                            vec![Constraint::Min(1), Constraint::Length(1)]
                        })
                        .split(area);
                    // Sync the statusbar buffer (same as normal mode).
                    if let Some(ref panels) = self.panels {
                        if let Ok(panels) = panels.read() {
                            panels.update_status(
                                runtime,
                                "TERMINAL",
                                &file_name,
                                cursor_row + 1,
                                cursor_col,
                                modified,
                            );
                        }
                    }
                    ext.draw(f, vertical[0]);
                    if echo_active {
                        self.render_echo_area(f, runtime, vertical[1]);
                    }
                    self.render_statusbar_line(f, runtime, vertical[vertical.len() - 1]);
                    return;
                }
            }
        }

        // Sync the statusbar panel buffer with current state
        if let Some(ref panels) = self.panels {
            if let Ok(panels) = panels.read() {
                let mode_str = match mode {
                    EditorMode::Basic => "BASIC",
                    EditorMode::Normal => "NORMAL",
                    EditorMode::Insert => "INSERT",
                    EditorMode::Command => "COMMAND",
                    EditorMode::Search => "SEARCH",
                    EditorMode::Terminal => "TERMINAL",
                };
                panels.update_status(
                    runtime,
                    mode_str,
                    &file_name,
                    cursor_row + 1,
                    cursor_col,
                    modified,
                );
            }
        }

        let area = f.area();

        // Echo area is shown on demand — same rule in every mode.
        let echo_active = self.echo_active(runtime);
        let echo_height: u16 = self.echo_height();

        let vertical = Layout::default()
            .direction(Direction::Vertical)
            .constraints(if echo_active {
                vec![
                    Constraint::Min(1),
                    Constraint::Length(echo_height),
                    Constraint::Length(1),
                ]
            } else {
                vec![Constraint::Min(1), Constraint::Length(1)]
            })
            .split(area);

        let editor_area = vertical[0];
        let echo_area = if echo_active { Some(vertical[1]) } else { None };
        let status_area = vertical[vertical.len() - 1];

        // Preserve trailing empty lines (cursor row after Enter at EOL)
        let all_lines = crate::core::buffer::content_to_lines(&content);
        let max_line = all_lines.len().max(1);
        let num_digits = max_line.to_string().len();
        let num_width = if self.show_line_numbers {
            num_digits + 1
        } else {
            0
        };

        let inner_rows = editor_area.height.saturating_sub(2) as usize;
        let inner_cols = editor_area.width.saturating_sub(2) as usize;
        let scroll_col_now = self.scroll_col();
        let gutter = if scroll_col_now == 0 { num_width } else { 0 };
        let visible_cols = inner_cols.saturating_sub(gutter).max(1);
        self.set_viewport(inner_rows.max(1), visible_cols);

        self.clamp_scroll(
            max_line,
            all_lines
                .iter()
                .map(|l| l.chars().count())
                .max()
                .unwrap_or(0),
        );

        let scroll_row = self.scroll_row() as u16;
        let scroll_col = self.scroll_col() as u16;
        let is_insert = matches!(mode, EditorMode::Insert);
        let cursor_style = if is_insert {
            Style::default()
                .fg(Color::Black)
                .bg(self.theme.cursor_insert)
        } else {
            Style::default()
                .fg(Color::Black)
                .bg(self.theme.cursor_normal)
        };
        let lines: Vec<Line> = all_lines
            .iter()
            .enumerate()
            .map(|(i, l)| {
                let l = l.as_str();
                let row_offset = i as u16;
                let visible_row = row_offset.saturating_sub(scroll_row);
                let cursor_visible_row = (cursor_row as u16).saturating_sub(scroll_row);
                let is_cursor_row = visible_row == cursor_visible_row;

                let text_spans = if is_cursor_row && cursor_col <= l.len() {
                    let cursor_col_usize = cursor_col;
                    let before = &l[..cursor_col_usize.min(l.len())];
                    let cursor_char = l.chars().nth(cursor_col_usize).unwrap_or(' ');
                    let after_start = (cursor_col_usize + 1).min(l.len());
                    let after = &l[after_start..];
                    let mut spans = Vec::new();
                    if self.show_line_numbers {
                        let padded = format!("{:>width$} ", i + 1, width = num_digits);
                        spans.push(Span::styled(
                            padded,
                            Style::default().fg(self.theme.line_number_fg),
                        ));
                    }
                    spans.push(Span::raw(before.to_string()));
                    spans.push(Span::styled(cursor_char.to_string(), cursor_style));
                    spans.push(Span::raw(after.to_string()));
                    Line::from(spans)
                } else {
                    let mut spans = vec![Span::raw(l.to_string())];
                    if self.show_line_numbers {
                        let padded = format!("{:>width$} ", i + 1, width = num_digits);
                        let mut new_spans = vec![Span::styled(
                            padded,
                            Style::default().fg(self.theme.line_number_fg),
                        )];
                        new_spans.append(&mut spans);
                        Line::from(new_spans)
                    } else {
                        Line::from(spans)
                    }
                };
                text_spans
            })
            .collect();

        let paragraph = Paragraph::new(lines)
            .block(
                Block::default()
                    .title(format!(" paperOS — {} ", file_name))
                    .borders(Borders::ALL)
                    .border_style(Style::default().fg(self.theme.border)),
            )
            .wrap(Wrap { trim: false })
            .scroll((scroll_row, scroll_col + num_width as u16));
        f.render_widget(paragraph, editor_area);

        let _inner_x =
            editor_area.x + 1 + num_width as u16 + (cursor_col as u16).saturating_sub(scroll_col);
        let _inner_y = editor_area.y + 1 + (cursor_row as u16).saturating_sub(scroll_row);

        // Echo / Minibuffer region
        if let Some(echo_area) = echo_area {
            if let Some(ref panels) = self.panels {
                if let Ok(panels) = panels.read() {
                    if panels.minibuffer_active() {
                        // Split the echo area: input line at top,
                        // candidate list below (scrollable).
                        let candidate_rows = (echo_area.height.saturating_sub(1) as usize).max(1);
                        let sub = Layout::default()
                            .direction(Direction::Vertical)
                            .constraints([
                                Constraint::Length(1),
                                Constraint::Length(candidate_rows as u16),
                            ])
                            .split(echo_area);
                        let input_area = sub[0];
                        let list_area = sub[1];

                        // M-x input line
                        let mb_text = format!("M-x {}_", panels.minibuffer_content());
                        let width = input_area.width as usize;
                        let padded_text = if mb_text.len() < width {
                            format!("{}{}", mb_text, " ".repeat(width - mb_text.len()))
                        } else {
                            mb_text
                        };
                        let minibuffer = Paragraph::new(Line::from(Span::styled(
                            padded_text,
                            Style::default()
                                .fg(self.theme.candidate_fg)
                                .bg(self.theme.candidate_bg),
                        )));
                        f.render_widget(minibuffer, input_area);

                        // Candidate list (scrollable)
                        let visible = panels.visible_candidates(candidate_rows);
                        if !visible.is_empty() {
                            let lines: Vec<Line> = visible
                                .iter()
                                .map(|c| {
                                    Line::from(Span::styled(
                                        c.clone(),
                                        Style::default()
                                            .fg(self.theme.candidate_fg)
                                            .bg(self.theme.candidate_sel_bg),
                                    ))
                                })
                                .collect();
                            let list = Paragraph::new(lines);
                            f.render_widget(list, list_area);
                        }
                    } else {
                        let echo_lines = panels.get_lines(runtime, "echo");
                        if let Some(latest) = echo_lines.last() {
                            // Show only the most recent echo message — the echo
                            // line is one row; older messages must not crowd it.
                            let echo = Paragraph::new(Span::styled(
                                latest.clone(),
                                Style::default()
                                    .fg(self.theme.echo_fg)
                                    .bg(self.theme.candidate_sel_bg),
                            ));
                            f.render_widget(echo, echo_area);
                        } else {
                            let echo = Paragraph::new(Line::from(Span::raw(
                                self.message_sink.last().unwrap_or_default(),
                            )));
                            f.render_widget(echo, echo_area);
                        }
                    }
                }
            }
        }
        // Status bar — buffer-backed: read from the \"statusbar\" panel buffer.
        self.render_statusbar_line(f, runtime, status_area);
    }

    /// Draw the statusbar row from the "statusbar" panel buffer.
    /// Is the echo/minibuffer row visible? Minibuffer active OR non-empty
    /// echo output. Same rule in every mode.
    fn echo_active(&self, runtime: &Runtime) -> bool {
        if let Some(ref panels) = self.panels {
            if let Ok(panels) = panels.read() {
                if panels.minibuffer_active() {
                    return true;
                }
                // Show echo only if there's actual output
                let echo_lines = panels.get_lines(runtime, "echo");
                return echo_lines.last().map(|s| !s.is_empty()).unwrap_or(false);
            }
        }
        !self.message_sink.last().unwrap_or_default().is_empty()
    }

    /// Height of the echo/minibuffer region (1 + visible candidates,
    /// capped at 10).
    fn echo_height(&self) -> u16 {
        if !self.panels.is_some() {
            return 1;
        }
        if let Some(ref panels) = self.panels {
            if let Ok(panels) = panels.read() {
                let max_candidates = 10usize;
                let n = panels.candidate_count().min(max_candidates);
                return 1 + n as u16;
            }
        }
        1
    }

    /// Draw the echo/minibuffer row (shared by normal + terminal paths).
    fn render_echo_area(
        &self,
        f: &mut ratatui::Frame,
        runtime: &Runtime,
        echo_area: ratatui::layout::Rect,
    ) {
        if let Some(ref panels) = self.panels {
            if let Ok(panels) = panels.read() {
                if panels.minibuffer_active() {
                    // Split the echo area: input line at top,
                    // candidate list below (scrollable).
                    let candidate_rows = (echo_area.height.saturating_sub(1) as usize).max(1);
                    let sub = Layout::default()
                        .direction(Direction::Vertical)
                        .constraints([
                            Constraint::Length(1),
                            Constraint::Length(candidate_rows as u16),
                        ])
                        .split(echo_area);
                    let input_area = sub[0];
                    let list_area = sub[1];

                    // M-x input line
                    let mb_text = format!("M-x {}_", panels.minibuffer_content());
                    let width = input_area.width as usize;
                    let padded_text = if mb_text.len() < width {
                        format!("{}{}", mb_text, " ".repeat(width - mb_text.len()))
                    } else {
                        mb_text
                    };
                    let minibuffer = Paragraph::new(Line::from(Span::styled(
                        padded_text,
                        Style::default()
                            .fg(self.theme.candidate_fg)
                            .bg(self.theme.candidate_bg),
                    )));
                    f.render_widget(minibuffer, input_area);

                    // Candidate list (scrollable)
                    let visible = panels.visible_candidates(candidate_rows);
                    if !visible.is_empty() {
                        let lines: Vec<Line> = visible
                            .iter()
                            .map(|c| {
                                Line::from(Span::styled(
                                    c.clone(),
                                    Style::default()
                                        .fg(self.theme.candidate_fg)
                                        .bg(self.theme.candidate_sel_bg),
                                ))
                            })
                            .collect();
                        let list = Paragraph::new(lines);
                        f.render_widget(list, list_area);
                    }
                } else {
                    let echo_lines = panels.get_lines(runtime, "echo");
                    if let Some(latest) = echo_lines.last() {
                        // Show only the most recent echo message — the echo
                        // line is one row; older messages must not crowd it.
                        let echo = Paragraph::new(Span::styled(
                            latest.clone(),
                            Style::default()
                                .fg(self.theme.echo_fg)
                                .bg(self.theme.candidate_sel_bg),
                        ));
                        f.render_widget(echo, echo_area);
                    } else {
                        let echo = Paragraph::new(Line::from(Span::raw(
                            self.message_sink.last().unwrap_or_default(),
                        )));
                        f.render_widget(echo, echo_area);
                    }
                }
            }
        }
    }

    fn render_statusbar_line(
        &self,
        f: &mut ratatui::Frame,
        runtime: &Runtime,
        status_area: ratatui::layout::Rect,
    ) {
        if let Some(ref panels) = self.panels {
            if let Ok(panels) = panels.read() {
                let status_lines = panels.get_lines(runtime, "statusbar");
                if let Some(latest) = status_lines.last() {
                    let status = Paragraph::new(Line::from(Span::styled(
                        latest.clone(),
                        Style::default()
                            .fg(self.theme.statusbar_fg)
                            .bg(self.theme.statusbar_bg),
                    )));
                    f.render_widget(status, status_area);
                } else {
                    // No status yet — render empty
                    f.render_widget(
                        Paragraph::new(Line::from(Span::raw(
                            " ".repeat(status_area.width as usize),
                        ))),
                        status_area,
                    );
                }
            }
        }
    }

    fn get_buffer_content(&self, runtime: &Runtime) -> String {
        if let Some(buf) = self.buffer.lock().ok().and_then(|b| *b) {
            if let Ok(handle) = runtime.request(buf, BufferMessage::GetContent) {
                if let Ok(reply) = handle.recv_timeout(std::time::Duration::from_millis(100)) {
                    if let Ok(content) = reply.downcast::<String>() {
                        return (*content).clone();
                    }
                }
            }
        }
        String::new()
    }

    fn get_cursor_position(&self, runtime: &Runtime) -> (usize, usize) {
        if let Some(buf) = self.buffer.lock().ok().and_then(|b| *b) {
            if let Ok(handle) = runtime.request(buf, BufferMessage::GetCursorPosition) {
                if let Ok(reply) = handle.recv_timeout(std::time::Duration::from_millis(100)) {
                    if let Ok(pos) = reply.downcast::<(usize, usize)>() {
                        return *pos;
                    }
                }
            }
        }
        (0, 0)
    }

    pub fn get_mode(&self) -> EditorMode {
        if let Some(ref vi) = self.vi_input {
            if let Ok(vi_guard) = vi.read() {
                return vi_guard.mode();
            }
        }
        EditorMode::Basic
    }

    /// Public wrapper so acceptance tests can drive the real render path
    /// against a TestBackend (the private `render` is TUI-internal).
    #[allow(dead_code)]
    pub fn render_public(&self, f: &mut ratatui::Frame, runtime: &Runtime) {
        self.render(f, runtime);
    }

    fn get_file_name(&self, runtime: &Runtime) -> String {
        if let Some(buf) = self.buffer.lock().ok().and_then(|b| *b) {
            if let Ok(handle) = runtime.request(buf, BufferMessage::GetFilePath) {
                if let Ok(reply) = handle.recv_timeout(std::time::Duration::from_millis(100)) {
                    if let Ok(path) = reply.downcast::<Option<String>>() {
                        if let Some(p) = *path {
                            if let Some(name) = std::path::Path::new(&p).file_name() {
                                return name.to_string_lossy().to_string();
                            }
                            return p;
                        }
                    }
                }
            }
        }
        String::new()
    }

    fn is_modified(&self, runtime: &Runtime) -> bool {
        if let Some(buf) = self.buffer.lock().ok().and_then(|b| *b) {
            if let Ok(handle) = runtime.request(buf, BufferMessage::IsModified) {
                if let Ok(reply) = handle.recv_timeout(std::time::Duration::from_millis(100)) {
                    if let Ok(modified) = reply.downcast::<bool>() {
                        return *modified;
                    }
                }
            }
        }
        false
    }
}

/// Compute fuzzy-match candidates for the current minibuffer input and store
/// them in the PanelRegistry. Called on each keystroke and backspace in M-x mode.
fn update_candidates(panels: &mut PanelRegistry, runtime: &EditorRuntime, partial: &str) {
    let candidates: Vec<String> = runtime
        .list_commands()
        .iter()
        .map(|(name, _)| name.to_string())
        .filter(|name| name.to_lowercase().contains(&partial.to_lowercase()))
        .take(20)
        .collect();
    panels.set_candidates(candidates);
}

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

    #[test]
    fn test_render_sanity() {
        let _render = RenderExtension::new();
    }
}