copyrat 0.8.3

A tmux plugin for copy-pasting within tmux panes.
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
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
use std::char;
use std::cmp;
use std::collections::BTreeSet;
use std::io;
use std::io::Write;

use termion::{self, color, cursor, event, screen::IntoAlternateScreen, style};
use unicode_width::UnicodeWidthChar;

use super::colors::UiColors;
use super::Selection;
use super::{HintAlignment, HintStyle};
use crate::{config::extended::OutputDestination, textbuf};

/// Describes where a line from the buffer is displayed on the screen and how
/// much vertical lines it takes.
///
/// The `pos_y` field is the actual vertical position due to wrapped lines
/// before this line. The `size` field is the number of screen lines occupied
/// by this line.
///
/// For example, given a buffer in which
///
/// - the first line is smaller than the screen width,
/// - the second line is slightly larger,
/// - and the third line is smaller than the screen width,
///
/// The corresponding `WrappedLine`s are
///
/// - the first `WrappedLine` has `pos_y: 0` and `size: 1`
/// - the second `WrappedLine` has `pos_y: 1` and `size: 2` (larger than screen
///   width)
/// - the third `WrappedLine` has `pos_y: 3` and `size: 1`
///
struct WrappedLine {
    pos_y: usize,
}

/// Manages the visible portion of content when total content exceeds terminal height.
///
/// The viewport tracks which rows of the wrapped content are currently visible
/// and provides methods for scrolling and coordinate translation.
struct Viewport {
    /// First visible row in wrapped content space (0-indexed).
    top_row: usize,
    /// Terminal height (number of visible rows).
    height: usize,
}

impl Viewport {
    /// Create a new viewport with the given terminal height.
    fn new(height: usize) -> Self {
        Viewport { top_row: 0, height }
    }

    /// Check if a content row is within the visible viewport.
    fn is_visible(&self, content_row: usize) -> bool {
        content_row >= self.top_row && content_row < self.top_row + self.height
    }

    /// Convert a content row to screen Y coordinate (1-indexed for termion).
    /// Returns None if the row is not visible.
    fn screen_y(&self, content_row: usize) -> Option<u16> {
        if self.is_visible(content_row) {
            Some((content_row - self.top_row + 1) as u16)
        } else {
            None
        }
    }

    /// Scroll the viewport to make a content row visible.
    /// Returns true if scrolling occurred.
    fn ensure_visible(&mut self, content_row: usize) -> bool {
        if content_row < self.top_row {
            // Row is above viewport, scroll up
            self.top_row = content_row;
            true
        } else if content_row >= self.top_row + self.height {
            // Row is below viewport, scroll down
            self.top_row = content_row - self.height + 1;
            true
        } else {
            false
        }
    }

    /// Scroll up by the given number of lines.
    ///
    /// Returns `true` if scrolling occurred, `false` if already at top.
    fn scroll_up(&mut self, lines: usize) -> bool {
        if self.top_row > 0 {
            self.top_row = self.top_row.saturating_sub(lines);
            true
        } else {
            false
        }
    }

    /// Scroll down by the given number of lines.
    ///
    /// Returns `true` if scrolling occurred, `false` if already at bottom.
    fn scroll_down(&mut self, lines: usize, max_content_height: usize) -> bool {
        let max_top = max_content_height.saturating_sub(self.height);
        if self.top_row < max_top {
            self.top_row = cmp::min(self.top_row + lines, max_top);
            true
        } else {
            false
        }
    }
}

/// Configuration for multi-select mode.
pub struct MultiSelectConfig {
    pub enabled: bool,
    pub separator: String,
}

pub struct ViewController<'a> {
    model: &'a textbuf::Model<'a>,
    term_width: u16,
    term_height: u16,
    wrapped_lines: Vec<WrappedLine>,
    total_content_height: usize,
    viewport: Viewport,
    focus_index: usize,
    focus_wrap_around: bool,
    default_output_destination: OutputDestination,
    rendering_colors: &'a UiColors,
    hint_alignment: &'a HintAlignment,
    hint_style: Option<HintStyle>,
    multi_select: MultiSelectConfig,
    /// BTreeSet preserves index order, ensuring joined output matches document order.
    selected_indices: BTreeSet<usize>,
}

impl<'a> ViewController<'a> {
    // Initialize {{{1

    pub fn new(
        model: &'a textbuf::Model<'a>,
        focus_wrap_around: bool,
        default_output_destination: &OutputDestination,
        rendering_colors: &'a UiColors,
        hint_alignment: &'a HintAlignment,
        hint_style: Option<HintStyle>,
        multi_select: MultiSelectConfig,
    ) -> ViewController<'a> {
        let focus_index = if model.reverse {
            model.spans.len().saturating_sub(1)
        } else {
            0
        };

        let (term_width, term_height) = termion::terminal_size().unwrap_or((80u16, 30u16));
        let wrapped_lines = compute_wrapped_lines(model.lines, term_width);

        // Compute total content height from wrapped lines
        let total_content_height = if wrapped_lines.is_empty() {
            0
        } else {
            // Last line's pos_y + 1 (for that line itself)
            // We need to account for the last line's wrapping too
            let last_idx = wrapped_lines.len() - 1;
            let last_line = model.lines.get(last_idx).unwrap_or(&"");
            let last_line_width = display_width(last_line.trim_end(), DEFAULT_TAB_WIDTH);
            let last_line_extra =
                cmp::max(0, last_line_width as isize - 1) as usize / term_width as usize;
            wrapped_lines[last_idx].pos_y + 1 + last_line_extra
        };

        let viewport = Viewport::new(term_height as usize);

        // Auto-scroll to the initially focused span
        let mut vc = ViewController {
            model,
            term_width,
            term_height,
            wrapped_lines,
            total_content_height,
            viewport,
            focus_index,
            focus_wrap_around,
            default_output_destination: default_output_destination.clone(),
            rendering_colors,
            hint_alignment,
            hint_style,
            multi_select,
            selected_indices: BTreeSet::new(),
        };

        // Scroll to make the initially focused span visible
        if !model.spans.is_empty() {
            let content_row = vc.span_content_row(&model.spans[focus_index]);
            vc.viewport.ensure_visible(content_row);
        }

        vc
    }

    // }}}
    // Coordinates {{{1

    /// Returns the adjusted position of a given `Span` within the buffer
    /// line.
    ///
    /// This adjustment is necessary because the span's x coordinate is a byte
    /// offset, but we need the display column. The display column accounts for:
    /// - Tab expansion to tab stops (multiples of 8 columns)
    /// - Unicode character widths (combining chars, wide CJK chars, etc.)
    ///
    /// This computation must happen before mapping the span position to the
    /// wrapped screen space.
    fn adjusted_span_position(&self, span: &textbuf::Span<'a>) -> (usize, usize) {
        let pos_x = {
            let line = &self.model.lines[span.y as usize];
            let prefix = &line[0..span.x as usize];
            display_width(prefix, DEFAULT_TAB_WIDTH)
        };
        let pos_y = span.y as usize;

        (pos_x, pos_y)
    }

    /// Convert the `Span` text into the coordinates of the wrapped lines.
    ///
    /// Compute the new x position of the text as the remainder of the line width
    /// (e.g. the Span could start at position 120 in a 80-width terminal, the new
    /// position being 40).
    ///
    /// Compute the new y position of the text as the initial y position plus any
    /// additional offset due to previous split lines. This is obtained thanks to
    /// the `wrapped_lines` field.
    fn map_coords_to_wrapped_space(&self, pos_x: usize, pos_y: usize) -> (usize, usize) {
        let line_width = self.term_width as usize;

        let new_pos_x = pos_x % line_width;
        let new_pos_y = self.wrapped_lines[pos_y].pos_y + pos_x / line_width;

        (new_pos_x, new_pos_y)
    }

    /// Returns the content row (in wrapped space) where a span is located.
    fn span_content_row(&self, span: &textbuf::Span<'a>) -> usize {
        let (pos_x, pos_y) = self.adjusted_span_position(span);
        let (_, content_row) = self.map_coords_to_wrapped_space(pos_x, pos_y);
        content_row
    }

    // }}}
    // Focus management {{{1

    /// Move focus onto the previous hint, returning both the index of the
    /// previously focused Span, and the index of the newly focused one.
    fn prev_focus_index(&mut self) -> (usize, usize) {
        let old_index = self.focus_index;
        if self.focus_wrap_around {
            if self.focus_index == 0 {
                self.focus_index = self.model.spans.len() - 1;
            } else {
                self.focus_index -= 1;
            }
        } else if self.focus_index > 0 {
            self.focus_index -= 1;
        }
        let new_index = self.focus_index;
        (old_index, new_index)
    }

    /// Move focus onto the next hint, returning both the index of the
    /// previously focused Span, and the index of the newly focused one.
    fn next_focus_index(&mut self) -> (usize, usize) {
        let old_index = self.focus_index;
        if self.focus_wrap_around {
            if self.focus_index == self.model.spans.len() - 1 {
                self.focus_index = 0;
            } else {
                self.focus_index += 1;
            }
        } else if self.focus_index < self.model.spans.len() - 1 {
            self.focus_index += 1;
        }
        let new_index = self.focus_index;
        (old_index, new_index)
    }

    /// Handle focus change with scrolling. Returns true if a full render is needed.
    fn handle_focus_change(
        &mut self,
        old_index: usize,
        new_index: usize,
        writer: &mut dyn io::Write,
    ) {
        // Check if the new focused span is visible
        let content_row = self.span_content_row(&self.model.spans[new_index]);
        let scrolled = self.viewport.ensure_visible(content_row);

        if scrolled {
            // Viewport changed, need full render
            self.full_render(writer);
        } else {
            // Viewport didn't change, efficient diff render
            self.diff_render(writer, old_index, new_index);
        }
    }

    // }}}
    // Rendering {{{1

    /// Render entire model lines on provided writer, respecting viewport bounds.
    ///
    /// This renders the basic content on which spans and hints can be rendered.
    ///
    /// # Notes
    /// - All trailing whitespaces are trimmed, empty lines are skipped.
    /// - Only content within the viewport is rendered.
    /// - Long lines that wrap are handled correctly across viewport boundaries.
    /// - This writes directly on the writer, avoiding extra allocation.
    fn render_base_text(
        stdout: &mut dyn io::Write,
        lines: &[&str],
        wrapped_lines: &[WrappedLine],
        colors: &UiColors,
        viewport: &Viewport,
        term_width: u16,
    ) {
        write!(
            stdout,
            "{bg_color}{fg_color}",
            fg_color = color::Fg(colors.text_fg),
            bg_color = color::Bg(colors.text_bg),
        )
        .unwrap();

        let line_width = term_width as usize;

        for (line_index, line) in lines.iter().enumerate() {
            let trimmed_line = line.trim_end();

            if trimmed_line.is_empty() {
                continue;
            }

            let base_content_row = wrapped_lines[line_index].pos_y;
            let line_display_width = display_width(trimmed_line, DEFAULT_TAB_WIDTH);
            let num_wrapped_rows = if line_display_width == 0 {
                1
            } else {
                line_display_width.div_ceil(line_width)
            };

            // Check if any part of this line is visible
            let line_end_row = base_content_row + num_wrapped_rows - 1;
            if line_end_row < viewport.top_row
                || base_content_row >= viewport.top_row + viewport.height
            {
                continue; // Line is entirely outside viewport
            }

            // For each sub-row of this potentially wrapped line
            for sub_row in 0..num_wrapped_rows {
                let content_row = base_content_row + sub_row;
                if let Some(screen_y) = viewport.screen_y(content_row) {
                    // Calculate which portion of the line to render for this sub-row
                    // We need to find the character offset for this sub-row
                    let start_col = sub_row * line_width;
                    let end_col = start_col + line_width;

                    // Extract the substring for this sub-row by iterating through display widths
                    let mut col = 0;
                    let mut char_start: Option<usize> = None;
                    let mut char_end = trimmed_line.len();

                    for (byte_idx, ch) in trimmed_line.char_indices() {
                        // Set char_start when we reach or pass start_col
                        if char_start.is_none() && col >= start_col {
                            char_start = Some(byte_idx);
                        }

                        let ch_width = if ch == '\t' {
                            ((col / DEFAULT_TAB_WIDTH) + 1) * DEFAULT_TAB_WIDTH - col
                        } else {
                            ch.width().unwrap_or(0)
                        };
                        col += ch_width;

                        // Set char_end when we pass end_col
                        if col > end_col {
                            char_end = byte_idx;
                            break;
                        }
                    }

                    let char_start = char_start.unwrap_or(0);
                    let sub_text = &trimmed_line[char_start..char_end];
                    if !sub_text.is_empty() {
                        write!(
                            stdout,
                            "{goto}{text}",
                            goto = cursor::Goto(1, screen_y),
                            text = sub_text,
                        )
                        .unwrap();
                    }
                }
            }
        }

        write!(
            stdout,
            "{fg_reset}{bg_reset}",
            fg_reset = color::Fg(color::Reset),
            bg_reset = color::Bg(color::Reset),
        )
        .unwrap();
    }

    /// Render the Span's `text` field on provided writer using the `span_*g` color.
    ///
    /// If a Mach is "focused", it is then rendered with the `focused_*g` colors.
    ///
    /// # Arguments
    /// - `pos` is (x_in_content_space, screen_y) where screen_y is 1-indexed
    ///
    /// # Note
    ///
    /// This writes directly on the writer, avoiding extra allocation.
    fn render_span_text(
        stdout: &mut dyn io::Write,
        text: &str,
        state: SpanState,
        pos: (usize, u16),
        colors: &UiColors,
    ) {
        let (fg_color, bg_color) = match state {
            SpanState::Focused => (&colors.focused_fg, &colors.focused_bg),
            SpanState::Selected => (&colors.selected_fg, &colors.selected_bg),
            SpanState::Normal => (&colors.span_fg, &colors.span_bg),
        };

        // Render just the Span's text on top of existing content.
        write!(
            stdout,
            "{goto}{bg_color}{fg_color}{text}{fg_reset}{bg_reset}",
            goto = cursor::Goto(pos.0 as u16 + 1, pos.1),
            fg_color = color::Fg(*fg_color),
            bg_color = color::Bg(*bg_color),
            fg_reset = color::Fg(color::Reset),
            bg_reset = color::Bg(color::Reset),
            text = &text,
        )
        .unwrap();
    }

    /// Render a Span's `hint` field on the provided writer.
    ///
    /// This renders the hint according to some provided style:
    /// - just colors
    /// - styled (bold, italic, underlined) with colors
    /// - surrounding the hint's text with some delimiters, see
    ///   `HintStyle::Delimited`.
    ///
    /// # Arguments
    /// - `pos` is (x_in_content_space, screen_y) where screen_y is 1-indexed
    ///
    /// # Note
    ///
    /// This writes directly on the writer, avoiding extra allocation.
    fn render_span_hint(
        stdout: &mut dyn io::Write,
        hint_text: &str,
        pos: (usize, u16),
        colors: &UiColors,
        hint_style: &Option<HintStyle>,
    ) {
        let fg_color = color::Fg(colors.hint_fg);
        let bg_color = color::Bg(colors.hint_bg);
        let fg_reset = color::Fg(color::Reset);
        let bg_reset = color::Bg(color::Reset);
        let goto = cursor::Goto(pos.0 as u16 + 1, pos.1);

        match hint_style {
            None => {
                write!(
                    stdout,
                    "{goto}{bg_color}{fg_color}{hint_text}{fg_reset}{bg_reset}",
                )
                .unwrap();
            }
            Some(hint_style) => match hint_style {
                HintStyle::Bold => {
                    write!(
                        stdout,
                        "{goto}{bg_color}{fg_color}{sty}{hint}{sty_reset}{fg_reset}{bg_reset}",
                        goto = goto,
                        fg_color = fg_color,
                        bg_color = bg_color,
                        fg_reset = fg_reset,
                        bg_reset = bg_reset,
                        sty = style::Bold,
                        sty_reset = style::Reset, // NoBold is not sufficient
                        hint = hint_text,
                    )
                    .unwrap();
                }
                HintStyle::Italic => {
                    write!(
                        stdout,
                        "{goto}{bg_color}{fg_color}{sty}{hint}{sty_reset}{fg_reset}{bg_reset}",
                        goto = goto,
                        fg_color = fg_color,
                        bg_color = bg_color,
                        fg_reset = fg_reset,
                        bg_reset = bg_reset,
                        sty = style::Italic,
                        sty_reset = style::NoItalic,
                        hint = hint_text,
                    )
                    .unwrap();
                }
                HintStyle::Underline => {
                    write!(
                        stdout,
                        "{goto}{bg_color}{fg_color}{sty}{hint}{sty_reset}{fg_reset}{bg_reset}",
                        goto = goto,
                        fg_color = fg_color,
                        bg_color = bg_color,
                        fg_reset = fg_reset,
                        bg_reset = bg_reset,
                        sty = style::Underline,
                        sty_reset = style::NoUnderline,
                        hint = hint_text,
                    )
                    .unwrap();
                }
                HintStyle::Surround(opening, closing) => {
                    write!(
                        stdout,
                        "{goto}{bg_color}{fg_color}{opening}{hint_text}{closing}{fg_reset}{bg_reset}",
                    )
                    .unwrap();
                }
            },
        }
    }

    /// Convenience function that renders both the text span and its hint.
    /// Hints are shown for `Normal` and `Selected` states (so user can toggle),
    /// but hidden for `Focused`. Only renders if the span is visible in the viewport.
    fn render_span(&self, stdout: &mut dyn io::Write, span: &textbuf::Span<'a>, state: SpanState) {
        let text = span.text;

        let (pos_x, pos_y) = self.adjusted_span_position(span);
        let (pos_x, content_row) = self.map_coords_to_wrapped_space(pos_x, pos_y);

        // Check if span is visible in viewport
        let screen_y = match self.viewport.screen_y(content_row) {
            Some(y) => y,
            None => return, // Span not visible, skip rendering
        };

        ViewController::render_span_text(
            stdout,
            text,
            state,
            (pos_x, screen_y),
            self.rendering_colors,
        );

        if state != SpanState::Focused {
            // If not focused, render the hint (e.g. "eo") as an overlay on
            // top of the rendered text span, aligned at its leading or the
            // trailing edge.
            let offset = match self.hint_alignment {
                HintAlignment::Leading => 0,
                HintAlignment::Trailing => text.len() - span.hint.len(),
            };

            ViewController::render_span_hint(
                stdout,
                &span.hint,
                (pos_x + offset, screen_y),
                self.rendering_colors,
                &self.hint_style,
            );
        }
    }

    /// Render scroll position indicator in bottom-right corner.
    /// Only shown when content exceeds viewport height.
    fn render_scroll_indicator(&self, stdout: &mut dyn io::Write) {
        if self.total_content_height <= self.viewport.height {
            return; // No scrolling needed, no indicator
        }

        let max_top = self
            .total_content_height
            .saturating_sub(self.viewport.height);
        let indicator = format!("[{}/{}]", self.viewport.top_row + 1, max_top + 1);

        // Render in bottom-right corner with dim styling
        let x_pos = self.term_width.saturating_sub(indicator.len() as u16);
        write!(
            stdout,
            "{goto}{dim}{text}{reset}",
            goto = cursor::Goto(x_pos, self.term_height),
            dim = style::Faint,
            text = indicator,
            reset = style::Reset,
        )
        .unwrap();
    }

    /// Full render the Ui on the provided writer.
    ///
    /// This renders in 3 phases:
    /// - all lines are rendered verbatim (within viewport)
    /// - each Span's `text` is rendered as an overlay on top of it
    /// - each Span's `hint` text is rendered as a final overlay
    ///
    /// Depending on the value of `self.hint_alignment`, the hint can be
    /// rendered on the leading edge of the underlying Span's `text`, or on
    /// the trailing edge.
    ///
    /// # Note
    ///
    /// Multibyte characters are taken into account, so that the Span's `text`
    /// and `hint` are rendered in their proper position.
    fn full_render(&self, stdout: &mut dyn io::Write) {
        // Clear screen before rendering
        write!(stdout, "{}", termion::clear::All).unwrap();

        // 1. Trim all lines and render non-empty ones within viewport.
        ViewController::render_base_text(
            stdout,
            self.model.lines,
            &self.wrapped_lines,
            self.rendering_colors,
            &self.viewport,
            self.term_width,
        );

        // 2. Render spans (only visible ones)
        for (index, span) in self.model.spans.iter().enumerate() {
            let state = if index == self.focus_index {
                SpanState::Focused
            } else if self.selected_indices.contains(&index) {
                SpanState::Selected
            } else {
                SpanState::Normal
            };
            self.render_span(stdout, span, state);
        }

        // 3. Render scroll indicator if content exceeds viewport
        self.render_scroll_indicator(stdout);

        stdout.flush().unwrap();
    }

    /// Render the previous span with its hint, and render the newly focused
    /// span without its hint. This is more efficient than a full render.
    fn diff_render(
        &self,
        stdout: &mut dyn io::Write,
        old_focus_index: usize,
        new_focus_index: usize,
    ) {
        // Render the previously focused span: revert to Selected or Normal
        let span = self.model.spans.get(old_focus_index).unwrap();
        let old_state = if self.selected_indices.contains(&old_focus_index) {
            SpanState::Selected
        } else {
            SpanState::Normal
        };
        self.render_span(stdout, span, old_state);

        // Render the newly focused span
        let span = self.model.spans.get(new_focus_index).unwrap();
        self.render_span(stdout, span, SpanState::Focused);

        stdout.flush().unwrap();
    }

    /// Re-render a single span after its selection state has changed.
    fn toggle_render(&self, stdout: &mut dyn io::Write, span_index: usize) {
        let span = self.model.spans.get(span_index).unwrap();
        let state = if span_index == self.focus_index {
            SpanState::Focused
        } else if self.selected_indices.contains(&span_index) {
            SpanState::Selected
        } else {
            SpanState::Normal
        };
        self.render_span(stdout, span, state);
        stdout.flush().unwrap();
    }

    /// Toggle the selection state of a span and re-render it.
    fn toggle_selection(&mut self, stdout: &mut dyn io::Write, idx: usize) {
        if self.selected_indices.contains(&idx) {
            self.selected_indices.remove(&idx);
        } else {
            self.selected_indices.insert(idx);
        }
        self.toggle_render(stdout, idx);
    }

    /// Build a `Selection` event, joining all toggled spans in multi-select
    /// mode or returning the focused span in single-select mode.
    fn build_selection(&self, uppercased: bool, output_destination: OutputDestination) -> Event {
        let text = if self.multi_select.enabled && !self.selected_indices.is_empty() {
            self.selected_indices
                .iter()
                .map(|&i| self.model.spans[i].text)
                .collect::<Vec<_>>()
                .join(&self.multi_select.separator)
        } else {
            self.model.spans[self.focus_index].text.to_string()
        };
        Event::Select(Selection {
            text,
            uppercased,
            output_destination,
        })
    }

    // }}}
    // Listening {{{1

    /// Listen to keys entered on stdin, moving focus accordingly, or
    /// selecting one span.
    ///
    /// # Panics
    ///
    /// - This function panics if termion cannot read the entered keys on stdin.
    fn listen(&mut self, reader: &mut dyn io::Read, writer: &mut dyn io::Write) -> Event {
        use termion::input::TermRead; // Trait for `reader.keys().next()`.

        if self.model.spans.is_empty() {
            return Event::Exit;
        }

        let mut typed_hint = String::new();
        let mut uppercased = false;
        let mut output_destination = self.default_output_destination.clone();

        self.full_render(writer);

        loop {
            // This is an option of a result of a key... Let's pop error cases first.
            let next_key = reader.keys().next();

            if next_key.is_none() {
                // Nothing in the buffer. Wait for a bit...
                std::thread::sleep(std::time::Duration::from_millis(25));
                continue;
            }

            let key_res = next_key.unwrap();
            if let Err(err) = key_res {
                // Termion not being able to read from stdin is an unrecoverable error.
                panic!("{}", err);
            }

            match key_res.unwrap() {
                event::Key::Esc => {
                    break;
                }

                // Move focus to next/prev span with viewport scrolling.
                event::Key::Up => {
                    let (old_index, focused_index) = self.prev_focus_index();
                    self.handle_focus_change(old_index, focused_index, writer);
                }
                event::Key::Down => {
                    let (old_index, focused_index) = self.next_focus_index();
                    self.handle_focus_change(old_index, focused_index, writer);
                }
                event::Key::Left => {
                    let (old_index, focused_index) = self.prev_focus_index();
                    self.handle_focus_change(old_index, focused_index, writer);
                }
                event::Key::Right => {
                    let (old_index, focused_index) = self.next_focus_index();
                    self.handle_focus_change(old_index, focused_index, writer);
                }
                event::Key::Char('n') => {
                    let (old_index, focused_index) = if self.model.reverse {
                        self.prev_focus_index()
                    } else {
                        self.next_focus_index()
                    };
                    self.handle_focus_change(old_index, focused_index, writer);
                }
                event::Key::Char('N') => {
                    let (old_index, focused_index) = if self.model.reverse {
                        self.next_focus_index()
                    } else {
                        self.prev_focus_index()
                    };
                    self.handle_focus_change(old_index, focused_index, writer);
                }

                // Manual scrolling with PageUp/PageDown or Ctrl-B/Ctrl-F
                event::Key::PageUp | event::Key::Ctrl('b') => {
                    let scroll_amount = self.viewport.height / 2;
                    if self.viewport.scroll_up(scroll_amount) {
                        self.full_render(writer);
                    }
                }
                event::Key::PageDown | event::Key::Ctrl('f') => {
                    let scroll_amount = self.viewport.height / 2;
                    if self
                        .viewport
                        .scroll_down(scroll_amount, self.total_content_height)
                    {
                        self.full_render(writer);
                    }
                }

                // Tab: toggle focused span selection (multi-select mode)
                event::Key::Char('\t') if self.multi_select.enabled => {
                    let idx = self.focus_index;
                    self.toggle_selection(writer, idx);
                }

                // Yank/copy
                event::Key::Char('y') | event::Key::Char('\n') => {
                    return self.build_selection(false, output_destination);
                }
                event::Key::Char('Y') => {
                    return self.build_selection(true, output_destination);
                }

                event::Key::Char(' ') => {
                    output_destination.toggle();
                    let message = format!("output destination: `{output_destination}`");
                    duct::cmd!("tmux", "display-message", &message)
                        .run()
                        .expect("could not make tmux display the message.");
                    continue;
                }

                // Use a Trie or another data structure to determine
                // if the entered key belongs to a longer hint.
                // Attempts at finding a span with a corresponding hint.
                //
                // If any of the typed character is caps, the typed hint is
                // deemed as uppercased.
                event::Key::Char(ch) => {
                    let key = ch.to_string();
                    let lower_key = key.to_lowercase();

                    uppercased = uppercased || (key != lower_key);
                    typed_hint.push_str(&lower_key);

                    let node = self
                        .model
                        .lookup_trie
                        .get_node(&typed_hint.chars().collect::<Vec<char>>());

                    if node.is_none() {
                        if self.multi_select.enabled {
                            // In multi-select, don't exit on mistype
                            typed_hint.clear();
                            uppercased = false;
                            continue;
                        }
                        // A key outside the alphabet was entered.
                        return Event::Exit;
                    }

                    let node = node.unwrap();
                    if node.is_leaf() {
                        let span_index = node.value().expect(
                            "By construction, the Lookup Trie should have a value for each leaf.",
                        );

                        if self.multi_select.enabled {
                            // Toggle span selection instead of immediate return
                            self.toggle_selection(writer, *span_index);
                            typed_hint.clear();
                            uppercased = false;
                            continue;
                        }

                        // Single-select: immediate return
                        let span = self.model.spans.get(*span_index).expect("By construction, the value in a leaf should correspond to an existing hint.");
                        let text = span.text.to_string();
                        return Event::Select(Selection {
                            text,
                            uppercased,
                            output_destination,
                        });
                    }
                    // The prefix of a hint was entered, but we
                    // still need more keys.
                }

                // Unknown keys are ignored.
                _ => (),
            }

            // End of event processing loop.
        }

        Event::Exit
    }

    // }}}
    // Presenting {{{1

    /// Configure the terminal and display the `Ui`.
    ///
    /// - Setup steps: switch to alternate screen, switch to raw mode, hide the cursor.
    /// - Teardown steps: show cursor, back to main screen.
    pub fn present(&mut self) -> Option<Selection> {
        use termion::raw::IntoRawMode;

        let mut stdin = termion::async_stdin();
        let mut stdout = io::stdout()
            .into_raw_mode()
            .expect("Cannot access alternate screen.")
            .into_alternate_screen()
            .expect("Cannot access alternate screen.");

        // stdout.write(cursor::Hide.into()).unwrap();
        write!(stdout, "{}", cursor::Hide).unwrap();

        let selection = match self.listen(&mut stdin, &mut stdout) {
            Event::Exit => None,
            Event::Select(selection) => Some(selection),
        };

        write!(stdout, "{}", cursor::Show).unwrap();

        selection
    }

    // }}}
}

/// Default tab width in terminal columns.
const DEFAULT_TAB_WIDTH: usize = 8;

/// Compute the display width of a string, accounting for tab expansion and Unicode
/// character widths.
///
/// Tabs expand to the next tab stop (multiples of `tab_width`). Unicode characters
/// use their proper display width (e.g., CJK characters are 2 columns, combining
/// characters are 0 columns).
fn display_width(s: &str, tab_width: usize) -> usize {
    let mut col = 0;
    for ch in s.chars() {
        if ch == '\t' {
            // Expand tab to next tab stop
            col = ((col / tab_width) + 1) * tab_width;
        } else {
            col += ch.width().unwrap_or(0);
        }
    }
    col
}

/// Compute each line's actual y position and size if displayed in a terminal of width
/// `term_width`.
fn compute_wrapped_lines(lines: &[&str], term_width: u16) -> Vec<WrappedLine> {
    lines
        .iter()
        .scan(0, |position, &line| {
            // Save the value to return (yield is in unstable).
            let value = *position;

            let line_width = display_width(line.trim_end(), DEFAULT_TAB_WIDTH) as isize;

            // Amount of extra y space taken by this line.
            // If the line has n chars, on a term of width n, this does not
            // produce an extra line; it needs to exceed the width by 1 char.
            // In case the width is 0, we need to first clamp line_width - 1.
            let extra = cmp::max(0, line_width - 1) as usize / term_width as usize;

            // Update the position of the next line.
            *position += 1 + extra;

            Some(WrappedLine {
                pos_y: value,
                // size: 1 + extra,
            })
        })
        .collect()
}

/// Visual state of a span for rendering purposes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SpanState {
    /// Default appearance: span_fg/span_bg colors, hints shown.
    Normal,
    /// Selected in multi-select mode: selected_fg/selected_bg colors, hints shown.
    Selected,
    /// Currently focused span: focused_fg/focused_bg colors, hints hidden.
    Focused,
}

/// Returned value after the `Ui` has finished listening to events.
enum Event {
    /// Exit with no selected spans,
    Exit,
    /// The selected span of text and whether it was selected with uppercase.
    Select(Selection),
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{textbuf::alphabet, ui::colors};

    #[test]
    fn test_render_all_lines() {
        let content = "some text
* e006b06 - (12 days ago) swapper: Make quotes
path: /usr/local/bin/git


path: /usr/local/bin/cargo";
        let lines: Vec<&str> = content.split('\n').collect();
        let wrapped_lines: Vec<WrappedLine> = vec![
            WrappedLine { pos_y: 0 },
            WrappedLine { pos_y: 1 },
            WrappedLine { pos_y: 2 },
            WrappedLine { pos_y: 3 },
            WrappedLine { pos_y: 4 },
            WrappedLine { pos_y: 5 },
        ];

        let colors = UiColors {
            text_fg: colors::BLACK,
            text_bg: colors::WHITE,
            focused_fg: colors::RED,
            focused_bg: colors::BLUE,
            span_fg: colors::GREEN,
            span_bg: colors::MAGENTA,
            selected_fg: colors::GREEN,
            selected_bg: colors::RESET,
            hint_fg: colors::YELLOW,
            hint_bg: colors::CYAN,
        };

        // Viewport large enough to see all content
        let viewport = Viewport::new(10);
        let term_width = 80u16;

        let mut writer = vec![];
        ViewController::render_base_text(
            &mut writer,
            &lines,
            &wrapped_lines,
            &colors,
            &viewport,
            term_width,
        );

        let goto1 = cursor::Goto(1, 1);
        let goto2 = cursor::Goto(1, 2);
        let goto3 = cursor::Goto(1, 3);
        let goto6 = cursor::Goto(1, 6);
        assert_eq!(
            writer,
            format!(
                "{bg}{fg}{g1}some text{g2}* e006b06 - (12 days ago) swapper: Make quotes{g3}path: /usr/local/bin/git{g6}path: /usr/local/bin/cargo{fg_reset}{bg_reset}",
                g1 = goto1, g2 = goto2, g3 = goto3, g6 = goto6,
                fg = color::Fg(colors.text_fg),
                bg = color::Bg(colors.text_bg),
                fg_reset = color::Fg(color::Reset),
                bg_reset = color::Bg(color::Reset),
                )
            .as_bytes()
            );
    }

    #[test]
    fn test_render_focused_span_text() {
        let mut writer = vec![];
        let text = "https://en.wikipedia.org/wiki/Barcelona";
        let state = SpanState::Focused;
        // Position is (x_in_content_space, screen_y) where screen_y is 1-indexed
        let position: (usize, u16) = (3, 2);
        let colors = UiColors {
            text_fg: colors::BLACK,
            text_bg: colors::WHITE,
            focused_fg: colors::RED,
            focused_bg: colors::BLUE,
            span_fg: colors::GREEN,
            span_bg: colors::MAGENTA,
            selected_fg: colors::GREEN,
            selected_bg: colors::RESET,
            hint_fg: colors::YELLOW,
            hint_bg: colors::CYAN,
        };

        ViewController::render_span_text(&mut writer, text, state, position, &colors);

        assert_eq!(
            writer,
            format!(
                "{goto}{bg}{fg}{text}{fg_reset}{bg_reset}",
                goto = cursor::Goto(4, 2),
                fg = color::Fg(colors.focused_fg),
                bg = color::Bg(colors.focused_bg),
                fg_reset = color::Fg(color::Reset),
                bg_reset = color::Bg(color::Reset),
                text = &text,
            )
            .as_bytes()
        );
    }

    #[test]
    fn test_render_span_text() {
        let mut writer = vec![];
        let text = "https://en.wikipedia.org/wiki/Barcelona";
        let state = SpanState::Normal;
        // Position is (x_in_content_space, screen_y) where screen_y is 1-indexed
        let position: (usize, u16) = (3, 2);
        let colors = UiColors {
            text_fg: colors::BLACK,
            text_bg: colors::WHITE,
            focused_fg: colors::RED,
            focused_bg: colors::BLUE,
            span_fg: colors::GREEN,
            span_bg: colors::MAGENTA,
            selected_fg: colors::GREEN,
            selected_bg: colors::RESET,
            hint_fg: colors::YELLOW,
            hint_bg: colors::CYAN,
        };

        ViewController::render_span_text(&mut writer, text, state, position, &colors);

        assert_eq!(
            writer,
            format!(
                "{goto}{bg}{fg}{text}{fg_reset}{bg_reset}",
                goto = cursor::Goto(4, 2),
                fg = color::Fg(colors.span_fg),
                bg = color::Bg(colors.span_bg),
                fg_reset = color::Fg(color::Reset),
                bg_reset = color::Bg(color::Reset),
                text = &text,
            )
            .as_bytes()
        );
    }

    #[test]
    fn test_render_selected_span_text() {
        let mut writer = vec![];
        let text = "https://en.wikipedia.org/wiki/Barcelona";
        let state = SpanState::Selected;
        // Position is (x_in_content_space, screen_y) where screen_y is 1-indexed
        let position: (usize, u16) = (3, 2);
        let colors = UiColors {
            text_fg: colors::BLACK,
            text_bg: colors::WHITE,
            focused_fg: colors::RED,
            focused_bg: colors::BLUE,
            span_fg: colors::GREEN,
            span_bg: colors::MAGENTA,
            selected_fg: colors::GREEN,
            selected_bg: colors::RESET,
            hint_fg: colors::YELLOW,
            hint_bg: colors::CYAN,
        };

        ViewController::render_span_text(&mut writer, text, state, position, &colors);

        assert_eq!(
            writer,
            format!(
                "{goto}{bg}{fg}{text}{fg_reset}{bg_reset}",
                goto = cursor::Goto(4, 2),
                fg = color::Fg(colors.selected_fg),
                bg = color::Bg(colors.selected_bg),
                fg_reset = color::Fg(color::Reset),
                bg_reset = color::Bg(color::Reset),
                text = &text,
            )
            .as_bytes()
        );
    }

    #[test]
    fn test_render_unstyled_span_hint() {
        let mut writer = vec![];
        let hint_text = "eo";
        // Position is (x_in_content_space, screen_y) where screen_y is 1-indexed
        let position: (usize, u16) = (3, 2);
        let colors = UiColors {
            text_fg: colors::BLACK,
            text_bg: colors::WHITE,
            focused_fg: colors::RED,
            focused_bg: colors::BLUE,
            span_fg: colors::GREEN,
            span_bg: colors::MAGENTA,
            selected_fg: colors::GREEN,
            selected_bg: colors::RESET,
            hint_fg: colors::YELLOW,
            hint_bg: colors::CYAN,
        };

        let offset = 0;
        let hint_style = None;

        ViewController::render_span_hint(
            &mut writer,
            hint_text,
            (position.0 + offset, position.1),
            &colors,
            &hint_style,
        );

        assert_eq!(
            writer,
            format!(
                "{goto}{bg}{fg}{text}{fg_reset}{bg_reset}",
                goto = cursor::Goto(4, 2),
                fg = color::Fg(colors.hint_fg),
                bg = color::Bg(colors.hint_bg),
                fg_reset = color::Fg(color::Reset),
                bg_reset = color::Bg(color::Reset),
                text = "eo",
            )
            .as_bytes()
        );
    }

    #[test]
    fn test_render_underlined_span_hint() {
        let mut writer = vec![];
        let hint_text = "eo";
        // Position is (x_in_content_space, screen_y) where screen_y is 1-indexed
        let position: (usize, u16) = (3, 2);
        let colors = UiColors {
            text_fg: colors::BLACK,
            text_bg: colors::WHITE,
            focused_fg: colors::RED,
            focused_bg: colors::BLUE,
            span_fg: colors::GREEN,
            span_bg: colors::MAGENTA,
            selected_fg: colors::GREEN,
            selected_bg: colors::RESET,
            hint_fg: colors::YELLOW,
            hint_bg: colors::CYAN,
        };

        let offset = 0;
        let hint_style = Some(HintStyle::Underline);

        ViewController::render_span_hint(
            &mut writer,
            hint_text,
            (position.0 + offset, position.1),
            &colors,
            &hint_style,
        );

        assert_eq!(
            writer,
            format!(
                "{goto}{bg}{fg}{sty}{text}{sty_reset}{fg_reset}{bg_reset}",
                goto = cursor::Goto(4, 2),
                fg = color::Fg(colors.hint_fg),
                bg = color::Bg(colors.hint_bg),
                fg_reset = color::Fg(color::Reset),
                bg_reset = color::Bg(color::Reset),
                sty = style::Underline,
                sty_reset = style::NoUnderline,
                text = "eo",
            )
            .as_bytes()
        );
    }

    #[test]
    fn test_render_bracketed_span_hint() {
        let mut writer = vec![];
        let hint_text = "eo";
        // Position is (x_in_content_space, screen_y) where screen_y is 1-indexed
        let position: (usize, u16) = (3, 2);
        let colors = UiColors {
            text_fg: colors::BLACK,
            text_bg: colors::WHITE,
            focused_fg: colors::RED,
            focused_bg: colors::BLUE,
            span_fg: colors::GREEN,
            span_bg: colors::MAGENTA,
            selected_fg: colors::GREEN,
            selected_bg: colors::RESET,
            hint_fg: colors::YELLOW,
            hint_bg: colors::CYAN,
        };

        let offset = 0;
        let hint_style = Some(HintStyle::Surround('{', '}'));

        ViewController::render_span_hint(
            &mut writer,
            hint_text,
            (position.0 + offset, position.1),
            &colors,
            &hint_style,
        );

        assert_eq!(
            writer,
            format!(
                "{goto}{bg}{fg}{bra}{text}{bra_close}{fg_reset}{bg_reset}",
                goto = cursor::Goto(4, 2),
                fg = color::Fg(colors.hint_fg),
                bg = color::Bg(colors.hint_bg),
                fg_reset = color::Fg(color::Reset),
                bg_reset = color::Bg(color::Reset),
                bra = '{',
                bra_close = '}',
                text = "eo",
            )
            .as_bytes()
        );
    }

    #[test]
    /// Simulates rendering without any span.
    fn test_render_full_without_available_spans() {
        let buffer = "lorem 127.0.0.1 lorem

Barcelona https://en.wikipedia.org/wiki/Barcelona -   ";
        let lines = buffer.split('\n').collect::<Vec<_>>();

        let use_all_patterns = false;
        let named_pat = vec![];
        let custom_patterns = vec![];
        let alphabet = alphabet::Alphabet("abcd".to_string());
        let reverse = false;
        let unique_hint = false;
        let mut model = textbuf::Model::new(
            &lines,
            &alphabet,
            use_all_patterns,
            &named_pat,
            &custom_patterns,
            reverse,
            unique_hint,
        );
        let term_width: u16 = 80;
        let term_height: u16 = 30;
        let wrapped_lines = compute_wrapped_lines(model.lines, term_width);

        // Compute total content height
        let total_content_height = if wrapped_lines.is_empty() {
            0
        } else {
            let last_idx = wrapped_lines.len() - 1;
            wrapped_lines[last_idx].pos_y + 1
        };

        let rendering_colors = UiColors {
            text_fg: colors::BLACK,
            text_bg: colors::WHITE,
            focused_fg: colors::RED,
            focused_bg: colors::BLUE,
            span_fg: colors::GREEN,
            span_bg: colors::MAGENTA,
            selected_fg: colors::GREEN,
            selected_bg: colors::RESET,
            hint_fg: colors::YELLOW,
            hint_bg: colors::CYAN,
        };
        let hint_alignment = HintAlignment::Leading;
        let viewport = Viewport::new(term_height as usize);

        // create a Ui without any span
        let ui = ViewController {
            model: &mut model,
            term_width,
            term_height,
            wrapped_lines,
            total_content_height,
            viewport,
            focus_index: 0,
            focus_wrap_around: false,
            default_output_destination: OutputDestination::Tmux,
            rendering_colors: &rendering_colors,
            hint_alignment: &hint_alignment,
            hint_style: None,
            multi_select: MultiSelectConfig {
                enabled: false,
                separator: " ".to_string(),
            },
            selected_indices: BTreeSet::new(),
        };

        let mut writer = vec![];
        ui.full_render(&mut writer);

        let goto1 = cursor::Goto(1, 1);
        let goto3 = cursor::Goto(1, 3);

        let expected = format!(
            "{clear}{bg}{fg}{goto1}lorem 127.0.0.1 lorem\
        {goto3}Barcelona https://en.wikipedia.org/wiki/Barcelona -{fg_reset}{bg_reset}",
            clear = termion::clear::All,
            goto1 = goto1,
            goto3 = goto3,
            fg = color::Fg(rendering_colors.text_fg),
            bg = color::Bg(rendering_colors.text_bg),
            fg_reset = color::Fg(color::Reset),
            bg_reset = color::Bg(color::Reset),
        );

        // println!("{:?}", writer);
        // println!("{:?}", expected.as_bytes());

        assert_eq!(writer, expected.as_bytes());
    }

    #[test]
    /// Simulates rendering with available spans.
    fn test_render_full_with_spans() {
        let buffer = "lorem 127.0.0.1 lorem

Barcelona https://en.wikipedia.org/wiki/Barcelona -   ";
        let lines = buffer.split('\n').collect::<Vec<_>>();

        let use_all_patterns = true;
        let named_pat = vec![];
        let custom_patterns = vec![];
        let alphabet = alphabet::Alphabet("abcd".to_string());
        let reverse = true;
        let unique_hint = false;
        let model = textbuf::Model::new(
            &lines,
            &alphabet,
            use_all_patterns,
            &named_pat,
            &custom_patterns,
            reverse,
            unique_hint,
        );
        let wrap_around = false;
        let default_output_destination = OutputDestination::Tmux;

        let rendering_colors = UiColors {
            text_fg: colors::BLACK,
            text_bg: colors::WHITE,
            focused_fg: colors::RED,
            focused_bg: colors::BLUE,
            span_fg: colors::GREEN,
            span_bg: colors::MAGENTA,
            selected_fg: colors::GREEN,
            selected_bg: colors::RESET,
            hint_fg: colors::YELLOW,
            hint_bg: colors::CYAN,
        };
        let hint_alignment = HintAlignment::Leading;
        let hint_style = None;

        let ui = ViewController::new(
            &model,
            wrap_around,
            &default_output_destination,
            &rendering_colors,
            &hint_alignment,
            hint_style,
            MultiSelectConfig {
                enabled: false,
                separator: " ".to_string(),
            },
        );

        let mut writer = vec![];
        ui.full_render(&mut writer);

        let expected_content = {
            let goto1 = cursor::Goto(1, 1);
            let goto3 = cursor::Goto(1, 3);

            format!(
                "{clear}{bg}{fg}{goto1}lorem 127.0.0.1 lorem\
        {goto3}Barcelona https://en.wikipedia.org/wiki/Barcelona -{fg_reset}{bg_reset}",
                clear = termion::clear::All,
                goto1 = goto1,
                goto3 = goto3,
                fg = color::Fg(rendering_colors.text_fg),
                bg = color::Bg(rendering_colors.text_bg),
                fg_reset = color::Fg(color::Reset),
                bg_reset = color::Bg(color::Reset)
            )
        };

        let expected_span1_text = {
            let goto7_1 = cursor::Goto(7, 1);
            format!(
                "{goto7_1}{span_bg}{span_fg}127.0.0.1{fg_reset}{bg_reset}",
                goto7_1 = goto7_1,
                span_fg = color::Fg(rendering_colors.span_fg),
                span_bg = color::Bg(rendering_colors.span_bg),
                fg_reset = color::Fg(color::Reset),
                bg_reset = color::Bg(color::Reset)
            )
        };

        let expected_span1_hint = {
            let goto7_1 = cursor::Goto(7, 1);

            format!(
                "{goto7_1}{hint_bg}{hint_fg}b{fg_reset}{bg_reset}",
                goto7_1 = goto7_1,
                hint_fg = color::Fg(rendering_colors.hint_fg),
                hint_bg = color::Bg(rendering_colors.hint_bg),
                fg_reset = color::Fg(color::Reset),
                bg_reset = color::Bg(color::Reset)
            )
        };

        let expected_span2_text = {
            let goto11_3 = cursor::Goto(11, 3);
            format!(
        "{goto11_3}{focus_bg}{focus_fg}https://en.wikipedia.org/wiki/Barcelona{fg_reset}{bg_reset}",
        goto11_3 = goto11_3,
        focus_fg = color::Fg(rendering_colors.focused_fg),
        focus_bg = color::Bg(rendering_colors.focused_bg),
        fg_reset = color::Fg(color::Reset),
        bg_reset = color::Bg(color::Reset)
      )
        };

        // Because reverse is true, this second span is focused,
        // then the hint should not be rendered.

        // let expected_span2_hint = {
        //     let goto11_3 = cursor::Goto(11, 3);

        //     format!(
        //         "{goto11_3}{hint_bg}{hint_fg}a{fg_reset}{bg_reset}",
        //         goto11_3 = goto11_3,
        //         hint_fg = color::Fg(rendering_colors.hint_fg.as_ref()),
        //         hint_bg = color::Bg(rendering_colors.hint_bg.as_ref()),
        //         fg_reset = color::Fg(color::Reset),
        //         bg_reset = color::Bg(color::Reset)
        //     )
        // };

        let expected = [
            expected_content,
            expected_span1_text,
            expected_span1_hint,
            expected_span2_text,
            // expected_span2_hint,
        ]
        .concat();

        // println!("{:?}", writer);
        // println!("{:?}", expected.as_bytes());

        // let diff_point = writer
        //   .iter()
        //   .zip(expected.as_bytes().iter())
        //   .enumerate()
        //   .find(|(_idx, (&l, &r))| l != r);
        // println!("{:?}", diff_point);

        assert_eq!(2, ui.model.spans.len());

        assert_eq!(writer, expected.as_bytes());
    }

    #[test]
    fn test_display_width_without_tabs() {
        // Regular ASCII text
        assert_eq!(display_width("hello", 8), 5);
        assert_eq!(display_width("", 8), 0);
        assert_eq!(display_width("abc", 8), 3);
    }

    #[test]
    fn test_display_width_with_tabs() {
        // Tab at position 0 expands to 8 columns
        assert_eq!(display_width("\t", 8), 8);
        // Tab at position 1 expands to column 8 (7 more columns)
        assert_eq!(display_width("a\t", 8), 8);
        // Tab at position 7 expands to column 8 (1 more column)
        assert_eq!(display_width("1234567\t", 8), 8);
        // Tab at position 8 expands to column 16
        assert_eq!(display_width("12345678\t", 8), 16);
        // Multiple tabs
        assert_eq!(display_width("\t\t", 8), 16);
        // Tab followed by text
        assert_eq!(display_width("\tfile.txt", 8), 16); // 8 + 8
    }

    #[test]
    fn test_display_width_git_status_style() {
        // Simulates git status output with leading tab
        assert_eq!(display_width("\tTODO.md", 8), 15); // 8 (tab) + 7 (TODO.md)
        assert_eq!(display_width("\tsrc/textbuf/toto.rs", 8), 27); // 8 + 19
    }
}