edamame 0.1.1

A fast TUI Markdown editor and viewer
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
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
//! Bottom status region.
//!
//! Composes the contextual [`HintLine`] on top of the persistent
//! [`StatusBar`].  The hint line adapts to the cursor's context
//! (default / table / list) and can be overlaid by a transient message
//! or preempted by a modal prompt.

use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::{
    buffer::Buffer,
    layout::{Constraint, Direction, Layout, Rect},
    style::Style,
    text::{Line, Span},
    widgets::{Paragraph, Widget},
};

use crate::config::keymap::format_key_compact;
use crate::config::{Action, KeyMap, Theme};
use crate::diff::Decision;
use crate::editor::{EditorState, Mode};

use super::status_bar::{StatusBar, StatusBarState};

/// A single keybind chord + label pair (e.g. `^C` + `Copy`).  The
/// chord glyph alone renders in the contrasting `hint_chord` theme
/// slot (no surrounding padding inside the badge), followed by a
/// single space, the label in `hint_label`, and a two-space separator
/// between successive hints.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HintChord {
    pub chord: String,
    pub label: String,
}

impl HintChord {
    pub fn new(chord: impl Into<String>, label: impl Into<String>) -> Self {
        Self {
            chord: chord.into(),
            label: label.into(),
        }
    }
}

/// A default-hint payload: an optional leading plaintext hint (e.g.
/// `Press any key to edit` in Preview mode) followed by a chord row.
///
/// `search_match` carries the `(current, total)` match counter of an
/// active search flow.  It renders as an accent badge (`theme.status_mode_search`)
/// at the very front of the hint line — ahead of the prelude and chords
/// — mirroring the appearance it had when it lived on the status bar.
#[derive(Debug, Clone, Default)]
pub struct HintSet {
    pub prelude: Option<String>,
    pub chords: Vec<HintChord>,
    pub search_match: Option<(usize, usize)>,
}

/// What the hint line currently displays.  The three variants are
/// mutually exclusive — a transient message replaces the default
/// chords, and a modal prompt replaces both.
///
/// All variants own their strings so the hint can be built up-front
/// and then passed by value into [`EditorView`](crate::ui::editor_view::EditorView) without entangling its
/// borrow of `&mut self.editor`.
#[derive(Debug, Clone)]
pub enum HintContent {
    /// Default: contextual keybind chords, with an optional leading
    /// plaintext prelude.
    Chords(HintSet),
    /// Transient overlay (e.g. `Copied`, `Saved`).
    Transient {
        text: String,
        style: ratatui::style::Style,
    },
    /// Modal prompt: a leading prompt string followed by chord options.
    Prompt {
        prompt: String,
        chords: Vec<HintChord>,
    },
    /// Vim command line (`/` `?` `:`): a prefix glyph plus the typed text
    /// with a block cursor at char index `cursor`.  `cursor_visible`
    /// carries the blink phase so the cursor pulses like other inputs.
    CommandLine {
        prefix: char,
        text: String,
        cursor: usize,
        cursor_visible: bool,
    },
}

/// The UI-layer facts [`hint_line_for`] needs that aren't readable off
/// `EditorState`.  Passed as one named struct rather than a run of
/// positional `bool`s so a call site can't silently transpose them; build
/// it with `..Default::default()` and set only the fields that apply.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct HintCtx {
    /// True when the file / in-document history stack holds at least one
    /// back- or forward-entry.  Lives on the `App` (`nav_back` /
    /// `nav_forward`), not in document state.
    pub nav_available: bool,
    /// True while the vim handler is in the VisualLine sub-mode.  A V-LINE
    /// selection covering a single line is charwise-empty (`anchor ==
    /// active`) even though the whole line paints as highlighted, so the
    /// selection row can't be inferred from `state.selection_size()` alone.
    pub visual_line: bool,
}

/// Pick the default hint set for `state`, adapting to the cursor's
/// Markdown context.  Pure function so it can be unit-tested without
/// spinning up a terminal.
///
/// Chord glyphs are looked up dynamically from `keymap` so that
/// rebinds applied through the keybinds overlay (or via
/// `keybindings.toml`) appear in the hint line on the very next
/// frame — no chord text is hardcoded.  Chords for actions that the
/// user has unbound are silently dropped from the row.
///
/// Priority: active search > table (Rendered only) > task-list item >
/// mode-default.
/// Tables don't appear in Raw mode because the table-editing chords
/// don't work against the raw source — the user is editing the plain
/// Markdown and `Tab` / `⌥↑↓` insert characters or do nothing.
///
/// `ctx` carries the UI-layer facts that aren't readable off `state` — see
/// [`HintCtx`].  They're threaded in from the `App` rather than read off
/// `state` because the nav stacks and the vim sub-mode are UI-layer facts,
/// not document state.
///
/// The vim handler reuses this same row unchanged: vim's modal keys
/// (`i` / `v` / `:` / `/`, the Visual operators, …) are vim-internal and
/// the status bar already advertises the active sub-mode, so the hint line
/// shows edamame's own contextual + baseline chords in every vim sub-mode
/// rather than re-advertising vim's keys.  A Visual selection lands on the
/// shared selection row (Cut / Copy / Paste / …) because vim Visual sets
/// the editor `selection` just like a mouse drag does; VisualLine gets its
/// own shorter row (see [`visual_line_chords`]).
pub fn hint_line_for(state: &EditorState, keymap: &KeyMap, ctx: HintCtx) -> HintSet {
    // An active search flow replaces the row wholesale, whatever the
    // view mode — only the flow keys work while it's active.  The
    // Replace / Replace-all chords appear only in the replace flow
    // (non-empty replace field).
    if let Some(search) = state.search.as_ref() {
        let mut chords = search_flow_chords(search.is_replace_flow());
        // In the replace flow, surface the undo/redo chords (looked up
        // from the live keymap, like every non-hard-bound hint) right
        // before the trailing `Esc Exit` so a mis-replace is visibly
        // recoverable without leaving the flow.  Redo is gated on
        // `can_redo`, mirroring the baseline edit row.
        if search.is_replace_flow() {
            let exit_idx = chords.len().saturating_sub(1);
            if state.history.can_redo() {
                if let Some(c) = chord_for(keymap, &Action::Redo, "Redo") {
                    chords.insert(exit_idx, c);
                }
            }
            if let Some(c) = chord_for(keymap, &Action::Undo, "Undo") {
                chords.insert(exit_idx, c);
            }
        }
        return HintSet {
            prelude: None,
            chords,
            // The match counter leads the search-flow hint line; absent
            // when the result set is empty (e.g. after a replace-all
            // consumes every match).
            search_match: (!search.matches.is_empty())
                .then(|| (search.focused_idx + 1, search.matches.len())),
        };
    }
    match state.mode {
        Mode::Preview => {
            let mut chords = chords_from(
                keymap,
                &[
                    (Action::ShowCommandPalette, "Menu"),
                    (Action::GoToSection, "Go to"),
                    (Action::OpenSearch, "Find"),
                    (Action::Copy, "Copy"),
                    (Action::Quit, "Quit"),
                ],
            );
            // History navigation leads the row when there's somewhere to
            // go — Preview is browse mode, so back/forward is its most
            // relevant context.  Suppressed when the cursor sits in a
            // table: `Alt+Left/Right` reorder columns there (the nav
            // redirect in `app::actions` only fires outside a table), and
            // the cursor offset persists into Preview, so a table cell is
            // reachable here too.
            if ctx.nav_available && !cursor_in_table(state) {
                chords.insert(0, nav_chord());
            }
            HintSet {
                prelude: Some("Press any key to edit".to_owned()),
                chords,
                search_match: None,
            }
        }
        // A vim VisualLine selection covering a single line is charwise-empty
        // (anchor == active) yet paints the whole line as highlighted, so it
        // can't be inferred from `selection_size` — the `ctx.visual_line` flag
        // carries it.  The `selection.is_some()` conjunct keeps the row
        // self-consistent rather than trusting the App-layer invariant that
        // V-LINE always has one: an advertised Cut with nothing selected
        // would be a dead chord.
        Mode::Rendered | Mode::Raw if ctx.visual_line && state.selection.is_some() => HintSet {
            prelude: None,
            chords: visual_line_chords(keymap),
            search_match: None,
        },
        Mode::Rendered | Mode::Raw if state.selection_size().is_some() => HintSet {
            prelude: None,
            chords: chords_from(
                keymap,
                &[
                    (Action::Cut, "Cut"),
                    (Action::Copy, "Copy"),
                    // Paste is included so the user can replace the
                    // selection with the clipboard contents in one
                    // chord.  The whole baseline row is suppressed
                    // for the duration of the selection — mirroring
                    // how the table-context row replaces the row
                    // wholesale rather than prepending to it.
                    (Action::Paste, "Paste"),
                    // Bold / italic wrap the selection; they only make
                    // sense with one active, so they ride this row
                    // rather than the baseline.  Dropped automatically
                    // if the user has unbound them.
                    (Action::BoldSelection, "Bold"),
                    (Action::ItalicizeSelection, "Italic"),
                ],
            ),
            search_match: None,
        },
        Mode::Rendered if cursor_in_table(state) => HintSet {
            prelude: None,
            chords: table_chords(keymap),
            search_match: None,
        },
        Mode::Diff => {
            let all_resolved = state.diff.as_ref().is_some_and(|d| d.all_resolved());
            let focused_resolved = state.diff.as_ref().is_some_and(|d| {
                d.focused_decision()
                    .is_some_and(|dec| dec != Decision::Pending)
            });
            HintSet {
                prelude: None,
                chords: diff_review_chords(all_resolved, focused_resolved),
                search_match: None,
            }
        }
        Mode::Rendered | Mode::Raw => {
            // Baseline edit-mode hints — Menu anchors the row so
            // the command-palette chord is always the discovery
            // entry; then Paste / Undo / [Redo] / Open / Save /
            // Preview / view-mode toggle / Quit.  Redo is gated on
            // `state.history.can_redo()` so it only appears when
            // there's actually something to redo; the row shifts
            // by one slot when it pops in or out.  Cut / Copy are
            // absent from the baseline because they're only useful
            // with an active selection, which is handled by the
            // selection-override arm above.  The view-mode chord
            // label flips with the current mode (Rendered → "Raw",
            // Raw → "Render") and "Preview" / "Raw" / "Render" are
            // all destination labels — never the current state.
            //
            // Contextual chords (those that only make sense in a
            // specific state) are prepended to the front of the row
            // so the user sees them immediately.  Final order when
            // both are active: Link, Toggle, Menu, ...  Link leads
            // because its trigger is the narrowest (a specific
            // `[text](url)` span); Toggle follows.
            let view_toggle_label = match state.mode {
                Mode::Raw => "Render",
                _ => "Raw",
            };
            let redo_entry = state.history.can_redo().then_some((Action::Redo, "Redo"));
            let baseline = [
                Some((Action::ShowCommandPalette, "Menu")),
                Some((Action::GoToSection, "Go to")),
                Some((Action::OpenSearch, "Find")),
                Some((Action::Paste, "Paste")),
                Some((Action::Undo, "Undo")),
                redo_entry,
                Some((Action::Open, "Open")),
                Some((Action::Save, "Save")),
                Some((Action::ExitToPreview, "Preview")),
                Some((Action::ToggleRawMode, view_toggle_label)),
                Some((Action::Quit, "Quit")),
            ];
            let entries: Vec<(Action, &str)> = baseline.into_iter().flatten().collect();
            let mut chords = chords_from(keymap, &entries);
            // Insertion order here matters for the final layout:
            // each `insert(0, ..)` pushes the previous head back by
            // one slot, so the LAST insert ends up leftmost.  Order
            // of inserts below is the REVERSE of the desired visual
            // order: Back/fwd → Toggle → Link.  History navigation
            // goes in first so it lands rightmost of the contextual
            // block (just left of `Menu`) — its trigger (a non-empty
            // history stack) is the broadest, so it trails the narrower
            // Link / Toggle hints.  The `!cursor_in_table` guard keeps
            // the ⌥←→ chord hidden whenever the cursor sits in a table —
            // there `Alt+Left/Right` reorder columns instead of
            // navigating history (the redirect in `app::actions` only
            // fires outside a table).  The Rendered table arm above
            // returns before this point, but Raw mode has no such arm, so
            // the explicit check is what covers the Raw-in-table case.
            if ctx.nav_available && !cursor_in_table(state) {
                chords.insert(0, nav_chord());
            }
            if cursor_on_task_item(state) {
                if let Some(c) = chord_for(keymap, &Action::ToggleCheckbox, "Toggle") {
                    chords.insert(0, c);
                }
            }
            if cursor_on_link(state) {
                if let Some(c) = chord_for(keymap, &Action::FollowLinkUnderCursor, "Open link") {
                    chords.insert(0, c);
                }
            }
            HintSet {
                prelude: None,
                chords,
                search_match: None,
            }
        }
    }
}

/// The combined back/forward history-navigation hint (`⌥←→ Back/fwd`).
///
/// The chord glyph is fixed rather than looked up from `keymap` because
/// `NavigateBack` / `NavigateForward` carry no default binding — the keys
/// that actually fire them are `Alt+Left` / `Alt+Right`, which the `App`
/// redirects from `TableMoveColumnLeft` / `TableMoveColumnRight` when the
/// cursor is outside any table (see `app::actions::handle_app_action`).
/// One badge stands in for both directions, mirroring the table arm's
/// bundled `⌥↑↓←→` glyph.
fn nav_chord() -> HintChord {
    HintChord::new("⌥←→", "Back/fwd")
}

/// Look up the first key bound to `action` in `keymap` and pair it
/// with `label`.  Returns `None` when the action is unbound — the
/// caller drops unbound entries from the hint row entirely.
fn chord_for(keymap: &KeyMap, action: &Action, label: &str) -> Option<HintChord> {
    let ev = keymap.first_key_event_for(action)?;
    Some(HintChord::new(format_key_compact(&ev), label.to_owned()))
}

/// Convenience — apply [`chord_for`] over a slice and collect the
/// successful lookups in order.
fn chords_from(keymap: &KeyMap, entries: &[(Action, &str)]) -> Vec<HintChord> {
    entries
        .iter()
        .filter_map(|(action, label)| chord_for(keymap, action, label))
        .collect()
}

/// Diff Review hint row.  The key glyphs come from the shared
/// `diff_keys` table (via [`crate::input::diff_hint`]) — the same source
/// the input handler, keybinds overlay, decision divider, and
/// diff-intro modal read — so the advertised chord can never disagree
/// with the key that actually fires.  The labels are this row's own
/// (terse, to fit the bar).
///
/// `Esc Exit` trails the row, and only once every hunk is resolved:
/// diff mode can't be exited via `Esc` while hunks are still pending
/// (see `Action::DiffExit`), so advertising the chord before then
/// would be misleading.
fn diff_review_chords(all_resolved: bool, focused_resolved: bool) -> Vec<HintChord> {
    let mk = |action: &Action, label: &str| {
        HintChord::new(crate::input::diff_hint(action), label.to_owned())
    };
    let mut chords = vec![
        mk(&Action::DiffNext, "Next"),
        mk(&Action::DiffPrev, "Prev"),
        mk(&Action::DiffAcceptHunk, "Accept"),
        mk(&Action::DiffRejectHunk, "Reject"),
        mk(&Action::DiffAcceptAll, "Accept all"),
        mk(&Action::DiffRejectAll, "Reject all"),
    ];
    // `⌫ Reset` only makes sense once the focused hunk carries a
    // decision — it's a no-op on a still-`Pending` hunk, so advertising
    // it then would be misleading.
    if focused_resolved {
        chords.push(mk(&Action::DiffResetHunk, "Reset"));
    }
    // `Esc Exit` trails the row so the primary review actions lead; it
    // appears only once the whole diff is resolved.
    if all_resolved {
        chords.push(mk(&Action::DiffExit, "Exit"));
    }
    chords
}

/// Search-flow hint row.  Key glyphs come from the shared
/// `search::search_keys` table (via [`crate::search::search_hint`]) —
/// the same source the input handler reads — so the advertised chord
/// can never disagree with the key that actually fires.  `r Replace`
/// and `a Replace all` ride the row only in the replace flow; `Esc
/// Exit` trails so the navigation chords lead.
fn search_flow_chords(is_replace: bool) -> Vec<HintChord> {
    let mk = |action: &Action, label: &str| {
        HintChord::new(crate::search::search_hint(action), label.to_owned())
    };
    let mut chords = vec![
        mk(&Action::SearchNext, "Next"),
        mk(&Action::SearchPrev, "Prev"),
    ];
    if is_replace {
        chords.push(mk(&Action::SearchReplace, "Replace"));
        chords.push(mk(&Action::SearchReplaceAll, "Replace all"));
    }
    chords.push(mk(&Action::SearchExit, "Exit"));
    chords
}

/// Build the vim VisualLine hint row: the three clipboard chords that the
/// App widens to whole lines before dispatching
/// (`App::dispatch_visual_line_clipboard`), so each one acts on exactly the
/// highlighted rows.
///
/// Deliberately shorter than the charwise selection row — `Bold` / `Italic`
/// are omitted because `edit_ops::toggle_wrap` bails on both shapes a V-LINE
/// selection can take: an empty charwise span (a single-line V-LINE, where
/// `anchor == active`) and a span containing a newline (any multi-line one).
/// Advertising them here would be advertising two no-ops.
fn visual_line_chords(keymap: &KeyMap) -> Vec<HintChord> {
    chords_from(
        keymap,
        &[
            (Action::Cut, "Cut"),
            (Action::Copy, "Copy"),
            (Action::Paste, "Paste"),
        ],
    )
}

/// Build the table-context hint row.  When the four arrow-driven
/// actions of a bundle (`Move row/col`, `Insert row/col`) all share
/// modifiers and arrow key codes, we collapse them into a single
/// glyph (`⌥↑↓←→`) — the visually compact shape the user already
/// learns from the default keymap.  When the user has rebound any of
/// the four to a non-arrow chord, we fall back to listing the four
/// chords joined by `/` so the badge still reflects what's actually
/// bound.
fn table_chords(keymap: &KeyMap) -> Vec<HintChord> {
    let mut out: Vec<HintChord> = Vec::new();
    // "Next cell" reuses InsertTab's chord because table next-cell is
    // a context dispatch from InsertTab in `edit_ops`.  Looking up
    // InsertTab keeps the displayed chord truthful even if the user
    // rebinds Tab to something exotic.
    if let Some(c) = chord_for(keymap, &Action::InsertTab, "Next cell") {
        out.push(c);
    }
    if let Some(c) = chord_for(keymap, &Action::TablePrevCell, "Prev cell") {
        out.push(c);
    }
    if let Some(badge) = arrow_bundle_chord(
        keymap,
        &Action::TableMoveRowUp,
        &Action::TableMoveRowDown,
        &Action::TableMoveColumnLeft,
        &Action::TableMoveColumnRight,
    ) {
        out.push(HintChord::new(badge, "Move row/col"));
    }
    if let Some(badge) = arrow_bundle_chord(
        keymap,
        &Action::TableInsertRowAbove,
        &Action::TableInsertRowBelow,
        &Action::TableInsertColumnLeft,
        &Action::TableInsertColumnRight,
    ) {
        out.push(HintChord::new(badge, "Insert row/col"));
    }
    if let Some(c) = chord_for(keymap, &Action::TableDeleteRow, "Del row") {
        out.push(c);
    }
    if let Some(c) = chord_for(keymap, &Action::TableDeleteColumn, "Del col") {
        out.push(c);
    }
    out
}

/// Compose a single chord glyph for an arrow-driven bundle (e.g.
/// `⌥↑↓←→` for the four `TableMoveRow*` / `TableMoveColumn*`
/// actions).  Returns the bundled glyph when all four chords share
/// modifiers AND each maps to its expected arrow direction; falls
/// back to a slash-joined list of compact chords otherwise.  Returns
/// `None` only when none of the four actions is bound — there's
/// nothing to display in that case.
fn arrow_bundle_chord(
    keymap: &KeyMap,
    up: &Action,
    down: &Action,
    left: &Action,
    right: &Action,
) -> Option<String> {
    let bound: Vec<KeyEvent> = [up, down, left, right]
        .iter()
        .filter_map(|a| keymap.first_key_event_for(a))
        .collect();
    if bound.is_empty() {
        return None;
    }
    let modifiers_match = bound.iter().all(|e| e.modifiers == bound[0].modifiers);
    let arrows_match = bound.len() == 4
        && bound[0].code == KeyCode::Up
        && bound[1].code == KeyCode::Down
        && bound[2].code == KeyCode::Left
        && bound[3].code == KeyCode::Right;
    if modifiers_match && arrows_match {
        let mut prefix = String::new();
        if bound[0].modifiers.contains(KeyModifiers::CONTROL) {
            prefix.push('^');
        }
        if bound[0].modifiers.contains(KeyModifiers::ALT) {
            prefix.push('⌥');
        }
        if bound[0].modifiers.contains(KeyModifiers::SHIFT) {
            prefix.push('⇧');
        }
        return Some(format!("{prefix}↑↓←→"));
    }
    Some(
        bound
            .iter()
            .map(format_key_compact)
            .collect::<Vec<_>>()
            .join("/"),
    )
}

/// Lay out a chord list into spans.  Always renders every chord with
/// its label — if the row is too narrow, the trailing chords are
/// truncated by ratatui's non-wrapping `Paragraph`.  A bare chord
/// badge with no label isn't useful, so we don't bother dropping
/// labels under width pressure.
///
/// Layout per hint: `{chord}` in `hint_chord` (the badge is exactly
/// the chord glyph — no surrounding padding gets the badge bg), then
/// ` {label}` in `hint_label` (a single leading space separates label
/// from chord), then `  ` (two spaces) in `bar_style` as the separator
/// before the next hint.
///
/// `bar_style` is the hint-bar background for the active mode — normally
/// [`Theme::hint_bar`], but [`Theme::hint_bar_diff`] while in diff mode
/// so the inter-chord separators match the recolored bar instead of
/// punching the default hue through every gap.
pub fn lay_out_chords(chords: &[HintChord], theme: &Theme, bar_style: Style) -> Vec<Span<'static>> {
    // Wash the chord-badge and label backgrounds with the active bar's
    // bg so the whole hint row reads as one bar.  In every mode except
    // diff this is a no-op (`hint_bar`, `hint_chord` and `hint_label`
    // all share `surface_elevated`); in diff mode it extends the
    // recolored `hint_bar_diff` wash across the badges instead of
    // leaving them on the default surface.
    let chord_style = match bar_style.bg {
        Some(bg) => theme.hint_chord.bg(bg),
        None => theme.hint_chord,
    };
    let label_style = match bar_style.bg {
        Some(bg) => theme.hint_label.bg(bg),
        None => theme.hint_label,
    };
    let mut spans: Vec<Span<'static>> = Vec::with_capacity(chords.len() * 3);
    for chord in chords {
        spans.push(Span::styled(chord.chord.clone(), chord_style));
        spans.push(Span::styled(format!(" {}", chord.label), label_style));
        spans.push(Span::styled("  ".to_string(), bar_style));
    }
    spans
}

/// Build the spans for a vim command line: a leading ` {prefix}` glyph, then
/// the typed text with a block cursor (the unified modal `theme.cursor`) at
/// char index `cursor`.  The cursor is a single, blink-stable cell — the
/// character under it recolored when `cursor_visible`, shown plainly when not
/// (a space past end-of-line) — so an empty `/` still reserves the cursor cell
/// and the row never jitters on blink.
fn command_line_spans(
    prefix: char,
    text: &str,
    cursor: usize,
    cursor_visible: bool,
    theme: &Theme,
    bar_style: Style,
) -> Vec<Span<'static>> {
    let base = match bar_style.bg {
        Some(bg) => theme.hint_label.bg(bg),
        None => theme.hint_label,
    };
    // The cursor is the unified block — the same blink-stable one-cell slot
    // every other modal input uses, recoloring the character it sits on.
    let mut spans = vec![Span::styled(format!(" {prefix}"), base)];
    spans.extend(crate::ui::cursor::text_field_spans(
        text,
        cursor,
        cursor_visible,
        base,
        theme.cursor,
    ));
    spans
}

/// The hint-line widget.  Renders chords / transient / prompt onto a
/// single row, with a trailing fill using `bar_style`.
pub struct HintLine<'a> {
    pub content: HintContent,
    pub theme: &'a Theme,
    /// Background style for the bar fill and inter-chord separators.
    /// [`Theme::hint_bar`] in every mode except diff, which uses
    /// [`Theme::hint_bar_diff`] so the recolored bar signals the mode
    /// change.
    pub bar_style: Style,
}

impl<'a> Widget for HintLine<'a> {
    fn render(self, area: Rect, buf: &mut Buffer) {
        if area.height == 0 || area.width == 0 {
            return;
        }
        let width = area.width as usize;

        let spans: Vec<Span<'_>> = match &self.content {
            HintContent::Chords(set) => {
                let mut v: Vec<Span<'_>> = Vec::new();
                // Search match counter — an accent badge (` n/N `) that
                // leads the hint line ahead of every other item.  Same
                // `status_mode_search` styling it carried on the status
                // bar; a trailing bar-styled space pads it off from the
                // first chord so the gap matches the inter-chord one.
                if let Some((current, total)) = set.search_match {
                    v.push(Span::styled(
                        format!(" {}/{} ", current, total),
                        self.theme.status_mode_search,
                    ));
                    v.push(Span::styled(" ".to_string(), self.bar_style));
                }
                // Prelude — plain text on the hint bar, followed by a
                // two-space gap that acts as a separator before the
                // chord row.  Rendered as hint_bar bg + hint_label fg
                // so it reads as a sentence, not another chord.
                if let Some(prelude) = &set.prelude {
                    let text = format!(" {}  ", prelude);
                    let prelude_style = match self.bar_style.bg {
                        Some(bg) => self.theme.hint_label.bg(bg),
                        None => self.theme.hint_label,
                    };
                    v.push(Span::styled(text, prelude_style));
                }
                v.extend(lay_out_chords(&set.chords, self.theme, self.bar_style));
                v
            }
            HintContent::Transient { text, style } => {
                vec![Span::styled(format!(" {} ", text), *style)]
            }
            HintContent::Prompt { prompt, chords } => {
                let prompt_text = format!(" {}  ", prompt);
                let prompt_span = Span::styled(prompt_text, self.theme.transient_warning);
                let chord_spans = lay_out_chords(chords, self.theme, self.bar_style);
                let mut v = vec![prompt_span];
                v.extend(chord_spans);
                v
            }
            HintContent::CommandLine {
                prefix,
                text,
                cursor,
                cursor_visible,
            } => command_line_spans(
                *prefix,
                text,
                *cursor,
                *cursor_visible,
                self.theme,
                self.bar_style,
            ),
        };

        // Sum what we've rendered so we can pad the trailing fill with
        // the hint_bar background — otherwise the terminal shows its
        // own default background in the gap.
        let used: usize = spans
            .iter()
            .map(|s| s.content.chars().count())
            .sum::<usize>();
        let mut all_spans = spans;
        if used < width {
            all_spans.push(Span::styled(" ".repeat(width - used), self.bar_style));
        }

        Paragraph::new(Line::from(all_spans))
            .style(self.bar_style)
            .render(area, buf);
    }
}

/// Composite widget owning the bottom region layout.  Renders a
/// [`HintLine`] above a persistent [`StatusBar`].
pub struct BottomRegion<'a> {
    pub status: StatusBarState<'a>,
    pub hint: HintContent,
    pub theme: &'a Theme,
}

impl<'a> BottomRegion<'a> {
    /// Height in rows that [`BottomRegion`] requires.  Consulted by
    /// `EditorView` to partition the terminal area.
    pub fn height() -> u16 {
        2
    }
}

impl<'a> Widget for BottomRegion<'a> {
    fn render(self, area: Rect, buf: &mut Buffer) {
        if area.height == 0 {
            return;
        }
        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints([Constraint::Length(1), Constraint::Length(1)])
            .split(area);
        // Diff mode recolors the whole hint bar to match the
        // status bar's mode shift (§7).
        let bar_style = if matches!(self.status.mode, Mode::Diff) {
            self.theme.hint_bar_diff
        } else {
            self.theme.hint_bar
        };
        HintLine {
            content: self.hint,
            theme: self.theme,
            bar_style,
        }
        .render(chunks[0], buf);
        StatusBar {
            state: self.status,
            theme: self.theme,
        }
        .render(chunks[1], buf);
    }
}

/// True when the editor's cursor sits inside a Markdown table.  Mirror
/// of the App-internal helper so pure hint-line code doesn't depend on
/// private app state.
fn cursor_in_table(state: &EditorState) -> bool {
    let cursor_byte = state.buffer.rope().char_to_byte(state.cursor.offset);
    let source = state.buffer.contents();
    crate::editor::table_edit::find_table_at(&source, cursor_byte).is_some()
}

/// True when the cursor sits on a Markdown *task* list item (i.e. a
/// list item whose marker is followed by `[ ]` / `[x]`).  Regular
/// bullet / ordered items return false — they have no checkbox to
/// toggle, so offering `^Space Toggle` would just confuse the user.
fn cursor_on_task_item(state: &EditorState) -> bool {
    let cursor_byte = state.buffer.rope().char_to_byte(state.cursor.offset);
    let source = state.buffer.contents();
    let Some(list) = crate::editor::list_edit::find_list_at(&source, cursor_byte) else {
        return false;
    };
    list.items
        .iter()
        .find(|it| cursor_byte >= it.start && cursor_byte <= it.end)
        .is_some_and(|it| it.task.is_some())
}

/// True when the cursor sits inside a `[text](url)` link on the
/// current line.  Reuses the `link_at_offset` scan that
/// `mouse_ops` and `App::resolve_link_at_cursor` use, so hint
/// visibility and the actual `FollowLinkUnderCursor` dispatch agree
/// on what counts as a link.
fn cursor_on_link(state: &EditorState) -> bool {
    let cursor_byte = state.buffer.rope().char_to_byte(state.cursor.offset);
    let source = state.buffer.contents();
    crate::editor::mouse_ops::link_at_offset(&source, cursor_byte).is_some()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{KeyBindingOverrides, Theme};
    use crate::document::Buffer;
    use crate::editor::{EditorState, Mode};
    use ratatui::{backend::TestBackend, Terminal};

    fn theme() -> &'static Theme {
        Box::leak(Box::new(Theme::default()))
    }

    fn state(text: &str) -> EditorState {
        EditorState::new(Buffer::from_str(text), theme())
    }

    fn keymap() -> KeyMap {
        KeyMap::build(&KeyBindingOverrides::default()).unwrap()
    }

    // ── hint_line_for ─────────────────────────────────────────────

    #[test]
    fn preview_hint_has_prelude_and_menu_first() {
        let st = state("hello");
        let set = hint_line_for(&st, &keymap(), HintCtx::default());
        assert_eq!(set.prelude.as_deref(), Some("Press any key to edit"));
        assert_eq!(set.chords[0].chord, "^P");
        assert_eq!(set.chords[0].label, "Menu");
        assert!(set.chords.iter().any(|c| c.label == "Quit"));
    }

    #[test]
    fn diff_hint_gates_exit_on_full_resolution() {
        // Pending hunks: no `Esc Exit` hint (diff can't be exited yet),
        // and the navigation/decision chords lead the row.
        let pending = diff_review_chords(false, false);
        assert!(
            !pending.iter().any(|c| c.label == "Exit"),
            "Exit hint must be hidden while hunks are pending",
        );
        assert_eq!(pending[0].label, "Next", "Tab/Next leads when pending");

        // All resolved: the review actions still lead, and `Esc Exit`
        // appears at the very end of the row.
        let resolved = diff_review_chords(true, true);
        assert_eq!(resolved[0].label, "Next", "review actions lead the row");
        let last = resolved.last().expect("non-empty row");
        assert_eq!(last.chord, "Esc");
        assert_eq!(last.label, "Exit");
    }

    #[test]
    fn diff_reset_hint_only_when_focused_hunk_resolved() {
        // Focused hunk still pending → no `Reset` chord (it'd be a
        // no-op there).
        let pending = diff_review_chords(false, false);
        assert!(
            !pending.iter().any(|c| c.label == "Reset"),
            "Reset hint must be hidden while the focused hunk is pending",
        );
        // Focused hunk decided → `⌫ Reset` is offered.
        let decided = diff_review_chords(false, true);
        let reset = decided
            .iter()
            .find(|c| c.label == "Reset")
            .expect("Reset hint must appear once the focused hunk is decided");
        assert_eq!(reset.chord, "⌫");
    }

    #[test]
    fn rendered_hint_has_save_and_paste_and_raw() {
        let mut st = state("hello");
        st.mode = Mode::Rendered;
        let set = hint_line_for(&st, &keymap(), HintCtx::default());
        let labels: Vec<_> = set.chords.iter().map(|c| c.label.as_str()).collect();
        assert_eq!(set.chords[0].chord, "^P", "Menu is always first");
        assert!(labels.contains(&"Paste"));
        assert!(labels.contains(&"Save"));
        assert!(
            labels.contains(&"Raw"),
            "Rendered-mode chord toggles TO Raw"
        );
        assert!(labels.contains(&"Quit"));
        // Cut / Copy are selection-gated — no selection here.
        assert!(
            !labels.contains(&"Cut"),
            "Cut must stay hidden without an active selection"
        );
        assert!(
            !labels.contains(&"Copy"),
            "Copy must stay hidden without an active selection"
        );
        // Bold / Italic are selection-gated too.
        assert!(
            !labels.contains(&"Bold") && !labels.contains(&"Italic"),
            "Bold/Italic must stay hidden without an active selection"
        );
        // Plain paragraph has no link, so "Open link" must not appear.
        assert!(
            !labels.contains(&"Open link"),
            "link hint must stay hidden when the cursor isn't on a link"
        );
        // No prelude in edit mode.
        assert!(set.prelude.is_none());
    }

    #[test]
    fn redo_hint_only_appears_when_history_can_redo() {
        use crate::document::history::EditDelta;

        let mut st = state("hello");
        st.mode = Mode::Rendered;

        // Fresh history → no redo entry yet.
        let labels: Vec<_> = hint_line_for(&st, &keymap(), HintCtx::default())
            .chords
            .iter()
            .map(|c| c.label.clone())
            .collect();
        assert!(
            !labels.contains(&"Redo".to_string()),
            "Redo must be hidden when history.can_redo() is false: {labels:?}"
        );

        // Record an edit and undo it — now redo is available.
        st.buffer.insert(5, "!");
        st.history.record(EditDelta {
            offset: 5,
            removed: String::new(),
            inserted: "!".into(),
        });
        st.history.undo(&mut st.buffer).unwrap();
        assert!(st.history.can_redo(), "test premise");

        let labels: Vec<_> = hint_line_for(&st, &keymap(), HintCtx::default())
            .chords
            .iter()
            .map(|c| c.label.clone())
            .collect();
        assert!(
            labels.contains(&"Redo".to_string()),
            "Redo must appear once history.can_redo() is true: {labels:?}"
        );

        // Recording a fresh edit clears the redo stack — Redo vanishes.
        st.buffer.insert(0, "X");
        st.history.record(EditDelta {
            offset: 0,
            removed: String::new(),
            inserted: "X".into(),
        });
        assert!(!st.history.can_redo(), "test premise");
        let labels: Vec<_> = hint_line_for(&st, &keymap(), HintCtx::default())
            .chords
            .iter()
            .map(|c| c.label.clone())
            .collect();
        assert!(
            !labels.contains(&"Redo".to_string()),
            "Redo must disappear after the redo stack is cleared: {labels:?}"
        );
    }

    #[test]
    fn raw_mode_flips_view_toggle_label_to_render() {
        let mut st = state("hello");
        st.mode = Mode::Raw;
        let set = hint_line_for(&st, &keymap(), HintCtx::default());
        let labels: Vec<_> = set.chords.iter().map(|c| c.label.as_str()).collect();
        assert!(
            labels.contains(&"Render"),
            "Raw-mode chord toggles TO Render, got: {labels:?}"
        );
        assert!(!labels.contains(&"Raw"));
    }

    #[test]
    fn link_hint_appears_only_when_cursor_on_link() {
        let mut st = state("a [site](https://example.com) rest");
        st.mode = Mode::Rendered;
        // Cursor in the "site" link text → on a link.
        st.cursor.offset = 5;
        let on_link = hint_line_for(&st, &keymap(), HintCtx::default());
        assert_eq!(
            on_link.chords[0].label, "Open link",
            "contextual link hint must lead the row"
        );
        // Cursor in the trailing plain-text tail → not on a link.
        st.cursor.offset = 32;
        let off_link = hint_line_for(&st, &keymap(), HintCtx::default());
        assert!(
            !off_link.chords.iter().any(|c| c.label == "Open link"),
            "Open link hint leaked outside the link span"
        );
    }

    #[test]
    fn contextual_hints_lead_with_link_before_toggle() {
        // Task item that also contains a link — both contextual
        // chords should be at the front, with Open link first and
        // Toggle second, ahead of every baseline chord.
        let mut st = state("- [ ] see [docs](https://example.com)\n");
        st.mode = Mode::Rendered;
        st.cursor.offset = 14; // inside "docs"
        let set = hint_line_for(&st, &keymap(), HintCtx::default());
        assert_eq!(set.chords[0].label, "Open link");
        assert_eq!(set.chords[1].label, "Toggle");
        assert_eq!(
            set.chords[2].label, "Menu",
            "baseline Menu chord follows the contextual block"
        );
    }

    #[test]
    fn selection_replaces_baseline_with_cut_copy_paste() {
        use crate::document::Selection;
        let mut st = state("hello world");
        st.mode = Mode::Rendered;
        st.selection = Some(Selection {
            anchor: 0,
            active: 5,
        });
        let set = hint_line_for(&st, &keymap(), HintCtx::default());
        let labels: Vec<_> = set.chords.iter().map(|c| c.label.as_str()).collect();
        assert_eq!(
            labels,
            vec!["Cut", "Copy", "Paste", "Bold", "Italic"],
            "active selection must replace the baseline row with the selection chords only"
        );
    }

    #[test]
    fn visual_line_shows_selection_hints_despite_empty_charwise_span() {
        use crate::document::Selection;
        // V-LINE on a single line paints the whole line but leaves the
        // charwise selection empty (anchor == active), so `selection_size`
        // is None.  The `visual_line` flag must still surface the
        // selection row.
        let mut st = state("hello world");
        st.mode = Mode::Rendered;
        st.selection = Some(Selection {
            anchor: 3,
            active: 3,
        });
        assert!(
            st.selection_size().is_none(),
            "an anchor == active selection is charwise-empty"
        );
        let baseline = hint_line_for(&st, &keymap(), HintCtx::default());
        assert_ne!(
            baseline.chords.first().map(|c| c.label.as_str()),
            Some("Cut"),
            "without the V-LINE flag an empty selection shows the baseline row"
        );
        let set = hint_line_for(
            &st,
            &keymap(),
            HintCtx {
                visual_line: true,
                ..Default::default()
            },
        );
        let labels: Vec<_> = set.chords.iter().map(|c| c.label.as_str()).collect();
        assert_eq!(
            labels,
            vec!["Cut", "Copy", "Paste"],
            "V-LINE must show its clipboard row even with an empty charwise span"
        );
    }

    #[test]
    fn visual_line_row_omits_bold_and_italic() {
        use crate::document::Selection;
        // `toggle_wrap` bails on an empty span *and* on one containing a
        // newline, so Bold / Italic are no-ops under either V-LINE shape.
        // The charwise row still carries them.
        let mut st = state("alpha\nbeta\n");
        st.mode = Mode::Rendered;
        st.selection = Some(Selection {
            anchor: 2,
            active: 8,
        });
        let charwise = hint_line_for(&st, &keymap(), HintCtx::default());
        let charwise_labels: Vec<_> = charwise.chords.iter().map(|c| c.label.as_str()).collect();
        assert_eq!(
            charwise_labels,
            vec!["Cut", "Copy", "Paste", "Bold", "Italic"]
        );
        let v_line = hint_line_for(
            &st,
            &keymap(),
            HintCtx {
                visual_line: true,
                ..Default::default()
            },
        );
        let v_line_labels: Vec<_> = v_line.chords.iter().map(|c| c.label.as_str()).collect();
        assert_eq!(
            v_line_labels,
            vec!["Cut", "Copy", "Paste"],
            "V-LINE must not advertise the wrap chords it can't run"
        );
    }

    #[test]
    fn visual_line_flag_without_a_selection_falls_through() {
        // The V-LINE row is gated on an actual selection as well as the
        // flag, so a desynced sub-mode can't advertise a Cut with nothing
        // to cut.
        let mut st = state("hello world");
        st.mode = Mode::Rendered;
        assert!(st.selection.is_none(), "test premise");
        let set = hint_line_for(
            &st,
            &keymap(),
            HintCtx {
                visual_line: true,
                ..Default::default()
            },
        );
        assert_eq!(
            set.chords[0].label, "Menu",
            "no selection → the baseline row, whatever the sub-mode"
        );
    }

    #[test]
    fn clearing_selection_restores_baseline_hints() {
        use crate::document::Selection;
        let mut st = state("hello world");
        st.mode = Mode::Rendered;
        st.selection = Some(Selection {
            anchor: 0,
            active: 5,
        });
        assert_eq!(
            hint_line_for(&st, &keymap(), HintCtx::default())
                .chords
                .iter()
                .map(|c| c.label.clone())
                .collect::<Vec<_>>(),
            vec!["Cut", "Copy", "Paste", "Bold", "Italic"]
        );
        // Clearing the selection must drop the row back to the
        // baseline edit-mode chords with Menu leading.
        st.selection = None;
        let set = hint_line_for(&st, &keymap(), HintCtx::default());
        assert_eq!(set.chords[0].label, "Menu");
        let labels: Vec<_> = set.chords.iter().map(|c| c.label.as_str()).collect();
        assert!(!labels.contains(&"Cut"));
        assert!(!labels.contains(&"Copy"));
    }

    #[test]
    fn plain_list_item_does_not_show_toggle_chord() {
        // Cursor at byte 2 — inside `- a` (a regular bullet, NOT a task).
        let mut st = state("- a\n- b\n");
        st.mode = Mode::Rendered;
        st.cursor.offset = 2;
        let set = hint_line_for(&st, &keymap(), HintCtx::default());
        assert!(
            !set.chords.iter().any(|c| c.label == "Toggle"),
            "regular list items have no checkbox to toggle"
        );
    }

    #[test]
    fn task_list_item_shows_toggle_chord_first() {
        // Cursor inside a task-list item: `- [ ] todo`.
        let mut st = state("- [ ] todo\n");
        st.mode = Mode::Rendered;
        st.cursor.offset = 8;
        let set = hint_line_for(&st, &keymap(), HintCtx::default());
        assert_eq!(set.chords[0].chord, "^Space");
        assert_eq!(set.chords[0].label, "Toggle");
    }

    #[test]
    fn raw_mode_suppresses_table_hints() {
        let source = "| a | b |\n| - | - |\n| c | d |\n";
        let mut st = state(source);
        st.mode = Mode::Raw;
        st.cursor.offset = 22;
        let set = hint_line_for(&st, &keymap(), HintCtx::default());
        let labels: Vec<_> = set.chords.iter().map(|c| c.label.as_str()).collect();
        assert!(
            !labels.iter().any(|l| l.contains("cell")),
            "raw mode shows baseline edit hints, not table hints: {labels:?}"
        );
        assert!(labels.contains(&"Save"));
    }

    #[test]
    fn rebinding_action_updates_chord_in_hint_line() {
        // Move ShowCommandPalette off Ctrl-P onto F1 via the same
        // `KeyMap::rebind` call the keybinds overlay uses — which
        // (unlike the load-time merge in `KeyMap::build`) drops the
        // prior key for the action.  The Menu chord must follow.
        let mut km = keymap();
        let mut overrides = KeyBindingOverrides::default();
        km.rebind(&Action::ShowCommandPalette, "f1", &mut overrides)
            .unwrap();
        let mut st = state("hello");
        st.mode = Mode::Rendered;
        let set = hint_line_for(&st, &km, HintCtx::default());
        let menu = set
            .chords
            .iter()
            .find(|c| c.label == "Menu")
            .expect("Menu hint must still appear after rebind");
        assert_eq!(
            menu.chord, "F1",
            "hint chord must reflect the live binding, got: {menu:?}"
        );
        assert!(
            !set.chords.iter().any(|c| c.chord == "^P"),
            "stale ^P chord leaked into hint row: {:?}",
            set.chords
        );
    }

    #[test]
    fn unbinding_an_action_drops_its_chord_from_the_row() {
        // Steal Save's `Ctrl-S` slot by rebinding Quit onto it; the
        // override hands Ctrl-S to Quit and leaves Save without a
        // binding.  The Save chord must vanish from the hint row
        // entirely (not render as a blank chord).
        let mut overrides = KeyBindingOverrides::default();
        overrides.0.insert("Quit".into(), "ctrl+s".into());
        let km = KeyMap::build(&overrides).unwrap();
        assert!(
            km.first_key_event_for(&Action::Save).is_none(),
            "test premise: Save must be orphaned by the rebind"
        );
        let mut st = state("hello");
        st.mode = Mode::Rendered;
        let set = hint_line_for(&st, &km, HintCtx::default());
        let labels: Vec<_> = set.chords.iter().map(|c| c.label.as_str()).collect();
        assert!(
            !labels.contains(&"Save"),
            "unbound Save must drop from the hint row, got: {labels:?}"
        );
    }

    #[test]
    fn arrow_bundle_falls_back_to_slash_list_when_modifiers_diverge() {
        // Rebind one of the four `Move row/col` arrow actions through
        // the in-app rebind path so the prior arrow binding is
        // dropped — the bundle can no longer collapse to `⌥↑↓←→`,
        // and the badge must list the four bound chords joined by
        // `/`.
        let mut km = keymap();
        let mut overrides = KeyBindingOverrides::default();
        km.rebind(&Action::TableMoveRowUp, "ctrl+shift+u", &mut overrides)
            .unwrap();
        let source = "| a | b |\n| - | - |\n| c | d |\n";
        let mut st = state(source);
        st.mode = Mode::Rendered;
        st.cursor.offset = 22;
        let set = hint_line_for(&st, &km, HintCtx::default());
        let move_chord = set
            .chords
            .iter()
            .find(|c| c.label == "Move row/col")
            .expect("Move row/col bundle must remain");
        assert!(
            move_chord.chord.contains('/'),
            "fallback bundle must slash-join individual chords, got: {move_chord:?}"
        );
        assert!(
            move_chord.chord.contains("^⇧U"),
            "rebound chord must appear in the bundle, got: {move_chord:?}"
        );
    }

    #[test]
    fn nav_hint_appears_only_when_history_available() {
        let mut st = state("hello");
        st.mode = Mode::Rendered;
        // No history → no Back/fwd chord.
        let off = hint_line_for(&st, &keymap(), HintCtx::default());
        assert!(
            !off.chords.iter().any(|c| c.label == "Back/fwd"),
            "Back/fwd must stay hidden with an empty history stack"
        );
        // History present → the ⌥←→ chord rides the contextual block,
        // sitting just before the baseline `Menu` chord.
        let on = hint_line_for(
            &st,
            &keymap(),
            HintCtx {
                nav_available: true,
                ..Default::default()
            },
        );
        let nav = on
            .chords
            .iter()
            .position(|c| c.label == "Back/fwd")
            .expect("Back/fwd hint must appear when history is available");
        assert_eq!(on.chords[nav].chord, "⌥←→");
        let menu = on
            .chords
            .iter()
            .position(|c| c.label == "Menu")
            .expect("Menu still present");
        assert_eq!(nav + 1, menu, "Back/fwd must sit immediately before Menu");
    }

    #[test]
    fn nav_hint_suppressed_in_table() {
        // Alt+Left/Right reorder columns inside a table, so the history
        // chord must not be advertised there even when history exists.
        let source = "| a | b |\n| - | - |\n| c | d |\n";
        let mut st = state(source);
        st.mode = Mode::Rendered;
        st.cursor.offset = 22;
        let set = hint_line_for(
            &st,
            &keymap(),
            HintCtx {
                nav_available: true,
                ..Default::default()
            },
        );
        assert!(
            !set.chords.iter().any(|c| c.label == "Back/fwd"),
            "Back/fwd must stay hidden while the cursor is in a table"
        );
    }

    #[test]
    fn nav_hint_suppressed_in_table_raw_mode() {
        // Raw mode has no early-returning table arm, so the suppression
        // rests entirely on the explicit `!cursor_in_table` guard.  Without
        // it the row would advertise ⌥←→ while Alt+Left/Right actually
        // reorder the table column (the nav redirect fires only outside a
        // table, regardless of view mode).
        let source = "| a | b |\n| - | - |\n| c | d |\n";
        let mut st = state(source);
        st.mode = Mode::Raw;
        st.cursor.offset = 22;
        let set = hint_line_for(
            &st,
            &keymap(),
            HintCtx {
                nav_available: true,
                ..Default::default()
            },
        );
        assert!(
            !set.chords.iter().any(|c| c.label == "Back/fwd"),
            "Back/fwd must stay hidden in a table even in Raw mode"
        );
    }

    #[test]
    fn nav_hint_leads_preview_row() {
        // Preview is browse mode — history navigation leads the row.
        let st = state("hello");
        let set = hint_line_for(
            &st,
            &keymap(),
            HintCtx {
                nav_available: true,
                ..Default::default()
            },
        );
        assert_eq!(set.chords[0].label, "Back/fwd");
        assert_eq!(set.chords[0].chord, "⌥←→");
        assert_eq!(
            set.chords[1].label, "Menu",
            "baseline Menu follows the nav hint"
        );
    }

    #[test]
    fn nav_hint_trails_link_and_toggle() {
        // On a task line that also holds a link, the narrower Link /
        // Toggle hints lead and Back/fwd trails them, still ahead of the
        // baseline row.
        let mut st = state("- [ ] see [docs](https://example.com)\n");
        st.mode = Mode::Rendered;
        st.cursor.offset = 14; // inside "docs"
        let set = hint_line_for(
            &st,
            &keymap(),
            HintCtx {
                nav_available: true,
                ..Default::default()
            },
        );
        assert_eq!(set.chords[0].label, "Open link");
        assert_eq!(set.chords[1].label, "Toggle");
        assert_eq!(set.chords[2].label, "Back/fwd");
        assert_eq!(set.chords[3].label, "Menu");
    }

    #[test]
    fn rendered_table_cursor_shows_table_chords() {
        let source = "| a | b |\n| - | - |\n| c | d |\n";
        let mut st = state(source);
        st.mode = Mode::Rendered;
        st.cursor.offset = 22;
        let set = hint_line_for(&st, &keymap(), HintCtx::default());
        let labels: Vec<_> = set.chords.iter().map(|c| c.label.as_str()).collect();
        assert!(labels.iter().any(|l| l.contains("cell")));
        assert!(labels.iter().any(|l| l.contains("row")));
    }

    // ── active search ─────────────────────────────────────────────

    #[test]
    fn active_search_replaces_the_row() {
        use crate::search::SearchState;
        let mut st = state("foo foo foo");
        st.mode = Mode::Rendered;
        let search = SearchState::new("foo".to_owned(), None).unwrap();
        st.enter_search(search);
        // An active search replaces the whole row with the flow chords +
        // match counter — under vim too, since `hint_line_for` no longer
        // branches on the sub-mode (the App passes the same editor state
        // either way).
        let set = hint_line_for(&st, &keymap(), HintCtx::default());
        assert!(set.search_match.is_some(), "match counter must lead");
        assert!(set.chords.iter().any(|c| c.label == "Next"));
        assert!(
            !set.chords.iter().any(|c| c.label == "Menu"),
            "baseline chords must yield to the active search row"
        );
    }

    // ── lay_out_chords ────────────────────────────────────────────

    #[test]
    fn lay_out_always_includes_labels() {
        let chords = vec![
            HintChord::new("^A", "Alpha"),
            HintChord::new("^B", "Bravo"),
            HintChord::new("^C", "Charlie"),
        ];
        let spans = lay_out_chords(&chords, theme(), theme().hint_bar);
        let concat: String = spans.iter().map(|s| s.content.to_string()).collect();
        assert!(concat.contains("Alpha"));
        assert!(concat.contains("Bravo"));
        assert!(concat.contains("Charlie"));
    }

    // ── BottomRegion rendering ────────────────────────────────────

    fn render_region(width: u16, hint: HintContent) -> String {
        let t = theme();
        let height = BottomRegion::height();
        let backend = TestBackend::new(width, height);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal
            .draw(|frame| {
                let region = BottomRegion {
                    status: StatusBarState {
                        mode: Mode::Rendered,
                        filename: "test.md",
                        line_count: 3,
                        scroll_total: 3,
                        viewport_rows: 1,
                        modified: false,
                        scroll: 0,
                        cursor_line: Some(1),
                        cursor_col: Some(1),
                        section_path: Vec::new(),
                        diff_progress: None,
                        vim_mode_label: None,
                    },
                    hint,
                    theme: t,
                };
                frame.render_widget(region, frame.area());
            })
            .unwrap();
        let buf = terminal.backend().buffer().clone();
        let mut out = String::new();
        for y in 0..height {
            for x in 0..width {
                let sym = buf
                    .cell((x, y))
                    .map_or(' ', |c| c.symbol().chars().next().unwrap_or(' '));
                out.push(sym);
            }
            out.push('\n');
        }
        out
    }

    fn chord_set(chords: Vec<HintChord>) -> HintSet {
        HintSet {
            prelude: None,
            chords,
            search_match: None,
        }
    }

    #[test]
    fn bottom_region_renders_both_rows() {
        let set = chord_set(vec![HintChord::new("^S", "Save")]);
        let out = render_region(40, HintContent::Chords(set));
        assert!(out.contains("Save"), "out: {out}");
        assert!(out.contains("test.md"), "out: {out}");
    }

    #[test]
    fn transient_overlay_replaces_chords() {
        let out = render_region(
            40,
            HintContent::Transient {
                text: "Copied".to_owned(),
                style: Theme::default().transient_info,
            },
        );
        assert!(out.contains("Copied"), "out: {out}");
        // Chords shouldn't bleed through.
        assert!(!out.contains("Save"), "out: {out}");
    }

    #[test]
    fn prompt_shows_prompt_text_before_chords() {
        let chords = vec![HintChord::new("R", "Reload"), HintChord::new("I", "Ignore")];
        let out = render_region(
            60,
            HintContent::Prompt {
                prompt: "File changed on disk.".to_owned(),
                chords,
            },
        );
        assert!(out.contains("File changed"), "out: {out}");
        assert!(out.contains("Reload"), "out: {out}");
    }

    #[test]
    fn search_match_badge_leads_the_hint_line() {
        let set = HintSet {
            prelude: None,
            chords: vec![HintChord::new("⏎", "Next")],
            search_match: Some((2, 3)),
        };
        let out = render_region(80, HintContent::Chords(set));
        let first_line = out.lines().next().unwrap();
        let counter_idx = first_line.find("2/3").expect("match counter must render");
        let next_idx = first_line.find("Next").expect("chord must render");
        assert!(
            counter_idx < next_idx,
            "match counter must lead the hint line, line: {first_line:?}"
        );
    }

    #[test]
    fn no_search_match_badge_without_an_active_search() {
        let set = chord_set(vec![HintChord::new("^S", "Save")]);
        let out = render_region(80, HintContent::Chords(set));
        assert!(
            !out.contains('/'),
            "no counter when search_match is None: {out}"
        );
    }

    #[test]
    fn prelude_appears_before_chords() {
        let set = HintSet {
            prelude: Some("Press any key to edit".to_owned()),
            chords: vec![HintChord::new("^P", "Menu")],
            search_match: None,
        };
        let out = render_region(80, HintContent::Chords(set));
        let first_line = out.lines().next().unwrap();
        let prelude_idx = first_line.find("Press any key").unwrap();
        let menu_idx = first_line.find("^P").unwrap();
        assert!(prelude_idx < menu_idx, "prelude must precede chords");
    }
}