forked from martanne/vis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sam.c
1604 lines (1453 loc) · 46.3 KB
/
sam.c
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
/*
* Heavily inspired (and partially based upon) the X11 version of
* Rob Pike's sam text editor originally written for Plan 9.
*
* Copyright © 2016-2017 Marc André Tanner <mat at brain-dump.org>
* Copyright © 1998 by Lucent Technologies
*
* Permission to use, copy, modify, and distribute this software for any
* purpose without fee is hereby granted, provided that this entire notice
* is included in all copies of any software which is or includes a copy
* or modification of this software and in all copies of the supporting
* documentation for such software.
*
* THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTY. IN PARTICULAR, NEITHER THE AUTHORS NOR LUCENT TECHNOLOGIES MAKE ANY
* REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
* OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
*/
#include <string.h>
#include <strings.h>
#include <stdio.h>
#include <ctype.h>
#include <errno.h>
#include <unistd.h>
#include <limits.h>
#include "sam.h"
#include "vis-core.h"
#include "buffer.h"
#include "text.h"
#include "text-motions.h"
#include "text-objects.h"
#include "text-regex.h"
#include "util.h"
#define MAX_ARGV 8
typedef struct Address Address;
typedef struct Command Command;
typedef struct CommandDef CommandDef;
struct Change {
enum ChangeType {
TRANSCRIPT_INSERT = 1 << 0,
TRANSCRIPT_DELETE = 1 << 1,
TRANSCRIPT_CHANGE = TRANSCRIPT_INSERT|TRANSCRIPT_DELETE,
} type;
Win *win; /* window in which changed file is being displayed */
Cursor *cursor; /* cursor associated with this change, might be NULL */
Filerange range; /* inserts are denoted by zero sized range (same start/end) */
const char *data; /* will be free(3)-ed after transcript has been processed */
size_t len; /* size in bytes of the chunk pointed to by data */
Change *next; /* modification position increase monotonically */
};
struct Address {
char type; /* # (char) l (line) g (goto line) / ? . $ + - , ; % ' */
Regex *regex; /* NULL denotes default for x, y, X, and Y commands */
size_t number; /* line or character number */
Address *left; /* left hand side of a compound address , ; */
Address *right; /* either right hand side of a compound address or next address */
};
struct Command {
const char *argv[MAX_ARGV];/* [0]=cmd-name, [1..MAX_ARGV-2]=arguments, last element always NULL */
Address *address; /* range of text for command */
Regex *regex; /* regex to match, used by x, y, g, v, X, Y */
const CommandDef *cmddef; /* which command is this? */
int count; /* command count if any */
char flags; /* command specific flags */
Command *cmd; /* target of x, y, g, v, X, Y, { */
Command *next; /* next command in {} group */
};
struct CommandDef {
const char *name; /* command name */
VIS_HELP_DECL(const char *help;) /* short, one-line help text */
enum {
CMD_NONE = 0, /* standalone command without any arguments */
CMD_CMD = 1 << 0, /* does the command take a sub/target command? */
CMD_REGEX = 1 << 1, /* regex after command? */
CMD_REGEX_DEFAULT = 1 << 2, /* is the regex optional i.e. can we use a default? */
CMD_COUNT = 1 << 3, /* does the command support a count as in s2/../? */
CMD_TEXT = 1 << 4, /* does the command need a text to insert? */
CMD_ADDRESS_NONE = 1 << 5, /* is it an error to specify an address for the command? */
CMD_ADDRESS_POS = 1 << 6, /* no address implies an empty range at current cursor position */
CMD_ADDRESS_LINE = 1 << 7, /* if no address is given, use the current line */
CMD_ADDRESS_AFTER = 1 << 8, /* if no address is given, begin at the start of the next line */
CMD_ADDRESS_ALL = 1 << 9, /* if no address is given, apply to whole file (independent of #cursors) */
CMD_ADDRESS_ALL_1CURSOR = 1 << 10, /* if no address is given and only 1 cursor exists, apply to whole file */
CMD_SHELL = 1 << 11, /* command needs a shell command as argument */
CMD_FORCE = 1 << 12, /* can the command be forced with ! */
CMD_ARGV = 1 << 13, /* whether shell like argument splitting is desired */
CMD_ONCE = 1 << 14, /* command should only be executed once, not for every selection */
CMD_LOOP = 1 << 15, /* a looping construct like `x`, `y` */
CMD_GROUP = 1 << 16, /* a command group { ... } */
CMD_DESTRUCTIVE = 1 << 17, /* command potentially destroys window */
} flags;
const char *defcmd; /* name of a default target command */
bool (*func)(Vis*, Win*, Command*, const char *argv[], Cursor*, Filerange*); /* command implementation */
};
/* sam commands */
static bool cmd_insert(Vis*, Win*, Command*, const char *argv[], Cursor*, Filerange*);
static bool cmd_append(Vis*, Win*, Command*, const char *argv[], Cursor*, Filerange*);
static bool cmd_change(Vis*, Win*, Command*, const char *argv[], Cursor*, Filerange*);
static bool cmd_delete(Vis*, Win*, Command*, const char *argv[], Cursor*, Filerange*);
static bool cmd_guard(Vis*, Win*, Command*, const char *argv[], Cursor*, Filerange*);
static bool cmd_extract(Vis*, Win*, Command*, const char *argv[], Cursor*, Filerange*);
static bool cmd_select(Vis*, Win*, Command*, const char *argv[], Cursor*, Filerange*);
static bool cmd_print(Vis*, Win*, Command*, const char *argv[], Cursor*, Filerange*);
static bool cmd_files(Vis*, Win*, Command*, const char *argv[], Cursor*, Filerange*);
static bool cmd_pipein(Vis*, Win*, Command*, const char *argv[], Cursor*, Filerange*);
static bool cmd_pipeout(Vis*, Win*, Command*, const char *argv[], Cursor*, Filerange*);
static bool cmd_filter(Vis*, Win*, Command*, const char *argv[], Cursor*, Filerange*);
static bool cmd_launch(Vis*, Win*, Command*, const char *argv[], Cursor*, Filerange*);
static bool cmd_substitute(Vis*, Win*, Command*, const char *argv[], Cursor*, Filerange*);
static bool cmd_write(Vis*, Win*, Command*, const char *argv[], Cursor*, Filerange*);
static bool cmd_read(Vis*, Win*, Command*, const char *argv[], Cursor*, Filerange*);
static bool cmd_edit(Vis*, Win*, Command*, const char *argv[], Cursor*, Filerange*);
static bool cmd_quit(Vis*, Win*, Command*, const char *argv[], Cursor*, Filerange*);
static bool cmd_cd(Vis*, Win*, Command*, const char *argv[], Cursor*, Filerange*);
/* vi(m) commands */
static bool cmd_set(Vis*, Win*, Command*, const char *argv[], Cursor*, Filerange*);
static bool cmd_open(Vis*, Win*, Command*, const char *argv[], Cursor*, Filerange*);
static bool cmd_qall(Vis*, Win*, Command*, const char *argv[], Cursor*, Filerange*);
static bool cmd_split(Vis*, Win*, Command*, const char *argv[], Cursor*, Filerange*);
static bool cmd_vsplit(Vis*, Win*, Command*, const char *argv[], Cursor*, Filerange*);
static bool cmd_new(Vis*, Win*, Command*, const char *argv[], Cursor*, Filerange*);
static bool cmd_vnew(Vis*, Win*, Command*, const char *argv[], Cursor*, Filerange*);
static bool cmd_wq(Vis*, Win*, Command*, const char *argv[], Cursor*, Filerange*);
static bool cmd_earlier_later(Vis*, Win*, Command*, const char *argv[], Cursor*, Filerange*);
static bool cmd_help(Vis*, Win*, Command*, const char *argv[], Cursor*, Filerange*);
static bool cmd_map(Vis*, Win*, Command*, const char *argv[], Cursor*, Filerange*);
static bool cmd_unmap(Vis*, Win*, Command*, const char *argv[], Cursor*, Filerange*);
static bool cmd_langmap(Vis*, Win*, Command*, const char *argv[], Cursor*, Filerange*);
static bool cmd_user(Vis*, Win*, Command*, const char *argv[], Cursor*, Filerange*);
static const CommandDef cmds[] = {
// name help
// flags, default command, implemenation
{
"a", VIS_HELP("Append text after range")
CMD_TEXT, NULL, cmd_append
}, {
"c", VIS_HELP("Change text in range")
CMD_TEXT, NULL, cmd_change
}, {
"d", VIS_HELP("Delete text in range")
CMD_NONE, NULL, cmd_delete
}, {
"g", VIS_HELP("If range contains regexp, run command")
CMD_CMD|CMD_REGEX, "p", cmd_guard
}, {
"i", VIS_HELP("Insert text before range")
CMD_TEXT, NULL, cmd_insert
}, {
"p", VIS_HELP("Create selection covering range")
CMD_NONE, NULL, cmd_print
}, {
"s", VIS_HELP("Substitute: use x/pattern/ c/replacement/ instead")
CMD_SHELL|CMD_ADDRESS_LINE, NULL, cmd_substitute
}, {
"v", VIS_HELP("If range does not contain regexp, run command")
CMD_CMD|CMD_REGEX, "p", cmd_guard
}, {
"x", VIS_HELP("Set range and run command on each match")
CMD_CMD|CMD_REGEX|CMD_REGEX_DEFAULT|CMD_ADDRESS_ALL_1CURSOR|CMD_LOOP, "p", cmd_extract
}, {
"y", VIS_HELP("As `x` but select unmatched text")
CMD_CMD|CMD_REGEX|CMD_ADDRESS_ALL_1CURSOR|CMD_LOOP, "p", cmd_extract
}, {
"X", VIS_HELP("Run command on files whose name matches")
CMD_CMD|CMD_REGEX|CMD_REGEX_DEFAULT|CMD_ADDRESS_NONE|CMD_ONCE, NULL, cmd_files
}, {
"Y", VIS_HELP("As `X` but select unmatched files")
CMD_CMD|CMD_REGEX|CMD_ADDRESS_NONE|CMD_ONCE, NULL, cmd_files
}, {
">", VIS_HELP("Send range to stdin of command")
CMD_SHELL|CMD_ADDRESS_LINE, NULL, cmd_pipeout
}, {
"<", VIS_HELP("Replace range by stdout of command")
CMD_SHELL|CMD_ADDRESS_POS, NULL, cmd_pipein
}, {
"|", VIS_HELP("Pipe range through command")
CMD_SHELL|CMD_ADDRESS_POS, NULL, cmd_filter
}, {
"!", VIS_HELP("Run the command")
CMD_SHELL|CMD_ONCE|CMD_ADDRESS_NONE, NULL, cmd_launch
}, {
"w", VIS_HELP("Write range to named file")
CMD_ARGV|CMD_FORCE|CMD_ONCE|CMD_ADDRESS_ALL, NULL, cmd_write
}, {
"r", VIS_HELP("Replace range by contents of file")
CMD_ARGV|CMD_ADDRESS_AFTER, NULL, cmd_read
}, {
"{", VIS_HELP("Start of command group")
CMD_GROUP, NULL, NULL
}, {
"}", VIS_HELP("End of command group" )
CMD_NONE, NULL, NULL
}, {
"e", VIS_HELP("Edit file")
CMD_ARGV|CMD_FORCE|CMD_ONCE|CMD_ADDRESS_NONE|CMD_DESTRUCTIVE, NULL, cmd_edit
}, {
"q", VIS_HELP("Quit the current window")
CMD_FORCE|CMD_ONCE|CMD_ADDRESS_NONE|CMD_DESTRUCTIVE, NULL, cmd_quit
}, {
"cd", VIS_HELP("Change directory")
CMD_ARGV|CMD_ONCE|CMD_ADDRESS_NONE, NULL, cmd_cd
},
/* vi(m) related commands */
{
"help", VIS_HELP("Show this help")
CMD_ARGV|CMD_ONCE|CMD_ADDRESS_NONE, NULL, cmd_help
}, {
"map", VIS_HELP("Map key binding `:map <mode> <lhs> <rhs>`")
CMD_ARGV|CMD_FORCE|CMD_ONCE|CMD_ADDRESS_NONE, NULL, cmd_map
}, {
"map-window", VIS_HELP("As `map` but window local")
CMD_ARGV|CMD_FORCE|CMD_ONCE|CMD_ADDRESS_NONE, NULL, cmd_map
}, {
"unmap", VIS_HELP("Unmap key binding `:unmap <mode> <lhs>`")
CMD_ARGV|CMD_ONCE|CMD_ADDRESS_NONE, NULL, cmd_unmap
}, {
"unmap-window", VIS_HELP("As `unmap` but window local")
CMD_ARGV|CMD_ONCE|CMD_ADDRESS_NONE, NULL, cmd_unmap
}, {
"langmap", VIS_HELP("Map keyboard layout `:langmap <locale-keys> <latin-keys>`")
CMD_ARGV|CMD_FORCE|CMD_ONCE|CMD_ADDRESS_NONE, NULL, cmd_langmap
}, {
"new", VIS_HELP("Create new window")
CMD_ARGV|CMD_ONCE|CMD_ADDRESS_NONE, NULL, cmd_new
}, {
"open", VIS_HELP("Open file")
CMD_ARGV|CMD_ONCE|CMD_ADDRESS_NONE, NULL, cmd_open
}, {
"qall", VIS_HELP("Exit vis")
CMD_FORCE|CMD_ONCE|CMD_ADDRESS_NONE|CMD_DESTRUCTIVE, NULL, cmd_qall
}, {
"set", VIS_HELP("Set option")
CMD_ARGV|CMD_ONCE|CMD_ADDRESS_NONE, NULL, cmd_set
}, {
"split", VIS_HELP("Horizontally split window")
CMD_ARGV|CMD_ONCE|CMD_ADDRESS_NONE, NULL, cmd_split
}, {
"vnew", VIS_HELP("As `:new` but split vertically")
CMD_ARGV|CMD_ONCE|CMD_ADDRESS_NONE, NULL, cmd_vnew
}, {
"vsplit", VIS_HELP("Vertically split window")
CMD_ARGV|CMD_ONCE|CMD_ADDRESS_NONE, NULL, cmd_vsplit
}, {
"wq", VIS_HELP("Write file and quit")
CMD_ARGV|CMD_FORCE|CMD_ONCE|CMD_ADDRESS_ALL|CMD_DESTRUCTIVE, NULL, cmd_wq
}, {
"earlier", VIS_HELP("Go to older text state")
CMD_ARGV|CMD_ONCE|CMD_ADDRESS_NONE, NULL, cmd_earlier_later
}, {
"later", VIS_HELP("Go to newer text state")
CMD_ARGV|CMD_ONCE|CMD_ADDRESS_NONE, NULL, cmd_earlier_later
},
{ NULL, VIS_HELP(NULL) CMD_NONE, NULL, NULL },
};
static const CommandDef cmddef_select = {
NULL, VIS_HELP(NULL) CMD_NONE, NULL, cmd_select
};
/* :set command options */
typedef struct {
const char *names[3]; /* name and optional alias */
enum VisOption flags; /* option type, etc. */
VIS_HELP_DECL(const char *help;) /* short, one line help text */
VisOptionFunction *func; /* option handler, NULL for bulitins */
void *context; /* context passed to option handler function */
} OptionDef;
enum {
OPTION_SHELL,
OPTION_ESCDELAY,
OPTION_AUTOINDENT,
OPTION_EXPANDTAB,
OPTION_TABWIDTH,
OPTION_SHOW_SPACES,
OPTION_SHOW_TABS,
OPTION_SHOW_NEWLINES,
OPTION_NUMBER,
OPTION_NUMBER_RELATIVE,
OPTION_CURSOR_LINE,
OPTION_COLOR_COLUMN,
OPTION_SAVE_METHOD,
OPTION_CHANGE_256COLORS,
};
static const OptionDef options[] = {
[OPTION_SHELL] = {
{ "shell" },
VIS_OPTION_TYPE_STRING,
VIS_HELP("Shell to use for external commands (default: $SHELL, /etc/passwd, /bin/sh)")
},
[OPTION_ESCDELAY] = {
{ "escdelay" },
VIS_OPTION_TYPE_NUMBER,
VIS_HELP("Miliseconds to wait to distinguish <Escape> from terminal escape sequences")
},
[OPTION_AUTOINDENT] = {
{ "autoindent", "ai" },
VIS_OPTION_TYPE_BOOL,
VIS_HELP("Copy leading white space from previous line")
},
[OPTION_EXPANDTAB] = {
{ "expandtab", "et" },
VIS_OPTION_TYPE_BOOL,
VIS_HELP("Replace entered <Tab> with `tabwidth` spaces")
},
[OPTION_TABWIDTH] = {
{ "tabwidth", "tw" },
VIS_OPTION_TYPE_NUMBER,
VIS_HELP("Number of spaces to display (and insert if `expandtab` is enabled) for a tab")
},
[OPTION_SHOW_SPACES] = {
{ "show-spaces" },
VIS_OPTION_TYPE_BOOL|VIS_OPTION_NEED_WINDOW,
VIS_HELP("Display replacement symbol instead of a space")
},
[OPTION_SHOW_TABS] = {
{ "show-tabs" },
VIS_OPTION_TYPE_BOOL|VIS_OPTION_NEED_WINDOW,
VIS_HELP("Display replacement symbol for tabs")
},
[OPTION_SHOW_NEWLINES] = {
{ "show-newlines" },
VIS_OPTION_TYPE_BOOL|VIS_OPTION_NEED_WINDOW,
VIS_HELP("Display replacement symbol for newlines")
},
[OPTION_NUMBER] = {
{ "numbers", "nu" },
VIS_OPTION_TYPE_BOOL|VIS_OPTION_NEED_WINDOW,
VIS_HELP("Display absolute line numbers")
},
[OPTION_NUMBER_RELATIVE] = {
{ "relativenumbers", "rnu" },
VIS_OPTION_TYPE_BOOL|VIS_OPTION_NEED_WINDOW,
VIS_HELP("Display relative line numbers")
},
[OPTION_CURSOR_LINE] = {
{ "cursorline", "cul" },
VIS_OPTION_TYPE_BOOL|VIS_OPTION_NEED_WINDOW,
VIS_HELP("Highlight current cursor line")
},
[OPTION_COLOR_COLUMN] = {
{ "colorcolumn", "cc" },
VIS_OPTION_TYPE_NUMBER|VIS_OPTION_NEED_WINDOW,
VIS_HELP("Highlight a fixed column")
},
[OPTION_SAVE_METHOD] = {
{ "savemethod" },
VIS_OPTION_TYPE_STRING|VIS_OPTION_NEED_WINDOW,
VIS_HELP("Save method to use for current file 'auto', 'atomic' or 'inplace'")
},
[OPTION_CHANGE_256COLORS] = {
{ "change-256colors" },
VIS_OPTION_TYPE_BOOL,
VIS_HELP("Change 256 color palette to support 24bit colors")
},
};
bool sam_init(Vis *vis) {
if (!(vis->cmds = map_new()))
return false;
bool ret = true;
for (const CommandDef *cmd = cmds; cmd && cmd->name; cmd++)
ret &= map_put(vis->cmds, cmd->name, cmd);
if (!(vis->options = map_new()))
return false;
for (int i = 0; i < LENGTH(options); i++) {
for (const char *const *name = options[i].names; *name; name++)
ret &= map_put(vis->options, *name, &options[i]);
}
return ret;
}
const char *sam_error(enum SamError err) {
static const char *error_msg[] = {
[SAM_ERR_OK] = "Success",
[SAM_ERR_MEMORY] = "Out of memory",
[SAM_ERR_ADDRESS] = "Bad address",
[SAM_ERR_NO_ADDRESS] = "Command takes no address",
[SAM_ERR_UNMATCHED_BRACE] = "Unmatched `}'",
[SAM_ERR_REGEX] = "Bad regular expression",
[SAM_ERR_TEXT] = "Bad text",
[SAM_ERR_SHELL] = "Shell command expected",
[SAM_ERR_COMMAND] = "Unknown command",
[SAM_ERR_EXECUTE] = "Error executing command",
[SAM_ERR_NEWLINE] = "Newline expected",
[SAM_ERR_MARK] = "Invalid mark",
[SAM_ERR_CONFLICT] = "Conflicting changes",
[SAM_ERR_WRITE_CONFLICT] = "Can not write while changing",
[SAM_ERR_LOOP_INVALID_CMD] = "Destructive command in looping construct",
[SAM_ERR_GROUP_INVALID_CMD] = "Destructive command in group",
};
size_t idx = err;
return idx < LENGTH(error_msg) ? error_msg[idx] : NULL;
}
static void change_free(Change *c) {
if (!c)
return;
free((char*)c->data);
free(c);
}
static Change *change_new(Transcript *t, enum ChangeType type, Filerange *range, Win *win, Cursor *cur) {
if (!text_range_valid(range))
return NULL;
Change **prev, *next;
if (t->latest && t->latest->range.end <= range->start) {
prev = &t->latest->next;
next = t->latest->next;
} else {
prev = &t->changes;
next = t->changes;
}
while (next && next->range.end <= range->start) {
prev = &next->next;
next = next->next;
}
if (next && next->range.start < range->end) {
t->error = SAM_ERR_CONFLICT;
return NULL;
}
Change *new = calloc(1, sizeof *new);
if (new) {
new->type = type;
new->range = *range;
new->cursor = cur;
new->win = win;
new->next = next;
*prev = new;
t->latest = new;
}
return new;
}
static void sam_transcript_init(Transcript *t) {
memset(t, 0, sizeof *t);
}
static bool sam_transcript_error(Transcript *t, enum SamError error) {
if (t->changes)
t->error = error;
return t->error;
}
static void sam_transcript_free(Transcript *t) {
for (Change *c = t->changes, *next; c; c = next) {
next = c->next;
change_free(c);
}
}
static bool sam_insert(Win *win, Cursor *cur, size_t pos, const char *data, size_t len) {
Filerange range = text_range_new(pos, pos);
Change *c = change_new(&win->file->transcript, TRANSCRIPT_INSERT, &range, win, cur);
if (c) {
c->data = data;
c->len = len;
}
return c;
}
static bool sam_delete(Win *win, Cursor *cur, Filerange *range) {
return change_new(&win->file->transcript, TRANSCRIPT_DELETE, range, win, cur);
}
static bool sam_change(Win *win, Cursor *cur, Filerange *range, const char *data, size_t len) {
Change *c = change_new(&win->file->transcript, TRANSCRIPT_CHANGE, range, win, cur);
if (c) {
c->data = data;
c->len = len;
}
return c;
}
static Address *address_new(void) {
Address *addr = calloc(1, sizeof *addr);
if (addr)
addr->number = EPOS;
return addr;
}
static void address_free(Address *addr) {
if (!addr)
return;
text_regex_free(addr->regex);
address_free(addr->left);
address_free(addr->right);
free(addr);
}
static void skip_spaces(const char **s) {
while (**s == ' ' || **s == '\t')
(*s)++;
}
static char *parse_until(const char **s, const char *until, const char *escchars, int type){
Buffer buf;
buffer_init(&buf);
size_t len = strlen(until);
bool escaped = false;
for (; **s && (!memchr(until, **s, len) || escaped); (*s)++) {
if (type != CMD_SHELL && !escaped && **s == '\\') {
escaped = true;
continue;
}
char c = **s;
if (escaped) {
escaped = false;
if (c == '\n')
continue;
if (c == 'n') {
c = '\n';
} else if (c == 't') {
c = '\t';
} else if (type != CMD_REGEX && type != CMD_TEXT && c == '\\') {
// ignore one of the back slashes
} else {
bool delim = memchr(until, c, len);
bool esc = escchars && memchr(escchars, c, strlen(escchars));
if (!delim && !esc)
buffer_append(&buf, "\\", 1);
}
}
if (!buffer_append(&buf, &c, 1)) {
buffer_release(&buf);
return NULL;
}
}
buffer_terminate(&buf);
return buffer_move(&buf);
}
static char *parse_delimited(const char **s, int type) {
char delim[2] = { **s, '\0' };
if (!delim[0])
return NULL;
(*s)++;
char *chunk = parse_until(s, delim, NULL, type);
if (**s == delim[0])
(*s)++;
return chunk;
}
static char *parse_text(const char **s) {
skip_spaces(s);
if (**s != '\n') {
const char *before = *s;
char *text = parse_delimited(s, CMD_TEXT);
return (!text && *s != before) ? strdup("") : text;
}
Buffer buf;
buffer_init(&buf);
const char *start = *s + 1;
bool dot = false;
for ((*s)++; **s && (!dot || **s != '\n'); (*s)++)
dot = (**s == '.');
if (!dot || !buffer_put(&buf, start, *s - start - 1) ||
!buffer_append(&buf, "\0", 1)) {
buffer_release(&buf);
return NULL;
}
return buffer_move(&buf);
}
static char *parse_shellcmd(Vis *vis, const char **s) {
skip_spaces(s);
char *cmd = parse_until(s, "\n", NULL, false);
if (!cmd) {
const char *last_cmd = register_get(vis, &vis->registers[VIS_REG_SHELL], NULL);
return last_cmd ? strdup(last_cmd) : NULL;
}
register_put0(vis, &vis->registers[VIS_REG_SHELL], cmd);
return cmd;
}
static void parse_argv(const char **s, const char *argv[], size_t maxarg) {
for (size_t i = 0; i < maxarg; i++) {
skip_spaces(s);
if (**s == '"' || **s == '\'')
argv[i] = parse_delimited(s, CMD_ARGV);
else
argv[i] = parse_until(s, " \t\n", "\'\"", CMD_ARGV);
}
}
static char *parse_cmdname(const char **s) {
Buffer buf;
buffer_init(&buf);
skip_spaces(s);
while (**s && !isspace((unsigned char)**s) && (!ispunct((unsigned char)**s) || **s == '-'))
buffer_append(&buf, (*s)++, 1);
buffer_terminate(&buf);
return buffer_move(&buf);
}
static Regex *parse_regex(Vis *vis, const char **s) {
char *pattern = parse_delimited(s, CMD_REGEX);
Regex *regex = vis_regex(vis, pattern);
free(pattern);
return regex;
}
static int parse_number(const char **s) {
char *end = NULL;
int number = strtoull(*s, &end, 10);
if (end == *s)
return 1;
*s = end;
return number;
}
static Address *address_parse_simple(Vis *vis, const char **s, enum SamError *err) {
skip_spaces(s);
Address addr = {
.type = **s,
.regex = NULL,
.number = EPOS,
.left = NULL,
.right = NULL,
};
switch (addr.type) {
case '#': /* character #n */
(*s)++;
addr.number = parse_number(s);
break;
case '0': case '1': case '2': case '3': case '4': /* line n */
case '5': case '6': case '7': case '8': case '9':
addr.type = 'l';
addr.number = parse_number(s);
break;
case '\'':
(*s)++;
if ((addr.number = vis_mark_from(vis, **s)) == VIS_MARK_INVALID) {
*err = SAM_ERR_MARK;
return NULL;
}
(*s)++;
break;
case '/': /* regexp forwards */
case '?': /* regexp backwards */
addr.regex = parse_regex(vis, s);
if (!addr.regex) {
*err = SAM_ERR_REGEX;
return NULL;
}
break;
case '$': /* end of file */
case '.':
case '+':
case '-':
case '%':
(*s)++;
break;
default:
return NULL;
}
if ((addr.right = address_parse_simple(vis, s, err))) {
switch (addr.right->type) {
case '.':
case '$':
return NULL;
case '#':
case 'l':
case '/':
case '?':
if (addr.type != '+' && addr.type != '-') {
Address *plus = address_new();
if (!plus) {
address_free(addr.right);
return NULL;
}
plus->type = '+';
plus->right = addr.right;
addr.right = plus;
}
break;
}
}
Address *ret = address_new();
if (!ret) {
address_free(addr.right);
return NULL;
}
*ret = addr;
return ret;
}
static Address *address_parse_compound(Vis *vis, const char **s, enum SamError *err) {
Address addr = { 0 }, *left = address_parse_simple(vis, s, err), *right = NULL;
skip_spaces(s);
addr.type = **s;
switch (addr.type) {
case ',': /* a1,a2 */
case ';': /* a1;a2 */
(*s)++;
right = address_parse_compound(vis, s, err);
if (right && (right->type == ',' || right->type == ';') && !right->left) {
*err = SAM_ERR_ADDRESS;
goto fail;
}
break;
default:
return left;
}
addr.left = left;
addr.right = right;
Address *ret = address_new();
if (ret) {
*ret = addr;
return ret;
}
fail:
address_free(left);
address_free(right);
return NULL;
}
static Command *command_new(const char *name) {
Command *cmd = calloc(1, sizeof(Command));
if (!cmd)
return NULL;
if (name && !(cmd->argv[0] = strdup(name))) {
free(cmd);
return NULL;
}
return cmd;
}
static void command_free(Command *cmd) {
if (!cmd)
return;
for (Command *c = cmd->cmd, *next; c; c = next) {
next = c->next;
command_free(c);
}
for (const char **args = cmd->argv; *args; args++)
free((void*)*args);
address_free(cmd->address);
text_regex_free(cmd->regex);
free(cmd);
}
static const CommandDef *command_lookup(Vis *vis, const char *name) {
return map_closest(vis->cmds, name);
}
static Command *command_parse(Vis *vis, const char **s, enum SamError *err) {
if (!**s) {
*err = SAM_ERR_COMMAND;
return NULL;
}
Command *cmd = command_new(NULL);
if (!cmd)
return NULL;
cmd->address = address_parse_compound(vis, s, err);
skip_spaces(s);
cmd->argv[0] = parse_cmdname(s);
if (!cmd->argv[0]) {
char name[2] = { **s ? **s : 'p', '\0' };
if (**s)
(*s)++;
if (!(cmd->argv[0] = strdup(name)))
goto fail;
}
const CommandDef *cmddef = command_lookup(vis, cmd->argv[0]);
if (!cmddef) {
*err = SAM_ERR_COMMAND;
goto fail;
}
cmd->cmddef = cmddef;
if (strcmp(cmd->argv[0], "{") == 0) {
Command *prev = NULL, *next;
int level = vis->nesting_level++;
do {
while (**s == ' ' || **s == '\t' || **s == '\n')
(*s)++;
next = command_parse(vis, s, err);
if (*err)
goto fail;
if (prev)
prev->next = next;
else
cmd->cmd = next;
} while ((prev = next));
if (level != vis->nesting_level) {
*err = SAM_ERR_UNMATCHED_BRACE;
goto fail;
}
} else if (strcmp(cmd->argv[0], "}") == 0) {
if (vis->nesting_level-- == 0) {
*err = SAM_ERR_UNMATCHED_BRACE;
goto fail;
}
command_free(cmd);
return NULL;
}
if (cmddef->flags & CMD_ADDRESS_NONE && cmd->address) {
*err = SAM_ERR_NO_ADDRESS;
goto fail;
}
if (cmddef->flags & CMD_COUNT)
cmd->count = parse_number(s);
if (cmddef->flags & CMD_FORCE && **s == '!') {
cmd->flags = '!';
(*s)++;
}
if (cmddef->flags & CMD_REGEX) {
if ((cmddef->flags & CMD_REGEX_DEFAULT) && (!**s || **s == ' ')) {
skip_spaces(s);
} else if (!(cmd->regex = parse_regex(vis, s))) {
*err = SAM_ERR_REGEX;
goto fail;
}
}
if (cmddef->flags & CMD_SHELL && !(cmd->argv[1] = parse_shellcmd(vis, s))) {
*err = SAM_ERR_SHELL;
goto fail;
}
if (cmddef->flags & CMD_TEXT && !(cmd->argv[1] = parse_text(s))) {
*err = SAM_ERR_TEXT;
goto fail;
}
if (cmddef->flags & CMD_ARGV) {
parse_argv(s, &cmd->argv[1], MAX_ARGV-2);
cmd->argv[MAX_ARGV-1] = NULL;
}
if (cmddef->flags & CMD_CMD) {
skip_spaces(s);
if (cmddef->defcmd && (**s == '\n' || **s == '}' || **s == '\0')) {
if (**s == '\n')
(*s)++;
if (!(cmd->cmd = command_new(cmddef->defcmd)))
goto fail;
cmd->cmd->cmddef = command_lookup(vis, cmddef->defcmd);
} else {
if (!(cmd->cmd = command_parse(vis, s, err)))
goto fail;
if (strcmp(cmd->argv[0], "X") == 0 || strcmp(cmd->argv[0], "Y") == 0) {
Command *sel = command_new("select");
if (!sel)
goto fail;
sel->cmd = cmd->cmd;
sel->cmddef = &cmddef_select;
cmd->cmd = sel;
}
}
}
return cmd;
fail:
command_free(cmd);
return NULL;
}
static Command *sam_parse(Vis *vis, const char *cmd, enum SamError *err) {
vis->nesting_level = 0;
const char **s = &cmd;
Command *c = command_parse(vis, s, err);
if (!c)
return NULL;
while (**s == ' ' || **s == '\t' || **s == '\n')
(*s)++;
if (**s) {
*err = SAM_ERR_NEWLINE;
command_free(c);
return NULL;
}
Command *sel = command_new("select");
if (!sel) {
command_free(c);
return NULL;
}
sel->cmd = c;
sel->cmddef = &cmddef_select;
return sel;
}
static Filerange address_line_evaluate(Address *addr, File *file, Filerange *range, int sign) {
Text *txt = file->text;
size_t offset = addr->number != EPOS ? addr->number : 1;
size_t start = range->start, end = range->end, line;
if (sign > 0) {
char c;
if (end > 0 && text_byte_get(txt, end-1, &c) && c == '\n')
end--;
line = text_lineno_by_pos(txt, end);
line = text_pos_by_lineno(txt, line + offset);
} else if (sign < 0) {
line = text_lineno_by_pos(txt, start);
line = offset < line ? text_pos_by_lineno(txt, line - offset) : 0;
} else {
if (addr->number == 0)
return text_range_new(0, 0);
line = text_pos_by_lineno(txt, addr->number);
}
if (addr->type == 'g')
return text_range_new(line, line);
else
return text_range_new(line, text_line_next(txt, line));
}
static Filerange address_evaluate(Address *addr, File *file, Filerange *range, int sign) {
Filerange ret = text_range_empty();
do {
switch (addr->type) {
case '#':
if (sign > 0)
ret.start = ret.end = range->end + addr->number;
else if (sign < 0)
ret.start = ret.end = range->start - addr->number;
else
ret = text_range_new(addr->number, addr->number);
break;
case 'l':
case 'g':
ret = address_line_evaluate(addr, file, range, sign);
break;
case '\'':
{
size_t pos = text_mark_get(file->text, file->marks[addr->number]);
ret = text_range_new(pos, pos);
break;
}
case '?':
sign = sign == 0 ? -1 : -sign;
/* fall through */
case '/':
if (sign >= 0)
ret = text_object_search_forward(file->text, range->end, addr->regex);
else
ret = text_object_search_backward(file->text, range->start, addr->regex);
break;
case '$':
{
size_t size = text_size(file->text);
ret = text_range_new(size, size);
break;
}
case '.':
ret = *range;
break;
case '+':
case '-':
sign = addr->type == '+' ? +1 : -1;
if (!addr->right || addr->right->type == '+' || addr->right->type == '-')
ret = address_line_evaluate(addr, file, range, sign);
break;
case ',':