tuika 0.6.0

The application framework for Rust terminal UIs — flexbox layout, overlays, focus, keymap, components, and safe ratatui interoperability.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
//! A multi-line text editor: buffer, cursor, editing, soft-wrap, and a screen
//! cursor position the host can hand to the terminal.
//!
//! Like the rest of tuika's interactive widgets, state and view are split:
//! [`TextInputState`] owns the text and cursor and applies edits (via
//! [`TextInputState::handle`] or the explicit methods); [`TextInput`] borrows it
//! and renders. The view is word-soft-wrapped to the render width — a logical
//! line longer than the area breaks at the last space that fits (hard-breaking a
//! word longer than the width), and a line that fills the width exactly wraps the
//! cursor onto a fresh row, like a real editor.
//!
//! It is a *rendering + edit model*, not a terminal: the host reads
//! [`TextInputState::cursor_screen`] after layout and calls the backend's
//! `set_cursor_position`. Hosts can configure whether Enter or Shift+Enter
//! submits via [`TextInputMode`]; the other chord inserts a newline.

use ratatui_core::layout::Rect;
use ratatui_core::style::Style;
use unicode_width::UnicodeWidthChar;

use crate::event::{Event, KeyCode};
use crate::geometry::Size;
use crate::surface::Surface;
use crate::view::{RenderCtx, View};

/// The editable text and cursor of a [`TextInput`].
#[derive(Clone, Debug)]
pub struct TextInputState {
    /// Logical lines (split on `\n`); always at least one (possibly empty).
    lines: Vec<String>,
    /// Cursor row (logical line index).
    row: usize,
    /// Cursor column (char index within `lines[row]`).
    col: usize,
    mode: TextInputMode,
}

/// Controls which Enter chord submits a text input.
///
/// Applied by both [`TextInputState::handle_enter`] and [`TextInputState::handle`]
/// when it sees Enter / Shift+Enter. Ctrl+J always inserts a newline regardless
/// of this mode (emacs newline / raw-mode LF from terminals without enhanced
/// keyboard reporting).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TextInputMode {
    /// Enter submits; Shift+Enter inserts a newline.
    #[default]
    SubmitOnEnter,
    /// Shift+Enter submits; Enter inserts a newline.
    SubmitOnShiftEnter,
}

/// Where a [`Trigger`] character is allowed to open a token.
///
/// This is the whole of tuika's opinion about inline tokens: *where* the opening
/// character may sit. What `@` or `/` (or `#`, or `:`) then **means** — a file
/// mention, a command, an issue, an emoji — is the host's, and so is what it
/// shows for one.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TriggerAnchor {
    /// Any position, mid-word included (`foo@bar` opens a token at the `@`).
    Anywhere,
    /// Start of a word: the first column, or right after whitespace.
    #[default]
    WordStart,
    /// The first character of a logical line.
    LineStart,
    /// The very first character of the buffer — a whole-input mode switch, the
    /// way a command palette treats a leading `/`.
    BufferStart,
}

/// A character that opens an inline token in a [`TextInputState`].
///
/// A host declares the triggers it cares about and asks the state for the
/// [`Token`]s they produce ([`tokens`](TextInputState::tokens),
/// [`active_token`](TextInputState::active_token)); tuika finds and delimits
/// them, and does nothing else with them. Popups, completion sources, and
/// styling stay in the host, so a different app can give `/` and `@` entirely
/// different semantics — or use neither.
///
/// ```
/// use tuika::prelude::*;
///
/// // `/command` only as the whole input's first character; `@mention` anywhere
/// // a word starts; `#123` mid-word too.
/// let triggers = [
///     Trigger::new('/').anchor(TriggerAnchor::BufferStart),
///     Trigger::new('@'),
///     Trigger::new('#').anchor(TriggerAnchor::Anywhere),
/// ];
///
/// let state = TextInputState::from_text("review @src/lib.rs for #42");
/// let tokens = state.tokens(&triggers);
/// assert_eq!(tokens.len(), 2);
/// assert_eq!(tokens[0].text, "@src/lib.rs");
/// assert_eq!(tokens[0].query(), "src/lib.rs");
/// assert_eq!(tokens[1].text, "#42");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Trigger {
    /// The character that opens the token.
    pub start: char,
    /// Where that character may appear for it to count.
    pub anchor: TriggerAnchor,
    /// End the token at the first whitespace (the default). When false it runs
    /// to the end of its logical line, so a query can contain spaces —
    /// `/model gpt 5` as one token rather than three.
    pub stop_at_whitespace: bool,
}

impl Trigger {
    /// A trigger on `start`, anchored at a word start, ending at whitespace.
    pub fn new(start: char) -> Self {
        Self {
            start,
            anchor: TriggerAnchor::default(),
            stop_at_whitespace: true,
        }
    }

    /// Restrict where the trigger character may appear.
    pub fn anchor(mut self, anchor: TriggerAnchor) -> Self {
        self.anchor = anchor;
        self
    }

    /// Let the token run to the end of its line instead of stopping at the
    /// first whitespace.
    pub fn to_line_end(mut self) -> Self {
        self.stop_at_whitespace = false;
        self
    }

    /// Whether `col` on `line` is a position this trigger may open at.
    fn anchored_at(&self, chars: &[char], row: usize, col: usize) -> bool {
        match self.anchor {
            TriggerAnchor::Anywhere => true,
            TriggerAnchor::WordStart => {
                col == 0 || chars.get(col - 1).is_some_and(|c| c.is_whitespace())
            }
            TriggerAnchor::LineStart => col == 0,
            TriggerAnchor::BufferStart => row == 0 && col == 0,
        }
    }
}

/// A token a [`Trigger`] matched: where it sits and what it says.
///
/// Positions are **char** indices into the logical line, matching
/// [`TextInputState::cursor`], so a host can turn a token into a
/// [`TextSpan`] ([`span`](Token::span)) or replace it
/// ([`replace_token`](TextInputState::replace_token)) without re-deriving them.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Token {
    /// The trigger character that opened it.
    pub trigger: char,
    /// Logical line the token is on.
    pub row: usize,
    /// Char index of the trigger character.
    pub start: usize,
    /// Char index one past the token's last character.
    pub end: usize,
    /// The token including its trigger character (`"@src/lib.rs"`).
    pub text: String,
}

impl Token {
    /// The token without its trigger character — what a host filters on.
    pub fn query(&self) -> &str {
        let mut chars = self.text.chars();
        chars.next();
        chars.as_str()
    }

    /// This token as a styled range, for [`TextInput::highlights`].
    pub fn span(&self, style: Style) -> TextSpan {
        TextSpan {
            row: self.row,
            start: self.start,
            end: self.end,
            style,
        }
    }
}

/// A styled char range within one logical line, applied by
/// [`TextInput::highlights`].
///
/// Ranges are host-computed: from [`Token`]s, a regex, a spell checker, a
/// syntax pass — tuika only paints them. Later spans win where they overlap.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TextSpan {
    /// Logical line the range is on.
    pub row: usize,
    /// First char index covered.
    pub start: usize,
    /// One past the last char index covered.
    pub end: usize,
    /// Style painted over the base text style.
    pub style: Style,
}

impl TextSpan {
    /// A styled range over `start..end` of logical line `row`.
    pub fn new(row: usize, start: usize, end: usize, style: Style) -> Self {
        Self {
            row,
            start,
            end,
            style,
        }
    }

    fn covers(&self, row: usize, col: usize) -> bool {
        self.row == row && col >= self.start && col < self.end
    }
}

/// Result of applying an Enter chord to a text input.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextInputEvent {
    /// The chord inserted a newline; text changed.
    Changed,
    /// The chord requested submission.
    Submit,
}

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

impl TextInputState {
    /// An empty single-line buffer with cursor at the start.
    pub fn new() -> Self {
        Self {
            lines: vec![String::new()],
            row: 0,
            col: 0,
            mode: TextInputMode::default(),
        }
    }

    /// Set how Enter and Shift+Enter submit or insert newlines.
    pub fn set_mode(&mut self, mode: TextInputMode) {
        self.mode = mode;
    }

    /// Return the current Enter behavior.
    pub fn mode(&self) -> TextInputMode {
        self.mode
    }

    /// Apply an Enter chord according to the configured mode.
    pub fn handle_enter(&mut self, shift: bool) -> TextInputEvent {
        let submit = match self.mode {
            TextInputMode::SubmitOnEnter => !shift,
            TextInputMode::SubmitOnShiftEnter => shift,
        };
        if submit {
            TextInputEvent::Submit
        } else {
            self.newline();
            TextInputEvent::Changed
        }
    }

    /// Seed from `text`, cursor at the end.
    pub fn from_text(text: &str) -> Self {
        let mut s = Self::new();
        s.set_text(text);
        s
    }

    /// The full text, logical lines joined with `\n`.
    pub fn text(&self) -> String {
        self.lines.join("\n")
    }

    /// Whether the buffer is a single empty line.
    pub fn is_empty(&self) -> bool {
        self.lines.len() == 1 && self.lines[0].is_empty()
    }

    /// Number of logical lines.
    pub fn line_count(&self) -> usize {
        self.lines.len()
    }

    /// Cursor as `(row, col)` in logical (char-index) coordinates.
    pub fn cursor(&self) -> (usize, usize) {
        (self.row, self.col)
    }

    /// Replace all text; cursor moves to the end.
    pub fn set_text(&mut self, text: &str) {
        self.lines = text.split('\n').map(str::to_string).collect();
        if self.lines.is_empty() {
            self.lines.push(String::new());
        }
        self.row = self.lines.len() - 1;
        self.col = self.lines[self.row].chars().count();
    }

    /// Clear to a single empty line. Preserves [`TextInputMode`].
    pub fn clear(&mut self) {
        let mode = self.mode;
        *self = Self::new();
        self.mode = mode;
    }

    /// Move the cursor to `(row, col)`, clamped into the buffer. Lets a host
    /// mirror an external editor's cursor into this state for rendering.
    pub fn set_cursor(&mut self, row: usize, col: usize) {
        self.row = row.min(self.lines.len().saturating_sub(1));
        self.col = col.min(self.lines[self.row].chars().count());
    }

    fn row_chars(&self, row: usize) -> Vec<char> {
        self.lines[row].chars().collect()
    }

    fn set_row(&mut self, row: usize, chars: Vec<char>) {
        self.lines[row] = chars.into_iter().collect();
    }

    /// Insert one char at the cursor.
    pub fn insert_char(&mut self, ch: char) {
        if ch == '\n' {
            self.newline();
            return;
        }
        let mut chars = self.row_chars(self.row);
        let at = self.col.min(chars.len());
        chars.insert(at, ch);
        self.set_row(self.row, chars);
        self.col = at + 1;
    }

    /// Insert a string (honoring embedded newlines) at the cursor.
    pub fn insert_str(&mut self, s: &str) {
        for ch in s.chars() {
            self.insert_char(ch);
        }
    }

    /// Split the current line at the cursor into two lines.
    pub fn newline(&mut self) {
        let chars = self.row_chars(self.row);
        let at = self.col.min(chars.len());
        let tail: String = chars[at..].iter().collect();
        let head: String = chars[..at].iter().collect();
        self.lines[self.row] = head;
        self.lines.insert(self.row + 1, tail);
        self.row += 1;
        self.col = 0;
    }

    /// Delete the char before the cursor (joining lines at column 0).
    pub fn backspace(&mut self) {
        if self.col > 0 {
            let mut chars = self.row_chars(self.row);
            chars.remove(self.col - 1);
            self.col -= 1;
            self.set_row(self.row, chars);
        } else if self.row > 0 {
            let cur = self.lines.remove(self.row);
            self.row -= 1;
            self.col = self.lines[self.row].chars().count();
            self.lines[self.row].push_str(&cur);
        }
    }

    /// Delete the char at the cursor (joining the next line at line end).
    pub fn delete(&mut self) {
        let mut chars = self.row_chars(self.row);
        if self.col < chars.len() {
            chars.remove(self.col);
            self.set_row(self.row, chars);
        } else if self.row + 1 < self.lines.len() {
            let next = self.lines.remove(self.row + 1);
            self.lines[self.row].push_str(&next);
        }
    }

    fn clamp_col(&mut self) {
        self.col = self.col.min(self.lines[self.row].chars().count());
    }

    /// Move one char left, wrapping to the end of the previous line.
    pub fn move_left(&mut self) {
        if self.col > 0 {
            self.col -= 1;
        } else if self.row > 0 {
            self.row -= 1;
            self.col = self.lines[self.row].chars().count();
        }
    }

    /// Move one char right, wrapping to the start of the next line.
    pub fn move_right(&mut self) {
        let len = self.lines[self.row].chars().count();
        if self.col < len {
            self.col += 1;
        } else if self.row + 1 < self.lines.len() {
            self.row += 1;
            self.col = 0;
        }
    }

    /// Move to the previous line (clamping column), or to line start at the top.
    pub fn move_up(&mut self) {
        if self.row > 0 {
            self.row -= 1;
            self.clamp_col();
        } else {
            self.col = 0;
        }
    }

    /// Move to the next line (clamping column), or to line end at the bottom.
    pub fn move_down(&mut self) {
        if self.row + 1 < self.lines.len() {
            self.row += 1;
            self.clamp_col();
        } else {
            self.col = self.lines[self.row].chars().count();
        }
    }

    /// Move the cursor to the start of the current line.
    pub fn move_home(&mut self) {
        self.col = 0;
    }

    /// Move the cursor to the end of the current line.
    pub fn move_end(&mut self) {
        self.col = self.lines[self.row].chars().count();
    }

    /// The column of the previous word start on the current line: skip trailing
    /// whitespace, then the word itself. Used by word-move and word-delete.
    fn prev_word_col(&self) -> usize {
        let chars = self.row_chars(self.row);
        let mut i = self.col.min(chars.len());
        while i > 0 && chars[i - 1].is_whitespace() {
            i -= 1;
        }
        while i > 0 && !chars[i - 1].is_whitespace() {
            i -= 1;
        }
        i
    }

    /// The column of the next word end on the current line: skip leading
    /// whitespace, then the word itself.
    fn next_word_col(&self) -> usize {
        let chars = self.row_chars(self.row);
        let len = chars.len();
        let mut i = self.col.min(len);
        while i < len && chars[i].is_whitespace() {
            i += 1;
        }
        while i < len && !chars[i].is_whitespace() {
            i += 1;
        }
        i
    }

    /// Move to the previous word boundary, crossing to the prior line at col 0.
    pub fn move_word_left(&mut self) {
        if self.col == 0 {
            self.move_left();
            return;
        }
        self.col = self.prev_word_col();
    }

    /// Move to the next word boundary, crossing to the next line at line end.
    pub fn move_word_right(&mut self) {
        if self.col >= self.lines[self.row].chars().count() {
            self.move_right();
            return;
        }
        self.col = self.next_word_col();
    }

    /// Delete from the cursor back to the previous word boundary (joins the
    /// prior line when already at col 0).
    pub fn delete_word_left(&mut self) {
        if self.col == 0 {
            self.backspace();
            return;
        }
        let start = self.prev_word_col();
        let mut chars = self.row_chars(self.row);
        chars.drain(start..self.col);
        self.col = start;
        self.set_row(self.row, chars);
    }

    /// Delete from the cursor forward to the next word boundary (joins the next
    /// line when already at line end).
    pub fn delete_word_right(&mut self) {
        let len = self.lines[self.row].chars().count();
        if self.col >= len {
            self.delete();
            return;
        }
        let end = self.next_word_col();
        let mut chars = self.row_chars(self.row);
        chars.drain(self.col..end);
        self.set_row(self.row, chars);
    }

    /// Delete from the cursor to the end of the line; at line end, joins the
    /// next line (emacs `C-k`).
    pub fn kill_to_line_end(&mut self) {
        let mut chars = self.row_chars(self.row);
        if self.col < chars.len() {
            chars.truncate(self.col);
            self.set_row(self.row, chars);
        } else {
            self.delete();
        }
    }

    /// Delete from the start of the line to the cursor (emacs `C-u`).
    pub fn kill_to_line_start(&mut self) {
        let chars = self.row_chars(self.row);
        let tail: Vec<char> = chars[self.col.min(chars.len())..].to_vec();
        self.set_row(self.row, tail);
        self.col = 0;
    }

    /// Apply an input event according to the configured [`TextInputMode`].
    ///
    /// Returns [`None`] when the event is ignored; [`Some`] with
    /// [`TextInputEvent::Changed`] when the buffer or cursor changed, or
    /// [`TextInputEvent::Submit`] when the Enter chord requested submission
    /// (the buffer is left unchanged so the host can read [`Self::text`] and
    /// clear).
    ///
    /// Enter / Shift+Enter follow [`TextInputMode`]. Ctrl+J (emacs newline,
    /// and the raw-mode encoding of a bare LF that many terminals send for
    /// Shift+Enter without the kitty keyboard protocol) always inserts a
    /// newline.
    ///
    /// Beyond the plain keys, an emacs-style keymap covers the readline bindings
    /// a terminal composer is expected to honor (so the widget matches what
    /// `ratatui-textarea` gave hosts before): `C-a`/`C-e` line start/end,
    /// `C-f`/`C-b` char move, `C-p`/`C-n` line move, `C-h`/`C-d` delete,
    /// `C-j` newline, `C-k`/`C-u` kill to line end/start, `C-w`/`M-Backspace`
    /// delete word back, `M-f`/`M-b` word move, `M-d` delete word forward.
    pub fn handle(&mut self, event: &Event) -> Option<TextInputEvent> {
        match event {
            Event::Key(k) if k.ctrl && !k.alt => match k.code {
                KeyCode::Char('a') => {
                    self.move_home();
                    Some(TextInputEvent::Changed)
                }
                KeyCode::Char('e') => {
                    self.move_end();
                    Some(TextInputEvent::Changed)
                }
                KeyCode::Char('f') => {
                    self.move_right();
                    Some(TextInputEvent::Changed)
                }
                KeyCode::Char('b') => {
                    self.move_left();
                    Some(TextInputEvent::Changed)
                }
                KeyCode::Char('p') => {
                    self.move_up();
                    Some(TextInputEvent::Changed)
                }
                KeyCode::Char('n') => {
                    self.move_down();
                    Some(TextInputEvent::Changed)
                }
                KeyCode::Char('h') => {
                    self.backspace();
                    Some(TextInputEvent::Changed)
                }
                KeyCode::Char('d') => {
                    self.delete();
                    Some(TextInputEvent::Changed)
                }
                KeyCode::Char('j') => {
                    // Emacs newline; also raw-mode LF from terminals that map
                    // Shift+Enter to a bare `\n` without enhanced keyboard reporting.
                    self.newline();
                    Some(TextInputEvent::Changed)
                }
                KeyCode::Char('k') => {
                    self.kill_to_line_end();
                    Some(TextInputEvent::Changed)
                }
                KeyCode::Char('u') => {
                    self.kill_to_line_start();
                    Some(TextInputEvent::Changed)
                }
                KeyCode::Char('w') => {
                    self.delete_word_left();
                    Some(TextInputEvent::Changed)
                }
                _ => None,
            },
            Event::Key(k) if k.alt && !k.ctrl => match k.code {
                KeyCode::Char('f') => {
                    self.move_word_right();
                    Some(TextInputEvent::Changed)
                }
                KeyCode::Char('b') => {
                    self.move_word_left();
                    Some(TextInputEvent::Changed)
                }
                KeyCode::Char('d') => {
                    self.delete_word_right();
                    Some(TextInputEvent::Changed)
                }
                KeyCode::Backspace => {
                    self.delete_word_left();
                    Some(TextInputEvent::Changed)
                }
                _ => None,
            },
            Event::Key(k) if !k.ctrl && !k.alt => match k.code {
                KeyCode::Char(c) => {
                    self.insert_char(c);
                    Some(TextInputEvent::Changed)
                }
                KeyCode::Enter => Some(self.handle_enter(k.shift)),
                KeyCode::Backspace => {
                    self.backspace();
                    Some(TextInputEvent::Changed)
                }
                KeyCode::Delete => {
                    self.delete();
                    Some(TextInputEvent::Changed)
                }
                KeyCode::Left => {
                    self.move_left();
                    Some(TextInputEvent::Changed)
                }
                KeyCode::Right => {
                    self.move_right();
                    Some(TextInputEvent::Changed)
                }
                KeyCode::Up => {
                    self.move_up();
                    Some(TextInputEvent::Changed)
                }
                KeyCode::Down => {
                    self.move_down();
                    Some(TextInputEvent::Changed)
                }
                KeyCode::Home => {
                    self.move_home();
                    Some(TextInputEvent::Changed)
                }
                KeyCode::End => {
                    self.move_end();
                    Some(TextInputEvent::Changed)
                }
                _ => None,
            },
            Event::Paste(text) => {
                self.insert_str(text);
                Some(TextInputEvent::Changed)
            }
            _ => None,
        }
    }

    /// Every token in the buffer matched by any of `triggers`, in reading order.
    ///
    /// Scanning is left to right and the first trigger that matches at a
    /// position wins, so overlapping declarations resolve by their order in
    /// `triggers`.
    pub fn tokens(&self, triggers: &[Trigger]) -> Vec<Token> {
        let mut out = Vec::new();
        for (row, line) in self.lines.iter().enumerate() {
            let chars: Vec<char> = line.chars().collect();
            let mut col = 0;
            while col < chars.len() {
                let Some(trigger) = triggers
                    .iter()
                    .find(|t| t.start == chars[col] && t.anchored_at(&chars, row, col))
                else {
                    col += 1;
                    continue;
                };
                let mut end = col + 1;
                if trigger.stop_at_whitespace {
                    while end < chars.len() && !chars[end].is_whitespace() {
                        end += 1;
                    }
                } else {
                    end = chars.len();
                }
                out.push(Token {
                    trigger: trigger.start,
                    row,
                    start: col,
                    end,
                    text: chars[col..end].iter().collect(),
                });
                col = end.max(col + 1);
            }
        }
        out
    }

    /// The token the cursor is inside, if any — what a host opens a completion
    /// popup for.
    ///
    /// The cursor counts as inside from just after the trigger character
    /// through the token's end, so typing `@s` keeps the popup open and moving
    /// left onto the `@` itself closes it.
    pub fn active_token(&self, triggers: &[Trigger]) -> Option<Token> {
        self.tokens(triggers)
            .into_iter()
            .find(|t| t.row == self.row && self.col > t.start && self.col <= t.end)
    }

    /// Replace `token`'s range with `replacement`, leaving the cursor after it.
    ///
    /// This is completion: the host picked a row in its popup and hands back the
    /// text — `"@src/lib.rs "` for a file, `"/model "` for a command. The
    /// replacement is inserted verbatim, trailing space included or not, because
    /// only the host knows whether its token type wants one.
    pub fn replace_token(&mut self, token: &Token, replacement: &str) {
        let Some(line) = self.lines.get_mut(token.row) else {
            return;
        };
        let chars: Vec<char> = line.chars().collect();
        let start = token.start.min(chars.len());
        let end = token.end.min(chars.len()).max(start);
        let mut next: String = chars[..start].iter().collect();
        next.push_str(replacement);
        next.extend(chars[end..].iter());
        *line = next;
        self.row = token.row;
        self.col = start + replacement.chars().count();
    }

    /// Number of visual rows the text occupies at `width`.
    pub fn visual_height(&self, width: u16) -> u16 {
        wrap_visual_rows(&self.lines, width).len().max(1) as u16
    }

    /// The cursor's visual `(row, col)` in wrapped coordinates at `width`.
    fn visual_cursor(&self, width: u16) -> (u16, u16) {
        visual_cursor_at(&self.lines, self.row, self.col, width)
    }

    /// The visual-row scroll offset that keeps the cursor visible in a
    /// `height`-row viewport at `width`: once the text is taller than the
    /// viewport the cursor rests on the last visible row; otherwise 0. A bounded
    /// composer (see [`TextInput`]) renders and places its cursor through this.
    pub fn scroll_offset(&self, width: u16, height: u16) -> u16 {
        self.visual_cursor(width)
            .0
            .saturating_sub(height.saturating_sub(1))
    }

    /// The cursor cell in terminal coordinates, given the rendered `area`,
    /// accounting for scroll-to-cursor when the text is taller than the area.
    pub fn cursor_screen(&self, area: Rect) -> (u16, u16) {
        let (vrow, vcol) = self.visual_cursor(area.width);
        let offset = vrow.saturating_sub(area.height.saturating_sub(1));
        let x = area
            .x
            .saturating_add(vcol.min(area.width.saturating_sub(1)));
        let y = area
            .y
            .saturating_add((vrow - offset).min(area.height.saturating_sub(1)));
        (x, y)
    }
}

/// One wrapped visual row: which logical line it came from, the char index in
/// that line where it starts, and its chars.
struct VisualRow {
    logical: usize,
    start: usize,
    chars: Vec<char>,
}

/// The cursor's visual `(row, col)` for `lines` with the logical cursor at
/// `(row, col)`, word-soft-wrapped to `width`. Reuses [`wrap_visual_rows`] so the
/// rendered scroll offset and the placed cursor always agree with what's drawn.
fn visual_cursor_at(lines: &[String], row: usize, col: usize, width: u16) -> (u16, u16) {
    let rows = wrap_visual_rows(lines, width);
    let mut last_on_line: Option<(usize, usize)> = None; // (visual index, start col)
    for (vi, vr) in rows.iter().enumerate() {
        if vr.logical > row {
            break;
        }
        if vr.logical != row {
            continue;
        }
        let end = vr.start + vr.chars.len();
        last_on_line = Some((vi, vr.start));
        // A col at this row's end belongs to the next row's start, so only claim
        // it here when it falls strictly inside — except the line's last row,
        // handled below.
        if col >= vr.start && col < end {
            return (vi as u16, (col - vr.start) as u16);
        }
    }
    // Cursor at the end of the logical line: rest at the end of its last row
    // (which is an empty trailing row when the text filled the width exactly).
    if let Some((vi, start)) = last_on_line {
        return (vi as u16, col.saturating_sub(start) as u16);
    }
    (rows.len().saturating_sub(1) as u16, 0)
}

/// Word-soft-wrap `lines` to `width`: each logical line breaks at the last space
/// that fits, falling back to a hard char-break for a word longer than `width`.
/// A line whose final row fills the width exactly emits a trailing empty row so
/// the cursor can rest on a fresh line. Shared by [`visual_cursor_at`] (cursor
/// math) and [`TextInput`] (rendering) so both wrap identically.
fn wrap_visual_rows(lines: &[String], width: u16) -> Vec<VisualRow> {
    let width = width.max(1) as usize;
    let mut rows = Vec::new();
    for (r, line) in lines.iter().enumerate() {
        let chars: Vec<char> = line.chars().collect();
        if chars.is_empty() {
            rows.push(VisualRow {
                logical: r,
                start: 0,
                chars: Vec::new(),
            });
            continue;
        }
        let mut start = 0;
        let mut last_filled = false;
        while start < chars.len() {
            let remaining = chars.len() - start;
            let end = if remaining <= width {
                chars.len()
            } else {
                // Break after the last space within the width window; if the
                // window holds no space, hard-break at the width boundary.
                let hard = start + width;
                let brk = (start + 1..hard).rev().find(|&i| chars[i] == ' ');
                brk.map(|i| i + 1).unwrap_or(hard)
            };
            last_filled = end - start == width;
            rows.push(VisualRow {
                logical: r,
                start,
                chars: chars[start..end].to_vec(),
            });
            start = end;
        }
        if last_filled {
            rows.push(VisualRow {
                logical: r,
                start: chars.len(),
                chars: Vec::new(),
            });
        }
    }
    rows
}

/// Renders a snapshot of a [`TextInputState`]'s wrapped text.
///
/// Owns its lines (cloned from the state at construction, like [`Scroll`]) so it
/// is `'static` and composes into a [`view!`](crate::view!) tree. When the text
/// is taller than the render area it **scrolls to the cursor** (the cursor's
/// visual row stays on screen), so it backs a bounded composer without losing the
/// caret. The host places the terminal cursor through
/// [`TextInputState::cursor_screen`], which derives the same offset.
///
/// [`Scroll`]: crate::components::Scroll
///
/// ![textinput demo](https://raw.githubusercontent.com/everruns/tuika/main/docs/demos/textinput.gif)
pub struct TextInput {
    lines: Vec<String>,
    /// Logical cursor `(row, col)`, so a bounded render can scroll to it.
    cursor: (usize, usize),
    style: Style,
    /// Host-supplied styled ranges painted over `style`.
    highlights: Vec<TextSpan>,
    /// Shown, in its own style, while the buffer is empty.
    placeholder: Option<(String, Style)>,
}

impl TextInput {
    /// Snapshot `state`'s text and cursor for rendering.
    pub fn new(state: &TextInputState) -> Self {
        Self {
            lines: state.lines.clone(),
            cursor: (state.row, state.col),
            style: Style::default(),
            highlights: Vec::new(),
            placeholder: None,
        }
    }

    /// Set the text style applied to rendered glyphs.
    pub fn style(mut self, style: Style) -> Self {
        self.style = style;
        self
    }

    /// Paint `spans` over the base style — a mention in one color, a command in
    /// another, an unknown path struck through.
    ///
    /// The ranges are the host's to compute; [`Token::span`] turns a trigger
    /// match into one directly. Where spans overlap, the last one wins.
    ///
    /// ```
    /// use ratatui_core::style::{Color, Style};
    /// use tuika::prelude::*;
    ///
    /// let state = TextInputState::from_text("ship @docs/readme.md");
    /// let mention = Style::default().fg(Color::Cyan);
    /// let view = TextInput::new(&state).highlights(
    ///     state.tokens(&[Trigger::new('@')]).iter().map(|t| t.span(mention)).collect(),
    /// );
    /// # let _ = view;
    /// ```
    pub fn highlights(mut self, spans: Vec<TextSpan>) -> Self {
        self.highlights = spans;
        self
    }

    /// Text drawn in place of an empty buffer, in its own style.
    ///
    /// The cursor still sits at the start of the input, so the host places it
    /// through [`TextInputState::cursor_screen`] exactly as when there is text.
    pub fn placeholder(mut self, text: impl Into<String>, style: Style) -> Self {
        self.placeholder = Some((text.into(), style));
        self
    }

    /// Style for the char at `(row, col)`: the base, patched by every covering
    /// highlight in order.
    fn style_at(&self, row: usize, col: usize) -> Style {
        self.highlights
            .iter()
            .filter(|span| span.covers(row, col))
            .fold(self.style, |style, span| style.patch(span.style))
    }

    /// Whether the buffer is a single empty line (so the placeholder shows).
    fn is_empty(&self) -> bool {
        self.lines.len() == 1 && self.lines[0].is_empty()
    }

    /// Visual-row offset that keeps the cursor on screen in `height` rows.
    fn scroll_offset(&self, width: u16, height: u16) -> u16 {
        visual_cursor_at(&self.lines, self.cursor.0, self.cursor.1, width)
            .0
            .saturating_sub(height.saturating_sub(1))
    }
}

impl View for TextInput {
    fn measure(&self, available: Size) -> Size {
        let height = wrap_visual_rows(&self.lines, available.width).len().max(1) as u16;
        Size::new(available.width, height)
    }

    fn render(&self, area: Rect, surface: &mut Surface, _ctx: &RenderCtx) {
        if area.width == 0 || area.height == 0 {
            return;
        }
        if let Some((text, style)) = &self.placeholder
            && self.is_empty()
        {
            surface.set_string(area.x, area.y, text, *style);
            return;
        }
        let offset = self.scroll_offset(area.width, area.height) as usize;
        for (i, vr) in wrap_visual_rows(&self.lines, area.width)
            .into_iter()
            .enumerate()
            .skip(offset)
        {
            let y = area.y.saturating_add((i - offset) as u16);
            if y >= area.bottom() {
                break;
            }
            let mut x = area.x;
            for (n, ch) in vr.chars.into_iter().enumerate() {
                let w = UnicodeWidthChar::width(ch).unwrap_or(0) as u16;
                if w == 0 || x >= area.right() {
                    continue;
                }
                surface.set(x, y, ch, self.style_at(vr.logical, vr.start + n));
                x = x.saturating_add(w);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::event::{Event, Key, KeyCode};
    use crate::style::Theme;
    use crate::surface::Surface;
    use crate::tests::support::{buffer, render_el, render_view_rows};
    use crate::view::{RenderCtx, element};
    use ratatui_core::layout::Rect;
    use ratatui_core::style::Color;

    fn press(state: &mut TextInputState, code: KeyCode) -> bool {
        matches!(
            state.handle(&Event::Key(Key::new(code))),
            Some(TextInputEvent::Changed)
        )
    }

    fn press_shift(state: &mut TextInputState, code: KeyCode) -> bool {
        matches!(
            state.handle(&Event::Key(Key {
                code,
                ctrl: false,
                alt: false,
                shift: true,
            })),
            Some(TextInputEvent::Changed)
        )
    }

    fn press_ctrl(state: &mut TextInputState, code: KeyCode) -> bool {
        matches!(
            state.handle(&Event::Key(Key {
                code,
                ctrl: true,
                alt: false,
                shift: false,
            })),
            Some(TextInputEvent::Changed)
        )
    }

    fn press_alt(state: &mut TextInputState, code: KeyCode) -> bool {
        matches!(
            state.handle(&Event::Key(Key {
                code,
                ctrl: false,
                alt: true,
                shift: false,
            })),
            Some(TextInputEvent::Changed)
        )
    }

    fn type_str(state: &mut TextInputState, s: &str) {
        for ch in s.chars() {
            assert!(press(state, KeyCode::Char(ch)));
        }
    }

    #[test]
    fn text_input_starts_empty() {
        let state = TextInputState::new();
        assert!(state.is_empty());
        assert_eq!(state.text(), "");
        assert_eq!(state.cursor(), (0, 0));
        assert_eq!(state.line_count(), 1);
    }

    #[test]
    fn text_input_types_and_edits() {
        let mut state = TextInputState::new();
        type_str(&mut state, "helo");
        assert_eq!(state.text(), "helo");
        assert_eq!(state.cursor(), (0, 4));

        // Move back and insert the missing 'l' → "hello".
        press(&mut state, KeyCode::Left);
        press(&mut state, KeyCode::Left);
        assert_eq!(state.cursor(), (0, 2));
        assert!(press(&mut state, KeyCode::Char('l')));
        assert_eq!(state.text(), "hello");
        assert_eq!(state.cursor(), (0, 3));
    }

    #[test]
    fn text_input_backspace_and_delete() {
        let mut state = TextInputState::from_text("abc");
        assert_eq!(state.cursor(), (0, 3));
        press(&mut state, KeyCode::Backspace);
        assert_eq!(state.text(), "ab");
        press(&mut state, KeyCode::Home);
        press(&mut state, KeyCode::Delete);
        assert_eq!(state.text(), "b");
        assert_eq!(state.cursor(), (0, 0));
    }

    #[test]
    fn text_input_newline_splits_and_backspace_joins() {
        let mut state = TextInputState::from_text("abcd");
        press(&mut state, KeyCode::Home);
        press(&mut state, KeyCode::Right);
        press(&mut state, KeyCode::Right);
        assert_eq!(state.cursor(), (0, 2));
        // Default mode submits on Enter; Shift+Enter inserts the newline.
        assert!(press_shift(&mut state, KeyCode::Enter));
        assert_eq!(state.text(), "ab\ncd");
        assert_eq!(state.line_count(), 2);
        assert_eq!(state.cursor(), (1, 0));

        // Backspace at column 0 rejoins the two logical lines.
        press(&mut state, KeyCode::Backspace);
        assert_eq!(state.text(), "abcd");
        assert_eq!(state.cursor(), (0, 2));
        assert_eq!(state.line_count(), 1);
    }

    #[test]
    fn text_input_vertical_movement_clamps_column() {
        let mut state = TextInputState::from_text("longline\nhi");
        // Cursor is at end of "hi" (row 1, col 2). Move up onto the longer line:
        // column is preserved (2), not clamped, because "longline" is longer.
        press(&mut state, KeyCode::Up);
        assert_eq!(state.cursor(), (0, 2));
        // From end of "longline" move down — clamps onto the shorter "hi".
        press(&mut state, KeyCode::End);
        assert_eq!(state.cursor(), (0, 8));
        press(&mut state, KeyCode::Down);
        assert_eq!(state.cursor(), (1, 2));
    }

    #[test]
    fn text_input_paste_inserts_multiline() {
        let mut state = TextInputState::new();
        assert_eq!(
            state.handle(&Event::Paste("one\ntwo".to_string())),
            Some(TextInputEvent::Changed)
        );
        assert_eq!(state.text(), "one\ntwo");
        assert_eq!(state.line_count(), 2);
        assert_eq!(state.cursor(), (1, 3));
    }

    #[test]
    fn text_input_unbound_ctrl_keys_ignored() {
        // A ctrl combo with no binding (C-z) is a no-op the host can repurpose.
        let mut state = TextInputState::from_text("x");
        assert!(!press_ctrl(&mut state, KeyCode::Char('z')));
        assert_eq!(state.text(), "x");
    }

    #[test]
    fn text_input_emacs_cursor_bindings() {
        let mut state = TextInputState::from_text("hello");
        // C-a → line start, C-e → line end, C-f/C-b → char right/left.
        assert!(press_ctrl(&mut state, KeyCode::Char('a')));
        assert_eq!(state.cursor(), (0, 0));
        assert!(press_ctrl(&mut state, KeyCode::Char('f')));
        assert_eq!(state.cursor(), (0, 1));
        assert!(press_ctrl(&mut state, KeyCode::Char('e')));
        assert_eq!(state.cursor(), (0, 5));
        assert!(press_ctrl(&mut state, KeyCode::Char('b')));
        assert_eq!(state.cursor(), (0, 4));

        // C-p / C-n move between logical lines.
        state = TextInputState::from_text("ab\ncd");
        press(&mut state, KeyCode::Home);
        assert!(press_ctrl(&mut state, KeyCode::Char('p')));
        assert_eq!(state.cursor(), (0, 0));
        assert!(press_ctrl(&mut state, KeyCode::Char('n')));
        assert_eq!(state.cursor(), (1, 0));
    }

    #[test]
    fn text_input_emacs_delete_bindings() {
        // C-h backspaces, C-d deletes forward.
        let mut state = TextInputState::from_text("abc");
        assert!(press_ctrl(&mut state, KeyCode::Char('h')));
        assert_eq!(state.text(), "ab");
        press(&mut state, KeyCode::Home);
        assert!(press_ctrl(&mut state, KeyCode::Char('d')));
        assert_eq!(state.text(), "b");
    }

    #[test]
    fn text_input_kill_to_line_end_and_start() {
        // C-k kills from the cursor to end of line.
        let mut state = TextInputState::from_text("hello world");
        press(&mut state, KeyCode::Home);
        press(&mut state, KeyCode::Right);
        press(&mut state, KeyCode::Right);
        press(&mut state, KeyCode::Right);
        press(&mut state, KeyCode::Right);
        press(&mut state, KeyCode::Right); // cursor after "hello"
        assert!(press_ctrl(&mut state, KeyCode::Char('k')));
        assert_eq!(state.text(), "hello");
        assert_eq!(state.cursor(), (0, 5));

        // C-k at line end joins the next line.
        let mut state = TextInputState::from_text("ab\ncd");
        press(&mut state, KeyCode::Home);
        press(&mut state, KeyCode::Up);
        press(&mut state, KeyCode::End);
        assert!(press_ctrl(&mut state, KeyCode::Char('k')));
        assert_eq!(state.text(), "abcd");

        // C-u kills from line start to the cursor.
        let mut state = TextInputState::from_text("hello world");
        assert!(press_ctrl(&mut state, KeyCode::Char('u')));
        assert_eq!(state.text(), "");
        assert_eq!(state.cursor(), (0, 0));
    }

    #[test]
    fn text_input_word_move_and_delete() {
        // M-b / M-f jump by word; C-w / M-d delete a word back / forward.
        let mut state = TextInputState::from_text("foo bar baz");
        assert!(press_alt(&mut state, KeyCode::Char('b')));
        assert_eq!(state.cursor(), (0, 8)); // start of "baz"
        assert!(press_alt(&mut state, KeyCode::Char('b')));
        assert_eq!(state.cursor(), (0, 4)); // start of "bar"

        // C-w at the start of "bar" deletes the previous word "foo ".
        assert!(press_ctrl(&mut state, KeyCode::Char('w')));
        assert_eq!(state.text(), "bar baz");
        assert_eq!(state.cursor(), (0, 0));

        // M-f to the end of "bar", then M-d deletes the next word " baz".
        assert!(press_alt(&mut state, KeyCode::Char('f')));
        assert_eq!(state.cursor(), (0, 3)); // end of "bar"
        assert!(press_alt(&mut state, KeyCode::Char('d')));
        assert_eq!(state.text(), "bar");

        // M-Backspace deletes the previous word too.
        let mut state = TextInputState::from_text("alpha beta");
        assert!(press_alt(&mut state, KeyCode::Backspace));
        assert_eq!(state.text(), "alpha ");
    }

    #[test]
    fn text_input_scrolls_to_cursor_when_taller_than_area() {
        // 10 single-row lines; cursor at the end (line 9).
        let mut state = TextInputState::new();
        for i in 0..10 {
            type_str(&mut state, &format!("line{i}"));
            if i < 9 {
                state.newline();
            }
        }
        // A 3-row viewport shows the last three rows (containing the cursor), not the
        // top — the composer scrolls to the caret.
        let out = render_view_rows(&TextInput::new(&state), 10, 3);
        assert_eq!(out, vec!["line7", "line8", "line9"]);
        // The placed cursor sits on the last visible row, consistent with the scroll.
        let (_, y) = state.cursor_screen(Rect::new(0, 0, 10, 3));
        assert_eq!(y, 2);
        // Move to the top: the viewport follows the cursor back up.
        for _ in 0..9 {
            state.move_up();
        }
        let out = render_view_rows(&TextInput::new(&state), 10, 3);
        assert_eq!(out, vec!["line0", "line1", "line2"]);
        assert_eq!(state.cursor_screen(Rect::new(0, 0, 10, 3)).1, 0);
    }

    #[test]
    fn text_input_renders_wrapped_rows() {
        let mut state = TextInputState::new();
        type_str(&mut state, "abcdef");
        // Width 4 wraps "abcdef" onto two visual rows: "abcd" / "ef".
        assert_eq!(state.visual_height(4), 2);
        let out = render_view_rows(&TextInput::new(&state), 4, 2);
        assert_eq!(out[0], "abcd");
        assert_eq!(out[1], "ef");
    }

    #[test]
    fn text_input_word_wraps_at_spaces() {
        let mut state = TextInputState::new();
        type_str(&mut state, "hello world foo");
        // Width 8 breaks at the last space that fits, not mid-word: "hello " then
        // "world " then "foo".
        assert_eq!(state.visual_height(8), 3);
        let out = render_view_rows(&TextInput::new(&state), 8, 3);
        assert_eq!(out[0], "hello");
        assert_eq!(out[1], "world");
        assert_eq!(out[2], "foo");
    }

    #[test]
    fn text_input_hard_breaks_overlong_word() {
        let mut state = TextInputState::new();
        type_str(&mut state, "abcdefghij");
        // A single word longer than the width still hard-breaks so it fits.
        assert_eq!(state.visual_height(4), 3);
        let out = render_view_rows(&TextInput::new(&state), 4, 3);
        assert_eq!(out[0], "abcd");
        assert_eq!(out[1], "efgh");
        assert_eq!(out[2], "ij");
    }

    #[test]
    fn text_input_cursor_tracks_word_wrap() {
        let mut state = TextInputState::from_text("hello world");
        // Cursor at end (col 11). Width 8 → "hello " / "world"; cursor sits after
        // "world" on the second visual row at col 5.
        let area = Rect::new(0, 0, 8, 3);
        assert_eq!(state.cursor_screen(area), (5, 1));
        // Move to just after the space (col 6, start of "world") → row 1, col 0.
        state.move_home();
        for _ in 0..6 {
            state.move_right();
        }
        assert_eq!(state.cursor_screen(area), (0, 1));
    }

    #[test]
    fn text_input_cursor_screen_follows_wrap() {
        let mut state = TextInputState::new();
        type_str(&mut state, "abcd");
        // At width 4 the line fills exactly, so the cursor rests on a fresh row.
        assert_eq!(state.visual_height(4), 2);
        let area = Rect::new(2, 1, 4, 3);
        // Cursor after "abcd" → visual row 1, col 0, offset by area origin.
        assert_eq!(state.cursor_screen(area), (2, 2));
        // Move home → back to the first visual row.
        press(&mut state, KeyCode::Home);
        assert_eq!(state.cursor_screen(area), (2, 1));
    }

    #[test]
    fn text_input_set_and_clear() {
        let mut state = TextInputState::new();
        state.set_text("hello\nworld");
        assert_eq!(state.cursor(), (1, 5));
        assert_eq!(state.line_count(), 2);
        state.clear();
        assert!(state.is_empty());
        assert_eq!(state.cursor(), (0, 0));
    }

    #[test]
    fn text_input_set_cursor_clamps() {
        let mut state = TextInputState::from_text("hi\nthere");
        state.set_cursor(0, 1);
        assert_eq!(state.cursor(), (0, 1));
        // Row past the end clamps to the last line; col past its end clamps too.
        state.set_cursor(9, 9);
        assert_eq!(state.cursor(), (1, 5));
    }

    #[test]
    fn text_input_composes_into_view_tree() {
        // Owning its snapshot makes TextInput `'static`, so it splices into a
        // `view!` tree via `element(...)` — the property the fullscreen composer
        // relies on.
        let mut state = TextInputState::new();
        type_str(&mut state, "hi");
        let tree = element(TextInput::new(&state));
        let out = render_el(&tree, 4, 1);
        assert_eq!(out[0], "hi");
    }

    #[test]
    fn submit_on_enter_mode_uses_shift_enter_for_newline() {
        let mut state = TextInputState::new();
        assert_eq!(state.mode(), TextInputMode::SubmitOnEnter);
        assert_eq!(state.handle_enter(false), TextInputEvent::Submit);
        assert_eq!(state.handle_enter(true), TextInputEvent::Changed);
        assert_eq!(state.text(), "\n");
    }

    #[test]
    fn submit_on_shift_enter_mode_reverses_enter_chords() {
        let mut state = TextInputState::new();
        state.set_mode(TextInputMode::SubmitOnShiftEnter);
        assert_eq!(state.handle_enter(false), TextInputEvent::Changed);
        assert_eq!(state.handle_enter(true), TextInputEvent::Submit);
        assert_eq!(state.text(), "\n");
    }

    /// Reproduction: hosts that feed every key through [`TextInputState::handle`]
    /// (the natural component API) must still honor [`TextInputMode`]. Shift+Enter
    /// in the default `SubmitOnEnter` mode has to insert a newline — not submit,
    /// and not be ignored — without the host special-casing Enter.
    #[test]
    fn handle_honors_submit_on_enter_mode_for_shift_enter_newline() {
        let mut state = TextInputState::new();
        assert_eq!(state.mode(), TextInputMode::SubmitOnEnter);
        type_str(&mut state, "one");
        let shift_enter = Event::Key(Key {
            code: KeyCode::Enter,
            ctrl: false,
            alt: false,
            shift: true,
        });
        assert_eq!(
            state.handle(&shift_enter),
            Some(TextInputEvent::Changed),
            "Shift+Enter must insert a newline under SubmitOnEnter"
        );
        assert_eq!(state.text(), "one\n");
        type_str(&mut state, "two");
        assert_eq!(
            state.handle(&Event::Key(Key::new(KeyCode::Enter))),
            Some(TextInputEvent::Submit),
            "plain Enter must submit under SubmitOnEnter, not insert another newline"
        );
        assert_eq!(
            state.text(),
            "one\ntwo",
            "submit must leave the draft text intact"
        );
    }

    #[test]
    fn handle_honors_submit_on_shift_enter_mode() {
        let mut state = TextInputState::new();
        state.set_mode(TextInputMode::SubmitOnShiftEnter);
        type_str(&mut state, "one");
        assert_eq!(
            state.handle(&Event::Key(Key::new(KeyCode::Enter))),
            Some(TextInputEvent::Changed)
        );
        assert_eq!(state.text(), "one\n");
        type_str(&mut state, "two");
        let shift_enter = Event::Key(Key {
            code: KeyCode::Enter,
            ctrl: false,
            alt: false,
            shift: true,
        });
        assert_eq!(state.handle(&shift_enter), Some(TextInputEvent::Submit));
        assert_eq!(state.text(), "one\ntwo");
    }

    #[test]
    fn clear_preserves_enter_mode() {
        let mut state = TextInputState::new();
        state.set_mode(TextInputMode::SubmitOnShiftEnter);
        type_str(&mut state, "draft");
        state.clear();
        assert!(state.is_empty());
        assert_eq!(state.mode(), TextInputMode::SubmitOnShiftEnter);
    }

    /// Many terminals (VS Code / Cursor integrated terminal, classic xterm with
    /// no kitty keyboard protocol) encode Shift+Enter as a bare LF byte. In raw
    /// mode crossterm surfaces that as Ctrl+J — emacs newline — which must insert
    /// a newline rather than being ignored.
    #[test]
    fn handle_ctrl_j_inserts_newline() {
        let mut state = TextInputState::new();
        type_str(&mut state, "ab");
        assert!(press_ctrl(&mut state, KeyCode::Char('j')));
        assert_eq!(state.text(), "ab\n");
        assert_eq!(state.cursor(), (1, 0));
    }

    // -- triggers, tokens, and highlighting ---------------------------------

    #[test]
    fn tokens_respect_each_trigger_anchor() {
        let state = TextInputState::from_text("/model gpt\nsee @src/lib.rs and me@example.com");
        let triggers = [
            Trigger::new('/').anchor(TriggerAnchor::BufferStart),
            Trigger::new('@'),
        ];
        let found = state.tokens(&triggers);
        // `/` counts only as the buffer's first char; `@` only at a word start,
        // so the address's `@` is not a mention.
        assert_eq!(found.len(), 2);
        assert_eq!((found[0].trigger, found[0].text.as_str()), ('/', "/model"));
        assert_eq!(
            (found[1].trigger, found[1].text.as_str(), found[1].row),
            ('@', "@src/lib.rs", 1)
        );
    }

    #[test]
    fn a_trigger_can_span_a_query_with_spaces() {
        let state = TextInputState::from_text("/model gpt 5");
        let to_end = [Trigger::new('/')
            .anchor(TriggerAnchor::BufferStart)
            .to_line_end()];
        let tokens = state.tokens(&to_end);
        assert_eq!(tokens[0].text, "/model gpt 5");
        assert_eq!(tokens[0].query(), "model gpt 5");
    }

    #[test]
    fn active_token_follows_the_cursor() {
        let mut state = TextInputState::from_text("ship @doc");
        let triggers = [Trigger::new('@')];
        // Cursor at the end, inside the mention.
        assert_eq!(state.active_token(&triggers).unwrap().query(), "doc");

        // Moving onto the `@` itself leaves the token: a popup would close.
        state.set_cursor(0, 5);
        assert!(state.active_token(&triggers).is_none());

        // Just after the trigger, with nothing typed yet, is still inside it.
        state.set_cursor(0, 6);
        assert_eq!(state.active_token(&triggers).unwrap().query(), "doc");
    }

    #[test]
    fn replace_token_completes_in_place() {
        let mut state = TextInputState::from_text("ship @doc now");
        state.set_cursor(0, 9);
        let token = state.active_token(&[Trigger::new('@')]).unwrap();
        state.replace_token(&token, "@docs/readme.md");
        assert_eq!(state.text(), "ship @docs/readme.md now");
        // Cursor lands after the replacement, ready to keep typing.
        assert_eq!(state.cursor(), (0, 20));
    }

    #[test]
    fn highlights_style_only_their_range() {
        let state = TextInputState::from_text("hi @you");
        let mention = Style::default().fg(Color::Blue);
        let spans: Vec<TextSpan> = state
            .tokens(&[Trigger::new('@')])
            .iter()
            .map(|t| t.span(mention))
            .collect();
        let view = TextInput::new(&state)
            .style(Style::default().fg(Color::White))
            .highlights(spans);

        let theme = Theme::default();
        let mut buf = buffer(8, 1);
        let area = buf.area;
        let ctx = RenderCtx::new(&theme);
        view.render(area, &mut Surface::new(&mut buf, area), &ctx);
        assert_eq!(buf[(0, 0)].fg, Color::White); // 'h'
        assert_eq!(buf[(3, 0)].fg, Color::Blue); // '@'
        assert_eq!(buf[(6, 0)].fg, Color::Blue); // 'u'
    }

    #[test]
    fn placeholder_shows_only_while_empty() {
        let mut state = TextInputState::new();
        let dim = Style::default().fg(Color::DarkGray);
        let rows = render_view_rows(
            &TextInput::new(&state).placeholder("Ask me something", dim),
            18,
            1,
        );
        assert_eq!(rows[0].trim_end(), "Ask me something");

        state.insert_char('x');
        let rows = render_view_rows(
            &TextInput::new(&state).placeholder("Ask me something", dim),
            18,
            1,
        );
        assert_eq!(rows[0].trim_end(), "x");
    }
}