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