git-custom-cli 2.3.2

Fast, keyboard-driven terminal UI for dated Git commits
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
use anyhow::{anyhow, bail, Context, Result};
use crossterm::event::{
    self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton, MouseEventKind,
};
use std::{
    fs,
    process::{Command, Stdio},
};

use crate::{
    accounts::{self, invalidate_logins, Account},
    git, gitconfig,
    model::{
        adjust, current_year, extra_keys, preset_date, preset_time, preview, valid_date, valid_time, Config,
        Values,
    },
    screen,
};

/// Error text for every user cancel, so `main` can tell a cancel from a failure.
pub const CANCELLED: &str = "Cancelled";

const MENU_HINT: &str = "Up/Down move  ·  Left/Right change  ·  Enter or click select  ·  Esc/Q quit  ·  Ctrl+C quit";
const MENU_HINT_SHORT: &str = "Up/Down  Left/Right change  Enter  Esc quit";
const TREE_HINT: &str =
    "Up/Down or W/S scroll  ·  PgUp/PgDn  ·  Home/End  ·  Esc/Q back  ·  Ctrl+C quit";
const CONFIRM_HINT: &str = "Y yes  ·  N no  ·  Enter default  ·  Ctrl+C quit";
const LINE_HINT: &str = "Enter save  ·  Esc cancel  ·  Ctrl+C quit";
const MESSAGE_HINT: &str =
    "Click Save & go back  ·  Tab+Enter or Ctrl+Enter save  ·  Esc leave without saving  ·  Enter new line";
const MASK_HINT: &str =
    "Digits type  ·  n/y/-/+ presets  ·  Left/Right move  ·  Backspace clear  ·  Enter save  ·  Esc cancel";
const HISTORY_HINT: &str =
    "Tab switch  ·  Up/Down or W/S scroll  ·  PgUp/PgDn  ·  Home/End  ·  Esc/Q back  ·  Ctrl+C quit";
const PICK_HINT: &str = "Up/Down or W/S move  ·  Enter select  ·  Esc/Q cancel  ·  Ctrl+C quit";
const ACCOUNTS_HINT: &str = "Up/Down or W/S move  ·  Enter/Space set active  ·  A add  ·  E edit  ·  D delete  ·  L sign in  ·  R refresh  ·  Esc/Q back  ·  Ctrl+C quit";

enum Input {
    Key(KeyEvent),
    /// Left click on this body line.
    Click(usize),
}

/// Next key press or body click, or None when the screen should redraw (resize, or the pointer moved the mascot).
fn read_input() -> Result<Option<Input>> {
    loop {
        match event::read()? {
            Event::Key(key) if key.kind == KeyEventKind::Press => return Ok(Some(Input::Key(key))),
            Event::Mouse(mouse) if mouse.kind == MouseEventKind::Down(MouseButton::Left) => {
                if let Some(line) = screen::body_line(mouse.row) {
                    return Ok(Some(Input::Click(line)));
                }
            }
            Event::Mouse(mouse) if screen::track_pointer(mouse.column) => return Ok(None),
            Event::Resize(..) => {
                screen::invalidate();
                return Ok(None);
            }
            _ => {}
        }
    }
}

/// Like `read_input`, for screens that ignore clicks.
fn read_key() -> Result<Option<KeyEvent>> {
    loop {
        match read_input()? {
            Some(Input::Key(key)) => return Ok(Some(key)),
            Some(Input::Click(_)) => {}
            None => return Ok(None),
        }
    }
}

fn is_interrupt(key: &KeyEvent) -> bool {
    key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL)
}

pub fn is_cancel(error: &anyhow::Error) -> bool {
    error.to_string() == CANCELLED
}

/// Shows a frame until a key is pressed; the frame redraws when the mascot moves.
pub fn wait_key(body: &[String], footer: &str) -> Result<()> {
    loop {
        screen::draw(body, footer, None)?;
        if read_key()?.is_some() {
            return Ok(());
        }
    }
}

pub fn menu(
    context: &[String],
    values: &mut Values,
    notice: Option<&str>,
    index: &mut usize,
    active: &str,
    branches: &[String],
) -> Result<String> {
    loop {
        let choices = menu_choices(values, active, *index);
        let ready = [
            !values.date.is_empty(),
            !values.time.is_empty(),
            !values.branch.is_empty(),
            !values.message.trim().is_empty(),
        ]
        .into_iter()
        .filter(|ready| *ready)
        .count();
        let mut body = context.to_vec();
        body.push(String::new());
        body.push(screen::accent(format!(
            "MISSION CONTROL  [{ready}/4 FIELDS READY]"
        )));
        for (position, choice) in choices.iter().enumerate() {
            body.push(if position == SEPARATOR {
                screen::muted("  ------------")
            } else {
                styled_menu_line(position == *index, choice)
            });
        }
        if let Some(notice) = notice {
            body.push(String::new());
            body.push(screen::danger(notice));
        }
        // Scroll so the selected row stays visible on short terminals.
        let selected_line = context.len() + 2 + *index;
        let offset = selected_line.saturating_sub(screen::body_rows().saturating_sub(1));
        let narrow = crossterm::terminal::size()
            .is_ok_and(|(width, _)| (width as usize) < MENU_HINT.chars().count() + 6);
        let hint = if narrow { MENU_HINT_SHORT } else { MENU_HINT };
        screen::draw(&body[offset.min(body.len())..], hint, None)?;

        let key = match read_input()? {
            None => continue,
            Some(Input::Key(key)) => key,
            // Context lines 0-1 are branch and identity; the working-tree lines follow.
            Some(Input::Click(line)) if (2..context.len()).contains(&(line + offset)) => {
                return Ok("tree".into())
            }
            Some(Input::Click(line)) => {
                let line = line + offset;
                // Choices start after the context, a blank line and the title.
                match line.checked_sub(context.len() + 2) {
                    Some(position) if position < choices.len() && position != SEPARATOR => {
                        *index = position;
                        return Ok(choice_name(position).into());
                    }
                    _ => continue,
                }
            }
        };
        if is_interrupt(&key) {
            bail!(CANCELLED);
        }
        let mut code = key.code;
        if let KeyCode::Char(ch) = code {
            if !key.modifiers.contains(KeyModifiers::CONTROL)
                && !matches!(ch, 'w' | 'W' | 's' | 'S' | 'q' | 'Q' | ' ')
            {
                let has = |action: &str| extra_keys(action).contains(&ch);
                if has("up") {
                    code = KeyCode::Up;
                } else if has("down") {
                    code = KeyCode::Down;
                } else if has("select") {
                    code = KeyCode::Enter;
                } else if has("quit") {
                    code = KeyCode::Esc;
                } else if has("first") {
                    code = KeyCode::Home;
                } else if has("last") {
                    code = KeyCode::End;
                }
            }
        }
        match code {
            KeyCode::Up | KeyCode::BackTab | KeyCode::Char('w' | 'W') => {
                *index = previous_choice(*index)
            }
            KeyCode::Down | KeyCode::Tab | KeyCode::Char('s' | 'S') => {
                *index = next_choice(*index)
            }
            KeyCode::Home | KeyCode::PageUp => *index = 0,
            KeyCode::End | KeyCode::PageDown => *index = FINALIZE,
            KeyCode::Left | KeyCode::Right => {
                let delta = if code == KeyCode::Left { -1 } else { 1 };
                match *index {
                    0 | 1 | 2 | 5 => {
                        adjust(values, *index, delta, branches);
                    }
                    8 => {
                        return Ok(if delta < 0 {
                            "account-prev"
                        } else {
                            "account-next"
                        }
                        .into())
                    }
                    _ => {}
                }
            }
            KeyCode::Enter | KeyCode::Char(' ') => return Ok(choice_name(*index).into()),
            KeyCode::Esc | KeyCode::Char('q' | 'Q') => bail!(CANCELLED),
            _ => {}
        }
    }
}

fn menu_choices(values: &Values, active: &str, index: usize) -> Vec<String> {
    let mode = match (values.amend, values.dry_run) {
        (true, true) => "amend, dry-run",
        (true, false) => "amend",
        (false, true) => "dry-run",
        _ => "normal",
    };
    let message = if values.message.is_empty() {
        "[not set]".into()
    } else {
        preview(&values.message, 40)
    };
    let shown = |value: &str| {
        if value.is_empty() {
            "[not set]".to_string()
        } else {
            value.to_string()
        }
    };
    // The selected editable row shows arrows for Left/Right.
    let arrows = |row: usize, value: String| {
        if row == index {
            format!("◀ {value} ▶")
        } else {
            value
        }
    };
    vec![
        format!("Edit date     : {}", arrows(0, shown(&values.date))),
        format!("Edit time     : {}", arrows(1, shown(&values.time))),
        format!("Edit branch   : {}", arrows(2, shown(&values.branch))),
        format!("Edit message  : {message}"),
        format!("Edit msg (editor): {message}"),
        format!("Edit options  : {}", arrows(5, mode.to_string())),
        "View history".into(),
        "View working tree".into(),
        format!("Account: {}", arrows(8, active.to_string())),
        "Push only".into(),
        "------------".into(),
        "Finalize & commit".into(),
    ]
}

const SEPARATOR: usize = 10;
const FINALIZE: usize = 11;

fn choice_name(index: usize) -> &'static str {
    match index {
        0 => "date",
        1 => "time",
        2 => "branch",
        3 => "message",
        4 => "editor",
        5 => "options",
        6 => "history",
        7 => "tree",
        8 => "account",
        9 => "push",
        _ => "finalize",
    }
}

fn styled_menu_line(active: bool, text: &str) -> String {
    if active {
        screen::selected(format!("  ▶ {text}"))
    } else {
        format!("  {}", screen::muted(format!("◇ {text}")))
    }
}

/// Menu rows 0-5 are the fields, 6 History, 7 Working tree, 8 Account, 9 Push only, 10 a separator, 11 Finalize.
fn previous_choice(index: usize) -> usize {
    match index {
        0 => FINALIZE,
        FINALIZE => 9,
        _ => index - 1,
    }
}

fn next_choice(index: usize) -> usize {
    match index {
        9 => FINALIZE,
        FINALIZE => 0,
        _ => index + 1,
    }
}

/// Full `git status --short`, read fresh, scrollable. Load errors show as text.
pub fn working_tree() -> Result<()> {
    let rows = match git::status_lines() {
        Ok(lines) => lines,
        Err(error) => vec![screen::danger(format!("Could not read status: {error}"))],
    };
    let title = if rows == ["(clean working tree)"] {
        screen::success("Working tree clean")
    } else {
        screen::warning(format!(
            "Working tree: {} changes (all are staged by commit)",
            rows.len()
        ))
    };
    let mut offset = 0usize;
    loop {
        // The title sits above the list.
        let visible = screen::body_rows().saturating_sub(1);
        offset = offset.min(rows.len().saturating_sub(visible));
        let mut body = vec![title.clone()];
        body.extend(rows.iter().skip(offset).take(visible).cloned());
        screen::draw(&body, TREE_HINT, None)?;

        let Some(key) = read_key()? else { continue };
        if is_interrupt(&key) {
            bail!(CANCELLED);
        }
        match key.code {
            KeyCode::Up | KeyCode::Char('w' | 'W') => offset = offset.saturating_sub(1),
            KeyCode::Down | KeyCode::Char('s' | 'S') => offset = offset.saturating_add(1),
            KeyCode::PageUp => offset = offset.saturating_sub(visible),
            KeyCode::PageDown => offset = offset.saturating_add(visible),
            KeyCode::Home => offset = 0,
            KeyCode::End => offset = usize::MAX,
            KeyCode::Esc | KeyCode::Char('q' | 'Q') => return Ok(()),
            _ => {}
        }
    }
}

/// Read-only history: recent commits and remote branches, one tab each. Load errors show as text.
pub fn history() -> Result<()> {
    let head = match git::current_branch() {
        Ok(name) if name == "HEAD" => "detached HEAD".to_string(),
        Ok(name) => match git::upstream(&name) {
            Ok(Some(upstream)) => format!("{name} -> {upstream}"),
            _ => format!("{name} (no upstream)"),
        },
        Err(error) => format!("Branch unknown: {error}"),
    };
    let commits: Vec<String> = match git::recent_commits(200) {
        Ok(list) if list.is_empty() => vec![screen::muted("No commits yet")],
        Ok(list) => list
            .iter()
            .map(|commit| {
                let refs = if commit.refs.is_empty() {
                    String::new()
                } else {
                    format!(" ({})", commit.refs)
                };
                format!("{}  {}{refs}  {}", commit.hash, commit.date, commit.subject)
            })
            .collect(),
        Err(error) => vec![screen::danger(format!("Could not read commits: {error}"))],
    };
    let branches: Vec<String> = match git::remote_branches() {
        Ok(list) if list.is_empty() => vec![screen::muted("No remote branches")],
        Ok(list) => list,
        Err(error) => vec![screen::danger(format!("Could not read branches: {error}"))],
    };
    let lists = [commits, branches];
    let mut tab = 0usize;
    let mut offset = 0usize;
    loop {
        // The branch line and the tab bar sit above the list.
        let visible = screen::body_rows().saturating_sub(2);
        let rows = &lists[tab];
        offset = offset.min(rows.len().saturating_sub(visible));
        let tabs: Vec<String> = ["Recent commits", "Remote branches"]
            .iter()
            .enumerate()
            .map(|(index, name)| {
                if index == tab {
                    screen::selected(format!("[{name}]"))
                } else {
                    screen::muted(name)
                }
            })
            .collect();
        let mut body = vec![screen::accent(&head), tabs.join("  ")];
        body.extend(rows.iter().skip(offset).take(visible).cloned());
        screen::draw(&body, HISTORY_HINT, None)?;

        let Some(key) = read_key()? else { continue };
        if is_interrupt(&key) {
            bail!(CANCELLED);
        }
        match key.code {
            KeyCode::Tab => {
                tab = 1 - tab;
                offset = 0;
            }
            KeyCode::Up | KeyCode::Char('w' | 'W') => offset = offset.saturating_sub(1),
            KeyCode::Down | KeyCode::Char('s' | 'S') => offset = offset.saturating_add(1),
            KeyCode::PageUp => offset = offset.saturating_sub(visible),
            KeyCode::PageDown => offset = offset.saturating_add(visible),
            KeyCode::Home => offset = 0,
            KeyCode::End => offset = usize::MAX,
            KeyCode::Esc | KeyCode::Char('q' | 'Q') => return Ok(()),
            _ => {}
        }
    }
}

pub fn read_line(prompt: &str, initial: &str, multiline: bool) -> Result<String> {
    text_input(prompt, initial, multiline, false)
}

/// Switches the terminal cursor to a blinking bar while editing text and restores it after.
struct BlinkingBar;

impl BlinkingBar {
    fn set() -> Self {
        let _ = crossterm::execute!(
            std::io::stdout(),
            crossterm::cursor::SetCursorStyle::BlinkingBar
        );
        Self
    }
}

impl Drop for BlinkingBar {
    fn drop(&mut self) {
        let _ = crossterm::execute!(
            std::io::stdout(),
            crossterm::cursor::SetCursorStyle::DefaultUserShape
        );
    }
}

fn line_start(chars: &[char], cursor: usize) -> usize {
    chars[..cursor].iter().rposition(|c| *c == '\n').map_or(0, |i| i + 1)
}

fn line_end(chars: &[char], cursor: usize) -> usize {
    chars[cursor..].iter().position(|c| *c == '\n').map_or(chars.len(), |i| cursor + i)
}

/// Moves one line up or down, keeping the column where the shorter line allows.
fn move_vertical(chars: &[char], cursor: usize, down: bool) -> usize {
    let start = line_start(chars, cursor);
    let column = cursor - start;
    if down {
        let end = line_end(chars, cursor);
        if end >= chars.len() {
            return cursor;
        }
        let next = end + 1;
        next + column.min(line_end(chars, next) - next)
    } else {
        if start == 0 {
            return cursor;
        }
        let prev_end = start - 1;
        let prev = line_start(chars, prev_end);
        prev + column.min(prev_end - prev)
    }
}

fn word_left(chars: &[char], cursor: usize) -> usize {
    let mut i = cursor;
    while i > 0 && chars[i - 1].is_whitespace() {
        i -= 1;
    }
    while i > 0 && !chars[i - 1].is_whitespace() {
        i -= 1;
    }
    i
}

fn word_right(chars: &[char], cursor: usize) -> usize {
    let mut i = cursor;
    while i < chars.len() && !chars[i].is_whitespace() {
        i += 1;
    }
    while i < chars.len() && chars[i].is_whitespace() {
        i += 1;
    }
    i
}

/// Text rows and the button's body row for the multiline editor. Body row 0 is the prompt, then
/// `visible` text rows, then an optional one-row notice, then the button (the last row when it fits).
fn editor_layout(body_rows: usize, has_notice: bool) -> (usize, usize) {
    let notice = usize::from(has_notice);
    let visible = body_rows.saturating_sub(2 + notice).max(1);
    (visible, 1 + visible + notice)
}

/// `read_line` that can also be saved empty when `optional` is set.
///
/// Notepad-style editing: arrows (Up/Down on several lines), Home/End per line, Ctrl+Home/End,
/// Ctrl+Left/Right by word, PgUp/PgDn, a blinking bar cursor. The multiline editor ends with a
/// clickable "Save & go back" button (Tab then Enter, or Ctrl+Enter, press it too).
fn text_input(prompt: &str, initial: &str, multiline: bool, optional: bool) -> Result<String> {
    let _cursor_style = BlinkingBar::set();
    let mut chars: Vec<char> = initial.chars().collect();
    let mut cursor = chars.len();
    let mut notice: Option<&str> = None;
    let mut on_button = false;
    let mut top = 0usize;
    let hint = if multiline { MESSAGE_HINT } else { LINE_HINT };
    loop {
        let text: String = chars.iter().collect();
        let line = chars[..cursor].iter().filter(|c| **c == '\n').count();
        let column = cursor - line_start(&chars, cursor);

        let (visible, button_row) = if multiline {
            editor_layout(screen::body_rows(), notice.is_some())
        } else {
            (
                screen::body_rows()
                    .saturating_sub(1 + if notice.is_some() { 2 } else { 0 })
                    .max(1),
                0,
            )
        };
        if line < top {
            top = line;
        } else if line >= top + visible {
            top = line + 1 - visible;
        }

        let mut body = vec![prompt.to_string()];
        body.extend(text.split('\n').skip(top).take(visible).map(str::to_owned));
        if multiline {
            body.resize(1 + visible, String::new());
            if let Some(message) = notice {
                body.push(screen::danger(message));
            }
            body.push(if on_button {
                screen::selected("Save & go back")
            } else {
                screen::tag("Save & go back")
            });
        } else if let Some(message) = notice {
            body.push(String::new());
            body.push(screen::danger(message));
        }
        let cursor_at = (!on_button).then_some(((1 + line - top) as u16, column as u16));
        screen::draw(&body, hint, cursor_at)?;

        let mut submit = false;
        let input = if multiline { read_input()? } else { read_key()?.map(Input::Key) };
        let key = match input {
            None => continue,
            Some(Input::Click(row)) => {
                if row == button_row {
                    submit = true;
                }
                None
            }
            Some(Input::Key(key)) => Some(key),
        };
        notice = None;
        let mut ctrl = false;
        if let Some(key) = key {
            if is_interrupt(&key) {
                bail!(CANCELLED);
            }
            let alt = key.modifiers.contains(KeyModifiers::ALT);
            // Windows reports AltGr as Ctrl+Alt, so a Ctrl+Alt character is plain typing.
            ctrl = key.modifiers.contains(KeyModifiers::CONTROL) && !alt;
            if multiline && on_button {
                // Enter presses the button; any other key returns focus to the text and acts there.
                on_button = false;
                if key.code == KeyCode::Enter {
                    submit = true;
                } else if key.code == KeyCode::Tab {
                    continue;
                }
            } else if multiline && key.code == KeyCode::Tab {
                on_button = true;
                continue;
            }
            if key.code == KeyCode::Enter && (ctrl || !multiline) {
                submit = true;
            }
        }
        if submit {
            let value = text.trim();
            if value.is_empty() && !optional {
                notice = Some(if multiline { "Message is required" } else { "Value is required" });
                continue;
            }
            return Ok(value.to_string());
        }
        let Some(key) = key else { continue };
        match key.code {
            KeyCode::Esc => return Ok(initial.into()),
            KeyCode::Enter => {
                chars.insert(cursor, '\n');
                cursor += 1;
            }
            KeyCode::Backspace => {
                let from = cursor.saturating_sub(1);
                chars.drain(from..cursor);
                cursor = from;
            }
            KeyCode::Delete if cursor < chars.len() => {
                chars.remove(cursor);
            }
            KeyCode::Left if ctrl => cursor = word_left(&chars, cursor),
            KeyCode::Right if ctrl => cursor = word_right(&chars, cursor),
            KeyCode::Left => cursor = cursor.saturating_sub(1),
            KeyCode::Right => cursor = (cursor + 1).min(chars.len()),
            KeyCode::Up if multiline => cursor = move_vertical(&chars, cursor, false),
            KeyCode::Down if multiline => cursor = move_vertical(&chars, cursor, true),
            KeyCode::PageUp if multiline => {
                for _ in 0..visible {
                    cursor = move_vertical(&chars, cursor, false);
                }
            }
            KeyCode::PageDown if multiline => {
                for _ in 0..visible {
                    cursor = move_vertical(&chars, cursor, true);
                }
            }
            KeyCode::Home if ctrl => cursor = 0,
            KeyCode::End if ctrl => cursor = chars.len(),
            KeyCode::Home => cursor = line_start(&chars, cursor),
            KeyCode::End => cursor = line_end(&chars, cursor),
            KeyCode::Char(ch) if !ctrl => {
                chars.insert(cursor, ch);
                cursor += 1;
            }
            _ => {}
        }
    }
}

pub fn masked(prompt: &str, initial: &str, date: bool) -> Result<String> {
    let template = if date { "YYYY-MM-DD" } else { "hh:mm:ss" };
    let fallback = if date {
        format!("{}-__-__", current_year())
    } else {
        "00:__:__".into()
    };
    let initial_is_valid = (date && valid_date(initial)) || (!date && valid_time(initial));
    let mut chars: Vec<char> = if initial_is_valid {
        initial.chars().collect()
    } else {
        fallback.chars().collect()
    };
    let slots: Vec<usize> = chars
        .iter()
        .enumerate()
        .filter_map(|(index, value)| {
            (*value == '_'
                || template.chars().nth(index).is_some_and(|token| {
                    token == 'Y'
                        || token == 'M'
                        || token == 'D'
                        || token == 'h'
                        || token == 'm'
                        || token == 's'
                }))
            .then_some(index)
        })
        .collect();
    let mut slot = 0usize;
    let mut notice: Option<&str> = None;
    loop {
        let rendered: String = chars
            .iter()
            .enumerate()
            .map(|(index, value)| {
                if slots[slot] == index {
                    format!("\x1b[7;36m{value}\x1b[0m")
                } else {
                    value.to_string()
                }
            })
            .collect();
        let column = prompt.chars().count() as u16 + 1 + slots[slot] as u16;
        let mut body = vec![format!("{prompt} {rendered}")];
        if let Some(message) = notice {
            body.push(String::new());
            body.push(screen::danger(message));
        }
        screen::draw(&body, MASK_HINT, Some((0, column)))?;

        let Some(key) = read_key()? else { continue };
        notice = None;
        if is_interrupt(&key) {
            bail!(CANCELLED);
        }
        let preset_key = match key.code {
            KeyCode::Char(ch)
                if !key.modifiers.contains(KeyModifiers::CONTROL)
                    && ((if date {
                        matches!(ch.to_ascii_lowercase(), 'n' | 'y')
                    } else {
                        matches!(ch.to_ascii_lowercase(), 'n' | 'r')
                    }) || (matches!(ch, '-' | '+') && !chars.contains(&'_'))) =>
            {
                Some(ch.to_ascii_lowercase())
            }
            _ => None,
        };
        if let Some(ch) = preset_key {
            let current: String = chars.iter().collect();
            let preset = if date {
                preset_date(ch, &current)
            } else {
                preset_time(ch, &current)
            };
            if let Some(filled) = preset {
                if filled.chars().count() == chars.len() {
                    chars = filled.chars().collect();
                }
            }
            continue;
        }
        match key.code {
            KeyCode::Char(ch) if ch.is_ascii_digit() => {
                chars[slots[slot]] = ch;
                if slot + 1 < slots.len() {
                    slot += 1;
                }
            }
            KeyCode::Left => slot = slot.saturating_sub(1),
            KeyCode::Right => slot = (slot + 1).min(slots.len() - 1),
            KeyCode::Home => slot = 0,
            KeyCode::End => slot = slots.len() - 1,
            KeyCode::Backspace => {
                chars[slots[slot]] = '_';
                slot = slot.saturating_sub(1);
            }
            KeyCode::Delete => chars[slots[slot]] = '_',
            KeyCode::Esc => return Ok(initial.into()),
            KeyCode::Enter => {
                let result: String = chars.iter().collect();
                if result.contains('_') {
                    notice = Some("Complete all fields before continuing");
                } else if (date && !valid_date(&result)) || (!date && !valid_time(&result)) {
                    notice = Some(if date {
                        "Not a valid calendar date"
                    } else {
                        "Time out of range (00:00:00 - 23:59:59)"
                    });
                } else {
                    return Ok(result);
                }
            }
            _ => {}
        }
    }
}

pub fn external_editor(initial: &str) -> Result<String> {
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |elapsed| elapsed.as_nanos());
    let path = std::env::temp_dir().join(format!("git-cc-{}-{nanos}.txt", std::process::id()));
    {
        use std::io::Write;
        let mut file = fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&path)
            .context("could not create temp file for the editor")?;
        file.write_all(initial.as_bytes())?;
    }
    let editor = std::env::var("VISUAL")
        .or_else(|_| std::env::var("EDITOR"))
        .unwrap_or_else(|_| {
            if cfg!(windows) {
                "notepad".into()
            } else {
                "vi".into()
            }
        });
    let mut parts = split_command(&editor).into_iter();
    let Some(program) = parts.next() else {
        let _ = fs::remove_file(&path);
        bail!("editor command is empty");
    };
    // The editor needs the normal terminal, so leave the TUI while it runs.
    screen::suspend();
    let status = Command::new(program)
        .args(parts)
        .arg(&path)
        .stdin(Stdio::inherit())
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .status();
    let resumed = screen::resume();
    let result = match status {
        Ok(status) if status.success() => {
            fs::read_to_string(&path).context("could not read editor output")
        }
        Ok(status) => Err(anyhow!("editor exited with status {status}")),
        Err(error) => Err(error.into()),
    };
    let _ = fs::remove_file(&path);
    resumed?;
    let message = result?;
    if message.trim().is_empty() {
        bail!("Commit message is required");
    }
    Ok(message.trim().into())
}

/// Splits an editor command on whitespace, keeping "double" or 'single' quoted parts together (quotes removed).
/// Backslashes are literal so Windows paths survive.
fn split_command(command: &str) -> Vec<String> {
    let mut parts = Vec::new();
    let mut current = String::new();
    let mut started = false;
    let mut quote: Option<char> = None;
    for ch in command.chars() {
        match quote {
            Some(open) if ch == open => quote = None,
            Some(_) => current.push(ch),
            None if !started && (ch == '"' || ch == '\'') => {
                quote = Some(ch);
                started = true;
            }
            None if ch.is_whitespace() => {
                if started {
                    parts.push(std::mem::take(&mut current));
                    started = false;
                }
            }
            None => {
                current.push(ch);
                started = true;
            }
        }
    }
    if started {
        parts.push(current);
    }
    parts
}

pub fn options(values: &mut Values) -> Result<()> {
    values.amend = confirm(
        &[],
        "Amend the last commit instead of creating a new one?",
        false,
    )?;
    values.dry_run = confirm(&[], "Preview only (dry run, do not commit/push)?", false)?;
    Ok(())
}

/// Shows `context` above the question. Ctrl+C cancels with `CANCELLED`.
pub fn confirm(context: &[String], prompt: &str, default: bool) -> Result<bool> {
    let mut body = context.to_vec();
    if !body.is_empty() {
        body.push(String::new());
    }
    body.push(format!(
        "{prompt} ({})",
        if default { "Y/n" } else { "y/N" }
    ));
    loop {
        screen::draw(&body, CONFIRM_HINT, None)?;
        let Some(key) = read_key()? else { continue };
        if is_interrupt(&key) {
            bail!(CANCELLED);
        }
        match key.code {
            KeyCode::Enter => return Ok(default),
            KeyCode::Char('y' | 'Y') => return Ok(true),
            KeyCode::Char('n' | 'N') => return Ok(false),
            _ => {}
        }
    }
}

#[derive(Debug, PartialEq)]
pub enum Pick {
    Account(String),
    GitDefault,
}

/// Account chooser: "git default" first, then one row per account. Esc/Q gives None.
pub fn pick_account(accounts: &[Account], active: Option<&str>) -> Result<Option<Pick>> {
    accounts::invalidate_logins();
    let mut index = 0usize;
    let logins = accounts::stored_logins();
    loop {
        let mut body = vec![screen::accent("SELECT ACCOUNT"), String::new()];
        body.extend(account_rows(accounts, active, &logins, index));
        if accounts.is_empty() {
            body.push(String::new());
            body.push(screen::muted(
                "No accounts yet. Use gct --account to add one.",
            ));
        }
        screen::draw(&body, PICK_HINT, None)?;

        let Some(key) = read_key()? else { continue };
        if is_interrupt(&key) {
            bail!(CANCELLED);
        }
        let count = accounts.len() + 1;
        match key.code {
            KeyCode::Up | KeyCode::Char('w' | 'W') => index = (index + count - 1) % count,
            KeyCode::Down | KeyCode::Char('s' | 'S') => index = (index + 1) % count,
            KeyCode::Enter | KeyCode::Char(' ') => {
                return Ok(Some(if index == 0 {
                    Pick::GitDefault
                } else {
                    Pick::Account(accounts[index - 1].label.clone())
                }))
            }
            KeyCode::Esc | KeyCode::Char('q' | 'Q') => return Ok(None),
            _ => {}
        }
    }
}

/// Account manager: set active, add, edit, refresh, sign in, delete. Failures show in the body instead of exiting.
pub fn accounts_screen(config: &mut Config) -> Result<()> {
    let mut index = 0usize;
    let mut notice: Option<String> = None;
    let mut logins = accounts::stored_logins();
    let mut identity = gitconfig::read();
    loop {
        // Deleting the last account can leave the index past the end.
        index = index.min(config.accounts.len());
        let mut body = vec![
            screen::accent("ACCOUNTS"),
            format!("Active in git: {}", identity_text(&identity)),
            screen::muted("Press A to add a GitHub account; a browser window opens to sign in."),
            String::new(),
        ];
        if let Some(message) = &notice {
            body.push(screen::danger(message));
            body.push(String::new());
        }
        body.extend(account_rows(
            &config.accounts,
            config.active_account.as_deref(),
            &logins,
            index,
        ));
        if config.accounts.is_empty() {
            body.push(String::new());
            body.push(screen::muted(
                "No accounts yet. Press A, give it a label, and sign in with GitHub.",
            ));
        }
        screen::draw(&body, ACCOUNTS_HINT, None)?;

        let Some(key) = read_key()? else { continue };
        notice = None;
        if is_interrupt(&key) {
            bail!(CANCELLED);
        }
        let count = config.accounts.len() + 1;
        match key.code {
            KeyCode::Up | KeyCode::Char('w' | 'W') => index = (index + count - 1) % count,
            KeyCode::Down | KeyCode::Char('s' | 'S') => index = (index + 1) % count,
            KeyCode::Enter | KeyCode::Char(' ') => {
                let result = if index == 0 {
                    accounts::deactivate(config)
                } else {
                    let label = config.accounts[index - 1].label.clone();
                    accounts::activate(config, &label)
                };
                if let Err(error) = result {
                    notice = Some(error.to_string());
                }
            }
            KeyCode::Char('a' | 'A') => {
                notice = Some(match add_form(&config.accounts)? {
                    Some(label) => {
                        let mut username = String::new();
                        if ask("GitHub username:", &mut username)? {
                            match suspended(|| accounts::sign_in_new(&label, &username))? {
                                Ok(account) => {
                                    let message = format!(
                                        "Added {label}, signed in to GitHub as @{}",
                                        account.github_username
                                    );
                                    config.accounts.push(account);
                                    index = config.accounts.len();
                                    message
                                }
                                Err(error) => error.to_string(),
                            }
                        } else {
                            "Cancelled, no account saved".into()
                        }
                    }
                    None => "Cancelled, no account saved".into(),
                });
                invalidate_logins();
                logins = accounts::stored_logins();
            }
            KeyCode::Char('l' | 'L') if index > 0 => {
                notice = Some(
                    update_account(config, index - 1, true)
                        .unwrap_or_else(|error| error.to_string()),
                );
                invalidate_logins();
                logins = accounts::stored_logins();
            }
            KeyCode::Char('r' | 'R') if index > 0 => {
                notice = Some(
                    update_account(config, index - 1, false)
                        .unwrap_or_else(|error| error.to_string()),
                );
                invalidate_logins();
                logins = accounts::stored_logins();
            }
            KeyCode::Char('e' | 'E') if index > 0 => {
                notice = Some(match edit_form(&config.accounts, index - 1)? {
                    Some(edited) => {
                        let label = edited.label.clone();
                        let old = config.accounts[index - 1].clone();
                        let old_active = config.active_account.clone();
                        match replace_account(config, index - 1, edited) {
                            Ok(()) => format!("Saved {label}"),
                            Err(error) => {
                                // Activation failed, so the edit must not stay saved.
                                config.accounts[index - 1] = old;
                                config.active_account = old_active;
                                error.to_string()
                            }
                        }
                    }
                    None => "Cancelled, account unchanged".into(),
                });
            }
            KeyCode::Char('d' | 'D') if index > 0 => {
                let label = config.accounts[index - 1].label.clone();
                let prompt = format!(
                    "Delete account '{label}'? Its GitHub sign-in stays saved in Git Credential Manager."
                );
                if confirm(&[], &prompt, false)? {
                    let was_active = config.active_account.as_deref() == Some(label.as_str());
                    let deactivated = if was_active {
                        accounts::deactivate(config)
                    } else {
                        Ok(())
                    };
                    match deactivated {
                        Ok(()) => {
                            config.accounts.remove(index - 1);
                        }
                        Err(error) => notice = Some(error.to_string()),
                    }
                }
            }
            KeyCode::Esc | KeyCode::Char('q' | 'Q') => return Ok(()),
            _ => {}
        }
        // Only these actions can change git's identity, so re-read it just here.
        if matches!(
            key.code,
            KeyCode::Enter
                | KeyCode::Char(' ' | 'a' | 'A' | 'l' | 'L' | 'r' | 'R' | 'e' | 'E' | 'd' | 'D')
        ) {
            identity = gitconfig::read();
        }
    }
}

/// Runs `work` with the TUI suspended, so the browser or Credential Manager can use the terminal.
/// The outer error is a failed resume; the inner one is `work`'s own result.
fn suspended<T>(work: impl FnOnce() -> Result<T>) -> Result<Result<T>> {
    screen::suspend();
    let result = work();
    screen::resume()?;
    Ok(result)
}

/// Re-fetches name and email from GitHub for the account at `position`, signing in first when asked.
fn update_account(config: &mut Config, position: usize, sign_in: bool) -> Result<String> {
    let account = config.accounts[position].clone();
    let username = account.github_username.clone();
    let fresh = suspended(|| {
        if sign_in {
            accounts::login(&username)?;
        }
        let mut fresh = account;
        accounts::refresh(&mut fresh)?;
        Ok(fresh)
    })??;
    let label = fresh.label.clone();
    replace_account(config, position, fresh)?;
    Ok(if sign_in {
        format!("Signed in to GitHub as @{username}, {label} updated")
    } else {
        format!("Refreshed {label} from GitHub")
    })
}

/// Stores `account` at `position`. When it is the active one, git is re-pointed at the new values.
fn replace_account(config: &mut Config, position: usize, account: Account) -> Result<()> {
    let was_active =
        config.active_account.as_deref() == Some(config.accounts[position].label.as_str());
    let label = account.label.clone();
    let old_label = config.accounts[position].label.clone();
    let old = std::mem::replace(&mut config.accounts[position], account);
    if was_active {
        config.active_account = Some(label.clone());
        if let Err(error) = accounts::activate(config, &label) {
            // The switch failed, so keep the old values rather than the unapplied new ones.
            config.accounts[position] = old;
            config.active_account = Some(old_label);
            return Err(error);
        }
    }
    Ok(())
}

/// "Name <email>", the email alone without a name, or "not set" when git has neither.
fn identity_text(identity: &gitconfig::Identity) -> String {
    match (identity.name.as_deref(), identity.email.as_deref()) {
        (Some(name), Some(email)) => format!("{name} <{email}>"),
        (Some(name), None) => name.into(),
        (None, Some(email)) => email.into(),
        (None, None) => "not set".into(),
    }
}

/// "git default" row then the accounts, with the active one marked and its sign-in state shown.
fn account_rows(
    accounts: &[Account],
    active: Option<&str>,
    logins: &[String],
    index: usize,
) -> Vec<String> {
    let mut rows = vec![styled_menu_line(
        index == 0,
        &marked("git default", active.is_none()),
    )];
    for (position, account) in accounts.iter().enumerate() {
        let is_active = active == Some(account.label.as_str());
        let signed_in = logins
            .iter()
            .any(|login| login.eq_ignore_ascii_case(&account.github_username));
        rows.push(styled_menu_line(
            index == position + 1,
            &account_line(account, is_active, signed_in),
        ));
    }
    rows
}

/// One account: label, display name (the email when no name is saved), email, @username, sign-in state.
fn account_line(account: &Account, active: bool, signed_in: bool) -> String {
    let mut parts = vec![format!("{:<10}", account.label)];
    if account.name.trim().is_empty() {
        parts.push(account.email.clone());
    } else {
        parts.push(account.name.clone());
        parts.push(format!("<{}>", account.email));
    }
    parts.push(format!("@{}", account.github_username));
    parts.push(
        if signed_in {
            "[signed in]"
        } else {
            "[not signed in]"
        }
        .into(),
    );
    if active {
        parts.push("(active)".into());
    }
    parts.join("  ")
}

fn marked(text: &str, active: bool) -> String {
    if active {
        format!("{text}  (active)")
    } else {
        text.into()
    }
}

/// Asks one value. Returns false when it came back empty, which only happens when Esc is pressed on an empty prompt.
fn ask(prompt: &str, value: &mut String) -> Result<bool> {
    let answer = read_line(prompt, value.as_str(), false)?;
    let filled = !answer.is_empty();
    *value = answer;
    Ok(filled)
}

/// Label for a new account, pre-filled with the next free "account N". None on cancel.
fn add_form(accounts: &[Account]) -> Result<Option<String>> {
    let mut label = (1..)
        .map(|number| format!("account {number}"))
        .find(|label| !accounts.iter().any(|account| account.label == *label))
        .unwrap_or_default();
    loop {
        if !ask("Label (short name, e.g. work):", &mut label)? {
            return Ok(None);
        }
        if accounts.iter().any(|account| account.label == label) {
            wait_key(
                &[screen::danger(format!("label {label} is already used"))],
                "Press any key to fix the label",
            )?;
            continue;
        }
        return Ok(Some(label));
    }
}

/// Label and display name for the account at `position`. Name and email come from GitHub, so only these two change.
fn edit_form(accounts: &[Account], position: usize) -> Result<Option<Account>> {
    let mut candidate = accounts[position].clone();
    loop {
        if !ask("Label (short name, e.g. work):", &mut candidate.label)? {
            return Ok(None);
        }
        candidate.name = text_input(
            "Display name (blank shows the email):",
            &candidate.name,
            false,
            true,
        )?;
        let others: Vec<Account> = accounts
            .iter()
            .enumerate()
            .filter(|(other, _)| *other != position)
            .map(|(_, account)| account.clone())
            .collect();
        match accounts::problem(&candidate, &others) {
            None => return Ok(Some(candidate)),
            Some(message) => wait_key(
                &[screen::danger(message)],
                "Press any key to fix the values",
            )?,
        }
    }
}


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

    #[test]
    fn splits_plain_command() {
        assert_eq!(split_command("code --wait"), ["code", "--wait"]);
    }

    #[test]
    fn keeps_quoted_path_with_spaces_and_args() {
        assert_eq!(
            split_command(r#""C:\Program Files\Vim\vim.exe" -f --nofork"#),
            [r"C:\Program Files\Vim\vim.exe", "-f", "--nofork"]
        );
    }

    #[test]
    fn apostrophe_inside_token_is_literal() {
        assert_eq!(
            split_command(r"C:\Users\O'Brien\vim.exe -f"),
            [r"C:\Users\O'Brien\vim.exe", "-f"]
        );
    }
}

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

    fn c(text: &str) -> Vec<char> {
        text.chars().collect()
    }

    #[test]
    fn vertical_moves_keep_column() {
        let t = c("abcd\nef\nghij");
        assert_eq!(move_vertical(&t, 3, true), 7); // column 3 clamps to the end of "ef"
        assert_eq!(move_vertical(&t, 7, true), 10); // column 2 on "ghij"
        assert_eq!(move_vertical(&t, 10, false), 7);
        assert_eq!(move_vertical(&t, 2, false), 2); // already on the first line
        assert_eq!(move_vertical(&t, 12, true), 12); // already on the last line
    }

    #[test]
    fn home_end_are_per_line() {
        let t = c("ab\ncde");
        assert_eq!((line_start(&t, 5), line_end(&t, 3)), (3, 6));
        assert_eq!((line_start(&t, 1), line_end(&t, 1)), (0, 2));
    }

    #[test]
    fn editor_layout_puts_button_last() {
        assert_eq!(editor_layout(10, false), (8, 9));
        assert_eq!(editor_layout(10, true), (7, 9));
        assert_eq!(editor_layout(2, true), (1, 3)); // tiny: button follows the content
    }

    #[test]
    fn word_jumps() {
        let t = c("one  two three");
        assert_eq!(word_right(&t, 0), 5);
        assert_eq!(word_right(&t, 5), 9);
        assert_eq!(word_left(&t, 14), 9);
        assert_eq!(word_left(&t, 9), 5);
        assert_eq!(word_left(&t, 0), 0);
    }
}