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