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