Home | History | Annotate | Line # | Download | only in sed
process.c revision 1.36
      1  1.36  christos /*	$NetBSD: process.c,v 1.36 2006/04/02 03:40:06 christos Exp $	*/
      2  1.18       tls 
      3   1.1       alm /*-
      4  1.19       mrg  * Copyright (c) 1992, 1993, 1994
      5   1.8       cgd  *	The Regents of the University of California.  All rights reserved.
      6   1.1       alm  *
      7   1.1       alm  * This code is derived from software contributed to Berkeley by
      8   1.1       alm  * Diomidis Spinellis of Imperial College, University of London.
      9   1.1       alm  *
     10   1.1       alm  * Redistribution and use in source and binary forms, with or without
     11   1.1       alm  * modification, are permitted provided that the following conditions
     12   1.1       alm  * are met:
     13   1.1       alm  * 1. Redistributions of source code must retain the above copyright
     14   1.1       alm  *    notice, this list of conditions and the following disclaimer.
     15   1.1       alm  * 2. Redistributions in binary form must reproduce the above copyright
     16   1.1       alm  *    notice, this list of conditions and the following disclaimer in the
     17   1.1       alm  *    documentation and/or other materials provided with the distribution.
     18  1.33       agc  * 3. Neither the name of the University nor the names of its contributors
     19  1.33       agc  *    may be used to endorse or promote products derived from this software
     20  1.33       agc  *    without specific prior written permission.
     21  1.33       agc  *
     22  1.33       agc  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     23  1.33       agc  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     24  1.33       agc  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     25  1.33       agc  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     26  1.33       agc  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     27  1.33       agc  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     28  1.33       agc  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     29  1.33       agc  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     30  1.33       agc  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     31  1.33       agc  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     32  1.33       agc  * SUCH DAMAGE.
     33  1.33       agc  */
     34  1.33       agc 
     35  1.33       agc /*-
     36  1.33       agc  * Copyright (c) 1992 Diomidis Spinellis.
     37  1.33       agc  *
     38  1.33       agc  * This code is derived from software contributed to Berkeley by
     39  1.33       agc  * Diomidis Spinellis of Imperial College, University of London.
     40  1.33       agc  *
     41  1.33       agc  * Redistribution and use in source and binary forms, with or without
     42  1.33       agc  * modification, are permitted provided that the following conditions
     43  1.33       agc  * are met:
     44  1.33       agc  * 1. Redistributions of source code must retain the above copyright
     45  1.33       agc  *    notice, this list of conditions and the following disclaimer.
     46  1.33       agc  * 2. Redistributions in binary form must reproduce the above copyright
     47  1.33       agc  *    notice, this list of conditions and the following disclaimer in the
     48  1.33       agc  *    documentation and/or other materials provided with the distribution.
     49   1.1       alm  * 3. All advertising materials mentioning features or use of this software
     50   1.1       alm  *    must display the following acknowledgement:
     51   1.1       alm  *	This product includes software developed by the University of
     52   1.1       alm  *	California, Berkeley and its contributors.
     53   1.1       alm  * 4. Neither the name of the University nor the names of its contributors
     54   1.1       alm  *    may be used to endorse or promote products derived from this software
     55   1.1       alm  *    without specific prior written permission.
     56   1.1       alm  *
     57   1.1       alm  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     58   1.1       alm  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     59   1.1       alm  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     60   1.1       alm  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     61   1.1       alm  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     62   1.1       alm  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     63   1.1       alm  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     64   1.1       alm  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     65   1.1       alm  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     66   1.1       alm  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     67   1.1       alm  * SUCH DAMAGE.
     68   1.1       alm  */
     69   1.1       alm 
     70  1.20     lukem #include <sys/cdefs.h>
     71   1.1       alm #ifndef lint
     72  1.19       mrg #if 0
     73  1.19       mrg static char sccsid[] = "@(#)process.c	8.6 (Berkeley) 4/20/94";
     74  1.19       mrg #else
     75  1.36  christos __RCSID("$NetBSD: process.c,v 1.36 2006/04/02 03:40:06 christos Exp $");
     76  1.19       mrg #endif
     77   1.1       alm #endif /* not lint */
     78   1.1       alm 
     79   1.1       alm #include <sys/types.h>
     80   1.1       alm #include <sys/stat.h>
     81   1.1       alm #include <sys/ioctl.h>
     82   1.1       alm #include <sys/uio.h>
     83   1.1       alm 
     84   1.1       alm #include <ctype.h>
     85   1.1       alm #include <errno.h>
     86   1.1       alm #include <fcntl.h>
     87   1.1       alm #include <limits.h>
     88   1.1       alm #include <regex.h>
     89   1.1       alm #include <stdio.h>
     90   1.1       alm #include <stdlib.h>
     91   1.1       alm #include <string.h>
     92   1.1       alm #include <unistd.h>
     93   1.1       alm 
     94   1.1       alm #include "defs.h"
     95   1.1       alm #include "extern.h"
     96   1.1       alm 
     97   1.8       cgd static SPACE HS, PS, SS;
     98   1.1       alm #define	pd		PS.deleted
     99   1.1       alm #define	ps		PS.space
    100   1.1       alm #define	psl		PS.len
    101   1.1       alm #define	hs		HS.space
    102   1.1       alm #define	hsl		HS.len
    103   1.1       alm 
    104  1.32       wiz static inline int	 applies(struct s_command *);
    105  1.32       wiz static void		 flush_appends(void);
    106  1.32       wiz static void		 lputs(char *);
    107  1.32       wiz static inline int	 regexec_e(regex_t *, const char *, int, int, size_t);
    108  1.32       wiz static void		 regsub(SPACE *, char *, char *);
    109  1.32       wiz static int		 substitute(struct s_command *);
    110   1.1       alm 
    111   1.1       alm struct s_appends *appends;	/* Array of pointers to strings to append. */
    112   1.1       alm static int appendx;		/* Index into appends array. */
    113   1.1       alm int appendnum;			/* Size of appends array. */
    114   1.1       alm 
    115   1.1       alm static int lastaddr;		/* Set by applies if last address of a range. */
    116   1.1       alm static int sdone;		/* If any substitutes since last line input. */
    117   1.1       alm 				/* Iov structure for 'w' commands. */
    118   1.1       alm static regex_t *defpreg;
    119   1.1       alm size_t maxnsub;
    120   1.1       alm regmatch_t *match;
    121   1.1       alm 
    122   1.8       cgd #define OUT(s) { fwrite(s, sizeof(u_char), psl, stdout); }
    123   1.8       cgd 
    124   1.1       alm void
    125  1.32       wiz process(void)
    126   1.1       alm {
    127   1.1       alm 	struct s_command *cp;
    128   1.1       alm 	SPACE tspace;
    129  1.15   mycroft 	size_t len, oldpsl;
    130  1.15   mycroft 	char *p;
    131   1.1       alm 
    132  1.20     lukem 	oldpsl = 0;
    133   1.1       alm 	for (linenum = 0; mf_fgets(&PS, REPLACE);) {
    134   1.1       alm 		pd = 0;
    135  1.16   mycroft top:
    136   1.1       alm 		cp = prog;
    137   1.1       alm redirect:
    138   1.1       alm 		while (cp != NULL) {
    139   1.1       alm 			if (!applies(cp)) {
    140   1.1       alm 				cp = cp->next;
    141   1.1       alm 				continue;
    142   1.1       alm 			}
    143   1.1       alm 			switch (cp->code) {
    144   1.1       alm 			case '{':
    145   1.1       alm 				cp = cp->u.c;
    146   1.1       alm 				goto redirect;
    147   1.1       alm 			case 'a':
    148  1.35    itojun 				if (appendx >= appendnum) {
    149   1.1       alm 					appends = xrealloc(appends,
    150   1.1       alm 					    sizeof(struct s_appends) *
    151  1.35    itojun 					    (appendnum * 2));
    152  1.35    itojun 					appendnum *= 2;
    153  1.35    itojun 				}
    154   1.1       alm 				appends[appendx].type = AP_STRING;
    155   1.1       alm 				appends[appendx].s = cp->t;
    156   1.8       cgd 				appends[appendx].len = strlen(cp->t);
    157   1.1       alm 				appendx++;
    158   1.1       alm 				break;
    159   1.1       alm 			case 'b':
    160   1.1       alm 				cp = cp->u.c;
    161   1.1       alm 				goto redirect;
    162   1.1       alm 			case 'c':
    163   1.1       alm 				pd = 1;
    164   1.1       alm 				psl = 0;
    165   1.1       alm 				if (cp->a2 == NULL || lastaddr)
    166   1.1       alm 					(void)printf("%s", cp->t);
    167   1.1       alm 				break;
    168   1.1       alm 			case 'd':
    169   1.1       alm 				pd = 1;
    170   1.1       alm 				goto new;
    171   1.1       alm 			case 'D':
    172  1.30    atatat 				if (psl == 0)
    173  1.30    atatat 					pd = 1;
    174   1.1       alm 				if (pd)
    175   1.1       alm 					goto new;
    176  1.16   mycroft 				if ((p = memchr(ps, '\n', psl - 1)) == NULL) {
    177   1.1       alm 					pd = 1;
    178  1.16   mycroft 					goto new;
    179  1.28    atatat 				} else {
    180  1.13   mycroft 					psl -= (p + 1) - ps;
    181   1.1       alm 					memmove(ps, p + 1, psl);
    182  1.28    atatat 					goto top;
    183   1.1       alm 				}
    184   1.1       alm 			case 'g':
    185   1.1       alm 				cspace(&PS, hs, hsl, REPLACE);
    186   1.1       alm 				break;
    187   1.1       alm 			case 'G':
    188  1.25       kim 				if (hs == NULL)
    189  1.25       kim 					cspace(&HS, "\n", 1, REPLACE);
    190   1.8       cgd 				cspace(&PS, hs, hsl, 0);
    191   1.1       alm 				break;
    192   1.1       alm 			case 'h':
    193   1.1       alm 				cspace(&HS, ps, psl, REPLACE);
    194   1.1       alm 				break;
    195   1.1       alm 			case 'H':
    196   1.8       cgd 				cspace(&HS, ps, psl, 0);
    197   1.1       alm 				break;
    198   1.1       alm 			case 'i':
    199   1.1       alm 				(void)printf("%s", cp->t);
    200   1.1       alm 				break;
    201   1.1       alm 			case 'l':
    202   1.1       alm 				lputs(ps);
    203   1.1       alm 				break;
    204   1.1       alm 			case 'n':
    205   1.1       alm 				if (!nflag && !pd)
    206   1.8       cgd 					OUT(ps)
    207   1.1       alm 				flush_appends();
    208  1.14   mycroft 				if (!mf_fgets(&PS, REPLACE))
    209   1.1       alm 					exit(0);
    210   1.1       alm 				pd = 0;
    211   1.1       alm 				break;
    212   1.1       alm 			case 'N':
    213   1.1       alm 				flush_appends();
    214   1.8       cgd 				if (!mf_fgets(&PS, 0)) {
    215   1.1       alm 					if (!nflag && !pd)
    216   1.8       cgd 						OUT(ps)
    217   1.1       alm 					exit(0);
    218   1.1       alm 				}
    219   1.1       alm 				break;
    220   1.1       alm 			case 'p':
    221   1.1       alm 				if (pd)
    222   1.1       alm 					break;
    223   1.8       cgd 				OUT(ps)
    224   1.1       alm 				break;
    225   1.1       alm 			case 'P':
    226   1.1       alm 				if (pd)
    227   1.1       alm 					break;
    228  1.15   mycroft 				if ((p = memchr(ps, '\n', psl - 1)) != NULL) {
    229  1.15   mycroft 					oldpsl = psl;
    230  1.15   mycroft 					psl = (p + 1) - ps;
    231   1.1       alm 				}
    232   1.8       cgd 				OUT(ps)
    233   1.1       alm 				if (p != NULL)
    234  1.15   mycroft 					psl = oldpsl;
    235   1.1       alm 				break;
    236   1.1       alm 			case 'q':
    237   1.1       alm 				if (!nflag && !pd)
    238   1.8       cgd 					OUT(ps)
    239   1.1       alm 				flush_appends();
    240   1.1       alm 				exit(0);
    241   1.1       alm 			case 'r':
    242  1.35    itojun 				if (appendx >= appendnum) {
    243   1.1       alm 					appends = xrealloc(appends,
    244   1.1       alm 					    sizeof(struct s_appends) *
    245  1.35    itojun 					    (appendnum * 2));
    246  1.35    itojun 					appendnum *= 2;
    247  1.35    itojun 				}
    248   1.1       alm 				appends[appendx].type = AP_FILE;
    249   1.1       alm 				appends[appendx].s = cp->t;
    250   1.8       cgd 				appends[appendx].len = strlen(cp->t);
    251   1.1       alm 				appendx++;
    252   1.1       alm 				break;
    253   1.1       alm 			case 's':
    254   1.1       alm 				sdone |= substitute(cp);
    255   1.1       alm 				break;
    256   1.1       alm 			case 't':
    257   1.1       alm 				if (sdone) {
    258   1.1       alm 					sdone = 0;
    259   1.1       alm 					cp = cp->u.c;
    260   1.1       alm 					goto redirect;
    261   1.1       alm 				}
    262   1.1       alm 				break;
    263   1.1       alm 			case 'w':
    264   1.1       alm 				if (pd)
    265   1.1       alm 					break;
    266   1.1       alm 				if (cp->u.fd == -1 && (cp->u.fd = open(cp->t,
    267   1.1       alm 				    O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
    268   1.1       alm 				    DEFFILEMODE)) == -1)
    269  1.31    itojun 					err(FATAL, "%s: %s",
    270   1.1       alm 					    cp->t, strerror(errno));
    271   1.8       cgd 				if (write(cp->u.fd, ps, psl) != psl)
    272  1.31    itojun 					err(FATAL, "%s: %s",
    273   1.1       alm 					    cp->t, strerror(errno));
    274   1.1       alm 				break;
    275   1.1       alm 			case 'x':
    276   1.8       cgd 				if (hs == NULL)
    277  1.17       cgd 					cspace(&HS, "\n", 1, REPLACE);
    278   1.1       alm 				tspace = PS;
    279   1.1       alm 				PS = HS;
    280   1.1       alm 				HS = tspace;
    281   1.1       alm 				break;
    282   1.1       alm 			case 'y':
    283   1.1       alm 				if (pd)
    284   1.1       alm 					break;
    285   1.8       cgd 				for (p = ps, len = psl; --len; ++p)
    286  1.22       mrg 					*p = cp->u.y[(int)*p];
    287   1.1       alm 				break;
    288   1.1       alm 			case ':':
    289   1.1       alm 			case '}':
    290   1.1       alm 				break;
    291   1.1       alm 			case '=':
    292   1.1       alm 				(void)printf("%lu\n", linenum);
    293   1.1       alm 			}
    294   1.1       alm 			cp = cp->next;
    295   1.1       alm 		} /* for all cp */
    296   1.1       alm 
    297   1.1       alm new:		if (!nflag && !pd)
    298   1.8       cgd 			OUT(ps)
    299   1.1       alm 		flush_appends();
    300   1.1       alm 	} /* for all lines */
    301   1.1       alm }
    302   1.1       alm 
    303   1.1       alm /*
    304   1.1       alm  * TRUE if the address passed matches the current program state
    305   1.1       alm  * (lastline, linenumber, ps).
    306   1.1       alm  */
    307   1.8       cgd #define	MATCH(a)						\
    308   1.8       cgd 	(a)->type == AT_RE ? regexec_e((a)->u.r, ps, 0, 1, psl) :	\
    309   1.1       alm 	    (a)->type == AT_LINE ? linenum == (a)->u.l : lastline
    310   1.1       alm 
    311   1.1       alm /*
    312   1.1       alm  * Return TRUE if the command applies to the current line.  Sets the inrange
    313   1.1       alm  * flag to process ranges.  Interprets the non-select (``!'') flag.
    314   1.1       alm  */
    315   1.1       alm static inline int
    316  1.32       wiz applies(struct s_command *cp)
    317   1.1       alm {
    318   1.1       alm 	int r;
    319   1.1       alm 
    320   1.1       alm 	lastaddr = 0;
    321   1.1       alm 	if (cp->a1 == NULL && cp->a2 == NULL)
    322   1.1       alm 		r = 1;
    323  1.24  christos 	else if (cp->a2) {
    324   1.1       alm 		if (cp->inrange) {
    325   1.1       alm 			if (MATCH(cp->a2)) {
    326   1.1       alm 				cp->inrange = 0;
    327   1.1       alm 				lastaddr = 1;
    328   1.1       alm 			}
    329   1.1       alm 			r = 1;
    330  1.36  christos 		} else if (cp->a1 && MATCH(cp->a1)) {
    331   1.1       alm 			/*
    332   1.1       alm 			 * If the second address is a number less than or
    333   1.1       alm 			 * equal to the line number first selected, only
    334   1.1       alm 			 * one line shall be selected.
    335   1.1       alm 			 *	-- POSIX 1003.2
    336   1.1       alm 			 */
    337   1.1       alm 			if (cp->a2->type == AT_LINE &&
    338   1.1       alm 			    linenum >= cp->a2->u.l)
    339   1.1       alm 				lastaddr = 1;
    340   1.1       alm 			else
    341   1.1       alm 				cp->inrange = 1;
    342   1.1       alm 			r = 1;
    343   1.1       alm 		} else
    344   1.1       alm 			r = 0;
    345  1.24  christos 	} else
    346   1.1       alm 		r = MATCH(cp->a1);
    347   1.1       alm 	return (cp->nonsel ? ! r : r);
    348   1.1       alm }
    349   1.1       alm 
    350   1.1       alm /*
    351   1.1       alm  * substitute --
    352   1.1       alm  *	Do substitutions in the pattern space.  Currently, we build a
    353   1.1       alm  *	copy of the new pattern space in the substitute space structure
    354   1.1       alm  *	and then swap them.
    355   1.1       alm  */
    356   1.1       alm static int
    357  1.32       wiz substitute(struct s_command *cp)
    358   1.1       alm {
    359   1.1       alm 	SPACE tspace;
    360   1.1       alm 	regex_t *re;
    361   1.8       cgd 	size_t re_off, slen;
    362  1.19       mrg 	int lastempty, n;
    363   1.1       alm 	char *s;
    364   1.1       alm 
    365   1.1       alm 	s = ps;
    366   1.1       alm 	re = cp->u.s->re;
    367   1.1       alm 	if (re == NULL) {
    368   1.1       alm 		if (defpreg != NULL && cp->u.s->maxbref > defpreg->re_nsub) {
    369   1.1       alm 			linenum = cp->u.s->linenum;
    370   1.1       alm 			err(COMPILE, "\\%d not defined in the RE",
    371   1.1       alm 			    cp->u.s->maxbref);
    372   1.1       alm 		}
    373   1.1       alm 	}
    374   1.8       cgd 	if (!regexec_e(re, s, 0, 0, psl))
    375   1.1       alm 		return (0);
    376   1.1       alm 
    377   1.1       alm 	SS.len = 0;				/* Clean substitute space. */
    378   1.8       cgd 	slen = psl;
    379   1.1       alm 	n = cp->u.s->n;
    380  1.12       cgd 	lastempty = 1;
    381  1.12       cgd 
    382   1.1       alm 	switch (n) {
    383   1.1       alm 	case 0:					/* Global */
    384   1.1       alm 		do {
    385  1.12       cgd 			if (lastempty || match[0].rm_so != match[0].rm_eo) {
    386  1.12       cgd 				/* Locate start of replaced string. */
    387  1.12       cgd 				re_off = match[0].rm_so;
    388  1.12       cgd 				/* Copy leading retained string. */
    389  1.12       cgd 				cspace(&SS, s, re_off, APPEND);
    390  1.12       cgd 				/* Add in regular expression. */
    391  1.12       cgd 				regsub(&SS, s, cp->u.s->new);
    392  1.12       cgd 			}
    393  1.12       cgd 
    394   1.1       alm 			/* Move past this match. */
    395  1.12       cgd 			if (match[0].rm_so != match[0].rm_eo) {
    396  1.12       cgd 				s += match[0].rm_eo;
    397  1.12       cgd 				slen -= match[0].rm_eo;
    398  1.12       cgd 				lastempty = 0;
    399  1.12       cgd 			} else {
    400  1.12       cgd 				if (match[0].rm_so == 0)
    401  1.19       mrg 					cspace(&SS,
    402  1.19       mrg 					    s, match[0].rm_so + 1, APPEND);
    403  1.12       cgd 				else
    404  1.19       mrg 					cspace(&SS,
    405  1.19       mrg 					    s + match[0].rm_so, 1, APPEND);
    406  1.12       cgd 				s += match[0].rm_so + 1;
    407  1.12       cgd 				slen -= match[0].rm_so + 1;
    408  1.12       cgd 				lastempty = 1;
    409  1.12       cgd 			}
    410  1.12       cgd 		} while (slen > 0 && regexec_e(re, s, REG_NOTBOL, 0, slen));
    411   1.1       alm 		/* Copy trailing retained string. */
    412  1.12       cgd 		if (slen > 0)
    413  1.12       cgd 			cspace(&SS, s, slen, APPEND);
    414   1.1       alm 		break;
    415   1.1       alm 	default:				/* Nth occurrence */
    416   1.1       alm 		while (--n) {
    417   1.1       alm 			s += match[0].rm_eo;
    418   1.8       cgd 			slen -= match[0].rm_eo;
    419   1.8       cgd 			if (!regexec_e(re, s, REG_NOTBOL, 0, slen))
    420   1.1       alm 				return (0);
    421   1.1       alm 		}
    422   1.1       alm 		/* FALLTHROUGH */
    423   1.1       alm 	case 1:					/* 1st occurrence */
    424   1.1       alm 		/* Locate start of replaced string. */
    425   1.1       alm 		re_off = match[0].rm_so + (s - ps);
    426   1.1       alm 		/* Copy leading retained string. */
    427   1.1       alm 		cspace(&SS, ps, re_off, APPEND);
    428   1.1       alm 		/* Add in regular expression. */
    429   1.1       alm 		regsub(&SS, s, cp->u.s->new);
    430   1.1       alm 		/* Copy trailing retained string. */
    431   1.1       alm 		s += match[0].rm_eo;
    432   1.8       cgd 		slen -= match[0].rm_eo;
    433   1.8       cgd 		cspace(&SS, s, slen, APPEND);
    434   1.1       alm 		break;
    435   1.1       alm 	}
    436   1.1       alm 
    437   1.1       alm 	/*
    438   1.1       alm 	 * Swap the substitute space and the pattern space, and make sure
    439   1.1       alm 	 * that any leftover pointers into stdio memory get lost.
    440   1.1       alm 	 */
    441   1.1       alm 	tspace = PS;
    442   1.1       alm 	PS = SS;
    443   1.1       alm 	SS = tspace;
    444   1.1       alm 	SS.space = SS.back;
    445   1.1       alm 
    446   1.1       alm 	/* Handle the 'p' flag. */
    447   1.1       alm 	if (cp->u.s->p)
    448   1.8       cgd 		OUT(ps)
    449   1.1       alm 
    450   1.1       alm 	/* Handle the 'w' flag. */
    451   1.1       alm 	if (cp->u.s->wfile && !pd) {
    452   1.1       alm 		if (cp->u.s->wfd == -1 && (cp->u.s->wfd = open(cp->u.s->wfile,
    453   1.1       alm 		    O_WRONLY|O_APPEND|O_CREAT|O_TRUNC, DEFFILEMODE)) == -1)
    454  1.31    itojun 			err(FATAL, "%s: %s", cp->u.s->wfile, strerror(errno));
    455   1.8       cgd 		if (write(cp->u.s->wfd, ps, psl) != psl)
    456  1.31    itojun 			err(FATAL, "%s: %s", cp->u.s->wfile, strerror(errno));
    457   1.1       alm 	}
    458   1.1       alm 	return (1);
    459   1.1       alm }
    460   1.1       alm 
    461   1.1       alm /*
    462   1.1       alm  * Flush append requests.  Always called before reading a line,
    463   1.1       alm  * therefore it also resets the substitution done (sdone) flag.
    464   1.1       alm  */
    465   1.1       alm static void
    466  1.32       wiz flush_appends(void)
    467   1.1       alm {
    468   1.1       alm 	FILE *f;
    469   1.1       alm 	int count, i;
    470   1.1       alm 	char buf[8 * 1024];
    471   1.1       alm 
    472   1.1       alm 	for (i = 0; i < appendx; i++)
    473   1.1       alm 		switch (appends[i].type) {
    474   1.1       alm 		case AP_STRING:
    475   1.8       cgd 			fwrite(appends[i].s, sizeof(char), appends[i].len,
    476   1.8       cgd 			    stdout);
    477   1.1       alm 			break;
    478   1.1       alm 		case AP_FILE:
    479   1.1       alm 			/*
    480   1.1       alm 			 * Read files probably shouldn't be cached.  Since
    481   1.1       alm 			 * it's not an error to read a non-existent file,
    482   1.1       alm 			 * it's possible that another program is interacting
    483   1.1       alm 			 * with the sed script through the file system.  It
    484   1.1       alm 			 * would be truly bizarre, but possible.  It's probably
    485   1.1       alm 			 * not that big a performance win, anyhow.
    486   1.1       alm 			 */
    487   1.1       alm 			if ((f = fopen(appends[i].s, "r")) == NULL)
    488   1.1       alm 				break;
    489  1.20     lukem 			while ((count =
    490  1.21   thorpej 			    fread(buf, sizeof(char), sizeof(buf), f)) > 0)
    491   1.8       cgd 				(void)fwrite(buf, sizeof(char), count, stdout);
    492   1.1       alm 			(void)fclose(f);
    493   1.1       alm 			break;
    494   1.1       alm 		}
    495   1.1       alm 	if (ferror(stdout))
    496   1.1       alm 		err(FATAL, "stdout: %s", strerror(errno ? errno : EIO));
    497   1.1       alm 	appendx = sdone = 0;
    498   1.1       alm }
    499   1.1       alm 
    500   1.1       alm static void
    501  1.32       wiz lputs(char *s)
    502   1.1       alm {
    503  1.20     lukem 	int count;
    504  1.20     lukem 	char *escapes, *p;
    505   1.1       alm 	struct winsize win;
    506   1.1       alm 	static int termwidth = -1;
    507   1.1       alm 
    508  1.23      ross 	if (termwidth == -1) {
    509  1.20     lukem 		if ((p = getenv("COLUMNS")) != NULL)
    510   1.1       alm 			termwidth = atoi(p);
    511   1.1       alm 		else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == 0 &&
    512   1.1       alm 		    win.ws_col > 0)
    513   1.1       alm 			termwidth = win.ws_col;
    514   1.1       alm 		else
    515   1.1       alm 			termwidth = 60;
    516  1.23      ross 	}
    517   1.1       alm 	for (count = 0; *s; ++s) {
    518   1.1       alm 		if (count >= termwidth) {
    519   1.1       alm 			(void)printf("\\\n");
    520   1.1       alm 			count = 0;
    521   1.1       alm 		}
    522  1.24  christos 		if (isascii((unsigned char)*s) && isprint((unsigned char)*s) &&
    523  1.24  christos 		    *s != '\\') {
    524   1.1       alm 			(void)putchar(*s);
    525   1.1       alm 			count++;
    526   1.1       alm 		} else {
    527   1.1       alm 			escapes = "\\\a\b\f\n\r\t\v";
    528   1.1       alm 			(void)putchar('\\');
    529  1.20     lukem 			if ((p = strchr(escapes, *s)) != NULL) {
    530   1.1       alm 				(void)putchar("\\abfnrtv"[p - escapes]);
    531   1.1       alm 				count += 2;
    532   1.1       alm 			} else {
    533   1.8       cgd 				(void)printf("%03o", *(u_char *)s);
    534   1.1       alm 				count += 4;
    535   1.1       alm 			}
    536   1.1       alm 		}
    537   1.1       alm 	}
    538   1.1       alm 	(void)putchar('$');
    539   1.1       alm 	(void)putchar('\n');
    540   1.1       alm 	if (ferror(stdout))
    541   1.1       alm 		err(FATAL, "stdout: %s", strerror(errno ? errno : EIO));
    542   1.1       alm }
    543   1.1       alm 
    544   1.1       alm static inline int
    545  1.32       wiz regexec_e(regex_t *preg, const char *string, int eflags, int nomatch, size_t slen)
    546   1.1       alm {
    547   1.1       alm 	int eval;
    548  1.24  christos #ifndef REG_STARTEND
    549  1.24  christos 	char *buf;
    550  1.24  christos #endif
    551   1.8       cgd 
    552   1.1       alm 	if (preg == NULL) {
    553   1.1       alm 		if (defpreg == NULL)
    554   1.1       alm 			err(FATAL, "first RE may not be empty");
    555   1.1       alm 	} else
    556   1.1       alm 		defpreg = preg;
    557   1.1       alm 
    558   1.8       cgd 	/* Set anchors, discounting trailing newline (if any). */
    559   1.8       cgd 	if (slen > 0 && string[slen - 1] == '\n')
    560   1.8       cgd 		slen--;
    561  1.24  christos 
    562  1.24  christos #ifndef REG_STARTEND
    563  1.24  christos 	if ((buf = malloc(slen + 1)) == NULL)
    564  1.26  drochner 		err(1, NULL);
    565  1.24  christos 	(void)memcpy(buf, string, slen);
    566  1.24  christos 	buf[slen] = '\0';
    567  1.24  christos 	eval = regexec(defpreg, buf,
    568  1.24  christos 	    nomatch ? 0 : maxnsub + 1, match, eflags);
    569  1.24  christos 	free(buf);
    570  1.24  christos #else
    571   1.8       cgd 	match[0].rm_so = 0;
    572   1.8       cgd 	match[0].rm_eo = slen;
    573   1.1       alm 	eval = regexec(defpreg, string,
    574   1.8       cgd 	    nomatch ? 0 : maxnsub + 1, match, eflags | REG_STARTEND);
    575  1.24  christos #endif
    576   1.1       alm 	switch(eval) {
    577   1.1       alm 	case 0:
    578   1.1       alm 		return (1);
    579   1.1       alm 	case REG_NOMATCH:
    580   1.1       alm 		return (0);
    581   1.1       alm 	}
    582   1.1       alm 	err(FATAL, "RE error: %s", strregerror(eval, defpreg));
    583   1.1       alm 	/* NOTREACHED */
    584  1.20     lukem 	return (0);
    585   1.1       alm }
    586   1.1       alm 
    587   1.1       alm /*
    588   1.1       alm  * regsub - perform substitutions after a regexp match
    589   1.1       alm  * Based on a routine by Henry Spencer
    590   1.1       alm  */
    591   1.1       alm static void
    592  1.32       wiz regsub(SPACE *sp, char *string, char *src)
    593   1.1       alm {
    594  1.20     lukem 	int len, no;
    595  1.20     lukem 	char c, *dst;
    596   1.1       alm 
    597   1.1       alm #define	NEEDSP(reqlen)							\
    598  1.34    itojun 	if (sp->len + (reqlen) + 1 >= sp->blen) {			\
    599  1.35    itojun 		size_t newlen = sp->blen + (reqlen) + 1024;		\
    600  1.35    itojun 		sp->space = sp->back = xrealloc(sp->back, newlen);	\
    601  1.35    itojun 		sp->blen = newlen;					\
    602   1.1       alm 		dst = sp->space + sp->len;				\
    603   1.1       alm 	}
    604   1.1       alm 
    605   1.1       alm 	dst = sp->space + sp->len;
    606   1.1       alm 	while ((c = *src++) != '\0') {
    607   1.1       alm 		if (c == '&')
    608   1.1       alm 			no = 0;
    609  1.24  christos 		else if (c == '\\' && isdigit((unsigned char)*src))
    610   1.1       alm 			no = *src++ - '0';
    611   1.1       alm 		else
    612   1.1       alm 			no = -1;
    613   1.1       alm 		if (no < 0) {		/* Ordinary character. */
    614   1.1       alm  			if (c == '\\' && (*src == '\\' || *src == '&'))
    615   1.1       alm  				c = *src++;
    616   1.1       alm 			NEEDSP(1);
    617   1.1       alm  			*dst++ = c;
    618   1.1       alm 			++sp->len;
    619   1.1       alm  		} else if (match[no].rm_so != -1 && match[no].rm_eo != -1) {
    620   1.1       alm 			len = match[no].rm_eo - match[no].rm_so;
    621   1.1       alm 			NEEDSP(len);
    622   1.1       alm 			memmove(dst, string + match[no].rm_so, len);
    623   1.1       alm 			dst += len;
    624   1.1       alm 			sp->len += len;
    625   1.1       alm 		}
    626   1.1       alm 	}
    627   1.1       alm 	NEEDSP(1);
    628   1.1       alm 	*dst = '\0';
    629   1.1       alm }
    630   1.1       alm 
    631   1.1       alm /*
    632   1.1       alm  * aspace --
    633   1.1       alm  *	Append the source space to the destination space, allocating new
    634   1.1       alm  *	space as necessary.
    635   1.1       alm  */
    636   1.1       alm void
    637  1.32       wiz cspace(SPACE *sp, char *p, size_t len, enum e_spflag spflag)
    638   1.1       alm {
    639   1.1       alm 	size_t tlen;
    640   1.1       alm 
    641   1.8       cgd 	/* Make sure SPACE has enough memory and ramp up quickly. */
    642   1.8       cgd 	tlen = sp->len + len + 1;
    643   1.1       alm 	if (tlen > sp->blen) {
    644  1.35    itojun 		size_t newlen = tlen + 1024;
    645  1.35    itojun 		sp->space = sp->back = xrealloc(sp->back, newlen);
    646  1.35    itojun 		sp->blen = newlen;
    647   1.1       alm 	}
    648   1.1       alm 
    649   1.8       cgd 	if (spflag == REPLACE)
    650   1.1       alm 		sp->len = 0;
    651   1.1       alm 
    652   1.1       alm 	memmove(sp->space + sp->len, p, len);
    653   1.8       cgd 
    654   1.1       alm 	sp->space[sp->len += len] = '\0';
    655   1.1       alm }
    656   1.1       alm 
    657   1.1       alm /*
    658   1.1       alm  * Close all cached opened files and report any errors
    659   1.1       alm  */
    660   1.1       alm void
    661  1.32       wiz cfclose(struct s_command *cp, struct s_command *end)
    662   1.1       alm {
    663   1.1       alm 
    664   1.1       alm 	for (; cp != end; cp = cp->next)
    665   1.1       alm 		switch(cp->code) {
    666   1.1       alm 		case 's':
    667   1.1       alm 			if (cp->u.s->wfd != -1 && close(cp->u.s->wfd))
    668   1.1       alm 				err(FATAL,
    669   1.1       alm 				    "%s: %s", cp->u.s->wfile, strerror(errno));
    670   1.1       alm 			cp->u.s->wfd = -1;
    671   1.1       alm 			break;
    672   1.1       alm 		case 'w':
    673   1.1       alm 			if (cp->u.fd != -1 && close(cp->u.fd))
    674   1.1       alm 				err(FATAL, "%s: %s", cp->t, strerror(errno));
    675   1.1       alm 			cp->u.fd = -1;
    676   1.1       alm 			break;
    677   1.1       alm 		case '{':
    678   1.1       alm 			cfclose(cp->u.c, cp->next);
    679   1.1       alm 			break;
    680   1.1       alm 		}
    681   1.1       alm }
    682