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 | --
-- // Code by SoundOfSpouting#6980 (UID: 151149148639330304)
--
-- visual text editor inspired by Emacs evil mode
--
term = require "term"
text = require "text"
event = require "event"
unicode = require "unicode"
keyboard = require "keyboard"
serialization = require "serialization"
local args = {...}
editor = {}
editor.commands = {}
editor.buffer = {}
function dump(v)
return serialization.serialize(v, math.huge)
end
function dumpfile(f,v)
local f = io.open(f,"w")
f:write(type(v) == "string" and v or dump(v))
f:close()
end
local function main()
local state = {
args = args,
arg_n = 1,
arg_type = nil,
short_arg_n = nil,
args_done = false,
}
editor.set_mode("normal")
editor.buffer = editor.new_buffer()
while state.arg_n <= #state.args do
local arg = state.args[state.arg_n]
if not state.arg_type then
if arg == "--" then
state.args_done = true
elseif not state.args_done and arg:match("^%-%-") then
state.arg_type = "long"
state.arg = state.args[state.arg_n]:sub(3, -1)
elseif not state.args_done and arg:match("^%-") then
state.arg_type = "short"
state.short_arg_n = 2
state.arg = state.args[state.arg_n]:sub(
state.short_arg_n,
state.short_arg_n
)
else
editor.commands.open(arg)
end
end
if state.arg_type then
local func = editor[state.arg_type .. "opts"][state.arg]
local ok, err = true
if not func then
ok, err = nil,
"unknown option: "
.. ({
long = '--',
short = '-'
})[state.arg_type]
.. state.arg
end
if ok then
ok, err = func()
end
if not ok then
io.stderr:write(err,'\n')
return
end
if state.exit then
return
end
end
state.arg_n = state.arg_n + 1
end
editor.run()
return true
end
TheWeakster = {
__mode = "k"
}
function class(obj, super)
obj.__index = function(self, i)
local v
if self ~= obj then
v = obj[i]
end
if super and v == nil then
return super[i]
end
if self == obj then return nil end
return v
end
obj.__proto__ = obj
setmetatable(obj, obj)
return obj
end
function static(fn)
return function(self, ...)
if self.__proto__ ~= self then
return fn(self.__proto__, ...)
end
return fn(self, ...)
end
end
function unrecursive(fn)
local n = 0
local function pack(...)
return {n = select('#', ...), ...}
end
return function(...)
assert(n < 1, "recursion forbidden here")
n = n + 1
local ret = pack(fn(...))
n = n - 1
return (unpack or table.unpack)(ret, 1, ret.n)
end
end
local function DumpLengths(obj)
local prim = obj:Length()
for k,v in pairs(obj:Lengths()) do
if k ~= "chars" then
prim = ("%s, %s=%s"):format(prim, k, type(v)=="table" and v.chars or v)
end
end
return prim
end
Rope = class {}
Rope.__Fibo = {[0] = 1}
for n=1,64 do
Rope.__Fibo[n] =
(Rope.__Fibo[n - 1] or 0)
+ (Rope.__Fibo[n - 2] or 0)
end
function Rope:__call(String, LeafSize)
local obj = class ({}, self)
obj.String = String
obj.__LeafSize = __LeafSize or 200
obj.__empty = obj:New()
return obj
end
function Rope:__New(data, left, right, norebal)
local obj = setmetatable({}, self)
if data then
obj.__height = 1
obj.__data = data
obj.__count = 1
obj.__Lengths = data:Lengths()
assert(not (left or right), "branching leaf")
return obj
end
if left and not right then return left end
if right and not left then return right end
assert(left or right, "Bad")
obj.__height = math.max(left.__height, right.__height) + 1
obj.__count = left.__count + right.__count
obj.__left = left
obj.__right = right
local add = function(a,b) return a+b end
obj.__Lengths = self:LengthAdd(left:Lengths(), right:Lengths())
if not norebal then
if obj:__BalanceFactor() < -1 then
if left:__BalanceFactor() > 0 then
left = left:__rotateLeft()
end
obj = obj:__rotateRight()
left, right = obj.__left, obj.__right
elseif obj:__BalanceFactor() > 1 then
if right:__BalanceFactor() < 0 then
right = right:__rotateRight()
obj = self:__New(nil, left, right, true)
end
obj = obj:__rotateLeft()
left, right = obj.__left, obj.__right
end
end
return obj
end
Rope.__New = static(Rope.__New)
function Rope:__BalanceFactor()
if self.__height == 1 then return 0 end
return self.__right.__height - self.__left.__height
end
function Rope:New(...)
assert(self.String, "usage: Rope(String[, LeafSize]):New()")
local obj
for n = 1, select('#', ...) do
local v = select(n, ...)
local i = 1
local l = v:Length()
local objs = {}
if obj then
objs[#objs + 1] = obj
end
if l <= self.__LeafSize then
objs[#objs + 1] = self:__New(v)
else
while i <= l do
local s = v:Slice(i, i + self.__LeafSize - 1)
i = i + s:Length()
objs[#objs + 1] = self:__New(s)
end
end
obj = self:Join(objs)
end
return obj
end
function Rope:__rotateLeft()
if self.__height < 3 or self.__right.__height < 2 then
return self
end
local a, b, c =
self.__left,
self.__right.__left,
self.__right.__right
return self:__New(nil, self:__New(nil, a, b, true), c, true)
end
function Rope:__rotateRight()
if self.__height < 3 or self.__left.__height < 2 then
return self
end
local a, b, c =
self.__left.__left,
self.__left.__right,
self.__right
return self:__New(nil, a, self:__New(nil, b, c, true), true)
end
function Rope:Dump(i1)
i1 = i1 or ""
local i2 = i1 .. " "
if self.__data then
return self.__data:Dump(i1)
end
return (("%sRope(%s, height=%s(%s)) {\n%s\n%s\n%s}"):format(
i1,
DumpLengths(self),
self.__height,
self:__BalanceFactor(),
self.__left:Dump(i2),
self.__right:Dump(i2),
i1
))
end
function Rope:Length(Cat)
return self.String.Length(self, Cat)
end
function Rope:Lengths()
return self.__Lengths
end
function Rope:LengthAdd(this, other)
return self.String:LengthAdd(this, other)
end
function Rope:DefaultLengthAdd(this, other)
return self.String:DefaultLengthAdd(this, other)
end
function Rope:SliceTest(Cat, a, i,j, w)
return self.String:SliceTest(Cat, a, i,j, w)
end
function Rope:Leaves(rev)
if self.__data then
local b = true
return function()
if not b then
return
end
b = false
return self.__data
end
end
local function lazy(f)
local v = nil
local b = false
return function()
if not b then
v = f()
b = true
end
return v
end
end
local a, b =
lazy(function() return self.__left:Leaves(rev) end),
lazy(function() return self.__right:Leaves(rev) end)
if rev then
a, b = b, a
end
local function iter()
if not a then return end
local v = a()()
if v == nil then
a, b = b
return iter()
end
return v
end
return iter
end
function Rope:Implode()
if self.__data then
return self.__data
end
local leaves = {}
for leaf in self:Leaves() do
leaves[#leaves + 1] = leaf
end
return self.String:Join(leaves)
end
function Rope:__Join(other, rev)
if other.__height > self.__height then
return other:__Join(self, not rev)
end
if self.__data and other.__data then
if self:DefaultLengthAdd(self:Lengths(), other:Lengths()) <= self.__LeafSize then
if rev then
return self:__New(self.String:Join { other.__data, self.__data })
else
return self:__New(self.String:Join { self.__data, other.__data })
end
else
if rev then
return self:__New(nil, other, self)
else
return self:__New(nil, self, other)
end
end
end
if self.__height - other.__height > 1 or
(self.__height == 2
and other.__height == 1
and self:DefaultLengthAdd(self[rev and "__left" or "__right"]:Lengths(), other:Lengths()) <= self.__LeafSize)
then
if rev then
return self:__New(nil, self.__left:__Join(other, rev), self.__right)
else
return self:__New(nil, self.__left, self.__right:__Join(other, rev))
end
end
if rev then
return self:__New(nil, other, self)
else
return self:__New(nil, self, other)
end
end
function Rope:Join(Ropes)
local obj = self:PreJoin(Ropes, function(str)
local neut = false
return function()
if neut then return end
neut = true
return str
end
end, function(...)
return self:New(...)
end)
if obj then
return obj
end
for _, v in ipairs(Ropes) do
assert(v)
obj = obj and obj:__Join(v) or v
end
return obj
end
function Rope:SliceBy(Cat, i, j)
if i > j then
return self:Empty(self)
end
if self.__data then
local origin = self.__data
local sliced
if Cat == nil then
sliced = origin:Slice(i, j)
else
sliced = origin:SliceBy(Cat, i, j)
end
if origin == sliced then
return self
end
return self.__proto__:__New(sliced)
end
local test = function(a, i,j, w)
local b, ii, jj = self:SliceTest(Cat, a, i,j, w)
if b ~= nil then return b, ii, jj end
if not w then
return i<=a, i, j
else
return i>a or j>a, i-a, j-a
end
end
local t = {}
local f, ni, nj = test(self.__left:Length(Cat), i, j, false)
local f2, ni2, nj2 = test(self.__left:Length(Cat), i, j, true)
if f2 and i == -math.huge then
t[#t + 1] = self.__left
elseif f then
t[#t + 1] = self.__left:SliceBy(Cat, ni, f2 and math.huge or nj)
end
if f and j == math.huge then
t[#t + 1] = self.__right
elseif f2 then
t[#t + 1] = self.__right:SliceBy(Cat, f and -math.huge or ni2, nj2)
end
return self:Join(t)
end
function Rope:PreJoin(strs, bomb, factory)
return self.String.PreJoin(self, strs, function(obj)
return coroutine.wrap(function()
for obj in bomb(obj) do
for obj in obj:Leaves() do
coroutine.yield(obj)
end
end
end)
end, function(...)
return factory(self.String:New(...))
end)
end
function Rope:Empty(base)
return self:New(self.String:Empty(base))
end
function Rope:Slice(i, j)
return self:SliceBy(nil, i, j)
end
EditorString = class {}
function EditorString:__CharLProc(char, to)
if char == "\t" or char == "\n" then
to.tabcells_first = self:Empty(self):Lengths()
to.tabcells_last = self:Empty(self):Lengths()
to.tabcells = 2
else
to.tabcells_first = to
to.tabcells_last = to
to.tabcells = 1
end
if char == "\n" then
to.lines_first = self:Empty(self):Lengths()
to.lines_last = self:Empty(self):Lengths()
to.lines = 2
else
to.lines_first = to
to.lines_last = to
to.lines = 1
end
to.lines_longest_visual = to.lines_first
end
function EditorString:__NewLength()
local t = {
chars = 0,
visual = 0,
vis_broken_left = 0,
vis_broken_right = 0,
tabcells = 1,
lines = 1,
tabstop = nil,
offset = 0,
}
t.lines_first = t
t.lines_last = t
t.lines_longest_visual = t
t.tabcells_first = t
t.tabcells_last = t
return t
end
function EditorString:LengthAdd(this, other)
assert(
this.vis_broken_right == 0
and other.vis_broken_left == 0,
"cannot join")
local to = {}
assert(this.tabcells_first.tabcells == 1)
assert(this.tabcells_last.tabcells == 1)
assert(this.lines_first.lines == 1)
assert(this.lines_last.lines == 1)
to.chars = this.chars + other.chars
to.visual = this.visual + other.visual
to.vis_broken_left = this.vis_broken_left
to.vis_broken_right = other.vis_broken_right
to.tabcells = this.tabcells + other.tabcells - 1
to.lines = this.lines + other.lines - 1
to.tabstop = this.tabstop
to.offset = this.offset
if this.lines == 1 and other.lines > 1 then
to.lines_first = self:LengthAdd(
this,
other.lines_first
)
elseif this.lines == 1 then
to.lines_first = to
else
to.lines_first = this.lines_first
end
if other.lines == 1 and this.lines > 1 then
to.lines_last = self:LengthAdd(
this.lines_last,
other
)
elseif other.lines == 1 then
to.lines_last = to
else
to.lines_last = other.lines_last
end
if to.lines > 1 then
local longest = this.lines_longest_visual
if this.lines > 1 and other.lines > 1 then
local middle = self:LengthAdd(this.lines_last, other.lines_first)
longest = longest.visual < middle.visual and middle or longest
end
local last = to.lines_last
longest = longest.visual < last.visual and last or longest
local long2 = other.lines_longest_visual
longest = longest.visual < long2.visual and long2 or longest
to.lines_longest_visual = longest
else
to.lines_longest_visual = to
end
if this.tabcells == 1 and other.tabcells > 1 then
to.tabcells_first = self:LengthAdd(
this,
other.tabcells_first
)
elseif this.tabcells == 1 then
to.tabcells_first = to
else
to.tabcells_first = this.tabcells_first
end
if other.tabcells == 1 and this.tabcells > 1 then
to.tabcells_last = self:LengthAdd(
this.tabcells_last,
other
)
elseif other.tabcells == 1 then
to.tabcells_last = to
else
to.tabcells_last = other.tabcells_last
end
to.tabwidth = this.tabwidth or other.tabwidth or nil
if to.tabcells_first.chars == to.lines_first.chars then
to.tabwidth = nil
end
return to
end
function EditorString:DefaultLengthAdd(this, other)
return this.chars + other.chars
end
function EditorString:New(str, tabstop, offset)
local obj = setmetatable({}, self.__proto__)
offset = offset or 0
local i = 1
local t = {}
local charlen = self:__NewLength()
charlen.chars = 1
obj.__Lengths = self:__NewLength()
obj.__Lengths.tabstop = tabstop
obj.__Lengths.offset = offset % tabstop
while i <= #str do
local char = unicode.sub(str:sub(i, i+3), 1, 1)
i = i + #char
local charW
obj:__CharLProc(char, charlen)
if char == "\t" then
charW = tabstop - offset % tabstop
char = "\t" .. string.char(charW)
charlen.tabwidth = charW
else
charW = unicode.charWidth(char)
charlen.tabwidth = nil
end
if char == "\n" then
offset = -charW
end
charlen.visual = charW
offset = ((offset + charW) % tabstop)
obj.__Lengths = self:LengthAdd(
obj.__Lengths,
charlen,
obj.__Lengths
)
t[#t + 1] = char
end
obj.__data = table.concat(t)
return obj
end
function EditorString:SliceBy(Cat, i, j)
if i > j then
return self:Empty(self)
end
if (Cat == nil or Cat == "chars") and i <= 1 and j >= self.__Lengths.chars then
return self
end
local obj = setmetatable({}, self.__proto__)
obj.__Lengths = self:__NewLength()
obj.__Lengths.tabstop = self.__Lengths.tabstop
obj.__Lengths.offset = self.__Lengths.offset
local charlen = self:__NewLength()
charlen.chars = 1
local _ic = 1
local _i = 1
if Cat == "visual" then
_i = _i - self.__Lengths.vis_broken_left
j = math.min(self.__Lengths.visual, j)
i = math.max(1, i)
end
local t = {}
local left, right = 0, 0
while _ic <= #self.__data and _i <= j do
local char = unicode.sub(self.__data:sub(_ic, _ic+3), 1, 1)
local tab
_ic = _ic + #char
if char == "\t" then
tab = self.__data:sub(_ic, _ic)
_ic = _ic + 1
end
local charW
if tab then
charW = tab:byte()
else
charW = unicode.charWidth(char)
end
local ins
if Cat == nil or Cat == "chars" then
ins = _i >= i
if _i > j then
break
end
_i = _i + 1
elseif Cat == "visual" then
local _j = _i + charW - 1
if _i < i and _j >= i then
left = i - _i
ins = true
elseif _i >= i and _j > j then
right = _j - j
ins = true
elseif _i >= i then
ins = true
elseif _i > j then
break
end
_i = _j + 1
elseif Cat == "tabcells" or Cat == "lines" then
ins = _i >= i
local found = false
if char == "\n" or (Cat == "tabcells" and char == "\t") then
found = math.ceil(j) > j and _i <= j
_i = _i + 1
end
if _i > j and not found then
break
end
end
obj.__Lengths.offset = (obj.__Lengths.offset + charW) % obj.__Lengths.tabstop
if char == "\n" or tab then
obj.__Lengths.offset = 0
end
if ins then
self:__CharLProc(char, charlen)
if tab then
t[#t + 1] = char .. tab
charlen.tabwidth = tab:byte()
else
t[#t + 1] = char
charlen.tabwidth = nil
end
charlen.visual = charW
obj.__Lengths = self:LengthAdd(
obj.__Lengths,
charlen
)
end
end
obj.__Lengths.vis_broken_left = left
obj.__Lengths.vis_broken_right = right
obj.__data = table.concat(t)
return obj
end
function EditorString:PreJoin(strs, bomb, factory)
local modified = false
local strs2 = {}
local length
for k, v in ipairs(strs) do
local lv = v:Lengths()
if length then
if lv.tabstop ~= length.tabstop then
local tar = {}
for par in bomb(v) do
local offset = length.tabcell_last.visual
tar[#tar + 1] = factory(par:Implode(), length.tabstop, offset)
length = self:LengthAdd(length, tar[#tar]:Lengths())
end
v = self:Join(tar)
error("whag")
modified = true
else
local offset = length.tabcells_last.visual + lv.tabcells_first.visual
if lv.tabwidth and lv.tabcells_first.chars < lv.lines_first.chars
and length.tabcells >= 2
and lv.tabwidth ~= length.tabstop - offset % length.tabstop
then
v = self:Join {
v:Slice(-math.huge, lv.tabcells_first.chars),
factory("\t", length.tabstop, offset),
v:Slice(lv.tabcells_first.chars + 2, math.huge)
}
modified = true
end
length = self:LengthAdd(length, v:Lengths())
end
else
length = lv
end
assert(v)
strs2[#strs2 + 1] = v
end
if modified then
local jj = self:Join(strs2)
return jj
end
end
function EditorString:Join(strs)
if #strs == 0 then error(" ") end
local obj = self:PreJoin(strs, function(str)
local neut = false
return function()
if neut then return end
neut = true
return str
end
end, function(...)
return self:New(...)
end)
if obj then
return obj
end
obj = setmetatable({}, self)
obj.__Lengths = nil
local t = {}
for k, v in ipairs(strs) do
obj.__Lengths = obj.__Lengths
and self:LengthAdd(obj.__Lengths, v.__Lengths)
or v.__Lengths
t[#t + 1] = v.__data
end
obj.__data = table.concat(t)
return obj
end
EditorString.Join = static(EditorString.Join)
function EditorString:Implode(visual)
if visual then
local str = self.__data
local t = {}
local i = 1
local charWf = nil
local charWl = nil
while i <= #str do
local char = unicode.sub(self.__data:sub(i, i+3), 1, 1)
local tab
i = i + #char
if char == "\t" then
tab = self.__data:sub(i, i)
i = i + 1
end
local charW
if tab then
char = (" "):rep(tab:byte())
charW = #char
else
charW = unicode.charWidth(char)
end
if not charWf then
charWf = charW
end
charWl = charW
t[#t + 1] = char
end
if self:Length("vis_broken_left") > 0 then
t[1] = (" "):rep(charWf - self:Length("vis_broken_left"))
end
if self:Length("vis_broken_right") > 0 then
t[#t] = (" "):rep(charWl - self:Length("vis_broken_right"))
end
return table.concat(t)
end
return self.__data:gsub("\t(.)",function(tab)
return "\t"
end)
end
function EditorString:Slice(i, j)
return self:SliceBy(nil, i, j)
end
function EditorString:Dump(i1)
return i1.."String("..DumpLengths(self)..") "..(("%q"):format(self:Implode()):gsub("\\\n","\\n"))
end
function EditorString:SliceTest(Cat, a, i,j, w)
if Cat ~= "tabcells" and Cat ~= "lines" then
assert(
Cat == nil
or Cat == "chars"
or Cat == "visual",
"cannot slice"
)
return nil
end
if not w then
return i<=a, i, j
else
return i>=a or j>=a, i-a+1, j-a+1
end
end
function EditorString:Lengths()
return self.__Lengths
end
function EditorString:Length(Cat)
if Cat == nil then
return self:Length("chars")
end
return self:Lengths()[Cat]
end
function EditorString:Empty(base)
return self:New("", base:Length("tabstop"), 0)
end
EditorRope = Rope(EditorString)
function editor.new_buffer()
local buffer = {}
buffer.vdirty = {all=true}
buffer.data = EditorRope:New(EditorString:New("", editor.tabstop))
buffer.row = 1
buffer.col = 1
buffer.colTo = 1
buffer.vx = 1
buffer.vy = 1
return buffer
end
editor.movement = {}
editor.movement.arrows = {}
function editor.camera_move_horz(where)
local limit = editor.buffer.data
:SliceBy("lines",
editor.buffer.vy,
editor.buffer.vy + editor.buffer.vh - 1
)
:Lengths()
.lines_longest_visual
.visual - editor.buffer.vw + 2
local oldpos = editor.buffer.vx
local pos = math.max(1, math.min(limit, editor.buffer.vx + where))
if oldpos ~= pos then
editor.buffer.vx = pos
editor.buffer.vdirty = {all=true}
end
end
function editor.camera_notify_shift(r1, r2, where)
local gpu = term.gpu()
r1 = r1 - editor.buffer.vy + 1
r2 = r2 - editor.buffer.vy + 1
if (r1 > editor.buffer.vh and r2 > editor.buffer.vh) or (r1 < 1 and r2 < 1) then
return
end
r1, r2 = math.max(r1, 1), math.min(r2, editor.buffer.vh)
local t1, t2 = r1 + where, r2 + where
local o
if not editor.buffer.vdirty.all then
if math.abs(where) < editor.buffer.vh then
if where < 0 then
t2 = math.min(t2, editor.buffer.vh)
o = math.min(t2-t1+1, r2-r1+1)
r2, t2 = r1+o-1, t1+o-1
else
t1 = math.max(t1, 1)
o = math.min(t2-t1+1, r2-r1+1)
r1, t1 = r2-o+1, t2-o+1
end
gpu.copy(1, r1, editor.buffer.vw, o, 0, t1-r1)
local b2 = editor.buffer.vdirty
editor.buffer.vdirty = {}
for y = 1, #b2 do
if y >= t1 and y <= t2 then
editor.buffer.vdirty[y] = b2[y + (r1 - t1)]
elseif y >= r1 and y <= r2 then
editor.buffer.vdirty[y] = true
end
end
else
editor.buffer.vdirty.all = true
end
end
end
function editor.camera_move_vert(where)
local limit = editor.buffer.data:Length("lines") - editor.buffer.vh + 1
local oldpos = editor.buffer.vy
local pos = math.max(1, math.min(limit, editor.buffer.vy + where))
if oldpos ~= pos then
editor.camera_notify_shift(-math.huge, math.huge, oldpos - pos)
editor.buffer.vy = pos
end
end
function editor.cursor_move_horz(where)
local line = editor.buffer.data
:SliceBy("lines", editor.buffer.row, editor.buffer.row)
local width = line:Length()
local oldrow = editor.buffer.row
local oldcol = editor.buffer.col
editor.buffer.col = math.max(1, math.min(width + 1, editor.buffer.col + where))
if where == math.huge then
editor.buffer.colTo = math.huge
else
if not (oldrow == editor.buffer.row
and oldcol == editor.buffer.col)
then
editor.cursor_refresh_col()
end
end
end
function editor.cursor_refresh_col()
local colvis = editor.buffer.data
:SliceBy("lines", editor.buffer.row, editor.buffer.row)
:Slice(1,editor.buffer.col - 1)
:Length("visual") + 1
editor.buffer.colTo = colvis
end
function editor.cursor_move_vert(where)
editor.buffer.row = math.max(
1,
math.min(
editor.buffer.data:Length("lines"),
editor.buffer.row + where
)
)
local data = EditorRope:Join {
editor.buffer.data,
EditorRope:New(EditorString:New("\n", editor.buffer.data:Length("tabstop"), 0))
}
editor.buffer.col = data
:SliceBy("lines", editor.buffer.row, editor.buffer.row + .5)
:SliceBy("visual", -math.huge, editor.buffer.colTo)
:Length()
end
function editor.camera_to_cursor()
local colvis = editor.buffer.data
:SliceBy("lines", editor.buffer.row, editor.buffer.row)
:Slice(1,editor.buffer.col - 1)
:Length("visual") + 1
local x1,x2, y1,y2 =
editor.buffer.vx, editor.buffer.vx + editor.buffer.vw - 1,
editor.buffer.vy, editor.buffer.vy + editor.buffer.vh - 1
if colvis < x1 then
editor.camera_move_horz(colvis - x1)
elseif colvis > x2 then
editor.camera_move_horz(colvis - x2)
end
if editor.buffer.row < y1 then
editor.camera_move_vert(editor.buffer.row - y1)
elseif editor.buffer.row > y2 then
editor.camera_move_vert(editor.buffer.row - y2)
end
end
function outnormal_on_key(char, key, mod)
if key == "c" and mod.control then
editor.set_mode("normal")
return true
end
return
end
function rowcol_to_char(row, col, data)
return (data or editor.buffer.data)
:SliceBy("lines", -math.huge, row - 0.5)
:Length() + math.min(row >= 1 and (editor.buffer.data:SliceBy("lines", row, row):Length() + 1) or 0,math.max(1, col))
end
function char_to_rowcol(char, data)
local sub = (data or editor.buffer.data)
:Slice(-math.huge, char - 1)
local row = sub
:Length("lines")
local col = sub:Lengths().lines_last.chars + 1
return row, col
end
function rechar()
editor.buffer.row, editor.buffer.col = char_to_rowcol(rowcol_to_char(editor.buffer.row,editor.buffer.col))
end
function editor.delete(r1, c1, r2, c2)
if r1 > r2 or (r1 == r2 and c1 > c2) then
return editor.delete(r2, c2, r1, c1)
end
local i, j = rowcol_to_char(r1, c1), rowcol_to_char(r2, c2)
local count = j - i + 1
if count <= 0 then return end
local pos2 = rowcol_to_char(editor.buffer.row, editor.buffer.col)
local data = editor.buffer.data:Slice(i, j)
editor.buffer.data = EditorRope:Join {
editor.buffer.data:Slice(-math.huge, i - 1),
editor.buffer.data:Slice(j + 1, math.huge)
}
if pos2 > j then
editor.buffer.row, editor.buffer.col = char_to_rowcol(pos2 - count)
editor.cursor_refresh_col()
editor.camera_to_cursor()
elseif pos2 >= i then
editor.buffer.row, editor.buffer.col = char_to_rowcol(i)
editor.cursor_refresh_col()
editor.camera_to_cursor()
end
local r1v = r1 - editor.buffer.vy + 1
if r1v <= editor.buffer.vh and not editor.buffer.vdirty.all then
editor.buffer.vdirty[r1v] = true
editor.camera_notify_shift(r2 + 2, math.huge, -(data:Length("lines") - 1))
end
editor.buffer.dirty = true
end
function editor.insert(row, col, data)
local pos = rowcol_to_char(row, col)
editor.buffer.data = EditorRope:Join {
editor.buffer.data:Slice(-math.huge, pos - 1),
data,
editor.buffer.data:Slice(pos, math.huge)
}
local rv = row - editor.buffer.vy + 1
if rv <= editor.buffer.vh and not editor.buffer.vdirty.all then
editor.buffer.vdirty[rv] = true
editor.camera_notify_shift(rv + 1, math.huge, (data:Length("lines") - 1))
end
local pos2 = rowcol_to_char(editor.buffer.row, editor.buffer.col)
if pos2 >= pos then
editor.buffer.row, editor.buffer.col = char_to_rowcol(pos2 + data:Length())
editor.cursor_refresh_col()
editor.camera_to_cursor()
end
editor.buffer.dirty = true
end
function navigation_on_key(char, key, mod)
if tonumber(char) then
editor.counter = (editor.counter or 0)*10 + tonumber(char)
return true
end
local pg = math.ceil(editor.buffer.vh / 4)
if mod.control then
if key == "left" then
editor.camera_move_horz(-(editor.counter or 1))
elseif key == "right" then
editor.camera_move_horz((editor.counter or 1))
elseif key == "home" then
editor.camera_move_horz(-math.huge)
elseif key == "end" then
editor.camera_move_horz(math.huge)
elseif key == "up" then
editor.camera_move_vert(-(editor.counter or 1))
elseif key == "down" then
editor.camera_move_vert((editor.counter or 1))
elseif key == "pageUp" then
editor.camera_move_vert(-(editor.counter or 1) * pg)
elseif key == "pageDown" then
editor.camera_move_vert((editor.counter or 1) * pg)
else
return
end
else
if key == "left" then
editor.cursor_move_horz(-(editor.counter or 1))
elseif key == "right" then
editor.cursor_move_horz((editor.counter or 1))
elseif key == "home" then
editor.cursor_move_horz(-math.huge)
elseif key == "end" then
editor.cursor_move_horz(math.huge)
elseif key == "up" then
editor.cursor_move_vert(-(editor.counter or 1))
elseif key == "down" then
editor.cursor_move_vert((editor.counter or 1))
elseif key == "pageUp" then
editor.cursor_move_vert(-(editor.counter or 1) * pg)
editor.camera_move_vert(-(editor.counter or 1) * pg)
elseif key == "pageDown" then
editor.cursor_move_vert((editor.counter or 1) * pg)
editor.camera_move_vert((editor.counter or 1) * pg)
elseif char == "G" then
if not editor.counter then return end
local diff = editor.counter - editor.buffer.row
if diff ~= 0 then
editor.cursor_move_vert(diff)
end
else
return
end
editor.camera_to_cursor()
end
editor.counter = nil
return true
end
editor.modes = {}
editor.modes.normal = {}
function editor.modes.normal.init()
editor.set_status("")
editor.counter = nil
end
function editor.modes.normal.on_key(char, key, mod)
if outnormal_on_key(char, key, mod) then
return true
end
if char == "i" then
editor.set_mode("insert")
return true
end
if char == ":" then
editor.command_line()
return true
end
return navigation_on_key(char, key, mod)
end
editor.modes.insert = {}
function editor.modes.insert.init()
editor.set_status("-- INSERT --")
editor.counter = nil
end
function editor.modes.insert.on_key(char, key, mod)
if outnormal_on_key(char, key, mod) then
return true
end
if key == "back" then
local col = editor.buffer.col - 1
local row = editor.buffer.row
if col < 1 then row = row - 1 col = math.huge end
editor.delete(row, col, row, col)
return
elseif key == "delete" then
editor.delete(editor.buffer.row, editor.buffer.col, editor.buffer.row, editor.buffer.col)
return
end
if char == "\r" then
char = "\n"
end
if char then
editor.insert(editor.buffer.row, editor.buffer.col,
EditorRope:New(EditorString:New(char, editor.buffer.data:Length("tabstop"), 0))
)
end
return navigation_on_key(char, key, mod, true)
end
function editor.set_mode(mode)
editor.mode = editor.modes[mode]
editor.mode.init()
end
editor.status_line = ""
function editor.set_status(line)
editor.status_line = line
end
function editor.run()
while true do
editor.draw()
local ev = {(editor.buffer.cursor_oob and event or term).pull()}
if ev[1] == "key_down" then
local _, addr, char, code, player = (unpack or table.unpack)(ev)
editor.mode.on_key(char ~= 0 and unicode.char(char) or nil, keyboard.keys[code], {
control = keyboard.isControlDown(),
meta = keyboard.isAltDown(),
shift = keyboard.isShiftDown(),
})
end
end
end
function editor.set_cursor(x, y)
local ls = editor.buffer.data:Length("lines")
end
editor.cmd_hist = {}
function editor.command_line()
local gpu = term.gpu()
local vw, vh, vx, vy = term.getViewport()
term.setCursor(2,vh)
term.clearLine()
term.write(":")
local line = term.read(editor.cmd_hist)
editor.buffer.vdirty = {all = true}
if not line then
editor.set_status("")
return
end
line = line:match("([^\n]*)")
local cmd = line:match("([^ ]+)")
if not cmd then
editor.set_status("")
return
end
local param = line:sub(#cmd+2,-1)
editor.set_status(":"..line)
if not editor.commands[cmd] then
editor.set_status("No such command: "..cmd)
return
end
editor.commands[cmd](param)
end
function editor.draw()
local t = os.clock()
local gpu = term.gpu()
local vw, vh, vx, vy = term.getViewport()
local statusRight = {}
local resize = false
if editor.buffer.vw ~= vw or editor.buffer.vh ~= (vh-1) then
editor.buffer.vdirty.all = true
editor.buffer.vw = vw
editor.buffer.vh = vh - 1
end
editor.camera_move_horz(0)
editor.camera_move_vert(0)
if editor.buffer.vdirty.all then
editor.buffer.vdirty = {}
for n = 1, editor.buffer.vh do
editor.buffer.vdirty[n] = true
end
end
local ls = editor.buffer.data:Length("lines")
for y = 1, editor.buffer.vh do
if editor.buffer.vdirty[y] then
editor.buffer.vdirty[y] = false
local yy = editor.buffer.vy + y - 1
local xx = editor.buffer.vx
if yy < 1 or y > ls then
gpu.set(1, y, "~"..(" "):rep(vw - 1))
else
local pref = (" "):rep(math.max(0,1-xx))
local i = xx + #pref
local j = i + vw - #pref - 1
str = editor.buffer.data
:SliceBy("lines", yy, yy)
:SliceBy("visual", i, j)
local vlen = str:Length("visual")
str = str:Implode():Implode("visual")
str = pref .. str .. (" "):rep(vw - (vlen + #pref))
gpu.set(1, y, str)
end
end
end
local status = editor.status_line
if editor.counter then
statusRight[#statusRight+1] = editor.counter..""
end
local colvis = editor.buffer.data
:SliceBy("lines", editor.buffer.row, editor.buffer.row)
:Slice(1,editor.buffer.col - 1)
:Length("visual") + 1
statusRight[#statusRight + 1] = editor.buffer.row..","..editor.buffer.col.."-"..colvis
local lines = editor.buffer.data:Length("lines")
local where = (editor.buffer.vy - 1) / (lines - editor.buffer.vh)
if where == 0 then
where = "Top"
if lines < editor.buffer.vh then
where = "All"
end
elseif where == 1 then
where = "Bot"
else
where = ("%i%%"):format(math.floor(where * 100 + .5))
end
statusRight[#statusRight + 1] = where
statusRight = table.concat(statusRight," ")
status = status .. (" "):rep(vw - unicode.wlen(statusRight..status)) .. statusRight
gpu.set(1, vh, status)
local tx, ty =
colvis - editor.buffer.vx + 1,
editor.buffer.row - editor.buffer.vy + 1
if tx >= 1 and ty >= 1 and tx <= vw and ty < vh then
editor.buffer.cursor_oob = false
term.setCursor(tx, ty)
else
editor.buffer.cursor_oob = true
term.setCursor(1,1)
end
end
editor.tabstop = 4
function editor.__file_progressbar(file, progress, time, lines, chars)
local tw,th = term.getViewport()
local pgy = math.floor((th-2) / 2)
local pgw = math.ceil(tw*0.8)
local pgx = math.floor((tw-pgw)/2)
term.clear()
local oldbr = term.getCursorBlink()
term.setCursorBlink(false)
term.setCursor(pgx,pgy)
local progresst = math.floor(progress*(pgw-2)+.5)
term.write(("[%s%s]"):format(
("#"):rep(math.min(progresst,pgw-2)),
(" "):rep(pgw-2-progresst)
))
term.setCursor(pgx,pgy+2)
term.write(("%.1fs\t%q %sL, %sC"):format(time, file,
editor.buffer.data:Length("lines"),
editor.buffer.data:Length()))
term.setCursor(pgx+2+progresst,pgy)
term.setCursorBlink(oldbl)
end
function editor.commands.open(arg)
local file, err = io.open(arg,"rb")
if not file then
editor.set_status(err)
return nil, err
end
editor.buffer = editor.new_buffer()
editor.buffer.filename = arg
local block
local t = os.clock()
local tt = os.clock()
local invalid
local function check(s)
s = unicode.sub(s:sub(-4,-1), -1, -1)
if not pcall(unicode.charWidth, s) then
return #s
end
return 0
end
local tw,th = term.getViewport()
local pgy = math.floor((th-2) / 2)
local pgw = math.ceil(tw*0.8)
local pgx = math.floor((tw-pgw)/2)
local oldbl = term.getCursorBlink()
term.setCursorBlink(true)
term.clear()
local size = file:seek('end')
file:seek('set')
local progressb = 0
local progresst = 0
local begint = os.clock()
local drawbr = editor.__file_progressbar
drawbr(arg, 0, 0, 1, 0)
os.sleep()
while true do
block = file:read(40)
if not block then break end
if invalid then
block = invalid .. block
invalid = nil
end
local trail = check(block)
if trail > 0 then
invalid = block:sub(-trail, -1)
block = block:sub(1, -trail - 1)
end
local data = editor.buffer.data
local str = EditorString:New(block, editor.tabstop, data:Lengths().tabcells_last.chars)
local app = EditorRope:New(str)
editor.buffer.data = EditorRope:Join {
editor.buffer.data,
app
}
data = editor.buffer.data
progressb = progressb + #block
if os.clock()-tt > 0.5 then
drawbr(arg, progressb/size, os.clock()-begint, data:Length("lines"), data:Length())
os.sleep(0)
tt = os.clock()
end
end
editor.buffer.vdirty = {all=true}
os.sleep(0)
local data = editor.buffer.data
editor.set_status(("%q %sL, %sC"):format(arg, data:Length("lines"), data:Length()))
term.setCursorBlink(oldbl)
term.clear()
end
function editor.commands.eval(param)
local ok, err = (loadstring or load)(param)
local vw, vh = term.getViewport()
local out
if ok then
ok, err = pcall(function()
local ok, err = xpcall(ok,debug.traceback)
out = err
if type(out) ~= "string" then
out = serialization.serialize(out, vh)
end
return err
end)
end
err = out or err
err = text.detab(err)
err = {text.wrap(err, vw, vw)}
err[#err] = nil
if #err <= 1 then
editor.set_status(err[1] or "")
else
term.setCursor(1,vh)
term.clearLine()
print(table.concat(err,"\n"))
term.write("Press enter to continue... ")
editor.set_status("")
term.read()
editor.buffer.vdirty = {all=true}
end
end
function editor.commands.q()
os.exit()
end
function editor.commands.w(param)
if param == "" then param = nil end
param = editor.buffer.filename or param
if not param then
editor.set_status("No filename")
return
end
local file = io.open(param,"wb")
local progressb = 0
local size = editor.buffer.data:Length()
local begint = os.clock()
local drawbr = editor.__file_progressbar
drawbr(param, progressb/size, os.clock()-begint, 1, 0)
local len
local tt = os.clock()
for line in editor.buffer.data:Leaves() do
file:write((line:Implode()))
progressb = progressb + line:Length()
len = len and EditorString:LengthAdd(len, line:Lengths()) or line:Lengths()
if os.clock() - tt > 0.5 then
os.sleep()
tt = os.clock()
drawbr(param, progressb/size, os.clock()-begint, len.lines, len.chars)
end
end
file:close()
editor.set_status(("%q %sL, %sC written"):format(param, len.lines, len.chars))
editor.buffer.vdirty = {all = true}
editor.buffer.dirty = false
return true
end
function editor.commands.wq(param)
if not editor.commands.w(param) then
return
end
editor.commands.q()
return true
end
local function dirty_checked(k)
editor.commands[k .. "!"] = editor.commands[k]
editor.commands[k] = function(...)
if editor.buffer.dirty then
editor.set_status("No write since last change")
return
end
return editor.commands[k .. "!"](...)
end
end
dirty_checked("open")
dirty_checked("q")
editor.longopts = {}
editor.shortopts = {}
function editor.longopts.help()
local helpful_quotes = {
"Nothing is impossible, the word itself says ‘I’m possible.’",
"I cannot express how important it is to believe that taking one tiny—and possibly very uncomfortable—step at a time can ultimately add up to a great distance.",
"Here comes the sun. And I say, it’s all right.",
"Do your thing and don't care if they like it.",
"I’d rather regret the things I’ve done than the things I haven’t done.",
"Try to be a rainbow in someone else’s cloud.",
"Real change, enduring change, happens one step at a time.",
"A dead end is just a good place to turn around.",
"Choose to be optimistic, it feels better.",
"Just say yes and you’ll figure it out afterwards.",
"You can’t make a cloudy day a sunny day, but you can embrace it and decide it’s going to be a good day after all.",
"Find a group of people who challenge and inspire you, spend a lot of time with them, and it will change your life.",
"You can, you should, and if you’re brave enough to start, you will.",
"In your life expect some trouble. But when you worry, you make it double. But don't worry, be happy, be happy now.",
"You’re in the same boat with a lotta your friends. Waitin’ for the day your ship’ll come in, and the tide's gonna turn and it’s all gonna roll your way.",
"Keep your face always toward the sunshine, and shadows will fall behind you.",
"You are never too old to set another goal or to dream a new dream.",
"Life is like riding a bicycle. To keep your balance, you must keep moving.",
"It is never too late to be what you might have been.",
"Some people look for a beautiful place. Others make a place beautiful.",
"We must be willing to let go of the life we planned so as to have the life that is waiting for us.",
"Happiness is not by chance, but by choice.",
"If I cannot do great things, I can do small things in a great way.",
"My mission in life is not merely to survive, but to thrive.",
"You are enough just as you are.",
"The bad news is time flies. The good news is you're the pilot.",
"You make a life out of what you have, not what you're missing.",
"There are years that ask questions and years that answer.",
"All we have to decide is what to do with the time that is given us.",
"At first people refuse to believe that a strange new thing can be done, then they begin to hope it can be done, then they see it can be done—then it is done and all the world wonders why it was not done centuries ago.",
"Each of us is more than the worst thing we've ever done.",
"That is one good thing about this world ... there are always sure to be more springs.",
"These things are good things.",
"Pay attention to the present, you can improve upon it.",
"Be yourself; everyone else is already taken.",
"Imperfection is beauty, madness is genius and it's better to be absolutely ridiculous than absolutely boring.",
"You cannot change what you are, only what you do.",
"Thou must gather thine own sunshine.",
"It is not enough to have a good mind; the important thing is to use it well.",
"People begin to become successful the minute they decide to be.",
"Walk to your goal firmly and with bold steps.",
"Every strike brings me closer to the next home run.",
"Concentrate all your thoughts upon the work in hand. The Sun's rays do not burn until brought to a focus.",
"Lay plans for something big by starting with it when small.",
"No exact recipe for today. Gather all available ingredients and whip yourself up something delicious.",
"One's destination is never a place, but a new way of seeing things.",
"It's how you deal with failure that determines how you achieve success.",
"I have not failed. I've just found 10,000 ways that won't work.",
"It takes as much energy to wish as it does to plan.",
"Do anything, but let it produce joy.",
"Do your little bit of good where you are; it's those little bits of good put together that overwhelm the world.",
"No one is useless in this world who lightens the burdens of another.",
"As we work to create light for others, we naturally light our own way.",
"Dwell on the beauty of life. Watch the stars, and see yourself running with them.",
"That's what I consider true generosity: You give your all, and yet you always feel as if it costs you nothing.",
"You have brains in your head. You have feet in your shoes. You can steer yourself any direction you choose.",
"You rarely win, but sometimes you do.",
"I've got nothing to do today but smile.",
"I believe great people do things before they are ready.",
"I have discovered in life that there are ways of getting almost anywhere you want to go, if you really want to go.",
"If you spend too much time thinking about a thing, you'll never get it done.",
"For me, becoming isn't about arriving somewhere or achieving a certain aim. I see it instead as forward motion, a means of evolving, a way to reach continuously toward a better self. The journey doesn't end.",
"Anything is possible with sunshine and a little pink.",
"Imagine this: What would happen if we were all brave enough to believe in our own ability, to be a little more ambitious? I think the world would change.",
"You are the one that possesses the keys to your being. You carry the passport to your own happiness.",
"Take your victories, whatever they may be, cherish them, use them, but don't settle for them.",
"We do not need magic to change the world, we carry all the power we need inside ourselves already: We have the power to imagine better.",
"Just believe in yourself. Even if you don’t, pretend that you do and, at some point, you will.",
"Believe you can and you're halfway there.",
"You are imperfect, you are wired for struggle, but you are worthy of love and belonging.",
"If you see someone without a smile, give 'em yours!",
"You get in life what you have the courage to ask for.",
"Act as if what you do makes a difference. It does.",
"For there is always light. If only we’re brave enough to see it. If only we’re brave enough to be it.",
"You are your best thing.",
"There is no greater thing you can do with your life and your work than follow your passions–in a way that serves the world and you.",
"We talk on principal, but act on motivation.",
"The secret of getting ahead is getting started.",
"Winners never quit, and quitters never win.",
"When the going gets tough, the tough get going.",
"The best way to predict the future is to create it.",
"Always make a total effort, even when the odds are against you.",
"Don’t be afraid to give up the good to go for the great.",
"Don’t let the fear of losing be greater than the excitement of winning.",
"The question isn’t who is going to let me; it’s who is going to stop me.",
"It is better to fail in originality than to succeed in imitation.",
"Start where you are. Use what you have. Do what you can.",
"Your present circumstances don’t determine where you can go; they merely determine where you start.",
"You must expect great things of yourself before you can do them.",
"Do what you have to do until you can do what you want to do.",
"You can never cross the ocean until you have the courage to lose sight of the shore.",
"One way to keep momentum going is to have constantly greater goals.",
"You don’t have to see the whole staircase, just take the first step.",
"We are what we repeatedly do. Excellence, then, is not an act, but a habit.",
"God always strives together with those who strive.",
"Change your thoughts and you change your world.",
"It’s hard to beat a person who never gives up.",
"The only person you should try to be better than, is the person you were yesterday.",
"Never give up, for that is just the place and time that the tide will turn.",
"The difference between a stumbling block and a stepping stone is how high you raise your foot.",
"Study while others are sleeping; work while others are loafing; prepare while others are playing; and dream while others are wishing.",
"The difference between the impossible and the possible lies in a person’s determination.",
"More powerful than the will to win is the courage to begin.",
"Don’t be pushed by your problems; be led by your dreams.",
"You don’t drown by falling in water; you drown by staying there.",
"If you’re going through hell, keep going",
"Better to do something imperfectly than to do nothing flawlessly.",
"Our greatest weakness lies in giving up. The most certain way to succeed is always to try just one more time.",
"Fortune sides with him who dares.",
"If you want something you’ve never had, you must be willing to do something you’ve never done.",
"Nobody can go back and start a new beginning, but anyone can start today and make a new ending.",
"Nothing will work unless you do.",
"The more I want to get something done the less I call it work.",
"The work you do when you procrastinate is probably the work you should be doing for the rest of your life.",
"Focus on being productive instead of busy.",
"The beginning is the most important part of the work.",
"An employee’s motivation is a direct result of the sum of interactions with his or her manager.",
"If you don’t value your time, neither will others. Stop giving away your time and talents- start charging for it.",
"Things work out best for those who make the best of how things work out.",
"There will be obstacles. There will be doubters. There will be mistakes. But with hard work, there are no limits.",
"Build your own dreams, or someone else will hire you to build theirs.",
"If you are working on something that you really care about, you don’t have to be pushed. The vision pulls you.",
"To be successful you must accept all challenges that come your way. You can’t just accept the ones you like.",
"If you want to achieve excellence, you can get there today. As of this second, quit doing less-than-excellent work.",
"The only place where success comes before work is in the dictionary.",
"We aim above the mark to hit the mark.",
"Successful and unsuccessful people do not vary greatly in their abilities. They vary in their desires to reach their potential.",
"When someone tells me ‘no,’ it doesn’t mean I can’t do it, it simply means I can’t do it with them.",
"Strive not to be a success, but rather to be of value.",
"The individual who says it is not possible should get out of the way of those doing it.",
"You’ve got to get up every morning with determination if you’re going to go to bed with satisfaction.",
"I find that the harder I work, the more luck I seem to have.",
"Do not wait to strike till the iron is hot; but make it hot by striking.",
"Focus on the journey, not the destination. Joy is found not in finishing an activity but in doing it.",
"The secret of joy in work is contained in one word – excellence. To know how to do something well is to enjoy it.",
"Much of the stress that people feel doesn’t come from having too much to do. It comes from not finishing what they’ve started.",
"Don’t let what you cannot do interfere with what you can do.",
"The wise does at once what the fool does at last.",
"To know and not to do, is not to know.",
"Zeal without knowledge is fire without light.",
"Perfection is boring. Getting better is where all the fun is.",
"Our greatest fear should not be of failure but of succeeding at things in life that don’t really matter.",
"The most common way people give up their power is by thinking they don’t have any.",
"It’s not what you look at that matters, it’s what you see.",
"Somewhere, something incredible is waiting to be known.",
"Experience is a hard teacher because she gives the test first, the lesson afterwards.",
"Keep your eyes on the stars, and your feet on the ground.",
"I have been impressed with the urgency of doing. Knowing is not enough; we must apply. Being willing is not enough; we must do.",
"There are two kinds of people in this world; those who want to get things done, and those who don’t want to make mistakes.",
"If you are not willing to risk the usual you will have to settle for the ordinary.",
"Live out of your imagination, not your history.",
"If the decisions you make about where you invest your blood, sweat, and tears are not consistent with the person you aspire to be, you’ll never become that person.",
"A person who never made a mistake never tried anything new.",
"Always remember that you are absolutely unique; just like everyone else.",
"Twenty years from now you will be more disappointed by the things that you didn’t do than by the ones you did do, so throw off the bowlines, sail away from safe harbor, catch the trade winds in your sails. Explore, Dream, Discover.",
"The will to succeed is important, but what’s more important is the will to prepare.",
"Obstacles don’t have to stop you. If you run into a wall, don’t turn around and give up.",
"We can’t help everyone, but everyone can help someone.",
"There are two types of people who will tell you that you cannot make a difference in this world: those who are afraid to try and those who are afraid you will succeed.",
"We become what we think about most of the time, and that’s the strangest secret.",
"Develop success from failures. Discouragement and failure are two of the surest stepping stones to success.",
"If you continue to think they way you’ve always thought, you’ll continue to get what you’ve always got.",
"If you can imagine it, you can achieve it; if you can dream it, you can become it.",
"It is during our darkest moments that we must focus to see the light.",
"The more difficult the victory, the greater the happiness in winning.",
"Good things come to people who wait, but better things come to those who go out and get them.",
"Your talent is God’s gift to you. What you do with it is your gift back to God.",
"Real difficulties can be overcome; it is only the imaginary ones that are unconquerable.",
"You measure the size of the accomplishment by the obstacles you had to overcome to reach your goals.",
"The key is to keep company only with people who uplift you, whose presence calls forth your best.",
"Nurture your mind with great thoughts. To believe in the heroic makes heroes.",
"Don’t spend time beating on a wall, hoping to transform it into a door.",
"Work like there is someone working 24 hours a day to take it away from you.",
"I am not a product of my circumstances. I am a product of my decisions.",
"Press forward. Do not stop, do not linger in your journey, but strive for the mark set before you.",
"I can’t change the direction of the wind, but I can adjust my sails to always reach my destination.",
"Some people want it to happen, some wish it would happen, others make it happen.",
"You can’t put a limit on anything. The more you dream, the further you get.",
"Whatever the mind of man can conceive, and bring itself to believe, it can achieve.",
"Find a victory in every defeat to remain hopeful, and find a defeat in every victory to remain humble.",
"The reason most people never reach their goals is that they don’t define them, or ever seriously consider them as believable or achievable. Winners can tell you where they are going, what they plan to do along the way, and who will be sharing the adventure with them.",
"The tragedy in life doesn’t lie in not reaching your goal. The tragedy lies in having no goal to reach.",
"Don’t judge each day by the harvest you reap but by the seeds that you plant.",
"Don’t worry about the world coming to an end today. It’s already tomorrow in Australia.",
"Don’t downgrade your dream just to fit your reality. Upgrade your conviction to match your destiny.",
"Aim for the moon. If you miss, you may hit a star.",
"People often say that motivation doesn’t last. Well, neither does bathing – that’s why we recommend it daily.",
"Motivation is a fire from within. If someone else tries to light that fire under you, chances are it will burn very briefly.",
"There is only one motivation, and that is desire. No reasons or principle contain it or stand against it.",
"Everything boils down to motivation.",
"Be miserable. Or motivate yourself. Whatever has to be done, it’s always your choice.",
"Desire is the key to motivation, but it’s determination and commitment to an unrelenting pursuit of your goal — a commitment to excellence — that will enable you to attain the success you seek.",
"Competition is the best form of motivation.",
"Motivation, passion, and focus have to come from the top.",
"Motivation is what gets you started. Habit is what keeps you going.",
"Your talent determines what you can do. Your motivation determines how much you’re willing to do. Your attitude determines how well you do it.",
"Music – it’s motivational and just makes you relax.",
"When you fail you learn from the mistakes you made and it motivates you to work even harder.",
"I’m not one for those motivational speeches. I’ve always been more of an example guy.",
"People always need to hear good motivational speeches.",
"Real obsession needs an unconscious motivation behind it.",
"Motivation is the art of getting people to do what you want them to do because they want to do it.",
"With the new year comes a refueled motivation to improve on the past one.",
"Once something is a passion, the motivation is there.",
"A champion needs a motivation above and beyond winning.",
"For me, motivation is a person who has the capability to recruit the resources he needs to achieve a goal.",
"Don’t worry about motivation. Motivation is fickle. It comes and goes. It is unreliable – and when you are counting on motivation to get your goals accomplished, you will likely fall short.",
"Enthusiasm is excitement with inspiration, motivation, and a pinch of creativity.",
"I think it all comes down to motivation. If you really want to do something, you will work hard for it.",
"Motivation is everything. You can do the work of two people, but you can’t be two people. Instead, you have to inspire the next guy down the line and get him to inspire his people.",
"I didn’t need to be motivated by other people overlooking me. My motivation was internal, to be better every day.",
"Our greatest motivation in life comes from not knowing the future.",
"The changing of the goals helps keep the motivation fresh.",
"Other people’s success spurs me on to do well and gives me motivation.",
"If you want to lift yourself up, lift up someone else.",
"You are braver than you believe, stronger than you seem and smarter than you think.",
"I’m self-motivated. I’m motivated for myself to be the best I can be – for me to do that, I have to have my own motivation, my own positive energy.",
"I am not afraid… I was born to do this.",
"The distance between insanity and genius is measured only by success.",
"Don’t wait for your feelings to change to take the action. Take the action and your feelings will change.",
"If you want to make a permanent change, stop focusing on the size of your problems and start focusing on the size of you!",
"Very often a change of self is needed more than a change of scene.",
"If people are doubting how far you can go, go so far that you can’t hear them anymore.",
"There is no chance, no destiny, no fate, that can hinder or control the firm resolve of a determined soul.",
"Make sure your worst enemy doesn’t live between your own two ears.",
"It’s no use going back to yesterday, because I was a different person then.",
"The same boiling water that softens the potato hardens the egg. It’s what you’re made of. Not the circumstances.",
"You are confined only by the walls you build yourself.",
"What we achieve inwardly will change outer reality.",
"Man never made any material as resilient as the human spirit.",
"It isn’t the mountains ahead to climb that wear you out; it’s the pebble in your shoe.",
"Believe in yourself! Have faith in your abilities! Without a humble but reasonable confidence in your own powers you cannot be successful or happy.",
"The number one reason people fail in life is because they listen to their friends, family, and neighbors.",
"Where there is a will, there is a way. If there is a chance in a million that you can do something, anything, to keep what you want from ending, do it. Pry the door open or, if need be, wedge your foot in that door and keep it open.",
"When we strive to become better than we are, everything around us becomes better too.",
"With self-discipline most anything is possible.",
"When you’ve got something to prove, there’s nothing greater than a challenge.",
"Throw me to the wolves and I will return leading the pack.",
"It is a paradoxical but profoundly true and important principle of life that the most likely way to reach a goal is to be aiming not at that goal itself but at some more ambitious goal beyond it.",
"Perfection is not attainable, but if we chase perfection we can catch excellence.",
"Little minds are tamed and subdued by misfortune; but great minds rise above it.",
"All men who have achieved great things have been great dreamers.",
"Most of the important things in the world have been accomplished by people who have kept on trying when there seemed to be no help at all.",
"Don’t watch the clock; do what it does. Keep going.",
"To accomplish great things, we must not only act, but also dream, not only plan, but also believe.",
"Never do tomorrow what you can do today. Procrastination is the thief of time.",
"You may only succeed if you desire succeeding; you may only fail if you do not mind failing.",
"Action may not always bring happiness; but there is no happiness without action.",
"Everything you’ve ever wanted is on the other side of fear.",
"Your passion is waiting for your courage to catch up.",
"Do not wait; the time will never be ‘just right.’ Start where you stand, and work with whatever tools you may have at your command, and better tools will be found as you go along.",
"There are only two options regarding commitment. You’re either in or you’re out. There is no such thing as life in-between.",
"Never give in. Never, never, never, never—in nothing, great or small, large or petty—never give in, except to convictions of honour and good sense. Never yield to force. Never yield to the apparently overwhelming might of the enemy.",
"Live with intention. Walk to the edge. Listen hard. Practice wellness. Play with abandon. Laugh. Choose with no regret. Do what you love. Live as if this is all there is.",
"Things may come to those who wait, but only the things left by those who hustle.",
"Don’t live the same year 75 times and call it a life.",
"Do or do not. There is no try.",
"If you’re offered a seat on a rocket ship, don’t ask what seat! Just get on.",
"Give yourself an even greater challenge than the one you are trying to master and you will develop the powers necessary to overcome the original difficulty.",
"Change your life today. Don’t gamble on the future, act now, without delay.",
"How wonderful it is that nobody need wait a single moment before starting to improve the world.",
"Dream as if you’ll live forever, live as if you’ll die today.",
"Enter every activity without giving mental recognition to the possibility of defeat. Concentrate on your strengths, instead of your weaknesses… on your powers, instead of your problems.",
"My attitude is that if you push me towards something that you think is a weakness, then I will turn that perceived weakness into a strength.",
"If you want to achieve greatness stop asking for permission.",
"Taking it easy won’t take you anywhere.",
"Yesterday is not ours to recover, but tomorrow is ours to win or lose.",
"Fairy tales are more than true: not because they tell us that dragons exist, but because they tell us that dragons can be beaten.",
"Do what you feel in your heart to be right―for you’ll be criticized anyway.",
"Accept the challenges so that you can feel the exhilaration of victory.",
"When nothing seems to help, I go and look at a stonecutter hammering away at his rock perhaps a hundred times without as much as a crack showing in it. Yet at the hundred and first blow it will split in two, and I know it was not that blow that did it – but all that had gone before.",
}
print(helpful_quotes[math.random(1, #helpful_quotes)])
os.exit()
end
editor.shortopts['?'] = editor.longopts.help
return main()
|
post a comment