include seq.h in each file, now, only included in a few places
[nvi.git] / common / main.c
blobc8197c5d00a30b2cf2c7e359ec4eff8d650d6068
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.46 1993/11/19 10:54:05 bostic Exp $ (Berkeley) $Date: 1993/11/19 10:54:05 $";
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 GS *gs_init __P((void));
42 static void h_hup __P((int));
43 static void h_term __P((int));
44 static void h_winch __P((int));
45 static void msgflush __P((GS *));
46 static void obsolete __P((char *[]));
47 static void reset __P((GS *));
48 static void usage __P((void));
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 struct stat sb;
62 GS *gp;
63 FREF *frp;
64 SCR *sp;
65 u_int flags;
66 int ch, eval, flagchk, readonly, snapshot;
67 char *excmdarg, *myname, *p, *rec_f, *tag_f, *trace_f, *wsizearg;
68 char *av[2], path[MAXPATHLEN];
70 /* Stop if indirecting through a NULL pointer. */
71 if (reenter++)
72 abort();
74 /* Set screen type and mode based on the program name. */
75 readonly = 0;
76 if ((myname = strrchr(*argv, '/')) == NULL)
77 myname = *argv;
78 else
79 ++myname;
80 if (!strcmp(myname, "ex") || !strcmp(myname, "nex"))
81 LF_INIT(S_EX);
82 else {
83 /* View is readonly. */
84 if (!strcmp(myname, "view"))
85 readonly = 1;
86 LF_INIT(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 snapshot = 1;
96 while ((ch = getopt(argc, argv, "c:elmRr:sT:t:vw:x:")) != EOF)
97 switch (ch) {
98 case 'c': /* Run the command. */
99 excmdarg = optarg;
100 break;
101 case 'e': /* Ex mode. */
102 LF_CLR(S_SCREENS);
103 LF_SET(S_EX);
104 break;
105 case 'l':
106 if (flagchk != '\0' && flagchk != 'l')
107 errx(1,
108 "only one of -%c and -l may be specified.",
109 flagchk);
110 flagchk = 'l';
111 break;
112 case 'R': /* Readonly. */
113 readonly = 1;
114 break;
115 case 'r': /* Recover. */
116 if (flagchk == 'r')
117 errx(1,
118 "only one recovery file may be specified.");
119 if (flagchk != '\0')
120 errx(1,
121 "only one of -%c and -r may be specified.",
122 flagchk);
123 flagchk = 'r';
124 rec_f = optarg;
125 break;
126 case 's': /* No snapshot. */
127 snapshot = 0;
128 break;
129 case 'T': /* Trace. */
130 trace_f = optarg;
131 break;
132 case 't': /* Tag. */
133 if (flagchk == 't')
134 errx(1,
135 "only one tag file may be specified.");
136 if (flagchk != '\0')
137 errx(1,
138 "only one of -%c and -t may be specified.",
139 flagchk);
140 flagchk = 't';
141 tag_f = optarg;
142 break;
143 case 'v': /* Vi mode. */
144 LF_CLR(S_SCREENS);
145 LF_SET(S_VI_CURSES);
146 break;
147 case 'w':
148 wsizearg = optarg;
149 break;
150 case 'x':
151 if (!strcmp(optarg, "aw")) {
152 F_CLR(sp, S_SCREENS);
153 F_SET(sp, S_VI_XAW);
154 break;
156 /* FALLTHROUGH */
157 case '?':
158 default:
159 usage();
161 argc -= optind;
162 argv += optind;
164 /* Build and initialize the GS structure. */
165 __global_list = gp = gs_init();
167 if (snapshot)
168 F_SET(gp, G_SNAPSHOT);
170 /* Build and initialize the first/current screen. */
171 if (screen_init(NULL, &sp, flags))
172 goto err1;
173 CIRCLEQ_INSERT_HEAD(&__global_list->dq, sp, q);
175 if (trace_f != NULL) {
176 #ifdef DEBUG
177 if ((gp->tracefp = fopen(optarg, "w")) == NULL)
178 err(1, "%s", optarg);
179 (void)fprintf(gp->tracefp, "\n===\ntrace: open %s\n", optarg);
180 #else
181 msgq(sp, M_ERR, "-T support not compiled into this version.");
182 #endif
185 if (set_window_size(sp, 0, 0)) /* Set the window size. */
186 goto err1;
188 if (opts_init(sp)) /* Options initialization. */
189 goto err1;
190 if (readonly)
191 O_SET(sp, O_READONLY);
192 if (wsizearg != NULL) {
193 av[0] = path;
194 av[1] = NULL;
195 if (strtol(optarg, &p, 10) < 0 || *p)
196 errx(1, "illegal window size -- %s", optarg);
197 (void)snprintf(path, sizeof(path), "window=%s", optarg);
198 if (opts_set(sp, av))
199 msgq(sp, M_ERR,
200 "Unable to set command line window option");
203 /* Keymaps, special keys, must follow option initializations. */
204 if (term_init(sp))
205 goto err1;
207 #ifdef DIGRAPHS
208 if (digraph_init(sp)) /* Digraph initialization. */
209 goto err1;
210 #endif
213 * Source the system, environment, ~user and local .exrc values.
214 * If the environment exists, vi historically doesn't check ~user.
215 * This is done before the file is read in because things in the
216 * .exrc information can set, for example, the recovery directory.
218 if (!stat(_PATH_SYSEXRC, &sb))
219 (void)ex_cfile(sp, NULL, _PATH_SYSEXRC);
221 /* Source the EXINIT environment variable. */
222 if ((p = getenv("EXINIT")) != NULL)
223 if ((p = strdup(p)) == NULL) {
224 msgq(sp, M_SYSERR, NULL);
225 goto err1;
226 } else {
227 (void)ex_cstring(sp, NULL, p, strlen(p));
228 free(p);
230 else if ((p = getenv("HOME")) != NULL && *p) {
231 (void)snprintf(path, sizeof(path), "%s/%s", p, _PATH_NEXRC);
232 if (!stat(path, &sb))
233 (void)ex_cfile(sp, NULL, path);
234 else {
235 (void)snprintf(path,
236 sizeof(path), "%s/%s", p, _PATH_EXRC);
237 if (!stat(path, &sb))
238 (void)ex_cfile(sp, NULL, path);
241 if (O_ISSET(sp, O_EXRC) && !stat(_PATH_EXRC, &sb))
242 (void)ex_cfile(sp, NULL, _PATH_EXRC);
244 /* List recovery files if -l specified. */
245 if (flagchk == 'l')
246 exit(rcv_list(sp));
248 /* Use a tag file or recovery file if specified. */
249 if (tag_f != NULL && ex_tagfirst(sp, tag_f))
250 goto err1;
251 else if (rec_f != NULL && rcv_read(sp, rec_f))
252 goto err1;
254 /* Append any remaining arguments as file names. */
255 if (*argv != NULL)
256 for (; *argv != NULL; ++argv)
257 if (file_add(sp, NULL, *argv, 0) == NULL)
258 goto err1;
261 * If no recovery or tag file, get an EXF structure.
262 * If no argv file, use a temporary file.
264 if (tag_f == NULL && rec_f == NULL) {
265 if ((frp = file_first(sp, 1)) == NULL &&
266 (frp = file_add(sp, NULL, NULL, 0)) == NULL)
267 goto err1;
268 if (file_init(sp, frp, NULL, 0))
269 goto err1;
273 * Initialize the signals. Use sigaction(2), not signal(3), because
274 * we don't want to always restart system calls on 4BSD systems. It
275 * would be nice in some cases to restart system calls, but SA_RESTART
276 * is a 4BSD extension so we can't use it.
278 * SIGWINCH, SIGHUP, SIGTERM:
279 * Catch and set a global bit.
281 act.sa_handler = h_hup;
282 sigemptyset(&act.sa_mask);
283 act.sa_flags = 0;
284 (void)sigaction(SIGHUP, &act, NULL);
285 act.sa_handler = h_term;
286 sigemptyset(&act.sa_mask);
287 act.sa_flags = 0;
288 (void)sigaction(SIGTERM, &act, NULL);
289 act.sa_handler = h_winch;
290 sigemptyset(&act.sa_mask);
291 act.sa_flags = 0;
292 (void)sigaction(SIGWINCH, &act, NULL);
295 * SIGQUIT:
296 * Always ignore.
298 act.sa_handler = SIG_IGN;
299 sigemptyset(&act.sa_mask);
300 act.sa_flags = 0;
301 (void)sigaction(SIGQUIT, &act, NULL);
304 * If there's an initial command, push it on the command stack.
305 * Historically, it was always an ex command, not vi in vi mode
306 * or ex in ex mode. So, make it look like an ex command to vi.
308 if (excmdarg != NULL)
309 if (IN_EX_MODE(sp)) {
310 if (term_push(sp, sp->gp->tty,
311 excmdarg, strlen(excmdarg)))
312 goto err1;
313 } else if (IN_VI_MODE(sp)) {
314 if (term_push(sp, sp->gp->tty, "\n", 1))
315 goto err1;
316 if (term_push(sp, sp->gp->tty,
317 excmdarg, strlen(excmdarg)))
318 goto err1;
319 if (term_push(sp, sp->gp->tty, ":", 1))
320 goto err1;
323 /* Vi reads from the terminal. */
324 if (!F_ISSET(gp, G_ISFROMTTY) && !F_ISSET(sp, S_EX)) {
325 msgq(sp, M_ERR, "Vi's standard input must be a terminal.");
326 goto err1;
329 for (;;) {
330 if (sp->s_edit(sp, sp->ep))
331 goto err2;
334 * Edit the next screen on the display queue, or, move
335 * a screen from the hidden queue to the display queue.
337 if ((sp = __global_list->dq.cqh_first) ==
338 (void *)&__global_list->dq)
339 if ((sp = __global_list->hq.cqh_first) !=
340 (void *)&__global_list->hq) {
341 CIRCLEQ_REMOVE(&sp->gp->hq, sp, q);
342 CIRCLEQ_INSERT_TAIL(&sp->gp->dq, sp, q);
343 } else
344 break;
347 * The screen type may have changed -- reinitialize the
348 * functions in case it has.
350 switch (F_ISSET(sp, S_SCREENS)) {
351 case S_EX:
352 if (sex_screen_init(sp))
353 return (1);
354 break;
355 case S_VI_CURSES:
356 if (svi_screen_init(sp))
357 return (1);
358 break;
359 case S_VI_XAW:
360 if (xaw_screen_init(sp))
361 return (1);
362 break;
363 default:
364 abort();
369 * Two error paths. The first means that something failed before
370 * we called a screen routine. Swap the message pointers between
371 * the SCR and the GS, so messages get displayed. The second is
372 * something failed in a screen. NOTE: sp may be GONE when the
373 * screen returns, so only the gp can be trusted.
375 eval = 0;
376 if (0) {
377 err1: gp->msgq.lh_first = sp->msgq.lh_first;
378 err2: eval = 1;
381 /* Reset anything that needs resetting. */
382 reset(gp);
384 /* Flush any left-over error messages. */
385 msgflush(gp);
388 * DON'T FREE THE GLOBAL STRUCTURE -- WE DIDN'T TURN
389 * OFF SIGNALS/TIMERS, SO IT MAY STILL BE REFERENCED.
392 /* Make absolutely sure that the modes are restored correctly. */
393 if (F_ISSET(gp, G_ISFROMTTY) &&
394 tcsetattr(STDIN_FILENO, TCSADRAIN, &gp->original_termios))
395 err(1, "tcsetattr");
396 exit(eval);
400 * gs_init --
401 * Build and initialize the GS structure.
403 static GS *
404 gs_init()
406 GS *gp;
407 int fd;
409 if ((gp = malloc(sizeof(GS))) == NULL)
410 err(1, NULL);
411 memset(gp, 0, sizeof(GS));
413 CIRCLEQ_INIT(&gp->dq);
414 CIRCLEQ_INIT(&gp->hq);
415 LIST_INIT(&gp->msgq);
417 /* Structures shared by screens so stored in the GS structure. */
418 if ((gp->key = malloc(sizeof(IBUF))) == NULL)
419 err(1, NULL);
420 memset(gp->key, 0, sizeof(IBUF));
421 if ((gp->tty = malloc(sizeof(IBUF))) == NULL)
422 err(1, NULL);
423 memset(gp->tty, 0, sizeof(IBUF));
425 LIST_INIT(&gp->cutq);
426 LIST_INIT(&gp->seqq);
428 /* Set a flag if we're reading from the tty. */
429 if (isatty(STDIN_FILENO))
430 F_SET(gp, G_ISFROMTTY);
433 * XXX
434 * Set a flag and don't do terminal sets/resets if the input isn't
435 * from a tty. Under all circumstances put reasonable things into
436 * the original_termios field, as some routines (seq.c:seq_save()
437 * and term.c:term_init()) want values for special characters.
439 if (F_ISSET(gp, G_ISFROMTTY)) {
440 if (tcgetattr(STDIN_FILENO, &gp->original_termios))
441 err(1, "tcgetattr");
442 } else {
443 if ((fd = open(_PATH_TTY, O_RDONLY, 0)) == -1)
444 err(1, "%s", _PATH_TTY);
445 if (tcgetattr(fd, &gp->original_termios))
446 err(1, "tcgetattr");
447 (void)close(fd);
450 return (gp);
454 * reset --
455 * Reset any changed global state.
457 static void
458 reset(gp)
459 GS *gp;
461 char *tty;
463 if (gp->flags & G_SETMODE) /* O_MESG */
464 if ((tty = ttyname(STDERR_FILENO)) == NULL)
465 warn("ttyname");
466 else if (chmod(tty, gp->origmode) < 0)
467 warn("%s", tty);
471 * msgflush --
472 * Flush any remaining messages.
474 static void
475 msgflush(gp)
476 GS *gp;
478 MSG *mp;
480 /* Ring the bell. */
481 if (F_ISSET(gp, G_BELLSCHED))
482 (void)fprintf(stderr, "\07"); /* \a */
484 /* Display the messages. */
485 for (mp = gp->msgq.lh_first;
486 mp != NULL && !(F_ISSET(mp, M_EMPTY)); mp = mp->q.le_next)
487 (void)fprintf(stderr, "%.*s\n", (int)mp->len, mp->mbuf);
491 * h_hup --
492 * Handle SIGHUP.
494 static void
495 h_hup(signo)
496 int signo;
498 F_SET(__global_list, G_SIGHUP);
501 * If we're asleep, just die.
503 * XXX
504 * This isn't right if the windows are independent.
506 if (F_ISSET(__global_list, G_SLEEPING))
507 rcv_hup();
511 * h_term --
512 * Handle SIGTERM.
514 static void
515 h_term(signo)
516 int signo;
518 F_SET(__global_list, G_SIGTERM);
521 * If we're asleep, just die.
523 * XXX
524 * This isn't right if the windows are independent.
526 if (F_ISSET(__global_list, G_SLEEPING))
527 rcv_term();
531 * h_winch --
532 * Handle SIGWINCH.
534 static void
535 h_winch(signo)
536 int signo;
538 F_SET(__global_list, G_SIGWINCH);
541 static void
542 obsolete(argv)
543 char *argv[];
545 size_t len;
546 char *p, *myname;
549 * Translate old style arguments into something getopt will like.
550 * Make sure it's not text space memory, because ex changes the
551 * strings.
552 * Change "+" into "-c$".
553 * Change "+<anything else>" into "-c<anything else>".
554 * Change "-r" into "-l"
556 for (myname = argv[0]; *++argv;)
557 if (argv[0][0] == '+') {
558 if (argv[0][1] == '\0') {
559 if ((argv[0] = malloc(4)) == NULL)
560 err(1, NULL);
561 (void)strcpy(argv[0], "-c$");
562 } else {
563 p = argv[0];
564 len = strlen(argv[0]);
565 if ((argv[0] = malloc(len + 2)) == NULL)
566 err(1, NULL);
567 argv[0][0] = '-';
568 argv[0][1] = 'c';
569 (void)strcpy(argv[0] + 2, p + 1);
572 else if (argv[0][0] == '-' &&
573 argv[0][1] == 'r' && argv[0][2] == '\0' && argv[1] == NULL)
574 argv[0][1] = 'l';
577 static void
578 usage()
580 (void)fprintf(stderr, "%s%s\n",
581 "usage: vi [-eRsv] [-c command] [-m file] [-r file] ",
582 "[-t tag] [-w size] [-x aw]");
583 exit(1);