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 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_LAST) {
295 quit("First RE may not be null");
296 rep->ad1.type = A_RE;
297 rep->ad1.rp = lastre;
299 if(*cp == L',' || *cp == L';') {
302 if (rep->ad2.type == A_LAST) {
303 rep->ad2.type = A_RE;
304 rep->ad2.rp = lastre;
307 rep->ad2.type = A_NONE;
309 while(*cp == L' ' || *cp == L'\t')
315 quit("Unrecognized command: %S", linebuf);
323 rep->negfl = !rep->negfl;
324 cmpend[depth++] = &rep->lb1;
326 quit("Too many commands: %S", linebuf);
332 if(rep->ad1.type != A_NONE)
333 quit(AD0MES, linebuf);
335 quit("Too many }'s");
336 *cmpend[depth] = rep;
342 rep->command = EQCOM;
343 if(rep->ad2.type != A_NONE)
344 quit(AD1MES, linebuf);
348 if(rep->ad1.type != A_NONE)
349 quit(AD0MES, linebuf);
354 while (*cp && *cp != L';' && *cp != L' ' &&
355 *cp != L'\t' && *cp != L'#') {
357 if(tp >= &lab->uninm[8])
362 if (*lab->uninm == L'\0') /* no label? */
363 quit(CGMES, L":", linebuf);
364 if(lpt = search(lab)) {
366 quit("Duplicate labels: %S", linebuf);
371 quit("Too many labels: %S", linebuf);
376 rep--; /* reuse this slot */
381 if(rep->ad2.type != A_NONE)
382 quit(AD1MES, linebuf);
386 quit(CGMES, L"a", linebuf);
388 p = stext(p, addend);
395 quit(CGMES, L"c", linebuf);
397 p = stext(p, addend);
401 if(rep->ad2.type != A_NONE)
402 quit(AD1MES, linebuf);
406 quit(CGMES, L"i", linebuf);
408 p = stext(p, addend);
416 rep->command = CGCOM;
424 rep->command = CHCOM;
436 if(*cp == L'\0' || *cp == L';') {
437 /* no label; jump to end */
438 if(pt = ltab[0].chain) {
439 while((pt1 = pt->lb1) != nil)
447 /* copy label into lab->uninm */
449 while((*tp = *cp++) != L'\0' && *tp != L';')
450 if(++tp >= &lab->uninm[8])
455 if (*lab->uninm == L'\0')
456 /* shouldn't get here */
457 quit(CGMES, L"b or t", linebuf);
458 if((lpt = search(lab)) != nil) {
460 rep->lb1 = lpt->address;
462 for(pt = lpt->chain; pt != nil &&
463 (pt1 = pt->lb1) != nil; pt = pt1)
468 } else { /* add new label */
472 quit("Too many labels: %S", linebuf);
481 rep->command = CNCOM;
489 rep->command = CPCOM;
494 if(rep->ad2.type != A_NONE)
495 quit(AD1MES, linebuf);
497 quit(CGMES, L"r", linebuf);
499 p = stext(p, addend);
507 rep->command = CDCOM;
513 if(rep->ad2.type != A_NONE)
514 quit(AD1MES, linebuf);
524 if ((rep->re1 = compile()) == 0) {
526 quit("First RE may not be null");
530 if((p = compsub(p, addend)) == 0)
531 quit(CGMES, L"s", linebuf);
551 quit(CGMES, L"s", linebuf);
553 for(i = nfiles - 1; i >= 0; i--)
554 if(cmp(fname[nfiles], fname[i]) == 0) {
555 rep->fcode = fcode[i];
558 if(nfiles >= MAXFILES)
559 quit("Too many files in w commands 1");
560 rep->fcode = open_file(fname[nfiles]);
567 quit(CGMES, L"w", linebuf);
569 for(i = nfiles - 1; i >= 0; i--)
570 if(cmp(fname[nfiles], fname[i]) == 0) {
571 rep->fcode = fcode[i];
574 if(nfiles >= MAXFILES){
575 fprint(2, "sed: Too many files in w commands 2 \n");
576 fprint(2, "nfiles = %d; MAXF = %d\n",
580 rep->fcode = open_file(fname[nfiles]);
591 quit(CGMES, L"y", linebuf);
597 quit("Too many commands, last: %S", linebuf);
601 quit(CGMES, cp - 1, linebuf);
607 open_file(char *name)
612 if ((bp = malloc(sizeof(Biobuf))) == 0)
613 quit("Out of memory");
614 if ((fd = open(name, OWRITE)) < 0 &&
615 (fd = create(name, OWRITE, 0666)) < 0)
616 quit("Cannot create %s", name);
617 Binit(bp, fd, OWRITE);
620 fcode[nfiles++] = bp;
625 compsub(Rune *rhs, Rune *end)
629 while ((r = *cp++) != '\0') {
662 if((c = *cp++) == seof) /* L'//' */
666 if (c == L'\0' || c == L'\n')
667 quit(TMMES, linebuf);
669 if (ep >= expbuf+sizeof(expbuf))
670 quit(TMMES, linebuf);
671 ep += runetochar(ep, &c);
672 if ((c = *cp++) == L'n')
675 if (ep >= expbuf + sizeof(expbuf))
676 quit(TMMES, linebuf);
677 ep += runetochar(ep, &c);
678 } while ((c = *cp++) != seof);
680 return lastre = regcomp(expbuf);
687 quit(CGMES, L"r.e.-using", linebuf);
691 flushout(Biobufhdr *bp, void *v, long n)
695 for(i = 0; i < nfiles; i++)
697 return read(bp->fid, v, n);
701 newfile(enum PTYPE type, char *name)
706 if ((prog.bp = Bopen(name, OREAD)) == 0)
707 quit("Cannot open pattern-file: %s\n", name);
708 Blethal(prog.bp, nil);
709 if(uflag) Biofn(prog.bp, flushout);
715 rline(Rune *buf, Rune *end)
720 while ((c = getrune()) >= 0) {
725 if ((c = getrune()) < 0)
728 } else if (r == '\n') {
746 if (prog.type == P_ARG) {
747 if ((p = prog.curr) != 0) {
749 prog.curr += chartorune(&r, p);
752 c = '\n'; /* fake an end-of-line */
757 } else if ((c = Bgetrune(prog.bp)) < 0)
768 if((c = *cp++) == '$'){
773 if (ap->rp = compile())
778 else if (c >= '0' && c <= '9') {
780 while ((c = *cp) >= '0' && c <= '9')
781 lno = lno*10 + *cp++ - '0';
783 quit("line number 0 is illegal",0);
793 cmp(char *a, char *b) /* compare characters */
802 rcmp(Rune *a, Rune *b) /* compare runes */
813 text(char *p) /* extract character string */
817 while(*cp == ' ' || *cp == '\t')
820 if ((r = *cp++) == '\\' && (r = *cp++) == '\0')
823 while (*cp == ' ' || *cp == '\t')
825 p += runetochar(p, &r);
832 stext(Rune *p, Rune *end) /* extract rune string */
834 while(*cp == L' ' || *cp == L'\t')
837 if (*cp == L'\\' && *++cp == L'\0')
840 quit(TMMES, linebuf);
841 if ((*p++ = *cp++) == L'\n')
842 while(*cp == L' ' || *cp == L'\t')
855 for (rp = ltab; rp < ptr; rp++)
856 if(rcmp(rp->uninm, ptr->uninm) == 0)
865 SedCom *rptr, *trptr;
867 for(lptr = ltab; lptr < lab; lptr++) {
868 if(lptr->address == 0)
869 quit("Undefined label: %S", lptr->uninm);
872 while((trptr = rptr->lb1) != nil) {
873 rptr->lb1 = lptr->address;
876 rptr->lb1 = lptr->address;
889 for(tsp = cp; *tsp != seof; tsp++) {
892 if(*tsp == L'\n' || *tsp == L'\0')
898 if ((rp = r->text = (Rune *)malloc(sizeof(Rune) * (highc+2))) == nil)
899 quit("Out of memory");
900 *rp++ = highc; /* save upper bound */
901 for (i = 0; i <= highc; i++)
904 while((c = *sp++) != seof) {
905 if(c == L'\\' && *sp == L'n') {
909 if((rp[c] = *tsp++) == L'\\' && *tsp == L'n') {
913 if(rp[c] == seof || rp[c] == L'\0') {
933 while (spend = gline(linebuf)){
934 for(ipc = pspace; ipc->command; ) {
935 if (!executable(ipc)) {
945 if((ipc = ipc->lb1) == 0)
950 if(!nflag && !delflag)
951 putline(&fout, linebuf, spend - linebuf);
958 /* determine if a statement should be applied to an input line */
960 executable(SedCom *ipc)
962 if (ipc->active) { /* Addr1 satisfied - accept until Addr2 */
963 if (ipc->active == 1) /* Second line */
965 switch(ipc->ad2.type) {
966 case A_NONE: /* No second addr; use first */
969 case A_DOL: /* Accept everything */
971 case A_LINE: /* Line at end of range? */
972 if (lnum <= ipc->ad2.line) {
973 if (ipc->ad2.line == lnum)
977 ipc->active = 0; /* out of range */
979 case A_RE: /* Check for matching R.E. */
980 if (match(ipc->ad2.rp, linebuf))
984 quit("Internal error");
987 switch (ipc->ad1.type) { /* Check first address */
988 case A_NONE: /* Everything matches */
990 case A_DOL: /* Only last line */
994 case A_LINE: /* Check line number */
995 if (ipc->ad1.line == lnum) {
996 ipc->active = 1; /* In range */
1000 case A_RE: /* Check R.E. */
1001 if (match(ipc->ad1.rp, linebuf)) {
1002 ipc->active = 1; /* In range */
1007 quit("Internal error");
1013 match(Reprog *pattern, Rune *buf)
1017 subexp[0].rsp = buf;
1019 if (rregexec(pattern, linebuf, subexp, MAXSUB) > 0) {
1020 loc1 = subexp[0].rsp;
1021 loc2 = subexp[0].rep;
1029 substitute(SedCom *ipc)
1033 if(!match(ipc->re1, linebuf))
1037 * we have at least one match. some patterns, e.g. '$' or '^', can
1038 * produce 0-length matches, so during a global substitute we must
1039 * bump to the character after a 0-length match to keep from looping.
1042 if(ipc->gfl == 0) /* single substitution */
1045 do{ /* global substitution */
1046 len = loc2 - loc1; /* length of match */
1047 dosub(ipc->rhs); /* dosub moves loc2 */
1048 if(*loc2 == 0) /* end of string */
1050 if(len == 0) /* zero-length R.E. match */
1051 loc2++; /* bump over 0-length match */
1052 if(*loc2 == 0) /* end of string */
1054 } while(match(ipc->re1, loc2));
1071 sp = place(sp, loc1, loc2);
1074 if (c == Runemax && (c = *rp++) >= '1' && c < MAXSUB + '0') {
1076 if (subexp[n].rsp && subexp[n].rep) {
1077 sp = place(sp, subexp[n].rsp, subexp[n].rep);
1081 quit("Invalid back reference \\%d", n);
1085 if (sp >= &genbuf[LBSIZE])
1086 quit("Output line too long");
1089 loc2 = sp - genbuf + linebuf;
1090 while (*sp++ = *lp++)
1091 if (sp >= &genbuf[LBSIZE])
1092 quit("Output line too long");
1095 while (*lp++ = *sp++)
1101 place(Rune *sp, Rune *l1, Rune *l2)
1105 if (sp >= &genbuf[LBSIZE])
1106 quit("Output line too long");
1114 static char buf[] = "\\x0000";
1115 static char hex[] = "0123456789abcdef";
1129 buf[2] = hex[(c>>12)&0xF];
1130 buf[3] = hex[(c>>8)&0xF];
1131 buf[4] = hex[(c>>4)&0xF];
1132 buf[5] = hex[c&0xF];
1137 command(SedCom *ipc)
1141 Rune *execp, *p1, *p2, *rp;
1143 switch(ipc->command) {
1146 if(aptr >= abuf+MAXADDS)
1147 quit("Too many appends after line %ld", lnum);
1152 if(ipc->active == 1) {
1153 for(rp = ipc->text; *rp; rp++)
1154 Bputrune(&fout, *rp);
1163 while(*p1 != '\n') {
1170 while(*p2++ = *p1++)
1176 Bprint(&fout, "%ld\n", lnum);
1181 while(*p1++ = *p2++)
1189 while(*p1++ = *p2++)
1197 while(*p1++ = *p2++);
1204 while(*p1++ = *p2++)
1210 for(rp = ipc->text; *rp; rp++)
1211 Bputrune(&fout, *rp);
1219 for (i = 0, rp = linebuf; *rp; rp++) {
1221 if(c >= 0x20 && c < 0x7F && c != '\\') {
1224 Bprint(&fout, "\\\n");
1228 for (ucp = trans(*rp); *ucp; ucp++){
1232 Bprint(&fout, "\\\n");
1239 Bprint(&fout, "\\n");
1244 putline(&fout, linebuf, spend-linebuf);
1248 if((execp = gline(linebuf)) == 0) {
1258 if((execp = gline(spend)) == 0) {
1265 putline(&fout, linebuf, spend-linebuf);
1269 for(rp = linebuf; *rp && *rp != '\n'; rp++)
1275 putline(&fout, linebuf, spend-linebuf);
1281 if(aptr >= &abuf[MAXADDS])
1282 quit("Too many reads after line %ld", lnum);
1286 i = substitute(ipc);
1289 putline(&fout, linebuf, spend-linebuf);
1305 putline(ipc->fcode,linebuf, spend - linebuf);
1310 while(*p2++ = *p1++)
1314 while(*p2++ = *p1++)
1319 while(*p2++ = *p1++)
1326 for (i = *p2++; *p1; p1++)
1334 putline(Biobuf *bp, Rune *buf, int n)
1337 Bputrune(bp, *buf++);
1350 for (aptr = abuf; *aptr; aptr++) {
1351 if((*aptr)->command == ACOM) {
1352 for(p1 = (*aptr)->text; *p1; p1++ )
1353 Bputrune(&fout, *p1);
1356 for(s = buf, e = buf+sizeof(buf)-UTFmax-1, p1 = (*aptr)->text; *p1 && s < e; p1++)
1357 s += runetochar(s, p1);
1359 if((fi = Bopen(buf, OREAD)) == 0)
1362 if(uflag) Biofn(fi, flushout);
1363 while((c = Bgetc(fi)) >= 0)
1379 quit(char *fmt, ...)
1385 ep = msg + sizeof msg;
1386 p = seprint(msg, ep, "sed: ");
1388 p = vseprint(p, ep, fmt, arg);
1390 p = seprint(p, ep, "\n");
1391 write(2, msg, p - msg);
1400 static long peekc = 0;
1402 if (f == 0 && opendata() < 0)
1406 /* Bflush(&fout);********* dumped 4/30/92 - bobf****/
1409 for (c = (peekc? peekc: Bgetrune(f)); c >= 0; c = Bgetrune(f)) {
1411 if (dollars != 0 && (peekc = Bgetrune(f)) < 0 && fhead == nil)
1419 /* return partial final line, adding implicit newline */
1429 } while (opendata() > 0); /* Switch to next stream */
1435 * Data file input section - the intent is to transparently
1436 * catenate all data input streams.
1439 enroll(char *filename) /* Add a file to the input file cache */
1443 if ((fp = (FileCache *)malloc(sizeof (FileCache))) == nil)
1444 quit("Out of memory");
1451 fp->name = filename; /* 0 => stdin */
1460 if ((f = Bopen(fhead->name, OREAD)) == nil)
1461 quit("Can't open %s", fhead->name);
1463 Binit(&stdin, 0, OREAD);
1467 if(uflag) Biofn(f, flushout);
1468 fhead = fhead->next;