rsvim_core 0.1.3-alpha.2

The core library for RSVIM text editor.
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
//! Viewport internal algorithms.

use super::CursorViewport;
use super::Viewport;
use crate::buf::text::Text;
use crate::prelude::*;
use crate::ui::viewport::LineViewport;
use crate::ui::viewport::RowViewport;
use crate::ui::widget::window::opt::WindowOptions;
use icu::segmenter::WordSegmenter;
use icu::segmenter::options::WordBreakInvariantOptions;
use itertools::Itertools;
use litemap::LiteMap;
use ropey::RopeSlice;
use std::ops::Range;

#[derive(Debug, Copy, Clone, Default, PartialEq, Eq)]
/// Lines index inside the viewport.
pub struct ViewportLineRange {
  start_line_idx: usize,
  end_line_idx: usize,
}

impl ViewportLineRange {
  pub fn new(line_idx_range: Range<usize>) -> Self {
    Self {
      start_line_idx: line_idx_range.start,
      end_line_idx: line_idx_range.end,
    }
  }

  pub fn is_empty(&self) -> bool {
    self.end_line_idx <= self.start_line_idx
  }

  pub fn len(&self) -> usize {
    self.end_line_idx - self.start_line_idx
  }

  pub fn start_line_idx(&self) -> usize {
    self.start_line_idx
  }

  pub fn end_line_idx(&self) -> usize {
    self.end_line_idx
  }
}

/// Calculate viewport from top to bottom.
pub fn sync(
  opts: &WindowOptions,
  text: &Text,
  size: &U16Size,
  start_line: usize,
  start_column: usize,
) -> (ViewportLineRange, LiteMap<usize, LineViewport>) {
  // If window is zero-sized.
  if size.is_zero() {
    return (ViewportLineRange::default(), LiteMap::new());
  }

  match (opts.wrap(), opts.line_break()) {
    (false, _) => nowrap_sync(text, size, start_line, start_column),
    (true, false) => {
      wrap_nolinebreak_sync(text, size, start_line, start_column)
    }
    (true, true) => wrap_linebreak_sync(text, size, start_line, start_column),
  }
}

// Returns (end_char, end_filled_cols)
fn _end_char_and_filled_cols(
  text: &Text,
  buffer_line: &RopeSlice,
  current_line: usize,
  end_width_char: usize,
  end_width: usize,
) -> (usize, usize) {
  let c_width = text.width_until(current_line, end_width_char);
  if c_width > end_width {
    // If `the width of end_width_char > end_width`, then `end_width_char`
    // itself is the end char. And there are possibly `end_filled_cols`.
    let c_width_before = text.width_before(current_line, end_width_char);
    (end_width_char, end_width.saturating_sub(c_width_before))
  } else {
    // Here we use the last visible char in the line, thus avoid invisible
    // chars like line-break ('\n').
    debug_assert!(buffer_line.len_chars() > 0);
    let next_to_last_visible_char = text
      .last_char_idx_on_line_exclude_eol(current_line)
      .unwrap_or(0_usize)
      + 1;

    // If `the width of end_width_char <= end_width`, the char next to
    // `end_width_char` is the end char.
    let c_next = std::cmp::min(end_width_char + 1, next_to_last_visible_char);
    (c_next, 0_usize)
  }
}

#[allow(unused_assignments)]
/// Returns `rows`, `start_fills`, `end_fills`, `last_row` (in `rows`).
fn nowrap_line_process(
  text: &Text,
  start_column: usize,
  current_line: usize,
  current_row: u16,
  _window_height: u16,
  window_width: u16,
) -> (LiteMap<u16, RowViewport>, usize, usize, u16) {
  let buffer_line = text.rope().line(current_line);

  let mut rows: LiteMap<u16, RowViewport> = LiteMap::with_capacity(1);

  let mut start_fills: usize = 0;
  let mut end_fills: usize = 0;

  if buffer_line.len_chars() == 0 {
    // If current line is empty
    rows.insert(current_row, RowViewport::new(0..0));
    start_fills = 0;
    end_fills = 0;
  } else {
    if let Some(start_char) = text.char_after(current_line, start_column) {
      start_fills = {
        let width_before = text.width_before(current_line, start_char);
        width_before.saturating_sub(start_column)
      };

      let end_width = start_column + window_width as usize;
      let (end_char, end_f) = match text.char_at(current_line, end_width) {
        Some(end_width_char) => _end_char_and_filled_cols(
          text,
          &buffer_line,
          current_line,
          end_width_char,
          end_width,
        ),
        None => {
          // If the char not found, it means the `end_width` is too long
          // than the whole line. So the char next to the line's last
          // char is the end char.
          (buffer_line.len_chars(), 0)
        }
      };
      end_fills = end_f;
      rows.insert(current_row, RowViewport::new(start_char..end_char));
    } else {
      // If current line is empty
      start_fills = 0;
      end_fills = 0;
      rows.insert(current_row, RowViewport::new(0..0));
    }
  }

  (rows, start_fills, end_fills, current_row)
}

/// Implements [`sync`] with option `wrap=false`.
fn nowrap_sync(
  text: &Text,
  size: &U16Size,
  start_line: usize,
  start_column: usize,
) -> (ViewportLineRange, LiteMap<usize, LineViewport>) {
  let window_height = size.height();
  let window_width = size.width();
  let buffer_len_lines = text.rope().len_lines();

  let mut line_viewports: LiteMap<usize, LineViewport> =
    LiteMap::with_capacity(window_height as usize);

  // Current row in the window maps to the `start_line` in the buffer.
  let mut current_row = 0_u16;
  let mut current_line = start_line;

  if current_line < buffer_len_lines {
    // If `current_row` goes out of window, `current_line` goes out of buffer.
    while current_row < window_height && current_line < buffer_len_lines {
      let (rows, start_fills, end_fills, _last_row) = nowrap_line_process(
        text,
        start_column,
        current_line,
        current_row,
        window_height,
        window_width,
      );

      line_viewports.insert(
        current_line,
        LineViewport::new(rows, start_fills, end_fills),
      );

      // Go down to next row and line
      current_line += 1;
      current_row += 1;
    }

    (
      ViewportLineRange::new(start_line..current_line),
      line_viewports,
    )
  } else {
    (ViewportLineRange::default(), LiteMap::new())
  }
}

#[allow(unused_assignments)]
/// Returns `rows`, `start_fills`, `end_fills`, `last_row` (in `rows`).
fn wrap_nolinebreak_line_process(
  text: &Text,
  start_column: usize,
  current_line: usize,
  current_row: u16,
  window_height: u16,
  window_width: u16,
) -> (LiteMap<u16, RowViewport>, usize, usize, u16) {
  let buffer_line = text.rope().line(current_line);
  let mut rows: LiteMap<u16, RowViewport> =
    LiteMap::with_capacity(std::cmp::min(
      buffer_line.len_chars() / (window_width as usize),
      window_height as usize,
    ));

  let mut current_row = current_row;
  let mut start_fills: usize = 0;
  let mut end_fills: usize = 0;

  if buffer_line.len_chars() == 0 {
    // If current line is empty.
    rows.insert(current_row, RowViewport::new(0..0));
    start_fills = 0;
    end_fills = 0;
  } else {
    if let Some(mut start_char) = text.char_after(current_line, start_column) {
      start_fills = {
        let width_before = text.width_before(current_line, start_char);
        width_before.saturating_sub(start_column)
      };

      let mut end_width = start_column + window_width as usize;

      debug_assert!(current_row < window_height);
      while current_row < window_height {
        let (end_char, end_f) = match text.char_at(current_line, end_width) {
          Some(end_width_char) => _end_char_and_filled_cols(
            text,
            &buffer_line,
            current_line,
            end_width_char,
            end_width,
          ),
          None => {
            // If the char not found, it means the `end_width` is too long than the whole line.
            // So the char next to the line's last char is the end char.
            (buffer_line.len_chars(), 0_usize)
          }
        };
        end_fills = end_f;

        rows.insert(current_row, RowViewport::new(start_char..end_char));

        // Goes out of line.
        debug_assert!(buffer_line.len_chars() > 0);
        if end_char
          > text
            .last_char_idx_on_line_exclude_eol(current_line)
            .unwrap_or(0_usize)
        {
          break;
        }

        // Prepare next row.
        current_row += 1;
        start_char = end_char;
        end_width =
          text.width_before(current_line, end_char) + window_width as usize;
      }
    } else {
      start_fills = 0;
      end_fills = 0;
    }
  }

  (rows, start_fills, end_fills, current_row)
}

/// Implements [`sync`] with option `wrap=true` and `line-break=false`.
fn wrap_nolinebreak_sync(
  text: &Text,
  size: &U16Size,
  start_line: usize,
  start_column: usize,
) -> (ViewportLineRange, LiteMap<usize, LineViewport>) {
  let window_height = size.height();
  let window_width = size.width();
  let buffer_len_lines = text.rope().len_lines();

  let mut line_viewports: LiteMap<usize, LineViewport> =
    LiteMap::with_capacity(window_height as usize);

  // The first `current_row` in the window maps to the `start_line` in the buffer.
  let mut current_row = 0_u16;
  let mut current_line = start_line;

  if current_line < buffer_len_lines {
    // If `current_row` goes out of window, `current_line` goes out of buffer.
    while current_row < window_height && current_line < buffer_len_lines {
      let (rows, start_fills, end_fills, last_row) =
        wrap_nolinebreak_line_process(
          text,
          start_column,
          current_line,
          current_row,
          window_height,
          window_width,
        );
      current_row = last_row;

      line_viewports.insert(
        current_line,
        LineViewport::new(rows, start_fills, end_fills),
      );

      current_line += 1;
      current_row += 1;
    }

    (
      ViewportLineRange::new(start_line..current_line),
      line_viewports,
    )
  } else {
    (ViewportLineRange::default(), LiteMap::new())
  }
}

/// Find word index by char index.
///
/// Returns:
/// 1. The word index, which contains this `char_idx`.
/// 2. The first char index of this word.
/// 3. The end char index of this word.
fn _binary_search_word_by_char(
  words: &[&str],
  word_end_chars_index: &LiteMap<usize, usize>,
  char_idx: usize,
) -> (usize, usize, usize) {
  // trace!("words:{words:?}, words_end_chars:{word_end_chars_index:?},char_idx:{char_idx}");
  let mut low = 0;
  let mut high = words.len() - 1;

  while low <= high {
    let mid = (low + high) / 2;

    let start_char_idx = if mid > 0 {
      *word_end_chars_index.get(&(mid - 1)).unwrap()
    } else {
      0_usize
    };
    let end_char_idx = *word_end_chars_index.get(&mid).unwrap();

    // trace!(
    //   "low:{low},high:{high},mid:{mid},start_char_idx:{start_char_idx},end_char_idx:{end_char_idx},char_idx:{char_idx}"
    // );
    if start_char_idx <= char_idx && end_char_idx > char_idx {
      // trace!(
      //   "return mid:{mid},start_char_idx:{start_char_idx},end_char_idx:{end_char_idx},char_idx:{char_idx}"
      // );
      return (mid, start_char_idx, end_char_idx);
    } else if start_char_idx > char_idx {
      high = mid - 1;
    } else {
      low = mid + 1;
    }
  }

  unreachable!()
}

// Part-1 of the processing algorithm in [`wrap_linebreak_line_process`].
// Returns `(end_char, end_filled_cols)`.
fn _part1(
  words: &[&str],
  words_end_char_idx: &LiteMap<usize, usize>,
  text: &Text,
  buffer_line: &RopeSlice,
  current_line: usize,
  end_width_char: usize,
  end_width: usize,
  start_char: usize,
  last_word_is_too_long: &mut Option<(usize, usize, usize, usize)>,
) -> (usize, usize) {
  let (end_wd_idx, start_c_of_end_wd, end_c_of_end_wd) =
    _binary_search_word_by_char(words, words_end_char_idx, end_width_char);

  let end_c_width = text.width_before(current_line, end_c_of_end_wd);
  if end_c_width > end_width {
    // The current word is longer than current row, it needs to be put to next
    // row.

    // Part-1
    // Here's the **tricky** part, there are two sub-cases in this scenario:
    // 1. For most happy cases, the word is not longer than a whole row in the
    //    window, so it can be completely put to next row.
    // 2. For very rare cases, the word is just too long to put in an entire
    //    row in the window. We have to fallback to the no-line-break rendering
    //    behavior, i.e. just cut the word by chars and force rendering the
    //    word on multiple rows in the window (because otherwise there will
    //    never be enough places to put this word).

    if start_c_of_end_wd > start_char {
      // Part-1.1, simply wrapped this word to next row.
      // Here we use the `start_c_of_end_wd` as the end char for current row.

      _end_char_and_filled_cols(
        text,
        buffer_line,
        current_line,
        start_c_of_end_wd - 1,
        end_width,
      )
    } else {
      // Part-1.2, cut this word and force rendering it and ignores line-break
      // behavior.
      debug_assert!(start_c_of_end_wd <= start_char);
      // Save the position (`end_width_char`) where we cut the words into
      // pieces.
      *last_word_is_too_long = Some((
        end_wd_idx,
        start_c_of_end_wd,
        end_c_of_end_wd,
        end_width_char,
      ));

      // NOTE: Here we fallback to the same behavior of
      // `wrap_nolinebreak_line_process`.
      //
      // If `the width of end_width_char > end_width`, the `end_width_char`
      // itself is the end char.
      _end_char_and_filled_cols(
        text,
        buffer_line,
        current_line,
        end_width_char,
        end_width,
      )
    }
  } else {
    debug_assert_eq!(end_width_char + 1, end_c_of_end_wd);
    // The current word is not long, it can be put in current row.
    let c_next = std::cmp::min(end_c_of_end_wd, buffer_line.len_chars());
    (c_next, 0_usize)
  }
}

#[allow(unused_assignments)]
/// Returns `rows`, `start_fills`, `end_fills`, `last_row` (in `rows`).
fn wrap_linebreak_line_process(
  text: &Text,
  start_column: usize,
  current_line: usize,
  current_row: u16,
  window_height: u16,
  window_width: u16,
) -> (LiteMap<u16, RowViewport>, usize, usize, u16) {
  let buffer_line = text.rope().line(current_line);

  let mut rows: LiteMap<u16, RowViewport> =
    LiteMap::with_capacity(std::cmp::min(
      buffer_line.len_chars() / (window_width as usize),
      window_height as usize,
    ));

  let mut current_row = current_row;
  let mut start_fills: usize = 0;
  let mut end_fills: usize = 0;

  if buffer_line.len_chars() == 0 {
    rows.insert(current_row, RowViewport::new(0..0));
    start_fills = 0;
    end_fills = 0;
  } else {
    // Here clone the line with the max chars that can hold by current window/viewport,
    // i.e. the `height * width` cells count as the max chars in the line. This helps avoid
    // performance issue when iterating on super long lines.

    // Clone this line from `cloned_start_char`, thus we can limit the cloned text within the
    // window's size (i.e. height * width).
    let cloned_start_char = text
      .char_before(current_line, start_column)
      .unwrap_or(0_usize);
    let cloned_line = text
      .clone_line(
        current_line,
        cloned_start_char,
        (window_height as usize + 1) * (window_width as usize + 1) * 2 + 1,
      )
      .unwrap();

    // trace!(
    //   "cloned_line({}):{:?}, cloned_start_char:{}, start_column:{}",
    //   cloned_line.len(),
    //   cloned_line.as_str(),
    //   cloned_start_char,
    //   start_column
    // );

    let segmenter =
      WordSegmenter::new_auto(WordBreakInvariantOptions::default());
    // Words.
    let words: Vec<&str> = segmenter
      .segment_str(&cloned_line)
      .tuple_windows()
      .map(|(i, j)| &cloned_line[i..j])
      .collect();
    // Word index => its end char index
    let words_end_char_idx = words
      .iter()
      .enumerate()
      .scan(cloned_start_char, |state, (i, wd)| {
        *state += wd.chars().count();
        Some((i, *state))
      })
      .collect::<LiteMap<usize, usize>>();

    if let Some(mut start_char) = text.char_after(current_line, start_column) {
      start_fills = {
        let width_before = text.width_before(current_line, start_char);
        width_before.saturating_sub(start_column)
      };

      let mut end_width = start_column + window_width as usize;

      // Saved last word info, if it is too long to put in an entire row of
      // window.
      //
      // This tuple is:
      // 1. Word index.
      // 2. Start char of the word.
      // 3. End char of the word.
      // 4. Continued start char index of the word (which should be continued to rendering on
      //    current row).
      let mut last_word_is_too_long: Option<(usize, usize, usize, usize)> =
        None;

      debug_assert!(current_row < window_height);
      while current_row < window_height {
        let (end_char, end_f) = match text.char_at(current_line, end_width) {
          Some(end_width_char) => {
            match last_word_is_too_long {
              Some((
                last_wd_idx,
                start_c_of_last_wd,
                end_c_of_last_wd,
                _continued_c_of_last_wd,
              )) => {
                // Part-2
                // This is the following logic of part-1.2, you should see it
                // before this.
                //
                // If the word is too long to put in an entire row, and we cut
                // it into pieces. In this part, we need to continue rendering
                // the rest part of the word on current row.
                //
                // Here we also have two sub-cases:
                // 1. If the rest part of the word is still too long to put in
                //    current row.
                // 2. If the rest part of the word is not long and can be put
                //    in current row.

                if end_c_of_last_wd > end_width_char {
                  // Part-2.1, the rest part of the word is still too long.

                  // Record the position (c) where we cut the words into pieces.
                  last_word_is_too_long = Some((
                    last_wd_idx,
                    start_c_of_last_wd,
                    end_c_of_last_wd,
                    end_width_char,
                  ));

                  // If the char `c` width is greater than `end_width`, the `c` itself is
                  // the end char.
                  _end_char_and_filled_cols(
                    text,
                    &buffer_line,
                    current_line,
                    end_width_char,
                    end_width,
                  )
                } else {
                  // Part-2.2, the rest part of the word is not long.
                  // Thus we can go back to *normal* behavior, i.e. part-1.

                  _part1(
                    &words,
                    &words_end_char_idx,
                    text,
                    &buffer_line,
                    current_line,
                    end_width_char,
                    end_width,
                    start_char,
                    &mut last_word_is_too_long,
                  )
                }
              }
              None => {
                // Part-1
                _part1(
                  &words,
                  &words_end_char_idx,
                  text,
                  &buffer_line,
                  current_line,
                  end_width_char,
                  end_width,
                  start_char,
                  &mut last_word_is_too_long,
                )
              }
            }
          }
          None => {
            // If the char not found, it means the `end_width` is too long than the whole line.
            // So the char next to the line's last char is the end char.
            (buffer_line.len_chars(), 0_usize)
          }
        };
        end_fills = end_f;

        rows.insert(current_row, RowViewport::new(start_char..end_char));

        // Goes out of line.
        debug_assert!(buffer_line.len_chars() > 0);
        if end_char
          > text
            .last_char_idx_on_line_exclude_eol(current_line)
            .unwrap_or(0_usize)
        {
          break;
        }

        // Prepare next row.
        current_row += 1;
        start_char = end_char;
        end_width =
          text.width_before(current_line, end_char) + window_width as usize;
      }
    } else {
      start_fills = 0;
      end_fills = 0;
    }
  }

  (rows, start_fills, end_fills, current_row)
}

/// Implements [`sync`] with option `wrap=true` and `line-break=true`.
fn wrap_linebreak_sync(
  text: &Text,
  size: &U16Size,
  start_line: usize,
  start_column: usize,
) -> (ViewportLineRange, LiteMap<usize, LineViewport>) {
  let height = size.height();
  let width = size.width();
  let buffer_len_lines = text.rope().len_lines();

  let mut line_viewports: LiteMap<usize, LineViewport> =
    LiteMap::with_capacity(height as usize);

  // The first `current_row` in the window maps to the `start_line` in the buffer.
  let mut current_row = 0_u16;
  let mut current_line = start_line;

  if current_line < buffer_len_lines {
    // If `current_row` goes out of window, `current_line` goes out of buffer.
    while current_row < height && current_line < buffer_len_lines {
      let (rows, start_fills, end_fills, last_row) =
        wrap_linebreak_line_process(
          text,
          start_column,
          current_line,
          current_row,
          height,
          width,
        );
      current_row = last_row;

      line_viewports.insert(
        current_line,
        LineViewport::new(rows, start_fills, end_fills),
      );

      current_line += 1;
      current_row += 1;
    }

    (
      ViewportLineRange::new(start_line..current_line),
      line_viewports,
    )
  } else {
    (ViewportLineRange::default(), LiteMap::new())
  }
}

type WrapSyncFn = fn(
  /* text */ &Text,
  /* size */ &U16Size,
  /* start_line */ usize,
  /* start_column */ usize,
) -> (
  /* line range */ ViewportLineRange,
  /* lines_viewport */ LiteMap<usize, LineViewport>,
);

// Type alias for `wrap_xxx_line_process` functions.
type WrapLineProcessFn = fn(
  /* text */ &Text,
  /* start_column */ usize,
  /* current_line */ usize,
  /* mut current_row */ u16,
  /* window_height */ u16,
  /* window_width */ u16,
) -> (
  /* rows */ LiteMap<u16, RowViewport>,
  /* start_fills */ usize,
  /* end_fills */ usize,
  /* next_current_row */ u16,
);

type WrapHorizontalSearchFn =
  fn(
    /* sync_fn */ WrapSyncFn,
    /* line_process_fn */ WrapLineProcessFn,
    /* viewport */ &Viewport,
    /* cursor_viewport */ &CursorViewport,
    /* opts */ &WindowOptions,
    /* text */ &Text,
    /* size */ &U16Size,
    /* suggest_start_line */ usize,
    /* suggest_start_column */ usize,
    /* target_cursor_line */ usize,
    /* target_cursor_char */ usize,
  ) -> (/* start_line */ usize, /* start_column */ usize);

// Search a new viewport anchor (`start_line`, `start_column`).
//
// The new viewport anchor can help cursor moves and even scrolling the buffer
// if cursor reaches the border of the window viewport.
//
// Returns `(start_line, start_column)` for the new viewport.
pub fn search(
  viewport: &Viewport,
  cursor_viewport: &CursorViewport,
  opts: &WindowOptions,
  text: &Text,
  size: &U16Size,
  target_cursor_line: usize,
  target_cursor_char: usize,
) -> (usize, usize) {
  let buffer_len_lines = text.rope().len_lines();
  let target_cursor_line =
    std::cmp::min(target_cursor_line, buffer_len_lines.saturating_sub(1));
  let target_cursor_line_end_char =
    match text.last_char_idx_on_line_include_eol(target_cursor_line) {
      Some(last_char) => {
        if !text.is_eol(target_cursor_line, last_char)
          && target_cursor_char > last_char
        {
          // If the `last_char` is not a eol, and `target_cursor_char` is still
          // greater than it. It means `target_cursor_char` wants the line end,
          // which is actually out of the line.
          // This only happens when a line doesn't end with eol (i.e. `\n` or
          // `\r\n`). If a line ends with eol (`\n` or `\r\n`), the
          // `target_cursor_char` must be less than or equal to the eol.
          last_char + 1
        } else {
          last_char
        }
      }
      None => {
        // The line is empty
        0
      }
    };
  let target_cursor_char =
    std::cmp::min(target_cursor_char, target_cursor_line_end_char);

  let (sync_fn, line_process_fn, search_left_fn, search_right_fn): (
    WrapSyncFn,
    WrapLineProcessFn,
    WrapHorizontalSearchFn,
    WrapHorizontalSearchFn,
  ) = if opts.line_break() {
    (
      wrap_linebreak_sync,
      wrap_linebreak_line_process,
      wrap_search_left,
      wrap_search_right,
    )
  } else {
    (
      wrap_nolinebreak_sync,
      wrap_nolinebreak_line_process,
      wrap_search_left,
      wrap_search_right,
    )
  };

  if target_cursor_line < cursor_viewport.line_idx() {
    // Cursor moves upward
    if opts.wrap() {
      wrap_search_up(
        sync_fn,
        line_process_fn,
        search_left_fn,
        search_right_fn,
        viewport,
        cursor_viewport,
        opts,
        text,
        size,
        target_cursor_line,
        target_cursor_char,
      )
    } else {
      nowrap_search_up(
        viewport,
        cursor_viewport,
        text,
        size,
        target_cursor_line,
        target_cursor_char,
      )
    }
  } else {
    // Cursor moves downward, or just moves to left/right side. But in this
    // algorithm, we have to moves to downward (even just for 0-lines) before
    // moving to left/right side.
    if opts.wrap() {
      wrap_search_down(
        sync_fn,
        line_process_fn,
        search_left_fn,
        search_right_fn,
        viewport,
        cursor_viewport,
        opts,
        text,
        size,
        target_cursor_line,
        target_cursor_char,
      )
    } else {
      nowrap_search_down(
        viewport,
        cursor_viewport,
        text,
        size,
        target_cursor_line,
        target_cursor_char,
      )
    }
  }
}

// Returns if current viewport contains the `target_cursor_line`.
fn _if_contains_target_cursor_line(
  viewport: &Viewport,
  target_cursor_line: usize,
) -> bool {
  target_cursor_line >= viewport.start_line_idx()
    && target_cursor_line < viewport.end_line_idx()
}

// Returns whether the `target_cursor_line` is:
// 1. If the window cannot even contain it, because it is just too long.
// 2. If the window can exactly contain it, i.e. it will use the same rows that
//    equals to the window height.
fn _can_fully_contain_target_cursor_line(
  line_process_fn: WrapLineProcessFn,
  text: &Text,
  size: &U16Size,
  target_cursor_line: usize,
) -> (bool, bool) {
  let window_height = size.height();
  let window_width = size.width();

  // Try preview put the target cursor line with `start_column = 0`, start from
  // `current_row = 0`.
  let (
    preview_target_rows,
    _preview_target_start_fills,
    _preview_target_end_fills,
    _,
  ) = line_process_fn(
    text,
    0,
    target_cursor_line,
    0_u16,
    // Note: here use window_height + 3 to give a larger window, to test if the
    // line can use more rows.
    window_height.saturating_add(3),
    window_width,
  );

  // Current window cannot contain the target cursor line, i.e. target cursor
  // line is just too long to be put in current window.
  let cannot_fully_contain_target_cursor_line =
    preview_target_rows.len() > window_height as usize;

  // Current window can exactly contain the target cursor line, i.e. target
  // cursor line just happens to use all the rows in current window.
  let can_exactly_contain_target_cursor_line =
    preview_target_rows.len() == window_height as usize;

  (
    cannot_fully_contain_target_cursor_line,
    can_exactly_contain_target_cursor_line,
  )
}

fn nowrap_search_down(
  viewport: &Viewport,
  cursor_viewport: &CursorViewport,
  text: &Text,
  size: &U16Size,
  target_cursor_line: usize,
  target_cursor_char: usize,
) -> (usize, usize) {
  let window_height = size.height();

  // Try to keep current `viewport.start_line_idx` unchanged, this will keep
  // the viewport scrolls as small as we can, and thus avoid too big jumps for
  // users' eye.
  let already_contains_target_cursor_line =
    _if_contains_target_cursor_line(viewport, target_cursor_line);

  let current_cursor_column =
    text.width_before(cursor_viewport.line_idx(), cursor_viewport.char_idx());
  let target_cursor_column =
    text.width_before(target_cursor_line, target_cursor_char);

  if already_contains_target_cursor_line {
    // Yes it contains, this means we don't have to scroll the window viewport,
    // we can still use the `viewport.start_line_idx` as the first line for
    // the new viewport.

    let start_line = viewport.start_line_idx();
    let start_column = viewport.start_column_idx();

    if target_cursor_column < current_cursor_column {
      trace!(
        "viewport:{}/{},cursor_viewport:{:?},start_line/column:{}/{},target_cursor:{}/{}",
        viewport.start_line_idx(),
        viewport.start_column_idx(),
        cursor_viewport,
        start_line,
        start_column,
        target_cursor_line,
        target_cursor_char,
      );
      // Cursor moves to left side.
      nowrap_search_left(
        text,
        size,
        start_line,
        start_column,
        target_cursor_line,
        target_cursor_char,
      )
    } else {
      // Cursor moves to right side (even just for 0-chars).
      nowrap_search_right(
        text,
        size,
        start_line,
        start_column,
        target_cursor_line,
        target_cursor_char,
      )
    }
  } else {
    // Otherwise `target_cursor_line` is out of current viewport. We have to
    // find out the correct first line for the new viewport.

    let start_line = std::cmp::max(
      0,
      (target_cursor_line as isize) - (window_height as isize) + 1,
    ) as usize;
    let start_column = viewport.start_column_idx();

    if target_cursor_column < current_cursor_column {
      // To left side
      nowrap_search_left(
        text,
        size,
        start_line,
        start_column,
        target_cursor_line,
        target_cursor_char,
      )
    } else {
      // To right side
      nowrap_search_right(
        text,
        size,
        start_line,
        start_column,
        target_cursor_line,
        target_cursor_char,
      )
    }
  }
}

fn nowrap_search_up(
  viewport: &Viewport,
  cursor_viewport: &CursorViewport,
  text: &Text,
  size: &U16Size,
  target_cursor_line: usize,
  target_cursor_char: usize,
) -> (usize, usize) {
  // Try to keep current `viewport.start_line_idx` unchanged, this will keep
  // the viewport scrolls as small as we can, and thus avoid too big jumps for
  // users' eye.
  let already_contains_target_cursor_line =
    _if_contains_target_cursor_line(viewport, target_cursor_line);

  let current_cursor_column =
    text.width_before(cursor_viewport.line_idx(), cursor_viewport.char_idx());
  let target_cursor_column =
    text.width_before(target_cursor_line, target_cursor_char);

  if already_contains_target_cursor_line {
    // Yes it contains, this means we don't have to scroll the window viewport,
    // we can still use the `viewport.start_line_idx` as the first line for the
    // new viewport.

    let start_line = viewport.start_line_idx();
    let start_column = viewport.start_column_idx();

    if target_cursor_column < current_cursor_column {
      // Cursor moves to left side.
      nowrap_search_left(
        text,
        size,
        start_line,
        start_column,
        target_cursor_line,
        target_cursor_char,
      )
    } else {
      // Cursor moves to right side (even just for 0-chars).
      nowrap_search_right(
        text,
        size,
        start_line,
        start_column,
        target_cursor_line,
        target_cursor_char,
      )
    }
  } else {
    // Otherwise `target_cursor_line` is out of current viewport. We have to
    // find out the correct first line for the new viewport.

    let start_line = target_cursor_line;
    let start_column = viewport.start_column_idx();

    if target_cursor_column < current_cursor_column {
      // To left side
      nowrap_search_left(
        text,
        size,
        start_line,
        start_column,
        target_cursor_line,
        target_cursor_char,
      )
    } else {
      // To right side
      nowrap_search_right(
        text,
        size,
        start_line,
        start_column,
        target_cursor_line,
        target_cursor_char,
      )
    }
  }
}

// When cursor moves to downward and scrolls the window, we need to set a
// larger `start_line` for the new viewport to "contain" the target cursor line
// inside the window.
//
// In such case, how could we know what `start_line` we should use for the new
// viewport?
//
// We still iterate the lines (in the buffer) one by one, but from the
// `target_cursor_line` reversely, from bottom to top, until we find the first
// line which cannot "contain" the `target_cursor_line` any more. Then the
// `first_line + 1` is our `start_line`.
//
// Returns `start_line` for the new viewport.
fn _reverse_search_target_cursor_line(
  sync_fn: WrapSyncFn,
  line_process_fn: WrapLineProcessFn,
  viewport: &Viewport,
  text: &Text,
  size: &U16Size,
  target_cursor_line: usize,
  target_cursor_char: usize,
) -> usize {
  let window_height = size.height();
  let window_width = size.width();

  let mut current_row: usize = 0;
  let mut current_line: isize = target_cursor_line as isize;

  // Here we set the `current_line` iterates start from `target_cursor_line`,
  // until it cannot fully renders the `target_cursor_line`.
  //
  // In most happy case, the `current_line + 1` will be the `start_line` for
  // new viewport, the `target_cursor_line` will just be the last line in the
  // new viewport, which looks good for users.
  // For example:
  //
  // ```
  //  AAAAAAAAAA    <- current_line
  // +----------+
  // |BBBBBBBBBB|   <- current_line + 1
  // |BBBBBB.\n |
  // |CCCCCCCCCC|   <- target_cursor_line
  // |CCC.\n    |
  // +----------+
  // ```

  while (current_row < window_height as usize) && (current_line >= 0) {
    let (rows, _start_fills, _end_fills, _last_row) = line_process_fn(
      text,
      0,
      current_line as usize,
      0,
      window_height,
      window_width,
    );
    current_row += rows.len();
    current_line -= 1;
  }

  // Here we have an edge case: the `target_cursor_line` is partially rendered,
  // i.e. the `target_cursor_line` will not be fully shown in the new viewport.
  // For example:
  //
  // ```
  //  AAAAAAAAAA    <- current_line
  // +----------+
  // |BBBBBBBBBB|   <- current_line + 1
  // |BBBBBBBBBB|
  // |BB.\n     |
  // |CCCCCCCCCC|   <- target_cursor_line
  // +----------+
  //  CCC.\n
  // ```
  //
  // When `wrap = true` we always try to put the entire `target_cursor_line`
  // inside the window/viewport. So for this case, we use `current_line + 2`
  // as `start_line` for the new viewport.

  let start_line = if current_row > window_height as usize {
    debug_assert!(current_line + 2 <= target_cursor_line as isize);
    current_line + 2
  } else {
    debug_assert!(current_line < target_cursor_line as isize);
    current_line + 1
  };
  debug_assert!(start_line >= 0);
  debug_assert!(start_line <= target_cursor_line as isize);
  let start_line =
    std::cmp::max(viewport.start_line_idx(), start_line as usize);

  // Here we have another edge case: the `target_cursor_line` is fully rendered,
  // but `target_cursor_char` is eol or line end. Since our rendering algorithm
  // will not render eol (`\n` or `\r\n`), while in **insert** mode, cursor
  // will want the line end position (for appending characters at the end of
  // line). And it also happens that `target_cursor_line` is the last line, so
  // the cursor actually wants a position that is next to the right-bottom
  // corner of the window. For example:
  //
  // ```
  //  AAAAAAAAAA      <- current_line
  // +----------+
  // |BBBBBBBBBB|     <- current_line + 1
  // |BBBBBBBBBB|
  // |BB.\n     |
  // |CCCCCCCCCC|_\n  <- target_cursor_line, `_` is target_cursor_char
  // +----------+
  //  DDDDDD.\n
  // ```
  //
  // And there are two sub-cases:
  // 1. If the `target_cursor_line` is just too long to be put in current
  //    window. Then the current window will only have 1 line, i.e. the
  //    `target_cursor_line`. And we don't have to do anything, leave the
  //    left/right movements to other methods.
  // 2. If the `target_cursor_line` is not too long, and current window can
  //    contain more than 1 lines, include the `target_cursor_line`, just like
  //    the above example. Then we move 1 more line down to ensure the
  //    `target_cursor_char` can be safely put to the next row.
  //
  //     ```
  //      AAAAAAAAAA      <- current_line
  //      BBBBBBBBBB      <- current_line + 1
  //      BBBBBBBBBB
  //      BB.\n
  //     +----------+
  //     |CCCCCCCCCC|_\n  <- target_cursor_line, `_` is target_cursor_char
  //     |*DDDDD.\n |     <- `*` is the cursor rendered in terminal, it is put
  //     |          |        to next row.
  //     |          |
  //     +----------+
  //     ```

  let (
    cannot_fully_contain_target_cursor_line,
    can_exactly_contain_target_cursor_line,
  ) = _can_fully_contain_target_cursor_line(
    line_process_fn,
    text,
    size,
    target_cursor_line,
  );

  if cannot_fully_contain_target_cursor_line
    || can_exactly_contain_target_cursor_line
  {
    return start_line;
  }

  let (_preview_line_range, preview_viewport) =
    sync_fn(text, size, start_line, 0);
  debug_assert!(preview_viewport.last().is_some());
  let (last_preview_line, last_preview_line_viewport) =
    preview_viewport.last().unwrap();

  let target_cursor_char_is_at_right_bottom_corner = {
    // Target cursor line is the last line in preview viewport.
    let is_last_line = *last_preview_line == target_cursor_line;

    // Target cursor char is at right-bottom corner in the preview viewport.
    if is_last_line {
      if let Some((_last_preview_row, last_preview_row_viewport)) =
        last_preview_line_viewport.rows().last()
      {
        // 1. The last row of the preview viewport is not empty
        let last_row_not_empty = last_preview_row_viewport.end_char_idx()
          > last_preview_row_viewport.start_char_idx();

        // 2. The end char of last row <= `target_cursor_char`
        let at_last_row =
          last_preview_row_viewport.end_char_idx() <= target_cursor_char;

        // 3. The width of last row >= `window_width`
        let last_row_end_column = text.width_before(
          target_cursor_line,
          last_preview_row_viewport.end_char_idx(),
        );
        let last_row_start_column = text.width_before(
          target_cursor_line,
          last_preview_row_viewport.start_char_idx(),
        );
        let last_row_width =
          last_row_end_column.saturating_sub(last_row_start_column);
        let last_row_use_full_width = last_row_width >= window_width as usize;

        last_row_not_empty && at_last_row && last_row_use_full_width
      } else {
        false
      }
    } else {
      false
    }
  };

  let start_line = if target_cursor_char_is_at_right_bottom_corner {
    // Add 1 more line, but don't be greater than `target_cursor_line` itself.
    start_line + 1
  } else {
    start_line
  };
  std::cmp::min(start_line, target_cursor_line)
}

fn wrap_search_down(
  sync_fn: WrapSyncFn,
  line_process_fn: WrapLineProcessFn,
  search_left_fn: WrapHorizontalSearchFn,
  search_right_fn: WrapHorizontalSearchFn,
  viewport: &Viewport,
  cursor_viewport: &CursorViewport,
  opts: &WindowOptions,
  text: &Text,
  size: &U16Size,
  target_cursor_line: usize,
  target_cursor_char: usize,
) -> (usize, usize) {
  let current_cursor_column =
    text.width_before(cursor_viewport.line_idx(), cursor_viewport.char_idx());
  let target_cursor_column =
    text.width_before(target_cursor_line, target_cursor_char);

  let start_line = _reverse_search_target_cursor_line(
    sync_fn,
    line_process_fn,
    viewport,
    text,
    size,
    target_cursor_line,
    target_cursor_char,
  );
  let start_column = viewport.start_column_idx();

  // Cursor moves to left side.
  if target_cursor_column < current_cursor_column {
    search_left_fn(
      sync_fn,
      line_process_fn,
      viewport,
      cursor_viewport,
      opts,
      text,
      size,
      start_line,
      start_column,
      target_cursor_line,
      target_cursor_char,
    )
  } else {
    // Cursor moves to right side (even just for 0-chars).
    search_right_fn(
      sync_fn,
      line_process_fn,
      viewport,
      cursor_viewport,
      opts,
      text,
      size,
      start_line,
      start_column,
      target_cursor_line,
      target_cursor_char,
    )
  }
}

fn wrap_search_up(
  sync_fn: WrapSyncFn,
  line_process_fn: WrapLineProcessFn,
  search_left_fn: WrapHorizontalSearchFn,
  search_right_fn: WrapHorizontalSearchFn,
  viewport: &Viewport,
  cursor_viewport: &CursorViewport,
  opts: &WindowOptions,
  text: &Text,
  size: &U16Size,
  target_cursor_line: usize,
  target_cursor_char: usize,
) -> (usize, usize) {
  let current_cursor_column =
    text.width_before(cursor_viewport.line_idx(), cursor_viewport.char_idx());
  let target_cursor_column =
    text.width_before(target_cursor_line, target_cursor_char);

  let start_line = std::cmp::min(target_cursor_line, viewport.start_line_idx());
  let start_column = viewport.start_column_idx();

  // Cursor moves to left side.
  if target_cursor_column < current_cursor_column {
    search_left_fn(
      sync_fn,
      line_process_fn,
      viewport,
      cursor_viewport,
      opts,
      text,
      size,
      start_line,
      start_column,
      target_cursor_line,
      target_cursor_char,
    )
  } else {
    // Cursor moves to right side (even just for 0-chars).
    search_right_fn(
      sync_fn,
      line_process_fn,
      viewport,
      cursor_viewport,
      opts,
      text,
      size,
      start_line,
      start_column,
      target_cursor_line,
      target_cursor_char,
    )
  }
}

// For/to leftward
fn _find_target_cursor_column_exclude_eol(
  text: &Text,
  target_cursor_line: usize,
  target_cursor_char: usize,
) -> usize {
  let mut target_cursor_column =
    text.width_before(target_cursor_line, target_cursor_char);

  // If `target_cursor_char` is eol or line end, and now we are moving to left
  // side. It could be something like:
  //
  // ```
  //            +----------+
  //  AAAAAAAAAA|BBBBBBBBBB|\n   <- line-0
  //  CCCCCCCCCC|_\n       |     <- line-1
  //  3rd.\n    |          |     <- line-2
  //            +----------+
  // ```
  //
  // Note: The cursor is at line-1, the first column.
  // In such case, it will be better to move `start_column` to left for 1 more
  // column, and showing the first visible char (i.e. neither eol nor line
  // end). Then the new viewport will become something like:
  //
  // ```
  //           +----------+
  //  AAAAAAAAA|ABBBBBBBBB|B\n  <- line-0
  //  CCCCCCCCC|C_\n      |     <- line-1
  //  3rd.\n   |          |     <- line-2
  //           +----------+
  // ```
  //
  // Now it looks much better.

  if text.is_eol_or_line_end(target_cursor_line, target_cursor_char) {
    if cfg!(debug_assertions) {
      if let Some(last_char_exclude_eol) =
        text.last_char_idx_on_line_exclude_eol(target_cursor_line)
      {
        debug_assert!(
          target_cursor_char > last_char_exclude_eol
            && target_cursor_char <= last_char_exclude_eol + 2
        );
      }
    }
    let last_char_exclude_eol = text
      .last_char_idx_on_line_exclude_eol(target_cursor_line)
      .unwrap_or(0);
    target_cursor_column =
      text.width_before(target_cursor_line, last_char_exclude_eol);
  }

  target_cursor_column
}

// For/to rightward
fn _find_target_cursor_column_include_eol(
  text: &Text,
  target_cursor_line: usize,
  target_cursor_char: usize,
) -> usize {
  let out_of_line =
    text.is_eol_or_line_end(target_cursor_line, target_cursor_char);

  // For eol or line-end, add 1 more column
  text.width_until(target_cursor_line, target_cursor_char)
    + if out_of_line { 1 } else { 0 }
}

fn nowrap_search_left(
  text: &Text,
  _size: &U16Size,
  suggest_start_line: usize,
  suggest_start_column: usize,
  target_cursor_line: usize,
  target_cursor_char: usize,
) -> (usize, usize) {
  let mut suggest_start_column = suggest_start_column;
  let target_cursor_column = _find_target_cursor_column_exclude_eol(
    text,
    target_cursor_line,
    target_cursor_char,
  );

  if target_cursor_column < suggest_start_column {
    suggest_start_column = target_cursor_column;
  }

  trace!(
    "suggest_line/column:{}/{},target_line/char/column:{}/{}/{}",
    suggest_start_line,
    suggest_start_column,
    target_cursor_line,
    target_cursor_char,
    target_cursor_column,
  );
  (suggest_start_line, suggest_start_column)
}

fn nowrap_search_right(
  text: &Text,
  size: &U16Size,
  suggest_start_line: usize,
  suggest_start_column: usize,
  target_cursor_line: usize,
  target_cursor_char: usize,
) -> (usize, usize) {
  let window_width = size.width();
  let suggest_end_column = suggest_start_column + window_width as usize;
  let mut suggest_start_column = suggest_start_column;

  let target_cursor_column = _find_target_cursor_column_include_eol(
    text,
    target_cursor_line,
    target_cursor_char,
  );
  if target_cursor_column > suggest_end_column {
    suggest_start_column =
      target_cursor_column.saturating_sub(window_width as usize);
  }

  // This "search_right" method can be called if the
  // `target_cursor_column == current_cursor_column`, which means this method
  // also need to consider non-right case, or even search to leftward case.
  //
  // If in `target_cursor_line`, the `target_cursor_char` is already the last
  // char, and it is eol or line end, and there is no other visible char in
  // `target_cursor_line`, we should actually move the `suggest_start_column`
  // to leftward for 1 visible char, to ensure the `target_cursor_line`
  // contains at least 1 visible char.
  let last_char = text
    .last_char_idx_on_line_exclude_eol(target_cursor_line)
    .unwrap_or(0);
  let last_char_column = text.width_before(target_cursor_line, last_char);
  let suggest_start_column =
    std::cmp::min(suggest_start_column, last_char_column);

  (suggest_start_line, suggest_start_column)
}

fn wrap_search_left(
  _sync_fn: WrapSyncFn,
  line_process_fn: WrapLineProcessFn,
  _viewport: &Viewport,
  _cursor_viewport: &CursorViewport,
  _opts: &WindowOptions,
  text: &Text,
  size: &U16Size,
  suggest_start_line: usize,
  suggest_start_column: usize,
  target_cursor_line: usize,
  target_cursor_char: usize,
) -> (usize, usize) {
  let window_height = size.height();
  let window_width = size.width();

  let (
    cannot_fully_contain_target_cursor_line,
    can_exactly_contain_target_cursor_line,
  ) = _can_fully_contain_target_cursor_line(
    line_process_fn,
    text,
    size,
    target_cursor_line,
  );

  let target_cursor_column = _find_target_cursor_column_exclude_eol(
    text,
    target_cursor_line,
    target_cursor_char,
  );

  if cannot_fully_contain_target_cursor_line
    || can_exactly_contain_target_cursor_line
  {
    // For `start_line`, force it to be `target_cursor_line`, because viewport
    // can only contain this line (and still cannot put all of it inside).
    let start_line = target_cursor_line;

    // For `start_column`, it seems that we only need to pick the smaller one
    // between `target_cursor_column` and `suggest_start_column`. But there is an
    // edge case we need to consider, for example:
    //
    // ```
    //           +----------+
    // AAAAAAAAAA|AAAAAAAAAA|     <- line-0
    //           |AAAAAAAAAA|
    //           |AAAAAAAAA_|\n   <- Now cursor is at line-0, char-39. `start_column` is 10.
    //           +----------+
    //            BBBBBBBBBB      <- line-1
    //            BBBBBBBBBB
    //            BBBBBBBBBB
    //            BB_\n           <- Cursor wants line-1, char-32.
    // ```
    //
    // Cursor wants to move down to line-1, move left to char-32.
    // In such case, the `suggest_start_column` is 10 (it is the current viewport
    // `start_column`), the `target_cursor_column` is 32. If we simply use the
    // smaller one between `suggest_start_column` and `target_cursor_column`, then
    // the `start_column` is 10. And the viewport becomes:
    //
    // ```
    //            AAAAAAAAAA     <- line-0
    //            AAAAAAAAAA
    //            AAAAAAAAAA
    //            AAAAAAAAA\n    <- Previous cursor is at line-0, char-39.
    //           +----------+
    // BBBBBBBBBB|BBBBBBBBBB|    <- line-1
    //           |BBBBBBBBBB|
    //           |BB_\n     |    <- Cursor is at line-1, char-32, `start_column` is 10.
    //           +----------+
    // ```
    //
    // The looking is weird because there still are some empty columns left at
    // the end of the last row, while at the beginning of the line, 10 `B`
    // characters are not rendered in the viewport. The window spaces are
    // wasted.

    let start_column =
      std::cmp::min(suggest_start_column, target_cursor_column);

    // So we try to do some more additional leftward movement on
    // the `target_cursor_column`, to make give the new viewport can
    // contain the `target_cursor_char`.
    let target_cursor_line_end_char = text
      .last_char_idx_on_line_include_eol(target_cursor_line)
      .unwrap_or(0);
    let target_cursor_line_end_column = text
      .width_until(target_cursor_line, target_cursor_line_end_char)
      + if text
        .is_eol_or_line_end(target_cursor_line, target_cursor_line_end_char)
      {
        1
      } else {
        0
      };
    let target_cursor_line_start_column = target_cursor_line_end_column
      .saturating_sub((window_width as usize) * (window_height as usize));

    // NOTE: only contain 1 line
    debug_assert!(
      cannot_fully_contain_target_cursor_line
        || can_exactly_contain_target_cursor_line
    );
    let target_cursor_line_start_column = _reverse_search_start_column(
      line_process_fn,
      text,
      size,
      start_line,
      target_cursor_line_start_column,
      target_cursor_line,
      target_cursor_line_end_char,
    );

    let start_column =
      std::cmp::min(start_column, target_cursor_line_start_column);

    (start_line, start_column)
  } else {
    // For `start_column`, force it to be 0.
    let start_column = 0;
    let start_line = suggest_start_line;

    (start_line, start_column)
  }
}

// By the formula:
//
// ```
// target_cursor_start_column = target_cursor_end_column - (window_height * window_width)
// ```
//
// It cannot handle the potential empty columns at the end of rows, "potential"
// means:
//
// 1. Bad case: There are some empty columns. In this case, the final rendered
//    columns of `[target_cursor_start_column,target_cursor_end_column)` (or
//    `[target_cursor_start_column,target_cursor_char)`) will be longer than
//    `(window_height * window_width)`, because these extra empty columns are
//    wasted.
// 2. Good case: There are no empty columns. In this case, the final rendered
//    columns is exactly `(window_height * window_width)`.
//
// We can see the `target_cursor_start_column` can be still or larger, but
// can never be smaller.
//
// This method try to use a larger `start_column`, based on the
// `target_cursor_start_column` we calculated with above formula. It repeatedly
// searches to rightward by `target_cursor_start_column += 1`, and check if the
// result are better.
fn _reverse_search_start_column(
  line_process_fn: WrapLineProcessFn,
  text: &Text,
  size: &U16Size,
  _suggest_start_line: usize,
  suggest_start_column: usize,
  target_cursor_line: usize,
  target_cursor_char: usize,
) -> usize {
  let window_height = size.height();
  let window_width = size.width();
  let bufline = text.rope().line(target_cursor_line);
  let bufline_len_char = bufline.len_chars();
  let bufline_chars_width =
    text.width_until(target_cursor_line, bufline_len_char);

  let eol_or_line_end =
    text.is_eol_or_line_end(target_cursor_line, target_cursor_char);
  let mut suggest_start_column = suggest_start_column;

  while suggest_start_column < bufline_chars_width {
    let (preview_target_rows, _preview_start_fills, _preview_end_fills, _) =
      line_process_fn(
        text,
        suggest_start_column,
        target_cursor_line,
        0_u16,
        window_height,
        window_width,
      );

    // This method is only used when `wrap = true`, and the line is long enough
    // that 1 single line uses the entier window/viewport.
    debug_assert!(preview_target_rows.len() <= window_height as usize);

    // If this preview viewport can contain `target_cursor_char`.
    let contains_target_cursor_char =
      preview_target_rows.iter().any(|(_row_idx, row_viewport)| {
        target_cursor_char >= row_viewport.start_char_idx()
          && target_cursor_char < row_viewport.end_char_idx()
      });
    if contains_target_cursor_char {
      return suggest_start_column;
    }

    // 1. If `target_cursor_char` is eol or line end
    // 2. If this preview viewport last row has the eol or line end
    // 3. The last row doesn't use all the columns in the row, i.e. it has at
    //    least 1 empty column to put the `target_cursor_char` at line end.
    if eol_or_line_end {
      let contains_target_cursor_char_as_eol =
        preview_target_rows.iter().any(|(_row_idx, row_viewport)| {
          target_cursor_char == row_viewport.end_char_idx()
        });

      if contains_target_cursor_char_as_eol {
        // The width of last row == `window_width`, i.e. the last row already
        // uses all columns (full width).
        // In such case, if the `target_cursor_char` is eol, we will need to
        // give it 1 more column for it.
        let last_row_use_full_width = {
          debug_assert!(preview_target_rows.last().is_some());
          let (_last_preview_row_idx, last_preview_row_viewport) =
            preview_target_rows.last().unwrap();
          let last_row_end_column = text.width_before(
            target_cursor_line,
            last_preview_row_viewport.end_char_idx(),
          );
          let last_row_start_column = text.width_before(
            target_cursor_line,
            last_preview_row_viewport.start_char_idx(),
          );
          let last_row_width =
            last_row_end_column.saturating_sub(last_row_start_column);
          last_row_width >= window_width as usize
        };

        if !last_row_use_full_width {
          return suggest_start_column;
        }
      }
    }

    suggest_start_column += 1;
  }

  unreachable!()
}

fn wrap_search_right(
  _sync_fn: WrapSyncFn,
  line_process_fn: WrapLineProcessFn,
  _viewport: &Viewport,
  _cursor_viewport: &CursorViewport,
  _opts: &WindowOptions,
  text: &Text,
  size: &U16Size,
  suggest_start_line: usize,
  suggest_start_column: usize,
  target_cursor_line: usize,
  target_cursor_char: usize,
) -> (usize, usize) {
  let window_height = size.height();
  let window_width = size.width();

  let (
    cannot_fully_contain_target_cursor_line,
    can_exactly_contain_target_cursor_line,
  ) = _can_fully_contain_target_cursor_line(
    line_process_fn,
    text,
    size,
    target_cursor_line,
  );

  let target_cursor_column =
    text.width_until(target_cursor_line, target_cursor_char);

  if cannot_fully_contain_target_cursor_line
    || can_exactly_contain_target_cursor_line
  {
    // For `start_line`, force it to be `target_cursor_line`, because viewport
    // can only contain this line (and still cannot put all of it inside).
    let start_line = target_cursor_line;

    // For `start_column`, calculate the `target_cursor_start_column` based on
    // the `target_cursor_column` as the end column in the window.
    //
    // But when `wrap = true` (no matter `linebreak` is `true` or `false`),
    // there is an edge case, that some character or word can leaves columns
    // not fully filled at the end of a window row.
    //
    // When `wrap = true, linebreak = false`:
    //
    // Example-1.1
    //
    // ```
    // +----------+
    // |AAAAAAAA<<|   <- row-0
    // |\tBBB.\n  |   <- row-1
    // +----------+
    // ```
    //
    // Example-1.2
    //
    // ```
    // +----------+
    // |AAAAAAAAA<|   <- row-0
    // |你好.\n   |   <- row-1
    // +----------+
    // ```
    //
    // For example-1.1, at the end of row-0, there are 2 empty columns because
    // the following character `\t` are rendered as 8 columns, but the 2
    // columns at the end of row-0 is not enough for `\t`. The rendering
    // algorithm force to put the `\t` to row-1, and leaves 2 empty columns at
    // the end of row-0.
    //
    // For example-1.2, there are 1 empty column at the end of row-0, because
    // the following character `你` are rendered as 2 columns, but the 1 column
    // at the end of row-0 is not enough.
    //
    // When `wrap = true, linebreak = true`:
    //
    // Example-2.1
    //
    // ```
    // +----------+
    // |This is <<|   <- row-0
    // |ours.\n   |   <- row-1
    // +----------+
    // ```
    //
    // There are 2 empty columns at the end of row-0, because the following
    // word `ours` are rendered as 4 columns, and the rendering algorithm
    // force to put a word in 1 row when `linebreak=true`, thus it leaves 2
    // empty columns at the end of row-0.

    // If `target_cursor_char` is a eol or line end, we move to right for 1
    // more column to allow the invisible eol or line end.
    let target_cursor_end_column =
      if text.is_eol_or_line_end(target_cursor_line, target_cursor_char) {
        target_cursor_column + 1
      } else {
        target_cursor_column
      };

    // In such case, we cannot simply use `target_cursor_end_column -
    // (window_height * window_width)` to calculate the
    // `target_cursor_start_column`.
    let target_cursor_start_column = target_cursor_end_column
      .saturating_sub((window_width as usize) * (window_height as usize));

    // NOTE: only contain 1 line
    debug_assert!(
      cannot_fully_contain_target_cursor_line
        || can_exactly_contain_target_cursor_line
    );
    // We try to do some more additional rightward movement on
    // `target_cursor_start_column`, to make sure the new viewport can
    // contain the `target_cursor_char`.
    let target_cursor_start_column = _reverse_search_start_column(
      line_process_fn,
      text,
      size,
      start_line,
      target_cursor_start_column,
      target_cursor_line,
      target_cursor_char,
    );

    let start_column =
      std::cmp::max(suggest_start_column, target_cursor_start_column);

    (start_line, start_column)
  } else {
    // For `start_column`, force it to be 0.
    let start_column = 0;
    let start_line = suggest_start_line;

    (start_line, start_column)
  }
}