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