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