]> git.lizzy.rs Git - plan9front.git/blob - sys/src/cmd/sed.c
fixed error handling in p, pr, sed, xd, yacc
[plan9front.git] / sys / src / cmd / sed.c
1 /*
2  * sed -- stream editor
3  */
4 #include <u.h>
5 #include <libc.h>
6 #include <bio.h>
7 #include <regexp.h>
8
9 enum {
10         DEPTH           = 20,           /* max nesting depth of {} */
11         MAXCMDS         = 512,          /* max sed commands */
12         ADDSIZE         = 10000,        /* size of add & read buffer */
13         MAXADDS         = 20,           /* max pending adds and reads */
14         LBSIZE          = 8192,         /* input line size */
15         LABSIZE         = 50,           /* max number of labels */
16         MAXSUB          = 10,           /* max number of sub reg exp */
17         MAXFILES        = 120,          /* max output files */
18 };
19
20 /*
21  * An address is a line #, a R.E., "$", a reference to the last
22  * R.E., or nothing.
23  */
24 typedef struct {
25         enum {
26                 A_NONE,
27                 A_DOL,
28                 A_LINE,
29                 A_RE,
30                 A_LAST,
31         }type;
32         union {
33                 long    line;           /* Line # */
34                 Reprog  *rp;            /* Compiled R.E. */
35         };
36 } Addr;
37
38 typedef struct  SEDCOM {
39         Addr    ad1;                    /* optional start address */
40         Addr    ad2;                    /* optional end address */
41         union {
42                 Reprog  *re1;           /* compiled R.E. */
43                 Rune    *text;          /* added text or file name */
44                 struct  SEDCOM  *lb1;   /* destination command of branch */
45         };
46         Rune    *rhs;                   /* Right-hand side of substitution */
47         Biobuf* fcode;                  /* File ID for read and write */
48         char    command;                /* command code -see below */
49         char    gfl;                    /* 'Global' flag for substitutions */
50         char    pfl;                    /* 'print' flag for substitutions */
51         char    active;                 /* 1 => data between start and end */
52         char    negfl;                  /* negation flag */
53 } SedCom;
54
55 /* Command Codes for field SedCom.command */
56 #define ACOM    01
57 #define BCOM    020
58 #define CCOM    02
59 #define CDCOM   025
60 #define CNCOM   022
61 #define COCOM   017
62 #define CPCOM   023
63 #define DCOM    03
64 #define ECOM    015
65 #define EQCOM   013
66 #define FCOM    016
67 #define GCOM    027
68 #define CGCOM   030
69 #define HCOM    031
70 #define CHCOM   032
71 #define ICOM    04
72 #define LCOM    05
73 #define NCOM    012
74 #define PCOM    010
75 #define QCOM    011
76 #define RCOM    06
77 #define SCOM    07
78 #define TCOM    021
79 #define WCOM    014
80 #define CWCOM   024
81 #define YCOM    026
82 #define XCOM    033
83
84 typedef struct label {                  /* Label symbol table */
85         Rune    uninm[9];               /* Label name */
86         SedCom  *chain;
87         SedCom  *address;               /* Command associated with label */
88 } Label;
89
90 typedef struct  FILE_CACHE {            /* Data file control block */
91         struct FILE_CACHE *next;        /* Forward Link */
92         char    *name;                  /* Name of file */
93 } FileCache;
94
95 SedCom pspace[MAXCMDS];                 /* Command storage */
96 SedCom *pend = pspace+MAXCMDS;          /* End of command storage */
97 SedCom *rep = pspace;                   /* Current fill point */
98
99 Reprog  *lastre = 0;                    /* Last regular expression */
100 Resub   subexp[MAXSUB];                 /* sub-patterns of pattern match*/
101
102 Rune    addspace[ADDSIZE];              /* Buffer for a, c, & i commands */
103 Rune    *addend = addspace+ADDSIZE;
104
105 SedCom  *abuf[MAXADDS];                 /* Queue of pending adds & reads */
106 SedCom  **aptr = abuf;
107
108 struct {                                /* Sed program input control block */
109         enum PTYPE {                    /* Either on command line or in file */
110                 P_ARG,
111                 P_FILE,
112         } type;
113         union PCTL {                    /* Pointer to data */
114                 Biobuf  *bp;
115                 char    *curr;
116         };
117 } prog;
118
119 Rune    genbuf[LBSIZE];                 /* Miscellaneous buffer */
120
121 FileCache       *fhead = 0;             /* Head of File Cache Chain */
122 FileCache       *ftail = 0;             /* Tail of File Cache Chain */
123
124 Rune    *loc1;                          /* Start of pattern match */
125 Rune    *loc2;                          /* End of pattern match */
126 Rune    seof;                           /* Pattern delimiter char */
127
128 Rune    linebuf[LBSIZE+1];              /* Input data buffer */
129 Rune    *lbend = linebuf+LBSIZE;        /* End of buffer */
130 Rune    *spend = linebuf;               /* End of input data */
131 Rune    *cp;                            /* Current scan point in linebuf */
132
133 Rune    holdsp[LBSIZE+1];               /* Hold buffer */
134 Rune    *hend = holdsp+LBSIZE;          /* End of hold buffer */
135 Rune    *hspend = holdsp;               /* End of hold data */
136
137 int     nflag;                          /* Command line flags */
138 int     gflag;
139
140 int     dolflag;                        /* Set when at true EOF */
141 int     sflag;                          /* Set when substitution done */
142 int     jflag;                          /* Set when jump required */
143 int     delflag;                        /* Delete current line when set */
144
145 long    lnum = 0;                       /* Input line count */
146
147 char    fname[MAXFILES][40];            /* File name cache */
148 Biobuf  *fcode[MAXFILES];               /* File ID cache */
149 int     nfiles = 0;                     /* Cache fill point */
150
151 Biobuf  fout;                           /* Output stream */
152 Biobuf  stdin;                          /* Default input */
153 Biobuf* f = 0;                          /* Input data */
154
155 Label   ltab[LABSIZE];                  /* Label name symbol table */
156 Label   *labend = ltab+LABSIZE;         /* End of label table */
157 Label   *lab = ltab+1;                  /* Current Fill point */
158
159 int     depth = 0;                      /* {} stack pointer */
160
161 Rune    bad;                            /* Dummy err ptr reference */
162 Rune    *badp = &bad;
163
164
165 char    CGMES[]  =      "%S command garbled: %S";
166 char    TMMES[]  =      "Too much text: %S";
167 char    LTL[]    =      "Label too long: %S";
168 char    AD0MES[] =      "No addresses allowed: %S";
169 char    AD1MES[] =      "Only one address allowed: %S";
170
171 void    address(Addr *);
172 void    arout(void);
173 int     cmp(char *, char *);
174 int     rcmp(Rune *, Rune *);
175 void    command(SedCom *);
176 Reprog  *compile(void);
177 Rune    *compsub(Rune *, Rune *);
178 void    dechain(void);
179 void    dosub(Rune *);
180 int     ecmp(Rune *, Rune *, int);
181 void    enroll(char *);
182 void    errexit(void);
183 int     executable(SedCom *);
184 void    execute(void);
185 void    fcomp(void);
186 long    getrune(void);
187 Rune    *gline(Rune *);
188 int     match(Reprog *, Rune *);
189 void    newfile(enum PTYPE, char *);
190 int     opendata(void);
191 Biobuf  *open_file(char *);
192 Rune    *place(Rune *, Rune *, Rune *);
193 void    quit(char *, ...);
194 int     rline(Rune *, Rune *);
195 Label   *search(Label *);
196 int     substitute(SedCom *);
197 char    *text(char *);
198 Rune    *stext(Rune *, Rune *);
199 int     ycomp(SedCom *);
200 char *  trans(int c);
201 void    putline(Biobuf *bp, Rune *buf, int n);
202
203 void
204 main(int argc, char **argv)
205 {
206         int compfl;
207
208         lnum = 0;
209         Binit(&fout, 1, OWRITE);
210         Blethal(&fout, nil);
211         fcode[nfiles++] = &fout;
212         compfl = 0;
213
214         if(argc == 1)
215                 exits(0);
216         ARGBEGIN{
217         case 'e':
218                 if (argc <= 1)
219                         quit("missing pattern");
220                 newfile(P_ARG, ARGF());
221                 fcomp();
222                 compfl = 1;
223                 continue;
224         case 'f':
225                 if(argc <= 1)
226                         quit("no pattern-file");
227                 newfile(P_FILE, ARGF());
228                 fcomp();
229                 compfl = 1;
230                 continue;
231         case 'g':
232                 gflag++;
233                 continue;
234         case 'n':
235                 nflag++;
236                 continue;
237         default:
238                 fprint(2, "sed: Unknown flag: %c\n", ARGC());
239                 continue;
240         } ARGEND
241
242         if(compfl == 0) {
243                 if (--argc < 0)
244                         quit("missing pattern");
245                 newfile(P_ARG, *argv++);
246                 fcomp();
247         }
248
249         if(depth)
250                 quit("Too many {'s");
251
252         ltab[0].address = rep;
253
254         dechain();
255
256         if(argc <= 0)
257                 enroll(0);              /* Add stdin to cache */
258         else
259                 while(--argc >= 0)
260                         enroll(*argv++);
261         execute();
262         exits(0);
263 }
264
265 void
266 fcomp(void)
267 {
268         int     i;
269         Label   *lpt;
270         Rune    *tp;
271         SedCom  *pt, *pt1;
272         static Rune     *p = addspace;
273         static SedCom   **cmpend[DEPTH];        /* stack of {} operations */
274
275         while (rline(linebuf, lbend) >= 0) {
276                 cp = linebuf;
277 comploop:
278                 while(*cp == L' ' || *cp == L'\t')
279                         cp++;
280                 if(*cp == L'\0' || *cp == L'#')
281                         continue;
282                 if(*cp == L';') {
283                         cp++;
284                         goto comploop;
285                 }
286
287                 address(&rep->ad1);
288                 if (rep->ad1.type != A_NONE) {
289                         if (rep->ad1.type == A_LAST) {
290                                 if (!lastre)
291                                         quit("First RE may not be null");
292                                 rep->ad1.type = A_RE;
293                                 rep->ad1.rp = lastre;
294                         }
295                         if(*cp == L',' || *cp == L';') {
296                                 cp++;
297                                 address(&rep->ad2);
298                                 if (rep->ad2.type == A_LAST) {
299                                         rep->ad2.type = A_RE;
300                                         rep->ad2.rp = lastre;
301                                 }
302                         } else
303                                 rep->ad2.type = A_NONE;
304                 }
305                 while(*cp == L' ' || *cp == L'\t')
306                         cp++;
307
308 swit:
309                 switch(*cp++) {
310                 default:
311                         quit("Unrecognized command: %S", linebuf);
312
313                 case '!':
314                         rep->negfl = 1;
315                         goto swit;
316
317                 case '{':
318                         rep->command = BCOM;
319                         rep->negfl = !rep->negfl;
320                         cmpend[depth++] = &rep->lb1;
321                         if(++rep >= pend)
322                                 quit("Too many commands: %S", linebuf);
323                         if(*cp == '\0')
324                                 continue;
325                         goto comploop;
326
327                 case '}':
328                         if(rep->ad1.type != A_NONE)
329                                 quit(AD0MES, linebuf);
330                         if(--depth < 0)
331                                 quit("Too many }'s");
332                         *cmpend[depth] = rep;
333                         if(*cp == 0)
334                                 continue;
335                         goto comploop;
336
337                 case '=':
338                         rep->command = EQCOM;
339                         if(rep->ad2.type != A_NONE)
340                                 quit(AD1MES, linebuf);
341                         break;
342
343                 case ':':
344                         if(rep->ad1.type != A_NONE)
345                                 quit(AD0MES, linebuf);
346
347                         while(*cp == L' ')
348                                 cp++;
349                         tp = lab->uninm;
350                         while (*cp && *cp != L';' && *cp != L' ' &&
351                             *cp != L'\t' && *cp != L'#') {
352                                 *tp++ = *cp++;
353                                 if(tp >= &lab->uninm[8])
354                                         quit(LTL, linebuf);
355                         }
356                         *tp = L'\0';
357
358                         if (*lab->uninm == L'\0')               /* no label? */
359                                 quit(CGMES, L":", linebuf);
360                         if(lpt = search(lab)) {
361                                 if(lpt->address)
362                                         quit("Duplicate labels: %S", linebuf);
363                         } else {
364                                 lab->chain = 0;
365                                 lpt = lab;
366                                 if(++lab >= labend)
367                                         quit("Too many labels: %S", linebuf);
368                         }
369                         lpt->address = rep;
370                         if (*cp == L'#')
371                                 continue;
372                         rep--;                  /* reuse this slot */
373                         break;
374
375                 case 'a':
376                         rep->command = ACOM;
377                         if(rep->ad2.type != A_NONE)
378                                 quit(AD1MES, linebuf);
379                         if(*cp == L'\\')
380                                 cp++;
381                         if(*cp++ != L'\n')
382                                 quit(CGMES, L"a", linebuf);
383                         rep->text = p;
384                         p = stext(p, addend);
385                         break;
386                 case 'c':
387                         rep->command = CCOM;
388                         if(*cp == L'\\')
389                                 cp++;
390                         if(*cp++ != L'\n')
391                                 quit(CGMES, L"c", linebuf);
392                         rep->text = p;
393                         p = stext(p, addend);
394                         break;
395                 case 'i':
396                         rep->command = ICOM;
397                         if(rep->ad2.type != A_NONE)
398                                 quit(AD1MES, linebuf);
399                         if(*cp == L'\\')
400                                 cp++;
401                         if(*cp++ != L'\n')
402                                 quit(CGMES, L"i", linebuf);
403                         rep->text = p;
404                         p = stext(p, addend);
405                         break;
406
407                 case 'g':
408                         rep->command = GCOM;
409                         break;
410
411                 case 'G':
412                         rep->command = CGCOM;
413                         break;
414
415                 case 'h':
416                         rep->command = HCOM;
417                         break;
418
419                 case 'H':
420                         rep->command = CHCOM;
421                         break;
422
423                 case 't':
424                         rep->command = TCOM;
425                         goto jtcommon;
426
427                 case 'b':
428                         rep->command = BCOM;
429 jtcommon:
430                         while(*cp == L' ')
431                                 cp++;
432                         if(*cp == L'\0' || *cp == L';') {
433                                 /* no label; jump to end */
434                                 if(pt = ltab[0].chain) {
435                                         while((pt1 = pt->lb1) != nil)
436                                                 pt = pt1;
437                                         pt->lb1 = rep;
438                                 } else
439                                         ltab[0].chain = rep;
440                                 break;
441                         }
442
443                         /* copy label into lab->uninm */
444                         tp = lab->uninm;
445                         while((*tp = *cp++) != L'\0' && *tp != L';')
446                                 if(++tp >= &lab->uninm[8])
447                                         quit(LTL, linebuf);
448                         cp--;
449                         *tp = L'\0';
450
451                         if (*lab->uninm == L'\0')
452                                 /* shouldn't get here */
453                                 quit(CGMES, L"b or t", linebuf);
454                         if((lpt = search(lab)) != nil) {
455                                 if(lpt->address)
456                                         rep->lb1 = lpt->address;
457                                 else {
458                                         for(pt = lpt->chain; pt != nil &&
459                                             (pt1 = pt->lb1) != nil; pt = pt1)
460                                                 ;
461                                         if (pt)
462                                                 pt->lb1 = rep;
463                                 }
464                         } else {                        /* add new label */
465                                 lab->chain = rep;
466                                 lab->address = 0;
467                                 if(++lab >= labend)
468                                         quit("Too many labels: %S", linebuf);
469                         }
470                         break;
471
472                 case 'n':
473                         rep->command = NCOM;
474                         break;
475
476                 case 'N':
477                         rep->command = CNCOM;
478                         break;
479
480                 case 'p':
481                         rep->command = PCOM;
482                         break;
483
484                 case 'P':
485                         rep->command = CPCOM;
486                         break;
487
488                 case 'r':
489                         rep->command = RCOM;
490                         if(rep->ad2.type != A_NONE)
491                                 quit(AD1MES, linebuf);
492                         if(*cp++ != L' ')
493                                 quit(CGMES, L"r", linebuf);
494                         rep->text = p;
495                         p = stext(p, addend);
496                         break;
497
498                 case 'd':
499                         rep->command = DCOM;
500                         break;
501
502                 case 'D':
503                         rep->command = CDCOM;
504                         rep->lb1 = pspace;
505                         break;
506
507                 case 'q':
508                         rep->command = QCOM;
509                         if(rep->ad2.type != A_NONE)
510                                 quit(AD1MES, linebuf);
511                         break;
512
513                 case 'l':
514                         rep->command = LCOM;
515                         break;
516
517                 case 's':
518                         rep->command = SCOM;
519                         seof = *cp++;
520                         if ((rep->re1 = compile()) == 0) {
521                                 if(!lastre)
522                                         quit("First RE may not be null.");
523                                 rep->re1 = lastre;
524                         }
525                         rep->rhs = p;
526                         if((p = compsub(p, addend)) == 0)
527                                 quit(CGMES, L"s", linebuf);
528                         if(*cp == L'g') {
529                                 cp++;
530                                 rep->gfl++;
531                         } else if(gflag)
532                                 rep->gfl++;
533
534                         if(*cp == L'p') {
535                                 cp++;
536                                 rep->pfl = 1;
537                         }
538
539                         if(*cp == L'P') {
540                                 cp++;
541                                 rep->pfl = 2;
542                         }
543
544                         if(*cp == L'w') {
545                                 cp++;
546                                 if(*cp++ !=  L' ')
547                                         quit(CGMES, L"s", linebuf);
548                                 text(fname[nfiles]);
549                                 for(i = nfiles - 1; i >= 0; i--)
550                                         if(cmp(fname[nfiles], fname[i]) == 0) {
551                                                 rep->fcode = fcode[i];
552                                                 goto done;
553                                         }
554                                 if(nfiles >= MAXFILES)
555                                         quit("Too many files in w commands 1");
556                                 rep->fcode = open_file(fname[nfiles]);
557                         }
558                         break;
559
560                 case 'w':
561                         rep->command = WCOM;
562                         if(*cp++ != L' ')
563                                 quit(CGMES, L"w", linebuf);
564                         text(fname[nfiles]);
565                         for(i = nfiles - 1; i >= 0; i--)
566                                 if(cmp(fname[nfiles], fname[i]) == 0) {
567                                         rep->fcode = fcode[i];
568                                         goto done;
569                                 }
570                         if(nfiles >= MAXFILES){
571                                 fprint(2, "sed: Too many files in w commands 2 \n");
572                                 fprint(2, "nfiles = %d; MAXF = %d\n",
573                                         nfiles, MAXFILES);
574                                 errexit();
575                         }
576                         rep->fcode = open_file(fname[nfiles]);
577                         break;
578
579                 case 'x':
580                         rep->command = XCOM;
581                         break;
582
583                 case 'y':
584                         rep->command = YCOM;
585                         seof = *cp++;
586                         if (ycomp(rep) == 0)
587                                 quit(CGMES, L"y", linebuf);
588                         break;
589
590                 }
591 done:
592                 if(++rep >= pend)
593                         quit("Too many commands, last: %S", linebuf);
594                 if(*cp++ != L'\0') {
595                         if(cp[-1] == L';')
596                                 goto comploop;
597                         quit(CGMES, cp - 1, linebuf);
598                 }
599         }
600 }
601
602 Biobuf *
603 open_file(char *name)
604 {
605         int fd;
606         Biobuf *bp;
607
608         if ((bp = malloc(sizeof(Biobuf))) == 0)
609                 quit("Out of memory");
610         if ((fd = open(name, OWRITE)) < 0 &&
611             (fd = create(name, OWRITE, 0666)) < 0)
612                 quit("Cannot create %s", name);
613         Binit(bp, fd, OWRITE);
614         Blethal(bp, nil);
615         Bseek(bp, 0, 2);
616         fcode[nfiles++] = bp;
617         return bp;
618 }
619
620 Rune *
621 compsub(Rune *rhs, Rune *end)
622 {
623         Rune r;
624
625         while ((r = *cp++) != '\0') {
626                 if(r == '\\') {
627                         if (rhs < end)
628                                 *rhs++ = 0xFFFF;
629                         else
630                                 return 0;
631                         r = *cp++;
632                         if(r == 'n')
633                                 r = '\n';
634                 } else {
635                         if(r == seof) {
636                                 if (rhs < end)
637                                         *rhs++ = '\0';
638                                 else
639                                         return 0;
640                                 return rhs;
641                         }
642                 }
643                 if (rhs < end)
644                         *rhs++ = r;
645                 else
646                         return 0;
647         }
648         return 0;
649 }
650
651 Reprog *
652 compile(void)
653 {
654         Rune c;
655         char *ep;
656         char expbuf[512];
657
658         if((c = *cp++) == seof)         /* L'//' */
659                 return 0;
660         ep = expbuf;
661         do {
662                 if (c == L'\0' || c == L'\n')
663                         quit(TMMES, linebuf);
664                 if (c == L'\\') {
665                         if (ep >= expbuf+sizeof(expbuf))
666                                 quit(TMMES, linebuf);
667                         ep += runetochar(ep, &c);
668                         if ((c = *cp++) == L'n')
669                                 c = L'\n';
670                 }
671                 if (ep >= expbuf + sizeof(expbuf))
672                         quit(TMMES, linebuf);
673                 ep += runetochar(ep, &c);
674         } while ((c = *cp++) != seof);
675         *ep = 0;
676         return lastre = regcomp(expbuf);
677 }
678
679 void
680 regerror(char *s)
681 {
682         USED(s);
683         quit(CGMES, L"r.e.-using", linebuf);
684 }
685
686 void
687 newfile(enum PTYPE type, char *name)
688 {
689         if (type == P_ARG)
690                 prog.curr = name;
691         else if ((prog.bp = Bopen(name, OREAD)) == 0)
692                 quit("Cannot open pattern-file: %s\n", name);
693         Blethal(prog.bp, nil);
694         prog.type = type;
695 }
696
697 int
698 rline(Rune *buf, Rune *end)
699 {
700         long c;
701         Rune r;
702
703         while ((c = getrune()) >= 0) {
704                 r = c;
705                 if (r == '\\') {
706                         if (buf <= end)
707                                 *buf++ = r;
708                         if ((c = getrune()) < 0)
709                                 break;
710                         r = c;
711                 } else if (r == '\n') {
712                         *buf = '\0';
713                         return 1;
714                 }
715                 if (buf <= end)
716                         *buf++ = r;
717         }
718         *buf = '\0';
719         return -1;
720 }
721
722 long
723 getrune(void)
724 {
725         long c;
726         Rune r;
727         char *p;
728
729         if (prog.type == P_ARG) {
730                 if ((p = prog.curr) != 0) {
731                         if (*p) {
732                                 prog.curr += chartorune(&r, p);
733                                 c = r;
734                         } else {
735                                 c = '\n';       /* fake an end-of-line */
736                                 prog.curr = 0;
737                         }
738                 } else
739                         c = -1;
740         } else if ((c = Bgetrune(prog.bp)) < 0)
741                 Bterm(prog.bp);
742         return c;
743 }
744
745 void
746 address(Addr *ap)
747 {
748         int c;
749         long lno;
750
751         if((c = *cp++) == '$')
752                 ap->type = A_DOL;
753         else if(c == '/') {
754                 seof = c;
755                 if (ap->rp = compile())
756                         ap->type = A_RE;
757                 else
758                         ap->type = A_LAST;
759         }
760         else if (c >= '0' && c <= '9') {
761                 lno = c - '0';
762                 while ((c = *cp) >= '0' && c <= '9')
763                         lno = lno*10 + *cp++ - '0';
764                 if(!lno)
765                         quit("line number 0 is illegal",0);
766                 ap->type = A_LINE;
767                 ap->line = lno;
768         }
769         else {
770                 cp--;
771                 ap->type = A_NONE;
772         }
773 }
774
775 cmp(char *a, char *b)           /* compare characters */
776 {
777         while(*a == *b++)
778                 if (*a == '\0')
779                         return 0;
780                 else
781                         a++;
782         return 1;
783 }
784 rcmp(Rune *a, Rune *b)          /* compare runes */
785 {
786         while(*a == *b++)
787                 if (*a == '\0')
788                         return 0;
789                 else
790                         a++;
791         return 1;
792 }
793
794 char *
795 text(char *p)           /* extract character string */
796 {
797         Rune r;
798
799         while(*cp == ' ' || *cp == '\t')
800                 cp++;
801         while (*cp) {
802                 if ((r = *cp++) == '\\' && (r = *cp++) == '\0')
803                         break;
804                 if (r == '\n')
805                         while (*cp == ' ' || *cp == '\t')
806                                 cp++;
807                 p += runetochar(p, &r);
808         }
809         *p++ = '\0';
810         return p;
811 }
812
813 Rune *
814 stext(Rune *p, Rune *end)               /* extract rune string */
815 {
816         while(*cp == L' ' || *cp == L'\t')
817                 cp++;
818         while (*cp) {
819                 if (*cp == L'\\' && *++cp == L'\0')
820                         break;
821                 if (p >= end-1)
822                         quit(TMMES, linebuf);
823                 if ((*p++ = *cp++) == L'\n')
824                         while(*cp == L' ' || *cp == L'\t')
825                                 cp++;
826         }
827         *p++ = 0;
828         return p;
829 }
830
831
832 Label *
833 search(Label *ptr)
834 {
835         Label   *rp;
836
837         for (rp = ltab; rp < ptr; rp++)
838                 if(rcmp(rp->uninm, ptr->uninm) == 0)
839                         return(rp);
840         return(0);
841 }
842
843 void
844 dechain(void)
845 {
846         Label   *lptr;
847         SedCom  *rptr, *trptr;
848
849         for(lptr = ltab; lptr < lab; lptr++) {
850                 if(lptr->address == 0)
851                         quit("Undefined label: %S", lptr->uninm);
852                 if(lptr->chain) {
853                         rptr = lptr->chain;
854                         while((trptr = rptr->lb1) != nil) {
855                                 rptr->lb1 = lptr->address;
856                                 rptr = trptr;
857                         }
858                         rptr->lb1 = lptr->address;
859                 }
860         }
861 }
862
863 int
864 ycomp(SedCom *r)
865 {
866         int i;
867         Rune *rp, *sp, *tsp;
868         Rune c, highc;
869
870         highc = 0;
871         for(tsp = cp; *tsp != seof; tsp++) {
872                 if(*tsp == L'\\')
873                         tsp++;
874                 if(*tsp == L'\n' || *tsp == L'\0')
875                         return 0;
876                 if (*tsp > highc)
877                         highc = *tsp;
878         }
879         tsp++;
880         if ((rp = r->text = (Rune *)malloc(sizeof(Rune) * (highc+2))) == nil)
881                 quit("Out of memory");
882         *rp++ = highc;                          /* save upper bound */
883         for (i = 0; i <= highc; i++)
884                 rp[i] = i;
885         sp = cp;
886         while((c = *sp++) != seof) {
887                 if(c == L'\\' && *sp == L'n') {
888                         sp++;
889                         c = L'\n';
890                 }
891                 if((rp[c] = *tsp++) == L'\\' && *tsp == L'n') {
892                         rp[c] = L'\n';
893                         tsp++;
894                 }
895                 if(rp[c] == seof || rp[c] == L'\0') {
896                         free(r->re1);
897                         r->re1 = nil;
898                         return 0;
899                 }
900         }
901         if(*tsp != seof) {
902                 free(r->re1);
903                 r->re1 = nil;
904                 return 0;
905         }
906         cp = tsp+1;
907         return 1;
908 }
909
910 void
911 execute(void)
912 {
913         SedCom  *ipc;
914
915         while (spend = gline(linebuf)){
916                 for(ipc = pspace; ipc->command; ) {
917                         if (!executable(ipc)) {
918                                 ipc++;
919                                 continue;
920                         }
921                         command(ipc);
922
923                         if(delflag)
924                                 break;
925                         if(jflag) {
926                                 jflag = 0;
927                                 if((ipc = ipc->lb1) == 0)
928                                         break;
929                         } else
930                                 ipc++;
931                 }
932                 if(!nflag && !delflag)
933                         putline(&fout, linebuf, spend - linebuf);
934                 if(aptr > abuf)
935                         arout();
936                 delflag = 0;
937         }
938 }
939
940 /* determine if a statement should be applied to an input line */
941 int
942 executable(SedCom *ipc)
943 {
944         if (ipc->active) {      /* Addr1 satisfied - accept until Addr2 */
945                 if (ipc->active == 1)           /* Second line */
946                         ipc->active = 2;
947                 switch(ipc->ad2.type) {
948                 case A_NONE:            /* No second addr; use first */
949                         ipc->active = 0;
950                         break;
951                 case A_DOL:             /* Accept everything */
952                         return !ipc->negfl;
953                 case A_LINE:            /* Line at end of range? */
954                         if (lnum <= ipc->ad2.line) {
955                                 if (ipc->ad2.line == lnum)
956                                         ipc->active = 0;
957                                 return !ipc->negfl;
958                         }
959                         ipc->active = 0;        /* out of range */
960                         return ipc->negfl;
961                 case A_RE:              /* Check for matching R.E. */
962                         if (match(ipc->ad2.rp, linebuf))
963                                 ipc->active = 0;
964                         return !ipc->negfl;
965                 default:
966                         quit("Internal error");
967                 }
968         }
969         switch (ipc->ad1.type) {        /* Check first address */
970         case A_NONE:                    /* Everything matches */
971                 return !ipc->negfl;
972         case A_DOL:                     /* Only last line */
973                 if (dolflag)
974                         return !ipc->negfl;
975                 break;
976         case A_LINE:                    /* Check line number */
977                 if (ipc->ad1.line == lnum) {
978                         ipc->active = 1;        /* In range */
979                         return !ipc->negfl;
980                 }
981                 break;
982         case A_RE:                      /* Check R.E. */
983                 if (match(ipc->ad1.rp, linebuf)) {
984                         ipc->active = 1;        /* In range */
985                         return !ipc->negfl;
986                 }
987                 break;
988         default:
989                 quit("Internal error");
990         }
991         return ipc->negfl;
992 }
993
994 int
995 match(Reprog *pattern, Rune *buf)
996 {
997         if (!pattern)
998                 return 0;
999         subexp[0].rsp = buf;
1000         subexp[0].ep = 0;
1001         if (rregexec(pattern, linebuf, subexp, MAXSUB) > 0) {
1002                 loc1 = subexp[0].rsp;
1003                 loc2 = subexp[0].rep;
1004                 return 1;
1005         }
1006         loc1 = loc2 = 0;
1007         return 0;
1008 }
1009
1010 int
1011 substitute(SedCom *ipc)
1012 {
1013         int len;
1014
1015         if(!match(ipc->re1, linebuf))
1016                 return 0;
1017
1018         /*
1019          * we have at least one match.  some patterns, e.g. '$' or '^', can
1020          * produce 0-length matches, so during a global substitute we must
1021          * bump to the character after a 0-length match to keep from looping.
1022          */
1023         sflag = 1;
1024         if(ipc->gfl == 0)                       /* single substitution */
1025                 dosub(ipc->rhs);
1026         else
1027                 do{                             /* global substitution */
1028                         len = loc2 - loc1;      /* length of match */
1029                         dosub(ipc->rhs);        /* dosub moves loc2 */
1030                         if(*loc2 == 0)          /* end of string */
1031                                 break;
1032                         if(len == 0)            /* zero-length R.E. match */
1033                                 loc2++;         /* bump over 0-length match */
1034                         if(*loc2 == 0)          /* end of string */
1035                                 break;
1036                 } while(match(ipc->re1, loc2));
1037         return 1;
1038 }
1039
1040 void
1041 dosub(Rune *rhsbuf)
1042 {
1043         int c, n;
1044         Rune *lp, *sp, *rp;
1045
1046         lp = linebuf;
1047         sp = genbuf;
1048         rp = rhsbuf;
1049         while (lp < loc1)
1050                 *sp++ = *lp++;
1051         while(c = *rp++) {
1052                 if (c == '&') {
1053                         sp = place(sp, loc1, loc2);
1054                         continue;
1055                 }
1056                 if (c == 0xFFFF && (c = *rp++) >= '1' && c < MAXSUB + '0') {
1057                         n = c-'0';
1058                         if (subexp[n].rsp && subexp[n].rep) {
1059                                 sp = place(sp, subexp[n].rsp, subexp[n].rep);
1060                                 continue;
1061                         }
1062                         else {
1063                                 fprint(2, "sed: Invalid back reference \\%d\n",n);
1064                                 errexit();
1065                         }
1066                 }
1067                 *sp++ = c;
1068                 if (sp >= &genbuf[LBSIZE])
1069                         fprint(2, "sed: Output line too long.\n");
1070         }
1071         lp = loc2;
1072         loc2 = sp - genbuf + linebuf;
1073         while (*sp++ = *lp++)
1074                 if (sp >= &genbuf[LBSIZE])
1075                         fprint(2, "sed: Output line too long.\n");
1076         lp = linebuf;
1077         sp = genbuf;
1078         while (*lp++ = *sp++)
1079                 ;
1080         spend = lp - 1;
1081 }
1082
1083 Rune *
1084 place(Rune *sp, Rune *l1, Rune *l2)
1085 {
1086         while (l1 < l2) {
1087                 *sp++ = *l1++;
1088                 if (sp >= &genbuf[LBSIZE])
1089                         fprint(2, "sed: Output line too long.\n");
1090         }
1091         return sp;
1092 }
1093
1094 char *
1095 trans(int c)
1096 {
1097         static char buf[] = "\\x0000";
1098         static char hex[] = "0123456789abcdef";
1099
1100         switch(c) {
1101         case '\b':
1102                 return "\\b";
1103         case '\n':
1104                 return "\\n";
1105         case '\r':
1106                 return "\\r";
1107         case '\t':
1108                 return "\\t";
1109         case '\\':
1110                 return "\\\\";
1111         }
1112         buf[2] = hex[(c>>12)&0xF];
1113         buf[3] = hex[(c>>8)&0xF];
1114         buf[4] = hex[(c>>4)&0xF];
1115         buf[5] = hex[c&0xF];
1116         return buf;
1117 }
1118
1119 void
1120 command(SedCom *ipc)
1121 {
1122         int i, c;
1123         char *ucp;
1124         Rune *execp, *p1, *p2, *rp;
1125
1126         switch(ipc->command) {
1127         case ACOM:
1128                 *aptr++ = ipc;
1129                 if(aptr >= abuf+MAXADDS)
1130                         quit("sed: Too many appends after line %ld\n",
1131                                 (char *)lnum);
1132                 *aptr = 0;
1133                 break;
1134         case CCOM:
1135                 delflag = 1;
1136                 if(ipc->active == 1) {
1137                         for(rp = ipc->text; *rp; rp++)
1138                                 Bputrune(&fout, *rp);
1139                         Bputc(&fout, '\n');
1140                 }
1141                 break;
1142         case DCOM:
1143                 delflag++;
1144                 break;
1145         case CDCOM:
1146                 p1 = p2 = linebuf;
1147                 while(*p1 != '\n') {
1148                         if(*p1++ == 0) {
1149                                 delflag++;
1150                                 return;
1151                         }
1152                 }
1153                 p1++;
1154                 while(*p2++ = *p1++)
1155                         ;
1156                 spend = p2 - 1;
1157                 jflag++;
1158                 break;
1159         case EQCOM:
1160                 Bprint(&fout, "%ld\n", lnum);
1161                 break;
1162         case GCOM:
1163                 p1 = linebuf;
1164                 p2 = holdsp;
1165                 while(*p1++ = *p2++)
1166                         ;
1167                 spend = p1 - 1;
1168                 break;
1169         case CGCOM:
1170                 *spend++ = '\n';
1171                 p1 = spend;
1172                 p2 = holdsp;
1173                 while(*p1++ = *p2++)
1174                         if(p1 >= lbend)
1175                                 break;
1176                 spend = p1 - 1;
1177                 break;
1178         case HCOM:
1179                 p1 = holdsp;
1180                 p2 = linebuf;
1181                 while(*p1++ = *p2++);
1182                 hspend = p1 - 1;
1183                 break;
1184         case CHCOM:
1185                 *hspend++ = '\n';
1186                 p1 = hspend;
1187                 p2 = linebuf;
1188                 while(*p1++ = *p2++)
1189                         if(p1 >= hend)
1190                                 break;
1191                 hspend = p1 - 1;
1192                 break;
1193         case ICOM:
1194                 for(rp = ipc->text; *rp; rp++)
1195                         Bputrune(&fout, *rp);
1196                 Bputc(&fout, '\n');
1197                 break;
1198         case BCOM:
1199                 jflag = 1;
1200                 break;
1201         case LCOM:
1202                 c = 0;
1203                 for (i = 0, rp = linebuf; *rp; rp++) {
1204                         c = *rp;
1205                         if(c >= 0x20 && c < 0x7F && c != '\\') {
1206                                 Bputc(&fout, c);
1207                                 if(i++ > 71) {
1208                                         Bprint(&fout, "\\\n");
1209                                         i = 0;
1210                                 }
1211                         } else {
1212                                 for (ucp = trans(*rp); *ucp; ucp++){
1213                                         c = *ucp;
1214                                         Bputc(&fout, c);
1215                                         if(i++ > 71) {
1216                                                 Bprint(&fout, "\\\n");
1217                                                 i = 0;
1218                                         }
1219                                 }
1220                         }
1221                 }
1222                 if(c == ' ')
1223                         Bprint(&fout, "\\n");
1224                 Bputc(&fout, '\n');
1225                 break;
1226         case NCOM:
1227                 if(!nflag)
1228                         putline(&fout, linebuf, spend-linebuf);
1229
1230                 if(aptr > abuf)
1231                         arout();
1232                 if((execp = gline(linebuf)) == 0) {
1233                         delflag = 1;
1234                         break;
1235                 }
1236                 spend = execp;
1237                 break;
1238         case CNCOM:
1239                 if(aptr > abuf)
1240                         arout();
1241                 *spend++ = '\n';
1242                 if((execp = gline(spend)) == 0) {
1243                         delflag = 1;
1244                         break;
1245                 }
1246                 spend = execp;
1247                 break;
1248         case PCOM:
1249                 putline(&fout, linebuf, spend-linebuf);
1250                 break;
1251         case CPCOM:
1252 cpcom:
1253                 for(rp = linebuf; *rp && *rp != '\n'; rp++)
1254                         Bputc(&fout, *rp);
1255                 Bputc(&fout, '\n');
1256                 break;
1257         case QCOM:
1258                 if(!nflag)
1259                         putline(&fout, linebuf, spend-linebuf);
1260                 if(aptr > abuf)
1261                         arout();
1262                 exits(0);
1263         case RCOM:
1264                 *aptr++ = ipc;
1265                 if(aptr >= &abuf[MAXADDS])
1266                         quit("sed: Too many reads after line %ld\n",
1267                                 (char *)lnum);
1268                 *aptr = 0;
1269                 break;
1270         case SCOM:
1271                 i = substitute(ipc);
1272                 if(i && ipc->pfl)
1273                         if(ipc->pfl == 1)
1274                                 putline(&fout, linebuf, spend-linebuf);
1275                         else
1276                                 goto cpcom;
1277                 if(i && ipc->fcode)
1278                         goto wcom;
1279                 break;
1280
1281         case TCOM:
1282                 if(sflag) {
1283                         sflag = 0;
1284                         jflag = 1;
1285                 }
1286                 break;
1287
1288         case WCOM:
1289 wcom:
1290                 putline(ipc->fcode,linebuf, spend - linebuf);
1291                 break;
1292         case XCOM:
1293                 p1 = linebuf;
1294                 p2 = genbuf;
1295                 while(*p2++ = *p1++)
1296                         ;
1297                 p1 = holdsp;
1298                 p2 = linebuf;
1299                 while(*p2++ = *p1++)
1300                         ;
1301                 spend = p2 - 1;
1302                 p1 = genbuf;
1303                 p2 = holdsp;
1304                 while(*p2++ = *p1++)
1305                         ;
1306                 hspend = p2 - 1;
1307                 break;
1308         case YCOM:
1309                 p1 = linebuf;
1310                 p2 = ipc->text;
1311                 for (i = *p2++; *p1; p1++)
1312                         if (*p1 <= i)
1313                                 *p1 = p2[*p1];
1314                 break;
1315         }
1316 }
1317
1318 void
1319 putline(Biobuf *bp, Rune *buf, int n)
1320 {
1321         while (n--)
1322                 Bputrune(bp, *buf++);
1323         Bputc(bp, '\n');
1324 }
1325 ecmp(Rune *a, Rune *b, int count)
1326 {
1327         while(count--)
1328                 if(*a++ != *b++)
1329                         return 0;
1330         return 1;
1331 }
1332
1333 void
1334 arout(void)
1335 {
1336         int     c;
1337         char    *s;
1338         char    buf[128];
1339         Rune    *p1;
1340         Biobuf  *fi;
1341
1342         for (aptr = abuf; *aptr; aptr++) {
1343                 if((*aptr)->command == ACOM) {
1344                         for(p1 = (*aptr)->text; *p1; p1++ )
1345                                 Bputrune(&fout, *p1);
1346                         Bputc(&fout, '\n');
1347                 } else {
1348                         for(s = buf, p1 = (*aptr)->text; *p1; p1++)
1349                                 s += runetochar(s, p1);
1350                         *s = '\0';
1351                         if((fi = Bopen(buf, OREAD)) == 0)
1352                                 continue;
1353                         Blethal(fi, nil);
1354                         while((c = Bgetc(fi)) >= 0)
1355                                 Bputc(&fout, c);
1356                         Bterm(fi);
1357                 }
1358         }
1359         aptr = abuf;
1360         *aptr = 0;
1361 }
1362
1363 void
1364 errexit(void)
1365 {
1366         exits("error");
1367 }
1368
1369 void
1370 quit(char *fmt, ...)
1371 {
1372         char *p, *ep;
1373         char msg[256];
1374         va_list arg;
1375
1376         ep = msg + sizeof msg;
1377         p = seprint(msg, ep, "sed: ");
1378         va_start(arg, fmt);
1379         p = vseprint(p, ep, fmt, arg);
1380         va_end(arg);
1381         p = seprint(p, ep, "\n");
1382         write(2, msg, p - msg);
1383         errexit();
1384 }
1385
1386 Rune *
1387 gline(Rune *addr)
1388 {
1389         long c;
1390         Rune *p;
1391         static long peekc = 0;
1392
1393         if (f == 0 && opendata() < 0)
1394                 return 0;
1395         sflag = 0;
1396         lnum++;
1397 /*      Bflush(&fout);********* dumped 4/30/92 - bobf****/
1398         do {
1399                 p = addr;
1400                 for (c = (peekc? peekc: Bgetrune(f)); c >= 0; c = Bgetrune(f)) {
1401                         if (c == '\n') {
1402                                 if ((peekc = Bgetrune(f)) < 0 && fhead == 0)
1403                                         dolflag = 1;
1404                                 *p = '\0';
1405                                 return p;
1406                         }
1407                         if (c && p < lbend)
1408                                 *p++ = c;
1409                 }
1410                 /* return partial final line, adding implicit newline */
1411                 if(p != addr) {
1412                         *p = '\0';
1413                         peekc = -1;
1414                         if (fhead == 0)
1415                                 dolflag = 1;
1416                         return p;
1417                 }
1418                 peekc = 0;
1419                 Bterm(f);
1420         } while (opendata() > 0);               /* Switch to next stream */
1421         f = 0;
1422         return 0;
1423 }
1424
1425 /*
1426  * Data file input section - the intent is to transparently
1427  *      catenate all data input streams.
1428  */
1429 void
1430 enroll(char *filename)          /* Add a file to the input file cache */
1431 {
1432         FileCache *fp;
1433
1434         if ((fp = (FileCache *)malloc(sizeof (FileCache))) == nil)
1435                 quit("Out of memory");
1436         if (ftail == nil)
1437                 fhead = fp;
1438         else
1439                 ftail->next = fp;
1440         ftail = fp;
1441         fp->next = nil;
1442         fp->name = filename;            /* 0 => stdin */
1443 }
1444
1445 int
1446 opendata(void)
1447 {
1448         if (fhead == nil)
1449                 return -1;
1450         if (fhead->name) {
1451                 if ((f = Bopen(fhead->name, OREAD)) == nil)
1452                         quit("Can't open %s", fhead->name);
1453         } else {
1454                 Binit(&stdin, 0, OREAD);
1455                 f = &stdin;
1456         }
1457         Blethal(f, nil);
1458         fhead = fhead->next;
1459         return 1;
1460 }