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