go to 0.81
[nvi.git] / common / main.c
blob0a9cbca1aeb35eeec1db94acf4ce039af749b962
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.34 1993/11/04 16:16:07 bostic Exp $ (Berkeley) $Date: 1993/11/04 16:16:07 $";
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 "recover.h"
39 #include "pathnames.h"
40 #include "tag.h"
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 enum { EX_SCR, VI_CURSES_SCR, VI_XAW_SCR } scr_type;
61 struct sigaction act;
62 struct stat sb;
63 GS *gp;
64 FREF *frp;
65 SCR *nsp, *sp;
66 int ch, fd, flagchk, eval;
67 char *excmdarg, *errf, *myname, *p, *rfname, *tfname;
68 char *av[2], path[MAXPATHLEN];
70 /* Stop if indirecting through a NULL pointer. */
71 if (reenter++)
72 abort();
74 eval = 0;
76 /* Figure out the program name. */
77 if ((myname = strrchr(*argv, '/')) == NULL)
78 myname = *argv;
79 else
80 ++myname;
82 /* Build and initialize the GS structure. */
83 if ((gp = malloc(sizeof(GS))) == NULL)
84 err(1, NULL);
85 __global_list = gp;
86 memset(gp, 0, sizeof(GS));
88 /* Structures shared by screens so stored in the GS structure. */
89 if ((gp->key = malloc(sizeof(IBUF))) == NULL)
90 err(1, NULL);
91 memset(gp->key, 0, sizeof(IBUF));
92 if ((gp->tty = malloc(sizeof(IBUF))) == NULL)
93 err(1, NULL);
94 memset(gp->tty, 0, sizeof(IBUF));
96 /* Set a flag if we're reading from the tty. */
97 if (isatty(STDIN_FILENO))
98 F_SET(gp, G_ISFROMTTY);
101 * XXX
102 * Set a flag and don't do terminal sets/resets if the input isn't
103 * from a tty. This should eventually be fixed so that users can
104 * pipe input to nvi. Note, under all circumstances put reasonable
105 * things into the original_termios field, as seq.c:seq_save() and
106 * term.c:term_init() want values for special characters.
108 if (F_ISSET(gp, G_ISFROMTTY)) {
109 if (tcgetattr(STDIN_FILENO, &gp->original_termios))
110 err(1, "tcgetattr");
111 } else {
112 if ((fd = open(_PATH_TTY, O_RDONLY, 0)) == -1)
113 err(1, "%s", _PATH_TTY);
114 if (tcgetattr(fd, &gp->original_termios))
115 err(1, "tcgetattr");
116 (void)close(fd);
119 /* Build and initialize the first/current screen. */
120 if ((sp = malloc(sizeof(SCR))) == NULL)
121 err(1, NULL);
122 if (screen_init(NULL, sp))
123 err(1, NULL);
125 sp->gp = gp; /* All screens point to the GS structure. */
127 if (set_window_size(sp, 0, 0)) /* Set the window size. */
128 goto err1;
130 if (opts_init(sp)) /* Options initialization. */
131 goto err1;
134 * Keymaps, special keys.
135 * Must follow options and sequence map initializations.
137 if (term_init(sp))
138 goto err1;
140 #ifndef NO_DIGRAPH
141 if (digraph_init(sp)) /* Digraph initialization. */
142 goto err1;
143 #endif
144 /* Set screen type and mode based on the program name. */
145 if (!strcmp(myname, "ex") || !strcmp(myname, "nex")) {
146 F_SET(sp, S_MODE_EX);
147 scr_type = EX_SCR;
148 } else {
149 if (!strcmp(myname, "view"))
150 O_SET(sp, O_READONLY);
151 F_SET(sp, S_MODE_VI);
152 scr_type = VI_CURSES_SCR;
155 /* Convert old-style arguments into new-style ones. */
156 obsolete(argv);
158 F_SET(gp, G_SNAPSHOT); /* Default to a snapshot. */
160 /* Parse the arguments. */
161 flagchk = '\0';
162 excmdarg = errf = rfname = tfname = NULL;
163 while ((ch = getopt(argc, argv, "c:elmRr:sT:t:vw:x:")) != EOF)
164 switch (ch) {
165 case 'c': /* Run the command. */
166 excmdarg = optarg;
167 break;
168 case 'e': /* Ex mode. */
169 F_SET(sp, S_MODE_EX);
170 break;
171 case 'l':
172 if (flagchk != '\0' && flagchk != 'l')
173 errx(1,
174 "only one of -%c and -l may be specified.",
175 flagchk);
176 flagchk = 'l';
177 break;
178 case 'R': /* Readonly. */
179 O_SET(sp,O_READONLY);
180 break;
181 case 'r': /* Recover. */
182 if (flagchk == 'r')
183 errx(1,
184 "only one recovery file may be specified.");
185 if (flagchk != '\0')
186 errx(1,
187 "only one of -%c and -r may be specified.",
188 flagchk);
189 flagchk = 'r';
190 rfname = optarg;
191 break;
192 case 's': /* No snapshot. */
193 F_CLR(gp, G_SNAPSHOT);
194 break;
195 case 'T': /* Trace. */
196 #ifdef DEBUG
197 if ((gp->tracefp = fopen(optarg, "w")) == NULL)
198 err(1, "%s", optarg);
199 (void)fprintf(gp->tracefp,
200 "\n===\ntrace: open %s\n", optarg);
201 #else
202 msgq(sp, M_ERR,
203 "-T support not compiled into this version.");
204 #endif
205 break;
206 case 't': /* Tag. */
207 if (flagchk == 't')
208 errx(1,
209 "only one tag file may be specified.");
210 if (flagchk != '\0')
211 errx(1,
212 "only one of -%c and -t may be specified.",
213 flagchk);
214 flagchk = 't';
215 tfname = optarg;
216 break;
217 case 'v': /* Vi mode. */
218 F_SET(sp, S_MODE_VI);
219 if (scr_type == EX_SCR)
220 scr_type = VI_CURSES_SCR;
221 break;
222 case 'w':
223 av[0] = path;
224 av[1] = NULL;
225 if (strtol(optarg, &p, 10) < 0 || *p)
226 errx(1, "illegal window size -- %s", optarg);
227 (void)snprintf(path,
228 sizeof(path), "window=%s", optarg);
229 if (opts_set(sp, av))
230 msgq(sp, M_ERR,
231 "Unable to set command line window option");
232 break;
233 case 'x':
234 if (!strcmp(optarg, "aw")) {
235 scr_type = VI_XAW_SCR;
236 break;
238 /* FALLTHROUGH */
239 case '?':
240 default:
241 usage();
243 argc -= optind;
244 argv += optind;
247 * Source the system, environment, ~user and local .exrc values.
248 * If the environment exists, vi historically doesn't check ~user.
249 * This is done before the file is read in because things in the
250 * .exrc information can set, for example, the recovery directory.
252 if (!stat(_PATH_SYSEXRC, &sb))
253 (void)ex_cfile(sp, NULL, _PATH_SYSEXRC);
255 /* Source the EXINIT environment variable. */
256 if ((p = getenv("EXINIT")) != NULL)
257 if ((p = strdup(p)) == NULL) {
258 msgq(sp, M_ERR, "Error: %s", strerror(errno));
259 goto err1;
260 } else {
261 (void)ex_cstring(sp, NULL, p, strlen(p));
262 free(p);
264 else if ((p = getenv("HOME")) != NULL && *p) {
265 (void)snprintf(path, sizeof(path), "%s/%s", p, _PATH_NEXRC);
266 if (!stat(path, &sb))
267 (void)ex_cfile(sp, NULL, path);
268 else {
269 (void)snprintf(path,
270 sizeof(path), "%s/%s", p, _PATH_EXRC);
271 if (!stat(path, &sb))
272 (void)ex_cfile(sp, NULL, path);
275 if (O_ISSET(sp, O_EXRC) && !stat(_PATH_EXRC, &sb))
276 (void)ex_cfile(sp, NULL, _PATH_EXRC);
278 /* List recovery files if -l specified. */
279 if (flagchk == 'l')
280 exit(rcv_list(sp));
282 /* Use a tag file or recovery file if specified. */
283 if (tfname != NULL && ex_tagfirst(sp, tfname))
284 goto err1;
285 else if (rfname != NULL && rcv_read(sp, rfname))
286 goto err1;
288 /* Append any remaining arguments as file names. */
289 if (*argv != NULL)
290 for (; *argv != NULL; ++argv)
291 if (file_add(sp, NULL, *argv, 0) == NULL)
292 goto err1;
295 * If no recovery or tag file, get an EXF structure.
296 * If no argv file, use a temporary file.
298 if (tfname == NULL && rfname == NULL) {
299 if ((frp = file_first(sp, 1)) == NULL &&
300 (frp = file_add(sp, NULL, NULL, 0)) == NULL)
301 goto err1;
302 if (file_init(sp, frp, NULL, 0))
303 goto err1;
307 * Initialize the signals. Use sigaction(2), not signal(3), because
308 * we don't want to always restart system calls on 4BSD systems. It
309 * would be nice in some cases to restart system calls, but SA_RESTART
310 * is a 4BSD extension so we can't use it.
312 * SIGWINCH, SIGHUP, SIGTERM:
313 * Catch and set a global bit.
315 act.sa_handler = h_hup;
316 sigemptyset(&act.sa_mask);
317 act.sa_flags = 0;
318 (void)sigaction(SIGHUP, &act, NULL);
319 act.sa_handler = h_term;
320 sigemptyset(&act.sa_mask);
321 act.sa_flags = 0;
322 (void)sigaction(SIGTERM, &act, NULL);
323 act.sa_handler = h_winch;
324 sigemptyset(&act.sa_mask);
325 act.sa_flags = 0;
326 (void)sigaction(SIGWINCH, &act, NULL);
329 * SIGQUIT:
330 * Always ignore.
332 act.sa_handler = SIG_IGN;
333 sigemptyset(&act.sa_mask);
334 act.sa_flags = 0;
335 (void)sigaction(SIGQUIT, &act, NULL);
338 * If there's an initial command, push it on the command stack.
339 * Historically, it was always an ex command, not vi in vi mode
340 * or ex in ex mode. So, make it look like an ex command to vi.
342 if (excmdarg != NULL)
343 switch (F_ISSET(sp, S_MODE_EX | S_MODE_VI)) {
344 case S_MODE_EX:
345 if (term_push(sp, sp->gp->tty,
346 excmdarg, strlen(excmdarg)))
347 goto err1;
348 break;
349 case S_MODE_VI:
350 if (term_push(sp, sp->gp->tty, "\n", 1))
351 goto err1;
352 if (term_push(sp, sp->gp->tty,
353 excmdarg, strlen(excmdarg)))
354 goto err1;
355 if (term_push(sp, sp->gp->tty, ":", 1))
356 goto err1;
357 break;
358 default:
359 abort();
360 /* NOTREACHED */
363 /* Vi reads from the terminal. */
364 if (!F_ISSET(gp, G_ISFROMTTY) && !F_ISSET(sp, S_MODE_EX)) {
365 msgq(sp, M_ERR, "Vi's standard input must be a terminal.");
366 goto err1;
370 * Call a screen. There's two things that we look at. In the
371 * screen flags word there's a bit if it's a vi or ex screen.
372 * Since there are multiple vi screens, we use scr_type to decide.
374 for (; sp != NULL; sp = nsp)
375 if (F_ISSET(sp, S_MODE_EX)) {
376 if (sex(sp, sp->ep, &nsp))
377 goto err2;
378 } else
379 switch (scr_type) {
380 case EX_SCR:
381 abort();
382 /* NOTREACHED */
383 case VI_CURSES_SCR:
384 if (svi(sp, sp->ep, &nsp))
385 goto err2;
386 break;
387 case VI_XAW_SCR:
388 if (xaw(sp, sp->ep, &nsp))
389 goto err2;
390 break;
391 default:
392 abort();
393 /* NOTREACHED */
397 * Two error paths. The first means that something failed before
398 * we called a screen routine. Swap the message pointers between
399 * the SCR and the GS, so messages get displayed. The second is
400 * something failed in a screen. NOTE: sp may be GONE when the
401 * screen returns, so only the gp can be trusted.
403 if (0) {
404 err1: gp->msgp = sp->msgp;
405 err2: eval = 1;
408 /* Reset anything that needs resetting. */
409 reset(gp);
411 /* Flush any left-over error messages. */
412 msgflush(gp);
415 * DON'T FREE THE GLOBAL STRUCTURE -- WE DIDN'T TURN
416 * OFF SIGNALS/TIMERS, SO IT MAY STILL BE REFERENCED.
419 /* Make absolutely sure that the modes are restored correctly. */
420 if (F_ISSET(gp, G_ISFROMTTY) &&
421 tcsetattr(STDIN_FILENO, TCSADRAIN, &gp->original_termios))
422 err(1, "tcsetattr");
423 exit(eval);
427 * reset --
428 * Reset any changed global state.
430 static void
431 reset(gp)
432 GS *gp;
434 char *tty;
436 if (gp->flags & G_SETMODE) /* O_MESG */
437 if ((tty = ttyname(STDERR_FILENO)) == NULL)
438 warn("ttyname");
439 else if (chmod(tty, gp->origmode) < 0)
440 warn("%s", tty);
444 * msgflush --
445 * Flush any remaining messages.
447 static void
448 msgflush(gp)
449 GS *gp;
451 MSG *mp;
453 /* Ring the bell. */
454 if (F_ISSET(gp, G_BELLSCHED))
455 (void)fprintf(stderr, "\07"); /* \a */
457 /* Display the messages. */
458 for (mp = gp->msgp;
459 mp != NULL && !(F_ISSET(mp, M_EMPTY)); mp = mp->next)
460 (void)fprintf(stderr, "%.*s\n", (int)mp->len, mp->mbuf);
464 * h_hup --
465 * Handle SIGHUP.
467 static void
468 h_hup(signo)
469 int signo;
471 F_SET(__global_list, G_SIGHUP);
474 * If we're asleep, just die.
476 * XXX
477 * This isn't right if the windows are independent.
479 if (F_ISSET(__global_list, G_SLEEPING))
480 rcv_hup();
484 * h_term --
485 * Handle SIGTERM.
487 static void
488 h_term(signo)
489 int signo;
491 F_SET(__global_list, G_SIGTERM);
494 * If we're asleep, just die.
496 * XXX
497 * This isn't right if the windows are independent.
499 if (F_ISSET(__global_list, G_SLEEPING))
500 rcv_term();
504 * h_winch --
505 * Handle SIGWINCH.
507 static void
508 h_winch(signo)
509 int signo;
511 F_SET(__global_list, G_SIGWINCH);
514 static void
515 obsolete(argv)
516 char *argv[];
518 size_t len;
519 char *p, *myname;
522 * Translate old style arguments into something getopt will like.
523 * Make sure it's not text space memory, because ex changes the
524 * strings.
525 * Change "+/command" into "-ccommand".
526 * Change "+" and "+$" into "-c$".
527 * Change "+[0-9]*" into "-c[0-9]".
528 * Change "-r" into "-l"
530 for (myname = argv[0]; *++argv;)
531 if (argv[0][0] == '+') {
532 if (argv[0][1] == '\0' || argv[0][1] == '$') {
533 if ((argv[0] = malloc(4)) == NULL)
534 err(1, NULL);
535 memmove(argv[0], "-c$", 4);
536 } else if (argv[0][1] == '/') {
537 p = argv[0];
538 len = strlen(argv[0]);
539 if ((argv[0] = malloc(len + 3)) == NULL)
540 err(1, NULL);
541 argv[0][0] = '-';
542 argv[0][1] = 'c';
543 (void)strcpy(argv[0] + 2, p + 1);
544 } else if (isdigit(argv[0][1])) {
545 p = argv[0];
546 len = strlen(argv[0]);
547 if ((argv[0] = malloc(len + 2)) == NULL)
548 err(1, NULL);
549 argv[0][0] = '-';
550 argv[0][1] = 'c';
551 (void)strcpy(argv[0] + 2, p + 1);
554 else if (argv[0][0] == '-' &&
555 argv[0][1] == 'r' && argv[0][2] == '\0' && argv[1] == NULL)
556 argv[0][1] = 'l';
559 static void
560 usage()
562 (void)fprintf(stderr, "%s%s\n",
563 "usage: vi [-eRsv] [-c command] [-m file] [-r file] ",
564 "[-t tag] [-w size] [-x aw]");
565 exit(1);