2 * Copyright (c) 1992 Diomidis Spinellis.
3 * Copyright (c) 1992, 1993, 1994
4 * The Regents of the University of California. All rights reserved.
6 * This code is derived from software contributed to Berkeley by
7 * Diomidis Spinellis of Imperial College, University of London.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. All advertising materials mentioning features or use of this software
18 * must display the following acknowledgement:
19 * This product includes software developed by the University of
20 * California, Berkeley and its contributors.
21 * 4. Neither the name of the University nor the names of its contributors
22 * may be used to endorse or promote products derived from this software
23 * without specific prior written permission.
25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40 static char sccsid[] = "@(#)process.c 8.6 (Berkeley) 4/20/94";
42 static const char rcsid[] =
46 #include <sys/types.h>
48 #include <sys/ioctl.h>
65 static SPACE HS, PS, SS;
72 static inline int applies __P((struct s_command *));
73 static void flush_appends __P((void));
74 static void lputs __P((char *));
75 static inline int regexec_e __P((regex_t *, const char *, int, int, size_t));
76 static void regsub __P((SPACE *, char *, char *));
77 static int substitute __P((struct s_command *));
79 struct s_appends *appends; /* Array of pointers to strings to append. */
80 static int appendx; /* Index into appends array. */
81 int appendnum; /* Size of appends array. */
83 static int lastaddr; /* Set by applies if last address of a range. */
84 static int sdone; /* If any substitutes since last line input. */
85 /* Iov structure for 'w' commands. */
86 static regex_t *defpreg;
90 #define OUT(s) { fwrite(s, sizeof(u_char), psl, stdout); }
97 size_t len, oldpsl = 0;
100 for (linenum = 0; mf_fgets(&PS, REPLACE);) {
115 if (appendx >= appendnum)
116 appends = xrealloc(appends,
117 sizeof(struct s_appends) *
119 appends[appendx].type = AP_STRING;
120 appends[appendx].s = cp->t;
121 appends[appendx].len = strlen(cp->t);
130 if (cp->a2 == NULL || lastaddr)
131 (void)printf("%s", cp->t);
139 if ((p = memchr(ps, '\n', psl - 1)) == NULL) {
144 memmove(ps, p + 1, psl);
148 cspace(&PS, hs, hsl, REPLACE);
151 cspace(&PS, hs, hsl, 0);
154 cspace(&HS, ps, psl, REPLACE);
157 cspace(&HS, ps, psl, 0);
160 (void)printf("%s", cp->t);
169 if (!mf_fgets(&PS, REPLACE))
175 if (!mf_fgets(&PS, 0)) {
189 if ((p = memchr(ps, '\n', psl - 1)) != NULL) {
203 if (appendx >= appendnum)
204 appends = xrealloc(appends,
205 sizeof(struct s_appends) *
207 appends[appendx].type = AP_FILE;
208 appends[appendx].s = cp->t;
209 appends[appendx].len = strlen(cp->t);
213 sdone |= substitute(cp);
225 if (cp->u.fd == -1 && (cp->u.fd = open(cp->t,
226 O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
229 if (write(cp->u.fd, ps, psl) != psl)
234 cspace(&HS, "\n", 1, REPLACE);
242 for (p = ps, len = psl; --len; ++p)
243 *p = cp->u.y[(unsigned char)*p];
249 (void)printf("%lu\n", linenum);
254 new: if (!nflag && !pd)
257 } /* for all lines */
261 * TRUE if the address passed matches the current program state
262 * (lastline, linenumber, ps).
265 (a)->type == AT_RE ? regexec_e((a)->u.r, ps, 0, 1, psl) : \
266 (a)->type == AT_LINE ? linenum == (a)->u.l : lastline
269 * Return TRUE if the command applies to the current line. Sets the inrange
270 * flag to process ranges. Interprets the non-select (``!'') flag.
274 struct s_command *cp;
279 if (cp->a1 == NULL && cp->a2 == NULL)
288 } else if (MATCH(cp->a1)) {
290 * If the second address is a number less than or
291 * equal to the line number first selected, only
292 * one line shall be selected.
295 if (cp->a2->type == AT_LINE &&
296 linenum >= cp->a2->u.l)
305 return (cp->nonsel ? ! r : r);
310 * Do substitutions in the pattern space. Currently, we build a
311 * copy of the new pattern space in the substitute space structure
312 * and then swap them.
316 struct s_command *cp;
327 if (defpreg != NULL && cp->u.s->maxbref > defpreg->re_nsub) {
328 linenum = cp->u.s->linenum;
329 errx(1, "%lu: %s: \\%d not defined in the RE",
330 linenum, fname, cp->u.s->maxbref);
333 if (!regexec_e(re, s, 0, 0, psl))
336 SS.len = 0; /* Clean substitute space. */
344 if (lastempty || match[0].rm_so != match[0].rm_eo) {
345 /* Locate start of replaced string. */
346 re_off = match[0].rm_so;
347 /* Copy leading retained string. */
348 cspace(&SS, s, re_off, APPEND);
349 /* Add in regular expression. */
350 regsub(&SS, s, cp->u.s->new);
353 /* Move past this match. */
354 if (match[0].rm_so != match[0].rm_eo) {
356 slen -= match[0].rm_eo;
359 if (match[0].rm_so == 0)
360 cspace(&SS, s, match[0].rm_so + 1,
363 cspace(&SS, s + match[0].rm_so, 1,
365 s += match[0].rm_so + 1;
366 slen -= match[0].rm_so + 1;
369 } while (slen > 0 && regexec_e(re, s, REG_NOTBOL, 0, slen));
370 /* Copy trailing retained string. */
372 cspace(&SS, s, slen, APPEND);
374 default: /* Nth occurrence */
377 slen -= match[0].rm_eo;
378 if (!regexec_e(re, s, REG_NOTBOL, 0, slen))
382 case 1: /* 1st occurrence */
383 /* Locate start of replaced string. */
384 re_off = match[0].rm_so + (s - ps);
385 /* Copy leading retained string. */
386 cspace(&SS, ps, re_off, APPEND);
387 /* Add in regular expression. */
388 regsub(&SS, s, cp->u.s->new);
389 /* Copy trailing retained string. */
391 slen -= match[0].rm_eo;
392 cspace(&SS, s, slen, APPEND);
397 * Swap the substitute space and the pattern space, and make sure
398 * that any leftover pointers into stdio memory get lost.
405 /* Handle the 'p' flag. */
409 /* Handle the 'w' flag. */
410 if (cp->u.s->wfile && !pd) {
411 if (cp->u.s->wfd == -1 && (cp->u.s->wfd = open(cp->u.s->wfile,
412 O_WRONLY|O_APPEND|O_CREAT|O_TRUNC, DEFFILEMODE)) == -1)
413 err(1, "%s", cp->u.s->wfile);
414 if (write(cp->u.s->wfd, ps, psl) != psl)
415 err(1, "%s", cp->u.s->wfile);
421 * Flush append requests. Always called before reading a line,
422 * therefore it also resets the substitution done (sdone) flag.
431 for (i = 0; i < appendx; i++)
432 switch (appends[i].type) {
434 fwrite(appends[i].s, sizeof(char), appends[i].len,
439 * Read files probably shouldn't be cached. Since
440 * it's not an error to read a non-existent file,
441 * it's possible that another program is interacting
442 * with the sed script through the file system. It
443 * would be truly bizarre, but possible. It's probably
444 * not that big a performance win, anyhow.
446 if ((f = fopen(appends[i].s, "r")) == NULL)
448 while ((count = fread(buf, sizeof(char), sizeof(buf), f)))
449 (void)fwrite(buf, sizeof(char), count, stdout);
454 errx(1, "stdout: %s", strerror(errno ? errno : EIO));
463 register char *escapes, *p;
465 static int termwidth = -1;
467 if (termwidth == -1) {
468 if ((p = getenv("COLUMNS")))
470 else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == 0 &&
472 termwidth = win.ws_col;
477 for (count = 0; *s; ++s) {
478 if (count >= termwidth) {
479 (void)printf("\\\n");
482 if (isprint((unsigned char)*s) && *s != '\\') {
486 escapes = "\\\a\b\f\n\r\t\v";
488 if ((p = strchr(escapes, *s))) {
489 (void)putchar("\\abfnrtv"[p - escapes]);
492 (void)printf("%03o", *(u_char *)s);
500 errx(1, "stdout: %s", strerror(errno ? errno : EIO));
504 regexec_e(preg, string, eflags, nomatch, slen)
514 errx(1, "first RE may not be empty");
518 /* Set anchors, discounting trailing newline (if any). */
519 if (slen > 0 && string[slen - 1] == '\n')
522 match[0].rm_eo = slen;
524 eval = regexec(defpreg, string,
525 nomatch ? 0 : maxnsub + 1, match, eflags | REG_STARTEND);
532 errx(1, "RE error: %s", strregerror(eval, defpreg));
537 * regsub - perform substitutions after a regexp match
538 * Based on a routine by Henry Spencer
541 regsub(sp, string, src)
545 register int len, no;
546 register char c, *dst;
548 #define NEEDSP(reqlen) \
549 if (sp->len >= sp->blen - (reqlen) - 1) { \
550 sp->blen += (reqlen) + 1024; \
551 sp->space = sp->back = xrealloc(sp->back, sp->blen); \
552 dst = sp->space + sp->len; \
555 dst = sp->space + sp->len;
556 while ((c = *src++) != '\0') {
559 else if (c == '\\' && isdigit((unsigned char)*src))
563 if (no < 0) { /* Ordinary character. */
564 if (c == '\\' && (*src == '\\' || *src == '&'))
569 } else if (match[no].rm_so != -1 && match[no].rm_eo != -1) {
570 len = match[no].rm_eo - match[no].rm_so;
572 memmove(dst, string + match[no].rm_so, len);
583 * Append the source space to the destination space, allocating new
584 * space as necessary.
587 cspace(sp, p, len, spflag)
591 enum e_spflag spflag;
595 /* Make sure SPACE has enough memory and ramp up quickly. */
596 tlen = sp->len + len + 1;
597 if (tlen > sp->blen) {
598 sp->blen = tlen + 1024;
599 sp->space = sp->back = xrealloc(sp->back, sp->blen);
602 if (spflag == REPLACE)
605 memmove(sp->space + sp->len, p, len);
607 sp->space[sp->len += len] = '\0';
611 * Close all cached opened files and report any errors
615 register struct s_command *cp, *end;
618 for (; cp != end; cp = cp->next)
621 if (cp->u.s->wfd != -1 && close(cp->u.s->wfd))
622 err(1, "%s", cp->u.s->wfile);
626 if (cp->u.fd != -1 && close(cp->u.fd))
631 cfclose(cp->u.c, cp->next);