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);
210 fcode[nfiles++] = &fout;
218 quit("missing pattern");
219 newfile(P_ARG, ARGF());
225 quit("no pattern-file");
226 newfile(P_FILE, ARGF());
237 fprint(2, "sed: Unknown flag: %c\n", ARGC());
243 quit("missing pattern");
244 newfile(P_ARG, *argv++);
249 quit("Too many {'s");
251 ltab[0].address = rep;
256 enroll(0); /* Add stdin to cache */
271 static Rune *p = addspace;
272 static SedCom **cmpend[DEPTH]; /* stack of {} operations */
274 while (rline(linebuf, lbend) >= 0) {
277 while(*cp == L' ' || *cp == L'\t')
279 if(*cp == L'\0' || *cp == L'#')
287 if (rep->ad1.type != A_NONE) {
288 if (rep->ad1.type == A_LAST) {
290 quit("First RE may not be null");
291 rep->ad1.type = A_RE;
292 rep->ad1.rp = lastre;
294 if(*cp == L',' || *cp == L';') {
297 if (rep->ad2.type == A_LAST) {
298 rep->ad2.type = A_RE;
299 rep->ad2.rp = lastre;
302 rep->ad2.type = A_NONE;
304 while(*cp == L' ' || *cp == L'\t')
310 quit("Unrecognized command: %S", linebuf);
318 rep->negfl = !rep->negfl;
319 cmpend[depth++] = &rep->lb1;
321 quit("Too many commands: %S", linebuf);
327 if(rep->ad1.type != A_NONE)
328 quit(AD0MES, linebuf);
330 quit("Too many }'s");
331 *cmpend[depth] = rep;
337 rep->command = EQCOM;
338 if(rep->ad2.type != A_NONE)
339 quit(AD1MES, linebuf);
343 if(rep->ad1.type != A_NONE)
344 quit(AD0MES, linebuf);
349 while (*cp && *cp != L';' && *cp != L' ' &&
350 *cp != L'\t' && *cp != L'#') {
352 if(tp >= &lab->uninm[8])
357 if (*lab->uninm == L'\0') /* no label? */
358 quit(CGMES, L":", linebuf);
359 if(lpt = search(lab)) {
361 quit("Duplicate labels: %S", linebuf);
366 quit("Too many labels: %S", linebuf);
371 rep--; /* reuse this slot */
376 if(rep->ad2.type != A_NONE)
377 quit(AD1MES, linebuf);
381 quit(CGMES, L"a", linebuf);
383 p = stext(p, addend);
390 quit(CGMES, L"c", linebuf);
392 p = stext(p, addend);
396 if(rep->ad2.type != A_NONE)
397 quit(AD1MES, linebuf);
401 quit(CGMES, L"i", linebuf);
403 p = stext(p, addend);
411 rep->command = CGCOM;
419 rep->command = CHCOM;
431 if(*cp == L'\0' || *cp == L';') {
432 /* no label; jump to end */
433 if(pt = ltab[0].chain) {
434 while((pt1 = pt->lb1) != nil)
442 /* copy label into lab->uninm */
444 while((*tp = *cp++) != L'\0' && *tp != L';')
445 if(++tp >= &lab->uninm[8])
450 if (*lab->uninm == L'\0')
451 /* shouldn't get here */
452 quit(CGMES, L"b or t", linebuf);
453 if((lpt = search(lab)) != nil) {
455 rep->lb1 = lpt->address;
457 for(pt = lpt->chain; pt != nil &&
458 (pt1 = pt->lb1) != nil; pt = pt1)
463 } else { /* add new label */
467 quit("Too many labels: %S", linebuf);
476 rep->command = CNCOM;
484 rep->command = CPCOM;
489 if(rep->ad2.type != A_NONE)
490 quit(AD1MES, linebuf);
492 quit(CGMES, L"r", linebuf);
494 p = stext(p, addend);
502 rep->command = CDCOM;
508 if(rep->ad2.type != A_NONE)
509 quit(AD1MES, linebuf);
519 if ((rep->re1 = compile()) == 0) {
521 quit("First RE may not be null.");
525 if((p = compsub(p, addend)) == 0)
526 quit(CGMES, L"s", linebuf);
546 quit(CGMES, L"s", linebuf);
548 for(i = nfiles - 1; i >= 0; i--)
549 if(cmp(fname[nfiles], fname[i]) == 0) {
550 rep->fcode = fcode[i];
553 if(nfiles >= MAXFILES)
554 quit("Too many files in w commands 1");
555 rep->fcode = open_file(fname[nfiles]);
562 quit(CGMES, L"w", linebuf);
564 for(i = nfiles - 1; i >= 0; i--)
565 if(cmp(fname[nfiles], fname[i]) == 0) {
566 rep->fcode = fcode[i];
569 if(nfiles >= MAXFILES){
570 fprint(2, "sed: Too many files in w commands 2 \n");
571 fprint(2, "nfiles = %d; MAXF = %d\n",
575 rep->fcode = open_file(fname[nfiles]);
586 quit(CGMES, L"y", linebuf);
592 quit("Too many commands, last: %S", linebuf);
596 quit(CGMES, cp - 1, linebuf);
602 open_file(char *name)
607 if ((bp = malloc(sizeof(Biobuf))) == 0)
608 quit("Out of memory");
609 if ((fd = open(name, OWRITE)) < 0 &&
610 (fd = create(name, OWRITE, 0666)) < 0)
611 quit("Cannot create %s", name);
612 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)
689 else if ((prog.bp = Bopen(name, OREAD)) == 0)
690 quit("Cannot open pattern-file: %s\n", name);
695 rline(Rune *buf, Rune *end)
700 while ((c = getrune()) >= 0) {
705 if ((c = getrune()) < 0)
708 } else if (r == '\n') {
726 if (prog.type == P_ARG) {
727 if ((p = prog.curr) != 0) {
729 prog.curr += chartorune(&r, p);
732 c = '\n'; /* fake an end-of-line */
737 } else if ((c = Bgetrune(prog.bp)) < 0)
748 if((c = *cp++) == '$')
752 if (ap->rp = compile())
757 else if (c >= '0' && c <= '9') {
759 while ((c = *cp) >= '0' && c <= '9')
760 lno = lno*10 + *cp++ - '0';
762 quit("line number 0 is illegal",0);
772 cmp(char *a, char *b) /* compare characters */
781 rcmp(Rune *a, Rune *b) /* compare runes */
792 text(char *p) /* extract character string */
796 while(*cp == ' ' || *cp == '\t')
799 if ((r = *cp++) == '\\' && (r = *cp++) == '\0')
802 while (*cp == ' ' || *cp == '\t')
804 p += runetochar(p, &r);
811 stext(Rune *p, Rune *end) /* extract rune string */
813 while(*cp == L' ' || *cp == L'\t')
816 if (*cp == L'\\' && *++cp == L'\0')
819 quit(TMMES, linebuf);
820 if ((*p++ = *cp++) == L'\n')
821 while(*cp == L' ' || *cp == L'\t')
834 for (rp = ltab; rp < ptr; rp++)
835 if(rcmp(rp->uninm, ptr->uninm) == 0)
844 SedCom *rptr, *trptr;
846 for(lptr = ltab; lptr < lab; lptr++) {
847 if(lptr->address == 0)
848 quit("Undefined label: %S", lptr->uninm);
851 while((trptr = rptr->lb1) != nil) {
852 rptr->lb1 = lptr->address;
855 rptr->lb1 = lptr->address;
868 for(tsp = cp; *tsp != seof; tsp++) {
871 if(*tsp == L'\n' || *tsp == L'\0')
877 if ((rp = r->text = (Rune *)malloc(sizeof(Rune) * (highc+2))) == nil)
878 quit("Out of memory");
879 *rp++ = highc; /* save upper bound */
880 for (i = 0; i <= highc; i++)
883 while((c = *sp++) != seof) {
884 if(c == L'\\' && *sp == L'n') {
888 if((rp[c] = *tsp++) == L'\\' && *tsp == L'n') {
892 if(rp[c] == seof || rp[c] == L'\0') {
912 while (spend = gline(linebuf)){
913 for(ipc = pspace; ipc->command; ) {
914 if (!executable(ipc)) {
924 if((ipc = ipc->lb1) == 0)
929 if(!nflag && !delflag)
930 putline(&fout, linebuf, spend - linebuf);
937 /* determine if a statement should be applied to an input line */
939 executable(SedCom *ipc)
941 if (ipc->active) { /* Addr1 satisfied - accept until Addr2 */
942 if (ipc->active == 1) /* Second line */
944 switch(ipc->ad2.type) {
945 case A_NONE: /* No second addr; use first */
948 case A_DOL: /* Accept everything */
950 case A_LINE: /* Line at end of range? */
951 if (lnum <= ipc->ad2.line) {
952 if (ipc->ad2.line == lnum)
956 ipc->active = 0; /* out of range */
958 case A_RE: /* Check for matching R.E. */
959 if (match(ipc->ad2.rp, linebuf))
963 quit("Internal error");
966 switch (ipc->ad1.type) { /* Check first address */
967 case A_NONE: /* Everything matches */
969 case A_DOL: /* Only last line */
973 case A_LINE: /* Check line number */
974 if (ipc->ad1.line == lnum) {
975 ipc->active = 1; /* In range */
979 case A_RE: /* Check R.E. */
980 if (match(ipc->ad1.rp, linebuf)) {
981 ipc->active = 1; /* In range */
986 quit("Internal error");
992 match(Reprog *pattern, Rune *buf)
998 if (rregexec(pattern, linebuf, subexp, MAXSUB) > 0) {
999 loc1 = subexp[0].rsp;
1000 loc2 = subexp[0].rep;
1008 substitute(SedCom *ipc)
1012 if(!match(ipc->re1, linebuf))
1016 * we have at least one match. some patterns, e.g. '$' or '^', can
1017 * produce 0-length matches, so during a global substitute we must
1018 * bump to the character after a 0-length match to keep from looping.
1021 if(ipc->gfl == 0) /* single substitution */
1024 do{ /* global substitution */
1025 len = loc2 - loc1; /* length of match */
1026 dosub(ipc->rhs); /* dosub moves loc2 */
1027 if(*loc2 == 0) /* end of string */
1029 if(len == 0) /* zero-length R.E. match */
1030 loc2++; /* bump over 0-length match */
1031 if(*loc2 == 0) /* end of string */
1033 } while(match(ipc->re1, loc2));
1050 sp = place(sp, loc1, loc2);
1053 if (c == 0xFFFF && (c = *rp++) >= '1' && c < MAXSUB + '0') {
1055 if (subexp[n].rsp && subexp[n].rep) {
1056 sp = place(sp, subexp[n].rsp, subexp[n].rep);
1060 fprint(2, "sed: Invalid back reference \\%d\n",n);
1065 if (sp >= &genbuf[LBSIZE])
1066 fprint(2, "sed: Output line too long.\n");
1069 loc2 = sp - genbuf + linebuf;
1070 while (*sp++ = *lp++)
1071 if (sp >= &genbuf[LBSIZE])
1072 fprint(2, "sed: Output line too long.\n");
1075 while (*lp++ = *sp++)
1081 place(Rune *sp, Rune *l1, Rune *l2)
1085 if (sp >= &genbuf[LBSIZE])
1086 fprint(2, "sed: Output line too long.\n");
1094 static char buf[] = "\\x0000";
1095 static char hex[] = "0123456789abcdef";
1109 buf[2] = hex[(c>>12)&0xF];
1110 buf[3] = hex[(c>>8)&0xF];
1111 buf[4] = hex[(c>>4)&0xF];
1112 buf[5] = hex[c&0xF];
1117 command(SedCom *ipc)
1121 Rune *execp, *p1, *p2, *rp;
1123 switch(ipc->command) {
1126 if(aptr >= abuf+MAXADDS)
1127 quit("sed: Too many appends after line %ld\n",
1133 if(ipc->active == 1) {
1134 for(rp = ipc->text; *rp; rp++)
1135 Bputrune(&fout, *rp);
1144 while(*p1 != '\n') {
1151 while(*p2++ = *p1++)
1157 Bprint(&fout, "%ld\n", lnum);
1162 while(*p1++ = *p2++)
1170 while(*p1++ = *p2++)
1178 while(*p1++ = *p2++);
1185 while(*p1++ = *p2++)
1191 for(rp = ipc->text; *rp; rp++)
1192 Bputrune(&fout, *rp);
1200 for (i = 0, rp = linebuf; *rp; rp++) {
1202 if(c >= 0x20 && c < 0x7F && c != '\\') {
1205 Bprint(&fout, "\\\n");
1209 for (ucp = trans(*rp); *ucp; ucp++){
1213 Bprint(&fout, "\\\n");
1220 Bprint(&fout, "\\n");
1225 putline(&fout, linebuf, spend-linebuf);
1229 if((execp = gline(linebuf)) == 0) {
1239 if((execp = gline(spend)) == 0) {
1246 putline(&fout, linebuf, spend-linebuf);
1250 for(rp = linebuf; *rp && *rp != '\n'; rp++)
1256 putline(&fout, linebuf, spend-linebuf);
1262 if(aptr >= &abuf[MAXADDS])
1263 quit("sed: Too many reads after line %ld\n",
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++);
1322 ecmp(Rune *a, Rune *b, int count)
1339 for (aptr = abuf; *aptr; aptr++) {
1340 if((*aptr)->command == ACOM) {
1341 for(p1 = (*aptr)->text; *p1; p1++ )
1342 Bputrune(&fout, *p1);
1345 for(s = buf, p1 = (*aptr)->text; *p1; p1++)
1346 s += runetochar(s, p1);
1348 if((fi = Bopen(buf, OREAD)) == 0)
1350 while((c = Bgetc(fi)) >= 0)
1366 quit(char *fmt, ...)
1372 ep = msg + sizeof msg;
1373 p = seprint(msg, ep, "sed: ");
1375 p = vseprint(p, ep, fmt, arg);
1377 p = seprint(p, ep, "\n");
1378 write(2, msg, p - msg);
1387 static long peekc = 0;
1389 if (f == 0 && opendata() < 0)
1393 /* Bflush(&fout);********* dumped 4/30/92 - bobf****/
1396 for (c = (peekc? peekc: Bgetrune(f)); c >= 0; c = Bgetrune(f)) {
1398 if ((peekc = Bgetrune(f)) < 0 && fhead == 0)
1406 /* return partial final line, adding implicit newline */
1416 } while (opendata() > 0); /* Switch to next stream */
1422 * Data file input section - the intent is to transparently
1423 * catenate all data input streams.
1426 enroll(char *filename) /* Add a file to the input file cache */
1430 if ((fp = (FileCache *)malloc(sizeof (FileCache))) == nil)
1431 quit("Out of memory");
1438 fp->name = filename; /* 0 => stdin */
1447 if ((f = Bopen(fhead->name, OREAD)) == nil)
1448 quit("Can't open %s", fhead->name);
1450 Binit(&stdin, 0, OREAD);
1453 fhead = fhead->next;