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
|
#include "../command.h"
#include "../util//regex.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define INPUT_LEN 1024
static char** lines = NULL;
static unsigned long line_capacity;
static unsigned long line_count;
static unsigned long line_current;
static bool pending_writes;
static char* default_filename = NULL;
static re_t last_regex = NULL;
enum LineAddressType {
INDEX,
RANGE,
SET,
FREE
};
struct LineAddress {
enum LineAddressType type;
union {
struct {
long int i;
} index;
struct {
long int a;
long int b;
} range;
struct {
long int* b;
unsigned long c;
unsigned long s;
} set;
} data;
bool empty;
};
enum RegexDirection {
BEFORE,
AFTER,
ALL
};
static bool parse_regex(char** end, struct LineAddress* address, enum RegexDirection dir) {
char c;
char* index = *end;
char* regex_str = index;
while(true) {
c = *(index++);
if (c == '\0') {
fprintf(stderr, "error: missing regex after %c\n", dir == BEFORE ? '?' : '/');
return false;
}
if (c == (dir == BEFORE ? '?' : '/')) {
*(index - 1) = '\0';
break;
}
}
unsigned long cap = 8;
unsigned long siz = 0;
long int* buf = malloc(cap * sizeof(unsigned long));
re_t regex = re_compile(regex_str);
last_regex = regex;
unsigned long i = (dir == ALL ? 0 : line_current);
unsigned long until = (dir == BEFORE ? 0 : line_count - 1);
for (; (dir == BEFORE ? i >= until : i < until); dir == BEFORE ? i-- : i++) {
int len;
if (re_matchp(regex, lines[i], &len) == -1) {
if (dir == BEFORE && i == 0) break;
continue;
}
if (cap == siz) {
cap *= 2;
buf = realloc(buf, cap * sizeof(unsigned long));
}
buf[siz] = i;
siz++;
if (dir == BEFORE && i == 0) break;
}
address->empty = false;
address->type = SET;
address->data.set.s = siz;
address->data.set.c = cap;
address->data.set.b = buf;
*end = index;
return true;
}
static bool read_address(char** command, bool whitespace, struct LineAddress* a) {
char* index = *command;
struct LineAddress address;
memset(&address, 0, sizeof(struct LineAddress));
address.empty = false;
if (strlen(*command) < 1) {
address.type = INDEX;
address.data.index.i = line_current + 1;
if (line_current >= line_count) line_current = line_count - 1;
*a = address;
return true;
}
char* end_pre;
long int n_pre = strtol(index, &end_pre, 10) - 1;
if (end_pre == index) {
n_pre = -1;
} else {
if (n_pre < 0) {
fprintf(stderr, "error: input cannot be negative\n");
return false;
}
index = end_pre;
}
char pre = *(index++);
switch (pre) {
case '.':
address.type = INDEX;
address.data.index.i = line_current;
break;
case '$':
address.type = INDEX;
address.data.index.i = line_count - 1;
break;
case '-':
case '^': {
address.type = INDEX;
char* end;
long int n = strtol(index, &end, 10) - 1;
if (n < 0) {
fprintf(stderr, "error: input cannot be negative\n");
return false;
}
if (index == end) {
address.data.index.i = line_current - 1;
} else {
address.data.index.i = line_current - n;
}
if (address.data.index.i < 0) {
fprintf(stderr, "error: line number %ld does not exist\n", address.data.index.i + 1);
return false;
}
break;
}
case '+': {
address.type = INDEX;
char* end;
long int n = strtol(index, &end, 10) - 1;
if (n < 0) {
fprintf(stderr, "error: input cannot be negative\n");
return false;
}
if (index == end) {
address.data.index.i = line_current + 1;
} else {
address.data.index.i = line_current + n;
}
if (address.data.index.i >= (long int) line_count) {
fprintf(stderr, "error: line number %ld does not exist\n", address.data.index.i + 1);
return false;
}
break;
}
case '%':
address.type = RANGE;
address.data.range.a = 0;
address.data.range.b = line_count - 1;
break;
case ';':
address.type = RANGE;
address.data.range.a = line_current;
address.data.range.b = line_count - 1;
break;
case '/':
if (!parse_regex(&index, &address, AFTER)) return false;
break;
case '?':
if (!parse_regex(&index, &address, BEFORE)) return false;
break;
default: {
index--;
if (n_pre == -1) {
address.type = INDEX;
address.data.index.i = line_current;
address.empty = true;
break;
} else if (whitespace) {
address.type = INDEX;
address.data.index.i = line_current + n_pre;
} else {
address.type = INDEX;
address.data.index.i = n_pre;
}
if (address.data.index.i < 0 || address.data.index.i >= (long int) line_count) {
fprintf(stderr, "error: line number %ld does not exist\n", address.data.index.i + 1);
return false;
}
}
}
*command = index;
*a = address;
return true;
}
static void free_address (struct LineAddress address) {
if (address.type != SET) return;
address.type = FREE;
free(address.data.set.b);
}
static void free_data(bool all) {
if (lines != NULL) {
for (unsigned long i = 0; i < line_count; i++) {
free(lines[i]);
}
free(lines);
lines = NULL;
}
if (all && default_filename != NULL) {
free(default_filename);
default_filename = NULL;
}
}
static void load_empty() {
free_data(false);
line_capacity = 8;
lines = malloc(sizeof(char*) * line_capacity);
line_count = 0;
line_current = 0;
pending_writes = false;
}
static void get_input(FILE* file, char*** buffer, unsigned long* capacity, unsigned long* size) {
unsigned long cap = 8;
unsigned long siz = 0;
char** buf = malloc(sizeof(char*) * cap);
char* line = NULL;
size_t offset = 0;
clearerr(stdin);
while (getline(&line, &offset, file) != -1) {
if (cap == siz) {
cap *= 2;
buf = realloc(buf, sizeof(char*) * cap);
}
buf[siz] = line;
siz++;
line = NULL;
}
free(line);
*buffer = buf;
*capacity = cap;
*size = siz;
}
int ed_getline(char *buf, size_t size) {
size_t i = 0;
int ch;
clearerr(stdin);
while ((ch = getchar()) != EOF) { // Read until EOF ...
if (i + 1 < size) {
buf[i++] = ch;
}
if (ch == '\n') { // ... or end of line
break;
}
}
buf[i] = '\0';
if (i == 0) {
return EOF;
}
return i;
}
static void load_file(FILE* file) {
free_data(false);
line_current = 0;
get_input(file, &lines, &line_capacity, &line_count);
if (file != stdin)
fclose(file);
}
static bool check_if_sure(char* prompt) {
if (!pending_writes) {
return true;
}
printf("%s", prompt);
fflush(stdout);
char buf[INPUT_LEN];
if (ed_getline(buf, INPUT_LEN) == EOF) {
putchar('\n');
return false;
}
return prefix("y", buf);
}
static bool skip_whitespace(char** index) {
char c;
bool w = false;
while (c = **index, c == ' ' || c == '\t') { (*index)++; w = true; }
return w;
}
static void expand(unsigned long count) {
if (count < line_capacity) return;
line_capacity *= 2;
if (count > line_capacity) line_capacity = count;
lines = realloc(lines, line_capacity * sizeof(char*));
}
static void append_lines(unsigned long index, char** new, unsigned long new_len) {
if (new_len < 1) return;
pending_writes = true;
expand(line_count + new_len);
if (index + 1 <= line_count)
memmove(&lines[index+new_len], &lines[index], sizeof(char*) * (line_count - index));
memcpy(&lines[index], new, sizeof(char*) * new_len);
line_count += new_len;
}
static void delete_lines(unsigned long a, unsigned long b) {
if (b < a) return;
pending_writes = true;
for (unsigned long i = a; i <= b; i++) {
free(lines[i]);
}
if (b == line_count - 1) {
line_count = a;
return;
}
memmove(&lines[a], &lines[b+1], sizeof(char*) * (line_count - (b + 1)));
line_count -= (b - a) + 1;
line_current = a;
if (line_current >= line_count) line_current = line_count - 1;
}
static bool handle_append(struct LineAddress* address) {
if (address->type != INDEX) {
fprintf(stderr, "error: append command requires index addressing\n");
return false;
}
if (line_count == 0) {
address->data.index.i = -1;
}
char** buf;
unsigned long cap, size;
get_input(stdin, &buf, &cap, &size);
if (size > 0) {
append_lines(address->data.index.i + 1, buf, size);
printf("ed: appened %lu lines\n", size);
}
line_current += size;
free(buf);
return true;
}
static bool handle_delete(struct LineAddress* address) {
if (address->empty && address->data.index.i >= (long int) line_count) {
fprintf(stderr, "error: line number %ld does not exist\n", address->data.index.i + 1);
return false;
}
if (address->type == INDEX) {
delete_lines(address->data.index.i, address->data.index.i);
printf("ed: deleted line %ld\n", address->data.index.i+1);
} else if (address->type == RANGE) {
delete_lines(address->data.range.a, address->data.range.b);
printf("ed: deleted lines %ld-%ld\n", address->data.range.a+1, address->data.range.b+1);
} else if (address->type == SET) {
for (unsigned long i = 0; i < address->data.set.s; i++) {
delete_lines(address->data.set.b[i], address->data.set.b[i]);
}
printf("ed: deleted %lu lines\n", address->data.set.s);
}
return true;
}
static bool get_file_name(char** filename) {
size_t len = strlen(*filename);
if (len < 1 || (len == 1 && **filename == '\n')) {
if (default_filename == NULL) {
fprintf(stderr, "error: no default filename specified\n");
return false;
}
*filename = default_filename;
} else {
if ((*filename)[len - 1] == '\n') {
(*filename)[len - 1] = '\0';
len--;
}
if (default_filename != NULL) {
default_filename = realloc(default_filename, len + 1);
} else {
default_filename = malloc(len + 1);
}
memcpy(default_filename, *filename, len + 1);
*filename = default_filename;
}
return true;
}
static void write_file(char* filename, struct LineAddress* address, char* type) {
if (line_count < 1) {
fprintf(stderr, "error: cannot write empty file\n");
return;
}
if (!get_file_name(&filename)) return;
FILE* file = get_file_s(filename, type);
if (file == NULL) return;
int wrote = 0;
if (address->empty) {
for (unsigned long i = 0; i < line_count; i++) {
fprintf(file, "%s", lines[i]);
wrote++;
}
} else if (address->type == INDEX) {
long int i = address->data.index.i;
fprintf(file, "%s", lines[i]);
wrote++;
} else if (address->type == RANGE) {
for (long int i = address->data.range.a; i < address->data.range.b; i++) {
fprintf(file, "%s", lines[i]);
wrote++;
}
} else if (address->type == SET) {
for (unsigned long i = 0; i < address->data.set.s; i++) {
fprintf(file, "%s", lines[address->data.set.b[i]]);
wrote++;
}
}
pending_writes = false;
fclose(file);
printf("ed: wrote %d lines from %s\n", wrote, filename);
}
static void read_file(char* filename) {
if (!get_file_name(&filename)) return;
FILE* file = get_file_s(filename, "r");
if (file == NULL) return;
unsigned long capacty = 8;
unsigned long size = 0;
char** buf = malloc(capacty * sizeof(char*));
get_input(file, &buf, &capacty, &size);
if (size < 1) {
free(buf);
fprintf(stderr, "error: attempted to read a empty file\n");
return;
}
long int line = -1;
if (line_count > 0) {
line = line_count - 1;
}
append_lines(line, buf, size);
free(buf);
printf("ed: read and appended %lu lines from %s\n", size, filename);
}
static void expand_string(char** buf, int* capacity, int* size, char* text, int len) {
if (*size + len >= *capacity) {
*capacity *= 2;
if (*capacity < *size + len) *capacity = *size + len;
*buf = realloc(*buf, *capacity);
}
memcpy(*buf + *size, text, len);
*size += len;
}
static int substute_string(long int index, long int matches, re_t regex, char* sub, int sub_len) {
int capacity = 8;
int size = 0;
char* buf = malloc(sizeof(char) * capacity);
int offset = 0;
int matches_found = 0;
while(true) {
if (lines[index][offset] == '\0') break;
if (matches_found >= matches && matches > 0) break;
int distance, len;
if ((distance = re_matchp(regex, &lines[index][offset], &len)) == -1) {
break;
}
if (distance > 0)
expand_string(&buf, &capacity, &size, &lines[index][offset], distance);
expand_string(&buf, &capacity, &size, sub, sub_len);
offset += len + distance;
matches_found++;
}
long int left = strlen(lines[index] + offset);
expand_string(&buf, &capacity, &size, &lines[index][offset], left + 1);
free(lines[index]);
lines[index] = buf;
return matches_found;
}
static void prompt() {
printf(": ");
fflush(stdout);
char buf[INPUT_LEN];
if (ed_getline(buf, INPUT_LEN) == EOF) { putchar('\n'); return; }
if (buf[0] == '\0') { putchar('\n'); return; }
char* index = &buf[0];
bool whitespace = skip_whitespace(&index);
struct LineAddress address;
if (!read_address(&index, whitespace, &address)) return;
char cmd = *(index++);
if (cmd == ',') {
if (address.type != INDEX) {
fprintf(stderr, "error: comma range addressing requires two index addresses\n");
free_address(address);
return;
}
struct LineAddress address2;
whitespace = skip_whitespace(&index);
if (!read_address(&index, whitespace, &address2)) {
free_address(address);
return;
}
if (address2.type != INDEX) {
fprintf(stderr, "error: comma range addressing requires two index addresses\n");
free_address(address);
free_address(address2);
return;
}
address.type = RANGE;
address.data.range.a = address.data.index.i; // cursed
address.data.range.b = address2.data.index.i;
cmd = *(index++);
}
if (address.type == RANGE && address.data.range.a > address.data.range.b) {
fprintf(stderr, "error: range addressing must be in ascending order\n");
free_address(address);
return;
}
bool linenumbers = false;
test:
switch (cmd) {
case '\0':
case '\n':
if (address.empty) {
if (line_current == line_count) {
fprintf(stderr, "error: line number %ld does not exist\n", line_current + 1);
break;
} else if (line_current + 1 == line_count) {
fprintf(stderr, "error: line number %ld does not exist\n", line_current + 2);
break;
} else {
line_current++;
}
printf("%s", lines[line_current]);
break;
}
if (address.type == INDEX) {
line_current = address.data.index.i;
} else if (address.type == RANGE) {
line_current = address.data.range.b;
} else if (address.type == SET) {
fprintf(stderr, "error: unexpected range addressing\n");
break;
}
printf("%s", lines[line_current]);
break;
case 'a':
handle_append(&address);
break;
case 'd':
handle_delete(&address);
break;
case 'c':
if (!handle_delete(&address)) { break; }
address.type = INDEX;
address.data.index.i = line_current - 1;
handle_append(&address);
break;
case 'n':
linenumbers = true;
__attribute__((fallthrough));
case 'p':
if (address.empty && address.data.index.i >= (long int) line_count) {
fprintf(stderr, "error: line number %ld does not exist\n", address.data.index.i + 1);
break;
}
if (address.type == INDEX) {
if (linenumbers) printf("%ld\t", address.data.index.i + 1);
printf("%s", lines[address.data.index.i]);
} else if (address.type == RANGE) {
for (long int i = address.data.range.a; i <= address.data.range.b; i++) {
if (linenumbers) printf("%ld\t", i + 1);
printf("%s", lines[i]);
}
} else if (address.type == SET) {
for (unsigned long i = 0; i < address.data.set.s; i++) {
if (linenumbers) printf("%ld\t", i +1);
printf("%s", lines[address.data.set.b[i]]);
}
}
break;
case 'q':
if (!check_if_sure("Quit for sure? ")) break;
__attribute__((fallthrough));
case 'Q':
free_address(address);
free_data(true);
exit(EXIT_SUCCESS);
break;
case 'g':
skip_whitespace(&index);
free_address(address);
if (*(index++) != '/') {
fprintf(stderr, "error: unexpected character at start of regex\n");
break;
}
if (!parse_regex(&index, &address, ALL)) { return; }
skip_whitespace(&index);
if (*index == '\n' || *index == '\0') {
cmd = 'p';
} else {
cmd = *(index++);
}
goto test;
break;
case 's':
skip_whitespace(&index);
free_address(address);
if (*(index++) != '/') {
fprintf(stderr, "error: unexpected character at start of regex\n");
break;
}
if (!parse_regex(&index, &address, ALL)) { return; }
char* replace = index;
while(*index != '\0' && *index != '/') index++;
if (*index != '/') {
fprintf(stderr, "error: / missing after %c\n", *index);
break;
}
if (address.data.set.s < 1) {
printf("ed: no matches found\n");
break;
}
*(index++) = '\0';
long int matches;
if (*index == '\0') {
matches = 1;
} else if (*index == 'g') {
matches = -1;
} else {
char* end;
matches = strtol(index, &end, 10);
if (end == index) {
fprintf(stderr, "error: invalid number: %s\n", index);
break;
}
}
long int sub_len = strlen(replace);
long int matches_found = 0;
for (unsigned long i = 0; i < address.data.set.s; i++) {
matches_found += substute_string(address.data.set.b[i], matches, last_regex, replace, sub_len);
}
printf("ed: replaced %ld matches over %ld lines\n", matches_found, address.data.set.s);
pending_writes = true;
break;
case 'w': {
bool quit = false;
if (*index == 'q') {
index++;
quit = true;
}
skip_whitespace(&index);
write_file(index, &address, "w");
if (quit) {
free_address(address);
free_data(true);
exit(EXIT_SUCCESS);
}
break;
}
case 'r': {
skip_whitespace(&index);
read_file(index);
break;
}
case 'e':
if (!check_if_sure("Load new file for sure? ")) break;
__attribute__((fallthrough));
case 'E': {
skip_whitespace(&index);
char* filename = index;
if(!get_file_name(&filename)) break;
FILE* file = get_file_s(filename, "r");
if (file == NULL) break;
load_file(file);
break;
}
case 'W':
skip_whitespace(&index);
write_file(index, &address, "a");
break;
case '=':
printf("%ld\n", line_current + 1);
break;
default:
fprintf(stderr, "error: unimplemented command\n");
break;
}
free_address(address);
}
static void prompt_loop() {
while (true) {
prompt();
}
}
COMMAND(ed) {
if (argc < 1) {
load_empty();
prompt_loop();
} else {
FILE* file = get_file(argv[0], "r");
load_file(file);
get_file_name(&argv[0]);
prompt_loop();
}
return EXIT_SUCCESS;
}
|