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 */
21 * An address is a line #, a R.E., "$", a reference to the last
33 long line; /* Line # */
34 Reprog *rp; /* Compiled R.E. */
38 typedef struct SEDCOM {
39 Addr ad1; /* optional start address */
40 Addr ad2; /* optional end address */
42 Reprog *re1; /* compiled R.E. */
43 Rune *text; /* added text or file name */
44 struct SEDCOM *lb1; /* destination command of branch */
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 */
55 /* Command Codes for field SedCom.command */
84 typedef struct label { /* Label symbol table */
85 Rune uninm[9]; /* Label name */
87 SedCom *address; /* Command associated with label */
90 typedef struct FILE_CACHE { /* Data file control block */
91 struct FILE_CACHE *next; /* Forward Link */
92 char *name; /* Name of file */
95 SedCom pspace[MAXCMDS]; /* Command storage */
96 SedCom *pend = pspace+MAXCMDS; /* End of command storage */
97 SedCom *rep = pspace; /* Current fill point */
99 int dollars; /* Number of dollar (first) addresses */
101 Reprog *lastre; /* Last regular expression */
102 Resub subexp[MAXSUB]; /* sub-patterns of pattern match*/
104 Rune addspace[ADDSIZE]; /* Buffer for a, c, & i commands */
105 Rune *addend = addspace+ADDSIZE;
107 SedCom *abuf[MAXADDS]; /* Queue of pending adds & reads */
108 SedCom **aptr = abuf;
110 struct { /* Sed program input control block */
111 enum PTYPE { /* Either on command line or in file */
115 union PCTL { /* Pointer to data */
121 Rune genbuf[LBSIZE+1]; /* Miscellaneous buffer */
123 FileCache *fhead; /* Head of File Cache Chain */
124 FileCache *ftail; /* Tail of File Cache Chain */
126 Rune *loc1; /* Start of pattern match */
127 Rune *loc2; /* End of pattern match */
128 Rune seof; /* Pattern delimiter char */
130 Rune linebuf[LBSIZE+1]; /* Input data buffer */
131 Rune *lbend = linebuf+LBSIZE; /* End of buffer */
132 Rune *spend = linebuf; /* End of input data */
133 Rune *cp; /* Current scan point in linebuf */
135 Rune holdsp[LBSIZE+1]; /* Hold buffer */
136 Rune *hend = holdsp+LBSIZE; /* End of hold buffer */
137 Rune *hspend = holdsp; /* End of hold data */
139 int nflag; /* Command line flags */
143 int dolflag; /* Set when at true EOF */
144 int sflag; /* Set when substitution done */
145 int jflag; /* Set when jump required */
146 int delflag; /* Delete current line when set */
148 long lnum; /* Input line count */
150 char fname[MAXFILES][40]; /* File name cache */
151 Biobuf *fcode[MAXFILES]; /* File ID cache */
152 int nfiles; /* Cache fill point */
154 Biobuf fout; /* Output stream */
155 Biobuf stdin; /* Default input */
156 Biobuf* f; /* Input data */
158 Label ltab[LABSIZE]; /* Label name symbol table */
159 Label *labend = ltab+LABSIZE; /* End of label table */
160 Label *lab = ltab+1; /* Current Fill point */
162 int depth; /* {} stack pointer */
164 Rune bad; /* Dummy err ptr reference */
168 char CGMES[] = "%S command garbled: %S";
169 char TMMES[] = "Too much text: %S";
170 char LTL[] = "Label too long: %S";
171 char AD0MES[] = "No addresses allowed: %S";
172 char AD1MES[] = "Only one address allowed: %S";
174 void address(Addr *);
176 int cmp(char *, char *);
177 int rcmp(Rune *, Rune *);
178 void command(SedCom *);
179 Reprog *compile(void);
180 Rune *compsub(Rune *, Rune *);
185 int executable(SedCom *);
190 int match(Reprog *, Rune *);
191 void newfile(enum PTYPE, char *);
193 Biobuf *open_file(char *);
194 Rune *place(Rune *, Rune *, Rune *);
195 void quit(char *, ...);
196 int rline(Rune *, Rune *);
197 Label *search(Label *);
198 int substitute(SedCom *);
200 Rune *stext(Rune *, Rune *);
203 void putline(Biobuf *bp, Rune *buf, int n);
206 main(int argc, char **argv)
211 Binit(&fout, 1, OWRITE);
213 fcode[nfiles++] = &fout;
221 quit("missing pattern");
222 newfile(P_ARG, ARGF());
228 quit("no pattern-file");
229 newfile(P_FILE, ARGF());
243 quit("Unknown flag: %c", ARGC());
248 quit("missing pattern");
249 newfile(P_ARG, *argv++);
254 quit("Too many {'s");
256 ltab[0].address = rep;
261 enroll(nil); /* Add stdin to cache */
276 static Rune *p = addspace;
277 static SedCom **cmpend[DEPTH]; /* stack of {} operations */
279 while (rline(linebuf, lbend) >= 0) {
282 while(*cp == L' ' || *cp == L'\t')
284 if(*cp == L'\0' || *cp == L'#')
292 if (rep->ad1.type != A_NONE) {
293 if (rep->ad1.type == A_DOL)
295 if (rep->ad1.type == A_LAST) {
297 quit("First RE may not be null");
298 rep->ad1.type = A_RE;
299 rep->ad1.rp = lastre;
301 if(*cp == L',' || *cp == L';') {
304 if (rep->ad2.type == A_LAST) {
305 rep->ad2.type = A_RE;
306 rep->ad2.rp = lastre;
309 rep->ad2.type = A_NONE;
312 while(*cp == L' ' || *cp == L'\t')
317 quit("Unrecognized command: %S", linebuf);
325 rep->negfl = !rep->negfl;
326 cmpend[depth++] = &rep->lb1;
328 quit("Too many commands: %S", linebuf);
334 if(rep->ad1.type != A_NONE)
335 quit(AD0MES, linebuf);
337 quit("Too many }'s");
338 *cmpend[depth] = rep;
344 rep->command = EQCOM;
345 if(rep->ad2.type != A_NONE)
346 quit(AD1MES, linebuf);
350 if(rep->ad1.type != A_NONE)
351 quit(AD0MES, linebuf);
356 while (*cp && *cp != L';' && *cp != L' ' &&
357 *cp != L'\t' && *cp != L'#') {
359 if(tp >= &lab->uninm[8])
364 if (*lab->uninm == L'\0') /* no label? */
365 quit(CGMES, L":", linebuf);
366 if(lpt = search(lab)) {
368 quit("Duplicate labels: %S", linebuf);
373 quit("Too many labels: %S", linebuf);
378 rep--; /* reuse this slot */
383 if(rep->ad2.type != A_NONE)
384 quit(AD1MES, linebuf);
388 quit(CGMES, L"a", linebuf);
390 p = stext(p, addend);
397 quit(CGMES, L"c", linebuf);
399 p = stext(p, addend);
403 if(rep->ad2.type != A_NONE)
404 quit(AD1MES, linebuf);
408 quit(CGMES, L"i", linebuf);
410 p = stext(p, addend);
418 rep->command = CGCOM;
426 rep->command = CHCOM;
438 if(*cp == L'\0' || *cp == L';') {
439 /* no label; jump to end */
440 if(pt = ltab[0].chain) {
441 while((pt1 = pt->lb1) != nil)
449 /* copy label into lab->uninm */
451 while((*tp = *cp++) != L'\0' && *tp != L';')
452 if(++tp >= &lab->uninm[8])
457 if (*lab->uninm == L'\0')
458 /* shouldn't get here */
459 quit(CGMES, L"b or t", linebuf);
460 if((lpt = search(lab)) != nil) {
462 rep->lb1 = lpt->address;
464 for(pt = lpt->chain; pt != nil &&
465 (pt1 = pt->lb1) != nil; pt = pt1)
470 } else { /* add new label */
474 quit("Too many labels: %S", linebuf);
483 rep->command = CNCOM;
491 rep->command = CPCOM;
496 if(rep->ad2.type != A_NONE)
497 quit(AD1MES, linebuf);
499 quit(CGMES, L"r", linebuf);
501 p = stext(p, addend);
509 rep->command = CDCOM;
515 if(rep->ad2.type != A_NONE)
516 quit(AD1MES, linebuf);
526 if ((rep->re1 = compile()) == 0) {
528 quit("First RE may not be null");
532 if((p = compsub(p, addend)) == 0)
533 quit(CGMES, L"s", linebuf);
553 quit(CGMES, L"s", linebuf);
555 for(i = nfiles - 1; i >= 0; i--)
556 if(cmp(fname[nfiles], fname[i]) == 0) {
557 rep->fcode = fcode[i];
560 if(nfiles >= MAXFILES)
561 quit("Too many files in w commands 1");
562 rep->fcode = open_file(fname[nfiles]);
569 quit(CGMES, L"w", linebuf);
571 for(i = nfiles - 1; i >= 0; i--)
572 if(cmp(fname[nfiles], fname[i]) == 0) {
573 rep->fcode = fcode[i];
576 if(nfiles >= MAXFILES){
577 fprint(2, "sed: Too many files in w commands 2 \n");
578 fprint(2, "nfiles = %d; MAXF = %d\n",
582 rep->fcode = open_file(fname[nfiles]);
593 quit(CGMES, L"y", linebuf);
599 quit("Too many commands, last: %S", linebuf);
603 quit(CGMES, cp - 1, linebuf);
609 open_file(char *name)
614 if ((bp = malloc(sizeof(Biobuf))) == 0)
615 quit("Out of memory");
616 if ((fd = open(name, OWRITE)) < 0 &&
617 (fd = create(name, OWRITE, 0666)) < 0)
618 quit("Cannot create %s", name);
619 Binit(bp, fd, OWRITE);
622 fcode[nfiles++] = bp;
627 compsub(Rune *rhs, Rune *end)
631 while ((r = *cp++) != '\0') {
664 if((c = *cp++) == seof) /* L'//' */
668 if (c == L'\0' || c == L'\n')
669 quit(TMMES, linebuf);
671 if (ep >= expbuf+sizeof(expbuf))
672 quit(TMMES, linebuf);
673 ep += runetochar(ep, &c);
674 if ((c = *cp++) == L'n')
677 if (ep >= expbuf + sizeof(expbuf))
678 quit(TMMES, linebuf);
679 ep += runetochar(ep, &c);
680 } while ((c = *cp++) != seof);
682 return lastre = regcomp(expbuf);
689 quit(CGMES, L"r.e.-using", linebuf);
693 flushout(Biobufhdr *bp, void *v, long n)
697 for(i = 0; i < nfiles; i++)
699 return read(bp->fid, v, n);
703 newfile(enum PTYPE type, char *name)
708 if ((prog.bp = Bopen(name, OREAD)) == 0)
709 quit("Cannot open pattern-file: %s\n", name);
710 Blethal(prog.bp, nil);
711 if(uflag) Biofn(prog.bp, flushout);
717 rline(Rune *buf, Rune *end)
722 while ((c = getrune()) >= 0) {
727 if ((c = getrune()) < 0)
730 } else if (r == '\n') {
748 if (prog.type == P_ARG) {
749 if ((p = prog.curr) != 0) {
751 prog.curr += chartorune(&r, p);
754 c = '\n'; /* fake an end-of-line */
759 } else if ((c = Bgetrune(prog.bp)) < 0)
770 if((c = *cp++) == '$')
774 if (ap->rp = compile())
779 else if (c >= '0' && c <= '9') {
781 while ((c = *cp) >= '0' && c <= '9')
782 lno = lno*10 + *cp++ - '0';
784 quit("line number 0 is illegal",0);
794 cmp(char *a, char *b) /* compare characters */
803 rcmp(Rune *a, Rune *b) /* compare runes */
814 text(char *p) /* extract character string */
818 while(*cp == ' ' || *cp == '\t')
821 if ((r = *cp++) == '\\' && (r = *cp++) == '\0')
824 while (*cp == ' ' || *cp == '\t')
826 p += runetochar(p, &r);
833 stext(Rune *p, Rune *end) /* extract rune string */
835 while(*cp == L' ' || *cp == L'\t')
838 if (*cp == L'\\' && *++cp == L'\0')
841 quit(TMMES, linebuf);
842 if ((*p++ = *cp++) == L'\n')
843 while(*cp == L' ' || *cp == L'\t')
856 for (rp = ltab; rp < ptr; rp++)
857 if(rcmp(rp->uninm, ptr->uninm) == 0)
866 SedCom *rptr, *trptr;
868 for(lptr = ltab; lptr < lab; lptr++) {
869 if(lptr->address == 0)
870 quit("Undefined label: %S", lptr->uninm);
873 while((trptr = rptr->lb1) != nil) {
874 rptr->lb1 = lptr->address;
877 rptr->lb1 = lptr->address;
890 for(tsp = cp; *tsp != seof; tsp++) {
893 if(*tsp == L'\n' || *tsp == L'\0')
899 if ((rp = r->text = (Rune *)malloc(sizeof(Rune) * (highc+2))) == nil)
900 quit("Out of memory");
901 *rp++ = highc; /* save upper bound */
902 for (i = 0; i <= highc; i++)
905 while((c = *sp++) != seof) {
906 if(c == L'\\' && *sp == L'n') {
910 if((rp[c] = *tsp++) == L'\\' && *tsp == L'n') {
914 if(rp[c] == seof || rp[c] == L'\0') {
934 while (spend = gline(linebuf)){
935 for(ipc = pspace; ipc->command; ) {
936 if (!executable(ipc)) {
946 if((ipc = ipc->lb1) == 0)
951 if(!nflag && !delflag)
952 putline(&fout, linebuf, spend - linebuf);
959 /* determine if a statement should be applied to an input line */
961 executable(SedCom *ipc)
963 if (ipc->active) { /* Addr1 satisfied - accept until Addr2 */
964 if (ipc->active == 1) /* Second line */
966 switch(ipc->ad2.type) {
967 case A_NONE: /* No second addr; use first */
970 case A_DOL: /* Accept everything */
972 case A_LINE: /* Line at end of range? */
973 if (lnum <= ipc->ad2.line) {
974 if (ipc->ad2.line == lnum)
978 ipc->active = 0; /* out of range */
980 case A_RE: /* Check for matching R.E. */
981 if (match(ipc->ad2.rp, linebuf))
985 quit("Internal error");
988 switch (ipc->ad1.type) { /* Check first address */
989 case A_NONE: /* Everything matches */
991 case A_DOL: /* Only last line */
995 case A_LINE: /* Check line number */
996 if (ipc->ad1.line == lnum) {
997 ipc->active = 1; /* In range */
1001 case A_RE: /* Check R.E. */
1002 if (match(ipc->ad1.rp, linebuf)) {
1003 ipc->active = 1; /* In range */
1008 quit("Internal error");
1014 match(Reprog *pattern, Rune *buf)
1018 subexp[0].rsp = buf;
1020 if (rregexec(pattern, linebuf, subexp, MAXSUB) > 0) {
1021 loc1 = subexp[0].rsp;
1022 loc2 = subexp[0].rep;
1030 substitute(SedCom *ipc)
1034 if(!match(ipc->re1, linebuf))
1038 * we have at least one match. some patterns, e.g. '$' or '^', can
1039 * produce 0-length matches, so during a global substitute we must
1040 * bump to the character after a 0-length match to keep from looping.
1043 if(ipc->gfl == 0) /* single substitution */
1046 do{ /* global substitution */
1047 len = loc2 - loc1; /* length of match */
1048 dosub(ipc->rhs); /* dosub moves loc2 */
1049 if(*loc2 == 0) /* end of string */
1051 if(len == 0) /* zero-length R.E. match */
1052 loc2++; /* bump over 0-length match */
1053 if(*loc2 == 0) /* end of string */
1055 } while(match(ipc->re1, loc2));
1072 sp = place(sp, loc1, loc2);
1075 if (c == Runemax && (c = *rp++) >= '1' && c < MAXSUB + '0') {
1077 if (subexp[n].rsp && subexp[n].rep) {
1078 sp = place(sp, subexp[n].rsp, subexp[n].rep);
1082 quit("Invalid back reference \\%d", n);
1086 if (sp >= &genbuf[LBSIZE])
1087 quit("Output line too long");
1090 loc2 = sp - genbuf + linebuf;
1091 while (*sp++ = *lp++)
1092 if (sp >= &genbuf[LBSIZE])
1093 quit("Output line too long");
1096 while (*lp++ = *sp++)
1102 place(Rune *sp, Rune *l1, Rune *l2)
1106 if (sp >= &genbuf[LBSIZE])
1107 quit("Output line too long");
1115 static char buf[] = "\\x0000";
1116 static char hex[] = "0123456789abcdef";
1130 buf[2] = hex[(c>>12)&0xF];
1131 buf[3] = hex[(c>>8)&0xF];
1132 buf[4] = hex[(c>>4)&0xF];
1133 buf[5] = hex[c&0xF];
1138 command(SedCom *ipc)
1142 Rune *execp, *p1, *p2, *rp;
1144 switch(ipc->command) {
1147 if(aptr >= abuf+MAXADDS)
1148 quit("Too many appends after line %ld", lnum);
1153 if(ipc->active == 1) {
1154 for(rp = ipc->text; *rp; rp++)
1155 Bputrune(&fout, *rp);
1164 while(*p1 != '\n') {
1171 while(*p2++ = *p1++)
1177 Bprint(&fout, "%ld\n", lnum);
1182 while(*p1++ = *p2++)
1190 while(*p1++ = *p2++)
1198 while(*p1++ = *p2++);
1205 while(*p1++ = *p2++)
1211 for(rp = ipc->text; *rp; rp++)
1212 Bputrune(&fout, *rp);
1220 for (i = 0, rp = linebuf; *rp; rp++) {
1222 if(c >= 0x20 && c < 0x7F && c != '\\') {
1225 Bprint(&fout, "\\\n");
1229 for (ucp = trans(*rp); *ucp; ucp++){
1233 Bprint(&fout, "\\\n");
1240 Bprint(&fout, "\\n");
1245 putline(&fout, linebuf, spend-linebuf);
1249 if((execp = gline(linebuf)) == 0) {
1259 if((execp = gline(spend)) == 0) {
1266 putline(&fout, linebuf, spend-linebuf);
1270 for(rp = linebuf; *rp && *rp != '\n'; rp++)
1276 putline(&fout, linebuf, spend-linebuf);
1282 if(aptr >= &abuf[MAXADDS])
1283 quit("Too many reads after line %ld", lnum);
1287 i = substitute(ipc);
1290 putline(&fout, linebuf, spend-linebuf);
1306 putline(ipc->fcode,linebuf, spend - linebuf);
1311 while(*p2++ = *p1++)
1315 while(*p2++ = *p1++)
1320 while(*p2++ = *p1++)
1327 for (i = *p2++; *p1; p1++)
1335 putline(Biobuf *bp, Rune *buf, int n)
1338 Bputrune(bp, *buf++);
1351 for (aptr = abuf; *aptr; aptr++) {
1352 if((*aptr)->command == ACOM) {
1353 for(p1 = (*aptr)->text; *p1; p1++ )
1354 Bputrune(&fout, *p1);
1357 for(s = buf, e = buf+sizeof(buf)-UTFmax-1, p1 = (*aptr)->text; *p1 && s < e; p1++)
1358 s += runetochar(s, p1);
1360 if((fi = Bopen(buf, OREAD)) == 0)
1363 if(uflag) Biofn(fi, flushout);
1364 while((c = Bgetc(fi)) >= 0)
1380 quit(char *fmt, ...)
1386 ep = msg + sizeof msg;
1387 p = seprint(msg, ep, "sed: ");
1389 p = vseprint(p, ep, fmt, arg);
1391 p = seprint(p, ep, "\n");
1392 write(2, msg, p - msg);
1401 static long peekc = 0;
1403 if (f == 0 && opendata() < 0)
1407 /* Bflush(&fout);********* dumped 4/30/92 - bobf****/
1410 for (c = (peekc? peekc: Bgetrune(f)); c >= 0; c = Bgetrune(f)) {
1412 if (dollars != 0 && (peekc = Bgetrune(f)) < 0 && fhead == nil)
1420 /* return partial final line, adding implicit newline */
1430 } while (opendata() > 0); /* Switch to next stream */
1436 * Data file input section - the intent is to transparently
1437 * catenate all data input streams.
1440 enroll(char *filename) /* Add a file to the input file cache */
1444 if ((fp = (FileCache *)malloc(sizeof (FileCache))) == nil)
1445 quit("Out of memory");
1452 fp->name = filename; /* 0 => stdin */
1461 if ((f = Bopen(fhead->name, OREAD)) == nil)
1462 quit("Can't open %s", fhead->name);
1464 Binit(&stdin, 0, OREAD);
1468 if(uflag) Biofn(f, flushout);
1469 fhead = fhead->next;