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