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