iced-code-editor 0.3.8

A custom code editor widget for the Iced GUI framework with syntax highlighting, line numbers, and scrolling support.
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
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
//! Canvas-based text editor widget for maximum performance.
//!
//! This module provides a custom Canvas widget that handles all text rendering
//! and input directly, bypassing Iced's higher-level widgets for optimal speed.

use iced::advanced::text::{
    Alignment, Paragraph, Renderer as TextRenderer, Text,
};
use iced::widget::operation::{RelativeOffset, snap_to};
use iced::widget::{Id, canvas};
use std::cell::{Cell, RefCell};
use std::cmp::Ordering as CmpOrdering;
use std::ops::Range;
use std::rc::Rc;
use std::sync::atomic::{AtomicU64, Ordering};
#[cfg(not(target_arch = "wasm32"))]
use std::time::Instant;
use unicode_width::UnicodeWidthChar;

use crate::i18n::Translations;
use crate::text_buffer::TextBuffer;
use crate::theme::Style;
pub use history::CommandHistory;

#[cfg(target_arch = "wasm32")]
use web_time::Instant;

/// Global counter for generating unique editor IDs (starts at 1)
static EDITOR_ID_COUNTER: AtomicU64 = AtomicU64::new(1);

/// ID of the currently focused editor (0 = no editor focused)
static FOCUSED_EDITOR_ID: AtomicU64 = AtomicU64::new(0);

// Re-export submodules
mod canvas_impl;
mod clipboard;
pub mod command;
mod cursor;
pub(crate) mod cursor_set;
pub mod history;
pub mod ime_requester;
pub mod lsp;
#[cfg(all(feature = "lsp-process", not(target_arch = "wasm32")))]
pub mod lsp_process;
mod search;
mod search_dialog;
mod selection;
mod update;
mod view;
mod wrapping;

/// Canvas-based text editor constants
pub(crate) const FONT_SIZE: f32 = 14.0;
pub(crate) const LINE_HEIGHT: f32 = 20.0;
pub(crate) const CHAR_WIDTH: f32 = 8.4; // Monospace character width
pub(crate) const TAB_WIDTH: usize = 4;
pub(crate) const GUTTER_WIDTH: f32 = 45.0;
pub(crate) const CURSOR_BLINK_INTERVAL: std::time::Duration =
    std::time::Duration::from_millis(530);

/// Measures the width of a single character.
///
/// # Arguments
///
/// * `c` - The character to measure
/// * `full_char_width` - The width of a full-width character
/// * `char_width` - The width of the character
///
/// # Returns
///
/// The calculated width of the character as a `f32`
pub(crate) fn measure_char_width(
    c: char,
    full_char_width: f32,
    char_width: f32,
) -> f32 {
    if c == '\t' {
        return char_width * TAB_WIDTH as f32;
    }
    match c.width() {
        Some(w) if w > 1 => full_char_width,
        Some(_) => char_width,
        None => 0.0,
    }
}

/// Measures rendered text width, accounting for CJK wide characters.
///
/// - Wide characters (e.g. Chinese) use FONT_SIZE.
/// - Narrow characters (e.g. Latin) use CHAR_WIDTH.
/// - Control characters (except tab) have width 0.
///
/// # Arguments
///
/// * `text` - The text string to measure
/// * `full_char_width` - The width of a full-width character
/// * `char_width` - The width of a regular character
///
/// # Returns
///
/// The total calculated width of the text as a `f32`
pub(crate) fn measure_text_width(
    text: &str,
    full_char_width: f32,
    char_width: f32,
) -> f32 {
    text.chars()
        .map(|c| measure_char_width(c, full_char_width, char_width))
        .sum()
}

/// Epsilon value for floating-point comparisons in text layout.
pub(crate) const EPSILON: f32 = 0.001;
/// Multiplier used to extend the cached render window beyond the visible range.
/// The cache window margin is computed as:
///     margin = visible_lines_count * CACHE_WINDOW_MARGIN_MULTIPLIER
/// A larger margin reduces how often we clear and rebuild the canvas cache when
/// scrolling, improving performance on very large files while still ensuring
/// correct initial rendering during the first scroll.
pub(crate) const CACHE_WINDOW_MARGIN_MULTIPLIER: usize = 2;

/// Compares two floating point numbers with a small epsilon tolerance.
///
/// # Arguments
///
/// * `a` - first float number
/// * `b` - second float number
///
/// # Returns
///
/// * `Ordering::Equal` if `abs(a - b) < EPSILON`
/// * `Ordering::Greater` if `a > b` (and not equal)
/// * `Ordering::Less` if `a < b` (and not equal)
pub(crate) fn compare_floats(a: f32, b: f32) -> CmpOrdering {
    if (a - b).abs() < EPSILON {
        CmpOrdering::Equal
    } else if a > b {
        CmpOrdering::Greater
    } else {
        CmpOrdering::Less
    }
}

#[derive(Debug, Clone)]
pub(crate) struct ImePreedit {
    pub(crate) content: String,
    pub(crate) selection: Option<Range<usize>>,
}

/// Canvas-based high-performance text editor.
pub struct CodeEditor {
    /// Unique ID for this editor instance (for focus management)
    pub(crate) editor_id: u64,
    /// Text buffer
    pub(crate) buffer: TextBuffer,
    /// All cursor positions (multi-cursor support).
    pub(crate) cursors: cursor_set::CursorSet,
    /// Horizontal scroll offset in pixels, only used when wrap_enabled = false
    pub(crate) horizontal_scroll_offset: f32,
    /// Editor theme style
    pub(crate) style: Style,
    /// Syntax highlighting language
    pub(crate) syntax: String,
    /// Last cursor blink time
    pub(crate) last_blink: Instant,
    /// Cursor visible state
    pub(crate) cursor_visible: bool,
    /// Mouse is currently dragging for selection
    pub(crate) is_dragging: bool,
    /// Cached geometry for the "content" layer.
    ///
    /// This layer includes expensive-to-build, mostly static visuals such as:
    /// - syntax-highlighted text glyphs
    /// - line numbers / gutter text
    ///
    /// It is intentionally kept stable across selection/cursor movement so
    /// that mouse-drag selection feels smooth.
    pub(crate) content_cache: canvas::Cache,
    /// Cached geometry for the "overlay" layer.
    ///
    /// This layer includes visuals that change frequently without modifying the
    /// underlying buffer, such as:
    /// - cursor and current-line highlight
    /// - selection highlight
    /// - search match highlights
    /// - IME preedit decorations
    ///
    /// Keeping overlays in a separate cache avoids invalidating the content
    /// layer on every cursor blink or selection drag.
    pub(crate) overlay_cache: canvas::Cache,
    /// Scrollable ID for programmatic scrolling
    pub(crate) scrollable_id: Id,
    /// ID for the horizontal scrollable widget (only used when wrap_enabled = false)
    pub(crate) horizontal_scrollable_id: Id,
    /// Cache for max content width: (buffer_revision, width_in_pixels)
    pub(crate) max_content_width_cache: RefCell<Option<(u64, f32)>>,
    /// Current viewport scroll position (Y offset)
    pub(crate) viewport_scroll: f32,
    /// Viewport height (visible area)
    pub(crate) viewport_height: f32,
    /// Viewport width (visible area)
    pub(crate) viewport_width: f32,
    /// Command history for undo/redo
    pub(crate) history: CommandHistory,
    /// Whether we're currently grouping commands (for smart undo)
    pub(crate) is_grouping: bool,
    /// Line wrapping enabled
    pub(crate) wrap_enabled: bool,
    /// Auto-indentation enabled
    pub(crate) auto_indent_enabled: bool,
    /// Indentation style (spaces or tab)
    pub(crate) indent_style: IndentStyle,
    /// Wrap column (None = wrap at viewport width)
    pub(crate) wrap_column: Option<usize>,
    /// Search state
    pub(crate) search_state: search::SearchState,
    /// Translations for UI text
    pub(crate) translations: Translations,
    /// Whether search/replace functionality is enabled
    pub(crate) search_replace_enabled: bool,
    /// Whether line numbers are displayed
    pub(crate) line_numbers_enabled: bool,
    /// Whether LSP support is enabled
    pub(crate) lsp_enabled: bool,
    /// Active LSP client connection, if configured.
    pub(crate) lsp_client: Option<Box<dyn lsp::LspClient>>,
    /// Metadata for the currently open LSP document.
    pub(crate) lsp_document: Option<lsp::LspDocument>,
    /// Pending incremental LSP text changes not yet flushed.
    pub(crate) lsp_pending_changes: Vec<lsp::LspTextChange>,
    /// Shadow copy of buffer content used to compute LSP deltas.
    pub(crate) lsp_shadow_text: String,
    /// Whether to auto-flush LSP changes after edits.
    pub(crate) lsp_auto_flush: bool,
    /// Whether the canvas has user input focus (for keyboard events)
    pub(crate) has_canvas_focus: bool,
    /// Whether input processing is locked to prevent focus stealing
    pub(crate) focus_locked: bool,
    /// Whether to show the cursor (for rendering)
    pub(crate) show_cursor: bool,
    /// Current keyboard modifiers state (Ctrl, Alt, Shift, Logo).
    ///
    /// This is updated via subscription events and used to handle modifier-dependent
    /// interactions, such as "Ctrl+Click" for jumping to a definition.
    pub(crate) modifiers: Cell<iced::keyboard::Modifiers>,
    /// The font used for rendering text
    pub(crate) font: iced::Font,
    /// IME pre-edit state (for CJK input)
    pub(crate) ime_preedit: Option<ImePreedit>,
    /// Font size in pixels
    pub(crate) font_size: f32,
    /// Full character width (wide chars like CJK) in pixels
    pub(crate) full_char_width: f32,
    /// Line height in pixels
    pub(crate) line_height: f32,
    /// Character width in pixels
    pub(crate) char_width: f32,
    /// Cached render window: the first visual line index included in the cache.
    /// We keep a larger window than the currently visible range to avoid clearing
    /// the canvas cache on every small scroll. Only when scrolling crosses the
    /// window boundary do we re-window and clear the cache.
    pub(crate) last_first_visible_line: usize,
    /// Cached render window start line (inclusive)
    pub(crate) cache_window_start_line: usize,
    /// Cached render window end line (exclusive)
    pub(crate) cache_window_end_line: usize,
    /// Monotonic revision counter for buffer content.
    ///
    /// Any operation that changes the buffer must bump this counter to
    /// invalidate derived layout caches (e.g. wrapping / visual lines). The
    /// exact value is not semantically meaningful, so `wrapping_add` is used to
    /// avoid overflow panics while still producing a different key.
    pub(crate) buffer_revision: u64,
    /// Cached result of line wrapping ("visual lines") for the current layout key.
    ///
    /// This is stored behind a `RefCell` because wrapping is needed during
    /// rendering (where we only have `&self`), but we still want to memoize the
    /// expensive computation without forcing external mutability.
    visual_lines_cache: RefCell<Option<VisualLinesCache>>,
}

#[derive(Clone, Copy, PartialEq, Eq)]
struct VisualLinesKey {
    buffer_revision: u64,
    /// `f32::to_bits()` is used so the cache key is stable and exact:
    /// - no epsilon comparisons are required
    /// - NaN payloads (if any) do not collapse unexpectedly
    viewport_width_bits: u32,
    gutter_width_bits: u32,
    wrap_enabled: bool,
    wrap_column: Option<usize>,
    full_char_width_bits: u32,
    char_width_bits: u32,
}

struct VisualLinesCache {
    key: VisualLinesKey,
    visual_lines: Rc<Vec<wrapping::VisualLine>>,
}

/// Messages emitted by the code editor
#[derive(Debug, Clone)]
pub enum Message {
    /// Character typed
    CharacterInput(char),
    /// Backspace pressed
    Backspace,
    /// Delete pressed
    Delete,
    /// Enter pressed
    Enter,
    /// Tab pressed (inserts 4 spaces)
    Tab,
    /// Arrow key pressed (direction, shift_pressed)
    ArrowKey(ArrowDirection, bool),
    /// Mouse clicked at position
    MouseClick(iced::Point),
    /// Mouse drag for selection
    MouseDrag(iced::Point),
    /// Mouse moved within the editor without dragging
    MouseHover(iced::Point),
    /// Mouse released
    MouseRelease,
    /// Copy selected text (Ctrl+C)
    Copy,
    /// Paste text from clipboard (Ctrl+V)
    Paste(String),
    /// Delete selected text (Shift+Delete)
    DeleteSelection,
    /// Request redraw for cursor blink
    Tick,
    /// Page Up pressed
    PageUp,
    /// Page Down pressed
    PageDown,
    /// Home key pressed (move to start of line, shift_pressed)
    Home(bool),
    /// End key pressed (move to end of line, shift_pressed)
    End(bool),
    /// Ctrl+Home pressed (move to start of document)
    CtrlHome,
    /// Ctrl+End pressed (move to end of document)
    CtrlEnd,
    /// Go to an explicit logical position (line, column), both 0-based.
    GotoPosition(usize, usize),
    /// Viewport scrolled - track scroll position
    Scrolled(iced::widget::scrollable::Viewport),
    /// Horizontal scrollbar scrolled (only when wrap is disabled)
    HorizontalScrolled(iced::widget::scrollable::Viewport),
    /// Undo last operation (Ctrl+Z)
    Undo,
    /// Redo last undone operation (Ctrl+Y)
    Redo,
    /// Open search dialog (Ctrl+F)
    OpenSearch,
    /// Open search and replace dialog (Ctrl+H)
    OpenSearchReplace,
    /// Close search dialog (Escape)
    CloseSearch,
    /// Search query text changed
    SearchQueryChanged(String),
    /// Replace text changed
    ReplaceQueryChanged(String),
    /// Toggle case sensitivity
    ToggleCaseSensitive,
    /// Find next match (F3)
    FindNext,
    /// Find previous match (Shift+F3)
    FindPrevious,
    /// Replace current match
    ReplaceNext,
    /// Replace all matches
    ReplaceAll,
    /// Tab pressed in search dialog (cycle forward)
    SearchDialogTab,
    /// Shift+Tab pressed in search dialog (cycle backward)
    SearchDialogShiftTab,
    /// Tab pressed for focus navigation (when search dialog is not open)
    FocusNavigationTab,
    /// Shift+Tab pressed for focus navigation (when search dialog is not open)
    FocusNavigationShiftTab,
    /// Canvas gained focus (mouse click)
    CanvasFocusGained,
    /// Canvas lost focus (external widget interaction)
    CanvasFocusLost,
    /// Triggered when the user performs a Ctrl+Click (or Cmd+Click on macOS)
    /// on the editor content, intending to jump to the definition of the symbol
    /// under the cursor.
    JumpClick(iced::Point),
    /// IME input method opened
    ImeOpened,
    /// IME pre-edit update (content, selection range)
    ImePreedit(String, Option<Range<usize>>),
    /// IME commit text
    ImeCommit(String),
    /// IME input method closed
    ImeClosed,
    /// Alt+Click: add a new cursor at the given canvas position
    AltClick(iced::Point),
    /// Ctrl+Alt+Up: add a cursor on the line above the primary cursor
    AddCursorAbove,
    /// Ctrl+Alt+Down: add a cursor on the line below the primary cursor
    AddCursorBelow,
    /// Ctrl+D: select the next occurrence of the currently selected text (or word under cursor)
    SelectNextOccurrence,
}

/// Indentation style used when pressing the Tab key.
///
/// Controls whether indentation inserts spaces or a tab character.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IndentStyle {
    /// Insert `n` space characters.
    Spaces(u8),
    /// Insert a single tab character (`\t`).
    Tab,
}

impl IndentStyle {
    /// All standard indentation styles available for selection.
    pub const ALL: [IndentStyle; 4] = [
        IndentStyle::Spaces(2),
        IndentStyle::Spaces(4),
        IndentStyle::Spaces(8),
        IndentStyle::Tab,
    ];
}

impl std::fmt::Display for IndentStyle {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            IndentStyle::Spaces(1) => write!(f, "1 space"),
            IndentStyle::Spaces(n) => write!(f, "{n} spaces"),
            IndentStyle::Tab => write!(f, "Tab"),
        }
    }
}

/// Arrow key directions
#[derive(Debug, Clone, Copy)]
pub enum ArrowDirection {
    Up,
    Down,
    Left,
    Right,
}

impl CodeEditor {
    /// Creates a new canvas-based text editor.
    ///
    /// # Arguments
    ///
    /// * `content` - Initial text content
    /// * `syntax` - Syntax highlighting language (e.g., "py", "lua", "rs")
    ///
    /// # Returns
    ///
    /// A new `CodeEditor` instance
    pub fn new(content: &str, syntax: &str) -> Self {
        // Generate a unique ID for this editor instance
        let editor_id = EDITOR_ID_COUNTER.fetch_add(1, Ordering::Relaxed);

        // Give focus to the first editor created (ID == 1)
        if editor_id == 1 {
            FOCUSED_EDITOR_ID.store(editor_id, Ordering::Relaxed);
        }

        let mut editor = Self {
            editor_id,
            buffer: TextBuffer::new(content),
            cursors: cursor_set::CursorSet::new((0, 0)),
            horizontal_scroll_offset: 0.0,
            style: crate::theme::from_iced_theme(&iced::Theme::TokyoNightStorm),
            syntax: syntax.to_string(),
            last_blink: Instant::now(),
            cursor_visible: true,
            is_dragging: false,
            content_cache: canvas::Cache::default(),
            overlay_cache: canvas::Cache::default(),
            scrollable_id: Id::unique(),
            horizontal_scrollable_id: Id::unique(),
            max_content_width_cache: RefCell::new(None),
            viewport_scroll: 0.0,
            viewport_height: 600.0, // Default, will be updated
            viewport_width: 800.0,  // Default, will be updated
            history: CommandHistory::new(100),
            is_grouping: false,
            wrap_enabled: true,
            auto_indent_enabled: true,
            indent_style: IndentStyle::Spaces(4),
            wrap_column: None,
            search_state: search::SearchState::new(),
            translations: Translations::default(),
            search_replace_enabled: true,
            line_numbers_enabled: true,
            lsp_enabled: true,
            lsp_client: None,
            lsp_document: None,
            lsp_pending_changes: Vec::new(),
            lsp_shadow_text: String::new(),
            lsp_auto_flush: true,
            has_canvas_focus: false,
            focus_locked: false,
            show_cursor: false,
            modifiers: Cell::new(iced::keyboard::Modifiers::default()),
            font: iced::Font::MONOSPACE,
            ime_preedit: None,
            font_size: FONT_SIZE,
            full_char_width: CHAR_WIDTH * 2.0,
            line_height: LINE_HEIGHT,
            char_width: CHAR_WIDTH,
            // Initialize render window tracking for virtual scrolling:
            // these indices define the cached visual line window. The window is
            // expanded beyond the visible range to amortize redraws and keep scrolling smooth.
            last_first_visible_line: 0,
            cache_window_start_line: 0,
            cache_window_end_line: 0,
            buffer_revision: 0,
            visual_lines_cache: RefCell::new(None),
        };

        // Perform initial character dimension calculation
        editor.recalculate_char_dimensions(false);

        editor
    }

    /// Sets the font used by the editor
    ///
    /// # Arguments
    ///
    /// * `font` - The iced font to set for the editor
    pub fn set_font(&mut self, font: iced::Font) {
        self.font = font;
        self.recalculate_char_dimensions(false);
    }

    /// Sets the font size and recalculates character dimensions.
    ///
    /// If `auto_adjust_line_height` is true, `line_height` will also be scaled to maintain
    /// the default proportion (Line Height ~ 1.43x).
    ///
    /// # Arguments
    ///
    /// * `size` - The font size in pixels
    /// * `auto_adjust_line_height` - Whether to automatically adjust the line height
    pub fn set_font_size(&mut self, size: f32, auto_adjust_line_height: bool) {
        self.font_size = size;
        self.recalculate_char_dimensions(auto_adjust_line_height);
    }

    /// Recalculates character dimensions based on current font and size.
    fn recalculate_char_dimensions(&mut self, auto_adjust_line_height: bool) {
        self.char_width = self.measure_single_char_width("a");
        // Use '汉' as a standard reference for CJK (Chinese, Japanese, Korean) wide characters
        self.full_char_width = self.measure_single_char_width("");

        // Fallback for infinite width measurements
        if self.char_width.is_infinite() {
            self.char_width = self.font_size / 2.0; // Rough estimate for monospace
        }

        if self.full_char_width.is_infinite() {
            self.full_char_width = self.font_size;
        }

        if auto_adjust_line_height {
            let line_height_ratio = LINE_HEIGHT / FONT_SIZE;
            self.line_height = self.font_size * line_height_ratio;
        }

        self.content_cache.clear();
        self.overlay_cache.clear();
    }

    /// Measures the width of a single character string using the current font settings.
    fn measure_single_char_width(&self, content: &str) -> f32 {
        let text = Text {
            content,
            font: self.font,
            size: iced::Pixels(self.font_size),
            line_height: iced::advanced::text::LineHeight::default(),
            bounds: iced::Size::new(f32::INFINITY, f32::INFINITY),
            align_x: Alignment::Left,
            align_y: iced::alignment::Vertical::Top,
            shaping: iced::advanced::text::Shaping::Advanced,
            wrapping: iced::advanced::text::Wrapping::default(),
        };
        let p = <iced::Renderer as TextRenderer>::Paragraph::with_text(text);
        p.min_width()
    }

    /// Returns the current font size.
    ///
    /// # Returns
    ///
    /// The font size in pixels
    pub fn font_size(&self) -> f32 {
        self.font_size
    }

    /// Returns the width of a standard narrow character in pixels.
    ///
    /// # Returns
    ///
    /// The character width in pixels
    pub fn char_width(&self) -> f32 {
        self.char_width
    }

    /// Returns the width of a wide character (e.g. CJK) in pixels.
    ///
    /// # Returns
    ///
    /// The full character width in pixels
    pub fn full_char_width(&self) -> f32 {
        self.full_char_width
    }

    /// Measures the rendered width for a given text snippet using editor metrics.
    pub fn measure_text_width(&self, text: &str) -> f32 {
        measure_text_width(text, self.full_char_width, self.char_width)
    }

    /// Sets the line height used by the editor
    ///
    /// # Arguments
    ///
    /// * `height` - The line height in pixels
    pub fn set_line_height(&mut self, height: f32) {
        self.line_height = height;
        self.content_cache.clear();
        self.overlay_cache.clear();
    }

    /// Returns the current line height.
    ///
    /// # Returns
    ///
    /// The line height in pixels
    pub fn line_height(&self) -> f32 {
        self.line_height
    }

    /// Returns the current viewport height in pixels.
    pub fn viewport_height(&self) -> f32 {
        self.viewport_height
    }

    /// Returns the current viewport width in pixels.
    pub fn viewport_width(&self) -> f32 {
        self.viewport_width
    }

    /// Returns the current vertical scroll offset in pixels.
    pub fn viewport_scroll(&self) -> f32 {
        self.viewport_scroll
    }

    /// Returns the current text content as a string.
    ///
    /// # Returns
    ///
    /// The complete text content of the editor
    pub fn content(&self) -> String {
        self.buffer.to_string()
    }

    /// Sets the viewport height for the editor.
    ///
    /// This determines the minimum height of the canvas, ensuring proper
    /// background rendering even when content is smaller than the viewport.
    ///
    /// # Arguments
    ///
    /// * `height` - The viewport height in pixels
    ///
    /// # Returns
    ///
    /// Self for method chaining
    ///
    /// # Example
    ///
    /// ```
    /// use iced_code_editor::CodeEditor;
    ///
    /// let editor = CodeEditor::new("fn main() {}", "rs")
    ///     .with_viewport_height(500.0);
    /// ```
    #[must_use]
    pub fn with_viewport_height(mut self, height: f32) -> Self {
        self.viewport_height = height;
        self
    }

    /// Sets the theme style for the editor.
    ///
    /// # Arguments
    ///
    /// * `style` - The style to apply to the editor
    ///
    /// # Example
    ///
    /// ```
    /// use iced_code_editor::{CodeEditor, theme};
    ///
    /// let mut editor = CodeEditor::new("fn main() {}", "rs");
    /// editor.set_theme(theme::from_iced_theme(&iced::Theme::TokyoNightStorm));
    /// ```
    pub fn set_theme(&mut self, style: Style) {
        self.style = style;
        self.content_cache.clear();
        self.overlay_cache.clear();
    }

    /// Sets the language for UI translations.
    ///
    /// This changes the language used for all UI text elements in the editor,
    /// including search dialog tooltips, placeholders, and labels.
    ///
    /// # Arguments
    ///
    /// * `language` - The language to use for UI text
    ///
    /// # Example
    ///
    /// ```
    /// use iced_code_editor::{CodeEditor, Language};
    ///
    /// let mut editor = CodeEditor::new("fn main() {}", "rs");
    /// editor.set_language(Language::French);
    /// ```
    pub fn set_language(&mut self, language: crate::i18n::Language) {
        self.translations.set_language(language);
        self.overlay_cache.clear();
    }

    /// Returns the current UI language.
    ///
    /// # Returns
    ///
    /// The currently active language for UI text
    ///
    /// # Example
    ///
    /// ```
    /// use iced_code_editor::{CodeEditor, Language};
    ///
    /// let editor = CodeEditor::new("fn main() {}", "rs");
    /// let current_lang = editor.language();
    /// ```
    pub fn language(&self) -> crate::i18n::Language {
        self.translations.language()
    }

    /// Attaches an LSP client and opens a document for the current buffer.
    ///
    /// This sends an initial `did_open` with the current buffer contents and
    /// resets any pending LSP change state.
    ///
    /// # Arguments
    ///
    /// * `client` - The LSP client to notify
    /// * `document` - Document metadata describing the buffer
    pub fn attach_lsp(
        &mut self,
        mut client: Box<dyn lsp::LspClient>,
        mut document: lsp::LspDocument,
    ) {
        if !self.lsp_enabled {
            return;
        }
        document.version = 1;
        let text = self.buffer.to_string();
        client.did_open(&document, &text);
        self.lsp_client = Some(client);
        self.lsp_document = Some(document);
        self.lsp_shadow_text = text;
        self.lsp_pending_changes.clear();
    }

    /// Opens a new document on the attached LSP client.
    ///
    /// If a document is already open, this will close it before opening the new
    /// one and reset pending change tracking.
    ///
    /// # Arguments
    ///
    /// * `document` - Document metadata describing the buffer
    pub fn lsp_open_document(&mut self, mut document: lsp::LspDocument) {
        let Some(client) = self.lsp_client.as_mut() else { return };
        if let Some(current) = self.lsp_document.as_ref() {
            client.did_close(current);
        }
        document.version = 1;
        let text = self.buffer.to_string();
        client.did_open(&document, &text);
        self.lsp_document = Some(document);
        self.lsp_shadow_text = text;
        self.lsp_pending_changes.clear();
    }

    /// Detaches the current LSP client and closes any open document.
    ///
    /// This clears all LSP-related state on the editor instance.
    pub fn detach_lsp(&mut self) {
        if let (Some(client), Some(document)) =
            (self.lsp_client.as_mut(), self.lsp_document.as_ref())
        {
            client.did_close(document);
        }
        self.lsp_client = None;
        self.lsp_document = None;
        self.lsp_shadow_text = String::new();
        self.lsp_pending_changes.clear();
    }

    /// Sends a `did_save` notification with the current buffer contents.
    pub fn lsp_did_save(&mut self) {
        if let (Some(client), Some(document)) =
            (self.lsp_client.as_mut(), self.lsp_document.as_ref())
        {
            let text = self.buffer.to_string();
            client.did_save(document, &text);
        }
    }

    /// Requests hover information at the current cursor position.
    pub fn lsp_request_hover(&mut self) {
        let position = self.lsp_position_from_cursor();
        if let (Some(client), Some(document)) =
            (self.lsp_client.as_mut(), self.lsp_document.as_ref())
        {
            client.request_hover(document, position);
        }
    }

    /// Requests hover information at a canvas point.
    ///
    /// Returns `true` if the point maps to a valid buffer position and the
    /// request was sent.
    pub fn lsp_request_hover_at(&mut self, point: iced::Point) -> bool {
        let Some(position) = self.lsp_position_from_point(point) else {
            return false;
        };
        if let (Some(client), Some(document)) =
            (self.lsp_client.as_mut(), self.lsp_document.as_ref())
        {
            client.request_hover(document, position);
            return true;
        }
        false
    }

    /// Requests hover information at an explicit LSP position.
    ///
    /// Returns `true` if an LSP client is attached and the request was sent.
    pub fn lsp_request_hover_at_position(
        &mut self,
        position: lsp::LspPosition,
    ) -> bool {
        if let (Some(client), Some(document)) =
            (self.lsp_client.as_mut(), self.lsp_document.as_ref())
        {
            client.request_hover(document, position);
            return true;
        }
        false
    }

    /// Converts a canvas point to an LSP position, if possible.
    pub fn lsp_position_at_point(
        &self,
        point: iced::Point,
    ) -> Option<lsp::LspPosition> {
        self.lsp_position_from_point(point)
    }

    /// Returns the hover anchor position and its canvas point for a given
    /// cursor location.
    ///
    /// The anchor is the start of the word under the cursor, which is useful
    /// for LSP hover and definition requests.
    pub fn lsp_hover_anchor_at_point(
        &self,
        point: iced::Point,
    ) -> Option<(lsp::LspPosition, iced::Point)> {
        let (line, col) = self.calculate_cursor_from_point(point)?;
        let line_content = self.buffer.line(line);
        let anchor_col = Self::word_start_in_line(line_content, col);
        let anchor_point =
            self.point_from_position(line, anchor_col).unwrap_or(point);
        let line = u32::try_from(line).unwrap_or(u32::MAX);
        let character = u32::try_from(anchor_col).unwrap_or(u32::MAX);
        Some((lsp::LspPosition { line, character }, anchor_point))
    }

    /// Requests completion items at the current cursor position.
    pub fn lsp_request_completion(&mut self) {
        let position = self.lsp_position_from_cursor();
        if let (Some(client), Some(document)) =
            (self.lsp_client.as_mut(), self.lsp_document.as_ref())
        {
            client.request_completion(document, position);
        }
    }

    /// Flushes pending LSP text changes to the attached client.
    ///
    /// This increments the document version and sends `did_change` with all
    /// queued changes.
    pub fn lsp_flush_pending_changes(&mut self) {
        if self.lsp_pending_changes.is_empty() {
            return;
        }

        if let (Some(client), Some(document)) =
            (self.lsp_client.as_mut(), self.lsp_document.as_mut())
        {
            let changes = std::mem::take(&mut self.lsp_pending_changes);
            document.version = document.version.saturating_add(1);
            client.did_change(document, &changes);
        }
    }

    /// Sets whether LSP changes are flushed automatically after edits.
    pub fn set_lsp_auto_flush(&mut self, auto_flush: bool) {
        self.lsp_auto_flush = auto_flush;
    }

    /// Requests focus for this editor.
    ///
    /// This method programmatically sets the focus to this editor instance,
    /// allowing it to receive keyboard events. Other editors will automatically
    /// lose focus.
    ///
    /// # Example
    ///
    /// ```
    /// use iced_code_editor::CodeEditor;
    ///
    /// let mut editor1 = CodeEditor::new("fn main() {}", "rs");
    /// let mut editor2 = CodeEditor::new("fn test() {}", "rs");
    ///
    /// // Give focus to editor2
    /// editor2.request_focus();
    /// ```
    pub fn request_focus(&self) {
        FOCUSED_EDITOR_ID.store(self.editor_id, Ordering::Relaxed);
    }

    /// Checks if this editor currently has focus.
    ///
    /// Returns `true` if this editor will receive keyboard events,
    /// `false` otherwise.
    ///
    /// # Returns
    ///
    /// `true` if focused, `false` otherwise
    ///
    /// # Example
    ///
    /// ```
    /// use iced_code_editor::CodeEditor;
    ///
    /// let editor = CodeEditor::new("fn main() {}", "rs");
    /// if editor.is_focused() {
    ///     println!("Editor has focus");
    /// }
    /// ```
    pub fn is_focused(&self) -> bool {
        FOCUSED_EDITOR_ID.load(Ordering::Relaxed) == self.editor_id
    }

    /// Resets the editor with new content.
    ///
    /// This method replaces the buffer content and resets all editor state
    /// (cursor position, selection, scroll, history) to initial values.
    /// Use this instead of creating a new `CodeEditor` instance to ensure
    /// proper widget tree updates in iced.
    ///
    /// Returns a `Task` that scrolls the editor to the top, which also
    /// forces a redraw of the canvas.
    ///
    /// # Arguments
    ///
    /// * `content` - The new text content
    ///
    /// # Returns
    ///
    /// A `Task<Message>` that should be returned from your update function
    ///
    /// # Example
    ///
    /// ```ignore
    /// use iced_code_editor::CodeEditor;
    ///
    /// let mut editor = CodeEditor::new("initial content", "lua");
    /// // Later, reset with new content and get the task
    /// let task = editor.reset("new content");
    /// // Return task.map(YourMessage::Editor) from your update function
    /// ```
    pub fn reset(&mut self, content: &str) -> iced::Task<Message> {
        self.buffer = TextBuffer::new(content);
        self.cursors.set_single((0, 0));
        self.horizontal_scroll_offset = 0.0;
        self.is_dragging = false;
        self.viewport_scroll = 0.0;
        self.history = CommandHistory::new(100);
        self.is_grouping = false;
        self.last_blink = Instant::now();
        self.cursor_visible = true;
        self.content_cache = canvas::Cache::default();
        self.overlay_cache = canvas::Cache::default();
        self.buffer_revision = self.buffer_revision.wrapping_add(1);
        *self.visual_lines_cache.borrow_mut() = None;
        self.enqueue_lsp_change();

        // Scroll to top to force a redraw
        snap_to(self.scrollable_id.clone(), RelativeOffset::START)
    }

    /// Resets the cursor blink animation.
    pub(crate) fn reset_cursor_blink(&mut self) {
        self.last_blink = Instant::now();
        self.cursor_visible = true;
    }

    /// Converts the current cursor position into an LSP position.
    fn lsp_position_from_cursor(&self) -> lsp::LspPosition {
        let pos = self.cursors.primary_position();
        let line = u32::try_from(pos.0).unwrap_or(u32::MAX);
        let character = u32::try_from(pos.1).unwrap_or(u32::MAX);
        lsp::LspPosition { line, character }
    }

    /// Converts a canvas point into an LSP position, if it hits the buffer.
    fn lsp_position_from_point(
        &self,
        point: iced::Point,
    ) -> Option<lsp::LspPosition> {
        let (line, col) = self.calculate_cursor_from_point(point)?;
        let line = u32::try_from(line).unwrap_or(u32::MAX);
        let character = u32::try_from(col).unwrap_or(u32::MAX);
        Some(lsp::LspPosition { line, character })
    }

    /// Converts a logical buffer position into a canvas point, if visible.
    fn point_from_position(
        &self,
        line: usize,
        col: usize,
    ) -> Option<iced::Point> {
        let visual_lines = self.visual_lines_cached(self.viewport_width);
        let visual_index = wrapping::WrappingCalculator::logical_to_visual(
            &visual_lines,
            line,
            col,
        )?;
        let visual_line = &visual_lines[visual_index];
        let line_content = self.buffer.line(visual_line.logical_line);
        let prefix_len = col.saturating_sub(visual_line.start_col);
        let prefix_text: String = line_content
            .chars()
            .skip(visual_line.start_col)
            .take(prefix_len)
            .collect();
        let x = self.gutter_width()
            + 5.0
            + measure_text_width(
                &prefix_text,
                self.full_char_width,
                self.char_width,
            );
        let y = visual_index as f32 * self.line_height;
        Some(iced::Point::new(x, y))
    }

    /// Returns the word-start column in a line for a given column.
    ///
    /// Word characters include ASCII alphanumerics and underscore.
    pub(crate) fn word_start_in_line(line: &str, col: usize) -> usize {
        let chars: Vec<char> = line.chars().collect();
        if chars.is_empty() {
            return 0;
        }
        let mut idx = col.min(chars.len());
        if idx == chars.len() {
            idx = idx.saturating_sub(1);
        }
        if !Self::is_word_char(chars[idx]) {
            if idx > 0 && Self::is_word_char(chars[idx - 1]) {
                idx -= 1;
            } else {
                return col.min(chars.len());
            }
        }
        while idx > 0 && Self::is_word_char(chars[idx - 1]) {
            idx -= 1;
        }
        idx
    }

    /// Returns the word-end column in a line for a given column.
    pub(crate) fn word_end_in_line(line: &str, col: usize) -> usize {
        let chars: Vec<char> = line.chars().collect();
        if chars.is_empty() {
            return 0;
        }
        let mut idx = col.min(chars.len());
        if idx == chars.len() {
            idx = idx.saturating_sub(1);
        }

        // If current char is not a word char, check if previous was (we might be just after the word)
        if !Self::is_word_char(chars[idx]) {
            if idx > 0 && Self::is_word_char(chars[idx - 1]) {
                // We are just after a word, so idx is the end (exclusive)
                // But wait, if we are at the space after "foo", idx points to space.
                // "foo " -> ' ' is at 3. word_end should be 3.
                // So if chars[idx] is not word char, and chars[idx-1] IS, then idx is the end.
                return idx;
            } else {
                // Not on a word
                return col.min(chars.len());
            }
        }

        // If we are on a word char, scan forward
        while idx < chars.len() && Self::is_word_char(chars[idx]) {
            idx += 1;
        }
        idx
    }

    /// Returns true when the character is part of an identifier-style word.
    pub(crate) fn is_word_char(ch: char) -> bool {
        ch == '_' || ch.is_alphanumeric()
    }

    /// Computes and queues the latest LSP text change for the buffer.
    ///
    /// When auto-flush is enabled, this immediately sends changes.
    fn enqueue_lsp_change(&mut self) {
        if self.lsp_document.is_none() {
            return;
        }

        let new_text = self.buffer.to_string();
        let old_text = self.lsp_shadow_text.as_str();
        if let Some(change) = lsp::compute_text_change(old_text, &new_text) {
            self.lsp_pending_changes.push(change);
        }
        self.lsp_shadow_text = new_text;
        if self.lsp_auto_flush {
            self.lsp_flush_pending_changes();
        }
    }

    /// Refreshes search matches after buffer modification.
    ///
    /// Should be called after any operation that modifies the buffer.
    /// If search is active, recalculates matches and selects the one
    /// closest to the current cursor position.
    pub(crate) fn refresh_search_matches_if_needed(&mut self) {
        if self.search_state.is_open && !self.search_state.query.is_empty() {
            // Recalculate matches with current query
            self.search_state.update_matches(&self.buffer);

            // Select match closest to cursor to maintain context
            self.search_state
                .select_match_near_cursor(self.cursors.primary_position());
        }
    }

    /// Returns whether the editor has unsaved changes.
    ///
    /// # Returns
    ///
    /// `true` if there are unsaved modifications, `false` otherwise
    pub fn is_modified(&self) -> bool {
        self.history.is_modified()
    }

    /// Marks the current state as saved.
    ///
    /// Call this after successfully saving the file to reset the modified state.
    pub fn mark_saved(&mut self) {
        self.history.mark_saved();
    }

    /// Returns whether undo is available.
    pub fn can_undo(&self) -> bool {
        self.history.can_undo()
    }

    /// Returns whether redo is available.
    pub fn can_redo(&self) -> bool {
        self.history.can_redo()
    }

    /// Sets whether line wrapping is enabled.
    ///
    /// When enabled, long lines will wrap at the viewport width or at a
    /// configured column width.
    ///
    /// # Arguments
    ///
    /// * `enabled` - Whether to enable line wrapping
    ///
    /// # Example
    ///
    /// ```
    /// use iced_code_editor::CodeEditor;
    ///
    /// let mut editor = CodeEditor::new("fn main() {}", "rs");
    /// editor.set_wrap_enabled(false); // Disable wrapping
    /// ```
    pub fn set_wrap_enabled(&mut self, enabled: bool) {
        if self.wrap_enabled != enabled {
            self.wrap_enabled = enabled;
            if enabled {
                self.horizontal_scroll_offset = 0.0;
            }
            self.content_cache.clear();
            self.overlay_cache.clear();
        }
    }

    /// Returns whether line wrapping is enabled.
    ///
    /// # Returns
    ///
    /// `true` if line wrapping is enabled, `false` otherwise
    pub fn wrap_enabled(&self) -> bool {
        self.wrap_enabled
    }

    /// Enables or disables automatic indentation on Enter.
    ///
    /// When enabled, pressing Enter copies the leading whitespace of the
    /// current line to the new line. When disabled, the cursor is placed
    /// at column 0 on the new line.
    ///
    /// # Arguments
    ///
    /// * `enabled` - `true` to enable auto-indentation, `false` to disable
    pub fn set_auto_indent_enabled(&mut self, enabled: bool) {
        self.auto_indent_enabled = enabled;
    }

    /// Returns whether auto-indentation is enabled.
    ///
    /// # Returns
    ///
    /// `true` if auto-indentation is enabled, `false` otherwise
    pub fn auto_indent_enabled(&self) -> bool {
        self.auto_indent_enabled
    }

    /// Sets the indentation style used when pressing the Tab key.
    ///
    /// # Arguments
    ///
    /// * `style` - The indentation style (`IndentStyle::Spaces(n)` or `IndentStyle::Tab`)
    pub fn set_indent_style(&mut self, style: IndentStyle) {
        self.indent_style = style;
    }

    /// Returns the current indentation style.
    ///
    /// # Returns
    ///
    /// The current [`IndentStyle`] configured for this editor
    pub fn indent_style(&self) -> IndentStyle {
        self.indent_style
    }

    /// Enables or disables the search/replace functionality.
    ///
    /// When disabled, search/replace keyboard shortcuts (Ctrl+F, Ctrl+H, F3)
    /// will be ignored. If the search dialog is currently open, it will be closed.
    ///
    /// # Arguments
    ///
    /// * `enabled` - Whether to enable search/replace functionality
    ///
    /// # Example
    ///
    /// ```
    /// use iced_code_editor::CodeEditor;
    ///
    /// let mut editor = CodeEditor::new("fn main() {}", "rs");
    /// editor.set_search_replace_enabled(false); // Disable search/replace
    /// ```
    pub fn set_search_replace_enabled(&mut self, enabled: bool) {
        self.search_replace_enabled = enabled;
        if !enabled && self.search_state.is_open {
            self.search_state.close();
        }
    }

    /// Returns whether search/replace functionality is enabled.
    ///
    /// # Returns
    ///
    /// `true` if search/replace is enabled, `false` otherwise
    pub fn search_replace_enabled(&self) -> bool {
        self.search_replace_enabled
    }

    /// Sets whether LSP support is enabled.
    ///
    /// When set to `false`, any attached LSP client is detached automatically.
    /// Calling [`attach_lsp`] while disabled is a no-op.
    ///
    /// # Example
    ///
    /// ```
    /// use iced_code_editor::CodeEditor;
    ///
    /// let mut editor = CodeEditor::new("fn main() {}", "rs");
    /// editor.set_lsp_enabled(false);
    /// ```
    ///
    /// [`attach_lsp`]: CodeEditor::attach_lsp
    pub fn set_lsp_enabled(&mut self, enabled: bool) {
        self.lsp_enabled = enabled;
        if !enabled {
            self.detach_lsp();
        }
    }

    /// Returns whether LSP support is enabled.
    ///
    /// `true` if LSP is enabled, `false` otherwise
    pub fn lsp_enabled(&self) -> bool {
        self.lsp_enabled
    }

    /// Returns the syntax highlighting language identifier for this editor.
    ///
    /// This is the language key passed at construction (e.g., `"lua"`, `"rs"`, `"py"`).
    ///
    /// # Examples
    ///
    /// ```
    /// use iced_code_editor::CodeEditor;
    /// let editor = CodeEditor::new("fn main() {}", "rs");
    /// assert_eq!(editor.syntax(), "rs");
    /// ```
    pub fn syntax(&self) -> &str {
        &self.syntax
    }

    /// Opens the search dialog programmatically.
    ///
    /// This is useful when wiring your own UI button instead of relying on
    /// keyboard shortcuts.
    ///
    /// # Returns
    ///
    /// A `Task<Message>` that focuses the search input.
    pub fn open_search_dialog(&mut self) -> iced::Task<Message> {
        self.update(&Message::OpenSearch)
    }

    /// Opens the search-and-replace dialog programmatically.
    ///
    /// This is useful when wiring your own UI button instead of relying on
    /// keyboard shortcuts.
    ///
    /// # Returns
    ///
    /// A `Task<Message>` that focuses the search input.
    pub fn open_search_replace_dialog(&mut self) -> iced::Task<Message> {
        self.update(&Message::OpenSearchReplace)
    }

    /// Closes the search dialog programmatically.
    ///
    /// # Returns
    ///
    /// A `Task<Message>` for any follow-up UI work.
    pub fn close_search_dialog(&mut self) -> iced::Task<Message> {
        self.update(&Message::CloseSearch)
    }

    /// Sets the line wrapping with builder pattern.
    ///
    /// # Arguments
    ///
    /// * `enabled` - Whether to enable line wrapping
    ///
    /// # Returns
    ///
    /// Self for method chaining
    ///
    /// # Example
    ///
    /// ```
    /// use iced_code_editor::CodeEditor;
    ///
    /// let editor = CodeEditor::new("fn main() {}", "rs")
    ///     .with_wrap_enabled(false);
    /// ```
    #[must_use]
    pub fn with_wrap_enabled(mut self, enabled: bool) -> Self {
        self.wrap_enabled = enabled;
        self
    }

    /// Sets the wrap column (fixed width wrapping).
    ///
    /// When set to `Some(n)`, lines will wrap at column `n`.
    /// When set to `None`, lines will wrap at the viewport width.
    ///
    /// # Arguments
    ///
    /// * `column` - The column to wrap at, or None for viewport-based wrapping
    ///
    /// # Example
    ///
    /// ```
    /// use iced_code_editor::CodeEditor;
    ///
    /// let editor = CodeEditor::new("fn main() {}", "rs")
    ///     .with_wrap_column(Some(80)); // Wrap at 80 characters
    /// ```
    #[must_use]
    pub fn with_wrap_column(mut self, column: Option<usize>) -> Self {
        self.wrap_column = column;
        self
    }

    /// Sets whether line numbers are displayed.
    ///
    /// When disabled, the gutter is completely removed (0px width),
    /// providing more space for code display.
    ///
    /// # Arguments
    ///
    /// * `enabled` - Whether to display line numbers
    ///
    /// # Example
    ///
    /// ```
    /// use iced_code_editor::CodeEditor;
    ///
    /// let mut editor = CodeEditor::new("fn main() {}", "rs");
    /// editor.set_line_numbers_enabled(false); // Hide line numbers
    /// ```
    pub fn set_line_numbers_enabled(&mut self, enabled: bool) {
        if self.line_numbers_enabled != enabled {
            self.line_numbers_enabled = enabled;
            self.content_cache.clear();
            self.overlay_cache.clear();
        }
    }

    /// Returns whether line numbers are displayed.
    ///
    /// # Returns
    ///
    /// `true` if line numbers are displayed, `false` otherwise
    pub fn line_numbers_enabled(&self) -> bool {
        self.line_numbers_enabled
    }

    /// Sets the line numbers display with builder pattern.
    ///
    /// # Arguments
    ///
    /// * `enabled` - Whether to display line numbers
    ///
    /// # Returns
    ///
    /// Self for method chaining
    ///
    /// # Example
    ///
    /// ```
    /// use iced_code_editor::CodeEditor;
    ///
    /// let editor = CodeEditor::new("fn main() {}", "rs")
    ///     .with_line_numbers_enabled(false);
    /// ```
    #[must_use]
    pub fn with_line_numbers_enabled(mut self, enabled: bool) -> Self {
        self.line_numbers_enabled = enabled;
        self
    }

    /// Returns the current gutter width based on whether line numbers are enabled.
    ///
    /// # Returns
    ///
    /// `GUTTER_WIDTH` if line numbers are enabled, `0.0` otherwise
    pub(crate) fn gutter_width(&self) -> f32 {
        if self.line_numbers_enabled { GUTTER_WIDTH } else { 0.0 }
    }

    /// Removes canvas focus from this editor.
    ///
    /// This method programmatically removes focus from the canvas, preventing
    /// it from receiving keyboard events. The cursor will be hidden, but the
    /// selection will remain visible.
    ///
    /// Call this when focus should move to another widget (e.g., text input).
    ///
    /// # Example
    ///
    /// ```
    /// use iced_code_editor::CodeEditor;
    ///
    /// let mut editor = CodeEditor::new("fn main() {}", "rs");
    /// editor.lose_focus();
    /// ```
    pub fn lose_focus(&mut self) {
        self.has_canvas_focus = false;
        self.show_cursor = false;
        self.ime_preedit = None;
    }

    /// Resets the focus lock state.
    ///
    /// This method can be called to manually unlock focus processing
    /// after a focus transition has completed. This is useful when
    /// you want to allow the editor to process input again after
    /// programmatic focus changes.
    ///
    /// # Example
    ///
    /// ```
    /// use iced_code_editor::CodeEditor;
    ///
    /// let mut editor = CodeEditor::new("fn main() {}", "rs");
    /// editor.reset_focus_lock();
    /// ```
    pub fn reset_focus_lock(&mut self) {
        self.focus_locked = false;
    }

    /// Returns the screen position of the cursor.
    ///
    /// This method returns the (x, y) coordinates of the current cursor position
    /// relative to the editor canvas, accounting for gutter width and line height.
    ///
    /// # Returns
    ///
    /// An `Option<iced::Point>` containing the cursor position, or `None` if
    /// the cursor position cannot be determined.
    ///
    /// # Example
    ///
    /// ```
    /// use iced_code_editor::CodeEditor;
    ///
    /// let editor = CodeEditor::new("fn main() {}", "rs");
    /// if let Some(point) = editor.cursor_screen_position() {
    ///     println!("Cursor at: ({}, {})", point.x, point.y);
    /// }
    /// ```
    pub fn cursor_screen_position(&self) -> Option<iced::Point> {
        let pos = self.cursors.primary_position();
        self.point_from_position(pos.0, pos.1)
    }

    /// Returns the current cursor position as (line, column).
    ///
    /// This method returns the logical cursor position in the buffer,
    /// where line and column are both 0-indexed.
    ///
    /// # Returns
    ///
    /// A tuple `(line, column)` representing the cursor position.
    ///
    /// # Example
    ///
    /// ```
    /// use iced_code_editor::CodeEditor;
    ///
    /// let editor = CodeEditor::new("fn main() {}", "rs");
    /// let (line, col) = editor.cursor_position();
    /// println!("Cursor at line {}, column {}", line, col);
    /// ```
    pub fn cursor_position(&self) -> (usize, usize) {
        self.cursors.primary_position()
    }

    /// Returns the maximum content width across all lines, in pixels.
    ///
    /// Used to size the horizontal scrollbar when `wrap_enabled = false`.
    /// The result is cached keyed by `buffer_revision` so repeated calls are cheap.
    ///
    /// # Returns
    ///
    /// Total width in pixels including gutter, padding and a right margin.
    pub(crate) fn max_content_width(&self) -> f32 {
        let mut cache = self.max_content_width_cache.borrow_mut();
        if let Some((rev, w)) = *cache
            && rev == self.buffer_revision
        {
            return w;
        }

        let gutter = self.gutter_width();
        let max_line_width = (0..self.buffer.line_count())
            .map(|i| {
                measure_text_width(
                    self.buffer.line(i),
                    self.full_char_width,
                    self.char_width,
                )
            })
            .fold(0.0_f32, f32::max);

        // gutter + left padding + text + right margin
        let total = gutter + 5.0 + max_line_width + 20.0;
        *cache = Some((self.buffer_revision, total));
        total
    }

    /// Returns wrapped "visual lines" for the current buffer and layout, with memoization.
    ///
    /// The editor frequently needs the wrapped view of the buffer:
    /// - hit-testing (mouse selection, cursor placement)
    /// - mapping logical ↔ visual positions
    /// - rendering (text, line numbers, highlights)
    ///
    /// Computing visual lines is relatively expensive for large files, so we
    /// cache the result keyed by:
    /// - `buffer_revision` (buffer content changes)
    /// - viewport width / gutter width (layout changes)
    /// - wrapping settings (wrap enabled / wrap column)
    /// - measured character widths (font / size changes)
    ///
    /// The returned `Rc<Vec<VisualLine>>` is cheap to clone and allows multiple
    /// rendering passes (content + overlay layers) to share the same computed
    /// layout without extra allocation.
    pub(crate) fn visual_lines_cached(
        &self,
        viewport_width: f32,
    ) -> Rc<Vec<wrapping::VisualLine>> {
        let key = VisualLinesKey {
            buffer_revision: self.buffer_revision,
            viewport_width_bits: viewport_width.to_bits(),
            gutter_width_bits: self.gutter_width().to_bits(),
            wrap_enabled: self.wrap_enabled,
            wrap_column: self.wrap_column,
            full_char_width_bits: self.full_char_width.to_bits(),
            char_width_bits: self.char_width.to_bits(),
        };

        let mut cache = self.visual_lines_cache.borrow_mut();
        if let Some(existing) = cache.as_ref()
            && existing.key == key
        {
            return existing.visual_lines.clone();
        }

        let wrapping_calc = wrapping::WrappingCalculator::new(
            self.wrap_enabled,
            self.wrap_column,
            self.full_char_width,
            self.char_width,
        );
        let visual_lines = wrapping_calc.calculate_visual_lines(
            &self.buffer,
            viewport_width,
            self.gutter_width(),
        );
        let visual_lines = Rc::new(visual_lines);

        *cache =
            Some(VisualLinesCache { key, visual_lines: visual_lines.clone() });
        visual_lines
    }

    /// Initiates a "Go to Definition" request for the symbol at the current cursor position.
    ///
    /// This method converts the current cursor coordinates into an LSP-compatible position
    /// and delegates the request to the active `LspClient`, if one is attached.
    pub fn lsp_request_definition(&mut self) {
        let position = self.lsp_position_from_cursor();
        if let (Some(client), Some(document)) =
            (self.lsp_client.as_mut(), self.lsp_document.as_ref())
        {
            client.request_definition(document, position);
        }
    }

    /// Initiates a "Go to Definition" request for the symbol at the specified screen coordinates.
    ///
    /// This is typically used for mouse interactions (e.g., Ctrl+Click). It first resolves
    /// the screen coordinates to a text position and then sends the request.
    ///
    /// # Returns
    ///
    /// `true` if the request was successfully sent (i.e., a valid position was found and an LSP client is active),
    /// `false` otherwise.
    pub fn lsp_request_definition_at(&mut self, point: iced::Point) -> bool {
        let Some(position) = self.lsp_position_from_point(point) else {
            return false;
        };
        if let (Some(client), Some(document)) =
            (self.lsp_client.as_mut(), self.lsp_document.as_ref())
        {
            client.request_definition(document, position);
            return true;
        }
        false
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::cell::RefCell;
    use std::rc::Rc;

    #[test]
    fn test_compare_floats() {
        // Equal cases
        assert_eq!(
            compare_floats(1.0, 1.0),
            CmpOrdering::Equal,
            "Exact equality"
        );
        assert_eq!(
            compare_floats(1.0, 1.0 + 0.0001),
            CmpOrdering::Equal,
            "Within epsilon (positive)"
        );
        assert_eq!(
            compare_floats(1.0, 1.0 - 0.0001),
            CmpOrdering::Equal,
            "Within epsilon (negative)"
        );

        // Greater cases
        assert_eq!(
            compare_floats(1.0 + 0.002, 1.0),
            CmpOrdering::Greater,
            "Definitely greater"
        );
        assert_eq!(
            compare_floats(1.0011, 1.0),
            CmpOrdering::Greater,
            "Just above epsilon"
        );

        // Less cases
        assert_eq!(
            compare_floats(1.0, 1.0 + 0.002),
            CmpOrdering::Less,
            "Definitely less"
        );
        assert_eq!(
            compare_floats(1.0, 1.0011),
            CmpOrdering::Less,
            "Just below negative epsilon"
        );
    }

    #[test]
    fn test_measure_text_width_ascii() {
        // "abc" (3 chars) -> 3 * CHAR_WIDTH
        let text = "abc";
        let width = measure_text_width(text, FONT_SIZE, CHAR_WIDTH);
        let expected = CHAR_WIDTH * 3.0;
        assert_eq!(
            compare_floats(width, expected),
            CmpOrdering::Equal,
            "Width mismatch for ASCII"
        );
    }

    #[test]
    fn test_measure_text_width_cjk() {
        // "你好" (2 chars) -> 2 * FONT_SIZE
        // Chinese characters are typically full-width.
        // width = 2 * FONT_SIZE
        let text = "你好";
        let width = measure_text_width(text, FONT_SIZE, CHAR_WIDTH);
        let expected = FONT_SIZE * 2.0;
        assert_eq!(
            compare_floats(width, expected),
            CmpOrdering::Equal,
            "Width mismatch for CJK"
        );
    }

    #[test]
    fn test_measure_text_width_mixed() {
        // "Hi" (2 chars) -> 2 * CHAR_WIDTH
        // "你好" (2 chars) -> 2 * FONT_SIZE
        let text = "Hi你好";
        let width = measure_text_width(text, FONT_SIZE, CHAR_WIDTH);
        let expected = CHAR_WIDTH * 2.0 + FONT_SIZE * 2.0;
        assert_eq!(
            compare_floats(width, expected),
            CmpOrdering::Equal,
            "Width mismatch for mixed content"
        );
    }

    #[test]
    fn test_measure_text_width_control_chars() {
        // "\t\n" (2 chars)
        // width = 4 * CHAR_WIDTH (tab) + 0 (newline)
        let text = "\t\n";
        let width = measure_text_width(text, FONT_SIZE, CHAR_WIDTH);
        let expected = CHAR_WIDTH * TAB_WIDTH as f32;
        assert_eq!(
            compare_floats(width, expected),
            CmpOrdering::Equal,
            "Width mismatch for control chars"
        );
    }

    #[test]
    fn test_measure_text_width_empty() {
        let text = "";
        let width = measure_text_width(text, FONT_SIZE, CHAR_WIDTH);
        assert!(
            (width - 0.0).abs() < f32::EPSILON,
            "Width should be 0 for empty string"
        );
    }

    #[test]
    fn test_measure_text_width_emoji() {
        // "👋" (1 char, width > 1) -> FONT_SIZE
        let text = "👋";
        let width = measure_text_width(text, FONT_SIZE, CHAR_WIDTH);
        let expected = FONT_SIZE;
        assert_eq!(
            compare_floats(width, expected),
            CmpOrdering::Equal,
            "Width mismatch for emoji"
        );
    }

    #[test]
    fn test_measure_text_width_korean() {
        // "안녕하세요" (5 chars)
        // Korean characters are typically full-width.
        // width = 5 * FONT_SIZE
        let text = "안녕하세요";
        let width = measure_text_width(text, FONT_SIZE, CHAR_WIDTH);
        let expected = FONT_SIZE * 5.0;
        assert_eq!(
            compare_floats(width, expected),
            CmpOrdering::Equal,
            "Width mismatch for Korean"
        );
    }

    #[test]
    fn test_measure_text_width_japanese() {
        // "こんにちは" (Hiragana, 5 chars) -> 5 * FONT_SIZE
        // "カタカナ" (Katakana, 4 chars) -> 4 * FONT_SIZE
        // "漢字" (Kanji, 2 chars) -> 2 * FONT_SIZE

        let text_hiragana = "こんにちは";
        let width_hiragana =
            measure_text_width(text_hiragana, FONT_SIZE, CHAR_WIDTH);
        let expected_hiragana = FONT_SIZE * 5.0;
        assert_eq!(
            compare_floats(width_hiragana, expected_hiragana),
            CmpOrdering::Equal,
            "Width mismatch for Hiragana"
        );

        let text_katakana = "カタカナ";
        let width_katakana =
            measure_text_width(text_katakana, FONT_SIZE, CHAR_WIDTH);
        let expected_katakana = FONT_SIZE * 4.0;
        assert_eq!(
            compare_floats(width_katakana, expected_katakana),
            CmpOrdering::Equal,
            "Width mismatch for Katakana"
        );

        let text_kanji = "漢字";
        let width_kanji = measure_text_width(text_kanji, FONT_SIZE, CHAR_WIDTH);
        let expected_kanji = FONT_SIZE * 2.0;
        assert_eq!(
            compare_floats(width_kanji, expected_kanji),
            CmpOrdering::Equal,
            "Width mismatch for Kanji"
        );
    }

    #[test]
    fn test_set_font_size() {
        let mut editor = CodeEditor::new("", "rs");

        // Initial state (defaults)
        assert!((editor.font_size() - 14.0).abs() < f32::EPSILON);
        assert!((editor.line_height() - 20.0).abs() < f32::EPSILON);

        // Test auto adjust = true
        editor.set_font_size(28.0, true);
        assert!((editor.font_size() - 28.0).abs() < f32::EPSILON);
        // Line height should double: 20.0 * (28.0/14.0) = 40.0
        assert_eq!(
            compare_floats(editor.line_height(), 40.0),
            CmpOrdering::Equal
        );

        // Test auto adjust = false
        // First set line height to something custom
        editor.set_line_height(50.0);
        // Change font size but keep line height
        editor.set_font_size(14.0, false);
        assert!((editor.font_size() - 14.0).abs() < f32::EPSILON);
        // Line height should stay 50.0
        assert_eq!(
            compare_floats(editor.line_height(), 50.0),
            CmpOrdering::Equal
        );
        // Char width should have scaled back to roughly default (but depends on measurement)
        // We check if it is close to the expected value, but since measurement can vary,
        // we just ensure it is positive and close to what we expect (around 8.4)
        assert!(editor.char_width > 0.0);
        assert!((editor.char_width - CHAR_WIDTH).abs() < 0.5);
    }

    #[test]
    fn test_measure_single_char_width() {
        let editor = CodeEditor::new("", "rs");

        // Measure 'a'
        let width_a = editor.measure_single_char_width("a");
        assert!(width_a > 0.0, "Width of 'a' should be positive");

        // Measure Chinese char
        let width_cjk = editor.measure_single_char_width("");
        assert!(width_cjk > 0.0, "Width of '汉' should be positive");

        assert!(
            width_cjk > width_a,
            "Width of '汉' should be greater than 'a'"
        );

        // Check that width_cjk is roughly double of width_a (common in terminal fonts)
        // but we just check it is significantly larger
        assert!(width_cjk >= width_a * 1.5);
    }

    #[test]
    fn test_set_line_height() {
        let mut editor = CodeEditor::new("", "rs");

        // Initial state
        assert!((editor.line_height() - LINE_HEIGHT).abs() < f32::EPSILON);

        // Set custom line height
        editor.set_line_height(35.0);
        assert!((editor.line_height() - 35.0).abs() < f32::EPSILON);

        // Font size should remain unchanged
        assert!((editor.font_size() - FONT_SIZE).abs() < f32::EPSILON);
    }

    #[test]
    fn test_visual_lines_cached_reuses_cache_for_same_key() {
        let editor = CodeEditor::new("a\nb\nc", "rs");

        let first = editor.visual_lines_cached(800.0);
        let second = editor.visual_lines_cached(800.0);

        assert!(
            Rc::ptr_eq(&first, &second),
            "visual_lines_cached should reuse the cached Rc for identical keys"
        );
    }

    #[derive(Default)]
    struct TestLspClient {
        changes: Rc<RefCell<Vec<Vec<lsp::LspTextChange>>>>,
    }

    impl lsp::LspClient for TestLspClient {
        fn did_change(
            &mut self,
            _document: &lsp::LspDocument,
            changes: &[lsp::LspTextChange],
        ) {
            self.changes.borrow_mut().push(changes.to_vec());
        }
    }

    #[test]
    fn test_word_start_in_line() {
        let line = "foo_bar baz";
        assert_eq!(CodeEditor::word_start_in_line(line, 0), 0);
        assert_eq!(CodeEditor::word_start_in_line(line, 2), 0);
        assert_eq!(CodeEditor::word_start_in_line(line, 4), 0);
        assert_eq!(CodeEditor::word_start_in_line(line, 7), 0);
        assert_eq!(CodeEditor::word_start_in_line(line, 9), 8);
    }

    #[test]
    fn test_enqueue_lsp_change_auto_flush() {
        let changes = Rc::new(RefCell::new(Vec::new()));
        let client = TestLspClient { changes: Rc::clone(&changes) };
        let mut editor = CodeEditor::new("hello", "rs");
        editor.attach_lsp(
            Box::new(client),
            lsp::LspDocument::new("file:///test.rs", "rust"),
        );
        editor.set_lsp_auto_flush(true);

        editor.buffer.insert_char(0, 5, '!');
        editor.enqueue_lsp_change();

        let changes = changes.borrow();
        assert_eq!(changes.len(), 1);
        assert_eq!(changes[0].len(), 1);
        let change = &changes[0][0];
        assert_eq!(change.text, "!");
        assert_eq!(change.range.start.line, 0);
        assert_eq!(change.range.start.character, 5);
        assert_eq!(change.range.end.line, 0);
        assert_eq!(change.range.end.character, 5);
    }

    #[test]
    fn test_visual_lines_cached_changes_on_viewport_width_change() {
        let editor = CodeEditor::new("a\nb\nc", "rs");

        let first = editor.visual_lines_cached(800.0);
        let second = editor.visual_lines_cached(801.0);

        assert!(
            !Rc::ptr_eq(&first, &second),
            "visual_lines_cached should recompute when viewport width changes"
        );
    }

    #[test]
    fn test_visual_lines_cached_changes_on_buffer_revision_change() {
        let mut editor = CodeEditor::new("a\nb\nc", "rs");

        let first = editor.visual_lines_cached(800.0);
        editor.buffer_revision = editor.buffer_revision.wrapping_add(1);
        let second = editor.visual_lines_cached(800.0);

        assert!(
            !Rc::ptr_eq(&first, &second),
            "visual_lines_cached should recompute when buffer_revision changes"
        );
    }

    #[test]
    fn test_max_content_width_increases_with_longer_lines() {
        let short = CodeEditor::new("ab", "rs");
        let long =
            CodeEditor::new("abcdefghijklmnopqrstuvwxyz0123456789", "rs");

        assert!(
            long.max_content_width() > short.max_content_width(),
            "Longer lines should produce a greater max_content_width"
        );
    }

    #[test]
    fn test_max_content_width_cached_by_revision() {
        let mut editor = CodeEditor::new("hello", "rs");
        let w1 = editor.max_content_width();

        // Same revision → cache hit
        let w2 = editor.max_content_width();
        assert!(
            (w1 - w2).abs() < f32::EPSILON,
            "Repeated calls with same revision should return identical value"
        );

        // Bump revision to simulate edit
        editor.buffer_revision = editor.buffer_revision.wrapping_add(1);
        // Update the buffer to reflect a longer line
        editor.buffer = crate::text_buffer::TextBuffer::new(
            "hello world with extra content",
        );
        let w3 = editor.max_content_width();
        assert!(
            w3 > w1,
            "After revision bump with longer content, width should increase"
        );
    }

    #[test]
    fn test_syntax_getter() {
        let editor = CodeEditor::new("", "lua");
        assert_eq!(editor.syntax(), "lua");
    }
}