xref: /freebsd/bin/ed/main.c (revision d48a2d23039536ab9f92f88a72c27b9895796abf)
1 /* main.c: This file contains the main control and user-interface routines
2    for the ed line editor. */
3 /*-
4  * Copyright (c) 1993 Andrew Moore, Talke Studio.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #ifndef lint
30 #if 0
31 static const char copyright[] =
32 "@(#) Copyright (c) 1993 Andrew Moore, Talke Studio. \n\
33  All rights reserved.\n";
34 #endif
35 #endif /* not lint */
36 
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39 
40 /*
41  * CREDITS
42  *
43  *	This program is based on the editor algorithm described in
44  *	Brian W. Kernighan and P. J. Plauger's book "Software Tools
45  *	in Pascal," Addison-Wesley, 1981.
46  *
47  *	The buffering algorithm is attributed to Rodney Ruddock of
48  *	the University of Guelph, Guelph, Ontario.
49  *
50  *	The cbc.c encryption code is adapted from
51  *	the bdes program by Matt Bishop of Dartmouth College,
52  *	Hanover, NH.
53  *
54  */
55 
56 #include <sys/types.h>
57 
58 #include <sys/ioctl.h>
59 #include <sys/wait.h>
60 #include <ctype.h>
61 #include <locale.h>
62 #include <pwd.h>
63 #include <setjmp.h>
64 
65 #include "ed.h"
66 
67 
68 #ifdef _POSIX_SOURCE
69 static sigjmp_buf env;
70 #else
71 static jmp_buf env;
72 #endif
73 
74 /* static buffers */
75 char stdinbuf[1];		/* stdin buffer */
76 static char *shcmd;		/* shell command buffer */
77 static int shcmdsz;		/* shell command buffer size */
78 static int shcmdi;		/* shell command buffer index */
79 char *ibuf;			/* ed command-line buffer */
80 int ibufsz;			/* ed command-line buffer size */
81 char *ibufp;			/* pointer to ed command-line buffer */
82 
83 /* global flags */
84 int des = 0;			/* if set, use crypt(3) for i/o */
85 static int garrulous = 0;	/* if set, print all error messages */
86 int isbinary;			/* if set, buffer contains ASCII NULs */
87 int isglobal;			/* if set, doing a global command */
88 int modified;			/* if set, buffer modified since last write */
89 int mutex = 0;			/* if set, signals set "sigflags" */
90 static int red = 0;		/* if set, restrict shell/directory access */
91 int scripted = 0;		/* if set, suppress diagnostics */
92 int sigflags = 0;		/* if set, signals received while mutex set */
93 static int sigactive = 0;	/* if set, signal handlers are enabled */
94 
95 static char old_filename[PATH_MAX] = ""; /* default filename */
96 long current_addr;		/* current address in editor buffer */
97 long addr_last;			/* last address in editor buffer */
98 int lineno;			/* script line number */
99 static const char *prompt;	/* command-line prompt */
100 static const char *dps = "*";	/* default command-line prompt */
101 
102 static const char *usage = "usage: %s [-] [-sx] [-p string] [file]\n";
103 
104 /* ed: line editor */
105 int
106 main(volatile int argc, char ** volatile argv)
107 {
108 	int c, n;
109 	long status = 0;
110 
111 	(void)setlocale(LC_ALL, "");
112 
113 	red = (n = strlen(argv[0])) > 2 && argv[0][n - 3] == 'r';
114 top:
115 	while ((c = getopt(argc, argv, "p:sx")) != -1)
116 		switch(c) {
117 		case 'p':				/* set prompt */
118 			prompt = optarg;
119 			break;
120 		case 's':				/* run script */
121 			scripted = 1;
122 			break;
123 		case 'x':				/* use crypt */
124 #ifdef DES
125 			des = get_keyword();
126 #else
127 			fprintf(stderr, "crypt unavailable\n?\n");
128 #endif
129 			break;
130 
131 		default:
132 			fprintf(stderr, usage, red ? "red" : "ed");
133 			exit(1);
134 		}
135 	argv += optind;
136 	argc -= optind;
137 	if (argc && **argv == '-') {
138 		scripted = 1;
139 		if (argc > 1) {
140 			optind = 1;
141 			goto top;
142 		}
143 		argv++;
144 		argc--;
145 	}
146 	/* assert: reliable signals! */
147 #ifdef SIGWINCH
148 	handle_winch(SIGWINCH);
149 	if (isatty(0)) signal(SIGWINCH, handle_winch);
150 #endif
151 	signal(SIGHUP, signal_hup);
152 	signal(SIGQUIT, SIG_IGN);
153 	signal(SIGINT, signal_int);
154 #ifdef _POSIX_SOURCE
155 	if ((status = sigsetjmp(env, 1)))
156 #else
157 	if ((status = setjmp(env)))
158 #endif
159 	{
160 		fputs("\n?\n", stderr);
161 		errmsg = "interrupt";
162 	} else {
163 		init_buffers();
164 		sigactive = 1;			/* enable signal handlers */
165 		if (argc && **argv && is_legal_filename(*argv)) {
166 			if (read_file(*argv, 0) < 0 && !isatty(0))
167 				quit(2);
168 			else if (**argv != '!')
169 				if (strlcpy(old_filename, *argv, sizeof(old_filename))
170 				    >= sizeof(old_filename))
171 					quit(2);
172 		} else if (argc) {
173 			fputs("?\n", stderr);
174 			if (**argv == '\0')
175 				errmsg = "invalid filename";
176 			if (!isatty(0))
177 				quit(2);
178 		}
179 	}
180 	for (;;) {
181 		if (status < 0 && garrulous)
182 			fprintf(stderr, "%s\n", errmsg);
183 		if (prompt) {
184 			printf("%s", prompt);
185 			fflush(stdout);
186 		}
187 		if ((n = get_tty_line()) < 0) {
188 			status = ERR;
189 			continue;
190 		} else if (n == 0) {
191 			if (modified && !scripted) {
192 				fputs("?\n", stderr);
193 				errmsg = "warning: file modified";
194 				if (!isatty(0)) {
195 					if (garrulous)
196 						fprintf(stderr,
197 						    "script, line %d: %s\n",
198 						    lineno, errmsg);
199 					quit(2);
200 				}
201 				clearerr(stdin);
202 				modified = 0;
203 				status = EMOD;
204 				continue;
205 			} else
206 				quit(0);
207 		} else if (ibuf[n - 1] != '\n') {
208 			/* discard line */
209 			errmsg = "unexpected end-of-file";
210 			clearerr(stdin);
211 			status = ERR;
212 			continue;
213 		}
214 		isglobal = 0;
215 		if ((status = extract_addr_range()) >= 0 &&
216 		    (status = exec_command()) >= 0)
217 			if (!status ||
218 			    (status = display_lines(current_addr, current_addr,
219 			        status)) >= 0)
220 				continue;
221 		switch (status) {
222 		case EOF:
223 			quit(0);
224 		case EMOD:
225 			modified = 0;
226 			fputs("?\n", stderr);		/* give warning */
227 			errmsg = "warning: file modified";
228 			if (!isatty(0)) {
229 				if (garrulous)
230 					fprintf(stderr, "script, line %d: %s\n",
231 					    lineno, errmsg);
232 				quit(2);
233 			}
234 			break;
235 		case FATAL:
236 			if (!isatty(0)) {
237 				if (garrulous)
238 					fprintf(stderr, "script, line %d: %s\n",
239 					    lineno, errmsg);
240 			} else if (garrulous)
241 				fprintf(stderr, "%s\n", errmsg);
242 			quit(3);
243 		default:
244 			fputs("?\n", stderr);
245 			if (!isatty(0)) {
246 				if (garrulous)
247 					fprintf(stderr, "script, line %d: %s\n",
248 					    lineno, errmsg);
249 				quit(2);
250 			}
251 			break;
252 		}
253 	}
254 	/*NOTREACHED*/
255 }
256 
257 long first_addr, second_addr;
258 static long addr_cnt;
259 
260 /* extract_addr_range: get line addresses from the command buffer until an
261    illegal address is seen; return status */
262 int
263 extract_addr_range(void)
264 {
265 	long addr;
266 
267 	addr_cnt = 0;
268 	first_addr = second_addr = current_addr;
269 	while ((addr = next_addr()) >= 0) {
270 		addr_cnt++;
271 		first_addr = second_addr;
272 		second_addr = addr;
273 		if (*ibufp != ',' && *ibufp != ';')
274 			break;
275 		else if (*ibufp++ == ';')
276 			current_addr = addr;
277 	}
278 	if ((addr_cnt = min(addr_cnt, 2)) == 1 || second_addr != addr)
279 		first_addr = second_addr;
280 	return (addr == ERR) ? ERR : 0;
281 }
282 
283 
284 #define SKIP_BLANKS() while (isspace((unsigned char)*ibufp) && *ibufp != '\n') ibufp++
285 
286 #define MUST_BE_FIRST() do {					\
287 	if (!first) {						\
288 		errmsg = "invalid address";			\
289 		return ERR;					\
290 	}							\
291 } while (0)
292 
293 /*  next_addr: return the next line address in the command buffer */
294 long
295 next_addr(void)
296 {
297 	const char *hd;
298 	long addr = current_addr;
299 	long n;
300 	int first = 1;
301 	int c;
302 
303 	SKIP_BLANKS();
304 	for (hd = ibufp;; first = 0)
305 		switch (c = *ibufp) {
306 		case '+':
307 		case '\t':
308 		case ' ':
309 		case '-':
310 		case '^':
311 			ibufp++;
312 			SKIP_BLANKS();
313 			if (isdigit((unsigned char)*ibufp)) {
314 				STRTOL(n, ibufp);
315 				addr += (c == '-' || c == '^') ? -n : n;
316 			} else if (!isspace((unsigned char)c))
317 				addr += (c == '-' || c == '^') ? -1 : 1;
318 			break;
319 		case '0': case '1': case '2':
320 		case '3': case '4': case '5':
321 		case '6': case '7': case '8': case '9':
322 			MUST_BE_FIRST();
323 			STRTOL(addr, ibufp);
324 			break;
325 		case '.':
326 		case '$':
327 			MUST_BE_FIRST();
328 			ibufp++;
329 			addr = (c == '.') ? current_addr : addr_last;
330 			break;
331 		case '/':
332 		case '?':
333 			MUST_BE_FIRST();
334 			if ((addr = get_matching_node_addr(
335 			    get_compiled_pattern(), c == '/')) < 0)
336 				return ERR;
337 			else if (c == *ibufp)
338 				ibufp++;
339 			break;
340 		case '\'':
341 			MUST_BE_FIRST();
342 			ibufp++;
343 			if ((addr = get_marked_node_addr(*ibufp++)) < 0)
344 				return ERR;
345 			break;
346 		case '%':
347 		case ',':
348 		case ';':
349 			if (first) {
350 				ibufp++;
351 				addr_cnt++;
352 				second_addr = (c == ';') ? current_addr : 1;
353 				addr = addr_last;
354 				break;
355 			}
356 			/* FALLTHROUGH */
357 		default:
358 			if (ibufp == hd)
359 				return EOF;
360 			else if (addr < 0 || addr_last < addr) {
361 				errmsg = "invalid address";
362 				return ERR;
363 			} else
364 				return addr;
365 		}
366 	/* NOTREACHED */
367 }
368 
369 
370 #ifdef BACKWARDS
371 /* GET_THIRD_ADDR: get a legal address from the command buffer */
372 #define GET_THIRD_ADDR(addr) \
373 { \
374 	long ol1, ol2; \
375 \
376 	ol1 = first_addr, ol2 = second_addr; \
377 	if (extract_addr_range() < 0) \
378 		return ERR; \
379 	else if (addr_cnt == 0) { \
380 		errmsg = "destination expected"; \
381 		return ERR; \
382 	} else if (second_addr < 0 || addr_last < second_addr) { \
383 		errmsg = "invalid address"; \
384 		return ERR; \
385 	} \
386 	addr = second_addr; \
387 	first_addr = ol1, second_addr = ol2; \
388 }
389 #else	/* BACKWARDS */
390 /* GET_THIRD_ADDR: get a legal address from the command buffer */
391 #define GET_THIRD_ADDR(addr) \
392 { \
393 	long ol1, ol2; \
394 \
395 	ol1 = first_addr, ol2 = second_addr; \
396 	if (extract_addr_range() < 0) \
397 		return ERR; \
398 	if (second_addr < 0 || addr_last < second_addr) { \
399 		errmsg = "invalid address"; \
400 		return ERR; \
401 	} \
402 	addr = second_addr; \
403 	first_addr = ol1, second_addr = ol2; \
404 }
405 #endif
406 
407 
408 /* GET_COMMAND_SUFFIX: verify the command suffix in the command buffer */
409 #define GET_COMMAND_SUFFIX() { \
410 	int done = 0; \
411 	do { \
412 		switch(*ibufp) { \
413 		case 'p': \
414 			gflag |= GPR, ibufp++; \
415 			break; \
416 		case 'l': \
417 			gflag |= GLS, ibufp++; \
418 			break; \
419 		case 'n': \
420 			gflag |= GNP, ibufp++; \
421 			break; \
422 		default: \
423 			done++; \
424 		} \
425 	} while (!done); \
426 	if (*ibufp++ != '\n') { \
427 		errmsg = "invalid command suffix"; \
428 		return ERR; \
429 	} \
430 }
431 
432 
433 /* sflags */
434 #define SGG 001		/* complement previous global substitute suffix */
435 #define SGP 002		/* complement previous print suffix */
436 #define SGR 004		/* use last regex instead of last pat */
437 #define SGF 010		/* repeat last substitution */
438 
439 int patlock = 0;	/* if set, pattern not freed by get_compiled_pattern() */
440 
441 long rows = 22;		/* scroll length: ws_row - 2 */
442 
443 /* exec_command: execute the next command in command buffer; return print
444    request, if any */
445 int
446 exec_command(void)
447 {
448 	static pattern_t *pat = NULL;
449 	static int sgflag = 0;
450 	static long sgnum = 0;
451 
452 	pattern_t *tpat;
453 	char *fnp;
454 	int gflag = 0;
455 	int sflags = 0;
456 	long addr = 0;
457 	int n = 0;
458 	int c;
459 
460 	SKIP_BLANKS();
461 	switch(c = *ibufp++) {
462 	case 'a':
463 		GET_COMMAND_SUFFIX();
464 		if (!isglobal) clear_undo_stack();
465 		if (append_lines(second_addr) < 0)
466 			return ERR;
467 		break;
468 	case 'c':
469 		if (check_addr_range(current_addr, current_addr) < 0)
470 			return ERR;
471 		GET_COMMAND_SUFFIX();
472 		if (!isglobal) clear_undo_stack();
473 		if (delete_lines(first_addr, second_addr) < 0 ||
474 		    append_lines(current_addr) < 0)
475 			return ERR;
476 		break;
477 	case 'd':
478 		if (check_addr_range(current_addr, current_addr) < 0)
479 			return ERR;
480 		GET_COMMAND_SUFFIX();
481 		if (!isglobal) clear_undo_stack();
482 		if (delete_lines(first_addr, second_addr) < 0)
483 			return ERR;
484 		else if ((addr = INC_MOD(current_addr, addr_last)) != 0)
485 			current_addr = addr;
486 		break;
487 	case 'e':
488 		if (modified && !scripted)
489 			return EMOD;
490 		/* FALLTHROUGH */
491 	case 'E':
492 		if (addr_cnt > 0) {
493 			errmsg = "unexpected address";
494 			return ERR;
495 		} else if (!isspace((unsigned char)*ibufp)) {
496 			errmsg = "unexpected command suffix";
497 			return ERR;
498 		} else if ((fnp = get_filename()) == NULL)
499 			return ERR;
500 		GET_COMMAND_SUFFIX();
501 		if (delete_lines(1, addr_last) < 0)
502 			return ERR;
503 		clear_undo_stack();
504 		if (close_sbuf() < 0)
505 			return ERR;
506 		else if (open_sbuf() < 0)
507 			return FATAL;
508 		if (*fnp && *fnp != '!')
509 			 strlcpy(old_filename, fnp, PATH_MAX);
510 #ifdef BACKWARDS
511 		if (*fnp == '\0' && *old_filename == '\0') {
512 			errmsg = "no current filename";
513 			return ERR;
514 		}
515 #endif
516 		if (read_file(*fnp ? fnp : old_filename, 0) < 0)
517 			return ERR;
518 		clear_undo_stack();
519 		modified = 0;
520 		u_current_addr = u_addr_last = -1;
521 		break;
522 	case 'f':
523 		if (addr_cnt > 0) {
524 			errmsg = "unexpected address";
525 			return ERR;
526 		} else if (!isspace((unsigned char)*ibufp)) {
527 			errmsg = "unexpected command suffix";
528 			return ERR;
529 		} else if ((fnp = get_filename()) == NULL)
530 			return ERR;
531 		else if (*fnp == '!') {
532 			errmsg = "invalid redirection";
533 			return ERR;
534 		}
535 		GET_COMMAND_SUFFIX();
536 		if (*fnp)
537 			strlcpy(old_filename, fnp, PATH_MAX);
538 		printf("%s\n", strip_escapes(old_filename));
539 		break;
540 	case 'g':
541 	case 'v':
542 	case 'G':
543 	case 'V':
544 		if (isglobal) {
545 			errmsg = "cannot nest global commands";
546 			return ERR;
547 		} else if (check_addr_range(1, addr_last) < 0)
548 			return ERR;
549 		else if (build_active_list(c == 'g' || c == 'G') < 0)
550 			return ERR;
551 		else if ((n = (c == 'G' || c == 'V')))
552 			GET_COMMAND_SUFFIX();
553 		isglobal++;
554 		if (exec_global(n, gflag) < 0)
555 			return ERR;
556 		break;
557 	case 'h':
558 		if (addr_cnt > 0) {
559 			errmsg = "unexpected address";
560 			return ERR;
561 		}
562 		GET_COMMAND_SUFFIX();
563 		if (*errmsg) fprintf(stderr, "%s\n", errmsg);
564 		break;
565 	case 'H':
566 		if (addr_cnt > 0) {
567 			errmsg = "unexpected address";
568 			return ERR;
569 		}
570 		GET_COMMAND_SUFFIX();
571 		if ((garrulous = 1 - garrulous) && *errmsg)
572 			fprintf(stderr, "%s\n", errmsg);
573 		break;
574 	case 'i':
575 		if (second_addr == 0) {
576 			errmsg = "invalid address";
577 			return ERR;
578 		}
579 		GET_COMMAND_SUFFIX();
580 		if (!isglobal) clear_undo_stack();
581 		if (append_lines(second_addr - 1) < 0)
582 			return ERR;
583 		break;
584 	case 'j':
585 		if (check_addr_range(current_addr, current_addr + 1) < 0)
586 			return ERR;
587 		GET_COMMAND_SUFFIX();
588 		if (!isglobal) clear_undo_stack();
589 		if (first_addr != second_addr &&
590 		    join_lines(first_addr, second_addr) < 0)
591 			return ERR;
592 		break;
593 	case 'k':
594 		c = *ibufp++;
595 		if (second_addr == 0) {
596 			errmsg = "invalid address";
597 			return ERR;
598 		}
599 		GET_COMMAND_SUFFIX();
600 		if (mark_line_node(get_addressed_line_node(second_addr), c) < 0)
601 			return ERR;
602 		break;
603 	case 'l':
604 		if (check_addr_range(current_addr, current_addr) < 0)
605 			return ERR;
606 		GET_COMMAND_SUFFIX();
607 		if (display_lines(first_addr, second_addr, gflag | GLS) < 0)
608 			return ERR;
609 		gflag = 0;
610 		break;
611 	case 'm':
612 		if (check_addr_range(current_addr, current_addr) < 0)
613 			return ERR;
614 		GET_THIRD_ADDR(addr);
615 		if (first_addr <= addr && addr < second_addr) {
616 			errmsg = "invalid destination";
617 			return ERR;
618 		}
619 		GET_COMMAND_SUFFIX();
620 		if (!isglobal) clear_undo_stack();
621 		if (move_lines(addr) < 0)
622 			return ERR;
623 		break;
624 	case 'n':
625 		if (check_addr_range(current_addr, current_addr) < 0)
626 			return ERR;
627 		GET_COMMAND_SUFFIX();
628 		if (display_lines(first_addr, second_addr, gflag | GNP) < 0)
629 			return ERR;
630 		gflag = 0;
631 		break;
632 	case 'p':
633 		if (check_addr_range(current_addr, current_addr) < 0)
634 			return ERR;
635 		GET_COMMAND_SUFFIX();
636 		if (display_lines(first_addr, second_addr, gflag | GPR) < 0)
637 			return ERR;
638 		gflag = 0;
639 		break;
640 	case 'P':
641 		if (addr_cnt > 0) {
642 			errmsg = "unexpected address";
643 			return ERR;
644 		}
645 		GET_COMMAND_SUFFIX();
646 		prompt = prompt ? NULL : optarg ? optarg : dps;
647 		break;
648 	case 'q':
649 	case 'Q':
650 		if (addr_cnt > 0) {
651 			errmsg = "unexpected address";
652 			return ERR;
653 		}
654 		GET_COMMAND_SUFFIX();
655 		gflag =  (modified && !scripted && c == 'q') ? EMOD : EOF;
656 		break;
657 	case 'r':
658 		if (!isspace((unsigned char)*ibufp)) {
659 			errmsg = "unexpected command suffix";
660 			return ERR;
661 		} else if (addr_cnt == 0)
662 			second_addr = addr_last;
663 		if ((fnp = get_filename()) == NULL)
664 			return ERR;
665 		GET_COMMAND_SUFFIX();
666 		if (!isglobal) clear_undo_stack();
667 		if (*old_filename == '\0' && *fnp != '!')
668 			strlcpy(old_filename, fnp, PATH_MAX);
669 #ifdef BACKWARDS
670 		if (*fnp == '\0' && *old_filename == '\0') {
671 			errmsg = "no current filename";
672 			return ERR;
673 		}
674 #endif
675 		if ((addr = read_file(*fnp ? fnp : old_filename, second_addr)) < 0)
676 			return ERR;
677 		else if (addr && addr != addr_last)
678 			modified = 1;
679 		break;
680 	case 's':
681 		do {
682 			switch(*ibufp) {
683 			case '\n':
684 				sflags |=SGF;
685 				break;
686 			case 'g':
687 				sflags |= SGG;
688 				ibufp++;
689 				break;
690 			case 'p':
691 				sflags |= SGP;
692 				ibufp++;
693 				break;
694 			case 'r':
695 				sflags |= SGR;
696 				ibufp++;
697 				break;
698 			case '0': case '1': case '2': case '3': case '4':
699 			case '5': case '6': case '7': case '8': case '9':
700 				STRTOL(sgnum, ibufp);
701 				sflags |= SGF;
702 				sgflag &= ~GSG;		/* override GSG */
703 				break;
704 			default:
705 				if (sflags) {
706 					errmsg = "invalid command suffix";
707 					return ERR;
708 				}
709 			}
710 		} while (sflags && *ibufp != '\n');
711 		if (sflags && !pat) {
712 			errmsg = "no previous substitution";
713 			return ERR;
714 		} else if (sflags & SGG)
715 			sgnum = 0;		/* override numeric arg */
716 		if (*ibufp != '\n' && *(ibufp + 1) == '\n') {
717 			errmsg = "invalid pattern delimiter";
718 			return ERR;
719 		}
720 		tpat = pat;
721 		SPL1();
722 		if ((!sflags || (sflags & SGR)) &&
723 		    (tpat = get_compiled_pattern()) == NULL) {
724 		 	SPL0();
725 			return ERR;
726 		} else if (tpat != pat) {
727 			if (pat) {
728 				regfree(pat);
729 				free(pat);
730 			}
731 			pat = tpat;
732 			patlock = 1;		/* reserve pattern */
733 		}
734 		SPL0();
735 		if (!sflags && extract_subst_tail(&sgflag, &sgnum) < 0)
736 			return ERR;
737 		else if (isglobal)
738 			sgflag |= GLB;
739 		else
740 			sgflag &= ~GLB;
741 		if (sflags & SGG)
742 			sgflag ^= GSG;
743 		if (sflags & SGP)
744 			sgflag ^= GPR, sgflag &= ~(GLS | GNP);
745 		do {
746 			switch(*ibufp) {
747 			case 'p':
748 				sgflag |= GPR, ibufp++;
749 				break;
750 			case 'l':
751 				sgflag |= GLS, ibufp++;
752 				break;
753 			case 'n':
754 				sgflag |= GNP, ibufp++;
755 				break;
756 			default:
757 				n++;
758 			}
759 		} while (!n);
760 		if (check_addr_range(current_addr, current_addr) < 0)
761 			return ERR;
762 		GET_COMMAND_SUFFIX();
763 		if (!isglobal) clear_undo_stack();
764 		if (search_and_replace(pat, sgflag, sgnum) < 0)
765 			return ERR;
766 		break;
767 	case 't':
768 		if (check_addr_range(current_addr, current_addr) < 0)
769 			return ERR;
770 		GET_THIRD_ADDR(addr);
771 		GET_COMMAND_SUFFIX();
772 		if (!isglobal) clear_undo_stack();
773 		if (copy_lines(addr) < 0)
774 			return ERR;
775 		break;
776 	case 'u':
777 		if (addr_cnt > 0) {
778 			errmsg = "unexpected address";
779 			return ERR;
780 		}
781 		GET_COMMAND_SUFFIX();
782 		if (pop_undo_stack() < 0)
783 			return ERR;
784 		break;
785 	case 'w':
786 	case 'W':
787 		if ((n = *ibufp) == 'q' || n == 'Q') {
788 			gflag = EOF;
789 			ibufp++;
790 		}
791 		if (!isspace((unsigned char)*ibufp)) {
792 			errmsg = "unexpected command suffix";
793 			return ERR;
794 		} else if ((fnp = get_filename()) == NULL)
795 			return ERR;
796 		if (addr_cnt == 0 && !addr_last)
797 			first_addr = second_addr = 0;
798 		else if (check_addr_range(1, addr_last) < 0)
799 			return ERR;
800 		GET_COMMAND_SUFFIX();
801 		if (*old_filename == '\0' && *fnp != '!')
802 			strlcpy(old_filename, fnp, PATH_MAX);
803 #ifdef BACKWARDS
804 		if (*fnp == '\0' && *old_filename == '\0') {
805 			errmsg = "no current filename";
806 			return ERR;
807 		}
808 #endif
809 		if ((addr = write_file(*fnp ? fnp : old_filename,
810 		    (c == 'W') ? "a" : "w", first_addr, second_addr)) < 0)
811 			return ERR;
812 		else if (addr == addr_last)
813 			modified = 0;
814 		else if (modified && !scripted && n == 'q')
815 			gflag = EMOD;
816 		break;
817 	case 'x':
818 		if (addr_cnt > 0) {
819 			errmsg = "unexpected address";
820 			return ERR;
821 		}
822 		GET_COMMAND_SUFFIX();
823 #ifdef DES
824 		des = get_keyword();
825 		break;
826 #else
827 		errmsg = "crypt unavailable";
828 		return ERR;
829 #endif
830 	case 'z':
831 #ifdef BACKWARDS
832 		if (check_addr_range(first_addr = 1, current_addr + 1) < 0)
833 #else
834 		if (check_addr_range(first_addr = 1, current_addr + !isglobal) < 0)
835 #endif
836 			return ERR;
837 		else if ('0' < *ibufp && *ibufp <= '9')
838 			STRTOL(rows, ibufp);
839 		GET_COMMAND_SUFFIX();
840 		if (display_lines(second_addr, min(addr_last,
841 		    second_addr + rows), gflag) < 0)
842 			return ERR;
843 		gflag = 0;
844 		break;
845 	case '=':
846 		GET_COMMAND_SUFFIX();
847 		printf("%ld\n", addr_cnt ? second_addr : addr_last);
848 		break;
849 	case '!':
850 		if (addr_cnt > 0) {
851 			errmsg = "unexpected address";
852 			return ERR;
853 		} else if ((sflags = get_shell_command()) < 0)
854 			return ERR;
855 		GET_COMMAND_SUFFIX();
856 		if (sflags) printf("%s\n", shcmd + 1);
857 		system(shcmd + 1);
858 		if (!scripted) printf("!\n");
859 		break;
860 	case '\n':
861 #ifdef BACKWARDS
862 		if (check_addr_range(first_addr = 1, current_addr + 1) < 0
863 #else
864 		if (check_addr_range(first_addr = 1, current_addr + !isglobal) < 0
865 #endif
866 		 || display_lines(second_addr, second_addr, 0) < 0)
867 			return ERR;
868 		break;
869 	default:
870 		errmsg = "unknown command";
871 		return ERR;
872 	}
873 	return gflag;
874 }
875 
876 
877 /* check_addr_range: return status of address range check */
878 int
879 check_addr_range(long n, long m)
880 {
881 	if (addr_cnt == 0) {
882 		first_addr = n;
883 		second_addr = m;
884 	}
885 	if (first_addr > second_addr || 1 > first_addr ||
886 	    second_addr > addr_last) {
887 		errmsg = "invalid address";
888 		return ERR;
889 	}
890 	return 0;
891 }
892 
893 
894 /* get_matching_node_addr: return the address of the next line matching a
895    pattern in a given direction.  wrap around begin/end of editor buffer if
896    necessary */
897 long
898 get_matching_node_addr(pattern_t *pat, int dir)
899 {
900 	char *s;
901 	long n = current_addr;
902 	line_t *lp;
903 
904 	if (!pat) return ERR;
905 	do {
906 	       if ((n = dir ? INC_MOD(n, addr_last) : DEC_MOD(n, addr_last))) {
907 			lp = get_addressed_line_node(n);
908 			if ((s = get_sbuf_line(lp)) == NULL)
909 				return ERR;
910 			if (isbinary)
911 				NUL_TO_NEWLINE(s, lp->len);
912 			if (!regexec(pat, s, 0, NULL, 0))
913 				return n;
914 	       }
915 	} while (n != current_addr);
916 	errmsg = "no match";
917 	return  ERR;
918 }
919 
920 
921 /* get_filename: return pointer to copy of filename in the command buffer */
922 char *
923 get_filename(void)
924 {
925 	static char *file = NULL;
926 	static int filesz = 0;
927 
928 	int n;
929 
930 	if (*ibufp != '\n') {
931 		SKIP_BLANKS();
932 		if (*ibufp == '\n') {
933 			errmsg = "invalid filename";
934 			return NULL;
935 		} else if ((ibufp = get_extended_line(&n, 1)) == NULL)
936 			return NULL;
937 		else if (*ibufp == '!') {
938 			ibufp++;
939 			if ((n = get_shell_command()) < 0)
940 				return NULL;
941 			if (n)
942 				printf("%s\n", shcmd + 1);
943 			return shcmd;
944 		} else if (n > PATH_MAX - 1) {
945 			errmsg = "filename too long";
946 			return  NULL;
947 		}
948 	}
949 #ifndef BACKWARDS
950 	else if (*old_filename == '\0') {
951 		errmsg = "no current filename";
952 		return  NULL;
953 	}
954 #endif
955 	REALLOC(file, filesz, PATH_MAX, NULL);
956 	for (n = 0; *ibufp != '\n';)
957 		file[n++] = *ibufp++;
958 	file[n] = '\0';
959 	return is_legal_filename(file) ? file : NULL;
960 }
961 
962 
963 /* get_shell_command: read a shell command from stdin; return substitution
964    status */
965 int
966 get_shell_command(void)
967 {
968 	static char *buf = NULL;
969 	static int n = 0;
970 
971 	char *s;			/* substitution char pointer */
972 	int i = 0;
973 	int j = 0;
974 
975 	if (red) {
976 		errmsg = "shell access restricted";
977 		return ERR;
978 	} else if ((s = ibufp = get_extended_line(&j, 1)) == NULL)
979 		return ERR;
980 	REALLOC(buf, n, j + 1, ERR);
981 	buf[i++] = '!';			/* prefix command w/ bang */
982 	while (*ibufp != '\n')
983 		switch (*ibufp) {
984 		default:
985 			REALLOC(buf, n, i + 2, ERR);
986 			buf[i++] = *ibufp;
987 			if (*ibufp++ == '\\')
988 				buf[i++] = *ibufp++;
989 			break;
990 		case '!':
991 			if (s != ibufp) {
992 				REALLOC(buf, n, i + 1, ERR);
993 				buf[i++] = *ibufp++;
994 			}
995 #ifdef BACKWARDS
996 			else if (shcmd == NULL || *(shcmd + 1) == '\0')
997 #else
998 			else if (shcmd == NULL)
999 #endif
1000 			{
1001 				errmsg = "no previous command";
1002 				return ERR;
1003 			} else {
1004 				REALLOC(buf, n, i + shcmdi, ERR);
1005 				for (s = shcmd + 1; s < shcmd + shcmdi;)
1006 					buf[i++] = *s++;
1007 				s = ibufp++;
1008 			}
1009 			break;
1010 		case '%':
1011 			if (*old_filename  == '\0') {
1012 				errmsg = "no current filename";
1013 				return ERR;
1014 			}
1015 			j = strlen(s = strip_escapes(old_filename));
1016 			REALLOC(buf, n, i + j, ERR);
1017 			while (j--)
1018 				buf[i++] = *s++;
1019 			s = ibufp++;
1020 			break;
1021 		}
1022 	REALLOC(shcmd, shcmdsz, i + 1, ERR);
1023 	memcpy(shcmd, buf, i);
1024 	shcmd[shcmdi = i] = '\0';
1025 	return *s == '!' || *s == '%';
1026 }
1027 
1028 
1029 /* append_lines: insert text from stdin to after line n; stop when either a
1030    single period is read or EOF; return status */
1031 int
1032 append_lines(long n)
1033 {
1034 	int l;
1035 	const char *lp = ibuf;
1036 	const char *eot;
1037 	undo_t *up = NULL;
1038 
1039 	for (current_addr = n;;) {
1040 		if (!isglobal) {
1041 			if ((l = get_tty_line()) < 0)
1042 				return ERR;
1043 			else if (l == 0 || ibuf[l - 1] != '\n') {
1044 				clearerr(stdin);
1045 				return  l ? EOF : 0;
1046 			}
1047 			lp = ibuf;
1048 		} else if (*(lp = ibufp) == '\0')
1049 			return 0;
1050 		else {
1051 			while (*ibufp++ != '\n')
1052 				;
1053 			l = ibufp - lp;
1054 		}
1055 		if (l == 2 && lp[0] == '.' && lp[1] == '\n') {
1056 			return 0;
1057 		}
1058 		eot = lp + l;
1059 		SPL1();
1060 		do {
1061 			if ((lp = put_sbuf_line(lp)) == NULL) {
1062 				SPL0();
1063 				return ERR;
1064 			} else if (up)
1065 				up->t = get_addressed_line_node(current_addr);
1066 			else if ((up = push_undo_stack(UADD, current_addr,
1067 			    current_addr)) == NULL) {
1068 				SPL0();
1069 				return ERR;
1070 			}
1071 		} while (lp != eot);
1072 		modified = 1;
1073 		SPL0();
1074 	}
1075 	/* NOTREACHED */
1076 }
1077 
1078 
1079 /* join_lines: replace a range of lines with the joined text of those lines */
1080 int
1081 join_lines(long from, long to)
1082 {
1083 	static char *buf = NULL;
1084 	static int n;
1085 
1086 	char *s;
1087 	int size = 0;
1088 	line_t *bp, *ep;
1089 
1090 	ep = get_addressed_line_node(INC_MOD(to, addr_last));
1091 	bp = get_addressed_line_node(from);
1092 	for (; bp != ep; bp = bp->q_forw) {
1093 		if ((s = get_sbuf_line(bp)) == NULL)
1094 			return ERR;
1095 		REALLOC(buf, n, size + bp->len, ERR);
1096 		memcpy(buf + size, s, bp->len);
1097 		size += bp->len;
1098 	}
1099 	REALLOC(buf, n, size + 2, ERR);
1100 	memcpy(buf + size, "\n", 2);
1101 	if (delete_lines(from, to) < 0)
1102 		return ERR;
1103 	current_addr = from - 1;
1104 	SPL1();
1105 	if (put_sbuf_line(buf) == NULL ||
1106 	    push_undo_stack(UADD, current_addr, current_addr) == NULL) {
1107 		SPL0();
1108 		return ERR;
1109 	}
1110 	modified = 1;
1111 	SPL0();
1112 	return 0;
1113 }
1114 
1115 
1116 /* move_lines: move a range of lines */
1117 int
1118 move_lines(long addr)
1119 {
1120 	line_t *b1, *a1, *b2, *a2;
1121 	long n = INC_MOD(second_addr, addr_last);
1122 	long p = first_addr - 1;
1123 	int done = (addr == first_addr - 1 || addr == second_addr);
1124 
1125 	SPL1();
1126 	if (done) {
1127 		a2 = get_addressed_line_node(n);
1128 		b2 = get_addressed_line_node(p);
1129 		current_addr = second_addr;
1130 	} else if (push_undo_stack(UMOV, p, n) == NULL ||
1131 	    push_undo_stack(UMOV, addr, INC_MOD(addr, addr_last)) == NULL) {
1132 		SPL0();
1133 		return ERR;
1134 	} else {
1135 		a1 = get_addressed_line_node(n);
1136 		if (addr < first_addr) {
1137 			b1 = get_addressed_line_node(p);
1138 			b2 = get_addressed_line_node(addr);
1139 					/* this get_addressed_line_node last! */
1140 		} else {
1141 			b2 = get_addressed_line_node(addr);
1142 			b1 = get_addressed_line_node(p);
1143 					/* this get_addressed_line_node last! */
1144 		}
1145 		a2 = b2->q_forw;
1146 		REQUE(b2, b1->q_forw);
1147 		REQUE(a1->q_back, a2);
1148 		REQUE(b1, a1);
1149 		current_addr = addr + ((addr < first_addr) ?
1150 		    second_addr - first_addr + 1 : 0);
1151 	}
1152 	if (isglobal)
1153 		unset_active_nodes(b2->q_forw, a2);
1154 	modified = 1;
1155 	SPL0();
1156 	return 0;
1157 }
1158 
1159 
1160 /* copy_lines: copy a range of lines; return status */
1161 int
1162 copy_lines(long addr)
1163 {
1164 	line_t *lp, *np = get_addressed_line_node(first_addr);
1165 	undo_t *up = NULL;
1166 	long n = second_addr - first_addr + 1;
1167 	long m = 0;
1168 
1169 	current_addr = addr;
1170 	if (first_addr <= addr && addr < second_addr) {
1171 		n =  addr - first_addr + 1;
1172 		m = second_addr - addr;
1173 	}
1174 	for (; n > 0; n=m, m=0, np = get_addressed_line_node(current_addr + 1))
1175 		for (; n-- > 0; np = np->q_forw) {
1176 			SPL1();
1177 			if ((lp = dup_line_node(np)) == NULL) {
1178 				SPL0();
1179 				return ERR;
1180 			}
1181 			add_line_node(lp);
1182 			if (up)
1183 				up->t = lp;
1184 			else if ((up = push_undo_stack(UADD, current_addr,
1185 			    current_addr)) == NULL) {
1186 				SPL0();
1187 				return ERR;
1188 			}
1189 			modified = 1;
1190 			SPL0();
1191 		}
1192 	return 0;
1193 }
1194 
1195 
1196 /* delete_lines: delete a range of lines */
1197 int
1198 delete_lines(long from, long to)
1199 {
1200 	line_t *n, *p;
1201 
1202 	SPL1();
1203 	if (push_undo_stack(UDEL, from, to) == NULL) {
1204 		SPL0();
1205 		return ERR;
1206 	}
1207 	n = get_addressed_line_node(INC_MOD(to, addr_last));
1208 	p = get_addressed_line_node(from - 1);
1209 					/* this get_addressed_line_node last! */
1210 	if (isglobal)
1211 		unset_active_nodes(p->q_forw, n);
1212 	REQUE(p, n);
1213 	addr_last -= to - from + 1;
1214 	current_addr = from - 1;
1215 	modified = 1;
1216 	SPL0();
1217 	return 0;
1218 }
1219 
1220 
1221 /* display_lines: print a range of lines to stdout */
1222 int
1223 display_lines(long from, long to, int gflag)
1224 {
1225 	line_t *bp;
1226 	line_t *ep;
1227 	char *s;
1228 
1229 	if (!from) {
1230 		errmsg = "invalid address";
1231 		return ERR;
1232 	}
1233 	ep = get_addressed_line_node(INC_MOD(to, addr_last));
1234 	bp = get_addressed_line_node(from);
1235 	for (; bp != ep; bp = bp->q_forw) {
1236 		if ((s = get_sbuf_line(bp)) == NULL)
1237 			return ERR;
1238 		if (put_tty_line(s, bp->len, current_addr = from++, gflag) < 0)
1239 			return ERR;
1240 	}
1241 	return 0;
1242 }
1243 
1244 
1245 #define MAXMARK 26			/* max number of marks */
1246 
1247 static line_t *mark[MAXMARK];		/* line markers */
1248 static int markno;			/* line marker count */
1249 
1250 /* mark_line_node: set a line node mark */
1251 int
1252 mark_line_node(line_t *lp, int n)
1253 {
1254 	if (!islower((unsigned char)n)) {
1255 		errmsg = "invalid mark character";
1256 		return ERR;
1257 	} else if (mark[n - 'a'] == NULL)
1258 		markno++;
1259 	mark[n - 'a'] = lp;
1260 	return 0;
1261 }
1262 
1263 
1264 /* get_marked_node_addr: return address of a marked line */
1265 long
1266 get_marked_node_addr(int n)
1267 {
1268 	if (!islower((unsigned char)n)) {
1269 		errmsg = "invalid mark character";
1270 		return ERR;
1271 	}
1272 	return get_line_node_addr(mark[n - 'a']);
1273 }
1274 
1275 
1276 /* unmark_line_node: clear line node mark */
1277 void
1278 unmark_line_node(line_t *lp)
1279 {
1280 	int i;
1281 
1282 	for (i = 0; markno && i < MAXMARK; i++)
1283 		if (mark[i] == lp) {
1284 			mark[i] = NULL;
1285 			markno--;
1286 		}
1287 }
1288 
1289 
1290 /* dup_line_node: return a pointer to a copy of a line node */
1291 line_t *
1292 dup_line_node(line_t *lp)
1293 {
1294 	line_t *np;
1295 
1296 	if ((np = (line_t *) malloc(sizeof(line_t))) == NULL) {
1297 		fprintf(stderr, "%s\n", strerror(errno));
1298 		errmsg = "out of memory";
1299 		return NULL;
1300 	}
1301 	np->seek = lp->seek;
1302 	np->len = lp->len;
1303 	return np;
1304 }
1305 
1306 
1307 /* has_trailing_escape:  return the parity of escapes preceding a character
1308    in a string */
1309 int
1310 has_trailing_escape(char *s, char *t)
1311 {
1312     return (s == t || *(t - 1) != '\\') ? 0 : !has_trailing_escape(s, t - 1);
1313 }
1314 
1315 
1316 /* strip_escapes: return copy of escaped string of at most length PATH_MAX */
1317 char *
1318 strip_escapes(char *s)
1319 {
1320 	static char *file = NULL;
1321 	static int filesz = 0;
1322 
1323 	int i = 0;
1324 
1325 	REALLOC(file, filesz, PATH_MAX, NULL);
1326 	while (i < filesz - 1	/* Worry about a possible trailing escape */
1327 	       && (file[i++] = (*s == '\\') ? *++s : *s))
1328 		s++;
1329 	return file;
1330 }
1331 
1332 
1333 void
1334 signal_hup(int signo)
1335 {
1336 	if (mutex)
1337 		sigflags |= (1 << (signo - 1));
1338 	else
1339 		handle_hup(signo);
1340 }
1341 
1342 
1343 void
1344 signal_int(int signo)
1345 {
1346 	if (mutex)
1347 		sigflags |= (1 << (signo - 1));
1348 	else
1349 		handle_int(signo);
1350 }
1351 
1352 
1353 void
1354 handle_hup(int signo)
1355 {
1356 	char *hup = NULL;		/* hup filename */
1357 	char *s;
1358 	char ed_hup[] = "ed.hup";
1359 	int n;
1360 
1361 	if (!sigactive)
1362 		quit(1);
1363 	sigflags &= ~(1 << (signo - 1));
1364 	if (addr_last && write_file(ed_hup, "w", 1, addr_last) < 0 &&
1365 	    (s = getenv("HOME")) != NULL &&
1366 	    (n = strlen(s)) + 8 <= PATH_MAX &&	/* "ed.hup" + '/' */
1367 	    (hup = (char *) malloc(n + 10)) != NULL) {
1368 		strcpy(hup, s);
1369 		if (hup[n - 1] != '/')
1370 			hup[n] = '/', hup[n+1] = '\0';
1371 		strcat(hup, "ed.hup");
1372 		write_file(hup, "w", 1, addr_last);
1373 	}
1374 	quit(2);
1375 }
1376 
1377 
1378 void
1379 handle_int(int signo)
1380 {
1381 	if (!sigactive)
1382 		quit(1);
1383 	sigflags &= ~(1 << (signo - 1));
1384 #ifdef _POSIX_SOURCE
1385 	siglongjmp(env, -1);
1386 #else
1387 	longjmp(env, -1);
1388 #endif
1389 }
1390 
1391 
1392 int cols = 72;				/* wrap column */
1393 
1394 void
1395 handle_winch(int signo)
1396 {
1397 	int save_errno = errno;
1398 
1399 	struct winsize ws;		/* window size structure */
1400 
1401 	sigflags &= ~(1 << (signo - 1));
1402 	if (ioctl(0, TIOCGWINSZ, (char *) &ws) >= 0) {
1403 		if (ws.ws_row > 2) rows = ws.ws_row - 2;
1404 		if (ws.ws_col > 8) cols = ws.ws_col - 8;
1405 	}
1406 	errno = save_errno;
1407 }
1408 
1409 
1410 /* is_legal_filename: return a legal filename */
1411 int
1412 is_legal_filename(char *s)
1413 {
1414 	if (red && (*s == '!' || !strcmp(s, "..") || strchr(s, '/'))) {
1415 		errmsg = "shell access restricted";
1416 		return 0;
1417 	}
1418 	return 1;
1419 }
1420