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