ztmux 3.7.20

A Rust port of tmux — the full terminal multiplexer, server and client
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
// Copyright (c) 2007 Nicholas Marriott <nichu8gmail.com>
//
// Permission to use, copy, modify, and distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
// IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
// OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
use crate::*;
use crate::options_::options_get_number_;

// Entry in the key tree.
pub struct input_key_entry {
    pub key: key_code,
    pub data: *const u8,

    pub entry: rb_entry<input_key_entry>,
}
pub type input_key_tree = rb_head<input_key_entry>;

impl input_key_entry {
    const fn new(key: key_code, data: &'static CStr) -> Self {
        Self {
            key,
            data: data.as_ptr().cast(),
            entry: unsafe { zeroed() },
        }
    }
}

/// Input key comparison function.
/// C `vendor/tmux/input-keys.c:331`: `static int input_key_cmp(struct input_key_entry *ike1, struct input_key_entry *ike2)`
pub fn input_key_cmp(ike1: &input_key_entry, ike2: &input_key_entry) -> cmp::Ordering {
    ike1.key.cmp(&ike2.key)
}

RB_GENERATE!(
    input_key_tree,
    input_key_entry,
    entry,
    discr_entry,
    input_key_cmp
);
static mut INPUT_KEY_TREE: input_key_tree = rb_initializer();

const INPUT_KEY_DEFAULTS_LEN: usize = 85;

static mut INPUT_KEY_DEFAULTS: [input_key_entry; 85] = [
    // Paste keys.
    input_key_entry::new(keyc::KEYC_PASTE_START as u64, c"\x1b[200~"),
    input_key_entry::new(keyc::KEYC_PASTE_START as u64 | KEYC_IMPLIED_META, c"\x1b[200~"),
    input_key_entry::new(keyc::KEYC_PASTE_END as u64, c"\x1b[201~"),
    input_key_entry::new(keyc::KEYC_PASTE_END as u64 | KEYC_IMPLIED_META, c"\x1b[201~"),
    // Function keys.
    input_key_entry::new(keyc::KEYC_F1 as u64, c"\x1bOP"),
    input_key_entry::new(keyc::KEYC_F2 as u64, c"\x1bOQ"),
    input_key_entry::new(keyc::KEYC_F3 as u64, c"\x1bOR"),
    input_key_entry::new(keyc::KEYC_F4 as u64, c"\x1bOS"),
    input_key_entry::new(keyc::KEYC_F5 as u64, c"\x1b[15~"),
    input_key_entry::new(keyc::KEYC_F6 as u64, c"\x1b[17~"),
    input_key_entry::new(keyc::KEYC_F7 as u64, c"\x1b[18~"),
    input_key_entry::new(keyc::KEYC_F8 as u64, c"\x1b[19~"),
    input_key_entry::new(keyc::KEYC_F9 as u64, c"\x1b[20~"),
    input_key_entry::new(keyc::KEYC_F10 as u64, c"\x1b[21~"),
    input_key_entry::new(keyc::KEYC_F11 as u64, c"\x1b[23~"),
    input_key_entry::new(keyc::KEYC_F12 as u64, c"\x1b[24~"),
    input_key_entry::new(keyc::KEYC_IC as u64, c"\x1b[2~"),
    input_key_entry::new(keyc::KEYC_DC as u64, c"\x1b[3~"),
    input_key_entry::new(keyc::KEYC_HOME as u64, c"\x1b[1~"),
    input_key_entry::new(keyc::KEYC_END as u64, c"\x1b[4~"),
    input_key_entry::new(keyc::KEYC_NPAGE as u64, c"\x1b[6~"),
    input_key_entry::new(keyc::KEYC_PPAGE as u64, c"\x1b[5~"),
    input_key_entry::new(keyc::KEYC_BTAB as u64, c"\x1b[Z"),
    // Arrow keys.
    input_key_entry::new(keyc::KEYC_UP as u64 | KEYC_CURSOR, c"\x1bOA"),
    input_key_entry::new(keyc::KEYC_DOWN as u64 | KEYC_CURSOR, c"\x1bOB"),
    input_key_entry::new(keyc::KEYC_RIGHT as u64 | KEYC_CURSOR, c"\x1bOC"),
    input_key_entry::new(keyc::KEYC_LEFT as u64 | KEYC_CURSOR, c"\x1bOD"),
    input_key_entry::new(keyc::KEYC_UP as u64, c"\x1b[A"),
    input_key_entry::new(keyc::KEYC_DOWN as u64, c"\x1b[B"),
    input_key_entry::new(keyc::KEYC_RIGHT as u64, c"\x1b[C"),
    input_key_entry::new(keyc::KEYC_LEFT as u64, c"\x1b[D"),
    // Keypad keys.
    input_key_entry::new(keyc::KEYC_KP_SLASH as u64 | KEYC_KEYPAD, c"\x1bOo"),
    input_key_entry::new(keyc::KEYC_KP_STAR as u64 | KEYC_KEYPAD, c"\x1bOj"),
    input_key_entry::new(keyc::KEYC_KP_MINUS as u64 | KEYC_KEYPAD, c"\x1bOm"),
    input_key_entry::new(keyc::KEYC_KP_SEVEN as u64 | KEYC_KEYPAD, c"\x1bOw"),
    input_key_entry::new(keyc::KEYC_KP_EIGHT as u64 | KEYC_KEYPAD, c"\x1bOx"),
    input_key_entry::new(keyc::KEYC_KP_NINE as u64 | KEYC_KEYPAD, c"\x1bOy"),
    input_key_entry::new(keyc::KEYC_KP_PLUS as u64 | KEYC_KEYPAD, c"\x1bOk"),
    input_key_entry::new(keyc::KEYC_KP_FOUR as u64 | KEYC_KEYPAD, c"\x1bOt"),
    input_key_entry::new(keyc::KEYC_KP_FIVE as u64 | KEYC_KEYPAD, c"\x1bOu"),
    input_key_entry::new(keyc::KEYC_KP_SIX as u64 | KEYC_KEYPAD, c"\x1bOv"),
    input_key_entry::new(keyc::KEYC_KP_ONE as u64 | KEYC_KEYPAD, c"\x1bOq"),
    input_key_entry::new(keyc::KEYC_KP_TWO as u64 | KEYC_KEYPAD, c"\x1bOr"),
    input_key_entry::new(keyc::KEYC_KP_THREE as u64 | KEYC_KEYPAD, c"\x1bOs"),
    input_key_entry::new(keyc::KEYC_KP_ENTER as u64 | KEYC_KEYPAD, c"\x1bOM"),
    input_key_entry::new(keyc::KEYC_KP_ZERO as u64 | KEYC_KEYPAD, c"\x1bOp"),
    input_key_entry::new(keyc::KEYC_KP_PERIOD as u64 | KEYC_KEYPAD, c"\x1bOn"),
    input_key_entry::new(keyc::KEYC_KP_SLASH as u64, c"/"),
    input_key_entry::new(keyc::KEYC_KP_STAR as u64, c"*"),
    input_key_entry::new(keyc::KEYC_KP_MINUS as u64, c"-"),
    input_key_entry::new(keyc::KEYC_KP_SEVEN as u64, c"7"),
    input_key_entry::new(keyc::KEYC_KP_EIGHT as u64, c"8"),
    input_key_entry::new(keyc::KEYC_KP_NINE as u64, c"9"),
    input_key_entry::new(keyc::KEYC_KP_PLUS as u64, c"+"),
    input_key_entry::new(keyc::KEYC_KP_FOUR as u64, c"4"),
    input_key_entry::new(keyc::KEYC_KP_FIVE as u64, c"5"),
    input_key_entry::new(keyc::KEYC_KP_SIX as u64, c"6"),
    input_key_entry::new(keyc::KEYC_KP_ONE as u64, c"1"),
    input_key_entry::new(keyc::KEYC_KP_TWO as u64, c"2"),
    input_key_entry::new(keyc::KEYC_KP_THREE as u64, c"3"),
    input_key_entry::new(keyc::KEYC_KP_ENTER as u64, c"\n"),
    input_key_entry::new(keyc::KEYC_KP_ZERO as u64, c"0"),
    input_key_entry::new(keyc::KEYC_KP_PERIOD as u64, c"."),
    // Keys with an embedded modifier.
    input_key_entry::new(keyc::KEYC_F1 as u64 | KEYC_BUILD_MODIFIERS, c"\x1b[1;_P"),
    input_key_entry::new(keyc::KEYC_F2 as u64 | KEYC_BUILD_MODIFIERS, c"\x1b[1;_Q"),
    input_key_entry::new(keyc::KEYC_F3 as u64 | KEYC_BUILD_MODIFIERS, c"\x1b[1;_R"),
    input_key_entry::new(keyc::KEYC_F4 as u64 | KEYC_BUILD_MODIFIERS, c"\x1b[1;_S"),
    input_key_entry::new(keyc::KEYC_F5 as u64 | KEYC_BUILD_MODIFIERS, c"\x1b[15;_~"),
    input_key_entry::new(keyc::KEYC_F6 as u64 | KEYC_BUILD_MODIFIERS, c"\x1b[17;_~"),
    input_key_entry::new(keyc::KEYC_F7 as u64 | KEYC_BUILD_MODIFIERS, c"\x1b[18;_~"),
    input_key_entry::new(keyc::KEYC_F8 as u64 | KEYC_BUILD_MODIFIERS, c"\x1b[19;_~"),
    input_key_entry::new(keyc::KEYC_F9 as u64 | KEYC_BUILD_MODIFIERS, c"\x1b[20;_~"),
    input_key_entry::new(keyc::KEYC_F10 as u64 | KEYC_BUILD_MODIFIERS, c"\x1b[21;_~"),
    input_key_entry::new(keyc::KEYC_F11 as u64 | KEYC_BUILD_MODIFIERS, c"\x1b[23;_~"),
    input_key_entry::new(keyc::KEYC_F12 as u64 | KEYC_BUILD_MODIFIERS, c"\x1b[24;_~"),
    input_key_entry::new(keyc::KEYC_UP as u64 | KEYC_BUILD_MODIFIERS, c"\x1b[1;_A"),
    input_key_entry::new(keyc::KEYC_DOWN as u64 | KEYC_BUILD_MODIFIERS, c"\x1b[1;_B"),
    input_key_entry::new(keyc::KEYC_RIGHT as u64 | KEYC_BUILD_MODIFIERS, c"\x1b[1;_C"),
    input_key_entry::new(keyc::KEYC_LEFT as u64 | KEYC_BUILD_MODIFIERS, c"\x1b[1;_D"),
    input_key_entry::new(keyc::KEYC_HOME as u64 | KEYC_BUILD_MODIFIERS, c"\x1b[1;_H"),
    input_key_entry::new(keyc::KEYC_END as u64 | KEYC_BUILD_MODIFIERS, c"\x1b[1;_F"),
    input_key_entry::new(keyc::KEYC_PPAGE as u64 | KEYC_BUILD_MODIFIERS, c"\x1b[5;_~"),
    input_key_entry::new(keyc::KEYC_NPAGE as u64 | KEYC_BUILD_MODIFIERS, c"\x1b[6;_~"),
    input_key_entry::new(keyc::KEYC_IC as u64 | KEYC_BUILD_MODIFIERS, c"\x1b[2;_~"),
    input_key_entry::new(keyc::KEYC_DC as u64 | KEYC_BUILD_MODIFIERS, c"\x1b[3;_~"),
];

static INPUT_KEY_MODIFIERS: [key_code; 9] = [
    0,
    0,
    KEYC_SHIFT,
    KEYC_META | KEYC_IMPLIED_META,
    KEYC_SHIFT | KEYC_META | KEYC_IMPLIED_META,
    KEYC_CTRL,
    KEYC_SHIFT | KEYC_CTRL,
    KEYC_META | KEYC_IMPLIED_META | KEYC_CTRL,
    KEYC_SHIFT | KEYC_META | KEYC_IMPLIED_META | KEYC_CTRL,
];

/// Look for key in tree.
/// C `vendor/tmux/input-keys.c:342`: `static struct input_key_entry *input_key_get(key_code key)`
pub unsafe fn input_key_get(key: key_code) -> *mut input_key_entry {
    unsafe {
        let mut entry = MaybeUninit::<input_key_entry>::uninit();
        (*entry.as_mut_ptr()).key = key;
        rb_find(&raw mut INPUT_KEY_TREE, entry.as_mut_ptr())
    }
}

/// C `vendor/tmux/input-keys.c:351`: `static size_t input_key_split2(u_int c, u_char *dst)`
pub unsafe fn input_key_split2(c: u32, dst: *mut u8) -> usize {
    unsafe {
        if c > 0x7f {
            *dst = (c >> 6) as u8 | 0xc0;
            *dst.add(1) = (c as u8 & 0x3f) | 0x80;

            2
        } else {
            *dst = c as u8;

            1
        }
    }
}

#[expect(clippy::needless_range_loop)]
/// Build input key tree.
/// C `vendor/tmux/input-keys.c:364`: `void input_key_build(void)`
pub unsafe extern "C-unwind" fn input_key_build() {
    unsafe {
        for i in 0..INPUT_KEY_DEFAULTS_LEN {
            let ike = &raw mut INPUT_KEY_DEFAULTS[i];
            if !(*ike).key & KEYC_BUILD_MODIFIERS != 0 {
                rb_insert(&raw mut INPUT_KEY_TREE, ike);
                continue;
            }

            for (j, input_key_modifiers_j) in
                INPUT_KEY_MODIFIERS.iter().copied().enumerate().skip(2)
            {
                let key = (*ike).key & !KEYC_BUILD_MODIFIERS;
                let data = xstrdup((*ike).data).as_ptr();
                *data.add(libc::strcspn(data, c!("_"))) = b'0' + j as u8;

                let new = xcalloc1::<input_key_entry>();
                new.key = key | input_key_modifiers_j;
                new.data = data;
                rb_insert(&raw mut INPUT_KEY_TREE, new);
            }
        }

        for ike in rb_foreach(&raw mut INPUT_KEY_TREE).map(NonNull::as_ptr) {
            log_debug!(
                "{}:{} : 0x{:x} ({}) is {}",
                file!(),
                line!(),
                (*ike).key,
                _s(key_string_lookup_key((*ike).key, 1)),
                _s((*ike).data)
            );
        }
    }
}

/// Translate a key code into an output key sequence for a pane.
/// C `vendor/tmux/input-keys.c:398`: `int input_key_pane(struct window_pane *wp, key_code key, struct mouse_event *m)`
pub unsafe fn input_key_pane(wp: *mut window_pane, key: key_code, m: *mut mouse_event) -> i32 {
    unsafe {
        if log_get_level() != 0 {
            log_debug!(
                "writing key 0x{:x} ({}) to %{}",
                key,
                _s(key_string_lookup_key(key, 1)),
                (*wp).id
            );
        }

        if KEYC_IS_MOUSE(key) {
            if !m.is_null() && (*m).wp != -1 && (*m).wp as u32 == (*wp).id {
                input_key_mouse(wp, m);
            }
            return 0;
        }
        input_key((*wp).screen, (*wp).event, key)
    }
}

/// C `vendor/tmux/input-keys.c:414`: `static void input_key_write(const char *from, struct bufferevent *bev, const char *data, size_t size)`
pub unsafe fn input_key_write(
    from: *const u8,
    bev: *mut bufferevent,
    data: *const u8,
    size: usize,
) {
    unsafe {
        log_debug!("input_key_write {0}: {2:1$}", _s(from), size, _s(data));
        bufferevent_write(bev, data.cast(), size);
    }
}

/// C `vendor/tmux/input-keys.c:426`: `static int input_key_extended(struct bufferevent *bev, key_code key)`
pub unsafe fn input_key_extended(bev: *mut bufferevent, mut key: key_code) -> i32 {
    let __func__ = c!("input_key_extended");
    unsafe {
        let sizeof_tmp = 64;
        let mut tmp = MaybeUninit::<[u8; 64]>::uninit();
        let mut wc: wchar_t = 0;

        const KEYC_SHIFT_OR_META: u64 = KEYC_SHIFT | KEYC_META;
        const KEYC_SHIFT_OR_CTRL: u64 = KEYC_SHIFT | KEYC_CTRL;
        const KEYC_META_OR_CTRL: u64 = KEYC_META | KEYC_CTRL;
        const KEYC_SHIFT_OR_META_OR_CTRL: u64 = KEYC_SHIFT | KEYC_META | KEYC_CTRL;

        let modifier = match key & KEYC_MASK_MODIFIERS {
            KEYC_SHIFT => b'2',
            KEYC_META => b'3',
            KEYC_SHIFT_OR_META => b'4',
            KEYC_CTRL => b'5',
            KEYC_SHIFT_OR_CTRL => b'6',
            KEYC_META_OR_CTRL => b'7',
            KEYC_SHIFT_OR_META_OR_CTRL => b'8',
            _ => return -1,
        };

        if KEYC_IS_UNICODE(key) {
            let ud = utf8_to_data((key & KEYC_MASK_KEY) as u32);
            if utf8_towc(&ud, &raw mut wc) == utf8_state::UTF8_DONE {
                key = wc as u64;
            } else {
                return -1;
            }
        } else {
            key &= KEYC_MASK_KEY;
        }

        if options_get_number_(GLOBAL_OPTIONS, "extended-keys-format") == 1 {
            _ = xsnprintf_!(
                tmp.as_mut_ptr().cast(),
                sizeof_tmp,
                "\x1b[27;{};{}~",
                modifier as char,
                key,
            );
        } else {
            _ = xsnprintf_!(
                tmp.as_mut_ptr().cast(),
                sizeof_tmp,
                "\x1b[{};{}u",
                key,
                modifier as char,
            );
        }

        input_key_write(
            __func__,
            bev,
            tmp.as_ptr().cast(),
            strlen(tmp.as_ptr().cast()),
        );
        0
    }
}

#[expect(
    clippy::manual_c_str_literals,
    reason = "false positive if c string contains NUL"
)]
static STANDARD_MAP: [SyncCharPtr; 2] = [
    SyncCharPtr::from_ptr(c!("1!9(0)=+;:'\",<.>/-8? 2")),
    SyncCharPtr::from_ptr(b"119900=+;;'',,..\x1f\x1f\x7f\x7f\0\0\0".as_ptr().cast()),
];

/// Outputs the key in the "standard" mode. This is by far the most
/// complicated output mode, with a lot of remapping in order to
/// emulate quirks of terminals that today can be only found in museums.
/// C `vendor/tmux/input-keys.c:482`: `static int input_key_vt10x(struct bufferevent *bev, key_code key)`
pub unsafe fn input_key_vt10x(bev: *mut bufferevent, mut key: key_code) -> i32 {
    let __func__ = c!("input_key_vt10x");
    unsafe {
        let mut ud: utf8_data = zeroed(); // TODO use uninit

        log_debug!("{}: key in {}", _s(__func__), key);

        if key & KEYC_META != 0 {
            input_key_write(__func__, bev, c!("\x1b"), 1);
        }

        /*
         * There's no way to report modifiers for unicode keys in standard mode
         * so lose the modifiers.
         */
        if KEYC_IS_UNICODE(key) {
            ud = utf8_to_data(key as u32);
            input_key_write(__func__, bev, ud.data.as_ptr().cast(), ud.size as usize);
            return 0;
        }

        /* Prevent TAB, CR and LF from being swallowed by the C0 remapping logic. */
        let onlykey: key_code = key & KEYC_MASK_KEY;
        if onlykey == b'\r' as u64 || onlykey == b'\n' as u64 || onlykey == b'\t' as u64 {
            key &= !KEYC_CTRL;
        }

        /*
         * Convert keys with Ctrl modifier into corresponding C0 control codes,
         * with the exception of *some* keys, which are remapped into printable
         * ASCII characters.
         *
         * There is no special handling for Shift modifier, which is pretty
         * much redundant anyway, as no terminal will send <base key>|SHIFT,
         * but only <shifted key>|SHIFT.
         */
        if key & KEYC_CTRL != 0 {
            let p = libc::strchr(STANDARD_MAP[0].as_ptr(), onlykey as i32);
            key = if !p.is_null() {
                *STANDARD_MAP[1]
                    .as_ptr()
                    .add(p.addr() - STANDARD_MAP[0].as_ptr().addr()) as u64
            } else if onlykey >= b'3' as u64 && onlykey <= b'7' as u64 {
                onlykey - b'\x18' as u64
            } else if onlykey >= b'@' as u64 && onlykey <= b'~' as u64 {
                onlykey & 0x1f
            } else {
                return -1;
            };
        }

        log_debug!("{}: key out {}", _s(__func__), key);

        ud.data[0] = (key & 0x7f) as u8;
        input_key_write(__func__, bev, ud.data.as_ptr().cast(), 1);

        0
    }
}

/// Pick keys that are reported as vt10x keys in modifyOtherKeys=1 mode.
/// C `vendor/tmux/input-keys.c:545`: `static int input_key_mode1(struct bufferevent *bev, key_code key)`
pub unsafe fn input_key_mode1(bev: *mut bufferevent, key: key_code) -> i32 {
    unsafe {
        log_debug!("{}: key in {}", "input_key_mode1", key);

        // As per https://invisible-island.net/xterm/modified-keys-us-pc105.html.
        let onlykey = key & KEYC_MASK_KEY;
        if (key & KEYC_CTRL) != 0
            && (onlykey == ' ' as u64
                || onlykey == '/' as u64
                || onlykey == '@' as u64
                || onlykey == '^' as u64
                || (onlykey >= '2' as u64 && onlykey <= '8' as u64)
                || (onlykey >= '@' as u64 && onlykey <= '~' as u64))
        {
            return input_key_vt10x(bev, key);
        }

        // A regular key + Meta. In the absence of a standard to back this, we mimic what iTerm 2 does.
        if (key & (KEYC_CTRL | KEYC_META)) == KEYC_META {
            return input_key_vt10x(bev, key);
        }
    }

    -1
}

/// Translate a key code into an output key sequence.
/// C `vendor/tmux/input-keys.c:574`: `int input_key(struct screen *s, struct bufferevent *bev, key_code key)`
pub unsafe fn input_key(s: *mut screen, bev: *mut bufferevent, mut key: key_code) -> i32 {
    let __func__ = c!("input_key");
    unsafe {
        let mut ike: *mut input_key_entry = null_mut();
        let mut ud: utf8_data = zeroed();

        // Mouse keys need a pane.
        if KEYC_IS_MOUSE(key) {
            return 0;
        }

        // Literal keys go as themselves (can't be more than eight bits).
        if key & KEYC_LITERAL != 0 {
            ud.data[0] = key as u8;
            input_key_write(__func__, bev, ud.data.as_ptr().cast(), 1);
            return 0;
        }

        // Is this backspace?
        if (key & KEYC_MASK_KEY) == keyc::KEYC_BSPACE as u64 {
            let mut newkey = options_get_number_(GLOBAL_OPTIONS, "backspace") as key_code;
            log_debug!(
                "{}: key 0x{:x} is backspace -> 0x{:x}",
                _s(__func__),
                key,
                newkey
            );
            if (key & KEYC_MASK_MODIFIERS) == 0 {
                ud.data[0] = 255;
                if (newkey & KEYC_MASK_MODIFIERS) == 0 {
                    ud.data[0] = newkey as u8;
                } else if (newkey & KEYC_MASK_MODIFIERS) == KEYC_CTRL {
                    newkey &= KEYC_MASK_KEY;
                    if newkey == '?' as u64 {
                        ud.data[0] = 0x7f;
                    } else if newkey >= '@' as u64 && newkey <= '_' as u64 {
                        ud.data[0] = (newkey - 0x40) as u8;
                    } else if newkey >= 'a' as u64 && newkey <= 'z' as u64 {
                        ud.data[0] = (newkey - 0x60) as u8;
                    }
                }
                if ud.data[0] != 255 {
                    input_key_write(__func__, bev, ud.data.as_ptr().cast(), 1);
                }
                return 0;
            }
            key = newkey | (key & (KEYC_MASK_FLAGS | KEYC_MASK_MODIFIERS));
        }

        // Is this backtab?
        if (key & KEYC_MASK_KEY) == keyc::KEYC_BTAB as u64 {
            if (*s).mode.intersects(EXTENDED_KEY_MODES) {
                // When in xterm extended mode, remap into S-Tab.
                key = '\x09' as u64 | (key & !KEYC_MASK_KEY) | KEYC_SHIFT;
            } else {
                // Otherwise clear modifiers.
                key &= !KEYC_MASK_MODIFIERS;
            }
        }

        // A trivial case, that is a 7-bit key, excluding C0 control characters
        // that can't be entered from the keyboard, and no modifiers; or a UTF-8
        // key and no modifiers.
        if (key & !KEYC_MASK_KEY) == 0 {
            if key == c0::C0_HT as u64
                || key == c0::C0_CR as u64
                || key == c0::C0_ESC as u64
                || (0x20..=0x7f).contains(&key)
            {
                ud.data[0] = key as u8;
                input_key_write(__func__, bev, ud.data.as_ptr().cast(), 1);
                return 0;
            }
            if KEYC_IS_UNICODE(key) {
                ud = utf8_to_data(key as u32);
                input_key_write(__func__, bev, ud.data.as_ptr().cast(), ud.size as usize);
                return 0;
            }
        }

        // Look up the standard VT10x keys in the tree. If not in application
        // keypad or cursor mode, remove the respective flags from the key.
        if !(*s).mode.intersects(mode_flag::MODE_KKEYPAD) {
            key &= !KEYC_KEYPAD;
        }
        if !(*s).mode.intersects(mode_flag::MODE_KCURSOR) {
            key &= !KEYC_CURSOR;
        }
        if ike.is_null() {
            ike = input_key_get(key);
        }
        if ike.is_null() && (key & KEYC_META != 0) && (!key & KEYC_IMPLIED_META != 0) {
            ike = input_key_get(key & !KEYC_META);
        }
        if ike.is_null() && (key & KEYC_CURSOR != 0) {
            ike = input_key_get(key & !KEYC_CURSOR);
        }
        if ike.is_null() && (key & KEYC_KEYPAD != 0) {
            ike = input_key_get(key & !KEYC_KEYPAD);
        }
        if !ike.is_null() {
            log_debug!(
                "{}: found key 0x{}: \"{}\"",
                _s(__func__),
                key,
                _s((*ike).data)
            );
            if ((key & KEYC_MASK_KEY) == keyc::KEYC_PASTE_START as u64
                || (key & KEYC_MASK_KEY) == keyc::KEYC_PASTE_END as u64)
                && !(*s).mode.intersects(mode_flag::MODE_BRACKETPASTE)
            {
                return 0;
            }
            if (key & KEYC_META != 0) && (!key & KEYC_IMPLIED_META != 0) {
                input_key_write(__func__, bev, c!("\x1b"), 1);
            }
            input_key_write(__func__, bev, (*ike).data, strlen((*ike).data));
            return 0;
        }

        // Ignore internal function key codes.
        if (key >= KEYC_BASE && key < keyc::KEYC_BASE_END as u64)
            || (KEYC_USER..KEYC_USER_END).contains(&key)
        {
            log_debug!("{}: ignoring key 0x{}", _s(__func__), key);
            return 0;
        }

        // No builtin key sequence; construct an extended key sequence
        // depending on the client mode.
        //
        // If something invalid reaches here, an invalid output may be
        // produced. For example Ctrl-Shift-2 is invalid (as there's
        // no way to enter it). The correct form is Ctrl-Shift-@, at
        // least in US English keyboard layout.
        match (*s).mode & EXTENDED_KEY_MODES {
            mode_flag::MODE_KEYS_EXTENDED_2 =>
            /*
             * The simplest mode to handle - *all* modified keys are
             * reported in the extended form.
             */
            {
                input_key_extended(bev, key)
            }
            mode_flag::MODE_KEYS_EXTENDED => {
                /*
                 * Some keys are still reported in standard mode, to maintain
                 * compatibility with applications unaware of extended keys.
                 */
                if input_key_mode1(bev, key) == -1 {
                    return input_key_extended(bev, key);
                }
                0
            }
            _ =>
            /* The standard mode. */
            {
                input_key_vt10x(bev, key)
            }
        }
    }
}

#[expect(static_mut_refs, reason = "FIXME")]
/// Get mouse event string.
/// C `vendor/tmux/input-keys.c:713`: `int input_key_get_mouse(struct screen *s, struct mouse_event *m, u_int x, u_int y, const char **rbuf, size_t *rlen)`
pub unsafe fn input_key_get_mouse(
    s: *mut screen,
    m: *mut mouse_event,
    x: u32,
    y: u32,
    rbuf: *mut *const u8,
    rlen: *mut usize,
) -> i32 {
    use std::io::Write;
    static mut BUF: [u8; 40] = [0; 40];

    unsafe {
        let sizeof_buf = 40;
        *rbuf = null_mut();
        *rlen = 0;

        // If this pane is not in button or all mode, discard motion events.
        if MOUSE_DRAG((*m).b) && !(*s).mode.intersects(MOTION_MOUSE_MODES) {
            return 0;
        }
        if !(*s).mode.intersects(ALL_MOUSE_MODES) {
            return 0;
        }

        // If this event is a release event and not in all mode, discard it.
        // In SGR mode we can tell absolutely because a release is normally
        // shown by the last character. Without SGR, we check if the last
        // buttons was also a release.
        if (*m).sgr_type != b' ' as u32 {
            if MOUSE_DRAG((*m).sgr_b)
                && MOUSE_RELEASE((*m).sgr_b)
                && !(*s).mode.intersects(mode_flag::MODE_MOUSE_ALL)
            {
                return 0;
            }
        } else if MOUSE_DRAG((*m).b)
            && MOUSE_RELEASE((*m).b)
            && MOUSE_RELEASE((*m).lb)
            && !(*s).mode.intersects(mode_flag::MODE_MOUSE_ALL)
        {
            return 0;
        }

        // Use the SGR (1006) extension only if the application requested it
        // and the underlying terminal also sent the event in this format (this
        // is because an old style mouse release event cannot be converted into
        // the new SGR format, since the released button is unknown). Otherwise
        // pretend that tmux doesn't speak this extension, and fall back to the
        // UTF-8 (1005) extension if the application requested, or to the
        // legacy format.
        let mut len: usize;
        if (*m).sgr_type != ' ' as u32 && (*s).mode.intersects(mode_flag::MODE_MOUSE_SGR) {
            len = xsnprintf_!(
                &raw mut BUF as *mut u8,
                sizeof_buf,
                "\x1b[<{};{};{}{}",
                (*m).sgr_b,
                x + 1,
                y + 1,
                (*m).sgr_type as u8 as char,
            )
            .unwrap() as usize;
        } else if (*s).mode.intersects(mode_flag::MODE_MOUSE_UTF8) {
            if (*m).b > (MOUSE_PARAM_UTF8_MAX - MOUSE_PARAM_BTN_OFF)
                || x > (MOUSE_PARAM_UTF8_MAX - MOUSE_PARAM_POS_OFF)
                || y > (MOUSE_PARAM_UTF8_MAX - MOUSE_PARAM_POS_OFF)
            {
                return 0;
            }
            len = BUF.as_mut_slice().write(b"\x1b[M").unwrap();
            len += input_key_split2((*m).b + MOUSE_PARAM_BTN_OFF, &raw mut BUF[len] as _);
            len += input_key_split2(x + MOUSE_PARAM_POS_OFF, &raw mut BUF[len] as _);
            len += input_key_split2(y + MOUSE_PARAM_POS_OFF, &raw mut BUF[len] as _);
        } else {
            if (*m).b + MOUSE_PARAM_BTN_OFF > MOUSE_PARAM_MAX {
                return 0;
            }

            len = BUF.as_mut_slice().write(b"\x1b[M").unwrap();
            BUF[len] = ((*m).b + MOUSE_PARAM_BTN_OFF) as u8;
            len += 1;

            // The incoming x and y may be out of the range which can be
            // supported by the "normal" mouse protocol. Clamp the
            // coordinates to the supported range.
            if x + MOUSE_PARAM_POS_OFF > MOUSE_PARAM_MAX {
                BUF[len] = MOUSE_PARAM_MAX as u8;
                len += 1;
            } else {
                BUF[len] = x as u8 + MOUSE_PARAM_POS_OFF as u8;
                len += 1;
            }
            if y + MOUSE_PARAM_POS_OFF > MOUSE_PARAM_MAX {
                BUF[len] = MOUSE_PARAM_MAX as u8;
                len += 1;
            } else {
                BUF[len] = y as u8 + MOUSE_PARAM_POS_OFF as u8;
                len += 1;
            }
        }

        *rbuf = &raw const BUF as *const u8;
        *rlen = len;
    }
    1
}

/// Translate mouse and output.
/// C `vendor/tmux/input-keys.c:797`: `static void input_key_mouse(struct window_pane *wp, struct mouse_event *m)`
pub unsafe fn input_key_mouse(wp: *mut window_pane, m: *mut mouse_event) {
    let __func__ = c!("input_key_mouse");
    unsafe {
        let s = (*wp).screen;
        let mut x = 0;
        let mut y = 0;
        let mut buf = null();
        let mut len: usize = 0;

        // Ignore events if no mouse mode or the pane is not visible.
        if (*m).ignore != 0 || !(*s).mode.intersects(ALL_MOUSE_MODES) {
            return;
        }
        if cmd_mouse_at(wp, m, &raw mut x, &raw mut y, 0) != 0 {
            return;
        }
        if !window_pane_visible(wp) {
            return;
        }
        if input_key_get_mouse(s, m, x, y, &raw mut buf, &raw mut len) == 0 {
            return;
        }
        log_debug!("writing mouse {1:0$} to %{2}", len, _s(buf), (*wp).id);
        input_key_write(__func__, (*wp).event, buf, len);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Mutex;
    use std::sync::Once;

    // `input_key_get_mouse` returns a pointer into a shared `static mut BUF`
    // (faithful to C tmux's single-threaded model). cargo runs tests in parallel
    // threads, so the mouse tests would clobber each other's buffer contents;
    // each holds this lock for its whole body to serialize access.
    static MOUSE_BUF_LOCK: Mutex<()> = Mutex::new(());

    // The key tree lives in the global `INPUT_KEY_TREE` static, built once from
    // `INPUT_KEY_DEFAULTS`. `input_key_build` inserts the default entries (and
    // the modifier-folded copies) into it; calling it twice would double-insert
    // the same nodes and corrupt the tree, so guard with a `Once`.
    static BUILT: Once = Once::new();
    fn ensure_built() {
        BUILT.call_once(|| unsafe {
            input_key_build();
        });
    }

    // Look up `key` in the tree and return its escape byte sequence, or None
    // when the key is absent. Mirrors C `input_key_get` + reading `ike->data`.
    unsafe fn lookup(key: key_code) -> Option<Vec<u8>> {
        unsafe {
            ensure_built();
            let ike = input_key_get(key);
            if ike.is_null() {
                None
            } else {
                Some(CStr::from_ptr((*ike).data.cast()).to_bytes().to_vec())
            }
        }
    }

    // C input-keys.c:331 input_key_cmp: orders entries purely by `key`.
    #[test]
    fn test_input_key_cmp() {
        let a = input_key_entry::new(keyc::KEYC_F1 as u64, c"x");
        let b = input_key_entry::new(keyc::KEYC_F2 as u64, c"y");
        // Different data, same key -> Equal (only `key` participates).
        let a2 = input_key_entry::new(keyc::KEYC_F1 as u64, c"zzz");
        assert_eq!(input_key_cmp(&a, &b), cmp::Ordering::Less);
        assert_eq!(input_key_cmp(&b, &a), cmp::Ordering::Greater);
        assert_eq!(input_key_cmp(&a, &a2), cmp::Ordering::Equal);
    }

    // C input-keys.c:351 input_key_split2: 7-bit stays one byte; anything above
    // 0x7f is emitted as a two-byte UTF-8 sequence.
    #[test]
    fn test_input_key_split2() {
        unsafe {
            let mut buf = [0u8; 4];

            // 'A' (0x41) <= 0x7f: single byte.
            assert_eq!(input_key_split2(b'A' as u32, buf.as_mut_ptr()), 1);
            assert_eq!(buf[0], 0x41);

            // Boundary 0x7f: still one byte.
            assert_eq!(input_key_split2(0x7f, buf.as_mut_ptr()), 1);
            assert_eq!(buf[0], 0x7f);

            // Boundary 0x80: (0x80>>6)|0xc0 = 0xc2, (0x80&0x3f)|0x80 = 0x80.
            assert_eq!(input_key_split2(0x80, buf.as_mut_ptr()), 2);
            assert_eq!(buf[0], 0xc2);
            assert_eq!(buf[1], 0x80);

            // 0x100: (0x100>>6)|0xc0 = 0xc4, (0x100&0x3f)|0x80 = 0x80.
            assert_eq!(input_key_split2(0x100, buf.as_mut_ptr()), 2);
            assert_eq!(buf[0], 0xc4);
            assert_eq!(buf[1], 0x80);
        }
    }

    // Regression: the SGR (1006) mouse sequence written to a pane must include
    // its terminating `M`/`m`. A stale `- 1` on the xsnprintf length once
    // dropped the final byte, so ztmux wrote a truncated `\033[<b;x;y` (no
    // terminator). crossterm/ratatui apps (storageshower, iftop-rs, ...) that
    // enabled SGR mouse then blocked in read() waiting for the terminator,
    // freezing the pane on any mouse or focus event while keyboard still worked.
    #[test]
    fn test_get_mouse_sgr_keeps_terminator() {
        let _g = MOUSE_BUF_LOCK.lock().unwrap();
        unsafe {
            let mut s: screen = std::mem::zeroed();
            s.mode = mode_flag::MODE_MOUSE_STANDARD | mode_flag::MODE_MOUSE_SGR;

            let mut m: mouse_event = std::mem::zeroed();
            m.sgr_type = b'M' as u32; // press
            m.sgr_b = 0; // button 0
            m.b = 0;

            let mut buf: *const u8 = null();
            let mut len: usize = 0;
            let r = input_key_get_mouse(&mut s, &mut m, 4, 4, &raw mut buf, &raw mut len);
            assert_eq!(r, 1);
            let bytes = std::slice::from_raw_parts(buf, len);
            assert_eq!(bytes, b"\x1b[<0;5;5M");
            assert_eq!(*bytes.last().unwrap(), b'M', "SGR mouse terminator dropped");

            // Release form ends in 'm'.
            m.sgr_type = b'm' as u32;
            let r = input_key_get_mouse(&mut s, &mut m, 4, 4, &raw mut buf, &raw mut len);
            assert_eq!(r, 1);
            assert_eq!(std::slice::from_raw_parts(buf, len), b"\x1b[<0;5;5m");
        }
    }

    // Regression (bug 1, continued): the same truncation would only manifest on
    // longer sequences, so exercise multi-digit coordinates and a non-zero
    // button. The formatted length must still include every byte through the
    // trailing terminator; an off-by-one on the length would clip the final
    // digit or the `M`/`m`.
    #[test]
    fn test_get_mouse_sgr_multidigit_and_button() {
        let _g = MOUSE_BUF_LOCK.lock().unwrap();
        unsafe {
            let mut s: screen = std::mem::zeroed();
            s.mode = mode_flag::MODE_MOUSE_STANDARD | mode_flag::MODE_MOUSE_SGR;

            let mut m: mouse_event = std::mem::zeroed();
            m.sgr_type = b'M' as u32;
            m.sgr_b = 64; // wheel-up button code
            m.b = 64;

            let mut buf: *const u8 = null();
            let mut len: usize = 0;
            // x=209, y=99 -> displayed 1-based as 210 and 100 (both multi-digit).
            let r = input_key_get_mouse(&mut s, &mut m, 209, 99, &raw mut buf, &raw mut len);
            assert_eq!(r, 1);
            let bytes = std::slice::from_raw_parts(buf, len);
            assert_eq!(bytes, b"\x1b[<64;210;100M");
            // len must count the whole sequence, terminator included.
            assert_eq!(len, bytes.len());
            assert_eq!(*bytes.last().unwrap(), b'M');
        }
    }

    // Regression (bug 1, continued): a drag/motion event reported in SGR form
    // (in all-mouse mode so it isn't discarded) must also keep its terminator.
    // Motion is what crossterm sends on mouse-move, and a truncated motion
    // report was one trigger of the pane freeze.
    #[test]
    fn test_get_mouse_sgr_drag_keeps_terminator() {
        let _g = MOUSE_BUF_LOCK.lock().unwrap();
        unsafe {
            let mut s: screen = std::mem::zeroed();
            // MODE_MOUSE_ALL keeps motion/drag events instead of discarding them.
            s.mode = mode_flag::MODE_MOUSE_ALL | mode_flag::MODE_MOUSE_SGR;

            let mut m: mouse_event = std::mem::zeroed();
            m.sgr_type = b'M' as u32;
            // 32 (MOUSE_MASK_DRAG) with a button in the low bits -> a drag report.
            m.sgr_b = 32;
            m.b = 32;

            let mut buf: *const u8 = null();
            let mut len: usize = 0;
            let r = input_key_get_mouse(&mut s, &mut m, 9, 9, &raw mut buf, &raw mut len);
            assert_eq!(r, 1);
            let bytes = std::slice::from_raw_parts(buf, len);
            assert_eq!(bytes, b"\x1b[<32;10;10M");
            assert_eq!(*bytes.last().unwrap(), b'M', "SGR drag terminator dropped");
        }
    }

    // C input-keys.c:66-123: function / edit / navigation keys map to their
    // fixed escape sequences.
    #[test]
    fn test_lookup_function_and_nav_keys() {
        unsafe {
            // SS3-prefixed F1..F4.
            assert_eq!(lookup(keyc::KEYC_F1 as u64).as_deref(), Some(&b"\x1bOP"[..]));
            assert_eq!(lookup(keyc::KEYC_F4 as u64).as_deref(), Some(&b"\x1bOS"[..]));
            // CSI-tilde F5..F12.
            assert_eq!(lookup(keyc::KEYC_F5 as u64).as_deref(), Some(&b"\x1b[15~"[..]));
            assert_eq!(lookup(keyc::KEYC_F12 as u64).as_deref(), Some(&b"\x1b[24~"[..]));
            // Edit / navigation block.
            assert_eq!(lookup(keyc::KEYC_IC as u64).as_deref(), Some(&b"\x1b[2~"[..]));
            assert_eq!(lookup(keyc::KEYC_DC as u64).as_deref(), Some(&b"\x1b[3~"[..]));
            assert_eq!(lookup(keyc::KEYC_HOME as u64).as_deref(), Some(&b"\x1b[1~"[..]));
            assert_eq!(lookup(keyc::KEYC_END as u64).as_deref(), Some(&b"\x1b[4~"[..]));
            assert_eq!(lookup(keyc::KEYC_NPAGE as u64).as_deref(), Some(&b"\x1b[6~"[..]));
            assert_eq!(lookup(keyc::KEYC_PPAGE as u64).as_deref(), Some(&b"\x1b[5~"[..]));
            assert_eq!(lookup(keyc::KEYC_BTAB as u64).as_deref(), Some(&b"\x1b[Z"[..]));
        }
    }

    // C input-keys.c:126-149: arrow keys have distinct application-cursor
    // (KEYC_CURSOR / SS3) and normal (CSI) forms; both are stored keyed on the
    // presence of KEYC_CURSOR.
    #[test]
    fn test_lookup_arrow_keys_cursor_mode() {
        unsafe {
            // Application cursor mode: SS3 prefix.
            assert_eq!(lookup(keyc::KEYC_UP as u64 | KEYC_CURSOR).as_deref(), Some(&b"\x1bOA"[..]));
            assert_eq!(lookup(keyc::KEYC_DOWN as u64 | KEYC_CURSOR).as_deref(), Some(&b"\x1bOB"[..]));
            assert_eq!(lookup(keyc::KEYC_RIGHT as u64 | KEYC_CURSOR).as_deref(), Some(&b"\x1bOC"[..]));
            assert_eq!(lookup(keyc::KEYC_LEFT as u64 | KEYC_CURSOR).as_deref(), Some(&b"\x1bOD"[..]));
            // Normal mode: CSI prefix.
            assert_eq!(lookup(keyc::KEYC_UP as u64).as_deref(), Some(&b"\x1b[A"[..]));
            assert_eq!(lookup(keyc::KEYC_DOWN as u64).as_deref(), Some(&b"\x1b[B"[..]));
            assert_eq!(lookup(keyc::KEYC_RIGHT as u64).as_deref(), Some(&b"\x1b[C"[..]));
            assert_eq!(lookup(keyc::KEYC_LEFT as u64).as_deref(), Some(&b"\x1b[D"[..]));
        }
    }

    // C input-keys.c:152-247: keypad keys have an application form (KEYC_KEYPAD
    // / SS3) and a plain literal form.
    #[test]
    fn test_lookup_keypad_keys() {
        unsafe {
            // Application keypad: SS3 letters.
            assert_eq!(lookup(keyc::KEYC_KP_SLASH as u64 | KEYC_KEYPAD).as_deref(), Some(&b"\x1bOo"[..]));
            assert_eq!(lookup(keyc::KEYC_KP_STAR as u64 | KEYC_KEYPAD).as_deref(), Some(&b"\x1bOj"[..]));
            assert_eq!(lookup(keyc::KEYC_KP_ENTER as u64 | KEYC_KEYPAD).as_deref(), Some(&b"\x1bOM"[..]));
            assert_eq!(lookup(keyc::KEYC_KP_ZERO as u64 | KEYC_KEYPAD).as_deref(), Some(&b"\x1bOp"[..]));
            assert_eq!(lookup(keyc::KEYC_KP_PERIOD as u64 | KEYC_KEYPAD).as_deref(), Some(&b"\x1bOn"[..]));
            // Plain keypad: literal characters.
            assert_eq!(lookup(keyc::KEYC_KP_SLASH as u64).as_deref(), Some(&b"/"[..]));
            assert_eq!(lookup(keyc::KEYC_KP_STAR as u64).as_deref(), Some(&b"*"[..]));
            assert_eq!(lookup(keyc::KEYC_KP_SEVEN as u64).as_deref(), Some(&b"7"[..]));
            assert_eq!(lookup(keyc::KEYC_KP_ENTER as u64).as_deref(), Some(&b"\n"[..]));
            assert_eq!(lookup(keyc::KEYC_KP_ZERO as u64).as_deref(), Some(&b"0"[..]));
            assert_eq!(lookup(keyc::KEYC_KP_PERIOD as u64).as_deref(), Some(&b"."[..]));
        }
    }

    // C input-keys.c:52-64: bracketed-paste sentinels. There are four entries:
    // PASTE_START, PASTE_START|KEYC_IMPLIED_META, PASTE_END and
    // PASTE_END|KEYC_IMPLIED_META. The IMPLIED_META copies must be present in
    // the tree so a paste sentinel that arrives with the implied-meta flag (from
    // tty_keys) still resolves in input_key's lookup; omitting them regressed
    // bracketed paste for implied-meta terminals.
    #[test]
    fn test_lookup_paste_keys() {
        unsafe {
            assert_eq!(lookup(keyc::KEYC_PASTE_START as u64).as_deref(), Some(&b"\x1b[200~"[..]));
            assert_eq!(lookup(keyc::KEYC_PASTE_END as u64).as_deref(), Some(&b"\x1b[201~"[..]));
            assert_eq!(
                lookup(keyc::KEYC_PASTE_START as u64 | KEYC_IMPLIED_META).as_deref(),
                Some(&b"\x1b[200~"[..])
            );
            assert_eq!(
                lookup(keyc::KEYC_PASTE_END as u64 | KEYC_IMPLIED_META).as_deref(),
                Some(&b"\x1b[201~"[..])
            );
        }
    }

    // C input-keys.c:249-315 + input_key_build (input-keys.c:378-388): entries
    // flagged KEYC_BUILD_MODIFIERS are expanded, for j = 2..8, into copies whose
    // key carries `input_key_modifiers[j]` and whose "_" placeholder becomes the
    // digit '0'+j. Verify the resulting modifier digit folds into the sequence.
    #[test]
    fn test_lookup_modifier_folding() {
        unsafe {
            // j=2 -> KEYC_SHIFT -> digit '2'.
            assert_eq!(
                lookup(keyc::KEYC_UP as u64 | KEYC_SHIFT).as_deref(),
                Some(&b"\x1b[1;2A"[..])
            );
            // j=3 -> KEYC_META|KEYC_IMPLIED_META -> digit '3'.
            assert_eq!(
                lookup(keyc::KEYC_HOME as u64 | KEYC_META | KEYC_IMPLIED_META).as_deref(),
                Some(&b"\x1b[1;3H"[..])
            );
            // j=5 -> KEYC_CTRL -> digit '5'; F-key placeholder is before 'P'.
            assert_eq!(
                lookup(keyc::KEYC_F1 as u64 | KEYC_CTRL).as_deref(),
                Some(&b"\x1b[1;5P"[..])
            );
            // j=5 on a CSI-tilde F-key: "\x1b[24;_~" -> "\x1b[24;5~".
            assert_eq!(
                lookup(keyc::KEYC_F12 as u64 | KEYC_CTRL).as_deref(),
                Some(&b"\x1b[24;5~"[..])
            );
            // j=8 -> Shift+Meta+Ctrl -> digit '8'.
            assert_eq!(
                lookup(
                    keyc::KEYC_UP as u64
                        | KEYC_SHIFT
                        | KEYC_META
                        | KEYC_IMPLIED_META
                        | KEYC_CTRL
                )
                .as_deref(),
                Some(&b"\x1b[1;8A"[..])
            );
            // End key with Ctrl uses the 'F' final byte.
            assert_eq!(
                lookup(keyc::KEYC_END as u64 | KEYC_CTRL).as_deref(),
                Some(&b"\x1b[1;5F"[..])
            );
        }
    }

    // input_key_get returns NULL for keys not present in the tree.
    #[test]
    fn test_lookup_missing_returns_none() {
        unsafe {
            // A plain ASCII 'a' is never a tree entry (handled directly by
            // input_key, not via the tree).
            assert_eq!(lookup(b'a' as key_code), None);
            // KEYC_UP without KEYC_CURSOR exists, but with a bogus KEYC_KEYPAD
            // flag it does not.
            assert_eq!(lookup(keyc::KEYC_UP as u64 | KEYC_KEYPAD), None);
            // A modifier combination the build never produces (j starts at 2, so
            // the unmodified KEYC_BUILD_MODIFIERS base key is not inserted).
            assert_eq!(lookup(keyc::KEYC_F1 as u64 | KEYC_BUILD_MODIFIERS), None);
        }
    }

    // input_key_modifiers[] (input-keys.c:322) maps each modifier combination to
    // the CSI final digit: j=2 Shift, 3 Meta, 4 Shift+Meta, 5 Ctrl, 6 Shift+Ctrl,
    // 7 Meta+Ctrl, 8 Shift+Meta+Ctrl. Sweep the arrow-up entry across all of them
    // so a mis-ordered modifier table (wrong digit) is caught.
    #[test]
    fn test_modifier_folding_all_digits() {
        unsafe {
            let up = keyc::KEYC_UP as u64;
            let meta = KEYC_META | KEYC_IMPLIED_META;
            assert_eq!(lookup(up | KEYC_SHIFT).as_deref(), Some(&b"\x1b[1;2A"[..]));
            assert_eq!(lookup(up | meta).as_deref(), Some(&b"\x1b[1;3A"[..]));
            assert_eq!(lookup(up | KEYC_SHIFT | meta).as_deref(), Some(&b"\x1b[1;4A"[..]));
            assert_eq!(lookup(up | KEYC_CTRL).as_deref(), Some(&b"\x1b[1;5A"[..]));
            assert_eq!(lookup(up | KEYC_SHIFT | KEYC_CTRL).as_deref(), Some(&b"\x1b[1;6A"[..]));
            assert_eq!(lookup(up | meta | KEYC_CTRL).as_deref(), Some(&b"\x1b[1;7A"[..]));
            assert_eq!(
                lookup(up | KEYC_SHIFT | meta | KEYC_CTRL).as_deref(),
                Some(&b"\x1b[1;8A"[..])
            );
        }
    }

    // The four arrows keep their distinct CSI final byte (A/B/C/D) after the
    // modifier digit is folded in (input-keys.c:280-283).
    #[test]
    fn test_modifier_folding_arrow_final_bytes() {
        unsafe {
            assert_eq!(lookup(keyc::KEYC_UP as u64 | KEYC_CTRL).as_deref(), Some(&b"\x1b[1;5A"[..]));
            assert_eq!(lookup(keyc::KEYC_DOWN as u64 | KEYC_CTRL).as_deref(), Some(&b"\x1b[1;5B"[..]));
            assert_eq!(lookup(keyc::KEYC_RIGHT as u64 | KEYC_CTRL).as_deref(), Some(&b"\x1b[1;5C"[..]));
            assert_eq!(lookup(keyc::KEYC_LEFT as u64 | KEYC_CTRL).as_deref(), Some(&b"\x1b[1;5D"[..]));
        }
    }

    // The CSI-tilde edit/navigation keys fold the modifier digit into the
    // parameter list before the '~' (input-keys.c:305-315): IC=2, DC=3, PPage=5,
    // NPage=6. Home/End use the letter finals H/F.
    #[test]
    fn test_modifier_folding_edit_and_nav_keys() {
        unsafe {
            let meta = KEYC_META | KEYC_IMPLIED_META;
            assert_eq!(lookup(keyc::KEYC_IC as u64 | KEYC_CTRL).as_deref(), Some(&b"\x1b[2;5~"[..]));
            assert_eq!(lookup(keyc::KEYC_DC as u64 | KEYC_SHIFT).as_deref(), Some(&b"\x1b[3;2~"[..]));
            assert_eq!(lookup(keyc::KEYC_PPAGE as u64 | meta).as_deref(), Some(&b"\x1b[5;3~"[..]));
            assert_eq!(lookup(keyc::KEYC_NPAGE as u64 | KEYC_CTRL).as_deref(), Some(&b"\x1b[6;5~"[..]));
            assert_eq!(
                lookup(keyc::KEYC_HOME as u64 | KEYC_SHIFT | meta).as_deref(),
                Some(&b"\x1b[1;4H"[..])
            );
            assert_eq!(lookup(keyc::KEYC_END as u64 | KEYC_CTRL).as_deref(), Some(&b"\x1b[1;5F"[..]));
        }
    }

    // The SS3-form F1..F4 keep their P/Q/R/S final byte when a modifier folds in
    // (input-keys.c:249-252), switching from SS3 to the CSI "1;<mod><final>" form.
    #[test]
    fn test_modifier_folding_ss3_function_keys() {
        unsafe {
            assert_eq!(lookup(keyc::KEYC_F1 as u64 | KEYC_CTRL).as_deref(), Some(&b"\x1b[1;5P"[..]));
            assert_eq!(lookup(keyc::KEYC_F2 as u64 | KEYC_SHIFT).as_deref(), Some(&b"\x1b[1;2Q"[..]));
            assert_eq!(lookup(keyc::KEYC_F3 as u64 | KEYC_CTRL).as_deref(), Some(&b"\x1b[1;5R"[..]));
            assert_eq!(lookup(keyc::KEYC_F4 as u64 | KEYC_CTRL).as_deref(), Some(&b"\x1b[1;5S"[..]));
        }
    }

    // input-keys.c:351 input_key_split2: exercise more of the two-byte range.
    #[test]
    fn test_input_key_split2_more_boundaries() {
        unsafe {
            let mut buf = [0u8; 4];
            // 0x00 stays one byte.
            assert_eq!(input_key_split2(0, buf.as_mut_ptr()), 1);
            assert_eq!(buf[0], 0);
            // 0x7ff is the max value the (c>>6)|0xc0 two-byte form can represent:
            // (0x7ff>>6)|0xc0 = 0xdf, (0x7ff&0x3f)|0x80 = 0xbf.
            assert_eq!(input_key_split2(0x7ff, buf.as_mut_ptr()), 2);
            assert_eq!(buf[0], 0xdf);
            assert_eq!(buf[1], 0xbf);
            // 0xa0 (a common Latin-1 boundary): 0xc2, 0xa0.
            assert_eq!(input_key_split2(0xa0, buf.as_mut_ptr()), 2);
            assert_eq!(buf[0], 0xc2);
            assert_eq!(buf[1], 0xa0);
        }
    }

    // input-keys.c:331 input_key_cmp compares the full 64-bit key; a truncating
    // comparator would misorder keys that differ only in the high bits.
    #[test]
    fn test_input_key_cmp_full_width() {
        let lo = input_key_entry::new(1u64, c"a");
        let hi = input_key_entry::new(0x0100_0000_0000_0001u64, c"b");
        assert_eq!(input_key_cmp(&lo, &hi), cmp::Ordering::Less);
        assert_eq!(input_key_cmp(&hi, &lo), cmp::Ordering::Greater);
    }
}