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