make cut buffer displays interruptible
[nvi.git] / common / main.c
blobf8b0259037c7561ab2846aa7d6f011b9687cd372
1 /*-
2 * Copyright (c) 1992, 1993
3 * The Regents of the University of California. All rights reserved.
5 * %sccs.include.redist.c%
6 */
8 #ifndef lint
9 static char copyright[] =
10 "%Z% Copyright (c) 1992, 1993\n\
11 The Regents of the University of California. All rights reserved.\n";
12 #endif /* not lint */
14 #ifndef lint
15 static char sccsid[] = "$Id: main.c,v 8.58 1993/12/26 11:22:45 bostic Exp $ (Berkeley) $Date: 1993/12/26 11:22:45 $";
16 #endif /* not lint */
18 #include <sys/param.h>
19 #include <sys/stat.h>
21 #include <ctype.h>
22 #include <err.h>
23 #include <errno.h>
24 #include <fcntl.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <termios.h>
28 #include <unistd.h>
30 #ifdef __STDC__
31 #include <stdarg.h>
32 #else
33 #include <varargs.h>
34 #endif
36 #include "vi.h"
37 #include "excmd.h"
38 #include "pathnames.h"
39 #include "tag.h"
41 static int exrc_isok __P((SCR *, char *, int));
42 static void gs_end __P((GS *));
43 static GS *gs_init __P((void));
44 static void h_hup __P((int));
45 static void h_term __P((int));
46 static void h_winch __P((int));
47 static void obsolete __P((char *[]));
48 static void usage __P((int));
50 GS *__global_list; /* GLOBAL: List of screens. */
52 int
53 main(argc, argv)
54 int argc;
55 char *argv[];
57 extern int optind;
58 extern char *optarg;
59 static int reenter; /* STATIC: Re-entrancy check. */
60 struct sigaction act;
61 GS *gp;
62 FREF *frp;
63 SCR *sp;
64 u_int flags, saved_vi_mode;
65 int ch, eval, flagchk, readonly, silent, snapshot;
66 char *excmdarg, *myname, *p, *rec_f, *tag_f, *trace_f, *wsizearg;
67 char path[MAXPATHLEN];
69 /* Stop if indirecting through a NULL pointer. */
70 if (reenter++)
71 abort();
73 /* Set screen type and mode based on the program name. */
74 readonly = 0;
75 if ((myname = strrchr(*argv, '/')) == NULL)
76 myname = *argv;
77 else
78 ++myname;
79 if (!strcmp(myname, "ex") || !strcmp(myname, "nex"))
80 LF_INIT(S_EX);
81 else {
82 /* View is readonly. */
83 if (!strcmp(myname, "view"))
84 readonly = 1;
85 LF_INIT(S_VI_CURSES);
87 saved_vi_mode = S_VI_CURSES;
89 /* Convert old-style arguments into new-style ones. */
90 obsolete(argv);
92 /* Parse the arguments. */
93 flagchk = '\0';
94 excmdarg = rec_f = tag_f = trace_f = wsizearg = NULL;
95 silent = 0;
96 snapshot = 1;
97 while ((ch = getopt(argc, argv, "c:eFlRr:sT:t:vw:x:")) != EOF)
98 switch (ch) {
99 case 'c': /* Run the command. */
100 excmdarg = optarg;
101 break;
102 case 'e': /* Ex mode. */
103 LF_CLR(S_SCREENS);
104 LF_SET(S_EX);
105 break;
106 case 'F': /* No snapshot. */
107 snapshot = 0;
108 break;
109 case 'l':
110 if (flagchk != '\0' && flagchk != 'l')
111 errx(1,
112 "only one of -%c and -l may be specified.",
113 flagchk);
114 flagchk = 'l';
115 break;
116 case 'R': /* Readonly. */
117 readonly = 1;
118 break;
119 case 'r': /* Recover. */
120 if (flagchk == 'r')
121 errx(1,
122 "only one recovery file may be specified.");
123 if (flagchk != '\0')
124 errx(1,
125 "only one of -%c and -r may be specified.",
126 flagchk);
127 flagchk = 'r';
128 rec_f = optarg;
129 break;
130 case 's':
131 if (!LF_ISSET(S_EX))
132 errx(1, "-s only applicable to ex.");
133 silent = 1;
134 break;
135 case 'T': /* Trace. */
136 trace_f = optarg;
137 break;
138 case 't': /* Tag. */
139 if (flagchk == 't')
140 errx(1,
141 "only one tag file may be specified.");
142 if (flagchk != '\0')
143 errx(1,
144 "only one of -%c and -t may be specified.",
145 flagchk);
146 flagchk = 't';
147 tag_f = optarg;
148 break;
149 case 'v': /* Vi mode. */
150 LF_CLR(S_SCREENS);
151 LF_SET(S_VI_CURSES);
152 break;
153 case 'w':
154 wsizearg = optarg;
155 break;
156 case 'x':
157 if (!strcmp(optarg, "aw")) {
158 LF_CLR(S_SCREENS);
159 LF_SET(S_VI_XAW);
160 saved_vi_mode = S_VI_XAW;
161 break;
163 /* FALLTHROUGH */
164 case '?':
165 default:
166 usage(LF_ISSET(S_EX));
168 argc -= optind;
169 argv += optind;
171 /* Build and initialize the GS structure. */
172 __global_list = gp = gs_init();
174 if (snapshot)
175 F_SET(gp, G_SNAPSHOT);
177 /* Build and initialize the first/current screen. */
178 if (screen_init(NULL, &sp, flags))
179 goto err1;
180 sp->saved_vi_mode = saved_vi_mode;
181 CIRCLEQ_INSERT_HEAD(&__global_list->dq, sp, q);
183 if (trace_f != NULL) {
184 #ifdef DEBUG
185 if ((gp->tracefp = fopen(optarg, "w")) == NULL)
186 err(1, "%s", optarg);
187 (void)fprintf(gp->tracefp, "\n===\ntrace: open %s\n", optarg);
188 #else
189 msgq(sp, M_ERR, "-T support not compiled into this version.");
190 #endif
193 if (set_window_size(sp, 0, 0)) /* Set the window size. */
194 goto err1;
196 if (opts_init(sp)) /* Options initialization. */
197 goto err1;
198 if (readonly)
199 O_SET(sp, O_READONLY);
200 if (silent) {
201 O_CLR(sp, O_AUTOPRINT);
202 O_CLR(sp, O_PROMPT);
203 O_CLR(sp, O_VERBOSE);
204 O_CLR(sp, O_WARN);
205 F_SET(sp, S_EXSILENT);
207 if (wsizearg != NULL) {
208 ARGS *av[2], a, b;
209 if (strtol(optarg, &p, 10) < 0 || *p)
210 errx(1, "illegal window size -- %s", optarg);
211 (void)snprintf(path, sizeof(path), "window=%s", optarg);
212 a.bp = path;
213 a.len = strlen(path);
214 b.bp = NULL;
215 b.len = 0;
216 av[0] = &a;
217 av[1] = &b;
218 if (opts_set(sp, av))
219 msgq(sp, M_ERR,
220 "Unable to set command line window option");
223 /* Keymaps, special keys, must follow option initializations. */
224 if (term_init(sp))
225 goto err1;
227 #ifdef DIGRAPHS
228 if (digraph_init(sp)) /* Digraph initialization. */
229 goto err1;
230 #endif
233 * Source the system, environment, ~user and local .exrc values.
234 * If the environment exists, vi historically doesn't check ~user.
235 * This is done before the file is read in because things in the
236 * .exrc information can set, for example, the recovery directory.
238 if (!silent) {
239 if (exrc_isok(sp, _PATH_SYSEXRC, 1))
240 (void)ex_cfile(sp, NULL, _PATH_SYSEXRC);
242 /* Source the EXINIT environment variable. */
243 if ((p = getenv("EXINIT")) != NULL)
244 if ((p = strdup(p)) == NULL) {
245 msgq(sp, M_SYSERR, NULL);
246 goto err1;
247 } else {
248 (void)ex_icmd(sp, NULL, p, strlen(p));
249 free(p);
251 else if ((p = getenv("HOME")) != NULL && *p) {
252 (void)snprintf(path,
253 sizeof(path), "%s/%s", p, _PATH_NEXRC);
254 if (exrc_isok(sp, path, 0))
255 (void)ex_cfile(sp, NULL, path);
256 else {
257 (void)snprintf(path,
258 sizeof(path), "%s/%s", p, _PATH_EXRC);
259 if (exrc_isok(sp, path, 0))
260 (void)ex_cfile(sp, NULL, path);
264 * !!!
265 * According to O'Reilly ("Learning the VI Editor", Fifth Ed.,
266 * May 1992, page 106), System V release 3.2 and later, has an
267 * option "[no]exrc", causing vi to not "read .exrc files in
268 * the current directory unless you first set the exrc option
269 * in your home directory's .exrc file". Yeah, right. Did
270 * someone actually believe that users would change their home
271 * .exrc file based on whether or not they wanted to source the
272 * current local .exrc? Or that users would want ALL the local
273 * .exrc files on some systems, and none of them on others?
274 * I think not.
276 * Apply the same tests to local .exrc files that are applied
277 * to any other .exrc file.
279 if (exrc_isok(sp, _PATH_EXRC, 0))
280 (void)ex_cfile(sp, NULL, _PATH_EXRC);
283 /* List recovery files if -l specified. */
284 if (flagchk == 'l')
285 exit(rcv_list(sp));
287 /* Use a tag file or recovery file if specified. */
288 if (tag_f != NULL && ex_tagfirst(sp, tag_f))
289 goto err1;
290 else if (rec_f != NULL && rcv_read(sp, rec_f))
291 goto err1;
293 /* Append any remaining arguments as file names. */
294 if (*argv != NULL)
295 for (; *argv != NULL; ++argv)
296 if (file_add(sp, NULL, *argv, 0) == NULL)
297 goto err1;
300 * If no recovery or tag file, get an EXF structure.
301 * If no argv file, use a temporary file.
303 if (tag_f == NULL && rec_f == NULL) {
304 if ((frp = file_first(sp)) == NULL &&
305 (frp = file_add(sp, NULL, NULL, 1)) == NULL)
306 goto err1;
307 if (file_init(sp, frp, NULL, 0))
308 goto err1;
311 /* Set up the argument pointer. */
312 sp->a_frp = sp->frp;
315 * Initialize the signals. Use sigaction(2), not signal(3), because
316 * we don't want to always restart system calls on 4BSD systems. It
317 * would be nice in some cases to restart system calls, but SA_RESTART
318 * is a 4BSD extension so we can't use it.
320 * SIGWINCH, SIGHUP, SIGTERM:
321 * Catch and set a global bit.
323 act.sa_handler = h_hup;
324 sigemptyset(&act.sa_mask);
325 act.sa_flags = 0;
326 (void)sigaction(SIGHUP, &act, NULL);
327 act.sa_handler = h_term;
328 sigemptyset(&act.sa_mask);
329 act.sa_flags = 0;
330 (void)sigaction(SIGTERM, &act, NULL);
331 act.sa_handler = h_winch;
332 sigemptyset(&act.sa_mask);
333 act.sa_flags = 0;
334 (void)sigaction(SIGWINCH, &act, NULL);
337 * SIGQUIT:
338 * Always ignore.
340 act.sa_handler = SIG_IGN;
341 sigemptyset(&act.sa_mask);
342 act.sa_flags = 0;
343 (void)sigaction(SIGQUIT, &act, NULL);
346 * If there's an initial command, push it on the command stack.
347 * Historically, it was always an ex command, not vi in vi mode
348 * or ex in ex mode. So, make it look like an ex command to vi.
350 if (excmdarg != NULL)
351 if (IN_EX_MODE(sp)) {
352 if (term_push(sp, excmdarg, strlen(excmdarg), 0, 0))
353 goto err1;
354 } else if (IN_VI_MODE(sp)) {
355 if (term_push(sp, "\n", 1, 0, 0))
356 goto err1;
357 if (term_push(sp, excmdarg, strlen(excmdarg), 0, 0))
358 goto err1;
359 if (term_push(sp, ":", 1, 0, 0))
360 goto err1;
363 /* Vi reads from the terminal. */
364 if (!F_ISSET(gp, G_ISFROMTTY) && !F_ISSET(sp, S_EX)) {
365 msgq(sp, M_ERR, "Vi's standard input must be a terminal.");
366 goto err1;
369 for (;;) {
370 if (sp->s_edit(sp, sp->ep))
371 goto err2;
374 * Edit the next screen on the display queue, or, move
375 * a screen from the hidden queue to the display queue.
377 if ((sp = __global_list->dq.cqh_first) ==
378 (void *)&__global_list->dq)
379 if ((sp = __global_list->hq.cqh_first) !=
380 (void *)&__global_list->hq) {
381 CIRCLEQ_REMOVE(&sp->gp->hq, sp, q);
382 CIRCLEQ_INSERT_TAIL(&sp->gp->dq, sp, q);
383 } else
384 break;
387 * The screen type may have changed -- reinitialize the
388 * functions in case it has.
390 switch (F_ISSET(sp, S_SCREENS)) {
391 case S_EX:
392 if (sex_screen_init(sp))
393 goto err2;
394 break;
395 case S_VI_CURSES:
396 if (svi_screen_init(sp))
397 goto err2;
398 break;
399 case S_VI_XAW:
400 if (xaw_screen_init(sp))
401 goto err2;
402 break;
403 default:
404 abort();
409 * Two error paths. The first means that something failed before
410 * we called a screen routine. Swap the message pointers between
411 * the SCR and the GS, so messages get displayed. The second is
412 * something failed in a screen. NOTE: sp may be GONE when the
413 * screen returns, so only the gp can be trusted.
415 eval = 0;
416 if (0) {
417 err1: gp->msgq.lh_first = sp->msgq.lh_first;
418 err2: eval = 1;
421 gs_end(gp);
423 /* Make absolutely sure that the modes are restored correctly. */
424 if (F_ISSET(gp, G_ISFROMTTY) &&
425 tcsetattr(STDIN_FILENO, TCSADRAIN, &gp->original_termios))
426 err(1, "tcsetattr");
427 exit(eval);
431 * gs_init --
432 * Build and initialize the GS structure.
434 static GS *
435 gs_init()
437 GS *gp;
438 int fd;
440 CALLOC_NOMSG(NULL, gp, GS *, 1, sizeof(GS));
441 if (gp == NULL)
442 err(1, NULL);
444 CIRCLEQ_INIT(&gp->dq);
445 CIRCLEQ_INIT(&gp->hq);
446 LIST_INIT(&gp->msgq);
448 /* Structures shared by screens so stored in the GS structure. */
449 CALLOC_NOMSG(NULL, gp->tty, IBUF *, 1, sizeof(IBUF));
450 if (gp->tty == NULL)
451 err(1, NULL);
453 LIST_INIT(&gp->cutq);
454 LIST_INIT(&gp->seqq);
456 /* Set a flag if we're reading from the tty. */
457 if (isatty(STDIN_FILENO))
458 F_SET(gp, G_ISFROMTTY);
461 * XXX
462 * Set a flag and don't do terminal sets/resets if the input isn't
463 * from a tty. Under all circumstances put reasonable things into
464 * the original_termios field, as some routines (seq.c:seq_save()
465 * and term.c:term_init()) want values for special characters.
467 if (F_ISSET(gp, G_ISFROMTTY)) {
468 if (tcgetattr(STDIN_FILENO, &gp->original_termios))
469 err(1, "tcgetattr");
470 } else {
471 if ((fd = open(_PATH_TTY, O_RDONLY, 0)) == -1)
472 err(1, "%s", _PATH_TTY);
473 if (tcgetattr(fd, &gp->original_termios))
474 err(1, "tcgetattr");
475 (void)close(fd);
478 return (gp);
483 * gs_end --
484 * End the GS structure.
486 static void
487 gs_end(gp)
488 GS *gp;
490 MSG *mp;
491 SCR *sp;
492 char *tty;
494 /* Reset anything that needs resetting. */
495 if (gp->flags & G_SETMODE) /* O_MESG */
496 if ((tty = ttyname(STDERR_FILENO)) == NULL)
497 warn("ttyname");
498 else if (chmod(tty, gp->origmode) < 0)
499 warn("%s", tty);
501 /* Ring the bell if scheduled. */
502 if (F_ISSET(gp, G_BELLSCHED))
503 (void)fprintf(stderr, "\07"); /* \a */
505 /* If there are any remaining screens, flush their messages. */
506 for (sp = __global_list->dq.cqh_first;
507 sp != (void *)&__global_list->dq; sp = sp->q.cqe_next)
508 for (mp = sp->msgq.lh_first;
509 mp != NULL && !(F_ISSET(mp, M_EMPTY)); mp = mp->q.le_next)
510 (void)fprintf(stderr, "%.*s\n", (int)mp->len, mp->mbuf);
511 for (sp = __global_list->hq.cqh_first;
512 sp != (void *)&__global_list->hq; sp = sp->q.cqe_next)
513 for (mp = sp->msgq.lh_first;
514 mp != NULL && !(F_ISSET(mp, M_EMPTY)); mp = mp->q.le_next)
515 (void)fprintf(stderr, "%.*s\n", (int)mp->len, mp->mbuf);
516 /* Flush messages on the global queue. */
517 for (mp = gp->msgq.lh_first;
518 mp != NULL && !(F_ISSET(mp, M_EMPTY)); mp = mp->q.le_next)
519 (void)fprintf(stderr, "%.*s\n", (int)mp->len, mp->mbuf);
521 FREE(gp->special_key, MAX_FAST_KEY);
524 * DON'T FREE THE GLOBAL STRUCTURE -- WE DIDN'T TURN
525 * OFF SIGNALS/TIMERS, SO IT MAY STILL BE REFERENCED.
530 * h_hup --
531 * Handle SIGHUP.
533 static void
534 h_hup(signo)
535 int signo;
537 F_SET(__global_list, G_SIGHUP);
540 * If we're asleep, just die.
542 * XXX
543 * This isn't right if the windows are independent.
545 if (F_ISSET(__global_list, G_SLEEPING))
546 rcv_hup();
550 * h_term --
551 * Handle SIGTERM.
553 static void
554 h_term(signo)
555 int signo;
557 F_SET(__global_list, G_SIGTERM);
560 * If we're asleep, just die.
562 * XXX
563 * This isn't right if the windows are independent.
565 if (F_ISSET(__global_list, G_SLEEPING))
566 rcv_term();
570 * h_winch --
571 * Handle SIGWINCH.
573 static void
574 h_winch(signo)
575 int signo;
577 F_SET(__global_list, G_SIGWINCH);
581 * exrc_isok --
582 * Check a .exrc for source-ability.
584 static int
585 exrc_isok(sp, path, rootok)
586 SCR *sp;
587 char *path;
588 int rootok;
590 struct stat sb;
591 uid_t uid;
592 char *emsg, buf[MAXPATHLEN];
594 /* Check for the file's existence. */
595 if (stat(path, &sb))
596 return (0);
599 * !!!
600 * Historically, vi did not read the .exrc files if they were owned
601 * by someone other than the user, unless the undocumented option
602 * sourceany was set. We don't support the sourceany option. We
603 * check that the user (or root, for system files) owns the file and
604 * require that it not be writeable by anyone other than the owner.
607 /* Owned by the user or root. */
608 uid = getuid();
609 if (rootok) {
610 if (sb.st_uid != uid && sb.st_uid != 0) {
611 emsg = "not owned by you or root";
612 goto err;
614 } else
615 if (sb.st_uid != uid) {
616 emsg = "not owned by you";
617 goto err;
620 /* Not writeable by anyone but the owner. */
621 if (sb.st_mode & (S_IWGRP | S_IWOTH)) {
622 emsg = "writeable by a user other than the owner";
623 err: if (strchr(path, '/') == NULL &&
624 getcwd(buf, sizeof(buf)) != NULL)
625 msgq(sp, M_ERR,
626 "%s/%s: not sourced: %s.", buf, path, emsg);
627 else
628 msgq(sp, M_ERR,
629 "%s: not sourced: %s.", path, emsg);
630 return (0);
632 return (1);
635 static void
636 obsolete(argv)
637 char *argv[];
639 size_t len;
640 char *p, *myname;
643 * Translate old style arguments into something getopt will like.
644 * Make sure it's not text space memory, because ex changes the
645 * strings.
646 * Change "+" into "-c$".
647 * Change "+<anything else>" into "-c<anything else>".
648 * Change "-" into "-s"
649 * Change "-r" into "-l"
651 for (myname = argv[0]; *++argv;)
652 if (argv[0][0] == '+') {
653 if (argv[0][1] == '\0') {
654 MALLOC_NOMSG(NULL, argv[0], char *, 4);
655 if (argv[0] == NULL)
656 err(1, NULL);
657 (void)strcpy(argv[0], "-c$");
658 } else {
659 p = argv[0];
660 len = strlen(argv[0]);
661 MALLOC_NOMSG(NULL, argv[0], char *, len + 2);
662 if (argv[0] == NULL)
663 err(1, NULL);
664 argv[0][0] = '-';
665 argv[0][1] = 'c';
666 (void)strcpy(argv[0] + 2, p + 1);
668 } else if (argv[0][0] == '-') {
669 if (argv[0][1] == 'r') {
670 if (argv[0][2] == '\0' && argv[1] == NULL)
671 argv[0][1] = 'l';
672 } else if (argv[0][1] == '\0') {
673 MALLOC_NOMSG(NULL, argv[0], char *, 3);
674 if (argv[0] == NULL)
675 err(1, NULL);
676 (void)strcpy(argv[0], "-s");
681 static void
682 usage(is_ex)
683 int is_ex;
685 #define EX_USAGE \
686 "usage: ex [-eFlRsv] [-c command] [-r file] [-t tag] [-w size] [-x aw]"
687 #define VI_USAGE \
688 "usage: vi [-eFlRv] [-c command] [-r file] [-t tag] [-w size] [-x aw]"
690 (void)fprintf(stderr, "%s\n", is_ex ? EX_USAGE : VI_USAGE);
691 exit(1);