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 = 0; /* 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]; /* Miscellaneous buffer */
121 FileCache *fhead = 0; /* Head of File Cache Chain */
122 FileCache *ftail = 0; /* 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 = 0; /* Input line count */
147 char fname[MAXFILES][40]; /* File name cache */
148 Biobuf *fcode[MAXFILES]; /* File ID cache */
149 int nfiles = 0; /* Cache fill point */
151 Biobuf fout; /* Output stream */
152 Biobuf stdin; /* Default input */
153 Biobuf* f = 0; /* 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 = 0; /* {} 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 *);
180 int ecmp(Rune *, Rune *, int);
183 int executable(SedCom *);
188 int match(Reprog *, Rune *);
189 void newfile(enum PTYPE, char *);
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 *);
198 Rune *stext(Rune *, Rune *);
201 void putline(Biobuf *bp, Rune *buf, int n);
204 main(int argc, char **argv)
209 Binit(&fout, 1, OWRITE);
211 fcode[nfiles++] = &fout;
219 quit("missing pattern");
220 newfile(P_ARG, ARGF());
226 quit("no pattern-file");
227 newfile(P_FILE, ARGF());
238 fprint(2, "sed: Unknown flag: %c\n", ARGC());
244 quit("missing pattern");
245 newfile(P_ARG, *argv++);
250 quit("Too many {'s");
252 ltab[0].address = rep;
257 enroll(0); /* Add stdin to cache */
272 static Rune *p = addspace;
273 static SedCom **cmpend[DEPTH]; /* stack of {} operations */
275 while (rline(linebuf, lbend) >= 0) {
278 while(*cp == L' ' || *cp == L'\t')
280 if(*cp == L'\0' || *cp == L'#')
288 if (rep->ad1.type != A_NONE) {
289 if (rep->ad1.type == A_LAST) {
291 quit("First RE may not be null");
292 rep->ad1.type = A_RE;
293 rep->ad1.rp = lastre;
295 if(*cp == L',' || *cp == L';') {
298 if (rep->ad2.type == A_LAST) {
299 rep->ad2.type = A_RE;
300 rep->ad2.rp = lastre;
303 rep->ad2.type = A_NONE;
305 while(*cp == L' ' || *cp == L'\t')
311 quit("Unrecognized command: %S", linebuf);
319 rep->negfl = !rep->negfl;
320 cmpend[depth++] = &rep->lb1;
322 quit("Too many commands: %S", linebuf);
328 if(rep->ad1.type != A_NONE)
329 quit(AD0MES, linebuf);
331 quit("Too many }'s");
332 *cmpend[depth] = rep;
338 rep->command = EQCOM;
339 if(rep->ad2.type != A_NONE)
340 quit(AD1MES, linebuf);
344 if(rep->ad1.type != A_NONE)
345 quit(AD0MES, linebuf);
350 while (*cp && *cp != L';' && *cp != L' ' &&
351 *cp != L'\t' && *cp != L'#') {
353 if(tp >= &lab->uninm[8])
358 if (*lab->uninm == L'\0') /* no label? */
359 quit(CGMES, L":", linebuf);
360 if(lpt = search(lab)) {
362 quit("Duplicate labels: %S", linebuf);
367 quit("Too many labels: %S", linebuf);
372 rep--; /* reuse this slot */
377 if(rep->ad2.type != A_NONE)
378 quit(AD1MES, linebuf);
382 quit(CGMES, L"a", linebuf);
384 p = stext(p, addend);
391 quit(CGMES, L"c", linebuf);
393 p = stext(p, addend);
397 if(rep->ad2.type != A_NONE)
398 quit(AD1MES, linebuf);
402 quit(CGMES, L"i", linebuf);
404 p = stext(p, addend);
412 rep->command = CGCOM;
420 rep->command = CHCOM;
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)
443 /* copy label into lab->uninm */
445 while((*tp = *cp++) != L'\0' && *tp != L';')
446 if(++tp >= &lab->uninm[8])
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) {
456 rep->lb1 = lpt->address;
458 for(pt = lpt->chain; pt != nil &&
459 (pt1 = pt->lb1) != nil; pt = pt1)
464 } else { /* add new label */
468 quit("Too many labels: %S", linebuf);
477 rep->command = CNCOM;
485 rep->command = CPCOM;
490 if(rep->ad2.type != A_NONE)
491 quit(AD1MES, linebuf);
493 quit(CGMES, L"r", linebuf);
495 p = stext(p, addend);
503 rep->command = CDCOM;
509 if(rep->ad2.type != A_NONE)
510 quit(AD1MES, linebuf);
520 if ((rep->re1 = compile()) == 0) {
522 quit("First RE may not be null.");
526 if((p = compsub(p, addend)) == 0)
527 quit(CGMES, L"s", linebuf);
547 quit(CGMES, L"s", linebuf);
549 for(i = nfiles - 1; i >= 0; i--)
550 if(cmp(fname[nfiles], fname[i]) == 0) {
551 rep->fcode = fcode[i];
554 if(nfiles >= MAXFILES)
555 quit("Too many files in w commands 1");
556 rep->fcode = open_file(fname[nfiles]);
563 quit(CGMES, L"w", linebuf);
565 for(i = nfiles - 1; i >= 0; i--)
566 if(cmp(fname[nfiles], fname[i]) == 0) {
567 rep->fcode = fcode[i];
570 if(nfiles >= MAXFILES){
571 fprint(2, "sed: Too many files in w commands 2 \n");
572 fprint(2, "nfiles = %d; MAXF = %d\n",
576 rep->fcode = open_file(fname[nfiles]);
587 quit(CGMES, L"y", linebuf);
593 quit("Too many commands, last: %S", linebuf);
597 quit(CGMES, cp - 1, linebuf);
603 open_file(char *name)
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);
616 fcode[nfiles++] = bp;
621 compsub(Rune *rhs, Rune *end)
625 while ((r = *cp++) != '\0') {
658 if((c = *cp++) == seof) /* L'//' */
662 if (c == L'\0' || c == L'\n')
663 quit(TMMES, linebuf);
665 if (ep >= expbuf+sizeof(expbuf))
666 quit(TMMES, linebuf);
667 ep += runetochar(ep, &c);
668 if ((c = *cp++) == L'n')
671 if (ep >= expbuf + sizeof(expbuf))
672 quit(TMMES, linebuf);
673 ep += runetochar(ep, &c);
674 } while ((c = *cp++) != seof);
676 return lastre = regcomp(expbuf);
683 quit(CGMES, L"r.e.-using", linebuf);
687 newfile(enum PTYPE type, char *name)
692 if ((prog.bp = Bopen(name, OREAD)) == 0)
693 quit("Cannot open pattern-file: %s\n", name);
694 Blethal(prog.bp, nil);
700 rline(Rune *buf, Rune *end)
705 while ((c = getrune()) >= 0) {
710 if ((c = getrune()) < 0)
713 } else if (r == '\n') {
731 if (prog.type == P_ARG) {
732 if ((p = prog.curr) != 0) {
734 prog.curr += chartorune(&r, p);
737 c = '\n'; /* fake an end-of-line */
742 } else if ((c = Bgetrune(prog.bp)) < 0)
753 if((c = *cp++) == '$')
757 if (ap->rp = compile())
762 else if (c >= '0' && c <= '9') {
764 while ((c = *cp) >= '0' && c <= '9')
765 lno = lno*10 + *cp++ - '0';
767 quit("line number 0 is illegal",0);
777 cmp(char *a, char *b) /* compare characters */
786 rcmp(Rune *a, Rune *b) /* compare runes */
797 text(char *p) /* extract character string */
801 while(*cp == ' ' || *cp == '\t')
804 if ((r = *cp++) == '\\' && (r = *cp++) == '\0')
807 while (*cp == ' ' || *cp == '\t')
809 p += runetochar(p, &r);
816 stext(Rune *p, Rune *end) /* extract rune string */
818 while(*cp == L' ' || *cp == L'\t')
821 if (*cp == L'\\' && *++cp == L'\0')
824 quit(TMMES, linebuf);
825 if ((*p++ = *cp++) == L'\n')
826 while(*cp == L' ' || *cp == L'\t')
839 for (rp = ltab; rp < ptr; rp++)
840 if(rcmp(rp->uninm, ptr->uninm) == 0)
849 SedCom *rptr, *trptr;
851 for(lptr = ltab; lptr < lab; lptr++) {
852 if(lptr->address == 0)
853 quit("Undefined label: %S", lptr->uninm);
856 while((trptr = rptr->lb1) != nil) {
857 rptr->lb1 = lptr->address;
860 rptr->lb1 = lptr->address;
873 for(tsp = cp; *tsp != seof; tsp++) {
876 if(*tsp == L'\n' || *tsp == L'\0')
882 if ((rp = r->text = (Rune *)malloc(sizeof(Rune) * (highc+2))) == nil)
883 quit("Out of memory");
884 *rp++ = highc; /* save upper bound */
885 for (i = 0; i <= highc; i++)
888 while((c = *sp++) != seof) {
889 if(c == L'\\' && *sp == L'n') {
893 if((rp[c] = *tsp++) == L'\\' && *tsp == L'n') {
897 if(rp[c] == seof || rp[c] == L'\0') {
917 while (spend = gline(linebuf)){
918 for(ipc = pspace; ipc->command; ) {
919 if (!executable(ipc)) {
929 if((ipc = ipc->lb1) == 0)
934 if(!nflag && !delflag)
935 putline(&fout, linebuf, spend - linebuf);
942 /* determine if a statement should be applied to an input line */
944 executable(SedCom *ipc)
946 if (ipc->active) { /* Addr1 satisfied - accept until Addr2 */
947 if (ipc->active == 1) /* Second line */
949 switch(ipc->ad2.type) {
950 case A_NONE: /* No second addr; use first */
953 case A_DOL: /* Accept everything */
955 case A_LINE: /* Line at end of range? */
956 if (lnum <= ipc->ad2.line) {
957 if (ipc->ad2.line == lnum)
961 ipc->active = 0; /* out of range */
963 case A_RE: /* Check for matching R.E. */
964 if (match(ipc->ad2.rp, linebuf))
968 quit("Internal error");
971 switch (ipc->ad1.type) { /* Check first address */
972 case A_NONE: /* Everything matches */
974 case A_DOL: /* Only last line */
978 case A_LINE: /* Check line number */
979 if (ipc->ad1.line == lnum) {
980 ipc->active = 1; /* In range */
984 case A_RE: /* Check R.E. */
985 if (match(ipc->ad1.rp, linebuf)) {
986 ipc->active = 1; /* In range */
991 quit("Internal error");
997 match(Reprog *pattern, Rune *buf)
1001 subexp[0].rsp = buf;
1003 if (rregexec(pattern, linebuf, subexp, MAXSUB) > 0) {
1004 loc1 = subexp[0].rsp;
1005 loc2 = subexp[0].rep;
1013 substitute(SedCom *ipc)
1017 if(!match(ipc->re1, linebuf))
1021 * we have at least one match. some patterns, e.g. '$' or '^', can
1022 * produce 0-length matches, so during a global substitute we must
1023 * bump to the character after a 0-length match to keep from looping.
1026 if(ipc->gfl == 0) /* single substitution */
1029 do{ /* global substitution */
1030 len = loc2 - loc1; /* length of match */
1031 dosub(ipc->rhs); /* dosub moves loc2 */
1032 if(*loc2 == 0) /* end of string */
1034 if(len == 0) /* zero-length R.E. match */
1035 loc2++; /* bump over 0-length match */
1036 if(*loc2 == 0) /* end of string */
1038 } while(match(ipc->re1, loc2));
1055 sp = place(sp, loc1, loc2);
1058 if (c == Runemax && (c = *rp++) >= '1' && c < MAXSUB + '0') {
1060 if (subexp[n].rsp && subexp[n].rep) {
1061 sp = place(sp, subexp[n].rsp, subexp[n].rep);
1065 fprint(2, "sed: Invalid back reference \\%d\n",n);
1070 if (sp >= &genbuf[LBSIZE])
1071 fprint(2, "sed: Output line too long.\n");
1074 loc2 = sp - genbuf + linebuf;
1075 while (*sp++ = *lp++)
1076 if (sp >= &genbuf[LBSIZE])
1077 fprint(2, "sed: Output line too long.\n");
1080 while (*lp++ = *sp++)
1086 place(Rune *sp, Rune *l1, Rune *l2)
1090 if (sp >= &genbuf[LBSIZE])
1091 fprint(2, "sed: Output line too long.\n");
1099 static char buf[] = "\\x0000";
1100 static char hex[] = "0123456789abcdef";
1114 buf[2] = hex[(c>>12)&0xF];
1115 buf[3] = hex[(c>>8)&0xF];
1116 buf[4] = hex[(c>>4)&0xF];
1117 buf[5] = hex[c&0xF];
1122 command(SedCom *ipc)
1126 Rune *execp, *p1, *p2, *rp;
1128 switch(ipc->command) {
1131 if(aptr >= abuf+MAXADDS)
1132 quit("sed: Too many appends after line %ld\n",
1138 if(ipc->active == 1) {
1139 for(rp = ipc->text; *rp; rp++)
1140 Bputrune(&fout, *rp);
1149 while(*p1 != '\n') {
1156 while(*p2++ = *p1++)
1162 Bprint(&fout, "%ld\n", lnum);
1167 while(*p1++ = *p2++)
1175 while(*p1++ = *p2++)
1183 while(*p1++ = *p2++);
1190 while(*p1++ = *p2++)
1196 for(rp = ipc->text; *rp; rp++)
1197 Bputrune(&fout, *rp);
1205 for (i = 0, rp = linebuf; *rp; rp++) {
1207 if(c >= 0x20 && c < 0x7F && c != '\\') {
1210 Bprint(&fout, "\\\n");
1214 for (ucp = trans(*rp); *ucp; ucp++){
1218 Bprint(&fout, "\\\n");
1225 Bprint(&fout, "\\n");
1230 putline(&fout, linebuf, spend-linebuf);
1234 if((execp = gline(linebuf)) == 0) {
1244 if((execp = gline(spend)) == 0) {
1251 putline(&fout, linebuf, spend-linebuf);
1255 for(rp = linebuf; *rp && *rp != '\n'; rp++)
1261 putline(&fout, linebuf, spend-linebuf);
1267 if(aptr >= &abuf[MAXADDS])
1268 quit("sed: Too many reads after line %ld\n",
1273 i = substitute(ipc);
1276 putline(&fout, linebuf, spend-linebuf);
1292 putline(ipc->fcode,linebuf, spend - linebuf);
1297 while(*p2++ = *p1++)
1301 while(*p2++ = *p1++)
1306 while(*p2++ = *p1++)
1313 for (i = *p2++; *p1; p1++)
1321 putline(Biobuf *bp, Rune *buf, int n)
1324 Bputrune(bp, *buf++);
1327 ecmp(Rune *a, Rune *b, int count)
1344 for (aptr = abuf; *aptr; aptr++) {
1345 if((*aptr)->command == ACOM) {
1346 for(p1 = (*aptr)->text; *p1; p1++ )
1347 Bputrune(&fout, *p1);
1350 for(s = buf, e = buf+sizeof(buf)-UTFmax-1, p1 = (*aptr)->text; *p1 && s < e; p1++)
1351 s += runetochar(s, p1);
1353 if((fi = Bopen(buf, OREAD)) == 0)
1356 while((c = Bgetc(fi)) >= 0)
1372 quit(char *fmt, ...)
1378 ep = msg + sizeof msg;
1379 p = seprint(msg, ep, "sed: ");
1381 p = vseprint(p, ep, fmt, arg);
1383 p = seprint(p, ep, "\n");
1384 write(2, msg, p - msg);
1393 static long peekc = 0;
1395 if (f == 0 && opendata() < 0)
1399 /* Bflush(&fout);********* dumped 4/30/92 - bobf****/
1402 for (c = (peekc? peekc: Bgetrune(f)); c >= 0; c = Bgetrune(f)) {
1404 if ((peekc = Bgetrune(f)) < 0 && fhead == 0)
1412 /* return partial final line, adding implicit newline */
1422 } while (opendata() > 0); /* Switch to next stream */
1428 * Data file input section - the intent is to transparently
1429 * catenate all data input streams.
1432 enroll(char *filename) /* Add a file to the input file cache */
1436 if ((fp = (FileCache *)malloc(sizeof (FileCache))) == nil)
1437 quit("Out of memory");
1444 fp->name = filename; /* 0 => stdin */
1453 if ((f = Bopen(fhead->name, OREAD)) == nil)
1454 quit("Can't open %s", fhead->name);
1456 Binit(&stdin, 0, OREAD);
1460 fhead = fhead->next;