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