quadraui 0.6.1

Cross-platform Rust UI toolkit: write one AppLogic and run it unmodified on TUI, GTK4 (Linux), macOS, and Windows backends
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
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
//! `Editor` primitive — code-editor viewport with gutter, syntax-
//! highlighted text, cursor, selections, diagnostics, and overlays.
//!
//! The data shape mirrors `vimcode::render::RenderedWindow` /
//! `RenderedLine` field-for-field. Two rasterisers consume the
//! primitive: `quadraui::tui::draw_editor` and
//! `quadraui::gtk::draw_editor`.
//!
//! ## Module shape
//!
//! Supporting types (`DiagnosticSeverity`, `GitLineStatus`, `DiffLine`,
//! `CursorShape`, `SelectionKind`, `CursorPos`, `EditorSelection`,
//! `EditorCursor`, `Style`, `StyledSpan`, `DiagnosticMark`,
//! `SpellMark`) and `quadraui::Theme` editor-paint fields define the
//! editor's appearance. The `Editor` + `EditorLine` data structs form
//! the primitive's data layer; rasterisers consume them.
//!
//! ## `EditorStyledSpan` vs `quadraui::types::StyledSpan`
//!
//! `quadraui::types::StyledSpan` is owned-text and serde-friendly —
//! used by Lua-pluggable surfaces. This module's [`EditorStyledSpan`]
//! is byte-range based (offsets into the line's `raw_text`) — necessary
//! for editor paint where tree-sitter / LSP / search highlighting all
//! produce byte ranges. Both shapes coexist under distinct names.
//!
//! ## `EditorSelection::cols_on`
//!
//! Selection column-range math (mapping a buffer-coordinate
//! [`EditorSelection`] onto one [`EditorLine`]'s own segment-local
//! columns — handling wrapped segments, ghost-text continuation rows,
//! and diff-padding filler rows) is now the single source of truth;
//! every backend calls it and only converts the returned
//! [`SelectionCols`] to on-screen positions.

use crate::event::Rect;
use crate::types::{Color, WidgetId};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};

// ─── DiagnosticSeverity ─────────────────────────────────────────────────────

/// LSP diagnostic severity, mirrored from `vimcode::core::lsp::DiagnosticSeverity`.
///
/// Values match the LSP wire format (1–4). Vimcode-side adapter at the
/// rasteriser boundary maps `lsp::DiagnosticSeverity` ↔ this enum.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum DiagnosticSeverity {
    Error = 1,
    Warning = 2,
    Information = 3,
    Hint = 4,
}

// ─── GitLineStatus ──────────────────────────────────────────────────────────

/// Per-line git diff status, mirrored from `vimcode::core::git::GitLineStatus`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum GitLineStatus {
    Added,
    Modified,
    /// Lines were deleted at this position (rasteriser draws `▾`).
    Deleted,
}

// ─── DiffLine ───────────────────────────────────────────────────────────────

/// Per-line two-way-diff status, mirrored from
/// `vimcode::core::engine::DiffLine`. `None` on `EditorLine.diff_status`
/// means diff mode is not active for the line's window.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum DiffLine {
    Same,
    Added,
    Removed,
    /// Filler line inserted for alignment — no buffer content.
    Padding,
}

// ─── CursorShape ────────────────────────────────────────────────────────────

/// Shape of the editor cursor.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum CursorShape {
    /// Filled block (Normal / Visual modes).
    Block,
    /// Thin vertical bar (Insert mode).
    Bar,
    /// Underline (pending replace-char `r` command).
    Underline,
}

// ─── SelectionKind ──────────────────────────────────────────────────────────

/// Visual-selection mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum SelectionKind {
    Char,
    Line,
    Block,
}

// ─── CursorPos ──────────────────────────────────────────────────────────────

/// Cursor position within the visible window area (view-line + char column).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct CursorPos {
    /// Index into `Editor.lines` (0 = topmost visible line).
    pub view_line: usize,
    /// Column (character index within the line).
    pub col: usize,
}

// ─── EditorCursor ───────────────────────────────────────────────────────────

/// Primary cursor: position plus shape.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct EditorCursor {
    pub pos: CursorPos,
    pub shape: CursorShape,
}

// ─── EditorSelection ────────────────────────────────────────────────────────

/// A normalised visual-selection range (start ≤ end) in buffer coordinates.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct EditorSelection {
    pub kind: SelectionKind,
    /// First selected buffer line.
    pub start_line: usize,
    /// First selected column (Char / Block; ignored for Line).
    pub start_col: usize,
    /// Last selected buffer line (inclusive).
    pub end_line: usize,
    /// Last selected column (Char / Block; ignored for Line).
    pub end_col: usize,
}

/// Segment-local column range that an [`EditorSelection`] highlights on
/// one [`EditorLine`], returned by [`EditorSelection::cols_on`].
///
/// `start`/`end` are half-open `[start, end)` character-column offsets
/// *within this visual segment's own text* (i.e. already adjusted for
/// `segment_col_offset` — subtract nothing further, they're ready to
/// hand to a per-character x-position lookup on `line.raw_text`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SelectionCols {
    pub start: usize,
    pub end: usize,
    /// True when the selection continues past this segment's own text —
    /// either onto a later buffer line, or (for a wrapped line) onto the
    /// next visual segment of the same buffer line — rather than ending
    /// exactly at `end`. Always `true` for [`SelectionKind::Line`] (a
    /// line selection always highlights the full row, independent of
    /// text length).
    ///
    /// Backends that measure text at pixel resolution (GTK/macOS) use
    /// this to decide whether to extend the highlight rectangle to the
    /// full rendered line width instead of stopping at the last
    /// character's edge. Backends that paint per fixed-width cell
    /// (TUI/Win) can ignore it — `end` already caps at the segment's own
    /// character count, which is all they need.
    pub extends_beyond: bool,
}

impl EditorSelection {
    /// Column range this selection highlights on `line`, or `None` if
    /// this visual row shows no part of the selection — outside
    /// `[start_line, end_line]`, a ghost-text continuation row (virtual,
    /// no buffer columns), or a diff-padding filler row (no buffer
    /// content to select).
    ///
    /// Single source of truth for selection column math; callers only
    /// need to convert the returned columns to on-screen x positions.
    pub fn cols_on(&self, line: &EditorLine) -> Option<SelectionCols> {
        if line.is_ghost_continuation || line.diff_status == Some(DiffLine::Padding) {
            return None;
        }
        let line_idx = line.line_idx;
        if line_idx < self.start_line || line_idx > self.end_line {
            return None;
        }

        let seg_offset = line.segment_col_offset;
        // `.max(1)`: an empty segment (a blank buffer line, or a wrapped
        // line's tail segment whose text ends exactly on the wrap
        // boundary) still gets one highlighted column when a Char/Block
        // selection passes through it — matches the convention of
        // showing at least a cursor-width highlight on a blank selected
        // line, rather than silently skipping it.
        let char_count = line.raw_text.trim_end_matches('\n').chars().count().max(1);
        let seg_end = seg_offset + char_count;

        let (buf_start, buf_end) = match self.kind {
            SelectionKind::Line => (0usize, usize::MAX),
            SelectionKind::Char => {
                let start = if line_idx == self.start_line {
                    self.start_col
                } else {
                    0
                };
                let end = if line_idx == self.end_line {
                    self.end_col + 1
                } else {
                    usize::MAX
                };
                (start, end)
            }
            SelectionKind::Block => (self.start_col, self.end_col + 1),
        };

        // Entirely before or after this segment's own columns.
        if buf_start >= seg_end && buf_end != usize::MAX {
            return None;
        }
        if buf_end <= seg_offset {
            return None;
        }

        let start = buf_start.saturating_sub(seg_offset);
        let end = if buf_end == usize::MAX {
            char_count
        } else {
            buf_end.saturating_sub(seg_offset).min(char_count)
        };
        if start >= end {
            return None;
        }
        let extends_beyond = end >= char_count && buf_end > seg_end;

        Some(SelectionCols {
            start,
            end,
            extends_beyond,
        })
    }
}

// ─── Style ──────────────────────────────────────────────────────────────────

/// Per-span text style used by the editor's byte-range
/// [`EditorStyledSpan`]. Mirrors `vimcode::render::Style`, with
/// `font_scale` narrowed from `f64` → `f32` so derives of
/// `PartialEq` / `Serialize` work without `Eq` blocking us.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct Style {
    pub fg: Color,
    pub bg: Option<Color>,
    #[serde(default)]
    pub bold: bool,
    #[serde(default)]
    pub italic: bool,
    /// Font scale factor (1.0 = normal). Used by GTK for markdown
    /// headings; TUI ignores. Cast to `f64` at the Pango call site.
    pub font_scale: f32,
}

// ─── EditorStyledSpan (byte-range) ──────────────────────────────────────────

/// A styled byte-range within a line's text.
///
/// `start_byte` and `end_byte` are offsets into the
/// `EditorLine.raw_text` of the line that owns the span. The byte-range
/// form is necessary because tree-sitter / LSP / search highlighting
/// all produce byte ranges; converting to owned-text spans (the shape
/// of `quadraui::types::StyledSpan`) would lose alignment with these
/// upstream sources.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EditorStyledSpan {
    pub start_byte: usize,
    pub end_byte: usize,
    pub style: Style,
}

// ─── DiagnosticMark ─────────────────────────────────────────────────────────

/// LSP diagnostic span on one line — drives inline underline / squiggle
/// painting plus tooltip-on-hover. `start_col` / `end_col` are character
/// indices within the line's `raw_text`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct DiagnosticMark {
    pub start_col: usize,
    pub end_col: usize,
    pub severity: DiagnosticSeverity,
    pub message: String,
}

// ─── SpellMark ──────────────────────────────────────────────────────────────

/// Misspelled-word span on one line — drives spell-check underline.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct SpellMark {
    pub start_col: usize,
    pub end_col: usize,
}

// ─── EditorLine ─────────────────────────────────────────────────────────────

/// One visible line in an [`Editor`] viewport, ready for the rasteriser.
///
/// Field shapes mirror `vimcode::render::RenderedLine` field-for-field
/// (verbatim port). The vimcode-side adapter at the rasteriser
/// boundary builds an `EditorLine` from a `RenderedLine` per frame.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EditorLine {
    /// Raw UTF-8 text (may include a trailing `\n`).
    pub raw_text: String,
    /// Pre-formatted gutter text (e.g. `"  42"` / `"   3"`).
    /// Empty when line numbers are disabled.
    pub gutter_text: String,
    /// Syntax-highlight + search-match spans (byte-offset based, into
    /// `raw_text`).
    pub spans: Vec<EditorStyledSpan>,
    /// Buffer line index this rendered row corresponds to. Used by
    /// click handlers to map screen row → buffer line.
    pub line_idx: usize,
    /// True when the cursor is on this line (drives gutter highlight).
    #[serde(default)]
    pub is_current_line: bool,
    /// True when this is the header of a closed fold.
    #[serde(default)]
    pub is_fold_header: bool,
    /// Number of lines hidden in the fold (0 unless `is_fold_header`).
    #[serde(default)]
    pub folded_line_count: usize,
    /// Git diff status (`Added` / `Modified` / `Deleted`). `None` when
    /// the buffer is not git-tracked or the line is unchanged.
    #[serde(default)]
    pub git_diff: Option<GitLineStatus>,
    /// Two-way diff status. `None` when diff mode is off.
    #[serde(default)]
    pub diff_status: Option<DiffLine>,
    /// LSP diagnostic spans on this line (may be empty).
    #[serde(default)]
    pub diagnostics: Vec<DiagnosticMark>,
    /// Spell-check error spans on this line (may be empty).
    #[serde(default)]
    pub spell_errors: Vec<SpellMark>,
    /// True when there is a DAP breakpoint set on this line.
    #[serde(default)]
    pub is_breakpoint: bool,
    /// True when the breakpoint has a condition / hit count / log
    /// message (rasteriser draws ◆ instead of ●).
    #[serde(default)]
    pub is_conditional_bp: bool,
    /// True when the DAP adapter is currently stopped at this line.
    #[serde(default)]
    pub is_dap_current: bool,
    /// True when this row is a wrap-continuation (the 2nd+ visual row
    /// of a long buffer line). The line number belongs to the
    /// preceding non-continuation row; `gutter_text` is blank.
    #[serde(default)]
    pub is_wrap_continuation: bool,
    /// Character offset within the buffer line where this visual
    /// segment begins. 0 for non-wrapped lines and the first visual
    /// segment of a wrapped line.
    #[serde(default)]
    pub segment_col_offset: usize,
    /// Inline annotation (virtual text — git blame, plugin output,
    /// etc.) shown after line content in `annotation_fg`.
    #[serde(default)]
    pub annotation: Option<String>,
    /// AI ghost text shown after the cursor on this line (Insert
    /// mode). Rendered in `ghost_text_fg`.
    #[serde(default)]
    pub ghost_suffix: Option<String>,
    /// True for virtual rows showing AI completion continuation lines.
    /// `raw_text` is empty; the full text is in `ghost_suffix` and
    /// rasterisers paint it from the left edge of the content area.
    #[serde(default)]
    pub is_ghost_continuation: bool,
    /// Column positions where indent-guide rules should be drawn.
    /// Empty when the `indent_guides` setting is off.
    #[serde(default)]
    pub indent_guides: Vec<usize>,
    /// Column positions where the colorcolumn background should be
    /// painted.
    #[serde(default)]
    pub colorcolumns: Vec<usize>,
}

// ─── Editor ─────────────────────────────────────────────────────────────────

/// Declarative description of one editor viewport (window / pane).
///
/// Mirrors `vimcode::render::RenderedWindow` field-for-field.
///
/// **Adding a field here is a breaking change** — this struct is
/// `#[non_exhaustive]` to require use of [`Editor::new`] plus the
/// `with_*` builder methods (besides `id`/`rect`) and a `Default` impl.
///
/// # Examples
///
/// ```
/// use quadraui::{Editor, EditorHit, EditorLine, Rect, WidgetId};
///
/// let line = EditorLine {
///     raw_text: "fn main() {}\n".to_string(),
///     gutter_text: "  1".to_string(),
///     spans: vec![],
///     line_idx: 0,
///     is_current_line: true,
///     is_fold_header: false,
///     folded_line_count: 0,
///     git_diff: None,
///     diff_status: None,
///     diagnostics: vec![],
///     spell_errors: vec![],
///     is_breakpoint: false,
///     is_conditional_bp: false,
///     is_dap_current: false,
///     is_wrap_continuation: false,
///     segment_col_offset: 0,
///     annotation: None,
///     ghost_suffix: None,
///     is_ghost_continuation: false,
///     indent_guides: vec![],
///     colorcolumns: vec![],
/// };
///
/// let rect = Rect::new(0.0, 0.0, 80.0, 24.0);
/// let editor = Editor::new(WidgetId::new("editor:main"), rect)
///     .with_lines(vec![line])
///     .with_total_lines(1)
///     .with_gutter_char_width(3);
///
/// let layout = editor.layout(rect, 1.0, 1.0);
/// match layout.hit_test(5.0, 0.0) {
///     EditorHit::BufferPos { line, .. } => assert_eq!(line, 0),
///     other => panic!("expected a buffer-position hit, got {other:?}"),
/// }
/// ```
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Editor {
    pub id: WidgetId,
    /// Pixel-space rectangle (used by GTK / Win-GUI; TUI ignores).
    pub rect: Rect,
    /// Visible lines, one per row.
    pub lines: Vec<EditorLine>,
    /// Primary cursor (position + shape). `None` when scrolled
    /// off-screen.
    #[serde(default)]
    pub cursor: Option<EditorCursor>,
    /// Secondary cursor positions for multi-cursor (Alt-D). Drawn as
    /// dimmed blocks.
    #[serde(default)]
    pub extra_cursors: Vec<CursorPos>,
    /// Active visual selection.
    #[serde(default)]
    pub selection: Option<EditorSelection>,
    /// Extra selections for Ctrl+D word-multi-cursor.
    #[serde(default)]
    pub extra_selections: Vec<EditorSelection>,
    /// Transient post-yank flash region. `None` when no flash active.
    #[serde(default)]
    pub yank_highlight: Option<EditorSelection>,
    /// Index of the first visible buffer line.
    pub scroll_top: usize,
    /// Number of character columns scrolled horizontally.
    #[serde(default)]
    pub scroll_left: usize,
    /// Total lines in the buffer (drives vertical scrollbar geometry).
    pub total_lines: usize,
    /// Max line length in the buffer (character cells, excl. trailing
    /// newline). Drives horizontal scrollbar.
    #[serde(default)]
    pub max_col: usize,
    /// Width of the line-number gutter in *character cells* (0 = no
    /// gutter). GTK multiplies by `char_width` to get pixels.
    #[serde(default)]
    pub gutter_char_width: usize,
    /// Whether this is the focused window.
    pub is_active: bool,
    /// Whether to render with the slightly-different active-window
    /// background — only true when `is_active` AND there are multiple
    /// windows. Drives the rasteriser's choice between
    /// `theme.editor_active_background` and `theme.background`.
    pub show_active_bg: bool,
    /// Whether the buffer has git diff data (controls git column).
    pub has_git_diff: bool,
    /// Whether to show the breakpoint gutter column.
    pub has_breakpoints: bool,
    /// Per-line worst diagnostic severity. Used for gutter icons.
    #[serde(default)]
    pub diagnostic_gutter: HashMap<usize, DiagnosticSeverity>,
    /// Lines with available LSP code actions (lightbulb gutter glyph).
    #[serde(default)]
    pub code_action_lines: HashSet<usize>,
    /// Bracket-pair positions to highlight (cursor bracket + match).
    /// Each `(view_line, col)`. Up to 2 entries.
    #[serde(default)]
    pub bracket_match_positions: Vec<(usize, usize)>,
    /// Indent-guide column highlighted as "active" (cursor's scope).
    #[serde(default)]
    pub active_indent_col: Option<usize>,
    /// Tab stop width for expanding `\t` to spaces (TUI rendering).
    pub tabstop: usize,
    /// Whether to draw cursorline highlight.
    pub cursorline: bool,
    /// Glyph the rasteriser draws in the gutter for lines with an
    /// available LSP code action. The host computes this from its
    /// icon registry per frame so nerd-font / fallback toggles
    /// propagate without the rasteriser depending on a host icon
    /// module. Apps without code-action icons can leave this at
    /// `'\0'` and the rasteriser skips painting.
    #[serde(default = "default_lightbulb_glyph")]
    pub lightbulb_glyph: char,
}

fn default_lightbulb_glyph() -> char {
    '!'
}

// ─── EditorPaintOptions ─────────────────────────────────────────────────────

/// Per-call paint options for [`Editor::layout`] / rasterisers that don't
/// have a home directly on the [`Editor`] snapshot itself.
///
/// Adding a field to `Editor` directly would break downstream exhaustive
/// struct literals with `E0063`. A small, independently-growable options
/// struct with no existing call sites to break sidesteps that, and can
/// gain more fields later.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct EditorPaintOptions {
    /// Suppress this editor's own vertical scrollbar even though the
    /// buffer overflows the viewport.
    ///
    /// A host running a scrollbar-style minimap beside the editor has no
    /// other way to stop the editor from reserving and painting a
    /// `v_scrollbar_bounds` column immediately next to it. Passing
    /// `suppress_v_scrollbar: true` makes `has_v_scrollbar` return `false`,
    /// so `v_scrollbar_bounds` is `None` and neither `EditorLayout::hit_test`
    /// nor [`crate::gtk::draw_editor_with_options`] reserves or paints that
    /// column. Leave at `false` (the default) for editors with no minimap,
    /// or one that isn't acting as a scrollbar.
    pub suppress_v_scrollbar: bool,
}

// ─── EditorLayout + hit_test ──────────────────────────────────────────────────

/// Classification of a hit-test result within an editor viewport.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EditorHit {
    /// Click landed on a text position. `line` is the buffer line index
    /// (always accurate — row height is uniform on every backend).
    ///
    /// `col` is a **uniform-monospace approximation** of the character
    /// column (`(x - text_bounds.x) / cell_width`, plus `scroll_left`;
    /// no tab expansion). It matches the painted glyph exactly on TUI's
    /// fixed-cell grid, but can drift from the actual glyph on
    /// proportional-font or per-span-attributed backends (bold /
    /// italic / `font_scale` spans paint at a different advance than
    /// `cell_width`). Callers that need the exact column on those backends
    /// should discard this field and resolve via
    /// [`crate::Backend::editor_col_at_x`] instead (falls back to this
    /// same approximation on TUI).
    BufferPos { line: usize, col: usize },
    /// Click landed in the gutter region.
    Gutter { line_idx: usize, gutter_col: usize },
    /// Click landed on the vertical scrollbar track.
    VScrollbar,
    /// Click landed on the horizontal scrollbar track.
    HScrollbar,
    /// Click landed outside any meaningful region.
    Empty,
}

/// Fully-resolved editor geometry for a single viewport. Produced by
/// [`Editor::layout`] and used by both rasterisers and click handlers.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct EditorLayout {
    /// Full editor bounds (the rect passed to layout).
    pub bounds: Rect,
    /// Gutter region (line numbers, git, diagnostics). `None` when
    /// `gutter_char_width == 0`.
    pub gutter_bounds: Option<Rect>,
    /// Code content region (text area).
    pub text_bounds: Rect,
    /// Vertical scrollbar track. `None` when content fits.
    pub v_scrollbar_bounds: Option<Rect>,
    /// Horizontal scrollbar track. `None` when content fits.
    pub h_scrollbar_bounds: Option<Rect>,
    /// Cell dimensions used for coordinate-to-position conversion.
    pub cell_width: f32,
    pub line_height: f32,
    /// Scroll offsets for buffer-position calculation.
    pub scroll_top: usize,
    pub scroll_left: usize,
    /// Number of visible text rows.
    pub visible_lines: usize,
    /// Number of visible text columns.
    pub visible_cols: usize,
}

impl EditorLayout {
    /// Resolve an absolute point to an editor zone with buffer-relative
    /// positions.
    ///
    /// Zone classification (gutter / scrollbar / text-area) and the
    /// resolved `line` are always accurate. The `col` on the returned
    /// [`EditorHit::BufferPos`] is a uniform-monospace approximation —
    /// see that variant's doc and [`Self::col_at_x`] /
    /// [`crate::Backend::editor_col_at_x`] for the text-engine-accurate
    /// resolution proportional/attributed backends need.
    pub fn hit_test(&self, x: f32, y: f32) -> EditorHit {
        if x < self.bounds.x
            || x >= self.bounds.x + self.bounds.width
            || y < self.bounds.y
            || y >= self.bounds.y + self.bounds.height
        {
            return EditorHit::Empty;
        }

        if let Some(vsb) = self.v_scrollbar_bounds {
            if x >= vsb.x && x < vsb.x + vsb.width && y >= vsb.y && y < vsb.y + vsb.height {
                return EditorHit::VScrollbar;
            }
        }

        if let Some(hsb) = self.h_scrollbar_bounds {
            if x >= hsb.x && x < hsb.x + hsb.width && y >= hsb.y && y < hsb.y + hsb.height {
                return EditorHit::HScrollbar;
            }
        }

        if let Some(g) = self.gutter_bounds {
            if x >= g.x && x < g.x + g.width && y >= g.y && y < g.y + g.height {
                let row = ((y - g.y) / self.line_height).floor() as usize;
                let line_idx = self.scroll_top + row;
                let gutter_col = ((x - g.x) / self.cell_width).floor() as usize;
                return EditorHit::Gutter {
                    line_idx,
                    gutter_col,
                };
            }
        }

        if x >= self.text_bounds.x
            && x < self.text_bounds.x + self.text_bounds.width
            && y >= self.text_bounds.y
            && y < self.text_bounds.y + self.text_bounds.height
        {
            let row = ((y - self.text_bounds.y) / self.line_height).floor() as usize;
            let col_offset = ((x - self.text_bounds.x) / self.cell_width).floor() as usize;
            let line = self.scroll_top + row;
            let col = self.scroll_left + col_offset;
            return EditorHit::BufferPos { line, col };
        }

        EditorHit::Empty
    }

    /// Resolve `x` to a character column within `editor.lines[view_row]`
    /// using uniform monospace division (`self.cell_width`).
    ///
    /// This is the default [`crate::Backend::editor_col_at_x`]
    /// implementation — correct for TUI's fixed-cell grid and any
    /// backend whose configured font renders every glyph at the same
    /// advance width. Backends that paint editor text with a real
    /// text-shaping engine and per-span attributes (bold / italic /
    /// `font_scale`) override `Backend::editor_col_at_x` with an exact
    /// glyph-position inverse of their `draw_editor` instead.
    ///
    /// The returned column already folds in `self.scroll_left` and the
    /// row's `segment_col_offset` (0 for non-wrapped lines and the
    /// first visual segment of a wrapped line), so it's directly usable
    /// as the buffer-line-relative column. Falls back to
    /// `self.scroll_left` alone (no segment offset) when `view_row` is
    /// out of range for `editor.lines`.
    pub fn col_at_x(&self, editor: &Editor, view_row: usize, x: f32) -> usize {
        let segment_col_offset = editor
            .lines
            .get(view_row)
            .map(|line| line.segment_col_offset)
            .unwrap_or(0);
        let col_offset = if self.cell_width > 0.0 {
            ((x - self.text_bounds.x) / self.cell_width)
                .floor()
                .max(0.0) as usize
        } else {
            0
        };
        self.scroll_left + col_offset + segment_col_offset
    }

    /// Resolve a character column within `editor.lines[view_row]` back to
    /// an absolute `x` — the exact inverse of [`Self::col_at_x`], so
    /// `col_at_x(x_at_col(editor, view_row, c)) == c` holds for any `c`
    /// reachable from a valid on-screen `x`.
    ///
    /// Like `col_at_x`, this is a uniform-monospace calculation
    /// (`self.cell_width`) with no tab expansion — correct for TUI's
    /// fixed-cell grid, and the default [`crate::Backend`] behaviour for
    /// any host that hasn't overridden the exact-glyph resolution. A host
    /// anchoring UI at a caret column (a popup, say) on a backend with
    /// per-span attributes or proportional fonts should resolve the exact
    /// pixel position through that backend's own text-shaping engine
    /// instead of this approximation.
    pub fn x_at_col(&self, editor: &Editor, view_row: usize, col: usize) -> f32 {
        let segment_col_offset = editor
            .lines
            .get(view_row)
            .map(|line| line.segment_col_offset)
            .unwrap_or(0);
        let col_offset = col.saturating_sub(self.scroll_left + segment_col_offset);
        self.text_bounds.x + col_offset as f32 * self.cell_width
    }
}

/// An editor viewport with no content and every optional/overlay field at
/// its empty default — the `new(required…)`/`with_*`/`Default` trio
/// that lets a consumer build an `Editor` without an
/// exhaustive struct literal. `tabstop` defaults to `4` and
/// `lightbulb_glyph` to `'!'`, matching [`default_lightbulb_glyph`] and
/// every existing call site's convention — not derived-`Default`'s `0`
/// / `'\0'`.
impl Default for Editor {
    fn default() -> Self {
        Self::new(WidgetId::new(String::new()), Rect::default())
    }
}

impl Editor {
    /// An editor viewport at `rect` with no lines, no cursor, and no
    /// overlays — chain `with_*` to fill it in.
    pub fn new(id: WidgetId, rect: Rect) -> Self {
        Self {
            id,
            rect,
            lines: Vec::new(),
            cursor: None,
            extra_cursors: Vec::new(),
            selection: None,
            extra_selections: Vec::new(),
            yank_highlight: None,
            scroll_top: 0,
            scroll_left: 0,
            total_lines: 0,
            max_col: 0,
            gutter_char_width: 0,
            is_active: false,
            show_active_bg: false,
            has_git_diff: false,
            has_breakpoints: false,
            diagnostic_gutter: HashMap::new(),
            code_action_lines: HashSet::new(),
            bracket_match_positions: Vec::new(),
            active_indent_col: None,
            tabstop: 4,
            cursorline: false,
            lightbulb_glyph: default_lightbulb_glyph(),
        }
    }

    /// Replace [`Self::lines`].
    #[must_use]
    pub fn with_lines(mut self, lines: Vec<EditorLine>) -> Self {
        self.lines = lines;
        self
    }

    /// Set [`Self::cursor`].
    #[must_use]
    pub fn with_cursor(mut self, cursor: EditorCursor) -> Self {
        self.cursor = Some(cursor);
        self
    }

    /// Replace [`Self::extra_cursors`].
    #[must_use]
    pub fn with_extra_cursors(mut self, extra_cursors: Vec<CursorPos>) -> Self {
        self.extra_cursors = extra_cursors;
        self
    }

    /// Set [`Self::selection`].
    #[must_use]
    pub fn with_selection(mut self, selection: EditorSelection) -> Self {
        self.selection = Some(selection);
        self
    }

    /// Replace [`Self::extra_selections`].
    #[must_use]
    pub fn with_extra_selections(mut self, extra_selections: Vec<EditorSelection>) -> Self {
        self.extra_selections = extra_selections;
        self
    }

    /// Set [`Self::yank_highlight`].
    #[must_use]
    pub fn with_yank_highlight(mut self, yank_highlight: EditorSelection) -> Self {
        self.yank_highlight = Some(yank_highlight);
        self
    }

    /// Set [`Self::scroll_top`].
    #[must_use]
    pub fn with_scroll_top(mut self, scroll_top: usize) -> Self {
        self.scroll_top = scroll_top;
        self
    }

    /// Set [`Self::scroll_left`].
    #[must_use]
    pub fn with_scroll_left(mut self, scroll_left: usize) -> Self {
        self.scroll_left = scroll_left;
        self
    }

    /// Set [`Self::total_lines`].
    #[must_use]
    pub fn with_total_lines(mut self, total_lines: usize) -> Self {
        self.total_lines = total_lines;
        self
    }

    /// Set [`Self::max_col`].
    #[must_use]
    pub fn with_max_col(mut self, max_col: usize) -> Self {
        self.max_col = max_col;
        self
    }

    /// Set [`Self::gutter_char_width`].
    #[must_use]
    pub fn with_gutter_char_width(mut self, gutter_char_width: usize) -> Self {
        self.gutter_char_width = gutter_char_width;
        self
    }

    /// Set [`Self::is_active`].
    #[must_use]
    pub fn with_is_active(mut self, is_active: bool) -> Self {
        self.is_active = is_active;
        self
    }

    /// Set [`Self::show_active_bg`].
    #[must_use]
    pub fn with_show_active_bg(mut self, show_active_bg: bool) -> Self {
        self.show_active_bg = show_active_bg;
        self
    }

    /// Set [`Self::has_git_diff`].
    #[must_use]
    pub fn with_has_git_diff(mut self, has_git_diff: bool) -> Self {
        self.has_git_diff = has_git_diff;
        self
    }

    /// Set [`Self::has_breakpoints`].
    #[must_use]
    pub fn with_has_breakpoints(mut self, has_breakpoints: bool) -> Self {
        self.has_breakpoints = has_breakpoints;
        self
    }

    /// Replace [`Self::diagnostic_gutter`].
    #[must_use]
    pub fn with_diagnostic_gutter(
        mut self,
        diagnostic_gutter: HashMap<usize, DiagnosticSeverity>,
    ) -> Self {
        self.diagnostic_gutter = diagnostic_gutter;
        self
    }

    /// Replace [`Self::code_action_lines`].
    #[must_use]
    pub fn with_code_action_lines(mut self, code_action_lines: HashSet<usize>) -> Self {
        self.code_action_lines = code_action_lines;
        self
    }

    /// Replace [`Self::bracket_match_positions`].
    #[must_use]
    pub fn with_bracket_match_positions(
        mut self,
        bracket_match_positions: Vec<(usize, usize)>,
    ) -> Self {
        self.bracket_match_positions = bracket_match_positions;
        self
    }

    /// Set [`Self::active_indent_col`].
    #[must_use]
    pub fn with_active_indent_col(mut self, active_indent_col: usize) -> Self {
        self.active_indent_col = Some(active_indent_col);
        self
    }

    /// Set [`Self::tabstop`].
    #[must_use]
    pub fn with_tabstop(mut self, tabstop: usize) -> Self {
        self.tabstop = tabstop;
        self
    }

    /// Set [`Self::cursorline`].
    #[must_use]
    pub fn with_cursorline(mut self, cursorline: bool) -> Self {
        self.cursorline = cursorline;
        self
    }

    /// Set [`Self::lightbulb_glyph`].
    #[must_use]
    pub fn with_lightbulb_glyph(mut self, lightbulb_glyph: char) -> Self {
        self.lightbulb_glyph = lightbulb_glyph;
        self
    }

    /// Compute the viewport geometry for hit-testing and rendering layout.
    ///
    /// # Arguments
    ///
    /// - `viewport` — the rectangle this editor occupies.
    /// - `cell_width` — character advance width (1.0 for TUI, font px for GTK).
    /// - `line_height` — row height (1.0 for TUI, font px for GTK).
    ///
    /// Equivalent to [`Self::layout_with_options`] with
    /// `EditorPaintOptions::default()` — kept as a separate, unchanged
    /// method (rather than growing this one's argument list) so every
    /// existing caller keeps compiling untouched. See
    /// [`EditorPaintOptions`] for why a new parameter here would be a
    /// breaking change for both known downstream consumers.
    pub fn layout(&self, viewport: Rect, cell_width: f32, line_height: f32) -> EditorLayout {
        self.layout_with_options(
            viewport,
            cell_width,
            line_height,
            EditorPaintOptions::default(),
        )
    }

    /// [`Self::layout`], plus [`EditorPaintOptions`] a host can set to
    /// override otherwise-automatic geometry decisions — currently just
    /// `suppress_v_scrollbar`.
    ///
    /// Equivalent to [`Self::layout_with_options_and_v_scrollbar_w`] with
    /// `v_scrollbar_w: None` (a `cell_width`-wide scrollbar column).
    pub fn layout_with_options(
        &self,
        viewport: Rect,
        cell_width: f32,
        line_height: f32,
        options: EditorPaintOptions,
    ) -> EditorLayout {
        self.layout_with_options_and_v_scrollbar_w(viewport, cell_width, line_height, options, None)
    }

    /// [`Self::layout_with_options`], plus a host-settable vertical
    /// scrollbar width in the same pixel units as `cell_width` /
    /// `line_height`.
    ///
    /// Without an override the vertical scrollbar column is exactly
    /// `cell_width` wide — right for TUI's fixed-cell grid, but on a GUI
    /// backend that ties the scrollbar's width to the font's glyph
    /// advance rather than to a fixed chrome dimension. VS Code's editor
    /// scrollbar is a constant 14px column independent of font size.
    /// `Some(px)` overrides just the scrollbar column's width (both
    /// `v_scrollbar_bounds.width` and the text-area narrowing it causes)
    /// while every other geometry calculation keeps using `cell_width`.
    /// `None` sizes the column at `cell_width`. Ignored (there is no
    /// column to size) when `options.suppress_v_scrollbar` is `true` or
    /// the buffer doesn't overflow the viewport.
    ///
    /// GUI hosts normally reach this through
    /// [`crate::Backend::set_editor_v_scrollbar_width`] rather than
    /// calling it directly.
    ///
    /// Equivalent to [`Self::layout_with_options_and_reserve`] with
    /// `right_reserve_w: 0.0`.
    pub fn layout_with_options_and_v_scrollbar_w(
        &self,
        viewport: Rect,
        cell_width: f32,
        line_height: f32,
        options: EditorPaintOptions,
        v_scrollbar_w: Option<f32>,
    ) -> EditorLayout {
        self.layout_with_options_and_reserve(
            viewport,
            cell_width,
            line_height,
            options,
            v_scrollbar_w,
            0.0,
        )
    }

    /// [`Self::layout_with_options_and_v_scrollbar_w`], plus a fixed-width
    /// strip a caller can reserve between the text area and the vertical
    /// scrollbar.
    ///
    /// Every other tier of `layout*` derives `text_w`/`visible_cols` and
    /// the scrollbar bounds from `viewport.width` alone, so a host that
    /// wants to dock something between the buffer text and the scrollbar
    /// — a minimap strip, for example — has no way to shrink the text
    /// area without also shifting the vertical scrollbar off the
    /// viewport's true right edge. `right_reserve_w` (in the same pixel
    /// units as `cell_width`/`line_height`) is subtracted from the text
    /// area only: `text_bounds`/`h_scrollbar_bounds` narrow by it, while
    /// `v_scrollbar_bounds` keeps hugging `viewport.x + viewport.width`.
    /// The reserved strip itself isn't a layout field — a caller derives
    /// its bounds as the gap between `text_bounds`'s right edge and
    /// `v_scrollbar_bounds`'s left edge (or the viewport's right edge
    /// when there's no vertical scrollbar). `right_reserve_w: 0.0`
    /// reproduces [`Self::layout_with_options_and_v_scrollbar_w`] exactly.
    ///
    /// A negative `right_reserve_w` is clamped to `0.0`.
    pub fn layout_with_options_and_reserve(
        &self,
        viewport: Rect,
        cell_width: f32,
        line_height: f32,
        options: EditorPaintOptions,
        v_scrollbar_w: Option<f32>,
        right_reserve_w: f32,
    ) -> EditorLayout {
        let right_reserve_w = right_reserve_w.max(0.0);
        let gutter_w = self.gutter_char_width as f32 * cell_width;
        let visible_lines = if line_height > 0.0 {
            (viewport.height / line_height).floor() as usize
        } else {
            0
        };
        let has_v_scrollbar = !options.suppress_v_scrollbar
            && self.total_lines > visible_lines
            && viewport.width > gutter_w + cell_width + right_reserve_w;
        let v_scrollbar_w = if has_v_scrollbar {
            v_scrollbar_w.unwrap_or(cell_width)
        } else {
            0.0
        };

        let text_w = (viewport.width - gutter_w - v_scrollbar_w - right_reserve_w).max(0.0);
        let visible_cols = if cell_width > 0.0 {
            (text_w / cell_width).floor() as usize
        } else {
            0
        };
        let has_h_scrollbar = self.max_col > visible_cols && viewport.height > line_height;
        let h_scrollbar_h = if has_h_scrollbar { line_height } else { 0.0 };

        let text_h = (viewport.height - h_scrollbar_h).max(0.0);
        let visible_lines_final = if line_height > 0.0 {
            (text_h / line_height).floor() as usize
        } else {
            0
        };

        let gutter_bounds = if gutter_w > 0.0 {
            Some(Rect::new(viewport.x, viewport.y, gutter_w, text_h))
        } else {
            None
        };

        let text_x = viewport.x + gutter_w;
        let text_bounds = Rect::new(text_x, viewport.y, text_w, text_h);

        let v_scrollbar_bounds = if has_v_scrollbar {
            let v_track_h = text_h;
            Some(Rect::new(
                viewport.x + viewport.width - v_scrollbar_w,
                viewport.y,
                v_scrollbar_w,
                v_track_h,
            ))
        } else {
            None
        };

        let h_scrollbar_bounds = if has_h_scrollbar {
            let h_track_x = viewport.x + gutter_w;
            let h_track_w = text_w;
            Some(Rect::new(
                h_track_x,
                viewport.y + text_h,
                h_track_w,
                h_scrollbar_h,
            ))
        } else {
            None
        };

        EditorLayout {
            bounds: viewport,
            gutter_bounds,
            text_bounds,
            v_scrollbar_bounds,
            h_scrollbar_bounds,
            cell_width,
            line_height,
            scroll_top: self.scroll_top,
            scroll_left: self.scroll_left,
            visible_lines: visible_lines_final,
            visible_cols,
        }
    }
}

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

    #[test]
    fn editor_line_default_constructible_via_serde() {
        // A minimal-ish `EditorLine` round-trips through serde with
        // its #[serde(default)] fields populated by their natural
        // defaults — proves the field set is plugin-friendly.
        let json = r#"{ "raw_text": "fn main() {}",
                       "gutter_text": "  1",
                       "spans": [],
                       "line_idx": 0 }"#;
        let line: EditorLine = serde_json::from_str(json).expect("EditorLine deserialise");
        assert_eq!(line.raw_text, "fn main() {}");
        assert_eq!(line.line_idx, 0);
        assert!(!line.is_current_line);
        assert!(line.diagnostics.is_empty());
        assert!(line.indent_guides.is_empty());
    }

    #[test]
    fn editor_round_trips_through_serde() {
        let editor = Editor {
            id: "editor:0".into(),
            rect: Rect::new(0.0, 0.0, 800.0, 600.0),
            lines: vec![EditorLine {
                raw_text: "let x = 1;".into(),
                gutter_text: "  1".into(),
                spans: vec![EditorStyledSpan {
                    start_byte: 0,
                    end_byte: 3,
                    style: Style {
                        fg: Color::rgb(200, 200, 200),
                        bg: None,
                        bold: false,
                        italic: false,
                        font_scale: 1.0,
                    },
                }],
                line_idx: 0,
                is_current_line: true,
                is_fold_header: false,
                folded_line_count: 0,
                git_diff: Some(GitLineStatus::Added),
                diff_status: None,
                diagnostics: vec![],
                spell_errors: vec![],
                is_breakpoint: false,
                is_conditional_bp: false,
                is_dap_current: false,
                is_wrap_continuation: false,
                segment_col_offset: 0,
                annotation: None,
                ghost_suffix: None,
                is_ghost_continuation: false,
                indent_guides: vec![],
                colorcolumns: vec![],
            }],
            cursor: Some(EditorCursor {
                pos: CursorPos {
                    view_line: 0,
                    col: 4,
                },
                shape: CursorShape::Block,
            }),
            extra_cursors: vec![],
            selection: None,
            extra_selections: vec![],
            yank_highlight: None,
            scroll_top: 0,
            scroll_left: 0,
            total_lines: 1,
            max_col: 10,
            gutter_char_width: 3,
            is_active: true,
            show_active_bg: false,
            has_git_diff: true,
            has_breakpoints: false,
            diagnostic_gutter: HashMap::new(),
            code_action_lines: HashSet::new(),
            bracket_match_positions: vec![],
            active_indent_col: None,
            tabstop: 4,
            cursorline: true,
            lightbulb_glyph: '!',
        };
        let json = serde_json::to_string(&editor).expect("Editor serialise");
        let back: Editor = serde_json::from_str(&json).expect("Editor deserialise");
        assert_eq!(back.lines.len(), 1);
        assert_eq!(back.lines[0].raw_text, "let x = 1;");
        assert!(matches!(back.lines[0].git_diff, Some(GitLineStatus::Added)));
        assert!(matches!(back.cursor.unwrap().shape, CursorShape::Block));
    }

    #[test]
    fn diagnostic_severity_lsp_order_preserved() {
        // Order Error < Warning < Information < Hint matches LSP
        // numeric ordering — important because vimcode picks the
        // worst severity per line by `min`.
        assert!(DiagnosticSeverity::Error < DiagnosticSeverity::Warning);
        assert!(DiagnosticSeverity::Warning < DiagnosticSeverity::Information);
        assert!(DiagnosticSeverity::Information < DiagnosticSeverity::Hint);
    }

    // ── EditorLayout + hit_test ─────────────────────────────────────

    fn make_editor(gutter_w: usize, total_lines: usize, max_col: usize) -> Editor {
        Editor {
            id: "ed".into(),
            rect: Rect::new(0.0, 0.0, 80.0, 24.0),
            lines: Vec::new(),
            cursor: None,
            extra_cursors: Vec::new(),
            selection: None,
            extra_selections: Vec::new(),
            yank_highlight: None,
            scroll_top: 0,
            scroll_left: 0,
            total_lines,
            max_col,
            gutter_char_width: gutter_w,
            is_active: true,
            show_active_bg: false,
            has_git_diff: false,
            has_breakpoints: false,
            diagnostic_gutter: HashMap::new(),
            code_action_lines: HashSet::new(),
            bracket_match_positions: Vec::new(),
            active_indent_col: None,
            tabstop: 4,
            cursorline: true,
            lightbulb_glyph: '!',
        }
    }

    #[test]
    fn editor_layout_tui_basic_zones() {
        let ed = make_editor(4, 100, 40);
        let vp = Rect::new(0.0, 0.0, 80.0, 24.0);
        let l = ed.layout(vp, 1.0, 1.0);
        // Gutter: 4 cells wide.
        let g = l.gutter_bounds.unwrap();
        assert_eq!(g.x, 0.0);
        assert_eq!(g.width, 4.0);
        // Text area: 80 - 4(gutter) - 1(v_scrollbar) = 75
        assert_eq!(l.text_bounds.x, 4.0);
        assert_eq!(l.text_bounds.width, 75.0);
        // V-scrollbar present (100 lines > 24 rows).
        assert!(l.v_scrollbar_bounds.is_some());
        let vsb = l.v_scrollbar_bounds.unwrap();
        assert_eq!(vsb.x, 79.0);
        assert_eq!(vsb.width, 1.0);
    }

    /// A host running its own scroll affordance beside the editor (e.g.
    /// a minimap) can pass `EditorPaintOptions { suppress_v_scrollbar:
    /// true, .. }` to stop the editor from also reserving/painting a
    /// redundant vertical scrollbar column, even though the buffer still
    /// overflows the viewport. `layout()` (no options) must remain
    /// unaffected.
    #[test]
    fn editor_layout_with_options_suppress_v_scrollbar_overrides_overflow() {
        let ed = make_editor(4, 100, 40);
        let vp = Rect::new(0.0, 0.0, 80.0, 24.0);

        // Baseline: plain `layout()` still reserves the column.
        assert!(ed.layout(vp, 1.0, 1.0).v_scrollbar_bounds.is_some());

        let l = ed.layout_with_options(
            vp,
            1.0,
            1.0,
            EditorPaintOptions {
                suppress_v_scrollbar: true,
            },
        );
        assert!(
            l.v_scrollbar_bounds.is_none(),
            "suppress_v_scrollbar should suppress the column even though total_lines overflows"
        );
        // The full width (minus gutter) goes back to text, exactly as
        // the no-overflow case below.
        assert_eq!(l.text_bounds.width, 76.0);
    }

    /// A host can override the vertical scrollbar's width via
    /// `layout_with_options_and_v_scrollbar_w` — e.g. to match VS Code's
    /// fixed 14px column regardless of `cell_width`. Both the reserved
    /// column's own width and the text area it narrows must reflect the
    /// override; `layout()` keeps the `cell_width` default.
    #[test]
    fn editor_layout_v_scrollbar_w_overrides_width() {
        let ed = make_editor(4, 100, 40);
        let vp = Rect::new(0.0, 0.0, 80.0, 24.0);

        // Baseline: plain `layout()` sizes the column at `cell_width` (1.0).
        let baseline = ed.layout(vp, 1.0, 1.0);
        let baseline_vsb = baseline.v_scrollbar_bounds.unwrap();
        assert_eq!(baseline_vsb.width, 1.0);
        assert_eq!(baseline.text_bounds.width, 75.0);

        let l = ed.layout_with_options_and_v_scrollbar_w(
            vp,
            1.0,
            1.0,
            EditorPaintOptions::default(),
            Some(14.0),
        );
        let vsb = l.v_scrollbar_bounds.expect("buffer overflows the viewport");
        assert_eq!(vsb.width, 14.0);
        // Scrollbar column stays pinned to the right edge.
        assert_eq!(vsb.x, vp.x + vp.width - 14.0);
        // Text area shrinks by the override width, not `cell_width`.
        assert_eq!(l.text_bounds.width, 80.0 - 4.0 - 14.0);
    }

    /// A `v_scrollbar_w` override has no column to size when the buffer
    /// fits the viewport (no scrollbar at all) or when
    /// `suppress_v_scrollbar` is set — in both cases it must be silently
    /// ignored, not force a column into existence.
    #[test]
    fn editor_layout_v_scrollbar_w_ignored_without_a_scrollbar() {
        let vp = Rect::new(0.0, 0.0, 80.0, 24.0);

        // Content fits: no scrollbar regardless of the override.
        let fits = make_editor(4, 10, 20);
        let l = fits.layout_with_options_and_v_scrollbar_w(
            vp,
            1.0,
            1.0,
            EditorPaintOptions::default(),
            Some(14.0),
        );
        assert!(l.v_scrollbar_bounds.is_none());
        assert_eq!(l.text_bounds.width, 76.0);

        // Overflowing buffer, but suppressed: still no column.
        let overflow = make_editor(4, 100, 40);
        let l = overflow.layout_with_options_and_v_scrollbar_w(
            vp,
            1.0,
            1.0,
            EditorPaintOptions {
                suppress_v_scrollbar: true,
            },
            Some(14.0),
        );
        assert!(l.v_scrollbar_bounds.is_none());
        assert_eq!(l.text_bounds.width, 76.0);
    }

    /// `right_reserve_w` narrows the text area and the horizontal
    /// scrollbar by exactly the reserve, while the vertical scrollbar
    /// stays pinned to the viewport's true right edge — the `text |
    /// reserved strip | scrollbar` layout a minimap-beside-editor host
    /// needs. `right_reserve_w: 0.0` must reproduce
    /// `layout_with_options_and_v_scrollbar_w` exactly.
    #[test]
    fn editor_layout_reserve_narrows_text_keeps_scrollbar_flush() {
        let ed = make_editor(4, 100, 40);
        let vp = Rect::new(0.0, 0.0, 80.0, 24.0);

        let zero_reserve = ed.layout_with_options_and_reserve(
            vp,
            1.0,
            1.0,
            EditorPaintOptions::default(),
            Some(14.0),
            0.0,
        );
        let baseline = ed.layout_with_options_and_v_scrollbar_w(
            vp,
            1.0,
            1.0,
            EditorPaintOptions::default(),
            Some(14.0),
        );
        assert_eq!(zero_reserve.text_bounds, baseline.text_bounds);
        assert_eq!(zero_reserve.v_scrollbar_bounds, baseline.v_scrollbar_bounds);

        let l = ed.layout_with_options_and_reserve(
            vp,
            1.0,
            1.0,
            EditorPaintOptions::default(),
            Some(14.0),
            10.0,
        );
        // gutter 4 + v_scrollbar 14 + reserve 10 = 28 consumed; text gets 52.
        assert_eq!(l.text_bounds.width, 80.0 - 4.0 - 14.0 - 10.0);
        let vsb = l.v_scrollbar_bounds.expect("buffer overflows the viewport");
        // Scrollbar stays flush with the viewport's true right edge,
        // unaffected by the reserve.
        assert_eq!(vsb.x, vp.x + vp.width - 14.0);
        assert_eq!(vsb.width, 14.0);
        // The reserved strip is the gap between text_bounds and the
        // scrollbar: [text_bounds right edge, v_scrollbar left edge).
        let reserved_strip_w = vsb.x - (l.text_bounds.x + l.text_bounds.width);
        assert_eq!(reserved_strip_w, 10.0);
    }

    /// A negative `right_reserve_w` must clamp to `0.0` rather than
    /// growing the text area or panicking on an unsigned-looking
    /// subtraction.
    #[test]
    fn editor_layout_reserve_negative_clamps_to_zero() {
        let ed = make_editor(4, 10, 20);
        let vp = Rect::new(0.0, 0.0, 80.0, 24.0);
        let l = ed.layout_with_options_and_reserve(
            vp,
            1.0,
            1.0,
            EditorPaintOptions::default(),
            None,
            -10.0,
        );
        assert_eq!(l.text_bounds.width, 76.0);
    }

    /// When the reserve consumes the whole viewport (beyond what's left
    /// after the gutter and a would-be scrollbar column), the vertical
    /// scrollbar must be dropped rather than given negative width.
    #[test]
    fn editor_layout_reserve_suppresses_scrollbar_when_viewport_too_narrow() {
        let ed = make_editor(4, 100, 40);
        let vp = Rect::new(0.0, 0.0, 80.0, 24.0);
        let l = ed.layout_with_options_and_reserve(
            vp,
            1.0,
            1.0,
            EditorPaintOptions::default(),
            None,
            76.0,
        );
        assert!(l.v_scrollbar_bounds.is_none());
        assert_eq!(l.text_bounds.width, 0.0);
    }

    #[test]
    fn editor_layout_no_scrollbar_when_content_fits() {
        let ed = make_editor(4, 10, 20);
        let vp = Rect::new(0.0, 0.0, 80.0, 24.0);
        let l = ed.layout(vp, 1.0, 1.0);
        assert!(l.v_scrollbar_bounds.is_none());
        assert!(l.h_scrollbar_bounds.is_none());
        // Text gets full width minus gutter.
        assert_eq!(l.text_bounds.width, 76.0);
    }

    #[test]
    fn editor_layout_h_scrollbar_present() {
        let ed = make_editor(4, 10, 200);
        let vp = Rect::new(0.0, 0.0, 80.0, 24.0);
        let l = ed.layout(vp, 1.0, 1.0);
        assert!(l.h_scrollbar_bounds.is_some());
        let hsb = l.h_scrollbar_bounds.unwrap();
        assert_eq!(hsb.y, 23.0); // bottom row
        assert_eq!(hsb.height, 1.0);
    }

    #[test]
    fn editor_hit_test_text_area() {
        let mut ed = make_editor(4, 100, 40);
        ed.scroll_top = 10;
        ed.scroll_left = 5;
        let vp = Rect::new(0.0, 0.0, 80.0, 24.0);
        let l = ed.layout(vp, 1.0, 1.0);
        // Click at text_bounds origin → line=scroll_top, col=scroll_left.
        assert_eq!(
            l.hit_test(4.0, 0.0),
            EditorHit::BufferPos { line: 10, col: 5 }
        );
        // Click 3 cols in, 2 rows down.
        assert_eq!(
            l.hit_test(7.0, 2.0),
            EditorHit::BufferPos { line: 12, col: 8 }
        );
    }

    #[test]
    fn editor_hit_test_gutter() {
        let mut ed = make_editor(4, 100, 40);
        ed.scroll_top = 5;
        let vp = Rect::new(0.0, 0.0, 80.0, 24.0);
        let l = ed.layout(vp, 1.0, 1.0);
        assert_eq!(
            l.hit_test(1.0, 3.0),
            EditorHit::Gutter {
                line_idx: 8,
                gutter_col: 1
            }
        );
    }

    #[test]
    fn editor_hit_test_v_scrollbar() {
        let ed = make_editor(4, 100, 40);
        let vp = Rect::new(0.0, 0.0, 80.0, 24.0);
        let l = ed.layout(vp, 1.0, 1.0);
        assert_eq!(l.hit_test(79.0, 5.0), EditorHit::VScrollbar);
    }

    #[test]
    fn editor_hit_test_h_scrollbar() {
        let ed = make_editor(4, 10, 200);
        let vp = Rect::new(0.0, 0.0, 80.0, 24.0);
        let l = ed.layout(vp, 1.0, 1.0);
        assert_eq!(l.hit_test(10.0, 23.0), EditorHit::HScrollbar);
    }

    #[test]
    fn editor_hit_test_outside() {
        let ed = make_editor(4, 100, 40);
        let vp = Rect::new(10.0, 10.0, 80.0, 24.0);
        let l = ed.layout(vp, 1.0, 1.0);
        assert_eq!(l.hit_test(5.0, 5.0), EditorHit::Empty);
    }

    #[test]
    fn editor_layout_pixel_units() {
        let ed = make_editor(4, 500, 200);
        let vp = Rect::new(0.0, 0.0, 800.0, 600.0);
        let l = ed.layout(vp, 8.0, 16.0);
        // Gutter: 4 * 8 = 32px.
        let g = l.gutter_bounds.unwrap();
        assert_eq!(g.width, 32.0);
        // V-scrollbar: 8px wide (one cell_width).
        let vsb = l.v_scrollbar_bounds.unwrap();
        assert_eq!(vsb.width, 8.0);
        // Text area: 800 - 32 - 8 = 760px.
        assert_eq!(l.text_bounds.width, 760.0);
        // visible_cols = 760 / 8 = 95
        assert_eq!(l.visible_cols, 95);
        // visible_lines with h_scrollbar: (600 - 16) / 16 = 36
        assert_eq!(l.visible_lines, 36);
    }

    // ── EditorLayout::col_at_x ──────────────────────────────────────

    fn line_with_segment_offset(segment_col_offset: usize) -> EditorLine {
        EditorLine {
            raw_text: "wrapped segment text".into(),
            gutter_text: String::new(),
            spans: Vec::new(),
            line_idx: 0,
            is_current_line: false,
            is_fold_header: false,
            folded_line_count: 0,
            git_diff: None,
            diff_status: None,
            diagnostics: Vec::new(),
            spell_errors: Vec::new(),
            is_breakpoint: false,
            is_conditional_bp: false,
            is_dap_current: false,
            is_wrap_continuation: segment_col_offset > 0,
            segment_col_offset,
            annotation: None,
            ghost_suffix: None,
            is_ghost_continuation: false,
            indent_guides: Vec::new(),
            colorcolumns: Vec::new(),
        }
    }

    #[test]
    fn editor_col_at_x_matches_hit_test_in_monospace_case() {
        // Non-wrapped row (segment_col_offset == 0): col_at_x must agree
        // with hit_test's BufferPos.col exactly, since both use the same
        // uniform cell-division formula.
        let mut ed = make_editor(4, 100, 40);
        ed.scroll_top = 10;
        ed.scroll_left = 5;
        ed.lines = vec![line_with_segment_offset(0)];
        let vp = Rect::new(0.0, 0.0, 80.0, 24.0);
        let l = ed.layout(vp, 1.0, 1.0);

        match l.hit_test(7.0, 2.0) {
            EditorHit::BufferPos { col, .. } => {
                assert_eq!(l.col_at_x(&ed, 2, 7.0), col);
            }
            other => panic!("expected BufferPos, got {other:?}"),
        }
    }

    #[test]
    fn editor_col_at_x_adds_segment_col_offset_for_wrapped_rows() {
        // A wrap-continuation row's resolved column must be shifted by
        // its segment_col_offset so it lands at the right buffer column,
        // not the visual column within the wrapped segment.
        let mut ed = make_editor(4, 100, 40);
        ed.lines = vec![line_with_segment_offset(20)];
        let vp = Rect::new(0.0, 0.0, 80.0, 24.0);
        let l = ed.layout(vp, 1.0, 1.0);

        // Click at text_bounds origin (col_offset == 0, scroll_left == 0):
        // resolved column should be exactly the segment offset.
        assert_eq!(l.col_at_x(&ed, 0, l.text_bounds.x), 20);
        // 3 cells further right adds 3.
        assert_eq!(l.col_at_x(&ed, 0, l.text_bounds.x + 3.0), 23);
    }

    #[test]
    fn editor_col_at_x_out_of_range_row_falls_back_to_scroll_left() {
        let mut ed = make_editor(4, 100, 40);
        ed.scroll_left = 7;
        ed.lines = Vec::new();
        let vp = Rect::new(0.0, 0.0, 80.0, 24.0);
        let l = ed.layout(vp, 1.0, 1.0);
        assert_eq!(l.col_at_x(&ed, 0, l.text_bounds.x), 7);
    }

    // ── EditorLayout::x_at_col ──────────────────────────────────────

    #[test]
    fn editor_x_at_col_round_trips_with_col_at_x_in_monospace_case() {
        let mut ed = make_editor(4, 100, 40);
        ed.scroll_top = 10;
        ed.scroll_left = 5;
        ed.lines = vec![line_with_segment_offset(0)];
        let vp = Rect::new(0.0, 0.0, 80.0, 24.0);
        let l = ed.layout(vp, 1.0, 1.0);

        let col = l.col_at_x(&ed, 2, 7.0);
        let x = l.x_at_col(&ed, 2, col);
        assert_eq!(l.col_at_x(&ed, 2, x), col);
    }

    #[test]
    fn editor_x_at_col_subtracts_segment_col_offset_for_wrapped_rows() {
        // Inverse of editor_col_at_x_adds_segment_col_offset_for_wrapped_rows:
        // a column within a wrap-continuation row's segment must resolve
        // back to the same x col_at_x derived it from.
        let mut ed = make_editor(4, 100, 40);
        ed.lines = vec![line_with_segment_offset(20)];
        let vp = Rect::new(0.0, 0.0, 80.0, 24.0);
        let l = ed.layout(vp, 1.0, 1.0);

        assert_eq!(l.x_at_col(&ed, 0, 20), l.text_bounds.x);
        assert_eq!(l.x_at_col(&ed, 0, 23), l.text_bounds.x + 3.0);
    }

    #[test]
    fn editor_x_at_col_out_of_range_row_falls_back_to_scroll_left() {
        let mut ed = make_editor(4, 100, 40);
        ed.scroll_left = 7;
        ed.lines = Vec::new();
        let vp = Rect::new(0.0, 0.0, 80.0, 24.0);
        let l = ed.layout(vp, 1.0, 1.0);
        assert_eq!(l.x_at_col(&ed, 0, 7), l.text_bounds.x);
    }

    #[test]
    fn editor_col_at_x_and_x_at_col_round_trip_over_a_range() {
        // The property the issue asks for directly: col_at_x(x_at_col(c))
        // == c for every valid on-screen column.
        let mut ed = make_editor(4, 100, 40);
        ed.scroll_left = 3;
        ed.lines = vec![line_with_segment_offset(2)];
        let vp = Rect::new(0.0, 0.0, 80.0, 24.0);
        let l = ed.layout(vp, 1.0, 1.0);

        let base = l.scroll_left + 2; // segment_col_offset
        for col in base..base + 20 {
            let x = l.x_at_col(&ed, 0, col);
            assert_eq!(
                l.col_at_x(&ed, 0, x),
                col,
                "round-trip failed for col {col}"
            );
        }
    }

    // ── `EditorSelection::cols_on` ──────────────────────────────────────

    /// Builds a minimal [`EditorLine`] for `cols_on` tests, varying only
    /// the fields that drive its column math.
    fn cols_line(
        line_idx: usize,
        raw_text: &str,
        segment_col_offset: usize,
        is_ghost_continuation: bool,
        diff_status: Option<DiffLine>,
    ) -> EditorLine {
        EditorLine {
            raw_text: raw_text.into(),
            gutter_text: String::new(),
            spans: Vec::new(),
            line_idx,
            is_current_line: false,
            is_fold_header: false,
            folded_line_count: 0,
            git_diff: None,
            diff_status,
            diagnostics: Vec::new(),
            spell_errors: Vec::new(),
            is_breakpoint: false,
            is_conditional_bp: false,
            is_dap_current: false,
            is_wrap_continuation: segment_col_offset > 0,
            segment_col_offset,
            annotation: None,
            ghost_suffix: None,
            is_ghost_continuation,
            indent_guides: Vec::new(),
            colorcolumns: Vec::new(),
        }
    }

    fn plain(line_idx: usize, raw_text: &str) -> EditorLine {
        cols_line(line_idx, raw_text, 0, false, None)
    }

    /// Plain line × Char selection: single-line range is `[start_col,
    /// end_col + 1)`, doesn't extend past its own text.
    #[test]
    fn cols_on_plain_line_char_selection() {
        let line = plain(0, "hello world");
        let sel = EditorSelection {
            kind: SelectionKind::Char,
            start_line: 0,
            start_col: 2,
            end_line: 0,
            end_col: 5,
        };
        let cols = sel.cols_on(&line).expect("line is within selection range");
        assert_eq!((cols.start, cols.end), (2, 6));
        assert!(!cols.extends_beyond);
    }

    /// A line outside `[start_line, end_line]` is not selected at all.
    #[test]
    fn cols_on_returns_none_outside_selection_line_range() {
        let sel = EditorSelection {
            kind: SelectionKind::Char,
            start_line: 3,
            start_col: 0,
            end_line: 5,
            end_col: 0,
        };
        assert_eq!(sel.cols_on(&plain(1, "before")), None);
        assert_eq!(sel.cols_on(&plain(6, "after")), None);
        assert!(sel.cols_on(&plain(4, "inside")).is_some());
    }

    /// A ghost-text continuation row is virtual (no buffer columns) and
    /// must never be selected, even when its `line_idx` falls inside the
    /// selection's buffer-line range (ghost rows repeat the owning
    /// line's `line_idx`).
    #[test]
    fn cols_on_ghost_continuation_row_is_none() {
        let line = cols_line(0, "", 0, true, None);
        let sel = EditorSelection {
            kind: SelectionKind::Line,
            start_line: 0,
            start_col: 0,
            end_line: 0,
            end_col: 0,
        };
        assert_eq!(sel.cols_on(&line), None);
    }

    /// A diff-padding filler row has no buffer content and must never be
    /// selected.
    #[test]
    fn cols_on_diff_padding_row_is_none() {
        let line = cols_line(2, "", 0, false, Some(DiffLine::Padding));
        let sel = EditorSelection {
            kind: SelectionKind::Block,
            start_line: 0,
            start_col: 0,
            end_line: 4,
            end_col: 3,
        };
        assert_eq!(sel.cols_on(&line), None);
    }

    /// Diff statuses other than `Padding` don't suppress selection.
    #[test]
    fn cols_on_diff_added_row_is_still_selectable() {
        let line = cols_line(0, "added line", 0, false, Some(DiffLine::Added));
        let sel = EditorSelection {
            kind: SelectionKind::Char,
            start_line: 0,
            start_col: 0,
            end_line: 0,
            end_col: 2,
        };
        assert_eq!(sel.cols_on(&line).map(|c| (c.start, c.end)), Some((0, 3)));
    }

    /// A wrap-continuation segment's returned columns are already
    /// shifted into segment-local space (subtract nothing further) — a
    /// selection covering buffer columns `[10, 25)` on a row whose
    /// `segment_col_offset` is 10 (this segment's own text spans buffer
    /// columns `[10, 30)`) highlights local columns `[0, 15)`.
    #[test]
    fn cols_on_wrapped_segment_offsets_into_local_columns() {
        let line = cols_line(0, &"x".repeat(20), 10, false, None);
        let sel = EditorSelection {
            kind: SelectionKind::Char,
            start_line: 0,
            start_col: 10,
            end_line: 0,
            end_col: 24,
        };
        let cols = sel.cols_on(&line).expect("segment overlaps selection");
        assert_eq!((cols.start, cols.end), (0, 15));
        assert!(!cols.extends_beyond);
    }

    /// A selection entirely before a wrapped segment's own columns
    /// doesn't touch that segment.
    #[test]
    fn cols_on_wrapped_segment_before_selection_is_none() {
        let line = cols_line(0, &"x".repeat(20), 10, false, None);
        let sel = EditorSelection {
            kind: SelectionKind::Char,
            start_line: 0,
            start_col: 0,
            end_line: 0,
            end_col: 4,
        };
        assert_eq!(sel.cols_on(&line), None);
    }

    /// A multi-line Char selection that continues past this segment's
    /// own text sets `extends_beyond` — the flag pixel-measuring
    /// backends (GTK/macOS) use to extend the highlight to the edge of
    /// the rendered line instead of stopping at the last character.
    #[test]
    fn cols_on_char_selection_spanning_multiple_lines_extends_beyond_last_line() {
        let line = plain(0, "short");
        let sel = EditorSelection {
            kind: SelectionKind::Char,
            start_line: 0,
            start_col: 0,
            end_line: 2,
            end_col: 3,
        };
        let cols = sel.cols_on(&line).expect("first line is in range");
        assert_eq!((cols.start, cols.end), (0, 5));
        assert!(
            cols.extends_beyond,
            "line 0 isn't the selection's last line"
        );
    }

    /// `SelectionKind::Line` always spans the whole row and always sets
    /// `extends_beyond` (a line selection is never bounded by its own
    /// text length).
    #[test]
    fn cols_on_line_kind_always_extends_beyond() {
        let line = plain(1, "abc");
        let sel = EditorSelection {
            kind: SelectionKind::Line,
            start_line: 0,
            start_col: 99, // ignored for Line
            end_line: 2,
            end_col: 99, // ignored for Line
        };
        let cols = sel.cols_on(&line).expect("line 1 is within [0, 2]");
        assert!(cols.extends_beyond);
    }

    /// `SelectionKind::Block` applies the exact same `[start_col,
    /// end_col]` column window to every covered line — unlike `Char`,
    /// it does not widen to the full line on interior rows.
    #[test]
    fn cols_on_block_kind_uses_same_columns_on_every_line() {
        let sel = EditorSelection {
            kind: SelectionKind::Block,
            start_line: 0,
            start_col: 2,
            end_line: 2,
            end_col: 4,
        };
        for idx in 0..=2 {
            let line = plain(idx, "0123456789");
            let cols = sel.cols_on(&line).unwrap();
            assert_eq!((cols.start, cols.end), (2, 5), "line {idx}");
        }
    }

    /// A blank buffer line inside a multi-line Char/Block selection still
    /// gets one highlighted column (vim's convention: a selected empty
    /// line shows a cursor-width highlight rather than nothing).
    #[test]
    fn cols_on_blank_interior_line_highlights_one_column() {
        let line = plain(1, "");
        let sel = EditorSelection {
            kind: SelectionKind::Char,
            start_line: 0,
            start_col: 5,
            end_line: 2,
            end_col: 1,
        };
        let cols = sel.cols_on(&line).expect("blank interior line is selected");
        assert_eq!((cols.start, cols.end), (0, 1));
    }

    // ── `new`/`with_*`/`Default` builders ──────────────────────────────

    /// `Default::default()` matches `Editor::new` with an empty id and a
    /// zero `Rect` — the `new(required…)`/`with_*`/`Default` trio only
    /// differs in what `id`/`rect` it carries.
    #[test]
    fn default_matches_new_with_empty_id_and_rect() {
        assert_eq!(
            Editor::default(),
            Editor::new(WidgetId::new(""), Rect::default())
        );
    }

    /// Chaining every `with_*` builder reaches exactly the values the
    /// exhaustive literal in `tests/downstream_struct_literals.rs` sets
    /// field-for-field, without writing a struct literal at all.
    #[test]
    fn with_builders_reach_every_field_a_struct_literal_can_set() {
        let ed = Editor::new(WidgetId::new("editor:0"), Rect::new(0.0, 0.0, 80.0, 24.0))
            .with_cursor(EditorCursor {
                pos: CursorPos {
                    view_line: 0,
                    col: 0,
                },
                shape: CursorShape::Bar,
            })
            .with_is_active(true)
            .with_tabstop(4)
            .with_cursorline(true);

        assert_eq!(
            ed,
            Editor {
                id: WidgetId::new("editor:0"),
                rect: Rect::new(0.0, 0.0, 80.0, 24.0),
                lines: Vec::new(),
                cursor: Some(EditorCursor {
                    pos: CursorPos {
                        view_line: 0,
                        col: 0,
                    },
                    shape: CursorShape::Bar,
                }),
                extra_cursors: Vec::new(),
                selection: None,
                extra_selections: Vec::new(),
                yank_highlight: None,
                scroll_top: 0,
                scroll_left: 0,
                total_lines: 0,
                max_col: 0,
                gutter_char_width: 0,
                is_active: true,
                show_active_bg: false,
                has_git_diff: false,
                has_breakpoints: false,
                diagnostic_gutter: HashMap::new(),
                code_action_lines: HashSet::new(),
                bracket_match_positions: Vec::new(),
                active_indent_col: None,
                tabstop: 4,
                cursorline: true,
                lightbulb_glyph: '!',
            }
        );
    }
}