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