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