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