aboutsummaryrefslogtreecommitdiff
path: root/src/nvim/mbyte.c
blob: af9e214d92459f7d8f0af50eb7d05ccf0c613db9 (plain) (blame)
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
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
// This is an open source non-commercial project. Dear PVS-Studio, please check
// it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com

/// mbyte.c: Code specifically for handling multi-byte characters.
/// Multibyte extensions partly by Sung-Hoon Baek
///
/// Strings internal to Nvim are always encoded as UTF-8 (thus the legacy
/// 'encoding' option is always "utf-8").
///
/// The cell width on the display needs to be determined from the character
/// value. Recognizing UTF-8 bytes is easy: 0xxx.xxxx is a single-byte char,
/// 10xx.xxxx is a trailing byte, 11xx.xxxx is a leading byte of a multi-byte
/// character. To make things complicated, up to six composing characters
/// are allowed. These are drawn on top of the first char. For most editing
/// the sequence of bytes with composing characters included is considered to
/// be one character.
///
/// UTF-8 is used everywhere in the core. This is in registers, text
/// manipulation, buffers, etc. Nvim core communicates with external plugins
/// and GUIs in this encoding.
///
/// The encoding of a file is specified with 'fileencoding'.  Conversion
/// is to be done when it's different from "utf-8".
///
/// Vim scripts may contain an ":scriptencoding" command. This has an effect
/// for some commands, like ":menutrans".

#include <inttypes.h>
#include <stdbool.h>
#include <string.h>
#include <wchar.h>
#include <wctype.h>

#include "nvim/ascii.h"
#include "nvim/vim.h"
#ifdef HAVE_LOCALE_H
# include <locale.h>
#endif
#include "nvim/arabic.h"
#include "nvim/charset.h"
#include "nvim/cursor.h"
#include "nvim/drawscreen.h"
#include "nvim/eval.h"
#include "nvim/fileio.h"
#include "nvim/func_attr.h"
#include "nvim/getchar.h"
#include "nvim/iconv.h"
#include "nvim/mark.h"
#include "nvim/mbyte.h"
#include "nvim/memline.h"
#include "nvim/memory.h"
#include "nvim/message.h"
#include "nvim/os/os.h"
#include "nvim/path.h"
#include "nvim/screen.h"
#include "nvim/spell.h"
#include "nvim/strings.h"

typedef struct {
  int rangeStart;
  int rangeEnd;
  int step;
  int offset;
} convertStruct;

struct interval {
  long first;
  long last;
};

#ifdef INCLUDE_GENERATED_DECLARATIONS
# include "mbyte.c.generated.h"

# include "unicode_tables.generated.h"
#endif

static char e_list_item_nr_is_not_list[]
  = N_("E1109: List item %d is not a List");
static char e_list_item_nr_does_not_contain_3_numbers[]
  = N_("E1110: List item %d does not contain 3 numbers");
static char e_list_item_nr_range_invalid[]
  = N_("E1111: List item %d range invalid");
static char e_list_item_nr_cell_width_invalid[]
  = N_("E1112: List item %d cell width invalid");
static char e_overlapping_ranges_for_nr[]
  = N_("E1113: Overlapping ranges for 0x%lx");
static char e_only_values_of_0x100_and_higher_supported[]
  = N_("E1114: Only values of 0x100 and higher supported");

// To speed up BYTELEN(); keep a lookup table to quickly get the length in
// bytes of a UTF-8 character from the first byte of a UTF-8 string.  Bytes
// which are illegal when used as the first byte have a 1.  The NUL byte has
// length 1.
const uint8_t utf8len_tab[] = {
  // ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9 ?A ?B ?C ?D ?E ?F
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // 0?
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // 1?
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // 2?
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // 3?
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // 4?
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // 5?
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // 6?
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // 7?
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // 8?
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // 9?
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // A?
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // B?
  2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,  // C?
  2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,  // D?
  3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,  // E?
  4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 1, 1,  // F?
};

// Like utf8len_tab above, but using a zero for illegal lead bytes.
const uint8_t utf8len_tab_zero[] = {
  // ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9 ?A ?B ?C ?D ?E ?F
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // 0?
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // 1?
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // 2?
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // 3?
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // 4?
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // 5?
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // 6?
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // 7?
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  // 8?
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  // 9?
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  // A?
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  // B?
  2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,  // C?
  2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,  // D?
  3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,  // E?
  4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 0, 0,  // F?
};

/*
 * Canonical encoding names and their properties.
 * "iso-8859-n" is handled by enc_canonize() directly.
 */
static struct
{   const char *name;   int prop;              int codepage; }
enc_canon_table[] =
{
#define IDX_LATIN_1     0
  { "latin1",          ENC_8BIT + ENC_LATIN1,  1252 },
#define IDX_ISO_2       1
  { "iso-8859-2",      ENC_8BIT,               0 },
#define IDX_ISO_3       2
  { "iso-8859-3",      ENC_8BIT,               0 },
#define IDX_ISO_4       3
  { "iso-8859-4",      ENC_8BIT,               0 },
#define IDX_ISO_5       4
  { "iso-8859-5",      ENC_8BIT,               0 },
#define IDX_ISO_6       5
  { "iso-8859-6",      ENC_8BIT,               0 },
#define IDX_ISO_7       6
  { "iso-8859-7",      ENC_8BIT,               0 },
#define IDX_ISO_8       7
  { "iso-8859-8",      ENC_8BIT,               0 },
#define IDX_ISO_9       8
  { "iso-8859-9",      ENC_8BIT,               0 },
#define IDX_ISO_10      9
  { "iso-8859-10",     ENC_8BIT,               0 },
#define IDX_ISO_11      10
  { "iso-8859-11",     ENC_8BIT,               0 },
#define IDX_ISO_13      11
  { "iso-8859-13",     ENC_8BIT,               0 },
#define IDX_ISO_14      12
  { "iso-8859-14",     ENC_8BIT,               0 },
#define IDX_ISO_15      13
  { "iso-8859-15",     ENC_8BIT + ENC_LATIN9,  0 },
#define IDX_KOI8_R      14
  { "koi8-r",          ENC_8BIT,               0 },
#define IDX_KOI8_U      15
  { "koi8-u",          ENC_8BIT,               0 },
#define IDX_UTF8        16
  { "utf-8",           ENC_UNICODE,            0 },
#define IDX_UCS2        17
  { "ucs-2",           ENC_UNICODE + ENC_ENDIAN_B + ENC_2BYTE, 0 },
#define IDX_UCS2LE      18
  { "ucs-2le",         ENC_UNICODE + ENC_ENDIAN_L + ENC_2BYTE, 0 },
#define IDX_UTF16       19
  { "utf-16",          ENC_UNICODE + ENC_ENDIAN_B + ENC_2WORD, 0 },
#define IDX_UTF16LE     20
  { "utf-16le",        ENC_UNICODE + ENC_ENDIAN_L + ENC_2WORD, 0 },
#define IDX_UCS4        21
  { "ucs-4",           ENC_UNICODE + ENC_ENDIAN_B + ENC_4BYTE, 0 },
#define IDX_UCS4LE      22
  { "ucs-4le",         ENC_UNICODE + ENC_ENDIAN_L + ENC_4BYTE, 0 },

  // For debugging DBCS encoding on Unix.
#define IDX_DEBUG       23
  { "debug",           ENC_DBCS,               DBCS_DEBUG },
#define IDX_EUC_JP      24
  { "euc-jp",          ENC_DBCS,               DBCS_JPNU },
#define IDX_SJIS        25
  { "sjis",            ENC_DBCS,               DBCS_JPN },
#define IDX_EUC_KR      26
  { "euc-kr",          ENC_DBCS,               DBCS_KORU },
#define IDX_EUC_CN      27
  { "euc-cn",          ENC_DBCS,               DBCS_CHSU },
#define IDX_EUC_TW      28
  { "euc-tw",          ENC_DBCS,               DBCS_CHTU },
#define IDX_BIG5        29
  { "big5",            ENC_DBCS,               DBCS_CHT },

  // MS-DOS and MS-Windows codepages are included here, so that they can be
  // used on Unix too.  Most of them are similar to ISO-8859 encodings, but
  // not exactly the same.
#define IDX_CP437       30
  { "cp437",           ENC_8BIT,               437 },   // like iso-8859-1
#define IDX_CP737       31
  { "cp737",           ENC_8BIT,               737 },   // like iso-8859-7
#define IDX_CP775       32
  { "cp775",           ENC_8BIT,               775 },   // Baltic
#define IDX_CP850       33
  { "cp850",           ENC_8BIT,               850 },   // like iso-8859-4
#define IDX_CP852       34
  { "cp852",           ENC_8BIT,               852 },   // like iso-8859-1
#define IDX_CP855       35
  { "cp855",           ENC_8BIT,               855 },   // like iso-8859-2
#define IDX_CP857       36
  { "cp857",           ENC_8BIT,               857 },   // like iso-8859-5
#define IDX_CP860       37
  { "cp860",           ENC_8BIT,               860 },   // like iso-8859-9
#define IDX_CP861       38
  { "cp861",           ENC_8BIT,               861 },   // like iso-8859-1
#define IDX_CP862       39
  { "cp862",           ENC_8BIT,               862 },   // like iso-8859-1
#define IDX_CP863       40
  { "cp863",           ENC_8BIT,               863 },   // like iso-8859-8
#define IDX_CP865       41
  { "cp865",           ENC_8BIT,               865 },   // like iso-8859-1
#define IDX_CP866       42
  { "cp866",           ENC_8BIT,               866 },   // like iso-8859-5
#define IDX_CP869       43
  { "cp869",           ENC_8BIT,               869 },   // like iso-8859-7
#define IDX_CP874       44
  { "cp874",           ENC_8BIT,               874 },   // Thai
#define IDX_CP932       45
  { "cp932",           ENC_DBCS,               DBCS_JPN },
#define IDX_CP936       46
  { "cp936",           ENC_DBCS,               DBCS_CHS },
#define IDX_CP949       47
  { "cp949",           ENC_DBCS,               DBCS_KOR },
#define IDX_CP950       48
  { "cp950",           ENC_DBCS,               DBCS_CHT },
#define IDX_CP1250      49
  { "cp1250",          ENC_8BIT,               1250 },   // Czech, Polish, etc.
#define IDX_CP1251      50
  { "cp1251",          ENC_8BIT,               1251 },   // Cyrillic
  // cp1252 is considered to be equal to latin1
#define IDX_CP1253      51
  { "cp1253",          ENC_8BIT,               1253 },   // Greek
#define IDX_CP1254      52
  { "cp1254",          ENC_8BIT,               1254 },   // Turkish
#define IDX_CP1255      53
  { "cp1255",          ENC_8BIT,               1255 },   // Hebrew
#define IDX_CP1256      54
  { "cp1256",          ENC_8BIT,               1256 },   // Arabic
#define IDX_CP1257      55
  { "cp1257",          ENC_8BIT,               1257 },   // Baltic
#define IDX_CP1258      56
  { "cp1258",          ENC_8BIT,               1258 },   // Vietnamese

#define IDX_MACROMAN    57
  { "macroman",        ENC_8BIT + ENC_MACROMAN, 0 },      // Mac OS
#define IDX_HPROMAN8    58
  { "hp-roman8",       ENC_8BIT,               0 },       // HP Roman8
#define IDX_COUNT       59
};

/*
 * Aliases for encoding names.
 */
static struct
{   const char *name; int canon; }
enc_alias_table[] =
{
  { "ansi",            IDX_LATIN_1 },
  { "iso-8859-1",      IDX_LATIN_1 },
  { "latin2",          IDX_ISO_2 },
  { "latin3",          IDX_ISO_3 },
  { "latin4",          IDX_ISO_4 },
  { "cyrillic",        IDX_ISO_5 },
  { "arabic",          IDX_ISO_6 },
  { "greek",           IDX_ISO_7 },
  { "hebrew",          IDX_ISO_8 },
  { "latin5",          IDX_ISO_9 },
  { "turkish",         IDX_ISO_9 },   // ?
  { "latin6",          IDX_ISO_10 },
  { "nordic",          IDX_ISO_10 },  // ?
  { "thai",            IDX_ISO_11 },  // ?
  { "latin7",          IDX_ISO_13 },
  { "latin8",          IDX_ISO_14 },
  { "latin9",          IDX_ISO_15 },
  { "utf8",            IDX_UTF8 },
  { "unicode",         IDX_UCS2 },
  { "ucs2",            IDX_UCS2 },
  { "ucs2be",          IDX_UCS2 },
  { "ucs-2be",         IDX_UCS2 },
  { "ucs2le",          IDX_UCS2LE },
  { "utf16",           IDX_UTF16 },
  { "utf16be",         IDX_UTF16 },
  { "utf-16be",        IDX_UTF16 },
  { "utf16le",         IDX_UTF16LE },
  { "ucs4",            IDX_UCS4 },
  { "ucs4be",          IDX_UCS4 },
  { "ucs-4be",         IDX_UCS4 },
  { "ucs4le",          IDX_UCS4LE },
  { "utf32",           IDX_UCS4 },
  { "utf-32",          IDX_UCS4 },
  { "utf32be",         IDX_UCS4 },
  { "utf-32be",        IDX_UCS4 },
  { "utf32le",         IDX_UCS4LE },
  { "utf-32le",        IDX_UCS4LE },
  { "932",             IDX_CP932 },
  { "949",             IDX_CP949 },
  { "936",             IDX_CP936 },
  { "gbk",             IDX_CP936 },
  { "950",             IDX_CP950 },
  { "eucjp",           IDX_EUC_JP },
  { "unix-jis",        IDX_EUC_JP },
  { "ujis",            IDX_EUC_JP },
  { "shift-jis",       IDX_SJIS },
  { "pck",             IDX_SJIS },        // Sun: PCK
  { "euckr",           IDX_EUC_KR },
  { "5601",            IDX_EUC_KR },      // Sun: KS C 5601
  { "euccn",           IDX_EUC_CN },
  { "gb2312",          IDX_EUC_CN },
  { "euctw",           IDX_EUC_TW },
  { "japan",           IDX_EUC_JP },
  { "korea",           IDX_EUC_KR },
  { "prc",             IDX_EUC_CN },
  { "zh-cn",           IDX_EUC_CN },
  { "chinese",         IDX_EUC_CN },
  { "zh-tw",           IDX_EUC_TW },
  { "taiwan",          IDX_EUC_TW },
  { "cp950",           IDX_BIG5 },
  { "950",             IDX_BIG5 },
  { "mac",             IDX_MACROMAN },
  { "mac-roman",       IDX_MACROMAN },
  { NULL,              0 }
};

/*
 * Find encoding "name" in the list of canonical encoding names.
 * Returns -1 if not found.
 */
static int enc_canon_search(const char_u *name)
  FUNC_ATTR_PURE
{
  for (int i = 0; i < IDX_COUNT; i++) {
    if (STRCMP(name, enc_canon_table[i].name) == 0) {
      return i;
    }
  }
  return -1;
}

/*
 * Find canonical encoding "name" in the list and return its properties.
 * Returns 0 if not found.
 */
int enc_canon_props(const char_u *name)
  FUNC_ATTR_PURE
{
  int i = enc_canon_search(name);
  if (i >= 0) {
    return enc_canon_table[i].prop;
  } else if (STRNCMP(name, "2byte-", 6) == 0) {
    return ENC_DBCS;
  } else if (STRNCMP(name, "8bit-", 5) == 0 || STRNCMP(name, "iso-8859-", 9) == 0) {
    return ENC_8BIT;
  }
  return 0;
}

/*
 * Return the size of the BOM for the current buffer:
 * 0 - no BOM
 * 2 - UCS-2 or UTF-16 BOM
 * 4 - UCS-4 BOM
 * 3 - UTF-8 BOM
 */
int bomb_size(void)
  FUNC_ATTR_PURE
{
  int n = 0;

  if (curbuf->b_p_bomb && !curbuf->b_p_bin) {
    if (*curbuf->b_p_fenc == NUL
        || STRCMP(curbuf->b_p_fenc, "utf-8") == 0) {
      n = 3;
    } else if (STRNCMP(curbuf->b_p_fenc, "ucs-2", 5) == 0
               || STRNCMP(curbuf->b_p_fenc, "utf-16", 6) == 0) {
      n = 2;
    } else if (STRNCMP(curbuf->b_p_fenc, "ucs-4", 5) == 0) {
      n = 4;
    }
  }
  return n;
}

/*
 * Remove all BOM from "s" by moving remaining text.
 */
void remove_bom(char_u *s)
{
  char *p = (char *)s;

  while ((p = strchr(p, 0xef)) != NULL) {
    if ((uint8_t)p[1] == 0xbb && (uint8_t)p[2] == 0xbf) {
      STRMOVE(p, p + 3);
    } else {
      p++;
    }
  }
}

/*
 * Get class of pointer:
 * 0 for blank or NUL
 * 1 for punctuation
 * 2 for an (ASCII) word character
 * >2 for other word characters
 */
int mb_get_class(const char_u *p)
  FUNC_ATTR_PURE
{
  return mb_get_class_tab(p, curbuf->b_chartab);
}

int mb_get_class_tab(const char_u *p, const uint64_t *const chartab)
  FUNC_ATTR_PURE
{
  if (MB_BYTE2LEN(p[0]) == 1) {
    if (p[0] == NUL || ascii_iswhite(p[0])) {
      return 0;
    }
    if (vim_iswordc_tab(p[0], chartab)) {
      return 2;
    }
    return 1;
  }
  return utf_class_tab(utf_ptr2char((char *)p), chartab);
}

/*
 * Return true if "c" is in "table".
 */
static bool intable(const struct interval *table, size_t n_items, int c)
  FUNC_ATTR_PURE
{
  int mid, bot, top;

  // first quick check for Latin1 etc. characters
  if (c < table[0].first) {
    return false;
  }

  // binary search in table
  bot = 0;
  top = (int)(n_items - 1);
  while (top >= bot) {
    mid = (bot + top) / 2;
    if (table[mid].last < c) {
      bot = mid + 1;
    } else if (table[mid].first > c) {
      top = mid - 1;
    } else {
      return true;
    }
  }
  return false;
}

/// For UTF-8 character "c" return 2 for a double-width character, 1 for others.
/// Returns 4 or 6 for an unprintable character.
/// Is only correct for characters >= 0x80.
/// When p_ambw is "double", return 2 for a character with East Asian Width
/// class 'A'(mbiguous).
///
/// @note Tables `doublewidth` and `ambiguous` are generated by
///       gen_unicode_tables.lua, which must be manually invoked as needed.
int utf_char2cells(int c)
{
  if (c >= 0x100) {
    int n = cw_value(c);
    if (n != 0) {
      return n;
    }

    if (!utf_printable(c)) {
      return 6;                 // unprintable, displays <xxxx>
    }
    if (intable(doublewidth, ARRAY_SIZE(doublewidth), c)) {
      return 2;
    }
    if (p_emoji && intable(emoji_wide, ARRAY_SIZE(emoji_wide), c)) {
      return 2;
    }
  } else if (c >= 0x80 && !vim_isprintc(c)) {
    // Characters below 0x100 are influenced by 'isprint' option.
    return 4;                   // unprintable, displays <xx>
  }

  if (c >= 0x80 && *p_ambw == 'd'
      && intable(ambiguous, ARRAY_SIZE(ambiguous), c)) {
    return 2;
  }

  return 1;
}

/// Return the number of display cells character at "*p" occupies.
/// This doesn't take care of unprintable characters, use ptr2cells() for that.
int utf_ptr2cells(const char *p)
{
  int c;

  // Need to convert to a character number.
  if ((uint8_t)(*p) >= 0x80) {
    c = utf_ptr2char(p);
    // An illegal byte is displayed as <xx>.
    if (utf_ptr2len(p) == 1 || c == NUL) {
      return 4;
    }
    // If the char is ASCII it must be an overlong sequence.
    if (c < 0x80) {
      return char2cells(c);
    }
    return utf_char2cells(c);
  }
  return 1;
}

/// Like utf_ptr2cells(), but limit string length to "size".
/// For an empty string or truncated character returns 1.
int utf_ptr2cells_len(const char_u *p, int size)
{
  int c;

  // Need to convert to a wide character.
  if (size > 0 && *p >= 0x80) {
    if (utf_ptr2len_len(p, size) < utf8len_tab[*p]) {
      return 1;        // truncated
    }
    c = utf_ptr2char((char *)p);
    // An illegal byte is displayed as <xx>.
    if (utf_ptr2len((char *)p) == 1 || c == NUL) {
      return 4;
    }
    // If the char is ASCII it must be an overlong sequence.
    if (c < 0x80) {
      return char2cells(c);
    }
    return utf_char2cells(c);
  }
  return 1;
}

/// Calculate the number of cells occupied by string `str`.
///
/// @param str The source string, may not be NULL, must be a NUL-terminated
///            string.
/// @return The number of cells occupied by string `str`
size_t mb_string2cells(const char *str)
{
  size_t clen = 0;

  for (const char_u *p = (char_u *)str; *p != NUL; p += utfc_ptr2len((char *)p)) {
    clen += (size_t)utf_ptr2cells((char *)p);
  }

  return clen;
}

/// Get the number of cells occupied by string `str` with maximum length `size`
///
/// @param str The source string, may not be NULL, must be a NUL-terminated
///            string.
/// @param size maximum length of string. It will terminate on earlier NUL.
/// @return The number of cells occupied by string `str`
size_t mb_string2cells_len(const char *str, size_t size)
  FUNC_ATTR_NONNULL_ARG(1)
{
  size_t clen = 0;

  for (const char_u *p = (char_u *)str; *p != NUL && p < (char_u *)str + size;
       p += utfc_ptr2len_len(p, (int)size + (int)(p - (char_u *)str))) {
    clen += (size_t)utf_ptr2cells((char *)p);
  }

  return clen;
}

/// Convert a UTF-8 byte sequence to a character number.
///
/// If the sequence is illegal or truncated by a NUL then the first byte is
/// returned.
/// For an overlong sequence this may return zero.
/// Does not include composing characters for obvious reasons.
///
/// @param[in]  p  String to convert.
///
/// @return Unicode codepoint or byte value.
int utf_ptr2char(const char *const p_in)
  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
{
  uint8_t *p = (uint8_t *)p_in;
  if (p[0] < 0x80) {  // Be quick for ASCII.
    return p[0];
  }

  const uint8_t len = utf8len_tab_zero[p[0]];
  if (len > 1 && (p[1] & 0xc0) == 0x80) {
    if (len == 2) {
      return ((p[0] & 0x1f) << 6) + (p[1] & 0x3f);
    }
    if ((p[2] & 0xc0) == 0x80) {
      if (len == 3) {
        return (((p[0] & 0x0f) << 12) + ((p[1] & 0x3f) << 6)
                + (p[2] & 0x3f));
      }
      if ((p[3] & 0xc0) == 0x80) {
        if (len == 4) {
          return (((p[0] & 0x07) << 18) + ((p[1] & 0x3f) << 12)
                  + ((p[2] & 0x3f) << 6) + (p[3] & 0x3f));
        }
        if ((p[4] & 0xc0) == 0x80) {
          if (len == 5) {
            return (((p[0] & 0x03) << 24) + ((p[1] & 0x3f) << 18)
                    + ((p[2] & 0x3f) << 12) + ((p[3] & 0x3f) << 6)
                    + (p[4] & 0x3f));
          }
          if ((p[5] & 0xc0) == 0x80 && len == 6) {
            return (((p[0] & 0x01) << 30) + ((p[1] & 0x3f) << 24)
                    + ((p[2] & 0x3f) << 18) + ((p[3] & 0x3f) << 12)
                    + ((p[4] & 0x3f) << 6) + (p[5] & 0x3f));
          }
        }
      }
    }
  }
  // Illegal value: just return the first byte.
  return p[0];
}

/*
 * Convert a UTF-8 byte sequence to a wide character.
 * String is assumed to be terminated by NUL or after "n" bytes, whichever
 * comes first.
 * The function is safe in the sense that it never accesses memory beyond the
 * first "n" bytes of "s".
 *
 * On success, returns decoded codepoint, advances "s" to the beginning of
 * next character and decreases "n" accordingly.
 *
 * If end of string was reached, returns 0 and, if "n" > 0, advances "s" past
 * NUL byte.
 *
 * If byte sequence is illegal or incomplete, returns -1 and does not advance
 * "s".
 */
static int utf_safe_read_char_adv(const char_u **s, size_t *n)
{
  int c;

  if (*n == 0) {  // end of buffer
    return 0;
  }

  uint8_t k = utf8len_tab_zero[**s];

  if (k == 1) {
    // ASCII character or NUL
    (*n)--;
    return *(*s)++;
  }

  if (k <= *n) {
    // We have a multibyte sequence and it isn't truncated by buffer
    // limits so utf_ptr2char() is safe to use. Or the first byte is
    // illegal (k=0), and it's also safe to use utf_ptr2char().
    c = utf_ptr2char((char *)(*s));

    // On failure, utf_ptr2char() returns the first byte, so here we
    // check equality with the first byte. The only non-ASCII character
    // which equals the first byte of its own UTF-8 representation is
    // U+00C3 (UTF-8: 0xC3 0x83), so need to check that special case too.
    // It's safe even if n=1, else we would have k=2 > n.
    if (c != (int)(**s) || (c == 0xC3 && (*s)[1] == 0x83)) {
      // byte sequence was successfully decoded
      *s += k;
      *n -= k;
      return c;
    }
  }

  // byte sequence is incomplete or illegal
  return -1;
}

/*
 * Get character at **pp and advance *pp to the next character.
 * Note: composing characters are skipped!
 */
int mb_ptr2char_adv(const char_u **const pp)
{
  int c;

  c = utf_ptr2char((char *)(*pp));
  *pp += utfc_ptr2len((char *)(*pp));
  return c;
}

/*
 * Get character at **pp and advance *pp to the next character.
 * Note: composing characters are returned as separate characters.
 */
int mb_cptr2char_adv(const char_u **pp)
{
  int c;

  c = utf_ptr2char((char *)(*pp));
  *pp += utf_ptr2len((char *)(*pp));
  return c;
}

/*
 * Check if the character pointed to by "p2" is a composing character when it
 * comes after "p1".  For Arabic sometimes "ab" is replaced with "c", which
 * behaves like a composing character.
 */
bool utf_composinglike(const char_u *p1, const char_u *p2)
{
  int c2;

  c2 = utf_ptr2char((char *)p2);
  if (utf_iscomposing(c2)) {
    return true;
  }
  if (!arabic_maycombine(c2)) {
    return false;
  }
  return arabic_combine(utf_ptr2char((char *)p1), c2);
}

/// Convert a UTF-8 string to a wide character
///
/// Also gets up to #MAX_MCO composing characters.
///
/// @param[out]  pcc  Location where to store composing characters. Must have
///                   space at least for #MAX_MCO + 1 elements.
///
/// @return leading character.
int utfc_ptr2char(const char_u *p, int *pcc)
{
  int len;
  int c;
  int cc;
  int i = 0;

  c = utf_ptr2char((char *)p);
  len = utf_ptr2len((char *)p);

  // Only accept a composing char when the first char isn't illegal.
  if ((len > 1 || *p < 0x80)
      && p[len] >= 0x80
      && utf_composinglike(p, p + len)) {
    cc = utf_ptr2char((char *)p + len);
    for (;;) {
      pcc[i++] = cc;
      if (i == MAX_MCO) {
        break;
      }
      len += utf_ptr2len((char *)p + len);
      if (p[len] < 0x80 || !utf_iscomposing(cc = utf_ptr2char((char *)p + len))) {
        break;
      }
    }
  }

  if (i < MAX_MCO) {    // last composing char must be 0
    pcc[i] = 0;
  }

  return c;
}

/*
 * Convert a UTF-8 byte string to a wide character.  Also get up to MAX_MCO
 * composing characters.  Use no more than p[maxlen].
 *
 * @param [out] pcc: composing chars, last one is 0
 */
int utfc_ptr2char_len(const char_u *p, int *pcc, int maxlen)
{
  assert(maxlen > 0);

  int i = 0;

  int len = utf_ptr2len_len(p, maxlen);
  // Is it safe to use utf_ptr2char()?
  bool safe = len > 1 && len <= maxlen;
  int c = safe ? utf_ptr2char((char *)p) : *p;

  // Only accept a composing char when the first char isn't illegal.
  if ((safe || c < 0x80) && len < maxlen && p[len] >= 0x80) {
    for (; i < MAX_MCO; i++) {
      int len_cc = utf_ptr2len_len(p + len, maxlen - len);
      safe = len_cc > 1 && len_cc <= maxlen - len;
      if (!safe || (pcc[i] = utf_ptr2char((char *)p + len)) < 0x80
          || !(i == 0 ? utf_composinglike(p, p + len) : utf_iscomposing(pcc[i]))) {
        break;
      }
      len += len_cc;
    }
  }

  if (i < MAX_MCO) {
    // last composing char must be 0
    pcc[i] = 0;
  }

  return c;
#undef ISCOMPOSING
}

/// Get the length of a UTF-8 byte sequence representing a single codepoint
///
/// @param[in]  p  UTF-8 string.
///
/// @return Sequence length, 0 for empty string and 1 for non-UTF-8 byte
///         sequence.
int utf_ptr2len(const char *const p_in)
  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
{
  uint8_t *p = (uint8_t *)p_in;
  if (*p == NUL) {
    return 0;
  }
  const int len = utf8len_tab[*p];
  for (int i = 1; i < len; i++) {
    if ((p[i] & 0xc0) != 0x80) {
      return 1;
    }
  }
  return len;
}

/*
 * Return length of UTF-8 character, obtained from the first byte.
 * "b" must be between 0 and 255!
 * Returns 1 for an invalid first byte value.
 */
int utf_byte2len(int b)
{
  return utf8len_tab[b];
}

/*
 * Get the length of UTF-8 byte sequence "p[size]".  Does not include any
 * following composing characters.
 * Returns 1 for "".
 * Returns 1 for an illegal byte sequence (also in incomplete byte seq.).
 * Returns number > "size" for an incomplete byte sequence.
 * Never returns zero.
 */
int utf_ptr2len_len(const char_u *p, int size)
{
  int len;
  int i;
  int m;

  len = utf8len_tab[*p];
  if (len == 1) {
    return 1;           // NUL, ascii or illegal lead byte
  }
  if (len > size) {
    m = size;           // incomplete byte sequence.
  } else {
    m = len;
  }
  for (i = 1; i < m; ++i) {
    if ((p[i] & 0xc0) != 0x80) {
      return 1;
    }
  }
  return len;
}

/// Return the number of bytes occupied by a UTF-8 character in a string.
/// This includes following composing characters.
/// Returns zero for NUL.
int utfc_ptr2len(const char *const p_in)
  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
{
  uint8_t *p = (uint8_t *)p_in;
  uint8_t b0 = *p;

  if (b0 == NUL) {
    return 0;
  }
  if (b0 < 0x80 && p[1] < 0x80) {  // be quick for ASCII
    return 1;
  }

  // Skip over first UTF-8 char, stopping at a NUL byte.
  int len = utf_ptr2len((char *)p);

  // Check for illegal byte.
  if (len == 1 && b0 >= 0x80) {
    return 1;
  }

  // Check for composing characters.  We can handle only the first six, but
  // skip all of them (otherwise the cursor would get stuck).
  int prevlen = 0;
  for (;;) {
    if (p[len] < 0x80 || !utf_composinglike(p + prevlen, p + len)) {
      return len;
    }

    // Skip over composing char.
    prevlen = len;
    len += utf_ptr2len((char *)p + len);
  }
}

/*
 * Return the number of bytes the UTF-8 encoding of the character at "p[size]"
 * takes.  This includes following composing characters.
 * Returns 0 for an empty string.
 * Returns 1 for an illegal char or an incomplete byte sequence.
 */
int utfc_ptr2len_len(const char_u *p, int size)
{
  int len;
  int prevlen;

  if (size < 1 || *p == NUL) {
    return 0;
  }
  if (p[0] < 0x80 && (size == 1 || p[1] < 0x80)) {  // be quick for ASCII
    return 1;
  }

  // Skip over first UTF-8 char, stopping at a NUL byte.
  len = utf_ptr2len_len(p, size);

  // Check for illegal byte and incomplete byte sequence.
  if ((len == 1 && p[0] >= 0x80) || len > size) {
    return 1;
  }

  /*
   * Check for composing characters.  We can handle only the first six, but
   * skip all of them (otherwise the cursor would get stuck).
   */
  prevlen = 0;
  while (len < size) {
    int len_next_char;

    if (p[len] < 0x80) {
      break;
    }

    /*
     * Next character length should not go beyond size to ensure that
     * utf_composinglike(...) does not read beyond size.
     */
    len_next_char = utf_ptr2len_len(p + len, size - len);
    if (len_next_char > size - len) {
      break;
    }

    if (!utf_composinglike(p + prevlen, p + len)) {
      break;
    }

    // Skip over composing char
    prevlen = len;
    len += len_next_char;
  }
  return len;
}

/// Determine how many bytes certain unicode codepoint will occupy
int utf_char2len(const int c)
{
  if (c < 0x80) {
    return 1;
  } else if (c < 0x800) {
    return 2;
  } else if (c < 0x10000) {
    return 3;
  } else if (c < 0x200000) {
    return 4;
  } else if (c < 0x4000000) {
    return 5;
  } else {
    return 6;
  }
}

/// Convert Unicode character to UTF-8 string
///
/// @param c         character to convert to UTF-8 string in \p buf
/// @param[out] buf  UTF-8 string generated from \p c, does not add \0
///                  must have room for at least 6 bytes
/// @return Number of bytes (1-6).
int utf_char2bytes(const int c, char *const buf)
{
  if (c < 0x80) {  // 7 bits
    buf[0] = (char)c;
    return 1;
  } else if (c < 0x800) {  // 11 bits
    buf[0] = (char)(0xc0 + ((unsigned)c >> 6));
    buf[1] = (char)(0x80 + ((unsigned)c & 0x3f));
    return 2;
  } else if (c < 0x10000) {  // 16 bits
    buf[0] = (char)(0xe0 + ((unsigned)c >> 12));
    buf[1] = (char)(0x80 + (((unsigned)c >> 6) & 0x3f));
    buf[2] = (char)(0x80 + ((unsigned)c & 0x3f));
    return 3;
  } else if (c < 0x200000) {  // 21 bits
    buf[0] = (char)(0xf0 + ((unsigned)c >> 18));
    buf[1] = (char)(0x80 + (((unsigned)c >> 12) & 0x3f));
    buf[2] = (char)(0x80 + (((unsigned)c >> 6) & 0x3f));
    buf[3] = (char)(0x80 + ((unsigned)c & 0x3f));
    return 4;
  } else if (c < 0x4000000) {  // 26 bits
    buf[0] = (char)(0xf8 + ((unsigned)c >> 24));
    buf[1] = (char)(0x80 + (((unsigned)c >> 18) & 0x3f));
    buf[2] = (char)(0x80 + (((unsigned)c >> 12) & 0x3f));
    buf[3] = (char)(0x80 + (((unsigned)c >> 6) & 0x3f));
    buf[4] = (char)(0x80 + ((unsigned)c & 0x3f));
    return 5;
  } else {  // 31 bits
    buf[0] = (char)(0xfc + ((unsigned)c >> 30));
    buf[1] = (char)(0x80 + (((unsigned)c >> 24) & 0x3f));
    buf[2] = (char)(0x80 + (((unsigned)c >> 18) & 0x3f));
    buf[3] = (char)(0x80 + (((unsigned)c >> 12) & 0x3f));
    buf[4] = (char)(0x80 + (((unsigned)c >> 6) & 0x3f));
    buf[5] = (char)(0x80 + ((unsigned)c & 0x3f));
    return 6;
  }
}

/*
 * Return true if "c" is a composing UTF-8 character.  This means it will be
 * drawn on top of the preceding character.
 * Based on code from Markus Kuhn.
 */
bool utf_iscomposing(int c)
{
  return intable(combining, ARRAY_SIZE(combining), c);
}

/*
 * Return true for characters that can be displayed in a normal way.
 * Only for characters of 0x100 and above!
 */
bool utf_printable(int c)
{
  // Sorted list of non-overlapping intervals.
  // 0xd800-0xdfff is reserved for UTF-16, actually illegal.
  static struct interval nonprint[] =
  {
    { 0x070f, 0x070f }, { 0x180b, 0x180e }, { 0x200b, 0x200f }, { 0x202a, 0x202e },
    { 0x2060, 0x206f }, { 0xd800, 0xdfff }, { 0xfeff, 0xfeff }, { 0xfff9, 0xfffb },
    { 0xfffe, 0xffff }
  };

  return !intable(nonprint, ARRAY_SIZE(nonprint), c);
}

/*
 * Get class of a Unicode character.
 * 0: white space
 * 1: punctuation
 * 2 or bigger: some class of word character.
 */
int utf_class(const int c)
{
  return utf_class_tab(c, curbuf->b_chartab);
}

int utf_class_tab(const int c, const uint64_t *const chartab)
  FUNC_ATTR_PURE
{
  // sorted list of non-overlapping intervals
  static struct clinterval {
    unsigned int first;
    unsigned int last;
    unsigned int class;
  } classes[] = {
    { 0x037e, 0x037e, 1 },              // Greek question mark
    { 0x0387, 0x0387, 1 },              // Greek ano teleia
    { 0x055a, 0x055f, 1 },              // Armenian punctuation
    { 0x0589, 0x0589, 1 },              // Armenian full stop
    { 0x05be, 0x05be, 1 },
    { 0x05c0, 0x05c0, 1 },
    { 0x05c3, 0x05c3, 1 },
    { 0x05f3, 0x05f4, 1 },
    { 0x060c, 0x060c, 1 },
    { 0x061b, 0x061b, 1 },
    { 0x061f, 0x061f, 1 },
    { 0x066a, 0x066d, 1 },
    { 0x06d4, 0x06d4, 1 },
    { 0x0700, 0x070d, 1 },              // Syriac punctuation
    { 0x0964, 0x0965, 1 },
    { 0x0970, 0x0970, 1 },
    { 0x0df4, 0x0df4, 1 },
    { 0x0e4f, 0x0e4f, 1 },
    { 0x0e5a, 0x0e5b, 1 },
    { 0x0f04, 0x0f12, 1 },
    { 0x0f3a, 0x0f3d, 1 },
    { 0x0f85, 0x0f85, 1 },
    { 0x104a, 0x104f, 1 },              // Myanmar punctuation
    { 0x10fb, 0x10fb, 1 },              // Georgian punctuation
    { 0x1361, 0x1368, 1 },              // Ethiopic punctuation
    { 0x166d, 0x166e, 1 },              // Canadian Syl. punctuation
    { 0x1680, 0x1680, 0 },
    { 0x169b, 0x169c, 1 },
    { 0x16eb, 0x16ed, 1 },
    { 0x1735, 0x1736, 1 },
    { 0x17d4, 0x17dc, 1 },              // Khmer punctuation
    { 0x1800, 0x180a, 1 },              // Mongolian punctuation
    { 0x2000, 0x200b, 0 },              // spaces
    { 0x200c, 0x2027, 1 },              // punctuation and symbols
    { 0x2028, 0x2029, 0 },
    { 0x202a, 0x202e, 1 },              // punctuation and symbols
    { 0x202f, 0x202f, 0 },
    { 0x2030, 0x205e, 1 },              // punctuation and symbols
    { 0x205f, 0x205f, 0 },
    { 0x2060, 0x27ff, 1 },              // punctuation and symbols
    { 0x2070, 0x207f, 0x2070 },         // superscript
    { 0x2080, 0x2094, 0x2080 },         // subscript
    { 0x20a0, 0x27ff, 1 },              // all kinds of symbols
    { 0x2800, 0x28ff, 0x2800 },         // braille
    { 0x2900, 0x2998, 1 },              // arrows, brackets, etc.
    { 0x29d8, 0x29db, 1 },
    { 0x29fc, 0x29fd, 1 },
    { 0x2e00, 0x2e7f, 1 },              // supplemental punctuation
    { 0x3000, 0x3000, 0 },              // ideographic space
    { 0x3001, 0x3020, 1 },              // ideographic punctuation
    { 0x3030, 0x3030, 1 },
    { 0x303d, 0x303d, 1 },
    { 0x3040, 0x309f, 0x3040 },         // Hiragana
    { 0x30a0, 0x30ff, 0x30a0 },         // Katakana
    { 0x3300, 0x9fff, 0x4e00 },         // CJK Ideographs
    { 0xac00, 0xd7a3, 0xac00 },         // Hangul Syllables
    { 0xf900, 0xfaff, 0x4e00 },         // CJK Ideographs
    { 0xfd3e, 0xfd3f, 1 },
    { 0xfe30, 0xfe6b, 1 },              // punctuation forms
    { 0xff00, 0xff0f, 1 },              // half/fullwidth ASCII
    { 0xff1a, 0xff20, 1 },              // half/fullwidth ASCII
    { 0xff3b, 0xff40, 1 },              // half/fullwidth ASCII
    { 0xff5b, 0xff65, 1 },              // half/fullwidth ASCII
    { 0x1d000, 0x1d24f, 1 },            // Musical notation
    { 0x1d400, 0x1d7ff, 1 },            // Mathematical Alphanumeric Symbols
    { 0x1f000, 0x1f2ff, 1 },            // Game pieces; enclosed characters
    { 0x1f300, 0x1f9ff, 1 },            // Many symbol blocks
    { 0x20000, 0x2a6df, 0x4e00 },       // CJK Ideographs
    { 0x2a700, 0x2b73f, 0x4e00 },       // CJK Ideographs
    { 0x2b740, 0x2b81f, 0x4e00 },       // CJK Ideographs
    { 0x2f800, 0x2fa1f, 0x4e00 },       // CJK Ideographs
  };
  int bot = 0;
  int top = ARRAY_SIZE(classes) - 1;
  int mid;

  // First quick check for Latin1 characters, use 'iskeyword'.
  if (c < 0x100) {
    if (c == ' ' || c == '\t' || c == NUL || c == 0xa0) {
      return 0;             // blank
    }
    if (vim_iswordc_tab(c, chartab)) {
      return 2;             // word character
    }
    return 1;               // punctuation
  }

  // emoji
  if (intable(emoji_all, ARRAY_SIZE(emoji_all), c)) {
    return 3;
  }

  // binary search in table
  while (top >= bot) {
    mid = (bot + top) / 2;
    if (classes[mid].last < (unsigned int)c) {
      bot = mid + 1;
    } else if (classes[mid].first > (unsigned int)c) {
      top = mid - 1;
    } else {
      return (int)classes[mid].class;
    }
  }

  // most other characters are "word" characters
  return 2;
}

bool utf_ambiguous_width(int c)
{
  return c >= 0x80 && (intable(ambiguous, ARRAY_SIZE(ambiguous), c)
                       || intable(emoji_all, ARRAY_SIZE(emoji_all), c));
}

/*
 * Generic conversion function for case operations.
 * Return the converted equivalent of "a", which is a UCS-4 character.  Use
 * the given conversion "table".  Uses binary search on "table".
 */
static int utf_convert(int a, const convertStruct *const table, size_t n_items)
{
  size_t start, mid, end;   // indices into table

  start = 0;
  end = n_items;
  while (start < end) {
    // need to search further
    mid = (end + start) / 2;
    if (table[mid].rangeEnd < a) {
      start = mid + 1;
    } else {
      end = mid;
    }
  }
  if (start < n_items
      && table[start].rangeStart <= a
      && a <= table[start].rangeEnd
      && (a - table[start].rangeStart) % table[start].step == 0) {
    return a + table[start].offset;
  } else {
    return a;
  }
}

/*
 * Return the folded-case equivalent of "a", which is a UCS-4 character.  Uses
 * simple case folding.
 */
int utf_fold(int a)
{
  if (a < 0x80) {
    // be fast for ASCII
    return a >= 0x41 && a <= 0x5a ? a + 32 : a;
  }
  return utf_convert(a, foldCase, ARRAY_SIZE(foldCase));
}

// Vim's own character class functions.  These exist because many library
// islower()/toupper() etc. do not work properly: they crash when used with
// invalid values or can't handle latin1 when the locale is C.
// Speed is most important here.

/// Return the upper-case equivalent of "a", which is a UCS-4 character.  Use
/// simple case folding.
int mb_toupper(int a)
{
  // If 'casemap' contains "keepascii" use ASCII style toupper().
  if (a < 128 && (cmp_flags & CMP_KEEPASCII)) {
    return TOUPPER_ASC(a);
  }

#if defined(__STDC_ISO_10646__)
  // If towupper() is available and handles Unicode, use it.
  if (!(cmp_flags & CMP_INTERNAL)) {
    return (int)towupper((wint_t)a);
  }
#endif

  // For characters below 128 use locale sensitive toupper().
  if (a < 128) {
    return TOUPPER_LOC(a);
  }

  // For any other characters use the above mapping table.
  return utf_convert(a, toUpper, ARRAY_SIZE(toUpper));
}

bool mb_islower(int a)
{
  // German sharp s is lower case but has no upper case equivalent.
  return (mb_toupper(a) != a) || a == 0xdf;
}

/// Return the lower-case equivalent of "a", which is a UCS-4 character.  Use
/// simple case folding.
int mb_tolower(int a)
{
  // If 'casemap' contains "keepascii" use ASCII style tolower().
  if (a < 128 && (cmp_flags & CMP_KEEPASCII)) {
    return TOLOWER_ASC(a);
  }

#if defined(__STDC_ISO_10646__)
  // If towlower() is available and handles Unicode, use it.
  if (!(cmp_flags & CMP_INTERNAL)) {
    return (int)towlower((wint_t)a);
  }
#endif

  // For characters below 128 use locale sensitive tolower().
  if (a < 128) {
    return TOLOWER_LOC(a);
  }

  // For any other characters use the above mapping table.
  return utf_convert(a, toLower, ARRAY_SIZE(toLower));
}

bool mb_isupper(int a)
{
  return mb_tolower(a) != a;
}

bool mb_isalpha(int a)
  FUNC_ATTR_WARN_UNUSED_RESULT
{
  return mb_islower(a) || mb_isupper(a);
}

static int utf_strnicmp(const char_u *s1, const char_u *s2, size_t n1, size_t n2)
{
  int c1, c2, cdiff;
  char buffer[6];

  for (;;) {
    c1 = utf_safe_read_char_adv(&s1, &n1);
    c2 = utf_safe_read_char_adv(&s2, &n2);

    if (c1 <= 0 || c2 <= 0) {
      break;
    }

    if (c1 == c2) {
      continue;
    }

    cdiff = utf_fold(c1) - utf_fold(c2);
    if (cdiff != 0) {
      return cdiff;
    }
  }

  // some string ended or has an incomplete/illegal character sequence

  if (c1 == 0 || c2 == 0) {
    // some string ended. shorter string is smaller
    if (c1 == 0 && c2 == 0) {
      return 0;
    }
    return c1 == 0 ? -1 : 1;
  }

  // Continue with bytewise comparison to produce some result that
  // would make comparison operations involving this function transitive.
  //
  // If only one string had an error, comparison should be made with
  // folded version of the other string. In this case it is enough
  // to fold just one character to determine the result of comparison.

  if (c1 != -1 && c2 == -1) {
    n1 = (size_t)utf_char2bytes(utf_fold(c1), (char *)buffer);
    s1 = (char_u *)buffer;
  } else if (c2 != -1 && c1 == -1) {
    n2 = (size_t)utf_char2bytes(utf_fold(c2), (char *)buffer);
    s2 = (char_u *)buffer;
  }

  while (n1 > 0 && n2 > 0 && *s1 != NUL && *s2 != NUL) {
    cdiff = (int)(*s1) - (int)(*s2);
    if (cdiff != 0) {
      return cdiff;
    }

    s1++;
    s2++;
    n1--;
    n2--;
  }

  if (n1 > 0 && *s1 == NUL) {
    n1 = 0;
  }
  if (n2 > 0 && *s2 == NUL) {
    n2 = 0;
  }

  if (n1 == 0 && n2 == 0) {
    return 0;
  }
  return n1 == 0 ? -1 : 1;
}

#ifdef WIN32
# ifndef CP_UTF8
#  define CP_UTF8 65001  // magic number from winnls.h
# endif

/// Converts string from UTF-8 to UTF-16.
///
/// @param utf8  UTF-8 string.
/// @param utf8len  Length of `utf8`. May be -1 if `utf8` is NUL-terminated.
/// @param utf16[out,allocated]  NUL-terminated UTF-16 string, or NULL on error
/// @return 0 on success, or libuv error code
int utf8_to_utf16(const char *utf8, int utf8len, wchar_t **utf16)
  FUNC_ATTR_NONNULL_ALL
{
  // Compute the length needed for the converted UTF-16 string.
  int bufsize = MultiByteToWideChar(CP_UTF8,
                                    0,     // dwFlags: must be 0 for UTF-8
                                    utf8,  // -1: process up to NUL
                                    utf8len,
                                    NULL,
                                    0);    // 0: get length, don't convert
  if (bufsize == 0) {
    *utf16 = NULL;
    return uv_translate_sys_error(GetLastError());
  }

  // Allocate the destination buffer adding an extra byte for the terminating
  // NULL. If `utf8len` is not -1 MultiByteToWideChar will not add it, so
  // we do it ourselves always, just in case.
  *utf16 = xmalloc(sizeof(wchar_t) * (bufsize + 1));

  // Convert to UTF-16.
  bufsize = MultiByteToWideChar(CP_UTF8, 0, utf8, utf8len, *utf16, bufsize);
  if (bufsize == 0) {
    XFREE_CLEAR(*utf16);
    return uv_translate_sys_error(GetLastError());
  }

  (*utf16)[bufsize] = L'\0';
  return 0;
}

/// Converts string from UTF-16 to UTF-8.
///
/// @param utf16  UTF-16 string.
/// @param utf16len  Length of `utf16`. May be -1 if `utf16` is NUL-terminated.
/// @param utf8[out,allocated]  NUL-terminated UTF-8 string, or NULL on error
/// @return 0 on success, or libuv error code
int utf16_to_utf8(const wchar_t *utf16, int utf16len, char **utf8)
  FUNC_ATTR_NONNULL_ALL
{
  // Compute the space needed for the converted UTF-8 string.
  DWORD bufsize = WideCharToMultiByte(CP_UTF8,
                                      0,
                                      utf16,
                                      utf16len,
                                      NULL,
                                      0,
                                      NULL,
                                      NULL);
  if (bufsize == 0) {
    *utf8 = NULL;
    return uv_translate_sys_error(GetLastError());
  }

  // Allocate the destination buffer adding an extra byte for the terminating
  // NULL. If `utf16len` is not -1 WideCharToMultiByte will not add it, so
  // we do it ourselves always, just in case.
  *utf8 = xmalloc(bufsize + 1);

  // Convert to UTF-8.
  bufsize = WideCharToMultiByte(CP_UTF8,
                                0,
                                utf16,
                                utf16len,
                                *utf8,
                                bufsize,
                                NULL,
                                NULL);
  if (bufsize == 0) {
    XFREE_CLEAR(*utf8);
    return uv_translate_sys_error(GetLastError());
  }

  (*utf8)[bufsize] = '\0';
  return 0;
}

#endif

/// Measure the length of a string in corresponding UTF-32 and UTF-16 units.
///
/// Invalid UTF-8 bytes, or embedded surrogates, count as one code point/unit
/// each.
///
/// The out parameters are incremented. This is used to measure the size of
/// a buffer region consisting of multiple line segments.
///
/// @param s the string
/// @param len maximum length (an earlier NUL terminates)
/// @param[out] codepoints incremented with UTF-32 code point size
/// @param[out] codeunits incremented with UTF-16 code unit size
void mb_utflen(const char_u *s, size_t len, size_t *codepoints, size_t *codeunits)
  FUNC_ATTR_NONNULL_ALL
{
  size_t count = 0, extra = 0;
  size_t clen;
  for (size_t i = 0; i < len && s[i] != NUL; i += clen) {
    clen = (size_t)utf_ptr2len_len(s + i, (int)(len - i));
    // NB: gets the byte value of invalid sequence bytes.
    // we only care whether the char fits in the BMP or not
    int c = (clen > 1) ? utf_ptr2char((char *)s + i) : s[i];
    count++;
    if (c > 0xFFFF) {
      extra++;
    }
  }
  *codepoints += count;
  *codeunits += count + extra;
}

ssize_t mb_utf_index_to_bytes(const char_u *s, size_t len, size_t index, bool use_utf16_units)
  FUNC_ATTR_NONNULL_ALL
{
  size_t count = 0;
  size_t clen, i;
  if (index == 0) {
    return 0;
  }
  for (i = 0; i < len && s[i] != NUL; i += clen) {
    clen = (size_t)utf_ptr2len_len(s + i, (int)(len - i));
    // NB: gets the byte value of invalid sequence bytes.
    // we only care whether the char fits in the BMP or not
    int c = (clen > 1) ? utf_ptr2char((char *)s + i) : s[i];
    count++;
    if (use_utf16_units && c > 0xFFFF) {
      count++;
    }
    if (count >= index) {
      return (ssize_t)(i + clen);
    }
  }
  return -1;
}

/*
 * Version of strnicmp() that handles multi-byte characters.
 * Needed for Big5, Shift-JIS and UTF-8 encoding.  Other DBCS encodings can
 * probably use strnicmp(), because there are no ASCII characters in the
 * second byte.
 * Returns zero if s1 and s2 are equal (ignoring case), the difference between
 * two characters otherwise.
 */
int mb_strnicmp(const char_u *s1, const char_u *s2, const size_t nn)
{
  return utf_strnicmp(s1, s2, nn, nn);
}

/// Compare strings case-insensitively
///
/// @note We need to call mb_stricmp() even when we aren't dealing with
///       a multi-byte encoding because mb_stricmp() takes care of all ASCII and
///       non-ascii encodings, including characters with umlauts in latin1,
///       etc., while STRICMP() only handles the system locale version, which
///       often does not handle non-ascii properly.
///
/// @param[in]  s1  First string to compare, not more then #MAXCOL characters.
/// @param[in]  s2  Second string to compare, not more then #MAXCOL characters.
///
/// @return 0 if strings are equal, <0 if s1 < s2, >0 if s1 > s2.
int mb_stricmp(const char *s1, const char *s2)
{
  return mb_strnicmp((const char_u *)s1, (const char_u *)s2, MAXCOL);
}

/*
 * "g8": show bytes of the UTF-8 char under the cursor.  Doesn't matter what
 * 'encoding' has been set to.
 */
void show_utf8(void)
{
  int len;
  int rlen = 0;
  char_u *line;
  int clen;
  int i;

  // Get the byte length of the char under the cursor, including composing
  // characters.
  line = get_cursor_pos_ptr();
  len = utfc_ptr2len((char *)line);
  if (len == 0) {
    msg("NUL");
    return;
  }

  clen = 0;
  for (i = 0; i < len; ++i) {
    if (clen == 0) {
      // start of (composing) character, get its length
      if (i > 0) {
        STRCPY(IObuff + rlen, "+ ");
        rlen += 2;
      }
      clen = utf_ptr2len((char *)line + i);
    }
    sprintf((char *)IObuff + rlen, "%02x ",
            (line[i] == NL) ? NUL : line[i]);          // NUL is stored as NL
    clen--;
    rlen += (int)STRLEN(IObuff + rlen);
    if (rlen > IOSIZE - 20) {
      break;
    }
  }

  msg((char *)IObuff);
}

/// Return offset from "p" to the start of a character, including composing characters.
/// "base" must be the start of the string, which must be NUL terminated.
/// If "p" points to the NUL at the end of the string return 0.
/// Returns 0 when already at the first byte of a character.
int utf_head_off(const char_u *base, const char_u *p)
{
  int c;
  int len;

  if (*p < 0x80) {              // be quick for ASCII
    return 0;
  }

  // Skip backwards over trailing bytes: 10xx.xxxx
  // Skip backwards again if on a composing char.
  const char_u *q;
  for (q = p;; --q) {
    // Move s to the last byte of this char.
    const char_u *s;
    for (s = q; (s[1] & 0xc0) == 0x80; ++s) {}

    // Move q to the first byte of this char.
    while (q > base && (*q & 0xc0) == 0x80) {
      q--;
    }
    // Check for illegal sequence. Do allow an illegal byte after where we
    // started.
    len = utf8len_tab[*q];
    if (len != (int)(s - q + 1) && len != (int)(p - q + 1)) {
      return 0;
    }

    if (q <= base) {
      break;
    }

    c = utf_ptr2char((char *)q);
    if (utf_iscomposing(c)) {
      continue;
    }

    if (arabic_maycombine(c)) {
      // Advance to get a sneak-peak at the next char
      const char_u *j = q;
      j--;
      // Move j to the first byte of this char.
      while (j > base && (*j & 0xc0) == 0x80) {
        j--;
      }
      if (arabic_combine(utf_ptr2char((char *)j), c)) {
        continue;
      }
    }
    break;
  }

  return (int)(p - q);
}

// Whether space is NOT allowed before/after 'c'.
bool utf_eat_space(int cc)
  FUNC_ATTR_CONST FUNC_ATTR_WARN_UNUSED_RESULT
{
  return (cc >= 0x2000 && cc <= 0x206F)   // General punctuations
         || (cc >= 0x2e00 && cc <= 0x2e7f)   // Supplemental punctuations
         || (cc >= 0x3000 && cc <= 0x303f)   // CJK symbols and punctuations
         || (cc >= 0xff01 && cc <= 0xff0f)   // Full width ASCII punctuations
         || (cc >= 0xff1a && cc <= 0xff20)   // ..
         || (cc >= 0xff3b && cc <= 0xff40)   // ..
         || (cc >= 0xff5b && cc <= 0xff65);  // ..
}

// Whether line break is allowed before "cc".
bool utf_allow_break_before(int cc)
  FUNC_ATTR_CONST FUNC_ATTR_WARN_UNUSED_RESULT
{
  static const int BOL_prohibition_punct[] = {
    '!',
    '%',
    ')',
    ',',
    ':',
    ';',
    '>',
    '?',
    ']',
    '}',
    0x2019,  // ’ right single quotation mark
    0x201d,  // ” right double quotation mark
    0x2020,  // † dagger
    0x2021,  // ‡ double dagger
    0x2026,  // … horizontal ellipsis
    0x2030,  // ‰ per mille sign
    0x2031,  // ‱ per then thousand sign
    0x203c,  // ‼ double exclamation mark
    0x2047,  // ⁇ double question mark
    0x2048,  // ⁈ question exclamation mark
    0x2049,  // ⁉ exclamation question mark
    0x2103,  // ℃ degree celsius
    0x2109,  // ℉ degree fahrenheit
    0x3001,  // 、 ideographic comma
    0x3002,  // 。 ideographic full stop
    0x3009,  // 〉 right angle bracket
    0x300b,  // 》 right double angle bracket
    0x300d,  // 」 right corner bracket
    0x300f,  // 』 right white corner bracket
    0x3011,  // 】 right black lenticular bracket
    0x3015,  // 〕 right tortoise shell bracket
    0x3017,  // 〗 right white lenticular bracket
    0x3019,  // 〙 right white tortoise shell bracket
    0x301b,  // 〛 right white square bracket
    0xff01,  // ! fullwidth exclamation mark
    0xff09,  // ) fullwidth right parenthesis
    0xff0c,  // , fullwidth comma
    0xff0e,  // . fullwidth full stop
    0xff1a,  // : fullwidth colon
    0xff1b,  // ; fullwidth semicolon
    0xff1f,  // ? fullwidth question mark
    0xff3d,  // ] fullwidth right square bracket
    0xff5d,  // } fullwidth right curly bracket
  };

  int first = 0;
  int last = ARRAY_SIZE(BOL_prohibition_punct) - 1;

  while (first < last) {
    const int mid = (first + last) / 2;

    if (cc == BOL_prohibition_punct[mid]) {
      return false;
    } else if (cc > BOL_prohibition_punct[mid]) {
      first = mid + 1;
    } else {
      last = mid - 1;
    }
  }

  return cc != BOL_prohibition_punct[first];
}

// Whether line break is allowed after "cc".
bool utf_allow_break_after(int cc)
  FUNC_ATTR_CONST FUNC_ATTR_WARN_UNUSED_RESULT
{
  static const int EOL_prohibition_punct[] = {
    '(',
    '<',
    '[',
    '`',
    '{',
    // 0x2014,  // — em dash
    0x2018,     // ‘ left single quotation mark
    0x201c,     // “ left double quotation mark
    // 0x2053,  // ~ swung dash
    0x3008,     // 〈 left angle bracket
    0x300a,     // 《 left double angle bracket
    0x300c,     // 「 left corner bracket
    0x300e,     // 『 left white corner bracket
    0x3010,     // 【 left black lenticular bracket
    0x3014,     // 〔 left tortoise shell bracket
    0x3016,     // 〖 left white lenticular bracket
    0x3018,     // 〘 left white tortoise shell bracket
    0x301a,     // 〚 left white square bracket
    0xff08,     // ( fullwidth left parenthesis
    0xff3b,     // [ fullwidth left square bracket
    0xff5b,     // { fullwidth left curly bracket
  };

  int first = 0;
  int last = ARRAY_SIZE(EOL_prohibition_punct) - 1;

  while (first < last) {
    const int mid = (first + last)/2;

    if (cc == EOL_prohibition_punct[mid]) {
      return false;
    } else if (cc > EOL_prohibition_punct[mid]) {
      first = mid + 1;
    } else {
      last = mid - 1;
    }
  }

  return cc != EOL_prohibition_punct[first];
}

// Whether line break is allowed between "cc" and "ncc".
bool utf_allow_break(int cc, int ncc)
  FUNC_ATTR_CONST FUNC_ATTR_WARN_UNUSED_RESULT
{
  // don't break between two-letter punctuations
  if (cc == ncc
      && (cc == 0x2014         // em dash
          || cc == 0x2026)) {  // horizontal ellipsis
    return false;
  }
  return utf_allow_break_after(cc) && utf_allow_break_before(ncc);
}

/// Copy a character, advancing the pointers
///
/// @param[in,out]  fp  Source of the character to copy.
/// @param[in,out]  tp  Destination to copy to.
void mb_copy_char(const char **const fp, char **const tp)
{
  const size_t l = (size_t)utfc_ptr2len(*fp);

  memmove(*tp, *fp, l);
  *tp += l;
  *fp += l;
}

/// Return the offset from "p" to the first byte of a character.  When "p" is
/// at the start of a character 0 is returned, otherwise the offset to the next
/// character.  Can start anywhere in a stream of bytes.
int mb_off_next(const char_u *base, const char_u *p)
{
  int i;
  int j;

  if (*p < 0x80) {              // be quick for ASCII
    return 0;
  }

  // Find the next character that isn't 10xx.xxxx
  for (i = 0; (p[i] & 0xc0) == 0x80; i++) {}
  if (i > 0) {
    // Check for illegal sequence.
    for (j = 0; p - j > base; j++) {
      if ((p[-j] & 0xc0) != 0x80) {
        break;
      }
    }
    if (utf8len_tab[p[-j]] != i + j) {
      return 0;
    }
  }
  return i;
}

/// Return the offset from `p_in` to the last byte of the codepoint it points
/// to.  Can start anywhere in a stream of bytes.
/// Note: Counts individual codepoints of composed characters separately.
int utf_cp_tail_off(const char *base, const char *p_in)
{
  const uint8_t *p = (uint8_t *)p_in;
  int i;
  int j;

  if (*p == NUL) {
    return 0;
  }

  // Find the last character that is 10xx.xxxx
  for (i = 0; (p[i + 1] & 0xc0) == 0x80; i++) {}

  // Check for illegal sequence.
  for (j = 0; p_in - j > base; j++) {
    if ((p[-j] & 0xc0) != 0x80) {
      break;
    }
  }

  if (utf8len_tab[p[-j]] != i + j + 1) {
    return 0;
  }
  return i;
}

/// Return the offset from "p" to the first byte of the codepoint it points
/// to. Can start anywhere in a stream of bytes.
/// Note: Unlike `utf_head_off`, this counts individual codepoints of composed characters
/// separately and returns a negative offset.
///
/// @param[in] base  Pointer to start of string
/// @param[in] p     Pointer to byte for which to return the offset to the previous codepoint
//
/// @return 0 if invalid sequence, else offset to previous codepoint
int utf_cp_head_off(const char_u *base, const char_u *p)
{
  int i;
  int j;

  if (*p == NUL) {
    return 0;
  }

  // Find the first character that is not 10xx.xxxx
  for (i = 0; p - i > base; i--) {
    if ((p[i] & 0xc0) != 0x80) {
      break;
    }
  }

  // Find the last character that is 10xx.xxxx
  for (j = 0; (p[j + 1] & 0xc0) == 0x80; j++) {}

  // Check for illegal sequence.
  if (utf8len_tab[p[i]] == 1) {
    return 0;
  }
  return i;
}

/*
 * Find the next illegal byte sequence.
 */
void utf_find_illegal(void)
{
  pos_T pos = curwin->w_cursor;
  char_u *p;
  int len;
  vimconv_T vimconv;
  char_u *tofree = NULL;

  vimconv.vc_type = CONV_NONE;
  if (enc_canon_props(curbuf->b_p_fenc) & ENC_8BIT) {
    // 'encoding' is "utf-8" but we are editing a 8-bit encoded file,
    // possibly a utf-8 file with illegal bytes.  Setup for conversion
    // from utf-8 to 'fileencoding'.
    convert_setup(&vimconv, p_enc, curbuf->b_p_fenc);
  }

  curwin->w_cursor.coladd = 0;
  for (;;) {
    p = get_cursor_pos_ptr();
    if (vimconv.vc_type != CONV_NONE) {
      xfree(tofree);
      tofree = string_convert(&vimconv, p, NULL);
      if (tofree == NULL) {
        break;
      }
      p = tofree;
    }

    while (*p != NUL) {
      // Illegal means that there are not enough trail bytes (checked by
      // utf_ptr2len()) or too many of them (overlong sequence).
      len = utf_ptr2len((char *)p);
      if (*p >= 0x80 && (len == 1
                         || utf_char2len(utf_ptr2char((char *)p)) != len)) {
        if (vimconv.vc_type == CONV_NONE) {
          curwin->w_cursor.col += (colnr_T)(p - get_cursor_pos_ptr());
        } else {
          int l;

          len = (int)(p - tofree);
          for (p = get_cursor_pos_ptr(); *p != NUL && len-- > 0; p += l) {
            l = utf_ptr2len((char *)p);
            curwin->w_cursor.col += l;
          }
        }
        goto theend;
      }
      p += len;
    }
    if (curwin->w_cursor.lnum == curbuf->b_ml.ml_line_count) {
      break;
    }
    ++curwin->w_cursor.lnum;
    curwin->w_cursor.col = 0;
  }

  // didn't find it: don't move and beep
  curwin->w_cursor = pos;
  beep_flush();

theend:
  xfree(tofree);
  convert_setup(&vimconv, NULL, NULL);
}

/// @return  true if string "s" is a valid utf-8 string.
/// When "end" is NULL stop at the first NUL.
/// When "end" is positive stop there.
bool utf_valid_string(const char_u *s, const char_u *end)
{
  const char_u *p = s;

  while (end == NULL ? *p != NUL : p < end) {
    int l = utf8len_tab_zero[*p];
    if (l == 0) {
      return false;  // invalid lead byte
    }
    if (end != NULL && p + l > end) {
      return false;  // incomplete byte sequence
    }
    p++;
    while (--l > 0) {
      if ((*p++ & 0xc0) != 0x80) {
        return false;  // invalid trail byte
      }
    }
  }
  return true;
}

/*
 * If the cursor moves on an trail byte, set the cursor on the lead byte.
 * Thus it moves left if necessary.
 */
void mb_adjust_cursor(void)
{
  mark_mb_adjustpos(curbuf, &curwin->w_cursor);
}

/// Checks and adjusts cursor column. Not mode-dependent.
/// @see check_cursor_col_win
///
/// @param  win_  Places cursor on a valid column for this window.
void mb_check_adjust_col(void *win_)
{
  win_T *win = (win_T *)win_;
  colnr_T oldcol = win->w_cursor.col;

  // Column 0 is always valid.
  if (oldcol != 0) {
    char *p = (char *)ml_get_buf(win->w_buffer, win->w_cursor.lnum, false);
    colnr_T len = (colnr_T)STRLEN(p);

    // Empty line or invalid column?
    if (len == 0 || oldcol < 0) {
      win->w_cursor.col = 0;
    } else {
      // Cursor column too big for line?
      if (oldcol > len) {
        win->w_cursor.col = len - 1;
      }
      // Move the cursor to the head byte.
      win->w_cursor.col -= utf_head_off((char_u *)p, (char_u *)p + win->w_cursor.col);
    }

    // Reset `coladd` when the cursor would be on the right half of a
    // double-wide character.
    if (win->w_cursor.coladd == 1 && p[win->w_cursor.col] != TAB
        && vim_isprintc(utf_ptr2char(p + win->w_cursor.col))
        && ptr2cells(p + win->w_cursor.col) > 1) {
      win->w_cursor.coladd = 0;
    }
  }
}

/// @param line  start of the string
///
/// @return      a pointer to the character before "*p", if there is one.
char_u *mb_prevptr(char_u *line, char_u *p)
{
  if (p > line) {
    MB_PTR_BACK(line, p);
  }
  return p;
}

/// Return the character length of "str".  Each multi-byte character (with
/// following composing characters) counts as one.
int mb_charlen(const char_u *str)
{
  const char_u *p = str;
  int count;

  if (p == NULL) {
    return 0;
  }

  for (count = 0; *p != NUL; count++) {
    p += utfc_ptr2len((char *)p);
  }

  return count;
}

/// Like mb_charlen() but for a string with specified length.
int mb_charlen_len(const char_u *str, int len)
{
  const char_u *p = str;
  int count;

  for (count = 0; *p != NUL && p < str + len; count++) {
    p += utfc_ptr2len((char *)p);
  }

  return count;
}

/// Try to unescape a multibyte character
///
/// Used for the rhs and lhs of the mappings.
///
/// @param[in,out]  pp  String to unescape. Is advanced to just after the bytes
///                     that form a multibyte character.
///
/// @return Unescaped string if it is a multibyte character, NULL if no
///         multibyte character was found. Returns a static buffer, always one
///         and the same.
const char *mb_unescape(const char **const pp)
  FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
{
  static char buf[6];
  size_t buf_idx = 0;
  uint8_t *str = (uint8_t *)(*pp);

  // Must translate K_SPECIAL KS_SPECIAL KE_FILLER to K_SPECIAL.
  // Maximum length of a utf-8 character is 4 bytes.
  for (size_t str_idx = 0; str[str_idx] != NUL && buf_idx < 4; str_idx++) {
    if (str[str_idx] == K_SPECIAL
        && str[str_idx + 1] == KS_SPECIAL
        && str[str_idx + 2] == KE_FILLER) {
      buf[buf_idx++] = (char)K_SPECIAL;
      str_idx += 2;
    } else if (str[str_idx] == K_SPECIAL) {
      break;  // A special key can't be a multibyte char.
    } else {
      buf[buf_idx++] = (char)str[str_idx];
    }
    buf[buf_idx] = NUL;

    // Return a multi-byte character if it's found.  An illegal sequence
    // will result in a 1 here.
    if (utf_ptr2len(buf) > 1) {
      *pp = (const char *)str + str_idx + 1;
      return buf;
    }

    // Bail out quickly for ASCII.
    if ((uint8_t)buf[0] < 128) {
      break;
    }
  }
  return NULL;
}

/*
 * Skip the Vim specific head of a 'encoding' name.
 */
char_u *enc_skip(char_u *p)
{
  if (STRNCMP(p, "2byte-", 6) == 0) {
    return p + 6;
  }
  if (STRNCMP(p, "8bit-", 5) == 0) {
    return p + 5;
  }
  return p;
}

/*
 * Find the canonical name for encoding "enc".
 * When the name isn't recognized, returns "enc" itself, but with all lower
 * case characters and '_' replaced with '-'.
 * Returns an allocated string.
 */
char_u *enc_canonize(char_u *enc) FUNC_ATTR_NONNULL_RET
{
  char_u *p, *s;
  int i;

  if (STRCMP(enc, "default") == 0) {
    // Use the default encoding as found by set_init_1().
    return vim_strsave(fenc_default);
  }

  // copy "enc" to allocated memory, with room for two '-'
  char_u *r = xmalloc(STRLEN(enc) + 3);
  // Make it all lower case and replace '_' with '-'.
  p = r;
  for (s = enc; *s != NUL; ++s) {
    if (*s == '_') {
      *p++ = '-';
    } else {
      *p++ = (char_u)TOLOWER_ASC(*s);
    }
  }
  *p = NUL;

  // Skip "2byte-" and "8bit-".
  p = enc_skip(r);

  // Change "microsoft-cp" to "cp".  Used in some spell files.
  if (STRNCMP(p, "microsoft-cp", 12) == 0) {
    STRMOVE(p, p + 10);
  }

  // "iso8859" -> "iso-8859"
  if (STRNCMP(p, "iso8859", 7) == 0) {
    STRMOVE(p + 4, p + 3);
    p[3] = '-';
  }

  // "iso-8859n" -> "iso-8859-n"
  if (STRNCMP(p, "iso-8859", 8) == 0 && p[8] != '-') {
    STRMOVE(p + 9, p + 8);
    p[8] = '-';
  }

  // "latin-N" -> "latinN"
  if (STRNCMP(p, "latin-", 6) == 0) {
    STRMOVE(p + 5, p + 6);
  }

  if (enc_canon_search(p) >= 0) {
    // canonical name can be used unmodified
    if (p != r) {
      STRMOVE(r, p);
    }
  } else if ((i = enc_alias_search(p)) >= 0) {
    // alias recognized, get canonical name
    xfree(r);
    r = vim_strsave((char_u *)enc_canon_table[i].name);
  }
  return r;
}

/// Search for an encoding alias of "name".
/// Returns -1 when not found.
static int enc_alias_search(const char_u *name)
{
  int i;

  for (i = 0; enc_alias_table[i].name != NULL; ++i) {
    if (STRCMP(name, enc_alias_table[i].name) == 0) {
      return enc_alias_table[i].canon;
    }
  }
  return -1;
}

#ifdef HAVE_LANGINFO_H
# include <langinfo.h>
#endif

/*
 * Get the canonicalized encoding of the current locale.
 * Returns an allocated string when successful, NULL when not.
 */
char_u *enc_locale(void)
{
  int i;
  char buf[50];

  const char *s;
#ifdef HAVE_NL_LANGINFO_CODESET
  if (!(s = nl_langinfo(CODESET)) || *s == NUL)
#endif
  {
#if defined(HAVE_LOCALE_H)
    if (!(s = setlocale(LC_CTYPE, NULL)) || *s == NUL)
#endif
    {
      if ((s = os_getenv("LC_ALL"))) {
        if ((s = os_getenv("LC_CTYPE"))) {
          s = os_getenv("LANG");
        }
      }
    }
  }

  if (!s) {
    return NULL;
  }

  // The most generic locale format is:
  // language[_territory][.codeset][@modifier][+special][,[sponsor][_revision]]
  // If there is a '.' remove the part before it.
  // if there is something after the codeset, remove it.
  // Make the name lowercase and replace '_' with '-'.
  // Exception: "ja_JP.EUC" == "euc-jp", "zh_CN.EUC" = "euc-cn",
  // "ko_KR.EUC" == "euc-kr"
  const char *p = vim_strchr(s, '.');
  if (p != NULL) {
    if (p > s + 2 && !STRNICMP(p + 1, "EUC", 3)
        && !isalnum((int)p[4]) && p[4] != '-' && p[-3] == '_') {
      // Copy "XY.EUC" to "euc-XY" to buf[10].
      memmove(buf, "euc-", 4);
      buf[4] = (char)(ASCII_ISALNUM(p[-2]) ? TOLOWER_ASC(p[-2]) : 0);
      buf[5] = (char)(ASCII_ISALNUM(p[-1]) ? TOLOWER_ASC(p[-1]) : 0);
      buf[6] = NUL;
    } else {
      s = p + 1;
      goto enc_locale_copy_enc;
    }
  } else {
enc_locale_copy_enc:
    for (i = 0; i < (int)sizeof(buf) - 1 && s[i] != NUL; i++) {
      if (s[i] == '_' || s[i] == '-') {
        buf[i] = '-';
      } else if (ASCII_ISALNUM((uint8_t)s[i])) {
        buf[i] = (char)TOLOWER_ASC(s[i]);
      } else {
        break;
      }
    }
    buf[i] = NUL;
  }

  return enc_canonize((char_u *)buf);
}

#if defined(HAVE_ICONV)

/*
 * Call iconv_open() with a check if iconv() works properly (there are broken
 * versions).
 * Returns (void *)-1 if failed.
 * (should return iconv_t, but that causes problems with prototypes).
 */
void *my_iconv_open(char_u *to, char_u *from)
{
  iconv_t fd;
# define ICONV_TESTLEN 400
  char_u tobuf[ICONV_TESTLEN];
  char *p;
  size_t tolen;
  static WorkingStatus iconv_working = kUnknown;

  if (iconv_working == kBroken) {
    return (void *)-1;          // detected a broken iconv() previously
  }
  fd = iconv_open((char *)enc_skip(to), (char *)enc_skip(from));

  if (fd != (iconv_t)-1 && iconv_working == kUnknown) {
    /*
     * Do a dummy iconv() call to check if it actually works.  There is a
     * version of iconv() on Linux that is broken.  We can't ignore it,
     * because it's wide-spread.  The symptoms are that after outputting
     * the initial shift state the "to" pointer is NULL and conversion
     * stops for no apparent reason after about 8160 characters.
     */
    p = (char *)tobuf;
    tolen = ICONV_TESTLEN;
    (void)iconv(fd, NULL, NULL, &p, &tolen);
    if (p == NULL) {
      iconv_working = kBroken;
      iconv_close(fd);
      fd = (iconv_t)-1;
    } else {
      iconv_working = kWorking;
    }
  }

  return (void *)fd;
}

/*
 * Convert the string "str[slen]" with iconv().
 * If "unconvlenp" is not NULL handle the string ending in an incomplete
 * sequence and set "*unconvlenp" to the length of it.
 * Returns the converted string in allocated memory.  NULL for an error.
 * If resultlenp is not NULL, sets it to the result length in bytes.
 */
static char_u *iconv_string(const vimconv_T *const vcp, char_u *str, size_t slen,
                            size_t *unconvlenp, size_t *resultlenp)
{
  const char *from;
  size_t fromlen;
  char *to;
  size_t tolen;
  size_t len = 0;
  size_t done = 0;
  char_u *result = NULL;
  char_u *p;
  int l;

  from = (char *)str;
  fromlen = slen;
  for (;;) {
    if (len == 0 || ICONV_ERRNO == ICONV_E2BIG) {
      // Allocate enough room for most conversions.  When re-allocating
      // increase the buffer size.
      len = len + fromlen * 2 + 40;
      p = xmalloc(len);
      if (done > 0) {
        memmove(p, result, done);
      }
      xfree(result);
      result = p;
    }

    to = (char *)result + done;
    tolen = len - done - 2;
    // Avoid a warning for systems with a wrong iconv() prototype by
    // casting the second argument to void *.
    if (iconv(vcp->vc_fd, (void *)&from, &fromlen, &to, &tolen) != SIZE_MAX) {
      // Finished, append a NUL.
      *to = NUL;
      break;
    }

    // Check both ICONV_EINVAL and EINVAL, because the dynamically loaded
    // iconv library may use one of them.
    if (!vcp->vc_fail && unconvlenp != NULL
        && (ICONV_ERRNO == ICONV_EINVAL || ICONV_ERRNO == EINVAL)) {
      // Handle an incomplete sequence at the end.
      *to = NUL;
      *unconvlenp = fromlen;
      break;
    } else if (!vcp->vc_fail
               && (ICONV_ERRNO == ICONV_EILSEQ || ICONV_ERRNO == EILSEQ
                   || ICONV_ERRNO == ICONV_EINVAL || ICONV_ERRNO == EINVAL)) {
      // Check both ICONV_EILSEQ and EILSEQ, because the dynamically loaded
      // iconv library may use one of them.

      // Can't convert: insert a '?' and skip a character.  This assumes
      // conversion from 'encoding' to something else.  In other
      // situations we don't know what to skip anyway.
      *to++ = '?';
      if (utf_ptr2cells(from) > 1) {
        *to++ = '?';
      }
      l = utfc_ptr2len_len((const char_u *)from, (int)fromlen);
      from += l;
      fromlen -= (size_t)l;
    } else if (ICONV_ERRNO != ICONV_E2BIG) {
      // conversion failed
      XFREE_CLEAR(result);
      break;
    }
    // Not enough room or skipping illegal sequence.
    done = (size_t)(to - (char *)result);
  }

  if (resultlenp != NULL && result != NULL) {
    *resultlenp = (size_t)(to - (char *)result);
  }
  return result;
}

#endif  // HAVE_ICONV

/*
 * Setup "vcp" for conversion from "from" to "to".
 * The names must have been made canonical with enc_canonize().
 * vcp->vc_type must have been initialized to CONV_NONE.
 * Note: cannot be used for conversion from/to ucs-2 and ucs-4 (will use utf-8
 * instead).
 * Afterwards invoke with "from" and "to" equal to NULL to cleanup.
 * Return FAIL when conversion is not supported, OK otherwise.
 */
int convert_setup(vimconv_T *vcp, char_u *from, char_u *to)
{
  return convert_setup_ext(vcp, from, true, to, true);
}

/// As convert_setup(), but only when from_unicode_is_utf8 is true will all
/// "from" unicode charsets be considered utf-8.  Same for "to".
int convert_setup_ext(vimconv_T *vcp, char_u *from, bool from_unicode_is_utf8, char_u *to,
                      bool to_unicode_is_utf8)
{
  int from_prop;
  int to_prop;
  int from_is_utf8;
  int to_is_utf8;

  // Reset to no conversion.
#ifdef HAVE_ICONV
  if (vcp->vc_type == CONV_ICONV && vcp->vc_fd != (iconv_t)-1) {
    iconv_close(vcp->vc_fd);
  }
#endif
  *vcp = (vimconv_T)MBYTE_NONE_CONV;

  // No conversion when one of the names is empty or they are equal.
  if (from == NULL || *from == NUL || to == NULL || *to == NUL
      || STRCMP(from, to) == 0) {
    return OK;
  }

  from_prop = enc_canon_props(from);
  to_prop = enc_canon_props(to);
  if (from_unicode_is_utf8) {
    from_is_utf8 = from_prop & ENC_UNICODE;
  } else {
    from_is_utf8 = from_prop == ENC_UNICODE;
  }
  if (to_unicode_is_utf8) {
    to_is_utf8 = to_prop & ENC_UNICODE;
  } else {
    to_is_utf8 = to_prop == ENC_UNICODE;
  }

  if ((from_prop & ENC_LATIN1) && to_is_utf8) {
    // Internal latin1 -> utf-8 conversion.
    vcp->vc_type = CONV_TO_UTF8;
    vcp->vc_factor = 2;         // up to twice as long
  } else if ((from_prop & ENC_LATIN9) && to_is_utf8) {
    // Internal latin9 -> utf-8 conversion.
    vcp->vc_type = CONV_9_TO_UTF8;
    vcp->vc_factor = 3;         // up to three as long (euro sign)
  } else if (from_is_utf8 && (to_prop & ENC_LATIN1)) {
    // Internal utf-8 -> latin1 conversion.
    vcp->vc_type = CONV_TO_LATIN1;
  } else if (from_is_utf8 && (to_prop & ENC_LATIN9)) {
    // Internal utf-8 -> latin9 conversion.
    vcp->vc_type = CONV_TO_LATIN9;
  }
#ifdef HAVE_ICONV
  else {  // NOLINT(readability/braces)
    // Use iconv() for conversion.
    vcp->vc_fd = (iconv_t)my_iconv_open(to_is_utf8 ? (char_u *)"utf-8" : to,
                                        from_is_utf8 ? (char_u *)"utf-8" : from);
    if (vcp->vc_fd != (iconv_t)-1) {
      vcp->vc_type = CONV_ICONV;
      vcp->vc_factor = 4;       // could be longer too...
    }
  }
#endif
  if (vcp->vc_type == CONV_NONE) {
    return FAIL;
  }

  return OK;
}

/*
 * Convert text "ptr[*lenp]" according to "vcp".
 * Returns the result in allocated memory and sets "*lenp".
 * When "lenp" is NULL, use NUL terminated strings.
 * Illegal chars are often changed to "?", unless vcp->vc_fail is set.
 * When something goes wrong, NULL is returned and "*lenp" is unchanged.
 */
char_u *string_convert(const vimconv_T *const vcp, char_u *ptr, size_t *lenp)
{
  return string_convert_ext(vcp, ptr, lenp, NULL);
}

/*
 * Like string_convert(), but when "unconvlenp" is not NULL and there are is
 * an incomplete sequence at the end it is not converted and "*unconvlenp" is
 * set to the number of remaining bytes.
 */
char_u *string_convert_ext(const vimconv_T *const vcp, char_u *ptr, size_t *lenp,
                           size_t *unconvlenp)
{
  char_u *retval = NULL;
  char_u *d;
  int l;
  int c;

  size_t len;
  if (lenp == NULL) {
    len = STRLEN(ptr);
  } else {
    len = *lenp;
  }
  if (len == 0) {
    return vim_strsave((char_u *)"");
  }

  switch (vcp->vc_type) {
  case CONV_TO_UTF8:            // latin1 to utf-8 conversion
    retval = xmalloc(len * 2 + 1);
    d = retval;
    for (size_t i = 0; i < len; ++i) {
      c = ptr[i];
      if (c < 0x80) {
        *d++ = (char_u)c;
      } else {
        *d++ = (char_u)(0xc0 + (char_u)((unsigned)c >> 6));
        *d++ = (char_u)(0x80 + (c & 0x3f));
      }
    }
    *d = NUL;
    if (lenp != NULL) {
      *lenp = (size_t)(d - retval);
    }
    break;

  case CONV_9_TO_UTF8:          // latin9 to utf-8 conversion
    retval = xmalloc(len * 3 + 1);
    d = retval;
    for (size_t i = 0; i < len; ++i) {
      c = ptr[i];
      switch (c) {
      case 0xa4:
        c = 0x20ac; break;                 // euro
      case 0xa6:
        c = 0x0160; break;                 // S hat
      case 0xa8:
        c = 0x0161; break;                 // S -hat
      case 0xb4:
        c = 0x017d; break;                 // Z hat
      case 0xb8:
        c = 0x017e; break;                 // Z -hat
      case 0xbc:
        c = 0x0152; break;                 // OE
      case 0xbd:
        c = 0x0153; break;                 // oe
      case 0xbe:
        c = 0x0178; break;                 // Y
      }
      d += utf_char2bytes(c, (char *)d);
    }
    *d = NUL;
    if (lenp != NULL) {
      *lenp = (size_t)(d - retval);
    }
    break;

  case CONV_TO_LATIN1:          // utf-8 to latin1 conversion
  case CONV_TO_LATIN9:          // utf-8 to latin9 conversion
    retval = xmalloc(len + 1);
    d = retval;
    for (size_t i = 0; i < len; i++) {
      l = utf_ptr2len_len(ptr + i, (int)(len - i));
      if (l == 0) {
        *d++ = NUL;
      } else if (l == 1) {
        uint8_t l_w = utf8len_tab_zero[ptr[i]];

        if (l_w == 0) {
          // Illegal utf-8 byte cannot be converted
          xfree(retval);
          return NULL;
        }
        if (unconvlenp != NULL && l_w > len - i) {
          // Incomplete sequence at the end.
          *unconvlenp = len - i;
          break;
        }
        *d++ = ptr[i];
      } else {
        c = utf_ptr2char((char *)ptr + i);
        if (vcp->vc_type == CONV_TO_LATIN9) {
          switch (c) {
          case 0x20ac:
            c = 0xa4; break;                     // euro
          case 0x0160:
            c = 0xa6; break;                     // S hat
          case 0x0161:
            c = 0xa8; break;                     // S -hat
          case 0x017d:
            c = 0xb4; break;                     // Z hat
          case 0x017e:
            c = 0xb8; break;                     // Z -hat
          case 0x0152:
            c = 0xbc; break;                     // OE
          case 0x0153:
            c = 0xbd; break;                     // oe
          case 0x0178:
            c = 0xbe; break;                     // Y
          case 0xa4:
          case 0xa6:
          case 0xa8:
          case 0xb4:
          case 0xb8:
          case 0xbc:
          case 0xbd:
          case 0xbe:
            c = 0x100; break;                   // not in latin9
          }
        }
        if (!utf_iscomposing(c)) {              // skip composing chars
          if (c < 0x100) {
            *d++ = (char_u)c;
          } else if (vcp->vc_fail) {
            xfree(retval);
            return NULL;
          } else {
            *d++ = 0xbf;
            if (utf_char2cells(c) > 1) {
              *d++ = '?';
            }
          }
        }
        i += (size_t)l - 1;
      }
    }
    *d = NUL;
    if (lenp != NULL) {
      *lenp = (size_t)(d - retval);
    }
    break;

#ifdef HAVE_ICONV
  case CONV_ICONV:  // conversion with vcp->vc_fd
    retval = iconv_string(vcp, ptr, len, unconvlenp, lenp);
    break;
#endif
  }

  return retval;
}

/// Table set by setcellwidths().
typedef struct {
  long first;
  long last;
  char width;
} cw_interval_T;

static cw_interval_T *cw_table = NULL;
static size_t cw_table_size = 0;

/// Return the value of the cellwidth table for the character `c`.
///
/// @param c The source character.
/// @return 1 or 2 when `c` is in the cellwidth table, 0 if not.
static int cw_value(int c)
{
  if (cw_table == NULL) {
    return 0;
  }

  // first quick check for Latin1 etc. characters
  if (c < cw_table[0].first) {
    return 0;
  }

  // binary search in table
  int bot = 0;
  int top = (int)cw_table_size - 1;
  while (top >= bot) {
    int mid = (bot + top) / 2;
    if (cw_table[mid].last < c) {
      bot = mid + 1;
    } else if (cw_table[mid].first > c) {
      top = mid - 1;
    } else {
      return cw_table[mid].width;
    }
  }
  return 0;
}

static int tv_nr_compare(const void *a1, const void *a2)
{
  const listitem_T *const li1 = tv_list_first(*(const list_T **)a1);
  const listitem_T *const li2 = tv_list_first(*(const list_T **)a2);

  return (int)(TV_LIST_ITEM_TV(li1)->vval.v_number - TV_LIST_ITEM_TV(li2)->vval.v_number);
}

/// "setcellwidths()" function
void f_setcellwidths(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
  if (argvars[0].v_type != VAR_LIST || argvars[0].vval.v_list == NULL) {
    emsg(_(e_listreq));
    return;
  }
  const list_T *const l = argvars[0].vval.v_list;
  if (tv_list_len(l) == 0) {
    // Clearing the table.
    xfree(cw_table);
    cw_table = NULL;
    cw_table_size = 0;
    return;
  }

  // Note: use list_T instead of listitem_T so that TV_LIST_ITEM_NEXT can be used properly below.
  const list_T **ptrs = xmalloc(sizeof(const list_T *) * (size_t)tv_list_len(l));

  // Check that all entries are a list with three numbers, the range is
  // valid and the cell width is valid.
  int item = 0;
  TV_LIST_ITER_CONST(l, li, {
    const typval_T *const li_tv = TV_LIST_ITEM_TV(li);

    if (li_tv->v_type != VAR_LIST || li_tv->vval.v_list == NULL) {
      semsg(_(e_list_item_nr_is_not_list), item);
      xfree(ptrs);
      return;
    }

    const list_T *const li_l = li_tv->vval.v_list;
    ptrs[item] = li_l;
    const listitem_T *lili = tv_list_first(li_l);
    int i;
    varnumber_T n1;
    for (i = 0; lili != NULL; lili = TV_LIST_ITEM_NEXT(li_l, lili), i++) {
      const typval_T *const lili_tv = TV_LIST_ITEM_TV(lili);
      if (lili_tv->v_type != VAR_NUMBER) {
        break;
      }
      if (i == 0) {
        n1 = lili_tv->vval.v_number;
        if (n1 < 0x100) {
          emsg(_(e_only_values_of_0x100_and_higher_supported));
          xfree(ptrs);
          return;
        }
      } else if (i == 1 && lili_tv->vval.v_number < n1) {
        semsg(_(e_list_item_nr_range_invalid), item);
        xfree(ptrs);
        return;
      } else if (i == 2 && (lili_tv->vval.v_number < 1 || lili_tv->vval.v_number > 2)) {
        semsg(_(e_list_item_nr_cell_width_invalid), item);
        xfree(ptrs);
        return;
      }
    }

    if (i != 3) {
      semsg(_(e_list_item_nr_does_not_contain_3_numbers), item);
      xfree(ptrs);
      return;
    }

    item++;
  });

  // Sort the list on the first number.
  qsort((void *)ptrs, (size_t)tv_list_len(l), sizeof(const list_T *), tv_nr_compare);

  cw_interval_T *table = xmalloc(sizeof(cw_interval_T) * (size_t)tv_list_len(l));

  // Store the items in the new table.
  for (item = 0; item < tv_list_len(l); item++) {
    const list_T *const li_l = ptrs[item];
    const listitem_T *lili = tv_list_first(li_l);
    const varnumber_T n1 = TV_LIST_ITEM_TV(lili)->vval.v_number;
    if (item > 0 && n1 <= table[item - 1].last) {
      semsg(_(e_overlapping_ranges_for_nr), (long)n1);
      xfree(ptrs);
      xfree(table);
      return;
    }
    table[item].first = n1;
    lili = TV_LIST_ITEM_NEXT(li_l, lili);
    table[item].last = TV_LIST_ITEM_TV(lili)->vval.v_number;
    lili = TV_LIST_ITEM_NEXT(li_l, lili);
    table[item].width = (char)TV_LIST_ITEM_TV(lili)->vval.v_number;
  }

  xfree(ptrs);

  cw_interval_T *const cw_table_save = cw_table;
  const size_t cw_table_size_save = cw_table_size;
  cw_table = table;
  cw_table_size = (size_t)tv_list_len(l);

  // Check that the new value does not conflict with 'listchars' or
  // 'fillchars'.
  const char *const error = check_chars_options();
  if (error != NULL) {
    emsg(_(error));
    cw_table = cw_table_save;
    cw_table_size = cw_table_size_save;
    xfree(table);
    return;
  }

  xfree(cw_table_save);
  redraw_all_later(NOT_VALID);
}

void f_charclass(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
  if (tv_check_for_string(&argvars[0]) == FAIL
      || argvars[0].vval.v_string == NULL) {
    return;
  }
  rettv->vval.v_number = mb_get_class((const char_u *)argvars[0].vval.v_string);
}