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
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
|
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <sys/stat.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <ctype.h>
#include <syslog.h>
#include <errno.h>
#include <debug.h>
#include <nuttx/ascii.h>
#include <nuttx/vt100.h>
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
#ifndef CONFIG_SYSTEM_VI_ROWS
# define CONFIG_SYSTEM_VI_ROWS 16
#endif
#ifndef CONFIG_SYSTEM_VI_COLS
# define CONFIG_SYSTEM_VI_COLS 64
#endif
/* Some environments may return CR as end-of-line, others LF, and others
* both. If not specified, the logic here assumes either (but not both) as
* the default.
*/
#if defined(CONFIG_EOL_IS_CR)
# undef CONFIG_EOL_IS_LF
# undef CONFIG_EOL_IS_BOTH_CRLF
# undef CONFIG_EOL_IS_EITHER_CRLF
#elif defined(CONFIG_EOL_IS_LF)
# undef CONFIG_EOL_IS_CR
# undef CONFIG_EOL_IS_BOTH_CRLF
# undef CONFIG_EOL_IS_EITHER_CRLF
#elif defined(CONFIG_EOL_IS_BOTH_CRLF)
# undef CONFIG_EOL_IS_CR
# undef CONFIG_EOL_IS_LF
# undef CONFIG_EOL_IS_EITHER_CRLF
#elif defined(CONFIG_EOL_IS_EITHER_CRLF)
# undef CONFIG_EOL_IS_CR
# undef CONFIG_EOL_IS_LF
# undef CONFIG_EOL_IS_BOTH_CRLF
#else
# undef CONFIG_EOL_IS_CR
# undef CONFIG_EOL_IS_LF
# undef CONFIG_EOL_IS_BOTH_CRLF
# define CONFIG_EOL_IS_EITHER_CRLF 1
#endif
/* Control characters */
#undef CTRL
#define CTRL(a) ((a) & 0x1f)
/* Sizes of things */
#define MAX_STRING 64 /* The maximum size of a filename or search string */
#define SCRATCH_BUFSIZE 128 /* The maximum size of the scratch buffer */
#define TEXT_GULP_SIZE 512 /* Text buffer allocations are managed with this unit */
#define TEXT_GULP_MASK 511 /* Mask for aligning buffer allocation sizes */
#define ALIGN_GULP(x) (((x) + TEXT_GULP_MASK) & ~TEXT_GULP_MASK)
#define TABSIZE 8 /* A TAB is eight characters */
#define TABMASK 7 /* Mask for TAB alignment */
#define NEXT_TAB(p) (((p) + TABSIZE) & ~TABMASK)
/* Debug */
#ifndef CONFIG_SYSTEM_VI_DEBUGLEVEL
# define CONFIG_SYSTEM_VI_DEBUGLEVEL 0
#endif
#ifdef CONFIG_CPP_HAVE_VARARGS
# if CONFIG_SYSTEM_VI_DEBUGLEVEL > 0
# define vidbg(format, arg...) \
syslog(EXTRA_FMT format EXTRA_ARG, ##arg)
# define vvidbg(format, ap) \
vsyslog(format, ap)
# else
# define vidbg(x...)
# define vvidbg(x...)
# endif
# if CONFIG_SYSTEM_VI_DEBUGLEVEL > 1
# define vivdbg(format, arg...) \
syslog(EXTRA_FMT format EXTRA_ARG, ##arg)
# else
# define vivdbg(x...)
# endif
#else
# if CONFIG_SYSTEM_VI_DEBUGLEVEL > 0
# define vidbg syslog
# define vvidbg vsyslog
# else
# define vidbg (void)
# define vvidbg (void)
# endif
# if CONFIG_SYSTEM_VI_DEBUGLEVEL > 1
# define vivdbg syslog
# else
# define vivdbg (void)
# endif
#endif
/****************************************************************************
* Private Types
****************************************************************************/
/* VI Key Bindings */
enum vi_cmdmode_key_e
{
KEY_CMDMODE_BEGINLINE = '0', /* Move cursor to start of current line */
KEY_CMDMODE_APPEND = 'a', /* Enter insertion mode after current character */
KEY_CMDMODE_DEL_LINE = 'd', /* "dd" deletes a lines */
KEY_CMDMODE_LEFT = 'h', /* Move left one character */
KEY_CMDMODE_INSERT = 'i', /* Enter insertion mode before current character */
KEY_CMDMODE_DOWN = 'j', /* Move down one line */
KEY_CMDMODE_UP = 'k', /* Move up one line */
KEY_CMDMODE_RIGHT = 'l', /* Move right one character */
KEY_CMDMODE_MARK = 'm', /* Place a mark beginning at the current cursor position */
KEY_CMDMODE_OPENBELOW = 'o', /* Enter insertion mode in new line below current */
KEY_CMDMODE_PASTE = 'p', /* Paste line(s) from into text after current line */
KEY_CMDMODE_REPLACECH = 'r', /* Replace character(s) under cursor */
KEY_CMDMODE_YANK = 'y', /* "yy" yanks the current line(s) into the buffer */
KEY_CMDMODE_DEL = 'x', /* Delete a single character */
KEY_CMDMODE_APPENDEND = 'A', /* Enter insertion mode at the end of the current line */
KEY_CMDMODE_GOTO = 'G', /* Got to line */
KEY_CMDMODE_INSBEGIN = 'I', /* Enter insertion mode at the beginning of the current */
KEY_CMDMODE_OPENABOVE = 'O', /* Enter insertion mode in new line above current line */
KEY_CMDMODE_REPLACE = 'R', /* Replace character(s) under cursor until ESC */
KEY_CMDMODE_COLONMODE = ':', /* The next character command prefaced with a colon */
KEY_CMDMODE_FINDMODE = '/', /* Enter forward search string */
KEY_CMDMODE_ENDLINE = '$', /* Move cursor to end of current line */
KEY_CMDMODE_PAGEUP = CTRL('b'), /* Move backward one screen */
KEY_CMDMODE_HALFDOWN = CTRL('d'), /* Move down (forward) one half screen */
KEY_CMDMODE_PAGEDOWN = CTRL('f'), /* Move forward one screen */
KEY_CMDMODE_REDRAW = CTRL('l'), /* Redraws the screen */
KEY_CMDMODE_REDRAW2 = CTRL('r'), /* Redraws the screen, removing deleted lines */
KEY_CMDMODE_HALFUP = CTRL('u') /* Move up (back) one half screen */
};
enum vi_insmode_key_e
{
KEY_INSMODE_QUOTE = '\\', /* The next character is quote (use literal value) */
};
enum vi_colonmode_key_e
{
KEY_COLMODE_QUIT = 'q', /* Quit vi */
KEY_COLMODE_WRITE = 'w', /* Write file */
KEY_COLMODE_FORCE = '!', /* Force operation */
KEY_COLMODE_QUOTE = '\\' /* The next character is quote (use literal value) */
};
enum vi_findmode_key_e
{
KEY_FINDMODE_QUOTE = '\\' /* The next character is quote (use literal value) */
};
/* VI modes */
enum vi_mode_s
{
MODE_COMMAND = 0, /* ESC Command mode */
SUBMODE_COLON, /* : Command sub-mode */
SUBMODE_FIND, /* / Search sub-mode */
SUBMODE_REPLACECH, /* r Replace sub-mode 1 */
MODE_INSERT, /* i,I,a,A,o,O Insert mode */
MODE_REPLACE /* R Replace sub-mode 2 */
};
/* This structure represents a cursor position */
struct vi_pos_s
{
uint16_t row;
uint16_t column;
};
/* This structure describes the overall state of the editor */
struct vi_s
{
struct vi_pos_s cursor; /* Current cursor position */
struct vi_pos_s cursave; /* Saved cursor position */
struct vi_pos_s display; /* Display size */
off_t curpos; /* The current cursor offset into the text buffer */
off_t textsize; /* The size of the text buffer */
off_t winpos; /* Offset corresponding to the start of the display */
off_t prevpos; /* Previous display position */
uint16_t hscroll; /* Horizontal display offset */
uint16_t value; /* Numeric value entered prior to a command */
uint8_t mode; /* See enum vi_mode_s */
uint8_t cmdlen; /* Length of the command in the scratch[] buffer */
bool modified; /* True: The file has modified */
bool error; /* True: There is an error message on the last line */
bool delarm; /* One more 'd' and the line(s) will be deleted */
bool yankarm; /* One more 'y' and the line(s) will be yanked */
/* Buffers */
FAR char *text; /* Dynamically allocated text buffer */
size_t txtalloc; /* Current allocated size of the text buffer */
FAR char *yank; /* Dynamically allocated yank buffer */
size_t yankalloc; /* Current allocated size of the yank buffer */
char filename[MAX_STRING]; /* Holds the currently selected filename */
char findstr[MAX_STRING]; /* Holds the current search string */
char scratch[SCRATCH_BUFSIZE]; /* For general, scratch usage */
};
/****************************************************************************
* Private Function Prototypes
****************************************************************************/
/* Low-level display and data entry functions */
static void vi_write(FAR struct vi_s *vi, FAR const char *buffer,
size_t buflen);
static void vi_putch(FAR struct vi_s *vi, char ch);
static char vi_getch(FAR struct vi_s *vi);
static void vi_blinkon(FAR struct vi_s *vi);
static void vi_attriboff(FAR struct vi_s *vi);
static void vi_boldon(FAR struct vi_s *vi);
static void vi_attriboff(FAR struct vi_s *vi);
static void vi_reverseon(FAR struct vi_s *vi);
static void vi_attriboff(FAR struct vi_s *vi);
static void vi_cursorhome(FAR struct vi_s *vi);
static void vi_setcursor(FAR struct vi_s *vi, uint16_t row,
uint16_t column);
static void vi_clrtoeol(FAR struct vi_s *vi);
static void vi_clrscreen(FAR struct vi_s *vi);
/* Error dispaly */
static void vi_error(FAR struct vi_s *vi, FAR const char *fmt, ...);
/* Line positioning */
static off_t vi_linebegin(FAR struct vi_s *vi, off_t pos);
static off_t vi_prevline(FAR struct vi_s *vi, off_t pos);
static off_t vi_lineend(FAR struct vi_s *vi, off_t pos);
static off_t vi_nextline(FAR struct vi_s *vi, off_t pos);
/* Text buffer management */
static bool vi_extendtext(FAR struct vi_s *vi, off_t pos,
size_t increment);
static void vi_shrinkpos(off_t delpos, size_t delsize, FAR off_t *pos);
static void vi_shrinktext(FAR struct vi_s *vi, off_t pos, size_t size);
/* File access */
static bool vi_insertfile(FAR struct vi_s *vi, FAR char *filename);
static bool vi_savetext(FAR struct vi_s *vi, FAR char *filename,
off_t pos, size_t size);
static bool vi_checkfile(FAR struct vi_s *vi, FAR char *filename);
/* Mode management */
static void vi_setmode(FAR struct vi_s *vi, uint8_t mode, long value);
static void vi_setsubmode(FAR struct vi_s *vi, uint8_t mode,
char prompt, long value);
static void vi_exitsubmode(FAR struct vi_s *vi, uint8_t mode);
/* Display management */
static uint16_t vi_wincolumn(FAR struct vi_s *vi, off_t start, off_t end);
static void vi_scrollcheck(FAR struct vi_s *vi);
static void vi_show(FAR struct vi_s *vi);
/* Command mode */
static void vi_cusorup(FAR struct vi_s *vi, int nlines);
static void vi_cursordown(FAR struct vi_s *vi, int nlines);
static off_t vi_cursorleft(FAR struct vi_s *vi, off_t curpos,
int ncolumns);
static off_t vi_cursorright(FAR struct vi_s *vi, off_t curpos,
int ncolumns);
static void vi_delforward(FAR struct vi_s *vi);
static void vi_delbackward(FAR struct vi_s *vi);
static void vi_yank(FAR struct vi_s *vi);
static void vi_paste(FAR struct vi_s *vi);
static void vi_gotoline(FAR struct vi_s *vi);
static void vi_cmd_mode(FAR struct vi_s *vi);
/* Command sub-modes */
static void vi_cmdch(FAR struct vi_s *vi, char ch);
static void vi_cmdbackspace(FAR struct vi_s *vi);
static void vi_parsecolon(FAR struct vi_s *vi);
static void vi_cmd_submode(FAR struct vi_s *vi);
static bool vi_findstring(FAR struct vi_s *vi);
static void vi_parsefind(FAR struct vi_s *vi);
static void vi_find_submode(FAR struct vi_s *vi);
static void vi_replacech(FAR struct vi_s *vi, char ch);
static void vi_replacech_submode(FAR struct vi_s *vi);
/* Insert and replace modes */
static void vi_insertch(FAR struct vi_s *vi, char ch);
static void vi_insert_mode(FAR struct vi_s *vi);
static void vi_replace_mode(FAR struct vi_s *vi);
/* Command line processing */
static void vi_release(FAR struct vi_s *vi);
static void vi_showusage(FAR struct vi_s *vi, FAR const char *progname,
int exitcode);
/****************************************************************************
* Private Data
****************************************************************************/
/* VT100 escape sequences */
static const char g_cursorhome[] = VT100_CURSORHOME;
static const char g_erasetoeol[] = VT100_CLEAREOL;
static const char g_clrscreen[] = VT100_CLEARSCREEN;
static const char g_index[] = VT100_INDEX;
static const char g_revindex[] = VT100_REVINDEX;
static const char g_attriboff[] = VT100_MODESOFF;
static const char g_boldon[] = VT100_BOLD;
static const char g_reverseon[] = VT100_REVERSE;
static const char g_blinkon[] = VT100_BLINK;
static const char g_fmtcursorpos[] = VT100_FMT_CURSORPOS;
/* Error format strings */
static const char g_fmtallocfail[] = "Failed to allocate memory";
static const char g_fmtcmdfail[] = "%s failed: %d";
static const char g_fmtnotfile[] = "%s is not a regular file";
static const char g_fmtfileexists[] = "File exists (add ! to override)";
static const char g_fmtmodified[] = "No write since last change (add ! to override)";
static const char g_fmtnotvalid[] = "Command not valid";
/****************************************************************************
* Private Functions
****************************************************************************/
/****************************************************************************
* Low-level display and data entry functions
****************************************************************************/
/****************************************************************************
* Name: vi_write
*
* Description:
* Write a sequence of bytes to the console device (stdout, fd = 1).
*
****************************************************************************/
static void vi_write(FAR struct vi_s *vi, FAR const char *buffer,
size_t buflen)
{
ssize_t nwritten;
size_t nremaining = buflen;
//vivdbg("buffer=%p buflen=%d\n", buffer, (int)buflen);
/* Loop until all bytes have been successuflly written (or until a
* un-recoverable error is encountered)
*/
do
{
/* Take the next gulp */
nwritten = write(1, buffer, buflen);
/* Handle write errors. write() should neve return 0. */
if (nwritten <= 0)
{
/* EINTR is not really an error; it simply means that a signal was
* received while waiting for write.
*/
int errcode = errno;
if (nwritten == 0 || errcode != EINTR)
{
fprintf(stderr, "ERROR: write to stdout failed: %d\n",
errcode);
exit(EXIT_FAILURE);
}
}
/* Decrement the count of bytes remaining to be sent (to handle the
* case of a partial write)
*/
else
{
nremaining -= nwritten;
}
}
while (nremaining > 0);
}
/****************************************************************************
* Name: vi_putch
*
* Description:
* Write a single character to the console device.
*
****************************************************************************/
static void vi_putch(FAR struct vi_s *vi, char ch)
{
vi_write(vi, &ch, 1);
}
/****************************************************************************
* Name: vi_getch
*
* Description:
* Get a single character from the console device (stdin, fd = 0).
*
****************************************************************************/
static char vi_getch(FAR struct vi_s *vi)
{
char buffer;
ssize_t nread;
/* Loop until we successfully read a character (or until an unexpected
* error occurs).
*/
do
{
/* Read one character from the incoming stream */
nread = read(0, &buffer, 1);
/* Check for error or end-of-file. */
if (nread <= 0)
{
/* EINTR is not really an error; it simply means that a signal we
* received while waiting for input.
*/
int errcode = errno;
if (nread == 0 || errcode != EINTR)
{
fprintf(stderr, "ERROR: read from stdin failed: %d\n",
errcode);
exit(EXIT_FAILURE);
}
}
}
while (nread < 1);
/* On success, return the character that was read */
vivdbg("Returning: %c[%02x]\n", isprint(buffer) ? buffer : '.', buffer);
return buffer;
}
/****************************************************************************
* Name: vi_blinkon
*
* Description:
* Enable the blinking attribute at the current cursor location
*
****************************************************************************/
static void vi_blinkon(FAR struct vi_s *vi)
{
/* Send the VT100 BLINKON command */
vi_write(vi, g_blinkon, sizeof(g_blinkon));
}
/****************************************************************************
* Name: vi_boldon
*
* Description:
* Enable the blinking attribute at the current cursor location
*
****************************************************************************/
static void vi_boldon(FAR struct vi_s *vi)
{
/* Send the VT100 BOLDON command */
vi_write(vi, g_boldon, sizeof(g_boldon));
}
/****************************************************************************
* Name: vi_reverseon
*
* Description:
* Enable the blinking attribute at the current cursor location
*
****************************************************************************/
static void vi_reverseon(FAR struct vi_s *vi)
{
/* Send the VT100 REVERSON command */
vi_write(vi, g_reverseon, sizeof(g_reverseon));
}
/****************************************************************************
* Name:
*
* Description:
* Disable all previously selected attributes.
*
****************************************************************************/
static void vi_attriboff(FAR struct vi_s *vi)
{
/* Send the VT100 ATTRIBOFF command */
vi_write(vi, g_attriboff, sizeof(g_attriboff));
}
/****************************************************************************
* Name: vi_cursorhome
*
* Description:
* Move the current cursor to the upper left hand corner of the display
*
****************************************************************************/
static void vi_cursorhome(FAR struct vi_s *vi)
{
/* Send the VT100 CURSORHOME command */
vi_write(vi, g_cursorhome, sizeof(g_cursorhome));
}
/****************************************************************************
* Name: vi_setcursor
*
* Description:
* Move the current cursor position to position (row,col)
*
****************************************************************************/
static void vi_setcursor(FAR struct vi_s *vi, uint16_t row, uint16_t column)
{
char buffer[16];
int len;
vivdbg("row=%d column=%d\n", row, column);
/* Format the cursor position command */
len = snprintf(buffer, 16, g_fmtcursorpos, row, column);
/* Send the VT100 CURSORPOS command */
vi_write(vi, buffer, len);
}
/****************************************************************************
* Name: vi_clrtoeol
*
* Description:
* Clear the display from the current cursor position to the end of the
* current line.
*
****************************************************************************/
static void vi_clrtoeol(FAR struct vi_s *vi)
{
/* Send the VT100 ERASETOEOL command */
vi_write(vi, g_erasetoeol, sizeof(g_erasetoeol));
}
/****************************************************************************
* Name: vi_clrscreen
*
* Description:
* Clear the entire display
*
****************************************************************************/
static void vi_clrscreen(FAR struct vi_s *vi)
{
/* Send the VT100 CLRSCREEN command */
vi_write(vi, g_clrscreen, sizeof(g_clrscreen));
}
/****************************************************************************
* Name: vi_scrollup
*
* Description:
* Scroll the display up 'nlines' by sending the VT100 INDEX command.
*
****************************************************************************/
static void vi_scrollup(FAR struct vi_s *vi, uint16_t nlines)
{
vivdbg("nlines=%d\n", nlines);
/* Scroll for the specified number of lines */
for (; nlines; nlines--)
{
/* Send the VT100 INDEX command */
vi_write(vi, g_index, sizeof(g_index));
}
}
/****************************************************************************
* Name: vi_scrolldown
*
* Description:
* Scroll the display down 'nlines' by sending the VT100 REVINDEX command.
*
****************************************************************************/
static void vi_scrolldown(FAR struct vi_s *vi, uint16_t nlines)
{
vivdbg("nlines=%d\n", nlines);
/* Scroll for the specified number of lines */
for (; nlines; nlines--)
{
/* Send the VT100 REVINDEX command */
vi_write(vi, g_revindex, sizeof(g_revindex));
}
}
/****************************************************************************
* Name: vi_error
*
* Description:
* Show a highlighted error message at the final line of the display.
*
****************************************************************************/
static void vi_error(FAR struct vi_s *vi, FAR const char *fmt, ...)
{
struct vi_pos_s cursor;
va_list ap;
int len;
/* Save the current cursor position */
cursor.row = vi->cursor.row;
cursor.column = vi->cursor.column;
/* Set up for a reverse text message on the final line */
vi_setcursor(vi, vi->display.row - 1, 0);
vi_reverseon(vi);
/* Expand the error message in the scratch buffer */
len = snprintf(vi->scratch, SCRATCH_BUFSIZE, "ERROR: ");
va_start(ap, fmt);
len += vsnprintf(vi->scratch + len, SCRATCH_BUFSIZE - len, fmt, ap);
vvidbg(fmt, ap);
va_end(ap);
/* Write the error message to the display in reverse text */
vi_write(vi, vi->scratch, len);
/* Restore normal attributes */
vi_attriboff(vi);
/* Reposition the cursor */
vi_setcursor(vi, cursor.row, cursor.column);
/* Remember that there is an error message on the last line of the display.
* When the dispaly is refreshed, the last line will not be altered until
* the error is cleared.
*/
vi->error = TRUE;
}
/****************************************************************************
* Line positioning
****************************************************************************/
/****************************************************************************
* Name: vi_linebegin
*
* Description:
* Search backward for the beginning of the current line
*
****************************************************************************/
static off_t vi_linebegin(FAR struct vi_s *vi, off_t pos)
{
/* Search backward to find the previous newline character (or, possibly,
* the beginning of the text buffer).
*/
while (pos && vi->text[pos - 1] != '\n')
{
pos--;
}
vivdbg("Return pos=%ld\n", (long)pos);
return pos;
}
/****************************************************************************
* Name: vi_prevline
*
* Description:
* Search backward for the end of the previous line
*
****************************************************************************/
static off_t vi_prevline(FAR struct vi_s *vi, off_t pos)
{
/* Find the beginning the of current line */
pos = vi_linebegin(vi, pos);
/* If this not the first line, then back up one more character to position
* at the last byte of the previous line.
*/
if (pos > 0)
{
pos = vi_linebegin(vi, pos - 1);
}
vivdbg("Return pos=%ld\n", (long)pos);
return pos;
}
/****************************************************************************
* Name: vi_lineend
*
* Description:
* Search forward for the end of the current line
*
****************************************************************************/
static off_t vi_lineend(FAR struct vi_s *vi, off_t pos)
{
/* Search forward to find the next newline character. (or, possibly,
* the end of the text buffer).
*/
while (pos < vi->textsize && vi->text[pos] != '\n')
{
pos++;
}
vivdbg("Return pos=%ld\n", (long)pos);
return pos;
}
/****************************************************************************
* Name: vi_nextline
*
* Description:
* Search backward for the start of the next line
*
****************************************************************************/
static off_t vi_nextline(FAR struct vi_s *vi, off_t pos)
{
/* Position at the end of the current line */
pos = vi_lineend(vi, pos);
/* If this is not the last byte in the buffer, then increment by one
* for position of the first byte of the next line.
*/
if (pos < vi->textsize)
{
pos++;
}
vivdbg("Return pos=%ld\n", (long)pos);
return pos;
}
/****************************************************************************
* Text buffer management
****************************************************************************/
/****************************************************************************
* Name: vi_extendtext
*
* Description:
* Reallocate the in-memory file memory by (at least) 'increment' and make
* space for new text of size 'increment' at the current cursor position.
*
****************************************************************************/
static bool vi_extendtext(FAR struct vi_s *vi, off_t pos, size_t increment)
{
FAR char *alloc;
int i;
vivdbg("pos=%ld increment=%ld\n", (long)pos, (long)increment);
/* Check if we need to reallocate */
if (!vi->text || vi->textsize + increment > vi->txtalloc)
{
/* Allocate in chunksize so that we do not have to reallocate so
* often.
*/
size_t allocsize = ALIGN_GULP(vi->textsize + increment);
alloc = realloc(vi->text, allocsize);
if (!alloc)
{
/* Reallocation failed */
vi_error(vi, g_fmtallocfail);
return false;
}
/* Save the new buffer information */
vi->text = alloc;
vi->txtalloc = allocsize;
}
/* Move text to make space for new text of size 'increment' at the current
* cursor position
*/
for (i = vi->textsize - 1; i >= pos; i--)
{
vi->text[i + increment] = vi->text[i];
}
/* Adjust end of file position */
vi->textsize += increment;
vi->modified = true;
return true;
}
/****************************************************************************
* Name: vi_shrinkpos
*
* Description:
* This is really part of vi_shrinktext. When any text is deleted, any
* positions lying beyond the deleted region in the text buffer must be
* adjusted.
*
* Input Parameters:
* delpos The position where text was deleted
* delsize The number of bytes deleted.
* pos A pointer to a position that may need to be adjusted.
*
****************************************************************************/
static void vi_shrinkpos(off_t delpos, size_t delsize, FAR off_t *pos)
{
vivdbg("delpos=%ld delsize=%ld pos=%ld\n",
(long)delpos, (long)delsize, (long)*pos);
/* Check if the position is beyond the deleted region */
if (*pos > delpos + delsize)
{
/* Yes... just subtract the size of the deleted region */
*pos -= delsize;
}
/* What if the position is within the deleted region? Set it to the
* beginning of the deleted region.
*/
else if (*pos > delpos)
{
*pos = delpos;
}
}
/****************************************************************************
* Name: vi_shrinktext
*
* Description:
* Delete a region in the text buffer by copying the end of the text buffer
* over the deleted region and adjusting the size of the region. The text
* region may be reallocated in order to recover the unused memory.
*
****************************************************************************/
static void vi_shrinktext(FAR struct vi_s *vi, off_t pos, size_t size)
{
FAR char *alloc;
size_t allocsize;
int i;
vivdbg("pos=%ld size=%ld\n", (long)pos, (long)size);
/* Close up the gap to remove 'size' characters at 'pos' */
for (i = pos + size; i < vi->textsize; i++)
{
vi->text[i - size] = vi->text[i];
}
/* Adjust sizes and positions */
vi->textsize -= size;
vi->modified = true;
vi_shrinkpos(pos, size, &vi->curpos);
vi_shrinkpos(pos, size, &vi->winpos);
vi_shrinkpos(pos, size, &vi->prevpos);
/* Reallocate the buffer to free up memory no longer in use */
allocsize = ALIGN_GULP(vi->textsize);
if (allocsize < vi->txtalloc)
{
alloc = realloc(vi->text, allocsize);
if (!alloc)
{
vi_error(vi, g_fmtallocfail);
return;
}
/* Save the new buffer information */
vi->text = alloc;
vi->txtalloc = allocsize;
}
}
/****************************************************************************
* File access
****************************************************************************/
/****************************************************************************
* Name: vi_insertfile
*
* Description:
* Insert the contents of a file into the text buffer
*
****************************************************************************/
static bool vi_insertfile(FAR struct vi_s *vi, FAR char *filename)
{
struct stat buf;
FILE *stream;
off_t filesize;
size_t nread;
int result;
bool ret;
vivdbg("filename=\"%s\"\n", filename);
/* Get the size of the file */
result = stat(filename, &buf);
if (result < 0)
{
vi_error(vi, g_fmtcmdfail, "stat", errno);
return false;
}
/* Check for zero-length file */
filesize = buf.st_size;
if (filesize < 1)
{
return false;
}
/* Open the file for reading*/
stream = fopen(filename, "r");
if (!stream)
{
vi_error(vi, g_fmtcmdfail, "open", errno);
return false;
}
/* [Re]allocate the text buffer to hold the file contents at the current
* cursor position.
*/
ret = false;
if (vi_extendtext(vi, vi->curpos, filesize))
{
/* Read the contents of the file into the text buffer at the
* current cursor position.
*/
nread = fread(vi->text + vi->curpos, 1, filesize, stream);
if (nread < filesize)
{
/* Report the error (or partial read), EINTR is not handled */
vi_error(vi, g_fmtcmdfail, "fread", errno);
vi_shrinktext(vi, vi->curpos, filesize);
}
else
{
ret = true;
}
}
(void)fclose(stream);
return ret;
}
/****************************************************************************
* Name: vi_savetext
*
* Description:
* Save a region of the text buffer to 'filename'
*
****************************************************************************/
static bool vi_savetext(FAR struct vi_s *vi, FAR char *filename, off_t pos,
size_t size)
{
FILE *stream;
size_t nwritten;
vivdbg("filename=\"%s\" pos=%ld size=%ld\n",
filename, (long)pos, (long)size);
/* Open the file for writing */
stream = fopen(filename, "w");
if (!stream)
{
vi_error(vi, g_fmtcmdfail, "fopen", errno);
return false;
}
/* Write the region of the text buffer beginning at pos and extending
* through pos + size -1.
*/
nwritten = fwrite(vi->text + pos, 1, size, stream);
if (nwritten < size)
{
/* Report the error (or partial write). EINTR is not handled. */
vi_error(vi, g_fmtcmdfail, "fwrite", errno);
return false;
}
(void)fclose(stream);
return true;
}
/****************************************************************************
* Name: vi_checkfile
*
* Description:
* Check if a file by this name already exists.
*
****************************************************************************/
static bool vi_checkfile(FAR struct vi_s *vi, FAR char *filename)
{
struct stat buf;
int ret;
vivdbg("filename=\"%s\"\n", filename);
/* Get the size of the file */
ret = stat(filename, &buf);
if (ret < 0)
{
/* The file does not exist */
return false;
}
/* It exists, but is it a regular file */
if (!S_ISREG(buf.st_mode))
{
/* Report the error... there is really no good return value in
* this case.
*/
vi_error(vi, g_fmtnotfile, filename);
}
return true;
}
/****************************************************************************
* Mode Management Functions
****************************************************************************/
/****************************************************************************
* Name: vi_setmode
*
* Description:
* Set the new mode (or command sub-mode) and reset all other common state
* variables. NOTE that a numeric value may be passed to the new mode in
* the value field.
*
****************************************************************************/
static void vi_setmode(FAR struct vi_s *vi, uint8_t mode, long value)
{
vivdbg("mode=%d value=%ld\n", mode, value);
/* Set the mode and clear mode-dependent states that are not preserved
* across mode changes.
*/
vi->mode = mode;
vi->delarm = false;
vi->yankarm = false;
vi->error = false;
vi->value = value;
vi->cmdlen = 0;
}
/****************************************************************************
* Name: vi_setsubmode
*
* Description:
* Set up one of the data entry sub-modes of the command mode. These are
* modes in which commands or search data will be entered on the final line
* of the display.
*
****************************************************************************/
static void vi_setsubmode(FAR struct vi_s *vi, uint8_t mode, char prompt,
long value)
{
vivdbg("mode=%d prompt='%c' value=%ld\n", mode, prompt, value);
/* Set up the new mode */
vi_setmode(vi, mode, value);
/* Save the previous cursor position (not required by all modes) */
vi->cursave.row = vi->cursor.row;
vi->cursave.column = vi->cursor.column;
/* Set up for data entry on the final line */
vi->cursor.row = vi->display.row - 1;
vi->cursor.column = 0;
vi_setcursor(vi, vi->cursor.row, vi->cursor.column);
/* Output the prompt character in bold text */
vi_boldon(vi);
vi_putch(vi, prompt);
vi_attriboff(vi);
/* Update the cursor position */
vi->cursor.column = 1;
}
/****************************************************************************
* Name: vi_exitsubmode
*
* Description:
* Exit the data entry sub-mode and return to normal command mode.
*
****************************************************************************/
static void vi_exitsubmode(FAR struct vi_s *vi, uint8_t mode)
{
vivdbg("mode=%d\n", mode);
/* Set up the new mode */
vi_setmode(vi, mode, 0);
/* Restore the saved cursor position */
vi->cursor.row = vi->cursave.row;
vi->cursor.column = vi->cursave.column;
}
/****************************************************************************
* Display Management
****************************************************************************/
/****************************************************************************
* Name: vi_wincolumn
*
* Description:
* Based on the position of the cursor in the text buffer, determine the
* display cursor position, performing TAB expansion as necessary.
*
****************************************************************************/
static uint16_t vi_wincolumn(FAR struct vi_s *vi, off_t start, off_t end)
{
uint16_t column;
off_t offset;
vivdbg("start=%ld end=%ld\n", (long)start, (long)end);
/* Make sure that the end position is not beyond the end of the text. We
* assume that the start position is okay.
*/
if (end > vi->textsize)
{
end = vi->textsize;
}
/* Loop incrementing the text buffer offset while text buffer offset is
* within range.
*/
for (offset = start, column = 0; offset < end; offset++)
{
/* Does this offset point to the newline terminator? */
if (vi->text[offset] == '\n')
{
/* Yes... break out of the loop return the cursor column */
break;
}
/* No... does it refer to a TAB? */
else if (vi->text[offset] == '\t')
{
/* Yes.. expand the TAB */
column = NEXT_TAB(column);
}
/* No, then just increment the cursor column by one character */
else
{
column++;
}
}
return column;
}
/****************************************************************************
* Name: vi_scrollcheck
*
* Description:
* Check if any operations will require that we scroll the display.
*
****************************************************************************/
static void vi_scrollcheck(FAR struct vi_s *vi)
{
off_t curline;
off_t pos;
int column;
int nlines;
/* Get the text buffer offset to the beginning of the current line */
curline = vi_linebegin(vi, vi->curpos);
/* Check if the current line is above the first line on the display */
while (curline < vi->winpos)
{
/* Yes.. move the window position up by one line and check again */
pos = vi_prevline(vi, vi->winpos);
vi->winpos = vi_linebegin(vi, pos);
}
/* Reset the cursor row position so that it is relative to the
* top of the display.
*/
vi->cursor.row = 0;
for (pos = vi->winpos; pos < curline; pos = vi_nextline(vi, pos))
{
vi->cursor.row++;
}
/* Check if the cursor row position is below the bottom of the display */
for (; vi->cursor.row >= vi->display.row; vi->cursor.row--)
{
/* Yes.. move the window position down by one line and check again */
vi->winpos = vi_nextline(vi, vi->winpos);
}
/* Check if the cursor column is on the display. vi_wincolumn returns the
* unrestricted column number of cursor. hscroll is the horizontal offset
* in characters.
*/
column = (int)vi_wincolumn(vi, curline, vi->curpos) - (int)vi->hscroll;
/* Force the cursor column to lie on the display. First check if the
* column lies to the left of the horizontal scrolling position. If it
* does, move the scroll position to the left by tabs until the cursor
* lies on the display.
*/
while (column < 0)
{
column += TABSIZE;
vi->hscroll -= TABSIZE;
}
/* If the the cursor column lies to the right of the display, then adjust
* the horizontal scrolling position so that the cursor position does
* lie on the display.
*/
while (column >= vi->display.column)
{
column -= TABSIZE;
vi->hscroll += TABSIZE;
}
/* That final adjusted position is the display cursor column */
vi->cursor.column = column;
/* Check if new window position is below the previous position.
* In this case, we will need to scroll up until the new window
* position is at the top of the display.
*/
if (vi->winpos > vi->prevpos)
{
/* We will need to scroll up. Count how many lines we
* need to scroll.
*/
for (nlines = 0, pos = vi->prevpos;
pos != vi->winpos && nlines < vi->display.row;
nlines++)
{
pos = vi_nextline(vi, pos);
}
/* Then scroll up that number of lines */
if (nlines < vi->display.row)
{
vi_scrollup(vi, nlines);
}
}
/* Check if new window position is above the previous position.
* In this case, we will need to scroll down until the new window
* position is at the top of the display.
*/
else if (vi->winpos < vi->prevpos)
{
for (nlines = 0, pos = vi->prevpos;
pos != vi->winpos && nlines < vi->display.row;
nlines++)
{
pos = vi_prevline(vi, pos);
}
/* Then scroll down that number of lines */
if (nlines < vi->display.row)
{
vi_scrolldown(vi, nlines);
}
}
/* Save the previous top-of-display position for next time around.
* This can be modified asynchronously by text deletion operations.
*/
vi->prevpos = vi->winpos;
vivdbg("winpos=%ld hscroll=%d\n",
(long)vi->winpos, (long)vi->hscroll);
}
/****************************************************************************
* Name: vi_show
*
* Description:
* Update the display based on the last operation. This function is
* called at the beginning of the processing loop in Command and Insert
* modes (and also in the continuous replace mode).
*
****************************************************************************/
static void vi_show(FAR struct vi_s *vi)
{
off_t pos;
uint16_t row;
uint16_t endrow;
uint16_t column;
uint16_t endcol;
uint16_t tabcol;
/* Check if any of the preceding operations will cause the display to
* scroll.
*/
vi_scrollcheck(vi);
/* If there is an error message at the bottom of the display, then
* do not update the last line.
*/
endrow = vi->display.row;
if (vi->error)
{
endrow--;
}
/* Make sure that all character attributes are disabled. */
vi_attriboff(vi);
/* Write each line to the display, handling horizontal scrolling and
* tab expansion.
*/
for (pos = vi->winpos, row = 0;
pos < vi->textsize && row < endrow;
row++)
{
/* Get the last column on this row. Avoid writing into the last byte
* on the screen which may trigger a scroll.
*/
endcol = vi->display.column;
if (row >= vi->display.row - 1)
{
endcol--;
}
/* Get the offset into this line corresponding to column 0, accounting
* for horizontal scrolling and tab expansion.
*/
pos = vi_wincolumn(vi, pos, pos + vi->hscroll);
/* Set the cursor position to the beginning of this row and clear to
* the end of the line.
*/
vi_setcursor(vi, row, 0);
vi_clrtoeol(vi);
/* Loop for each column */
for (column = 0; pos < vi->textsize && column < endcol; pos++)
{
/* Break out of the loop if we encounter the newline before the
* last column is encountered.
*/
if (vi->text[pos] == '\n')
{
break;
}
/* Perform TAB expansion */
else if (vi->text[pos] == '\t')
{
tabcol = NEXT_TAB(column);
if (tabcol < endcol)
{
for (; column < tabcol; column++)
{
vi_putch(vi, ' ');
}
}
else
{
/* Break out of the loop... there is nothing left on the
* line but whitespace.
*/
break;
}
}
/* Add the normal character to the display */
else
{
vi_putch(vi, vi->text[pos]);
column++;
}
}
/* Skip to the beginning of the next line */
pos = vi_nextline(vi, pos);
}
/* If there was not enough text to fill the display, clear the
* remaining lines (except for any possible error line at the
& bottom of the display).
*/
for (; row < endrow; row++)
{
/* Set the cursor position to the beginning of the row and clear to
* the end of the line.
*/
vi_setcursor(vi, row, 0);
vi_clrtoeol(vi);
}
}
/****************************************************************************
* Command Mode Functions
****************************************************************************/
/****************************************************************************
* Name: vi_cusorup
*
* Description:
* Move the cursor up one line in the text buffer.
*
****************************************************************************/
static void vi_cusorup(FAR struct vi_s *vi, int nlines)
{
int remaining;
off_t start;
off_t end;
off_t pos;
vivdbg("nlines=%d\n", nlines);
/* How many lines do we need to move? Zero means 1 (so does 1) */
remaining = (nlines == 0 ? 1 : nlines);
/* Get the offset to the start of the current line */
start = vi_linebegin(vi, vi->curpos);
/* Now move the cursor position back the correct number of lines */
for (; remaining > 0; remaining--)
{
pos = vi_prevline(vi, start);
start = vi_linebegin(vi, pos);
end = start + vi->cursor.column + vi->hscroll;
vi->curpos = vi_wincolumn(vi, start, end);
}
}
/****************************************************************************
* Name: vi_cursordown
*
* Description:
* Move the cursor down one line in the text buffer
*
****************************************************************************/
static void vi_cursordown(FAR struct vi_s *vi, int nlines)
{
int remaining;
off_t start;
off_t end;
vivdbg("nlines=%d\n", nlines);
/* How many lines do we need to move? Zero means 1 (so does 1) */
remaining = (nlines == 0 ? 1 : nlines);
/* Get the offset to the start of the current line */
start = vi_linebegin(vi, vi->curpos);
/* Now move the cursor position forward the correct number of lines */
for (; remaining > 0; remaining--)
{
if (!vi_lineend(vi, vi->curpos) < vi->textsize)
{
break;
}
start = vi_nextline(vi, start);
end = start + vi->cursor.column + vi->hscroll;
vi->curpos = vi_wincolumn(vi, start, end);
}
}
/****************************************************************************
* Name: vi_cursorleft
*
* Description:
* Move the cursor left 'ncolumns' columns in the text buffer (without moving
* to the preceding line). Note that a repetition count of 0 means to
* perform the movement once.
*
****************************************************************************/
static off_t vi_cursorleft(FAR struct vi_s *vi, off_t curpos, int ncolumns)
{
int remaining;
vivdbg("curpos=%ld ncolumns=%d\n", curpos, ncolumns);
for (remaining = ncolumns < 1 ? 1 : ncolumns;
curpos > 0 && remaining > 0 && vi->text[curpos] != '\n';
curpos--, remaining--);
return curpos;
}
/****************************************************************************
* Name: vi_cursorright
*
* Description:
* Move the cursor right 'ncolumns' columns in the text buffer (without
* moving to the next line). Note that a repetition count of 0 means to
* perform the movement once.
*
****************************************************************************/
static off_t vi_cursorright(FAR struct vi_s *vi, off_t curpos, int ncolumns)
{
int remaining;
vivdbg("curpos=%ld ncolumns=%d\n", curpos, ncolumns);
for (remaining = ncolumns < 1 ? 1 : ncolumns;
curpos < vi->textsize && remaining > 0 && vi->text[curpos] != '\n';
curpos++, remaining--);
return curpos;
}
/****************************************************************************
* Name: vi_delforward
*
* Description:
* Delete characters from the current cursor position forward
*
****************************************************************************/
static void vi_delforward(FAR struct vi_s *vi)
{
off_t end;
size_t size;
vivdbg("curpos=%ld value=%ld\n", (long)vi->curpos, vi->value);
end = vi_cursorright(vi, vi->curpos, vi->value);
size = end - vi->curpos - 1;
vi_shrinktext(vi, vi->curpos, size);
}
/****************************************************************************
* Name: vi_delbackward
*
* Description:
* Delete characters before the current cursor position
*
****************************************************************************/
static void vi_delbackward(FAR struct vi_s *vi)
{
off_t start;
off_t end;
size_t size;
vivdbg("curpos=%ld value=%ld\n", (long)vi->curpos, vi->value);
start = vi_cursorleft(vi, vi->curpos, 1);
end = vi_cursorleft(vi, start, vi->value);
size = end - start - 1;
vi_shrinktext(vi, start, size);
}
/****************************************************************************
* Name: vi_yank
*
* Description:
* Remove N lines from the text buffer, beginning at the current line and
* copy the lines to an allocated yank buffer.
*
****************************************************************************/
static void vi_yank(FAR struct vi_s *vi)
{
off_t start;
off_t end;
off_t next;
int nlines;
/* Get the offset in the text buffer to the beginning of the current line */
start = vi_linebegin(vi, vi->curpos);
/* Move one line unless a repetition count was provided */
nlines = (vi->value > 0 ? vi->value : 1);
vivdbg("start=%ld nlines=%d\n", (long)start, nlines);
/* Search ahead to find the end of the last line to yank */
for (next = start; nlines > 1; nlines--)
{
next = vi_nextline(vi, next);
}
end = vi_lineend(vi, next);
/* Free any previously yanked lines */
if (vi->yank)
{
free(vi->yank);
}
/* Allocate a yank buffer biggest enough to hold the lines */
vi->yankalloc = end - start + 1;
vi->yank = (FAR char *)malloc(vi->yankalloc);
if (!vi->yank)
{
vi_error(vi, g_fmtallocfail);
vi->yankalloc = 0;
return;
}
/* Copy the block from the text buffer to the yank buffer */
memcpy(vi->yank, &vi->text[start], vi->yankalloc);
/* Remove the yanked text from the text buffer */
vi_shrinktext(vi, start, vi->yankalloc);
}
/****************************************************************************
* Name: vi_paste
*
* Description:
* Copy line(s) from the yank buffer, and past them after the current line.
* The contents of the yank buffer are released.
*
****************************************************************************/
static void vi_paste(FAR struct vi_s *vi)
{
off_t start;
vivdbg("curpos=%ld yankalloc=%d\n", (long)vi->curpos, (long)vi->yankalloc);
/* Make sure there is something to be yanked */
if (!vi->yank || vi->yankalloc <= 0)
{
return;
}
/* Paste at the beginning of the next line */
start = vi_nextline(vi, vi->curpos);
/* Reallocate the text buffer to hold the yank buffer contents at the
* the beginning of the next line.
*/
if (vi_extendtext(vi, start, vi->yankalloc))
{
/* Copy the contents of the yank buffer into the text buffer at the
* position where the start of the next line was.
*/
memcpy(&vi->text[start], vi->yank, vi->yankalloc);
}
/* Free the yank buffer in any event */
free(vi->yank);
vi->yank = NULL;
vi->yankalloc = 0;
}
/****************************************************************************
* Name: vi_gotoline
*
* Description:
*
*
****************************************************************************/
static void vi_gotoline(FAR struct vi_s *vi)
{
vivdbg("curpos=%ld value=%ld\n", (long)vi->curpos, vi->value);
/* Special case the first line */
if (vi->value == 1)
{
vi->curpos = 0;
}
/* Work harder to position to lines in the middle */
else if (vi->value > 0)
{
uint32_t line;
/* Got to the line == value */
for (line = vi->value, vi->curpos = 0;
--line > 0 && vi->curpos < vi->textsize;
)
{
vi->curpos = vi_nextline(vi, vi->curpos);
}
}
/* No value means to go to beginning of the last line */
else
{
/* Get the beginning of the last line */
vi->curpos = vi_linebegin(vi, vi->textsize);
}
}
/****************************************************************************
* Name: vi_cmd_mode
*
* Description:
* Command mode loop
*
****************************************************************************/
static void vi_cmd_mode(FAR struct vi_s *vi)
{
int ch;
vivdbg("Enter command mode\n");
/* Loop while we are in command mode */
while (vi->mode == MODE_COMMAND)
{
/* Make sure that the display reflects the current state */
vi_show(vi);
vi_setcursor(vi, vi->cursor.row, vi->cursor.column);
/* Get the next character from the input */
ch = vi_getch(vi);
/* Anything other than 'd' disarms line deletion */
if (ch != 'd')
{
vi->delarm = false;
}
/* Anything other than 'y' disarms line yanking */
if (ch != 'y')
{
vi->yankarm = false;
}
/* Any key press clears the error message */
vi->error = false;
/* Handle numeric input. Zero (0) with no preceding value is a
* special case: It means to go to the beginning o the line.
*/
if (isdigit(ch) && (vi->value > 0 || ch != '0'))
{
uint32_t tmp = 10 * vi->value + (ch - '0');
if (tmp > UINT16_MAX)
{
tmp = UINT16_MAX;
}
/* Update the command repetition count */
vi->value = tmp;
vivdbg("Value=%ld\n", vi->value);
continue;
}
/* Then handle the non-numeric character */
switch (ch)
{
case KEY_CMDMODE_UP: /* Move the cursor up one line */
{
vi_cusorup(vi, vi->value);
}
break;
case KEY_CMDMODE_DOWN: /* Move the cursor down one line */
{
vi_cursordown(vi, vi->value);
}
break;
case KEY_CMDMODE_LEFT: /* Move the cursor left N characters */
{
vi->curpos = vi_cursorleft(vi, vi->curpos, vi->value);
}
break;
case KEY_CMDMODE_RIGHT: /* Move the cursor right one character */
{
vi->curpos = vi_cursorright(vi, vi->curpos, vi->value);
}
break;
case KEY_CMDMODE_BEGINLINE: /* Move cursor to start of current line */
{
vi->curpos = vi_linebegin(vi, vi->curpos);
}
break;
case KEY_CMDMODE_ENDLINE: /* Move cursor to end of current line */
{
vi->curpos = vi_lineend(vi, vi->curpos);
}
break;
case KEY_CMDMODE_PAGEUP: /* Move up (backward) one screen */
{
vi_cusorup(vi, vi->display.row);
}
break;
case KEY_CMDMODE_PAGEDOWN: /* Move down (forward) one screen */
{
vi_cursordown(vi, vi->display.row);
}
break;
case KEY_CMDMODE_HALFUP: /* Move up (backward) one screen */
{
vi_cusorup(vi, vi->display.row >> 1);
}
break;
case KEY_CMDMODE_HALFDOWN: /* Move down (forward) one half screen */
{
vi_cursordown(vi, vi->display.row >> 1);
}
break;
case KEY_CMDMODE_REDRAW: /* Redraws the screen */
case KEY_CMDMODE_REDRAW2: /* Redraws the screen, removing deleted lines */
break; /* Not implemented */
case KEY_CMDMODE_DEL: /* Delete N characters at the cursor */
case ASCII_DEL:
{
vi_delforward(vi);
}
break;
case ASCII_BS: /* Delete N characters before the cursor */
{
vi_delbackward(vi);
}
break;
case KEY_CMDMODE_DEL_LINE: /* Delete the current line */
{
if (vi->delarm)
{
off_t curline = vi_linebegin(vi, vi->curpos);
vi_shrinktext(vi, curline, vi_nextline(vi, curline) - curline);
}
else
{
vi->delarm = true;
}
}
break;
case KEY_CMDMODE_YANK: /* Yank the current line(s) into the buffer */
{
if (vi->yankarm)
{
vi_yank(vi);
}
else
{
vi->yankarm = true;
}
}
break;
case KEY_CMDMODE_PASTE: /* Paste line(s) from into text after current line */
{
vi_paste(vi);
}
break;
case KEY_CMDMODE_MARK: /* Place a mark beginning at the current cursor position */
break; /* Not implemented */
case KEY_CMDMODE_REPLACECH: /* Replace character(s) under cursor */
{
vi_setmode(vi, SUBMODE_REPLACECH, vi->value);
}
break;
case KEY_CMDMODE_REPLACE: /* Replace character(s) under cursor until ESC */
{
vi_setmode(vi, MODE_REPLACE, 0);
}
break; /* Not implemented */
case KEY_CMDMODE_OPENBELOW: /* Enter insertion mode in new line below current */
{
/* Insert a newline to break the line. The cursor now points
* beginning of the new line.
*/
vi_insertch(vi, '\n');
/* Then enter insert mode */
vi_setmode(vi, MODE_INSERT, 0);
}
break;
case KEY_CMDMODE_OPENABOVE: /* Enter insertion mode in new line above current */
{
/* Insert a newline to break the line. Backup the cursor so
* that it points to the end of the (previous) current line.
*/
vi_insertch(vi, '\n');
vi->curpos = vi_prevline(vi, vi->curpos);
/* Then enter insert mode */
vi_setmode(vi, MODE_INSERT, 0);
}
break;
case KEY_CMDMODE_APPEND: /* Enter insertion mode after the current cursor position */
{
vi->curpos = vi_cursorleft(vi, vi->curpos, 1);
vi_setmode(vi, MODE_INSERT, 0);
}
break;
case KEY_CMDMODE_APPENDEND: /* Enter insertion mode at the end of the current line */
{
vi->curpos = vi_lineend(vi, vi->curpos);
vi_setmode(vi, MODE_INSERT, 0);
}
break;
case KEY_CMDMODE_INSBEGIN: /* Enter insertion mode at the beginning of the current line */
{
vi->curpos = vi_linebegin(vi, vi->curpos);
}
/* Fall through */
case KEY_CMDMODE_INSERT: /* Enter insertion mode before the current cursor position */
{
vi_setmode(vi, MODE_INSERT, 0);
}
break;
case KEY_CMDMODE_COLONMODE: /* Enter : command sub-mode */
{
vi_setsubmode(vi, SUBMODE_COLON, ':', 0);
}
break;
case KEY_CMDMODE_FINDMODE: /* Enter / find sub-mode */
{
vi_setsubmode(vi, SUBMODE_FIND, '/', 0);
}
break;
case KEY_CMDMODE_GOTO: /* Go to line specified by the accumulated value */
{
vi_gotoline(vi);
}
break;
default:
break;
}
/* Any non-numeric input will reset the accumulated value (after it has
* been used)
*/
vi->value = 0;
}
}
/****************************************************************************
* Common Sub-Mode Functions
****************************************************************************/
/****************************************************************************
* Name: vi_cmdch
*
* Description:
* Insert one character into the data entry line
*
****************************************************************************/
static void vi_cmdch(FAR struct vi_s *vi, char ch)
{
int index = vi->cmdlen;
int next = index + 1;
vivdbg("cmdlen=%d ch=%c[%02x]\n", vi->cmdlen, isprint(ch) ? ch : '.', ch);
/* Abort gracelessly if the scratch buffer becomes full */
if (next >= SCRATCH_BUFSIZE)
{
vi_exitsubmode(vi, MODE_COMMAND);
return;
}
/* Add the new character to the scratch buffer */
vi->scratch[index] = ch;
vi->cmdlen = next;
/* Update the cursor position */
vi->cursor.column = next + 1;
/* And add the new character to the display */
vi_putch(vi, ch);
}
/****************************************************************************
* Name: vi_cmdbackspace
*
* Description:
* Process a backspace character in the data entry line
*
****************************************************************************/
static void vi_cmdbackspace(FAR struct vi_s *vi)
{
vivdbg("cmdlen=%d\n", vi->cmdlen);
if (vi->cmdlen > 0)
{
vi_setcursor(vi, vi->display.row - 1, vi->cmdlen);
vi_clrtoeol(vi);
/* Update the command index and cursor position */
vi->cursor.column = vi->cmdlen;
/* Decrement the number of characters on in the command */
vi->cmdlen--;
}
}
/****************************************************************************
* Colon Data Entry Sub-Mode Functions
****************************************************************************/
/****************************************************************************
* Name: vi_parsecolon
*
* Description:
* Parse the colon command collected in the scratch buffer
*
****************************************************************************/
static void vi_parsecolon(FAR struct vi_s *vi)
{
FAR char *filename = NULL; /* May be replaced with new filename in scratch buffer */
bool dowrite = false; /* True: We need to write the text buffer to a file */
bool doquit = false; /* True: Exit vi */
bool forcewrite = false; /* True: Write even if the new file exists */
bool forcequit = false; /* True: Quite even if there are un-saved changes */
bool done = false; /* True: Terminates parsing loop */
int ch;
int lastch = 0;
int col;
vivdbg("Parse: \"%s\"\n", vi->scratch);
/* NUL terminate the command */
vi->scratch[vi->cmdlen] = '\0';
/* Then parse the contents of the scratch buffer */
for (col = 0; col < vi->cmdlen && !done; col++)
{
ch = vi->scratch[col];
switch (ch)
{
case KEY_COLMODE_WRITE:
{
dowrite = true;
lastch = ch;
}
break;
case KEY_COLMODE_QUIT:
{
doquit = true;
lastch = ch;
}
break;
case KEY_COLMODE_FORCE:
{
if (lastch == KEY_COLMODE_WRITE)
{
forcewrite = true;
}
else if (lastch == KEY_COLMODE_QUIT)
{
forcequit = true;
}
}
break;
default:
{
/* Ignore whitespace */
if (ch != ' ')
{
/* Anything else terminates the loop */
done = true;
/* If there is anything else on the line, then it must be
* a file name. If we are writing, then we need to copy
* the file into the filename storage area.
*/
if (ch != '\0' && dowrite)
{
/* For now, just remember where the file is in the
* scratch buffer.
*/
filename = &vi->scratch[col];
}
}
}
break;
}
}
/* Are we writing to a new filename? If we are not forcing the write,
* then we have to check if the file exists.
*/
vivdbg("dowrite=%d forcewrite=%d filename=\"%s\"\n",
dowrite, forcewrite, filename ? filename : vi->filename);
if (dowrite && filename && !forcewrite && vi_checkfile(vi, vi->filename))
{
vi_error(vi, g_fmtfileexists);
dowrite = false;
doquit = false;
}
/* Check if we are trying to quit with un-saved changes. The use must
* force quitting in this case.
*/
vivdbg("doquit=%d forcequit=%d modified=%d\n",
doquit, forcequit, vi->modified);
if (doquit && vi->modified && !forcequit)
{
vi_error(vi, g_fmtmodified);
dowrite = false;
doquit = false;
}
/* Are we now commit to writing the file? */
vivdbg("dowrite=%d filename=\"%s modified=%d\n",
dowrite, filename ? filename : vi->filename, vi->modified);
if (dowrite)
{
/* If we are writing to a new file, then we need to copy the filename
* from the scratch buffer to the filename buffer.
*/
if (filename)
{
strncpy(vi->filename, filename, MAX_STRING - 1);
/* Make sure that the (possibly truncated) file name is NUL
* terminated
*/
vi->filename[MAX_STRING - 1] = '\0';
}
/* If it is not a new file and if there are no changes to the text
* buffer, then ignore the write.
*/
if (filename || vi->modified)
{
/* Now, finally, we can save the file */
if (vi_savetext(vi, vi->filename, 0, vi->textsize) && !forcequit)
{
/* An error occurred while saving the file and we are
* not forcing the quit operation. So cancel the
* quit.
*/
doquit = false;
}
}
}
/* Are we committed to exit-ing? */
vivdbg("doquit=%d\n", doquit);
if (doquit)
{
/* Yes... free resources and exit */
vi_release(vi);
exit(EXIT_SUCCESS);
}
/* Otherwise, revert to command mode */
vi_exitsubmode(vi, MODE_COMMAND);
}
/****************************************************************************
* Name: vi_cmd_submode
*
* Description:
* Colon command sub-mode of the command mode processing
*
****************************************************************************/
static void vi_cmd_submode(FAR struct vi_s *vi)
{
int ch;
vivdbg("Enter colon command sub-mode\n");
/* Loop while we are in colon command mode */
while (vi->mode == SUBMODE_COLON)
{
/* Get the next character from the input */
ch = vi_getch(vi);
/* Handle the newly received character */
switch (ch)
{
case KEY_COLMODE_QUOTE: /* Quoted character follows */
{
/* Insert the next character unconditionally */
vi_cmdch(vi, vi_getch(vi));
}
break;
case ASCII_BS: /* Delete the character(s) before the cursor */
{
vi_cmdbackspace(vi);
}
break;
case ASCII_ESC: /* Escape exits colon mode */
{
vi_exitsubmode(vi, MODE_COMMAND);
}
break;
/* What do we do with carriage returns? line feeds? */
#if defined(CONFIG_EOL_IS_CR)
case '\r': /* CR terminates line */
{
vi_parsecolon(vi);
}
break;
#elif defined(CONFIG_EOL_IS_BOTH_CRLF)
case '\r': /* Wait for the LF */
break;
#endif
#if defined(CONFIG_EOL_IS_LF) || defined(CONFIG_EOL_IS_BOTH_CRLF)
case '\n': /* LF terminates line */
{
vi_parsecolon(vi);
}
break;
#endif
#ifdef CONFIG_EOL_IS_EITHER_CRLF
case '\r': /* Ether CR or LF terminates line */
case '\n':
{
vi_parsecolon(vi);
}
break;
#endif
default:
{
/* Ignore all but printable characters */
if (isprint(ch))
{
/* Insert the filtered character into the scratch buffer */
vi_cmdch(vi, ch);
}
}
break;
}
}
}
/****************************************************************************
* Find Data Entry Sub-Mode Functions
****************************************************************************/
/****************************************************************************
* Name: vi_findstring
*
* Description:
* Find the the string in the findstr buffer by searching for a matching
* sub-string in the text buffer, starting at the current cursor position.
*
****************************************************************************/
static bool vi_findstring(FAR struct vi_s *vi)
{
off_t pos;
int len;
vivdbg("findstr: \"%s\"\n", vi->findstr);
/* The search string is in the find buffer */
len = strlen(vi->findstr);
if (!len)
{
return false;
}
/* Search from the current cursor position forward for a
* matching sub-string. Stop loo
*/
for (pos = vi->curpos;
pos + len <= vi->textsize;
pos++)
{
/* Check for the matching sub-string */
if (strncmp(vi->text + pos, vi->scratch, len) == 0)
{
/* Found it... save the cursor position and
* return success.
*/
vi->curpos = pos;
return true;
}
}
/* If we get here, then the search string was not found anywhere after the
* current cursor position.
*/
return false;
}
/****************************************************************************
* Name: vi_parsefind
*
* Description:
* Find the string collected in the scratch buffer.
*
****************************************************************************/
static void vi_parsefind(FAR struct vi_s *vi)
{
/* Make certain that the scratch buffer contents are NUL terminated */
vi->scratch[vi->cmdlen] = '\0';
/* Is there anything in the scratch buffer? If not, then we will use the
* string from the previous find operation.
*/
vivdbg("scratch: \"%s\"\n", vi->scratch);
if (vi->cmdlen > 0)
{
/* Copy the new search string from the scratch to the find buffer */
strncpy(vi->findstr, vi->scratch, MAX_STRING - 1);
/* Make sure that the (possibly truncated) search string is NUL
* terminated
*/
vi->findstr[MAX_STRING - 1] = '\0';
}
/* Then attempt to find the string */
(void)vi_findstring(vi);
/* Exit the sub-mode and revert to command mode */
vi_exitsubmode(vi, MODE_COMMAND);
}
/****************************************************************************
* Name: vi_find_submode
*
* Description:
* Find command sub-mode of the command mode processing
*
****************************************************************************/
static void vi_find_submode(FAR struct vi_s *vi)
{
int ch;
vivdbg("Enter find sub-mode\n");
/* Loop while we are in find mode */
while (vi->mode == SUBMODE_FIND)
{
/* Get the next character from the input */
ch = vi_getch(vi);
/* Handle the newly received character */
switch (ch)
{
case KEY_FINDMODE_QUOTE: /* Quoted character follows */
{
/* Insert the next character unconditionally */
vi_cmdch(vi, vi_getch(vi));
}
break;
case ASCII_BS: /* Delete the character before the cursor */
{
vi_cmdbackspace(vi);
}
break;
case ASCII_ESC: /* Escape exits find mode */
{
vi_exitsubmode(vi, MODE_COMMAND);
}
break;
/* What do we do with carriage returns? line feeds? */
#if defined(CONFIG_EOL_IS_CR)
case '\r': /* CR terminates line */
{
vi_parsefind(vi);
}
break;
#elif defined(CONFIG_EOL_IS_BOTH_CRLF)
case '\r': /* Wait for the LF */
break;
#endif
#if defined(CONFIG_EOL_IS_LF) || defined(CONFIG_EOL_IS_BOTH_CRLF)
case '\n': /* LF terminates line */
{
vi_parsefind(vi);
}
break;
#endif
#ifdef CONFIG_EOL_IS_EITHER_CRLF
case '\r': /* Ether CR or LF terminates line */
case '\n':
{
vi_parsefind(vi);
}
break;
#endif
default:
{
/* Ignore all but printable characters */
if (isprint(ch))
{
/* Insert the filtered character into the scratch buffer */
vi_cmdch(vi, ch);
}
}
break;
}
}
}
/****************************************************************************
* Replace Text Sub-Mode Functions
****************************************************************************/
/****************************************************************************
* Name: vi_replacech
*
* Description:
* Replace the character at the current position. If the current position
* is the end of line, then insert the character.
*
****************************************************************************/
static void vi_replacech(FAR struct vi_s *vi, char ch)
{
vivdbg("curpos=%ld ch=%c[%02x]\n", vi->curpos, isprint(ch) ? ch : '.', ch);
/* Is there a newline at the current cursor position? */
if (vi->text[vi->curpos] == '\n')
{
/* Yes, then insert the new character before the newline */
vi_insertch(vi, ch);
}
else
{
/* No, just replace the character and increment the cursor position */
vi->text[vi->curpos++] = ch;
}
}
/****************************************************************************
* Name: vi_replacech_submode
*
* Description:
* Replace character command sub-mode of the command mode processing
*
****************************************************************************/
static void vi_replacech_submode(FAR struct vi_s *vi)
{
off_t end;
long nchars;
bool found = false;
int ch;
/* Get the number of characters to replace */
nchars = (vi->value > 0 ? vi->value : 1);
vivdbg("Enter replaces character(s) sub-mode: nchars=%d\n", nchars);
/* Are there that many characters left on the line to be replaced? */
end = vi_lineend(vi, vi->curpos);
if (vi->curpos + nchars > end)
{
vi_error(vi, g_fmtnotvalid);
vi_exitsubmode(vi, MODE_COMMAND);
vi_setmode(vi, MODE_COMMAND, 0);
}
/* Loop until we get the replacement character */
while (!found)
{
/* Get the next character from the input */
ch = vi_getch(vi);
/* Handle the newly received character */
switch (ch)
{
case KEY_FINDMODE_QUOTE: /* Quoted character follows */
{
/* Insert the next character unconditionally */
ch = vi_getch(vi);
found = true;
}
break;
case ASCII_ESC: /* Escape exits replace mode */
{
vi_setmode(vi, MODE_COMMAND, 0);
}
break;
/* What do we do with carriage returns? line feeds? */
#if defined(CONFIG_EOL_IS_CR)
case '\r': /* CR terminates line */
{
ch = '\n';
found = true;
}
break;
#elif defined(CONFIG_EOL_IS_BOTH_CRLF)
case '\r': /* Wait for the LF */
break;
#endif
#if defined(CONFIG_EOL_IS_LF) || defined(CONFIG_EOL_IS_BOTH_CRLF)
case '\n': /* LF terminates line */
{
found = true;
}
break;
#endif
#ifdef CONFIG_EOL_IS_EITHER_CRLF
case '\r': /* Ether CR or LF terminates line */
case '\n':
{
ch = '\n';
found = true;
}
break;
#endif
default:
{
/* Ignore all but printable characters and tab */
found = (isprint(ch) || ch == '\t');
}
break;
}
}
/* Now replace with the character nchar times */
while (nchars > 0)
{
vi_replacech(vi, ch);
}
/* Revert to command mode */
vi_setmode(vi, MODE_COMMAND, 0);
}
/****************************************************************************
* Insert and Replace Mode Functions
****************************************************************************/
/****************************************************************************
* Name: vi_insertch
*
* Description:
* Insert one character into the text buffer
*
****************************************************************************/
static void vi_insertch(FAR struct vi_s *vi, char ch)
{
vivdbg("curpos=%ld ch=%c[%02x]\n", vi->curpos, isprint(ch) ? ch : '.', ch);
/* Make space in the buffer for the new character */
if (vi_extendtext(vi, vi->curpos, 1))
{
/* Add the new character to the buffer */
vi->text[vi->curpos++] = ch;
}
}
/****************************************************************************
* Name: vi_insert_mode
*
* Description:
* Insert mode loop
*
****************************************************************************/
static void vi_insert_mode(FAR struct vi_s *vi)
{
int ch;
vivdbg("Enter insert mode\n");
/* Loop while we are in insert mode */
while (vi->mode == MODE_INSERT)
{
/* Make sure that the display reflects the current state */
vi_show(vi);
vi_setcursor(vi, vi->cursor.row, vi->cursor.column);
/* Get the next character from the input */
ch = vi_getch(vi);
/* Any key press clears the error message */
vi->error = false;
/* Handle the newly received character */
switch (ch)
{
case KEY_INSMODE_QUOTE: /* Quoted character follows */
{
/* Insert the next character unconditionally */
vi_insertch(vi, vi_getch(vi));
}
break;
case ASCII_DEL:
{
if (vi->curpos < vi->textsize)
{
vi_shrinktext(vi, vi->curpos, 1);
}
}
break;
case ASCII_BS:
{
if (vi->curpos)
{
vi_shrinktext(vi, --vi->curpos, 1);
}
}
break;
case ASCII_ESC: /* Escape exits insert mode */
{
vi_setmode(vi, MODE_COMMAND, 0);
}
break;
/* What do we do with carriage returns? */
#if defined(CONFIG_EOL_IS_CR)
case '\r': /* CR terminates line */
{
vi_insertch(vi, '\n');
}
break;
#elif defined(CONFIG_EOL_IS_BOTH_CRLF)
case '\r': /* Wait for the LF */
break;
#endif
#if defined(CONFIG_EOL_IS_LF) || defined(CONFIG_EOL_IS_BOTH_CRLF)
case '\n': /* LF terminates line */
{
vi_insertch(vi, '\n');
}
break;
#endif
#ifdef CONFIG_EOL_IS_EITHER_CRLF
case '\r': /* Ether CR or LF terminates line */
case '\n':
{
vi_insertch(vi, '\n');
}
break;
#endif
default:
{
/* Ignore all control characters except for tab and newline */
if (!iscntrl(ch) || ch == '\t')
{
/* Insert the filtered character into the buffer */
vi_insertch(vi, ch);
}
}
break;
}
}
}
/****************************************************************************
* Name: vi_replace_mode
*
* Description:
* Replace mode loop
*
****************************************************************************/
static void vi_replace_mode(FAR struct vi_s *vi)
{
off_t start = vi->curpos;
int ch;
vivdbg("Enter replace mode\n");
/* Loop until ESC is pressed */
while (vi->mode == MODE_REPLACE)
{
/* Make sure that the display reflects the current state */
vi_show(vi);
vi_setcursor(vi, vi->cursor.row, vi->cursor.column);
/* Get the next character from the input */
ch = vi_getch(vi);
/* Any key press clears the error message */
vi->error = false;
/* Handle the newly received character */
switch (ch)
{
case KEY_FINDMODE_QUOTE: /* Quoted character follows */
{
/* Replace the next character unconditionally */
vi_replacech(vi, ch);
}
break;
case ASCII_BS: /* Delete the character before the cursor */
{
if (vi->curpos > start)
{
vi_cursorleft(vi, vi->curpos, 1);
}
}
break;
case ASCII_ESC: /* Escape exits find mode */
{
vi_setmode(vi, MODE_COMMAND, 0);
}
break;
/* What do we do with carriage returns? line feeds? */
#if defined(CONFIG_EOL_IS_CR)
case '\r': /* CR terminates line */
{
vi_replacech(vi, '\n');
}
break;
#elif defined(CONFIG_EOL_IS_BOTH_CRLF)
case '\r': /* Wait for the LF */
break;
#endif
#if defined(CONFIG_EOL_IS_LF) || defined(CONFIG_EOL_IS_BOTH_CRLF)
case '\n': /* LF terminates line */
{
vi_replacech(vi, '\n');
}
break;
#endif
#ifdef CONFIG_EOL_IS_EITHER_CRLF
case '\r': /* Ether CR or LF terminates line */
case '\n':
{
vi_replacech(vi, '\n');
}
break;
#endif
default:
{
/* Ignore all but printable characters and TABs */
if (isprint(ch) || ch == '\t')
{
/* Insert the filtered character into the text buffer */
vi_replacech(vi, '\n');
}
}
break;
}
}
}
/****************************************************************************
* Command line processing
****************************************************************************/
/****************************************************************************
* Name: vi_showusage
*
* Description:
* Show command line arguments and exit.
*
****************************************************************************/
static void vi_release(FAR struct vi_s *vi)
{
if (vi)
{
if (vi->text)
{
free(vi->text);
}
if (vi->yank)
{
free(vi->yank);
}
free(vi);
}
}
/****************************************************************************
* Name: vi_showusage
*
* Description:
* Show command line arguments and exit.
*
****************************************************************************/
static void vi_showusage(FAR struct vi_s *vi, FAR const char *progname,
int exitcode)
{
fprintf(stderr, "\nUSAGE:\t%s [-c <columns] [-r <rows>] [<filename>]\n",
progname);
fprintf(stderr, "\nUSAGE:\t%s -h\n\n",
progname);
fprintf(stderr, "Where:\n");
fprintf(stderr, "\t<filename>:\n");
fprintf(stderr, "\t\tOptional name of the file to open\n");
fprintf(stderr, "\t-c <columns>:\n");
fprintf(stderr, "\t\tOptional width of the display in columns. Default: %d\n",
CONFIG_SYSTEM_VI_COLS);
fprintf(stderr, "\t-r <rows>:\n");
fprintf(stderr, "\t\tOptional height of the display in rows. Default: %d\n",
CONFIG_SYSTEM_VI_ROWS);
fprintf(stderr, "\t-h:\n");
fprintf(stderr, "\t\tShows this message and exits.\n");
/* Release all allocated resources and exit */
vi_release(vi);
exit(exitcode);
}
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: vi_main
*
* Description:
* The main entry point into vi.
*
****************************************************************************/
int vi_main(int argc, char **argv)
{
FAR struct vi_s *vi;
int option;
/* Allocate a vi state structure */
vi = (FAR struct vi_s *)zalloc(sizeof(struct vi_s));
if (!vi)
{
vi_error(vi, g_fmtallocfail);
return EXIT_FAILURE;
}
/* Initialize non-zero elements of the vi state structure */
vi->display.row = CONFIG_SYSTEM_VI_ROWS;
vi->display.column = CONFIG_SYSTEM_VI_COLS;
/* Parse command line arguments */
while ((option = getopt(argc, argv, ":c:r:h")) != ERROR)
{
switch (option)
{
case 'c': /* Display width in columns */
{
unsigned long value = strtoul(optarg, NULL, 10);
if (value <= UINT16_MAX)
{
vi->display.column = (uint16_t)value;
}
else
{
fprintf(stderr, "ERROR: Column value out of range: %ld\n",
value);
vi_showusage(vi, argv[0], EXIT_FAILURE);
}
}
break;
case 'r': /* Display width in columns */
{
unsigned long value = strtoul(optarg, NULL, 10);
if (value <= UINT16_MAX)
{
vi->display.row = (uint16_t)value;
}
else
{
fprintf(stderr, "ERROR: Row value out of range: %ld\n",
value);
vi_showusage(vi, argv[0], EXIT_FAILURE);
}
}
break;
case 'h':
{
vi_showusage(vi, argv[0], EXIT_SUCCESS);
}
break;
case ':':
{
fprintf(stderr, "ERROR: Missing parameter argument\n");
vi_showusage(vi, argv[0], EXIT_FAILURE);
}
break;
case '?':
default:
{
fprintf(stderr, "ERROR: Unrecognized parameter\n");
vi_showusage(vi, argv[0], EXIT_FAILURE);
}
break;
}
}
/* There may be one additional argument on the command line: The filename */
if (optind < argc)
{
/* Copy the file name into the file name buffer */
strncpy(vi->filename, argv[optind], MAX_STRING - 1);
/* Make sure that the (possibly truncated) file name is NUL terminated */
vi->filename[MAX_STRING - 1] = '\0';
/* Load the file into memory */
(void)vi_insertfile(vi, vi->filename);
/* Skip over the filename argument. There should nothing after this */
optind++;
}
if (optind != argc)
{
fprintf(stderr, "ERROR: Too many arguments\n");
vi_showusage(vi, argv[0], EXIT_FAILURE);
}
/* The editor loop */
for (;;)
{
/* We loop, processing each mode change */
vivdbg("mode=%d\n", vi->mode);
switch (vi->mode)
{
default:
case MODE_COMMAND: /* Command mode */
vi_cmd_mode(vi);
break;
case SUBMODE_COLON: /* Colon data entry in command mode */
vi_cmd_submode(vi);
break;
case SUBMODE_FIND: /* Find data entry in command mode */
vi_find_submode(vi);
break;
case SUBMODE_REPLACECH: /* Replace characters in command mode */
vi_replacech_submode(vi);
break;
case MODE_INSERT: /* Insert mode */
vi_insert_mode(vi);
break;
case MODE_REPLACE: /* Replace character(s) under cursor until ESC */
vi_replace_mode(vi);
break;
}
}
/* We won't get here */
}
|