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