previndexinfo

code guessing, round #62 (completed)

started at ; stage 2 at ; ended at

specification

FUCK
your challenge is to implement a text editor. submissions may be written in any language.

what is a text editor? well, it's a program that can:

they usually have more features than this, but that's the minimum baseline here. good luck.

results

  1. 👑 moshikoi +6 -0 = 6
    1. seshoumara
    2. Dolphy (was kimapr)
    3. kotnen
    4. yeti (was Dolphy)
    5. LyricLy (was Proloy)
    6. luatic
    7. at (was LyricLy)
    8. Olivia
    9. yui
    10. kimapr (was yeti)
    11. taswelll
    12. Proloy (was at)
  2. LyricLy +8 -3 = 5
    1. seshoumara
    2. kimapr
    3. kotnen
    4. moshikoi (was Dolphy)
    5. Proloy
    6. luatic
    7. Olivia
    8. yui (was moshikoi)
    9. yeti (was yui)
    10. Dolphy (was yeti)
    11. taswelll
    12. at
  3. Dolphy +6 -1 = 5
    1. seshoumara
    2. kimapr
    3. yeti (was kotnen)
    4. at (was Proloy)
    5. luatic
    6. LyricLy
    7. Olivia
    8. yui (was moshikoi)
    9. kotnen (was yui)
    10. Proloy (was yeti)
    11. taswelll
    12. moshikoi (was at)
  4. yui +6 -1 = 5
    1. seshoumara
    2. kimapr
    3. Dolphy (was kotnen)
    4. kotnen (was Dolphy)
    5. yeti (was Proloy)
    6. luatic
    7. moshikoi (was LyricLy)
    8. Olivia
    9. LyricLy (was moshikoi)
    10. Proloy (was yeti)
    11. taswelll
    12. at
  5. Proloy +5 -1 = 4
    1. seshoumara
    2. kimapr
    3. kotnen
    4. at (was Dolphy)
    5. luatic
    6. Dolphy (was LyricLy)
    7. Olivia
    8. yui (was moshikoi)
    9. taswelll (was yui)
    10. LyricLy (was yeti)
    11. yeti (was taswelll)
    12. moshikoi (was at)
  6. yeti +3 -2 = 1
    1. seshoumara
    2. taswelll (was kimapr)
    3. kimapr (was kotnen)
    4. at (was Dolphy)
    5. LyricLy (was Proloy)
    6. luatic
    7. moshikoi (was LyricLy)
    8. Olivia
    9. yui (was moshikoi)
    10. kotnen (was yui)
    11. Dolphy (was taswelll)
    12. Proloy (was at)
  7. at +3 -2 = 1
    1. seshoumara
    2. luatic (was kimapr)
    3. yui (was kotnen)
    4. Proloy (was Dolphy)
    5. LyricLy (was Proloy)
    6. moshikoi (was luatic)
    7. kotnen (was LyricLy)
    8. Olivia
    9. yeti (was moshikoi)
    10. Dolphy (was yui)
    11. kimapr (was yeti)
    12. taswelll
  8. luatic +7 -8 = -1
    1. seshoumara
    2. kimapr
    3. kotnen
    4. at (was Dolphy)
    5. moshikoi (was Proloy)
    6. LyricLy
    7. Olivia
    8. Proloy (was moshikoi)
    9. Dolphy (was yui)
    10. yeti
    11. taswelll
    12. yui (was at)
  9. taswelll +6 -7 = -1
    1. seshoumara
    2. Dolphy (was kimapr)
    3. kotnen
    4. kimapr (was Dolphy)
    5. moshikoi (was Proloy)
    6. luatic
    7. LyricLy
    8. Olivia
    9. Proloy (was moshikoi)
    10. at (was yui)
    11. yeti
    12. yui (was at)
  10. kotnen +3 -5 = -2
    1. seshoumara
    2. kimapr
    3. luatic (was Dolphy)
    4. LyricLy (was Proloy)
    5. Dolphy (was luatic)
    6. yeti (was LyricLy)
    7. Olivia
    8. yui (was moshikoi)
    9. at (was yui)
    10. Proloy (was yeti)
    11. moshikoi (was taswelll)
    12. taswelll (was at)
  11. kimapr +4 -7 = -3
    1. seshoumara
    2. Dolphy (was kotnen)
    3. at (was Dolphy)
    4. yeti (was Proloy)
    5. luatic
    6. Proloy (was LyricLy)
    7. Olivia
    8. yui (was moshikoi)
    9. kotnen (was yui)
    10. LyricLy (was yeti)
    11. taswelll
    12. moshikoi (was at)
  12. seshoumara +2 -11 = -9
    1. kimapr
    2. at (was kotnen)
    3. Proloy (was Dolphy)
    4. luatic (was Proloy)
    5. kotnen (was luatic)
    6. yeti (was LyricLy)
    7. Olivia
    8. Dolphy (was moshikoi)
    9. taswelll (was yui)
    10. LyricLy (was yeti)
    11. yui (was taswelll)
    12. moshikoi (was at)
  13. Olivia +1 -12 = -11
    1. luatic (was seshoumara)
    2. kotnen (was kimapr)
    3. kimapr (was kotnen)
    4. Dolphy
    5. LyricLy (was Proloy)
    6. yui (was luatic)
    7. moshikoi (was LyricLy)
    8. seshoumara (was moshikoi)
    9. yeti (was yui)
    10. taswelll (was yeti)
    11. at (was taswelll)
    12. Proloy (was at)

entries

you can download all the entries

entry #1

written by seshoumara
submitted at
1 like

guesses
comments 0

post a comment


cg62_editor.sed ASCII text
  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
#!/usr/bin/sed -nrf

#################################################### WARNING ####################################################
#                               Back-up any file before you open it in this editor!!                            #
#################################################################################################################

:_Problem
    # text editor
    # https://cg.esolangs.gay/62/
:_Restrictions
    # run as: FILE="file.txt" ./cg62_editor.sed (stdin used for input of commands)
    # escape character (\o033) and "EOF" keyword are reserved, can't be in the file
    # errors aren't handled, they close the editor instantly (no save!)
    # vertical scrolling isn't implemented, cursor can go out of screen (use file with few lines to test)


################################################# SETUP #########################################################

:init
	1v;1x
	1b f5
1!b apply_cmd

################################################# COMMANDS ######################################################

:apply_cmd
	/^u$/		{	x;b u		}
	/^uu$/		{	x;b uu		}
	/^d$/		{	x;b d		}
	/^dd$/		{	x;b dd		}
	/^l$/		{	x;b l		}
	/^ll$/		{	x;b ll		}
	/^r$/		{	x;b r		}
	/^rr$/		{	x;b rr		}
	/^tab$/		{	x;b tab		}
	/^enter$/	{	x;b enter	}
	/^i ./		{	x;b i		}
	/^k$/		{	x;b k		}
	/^kk$/		{	x;b kk		}
	/^kkk$/		{	x;b kkk		}
	/^clear$/	{	x;b clear	}
	/^f5$/		{	x;b f5		}
	/^s$/		{	x;b s		}
	/^quit$/	{	x;b quit	}
	/^help$/	{	x;b help	}
	s@.*@Input error: unknown command!.@p
b quit_error

:u
	/^0/b display
	s:([^\n]*\n?[^\n]*)(\o033\[91m>\o033\[0m):\2\1:
	s:^(\o033\[91m>\o033\[0m)1:1\1:
b display

:uu
	/^1/s:^1(.*)(\o033\[91m>\o033\[0m):1\2\1:
b display

:d
	/^1/s:(\o033\[91m>\o033\[0m)([^\n]*\n?):\2\1:
b display

:dd
	/^1/s:(\o033\[91m>\o033\[0m)(.*):\2\1:
b display

:l
	/^1/s:^(1.*)(.)(\o033\[91m>\o033\[0m):\1\3\2:
b display

:ll
	/^0/b display
	s:([^\n]*)(\o033\[91m>\o033\[0m):\2\1:
	s:^(\o033\[91m>\o033\[0m)1:1\1:
b display

:r
	/^1/s:(\o033\[91m>\o033\[0m)(.):\2\1:
b display

:rr
	/^1/s:(\o033\[91m>\o033\[0m)([^\n]*):\2\1:
b display

:tab
	/^1/s:\o033\[91m>\o033\[0m:\t&:
b display

:enter
	/^1/s:\o033\[91m>\o033\[0m:\n&:
b display

:i
	/^0/b display
	x
	s:^i ::
	/\o033/{
		s@.*@Input error: ESCAPE is a reserved character!@p
		b quit_error
	}
	/EOF/{
		s@.*@Input error: 'EOF' is a reserved keyword!@p
		b quit_error
	}
	G;h;x
	s:^([^\n]+)\n(1.*)(\o033\[91m>\o033\[0m):\2\1\3:
b display

:k
	/^1/s:(\o033\[91m>\o033\[0m).:\1:
b display

:kk
	/^1/s:(\o033\[91m>\o033\[0m)[^\n]*:\1:
b display

:kkk
	/^1/s:(\o033\[91m>\o033\[0m).*:\1:
b display

:clear
	/^1/s:.*:1\o033[91m>\o033[0m:
b display

:f5
	/^0/b display
	s:.*:cat "$FILE":e
	#how to test if file doesn't exist?
	/\o033/{
		s@.*@File error: ESCAPE is a reserved character!@p
		b quit_error
	}
	/EOF/{
		s@.*@File error: 'EOF' is a reserved keyword!@p
		b quit_error
	}
	s:^:1\o033[91m>\o033[0m:
b display

:s
	/^0/b display
	h;x
	s:^1::
	s:\o033\[91m>\o033\[0m::
	s:.*:cat << 'EOF' > "$FILE"\n&\nEOF:e
	x
b display

:quit
b quit_ok

:help
	/^0/{
		s::1:
		b display
	}
	s:^1:0:
b display

:get_help
	#this should have been part of :help, but then both pattern and hold space would be occupied
	#display needs one free space to call to bash and other things, so the help text is JIT generated
	s:.*:u    move cursor to the start of the line above\n:
	s:$:uu    move cursor to the start of the file\n:
	s:$:d     move cursor to the start of the line below\n:
	s:$:dd    move cursor to the end of the file\n\n:
	s:$:l     move cursor to the left\n:
	s:$:ll    move cursor to the start of the current line\n:
	s:$:r     move cursor to the right\n:
	s:$:rr    move cursor to the end of the current line\n\n:
	s:$:tab   insert tab\n:
	s:$:enter insert enter\n:
	s:$:i TXT insert TXT characters (except tab and enter)\n\n:
	s:$:k     kill character after the cursor\n:
	s:$:kk    kill all characters after the cursor till the end of the current line\n:
	s:$:kkk   kill all characters after the cursor till the end of the file\n:
	s:$:clear kill all characters from the file\n\n:
	s:$:f5    reload content from the file on disk (unsaved changes lost)\n:
	s:$:s     save content to file on disk\n:
	s:$:quit  quit, discarding all changes! (works in help mode)\n\n:
	s:$:help  toggle this help screen (works in help mode):
b continue_display

################################################# DISPLAY #######################################################

:display
	/^1/{
		h;x
		s:::
	}
	/^0/{
		x
		b get_help
		:continue_display
	}
	:number_lines_and_wrap
		#Shit! No time left, let's cheat :D
		s@.*@cat -n << 'EOF'|sed 's:^[ \t]*::;s:\t:):'|fold -$(tput cols)\n&\nEOF@e
	#clear screen
	s:^:\o033[H\o033[J:
	s@$@\n~\nEnter command (type help for a list of available commands):@p
b EOS

:get_terminal_stats
	#sed can't directly access environmental var $FILE and terminal size
	s:.*:echo "$FILE";tput cols;tput lines:e
b#?

################################################# THE END #######################################################

:quit_ok
	Q 0

:quit_error
	Q 1

:EOS

entry #2

written by kimapr
submitted at
0 likes

guesses
comments 0

post a comment


emacs.lua Unicode text, UTF-8 text
   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()

entry #3

written by kotnen
submitted at
0 likes

guesses
comments 0

post a comment


cg62.o Intel amd64 COFF object file, no line number info, not stripped, 7 sections, symbol offset=0xe5c, 38 symbols, 1st section name ".text"

entry #4

written by Dolphy
submitted at
0 likes

guesses
comments 0

post a comment


dir Subsed
dir app
CommandParser.hs ASCII text
  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
module CommandParser (
    Command(..),
    Action(..),
    Parser,
    parseCommand,
    currentLine,
    lastLine,
    runParser
) where

import Control.Applicative
import Data.Char (isNumber)

data Command =
             Plus Int
           | Minus Int
           | File
           | SetFile FilePath
           | Write
           | WriteFile FilePath
           | Quit
           | ForceQuit
           | Slice { getSliceBegin :: Int, getSliceEnd :: Int, getSliceAction :: Action}
           | Num Int
           | LastError
    deriving (Show, Eq)

data Action =
            Print
          | LineNumber
          | Line
          | Append
          | Insert
          | Change
          | Delete
    deriving (Show, Eq)

newtype Parser a = Parser { runParser :: String -> Maybe (String, a) }

instance Functor Parser where
    fmap :: (a -> b) -> Parser a -> Parser b
    fmap f (Parser p) = Parser $ \s -> case p s of
        Nothing -> Nothing
        (Just (rest, x)) -> Just (rest, f x)

instance Applicative Parser where
    pure :: a -> Parser a
    pure x = Parser $ \s -> Just (s, x)

    (<*>) :: Parser (a -> b) -> Parser a -> Parser b
    (Parser pf) <*> (Parser pa) = Parser $ \s -> do
        (rest, f) <- pf s
        (rest', a) <- pa rest
        return (rest', f a)

instance Alternative Parser where
    empty :: Parser a
    empty = Parser $ const Nothing

    (<|>) :: Parser a -> Parser a -> Parser a
    (Parser p1) <|> (Parser p2) = Parser $ \s -> p1 s <|> p2 s

parseChar :: Char -> Parser Char
parseChar c = Parser f
    where f [] = Nothing
          f (x:xs)
              | x == c = Just (xs, c)
              | otherwise = Nothing

parseCommandHelper :: Char -> Command -> (Char -> Command)
parseCommandHelper c cmd = \ch -> if ch == c then cmd else undefined

parseActionHelper :: Char -> Action -> (Char -> Action)
parseActionHelper c act = \ch -> if ch == c then act else undefined

currentLine :: Int
currentLine = -2

lastLine :: Int
lastLine = -1

parseQuit :: Parser Command
parseQuit = parseCommandHelper 'q' Quit <$> parseChar 'q'

parseForceQuit :: Parser Command
parseForceQuit = parseCommandHelper 'Q' ForceQuit <$> parseChar 'Q'

parseLastError :: Parser Command
parseLastError = parseCommandHelper 'h' LastError <$> parseChar 'h'

parseWriteFile :: Parser Command
parseWriteFile = f <$> (parseChar 'w' *> parseWs *> parseNonWs)
    where f [] = Write
          f str = WriteFile str

parseSetFile :: Parser Command
parseSetFile = f <$> (parseChar 'f' *> parseWs *> parseNonWs)
    where f [] = File
          f str = SetFile str

parsePlusNum :: Parser Command
parsePlusNum = Plus <$> (parseChar '+' *> parseWs *> parseNumber)

parsePlusses :: Parser Command
parsePlusses = Plus . (+1) . length <$> (parseChar '+' *> spanP (=='+'))

parseMinusNum :: Parser Command
parseMinusNum = Minus <$> (parseChar '-' *> parseWs *> parseNumber)

parseMinuses :: Parser Command
parseMinuses = Minus . (+1) . length <$> (parseChar '-' *> spanP (=='-'))

parseComma :: Parser Command
parseComma = Parser $ \s -> do
    (rest, num1) <- runParser (parseNumber <|> pure 1) s
    (rest', _) <- runParser (parseWs *> parseChar ',') rest
    (rest'', num2) <- runParser (parseNumber <|> pure lastLine) rest'
    (rest''', act) <- runParser (parseWs *> parseAction) rest''

    return (rest''', Slice num1 num2 act)

parseSemicolon :: Parser Command
parseSemicolon = Parser $ \s -> do
    (rest, num1) <- runParser (parseNumber <|> pure currentLine) s
    (rest', _) <- runParser (parseWs *> parseChar ';') rest
    (rest'', num2) <- runParser (parseNumber <|> pure lastLine) rest'
    (rest''', act) <- runParser (parseWs *> parseAction) rest''

    return (rest''', Slice num1 num2 act)

parseSingleSlice :: Parser Command
parseSingleSlice = Parser $ \s -> do
    (rest, num) <- runParser parseNumber s
    (rest', act) <- runParser (parseWs *> parseAction) rest

    return (rest', Slice num num act)

parseNumberCommand :: Parser Command
parseNumberCommand = Num <$> parseNumber

parsePrint :: Parser Action
parsePrint = parseActionHelper 'p' Print <$> parseChar 'p'

parseDelete :: Parser Action
parseDelete = parseActionHelper 'd' Delete <$> parseChar 'd'

parseLine :: Parser Action
parseLine = parseActionHelper 'l' Line <$> parseChar 'l'

parseAppend :: Parser Action
parseAppend = parseActionHelper 'a' Append <$> parseChar 'a'

parseInsert :: Parser Action
parseInsert = parseActionHelper 'i' Insert <$> parseChar 'i'

parseChange :: Parser Action
parseChange = parseActionHelper 'c' Change <$> parseChar 'c'

parseLineNumber :: Parser Action
parseLineNumber = parseActionHelper 'n' LineNumber <$> parseChar 'n'

stringToInt :: String -> Int
stringToInt s
    | s == "$" = lastLine
    | s == "." = currentLine
    | otherwise = read s

isNumberPred :: Char -> Bool
isNumberPred c
    | c == '.' = True
    | c == '$' = True
    | otherwise = isNumber c

parseNumber :: Parser Int
parseNumber = Parser $ \s ->
    case span isNumberPred s of
        ("", _) -> Nothing
        (digits, rest) -> Just (rest, stringToInt digits)


spanP :: (Char -> Bool) -> Parser String
spanP f =
  Parser $ \input -> do
    let (str, rest) = span f input
    return (rest, str)

isWhiteSpace :: Char -> Bool
isWhiteSpace c
    | c == ' ' = True
    | c == '\t' = True
    | otherwise = False

parseWs :: Parser String
parseWs = spanP isWhiteSpace

parseNonWs :: Parser String
parseNonWs = spanP (not . isWhiteSpace)

parseAction :: Parser Action
parseAction = parsePrint <|> parseDelete <|> parseLine <|> parseAppend <|> parseInsert <|> parseChange <|> parseLineNumber

makeSlice :: Action -> Command
makeSlice = Slice currentLine currentLine

parseActionCommand :: Parser Command
parseActionCommand = makeSlice <$> parseAction

parseCommand :: Parser Command
parseCommand = parseWs *> (
                 parseQuit <|> parseForceQuit <|> parseActionCommand <|> parseWriteFile <|>
                 parseSetFile <|> parsePlusNum <|> parsePlusses <|> parseMinusNum <|>
                 parseMinuses <|> parseComma <|> parseSemicolon <|> parseSingleSlice <|>
                 parseNumberCommand <|> parseLastError
               ) <* parseWs
Main.hs ASCII text
 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
module Main where

import qualified CommandParser as C
import qualified Program as P
import qualified Control.Monad.Trans.State as ST
import System.Environment
import System.Directory

runProgram :: P.Program -> IO ()
runProgram p@(P.Program buf cl fname chg qs lastError) = do
    line <- getLine
    let command = C.runParser C.parseCommand line
    case command of
        Nothing -> do
            putStrLn "?"
            runProgram $ P.Program buf cl fname chg qs "Invalid command suffix"
        (Just (rest, cmd)) -> do
            if null rest then do
                (_, next) <- ST.runStateT (P.runCommand cmd) p
                if P.getQuitState next == P.QuitForcefully then return ()
                else runProgram next
            else do
                putStrLn "?"
                runProgram $ P.Program buf cl fname chg qs "Invalid command suffix"

main :: IO ()
main = do
    args <- getArgs
    if null args then
        runProgram P.defaultProgram
    else do
        let fname = head args
        e <- doesFileExist fname
        if e then do
            content <- readFile fname
            let bytes = length content
            let buf = lines content
            print bytes
            runProgram $ P.Program buf (length buf) (Just fname) False P.NoQuit ""
        else do
            putStr fname
            putStrLn " No such file or directory"
            runProgram $ P.Program [] 0 Nothing False P.NoQuit "Cannot open input file"
            
Program.hs ASCII text
  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
module Program where

import CommandParser qualified as C
import Control.Monad.State
import System.IO
import qualified Control.Monad.Trans.State as ST

data QuitState = NoQuit | HasChanges | QuitForcefully deriving (Show, Eq, Enum)

data Program = Program
  { getBuffer :: [String],
    getCurrentLine :: Int,
    getFilename :: Maybe FilePath,
    hasUnsavedchanges :: Bool,
    getQuitState :: QuitState,
    getLastError :: String
  }

defaultProgram :: Program
defaultProgram = Program [] 0 Nothing False NoQuit ""

type ProgramStateT = ST.StateT Program IO

sliceToIndex :: Program -> Int -> Int
sliceToIndex (Program buf cl _ _ _ _) x
  | x == C.currentLine = cl - 1
  | x == C.lastLine = length buf - 1
  | otherwise = x - 1

slicesToIndices :: Program -> Int -> Int -> (Int, Int)
slicesToIndices p x y = (sliceToIndex p x, sliceToIndex p y)

sliceList :: [a] -> Int -> Int -> [a]
sliceList l beg end = take (end - beg + 1) $ drop beg l

takeInput :: IO String
takeInput = do
    input <- getLine
    if input /= "." then do
        i2 <- takeInput
        return $ input ++ "\n" ++ i2
    else return ""

runCommand :: C.Command -> ProgramStateT ()
runCommand (C.Plus n) = do
    (Program buf cl fname chg qs lastError) <- get
    if (cl + n) > length buf then do
        put $ Program buf cl fname chg NoQuit "Invalid address"
        liftIO $ putStrLn "?"
    else do
        put $ Program buf (cl + n) fname chg NoQuit lastError
        liftIO . putStrLn $ buf !! (cl + n)

runCommand (C.Minus n) = do
    (Program buf cl fname chg qs lastError) <- get
    if (cl - n) < 1 then do
        put $ Program buf cl fname chg NoQuit "Invalid address"
        liftIO $ putStrLn "?"
    else do
        put $ Program buf (cl - n) fname chg NoQuit lastError
        liftIO . putStrLn $ buf !! (cl - n)

runCommand C.File = do
    p@(Program buf cl fname chg qs lastError) <- get
    case fname of
        Nothing -> do
            put $ Program buf cl fname chg NoQuit "No current filename"
            liftIO $ putStrLn "?"
        (Just f) -> do
            put $ Program buf cl fname chg NoQuit lastError
            liftIO $ putStrLn f

runCommand (C.SetFile path) = do
    (Program buf cl fname chg qs lastError) <- get
    put $ Program buf cl (Just path) chg NoQuit lastError
    liftIO $ putStrLn path

runCommand C.Write = do
    (Program buf cl fname chg qs lastError) <- get
    case fname of
        Nothing -> do
            put $ Program buf cl fname chg NoQuit "No current filename"
            liftIO $ putStrLn "?"
        (Just filename) -> do
            let str = foldr (\a acc -> a ++ "\n" ++ acc) "" buf
            let bytes = length str
            liftIO $ do
                writeFile filename str
                print bytes
            put $ Program buf cl fname False NoQuit lastError

runCommand (C.WriteFile path) = do
    (Program buf cl fname chg qs lastError) <- get
    put $ Program buf cl (Just path) chg NoQuit lastError
    runCommand C.Write

runCommand C.Quit = do
    (Program buf cl fname chg qs lastError) <- get
    if qs == HasChanges then
        put $ Program buf cl fname chg QuitForcefully lastError
    else
        if chg then do
            liftIO $ putStrLn "?"
            put $ Program buf cl fname True HasChanges "Warning: buffer modified"
        else do
            put $ Program buf cl fname True QuitForcefully lastError

runCommand C.ForceQuit = do
    (Program buf cl fname chg qs lastError) <- get
    put $ Program buf cl fname chg QuitForcefully lastError

runCommand (C.Slice beg end C.Print) = do
    p@(Program buf cl fname chg qs lastError) <- get
    let (sbeg, send) = slicesToIndices p beg end
    if sbeg > send || send >= length buf then do
        put $ Program buf cl fname chg NoQuit "Invalid address"
        liftIO $ putStrLn "?"
    else do
        put $ Program buf (send + 1) fname chg NoQuit lastError
        liftIO . mapM_ putStrLn $ sliceList buf sbeg send

runCommand (C.Slice beg end C.LineNumber) = do
    p@(Program buf cl fname chg qs lastError) <- get
    let (sbeg, send) = slicesToIndices p beg end
    if sbeg > send || send >= length buf then do
        put $ Program buf cl fname chg NoQuit "Invalid address"
        liftIO $ putStrLn "?"
    else do
        put $ Program buf (send + 1) fname chg NoQuit lastError
        liftIO $ mapM_ putStrLn $ enumerateLines sbeg send $ sliceList buf sbeg send
    where enumerateLines _ _ [] = []
          enumerateLines sbeg send (x:xs) = (show (sbeg + 1) ++ "\t"++x):enumerateLines (sbeg + 1) send xs

runCommand (C.Slice beg end C.Line) = do
    p@(Program buf cl fname chg qs lastError) <- get
    let (sbeg, send) = slicesToIndices p beg end
    if sbeg > send || send >= length buf then do
        put $ Program buf cl fname chg NoQuit "Invalid address"
        liftIO $ putStrLn "?"
    else do
        put $ Program buf (send + 1) fname chg NoQuit lastError
        liftIO $ mapM_ (putStrLn . (++"$")) $ sliceList buf sbeg send

runCommand (C.Slice beg end C.Append) = do
    p@(Program buf cl fname chg qs lastError) <- get
    let (sbeg, send) = slicesToIndices p beg end
    if sbeg > send || send >= length buf then do
        put $ Program buf cl fname chg NoQuit "Invalid address"
        liftIO $ putStrLn "?"
    else do
        inputLines <- liftIO takeInput
        let newText = lines inputLines
        let newBuf = take (send + 1) buf ++ newText ++ drop (send + 1) buf
        put $ Program newBuf (send + 1 + length newText) fname True NoQuit lastError

runCommand (C.Slice beg end C.Insert) = do
    p@(Program buf cl fname chg qs lastError) <- get
    let (sbeg, send) = slicesToIndices p beg end
    if sbeg > send || send >= length buf then do
        put $ Program buf cl fname chg NoQuit "Invalid address"
        liftIO $ putStrLn "?"
    else do
        inputLines <- liftIO takeInput
        let newText = lines inputLines
        let newBuf = take send buf ++ newText ++ drop send buf
        put $ Program newBuf (send + 1) fname True NoQuit lastError

runCommand (C.Slice beg end C.Change) = do
    runCommand (C.Slice beg end C.Delete)
    runCommand (C.Slice beg beg C.Insert)

runCommand (C.Slice beg end C.Delete) = do
    p@(Program buf cl fname chg NoQuit lastError) <- get
    let (sbeg, send) = slicesToIndices p beg end
    if sbeg > send || send >= length buf then do
        put $ Program buf cl fname chg NoQuit "Invalid address"
        liftIO $ putStrLn "?"
    else do
        put $ Program (take sbeg buf ++ drop (send + 1) buf) (sbeg + 1) fname True NoQuit lastError

runCommand (C.Num n) = do
    p@(Program buf cl fname chg qs lastError) <- get
    let sn = sliceToIndex p n

    if (sn < 0) || (sn >= length buf) then do
        put $ Program buf cl fname chg NoQuit "Invalid address"
        liftIO $ putStrLn "?"
    else do
        put $ Program buf (sn + 1) fname chg NoQuit lastError
        liftIO . putStrLn $ buf !! sn

runCommand C.LastError = do
    (Program buf cl fname chg qs lastError) <- get
    if null lastError then
        return ()
    else do
        liftIO $ putStrLn lastError
    put $ Program buf cl fname chg NoQuit lastError
subsed.cabal ASCII text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
cabal-version:      3.0
name:               subsed
version:            0.1.0.0
description:        A subset of ed
license:            NONE
build-type:         Simple

common warnings
    ghc-options: -Wall

executable subsed
    import:           warnings
    main-is:          Main.hs
    other-modules:    CommandParser
                    , Program
    build-depends:    base ^>=4.17.2.1
                    , mtl ^>= 2.2.2
                    , transformers ^>= 0.5.6.2
                    , directory ^>= 1.3.7.1
    hs-source-dirs:   app
    default-language: GHC2021

entry #5

written by Proloy
submitted at
0 likes

guesses
comments 0

post a comment


62.py ASCII text
 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
import sys

def is_digit(c): return c in '0123456789'

lines=[]
fname=sys.argv[1]

open(fname, 'a').close()

with open(fname, "r+") as f:
    lines = f.readlines()

    print("> ", end='')
    sys.stdout.flush()
    for line in sys.stdin:
        line=line.lstrip()
        if line.rstrip() in ["quit", "q", "exit"]: break
        i=0
        while i<len(line) and is_digit(line[i]): i+=1
        loc=int(line[:i])-1
        line = line[i:].lstrip()
        if len(line)==0 or line[0] not in "ei":
            print(loc+1, "|", lines[loc])
        elif line[0] == 'e':
            lines[loc] = line[1:]
        elif line[0] == 'i':
            lines = lines[:loc] + [line[1:]] + lines[loc:]
        print("> ", end='')
        sys.stdout.flush()

    f.seek(0)
    f.writelines(lines)
    f.flush()

entry #6

written by luatic
submitted at
2 likes

guesses
comments 0

post a comment


dir sped
dir src
dir e
josh.zig ASCII text, with very long lines (65536), with no line terminators
oom.zig ASCII text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// https://www.gamers.org/~fpv/doomlogo.html
pub const oom =
    \\                      ===============     ===============   ========  ========
    \\                     //. . . . . . .\\   //. . . . . . .\\  \\. . .\\// . . //
    \\                    ||. . ._____. . .|| ||. . ._____. . .|| || . . .\/ . . .||
    \\                    || . .||   ||. . || || . .||   ||. . || ||. . . . . . . ||
    \\                    ||. . ||   || . .|| ||. . ||   || . .|| || . | . . . . .||
    \\                    ||-_ .||   ||. . || || . .||   ||. _-|| ||-_.|\ . . . . ||
    \\                    ||  `-||   || . .|| ||. . ||   ||-'  || ||  `|\_ . .|. .||
    \\                    ||    ||   ||_ . || || . _||   ||    || ||   |\ `-_/| . ||
    \\                    ||    \|.  || `-_|| ||_-' ||  .|/    || ||   | \  / |-_.||
    \\                    ||      `-_||    || ||    ||_-'      || ||   | \  / |  `||
    \\                    ||         `'    || ||    `'         || ||   | \  / |   ||
    \\                    `===.         .==='.`===.         .===' /==. |  \/  |   ||
    \\                    |-_ `===. .==='   _|_   `===. .===' _-|/   `==  \/  |   ||
    \\                       `-_  `='    _-'   `-_    `='  _-'   `-_  /|  \/  |   ||
    \\                          `-__\._-'         `-_./__-'         `' |. /|  |   ||
    \\                                                                  `' |  /==.||
    \\                                                                      \/   `==
    \\                                                                       `-_   /
    \\                                                                          ``'
    \\
;
dir reg
dfa.zig ASCII text
 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
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayListUnmanaged;
const DynamicBitSet = std.bit_set.DynamicBitSet;

const AutoHashMap = std.AutoArrayHashMapUnmanaged;
fn CharMap(V: type) type {
    return AutoHashMap(u8, V);
}

pub fn DFA(V: type) type {
    const State = struct {
        const Self = @This();
        out: CharMap(usize),
        accepting: bool,
        value: V,
        pub fn init(allocator: Allocator, accepting: bool, value: V) !Self {
            return .{
                .out = try AutoHashMap(u8, usize).init(allocator, &.{}, &.{}),
                .accepting = accepting,
                .value = value,
            };
        }
        pub fn deinit(self: *Self, allocator: Allocator) void {
            self.out.deinit(allocator);
        }
    };
    return struct {
        const Self = @This();
        states: ArrayList(State),
        allocator: Allocator,
        pub fn init(allocator: Allocator) Self {
            return .{
                .states = ArrayList(State).initBuffer(&.{}),
                .allocator = allocator,
            };
        }
        pub fn deinit(self: *Self) void {
            for (self.states.items) |*state|
                state.deinit(self.allocator);
            self.states.deinit(self.allocator);
        }
        pub fn addState(self: *Self, accepting: bool, value: V) !usize {
            try self.states.append(self.allocator, try State.init(self.allocator, accepting, value));
            return self.states.items.len - 1;
        }
        pub fn addTransition(self: *Self, from: usize, via: u8, to: usize) !void {
            try self.states.items[from].out.put(self.allocator, via, to);
        }
        pub fn getTransition(self: Self, from: usize, via: u8) ?usize {
            return self.states.items[from].out.get(via);
        }
        pub fn accepts(self: Self, input: []const u8) bool {
            var state: usize = 0;
            for (input) |c| {
                if (self.getTransition(state, c)) |next_state|
                    state = next_state
                else
                    return false;
            }
            return self.states.items[state].accepting;
        }
    };
}
ex.zig ASCII text
  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
const std = @import("std");
const Allocator = std.mem.Allocator;
const NFAC = @import("nfa.zig").NFA;
const DFAC = @import("dfa.zig").DFA;
const CharSet = std.bit_set.IntegerBitSet(256);

pub fn RegexReader(V: type) type {
    return struct {
        const NFA = NFAC(V);
        const DFA = DFAC(V);
        const Self = @This();
        pub const SyntaxError = error{
            UnexpectedEOF,
            UnclosedParenthesis,
            ExpectedOperand,
            UnexpectedChar,
            InvalidEscape,
        };
        pub const ReadError = SyntaxError || Allocator.Error;
        nfa: *NFA,
        i: usize,
        buf: []const u8,
        pub fn init(nfa: *NFA, expr: []const u8) Self {
            return .{
                .nfa = nfa,
                .i = 0,
                .buf = expr,
            };
        }
        fn getch(self: *Self) ?u8 {
            if (self.eof()) return null;
            const c = self.buf[self.i];
            self.i += 1;
            return c;
        }
        fn getch2(self: *Self) ReadError!u8 {
            return self.getch() orelse return SyntaxError.UnexpectedEOF;
        }
        fn ungetch(self: *Self) void {
            self.i -= 1;
        }
        fn eof(self: Self) bool {
            return self.i >= self.buf.len;
        }
        fn readEscape(self: *Self) ReadError!u8 {
            return switch (try self.getch2()) {
                'x' => l: {
                    const hi = try self.getch2();
                    const lo = try self.getch2();
                    break :l std.fmt.parseUnsigned(u8, &.{ hi, lo }, 16) catch |e| switch (e) {
                        error.Overflow => unreachable,
                        error.InvalidCharacter => return SyntaxError.InvalidEscape,
                    };
                },
                else => |c| c,
            };
        }
        fn readAtom(self: *Self) ReadError!?NFA.Sub {
            if (self.eof()) return null;
            switch (self.getch().?) {
                '(' => {
                    const res = try self.readChoice();
                    return if (try self.getch2() != ')') SyntaxError.UnclosedParenthesis else res;
                },
                '%' => return try self.nfa.str(&.{try self.readEscape()}),
                '[' => {
                    var charset = CharSet.initEmpty();
                    const complement = try self.getch2() == '^';
                    if (!complement) self.ungetch();
                    while (true) {
                        var c = try self.getch2();
                        if (c == ']') break;
                        if (c == '%')
                            c = try self.readEscape();
                        const c2 = try self.getch2();
                        if (c2 == '-') {
                            const c3 = try self.getch2();
                            if (c > c3) continue; // empty range
                            charset.setRangeValue(.{ .start = c, .end = c3 }, true);
                        } else {
                            charset.set(c);
                            self.ungetch();
                        }
                    }
                    if (complement) charset = charset.complement();
                    return try self.nfa.charset(charset);
                },
                ')', '?', '+', '*', '|' => {
                    self.ungetch();
                    return null;
                },
                else => |c| return try self.nfa.str(&.{c}),
            }
        }
        fn readQuantified(self: *Self) ReadError!?NFA.Sub {
            const base = try self.readAtom() orelse return null;
            return try switch (self.getch() orelse return base) {
                '?' => self.nfa.opt(base),
                '+' => self.nfa.rep(base),
                '*' => self.nfa.kleene(base),
                else => {
                    self.ungetch();
                    return base;
                },
            };
        }
        fn readConcat(self: *Self) ReadError!NFA.Sub {
            var base = try self.readQuantified() orelse return SyntaxError.ExpectedOperand;
            while (try self.readQuantified()) |q| base = try self.nfa.concat(&.{ base, q });
            return base;
        }
        fn readChoice(self: *Self) ReadError!NFA.Sub {
            var base = try self.readConcat();
            while (true) {
                if (self.getch()) |c| {
                    if (c == '|') base = try self.nfa.choice(&.{ base, try self.readConcat() }) else {
                        self.ungetch();
                        return base;
                    }
                } else return base;
            }
        }
        pub fn read(self: *Self) !NFA.Sub {
            const res = try self.readChoice();
            if (!self.eof())
                return error.UnexpectedChar;
            return res;
        }
    };
}

fn nothing(_: void, _: void) void {
    return {};
}

pub fn regexToDFA(allocator: Allocator, regex: []const u8) !DFAC(void) {
    var nfa = NFAC(void).init(allocator, {});
    defer nfa.deinit();
    var rr = RegexReader(void).init(&nfa, regex);
    const sub = try rr.read();
    return nfa.toDFA(sub, nothing);
}
nfa.zig ASCII text
  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
const std = @import("std");
const Allocator = std.mem.Allocator;
const CharSet = std.bit_set.IntegerBitSet(256);
fn HashMap(K: type, V: type) type {
    return std.ArrayHashMapUnmanaged(K, V, struct {
        pub fn hash(_: @This(), k: K) u32 {
            var hasher = std.hash.Wyhash.init(1233543646);
            std.hash.autoHashStrat(&hasher, k, .DeepRecursive);
            return @truncate(hasher.final());
        }
        pub fn eql(_: anytype, k1: K, k2: K, _: anytype) bool {
            return std.mem.eql(@typeInfo(K).Pointer.child, k1, k2);
        }
    }, true);
}
const AutoHashMap = std.AutoArrayHashMapUnmanaged;
const ArrayList = std.ArrayListUnmanaged;

const DFA = @import("dfa.zig").DFA;

const Subset = []const usize;

fn orderUsize(_: void, a: usize, b: usize) std.math.Order {
    return std.math.order(a, b);
}

fn contains(set: Subset, end_state: usize) bool {
    return std.sort.binarySearch(usize, end_state, set, {}, orderUsize) != null;
}

pub fn NFA(V: type) type {
    const Transition = struct { char: ?u8, to: usize };

    const State = struct {
        const Self = @This();

        out: ArrayList(Transition),
        value: V,
        pub fn init(value: V) Self {
            return .{
                .out = ArrayList(Transition).initBuffer(&.{}),
                .value = value,
            };
        }
        pub fn deinit(self: *Self, allocator: Allocator) void {
            self.out.deinit(allocator);
        }
    };

    return struct {
        const Self = @This();

        pub const Sub = struct {
            start: usize,
            end: usize,
        };

        allocator: Allocator,
        states: ArrayList(State),
        value: V, // HACK this is lazy

        pub fn init(allocator: Allocator, value: V) Self {
            return .{
                .allocator = allocator,
                .states = ArrayList(State).initBuffer(&.{}),
                .value = value,
            };
        }
        pub fn deinit(self: *Self) void {
            for (self.states.items) |*state|
                state.deinit(self.allocator);
            self.states.deinit(self.allocator);
        }
        pub fn addState(self: *Self) Allocator.Error!usize {
            try self.states.append(self.allocator, State.init(self.value));
            return self.states.items.len - 1;
        }
        pub fn addTransition(self: *Self, from: usize, char: ?u8, to: usize) Allocator.Error!void {
            try self.states.items[from].out.append(self.allocator, .{ .char = char, .to = to });
        }
        pub fn rep(self: *Self, sub: Sub) Allocator.Error!Sub {
            try self.addTransition(sub.end, null, sub.start);
            return sub;
        }
        pub fn opt(self: *Self, sub: Sub) Allocator.Error!Sub {
            try self.addTransition(sub.start, null, sub.end);
            return sub;
        }
        pub fn kleene(self: *Self, sub: Sub) Allocator.Error!Sub {
            return self.rep(try self.opt(sub));
        }
        pub fn choice(self: *Self, subs: []const Sub) Allocator.Error!Sub {
            const new = Sub{ .start = try self.addState(), .end = try self.addState() };
            for (subs) |sub| {
                try self.addTransition(new.start, null, sub.start);
                try self.addTransition(sub.end, null, new.end);
            }
            return new;
        }
        pub fn concat(self: *Self, subs: []const Sub) Allocator.Error!Sub {
            var last_end = subs[0].end;
            for (subs[1..]) |sub| {
                try self.addTransition(last_end, null, sub.start);
                last_end = sub.end;
            }
            return .{ .start = subs[0].start, .end = last_end };
        }
        pub fn str(self: *Self, s: []const u8) Allocator.Error!Sub {
            const start = try self.addState();
            var end = start;
            for (s) |c| {
                const new_end = try self.addState();
                try self.addTransition(end, c, new_end);
                end = new_end;
            }
            return .{ .start = start, .end = end };
        }
        pub fn charset(self: *Self, set: CharSet) Allocator.Error!Sub {
            const start = try self.addState();
            const end = try self.addState();
            var chars = set.iterator(.{});
            while (chars.next()) |c|
                try self.addTransition(start, @intCast(c), end);
            return .{ .start = start, .end = end };
        }

        fn hull(self: Self, states: Subset, hull_allocator: Allocator) Allocator.Error![]usize {
            const allocator = self.allocator; // should maybe be separate (e.g. arena allocation while algo runs) but meh
            var level = try ArrayList(usize).initCapacity(allocator, 1);
            defer level.deinit(allocator);
            try level.appendSlice(allocator, states);
            var next_level = ArrayList(usize).initBuffer(&.{});
            defer next_level.deinit(allocator);
            var seen = try AutoHashMap(usize, void).init(allocator, states, allocator.alloc(void, states.len) catch unreachable);
            defer seen.deinit(allocator);
            while (level.items.len > 0) {
                for (level.items) |state| {
                    for (self.states.items[state].out.items) |transition| {
                        if (transition.char == null and seen.get(transition.to) == null) {
                            try seen.put(allocator, transition.to, {});
                            try next_level.append(allocator, transition.to);
                        }
                    }
                }
                level.clearRetainingCapacity();
                const old_level = level;
                level = next_level;
                next_level = old_level;
            }
            const res = try hull_allocator.alloc(usize, seen.count());
            var iter = seen.iterator();
            var i: usize = 0;
            while (iter.next()) |e| {
                res[i] = e.key_ptr.*;
                i += 1;
            }
            return res;
        }
        pub fn toDFA(self: Self, sub: Sub, merge_values: fn (v1: V, v2: V) V) Allocator.Error!DFA(V) {
            const allocator = self.allocator; // same here
            var dfa = DFA(V).init(allocator);
            var subsets = std.heap.ArenaAllocator.init(allocator);
            defer subsets.deinit();
            const start_subset = try self.hull(&.{sub.start}, subsets.allocator());
            var nfa_to_dfa = try HashMap(Subset, usize).init(allocator, &.{start_subset}, &.{
                try dfa.addState(contains(start_subset, sub.end), self.states.items[sub.start].value),
            });
            defer nfa_to_dfa.deinit(allocator);
            var next_level = ArrayList(Subset).initBuffer(&.{});
            defer next_level.deinit(allocator);
            var level = try ArrayList(Subset).initCapacity(allocator, 1);
            defer level.deinit(allocator);
            try level.append(allocator, start_subset);
            while (level.items.len > 0) {
                for (level.items) |subset| {
                    var transitions = try AutoHashMap(u8, AutoHashMap(usize, void)).init(allocator, &.{}, &.{});
                    defer {
                        for (transitions.values()) |*set|
                            set.deinit(allocator);
                        transitions.deinit(allocator);
                    }
                    for (subset) |state| {
                        for (self.states.items[state].out.items) |transition| {
                            if (transition.char) |char| {
                                if (transitions.getPtr(char)) |set| {
                                    try set.put(allocator, transition.to, {});
                                } else {
                                    try transitions.put(allocator, char, try AutoHashMap(usize, void).init(allocator, &.{transition.to}, &.{{}}));
                                }
                            }
                        }
                    }
                    var iter = transitions.iterator();
                    while (iter.next()) |e| {
                        var buf: [256]usize = undefined;
                        var i: usize = 0;
                        for (e.value_ptr.keys()) |state| {
                            buf[i] = state;
                            i += 1;
                        }
                        const reached_states = try self.hull(buf[0..i], subsets.allocator());
                        std.sort.pdq(usize, reached_states, {}, std.sort.asc(usize));
                        const gop = try nfa_to_dfa.getOrPut(allocator, reached_states);
                        if (!gop.found_existing) {
                            var v = self.states.items[reached_states[0]].value;
                            for (reached_states[1..]) |s|
                                v = merge_values(v, self.states.items[s].value);
                            const dfa_state = try dfa.addState(contains(reached_states, sub.end), v);
                            gop.value_ptr.* = dfa_state;
                            try next_level.append(allocator, reached_states);
                        }
                        try dfa.addTransition(nfa_to_dfa.get(subset).?, e.key_ptr.*, gop.value_ptr.*);
                    }
                }
                level.clearRetainingCapacity();
                const old_level = level;
                level = next_level;
                next_level = old_level;
            }
            return dfa;
        }
    };
}
test.zig ASCII text
  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
const std = @import("std");

const NFA = @import("nfa.zig").NFA(void);
const DFA = @import("dfa.zig").DFA(void);

const allocator = std.testing.allocator;

fn initNFA() NFA {
    return NFA.init(allocator, {});
}

fn nothing(_: void, _: void) void {
    return {};
}

const expect = std.testing.expect;

test "optional" {
    var nfa = initNFA();
    defer nfa.deinit();
    const sub = try nfa.opt(try nfa.str("test"));
    var dfa = try nfa.toDFA(sub, nothing);
    defer dfa.deinit();
    try expect(dfa.accepts("test"));
    try expect(dfa.accepts(""));
    try expect(!dfa.accepts("t"));
}

test "repetition" {
    var nfa = initNFA();
    defer nfa.deinit();
    const sub = try nfa.rep(try nfa.str("test"));
    var dfa = try nfa.toDFA(sub, nothing);
    defer dfa.deinit();
    try expect(dfa.accepts("test"));
    try expect(dfa.accepts("testtest"));
    try expect(!dfa.accepts(""));
    try expect(!dfa.accepts("t"));
    try expect(!dfa.accepts("testt"));
}

test "kleene" {
    var nfa = initNFA();
    defer nfa.deinit();
    const sub = try nfa.kleene(try nfa.str("test"));
    var dfa = try nfa.toDFA(sub, nothing);
    defer dfa.deinit();
    try expect(dfa.accepts("testtesttest"));
    try expect(dfa.accepts("test"));
    try expect(dfa.accepts(""));
    try expect(!dfa.accepts("t"));
    try expect(!dfa.accepts("testyay"));
}

test "concat" {
    var nfa = initNFA();
    defer nfa.deinit();
    const sub = try nfa.concat(&.{ try nfa.str("hello"), try nfa.str("world") });
    var dfa = try nfa.toDFA(sub, nothing);
    defer dfa.deinit();
    try expect(dfa.accepts("helloworld"));
    try expect(!dfa.accepts(""));
    try expect(!dfa.accepts("hello"));
    try expect(!dfa.accepts("world"));
}

test "choice" {
    var nfa = initNFA();
    defer nfa.deinit();
    const sub = try nfa.choice(&.{ try nfa.str("hi"), try nfa.str("hello") });
    var dfa = try nfa.toDFA(sub, nothing);
    defer dfa.deinit();
    try expect(dfa.accepts("hi"));
    try expect(dfa.accepts("hello"));
    try expect(!dfa.accepts(""));
    try expect(!dfa.accepts("h"));
    try expect(!dfa.accepts("helloworld"));
}

test "putting it all together" {
    var nfa = initNFA();
    defer nfa.deinit();
    const sub = try nfa.choice(&.{
        try nfa.concat(&.{
            try nfa.rep(try nfa.str("ab")),
            try nfa.str("cd"),
        }),
        try nfa.kleene(try nfa.str("ef")),
    });
    var dfa = try nfa.toDFA(sub, nothing);
    defer dfa.deinit();
    try expect(dfa.accepts("abcd"));
    try expect(dfa.accepts("abababcd"));
    try expect(dfa.accepts("efef"));
    try expect(dfa.accepts(""));
    try expect(!dfa.accepts("abcdef"));
    try expect(!dfa.accepts("g"));
    try expect(!dfa.accepts("a"));
}

const origRegexToDFA = @import("ex.zig").regexToDFA;
fn regexToDFA(regex: []const u8) !DFA {
    return origRegexToDFA(allocator, regex);
}

test "simple regex" {
    var dfa = try regexToDFA("(ab)+cd|(ef)*");
    defer dfa.deinit();
    try expect(dfa.accepts("abcd"));
    try expect(dfa.accepts("abababcd"));
    try expect(dfa.accepts("efef"));
    try expect(dfa.accepts(""));
    try expect(!dfa.accepts("abcdef"));
    try expect(!dfa.accepts("g"));
    try expect(!dfa.accepts("a"));
}

test "charset" {
    var dfa = try regexToDFA("[a%]|b]");
    defer dfa.deinit();
    try expect(dfa.accepts("a"));
    try expect(dfa.accepts("b"));
    try expect(dfa.accepts("]"));
    try expect(dfa.accepts("|"));
    try expect(!dfa.accepts("c"));
}

test "charset range" {
    var dfa = try regexToDFA("[a-c]");
    defer dfa.deinit();
    try expect(dfa.accepts("a"));
    try expect(dfa.accepts("b"));
    try expect(!dfa.accepts("d"));
}

test "charset complement" {
    var dfa = try regexToDFA("[^ab]");
    defer dfa.deinit();
    try expect(!dfa.accepts("a"));
    try expect(!dfa.accepts("b"));
    try expect(dfa.accepts("c"));
}
ansi.zig ASCII text
  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
// The necessary parts of ANSI escape sequence support required for this editor to work

const std = @import("std");
const fmt = std.fmt;
const Color = @import("color.zig").Color;
const Pos = @import("pos.zig");

pub fn parseCsiParams(res: []usize, comptime default: usize, params: []const u8, min_params: usize) ![]usize {
    var i: usize = 0;
    var si = std.mem.splitScalar(u8, params, ';');
    while (i < res.len) : (i += 1) {
        const param = si.next();
        if (param) |num| {
            res[i] = if (num.len == 0) default else try std.fmt.parseInt(usize, num, 10);
        } else {
            res[i] = default;
            break;
        }
    }
    if (i == res.len and si.next() != null)
        return error.TooManyParameters;
    while (i < min_params) : (i += 1)
        res[i] = default;
    return res[0..i];
}

pub const AnsiCommand = union(enum) {
    ignore, // something we don't recognize
    tab,
    backspace,
    delete,
    newline,
    carriage_return,
    insert,
    // Control characters (excluding those corresponding to the above)
    ctrl: u8, // a - z
    // Regular printable ASCII key presses
    print: u8,
    cursor_movement: CursorMovement,
    const CursorMovement = struct {
        const Action = enum { left, right, up, down, pos1, end };
        modifier: enum { none, shift, ctrl },
        action: Action,
        times: usize,
    };
};

pub const AnsiCommandIterator = struct {
    buf: []const u8,
    i: usize,
    fn getch(self: *AnsiCommandIterator) ?u8 {
        if (self.eof()) return null;
        const c = self.buf[self.i];
        self.i += 1;
        return c;
    }
    fn ungetch(self: *AnsiCommandIterator) void {
        self.i -= 1;
    }
    fn eof(self: *AnsiCommandIterator) bool {
        return self.i >= self.buf.len;
    }
    fn parseCursorMovement(
        kind: u8,
        params: []const u8,
    ) AnsiCommand {
        var movbuf: [2]usize = undefined;
        const movement = parseCsiParams(&movbuf, 1, params, 1) catch return .{ .ignore = {} };
        const action: AnsiCommand.CursorMovement.Action = switch (kind) {
            'A' => .up,
            'B' => .down,
            'C' => .right,
            'D' => .left,
            'H' => .pos1,
            'F' => .end,
            else => return .{ .ignore = {} },
        };
        const times = movement[0];
        return if (movement.len == 1)
            .{ .cursor_movement = .{ .modifier = .none, .action = action, .times = times } }
        else if (movement.len == 2)
            switch (movement[1]) {
                2 => .{ .cursor_movement = .{ .modifier = .shift, .action = action, .times = times } },
                5 => .{ .cursor_movement = .{ .modifier = .ctrl, .action = action, .times = times } },
                else => .{ .ignore = {} },
            }
        else
            .{ .ignore = {} };
    }
    pub fn next(self: *AnsiCommandIterator) ?AnsiCommand {
        const c = self.getch() orelse return null;
        return switch (c) {
            else => .{ .ignore = {} },
            0x08 => .{ .backspace = {} },
            0x7F => .{ .delete = {} },
            '\n' => .{ .newline = {} },
            '\r' => .{ .carriage_return = {} },
            '\t' => .{ .tab = {} },
            0x01...0x07, 0x0C, 0x0E...0x1A => .{ .ctrl = c - 1 + 'a' },
            // Printable ASCII
            ' '...'~' => .{ .print = c },
            // ANSI escape sequences
            0x1B => switch (self.getch() orelse return .{ .ignore = {} }) { // TODO possible ESC
                else => .{ .ignore = {} },
                // Fe sequence
                0x40...0x5A, 0x5C...0x5F => .{ .ignore = {} },
                '[' => {
                    // CSI sequence
                    if (self.eof()) return .{ .ignore = {} }; // TODO cut off?
                    const start = self.i;
                    var c2 = self.getch() orelse return .{ .ignore = {} };
                    while (c2 >= 0x30 and c2 <= 0x3F)
                        c2 = self.getch() orelse return .{ .ignore = {} };
                    while (c2 >= 0x20 and c2 <= 0x2F)
                        c2 = self.getch() orelse return .{ .ignore = {} };
                    if (c2 < 0x40 or c2 > 0x7E) {
                        self.ungetch();
                        return .{ .ignore = {} }; // TODO syntax error
                    }
                    const params = self.buf[start .. self.i - 1];
                    if (c2 == '~') return switch (fmt.parseInt(usize, params, 10) catch return .{ .ignore = {} }) {
                        2 => .{ .insert = {} },
                        else => .{ .ignore = {} },
                    };
                    return parseCursorMovement(c2, params);
                },
            },
        };
    }
};

pub fn parse(buf: []const u8) AnsiCommandIterator {
    return .{ .buf = buf, .i = 0 };
}

pub fn writeCsi(writer: anytype, seq: []const u8) !void {
    try writer.writeAll("\x1B[");
    try writer.writeAll(seq);
}

pub fn fmtCsi(writer: anytype, csi_type: u8, params: anytype) !void {
    try writer.writeAll("\x1B[");
    if (params.len > 0)
        try fmt.format(writer, "{d}", .{params[0]});
    var i: usize = 1;
    while (i < params.len) : (i += 1)
        try fmt.format(writer, ";{d}", .{params[i]});
    try writer.writeByte(csi_type);
}

pub fn setCursor(writer: anytype, pos: Pos) !void {
    return fmtCsi(writer, 'H', [_]usize{ pos.row + 1, pos.col + 1 });
}

pub fn setFg(writer: anytype, color: Color) !void {
    return fmtCsi(writer, 'm', [_]usize{ 38, 2, color.r, color.g, color.b });
}

pub fn setBg(writer: anytype, color: Color) !void {
    return fmtCsi(writer, 'm', [_]usize{ 48, 2, color.r, color.g, color.b });
}

pub fn clearScreen(writer: anytype) !void {
    return writeCsi(writer, "2J");
}
c.zig ASCII text
 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
const hex_digit = "[0-9A-Fa-f]";
const integer = "(([1-9][0-9]*|0[0-7]*|0[xX]" ++ hex_digit ++ "+)([uU](l|L|ll|LL)|(l|L|ll|LL)[uU]))";
const dexp = "([eE][+-]?[0-9]+)";
const hexp = "([pP][+-]?[0-9]+)";
const decfloat = "([0-9]+%.[0-9]*|%.[0-9]+)" ++ dexp ++ "?|[0-9]+" ++ dexp;
const hexfloat = "0[xX](" ++ hex_digit ++ "+%." ++ hex_digit ++ "*" ++ hexp ++ "?|" ++ hex_digit ++ "+" ++ hexp ++ ")";
const float = "(" ++ decfloat ++ "|" ++ hexfloat ++ ")[fF]";
// TODO fallback tainted invalid escape sequence
const hex_quad = hex_digit ++ hex_digit ++ hex_digit ++ hex_digit;
const escape = "(\\(['\"?\\abfnrtv]|[0-7][0-7]?[0-7]?|x" ++ hex_digit ++ "+|u" ++ hex_quad ++ "|U" ++ hex_quad ++ hex_quad ++ "))";

const tok = @import("tok.zig");
const RegexTokenizer = tok.RegexTokenizer;
const Token = tok.Token;

var cache: ?RegexTokenizer = null;
pub fn tokenizer() !RegexTokenizer {
    cache = cache orelse try RegexTokenizer.init(&.{
        // zig fmt: off
        .{.keyword, "auto|break|case|char|const|continue|default|do|double"
            ++ "|else|enum|extern|float|for|goto|if|inline|int|long"
            ++ "|register|restrict|return|short|signed|sizeof|static|struct|switch"
            ++ "|typedef|union|unsigned|void|volatile|while"
            ++ "|_Alignas|_Alignof|_Atomic|_Bool|_Complex|_Generic|_Imaginary|_Noreturn|_Static_assert|_Thread_local"},
        .{.identifier, "[a-zA-Z_]+[a-zA-Z0-9_]*"},
        .{.quoted, "(u8|[uUL])?\"([^\"\n\\]|" ++ escape ++ ")*\"|[uUL]?'([^'\n\\]|" ++ escape ++ ")*'"},
        .{.number, integer ++ "|" ++ float},
        .{.sym, "[(){}[%]<>.!&|+%-*/%]|%->|%+%+|%-%-|<<|>>|[!=<>]=|%^|&&|%|%||%?|:|;|%.%.%.|([*/&+%-^|]|<<|>>)?=|,|#|##"
            ++ "|<:|:>|<%%|%%>|%%:|%%:%%:"}, // darn digraphs
        .{.pp, "#include[ \t]*\"[^\n\"]*\"|<[^\n>]*>|#(pragma|define|undef|if(n?def)|else|elif|endif|line|error|warning)"},
        .{.comment, "//[^\n]*|/%*(/[^*]|[^/])*%*/"},
        .{.ignore, "[ \n\r\t]+"},
    });
    return cache.?;
}

const expectEq = @import("std").testing.expectEqual;
const Tester = struct {
    t: RegexTokenizer,
    buf: []const u8,
    i: usize = 0,
    pub fn expect(self: *@This(), kind: tok.TokenType, s: []const u8) !void {
        try expectEq(Token{.kind = kind, .len = s.len}, self.t.nextToken(self.buf[self.i..]));
        self.i += s.len;
    }
};
test "things" {
    const buf = "if (1) printf(\"blah\");";
    var t = Tester{.t = try tokenizer(), .buf = buf};
    try t.expect(.keyword, "if");
    try t.expect(.ignore, " ");
    try t.expect(.sym, "(");
    try t.expect(.number, "2");
    try t.expect(.sym, ")");
    try t.expect(.ignore, " ");
    try t.expect(.identifier, "printf");
    try t.expect(.sym, "(");
    try t.expect(.quoted, "\"blah\"");
    try t.expect(.sym, ")");
    try t.expect(.sym, ";");
}
color.zig ASCII text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
pub const Color = struct { r: u8, g: u8, b: u8 };

fn h(u: usize) Color {
    return .{ .r = (u >> 16) & 0xFF, .g = (u >> 8) & 0xFF, .b = u & 0xFF };
}

// not doing proper enum array rn
pub const FG = [_]Color{
    h(0x66ff66), // keyword
    h(0x116611), // identifier
    h(0xff7611), // quoted
    h(0x6666ff), // number
    h(0x113311), // sym
    h(0x1d0878), // pp
    h(0x888888), // comment
    h(0x111111), // ignore
};

pub const BG = Color{ .r = 255, .g = 255, .b = 255 };
editor.zig ASCII text
  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
const std = @import("std");
const os = std.os;
const posix = std.posix;
const File = std.fs.File;
const ArrayList = std.ArrayList;

const ansi = @import("ansi.zig");
const AnsiCommand = ansi.AnsiCommand;
const txtbuf = @import("txtbuf.zig");
const color = @import("color.zig");
const util = @import("util.zig");

const Pos = @import("pos.zig");
const TextBuffer = txtbuf.TextBuffer;

const tok = @import("tok.zig");

fn asgn(u: usize) isize {
    return @intCast(u);
}

fn asun(i: isize) usize {
    return @intCast(i);
}

const Allocator = std.mem.Allocator;

const Edit = struct {
    const Self = @This();
    at: usize,
    old: []const u8,
    new: []const u8,
    fn init(at: usize, old: []const u8, new: []const u8, a: Allocator) !Self {
        const self_new = try a.alloc(u8, new.len);
        @memcpy(self_new, new);
        const self_old = try a.alloc(u8, old.len);
        @memcpy(self_old, old);
        return .{ .at = at, .new = self_new, .old = self_old };
    }
    // Note: To play nice with arena allocators, this must be in reverse order vs. init!
    fn deinit(self: Self, a: Allocator) void {
        a.free(self.old);
        a.free(self.new);
    }
    fn redo(self: Self, buf: *TextBuffer) !usize {
        try buf.replaceRange(self.at, self.old.len, self.new);
        return self.at + self.new.len;
    }
    fn undo(self: Self, buf: *TextBuffer) !usize {
        try buf.replaceRange(self.at, self.new.len, self.old);
        return self.at + self.old.len;
    }
};

const allocator = std.heap.c_allocator;

// TODO cap history size

const History = struct {
    const Self = @This();
    const ArenaAllocator = std.heap.ArenaAllocator;
    arena: ArenaAllocator,
    edits: ArrayList(Edit),
    cursor: usize,
    pub fn init() Self {
        const arena = ArenaAllocator.init(std.heap.page_allocator);
        return .{
            .arena = arena,
            .edits = ArrayList(Edit).init(allocator),
            .cursor = 0,
        };
    }
    pub fn deinit(self: Self) void {
        self.arena.deinit();
        self.edits.deinit();
    }

    fn undo(self: *Self, text: *TextBuffer) !?usize {
        if (self.cursor == 0)
            return null;
        self.cursor -= 1;
        return try self.edits.items[self.cursor].undo(text);
    }

    fn redo(self: *Self, text: *TextBuffer) !?usize {
        if (self.cursor == self.edits.items.len)
            return null;
        const res = try self.edits.items[self.cursor].redo(text);
        self.cursor += 1;
        return res;
    }

    fn record(self: *Self, at: usize, old: []const u8, new: []const u8) !void {
        // TODO do better than throwing edits away
        // Deinitialize *in reverse order* so the arena can actually free the memory
        if (self.cursor < self.edits.items.len) {
            var i: usize = self.edits.items.len - 1;
            while (true) {
                self.edits.items[i].deinit(self.arena.allocator());
                if (i == self.cursor) break;
                i -= 1;
            }
            self.edits.shrinkRetainingCapacity(self.cursor);
        }
        try self.edits.append(try Edit.init(at, old, new, self.arena.allocator()));
        self.cursor += 1;
    }
};

const Clipboard = struct {
    const Self = @This();
    content: []u8,
    pub fn init() !Self {
        return .{ .content = try allocator.alloc(u8, 0) };
    }
    pub fn deinit(self: Self) void {
        allocator.free(self.content);
    }
    pub fn get(self: Self) []const u8 {
        return self.content;
    }
    pub fn set(self: *Self, content: []const u8) !void {
        self.content = try allocator.realloc(self.content, content.len);
        @memcpy(self.content, content);
    }
};

const TextPane = struct {
    const Self = @This();
    anchor: Pos,
    cursor: Pos,
    mark: ?Pos,
    text: TextBuffer,
    history: History,
    clipboard: *Clipboard,
    multiline: bool,
    pub fn init(clipboard: *Clipboard, multiline: bool) !Self {
        return .{
            .anchor = .{ .row = 0, .col = 0 },
            .cursor = .{ .row = 0, .col = 0 },
            .mark = null,
            .text = try TextBuffer.empty(),
            .history = History.init(),
            .clipboard = clipboard,
            .multiline = multiline,
        };
    }
    pub fn deinit(self: *Self) void {
        self.text.deinit();
        self.history.deinit();
    }

    fn setCursor(self: *Self, cursor: Pos) void {
        self.cursor = cursor;
        self.mark = null;
    }

    pub fn setText(self: *Self, text: TextBuffer) void {
        self.text = text;
        self.setCursor(.{ .row = 0, .col = 0 });
        self.anchor = .{ .row = 0, .col = 0 };
        self.history.deinit();
        self.history = History.init();
    }

    fn moveRows(self: *Self, d: isize) Pos {
        const row = @max(0, @min(asgn(self.text.nRows()) - 1, asgn(self.cursor.row) + d));
        const col = @max(0, @min(self.text.nCols(row), self.cursor.col));
        return .{ .row = row, .col = col };
    }

    fn moveCols(self: *Self, d_cols: isize) Pos {
        var cursor = self.cursor;
        var d = d_cols;
        while (d < 0) {
            const col = asgn(cursor.col) + d;
            if (col >= 0) {
                cursor.col = asun(col);
                break;
            }
            if (cursor.row == 0) {
                cursor.col = 0;
                break;
            }
            cursor.row -= 1;
            cursor.col = self.text.nCols(cursor.row);
            d = col + 1;
        }
        while (d > 0) {
            const col = asgn(cursor.col) + d;
            const nCols = self.text.nCols(cursor.row);
            if (col <= nCols) {
                cursor.col = asun(col);
                break;
            }
            if (cursor.row == self.text.nRows() - 1) {
                cursor.col = nCols;
                break;
            }
            cursor.row += 1;
            cursor.col = 0;
            d = col - asgn(nCols) - 1;
        }
        return cursor;
    }

    fn getCursorIdx(self: Self) usize {
        return self.text.getIdx(self.cursor);
    }

    const Span = struct { min: usize, max: usize };
    fn getSelection(self: Self) ?Span {
        if (self.mark) |mark| {
            const idx = self.getCursorIdx();
            const mark_idx = self.text.getIdx(mark);
            return .{ .min = @min(idx, mark_idx), .max = @max(idx, mark_idx) };
        }
        return null;
    }

    fn getCopySpan(self: Self) Span {
        const idx = self.text.getIdx(.{ .row = self.cursor.row, .col = 0 });
        return self.getSelection() orelse Span{ .min = idx, .max = idx + self.text.nCols(self.cursor.row) + 1 };
    }

    fn copy(self: *Self) !void {
        const sel = self.getCopySpan();
        try self.clipboard.set(self.text.getRange(sel.min, sel.max));
    }

    fn deleteSpan(self: *Self, sel: Span) !void {
        const old = self.text.getRange(sel.min, sel.max);
        try self.history.record(sel.min, old, &.{});
        try self.text.replaceRange(sel.min, old.len, &.{});
        self.setCursor(self.text.getPos(sel.min));
    }

    fn delete(self: *Self) !void {
        const idx = self.getCursorIdx();
        const sel = self.getSelection() orelse Span{ .min = if (idx == 0) return else idx - 1, .max = idx };
        return self.deleteSpan(sel);
    }

    fn cut(self: *Self) !void {
        try self.copy();
        try self.deleteSpan(self.getCopySpan());
    }

    fn insert(self: *Self, new: []const u8) !void {
        if (!self.multiline and std.mem.indexOfScalar(u8, new, '\n') != null)
            return;
        const cur_idx = self.getCursorIdx();
        const sel = self.getSelection() orelse Span{ .min = cur_idx, .max = cur_idx };
        const old = self.text.getRange(sel.min, sel.max);
        try self.history.record(sel.min, old, new);
        try self.text.replaceRange(sel.min, old.len, new);
        self.setCursor(self.text.getPos(sel.min + new.len));
    }

    fn insertNewline(self: *Self) !void {
        const start_row = if (self.mark) |pos| @min(pos.row, self.cursor.row) else self.cursor.row;
        const start_col = if (start_row < self.cursor.row) self.mark.?.col else @min((self.mark orelse self.cursor).col, self.cursor.col);
        const start_idx = self.text.getIdx(.{ .row = start_row, .col = 0 });
        const line = self.text.getRange(start_idx, start_idx + self.text.nCols(start_row));
        var i: usize = 0;
        while (i < start_col and (line[i] == ' ' or line[i] == '\t')) i += 1;
        const indent = line[0..i];
        const indented_line = try std.mem.concat(allocator, u8, &.{ "\n", indent });
        defer allocator.free(indented_line);
        try self.insert(indented_line);
    }

    fn paste(self: *Self) !void {
        try self.insert(self.clipboard.get());
    }

    fn undo(self: *Self) !void {
        if (try self.history.undo(&self.text)) |idx|
            self.setCursor(self.text.getPos(idx));
    }

    fn redo(self: *Self) !void {
        if (try self.history.redo(&self.text)) |idx|
            self.setCursor(self.text.getPos(idx));
    }

    fn selectAll(self: *Self) void {
        self.cursor = .{ .row = 0, .col = 0 };
        self.mark = .{ .row = self.text.nRows() - 1, .col = self.text.nCols(self.text.nRows() - 1) };
    }

    fn selectToken(self: *Self) void {
        var hint = tok.Tokenization.Hint{};
        const token = self.text.tokens.getToken(self.getCursorIdx(), &hint);
        // HACK don't let the trailing newline disappear
        self.cursor = self.text.getPos(@min(hint.sum, self.text.chars.items.len - 1));
        self.mark = self.text.getPos(hint.sum - token.len);
    }

    fn gotoPrevToken(self: *Self) void {
        self.setCursor(self.text.getPos(self.text.tokens.getPreviousTokenStart(self.getCursorIdx())));
    }

    fn gotoNextToken(self: *Self) void {
        self.setCursor(self.text.getPos(self.text.tokens.getNextTokenEnd(self.getCursorIdx())));
    }

    pub fn processCommand(self: *Self, cmd: AnsiCommand) !void {
        switch (cmd) {
            else => {},
            .backspace, .delete => try self.delete(),
            .newline, .carriage_return => try self.insertNewline(),
            .print => |c| try self.insert(&[_]u8{c}),
            .tab => try self.insert("    "), // HACK awful
            .ctrl => |c| switch (c) {
                'z' => try self.undo(),
                'y' => try self.redo(),
                'c' => try self.copy(),
                'x' => try self.cut(),
                'v' => try self.paste(),
                'a' => self.selectAll(),
                't' => self.selectToken(),
                else => {},
            },
            .cursor_movement => |cm| switch (cm.modifier) {
                .none => switch (cm.action) {
                    .up => self.setCursor(self.moveRows(-asgn(cm.times))),
                    .down => self.setCursor(self.moveRows(asgn(cm.times))),
                    .right => self.setCursor(self.moveCols(asgn(cm.times))),
                    .left => self.setCursor(self.moveCols(-asgn(cm.times))),
                    .pos1 => self.setCursor(.{ .col = 0, .row = self.cursor.row }),
                    .end => self.setCursor(.{ .col = self.text.nCols(self.cursor.row), .row = self.cursor.row }),
                },
                .ctrl => switch (cm.action) {
                    .up, .down => {}, // TODO
                    .left => self.gotoPrevToken(),
                    .right => self.gotoNextToken(),
                    .pos1 => self.setCursor(.{ .row = 0, .col = 0 }),
                    .end => self.setCursor(.{ .row = self.text.nRows() - 1, .col = self.text.nCols(self.text.nRows() - 1) }),
                },
                .shift => {
                    if (self.mark == null)
                        self.mark = self.cursor;
                    switch (cm.action) {
                        .up => self.cursor = self.moveRows(-asgn(cm.times)),
                        .down => self.cursor = self.moveRows(asgn(cm.times)),
                        .right => self.cursor = self.moveCols(asgn(cm.times)),
                        .left => self.cursor = self.moveCols(-asgn(cm.times)),
                        .pos1 => self.cursor.col = 0,
                        .end => self.cursor.col = self.text.nCols(self.cursor.row),
                    }
                },
            },
        }
    }

    fn scroll(self: *Self, dim: Pos) void {
        self.anchor = self.anchor.min(self.cursor);
        const bottom_right = self.anchor.add(dim);
        if (self.cursor.row >= bottom_right.row)
            self.anchor.row += self.cursor.row - bottom_right.row + 1;
        if (self.cursor.col >= bottom_right.col)
            self.anchor.col += self.cursor.col - bottom_right.col + 1;
    }

    const ColorManager = struct {
        const CM = @This();
        fg: color.Color,
        bg: color.Color,
        pub fn init(writer: anytype) !CM {
            const fg = color.FG[@intFromEnum(tok.TokenType.ignore)];
            try ansi.setFg(writer, fg);
            const bg = color.BG;
            try ansi.setBg(writer, bg);
            return .{
                .fg = fg,
                .bg = bg,
            };
        }
        pub fn set(self: *CM, writer: anytype, t: tok.TokenType, sel: bool) !void {
            var fg = color.FG[@intFromEnum(t)];
            var bg = color.BG;
            if (sel)
                std.mem.swap(color.Color, &fg, &bg);
            if (!std.meta.eql(fg, self.fg)) {
                try ansi.setFg(writer, fg);
                self.fg = fg;
            }
            if (!std.meta.eql(bg, self.bg)) {
                try ansi.setBg(writer, bg);
                self.bg = bg;
            }
        }
    };

    fn render(self: *Self, dim: Pos, writer: anytype, focus: bool) !void {
        self.scroll(dim);

        const idx = self.getCursorIdx();
        const sel = self.getSelection() orelse Span{ .min = idx, .max = idx + 1 };

        var row: usize = 0;
        var cm = try ColorManager.init(writer);
        var tok_hint: tok.Tokenization.Hint = .{};
        while (row < dim.row) : (row += 1) {
            var col: usize = 0;
            while (col < dim.col) : (col += 1) {
                const pos = .{ .row = row, .col = col };
                const abs = self.anchor.add(pos);
                const c = self.text.get(abs);
                var highlight = false;
                var tt = tok.TokenType.ignore;
                if (abs.row < self.text.nRows() and abs.col <= self.text.nCols(abs.row)) {
                    const c_idx = self.text.getIdx(abs);
                    if (focus) highlight = c_idx >= sel.min and c_idx < sel.max;
                    tt = self.text.tokens.getToken(c_idx, &tok_hint).kind;
                }
                try cm.set(writer, tt, highlight);
                switch (c orelse ' ') {
                    0x20...0x7e => |ch| try writer.writeByte(ch),
                    else => try writer.writeAll(" "),
                }
            }
            if (row + 1 < dim.row)
                try writer.writeAll("\r\n");
        }
        try cm.set(writer, .ignore, false);
    }
};

pub const Editor = struct {
    const Self = @This();
    const BW = @TypeOf(std.io.bufferedWriter(std.io.getStdOut().writer()));
    tty: File,
    tui: *BW,
    path: []u8,
    clipboard: *Clipboard,
    textpane: TextPane,
    state: union(enum) {
        normal: void,
        confirm_quit: void,
        save_path: TextPane,
    },
    pub fn init(tty: File, tui: *BW) !Self {
        const clipboard = try allocator.create(Clipboard);
        clipboard.* = try Clipboard.init();
        return .{
            .tty = tty,
            .tui = tui,
            .path = try allocator.alloc(u8, 0),
            .clipboard = clipboard,
            .textpane = try TextPane.init(clipboard, true),
            .state = .normal,
        };
    }
    pub fn deinit(self: *Self) void {
        self.textpane.deinit();
        self.clipboard.deinit();
        allocator.free(self.path);
        allocator.destroy(self.clipboard);
    }

    fn setPath(self: *Self, path: []const u8) !void {
        self.path = try allocator.realloc(self.path, path.len);
        @memcpy(self.path, path);
    }

    pub fn open(self: *Self, path: []const u8) !void {
        if (TextBuffer.open(path)) |text| {
            self.textpane.setText(text);
            try self.setPath(path);
        } else |err| switch (err) {
            error.FileNotFound => {
                self.textpane.setText(try TextBuffer.empty());
                try self.setPath(path);
            },
            else => try self.setPath(""),
        }
    }

    fn isSaved(self: *Self) bool {
        if (self.path.len == 0)
            return self.textpane.text.chars.items.len == 0;
        const file = std.fs.cwd().openFile(self.path, .{ .mode = .read_only }) catch return false;
        var chars = ArrayList(u8).init(allocator);
        defer chars.deinit();
        file.reader().readAllArrayList(&chars, 16384) catch return false;
        return std.mem.eql(u8, self.textpane.text.chars.items, chars.items);
    }

    fn save(self: *Self) !void {
        if (self.path.len > 0) {
            try self.textpane.text.save(self.path); // TODO error handling
        } else {
            self.state = .{ .save_path = try TextPane.init(self.clipboard, false) };
        }
    }

    fn processCommand(self: *Self, cmd: AnsiCommand) !bool {
        switch (self.state) {
            .normal => switch (cmd) {
                .ctrl => |c| switch (c) {
                    'q' => {
                        if (self.isSaved())
                            return true;
                        self.state = .{ .confirm_quit = {} };
                    },
                    's' => try self.save(),
                    else => try self.textpane.processCommand(cmd),
                },
                else => try self.textpane.processCommand(cmd),
            },
            .confirm_quit => switch (cmd) {
                .ctrl => |c| switch (c) {
                    'q' => return true,
                    else => self.state = .{ .normal = {} },
                },
                else => self.state = .{ .normal = {} },
            },
            .save_path => |prompt| switch (cmd) {
                .ctrl => |c| switch (c) {
                    'q' => {
                        self.state.save_path.deinit();
                        self.state = .{ .normal = {} };
                    },
                    else => try self.state.save_path.processCommand(cmd),
                },
                .newline, .carriage_return => {
                    const path = prompt.text.chars.items;
                    try self.setPath(path[0 .. path.len - 1]); // trim trailing newline (TODO refucktor)
                    try self.textpane.text.save(self.path); // TODO error handling
                    self.state.save_path.deinit();
                    self.state = .{ .normal = {} };
                },
                else => try self.state.save_path.processCommand(cmd),
            },
        }
        return false;
    }

    fn processInput(self: *Self, buf: []const u8) !bool {
        var iter = ansi.parse(buf);
        while (iter.next()) |cmd| {
            switch (cmd) {
                .ignore => {},
                .insert => @import("e/josh.zig").josh(self.tty, self.tui) catch {},
                else => if (try self.processCommand(cmd)) return true,
            }
        }
        return false;
    }

    fn render(self: *Self) !void {
        const us = std.time.microTimestamp();
        const writer = self.tui.writer();
        const dim = try util.getTtySize(self.tty);
        try ansi.setCursor(writer, .{ .row = 0, .col = 0 });
        try self.textpane.render(.{ .row = dim.row - 1, .col = dim.col }, writer, self.state == .normal);
        try writer.writeAll("\r\n");

        switch (self.state) {
            .normal => {
                var buf: [1000]u8 = undefined;
                var fixbuf = std.io.fixedBufferStream(&buf);
                @memset(buf[0..dim.col], ' ');
                std.fmt.format(fixbuf.writer(), "{s}:{d}:{d}  {d} us  {d} lines", .{
                    if (self.path.len == 0) "?" else self.path,
                    self.textpane.cursor.row + 1,
                    self.textpane.cursor.col + 1,
                    std.time.microTimestamp() - us,
                    self.textpane.text.nRows(),
                }) catch {};
                try writer.writeAll(buf[0..dim.col]);
            },
            .confirm_quit => {
                const msg = "You have unsaved changes. Press C-q to quit, any other key to cancel.";
                try writer.writeAll(if (dim.col < msg.len) msg[0..dim.col] else msg);
                var i = msg.len;
                while (i < dim.col) : (i += 1) try writer.writeByte(' ');
            },
            .save_path => {
                const prefix = "save as: ";
                try writer.writeAll(prefix);
                try self.state.save_path.render(.{ .row = 1, .col = dim.col - prefix.len }, writer, true);
            },
        }

        try self.tui.flush();
    }

    pub fn run(self: *Self) !void {
        try self.render();
        var buf: [1000]u8 = undefined;
        while (true) {
            // TODO deal with full buffer (unlikely in normal usage)
            const len = try self.tty.read(&buf);
            if (try self.processInput(buf[0..len]))
                return;
            try self.render();
        }
    }
};
main.zig ASCII text
 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
const std = @import("std");
const fs = std.fs;
const os = std.os;
const posix = std.posix;

const ansi = @import("ansi.zig");
const Editor = @import("editor.zig").Editor;

fn uncook(handle: anytype, tcattr: anytype) !void {
    var raw_attr = tcattr;
    raw_attr.lflag.ECHO = false;
    raw_attr.lflag.ICANON = false;
    raw_attr.lflag.ISIG = false;
    raw_attr.lflag.IEXTEN = false;
    raw_attr.iflag.IXON = false;
    raw_attr.iflag.ICRNL = false;
    raw_attr.iflag.BRKINT = false;
    raw_attr.iflag.INPCK = false;
    raw_attr.iflag.ISTRIP = false;
    raw_attr.oflag.OPOST = false;
    raw_attr.cflag.CSIZE = .CS8;
    // TODO think about these
    raw_attr.cc[@intFromEnum(std.posix.V.TIME)] = 0;
    raw_attr.cc[@intFromEnum(std.posix.V.MIN)] = 1;
    try std.posix.tcsetattr(handle, .FLUSH, raw_attr);
}

fn run() !void {
    var tty = try fs.cwd().openFile("/dev/tty", .{ .mode = .read_write });
    defer tty.close();

    const cooked_attr = try std.posix.tcgetattr(tty.handle);
    defer std.posix.tcsetattr(tty.handle, .FLUSH, cooked_attr) catch {};
    try uncook(tty.handle, cooked_attr);

    const stdout_file = std.io.getStdOut().writer();
    var bw = std.io.bufferedWriter(stdout_file);
    defer bw.flush() catch {};
    const stdout = bw.writer();
    const writeCsi = ansi.writeCsi;

    // Hide / unhide cursor
    try writeCsi(stdout, "?25l");
    defer writeCsi(stdout, "?25h") catch {};
    // Mouse on / off
    // try writeCsi(stdout, "?1000h");
    // defer writeCsi(stdout, "?1000l") catch {};
    // Save / restore cursor pos
    try writeCsi(stdout, "s");
    defer writeCsi(stdout, "u") catch {};
    // Save / restore screen
    try writeCsi(stdout, "?47h");
    defer writeCsi(stdout, "?47l") catch {};
    // Enable alternative buffer / switch back to original buffer
    try writeCsi(stdout, "?1049h");
    defer writeCsi(stdout, "?1049l") catch {};
    try bw.flush();

    var editor = try Editor.init(tty, &bw);
    defer editor.deinit();
    var args = std.process.args();
    if (args.next()) |_| {
        if (args.next()) |path| {
            if (args.next() == null)
                try editor.open(path);
        }
    }
    try editor.run();
}

pub fn main() !void {
    return run() catch |e| switch (e) {
        error.OutOfMemory => std.io.getStdOut().writer().writeAll(@import("e/oom.zig").oom),
        else => e,
    };
}
plain.zig ASCII text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
const tok = @import("tok.zig");
const RegexTokenizer = tok.RegexTokenizer;
const Token = tok.Token;

var cache: ?RegexTokenizer = null;
pub fn tokenizer() !RegexTokenizer {
    cache = cache orelse try RegexTokenizer.init(&.{
        // zig fmt: off
        .{.identifier, "[^ \n\r\t]+"},
        .{.ignore, "[ \n\r\t]+"},
    });
    return cache.?;
}
pos.zig ASCII text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
const Pos = @This();
row: usize,
col: usize,
pub fn add(p: Pos, q: Pos) Pos {
    return Pos{ .row = p.row + q.row, .col = p.col + q.col };
}
pub fn sub(p: Pos, q: Pos) Pos {
    return Pos{ .row = p.row - q.row, .col = p.col - q.col };
}
pub fn min(p: Pos, q: Pos) Pos {
    return Pos{ .row = @min(p.row, q.row), .col = @min(p.col, q.col) };
}
tok.zig ASCII text
  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
const std = @import("std");

const NFA = @import("reg/nfa.zig").NFA(StateInfo);
const DFA = @import("reg/dfa.zig").DFA(StateInfo);
const RegexReader = @import("reg/ex.zig").RegexReader(StateInfo);
const allocator = std.heap.c_allocator;

pub const TokenType = enum(u8) {
    keyword,
    identifier,
    quoted,
    number,
    sym,
    pp,
    comment,
    ignore,
};

pub const Token = struct {
    kind: TokenType,
    len: usize,
};

const StateInfo = struct {
    tt: TokenType,
    acc: bool,
};

fn mergeTokens(a: StateInfo, b: StateInfo) StateInfo {
    if (a.acc != b.acc) {
        return if (a.acc) a else b;
    }
    return .{
        .tt = @enumFromInt(@min(@intFromEnum(a.tt), @intFromEnum(b.tt))),
        .acc = a.acc,
    };
}

pub const RegexTokenizer = struct {
    const Self = @This();
    dfa: DFA,
    pub fn init(comptime rules: []const struct { TokenType, []const u8 }) !Self {
        var nfa = NFA.init(allocator, .{ .tt = .ignore, .acc = false });
        defer nfa.deinit();
        var subs: [rules.len]NFA.Sub = undefined;
        var i: usize = 0;
        while (i < rules.len) : (i += 1) {
            nfa.value = .{ .tt = rules[i][0], .acc = false };
            var rr = RegexReader.init(&nfa, rules[i][1]);
            subs[i] = try rr.read();
            nfa.states.items[subs[i].end].value.acc = true; // HACK
        }
        const sub = try nfa.choice(&subs);
        return .{
            .dfa = try nfa.toDFA(sub, mergeTokens),
        };
    }
    // no need to deinit
    pub fn nextToken(self: Self, buf: []const u8) Token {
        var state: usize = 0;
        var len: usize = 0;
        while (len < buf.len) : (len += 1) {
            const c = buf[len];
            if (self.dfa.getTransition(state, c)) |next_state| {
                state = next_state;
            } else {
                return .{
                    .kind = self.dfa.states.items[state].value.tt,
                    .len = @max(len, 1), // HACK
                };
            }
        }
        return .{
            .kind = self.dfa.states.items[state].value.tt,
            .len = @max(len, 1),
        };
    }
};

// Two interesting optimizations are possible here:
// - We could retokenize only the affected range.
// - We could use a clever data structure (e.g. B-trees augmented with sums of token lengths)
// All in all this would in theory allow updates in O(edit size) time.
// But we don't have working B-trees so we don't and this is O(text size) on every edit. Urgh.
pub const Tokenization = struct {
    const Self = @This();
    tokens: std.ArrayList(Token),
    pub fn init(text: []const u8, tokenizer: RegexTokenizer) !Self {
        var i: usize = 0;
        var tokens = std.ArrayList(Token).init(allocator);
        while (i < text.len) {
            const t = tokenizer.nextToken(text[i..]);
            try tokens.append(t);
            i += t.len;
        }
        return .{ .tokens = tokens };
    }
    pub fn deinit(self: *Self) void {
        self.tokens.deinit();
    }
    pub const Hint = struct {
        ti: usize = 0,
        sum: usize = 0,
    };
    pub fn getPreviousTokenStart(self: Self, i: usize) usize {
        var sum: usize = 0;
        var res: usize = 0;
        var j: usize = 0;
        while (sum < i and j < self.tokens.items.len) : (j += 1) {
            const token = self.tokens.items[j];
            if (token.kind != .ignore)
                res = sum;
            sum += token.len;
        }
        return res;
    }
    pub fn getNextTokenEnd(self: Self, i: usize) usize {
        var sum: usize = 0;
        var j: usize = 0;
        while (sum < i and j < self.tokens.items.len) {
            sum += self.tokens.items[j].len;
            j += 1;
        }
        while (j < self.tokens.items.len) : (j += 1) {
            sum += self.tokens.items[j].len;
            if (self.tokens.items[j].kind != .ignore) break;
        }
        return sum;
    }
    pub fn getToken(self: Self, i: usize, hint: *Hint) Token {
        while (hint.sum <= i and hint.ti < self.tokens.items.len) {
            hint.sum += self.tokens.items[hint.ti].len;
            hint.ti += 1;
        }
        return self.tokens.items[hint.ti - 1];
    }
};
txtbuf.zig ASCII text
  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
const std = @import("std");
const fs = std.fs;
const Path = []const u8;

const stdio = @cImport({
    @cInclude("stdio.h");
});

const Pos = @import("pos.zig");

const char = u8;

const allocator = std.heap.c_allocator;
const Allocator = std.mem.Allocator;

const ArrayList = std.ArrayList;

const Tokenization = @import("tok.zig").Tokenization;

pub const FileType = enum {
    plain,
    c,
    fn init(path: Path) FileType {
        return if (std.mem.endsWith(u8, path, ".c")) .c else .plain;
    }
};

fn tokenize(t: FileType, text: []const u8) !Tokenization {
    return Tokenization.init(text, switch (t) {
        .plain => try @import("plain.zig").tokenizer(),
        .c => try @import("c.zig").tokenizer(),
    });
}

pub const TextBuffer = struct {
    const Self = @This();
    chars: ArrayList(char),
    lineOffsets: ArrayList(usize), // where does the respective line end?
    fileType: FileType,
    tokens: Tokenization,
    pub fn empty() !Self {
        var chars = try ArrayList(char).initCapacity(allocator, 1);
        try chars.append('\n');
        return Self{
            .chars = chars,
            .lineOffsets = try calculateLineOffsets(chars.items),
            .tokens = try tokenize(.plain, chars.items),
            .fileType = .plain,
        };
    }
    pub fn open(path: Path) !Self {
        const file = try fs.cwd().openFile(path, .{ .mode = .read_only });
        const reader = file.reader();
        var chars = ArrayList(char).init(allocator);
        {
            defer file.close();
            try reader.readAllArrayList(&chars, 16384);
        }
        const ft = FileType.init(path);
        return .{
            .chars = chars,
            .lineOffsets = try Self.calculateLineOffsets(chars.items),
            .tokens = try tokenize(ft, chars.items),
            .fileType = ft,
        };
    }
    pub fn save(self: *TextBuffer, path: Path) !void {
        const old_ft = self.fileType;
        self.fileType = FileType.init(path);
        if (old_ft != self.fileType) {
            self.tokens.deinit();
            self.tokens = try tokenize(self.fileType, self.chars.items);
        }

        const dirname = fs.path.dirname(path);
        const basename = fs.path.basename(path);
        const tmpname = try std.mem.concat(allocator, u8, &.{ ".~sped-tmp-", basename });
        defer allocator.free(tmpname);
        const tmpath = try fs.path.join(allocator, if (dirname) |name| &.{ name, basename } else &.{basename});
        defer allocator.free(tmpath);
        const file = try fs.cwd().createFile(tmpath, .{});
        {
            defer file.close();
            try file.writeAll(self.chars.items);
        }
        try fs.cwd().rename(tmpath, path);
    }
    pub fn deinit(self: *Self) void {
        self.chars.deinit();
        self.lineOffsets.deinit();
        self.tokens.deinit();
    }
    /// Number of rows, always >= 1.
    pub fn nRows(self: Self) usize {
        return self.lineOffsets.items.len;
    }
    pub fn nCols(self: Self, row: usize) usize {
        return if (row == 0)
            self.lineOffsets.items[0]
        else
            self.lineOffsets.items[row] - self.lineOffsets.items[row - 1] - 1;
    }
    // TODO LFs (<=)
    pub fn inBounds(self: Self, pos: Pos) bool {
        return pos.row < self.nRows() and pos.col < self.nCols(pos.row);
    }
    fn rowStart(self: Self, row: usize) usize {
        return if (row == 0) 0 else self.lineOffsets.items[row - 1] + 1;
    }
    pub fn getIdx(self: Self, pos: Pos) usize {
        return self.rowStart(pos.row) + pos.col;
    }
    fn loLt(_: void, lhs: usize, rhs: usize) bool {
        return lhs < rhs;
    }
    /// O(log n)
    pub fn getPos(self: Self, idx: usize) Pos {
        const row = std.sort.lowerBound(usize, idx, self.lineOffsets.items, void{}, loLt);
        return .{ .row = row, .col = idx - self.rowStart(row) };
    }
    pub fn get(self: Self, pos: Pos) ?char {
        return if (self.inBounds(pos)) self.chars.items[self.getIdx(pos)] else null;
    }
    pub fn getRange(self: Self, from: usize, to: usize) []const u8 {
        return self.chars.items[from..to];
    }
    fn calculateLineOffsets(chars: []const u8) !ArrayList(usize) {
        var lineOffsets = ArrayList(usize).init(allocator);
        var i: usize = 0;
        while (std.mem.indexOfScalar(char, chars[i..], '\n')) |offset| {
            try lineOffsets.append(i + offset);
            i += offset + 1;
        }
        if (chars.len == 0 or i < chars.len) // no trailing newline
            try lineOffsets.append(chars.len); // note: no newline!
        return lineOffsets;
    }
    pub fn replaceRange(self: *Self, from: usize, len: usize, replacement: []const u8) !void {
        try self.chars.replaceRange(from, len, replacement);
        self.lineOffsets.deinit();
        self.lineOffsets = try calculateLineOffsets(self.chars.items);
        self.tokens.deinit();
        self.tokens = try tokenize(self.fileType, self.chars.items);
    }
};
util.zig ASCII text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
const std = @import("std");
const Pos = @import("pos.zig");

pub fn getTtySize(tty: std.fs.File) !Pos {
    var size: std.c.winsize = undefined;
    size.ws_row = 60;
    size.ws_col = 80;
    const err = std.c.ioctl(tty.handle, std.c.T.IOCGWINSZ, &size);
    if (err != 0)
        return error.TerminalSizeUnknown;
    return .{ .row = size.ws_row, .col = size.ws_col };
}
build.zig ASCII text
 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
const std = @import("std");

pub fn build(b: *std.Build) void {
    const target = b.standardTargetOptions(.{});
    const optimize = b.standardOptimizeOption(.{});

    const exe = b.addExecutable(.{
        .name = "sped",
        .root_source_file = b.path("src/main.zig"),
        .target = target,
        .optimize = optimize,
        .link_libc = true,
    });

    b.installArtifact(exe);

    const run_cmd = b.addRunArtifact(exe);

    run_cmd.step.dependOn(b.getInstallStep());

    if (b.args) |args| {
        run_cmd.addArgs(args);
    }

    const run_step = b.step("run", "Run editor");
    run_step.dependOn(&run_cmd.step);

    const exe_unit_tests = b.addTest(.{
        .root_source_file = b.path("src/c.zig"),
        .target = target,
        .optimize = optimize,
        .link_libc = true,
    });

    const run_exe_unit_tests = b.addRunArtifact(exe_unit_tests);

    const test_step = b.step("test", "Run unit tests");
    test_step.dependOn(&run_exe_unit_tests.step);
}
build.zig.zon ASCII text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
.{
    .name = "sped",
    .version = "0.0.0",
    .minimum_zig_version = "0.13.0",
    .dependencies = .{},
    .paths = .{
        "build.zig",
        "build.zig.zon",
        "src",
        // TODO license
    },
}
tut.txt ASCII text
 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
sped is a lightweight, primitive text editor

if first command line argument is a file that is opened

stuff marked with [ ] is not yet implemented

features:

- syntax highlighting (C only)
- [ ] good performance even for massive files

keybindings:

notation:

- Control: C
- Shift: S
- Arrow Keys: L, R, U, D

cursor movement:

- L / R / U / D: move cursor
- begin / end: move to begin / end of line
- C-begin / C-end: move to begin / end of file
- [ ] page up / page down: move cursor up / down one page
- C-L / C-R: move to previous / next token
- [ ] C-U / C-D:
    * if parentheses (tokens) are unmatched at cursor position:
      move to previous opening / subsequent closing parenthesis
    * otherwise:
      move to previous / subsequent smaller indentation level

selection:

- S-L / S-R / S-U / S-D: start or continue selection 
- C-c / C-x / C-v: copy / cut / paste
	* operate on the given line if nothing is selected
- C-a / C-t: select all / token

editing:

- character keys: insert character
- backspace: delete
- [ ] tab:
	* if preceding characters are whitespace (incl. newline): indent
	* otherwise: autocomplete token
- [ ] S-tab: dedent
- enter: insert newline (with indentation)
- C-z / C-y: undo / redo

meta:

- C-q: quit
- C-s: save file
- [ ] C-f: find
- [ ] C-r: replace
- [ ] C-g: goto
- [ ] C-i: help

entry #7

written by LyricLy
submitted at
3 likes

guesses
comments 0

post a comment


sokohen.py Unicode text, UTF-8 text
  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
import argparse
import signal
import sys
from blessed import Terminal

PH = "⬚"

parser = argparse.ArgumentParser(description="Edit a file.")
parser.add_argument("filename")
args = parser.parse_args()

buffer = []

def load(f):
    content = f.read()
    if not content:
        buffer.clear()
        return
    if any(ord(c) not in {10, *range(32, 126)} for c in content):
        raise ValueError("file is not printable ASCII")
    buffer[:] = [list(x + PH*x.endswith(" ")) for x in content.split("\n")]
    if not buffer[0]:
        buffer[0].append(PH)
    if not buffer[-1]:
        buffer[-1].append(PH)

def save(f):
    for i, line in enumerate(buffer):
        end = "\n" if i + 1 != len(buffer) else ""
        f.write("".join(c for c in line if c != PH) + end)

def at(y, x):
    y += origin
    if 0 <= y < len(buffer) and 0 <= x < len(buffer[y]):
        return buffer[y][x]
    else:
        return " "

def put(y, x, c):
    global origin
    if x < 0:
        return
    if not buffer:
        origin = -y
    if c != " ":
        y += origin
        prepend_by = max(-y, 0)
        origin += prepend_by
        y += prepend_by
        buffer[:0] = [[] for _ in range(prepend_by)]
        buffer.extend([] for _ in range(max(y-len(buffer)+1, 0)))
        line = buffer[y]
        line.extend(" " * max(x-len(line)+1, 0))
        line[x] = c
    else:
        if at(y, x) == " ":
            return
        clear_off.append((y, x))
        y += origin
        line = buffer[y]
        line[x] = " "
        while line and line[-1] == " ":
            line.pop()
        while buffer and not buffer[0]:
            origin -= 1
            buffer.pop(0)
        while buffer and not buffer[-1]:
            buffer.pop()

try:
    with open(args.filename) as f:
        load(f)
except FileNotFoundError:
    pass
except ValueError:
    print("oh no: file does not consist of printable ASCII", file=sys.stderr)
    sys.exit(1)

clear_off = []
origin = -1
uy = ux = cy = cx = 0
at_keyboard = False

term = Terminal()
norm = term.bright_white + term.on_color_rgb(0x26, 0x26, 0x26)
sb = term.white + term.on_color_rgb(0x36, 0x36, 0x36)

def total_clear():
    print(norm + term.clear)
    clear_off.clear()

def render():
    global cy, cx, ux

    o = cy, cx
    h = term.height
    cy += (uy-cy) // h * h
    s = cy + origin
    nw = len(str(max(s, 0) + h))

    if not at_keyboard and ux < ~nw:
        add_keyboard()
    if at_keyboard and ux >= at_keyboard:
        remove_keyboard()
    if at_keyboard:
        nw = -1
        ux = max(ux, 0)

    w = term.width - nw - 1
    cx += (ux-cx) // w * w
    cx = max(cx, 0)

    if (cy, cx) != o:
        total_clear()

    with term.hidden_cursor():
        print(norm, end="")
        for y, x in clear_off:
            print(term.move_yx(y - cy, x - cx + nw+1) + " ", end="")
        clear_off.clear()

        print(term.home, end="")
        for dry in range(s, s+h):
            end = "\r\n" if dry + 1 != s+h else ""
            if 0 <= dry < len(buffer):
                line = "".join(buffer[dry][cx:cx+w])
                if not at_keyboard:
                    print(f"{sb}{dry+1:>{nw}} ", end="")
                print(f"{norm}{line}", end=end)
            else:
                print("" if at_keyboard else sb + " "*(nw+1), end=end)

        print(term.move_yx(uy - cy, ux - cx + nw+1), end="", flush=True)

def on_resize(sig, action):
    render()

signal.signal(signal.SIGWINCH, on_resize)

def shift(dy, dx):
    global uy, ux
    uy += dy
    ux += dx
    y = uy
    x = ux
    shifting = " "
    while at(y, x) != " ":
        temp = at(y, x)
        put(y, x, shifting)
        shifting = temp
        y += dy
        x += dx
    put(y, x, shifting)

KEYBOARD = rf"""
` ~ 1 ! 2 @ 3 # 4 $ 5 % 6 ^ 7 & 8 * 9 ( 0 ) - _ = +

     q Q w W e E r R t T y Y u U i I o O p P [ {{ ] }} \ |

      a A s S d D f F g G h H j J k K l L ; : ' "

       z Z x X c C v V b B n N m M , < . > / ? {PH}
"""

def add_keyboard():
    global at_keyboard, ux
    shift = term.width + ~ux
    at_keyboard = shift
    ux += shift
    for l in buffer:
        if l:
            l[:0] = [" "] * shift
    rows = KEYBOARD.strip().splitlines()
    top = term.height // 2 - len(rows) // 2
    left = term.width // 2 - len(rows[2]) // 2
    for y, row in enumerate(rows):
        for x, c in enumerate(row):
            put(top+y, left+x, c) 
    total_clear()

def remove_keyboard():
    global at_keyboard, ux
    for y, l in enumerate(buffer):
        for x in range(0, at_keyboard):
            put(y-origin, x, " ")
        del l[:at_keyboard]
    ux -= at_keyboard
    at_keyboard = None

def ctrl(c):
    return chr(ord(c) & 31)

with term.fullscreen(), term.raw():
    total_clear()
    render()
    while True:
        next_key = term.inkey()
        if next_key == ctrl("q"):
            break
        elif next_key == ctrl("s"):
            with open(args.filename, "w") as f:
                save(f)
        elif next_key.code == term.KEY_UP:
            shift(-1, 0)
        elif next_key.code == term.KEY_DOWN:
            shift(1, 0)
        elif next_key.code == term.KEY_RIGHT:
            shift(0, 1)
        elif next_key.code == term.KEY_LEFT:
            shift(0, -1)
        render()
tut.txt ASCII text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
Welcome to sokohen! (Edit this file with `python sokohen.py tut.txt`.)

This editor works like the game Sokoban. Use arrow keys to move your cursor and push letters around!

  Youcanmove your cursor through the line number column. Try moving this entire sentence to the right, so it looks like the line below.
                        Youcanmoveyourcursorthroughthelinenumbercolumn.Trymovingthisentiresentencetotheright,soitlookslikethelinebelow.

Go all the way through the line numbers to the screen to the left to get a keyboard you can take letters from.
The keyboard automatically refreshes whenever you return to its screen, so characters are renewable.

Finally, the symbol below is a "placeholder" that represents... nothing at all! You can use it to insert trailing spaces or leading/trailing newlines. Have fun with sokohen!









                       

entry #8

written by Olivia
submitted at
6 likes

guesses
comments 0

post a comment


cooking.txt ASCII text
1
2
https://github.com/RocketRace/viiru
it certainly is an "editor" that is "text"

entry #9

written by moshikoi
submitted at
2 likes

guesses
comments 0

post a comment


index.html ASCII text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8" />
    <title>VSCode 2</title>
</head>

<body>
    <button id="open">Open</button>
    <button id="save">Save</button>
    <textarea id="input"></textarea>
    <script>
        document.getElementById('open').addEventListener('click', async _ => {
            const { path, content } = await electronAPI.openFile();
            document.getElementById('input').value = content
        });
        document.getElementById('save').addEventListener('click', async _ => {
            await electronAPI.saveFile(document.getElementById('input').value);
        });
    </script>
</body>

</html>
index.js ASCII text
 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
const { app, BrowserWindow, dialog, ipcMain } = require('electron');
const { readFile, writeFile } = require('node:fs/promises');
const { } = require('node:os');
const path = require('node:path');

var filePath = null;

var win;

async function handleFileOpen(event, obj) {
        const { canceled, filePaths } = await dialog.showOpenDialog(win);
        var content;
        if (canceled) {
                filePath = null;
                content = '';
        } else {
                filePath = filePaths[0];
                content = await readFile(filePaths[0], 'utf-8');
        }

        return { filePath, content };
}

async function handleFileSave(event, content) {
        await writeFile(filePath, content);
}

async function createWindow() {
        win = new BrowserWindow({
                width: 800,
                height: 600,
                webPreferences: {
                        preload: path.join(__dirname, 'preload.js')
                }
        });

        win.loadFile('index.html');
        ipcMain.handle('open-file', handleFileOpen);
        ipcMain.handle('save-file', handleFileSave);
};

app.whenReady().then(() => {
        createWindow();
});
package.json JSON text data
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
{
  "name": "cg62",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "electron .",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "SoundOfSpouting#6980 (UID: 151149148639330304)",
  "license": "ISC",
  "devDependencies": {
    "electron": "^31.3.1"
  }
}
preload.js ASCII text
1
2
3
4
5
6
const { contextBridge, ipcRenderer } = require('electron/renderer');

contextBridge.exposeInMainWorld('electronAPI', {
    openFile() { return ipcRenderer.invoke('open-file'); },
    saveFile(text) { return ipcRenderer.invoke('save-file', text); }
});

entry #10

written by yui
submitted at
0 likes

guesses
comments 0

post a comment


meow.html Unicode text, UTF-8 text
 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
<textarea id="according-to-all-known-laws-of-aviation" cols="72" rows="24" autocomplete="off"></textarea>
<br/>
<label for="there-is-no-way-that-a-bee-should-be-able-to-fly">
  <input type="file" id="there-is-no-way-that-a-bee-should-be-able-to-fly" style=display:none />
  <span>Load</span>
</label>
|
<a href="#" download="untitled" target="_blank" id="its-wings-are-too-small-to-get-its-fat-little-body-off-the-ground">Save</a>
<!-- meow 🥺 -->
<script>
  var meow = document.getElementById("according-to-all-known-laws-of-aviation")
  var meower = document.getElementById("there-is-no-way-that-a-bee-should-be-able-to-fly")
  var meowing = document.getElementById("its-wings-are-too-small-to-get-its-fat-little-body-off-the-ground")

  meower.oninput = function(){
    var uwu = meower.files[0];

    uwu.text().then(function(nya){
      meow["value"] = nya;
      meowing["download"] = uwu["name"];
    });
  }
  
  meowing.onclick = function(){
    var nya = meow["value"];
    var bowob = new Blob([nya]);
    var uwu = URL.createObjectURL(bowob)
    meowing["href"] = uwu;
    setTimeout( function(){
      URL.revokeObjectURL(uwu);
    }) ;
  }
</script>

entry #11

written by yeti
submitted at
0 likes

guesses
comments 0

post a comment


edit.py ASCII text
 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
from sortedcontainers import SortedDict
buffer = SortedDict({})
while True:
    inp = input(">> ")
    parts = inp.split(" ")
    if len(parts) == 0:
        continue
    if parts[0].isnumeric():
        num = int(parts[0])
        buffer[num] = " ".join(parts[1:])
    elif parts[0] == "list":
        for key in buffer.keys():
            print(f"{key}: {buffer[key]}")
    elif parts[0] == "save":
        file = open(parts[1], "w")
        for key in buffer.keys():
            file.write(buffer[key] + "\n")
        print("saved")
    elif parts[0] == "open":
        file = open(parts[1], "r")
        lineNum = 10
        for line in file:
            buffer[lineNum] = line.rstrip()
            lineNum += 10
    else:
        print(f"Unknown command {parts[0]}")

entry #12

written by taswelll
submitted at
2 likes

guesses
comments 0

post a comment


txt.k ASCII text
 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
#!/bin/awk /aw -ec/{system("stty raw -echo;k "ARGV[1]" $(stty size) "ARGV[2]";stty sane")}
(h;w):.'2#x; t:(~#:){,""}/0:fd:<`$fn:$[2=#x;`argv 1;x 2] /height;width, t:text(lines)
fcur:cur:scr:0 0; sel:0N 0N; clip:,"" /(fake)cursor, scroll, first selected, clipboard
CS:0x1b5b; CL:CS/" "\" H 2J"; (LI;TX;SE;BO):CS,/:" "\"37;100m 97;40m 90;47m 44m" /colors
foot:foot0:"^F Find Next  ^XCV Clipboard  ^E Eval  ^S Save  ^Q Quit" /footer
place:{[pos;str;a] $[~(0;h-1)'n:*pos-scr; a[n]:?[a[n];0|(w-4)&(pos-scr)1;str];]; a}
disp:{r:4$(4>#:)(4$-3$)//:$'1+no:scr[0]+!# m:(w-4)$scr[1]_/:((h-1)&#a)#a:scr[0]_t
 $[^*sel;s:!0;[(sa;sz):s:x@<x:(sel;cur); m:place[sa;SE]place[sz;TX]m]] /display selection
 `1:CL; `0:LI,/:r,'(TX;SE)[~(*'s)'no-1],'m,\:"\r"; f:"editing ",fn," at ",":"/$'1+cur
 `1:BO,(f,(-w-#f)$foot),CS,(";"/$'1 5+cur-scr),"H"} /r:ruler, m:main
read:{(sa;sz):sord`;$[^*sel;,t[*cur]; ~*sz-sa; ,(sz-sa)[1]#sa[1]_t[*sa] /selected lines
                      (,sa[1]_t[*sa]),((*sz-1+sa)#(1+*sa)_t),,sz[1]#t[*sz]]}
type:{(sa;sz):sord`;a:$[2>#x;,(sa[1]#t[*sa])    ,(    *x)       ,sz[1]_t@*sz /write lines
                            (,(sa[1]#t[*sa]),*x),(-1_1_x),,(*|x),sz[1]_t@*sz]
 t:: ?[t;(*sa;1+*sz);a]; desel (sa[0]+-1+#x;(sa[1]*2>#x)+#*|x)}; end:{l,#t@l:-1+#t};
sord:{a@<a:(cur^'sel;cur)}; desel:{sel::0N 0N;x}; up:{x*~0>*x}; dn:{~x[0]<#t}end/; /^v oob
sft:{ac[y]:{[f;x] $[x;;sel::cur];f 0}ac x}; scroll:{scr[0]:((#t)--2!h)&0|x+*scr;cur+x,0}
ac:(,"")!,0N; other:{[x;s] type@,(~0x1f<*x)`k/x}; /ac[key][selected?]>new cur, otherwise
ac[CS,"A"]:{x desel/up fcur-1 0}; ac[CS,"B"]:{x desel/dn fcur+1 0} /Up Down
ac[CS,"C"]:{{x[1]>#t@*x}{dn(1+*x;0)}/cur+0 1},{desel sord[] 1}     /Right
ac[CS,"D"]:{{0>x 1}{up a,#t@a:-1+*x}/cur-0 1},{desel sord[] 0}     /Left
ac[,0x13]:{fd 1:"\n"/t;>fd;fd::<`$fn;cur}; ac[,0x11]:{>fd;`1:CS,"0m",CL;`exit 0} /^S ^Q
ac[,0x05]:{$[x;type;{t::?[t;1+*cur;x];cur}]@"\n"\(~`C=@:)`k/.[.:;,"\n"/read`;::]} /^E
sprd:{t::@[t;&&(1--)\*'sord`;x]};ac[,"\t"]:{sprd@,[tw#" ";];$[x;sel+:0,tw;];cur+0,tw} /Tab
ac[CS,"Z"]:{sprd{(tw&+/&\x=" ")_x};$[x;sel::0|sel-0,tw;];0|cur-0,tw}; tw:4 /Sft+Tab, width
ac[,0x06]:{lb:&"\n"=tf:"\n"/t;m:(#a:"\n"/aa:read`)(a~)':tf; c:2+sa[1]+lb@-1+*sa:*sord` /^F
 c:c-lb@l:lb'c:$[^n:*&c_m;*&m;c+n];foot::"found ",$+/m;sel::1 -1+l,c;(l+#aa;0|c+-1+#*|aa)}
bs:{$[~+/(l;c):cur;0 0; ~c;[a:(l-1;#t l-1);t[l-1],:t[l];t_:l;a];[t[l]_:c-1;l,c-1]]} /Back
ac[,0x08]:ac[,0x7f]:bs,del:{type@,""};ac[,0x07]:{dn(-1+.,/-1_(|/~"A0"'){1:`}\"0";0)} /^G
ac[CS,"3~"]:{(l;c):cur;:[cur~end`;; c=#t@l;[t[l],:t[l+1];t_:l+1]; t[l]_:c];cur},del /Del
ac[CS,"H"]:{(l;c):cur;l,x*~c=x:+/&\" "=t l};ac[CS,"F"]:{x desel/cur[0],#t cur 0} /Home End
ac[CS,"1;5H"]:{0 0}; ac[CS,"1;5F"]:end; ac[,0x1b]:{desel`;cur}           /^Home ^End Esc
ac[CS,"5~"]:{up x desel/scroll@-h};ac[CS,"6~"]:{dn x desel/scroll h}     /PgUp PgDn
ac[CS,"1;5A"]:{up x desel/scroll -1};ac[CS,"1;5B"]:{dn x desel/scroll 1} /^Up ^Down
wc:,/`c$"0A_a"+!'10 26 1 26; wd:{a 0 1+(a:&^wc?t@*cur)'x} / wc:word chars. v ^Left ^Right
ac[CS,"1;5C"]:{cur[0],(#t@*cur)^wd[cur 1]1}; ac[CS,"1;5D"]:{cur[0],1+-1^wd[-2+cur 1]0}
ac[,"\r"]:{type("";(&\" "=)#t@*cur)};ac[,0x18]:{clip::read`;$[x;del`;[t_:l:*cur;l,0]]} /^X
ac[,0x03]:{clip::read`;cur};ac[,0x16]:{type clip};ac[,0x01]:{sel::0 0;end`} /^C ^V ^A
sft/'CS,/:/:{("1;",/:/:"56",\:/:x),("56",/:\:" "\"~ ;2~"),+1("1;2",)'\x}"ABCDFH" /shift+..
{1}{disp`; foot::foot0; fcur::{(other x)^ac x}[1:`][~^*sel][]; cur::{[l;c] l,c&#t@l}.fcur
 scr::cur&scr|cur-(h;w)-2 5; (cur~sel)desel/` }/`
/
needs ngn/k awk stty. usage: ./txt.k filename(optional). xterm/compatible recommended.
simple. usable. extensible. pick all three. type to a line and press Ctrl+E:
  TX:CS,"30;47m";SE:CS,"97;40m" / light mode
  foot0:"\"just do it and have fun while doing it\" - HelloBoi" / add your favorite quote
  ac[,0x0a]:{."\\eject";cur} / adds a new command in ^J
\

entry #13

written by at
submitted at
1 like

guesses
comments 0

post a comment


Makefile ASCII text, with CRLF line terminators
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
CC?=clang

all:
	$(CC) -pedantic -Wall -g -o drill main.c

nr: all
	./drill
	
dbg: all
	gdb drill
main.c Unicode text, UTF-8 text, with CRLF line terminators
  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
// DRILL.
// WRITTEN BY OLUS2000.
// INSPIRED BY SAM. http://sam.cat-v.org/ 
// COMES WITH NO WARRANTY.
// WILL EAT YOUR CAT.
// HACK THE PLANET.
// YOU WANT TO USE IT? EDIT MAIN.
// COMES WITH LOVENSE INTEGRATION.
// BORN TO DIE.
// WORLD IS A FUCK.
// 鬼䘥 KILL EM ALL 1989.
// I AM TRASH MAN.
// 410,757,864,530 DEAD COPS.
// THE ONLY WINNING MOVE IS NOT TO PLAY.
// REST IN PEACE AUGUST 20, 2018.

// BUILD WITH `make`. RUN WITH `./drill`.
// IT'S NOTHING BUT PURE COCAINE AND C99.
// I LOVE YOU.

// HERE'S A FUCKING PHILOSOPHY FOR YOU: 
// https://12ft.io/proxy?q=https%3A%2F%2Fwww.theatlantic.com%2Fscience%2Farchive%2F2017%2F08%2Fannie-dillards-total-eclipse%2F536148%2F
// READ 'EM AND WEEP.

#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#define MAX(a,b) ((a) > (b) ? (a) : (b))
#define MIN(a,b) ((a) < (b) ? (a) : (b))

#define DEBUG
// Remove the below line for debug mode.
#undef DEBUG

/* ~~~~~~~~~~~ VM ~~~~~~~~~~~ */
// walk the bytecode now
// sweet machine, focus on the text
// iterate quickly.
typedef struct Span {
    char* start;
    char* end;
} Span;

typedef struct Foci {
    unsigned long cnt;         // how many foci exist
    unsigned long contiguousc; // size of the foci arena.
    Span* s;                   // the foci
} Foci;

void foci_init(Foci* uninitialized) {
    *uninitialized = (Foci){ .cnt = 0, .contiguousc = 0, .s = NULL };
}

void foci_free(Foci in) {
    free(in.s);
}

typedef enum BytecodeTag {
    BCT_SUBSTITUTE, // Replace the foci with a given string
    BCT_DRILL,      // Narrow the foci to a given regex (well, string)
    BCT_AROUND,     // Narrow the foci to their 0-length beginnings and ends
    BCT_STARTS,     // Narrow the foci to their 0-length beginnings
    BCT_ENDS,       // Narrow the foci to their 0-length ends
    BCT_COMPLEMENT  // Invert focus
} BytecodeTag;

typedef struct Bytecode {
    BytecodeTag* tag;
    char** data;
    unsigned int cnt;         // count of elements in tags and data
    unsigned int contiguousc; // size of allocated arenas for tags and data
} Bytecode;

#define _print_bytecode_branch(idx, name) case name:\
    printf("%ld " #name, ip);\
    break;

void print_single_bytecode(Bytecode in, unsigned long ip) {
    switch (in.tag[ip]) {
        _print_bytecode_branch(ip, BCT_SUBSTITUTE)
        _print_bytecode_branch(ip, BCT_DRILL)
        _print_bytecode_branch(ip, BCT_AROUND)
        _print_bytecode_branch(ip, BCT_STARTS)
        _print_bytecode_branch(ip, BCT_ENDS)
        _print_bytecode_branch(ip, BCT_COMPLEMENT)
    }
    if (in.data[ip] == NULL) {
        printf(" (no data)\n");
    } else {
        printf(" \"%s\"\n", in.data[ip]);
    }
}

void print_bytecode(Bytecode in) {
    for (unsigned int i = 0; i < in.cnt; i++) {
        print_single_bytecode(in, i);
    }
}

void bytecode_recursive_free(Bytecode* bc) {
    for (unsigned int i = 0; i < bc->cnt; i++) {
        free(bc->data[i]);
    }
    free(bc->tag);
    free(bc);
}

void bytecode_init(Bytecode* uninitialized) { 
    *uninitialized = (Bytecode){ .tag = NULL, .data = NULL, .cnt = 0, .contiguousc = 0 };
}

// Reallocs the bytecode if it overflows with `newelems` entries added
void bytecode_realloc(Bytecode* in, unsigned int newelems) {
    while ((in->cnt + newelems) * sizeof(void*) > in->contiguousc) {
        in->contiguousc = (in->contiguousc + 1) * 2;
        in->tag = realloc(in->tag, in->contiguousc);
        in->data = realloc(in->data, in->contiguousc);
    }
}

// void* data should live until the deallocation of the bytecode
void bytecode_append(Bytecode* in, BytecodeTag tag, char* data) {
    bytecode_realloc(in, 1);
    in->tag[in->cnt] = tag;
    in->data[in->cnt] = data;
    in->cnt++;
}

void bytecode_concat(Bytecode* in, Bytecode other) {
    // realloc to get more space if we've run out
    bytecode_realloc(in, other.cnt);
    for (unsigned int i = 0; i < other.cnt; i++) {
        in->tag[in->cnt + i] = other.tag[i];
        in->data[in->cnt + i] = other.data[i];
    }
    in->cnt += other.cnt;
}


// once all appending actions have been done, make sure
// to call foci_merge_overlapping to deduplicate spans
void foci_append(Foci* foci, char* start, char* end) {    
    if (foci->contiguousc <= (foci->cnt + 1) * sizeof(Span)) {
        foci->contiguousc = (foci->cnt + 1) * sizeof(Span) * 2;
        foci->s = realloc(foci->s, foci->contiguousc);
    }
    foci->s[foci->cnt].start = start;
    foci->s[foci->cnt].end = end;
    foci->cnt++;
}

char* foci_min_start(Foci foci) {
    char* min_start = foci.s[0].start;
    for (unsigned long i = 1; i < foci.cnt; i++) {
        if (foci.s[i].start < min_start) {
            min_start = foci.s[i].start;
        }
    }
    return min_start;
}

char* foci_max_end(Foci foci) {
    char* max_end = foci.s[0].end;
    for (unsigned long i = 1; i < foci.cnt; i++) {
        if (foci.s[i].end > max_end) {
            max_end = foci.s[i].end;
        }
    }
    return max_end;
}

// returns the index of the first span focusing on the ptr, or -1.
long foci_check(Foci in, char* ptr) {
    for (unsigned long i = 0; i < in.cnt; i++) {
        Span tester = in.s[i];
        if (ptr >= tester.start && ptr < tester.end) {
            return i;
        }
    }
    return -1;
}

// this creates a distinct copy, it's safe to call foci_free on the input afterwards
// TODO: support distinct foci bordering each other... iterate and check if we're in two spans?
// TODO: this breaks 0 length spans
// TODO: can some sweet, silly code guesser fix this function for me? thx...
Foci foci_merge_overlapping(Foci in) {
    Foci out;
    foci_init(&out);
    if (in.cnt == 0) {
        return out;
    }
    char* min_start = foci_min_start(in);
    char* max_end = foci_max_end(in);
    foci_append(&out, min_start, min_start+1);
    char scanning = 1;
    for (char* ptr = min_start; ptr < max_end; ptr++) {
        if (foci_check(in, ptr) >= 0) {
            if (scanning) {
                out.s[out.cnt - 1].end = ptr+1;
            } else {
                foci_append(&out, ptr, ptr+1);
                scanning = 1;
            }
        } else {
            if (scanning) {
                scanning = 0;
            }
        }
    }
    return out;
}

void print_span(Span s) {
    printf("\"%.*s\"\n", (int)(s.end - s.start), s.start);
}

void print_foci(Foci f) {
    printf("Foci cnt: %ld\n", f.cnt);
    for (unsigned long i = 0; i < f.cnt; i++) {
        printf("%ld ", i);
        print_span(f.s[i]);
    }
}

// the core of the brain
// oh! watch the pointer move right
// implementing logic
typedef struct VM {            // Execution model
    unsigned long ip;          // current execution offset into Bytecode tag+data
    Bytecode bc;               // the bytecode we're executing
    char* text;                // the text to mutate
    Foci foci;                 // what text is currently focused?
} VM;

void vm_init(VM* uninitialized, char* in, Bytecode bc) {
    Foci foci;
    foci_init(&foci);
    // VMs start with everything focused
    foci_append(&foci, in, strchr(in, '\0'));
    *uninitialized = (VM){ .ip = 0, .bc = bc, .text = in, .foci = foci };
}

void vm_merge_overlapping_foci(VM* vm) {
    Foci old_foci = vm->foci;
    vm->foci = foci_merge_overlapping(vm->foci);
    foci_free(old_foci);
}

// expects vm->ip to be pointing to a BCT_DRILL tag and a regex in data
// drill drill drill drill drill
// drill drill drill drill drill drill drill
// drill drill drill drill drill
void vm_run_drill(VM* vm) {
    char* regex = vm->bc.data[vm->ip];
    unsigned long match_length = strlen(regex);
    Foci new_foci;
    foci_init(&new_foci);
    for (unsigned long i = 0; i < vm->foci.cnt; i++) {
        Span focus = vm->foci.s[i];
        unsigned long focus_length = focus.end - focus.start;
        char* haystack = focus.start;
        while (*haystack != '\0') {
            #ifdef DEBUG
            printf("calling strncmp with %s, %s, %ld, got %d\n", haystack, regex, match_length, strncmp(haystack, regex, match_length));
            #endif
            if (strncmp(haystack, regex, MIN(match_length, focus_length)) == 0) { // TODO: regex
                foci_append(&new_foci, haystack, haystack + match_length);
            } 
            haystack++;
        }
    }
    foci_free(vm->foci);
    vm->foci = new_foci;
}

// expects vm->ip to be pointing to a BCT_SUBSTITUTE tag and the sub string in data
void vm_run_substitute(VM* vm) {
    char* subby = vm->bc.data[vm->ip];
    // calculate length of string post-substitution
    unsigned long foci_length = 0;
    for (unsigned long i = 0; i < vm->foci.cnt; i++) {
        foci_length += vm->foci.s[i].end - vm->foci.s[i].end;
    }
    char* new_text = calloc(strlen(vm->text) - foci_length + strlen(subby) * vm->foci.cnt, sizeof(char));
    // copy focus structure
    Foci new_foci;
    foci_init(&new_foci);
    for (unsigned int i = 0; i < vm->foci.cnt; i++) {
        char* new_start = new_text + (vm->foci.s[i].start - vm->text);
        char* new_end = new_text + (vm->foci.s[i].end - vm->text);
        foci_append(&new_foci, new_start, new_end);
    }
    // build new_text from successive concatenations
    char* done = vm->text;
    unsigned long i = 0;
    for (; i < vm->foci.cnt; i++) {
        Span focus = vm->foci.s[i];
        strncat(new_text, done, focus.start - done);
        strcat(new_text, subby);
        done = focus.end;
        // adjust foci affected by this substitution, including pointing them to new_text
        unsigned long text_length_change = strlen(subby) - (focus.end - focus.start);
        new_foci.s[i].end += text_length_change;
        for (unsigned long j = i+1; j < vm->foci.cnt; j++) {
            new_foci.s[j].start += text_length_change;
            new_foci.s[j].end += text_length_change;
        }
    }
    strcat(new_text, done);
    free(vm->text);
    vm->text = new_text;
    foci_free(vm->foci);
    vm->foci = new_foci;
}

// expects vm->ip to be pointing to a BCT_AROUND tag
void vm_run_around(VM* vm) {    
    Foci new_foci;
    foci_init(&new_foci);
    for (unsigned long i = 0; i < vm->foci.cnt; i++) {
        Span focus = vm->foci.s[i];
        foci_append(&new_foci, focus.start, focus.start);
        foci_append(&new_foci, focus.end, focus.end);
    }
    foci_free(vm->foci);
    vm->foci = new_foci;
}

// expects vm->ip to be pointing to a BCT_STARTS tag
void vm_run_starts(VM* vm) {    
    Foci new_foci;
    foci_init(&new_foci);
    for (unsigned long i = 0; i < vm->foci.cnt; i++) {
        Span focus = vm->foci.s[i];
        foci_append(&new_foci, focus.start, focus.start);
    }
    foci_free(vm->foci);
    vm->foci = new_foci;
}

// expects vm->ip to be pointing to a BCT_ENDS tag
void vm_run_ends(VM* vm) {    
    Foci new_foci;
    foci_init(&new_foci);
    for (unsigned long i = 0; i < vm->foci.cnt; i++) {
        Span focus = vm->foci.s[i];
        foci_append(&new_foci, focus.end, focus.end);
    }
    foci_free(vm->foci);
    vm->foci = new_foci;
}

// expects vm->ip to be pointing to a BCT_COMPLEMENT tag
void vm_run_complement(VM* vm) {    
    Foci new_foci;
    foci_init(&new_foci);
    char* done = vm->text;
    for (unsigned long i = 0; i < vm->foci.cnt; i++) {
        Span focus = vm->foci.s[i];
        foci_append(&new_foci, done, focus.start);
        done = focus.end;
    }
    foci_append(&new_foci, done, strchr(vm->text, '\0')); 
    foci_free(vm->foci);
    vm->foci = new_foci;
}


void print_vm(VM vm) {
    printf("Text: %s\n", vm.text);
    printf("Bytecode:\n");
    print_bytecode(vm.bc);
    printf("IP: %ld\n", vm.ip);
    printf("Foci:\n");
    print_foci(vm.foci);
    puts("");
    puts("");
}

// returns pointer to mutated text on success, NULL on error
char* vm_run(VM vm) {
    #ifdef DEBUG
    printf("Initial state:\n");
    print_vm(vm);
    #endif
    for (; vm.ip < vm.bc.cnt; vm.ip++) {
        switch (vm.bc.tag[vm.ip]) {
            case BCT_DRILL:
                vm_run_drill(&vm);
                // TODO: figure out if merging overlapping foci is needed here
                // TODO: can test with a drill like /ss/ and a string like "sss"
                // vm_merge_overlapping_foci(&vm);
                break;
            case BCT_SUBSTITUTE:
                vm_run_substitute(&vm);
                break;
            case BCT_AROUND:
                vm_run_around(&vm);
                break;
            case BCT_STARTS:
                vm_run_starts(&vm);
                break;
            case BCT_ENDS:
                vm_run_ends(&vm);
                break;
            case BCT_COMPLEMENT:
                vm_run_complement(&vm);
                break;
            default:
                printf("Got unimplemented bytecode ");
                print_single_bytecode(vm.bc, vm.ip);
        }
        #ifdef DEBUG
        print_vm(vm);
        #endif
    }
    return vm.text;
}



/* ~~~~~~~~~~~ Parser ~~~~~~~~~~~ */
// let her speak! a voice
// feminine, or masculine,
// booming from heaven
#define PAD_SIZE 1024
typedef struct ParseState {
    Bytecode out; // Did this parser produce output? "No" represented by a zero-length Bytecode
    char* altout; // Some parsers produce strings instead
    char* rest; // The rest of the input stream
} ParseState;

void parsestate_init(ParseState* uninitialized, char* unparsed) {
    Bytecode bc;
    bytecode_init(&bc);
    *uninitialized = (ParseState){ .out = bc, .altout = NULL, .rest = unparsed };
}

void parsestate_free(ParseState ps) {
    free(ps.altout);
}

void die(const char* fmt,...) {
    va_list args;
    va_start(args, fmt);
    vprintf(fmt, args);
    va_end(args);
    exit(1);
}

void consume_subparse(ParseState* p, ParseState subparse) {
    if (subparse.out.cnt > 0) {
        bytecode_concat(&p->out, subparse.out);
    }
    p->rest = subparse.rest;
}

// parses regexp/, so like a regexp missing the leading slash & ending on a slash, places it in altout
ParseState parse_regexp(char* in) {
    ParseState o = { .altout = "", .rest = in };
    char pad[PAD_SIZE] = "";
    unsigned int padc = 0;
    while (padc < PAD_SIZE) {
        char c = *o.rest;
        switch (c) {
            case '\0':
                die("EOF while parsing regexp");
                break;
            case '/':
                goto done;
            default:
                pad[padc++] = *o.rest;
                pad[padc] = '\0';
                o.rest++;
        }
    } done:
    o.altout = strdup(pad);
    return o;
}

// parses quote", so like a string missing the leading quote & ending on a quote, places it in altout
ParseState parse_quote(char* in) {
    ParseState o = { .altout = "", .rest = in };
    char pad[PAD_SIZE] = "";
    unsigned int padc = 0;
    while (padc < PAD_SIZE) {
        char c = *o.rest;
        switch (c) {
            case '\0':
                die("EOF while parsing quote");
                break;
            case '"':
                goto done;
            default:
                pad[padc++] = *o.rest;
                pad[padc] = '\0';
                o.rest++;
        }
    } done:
    o.altout = strdup(pad);
    return o;
}

// parses s/regexp/
ParseState parse_substitute(char* in) {
    ParseState o;
    parsestate_init(&o, in);
    if (*(o.rest++) != 's') {
        die("Expected s at start of substitution");
    }
    if (*(o.rest++) != '/') {
        die("Expected s/ at start of substitution");
    }
    ParseState sub = parse_regexp(o.rest);
    consume_subparse(&o, sub);
    bytecode_append(&o.out, BCT_SUBSTITUTE, strdup(sub.altout));
    parsestate_free(sub);
    if (*(o.rest++) != '/') {
        die("Expected / at the end of substitution");
    }
    return o;
}

// parses /regexp/
ParseState parse_drill(char* in) {
    ParseState o;
    parsestate_init(&o, in);
    if (*(o.rest++) != '/') {
        die("Expected / at start of drill");
    }
    ParseState sub = parse_regexp(o.rest);
    consume_subparse(&o, sub);
    bytecode_append(&o.out, BCT_DRILL, strdup(sub.altout));
    parsestate_free(sub);
    if (*(o.rest++)!= '/') {
        die("Expected / at end of drill");
    }

    return o;
}


ParseState parse_root(char* in) {
    ParseState o;
    parsestate_init(&o, in);
    while (1) {
        char c = *o.rest;
        ParseState sub;
        switch (c) {
            case '\0':
                goto done;
            case 's':
                sub = parse_substitute(o.rest);
                consume_subparse(&o, sub);
                parsestate_free(sub);
                break;
            case '/':
                sub = parse_drill(o.rest);
                consume_subparse(&o, sub);
                parsestate_free(sub);
                break;
            case '^':
                o.rest++;
                bytecode_append(&o.out, BCT_STARTS, NULL);
                break;
            case '$':
                o.rest++;
                bytecode_append(&o.out, BCT_ENDS, NULL);
                break;
            // Philomena Cunk wuz here
            case '%':
                o.rest++;
                bytecode_append(&o.out, BCT_AROUND, NULL);
                break;
            case '@':
                o.rest++;
                bytecode_append(&o.out, BCT_COMPLEMENT, NULL);
                break;
            case ' ':
            case '\t':
            case '\n':
                o.rest++;
                break;
            default:
                die("Unexpected %c in root parser", c);
                break;
        }
    } done:
    return o;
}

Bytecode parse(char* in) {
    return parse_root(in).out;
}

// requires a heap-allocated text
char* run(char* progstr, char* text) {
    Bytecode prog = parse(progstr);
    #ifdef DEBUG
    print_bytecode(prog);
    puts("");
    #endif
    VM vm;
    vm_init(&vm, text, prog);
    return vm_run(vm);
}

// woag
int main(int argc, char** argv) {
    printf("%s\n", run("/hello,/ s// s/I'm ready to conquer the/", strdup("hello, world!")));
    printf("%s\n", run("^ s/This text is at the start /", strdup("hello, world!")));
    printf("%s\n", run("$ s/ This text is at the end/", strdup("hello, world!")));
    printf("%s\n", run("% s/ This text is at the start and the end /", strdup("hello, world!")));
    printf("%s\n", run("/l/ % s/ol/", strdup("hello, world!")));
    printf("%s\n", run("/,/ @ s/lol/", strdup("hello,,,  world! i love to sing, dance, and play video games!")));
    return 0;
}

// two men walk abreast
// into the dark night sky ablaze with
// ten thousand dying stars