sql-cli 1.73.0

SQL query tool for CSV/JSON with both interactive TUI and non-interactive CLI modes - perfect for exploration and automation
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
// Maps keyboard input to actions
// This will gradually replace direct key handling in TUI

use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use std::collections::HashMap;

use crate::buffer::AppMode;
use crate::ui::input::actions::{Action, ActionContext, CursorPosition, NavigateAction};

/// Maps keyboard input to actions based on context
pub struct KeyMapper {
    /// Static mappings that don't depend on mode
    global_mappings: HashMap<(KeyCode, KeyModifiers), Action>,

    /// Mode-specific mappings
    mode_mappings: HashMap<AppMode, HashMap<(KeyCode, KeyModifiers), Action>>,

    /// Vim-style count buffer for motions
    count_buffer: String,

    /// Buffer for multi-character vim commands (e.g., 'wa', 'oa')
    vim_command_buffer: String,
}

impl KeyMapper {
    #[must_use]
    pub fn new() -> Self {
        let mut mapper = Self {
            global_mappings: HashMap::new(),
            mode_mappings: HashMap::new(),
            count_buffer: String::new(),
            vim_command_buffer: String::new(),
        };

        mapper.init_global_mappings();
        mapper.init_mode_mappings();
        mapper
    }

    /// Initialize mappings that work regardless of mode
    fn init_global_mappings(&mut self) {
        use KeyCode::{Char, F};
        use KeyModifiers as Mod;

        // Function keys that work in any mode
        self.global_mappings
            .insert((F(1), Mod::NONE), Action::ShowHelp);
        self.global_mappings
            .insert((F(3), Mod::NONE), Action::ShowPrettyQuery);
        self.global_mappings
            .insert((F(5), Mod::NONE), Action::ShowDebugInfo);
        self.global_mappings
            .insert((F(6), Mod::NONE), Action::ToggleRowNumbers);
        self.global_mappings
            .insert((F(7), Mod::NONE), Action::ToggleCompactMode);
        self.global_mappings
            .insert((F(8), Mod::NONE), Action::ToggleCaseInsensitive);
        self.global_mappings
            .insert((F(9), Mod::NONE), Action::KillLine);
        self.global_mappings
            .insert((F(10), Mod::NONE), Action::KillLineBackward);
        self.global_mappings
            .insert((F(12), Mod::NONE), Action::ToggleKeyIndicator);

        // Force quit
        self.global_mappings
            .insert((Char('c'), Mod::CONTROL), Action::ForceQuit);
        self.global_mappings
            .insert((Char('C'), Mod::CONTROL), Action::ForceQuit);
    }

    /// Initialize mode-specific mappings
    fn init_mode_mappings(&mut self) {
        self.init_results_mappings();
        self.init_command_mappings();
        // Add other modes as we migrate them
    }

    /// Initialize Results mode mappings
    fn init_results_mappings(&mut self) {
        use crate::buffer::AppMode;
        use KeyCode::{Char, Down, End, Esc, Home, Left, PageDown, PageUp, Right, Up, F};
        use KeyModifiers as Mod;

        let mut mappings = HashMap::new();

        // Basic navigation (will be extracted in Phase 2)
        mappings.insert((Up, Mod::NONE), Action::Navigate(NavigateAction::Up(1)));
        mappings.insert((Down, Mod::NONE), Action::Navigate(NavigateAction::Down(1)));
        mappings.insert((Left, Mod::NONE), Action::Navigate(NavigateAction::Left(1)));
        mappings.insert(
            (Right, Mod::NONE),
            Action::Navigate(NavigateAction::Right(1)),
        );

        mappings.insert(
            (PageUp, Mod::NONE),
            Action::Navigate(NavigateAction::PageUp),
        );
        mappings.insert(
            (PageDown, Mod::NONE),
            Action::Navigate(NavigateAction::PageDown),
        );

        // Ctrl+F/B for page navigation (vim style)
        mappings.insert(
            (Char('f'), Mod::CONTROL),
            Action::Navigate(NavigateAction::PageDown),
        );
        mappings.insert(
            (Char('b'), Mod::CONTROL),
            Action::Navigate(NavigateAction::PageUp),
        );

        mappings.insert((Home, Mod::NONE), Action::Navigate(NavigateAction::Home));
        mappings.insert((End, Mod::NONE), Action::Navigate(NavigateAction::End));

        // Vim navigation
        mappings.insert(
            (Char('h'), Mod::NONE),
            Action::Navigate(NavigateAction::Left(1)),
        );
        mappings.insert(
            (Char('j'), Mod::NONE),
            Action::Navigate(NavigateAction::Down(1)),
        );
        mappings.insert(
            (Char('k'), Mod::NONE),
            Action::Navigate(NavigateAction::Up(1)),
        );
        mappings.insert(
            (Char('l'), Mod::NONE),
            Action::Navigate(NavigateAction::Right(1)),
        );

        // Arrow keys (same as vim navigation - no mode switching)
        mappings.insert((Left, Mod::NONE), Action::Navigate(NavigateAction::Left(1)));
        mappings.insert(
            (Right, Mod::NONE),
            Action::Navigate(NavigateAction::Right(1)),
        );
        mappings.insert((Down, Mod::NONE), Action::Navigate(NavigateAction::Down(1)));
        mappings.insert((Up, Mod::NONE), Action::Navigate(NavigateAction::Up(1))); // Up navigates up, bounded at row 0

        // Page navigation
        mappings.insert(
            (PageUp, Mod::NONE),
            Action::Navigate(NavigateAction::PageUp),
        );
        mappings.insert(
            (PageDown, Mod::NONE),
            Action::Navigate(NavigateAction::PageDown),
        );

        // Home/End navigation (using traditional vim gg/G pattern)
        // Note: Single 'g' is reserved for vim command sequences like 'ga'
        // Use 'gg' for go to top (handled in vim command sequences)
        mappings.insert(
            (Char('G'), Mod::SHIFT),
            Action::Navigate(NavigateAction::End),
        );

        // First/Last column navigation
        mappings.insert(
            (Char('0'), Mod::NONE),
            Action::Navigate(NavigateAction::FirstColumn),
        );
        mappings.insert(
            (Char('^'), Mod::NONE),
            Action::Navigate(NavigateAction::FirstColumn),
        );
        mappings.insert(
            (Char('$'), Mod::NONE),
            Action::Navigate(NavigateAction::LastColumn),
        );

        // Viewport navigation (H/M/L like vim)
        mappings.insert((Char('H'), Mod::SHIFT), Action::NavigateToViewportTop);
        mappings.insert((Char('M'), Mod::SHIFT), Action::NavigateToViewportMiddle);
        mappings.insert((Char('L'), Mod::SHIFT), Action::NavigateToViewportBottom);

        // Mode switching
        mappings.insert((Esc, Mod::NONE), Action::ExitCurrentMode);
        mappings.insert((Char('q'), Mod::NONE), Action::Quit);
        mappings.insert((Char('c'), Mod::CONTROL), Action::Quit); // Ctrl+C to quit

        // F2 to switch to Command mode
        mappings.insert((F(2), Mod::NONE), Action::SwitchMode(AppMode::Command));

        // Vim-style 'i' for insert/input mode (switch to Command at current position)
        mappings.insert(
            (Char('i'), Mod::NONE),
            Action::SwitchModeWithCursor(AppMode::Command, CursorPosition::Current),
        );

        // Vim-style 'a' for append mode (switch to Command at end)
        mappings.insert(
            (Char('a'), Mod::NONE),
            Action::SwitchModeWithCursor(AppMode::Command, CursorPosition::End),
        );

        // Column operations
        mappings.insert((Char('p'), Mod::NONE), Action::ToggleColumnPin);
        mappings.insert((Char('-'), Mod::NONE), Action::HideColumn); // '-' to hide column
        mappings.insert(
            (Char('H'), Mod::CONTROL | Mod::SHIFT),
            Action::UnhideAllColumns,
        );
        mappings.insert((Char('+'), Mod::NONE), Action::UnhideAllColumns); // '+' to unhide all
        mappings.insert((Char('='), Mod::NONE), Action::UnhideAllColumns); // '=' to unhide all (easier than shift+= for +)
                                                                           // Handle both lowercase and uppercase 'e' for hide empty columns
        mappings.insert((Char('e'), Mod::NONE), Action::HideEmptyColumns);
        mappings.insert((Char('E'), Mod::SHIFT), Action::HideEmptyColumns);
        mappings.insert((Left, Mod::SHIFT), Action::MoveColumnLeft);
        mappings.insert((Right, Mod::SHIFT), Action::MoveColumnRight);
        // Also support < and > characters for column movement (more intuitive)
        mappings.insert((Char('<'), Mod::NONE), Action::MoveColumnLeft);
        mappings.insert((Char('>'), Mod::NONE), Action::MoveColumnRight);
        // Search and filter operations
        mappings.insert((Char('/'), Mod::NONE), Action::StartSearch);
        mappings.insert((Char('\\'), Mod::NONE), Action::StartColumnSearch);
        mappings.insert((Char('f'), Mod::NONE), Action::StartFilter);
        mappings.insert((Char('F'), Mod::SHIFT), Action::StartFuzzyFilter);

        // Sorting
        mappings.insert((Char('s'), Mod::NONE), Action::Sort(None));

        // View toggles
        mappings.insert((Char('N'), Mod::NONE), Action::ToggleRowNumbers);
        mappings.insert((Char('C'), Mod::NONE), Action::ToggleCompactMode);

        // Export operations
        mappings.insert((Char('x'), Mod::CONTROL), Action::ExportToCsv);
        mappings.insert((Char('j'), Mod::CONTROL), Action::ExportToJson);

        // Clear filter (when filter is active)
        mappings.insert((Char('C'), Mod::SHIFT), Action::ClearFilter);

        // Jump to row
        mappings.insert((Char(':'), Mod::NONE), Action::StartJumpToRow);

        // Search navigation
        mappings.insert((Char('n'), Mod::NONE), Action::NextSearchMatch);
        mappings.insert((Char('N'), Mod::SHIFT), Action::PreviousSearchMatch);

        // Selection mode toggle (v key like vim visual mode)
        mappings.insert((Char('v'), Mod::NONE), Action::ToggleSelectionMode);

        // Column statistics
        mappings.insert((Char('S'), Mod::SHIFT), Action::ShowColumnStatistics);

        // Column packing mode
        mappings.insert((Char('s'), Mod::ALT), Action::CycleColumnPacking);

        // Viewport/cursor lock operations
        mappings.insert((Char(' '), Mod::NONE), Action::ToggleViewportLock);
        mappings.insert((Char('x'), Mod::NONE), Action::ToggleCursorLock);
        mappings.insert((Char('X'), Mod::SHIFT), Action::ToggleCursorLock);
        mappings.insert((Char(' '), Mod::CONTROL), Action::ToggleViewportLock);

        // Additional help key
        mappings.insert((Char('?'), Mod::NONE), Action::ShowHelp); // ? also shows help
                                                                   // F-key actions are now handled globally

        // Clear pins
        mappings.insert((Char('P'), Mod::SHIFT), Action::ClearAllPins);

        // History search
        mappings.insert((Char('r'), Mod::CONTROL), Action::StartHistorySearch);

        self.mode_mappings.insert(AppMode::Results, mappings);
    }

    /// Initialize Command mode mappings
    fn init_command_mappings(&mut self) {
        use crate::buffer::AppMode;
        use KeyCode::{Backspace, Char, Delete, Down, End, Enter, Home, Left, Right, Up, F};
        use KeyModifiers as Mod;

        let mut mappings = HashMap::new();

        // Execute query
        mappings.insert((Enter, Mod::NONE), Action::ExecuteQuery);

        // F2 to switch back to Results mode (if results exist)
        mappings.insert((F(2), Mod::NONE), Action::SwitchMode(AppMode::Results));

        // Clear line
        mappings.insert((Char('u'), Mod::CONTROL), Action::ClearLine);

        // Undo/Redo
        mappings.insert((Char('z'), Mod::CONTROL), Action::Undo);
        mappings.insert((Char('y'), Mod::CONTROL), Action::Redo);

        // Cursor movement
        mappings.insert((Left, Mod::NONE), Action::MoveCursorLeft);
        mappings.insert((Right, Mod::NONE), Action::MoveCursorRight);
        mappings.insert((Down, Mod::NONE), Action::SwitchMode(AppMode::Results)); // Down enters Results mode
        mappings.insert((Home, Mod::NONE), Action::MoveCursorHome);
        mappings.insert((End, Mod::NONE), Action::MoveCursorEnd);
        mappings.insert((Char('a'), Mod::CONTROL), Action::MoveCursorHome);
        mappings.insert((Char('e'), Mod::CONTROL), Action::MoveCursorEnd);
        mappings.insert((Left, Mod::CONTROL), Action::MoveCursorWordLeft);
        mappings.insert((Right, Mod::CONTROL), Action::MoveCursorWordRight);
        mappings.insert((Char('b'), Mod::ALT), Action::MoveCursorWordLeft);
        mappings.insert((Char('f'), Mod::ALT), Action::MoveCursorWordRight);
        mappings.insert((Char('['), Mod::ALT), Action::JumpToPrevToken);
        mappings.insert((Char(']'), Mod::ALT), Action::JumpToNextToken);
        // Terminal-safe aliases (Alt+[ is swallowed by CSI prefix in most terminals)
        mappings.insert((Char(','), Mod::ALT), Action::JumpToPrevToken);
        mappings.insert((Char('.'), Mod::ALT), Action::JumpToNextToken);

        // Text editing
        mappings.insert((Backspace, Mod::NONE), Action::Backspace);
        mappings.insert((Delete, Mod::NONE), Action::Delete);
        mappings.insert((Char('w'), Mod::CONTROL), Action::DeleteWordBackward);
        mappings.insert((Char('d'), Mod::ALT), Action::DeleteWordForward);
        mappings.insert((Char('k'), Mod::CONTROL), Action::KillLine);
        // F9 and F10 are now handled globally

        // Clipboard operations
        mappings.insert((Char('v'), Mod::CONTROL), Action::Paste);

        // History navigation
        mappings.insert((Char('p'), Mod::CONTROL), Action::PreviousHistoryCommand);
        mappings.insert((Char('n'), Mod::CONTROL), Action::NextHistoryCommand);
        mappings.insert((Up, Mod::ALT), Action::PreviousHistoryCommand);
        mappings.insert((Down, Mod::ALT), Action::NextHistoryCommand);

        // SQL expansion operations
        mappings.insert((Char('*'), Mod::CONTROL), Action::ExpandAsterisk);
        mappings.insert((Char('*'), Mod::ALT), Action::ExpandAsteriskVisible);

        // F-key actions are now handled globally

        self.mode_mappings.insert(AppMode::Command, mappings);
    }

    /// Map a key event to an action based on current context
    pub fn map_key(&mut self, key: KeyEvent, context: &ActionContext) -> Option<Action> {
        // Handle vim-style counts and commands in Results mode
        if context.mode == AppMode::Results {
            if let KeyCode::Char(c) = key.code {
                if key.modifiers.is_empty() {
                    // Check if we're building a vim command (only for 'gg' now, others moved to chords)
                    if !self.vim_command_buffer.is_empty() {
                        // We have a pending command, check for valid combinations
                        let command = format!("{}{}", self.vim_command_buffer, c);
                        let action = if command.as_str() == "gg" {
                            // Go to top (vim-style)
                            self.vim_command_buffer.clear();
                            Some(Action::Navigate(NavigateAction::Home))
                        } else {
                            // Invalid command, clear buffer
                            self.vim_command_buffer.clear();
                            None
                        };

                        if action.is_some() {
                            return action;
                        }
                    }

                    // Check for digits (vim counts)
                    if c.is_ascii_digit() {
                        self.count_buffer.push(c);
                        return None; // Collecting count, no action yet
                    }

                    // Check if this starts a vim command sequence, but only if no standalone mapping exists
                    // Only 'g' is used for vim commands now (gg = go to top)
                    // SQL clause navigation moved to chord handler (cw, cs, etc.)
                    if c == 'g' {
                        let key_combo = (key.code, key.modifiers);
                        if let Some(mode_mappings) = self.mode_mappings.get(&context.mode) {
                            if mode_mappings.contains_key(&key_combo) {
                                // This key has a standalone mapping, let it fall through to normal mapping
                                // Don't treat it as a vim command starter
                                tracing::debug!(
                                    "Key '{}' has standalone mapping, not treating as vim command",
                                    c
                                );
                            } else {
                                // No standalone mapping, treat as vim command starter
                                self.vim_command_buffer.push(c);
                                tracing::debug!("Starting vim command buffer with '{}'", c);
                                return None; // Collecting command, no action yet
                            }
                        }
                    }
                }
            }
        }

        // Check for action with count
        let action = self.map_key_internal(key, context);

        // Apply count if we have one
        if !self.count_buffer.is_empty() {
            if let Some(mut action) = action {
                if let Ok(count) = self.count_buffer.parse::<usize>() {
                    action = self.apply_count_to_action(action, count);
                }
                self.count_buffer.clear();
                return Some(action);
            }
            // If no action, clear count buffer
            self.count_buffer.clear();
        }

        action
    }

    /// Internal key mapping without count handling
    fn map_key_internal(&self, key: KeyEvent, context: &ActionContext) -> Option<Action> {
        let key_combo = (key.code, key.modifiers);

        // Check global mappings first
        if let Some(action) = self.global_mappings.get(&key_combo) {
            return Some(action.clone());
        }

        // Check mode-specific mappings
        if let Some(mode_mappings) = self.mode_mappings.get(&context.mode) {
            if let Some(action) = mode_mappings.get(&key_combo) {
                return Some(action.clone());
            }
        }

        // Handle regular character input in Command mode
        if context.mode == AppMode::Command {
            if let KeyCode::Char(c) = key.code {
                if key.modifiers.is_empty() || key.modifiers == KeyModifiers::SHIFT {
                    // Regular character input
                    return Some(Action::InsertChar(c));
                }
            }
        }

        // No mapping found
        None
    }

    /// Apply a count to an action (for vim-style motions)
    fn apply_count_to_action(&self, action: Action, count: usize) -> Action {
        match action {
            Action::Navigate(NavigateAction::Up(_)) => Action::Navigate(NavigateAction::Up(count)),
            Action::Navigate(NavigateAction::Down(_)) => {
                Action::Navigate(NavigateAction::Down(count))
            }
            Action::Navigate(NavigateAction::Left(_)) => {
                Action::Navigate(NavigateAction::Left(count))
            }
            Action::Navigate(NavigateAction::Right(_)) => {
                Action::Navigate(NavigateAction::Right(count))
            }
            // Other actions don't support counts yet
            _ => action,
        }
    }

    /// Clear any pending state (like count buffer and vim command buffer)
    pub fn clear_pending(&mut self) {
        self.count_buffer.clear();
        self.vim_command_buffer.clear();
    }

    /// Check if we're collecting a count
    #[must_use]
    pub fn is_collecting_count(&self) -> bool {
        !self.count_buffer.is_empty()
    }

    /// Get the current count buffer for display
    #[must_use]
    pub fn get_count_buffer(&self) -> &str {
        &self.count_buffer
    }
}

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

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

    #[test]
    fn test_basic_navigation_mapping() {
        let mut mapper = KeyMapper::new();
        let context = ActionContext {
            mode: AppMode::Results,
            selection_mode: SelectionMode::Row,
            has_results: true,
            has_filter: false,
            has_search: false,
            row_count: 100,
            column_count: 10,
            current_row: 0,
            current_column: 0,
        };

        // Test arrow down
        let key = KeyEvent::new(KeyCode::Down, KeyModifiers::NONE);
        let action = mapper.map_key(key, &context);
        assert_eq!(action, Some(Action::Navigate(NavigateAction::Down(1))));

        // Test vim j
        let key = KeyEvent::new(KeyCode::Char('j'), KeyModifiers::NONE);
        let action = mapper.map_key(key, &context);
        assert_eq!(action, Some(Action::Navigate(NavigateAction::Down(1))));
    }

    #[test]
    fn test_vim_count_motion() {
        let mut mapper = KeyMapper::new();
        let context = ActionContext {
            mode: AppMode::Results,
            selection_mode: SelectionMode::Row,
            has_results: true,
            has_filter: false,
            has_search: false,
            row_count: 100,
            column_count: 10,
            current_row: 0,
            current_column: 0,
        };

        // Type "5"
        let key = KeyEvent::new(KeyCode::Char('5'), KeyModifiers::NONE);
        let action = mapper.map_key(key, &context);
        assert_eq!(action, None); // No action yet, collecting count
        assert_eq!(mapper.get_count_buffer(), "5");

        // Type "j"
        let key = KeyEvent::new(KeyCode::Char('j'), KeyModifiers::NONE);
        let action = mapper.map_key(key, &context);
        assert_eq!(action, Some(Action::Navigate(NavigateAction::Down(5))));
        assert_eq!(mapper.get_count_buffer(), ""); // Buffer cleared
    }

    #[test]
    fn test_global_mapping_override() {
        let mut mapper = KeyMapper::new();
        let context = ActionContext {
            mode: AppMode::Results,
            selection_mode: SelectionMode::Row,
            has_results: true,
            has_filter: false,
            has_search: false,
            row_count: 100,
            column_count: 10,
            current_row: 0,
            current_column: 0,
        };

        // F1 should work in any mode
        let key = KeyEvent::new(KeyCode::F(1), KeyModifiers::NONE);
        let action = mapper.map_key(key, &context);
        assert_eq!(action, Some(Action::ShowHelp));
    }

    #[test]
    fn test_command_mode_editing_actions() {
        let mut mapper = KeyMapper::new();
        let context = ActionContext {
            mode: AppMode::Command,
            selection_mode: SelectionMode::Row,
            has_results: false,
            has_filter: false,
            has_search: false,
            row_count: 0,
            column_count: 0,
            current_row: 0,
            current_column: 0,
        };

        // Test character input
        let key = KeyEvent::new(KeyCode::Char('a'), KeyModifiers::NONE);
        let action = mapper.map_key(key, &context);
        assert_eq!(action, Some(Action::InsertChar('a')));

        // Test uppercase character
        let key = KeyEvent::new(KeyCode::Char('A'), KeyModifiers::SHIFT);
        let action = mapper.map_key(key, &context);
        assert_eq!(action, Some(Action::InsertChar('A')));

        // Test backspace
        let key = KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE);
        let action = mapper.map_key(key, &context);
        assert_eq!(action, Some(Action::Backspace));

        // Test delete
        let key = KeyEvent::new(KeyCode::Delete, KeyModifiers::NONE);
        let action = mapper.map_key(key, &context);
        assert_eq!(action, Some(Action::Delete));

        // Test cursor movement - left
        let key = KeyEvent::new(KeyCode::Left, KeyModifiers::NONE);
        let action = mapper.map_key(key, &context);
        assert_eq!(action, Some(Action::MoveCursorLeft));

        // Test cursor movement - right
        let key = KeyEvent::new(KeyCode::Right, KeyModifiers::NONE);
        let action = mapper.map_key(key, &context);
        assert_eq!(action, Some(Action::MoveCursorRight));

        // Test Ctrl+A (home)
        let key = KeyEvent::new(KeyCode::Char('a'), KeyModifiers::CONTROL);
        let action = mapper.map_key(key, &context);
        assert_eq!(action, Some(Action::MoveCursorHome));

        // Test Ctrl+E (end)
        let key = KeyEvent::new(KeyCode::Char('e'), KeyModifiers::CONTROL);
        let action = mapper.map_key(key, &context);
        assert_eq!(action, Some(Action::MoveCursorEnd));

        // Test Ctrl+U (clear line)
        let key = KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL);
        let action = mapper.map_key(key, &context);
        assert_eq!(action, Some(Action::ClearLine));

        // Test Ctrl+W (delete word backward)
        let key = KeyEvent::new(KeyCode::Char('w'), KeyModifiers::CONTROL);
        let action = mapper.map_key(key, &context);
        assert_eq!(action, Some(Action::DeleteWordBackward));

        // Test Ctrl+Z (undo)
        let key = KeyEvent::new(KeyCode::Char('z'), KeyModifiers::CONTROL);
        let action = mapper.map_key(key, &context);
        assert_eq!(action, Some(Action::Undo));

        // Test Enter (execute query)
        let key = KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE);
        let action = mapper.map_key(key, &context);
        assert_eq!(action, Some(Action::ExecuteQuery));
    }

    #[test]
    fn test_vim_style_append_modes() {
        let mut mapper = KeyMapper::new();
        let context = ActionContext {
            mode: AppMode::Results,
            selection_mode: SelectionMode::Row,
            has_results: true,
            has_filter: false,
            has_search: false,
            row_count: 100,
            column_count: 10,
            current_row: 0,
            current_column: 0,
        };

        // Test 'i' for insert at current
        let key = KeyEvent::new(KeyCode::Char('i'), KeyModifiers::NONE);
        let action = mapper.map_key(key, &context);
        assert_eq!(
            action,
            Some(Action::SwitchModeWithCursor(
                AppMode::Command,
                CursorPosition::Current
            ))
        );

        // Test 'a' for append at end
        let key = KeyEvent::new(KeyCode::Char('a'), KeyModifiers::NONE);
        let action = mapper.map_key(key, &context);
        assert_eq!(
            action,
            Some(Action::SwitchModeWithCursor(
                AppMode::Command,
                CursorPosition::End
            ))
        );

        // Note: SQL clause navigation (wa, oa, etc.) has been moved to the KeyChordHandler
        // and is now accessed via chord sequences like 'cw' for WHERE, 'co' for ORDER BY.
        // These are tested separately in the chord handler tests.
    }

    #[test]
    fn test_sort_key_mapping() {
        let mut mapper = KeyMapper::new();
        let context = ActionContext {
            mode: AppMode::Results,
            selection_mode: SelectionMode::Row,
            has_results: true,
            has_filter: false,
            has_search: false,
            row_count: 100,
            column_count: 10,
            current_row: 0,
            current_column: 0,
        };

        // Test 's' for standalone sort action (this was the original issue)
        let key = KeyEvent::new(KeyCode::Char('s'), KeyModifiers::NONE);
        let action = mapper.map_key(key, &context);
        assert_eq!(action, Some(Action::Sort(None)));
    }

    #[test]
    fn test_vim_go_to_top() {
        let mut mapper = KeyMapper::new();
        let context = ActionContext {
            mode: AppMode::Results,
            selection_mode: SelectionMode::Row,
            has_results: true,
            has_filter: false,
            has_search: false,
            row_count: 100,
            column_count: 10,
            current_row: 0,
            current_column: 0,
        };

        // Test 'gg' for go to top (vim-style)
        let key_g1 = KeyEvent::new(KeyCode::Char('g'), KeyModifiers::NONE);
        let action_g1 = mapper.map_key(key_g1, &context);
        assert_eq!(action_g1, None); // First 'g' starts collecting command

        let key_g2 = KeyEvent::new(KeyCode::Char('g'), KeyModifiers::NONE);
        let action_gg = mapper.map_key(key_g2, &context);
        assert_eq!(action_gg, Some(Action::Navigate(NavigateAction::Home)));
    }

    #[test]
    fn test_bug_reproduction_s_key_not_found() {
        // This test reproduces the original bug where 's' key mapping wasn't found
        let mut mapper = KeyMapper::new();
        let context = ActionContext {
            mode: AppMode::Results,
            selection_mode: SelectionMode::Row,
            has_results: true,
            has_filter: false,
            has_search: false,
            row_count: 100,
            column_count: 10,
            current_row: 0,
            current_column: 0,
        };

        // Before the fix, this would return None because 's' was being intercepted
        // by vim command logic. After the fix, it should return Sort action.
        let key = KeyEvent::new(KeyCode::Char('s'), KeyModifiers::NONE);
        let action = mapper.map_key(key, &context);

        // This should NOT be None - the bug was that map_key returned None
        assert!(
            action.is_some(),
            "Bug reproduction: 's' key should map to an action, not return None"
        );
        assert_eq!(
            action,
            Some(Action::Sort(None)),
            "Bug reproduction: 's' key should map to Sort action"
        );
    }
}