sbase

suckless unix tools
git clone git://git.suckless.org/sbase
Log | Files | Refs | README | LICENSE

ed.c (23300B)


      1 /* See LICENSE file for copyright and license details. */
      2 #include <sys/stat.h>
      3 #include <fcntl.h>
      4 #include <regex.h>
      5 #include <unistd.h>
      6 
      7 #include <ctype.h>
      8 #include <limits.h>
      9 #include <setjmp.h>
     10 #include <signal.h>
     11 #include <stdint.h>
     12 #include <stdio.h>
     13 #include <stdlib.h>
     14 #include <string.h>
     15 
     16 #include "util.h"
     17 
     18 #define REGEXSIZE  100
     19 #define LINESIZE    80
     20 #define NUMLINES    32
     21 #define CACHESIZ  4096
     22 #define AFTER     0
     23 #define BEFORE    1
     24 
     25 typedef struct {
     26 	char *str;
     27 	size_t cap;
     28 	size_t siz;
     29 } String;
     30 
     31 struct hline {
     32 	off_t seek;
     33 	char  global;
     34 	int   next, prev;
     35 };
     36 
     37 struct undo {
     38 	int curln, lastln;
     39 	size_t nr, cap;
     40 	struct link {
     41 		int to1, from1;
     42 		int to2, from2;
     43 	} *vec;
     44 };
     45 
     46 static char *prompt = "*";
     47 static regex_t *pattern;
     48 static regmatch_t matchs[10];
     49 static String lastre;
     50 
     51 static int optverbose, optprompt, exstatus, optdiag = 1;
     52 static int marks['z' - 'a'];
     53 static int nlines, line1, line2;
     54 static int curln, lastln, ocurln, olastln;
     55 static jmp_buf savesp;
     56 static char *lasterr;
     57 static size_t idxsize, lastidx;
     58 static struct hline *zero;
     59 static String text;
     60 static char savfname[FILENAME_MAX];
     61 static char tmpname[FILENAME_MAX];
     62 static int scratch;
     63 static int pflag, modflag, uflag, gflag;
     64 static size_t csize;
     65 static String cmdline;
     66 static char *ocmdline;
     67 static int repidx;
     68 static char *rhs;
     69 static char *lastmatch;
     70 static struct undo udata;
     71 static int newcmd;
     72 int eol, bol;
     73 
     74 static void
     75 discard(void)
     76 {
     77 	int c;
     78 
     79 	if (repidx >= 0)
     80 		return;
     81 
     82 	/* discard until the end of the line */
     83 	if (cmdline.siz > 0 && cmdline.str[cmdline.siz-1] == '\n')
     84 		return;
     85 
     86 	while ((c = getchar()) != '\n' && c != EOF)
     87 		;
     88 }
     89 
     90 static void undo(void);
     91 
     92 static void
     93 error(char *msg)
     94 {
     95 	exstatus = 1;
     96 	lasterr = msg;
     97 	puts("?");
     98 
     99 	if (optverbose)
    100 		puts(msg);
    101 	if (!newcmd)
    102 		undo();
    103 
    104 	discard();
    105 	curln = ocurln;
    106 	longjmp(savesp, 1);
    107 }
    108 
    109 static int
    110 nextln(int line)
    111 {
    112 	++line;
    113 	return (line > lastln) ? 0 : line;
    114 }
    115 
    116 static int
    117 prevln(int line)
    118 {
    119 	--line;
    120 	return (line < 0) ? lastln : line;
    121 }
    122 
    123 static char *
    124 addchar(char c, String *s)
    125 {
    126 	size_t cap = s->cap, siz = s->siz;
    127 	char *t = s->str;
    128 
    129 	if (siz >= cap &&
    130 	    (cap > SIZE_MAX - LINESIZE ||
    131 	     (t = realloc(t, cap += LINESIZE)) == NULL))
    132 			error("out of memory");
    133 	t[siz++] = c;
    134 	s->siz = siz;
    135 	s->cap = cap;
    136 	s->str = t;
    137 	return t;
    138 }
    139 
    140 static int
    141 input(void)
    142 {
    143 	int c;
    144 
    145 	if (repidx >= 0)
    146 		return ocmdline[repidx++];
    147 
    148 	if ((c = getchar()) != EOF)
    149 		addchar(c, &cmdline);
    150 	return c;
    151 }
    152 
    153 static int
    154 back(int c)
    155 {
    156 	if (repidx > 0) {
    157 		--repidx;
    158 	} else {
    159 		ungetc(c, stdin);
    160 		if (c != EOF)
    161 			--cmdline.siz;
    162 	}
    163 	return c;
    164 }
    165 
    166 static int
    167 makeline(char *s, int *off)
    168 {
    169 	struct hline *lp;
    170 	size_t len;
    171 	char c, *begin = s;
    172 
    173 	if (lastidx >= idxsize) {
    174 		lp = NULL;
    175 		if (idxsize <= SIZE_MAX - NUMLINES)
    176 		    lp = reallocarray(zero, idxsize + NUMLINES, sizeof(*lp));
    177 		if (!lp)
    178 			error("out of memory");
    179 		idxsize += NUMLINES;
    180 		zero = lp;
    181 	}
    182 	lp = zero + lastidx;
    183 
    184 	if (!s) {
    185 		lp->seek = -1;
    186 		len = 0;
    187 	} else {
    188 		while ((c = *s++) != '\n')
    189 			/* nothing */;
    190 		len = s - begin;
    191 		if ((lp->seek = lseek(scratch, 0, SEEK_END)) < 0 ||
    192 		    write(scratch, begin, len) < 0) {
    193 			error("input/output error");
    194 		}
    195 	}
    196 	if (off)
    197 		*off = len;
    198 	++lastidx;
    199 	return lp - zero;
    200 }
    201 
    202 static int
    203 getindex(int line)
    204 {
    205 	struct hline *lp;
    206 	int n;
    207 
    208 	if (line == -1)
    209 		line = 0;
    210 	for (n = 0, lp = zero; n != line; n++)
    211 		lp = zero + lp->next;
    212 
    213 	return lp - zero;
    214 }
    215 
    216 static char *
    217 gettxt(int line)
    218 {
    219 	static char buf[CACHESIZ];
    220 	static off_t lasto;
    221 	struct hline *lp;
    222 	off_t off, block;
    223 	ssize_t n;
    224 	char *p;
    225 
    226 	lp = zero + getindex(line);
    227 	text.siz = 0;
    228 	off = lp->seek;
    229 
    230 	if (off == (off_t) -1)
    231 		return addchar('\0', &text);
    232 
    233 repeat:
    234 	if (!csize || off < lasto || off - lasto >= csize) {
    235 		block = off & ~(CACHESIZ-1);
    236 		if (lseek(scratch, block, SEEK_SET) < 0 ||
    237 		    (n = read(scratch, buf, CACHESIZ)) < 0) {
    238 			error("input/output error");
    239 		}
    240 		csize = n;
    241 		lasto = block;
    242 	}
    243 	for (p = buf + off - lasto; p < buf + csize && *p != '\n'; ++p) {
    244 		++off;
    245 		addchar(*p, &text);
    246 	}
    247 	if (csize && p == buf + csize)
    248 		goto repeat;
    249 
    250 	addchar('\n', &text);
    251 	addchar('\0', &text);
    252 	return text.str;
    253 }
    254 
    255 static void
    256 setglobal(int i, int v)
    257 {
    258 	zero[getindex(i)].global = v;
    259 }
    260 
    261 static void
    262 clearundo(void)
    263 {
    264 	free(udata.vec);
    265 	udata.vec = NULL;
    266 	newcmd = udata.nr = udata.cap = 0;
    267 	modflag = 0;
    268 }
    269 
    270 static void
    271 newundo(int from1, int from2)
    272 {
    273 	struct link *p;
    274 
    275 	if (newcmd) {
    276 		clearundo();
    277 		udata.curln = ocurln;
    278 		udata.lastln = olastln;
    279 	}
    280 	if (udata.nr >= udata.cap) {
    281 		size_t siz = (udata.cap + 10) * sizeof(struct link);
    282 		if ((p = realloc(udata.vec, siz)) == NULL)
    283 			error("out of memory");
    284 		udata.vec = p;
    285 		udata.cap = udata.cap + 10;
    286 	}
    287 	p = &udata.vec[udata.nr++];
    288 	p->from1 = from1;
    289 	p->to1 = zero[from1].next;
    290 	p->from2 = from2;
    291 	p->to2 = zero[from2].prev;
    292 }
    293 
    294 /*
    295  * relink: to1   <- from1
    296  *         from2 -> to2
    297  */
    298 static void
    299 relink(int to1, int from1, int from2, int to2)
    300 {
    301 	newundo(from1, from2);
    302 	zero[from1].next = to1;
    303 	zero[from2].prev = to2;
    304 	modflag = 1;
    305 }
    306 
    307 static void
    308 undo(void)
    309 {
    310 	struct link *p;
    311 
    312 	if (udata.nr == 0)
    313 		return;
    314 	for (p = &udata.vec[udata.nr-1]; udata.nr > 0; --p) {
    315 		--udata.nr;
    316 		zero[p->from1].next = p->to1;
    317 		zero[p->from2].prev = p->to2;
    318 	}
    319 	free(udata.vec);
    320 	udata.vec = NULL;
    321 	udata.cap = 0;
    322 	curln = udata.curln;
    323 	lastln = udata.lastln;
    324 }
    325 
    326 static void
    327 inject(char *s, int where)
    328 {
    329 	int off, k, begin, end;
    330 
    331 	if (where == BEFORE) {
    332 		begin = getindex(curln-1);
    333 		end = getindex(nextln(curln-1));
    334 	} else {
    335 		begin = getindex(curln);
    336 		end = getindex(nextln(curln));
    337 	}
    338 	while (*s) {
    339 		k = makeline(s, &off);
    340 		s += off;
    341 		relink(k, begin, k, begin);
    342 		relink(end, k, end, k);
    343 		++lastln;
    344 		++curln;
    345 		begin = k;
    346 	}
    347 }
    348 
    349 static void
    350 clearbuf(void)
    351 {
    352 	if (scratch)
    353 		close(scratch);
    354 	remove(tmpname);
    355 	free(zero);
    356 	zero = NULL;
    357 	scratch = csize = idxsize = lastidx = curln = lastln = 0;
    358 	modflag = lastln = curln = 0;
    359 }
    360 
    361 static void
    362 setscratch(void)
    363 {
    364 	int r, k;
    365 	char *dir;
    366 
    367 	clearbuf();
    368 	clearundo();
    369 	if ((dir = getenv("TMPDIR")) == NULL)
    370 		dir = "/tmp";
    371 	r = snprintf(tmpname, sizeof(tmpname), "%s/%s",
    372 	             dir, "ed.XXXXXX");
    373 	if (r < 0 || (size_t)r >= sizeof(tmpname))
    374 		error("scratch filename too long");
    375 	if ((scratch = mkstemp(tmpname)) < 0)
    376 		error("failed to create scratch file");
    377 	if ((k = makeline(NULL, NULL)))
    378 		error("input/output error in scratch file");
    379 	relink(k, k, k, k);
    380 	clearundo();
    381 }
    382 
    383 static void
    384 compile(int delim)
    385 {
    386 	int n, ret, c,bracket;
    387 	static char buf[BUFSIZ];
    388 
    389 	if (!isgraph(delim))
    390 		error("invalid pattern delimiter");
    391 
    392 	eol = bol = bracket = lastre.siz = 0;
    393 	for (n = 0;; ++n) {
    394 		if ((c = input()) == delim && !bracket)
    395 			break;
    396 		if (c == '^') {
    397 			bol = 1;
    398 		} else if (c == '$') {
    399 			eol = 1;
    400 		} else if (c == '\n' || c == EOF) {
    401 			back(c);
    402 			break;
    403 		}
    404 
    405 		if (c == '\\') {
    406 			addchar(c, &lastre);
    407 			c = input();
    408 		} else if (c == '[') {
    409 			bracket = 1;
    410 		} else if (c == ']') {
    411 			bracket = 0;
    412 		}
    413 		addchar(c, &lastre);
    414 	}
    415 	if (n == 0) {
    416 		if (!pattern)
    417 			error("no previous pattern");
    418 		return;
    419 	}
    420 	addchar('\0', &lastre);
    421 
    422 	if (pattern)
    423 		regfree(pattern);
    424 	if (!pattern && (!(pattern = malloc(sizeof(*pattern)))))
    425 		error("out of memory");
    426 	if ((ret = regcomp(pattern, lastre.str, REG_NEWLINE))) {
    427 		regerror(ret, pattern, buf, sizeof(buf));
    428 		error(buf);
    429 	}
    430 }
    431 
    432 static int
    433 match(int num)
    434 {
    435 	lastmatch = gettxt(num);
    436 	return !regexec(pattern, lastmatch, 10, matchs, 0);
    437 }
    438 
    439 static int
    440 rematch(int num)
    441 {
    442 	regoff_t off = matchs[0].rm_eo;
    443 
    444 	if (!regexec(pattern, lastmatch + off, 10, matchs, 0)) {
    445 		lastmatch += off;
    446 		return 1;
    447 	}
    448 
    449 	return 0;
    450 }
    451 
    452 static int
    453 search(int way)
    454 {
    455 	int i;
    456 
    457 	i = curln;
    458 	do {
    459 		i = (way == '?') ? prevln(i) : nextln(i);
    460 		if (i > 0 && match(i))
    461 			return i;
    462 	} while (i != curln);
    463 
    464 	error("invalid address");
    465 	return -1; /* not reached */
    466 }
    467 
    468 static void
    469 skipblank(void)
    470 {
    471 	char c;
    472 
    473 	while ((c = input()) == ' ' || c == '\t')
    474 		/* nothing */;
    475 	back(c);
    476 }
    477 
    478 static int
    479 getnum(void)
    480 {
    481 	int ln, n, c;
    482 
    483 	for (ln = 0; isdigit(c = input()); ln += n) {
    484 		if (ln > INT_MAX/10)
    485 			goto invalid;
    486 		n = c - '0';
    487 		ln *= 10;
    488 		if (INT_MAX - ln < n)
    489 			goto invalid;
    490 	}
    491 	back(c);
    492 	return ln;
    493 
    494 invalid:
    495 	error("invalid address");
    496 	return -1; /* not reached */
    497 }
    498 
    499 static int
    500 linenum(int *line)
    501 {
    502 	int ln, c;
    503 
    504 	skipblank();
    505 
    506 	switch (c = input()) {
    507 	case '.':
    508 		ln = curln;
    509 		break;
    510 	case '\'':
    511 		skipblank();
    512 		if (!islower(c = input()))
    513 			error("invalid mark character");
    514 		if (!(ln = marks[c - 'a']))
    515 			error("invalid address");
    516 		break;
    517 	case '$':
    518 		ln = lastln;
    519 		break;
    520 	case '?':
    521 	case '/':
    522 		compile(c);
    523 		ln = search(c);
    524 		break;
    525 	case '^':
    526 	case '-':
    527 	case '+':
    528 		ln = curln;
    529 		back(c);
    530 		break;
    531 	default:
    532 		back(c);
    533 		if (isdigit(c))
    534 			ln = getnum();
    535 		else
    536 			return 0;
    537 		break;
    538 	}
    539 	*line = ln;
    540 	return 1;
    541 }
    542 
    543 static int
    544 address(int *line)
    545 {
    546 	int ln, sign, c, num;
    547 
    548 	if (!linenum(&ln))
    549 		return 0;
    550 
    551 	for (;;) {
    552 		skipblank();
    553 		if ((c = input()) != '+' && c != '-' && c != '^')
    554 			break;
    555 		sign = c == '+' ? 1 : -1;
    556 		num = isdigit(back(input())) ? getnum() : 1;
    557 		num *= sign;
    558 		if (INT_MAX - ln < num)
    559 			goto invalid;
    560 		ln += num;
    561 	}
    562 	back(c);
    563 
    564 	if (ln < 0 || ln > lastln)
    565 		error("invalid address");
    566 	*line = ln;
    567 	return 1;
    568 
    569 invalid:
    570 	error("invalid address");
    571 	return -1; /* not reached */
    572 }
    573 
    574 static void
    575 getlst(void)
    576 {
    577 	int ln, c;
    578 
    579 	if ((c = input()) == ',') {
    580 		line1 = 1;
    581 		line2 = lastln;
    582 		nlines = lastln;
    583 		return;
    584 	} else if (c == ';') {
    585 		line1 = curln;
    586 		line2 = lastln;
    587 		nlines = lastln - curln + 1;
    588 		return;
    589 	}
    590 	back(c);
    591 	line2 = curln;
    592 	for (nlines = 0; address(&ln); ) {
    593 		line1 = line2;
    594 		line2 = ln;
    595 		++nlines;
    596 
    597 		skipblank();
    598 		if ((c = input()) != ',' && c != ';') {
    599 			back(c);
    600 			break;
    601 		}
    602 		if (c == ';')
    603 			curln = line2;
    604 	}
    605 	if (nlines > 2)
    606 		nlines = 2;
    607 	else if (nlines <= 1)
    608 		line1 = line2;
    609 }
    610 
    611 static void
    612 deflines(int def1, int def2)
    613 {
    614 	if (!nlines) {
    615 		line1 = def1;
    616 		line2 = def2;
    617 	}
    618 	if (line1 > line2 || line1 < 0 || line2 > lastln)
    619 		error("invalid address");
    620 }
    621 
    622 static void
    623 dowrite(const char *fname, int trunc)
    624 {
    625 	FILE *fp;
    626 	size_t bytecount = 0;
    627 	int i, line;
    628 
    629 	if (!(fp = fopen(fname, (trunc) ? "w" : "a")))
    630 		error("input/output error");
    631 
    632 	line = curln;
    633 	for (i = line1; i <= line2; ++i) {
    634 		gettxt(i);
    635 		bytecount += text.siz - 1;
    636 		fwrite(text.str, 1, text.siz - 1, fp);
    637 	}
    638 
    639 	curln = line2;
    640 	if (fclose(fp))
    641 		error("input/output error");
    642 	strcpy(savfname, fname);
    643 	modflag = 0;
    644 	curln = line;
    645 	printf("%zu\n", bytecount);
    646 }
    647 
    648 static void
    649 doread(const char *fname)
    650 {
    651 	size_t cnt;
    652 	ssize_t n;
    653 	char *p;
    654 	FILE *aux;
    655 	static size_t len;
    656 	static char *s;
    657 	static FILE *fp;
    658 
    659 	if (fp)
    660 		fclose(fp);
    661 	if ((fp = fopen(fname, "r")) == NULL)
    662 		error("cannot open input file");
    663 
    664 	curln = line2;
    665 	for (cnt = 0; (n = getline(&s, &len, fp)) > 0; cnt += (size_t)n) {
    666 		if (s[n-1] != '\n') {
    667 			if (len == SIZE_MAX || !(p = realloc(s, ++len)))
    668 				error("out of memory");
    669 			s = p;
    670 			s[n-1] = '\n';
    671 			s[n] = '\0';
    672 		}
    673 		inject(s, AFTER);
    674 	}
    675 	if (optdiag)
    676 		printf("%zu\n", cnt);
    677 
    678 	aux = fp;
    679 	fp = NULL;
    680 	if (fclose(aux))
    681 		error("input/output error");
    682 }
    683 
    684 static void
    685 doprint(void)
    686 {
    687 	int i, c;
    688 	char *s, *str;
    689 
    690 	if (line1 <= 0 || line2 > lastln)
    691 		error("incorrect address");
    692 	for (i = line1; i <= line2; ++i) {
    693 		if (pflag == 'n')
    694 			printf("%d\t", i);
    695 		for (s = gettxt(i); (c = *s) != '\n'; ++s) {
    696 			if (pflag != 'l')
    697 				goto print_char;
    698 			switch (c) {
    699 			case '$':
    700 				str = "\\$";
    701 				goto print_str;
    702 			case '\t':
    703 				str = "\\t";
    704 				goto print_str;
    705 			case '\b':
    706 				str = "\\b";
    707 				goto print_str;
    708 			case '\\':
    709 				str = "\\\\";
    710 				goto print_str;
    711 			default:
    712 				if (!isprint(c)) {
    713 					printf("\\x%x", 0xFF & c);
    714 					break;
    715 				}
    716 			print_char:
    717 				putchar(c);
    718 				break;
    719 			print_str:
    720 				fputs(str, stdout);
    721 				break;
    722 			}
    723 		}
    724 		if (pflag == 'l')
    725 			fputs("$", stdout);
    726 		putc('\n', stdout);
    727 	}
    728 	curln = i - 1;
    729 }
    730 
    731 static void
    732 dohelp(void)
    733 {
    734 	if (lasterr)
    735 		puts(lasterr);
    736 }
    737 
    738 static void
    739 chkprint(int flag)
    740 {
    741 	char c;
    742 
    743 	if (flag) {
    744 		if ((c = input()) == 'p' || c == 'l' || c == 'n')
    745 			pflag = c;
    746 		else
    747 			back(c);
    748 	}
    749 	if (input() != '\n')
    750 		error("invalid command suffix");
    751 }
    752 
    753 static char *
    754 getfname(char comm)
    755 {
    756 	int c;
    757 	char *bp;
    758 	static char fname[FILENAME_MAX];
    759 
    760 	skipblank();
    761 	for (bp = fname; bp < &fname[FILENAME_MAX]; *bp++ = c) {
    762 		if ((c = input()) == EOF || c == '\n')
    763 			break;
    764 	}
    765 	if (bp == fname) {
    766 		if (savfname[0] == '\0')
    767 			error("no current filename");
    768 		return savfname;
    769 	} else if (bp == &fname[FILENAME_MAX]) {
    770 		error("file name too long");
    771 	} else {
    772 		*bp = '\0';
    773 		if (savfname[0] == '\0' || comm == 'e' || comm == 'f')
    774 			strcpy(savfname, fname);
    775 		return fname;
    776 	}
    777 
    778 	return NULL; /* not reached */
    779 }
    780 
    781 static void
    782 append(int num)
    783 {
    784 	char *s = NULL;
    785 	size_t len = 0;
    786 
    787 	curln = num;
    788 	while (getline(&s, &len, stdin) > 0) {
    789 		if (*s == '.' && s[1] == '\n')
    790 			break;
    791 		inject(s, AFTER);
    792 	}
    793 	free(s);
    794 }
    795 
    796 static void
    797 delete(int from, int to)
    798 {
    799 	int lto, lfrom;
    800 
    801 	if (!from)
    802 		error("incorrect address");
    803 
    804 	lfrom = getindex(prevln(from));
    805 	lto = getindex(nextln(to));
    806 	lastln -= to - from + 1;
    807 	curln = (from > lastln) ? lastln : from;;
    808 	relink(lto, lfrom, lto, lfrom);
    809 }
    810 
    811 static void
    812 move(int where)
    813 {
    814 	int before, after, lto, lfrom;
    815 
    816 	if (!line1 || (where >= line1 && where <= line2))
    817 		error("incorrect address");
    818 
    819 	before = getindex(prevln(line1));
    820 	after = getindex(nextln(line2));
    821 	lfrom = getindex(line1);
    822 	lto = getindex(line2);
    823 	relink(after, before, after, before);
    824 
    825 	if (where < line1) {
    826 		curln = where + line1 - line2 + 1;
    827 	} else {
    828 		curln = where;
    829 		where -= line1 - line2 + 1;
    830 	}
    831 	before = getindex(where);
    832 	after = getindex(nextln(where));
    833 	relink(lfrom, before, lfrom, before);
    834 	relink(after, lto, after, lto);
    835 }
    836 
    837 static void
    838 join(void)
    839 {
    840 	int i;
    841 	char *t, c;
    842 	String s;
    843 
    844 	s.str = NULL;
    845 	s.siz = s.cap = 0;
    846 	for (i = line1;; i = nextln(i)) {
    847 		for (t = gettxt(i); (c = *t) != '\n'; ++t)
    848 			addchar(*t, &s);
    849 		if (i == line2)
    850 			break;
    851 	}
    852 
    853 	addchar('\n', &s);
    854 	addchar('\0', &s);
    855 	delete(line1, line2);
    856 	inject(s.str, BEFORE);
    857 	free(s.str);
    858 }
    859 
    860 static void
    861 scroll(int num)
    862 {
    863 	int max, ln, cnt;
    864 
    865 	if (!line1 || line1 == lastln)
    866 		error("incorrect address");
    867 
    868 	ln = line1;
    869 	max = line1 + num;
    870 	if (max > lastln)
    871 		max = lastln;
    872 	for (cnt = line1; cnt < max; cnt++) {
    873 		fputs(gettxt(ln), stdout);
    874 		ln = nextln(ln);
    875 	}
    876 	curln = ln;
    877 }
    878 
    879 static void
    880 copy(int where)
    881 {
    882 
    883 	if (!line1)
    884 		error("incorrect address");
    885 	curln = where;
    886 
    887 	while (line1 <= line2) {
    888 		inject(gettxt(line1), AFTER);
    889 		if (line2 >= curln)
    890 			line2 = nextln(line2);
    891 		line1 = nextln(line1);
    892 		if (line1 >= curln)
    893 			line1 = nextln(line1);
    894 	}
    895 }
    896 
    897 static void
    898 quit(void)
    899 {
    900 	clearbuf();
    901 	exit(exstatus);
    902 }
    903 
    904 static void
    905 execsh(void)
    906 {
    907 	static String cmd;
    908 	char *p;
    909 	int c, repl = 0;
    910 
    911 	skipblank();
    912 	if ((c = input()) != '!') {
    913 		back(c);
    914 		cmd.siz = 0;
    915 	} else if (cmd.siz) {
    916 		--cmd.siz;
    917 		repl = 1;
    918 	} else {
    919 		error("no previous command");
    920 	}
    921 
    922 	while ((c = input()) != EOF && c != '\n') {
    923 		if (c == '%' && (cmd.siz == 0 || cmd.str[cmd.siz - 1] != '\\')) {
    924 			if (savfname[0] == '\0')
    925 				error("no current filename");
    926 			repl = 1;
    927 			for (p = savfname; *p; ++p)
    928 				addchar(*p, &cmd);
    929 		} else {
    930 			addchar(c, &cmd);
    931 		}
    932 	}
    933 	addchar('\0', &cmd);
    934 
    935 	if (repl)
    936 		puts(cmd.str);
    937 	system(cmd.str);
    938 	if (optdiag)
    939 		puts("!");
    940 }
    941 
    942 static void
    943 getrhs(int delim)
    944 {
    945 	int c;
    946 	static String s;
    947 
    948 	free(s.str);
    949 	s.str = NULL;
    950 	s.siz = s.cap = 0;
    951 	while ((c = input()) != '\n' && c != EOF && c != delim)
    952 		addchar(c, &s);
    953 	addchar('\0', &s);
    954 	if (c == EOF)
    955 		error("invalid pattern delimiter");
    956 	if (c == '\n') {
    957 		pflag = 'p';
    958 		back(c);
    959 	}
    960 
    961 	if (!strcmp("%", s.str)) {
    962 		free(s.str);
    963 		if (!rhs)
    964 			error("no previous substitution");
    965 	} else {
    966 		free(rhs);
    967 		rhs = s.str;
    968 	}
    969 	s.str = NULL;
    970 }
    971 
    972 static int
    973 getnth(void)
    974 {
    975 	int c;
    976 
    977 	if ((c = input()) == 'g') {
    978 		return -1;
    979 	} else if (isdigit(c)) {
    980 		if (c == '0')
    981 			return -1;
    982 		return c - '0';
    983 	} else {
    984 		back(c);
    985 		return 1;
    986 	}
    987 }
    988 
    989 static void
    990 addpre(String *s)
    991 {
    992 	char *p;
    993 
    994 	for (p = lastmatch; p < lastmatch + matchs[0].rm_so; ++p)
    995 		addchar(*p, s);
    996 }
    997 
    998 static void
    999 addpost(String *s)
   1000 {
   1001 	char c, *p;
   1002 
   1003 	for (p = lastmatch + matchs[0].rm_eo; (c = *p); ++p)
   1004 		addchar(c, s);
   1005 	addchar('\0', s);
   1006 }
   1007 
   1008 static int
   1009 addsub(String *s, int nth, int nmatch)
   1010 {
   1011 	char *end, *q, *p, c;
   1012 	int sub;
   1013 
   1014 	if (nth != nmatch && nth != -1) {
   1015 		q   = lastmatch + matchs[0].rm_so;
   1016 		end = lastmatch + matchs[0].rm_eo;
   1017 		while (q < end)
   1018 			addchar(*q++, s);
   1019 		return 0;
   1020 	}
   1021 
   1022 	for (p = rhs; (c = *p); ++p) {
   1023 		switch (c) {
   1024 		case '&':
   1025 			sub = 0;
   1026 			goto copy_match;
   1027 		case '\\':
   1028 			if ((c = *++p) == '\0')
   1029 				return 1;
   1030 			if (!isdigit(c))
   1031 				goto copy_char;
   1032 			sub = c - '0';
   1033 		copy_match:
   1034 			q   = lastmatch + matchs[sub].rm_so;
   1035 			end = lastmatch + matchs[sub].rm_eo;
   1036 			while (q < end)
   1037 				addchar(*q++, s);
   1038 			break;
   1039 		default:
   1040 		copy_char:
   1041 			addchar(c, s);
   1042 			break;
   1043 		}
   1044 	}
   1045 	return 1;
   1046 }
   1047 
   1048 static void
   1049 subline(int num, int nth)
   1050 {
   1051 	int i, m, changed;
   1052 	static String s;
   1053 
   1054 	i = changed = s.siz = 0;
   1055 	for (m = match(num); m; m = rematch(num)) {
   1056 		addpre(&s);
   1057 		changed |= addsub(&s, nth, ++i);
   1058 		if (eol || bol)
   1059 			break;
   1060 	}
   1061 	if (!changed)
   1062 		return;
   1063 	addpost(&s);
   1064 	delete(num, num);
   1065 	curln = prevln(num);
   1066 	inject(s.str, AFTER);
   1067 }
   1068 
   1069 static void
   1070 subst(int nth)
   1071 {
   1072 	int i;
   1073 
   1074 	for (i = line1; i <= line2; ++i)
   1075 		subline(i, nth);
   1076 }
   1077 
   1078 static void
   1079 docmd(void)
   1080 {
   1081 	char cmd;
   1082 	int rep = 0, c, line3, num, trunc;
   1083 
   1084 repeat:
   1085 	skipblank();
   1086 	cmd = input();
   1087 	trunc = pflag = 0;
   1088 	switch (cmd) {
   1089 	case '&':
   1090 		skipblank();
   1091 		chkprint(0);
   1092 		if (!ocmdline)
   1093 			error("no previous command");
   1094 		rep = 1;
   1095 		repidx = 0;
   1096 		getlst();
   1097 		goto repeat;
   1098 	case '!':
   1099 		execsh();
   1100 		break;
   1101 	case EOF:
   1102 		if (cmdline.siz == 0)
   1103 			quit();
   1104 	case '\n':
   1105 		if (gflag && uflag)
   1106 			return;
   1107 		num = gflag ? curln : curln+1;
   1108 		deflines(num, num);
   1109 		pflag = 'p';
   1110 		goto print;
   1111 	case 'l':
   1112 	case 'n':
   1113 	case 'p':
   1114 		back(cmd);
   1115 		chkprint(1);
   1116 		deflines(curln, curln);
   1117 		goto print;
   1118 	case 'g':
   1119 	case 'G':
   1120 	case 'v':
   1121 	case 'V':
   1122 		error("cannot nest global commands");
   1123 	case 'H':
   1124 		if (nlines > 0)
   1125 			goto unexpected;
   1126 		chkprint(0);
   1127 		optverbose ^= 1;
   1128 		break;
   1129 	case 'h':
   1130 		if (nlines > 0)
   1131 			goto unexpected;
   1132 		chkprint(0);
   1133 		dohelp();
   1134 		break;
   1135 	case 'w':
   1136 		trunc = 1;
   1137 	case 'W':
   1138 		deflines(nextln(0), lastln);
   1139 		dowrite(getfname(cmd), trunc);
   1140 		break;
   1141 	case 'r':
   1142 		if (nlines > 1)
   1143 			goto bad_address;
   1144 		deflines(lastln, lastln);
   1145 		doread(getfname(cmd));
   1146 		break;
   1147 	case 'd':
   1148 		chkprint(1);
   1149 		deflines(curln, curln);
   1150 		delete(line1, line2);
   1151 		break;
   1152 	case '=':
   1153 		if (nlines > 1)
   1154 			goto bad_address;
   1155 		chkprint(1);
   1156 		deflines(lastln, lastln);
   1157 		printf("%d\n", line1);
   1158 		break;
   1159 	case 'u':
   1160 		if (nlines > 0)
   1161 			goto bad_address;
   1162 		chkprint(1);
   1163 		if (udata.nr == 0)
   1164 			error("nothing to undo");
   1165 		undo();
   1166 		break;
   1167 	case 's':
   1168 		deflines(curln, curln);
   1169 		c = input();
   1170 		compile(c);
   1171 		getrhs(c);
   1172 		num = getnth();
   1173 		chkprint(1);
   1174 		subst(num);
   1175 		break;
   1176 	case 'i':
   1177 		if (nlines > 1)
   1178 			goto bad_address;
   1179 		chkprint(1);
   1180 		deflines(curln, curln);
   1181 		if (!line1)
   1182 			line1++;
   1183 		append(prevln(line1));
   1184 		break;
   1185 	case 'a':
   1186 		if (nlines > 1)
   1187 			goto bad_address;
   1188 		chkprint(1);
   1189 		deflines(curln, curln);
   1190 		append(line1);
   1191 		break;
   1192 	case 'm':
   1193 		deflines(curln, curln);
   1194 		if (!address(&line3))
   1195 			line3 = curln;
   1196 		chkprint(1);
   1197 		move(line3);
   1198 		break;
   1199 	case 't':
   1200 		deflines(curln, curln);
   1201 		if (!address(&line3))
   1202 			line3 = curln;
   1203 		chkprint(1);
   1204 		copy(line3);
   1205 		break;
   1206 	case 'c':
   1207 		chkprint(1);
   1208 		deflines(curln, curln);
   1209 		delete(line1, line2);
   1210 		append(prevln(line1));
   1211 		break;
   1212 	case 'j':
   1213 		chkprint(1);
   1214 		deflines(curln, curln+1);
   1215 		if (line1 != line2 && curln != 0)
   1216 	      		join();
   1217 		break;
   1218 	case 'z':
   1219 		if (nlines > 1)
   1220 			goto bad_address;
   1221 		if (isdigit(back(input())))
   1222 			num = getnum();
   1223 		else
   1224 			num = 24;
   1225 		chkprint(1);
   1226 		scroll(num);
   1227 		break;
   1228 	case 'k':
   1229 		if (nlines > 1)
   1230 			goto bad_address;
   1231 		if (!islower(c = input()))
   1232 			error("invalid mark character");
   1233 		chkprint(1);
   1234 		deflines(curln, curln);
   1235 		marks[c - 'a'] = line1;
   1236 		break;
   1237 	case 'P':
   1238 		if (nlines > 0)
   1239 			goto unexpected;
   1240 		chkprint(1);
   1241 		optprompt ^= 1;
   1242 		break;
   1243 	case 'Q':
   1244 		modflag = 0;
   1245 	case 'q':
   1246 		if (nlines > 0)
   1247 			goto unexpected;
   1248 		if (modflag)
   1249 			goto modified;
   1250 		quit();
   1251 		break;
   1252 	case 'f':
   1253 		if (nlines > 0)
   1254 			goto unexpected;
   1255 		if (back(input()) != '\n')
   1256 			getfname(cmd);
   1257 		else
   1258 			puts(savfname);
   1259 		chkprint(0);
   1260 		break;
   1261 	case 'E':
   1262 		modflag = 0;
   1263 	case 'e':
   1264 		if (nlines > 0)
   1265 			goto unexpected;
   1266 		if (modflag)
   1267 			goto modified;
   1268 		getfname(cmd);
   1269 		setscratch();
   1270 		deflines(curln, curln);
   1271 		doread(savfname);
   1272 		clearundo();
   1273 		break;
   1274 	default:
   1275 		error("unknown command");
   1276 	bad_address:
   1277 		error("invalid address");
   1278 	modified:
   1279 		modflag = 0;
   1280 		error("warning: file modified");
   1281 	unexpected:
   1282 		error("unexpected address");
   1283 	}
   1284 
   1285 	if (!pflag)
   1286 		goto save_last_cmd;
   1287 
   1288 	line1 = line2 = curln;
   1289 print:
   1290 	doprint();
   1291 
   1292 save_last_cmd:
   1293 	if (!uflag)
   1294 		repidx = 0;
   1295 	if (rep)
   1296 		return;
   1297 	free(ocmdline);
   1298 	addchar('\0', &cmdline);
   1299 	if ((ocmdline = strdup(cmdline.str)) == NULL)
   1300 		error("out of memory");
   1301 }
   1302 
   1303 static int
   1304 chkglobal(void)
   1305 {
   1306 	int delim, c, dir, i, v;
   1307 
   1308 	uflag = 1;
   1309 	gflag = 0;
   1310 	skipblank();
   1311 
   1312 	switch (c = input()) {
   1313 	case 'g':
   1314 		uflag = 0;
   1315 	case 'G':
   1316 		dir = 1;
   1317 		break;
   1318 	case 'v':
   1319 		uflag = 0;
   1320 	case 'V':
   1321 		dir = 0;
   1322 		break;
   1323 	default:
   1324 		back(c);
   1325 		return 0;
   1326 	}
   1327 	gflag = 1;
   1328 	deflines(nextln(0), lastln);
   1329 	delim = input();
   1330 	compile(delim);
   1331 
   1332 	for (i = 1; i <= lastln; ++i) {
   1333 		if (i >= line1 && i <= line2)
   1334 			v = match(i) == dir;
   1335 		else
   1336 			v = 0;
   1337 		setglobal(i, v);
   1338 	}
   1339 
   1340 	return 1;
   1341 }
   1342 
   1343 static void
   1344 doglobal(void)
   1345 {
   1346 	int cnt, ln, k;
   1347 
   1348 	skipblank();
   1349 	cmdline.siz = 0;
   1350 	gflag = 1;
   1351 	if (uflag)
   1352 		chkprint(0);
   1353 
   1354 	ln = line1;
   1355 	for (cnt = 0; cnt < lastln; ) {
   1356 		k = getindex(ln);
   1357 		if (zero[k].global) {
   1358 			zero[k].global = 0;
   1359 			curln = ln;
   1360 			nlines = 0;
   1361 			if (uflag) {
   1362 				line1 = line2 = ln;
   1363 				pflag = 0;
   1364 				doprint();
   1365 			}
   1366 			getlst();
   1367 			docmd();
   1368 		} else {
   1369 			cnt++;
   1370 			ln = nextln(ln);
   1371 		}
   1372 	}
   1373 	discard();   /* cover the case of not matching anything */
   1374 }
   1375 
   1376 static void
   1377 usage(void)
   1378 {
   1379 	eprintf("usage: %s [-s] [-p] [file]\n", argv0);
   1380 }
   1381 
   1382 static void
   1383 sigintr(int n)
   1384 {
   1385 	signal(SIGINT, sigintr);
   1386 	error("interrupt");
   1387 }
   1388 
   1389 static void
   1390 sighup(int dummy)
   1391 {
   1392 	int n;
   1393 	char *home = getenv("HOME"), fname[FILENAME_MAX];
   1394 
   1395 	if (modflag) {
   1396 		line1 = nextln(0);
   1397 		line2 = lastln;
   1398 		if (!setjmp(savesp)) {
   1399 			dowrite("ed.hup", 1);
   1400 		} else if (home && !setjmp(savesp)) {
   1401 			n = snprintf(fname,
   1402 			             sizeof(fname), "%s/%s", home, "ed.hup");
   1403 			if (n < sizeof(fname) && n > 0)
   1404 				dowrite(fname, 1);
   1405 		}
   1406 	}
   1407 	exstatus = 1;
   1408 	quit();
   1409 }
   1410 
   1411 static void
   1412 edit(void)
   1413 {
   1414 	for (;;) {
   1415 		newcmd = 1;
   1416 		ocurln = curln;
   1417 		olastln = lastln;
   1418 		cmdline.siz = 0;
   1419 		repidx = -1;
   1420 		if (optprompt) {
   1421 			fputs(prompt, stdout);
   1422 			fflush(stdout);
   1423 		}
   1424 		getlst();
   1425 		chkglobal() ? doglobal() : docmd();
   1426 	}
   1427 }
   1428 
   1429 static void
   1430 init(char *fname)
   1431 {
   1432 	size_t len;
   1433 
   1434 	setscratch();
   1435 	if (!fname)
   1436 		return;
   1437 	if ((len = strlen(fname)) >= FILENAME_MAX || len == 0)
   1438 		error("incorrect filename");
   1439 	memcpy(savfname, fname, len);
   1440 	doread(fname);
   1441 	clearundo();
   1442 }
   1443 
   1444 int
   1445 main(int argc, char *argv[])
   1446 {
   1447 	ARGBEGIN {
   1448 	case 'p':
   1449 		prompt = EARGF(usage());
   1450 		optprompt = 1;
   1451 		break;
   1452 	case 's':
   1453 		optdiag = 0;
   1454 		break;
   1455 	default:
   1456 		usage();
   1457 	} ARGEND
   1458 
   1459 	if (argc > 1)
   1460 		usage();
   1461 
   1462 	if (!setjmp(savesp)) {
   1463 		signal(SIGINT, sigintr);
   1464 		signal(SIGHUP, sighup);
   1465 		signal(SIGQUIT, SIG_IGN);
   1466 		init(*argv);
   1467 	}
   1468 	edit();
   1469 
   1470 	/* not reached */
   1471 	return 0;
   1472 }