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