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
|
# Lume Documentation
> **Lume 0.1 Alpha** — This documentation reflects the current alpha release. Behaviours described here are accurate as of this version but may change in future releases.
---
## Introduction
Lume is a terminal text editor written in C and Lua. It is small, fast, and deliberately limited in scope. It provides syntax highlighting, incremental search, multi-buffer editing, a kill ring, and autocompletion — the things that make a terminal editor genuinely comfortable to use — without venturing into the territory of language servers, linters, multi-line syntax analysis, or any other feature that requires the editor to form opinions about what your code means.
That last point is the heart of Lume's design. A great deal of effort in modern editors goes into understanding code at a semantic level — inferring types, resolving symbols, detecting errors before compilation. When this works, it is useful. When it does not, it produces false highlights, spurious warnings, autocorrections that fight you, and an editor that feels like it is constantly second-guessing you. For many languages and many workflows, it does not work reliably enough to be worth the cost. Lume takes the position that an editor's job is to help you write and navigate text, not to interpret it, and that a tool which does less but does it reliably is more useful than one which does more but does it inconsistently.
This does not mean Lume is minimal in the pejorative sense. The editing experience is modelled closely on Emacs — the keybindings, the kill ring, the minibuffer, the buffer model — because that model is exceptionally good for keyboard-driven editing. Lume simply applies that model without the layers of language intelligence that tend to go wrong.
**Philosophy.** The principles that guided Lume's development are:
- Code should be plainly readable without comments.
- As much logic as possible should live in Lua. C is used only to bridge to system interfaces — ncurses, the filesystem, the terminal — that Lua cannot reach on its own. The editor was designed Lua-first; the C layer was written to satisfy whatever the Lua layer needed.
- No external Lua libraries. The entire program is self-contained.
- Keep things simple and modular. Each subsystem should be easy to find, easy to read, and easy to replace.
- The user should always know what the editor is doing. Every significant action is reported in the status bar.
**Name and origins.** Lume began as LumoEdit, a name that combined *Lu* for Lua with *Lumo* — Proton's AI assistant, a nod to the fact that this program was written with AI assistance. LumoEdit was shortened first to *Lume* for a cleaner binary name, and the name stayed. It suits a program written to be used in candlelight at a terminal.
**Current state.** Lume 0.1 Alpha represents the core of the editor. The major systems — editing, search, buffers, highlighting, autocomplete, undo/redo — are all present and working. There are features that will come in future versions: block editing, improvements to automatic bracket pairing, and interface refinements. None of those are in this release. What is here is stable and complete enough to be used as a daily driver for the kinds of files it supports.
---
## Users
This section describes Lume as it works out of the box. No configuration files, no startup scripts, no modification of the source is assumed. Everything described here is the default behaviour of the editor as shipped.
If you are comfortable reading Lua and want to modify or extend the editor, see the [Developers](#developers) section. The two sections are intended to be read by the same people — most users of Lume will also be its developers, at least in a small way.
### Getting Started
Open Lume from the command line, passing any number of files as arguments:
```sh
lume
lume myfile.lua
lume main.c main.h util.c
```
With no arguments, Lume opens a single empty buffer. With one or more filenames, each file is opened into its own [buffer](#definitions-buffer). Files that do not yet exist are treated as new files and created on first save.
The interface has three regions: the **gutter** on the left (line numbers), the **text area** in the centre, and the **status bar** at the bottom. The status bar doubles as a minibuffer — it is where prompts, messages, and search input appear. There is no mode indicator because Lume has no modes. Every key either edits text or executes a command.
The column 80 position is marked with a subtle `|` character in the text area as a soft ruler. It does not enforce anything; it is purely visual.
### Keybinds
All keybinds use the following notation throughout this documentation:
| Notation | Meaning |
|---|---|
| `C-x` | Hold Control and press `x` |
| `M-x` | Press Escape, then press `x` |
| `C-x C-s` | The Control-x prefix chord, followed by Control-s |
The Meta key (`M-`) is entered by pressing and releasing Escape, then pressing the next key. On most terminal emulators, holding Alt will also work, though this depends on your terminal configuration.
#### Navigation
| Keybind | Action |
|---|---|
| `C-p` / `↑` | Move up one line |
| `C-n` / `↓` | Move down one line |
| `C-b` / `←` | Move left one character |
| `C-f` / `→` | Move right one character |
| `M-b` | Move backward one word |
| `M-f` | Move forward one word |
| `C-a` / `Home` | Move to start of line — see note below |
| `C-e` / `End` | Move to end of line |
| `PgUp` | Move up one screen page |
| `PgDn` | Move down one screen page |
| `M-<` | Jump to the top of the file |
| `M->` | Jump to the bottom of the file |
| `M-a` | Move to the start of the previous blank-line-delimited paragraph |
| `M-e` | Move to the start of the next blank-line-delimited paragraph |
| `M-g` | Prompt for a line number and jump to it |
| `M-m` | Jump to the bracket matching the one under the cursor |
| `C-l` | Recentre the view so the cursor line is in the middle of the screen |
**A note on `C-a` / `Home`.** Pressing `C-a` when the cursor is already past the first non-whitespace character moves it to the first non-whitespace character (the indentation point). Pressing it again — or pressing it when the cursor is already at the indentation point — moves it to column zero. This is intentional behaviour, not a quirk. It means you can get to either position with at most two presses, and for indented code you usually want the indentation point, not column zero.
Word movement (`M-b`, `M-f`) moves by alphanumeric word boundaries. The cursor lands at the start or end of a word, skipping over punctuation and whitespace.
#### Editing
| Keybind | Action |
|---|---|
| `Backspace` | Delete the character before the cursor — see note below |
| `C-d` / `Delete` | Delete the character after the cursor |
| `M-d` | Delete the word after the cursor |
| `M-Backspace` / `C-w` (no selection) | Delete the word before the cursor |
| `Tab` | Insert spaces to the next 2-column tab stop, or indent a [selection](#definitions-selection) |
| `Shift-Tab` | Remove up to 2 spaces of leading indentation from the current line, or dedent a selection |
| `Enter` | Insert a new line, carrying the current line's leading whitespace forward |
| `Shift-Enter` | Smart new line — see [Language Support](#language-support) |
| `M-p` | Move the current line (or selected lines) up one line |
| `M-n` | Move the current line (or selected lines) down one line |
| `M-;` | Toggle comment on the current line or selection |
| `M-c` | Duplicate the current line |
**A note on `Backspace`.** When the cursor is in a position where all text to its left on the line is whitespace, Backspace will delete two spaces at once rather than one. This makes unindenting by hand feel like deleting a tab stop — it is seamless when you are working inside indented blocks. When there is any non-whitespace content to the left of the cursor, Backspace deletes exactly one character (or one multi-byte UTF-8 sequence), as you would expect.
**Auto-pairing.** Typing an opening bracket or quote — `(`, `[`, `{`, or `"` — will automatically insert the matching closing character and leave the cursor between the two. If the cursor is already sitting on the closing character of a pair, typing that character will move the cursor through it rather than inserting a duplicate. This keeps the paired structure intact as you type through it.
#### Selection and the Kill Ring
Lume uses a *kill ring* rather than a simple clipboard. The kill ring is a circular buffer that holds multiple killed (cut) pieces of text. You can cycle through it after pasting to retrieve earlier kills. This is described in detail in [Kill Ring](#definitions-kill-ring).
| Keybind | Action |
|---|---|
| `C-Space` | Set the mark at the current cursor position, beginning a selection. Press again to clear the mark |
| `C-g` | Cancel — clears the mark, dismisses autocomplete, and cancels any pending prefix |
| `M-w` | Copy the selection to the kill ring without deleting it |
| `C-k` | Kill (cut) from the cursor to end of line, or kill the entire selection if one is active |
| `C-w` | Kill the selection if one is active; otherwise delete the word before the cursor |
| `C-y` | Yank (paste) the most recent kill ring entry at the cursor position |
| `M-y` | After a yank, cycle to the previous kill ring entry, replacing the just-yanked text |
| `Tab` (with selection) | Indent all lines in the selection by 2 spaces |
| `Shift-Tab` (with selection) | Dedent all lines in the selection by up to 2 spaces |
A [selection](#definitions-selection) is the region between the **mark** and the cursor. The mark is set with `C-Space` and remains fixed while you move the cursor. The selected region is highlighted. Most editing commands that affect a region — killing, copying, indenting — operate on the active selection when one exists, and fall back to line-level or character-level behaviour when no selection is active.
`C-y` also synchronises with the system clipboard on paste — if the system clipboard contains something that is not already in the kill ring, it is pushed onto the ring first. This means yanking after copying from another application works as expected.
#### Search
| Keybind | Action |
|---|---|
| `C-s` | Begin incremental search forward |
| `C-s` (during search) | Move to the next match |
| `C-r` (during search) | Move to the previous match (reverse) |
| `Enter` (during search) | Confirm and exit search, leaving the cursor at the current match |
| `C-g` (during search) | Cancel and return the cursor to where it was before searching |
| `M-%` | Search and replace across the entire buffer |
| `C-r` (normal mode) | Recursive grep — search across all files in the directory tree |
Search is described fully in [Searching](#searching).
#### Buffers
| Keybind | Action |
|---|---|
| `C-x C-f` | Open a file into a new buffer (with tab-completion in the prompt) |
| `C-x C-s` | Save the current buffer |
| `C-x C-r` | Revert the current buffer from disk, discarding unsaved changes |
| `C-x C-k` | Kill (close) the current buffer |
| `C-x C-b` | Open the buffer picker |
| `C-]` | Switch to the next buffer |
| `C-\` | Switch to the previous buffer |
#### Miscellaneous
| Keybind | Action |
|---|---|
| `C-/` | Undo |
| `M-/` | Redo |
| `M-x` | Evaluate a Lua expression in the minibuffer and display the result |
| `M-!` | Run a shell command and display the first line of output in the status bar |
| `C-x C-c` | Quit. Prompts for confirmation if any buffer has unsaved changes |
---
### Language Support
Lume provides syntax highlighting, comment toggling, and (for some languages) smart indentation for a set of built-in languages. All language support is registered through a single interface — [`register_filetype`](#register_filetype) — and can be extended in Lua without touching the C layer. See [Adding a Syntax Highlighter (Basic)](#adding-a-syntax-highlighter-basic) if you want to add support for another language.
An important thing to understand about Lume's highlighter model: highlighting is computed one line at a time with no state carried between lines. This is a deliberate design choice. Multi-line highlighting — tracking whether you are inside a block comment, a heredoc, or a multi-line string — requires the editor to maintain and synchronise parse state with the buffer. That state can drift out of sync when edits happen in the middle of a file, producing incorrect highlighting that is worse than no highlighting at all. Lume avoids this problem entirely by limiting itself to what can be determined from a single line. For most practical code, this is perfectly sufficient. For the exceptions — block comments, multi-line strings — those regions will simply appear uncoloured, which is an honest representation of uncertainty rather than a misleading one.
Language detection happens in two ways: by file extension, and by shebang line. Both are checked when a file is opened, and the file extension takes priority.
#### Lua
**Detected by:** `.lua` extension; `lua` shebang.
**Comment prefix:** `--`
Lua receives the most detailed highlighting of any supported language. Keywords are divided into three semantic categories, each with a distinct colour:
- *Definition keywords* (`function`, `local`) — these introduce names into scope.
- *Logic keywords* (`if`, `then`, `else`, `elseif`, `end`, `for`, `while`, `do`, `repeat`, `until`, `return`, `break`, `goto`, `in`, `not`, `and`, `or`) — these control flow and boolean logic.
- *Value keywords* (`true`, `false`, `nil`) — these are literal values.
Additionally, string literals (single and double quoted), numeric literals (including hex), operators and punctuation, and single-line `--` comments are all highlighted.
Lua also has **smart indentation** via `Shift-Enter`. When the cursor is at the end of a line that opens a block — a `function` definition, an `if ... then`, a `for ... do`, a `while ... do`, a `do` statement, a `repeat`, or a table literal opened with `{` — pressing `Shift-Enter` inserts a new indented line and, where appropriate, a closing keyword (`end`, `until`, or `}`) on the line below. For `else` and `elseif`, only the indented line is added (the block is already closed by the outer `if`'s `end`). Regular `Enter` always behaves the same regardless of context: it inserts a new line with the same leading whitespace as the current line.
#### C
**Detected by:** `.c`, `.h`, `.cc`, `.cpp` extensions.
**Comment prefix:** `//`
Highlights: C keywords and type names, string and character literals, numeric literals (including `0x` hex, and suffixes `u`, `U`, `l`, `L`), `//` line comments, and operators and punctuation.
> Block comments (`/* */`) span multiple lines and are not highlighted under Lume's single-line model. Lines inside a block comment will appear in the default text colour.
#### Shell
**Detected by:** `.sh`, `.bash`, `.zsh` extensions; `bash`, `sh`, or `zsh` shebangs.
**Comment prefix:** `#`
Highlights: shell keywords (`if`, `then`, `else`, `fi`, `for`, `while`, `do`, `done`, `case`, `esac`, `function`, `return`, `local`, `export`, `echo`, `exit`, and others), string literals, the `$` sigil, numeric literals, and `#` comments.
#### Adding More
Any language can be added by calling `register_filetype` in `main.lua`. No changes to `main.c` are required. See the [Adding a Syntax Highlighter (Basic)](#adding-a-syntax-highlighter-basic) and [Adding a Syntax Highlighter (Advanced)](#adding-a-syntax-highlighter-advanced) guides for a full walkthrough.
---
### Colour Scheme
Lume uses your terminal's colour palette directly via ncurses colour pairs. It does not embed its own colour values — the exact colours you see depend on your terminal emulator's theme. The numbers below are standard ncurses colour indices (0–15).
All colour pairs use a transparent background (`-1`, i.e. inherit the terminal background) unless otherwise noted. Pairs with a specific background colour are used for interactive highlighting — selected text, search matches, matching brackets, and menu items — to make them visually distinct from the surrounding content.
| Name | Pair | Foreground | Background | Used for |
|---|---|---|---|---|
| `KEYWORD` | 2 | 6 | default | General language keywords (C, Shell) |
| `KEYWORD_DEF` | 13 | 6 | default | Definition keywords (`function`, `local` in Lua) |
| `KEYWORD_LOGIC` | 14 | 4 | default | Logic/control keywords in Lua |
| `KEYWORD_VALUE` | 15 | 1 | default | Value literals (`true`, `false`, `nil`) |
| `STRING` | 3 | 2 | default | String literals |
| `COMMENT` | 4 | 8 | default | Comments |
| `NUMBER` | 5 | 9 | default | Numeric literals |
| `OPERATOR` | 6 | 3 | default | Operators and punctuation |
| `MATCH_BR` | 7 | 3 | 1 | Bracket under cursor and its matching bracket |
| `MENU_SEL` | 8 | 0 | 6 | Selected item in the autocomplete menu |
| `SELECTION` | 9 | 0 | 6 | Active text selection region |
| `GUTTER` | 10 | 8 | default | Line number gutter |
| `RULER` | 11 | 8 | default | Column 80 ruler mark |
| `SEARCH_MATCH` | 12 | 0 | 3 | Search match highlights |
Colour indices 1–9 correspond to the standard ANSI colours: 1 = red, 2 = green, 3 = yellow, 4 = blue, 6 = cyan, 8 = bright black (dark grey), 9 = bright red. These will appear as whatever those slots are set to in your terminal theme.
---
### Autocomplete
Lume provides word-completion that activates automatically as you type. When you have typed at least two characters of a word, Lume searches all open buffers for words that begin with what you have typed and, if it finds any, displays a small popup menu near the cursor. The menu dismisses automatically when you continue typing past a completion or move the cursor.
The completion search collects candidates from three sources, ranked in priority order from highest to lowest:
1. **Keywords of the current filetype.** Language keywords that match the prefix are weighted highest, so that `fun` in a Lua file will offer `function` prominently.
2. **Words in the current buffer.** Matches from the file you are actively editing rank above matches from other files, on the basis that you are more likely to want a word you have already used in this file.
3. **Words in other open buffers of the same filetype.** Matches from other buffers of the same language rank lowest.
Within each source, candidates are sorted by frequency — words you have used more often appear higher in the menu. The menu shows up to 8 candidates at a time.
The menu can appear either above or below the cursor, depending on how much screen space is available. The arrow key directions adjust to match: the menu always navigates in a consistent visual direction regardless of which side it is on.
| Keybind | Action |
|---|---|
| `Tab` | Accept the currently highlighted completion |
| `↑` / `C-p` | Move the selection up the menu |
| `↓` / `C-n` | Move the selection down the menu |
| `C-g` | Dismiss the completion menu without accepting anything |
Any other key dismisses the menu and processes the key normally — typing a space or a punctuation character, for instance, dismisses the menu and inserts that character.
---
### Searching
#### Incremental Search
Press `C-s` to enter incremental search. As you type, Lume highlights all matches in the buffer and keeps the cursor at the nearest match forward from where you started. The status bar shows the current match index and total count, e.g. `Search: fun [3/12]`.
- Press `C-s` again to advance to the next match.
- Press `C-r` to step backward to the previous match.
- Press `Enter` to confirm and leave the cursor at the current match.
- Press `C-g` to cancel and return the cursor to where it was before you started searching.
Search is **smart-case**: if your search term is entirely lower-case, the search is case-insensitive. If your term contains any upper-case character, the search becomes case-sensitive. This means you can search case-insensitively by default and opt into case-sensitivity simply by capitalising a character.
Matches are highlighted with the `SEARCH_MATCH` colour across the entire buffer while search is active. When you confirm or cancel, the highlights are cleared.
When you confirm a search, the matched region is left as an active [selection](#definitions-selection), which you can then operate on immediately — kill it, copy it, replace it.
#### Recursive Grep
Press `C-r` in normal editing mode to open the recursive grep interface. You will be prompted for a search term in the minibuffer, and Lume will then walk the entire directory tree from the current working directory, searching every file it finds. Results are shown in a full-screen list displaying the filename, line number, and matching line with syntax highlighting applied.
Navigate the results list with `↑`/`↓` or `C-p`/`C-n`. Press `Enter` to jump directly to the matching line, opening the file in a new buffer if it is not already open. Press `C-g` to return to the editor without jumping.
Grep search also uses smart-case.
#### Search and Replace
Press `M-%` to open search and replace. You will be prompted first for the pattern to find, then for the replacement text. Both are plain text — no regular expression syntax. The replacement is applied to every occurrence in the buffer at once, and the number of replacements made is reported in the status bar. The operation is undoable as a single step with `C-/`.
If a selection is active when you press `M-%`, the selected text is used as the default search term.
---
## Developers
This section is the technical reference for Lume's internals. It describes every function, option, and subsystem in the codebase in enough detail that you should be able to understand, modify, and extend any part of the editor after reading it.
Do not be put off by the label. This section is written for the same audience as the Users section — people who use Lume and want to understand how it works. The editor is deliberately transparent. The entire program is two files: `main.lua`, where the editor logic lives, and `main.c`, which provides the system interface. There is no build system beyond a C compiler, no package manager, and no hidden configuration. If you can read Lua, you can read the whole editor.
### Definitions
#### Editor
The *editor* in Lume is a single Lua table, `editor`, that holds all of the state for the currently active editing session. It contains the text of the current buffer (as a table of line strings), cursor position, scroll offsets, undo and redo stacks, the kill ring, search state, autocomplete state, and the list of all open buffers. It also contains all of the editing methods — `editor:insert_char`, `editor:delete_char`, `editor:save`, and so on.
Because Lua tables are reference types, passing `editor` to a function gives that function full access to the entire editor state. Most internal functions take `ed` as their first parameter for this reason.
The `editor` table's initial field values serve as the default options and configuration for the editor. See the [editor option](#option-editor) entry for the full list of fields and their defaults.
The editor is exposed as the global `_G.ed` so that code evaluated through `M-x` can access and modify it at runtime.
#### Buffer
A *buffer* is a self-contained unit of editable text, associated with a filename and a filetype. Each open file corresponds to one buffer. Buffers are stored in the `editor.buffers` table and have the same structure as the editor itself — they hold the line table, cursor position, scroll offset, undo stack, modification flag, and all other per-file state.
Only one buffer is active (displayed and editable) at a time. When you switch buffers, the editor's state is saved into the current buffer's entry in `editor.buffers`, and the new buffer's state is loaded back into the editor. This is done by [`save_editor_to_buffer`](#save_editor_to_buffer) and [`load_buffer_to_editor`](#load_buffer_to_editor).
Buffers are created by [`make_buffer`](#make_buffer). Each buffer carries its own highlighter function, keyword list, indentation completers, and comment prefix — these are set when the buffer is created based on the detected filetype, and remain fixed for the lifetime of the buffer.
#### Selection
A *selection* is the region of text between the **mark** and the cursor. The mark is a fixed position set with `C-Space`. Moving the cursor while the mark is set extends or contracts the selection. The mark and cursor together define an ordered range — it does not matter which is earlier in the file; the selection always covers the text between them.
There are two kinds of selection:
**Normal selections** are set explicitly by the user with `C-Space`. They persist until cleared with `C-g`, until a kill or copy operation consumes them, or until an insert operation replaces their content.
**Ephemeral selections** are created automatically by incremental search (`C-s`). When search finds a match, it sets the mark at the start of the match and moves the cursor to the end, creating a selection covering the match. The `ephemeral` flag on the editor marks this selection as temporary. Any action that is not a search operation — moving the cursor, typing, killing — clears an ephemeral selection automatically via [`clear_ephemeral`](#clear_ephemeral). This allows you to immediately act on a search result (delete it, copy it, overtype it) without having to manually clear the selection first.
The functions [`sel_ordered`](#sel_ordered), [`get_selection_text`](#get_selection_text), [`delete_selection`](#delete_selection), [`indent_selection`](#indent_selection), and [`col_in_selection`](#col_in_selection) form the complete interface for working with selections.
#### Highlighter
A *highlighter* is a Lua function that takes a single line of text as a string and returns a list of *spans* — each span describing a contiguous coloured region of that line. Highlighters are registered per-filetype via [`register_filetype`](#register_filetype) and called during rendering by [`editor:draw`](#editordraw).
The key constraint of Lume's highlighter model is that each call receives exactly one line and returns spans for that line only. No state is passed between calls, and no state is stored between lines. This means the highlighter cannot know whether it is inside a multi-line block comment or a multi-line string. This is intentional: a stateless highlighter is always correct for what it can see, whereas a stateful one can go wrong and then stay wrong for the rest of the file. An un-highlighted comment is better than a file that is half-incorrectly highlighted because an edit on line 40 confused the parser's state.
Spans are produced by calling [`push_span`](#push_span) and converted to a per-byte colour map by [`spans_to_color_map`](#spans_to_color_map) before rendering.
#### Kill Ring
The *kill ring* is a fixed-capacity circular list of text strings that have been killed (cut). It is stored in `editor.kill_ring` with a current-position index in `editor.kill_ring_idx`. The maximum number of entries is controlled by [`KILL_RING_MAX`](#kill_ring_max).
Any operation that removes text intentionally — `C-k`, `C-w`, `M-d`, `M-Backspace` — pushes the removed text onto the kill ring. `C-y` (yank) pastes the most recent entry. `M-y` (yank-pop) replaces the just-yanked text with the previous entry in the ring, cycling backward through the history. This allows you to retrieve any of the last `KILL_RING_MAX` killed strings, not just the most recent one.
The kill ring is also synchronised with the system clipboard. When text is killed, it is written to the clipboard via [`clipboard_write`](#clipboard_write). When yanking, if the system clipboard contains text that is not already the current kill ring entry, it is pushed onto the ring first. This means copying from another application and then pressing `C-y` in Lume works as expected.
#### Autocompletion
Autocompletion in Lume is *word completion*: it finds words in the open buffers that begin with the characters you have already typed. It does not analyse syntax, infer types, or consult an external language server. It is fast, always available, and never wrong in the sense of suggesting something that does not exist somewhere in your working set of files.
The completion state is stored in `editor.ac`. When the field is non-nil, the completion menu is visible. The structure holds the list of candidates, the currently selected index, and the length of the prefix that was typed (needed to compute how much to insert when a completion is accepted). The full mechanism is described under [`ac_build`](#ac_build), [`ac_apply`](#ac_apply), and [`ac_handle`](#ac_handle).
---
### Lua Reference
#### Logging
Lume includes a simple file-based logging system for development. It is disabled by default and has no effect on normal use.
##### Options
---
###### `DEBUG`
**Type:** `boolean` — **Default:** `false`
When `false`, all calls to [`log`](#log) are no-ops and no log file is opened or written. Set to `true` at the top of `main.lua` to enable logging, for example when debugging a new feature.
---
###### `LOG_FILE`
**Type:** `string` — **Default:** `"lume.log"`
The path of the log file. Only used when `DEBUG` is `true`. The file is opened in append mode on the first call to `log`, so multiple sessions accumulate in the same file. If the file cannot be opened, logging silently stops.
---
##### Functions
---
###### `log(msg)`
```lua
log(msg: any) -> nil
```
Writes a timestamped log entry to [`LOG_FILE`](#debug). The message is passed through `tostring`, so any Lua value can be logged. The timestamp is in UTC `HH:MM:SS` format.
When [`DEBUG`](#debug) is `false`, this function returns immediately and does nothing. The file handle is opened lazily on the first call and shared for the lifetime of the session, then closed by [`close_log`](#close_log).
| Parameter | Type | Description |
|---|---|---|
| `msg` | `any` | The value to log. Passed through `tostring`. |
---
###### `close_log()`
```lua
close_log() -> nil
```
Closes the log file handle if it is open. Called unconditionally by [`editor:cleanup`](#editorcleaning) on exit, so that log data is flushed even when the session ends due to an error.
---
#### Unicode
Lume works in UTF-8 throughout. The terminal input (`wget_wch` in ncurses) returns Unicode code points, and all text stored in buffers is UTF-8 encoded. The functions in this section are the foundation of correct cursor movement, display width calculation, and character insertion.
The fundamental challenge with UTF-8 in a text editor is that byte positions and display positions are not the same thing. A single character might occupy 1 to 4 bytes in the string. East Asian characters (CJK, Hangul, etc.) occupy 2 display columns rather than 1. Lume handles both of these correctly at the level of these functions, so that all higher-level code — drawing, cursor movement, selection — can operate on byte offsets without having to reason about encoding directly.
##### Functions
---
###### `utf8_char_head(b)`
```lua
utf8_char_head(b: integer) -> boolean
```
Returns `true` if byte `b` is the first byte of a UTF-8 character sequence. A byte is a sequence head if it is less than `0x80` (ASCII) or greater than or equal to `0xC0` (a multi-byte lead byte). Continuation bytes (`0x80`–`0xBF`) return `false`.
This is used by [`byte_prev`](#byte_prev) to walk backward through a UTF-8 string correctly: decrement the byte index until `utf8_char_head` returns `true`.
| Parameter | Type | Description |
|---|---|---|
| `b` | `integer` | A raw byte value (0–255) |
**Returns:** `true` if `b` is a sequence head, `false` if it is a continuation byte.
---
###### `utf8_char_len(b)`
```lua
utf8_char_len(b: integer) -> integer
```
Returns the byte length of the UTF-8 character whose first byte is `b`: 1 for ASCII (`< 0x80`), 1 for invalid continuation bytes (treated defensively), 2 for `0xC0–0xDF`, 3 for `0xE0–0xEF`, and 4 for `0xF0–0xFF`.
| Parameter | Type | Description |
|---|---|---|
| `b` | `integer` | The first byte of a UTF-8 sequence |
**Returns:** The byte length of the sequence (1–4).
---
###### `utf8_decode_at(s, i)`
```lua
utf8_decode_at(s: string, i: integer) -> (cp: integer|nil, next_i: integer)
```
Decodes the UTF-8 character starting at byte position `i` in string `s`. Returns the Unicode code point and the byte position of the start of the next character. If `i` is beyond the end of the string, returns `nil` and `i + 1`.
Missing continuation bytes are substituted with `0x80`, so malformed UTF-8 does not cause an error — it produces a replacement code point and advances past the bad byte.
This is the core iteration primitive used by the drawing code and display-width calculations. A typical forward iteration over a string looks like:
```lua
local i = 1
while i <= #s do
local cp, next_i = utf8_decode_at(s, i)
if not cp then break end
-- use cp here
i = next_i
end
```
| Parameter | Type | Description |
|---|---|---|
| `s` | `string` | The string to decode from |
| `i` | `integer` | Byte index of the start of the character (1-based) |
**Returns:** The code point as an integer, and the byte index of the next character.
---
###### `cp_to_utf8(cp)`
```lua
cp_to_utf8(cp: integer) -> string
```
Encodes a Unicode code point as a UTF-8 byte string. Handles the full range (1–4 bytes). Used whenever a character is inserted from keyboard input — `get_wchar` returns a code point, and `cp_to_utf8` converts it to the bytes that are stored in the buffer.
| Parameter | Type | Description |
|---|---|---|
| `cp` | `integer` | A Unicode code point |
**Returns:** A 1–4 byte string containing the UTF-8 encoding.
---
###### `cp_display_width(cp)`
```lua
cp_display_width(cp: integer) -> integer
```
Returns the number of terminal columns that code point `cp` occupies when displayed. Returns 0 for control characters below `0x20`, 2 for East Asian wide characters (CJK unified ideographs, Hangul, full-width forms, emoji blocks, and others), and 1 for everything else.
The ranges checked for double-width characters are a practical subset of the Unicode standard, covering the character sets most commonly encountered in source code and documentation.
| Parameter | Type | Description |
|---|---|---|
| `cp` | `integer` | A Unicode code point |
**Returns:** 0, 1, or 2.
---
###### `line_display_width(line, byte_limit)`
```lua
line_display_width(line: string, byte_limit: integer|nil) -> integer
```
Computes the total display width (in terminal columns) of a line string up to — but not including — byte position `byte_limit`. If `byte_limit` is `nil`, the entire line is measured.
Used by the horizontal scroll logic to convert between byte cursor positions and display column positions.
| Parameter | Type | Description |
|---|---|---|
| `line` | `string` | A line of text |
| `byte_limit` | `integer` or `nil` | Stop before this byte index. Pass `nil` to measure the whole string. |
**Returns:** The display width in terminal columns.
---
###### `byte_prev(s, pos)`
```lua
byte_prev(s: string, pos: integer) -> integer
```
Returns the byte index of the start of the UTF-8 character immediately before byte position `pos` in string `s`. Walks backward from `pos - 1` until it finds a byte that satisfies [`utf8_char_head`](#utf8_char_head). Returns 0 if already at or before the start.
Note that `pos` here is a 0-based byte offset (the convention used throughout the editor for cursor positions), not a 1-based Lua string index.
| Parameter | Type | Description |
|---|---|---|
| `s` | `string` | The string |
| `pos` | `integer` | Current byte offset (0-based) |
**Returns:** The byte offset of the previous character's first byte.
---
###### `byte_next(s, pos)`
```lua
byte_next(s: string, pos: integer) -> integer
```
Returns the byte offset of the start of the UTF-8 character immediately after the character at byte offset `pos`. Uses [`utf8_char_len`](#utf8_char_len) to determine how far to advance. Clamps to `#s` at the end of the string.
| Parameter | Type | Description |
|---|---|---|
| `s` | `string` | The string |
| `pos` | `integer` | Current byte offset (0-based) |
**Returns:** The byte offset of the next character.
---
###### `wch()`
```lua
wch() -> integer|nil
```
Reads one character of input from the terminal by calling the C-side `get_wchar`. Returns the Unicode code point of the key pressed, or `nil` if no input is available or an error occurred. Special keys (arrows, function keys, etc.) return ncurses key codes rather than Unicode code points; these are matched against the constants in [`KEY`](#option-key).
`wch` is the single input primitive used everywhere in Lume. All keyboard handling — the main loop, prompts, the search interface, the buffer picker — calls `wch` to read input.
**Returns:** An integer key code, or `nil` on error.
---
#### Text Handling
Utility functions for working with strings and text content at a level above raw bytes.
##### Functions
---
###### `get_lines(text)`
```lua
get_lines(text: string) -> table
```
Splits a string into a table of lines by splitting on `\n`. The trailing newline of the last line is not included as an empty entry. If the result would be an empty table (empty input), a table containing one empty string is returned instead, ensuring that the buffer always contains at least one line.
This is used when loading a file and when splitting pasted text during [`editor:yank`](#editoryank).
| Parameter | Type | Description |
|---|---|---|
| `text` | `string` | A multi-line string |
**Returns:** A table of line strings (no newline characters).
---
###### `lines_to_buffer(lines)`
```lua
lines_to_buffer(lines: table) -> string
```
Joins a table of line strings back into a single string, inserting `\n` between each line. The inverse of [`get_lines`](#get_lines). Used when saving a buffer to disk via [`editor:save`](#editorsave). Note that `editor:save` appends a final `\n` after calling this function, so the saved file always ends with a newline.
| Parameter | Type | Description |
|---|---|---|
| `lines` | `table` | A table of line strings |
**Returns:** A single newline-joined string.
---
###### `leading_spaces(line)`
```lua
leading_spaces(line: string) -> string
```
Returns the leading whitespace of `line` — the prefix of spaces and tabs before the first non-whitespace character. Returns an empty string if the line starts with a non-whitespace character or is empty.
Used throughout the editor to carry indentation forward when inserting new lines.
| Parameter | Type | Description |
|---|---|---|
| `line` | `string` | A line of text |
**Returns:** The leading whitespace string.
---
###### `trim_left(s)`
```lua
trim_left(s: string) -> string
```
Returns `s` with all leading whitespace removed. Used by [`editor:insert_newline_smart`](#editorinsert_newline_smart) to check a line's content against indentation completer patterns, which are written against the trimmed content (e.g. `"^function%s"`, not `"^%s*function%s"`).
| Parameter | Type | Description |
|---|---|---|
| `s` | `string` | A string |
**Returns:** The string with leading whitespace stripped.
---
###### `escape_pattern(s)`
```lua
escape_pattern(s: string) -> string
```
Escapes all Lua pattern special characters in `s` so that the result can be used as a literal string in `string.find` or `string.gsub`. The special characters escaped are: `( ) . % + - * ? [ ] ^ $`.
Used by [`editor:search_replace`](#editorsearch_replace) and [`editor:isearch`](#editorisearch) to treat the user's search input as a plain text string rather than a pattern. Lume's search does not expose pattern syntax to the user.
| Parameter | Type | Description |
|---|---|---|
| `s` | `string` | A raw search term |
**Returns:** The term with pattern metacharacters escaped.
---
###### `escape_replacement(s)`
```lua
escape_replacement(s: string) -> string
```
Escapes `%` characters in a replacement string so that they are treated literally by `string.gsub`. Without this, a replacement string containing `%1` would be interpreted as a capture reference.
Used by [`editor:search_replace`](#editorsearch_replace) alongside [`escape_pattern`](#escape_pattern).
| Parameter | Type | Description |
|---|---|---|
| `s` | `string` | A raw replacement string |
**Returns:** The string with `%` characters escaped.
---
#### File Handling
Functions for working with the filesystem: path manipulation, directory traversal, and file content search.
##### Functions
---
###### `path_join(a, b)`
```lua
path_join(a: string, b: string) -> string
```
Joins two path components, ensuring exactly one `/` between them. Trailing slashes are stripped from `a` and leading slashes from `b` before joining. This is used throughout the file-handling code rather than simple concatenation, to avoid double-slash paths.
| Parameter | Type | Description |
|---|---|---|
| `a` | `string` | The left path component (e.g. a directory) |
| `b` | `string` | The right path component (e.g. a filename) |
**Returns:** The joined path.
---
###### `normalize_path(p)`
```lua
normalize_path(p: string) -> string
```
Applies lightweight normalisation to a path string: collapses consecutive slashes (`//` → `/`) and removes a leading `./`. This is not a full path canonicalisation — it does not resolve `..` components or symlinks — but it is enough to ensure that paths entered by the user and paths constructed internally compare equal when they refer to the same file.
| Parameter | Type | Description |
|---|---|---|
| `p` | `string` | A file path |
**Returns:** The normalised path.
---
###### `collect_files(dir, results)`
```lua
collect_files(dir: string, results: table) -> nil
```
Recursively walks the directory tree rooted at `dir` and appends the path of every regular file found to the `results` table. Directories are traversed in the order `list_dir` returns them. Hidden files and directories (those whose names begin with `.`) are skipped entirely.
This is called by [`editor:recursive_search`](#editorrecursive_search) to build the list of files to search through.
| Parameter | Type | Description |
|---|---|---|
| `dir` | `string` | The root directory to walk |
| `results` | `table` | An existing table to append file paths to |
**Returns:** Nothing. Results are appended to the `results` table in place.
---
###### `search_in_file(path, pattern)`
```lua
search_in_file(path: string, pattern: string) -> table
```
Loads the file at `path` and searches every line for occurrences of `pattern` as a plain string. Returns a table of match records, each containing the fields `file` (the path), `line` (1-based line number), `col` (1-based column), and `text` (the full content of the matching line).
If the file cannot be loaded, an empty table is returned silently. If the pattern is entirely lower-case, the search is case-insensitive (smart-case); otherwise it is case-sensitive.
| Parameter | Type | Description |
|---|---|---|
| `path` | `string` | Path to the file to search |
| `pattern` | `string` | The plain-text search term |
**Returns:** A table of match records `{file, line, col, text}`.
---
#### Copy, Paste, and the Kill Ring
These functions implement Lume's kill ring — the multi-entry clipboard that is the core of Emacs-style cut-and-paste.
##### Options
---
###### `KILL_RING_MAX`
**Type:** `integer` — **Default:** `30`
The maximum number of entries the kill ring will hold. When a new entry is pushed and the ring is full, the oldest entry is removed. Increase this if you want a longer history; decrease it to reduce memory use (though kill ring entries are just strings, so the cost is minimal).
---
##### Functions
---
###### `clipboard_write(text)`
```lua
clipboard_write(text: string) -> nil
```
Writes `text` to the system clipboard by piping it to `pbcopy`. If `pbcopy` is unavailable (i.e. not on macOS), this silently does nothing. On Linux systems, you may wish to replace this with an `xclip` or `wl-copy` invocation. This is one of the few places where Lume makes a platform assumption.
| Parameter | Type | Description |
|---|---|---|
| `text` | `string` | The text to place on the clipboard |
---
###### `clipboard_read()`
```lua
clipboard_read() -> string
```
Reads the current system clipboard content by reading from `pbpaste`. Returns an empty string if unavailable. Called during [`editor:yank`](#editoryank) to check whether the clipboard contains something newer than the kill ring's current entry.
**Returns:** The clipboard contents as a string, or `""`.
---
###### `kill_ring_push(ed, text)`
```lua
kill_ring_push(ed: table, text: string) -> nil
```
Pushes `text` onto the kill ring. If `text` is empty or identical to the most recent entry, the push is skipped (to avoid duplicates from repeated kills of the same content). If the ring is at capacity, the oldest entry is removed from the front. The current index is updated to point to the new entry. Also calls [`clipboard_write`](#clipboard_write) to synchronise with the system clipboard.
| Parameter | Type | Description |
|---|---|---|
| `ed` | `table` | The editor state |
| `text` | `string` | The text to push |
---
###### `kill_ring_current(ed)`
```lua
kill_ring_current(ed: table) -> string|nil
```
Returns the kill ring entry at the current index, or `nil` if the ring is empty.
| Parameter | Type | Description |
|---|---|---|
| `ed` | `table` | The editor state |
**Returns:** The current kill ring entry, or `nil`.
---
###### `kill_ring_cycle(ed)`
```lua
kill_ring_cycle(ed: table) -> string|nil
```
Steps the kill ring index backward by one (wrapping around), and returns the entry at the new index. Used by [`editor:yank_pop`](#editoryank_pop) to implement `M-y`. Returns `nil` if the ring is empty.
| Parameter | Type | Description |
|---|---|---|
| `ed` | `table` | The editor state |
**Returns:** The newly selected kill ring entry, or `nil`.
---
#### Syntax Highlighting
The highlighting subsystem provides the infrastructure for per-filetype syntax highlighting. Individual language highlighters are registered here and called during rendering.
##### Options
---
###### `COLOR`
**Type:** `table` — **Default:** (see below)
A table mapping semantic colour names to ncurses colour pair indices. The values here are the pair numbers passed to `init_pair` and `COLOR_PAIR`. They correspond to the pairs described in the [Colour Scheme](#colour-scheme) section.
```lua
COLOR = {
NORMAL = 0,
KEYWORD = 2,
KEYWORD_DEF = 13,
KEYWORD_LOGIC= 14,
KEYWORD_VALUE= 15,
STRING = 3,
COMMENT = 4,
NUMBER = 5,
OPERATOR = 6,
MATCH_BR = 7,
MENU_SEL = 8,
SELECTION = 9,
GUTTER = 10,
RULER = 11,
SEARCH_MATCH = 12,
}
```
When writing a highlighter, always reference colours by their `COLOR.*` name rather than the raw number, both for clarity and so that future colour reassignments propagate automatically.
---
##### Functions
---
###### `setup_colors()`
```lua
setup_colors() -> nil
```
Initialises all ncurses colour pairs by calling [`init_color_pair`](#l_init_color_pair) for each entry in [`COLOR`](#option-color). Called once during [`editor:init`](#editorinit) after ncurses is started. Must be called before any colour rendering takes place.
If you add new colour pairs (for example, when adding a new language with custom colours), add corresponding `init_color_pair` calls here.
---
###### `register_filetype(name, exts, shebangs, kw_table, comment, hl_fn)`
```lua
register_filetype(
name: string,
exts: table,
shebangs: table,
kw_table: table,
comment: string,
hl_fn: function
) -> nil
```
Registers a new filetype with the highlighting system. After registration, any file whose name matches one of the patterns in `exts`, or whose first line matches one of the patterns in `shebangs`, will have `hl_fn` called on each line during rendering, `kw_table` used for autocomplete keyword candidates, and `comment` used as the prefix for `M-;` comment toggling.
| Parameter | Type | Description |
|---|---|---|
| `name` | `string` | A short filetype identifier, e.g. `"lua"`, `"c"`, `"python"` |
| `exts` | `table` | Lua pattern strings matched against the filename, e.g. `{"%.lua$", "%.luac$"}` |
| `shebangs` | `table` | Lua pattern strings matched against the first line of the file, e.g. `{"lua$"}`. Pass `{}` if shebang detection is not needed. |
| `kw_table` | `table` | A set-table of keyword strings: `{["keyword"]=true, ...}`. Used for autocomplete. |
| `comment` | `string` | The single-line comment prefix for this language, e.g. `"--"` or `"//"`. |
| `hl_fn` | `function` | A function `(line: string) -> table` that returns a list of spans. See the highlighter [guide](#adding-a-syntax-highlighter-basic). |
---
###### `get_filetype(fn, first_line)`
```lua
get_filetype(fn: string, first_line: string|nil) -> string|nil
```
Detects the filetype for a given filename and optional first line. Iterates over all registered filetypes, checking the filename against each registered extension pattern. If no extension match is found and `first_line` is provided, checks shebang patterns. Returns the filetype name string, or `nil` if no match is found.
Extension matching takes priority over shebang matching.
| Parameter | Type | Description |
|---|---|---|
| `fn` | `string` | The filename or path |
| `first_line` | `string` or `nil` | The first line of the file, for shebang detection |
**Returns:** A filetype name string, or `nil`.
---
###### `push_span(t, col, len, color)`
```lua
push_span(t: table, col: integer, len: integer, color: integer) -> nil
```
Appends a span to the span list `t`. A span records a coloured region: `col` is the 0-based byte offset of the first character, `len` is the number of bytes, and `color` is a `COLOR.*` value. Spans with `len <= 0` are silently ignored.
This is the only function that highlighter functions should call to produce output. Constructing span tables directly is possible but not necessary.
| Parameter | Type | Description |
|---|---|---|
| `t` | `table` | The span list being built (passed as `spans` inside a highlighter) |
| `col` | `integer` | 0-based byte offset of the span start |
| `len` | `integer` | Byte length of the span |
| `color` | `integer` | A `COLOR.*` value |
---
###### `get_highlighter(ft)`
```lua
get_highlighter(ft: string|nil) -> function|nil
```
Returns the highlighter function registered for filetype `ft`, or `nil` if none is registered or `ft` is `nil`. Called when creating a new buffer to set the buffer's `highlighter` field.
| Parameter | Type | Description |
|---|---|---|
| `ft` | `string` or `nil` | A filetype name |
**Returns:** A highlighter function, or `nil`.
---
###### `get_keywords(ft)`
```lua
get_keywords(ft: string|nil) -> table
```
Returns a list (not a set) of all keyword strings registered for filetype `ft`. Returns an empty table if `ft` is `nil` or has no registered keywords. Used when creating a buffer to populate the `keywords` field, which is used by [`ac_build`](#ac_build).
| Parameter | Type | Description |
|---|---|---|
| `ft` | `string` or `nil` | A filetype name |
**Returns:** A table of keyword strings.
---
###### `get_comment_prefix(ft)`
```lua
get_comment_prefix(ft: string|nil) -> string|nil
```
Returns the comment prefix string registered for filetype `ft`, or `nil` if none. Used when creating a buffer to set the `comment_prefix` field, which is used by [`editor:toggle_comment`](#editortoggle_comment).
| Parameter | Type | Description |
|---|---|---|
| `ft` | `string` or `nil` | A filetype name |
**Returns:** A comment prefix string such as `"--"` or `"//"`, or `nil`.
---
###### `spans_to_color_map(spans)`
```lua
spans_to_color_map(spans: table) -> table
```
Converts a list of spans (as produced by a highlighter) into a flat table mapping each byte offset to a `COLOR.*` value. If spans overlap, the last one in the list wins for any given byte. The resulting table is indexed by 0-based byte offset and used directly by [`editor:draw`](#editordraw) to look up the colour for each character.
| Parameter | Type | Description |
|---|---|---|
| `spans` | `table` | A list of span tables `{col, len, color}` |
**Returns:** A table `{[byte_offset] = COLOR.*}`.
---
#### Indentation and Brackets
##### Options
---
###### `indent_completers`
**Type:** `table` — **Default:** Lua rules only
A table mapping filetype names to lists of *completer rules*. Each rule is a table with three fields:
- `pattern` — a Lua pattern matched against the trimmed content of the current line.
- `indent` — the additional indentation string to add on the new line.
- `close` — a string to insert on the line below the new line as a closing delimiter, or `nil` if no closing delimiter is needed.
These rules are consulted by [`editor:insert_newline_smart`](#editorinsert_newline_smart) when `Shift-Enter` is pressed. Rules are checked in order; the first match wins.
To add completers for a new language, add an entry to this table:
```lua
indent_completers["python"] = {
{pattern = ":%s*$", indent = " ", close = nil},
}
```
---
###### `BRACKET_PAIRS`
**Type:** `table`
A table used by [`find_matching_bracket`](#find_matching_bracket) to define which characters are paired brackets and in which direction to search for their match. Each entry maps a bracket character to a table containing the open character, the close character, and the search direction (`1` for forward, `-1` for backward).
```lua
BRACKET_PAIRS = {
["("] = {open="(", close=")", dir= 1},
[")"] = {open="(", close=")", dir=-1},
["["] = {open="[", close="]", dir= 1},
["]"] = {open="[", close="]", dir=-1},
["{"] = {open="{", close="}", dir= 1},
["}"] = {open="{", close="}", dir=-1},
}
```
---
##### Functions
---
###### `get_indent_completers(ft)`
```lua
get_indent_completers(ft: string|nil) -> table
```
Returns the list of indentation completer rules for filetype `ft`, or an empty table if none are defined. Called when creating a buffer to populate the buffer's `completers` field.
| Parameter | Type | Description |
|---|---|---|
| `ft` | `string` or `nil` | A filetype name |
**Returns:** A list of completer rule tables, or `{}`.
---
###### `find_matching_bracket(lines, row, col)`
```lua
find_matching_bracket(lines: table, row: integer, col: integer) -> (integer, integer)|nil
```
Finds the bracket that matches the bracket character at `(row, col)` in `lines`. `row` and `col` are 0-based. If no bracket character is at that position, or no match is found within the buffer, returns `nil`. Otherwise returns the 0-based `(row, col)` of the matching bracket.
The search walks outward from the starting bracket, counting nesting depth. It terminates when depth reaches zero (match found) or when the start or end of the buffer is reached (no match). The direction of the walk is determined by [`BRACKET_PAIRS`](#bracket_pairs).
The matched bracket pair is highlighted in [`editor:draw`](#editordraw) using `COLOR.MATCH_BR`. `M-m` jumps the cursor to the matching bracket.
| Parameter | Type | Description |
|---|---|---|
| `lines` | `table` | The buffer's line table |
| `row` | `integer` | 0-based row of the bracket character |
| `col` | `integer` | 0-based byte column of the bracket character |
**Returns:** `(row, col)` of the matching bracket, or `nil` if not found.
---
#### Undo and Redo
Lume implements undo and redo via explicit snapshots. Each snapshot records the complete state of the buffer — all lines and the cursor position — at a given moment. This approach is simple and reliable, at the cost of memory proportional to the number of undo steps times the size of the file. For files of normal size, this cost is negligible.
##### Functions
---
###### `make_snapshot(ed)`
```lua
make_snapshot(ed: table) -> table
```
Creates a snapshot of the current buffer state: a shallow copy of the `lines` table (so each line string is shared but the table itself is independent), plus the current `cursor_row` and `cursor_col`. This is stored on the undo or redo stack.
| Parameter | Type | Description |
|---|---|---|
| `ed` | `table` | The editor state |
**Returns:** A snapshot table `{lines, cursor_row, cursor_col}`.
---
###### `push_undo(ed)`
```lua
push_undo(ed: table) -> nil
```
Pushes a snapshot of the current state onto the undo stack, and clears the redo stack (since a new edit invalidates any redoable future). If the undo stack exceeds 200 entries, the oldest entry is removed to bound memory use.
Every editing operation that modifies the buffer — character insertion, deletion, paste, search-replace — must call `push_undo` before making its change. This is the invariant that makes undo correct.
| Parameter | Type | Description |
|---|---|---|
| `ed` | `table` | The editor state |
---
###### `pop_undo(ed)`
```lua
pop_undo(ed: table) -> nil
```
Restores the most recent undo snapshot. Saves the current state onto the redo stack first. Restores the `lines`, `cursor_row`, and `cursor_col` from the snapshot. Sets `ed.modified = true` and clears any active selection. Reports `"Undo"` in the status bar, or `"Nothing to undo"` if the stack is empty.
| Parameter | Type | Description |
|---|---|---|
| `ed` | `table` | The editor state |
---
###### `pop_redo(ed)`
```lua
pop_redo(ed: table) -> nil
```
The counterpart to `pop_undo`. Restores the most recent redo snapshot, saving the current state onto the undo stack. Reports `"Redo"` or `"Nothing to redo"`.
| Parameter | Type | Description |
|---|---|---|
| `ed` | `table` | The editor state |
---
#### Selections
##### Functions
---
###### `sel_ordered(ed)`
```lua
sel_ordered(ed: table) -> table|nil
```
Returns the current selection as an ordered range `{r1, c1, r2, c2}` where `(r1, c1)` is always the earlier position and `(r2, c2)` the later, regardless of whether the mark or the cursor comes first. Returns `nil` if no mark is set.
All functions that operate on a selection — drawing, killing, copying, indenting — call `sel_ordered` to get the normalised range rather than working with the raw mark and cursor positions directly.
| Parameter | Type | Description |
|---|---|---|
| `ed` | `table` | The editor state |
**Returns:** `{r1, c1, r2, c2}` or `nil`.
---
###### `get_selection_text(ed)`
```lua
get_selection_text(ed: table) -> string|nil
```
Returns the text content of the current selection as a string, or `nil` if no selection is active. For single-line selections, returns the substring between the mark and cursor. For multi-line selections, joins the fragments with `\n`.
| Parameter | Type | Description |
|---|---|---|
| `ed` | `table` | The editor state |
**Returns:** The selected text, or `nil`.
---
###### `delete_selection(ed)`
```lua
delete_selection(ed: table) -> nil
```
Deletes the content of the current selection from the buffer. Calls `push_undo` before modifying. For single-line selections, splices out the selected substring. For multi-line selections, removes all intermediate lines and joins the head and tail of the first and last lines. Moves the cursor to the start of the deleted region, clears the mark, and sets `ed.modified = true`.
| Parameter | Type | Description |
|---|---|---|
| `ed` | `table` | The editor state |
---
###### `indent_selection(ed, dedent)`
```lua
indent_selection(ed: table, dedent: boolean) -> nil
```
Indents or dedents every line in the current selection. When `dedent` is `false`, prepends two spaces to each line. When `dedent` is `true`, removes up to two leading spaces from each line (using a single `gsub` with count 1, so it removes exactly `" "` if present and does nothing otherwise). Reports `"Indented"` or `"Dedented"` in the status bar.
| Parameter | Type | Description |
|---|---|---|
| `ed` | `table` | The editor state |
| `dedent` | `boolean` | `true` to remove indentation, `false` to add |
---
###### `col_in_selection(s, row, col)`
```lua
col_in_selection(s: table|nil, row: integer, col: integer) -> boolean
```
Returns `true` if byte position `(row, col)` falls within the ordered selection range `s`. Handles single-line and multi-line selections correctly. Returns `false` if `s` is `nil`.
This is called for every character in every visible line during [`editor:draw`](#editordraw) to determine whether to apply selection highlighting.
| Parameter | Type | Description |
|---|---|---|
| `s` | `table` or `nil` | An ordered selection range from `sel_ordered`, or `nil` |
| `row` | `integer` | 0-based row |
| `col` | `integer` | 0-based byte column |
**Returns:** `true` if the position is inside the selection.
---
###### `clear_ephemeral(ed)`
```lua
clear_ephemeral(ed: table) -> nil
```
Clears the mark and resets `ed.ephemeral` to `false` if `ed.ephemeral` is currently `true`. Called at the start of any editing operation that should dismiss an ephemeral (search-created) selection. Has no effect on normal user-set selections.
| Parameter | Type | Description |
|---|---|---|
| `ed` | `table` | The editor state |
---
#### Buffers
##### Functions
---
###### `make_buffer(filename, lines)`
```lua
make_buffer(filename: string, lines: table) -> table
```
Creates and returns a new buffer table with the given filename and line content. Detects the filetype from the filename and first line, and populates all filetype-dependent fields: `highlighter`, `completers`, `keywords`, and `comment_prefix`. All other fields (cursor position, scroll offsets, undo stacks, mark, etc.) are initialised to their defaults.
The returned table has the same structure as the editor itself — it can be saved to and loaded from the editor via `save_editor_to_buffer` and `load_buffer_to_editor`.
| Parameter | Type | Description |
|---|---|---|
| `filename` | `string` | The file path. May be empty for a new unnamed buffer. |
| `lines` | `table` | The initial line content. |
**Returns:** A new buffer table.
---
###### `save_editor_to_buffer(ed, buf)`
```lua
save_editor_to_buffer(ed: table, buf: table) -> nil
```
Copies all mutable editing state from the active editor into the buffer table `buf`. This is called before switching away from a buffer, so that the buffer's record in `editor.buffers` stays up to date. The fields copied are: `filename`, `filetype`, `lines`, `modified`, `cursor_row`, `cursor_col`, `col_offset`, `scroll_offset`, `mark`, `ephemeral`, `undo_stack`, `redo_stack`, `highlighter`, `completers`, `keywords`, and `comment_prefix`.
| Parameter | Type | Description |
|---|---|---|
| `ed` | `table` | The active editor state |
| `buf` | `table` | The buffer table to save into |
---
###### `load_buffer_to_editor(ed, buf)`
```lua
load_buffer_to_editor(ed: table, buf: table) -> nil
```
The counterpart to `save_editor_to_buffer`. Copies all fields from `buf` back into the editor, making that buffer active. Called by `editor:switch_to_buffer` after saving the current buffer.
| Parameter | Type | Description |
|---|---|---|
| `ed` | `table` | The active editor state |
| `buf` | `table` | The buffer table to load from |
---
#### User Interaction
The three prompt functions form the minibuffer interface. All of them take over the bottom line of the screen for input and return control to the caller when the user confirms or cancels.
##### Functions
---
###### `yn_prompt(ed, label)`
```lua
yn_prompt(ed: table, label: string) -> boolean
```
Displays `label` followed by `" (y/n)"` in the status bar and waits for a single key. Returns `true` if `y` or `Y` is pressed, `false` for any other key. Used for destructive confirmations: quitting with unsaved buffers, reverting a modified file, killing a modified buffer.
| Parameter | Type | Description |
|---|---|---|
| `ed` | `table` | The editor state (used for screen dimensions) |
| `label` | `string` | The prompt text |
**Returns:** `true` if confirmed, `false` otherwise.
---
###### `mini_prompt(ed, label, default)`
```lua
mini_prompt(ed: table, label: string, default: string|nil) -> string|nil
```
Displays an interactive text input in the status bar, prefixed with `label`. The user can type freely, use Backspace to delete, and press Enter to confirm or `C-g` to cancel. If `default` is provided, it pre-fills the input field.
Returns the final input string on confirmation, or `nil` on cancellation. The input is trimmed to fit the screen width if it grows longer than the available space.
Used for: go-to-line, search and replace, shell command, `M-x` expression, and the search interface.
| Parameter | Type | Description |
|---|---|---|
| `ed` | `table` | The editor state |
| `label` | `string` | The prompt label |
| `default` | `string` or `nil` | Optional pre-filled text |
**Returns:** The input string, or `nil` if cancelled.
---
###### `file_prompt(ed, label)`
```lua
file_prompt(ed: table, label: string) -> string|nil
```
A specialised prompt for file paths. Behaves like [`mini_prompt`](#mini_prompt) but adds tab-completion: as the user types, Lume lists the matching filesystem entries in a small popup above the status bar. `Tab` accepts the currently highlighted completion and advances to the next one. `↑` and `↓` navigate the completion list. Backspace updates the completion list as the input shrinks.
Completions are generated by listing the directory that the current input implies, so typing `src/` shows the contents of the `src` directory. Directory entries are shown with a trailing `/` so you can distinguish them from files and continue navigating into them.
Used for `C-x C-f` (open file) and for the save-as prompt in [`editor:save`](#editorsave).
| Parameter | Type | Description |
|---|---|---|
| `ed` | `table` | The editor state |
| `label` | `string` | The prompt label |
**Returns:** The selected or typed path, or `nil` if cancelled.
---
#### Autocompletion
##### Functions
---
###### `ac_build(ed)`
```lua
ac_build(ed: table) -> table|nil
```
Builds the autocomplete candidate list based on the word prefix immediately before the cursor. The prefix is found by scanning backward from the cursor position for a run of `[%a_][%w_]*` characters. If the prefix is shorter than 2 characters, no candidates are built and `nil` is returned.
Candidates are collected from three sources: keywords of the current filetype, words in the current buffer, and words in other open buffers of the same filetype. Within each source, candidates are sorted by frequency (higher frequency = later in the list, so they appear at the top of the menu, which is displayed in reverse). Duplicates between sources are eliminated, with higher-priority sources taking precedence.
Returns a table `{candidates, sel, prefix_len}` where `candidates` is the full list, `sel` is the initially selected index (the last entry, i.e. the top of the menu), and `prefix_len` is the byte length of the matched prefix (needed by [`ac_apply`](#ac_apply)).
| Parameter | Type | Description |
|---|---|---|
| `ed` | `table` | The editor state |
**Returns:** An autocomplete state table, or `nil` if no candidates found.
---
###### `ac_apply(ed, ac)`
```lua
ac_apply(ed: table, ac: table) -> nil
```
Inserts the suffix of the currently selected completion candidate into the buffer at the cursor position. The suffix is the part of the candidate that comes after the already-typed prefix — for example, if the prefix is `"fun"` and the candidate is `"function"`, the suffix `"ction"` is inserted. The cursor is advanced past the inserted suffix. Sets `ed.modified = true`.
| Parameter | Type | Description |
|---|---|---|
| `ed` | `table` | The editor state |
| `ac` | `table` | The autocomplete state from `ac_build` |
---
###### `ac_handle(ed, ch)`
```lua
ac_handle(ed: table, ch: integer) -> boolean
```
Processes a keypress when the autocomplete menu is visible. Returns `true` if the key was consumed by the autocomplete system (and should not be processed by the main keymap), or `false` if it was not.
Keys handled:
- `C-g` — dismisses the menu.
- `↑` / `C-p` — moves the menu selection up (direction-aware: adjusts based on whether the menu is above or below the cursor).
- `↓` / `C-n` — moves the menu selection down.
- `Tab` — accepts the current selection via [`ac_apply`](#ac_apply) and dismisses the menu.
- Any other key — dismisses the menu and returns `false`, so the key is processed normally.
| Parameter | Type | Description |
|---|---|---|
| `ed` | `table` | The editor state |
| `ch` | `integer` | The key code from `wch()` |
**Returns:** `true` if the key was consumed, `false` otherwise.
---
#### Keybinds
##### Options
---
###### `KEY`
**Type:** `table`
A table of named key code constants used throughout the keybind system. These map human-readable names to the integer codes returned by `wch()`. The full table:
```lua
KEY = {
ENTER = 10, CR = 13,
BS = 127, BS2 = 8, BS3 = 263,
DELETE = 330,
TAB = 9, SHIFT_TAB = 353,
UP = 259, DOWN = 258, LEFT = 260, RIGHT = 261,
HOME = 262, END = 360,
PGUP = 339, PGDN = 338,
ESC = 27,
CTRL_A=1, CTRL_B=2, CTRL_C=3, CTRL_D=4, CTRL_E=5, CTRL_F=6,
CTRL_G=7, CTRL_H=8, CTRL_K=11, CTRL_L=12, CTRL_N=14, CTRL_P=16,
CTRL_R=18, CTRL_S=19, CTRL_W=23, CTRL_X=24, CTRL_Y=25, CTRL_Z=26,
CTRL_SLASH=31, CTRL_SPACE=0,
CTRL_RBRACKET=29, CTRL_BACKSLASH=28,
}
```
Backspace has three entries (`BS`, `BS2`, `BS3`) because different terminal emulators send different codes for the Backspace key. All three are mapped to the same action in the keymaps. Similarly, Enter has two entries (`ENTER` and `CR`).
---
##### Functions
---
###### `read_csi()`
```lua
read_csi() -> string
```
Reads the bytes of a CSI (Control Sequence Introducer) escape sequence after the initial `ESC [` has been consumed. Reads up to 20 characters and stops when it encounters a terminating byte (a letter in the range `@`–`Z`, or `~`, or `u`). Returns the accumulated sequence as a string (not including the `ESC [`).
Used by the main input loop to parse terminal escape sequences for special keys like `Shift-Enter`.
**Returns:** The CSI sequence body as a string.
---
###### `is_shift_enter(seq)`
```lua
is_shift_enter(seq: string) -> boolean
```
Returns `true` if the CSI sequence `seq` represents a Shift-Enter keypress. The sequences checked are `"13;2~"`, `"13;2u"`, and `"27;2;13~"`, which are the three encoding schemes used by different terminals for this key combination.
| Parameter | Type | Description |
|---|---|---|
| `seq` | `string` | A CSI sequence body as returned by `read_csi()` |
**Returns:** `true` if the sequence is Shift-Enter.
---
###### `make_keymaps(ed)`
```lua
make_keymaps(ed: table) -> (table, table, table)
```
Creates and returns the three keymap tables used by the main editing loop: the main keymap, the Meta keymap, and the `C-x` prefix keymap. Each keymap is a table mapping integer key codes to zero-argument functions (closures over `ed`).
The main keymap handles keys pressed without any prefix. The Meta keymap handles keys pressed after Escape. The `C-x` keymap handles keys pressed after `C-x`.
The separation into three tables makes it straightforward to add, remove, or remap individual keybindings by modifying the tables returned by this function, or by replacing `make_keymaps` entirely. See the [Adding a Keybind](#adding-a-keybind-control) guides for examples.
| Parameter | Type | Description |
|---|---|---|
| `ed` | `table` | The editor state, captured by the closures |
**Returns:** `(main_map, meta_map, cx_map)` — three keymap tables.
---
#### Editor
##### Options
---
###### `editor` (default values)
The `editor` table is initialised with the following default values. These serve as the configurable defaults for the editor — changing them before calling `editor:init` will alter the editor's starting behaviour.
| Field | Default | Description |
|---|---|---|
| `SCROLL_MARGIN` | `5` | Lines of context kept above and below the cursor when scrolling vertically |
| `H_SCROLL_MARGIN` | `5` | Columns of context kept to the left and right of the cursor when scrolling horizontally |
| `GUTTER_WIDTH` | `5` | Width in columns of the line number gutter |
| `RULER_COL` | `80` | The column at which the vertical ruler `\|` is drawn |
The remaining fields (`lines`, `cursor_row`, `screen_rows`, etc.) are initialised to empty/zero values and are set properly by `editor:init`. They are not intended to be configured directly.
---
##### Functions
---
###### `editor:draw()`
```lua
editor:draw() -> nil
```
Renders the entire editor to the terminal. This is the central rendering function, called once per iteration of the main loop before reading the next key.
The drawing sequence is:
1. Calls `resize_terminal()` to handle any pending terminal resize events.
2. Queries the current terminal dimensions and updates `screen_rows` and `screen_cols`.
3. Clears the screen.
4. For each visible line (from `scroll_offset` to `scroll_offset + screen_rows - 2`):
a. Draws the gutter (line number), highlighted if it is the cursor row.
b. Calls the buffer's highlighter function to get colour spans for the line.
c. Builds a per-byte colour map from the spans.
d. Overlays search match highlighting and selection highlighting on the colour map.
e. Iterates over the line character by character (UTF-8 aware), skipping characters that have scrolled off the left edge (`col_offset`), and drawing each visible character with its assigned colour, selection highlight, cursor highlight, bracket-match highlight, or ruler mark.
f. Draws the cursor block at the end of the line if the cursor is past the last character.
5. Draws the autocomplete popup if `editor.ac` is non-nil.
6. Draws the status bar: modification flag, buffer count, filename, filetype, selection indicator, status message, and cursor position.
7. Calls `refresh_screen()` to flush the output to the terminal.
The status message (`ed.status_msg`) is cleared after each draw, so messages set during an operation appear for exactly one frame.
---
###### `editor:adjust_scroll()`
```lua
editor:adjust_scroll() -> nil
```
Ensures the cursor is within the visible area vertically. If the cursor row is within `SCROLL_MARGIN` lines of the top of the view, the scroll offset is moved up. If it is within `SCROLL_MARGIN` lines of the bottom, the scroll offset is moved down. The scroll offset is then clamped so the view cannot scroll past the end of the buffer. Calls `adjust_col_scroll` to also handle horizontal scrolling.
---
###### `editor:adjust_col_scroll()`
```lua
editor:adjust_col_scroll() -> nil
```
Ensures the cursor is within the visible area horizontally. Uses `line_display_width` to compute the cursor's display column, then adjusts `col_offset` so the cursor stays within `H_SCROLL_MARGIN` display columns of the left and right edges of the text area.
---
###### `editor:recenter()`
```lua
editor:recenter() -> nil
```
Resets `scroll_offset` so the cursor row is vertically centred on the screen, and resets `col_offset` to zero (scrolling the view back to the left margin). Bound to `C-l`. Useful when you have scrolled far from the cursor or want to reset the horizontal scroll.
---
###### `editor:_raw_insert(str)`
```lua
editor:_raw_insert(str: string) -> nil
```
Inserts `str` at the current cursor position in the current line without any checking, undo recording, or side effects beyond updating the cursor column and setting `modified`. This is the lowest-level insert primitive. It is used internally by `insert_char` and `insert_newline_*` after those functions have handled undo and any higher-level logic. It should not generally be called directly from user code; use `insert_char` or a higher-level method instead.
---
###### `editor:insert_char(str)`
```lua
editor:insert_char(str: string) -> nil
```
The main character insertion entry point, called for every printable key press in the main loop. Handles several concerns:
- If a selection is active, the selected text is deleted first (and sent to the kill ring), then `str` is inserted in its place.
- If `str` is the same as the character immediately to the right of the cursor and that character is a closing bracket or `"`, the cursor is advanced through it rather than inserting a duplicate (auto-pair skip-through).
- If `str` is `\t`, two spaces are inserted as a tab.
- If `str` follows non-whitespace content and is a space or punctuation, an undo checkpoint is created (word-boundary undo granularity).
- `str` is inserted via `_raw_insert`.
- If `str` is an opening bracket or `"`, the matching closing character is inserted after it (auto-pairing), and the cursor is left between the two.
---
###### `editor:delete_char()`
```lua
editor:delete_char() -> nil
```
Deletes the character before the cursor (Backspace behaviour). If a selection is active, deletes the selection instead. Otherwise, clears any ephemeral selection and records an undo checkpoint.
Special case: if all content to the left of the cursor on the current line is whitespace and there are at least two spaces immediately before the cursor, two spaces are deleted at once, simulating tab-stop deletion.
If the cursor is at column zero and not on the first line, the current line is joined to the previous one (the cursor moves to the end of the previous line and the lines are concatenated).
---
###### `editor:delete_forward()`
```lua
editor:delete_forward() -> nil
```
Deletes the character after the cursor (Delete key behaviour). If a selection is active, deletes the selection instead. Otherwise, deletes one UTF-8 character forward, or joins the next line if at the end of the current line. Records an undo checkpoint.
---
###### `editor:kill_to_eol()`
```lua
editor:kill_to_eol() -> nil
```
Kills text from the cursor to the end of the current line, pushing it onto the kill ring. If the cursor is already at the end of the line, kills the newline itself, joining the current line with the next. Records an undo checkpoint.
This is a sub-operation called by `kill_region` when no selection is active. It is not bound directly — `C-k` calls `kill_region`.
---
###### `editor:kill_region()`
```lua
editor:kill_region() -> nil
```
Kills the active selection (if one exists) or calls `kill_to_eol`. The killed text is pushed onto the kill ring. Bound to `C-k`. When a selection is active, this is equivalent to a cut operation.
---
###### `editor:copy_region()`
```lua
editor:copy_region() -> nil
```
Copies the active selection to the kill ring without deleting it. Clears the mark after copying. Reports `"Copied N chars"`. Bound to `M-w`. If no selection is active, reports `"No selection"`.
---
###### `editor:delete_word_back()`
```lua
editor:delete_word_back() -> nil
```
Deletes the word (or whitespace run) immediately before the cursor, in two passes: first skipping any whitespace, then deleting backward through alphanumeric characters. Records an undo checkpoint. If a selection is active, deletes the selection instead.
---
###### `editor:delete_word_forward()`
```lua
editor:delete_word_forward() -> nil
```
Deletes the word immediately after the cursor, skipping non-word characters first, then deleting through alphanumeric characters. Records an undo checkpoint. If a selection is active, deletes the selection instead.
---
###### `editor:insert_newline_simple()`
```lua
editor:insert_newline_simple() -> nil
```
Inserts a newline at the cursor position, carrying the leading whitespace of the current line forward onto the new line. The cursor moves to the start of the new line's indented content. This is the behaviour of the regular `Enter` key and does not consult the indentation completers.
---
###### `editor:insert_newline_smart()`
```lua
editor:insert_newline_smart() -> nil
```
Inserts a newline with smart indentation, bound to `Shift-Enter`. If the cursor is at or near the end of a line (only whitespace follows it) and the trimmed line content matches one of the current buffer's [`indent_completers`](#indent_completers) patterns, the smart behaviour is applied: a new indented line is inserted, and if the matching rule specifies a `close` string, an additional line with that closing delimiter is inserted below. Otherwise, behaves identically to `insert_newline_simple`.
This is how typing a `function` declaration and pressing `Shift-Enter` in a Lua file will automatically give you an indented body line and an `end` below it.
---
###### `editor:tab_or_indent()`
```lua
editor:tab_or_indent() -> nil
```
If a selection is active, indents all lines in the selection by 2 spaces via `indent_selection`. Otherwise, inserts enough spaces to reach the next 2-column tab stop: `2 - (cursor_col % 2)` spaces. This means Tab always results in a cursor at an even column, acting as a 2-space tab.
---
###### `editor:shift_tab()`
```lua
editor:shift_tab() -> nil
```
If a selection is active, dedents all lines in the selection. Otherwise, if the current line begins with two spaces, removes them and moves the cursor back by 2 (clamped to zero).
---
###### `editor:yank()`
```lua
editor:yank() -> nil
```
Pastes the current kill ring entry at the cursor position. First checks the system clipboard — if it contains text not already in the ring, pushes it onto the ring. Then inserts the current entry's text: single-line kills are inserted inline; multi-line kills are split by `\n` and inserted as multiple lines, with the remaining content of the current line moved to after the last inserted line. Records an undo checkpoint.
Sets `prev_was_yank = true` on the editor so that a subsequent `M-y` knows it can cycle the ring.
---
###### `editor:yank_pop()`
```lua
editor:yank_pop() -> nil
```
Replaces the most recently yanked text with the previous entry in the kill ring. Can only be used immediately after `C-y` or another `M-y`. Implemented by popping the most recent undo (which undoes the yank), cycling the ring with `kill_ring_cycle`, then re-applying the yank with the new entry and pushing a fresh undo.
---
###### `editor:toggle_comment()`
```lua
editor:toggle_comment() -> nil
```
Toggles comments on the current line or all lines in the active selection. First checks whether all selected lines are already commented (have the comment prefix after leading whitespace). If all are commented, removes the prefix from each. If any line is not commented, adds the prefix to all lines (after their leading whitespace). Reports `"Commented"` or `"Uncommented"`. If the buffer has no `comment_prefix` set (unknown filetype), reports an error instead.
---
###### `editor:move_lines(dir)`
```lua
editor:move_lines(dir: integer) -> nil
```
Moves the current line (or all lines in the selection) up or down by one position. `dir` must be `-1` (up) or `1` (down). The cursor row (and the mark row, if a selection is active) is adjusted to follow the moved lines. Bound to `M-p` (up) and `M-n` (down).
| Parameter | Type | Description |
|---|---|---|
| `dir` | `integer` | `-1` to move up, `1` to move down |
---
###### `editor:move_cursor(drow, dcol)`
```lua
editor:move_cursor(drow: integer, dcol: integer) -> nil
```
Moves the cursor by `drow` rows and `dcol` character positions. Row movement clamps to the buffer extent. Column movement of `±1` uses `byte_next` or `byte_prev` to move by one full UTF-8 character. Column movement of `0` leaves the column unchanged but clamps it to the current line length (needed after a row change, since lines may be of different lengths). Clears ephemeral selections.
---
###### `editor:move_to_line_start()`
```lua
editor:move_to_line_start() -> nil
```
Implements the toggle behaviour of `C-a` / `Home`. If the cursor is past the first non-whitespace character, moves it to the indentation point (the first non-whitespace position). If the cursor is already at or before the indentation point, moves it to column zero. This means repeated presses alternate between the two positions.
---
###### `editor:move_to_line_end()`
```lua
editor:move_to_line_end() -> nil
```
Moves the cursor to the byte position after the last character of the current line (i.e. `#line`). Clears ephemeral selections.
---
###### `editor:page_up()`
```lua
editor:page_up() -> nil
```
Moves the cursor up by `screen_rows - 2` lines (one full page), clamped to the top of the buffer. Calls `adjust_scroll`.
---
###### `editor:page_down()`
```lua
editor:page_down() -> nil
```
Moves the cursor down by `screen_rows - 2` lines (one full page), clamped to the bottom of the buffer. Calls `adjust_scroll`.
---
###### `editor:word_forward()`
```lua
editor:word_forward() -> nil
```
Moves the cursor forward to the end of the next word. First skips non-alphanumeric characters, then advances through alphanumeric characters, stopping at the first non-alphanumeric character or the end of the line.
---
###### `editor:word_backward()`
```lua
editor:word_backward() -> nil
```
Moves the cursor backward to the start of the previous word. First skips non-alphanumeric characters going left, then moves back through alphanumeric characters, stopping at the first non-alphanumeric character or the start of the line.
---
###### `editor:save()`
```lua
editor:save() -> nil
```
Saves the current buffer to its file. If the buffer has no filename, opens a [`file_prompt`](#file_prompt) to ask for one, and updates the filetype and highlighter based on the chosen name. Before writing, strips trailing whitespace from every line. Appends a final newline to the file content if one is not already present (so saved files always end with `\n`). Reports success or failure in the status bar.
---
###### `editor:revert_file()`
```lua
editor:revert_file() -> nil
```
Reloads the current buffer from disk, discarding all unsaved changes. If the buffer is modified, prompts for confirmation via `yn_prompt` first. On success, replaces the line table, clears undo/redo stacks, and resets the cursor to a valid position. Reports success or failure.
---
###### `editor:_open_file_as_buffer(filename)`
```lua
editor:_open_file_as_buffer(filename: string) -> integer
```
Opens a file as a buffer. If the file is already open in an existing buffer (matched by normalised path), switches to that buffer instead of opening a duplicate. Otherwise, loads the file, creates a new buffer with `make_buffer`, appends it to `editor.buffers`, and switches to it. Returns the index of the buffer in `editor.buffers`.
The leading underscore signals that this is an internal function called by `open_file` and `recursive_search`, not directly by keybinds.
| Parameter | Type | Description |
|---|---|---|
| `filename` | `string` | The path to open |
**Returns:** The buffer index.
---
###### `editor:switch_to_buffer(idx)`
```lua
editor:switch_to_buffer(idx: integer) -> nil
```
Saves the current editor state into the current buffer's entry, then loads buffer `idx` into the editor. Updates the terminal title and reports the buffer index, count, and filename in the status bar.
| Parameter | Type | Description |
|---|---|---|
| `idx` | `integer` | The 1-based index into `editor.buffers` |
---
###### `editor:open_file()`
```lua
editor:open_file() -> nil
```
Opens a `file_prompt` and calls `_open_file_as_buffer` with the result. Bound to `C-x C-f`.
---
###### `editor:kill_buffer()`
```lua
editor:kill_buffer() -> nil
```
Closes the current buffer. Prompts for confirmation if the buffer is modified. Removes the buffer from `editor.buffers`. If this was the last buffer, creates a new empty buffer in its place. Switches to an adjacent buffer otherwise. Reports the name of the killed buffer.
---
###### `editor:buffer_picker()`
```lua
editor:buffer_picker() -> nil
```
Opens a full-screen interactive buffer list. All open buffers are shown with their modification status and filename. Navigate with `↑`/`↓` or `C-p`/`C-n`. Press `Enter` to switch to the selected buffer. Press `k` to kill the selected buffer (removes it from the list without switching). Press `C-g` to cancel and return to the current buffer.
---
###### `editor:next_buffer()`
```lua
editor:next_buffer() -> nil
```
Switches to the next buffer in `editor.buffers`, wrapping around from the last to the first. Does nothing (with a message) if only one buffer is open. Bound to `C-]`.
---
###### `editor:prev_buffer()`
```lua
editor:prev_buffer() -> nil
```
Switches to the previous buffer, wrapping around from the first to the last. Bound to `C-\`.
---
###### `editor:goto_line_prompt()`
```lua
editor:goto_line_prompt() -> nil
```
Opens a `mini_prompt` asking for a line number, then moves the cursor to that line (1-based). Clamps the target line to the buffer extent. Calls `adjust_scroll`. Reports the destination line or an error if the input is not a valid number. Bound to `M-g`.
---
###### `editor:isearch()`
```lua
editor:isearch() -> nil
```
Implements incremental search, bound to `C-s`. Enters a sub-loop that reads characters and updates the search results with every keystroke. As the pattern grows, all matches are highlighted in the buffer using `COLOR.SEARCH_MATCH`. The cursor jumps to the nearest match forward from the starting position. `C-s` advances to the next match; `C-r` reverses direction. `Enter` confirms; `C-g` cancels and restores the cursor.
Search is smart-case: lower-case-only patterns search case-insensitively; patterns with any upper-case character are case-sensitive.
On confirmation, the matched text is left as an ephemeral selection.
---
###### `editor:search_replace()`
```lua
editor:search_replace() -> nil
```
Implements search and replace, bound to `M-%`. Prompts for a search pattern and a replacement string via `mini_prompt`. Both are treated as plain text (not Lua patterns). Applies the replacement globally across all lines of the buffer in a single pass using `string.gsub` with escaped pattern and replacement strings. Records a single undo checkpoint for the entire operation. Reports the number of replacements made.
---
###### `editor:recursive_search()`
```lua
editor:recursive_search() -> nil
```
Implements the recursive grep interface, bound to `C-r` in normal mode. Prompts for a search term, then calls `collect_files` to build the list of all files under `.`, and `search_in_file` on each. Displays results in a full-screen list with syntax highlighting on the matching lines. Navigate with `↑`/`↓` or `C-p`/`C-n`; `Enter` opens the file and jumps to the match; `C-g` cancels.
---
###### `editor:run_command()`
```lua
editor:run_command() -> nil
```
Bound to `M-x`. Opens a `mini_prompt` and passes the input to `lua_eval` (the C-side evaluator). The result is displayed in the status bar. This exposes the full Lua runtime to the user at runtime — the global `ed` is the live editor table, so expressions like `ed.cursor_row` or `ed:save()` work as expected.
---
###### `editor:run_shell()`
```lua
editor:run_shell() -> nil
```
Bound to `M-!`. Opens a `mini_prompt` for a shell command, runs it with `io.popen` (capturing stderr via `2>&1`), and displays the first line of output in the status bar (truncated to fit if necessary). Reports `"Done"` if the command produces no output.
---
###### `editor:init(filenames)`
```lua
editor:init(filenames: table) -> nil
```
Initialises the editor session. Called once at startup. Starts ncurses, queries the screen size, calls `setup_colors`, loads all files named in `filenames` into buffers, sets the active buffer to the first one, and updates the terminal title. If `filenames` is empty, creates one empty buffer.
| Parameter | Type | Description |
|---|---|---|
| `filenames` | `table` | A list of file path strings. May be empty. |
---
###### `editor:run()`
```lua
editor:run() -> nil
```
The main event loop. Calls `editor:draw()`, reads a key with `wch()`, and dispatches it through the keymaps: first to `ac_handle` if autocomplete is active, then to the Meta keymap (if an Escape was just read), then to the `C-x` keymap (if `C-x` was the previous key), then to the main keymap, and finally — for printable characters — to `insert_char`.
Tracks `prev_was_yank` so that `M-y` (yank-pop) knows whether the previous command was a yank. Runs until `editor._quit` is set to `true`.
---
###### `editor:cleanup()`
```lua
editor:cleanup() -> nil
```
Tears down the editor session: saves the current editor state back into its buffer entry, calls `end_ncurses` to restore the terminal, and calls `close_log` to flush and close the log file. Called both on normal exit and in the error handler, so the terminal is always properly restored.
---
### C Reference
The C layer (`main.c`) is a thin bridge between Lua and the system. Every function in it follows the same pattern: extract arguments from the Lua stack, perform a system call, push results back onto the stack, and return the number of results. No editor logic lives here. The C functions are registered as Lua globals by the `bindings` table in `main`, making them available to `main.lua` as ordinary Lua functions.
#### Options
---
##### `bindings[]`
```c
static const struct { const char *name; lua_CFunction func; } bindings[]
```
An array of name–function pairs that maps C functions to Lua global names. Each entry is registered at startup by iterating the array and calling `lua_pushcfunction` / `lua_setglobal`. Adding a new C function to Lume requires adding an entry here in addition to writing the function itself.
The array is terminated by a `{NULL, NULL}` sentinel.
---
#### Functions
---
##### `on_sigwinch`
```c
static void on_sigwinch(int sig)
```
Signal handler for `SIGWINCH`, the terminal resize signal. Sets the global flag `g_resize = 1`. The flag is checked by `l_resize_terminal` at the start of each draw cycle.
---
##### `push_error`
```c
static int push_error(lua_State *L, const char *msg)
```
A convenience function used by C functions that can fail. Pushes `nil` and the error string `msg` onto the Lua stack and returns 2 (the number of return values). Following Lua convention, failure is represented as `nil, error_string`.
---
##### `l_init_ncurses`
**Lua name:** *(called only from `editor:init`)*, not exposed as a named global but registered implicitly.
**Lua signature:** `init_ncurses() -> nil`
```c
static int l_init_ncurses(lua_State *L)
```
Initialises the ncurses library. In order: sets the locale (required for UTF-8 terminal input), calls `initscr`, enables `cbreak` and `raw` mode (so keypresses are delivered immediately without buffering or interpretation), disables echo, enables keypad mode (so arrow keys produce single key codes rather than escape sequences), disables the cursor, starts colour mode, enables use of default terminal colours (`use_default_colors`), initialises colour pair 1 (black on white, used for the cursor block), and installs `on_sigwinch` as the `SIGWINCH` handler.
---
##### `l_end_ncurses`
**Lua signature:** `end_ncurses() -> nil`
```c
static int l_end_ncurses(lua_State *L)
```
Calls `endwin()` to restore the terminal to its pre-ncurses state. Must be called before the program exits, or the terminal will be left in raw mode.
---
##### `l_resize_terminal`
**Lua signature:** `resize_terminal() -> nil`
```c
static int l_resize_terminal(lua_State *L)
```
Checks the `g_resize` flag (set by `on_sigwinch`). If set, clears the flag, then calls `endwin()` followed by `refresh()` and `clearok(stdscr, TRUE)` to force ncurses to re-query the terminal dimensions and redraw from scratch. This is the correct way to handle a resize in ncurses. Called at the top of each `editor:draw` cycle.
---
##### `l_refresh_screen`
**Lua signature:** `refresh_screen() -> nil`
```c
static int l_refresh_screen(lua_State *L)
```
Calls `wrefresh(stdscr)` to flush the ncurses virtual screen buffer to the terminal. Called at the end of each draw cycle and after each prompt draw.
---
##### `l_get_wchar`
**Lua signature:** `get_wchar() -> integer`
```c
static int l_get_wchar(lua_State *L)
```
Calls `wget_wch(stdscr, &ch)` to read one wide character of input. Returns the character as a Lua integer (a Unicode code point for regular characters, or an ncurses key code for special keys). Returns `-1` on error or if no input is available.
---
##### `l_set_title`
**Lua signature:** `set_title(title: string) -> nil`
```c
static int l_set_title(lua_State *L)
```
Sets the terminal window title by writing the OSC 0 escape sequence (`\033]0;title\007`) directly to stdout. This works in most terminal emulators that support xterm title sequences. Has no effect in terminals that do not support them.
| Lua Parameter | Type | Description |
|---|---|---|
| 1 | `string` | The title string |
---
##### `l_get_screen_size`
**Lua signature:** `get_screen_size() -> integer, integer`
```c
static int l_get_screen_size(lua_State *L)
```
Calls `getmaxyx(stdscr, rows, cols)` to query the current terminal dimensions. Returns rows and columns as two integers. Note that the column count returned is `cols + 1` — this compensates for an off-by-one in the ncurses `getmaxyx` macro on some implementations.
**Returns:** `rows, cols`
---
##### `l_clear_screen`
**Lua signature:** `clear_screen() -> nil`
```c
static int l_clear_screen(lua_State *L)
```
Calls ncurses `clear()`, which marks the entire virtual screen as blank. The actual terminal is not cleared until the next `refresh_screen()` call.
---
##### `l_move_cursor`
**Lua signature:** `move_cursor(y: integer, x: integer) -> nil`
```c
static int l_move_cursor(lua_State *L)
```
Calls ncurses `move(y, x)` to position the ncurses internal cursor. This does not move the editor's logical cursor; it positions the ncurses drawing cursor used by subsequent `print_at` calls.
| Lua Parameter | Type | Description |
|---|---|---|
| 1 | `integer` | Row (0-based, from top) |
| 2 | `integer` | Column (0-based, from left) |
---
##### `l_print_at`
**Lua signature:** `print_at(y: integer, x: integer, str: string) -> nil`
```c
static int l_print_at(lua_State *L)
```
Calls `mvprintw(y, x, "%s", str)` to print a string at the given screen position. The `%s` format is used rather than passing `str` directly as the format string, which prevents any `%` characters in the string from being interpreted as format specifiers.
| Lua Parameter | Type | Description |
|---|---|---|
| 1 | `integer` | Row |
| 2 | `integer` | Column |
| 3 | `string` | The string to print |
---
##### `l_set_reverse`
**Lua signature:** `set_reverse(on: boolean) -> nil`
```c
static int l_set_reverse(lua_State *L)
```
Enables or disables the ncurses `A_REVERSE` attribute (swaps foreground and background colours). Used for the status bar, gutter highlights, and prompt rendering.
---
##### `l_set_bold`
**Lua signature:** `set_bold(on: boolean) -> nil`
```c
static int l_set_bold(lua_State *L)
```
Enables or disables the ncurses `A_BOLD` attribute. Available for use in custom highlighters, though none of the built-in highlighters currently use it.
---
##### `l_set_color`
**Lua signature:** `set_color(pair: integer, on: boolean) -> nil`
```c
static int l_set_color(lua_State *L)
```
Enables or disables a specific ncurses colour pair. `pair` is an index corresponding to one of the pairs initialised by `l_init_color_pair`. When `on` is `true`, `attron(COLOR_PAIR(pair))` is called; when `false`, `attroff(COLOR_PAIR(pair))`.
| Lua Parameter | Type | Description |
|---|---|---|
| 1 | `integer` | Colour pair index |
| 2 | `boolean` | `true` to enable, `false` to disable |
---
##### `l_init_color_pair`
**Lua signature:** `init_color_pair(pair: integer, fg: integer, bg: integer) -> nil`
```c
static int l_init_color_pair(lua_State *L)
```
Calls ncurses `init_pair(pair, fg, bg)` to define a colour pair. `fg` and `bg` are standard ncurses colour numbers (0–7 for standard colours, or `-1` for the terminal default). This is called for all pairs by `setup_colors` at startup, and may be called again at runtime to redefine colours.
| Lua Parameter | Type | Description |
|---|---|---|
| 1 | `integer` | Pair index (1–255) |
| 2 | `integer` | Foreground colour number, or `-1` for default |
| 3 | `integer` | Background colour number, or `-1` for default |
---
##### `l_save_file`
**Lua signature:** `save_file(path: string, content: string) -> true | nil, string`
```c
static int l_save_file(lua_State *L)
```
Writes `content` to the file at `path`, creating or truncating the file. Returns `true` on success. On failure, returns `nil` and an error string (`"Open failed"` or `"Write failed"`).
| Lua Parameter | Type | Description |
|---|---|---|
| 1 | `string` | File path |
| 2 | `string` | File content |
**Returns:** `true` on success, or `nil, error_string` on failure.
---
##### `l_load_file`
**Lua signature:** `load_file(path: string) -> string | nil, string`
```c
static int l_load_file(lua_State *L)
```
Reads the entire content of the file at `path` and returns it as a Lua string. On failure, returns `nil` and an error string. The file is opened in text mode (`"r"`), so line ending translation is platform-dependent.
**Returns:** File content string, or `nil, error_string`.
---
##### `l_list_dir`
**Lua signature:** `list_dir(path: string) -> table | nil`
```c
static int l_list_dir(lua_State *L)
```
Opens the directory at `path` and returns a Lua table containing the names of all entries (including `.` and `..`). Returns `nil` if the directory cannot be opened. The order of entries matches the order returned by `readdir`, which is filesystem-dependent and not sorted.
**Returns:** A table of filename strings, or `nil`.
---
##### `l_stat_file`
**Lua signature:** `stat_file(path: string) -> string | nil`
```c
static int l_stat_file(lua_State *L)
```
Calls `stat(path, &st)` and returns a string describing the file type: `"file"` for a regular file, `"dir"` for a directory, `"other"` for anything else (symlinks, devices, sockets, etc.). Returns `nil` if `stat` fails (file does not exist, permission denied, etc.).
**Returns:** `"file"`, `"dir"`, `"other"`, or `nil`.
---
##### `l_lua_eval`
**Lua signature:** `lua_eval(code: string) -> string`
```c
static int l_lua_eval(lua_State *L)
```
Compiles and executes a Lua string in the global interpreter state (`G_L`, which is the same state that `main.lua` runs in). Returns a string result in all cases:
- If compilation fails, returns the compile error message.
- If execution fails, returns the runtime error message.
- If execution succeeds and returns one or more values, returns `tostring` of the first value.
- If execution succeeds and returns nothing, returns `"ok"`.
This function is the engine behind `editor:run_command` (`M-x`). Because it runs in the global state and the editor is exposed as `_G.ed`, evaluated code has unrestricted access to the entire editor. This is intentional — it provides a live Lua REPL into the running editor.
| Lua Parameter | Type | Description |
|---|---|---|
| 1 | `string` | Lua source code |
**Returns:** A result or error string.
---
## Guides
The guides in this section walk through specific modifications to Lume, showing how each part of the system fits together. Each guide implements a concrete example from start to finish. The goal is not just to show what to do, but to explain why, so that you can adapt the approach to whatever you want to build.
All modifications described here are made in `main.lua` only. No changes to `main.c` are needed for any of these guides.
---
### Adding a Syntax Highlighter (Basic)
This guide adds syntax highlighting support for the Python language. By the end, `.py` files and Python shebangs will receive keyword highlighting, string and comment support, and correct comment toggling with `M-;`.
The entry point for all of this is [`register_filetype`](#register_filetype). You call it once, at the top level of `main.lua` (anywhere after the `register_filetype` function itself is defined), and that is all that is needed.
**Step 1: Define the keyword set.**
The keyword set is a Lua table used as a set — keys are the keyword strings, values are `true`. This table is used by the autocomplete system to offer keyword completions.
```lua
local PYTHON_KW = {
["False"]=true, ["None"]=true, ["True"]=true,
["and"]=true, ["as"]=true, ["assert"]=true,
["async"]=true, ["await"]=true, ["break"]=true,
["class"]=true, ["continue"]=true,["def"]=true,
["del"]=true, ["elif"]=true, ["else"]=true,
["except"]=true, ["finally"]=true, ["for"]=true,
["from"]=true, ["global"]=true, ["if"]=true,
["import"]=true, ["in"]=true, ["is"]=true,
["lambda"]=true, ["nonlocal"]=true,["not"]=true,
["or"]=true, ["pass"]=true, ["raise"]=true,
["return"]=true, ["try"]=true, ["while"]=true,
["with"]=true, ["yield"]=true,
}
```
**Step 2: Write the highlighter function.**
The highlighter takes one line string and returns a list of spans. It does not need to handle multi-line constructs (see [Highlighter](#definitions-highlighter) for why). The pattern here follows the C highlighter: walk the line left to right, identify the next token, push a span for it, advance.
```lua
local function python_hl(line)
local spans, i, n = {}, 1, #line
while i <= n do
local ch = line:sub(i, i)
-- Line comment
if ch == "#" then
push_span(spans, i-1, n-i+1, COLOR.COMMENT)
break
-- String: single or double quoted
elseif ch == '"' or ch == "'" then
local q, j = ch, i+1
-- Handle triple-quote opening — treat the rest of the line as a string.
if line:sub(i, i+2) == q:rep(3) then
push_span(spans, i-1, n-i+1, COLOR.STRING)
break
end
while j <= n do
local c = line:sub(j, j)
if c == "\\" then j = j+2
elseif c == q then j = j+1; break
else j = j+1 end
end
push_span(spans, i-1, j-i, COLOR.STRING)
i = j
-- Number
elseif ch:match("%d") then
local j = i
while j <= n and line:sub(j,j):match("[%d%.xXa-fA-F_]") do j = j+1 end
push_span(spans, i-1, j-i, COLOR.NUMBER)
i = j
-- Identifier or keyword
elseif ch:match("[%a_]") then
local j = i
while j <= n and line:sub(j,j):match("[%w_]") do j = j+1 end
if PYTHON_KW[line:sub(i, j-1)] then
push_span(spans, i-1, j-i, COLOR.KEYWORD)
end
i = j
else
i = i+1
end
end
return spans
end
```
**Step 3: Register the filetype.**
```lua
register_filetype(
"python",
{"%.py$", "%.pyw$"},
{"python3?$", "python$"},
PYTHON_KW,
"#",
python_hl
)
```
That is everything. Reload Lume and open a `.py` file — highlighting, comment toggling, and autocomplete keyword suggestions will all work.
---
### Adding a Syntax Highlighter (Advanced)
This guide implements a more sophisticated highlighter for Lua, as a case study in the techniques available within Lume's single-line model. The goal is to show how to handle multiple keyword categories (as the built-in Lua highlighter already does), how to write a more careful string parser, and what the limits of the model are.
Look at the built-in Lua highlighter in `main.lua` as the reference implementation. Compare it to the C highlighter. The C highlighter has one keyword table and one colour for all keywords. The Lua highlighter has three keyword tables (`LUA_DEF`, `LUA_LOGIC`, `LUA_VALUE`) and picks a different colour depending on which table the word is found in. This is the main technique for "advanced" highlighting: sub-categorising tokens and assigning them distinct colours.
**Multiple keyword categories.**
To do this for a new language, define multiple keyword sets:
```lua
local MY_KW_TYPE = {["int"]=true, ["void"]=true, ["char"]=true}
local MY_KW_CONTROL = {["if"]=true, ["for"]=true, ["return"]=true}
local MY_KW_VALUE = {["true"]=true,["false"]=true, ["null"]=true}
```
Then in the identifier branch of the highlighter:
```lua
elseif ch:match("[%a_]") then
local j = i
while j <= n and line:sub(j,j):match("[%w_]") do j = j+1 end
local word = line:sub(i, j-1)
local color = MY_KW_TYPE[word] and COLOR.KEYWORD_DEF
or MY_KW_CONTROL[word] and COLOR.KEYWORD_LOGIC
or MY_KW_VALUE[word] and COLOR.KEYWORD_VALUE
if color then push_span(spans, i-1, j-i, color) end
i = j
```
Note the short-circuit evaluation: only one colour is applied per word.
**Adding new colour pairs.**
If the built-in `COLOR` values are not enough, you can define new pairs. Choose a pair number not already in use (see [`COLOR`](#option-color); 16 and above are free), call `init_color_pair` in `setup_colors`, and add a constant to the `COLOR` table:
```lua
-- In the COLOR table:
COLOR.MY_CUSTOM = 16
-- In setup_colors():
init_color_pair(COLOR.MY_CUSTOM, 5, -1) -- magenta on default
```
Then use `COLOR.MY_CUSTOM` in your highlighter's `push_span` calls.
**Detecting decorated identifiers.**
Some languages have sigil-prefixed identifiers — Python's decorators (`@name`), shell variables (`$name`), Perl's `$`, `@`, `%`. Handle these by checking the character before entering the identifier branch:
```lua
elseif ch == "@" and line:sub(i+1, i+1):match("[%a_]") then
local j = i+1
while j <= n and line:sub(j,j):match("[%w_]") do j = j+1 end
push_span(spans, i-1, j-i+1, COLOR.KEYWORD_DEF) -- includes the @
i = j
```
**What cannot be done within the single-line model.**
Multi-line strings and block comments cannot be highlighted correctly without carrying state between lines, and Lume does not do this. A `"""` triple-quoted string that starts on line 10 and ends on line 15 cannot be highlighted on lines 11–14 because those lines, processed independently, have no way to know they are inside a string.
The correct thing to do here is nothing: leave those lines unhighlighted. Do not attempt to simulate multi-line state by scanning backward for an unmatched delimiter — this approach produces incorrect results when edits happen in the middle of the file and creates confusing, unpredictable highlighting. An unhighlighted comment is less surprising than a comment that is sometimes highlighted and sometimes not.
---
### Adding a New Editor Function (Basic)
This guide adds a simple function that sorts the lines of the current selection alphabetically. It is a good example of the basic pattern: take the selection, do something to its content, put it back.
The function will be added directly to the `editor` table, invoked via `M-x` for now, and then given a keybind in the next guide.
```lua
function editor:sort_lines()
local s = sel_ordered(self)
if not s then
self.status_msg = "No selection"
return
end
-- Collect the selected lines
local selected = {}
for r = s.r1, s.r2 do
selected[#selected+1] = self.lines[r+1]
end
-- Sort them
table.sort(selected)
-- Write them back, with an undo checkpoint
push_undo(self)
for i, line in ipairs(selected) do
self.lines[s.r1 + i] = line
end
self.modified = true
self.status_msg = string.format("Sorted %d lines", #selected)
end
```
Place this function anywhere in `main.lua` after the `editor` table is defined — near the other `editor:*` functions is conventional.
To call it, open a file, select some lines with `C-Space`, and use `M-x`:
```
M-x ed:sort_lines()
```
(Because `editor` is exposed as `_G.ed`, you can call its methods from `M-x` as `ed:method()`.)
The function uses [`sel_ordered`](#sel_ordered) to get the selection, [`push_undo`](#push_undo) to record an undo checkpoint, and sets `status_msg` to report what it did — the three things that almost every editor function does.
---
### Adding a New Editor Function (Advanced)
This guide adds an `editor:align_table()` function that takes a selection of lines containing a common delimiter (such as `=` or `|`) and aligns all occurrences of that delimiter to the same column by padding with spaces. This is the kind of non-trivial transformation that is pleasant to have available but would be cumbersome to do by hand.
```lua
function editor:align_table()
-- Require a selection
local s = sel_ordered(self)
if not s then self.status_msg = "No selection"; return end
-- Prompt for the delimiter to align on
local delim = mini_prompt(self, "Align on: ")
if not delim or delim == "" then self.status_msg = "Cancelled"; return end
local esc = escape_pattern(delim)
local lines = {}
-- Collect the selected lines and find the maximum column of the delimiter
local max_col = 0
for r = s.r1, s.r2 do
local line = self.lines[r+1]
lines[#lines+1] = line
local col = line:find(esc)
if col and col-1 > max_col then max_col = col-1 end
end
-- Align: pad each line with spaces before the delimiter so it lands at max_col
push_undo(self)
for i, line in ipairs(lines) do
local col = line:find(esc)
if col then
local before = line:sub(1, col-1):gsub("%s+$", "") -- trim trailing spaces
local after = line:sub(col)
local pad = max_col - #before
self.lines[s.r1 + i] = before .. string.rep(" ", math.max(0, pad)) .. after
end
end
self.modified = true
self.status_msg = string.format("Aligned on '%s'", delim)
end
```
This function demonstrates several things worth noting:
- It uses [`mini_prompt`](#mini_prompt) inside an editor method. Prompts can be called from any editor function because they take `ed` (or `self`) as their first argument and use the same screen layout as any other prompt.
- It uses [`escape_pattern`](#escape_pattern) so that the delimiter can contain characters that are special in Lua patterns (e.g. `|`, `+`, `.`).
- It trims trailing whitespace from the left side before padding, so repeated applications do not accumulate spaces.
- A single `push_undo` covers the entire transformation.
---
### Adding a Keybind (Control)
Control-key bindings live in the `main_map` table returned by [`make_keymaps`](#make_keymaps). To add one, either modify `make_keymaps` directly or add to the table after it is returned.
The cleanest approach for a personal modification is to modify `make_keymaps`. Find the `main_map` table and add your entry:
```lua
-- In make_keymaps, inside the main_map table:
[KEY.CTRL_T] = function()
ed:sort_lines()
ed:adjust_scroll()
end,
```
`CTRL_T` is the code for Control-T. The key codes for control characters are their ASCII control codes: `C-a = 1`, `C-b = 2`, and so on. `C-t = 20`. You can either add the name to the [`KEY`](#option-key) table (`KEY.CTRL_T = 20`) or use the raw integer.
If you want to add the binding without modifying `make_keymaps`, you can do so after the keymaps are created in `editor:run`:
```lua
function editor:run()
local main_map, meta_map, cx_map = make_keymaps(self)
-- Add a custom binding after the fact:
main_map[20] = function() -- CTRL_T = 20
self:sort_lines()
self:adjust_scroll()
end
-- ... rest of the run loop unchanged
end
```
Be careful not to shadow an existing binding. Check the full `main_map` in `make_keymaps` to confirm the key is not already in use.
---
### Adding a Keybind (Meta)
Meta bindings follow the same pattern, but use `meta_map`. Meta keys are the character codes of the key pressed after Escape. To bind `M-t`:
```lua
-- In make_keymaps, inside the meta_map table:
[string.byte("t")] = function()
ed:align_table()
ed:adjust_scroll()
end,
```
`string.byte("t")` returns the ASCII code for `t` (116). You can also write `116` directly, but `string.byte` is more readable.
---
### Adding a Keybind (Control-x)
`C-x` prefix bindings live in `cx_map`. The pattern is identical:
```lua
-- In make_keymaps, inside the cx_map table:
[KEY.CTRL_T] = function()
ed:sort_lines()
end,
```
This would be invoked by pressing `C-x` followed by `C-t`. The `C-x` prefix is a good choice for less frequently used commands that do not need a one-key shortcut.
|