xref: /openbsd-src/usr.bin/vi/common/main.c (revision 43003dfe3ad45d1698bed8a37f2b0f5b14f20d4f)
1 /*	$OpenBSD: main.c,v 1.18 2009/02/01 21:57:21 miod Exp $	*/
2 
3 /*-
4  * Copyright (c) 1992, 1993, 1994
5  *	The Regents of the University of California.  All rights reserved.
6  * Copyright (c) 1992, 1993, 1994, 1995, 1996
7  *	Keith Bostic.  All rights reserved.
8  *
9  * See the LICENSE file for redistribution information.
10  */
11 
12 #include "config.h"
13 
14 #ifndef lint
15 static const char copyright[] =
16 "@(#) Copyright (c) 1992, 1993, 1994\n\
17 	The Regents of the University of California.  All rights reserved.\n\
18 @(#) Copyright (c) 1992, 1993, 1994, 1995, 1996\n\
19 	Keith Bostic.  All rights reserved.\n";
20 #endif /* not lint */
21 
22 #ifndef lint
23 static const char sccsid[] = "@(#)main.c	10.48 (Berkeley) 10/11/96";
24 #endif /* not lint */
25 
26 #include <sys/types.h>
27 #include <sys/queue.h>
28 #include <sys/stat.h>
29 #include <sys/time.h>
30 
31 #include <bitstring.h>
32 #include <errno.h>
33 #include <fcntl.h>
34 #include <limits.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <unistd.h>
39 
40 #include "common.h"
41 #include "../vi/vi.h"
42 #include "pathnames.h"
43 
44 #ifdef DEBUG
45 static void	 attach(GS *);
46 #endif
47 static void	 v_estr(char *, int, char *);
48 static int	 v_obsolete(char *, char *[]);
49 
50 /*
51  * editor --
52  *	Main editor routine.
53  *
54  * PUBLIC: int editor(GS *, int, char *[]);
55  */
56 int
57 editor(gp, argc, argv)
58 	GS *gp;
59 	int argc;
60 	char *argv[];
61 {
62 	extern int optind;
63 	extern char *optarg;
64 	const char *p;
65 	EVENT ev;
66 	FREF *frp;
67 	SCR *sp;
68 	size_t len;
69 	u_int flags;
70 	int ch, flagchk, lflag, secure, startup, readonly, rval, silent;
71 	char *tag_f, *wsizearg, path[256];
72 
73 	static const char *optstr[3] = {
74 #ifdef DEBUG
75 		"c:D:FlRrSsT:t:vw:",
76 		"c:D:eFlRrST:t:w:",
77 		"c:D:eFlrST:t:w:"
78 #else
79 		"c:FlRrSst:vw:",
80 		"c:eFlRrSt:w:",
81 		"c:eFlrSt:w:"
82 #endif
83 	};
84 
85 	/* Initialize the busy routine, if not defined by the screen. */
86 	if (gp->scr_busy == NULL)
87 		gp->scr_busy = vs_busy;
88 	/* Initialize the message routine, if not defined by the screen. */
89 	if (gp->scr_msg == NULL)
90 		gp->scr_msg = vs_msg;
91 
92 	/* Common global structure initialization. */
93 	CIRCLEQ_INIT(&gp->dq);
94 	CIRCLEQ_INIT(&gp->hq);
95 	LIST_INIT(&gp->ecq);
96 	LIST_INSERT_HEAD(&gp->ecq, &gp->excmd, q);
97 	gp->noprint = DEFAULT_NOPRINT;
98 
99 	/* Structures shared by screens so stored in the GS structure. */
100 	CIRCLEQ_INIT(&gp->frefq);
101 	CIRCLEQ_INIT(&gp->dcb_store.textq);
102 	LIST_INIT(&gp->cutq);
103 	LIST_INIT(&gp->seqq);
104 
105 	/* Set initial screen type and mode based on the program name. */
106 	readonly = 0;
107 	if (!strcmp(gp->progname, "ex") || !strcmp(gp->progname, "nex"))
108 		LF_INIT(SC_EX);
109 	else {
110 		/* Nview, view are readonly. */
111 		if (!strcmp(gp->progname, "nview") ||
112 		    !strcmp(gp->progname, "view"))
113 			readonly = 1;
114 
115 		/* Vi is the default. */
116 		LF_INIT(SC_VI);
117 	}
118 
119 	/* Convert old-style arguments into new-style ones. */
120 	if (v_obsolete(gp->progname, argv))
121 		return (1);
122 
123 	/* Parse the arguments. */
124 	flagchk = '\0';
125 	tag_f = wsizearg = NULL;
126 	lflag = secure = silent = 0;
127 	startup = 1;
128 
129 	/* Set the file snapshot flag. */
130 	F_SET(gp, G_SNAPSHOT);
131 
132 	pmode = MODE_EX;
133 	if (!strcmp(gp->progname, "ex"))
134 		pmode = MODE_EX;
135 	else if (!strcmp(gp->progname, "vi"))
136 		pmode = MODE_VI;
137 	else if (!strcmp(gp->progname, "view"))
138 		pmode = MODE_VIEW;
139 
140 	while ((ch = getopt(argc, argv, optstr[pmode])) != -1)
141 		switch (ch) {
142 		case 'c':		/* Run the command. */
143 			/*
144 			 * XXX
145 			 * We should support multiple -c options.
146 			 */
147 			if (gp->c_option != NULL) {
148 				v_estr(gp->progname, 0,
149 				    "only one -c command may be specified.");
150 				return (1);
151 			}
152 			gp->c_option = optarg;
153 			break;
154 #ifdef DEBUG
155 		case 'D':
156 			switch (optarg[0]) {
157 			case 's':
158 				startup = 0;
159 				break;
160 			case 'w':
161 				attach(gp);
162 				break;
163 			default:
164 				v_estr(gp->progname, 0,
165 				    "-D requires s or w argument.");
166 				return (1);
167 			}
168 			break;
169 #endif
170 		case 'e':		/* Ex mode. */
171 			LF_CLR(SC_VI);
172 			LF_SET(SC_EX);
173 			break;
174 		case 'F':		/* No snapshot. */
175 			F_CLR(gp, G_SNAPSHOT);
176 			break;
177 		case 'l':		/* Set lisp, showmatch options. */
178 			lflag = 1;
179 			break;
180 		case 'R':		/* Readonly. */
181 			readonly = 1;
182 			break;
183 		case 'r':		/* Recover. */
184 			if (flagchk == 't') {
185 				v_estr(gp->progname, 0,
186 				    "only one of -r and -t may be specified.");
187 				return (1);
188 			}
189 			flagchk = 'r';
190 			break;
191 		case 'S':
192 			secure = 1;
193 			break;
194 		case 's':
195 			silent = 1;
196 			break;
197 #ifdef DEBUG
198 		case 'T':		/* Trace. */
199 			if ((gp->tracefp = fopen(optarg, "w")) == NULL) {
200 				v_estr(gp->progname, errno, optarg);
201 				goto err;
202 			}
203 			(void)fprintf(gp->tracefp,
204 			    "\n===\ntrace: open %s\n", optarg);
205 			break;
206 #endif
207 		case 't':		/* Tag. */
208 			if (flagchk == 'r') {
209 				v_estr(gp->progname, 0,
210 				    "only one of -r and -t may be specified.");
211 				return (1);
212 			}
213 			if (flagchk == 't') {
214 				v_estr(gp->progname, 0,
215 				    "only one tag file may be specified.");
216 				return (1);
217 			}
218 			flagchk = 't';
219 			tag_f = optarg;
220 			break;
221 		case 'v':		/* Vi mode. */
222 			LF_CLR(SC_EX);
223 			LF_SET(SC_VI);
224 			break;
225 		case 'w':
226 			wsizearg = optarg;
227 			break;
228 		case '?':
229 		default:
230 			(void)gp->scr_usage();
231 			return (1);
232 		}
233 	argc -= optind;
234 	argv += optind;
235 
236 	/*
237 	 * -s option is only meaningful to ex.
238 	 *
239 	 * If not reading from a terminal, it's like -s was specified.
240 	 */
241 	if (silent && !LF_ISSET(SC_EX)) {
242 		v_estr(gp->progname, 0, "-s option is only applicable to ex.");
243 		goto err;
244 	}
245 	if (LF_ISSET(SC_EX) && F_ISSET(gp, G_SCRIPTED))
246 		silent = 1;
247 
248 	/*
249 	 * Build and initialize the first/current screen.  This is a bit
250 	 * tricky.  If an error is returned, we may or may not have a
251 	 * screen structure.  If we have a screen structure, put it on a
252 	 * display queue so that the error messages get displayed.
253 	 *
254 	 * !!!
255 	 * Everything we do until we go interactive is done in ex mode.
256 	 */
257 	if (screen_init(gp, NULL, &sp)) {
258 		if (sp != NULL)
259 			CIRCLEQ_INSERT_HEAD(&gp->dq, sp, q);
260 		goto err;
261 	}
262 	F_SET(sp, SC_EX);
263 	CIRCLEQ_INSERT_HEAD(&gp->dq, sp, q);
264 
265 	if (v_key_init(sp))		/* Special key initialization. */
266 		goto err;
267 
268 	{ int oargs[5], *oargp = oargs;
269 	if (lflag) {			/* Command-line options. */
270 		*oargp++ = O_LISP;
271 		*oargp++ = O_SHOWMATCH;
272 	}
273 	if (readonly)
274 		*oargp++ = O_READONLY;
275 	if (secure)
276 		*oargp++ = O_SECURE;
277 	*oargp = -1;			/* Options initialization. */
278 	if (opts_init(sp, oargs))
279 		goto err;
280 	}
281 	if (wsizearg != NULL) {
282 		ARGS *av[2], a, b;
283 		(void)snprintf(path, sizeof(path), "window=%s", wsizearg);
284 		a.bp = (CHAR_T *)path;
285 		a.len = strlen(path);
286 		b.bp = NULL;
287 		b.len = 0;
288 		av[0] = &a;
289 		av[1] = &b;
290 		(void)opts_set(sp, av, NULL);
291 	}
292 	if (silent) {			/* Ex batch mode option values. */
293 		O_CLR(sp, O_AUTOPRINT);
294 		O_CLR(sp, O_PROMPT);
295 		O_CLR(sp, O_VERBOSE);
296 		O_CLR(sp, O_WARN);
297 		F_SET(sp, SC_EX_SILENT);
298 	}
299 
300 	sp->rows = O_VAL(sp, O_LINES);	/* Make ex formatting work. */
301 	sp->cols = O_VAL(sp, O_COLUMNS);
302 
303 	if (!silent && startup) {	/* Read EXINIT, exrc files. */
304 		if (ex_exrc(sp))
305 			goto err;
306 		if (F_ISSET(sp, SC_EXIT | SC_EXIT_FORCE)) {
307 			if (screen_end(sp))
308 				goto err;
309 			goto done;
310 		}
311 	}
312 
313 	/*
314 	 * List recovery files if -r specified without file arguments.
315 	 * Note, options must be initialized and startup information
316 	 * read before doing this.
317 	 */
318 	if (flagchk == 'r' && argv[0] == NULL) {
319 		if (rcv_list(sp))
320 			goto err;
321 		if (screen_end(sp))
322 			goto err;
323 		goto done;
324 	}
325 
326 	/*
327 	 * !!!
328 	 * Initialize the default ^D, ^U scrolling value here, after the
329 	 * user has had every opportunity to set the window option.
330 	 *
331 	 * It's historic practice that changing the value of the window
332 	 * option did not alter the default scrolling value, only giving
333 	 * a count to ^D/^U did that.
334 	 */
335 	sp->defscroll = (O_VAL(sp, O_WINDOW) + 1) / 2;
336 
337 	/*
338 	 * If we don't have a command-line option, switch into the right
339 	 * editor now, so that we position default files correctly, and
340 	 * so that any tags file file-already-locked messages are in the
341 	 * vi screen, not the ex screen.
342 	 *
343 	 * XXX
344 	 * If we have a command-line option, the error message can end
345 	 * up in the wrong place, but I think that the combination is
346 	 * unlikely.
347 	 */
348 	if (gp->c_option == NULL) {
349 		F_CLR(sp, SC_EX | SC_VI);
350 		F_SET(sp, LF_ISSET(SC_EX | SC_VI));
351 	}
352 
353 	/* Open a tag file if specified. */
354 	if (tag_f != NULL && ex_tag_first(sp, tag_f))
355 		goto err;
356 
357 	/*
358 	 * Append any remaining arguments as file names.  Files are recovery
359 	 * files if -r specified.  If the tag option or ex startup commands
360 	 * loaded a file, then any file arguments are going to come after it.
361 	 */
362 	if (*argv != NULL) {
363 		if (sp->frp != NULL) {
364 			size_t l;
365 			/* Cheat -- we know we have an extra argv slot. */
366 			l = strlen(sp->frp->name) + 1;
367 			MALLOC_NOMSG(sp, *--argv, char *, l);
368 			if (*argv == NULL) {
369 				v_estr(gp->progname, errno, NULL);
370 				goto err;
371 			}
372 			(void)strlcpy(*argv, sp->frp->name, l);
373 		}
374 		sp->argv = sp->cargv = argv;
375 		F_SET(sp, SC_ARGNOFREE);
376 		if (flagchk == 'r')
377 			F_SET(sp, SC_ARGRECOVER);
378 	}
379 
380 	/*
381 	 * If the ex startup commands and or/the tag option haven't already
382 	 * created a file, create one.  If no command-line files were given,
383 	 * use a temporary file.
384 	 */
385 	if (sp->frp == NULL) {
386 		if (sp->argv == NULL) {
387 			if ((frp = file_add(sp, NULL)) == NULL)
388 				goto err;
389 		} else  {
390 			if ((frp = file_add(sp, (CHAR_T *)sp->argv[0])) == NULL)
391 				goto err;
392 			if (F_ISSET(sp, SC_ARGRECOVER))
393 				F_SET(frp, FR_RECOVER);
394 		}
395 
396 		if (file_init(sp, frp, NULL, 0))
397 			goto err;
398 		if (EXCMD_RUNNING(gp)) {
399 			(void)ex_cmd(sp);
400 			if (F_ISSET(sp, SC_EXIT | SC_EXIT_FORCE)) {
401 				if (screen_end(sp))
402 					goto err;
403 				goto done;
404 			}
405 		}
406 	}
407 
408 	/*
409 	 * Check to see if we need to wait for ex.  If SC_SCR_EX is set, ex
410 	 * was forced to initialize the screen during startup.  We'd like to
411 	 * wait for a single character from the user, but we can't because
412 	 * we're not in raw mode.  We can't switch to raw mode because the
413 	 * vi initialization will switch to xterm's alternate screen, causing
414 	 * us to lose the messages we're pausing to make sure the user read.
415 	 * So, wait for a complete line.
416 	 */
417 	if (F_ISSET(sp, SC_SCR_EX)) {
418 		p = msg_cmsg(sp, CMSG_CONT_R, &len);
419 		(void)write(STDOUT_FILENO, p, len);
420 		for (;;) {
421 			if (v_event_get(sp, &ev, 0, 0))
422 				goto err;
423 			if (ev.e_event == E_INTERRUPT ||
424 			    (ev.e_event == E_CHARACTER &&
425 			    (ev.e_value == K_CR || ev.e_value == K_NL)))
426 				break;
427 			(void)gp->scr_bell(sp);
428 		}
429 	}
430 
431 	/* Switch into the right editor, regardless. */
432 	F_CLR(sp, SC_EX | SC_VI);
433 	F_SET(sp, LF_ISSET(SC_EX | SC_VI) | SC_STATUS_CNT);
434 
435 	/*
436 	 * Main edit loop.  Vi handles split screens itself, we only return
437 	 * here when switching editor modes or restarting the screen.
438 	 */
439 	while (sp != NULL)
440 		if (F_ISSET(sp, SC_EX) ? ex(&sp) : vi(&sp))
441 			goto err;
442 
443 done:	rval = 0;
444 	if (0)
445 err:		rval = 1;
446 
447 	/* Clean out the global structure. */
448 	v_end(gp);
449 
450 	return (rval);
451 }
452 
453 /*
454  * v_end --
455  *	End the program, discarding screens and most of the global area.
456  *
457  * PUBLIC: void v_end(GS *);
458  */
459 void
460 v_end(gp)
461 	GS *gp;
462 {
463 	MSGS *mp;
464 	SCR *sp;
465 
466 	/* If there are any remaining screens, kill them off. */
467 	if (gp->ccl_sp != NULL) {
468 		(void)file_end(gp->ccl_sp, NULL, 1);
469 		(void)screen_end(gp->ccl_sp);
470 	}
471 	while ((sp = CIRCLEQ_FIRST(&gp->dq)) != CIRCLEQ_END(&gp->dq))
472 		(void)screen_end(sp);
473 	while ((sp = CIRCLEQ_FIRST(&gp->hq)) != CIRCLEQ_END(&gp->hq))
474 		(void)screen_end(sp);
475 
476 #ifdef HAVE_PERL_INTERP
477 	perl_end(gp);
478 #endif
479 
480 #if defined(DEBUG) || defined(PURIFY) || defined(LIBRARY)
481 	{ FREF *frp;
482 		/* Free FREF's. */
483 		while ((frp = CIRCLEQ_FIRST(&gp->frefq)) != CIRCLEQ_END(&gp->frefq)) {
484 			CIRCLEQ_REMOVE(&gp->frefq, frp, q);
485 			if (frp->name != NULL)
486 				free(frp->name);
487 			if (frp->tname != NULL)
488 				free(frp->tname);
489 			free(frp);
490 		}
491 	}
492 
493 	/* Free key input queue. */
494 	if (gp->i_event != NULL)
495 		free(gp->i_event);
496 
497 	/* Free cut buffers. */
498 	cut_close(gp);
499 
500 	/* Free map sequences. */
501 	seq_close(gp);
502 
503 	/* Free default buffer storage. */
504 	(void)text_lfree(&gp->dcb_store.textq);
505 
506 	/* Close message catalogs. */
507 	msg_close(gp);
508 #endif
509 
510 	/* Ring the bell if scheduled. */
511 	if (F_ISSET(gp, G_BELLSCHED))
512 		(void)fprintf(stderr, "\07");		/* \a */
513 
514 	/*
515 	 * Flush any remaining messages.  If a message is here, it's almost
516 	 * certainly the message about the event that killed us (although
517 	 * it's possible that the user is sourcing a file that exits from the
518 	 * editor).
519 	 */
520 	while ((mp = LIST_FIRST(&gp->msgq)) != NULL) {
521 		(void)fprintf(stderr, "%s%.*s",
522 		    mp->mtype == M_ERR ? "ex/vi: " : "", (int)mp->len, mp->buf);
523 		LIST_REMOVE(mp, q);
524 #if defined(DEBUG) || defined(PURIFY) || defined(LIBRARY)
525 		free(mp->buf);
526 		free(mp);
527 #endif
528 	}
529 
530 #if defined(DEBUG) || defined(PURIFY) || defined(LIBRARY)
531 	/* Free any temporary space. */
532 	if (gp->tmp_bp != NULL)
533 		free(gp->tmp_bp);
534 
535 #if defined(DEBUG)
536 	/* Close debugging file descriptor. */
537 	if (gp->tracefp != NULL)
538 		(void)fclose(gp->tracefp);
539 #endif
540 #endif
541 }
542 
543 /*
544  * v_obsolete --
545  *	Convert historic arguments into something getopt(3) will like.
546  */
547 static int
548 v_obsolete(name, argv)
549 	char *name, *argv[];
550 {
551 	size_t len;
552 	char *p;
553 
554 	/*
555 	 * Translate old style arguments into something getopt will like.
556 	 * Make sure it's not text space memory, because ex modifies the
557 	 * strings.
558 	 *	Change "+" into "-c$".
559 	 *	Change "+<anything else>" into "-c<anything else>".
560 	 *	Change "-" into "-s"
561 	 *	The c, T, t and w options take arguments so they can't be
562 	 *	    special arguments.
563 	 *
564 	 * Stop if we find "--" as an argument, the user may want to edit
565 	 * a file named "+foo".
566 	 */
567 	while (*++argv && strcmp(argv[0], "--"))
568 		if (argv[0][0] == '+') {
569 			if (argv[0][1] == '\0') {
570 				argv[0] = strdup("-c$");
571 				if (argv[0] == NULL)
572 					goto nomem;
573 			} else  {
574 				p = argv[0];
575 				len = strlen(argv[0]);
576 				MALLOC_NOMSG(NULL, argv[0], char *, len + 2);
577 				if (argv[0] == NULL)
578 					goto nomem;
579 				argv[0][0] = '-';
580 				argv[0][1] = 'c';
581 				(void)strlcpy(argv[0] + 2, p + 1, len);
582 			}
583 		} else if (argv[0][0] == '-') {
584 			if (argv[0][1] == '\0') {
585 				argv[0] = strdup("-s");
586 				if (argv[0] == NULL) {
587 nomem:					v_estr(name, errno, NULL);
588 					return (1);
589 				}
590 			} else
591 				if ((argv[0][1] == 'c' || argv[0][1] == 'T' ||
592 				    argv[0][1] == 't' || argv[0][1] == 'w') &&
593 				    argv[0][2] == '\0')
594 					++argv;
595 		}
596 	return (0);
597 }
598 
599 #ifdef DEBUG
600 static void
601 attach(gp)
602 	GS *gp;
603 {
604 	int fd;
605 	char ch;
606 
607 	if ((fd = open(_PATH_TTY, O_RDONLY, 0)) < 0) {
608 		v_estr(gp->progname, errno, _PATH_TTY);
609 		return;
610 	}
611 
612 	(void)printf("process %ld waiting, enter <CR> to continue: ",
613 	    (long)getpid());
614 	(void)fflush(stdout);
615 
616 	do {
617 		if (read(fd, &ch, 1) != 1) {
618 			(void)close(fd);
619 			return;
620 		}
621 	} while (ch != '\n' && ch != '\r');
622 	(void)close(fd);
623 }
624 #endif
625 
626 static void
627 v_estr(name, eno, msg)
628 	char *name, *msg;
629 	int eno;
630 {
631 	(void)fprintf(stderr, "%s", name);
632 	if (msg != NULL)
633 		(void)fprintf(stderr, ": %s", msg);
634 	if (eno)
635 		(void)fprintf(stderr, ": %s", strerror(errno));
636 	(void)fprintf(stderr, "\n");
637 }
638