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 Reprog *lastre; /* Last regular expression */
100 Resub subexp[MAXSUB]; /* sub-patterns of pattern match*/
102 Rune addspace[ADDSIZE]; /* Buffer for a, c, & i commands */
103 Rune *addend = addspace+ADDSIZE;
105 SedCom *abuf[MAXADDS]; /* Queue of pending adds & reads */
106 SedCom **aptr = abuf;
108 struct { /* Sed program input control block */
109 enum PTYPE { /* Either on command line or in file */
113 union PCTL { /* Pointer to data */
119 Rune genbuf[LBSIZE+1]; /* Miscellaneous buffer */
121 FileCache *fhead; /* Head of File Cache Chain */
122 FileCache *ftail; /* Tail of File Cache Chain */
124 Rune *loc1; /* Start of pattern match */
125 Rune *loc2; /* End of pattern match */
126 Rune seof; /* Pattern delimiter char */
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 */
133 Rune holdsp[LBSIZE+1]; /* Hold buffer */
134 Rune *hend = holdsp+LBSIZE; /* End of hold buffer */
135 Rune *hspend = holdsp; /* End of hold data */
137 int nflag; /* Command line flags */
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 */
145 long lnum; /* Input line count */
147 char fname[MAXFILES][40]; /* File name cache */
148 Biobuf *fcode[MAXFILES]; /* File ID cache */
149 int nfiles; /* Cache fill point */
151 Biobuf fout; /* Output stream */
152 Biobuf stdin; /* Default input */
153 Biobuf* f; /* Input data */
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 */
159 int depth; /* {} stack pointer */
161 Rune bad; /* Dummy err ptr reference */
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";
171 void address(Addr *);
173 int cmp(char *, char *);
174 int rcmp(Rune *, Rune *);
175 void command(SedCom *);
176 Reprog *compile(void);
177 Rune *compsub(Rune *, Rune *);
182 int executable(SedCom *);
187 int match(Reprog *, Rune *);
188 void newfile(enum PTYPE, char *);
190 Biobuf *open_file(char *);
191 Rune *place(Rune *, Rune *, Rune *);
192 void quit(char *, ...);
193 int rline(Rune *, Rune *);
194 Label *search(Label *);
195 int substitute(SedCom *);
197 Rune *stext(Rune *, Rune *);
200 void putline(Biobuf *bp, Rune *buf, int n);
203 main(int argc, char **argv)
208 Binit(&fout, 1, OWRITE);
210 fcode[nfiles++] = &fout;
218 quit("missing pattern");
219 newfile(P_ARG, ARGF());
225 quit("no pattern-file");
226 newfile(P_FILE, ARGF());
237 quit("Unknown flag: %c", ARGC());
242 quit("missing pattern");
243 newfile(P_ARG, *argv++);
248 quit("Too many {'s");
250 ltab[0].address = rep;
255 enroll(nil); /* Add stdin to cache */
270 static Rune *p = addspace;
271 static SedCom **cmpend[DEPTH]; /* stack of {} operations */
273 while (rline(linebuf, lbend) >= 0) {
276 while(*cp == L' ' || *cp == L'\t')
278 if(*cp == L'\0' || *cp == L'#')
286 if (rep->ad1.type != A_NONE) {
287 if (rep->ad1.type == A_LAST) {
289 quit("First RE may not be null");
290 rep->ad1.type = A_RE;
291 rep->ad1.rp = lastre;
293 if(*cp == L',' || *cp == L';') {
296 if (rep->ad2.type == A_LAST) {
297 rep->ad2.type = A_RE;
298 rep->ad2.rp = lastre;
301 rep->ad2.type = A_NONE;
303 while(*cp == L' ' || *cp == L'\t')
309 quit("Unrecognized command: %S", linebuf);
317 rep->negfl = !rep->negfl;
318 cmpend[depth++] = &rep->lb1;
320 quit("Too many commands: %S", linebuf);
326 if(rep->ad1.type != A_NONE)
327 quit(AD0MES, linebuf);
329 quit("Too many }'s");
330 *cmpend[depth] = rep;
336 rep->command = EQCOM;
337 if(rep->ad2.type != A_NONE)
338 quit(AD1MES, linebuf);
342 if(rep->ad1.type != A_NONE)
343 quit(AD0MES, linebuf);
348 while (*cp && *cp != L';' && *cp != L' ' &&
349 *cp != L'\t' && *cp != L'#') {
351 if(tp >= &lab->uninm[8])
356 if (*lab->uninm == L'\0') /* no label? */
357 quit(CGMES, L":", linebuf);
358 if(lpt = search(lab)) {
360 quit("Duplicate labels: %S", linebuf);
365 quit("Too many labels: %S", linebuf);
370 rep--; /* reuse this slot */
375 if(rep->ad2.type != A_NONE)
376 quit(AD1MES, linebuf);
380 quit(CGMES, L"a", linebuf);
382 p = stext(p, addend);
389 quit(CGMES, L"c", linebuf);
391 p = stext(p, addend);
395 if(rep->ad2.type != A_NONE)
396 quit(AD1MES, linebuf);
400 quit(CGMES, L"i", linebuf);
402 p = stext(p, addend);
410 rep->command = CGCOM;
418 rep->command = CHCOM;
430 if(*cp == L'\0' || *cp == L';') {
431 /* no label; jump to end */
432 if(pt = ltab[0].chain) {
433 while((pt1 = pt->lb1) != nil)
441 /* copy label into lab->uninm */
443 while((*tp = *cp++) != L'\0' && *tp != L';')
444 if(++tp >= &lab->uninm[8])
449 if (*lab->uninm == L'\0')
450 /* shouldn't get here */
451 quit(CGMES, L"b or t", linebuf);
452 if((lpt = search(lab)) != nil) {
454 rep->lb1 = lpt->address;
456 for(pt = lpt->chain; pt != nil &&
457 (pt1 = pt->lb1) != nil; pt = pt1)
462 } else { /* add new label */
466 quit("Too many labels: %S", linebuf);
475 rep->command = CNCOM;
483 rep->command = CPCOM;
488 if(rep->ad2.type != A_NONE)
489 quit(AD1MES, linebuf);
491 quit(CGMES, L"r", linebuf);
493 p = stext(p, addend);
501 rep->command = CDCOM;
507 if(rep->ad2.type != A_NONE)
508 quit(AD1MES, linebuf);
518 if ((rep->re1 = compile()) == 0) {
520 quit("First RE may not be null");
524 if((p = compsub(p, addend)) == 0)
525 quit(CGMES, L"s", linebuf);
545 quit(CGMES, L"s", linebuf);
547 for(i = nfiles - 1; i >= 0; i--)
548 if(cmp(fname[nfiles], fname[i]) == 0) {
549 rep->fcode = fcode[i];
552 if(nfiles >= MAXFILES)
553 quit("Too many files in w commands 1");
554 rep->fcode = open_file(fname[nfiles]);
561 quit(CGMES, L"w", linebuf);
563 for(i = nfiles - 1; i >= 0; i--)
564 if(cmp(fname[nfiles], fname[i]) == 0) {
565 rep->fcode = fcode[i];
568 if(nfiles >= MAXFILES){
569 fprint(2, "sed: Too many files in w commands 2 \n");
570 fprint(2, "nfiles = %d; MAXF = %d\n",
574 rep->fcode = open_file(fname[nfiles]);
585 quit(CGMES, L"y", linebuf);
591 quit("Too many commands, last: %S", linebuf);
595 quit(CGMES, cp - 1, linebuf);
601 open_file(char *name)
606 if ((bp = malloc(sizeof(Biobuf))) == 0)
607 quit("Out of memory");
608 if ((fd = open(name, OWRITE)) < 0 &&
609 (fd = create(name, OWRITE, 0666)) < 0)
610 quit("Cannot create %s", name);
611 Binit(bp, fd, OWRITE);
614 fcode[nfiles++] = bp;
619 compsub(Rune *rhs, Rune *end)
623 while ((r = *cp++) != '\0') {
656 if((c = *cp++) == seof) /* L'//' */
660 if (c == L'\0' || c == L'\n')
661 quit(TMMES, linebuf);
663 if (ep >= expbuf+sizeof(expbuf))
664 quit(TMMES, linebuf);
665 ep += runetochar(ep, &c);
666 if ((c = *cp++) == L'n')
669 if (ep >= expbuf + sizeof(expbuf))
670 quit(TMMES, linebuf);
671 ep += runetochar(ep, &c);
672 } while ((c = *cp++) != seof);
674 return lastre = regcomp(expbuf);
681 quit(CGMES, L"r.e.-using", linebuf);
685 newfile(enum PTYPE type, char *name)
690 if ((prog.bp = Bopen(name, OREAD)) == 0)
691 quit("Cannot open pattern-file: %s\n", name);
692 Blethal(prog.bp, nil);
698 rline(Rune *buf, Rune *end)
703 while ((c = getrune()) >= 0) {
708 if ((c = getrune()) < 0)
711 } else if (r == '\n') {
729 if (prog.type == P_ARG) {
730 if ((p = prog.curr) != 0) {
732 prog.curr += chartorune(&r, p);
735 c = '\n'; /* fake an end-of-line */
740 } else if ((c = Bgetrune(prog.bp)) < 0)
751 if((c = *cp++) == '$')
755 if (ap->rp = compile())
760 else if (c >= '0' && c <= '9') {
762 while ((c = *cp) >= '0' && c <= '9')
763 lno = lno*10 + *cp++ - '0';
765 quit("line number 0 is illegal",0);
775 cmp(char *a, char *b) /* compare characters */
784 rcmp(Rune *a, Rune *b) /* compare runes */
795 text(char *p) /* extract character string */
799 while(*cp == ' ' || *cp == '\t')
802 if ((r = *cp++) == '\\' && (r = *cp++) == '\0')
805 while (*cp == ' ' || *cp == '\t')
807 p += runetochar(p, &r);
814 stext(Rune *p, Rune *end) /* extract rune string */
816 while(*cp == L' ' || *cp == L'\t')
819 if (*cp == L'\\' && *++cp == L'\0')
822 quit(TMMES, linebuf);
823 if ((*p++ = *cp++) == L'\n')
824 while(*cp == L' ' || *cp == L'\t')
837 for (rp = ltab; rp < ptr; rp++)
838 if(rcmp(rp->uninm, ptr->uninm) == 0)
847 SedCom *rptr, *trptr;
849 for(lptr = ltab; lptr < lab; lptr++) {
850 if(lptr->address == 0)
851 quit("Undefined label: %S", lptr->uninm);
854 while((trptr = rptr->lb1) != nil) {
855 rptr->lb1 = lptr->address;
858 rptr->lb1 = lptr->address;
871 for(tsp = cp; *tsp != seof; tsp++) {
874 if(*tsp == L'\n' || *tsp == L'\0')
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++)
886 while((c = *sp++) != seof) {
887 if(c == L'\\' && *sp == L'n') {
891 if((rp[c] = *tsp++) == L'\\' && *tsp == L'n') {
895 if(rp[c] == seof || rp[c] == L'\0') {
915 while (spend = gline(linebuf)){
916 for(ipc = pspace; ipc->command; ) {
917 if (!executable(ipc)) {
927 if((ipc = ipc->lb1) == 0)
932 if(!nflag && !delflag)
933 putline(&fout, linebuf, spend - linebuf);
940 /* determine if a statement should be applied to an input line */
942 executable(SedCom *ipc)
944 if (ipc->active) { /* Addr1 satisfied - accept until Addr2 */
945 if (ipc->active == 1) /* Second line */
947 switch(ipc->ad2.type) {
948 case A_NONE: /* No second addr; use first */
951 case A_DOL: /* Accept everything */
953 case A_LINE: /* Line at end of range? */
954 if (lnum <= ipc->ad2.line) {
955 if (ipc->ad2.line == lnum)
959 ipc->active = 0; /* out of range */
961 case A_RE: /* Check for matching R.E. */
962 if (match(ipc->ad2.rp, linebuf))
966 quit("Internal error");
969 switch (ipc->ad1.type) { /* Check first address */
970 case A_NONE: /* Everything matches */
972 case A_DOL: /* Only last line */
976 case A_LINE: /* Check line number */
977 if (ipc->ad1.line == lnum) {
978 ipc->active = 1; /* In range */
982 case A_RE: /* Check R.E. */
983 if (match(ipc->ad1.rp, linebuf)) {
984 ipc->active = 1; /* In range */
989 quit("Internal error");
995 match(Reprog *pattern, Rune *buf)
1001 if (rregexec(pattern, linebuf, subexp, MAXSUB) > 0) {
1002 loc1 = subexp[0].rsp;
1003 loc2 = subexp[0].rep;
1011 substitute(SedCom *ipc)
1015 if(!match(ipc->re1, linebuf))
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.
1024 if(ipc->gfl == 0) /* single substitution */
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 */
1032 if(len == 0) /* zero-length R.E. match */
1033 loc2++; /* bump over 0-length match */
1034 if(*loc2 == 0) /* end of string */
1036 } while(match(ipc->re1, loc2));
1053 sp = place(sp, loc1, loc2);
1056 if (c == Runemax && (c = *rp++) >= '1' && c < MAXSUB + '0') {
1058 if (subexp[n].rsp && subexp[n].rep) {
1059 sp = place(sp, subexp[n].rsp, subexp[n].rep);
1063 quit("Invalid back reference \\%d", n);
1067 if (sp >= &genbuf[LBSIZE])
1068 quit("Output line too long");
1071 loc2 = sp - genbuf + linebuf;
1072 while (*sp++ = *lp++)
1073 if (sp >= &genbuf[LBSIZE])
1074 quit("Output line too long");
1077 while (*lp++ = *sp++)
1083 place(Rune *sp, Rune *l1, Rune *l2)
1087 if (sp >= &genbuf[LBSIZE])
1088 quit("Output line too long");
1096 static char buf[] = "\\x0000";
1097 static char hex[] = "0123456789abcdef";
1111 buf[2] = hex[(c>>12)&0xF];
1112 buf[3] = hex[(c>>8)&0xF];
1113 buf[4] = hex[(c>>4)&0xF];
1114 buf[5] = hex[c&0xF];
1119 command(SedCom *ipc)
1123 Rune *execp, *p1, *p2, *rp;
1125 switch(ipc->command) {
1128 if(aptr >= abuf+MAXADDS)
1129 quit("Too many appends after line %ld", lnum);
1134 if(ipc->active == 1) {
1135 for(rp = ipc->text; *rp; rp++)
1136 Bputrune(&fout, *rp);
1145 while(*p1 != '\n') {
1152 while(*p2++ = *p1++)
1158 Bprint(&fout, "%ld\n", lnum);
1163 while(*p1++ = *p2++)
1171 while(*p1++ = *p2++)
1179 while(*p1++ = *p2++);
1186 while(*p1++ = *p2++)
1192 for(rp = ipc->text; *rp; rp++)
1193 Bputrune(&fout, *rp);
1201 for (i = 0, rp = linebuf; *rp; rp++) {
1203 if(c >= 0x20 && c < 0x7F && c != '\\') {
1206 Bprint(&fout, "\\\n");
1210 for (ucp = trans(*rp); *ucp; ucp++){
1214 Bprint(&fout, "\\\n");
1221 Bprint(&fout, "\\n");
1226 putline(&fout, linebuf, spend-linebuf);
1230 if((execp = gline(linebuf)) == 0) {
1240 if((execp = gline(spend)) == 0) {
1247 putline(&fout, linebuf, spend-linebuf);
1251 for(rp = linebuf; *rp && *rp != '\n'; rp++)
1257 putline(&fout, linebuf, spend-linebuf);
1263 if(aptr >= &abuf[MAXADDS])
1264 quit("Too many reads after line %ld", lnum);
1268 i = substitute(ipc);
1271 putline(&fout, linebuf, spend-linebuf);
1287 putline(ipc->fcode,linebuf, spend - linebuf);
1292 while(*p2++ = *p1++)
1296 while(*p2++ = *p1++)
1301 while(*p2++ = *p1++)
1308 for (i = *p2++; *p1; p1++)
1316 putline(Biobuf *bp, Rune *buf, int n)
1319 Bputrune(bp, *buf++);
1332 for (aptr = abuf; *aptr; aptr++) {
1333 if((*aptr)->command == ACOM) {
1334 for(p1 = (*aptr)->text; *p1; p1++ )
1335 Bputrune(&fout, *p1);
1338 for(s = buf, e = buf+sizeof(buf)-UTFmax-1, p1 = (*aptr)->text; *p1 && s < e; p1++)
1339 s += runetochar(s, p1);
1341 if((fi = Bopen(buf, OREAD)) == 0)
1344 while((c = Bgetc(fi)) >= 0)
1360 quit(char *fmt, ...)
1366 ep = msg + sizeof msg;
1367 p = seprint(msg, ep, "sed: ");
1369 p = vseprint(p, ep, fmt, arg);
1371 p = seprint(p, ep, "\n");
1372 write(2, msg, p - msg);
1381 static long peekc = 0;
1383 if (f == 0 && opendata() < 0)
1387 /* Bflush(&fout);********* dumped 4/30/92 - bobf****/
1390 for (c = (peekc? peekc: Bgetrune(f)); c >= 0; c = Bgetrune(f)) {
1392 if ((peekc = Bgetrune(f)) < 0 && fhead == nil)
1400 /* return partial final line, adding implicit newline */
1410 } while (opendata() > 0); /* Switch to next stream */
1416 * Data file input section - the intent is to transparently
1417 * catenate all data input streams.
1420 enroll(char *filename) /* Add a file to the input file cache */
1424 if ((fp = (FileCache *)malloc(sizeof (FileCache))) == nil)
1425 quit("Out of memory");
1432 fp->name = filename; /* 0 => stdin */
1441 if ((f = Bopen(fhead->name, OREAD)) == nil)
1442 quit("Can't open %s", fhead->name);
1444 Binit(&stdin, 0, OREAD);
1448 fhead = fhead->next;