xref: /original-bsd/usr.bin/window/context.c (revision e85b5252)
1 /*
2  * Copyright (c) 1983, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Edward Wang at The University of California, Berkeley.
7  *
8  * %sccs.include.redist.c%
9  */
10 
11 #ifndef lint
12 static char sccsid[] = "@(#)context.c	8.1 (Berkeley) 06/06/93";
13 #endif /* not lint */
14 
15 #include "value.h"
16 #include "string.h"
17 #include "context.h"
18 #include <fcntl.h>
19 
20 /*
21  * Context push/pop for nested command files.
22  */
23 
24 char *malloc();
25 
cx_alloc()26 cx_alloc()
27 {
28 	register struct context *xp;
29 
30 	if (cx.x_type != 0) {
31 		xp = (struct context *)
32 			malloc((unsigned) sizeof (struct context));
33 		if (xp == 0)
34 			return -1;
35 		*xp = cx;
36 		cx.x_link = xp;
37 		cx.x_type = 0;
38 	}
39 	cx.x_erred = 0;
40 	cx.x_synerred = 0;
41 	cx.x_abort = 0;
42 	return 0;
43 }
44 
cx_free()45 cx_free()
46 {
47 	struct context *xp;
48 
49 	if ((xp = cx.x_link) != 0) {
50 		cx = *xp;
51 		free((char *)xp);
52 	} else
53 		cx.x_type = 0;
54 }
55 
cx_beginfile(filename)56 cx_beginfile(filename)
57 char *filename;
58 {
59 	if (cx_alloc() < 0)
60 		return -1;
61 	cx.x_type = X_FILE;
62 	if ((cx.x_filename = str_cpy(filename)) == 0)
63 		goto bad;
64 	cx.x_fp = fopen(filename, "r");
65 	if (cx.x_fp == 0)
66 		goto bad;
67 	(void) fcntl(fileno(cx.x_fp), F_SETFD, 1);
68 	cx.x_bol = 1;
69 	cx.x_lineno = 0;
70 	cx.x_errwin = 0;
71 	cx.x_noerr = 0;
72 	return 0;
73 bad:
74 	if (cx.x_filename != 0)
75 		str_free(cx.x_filename);
76 	cx_free();
77 	return -1;
78 }
79 
cx_beginbuf(buf,arg,narg)80 cx_beginbuf(buf, arg, narg)
81 char *buf;
82 struct value *arg;
83 int narg;
84 {
85 	if (cx_alloc() < 0)
86 		return -1;
87 	cx.x_type = X_BUF;
88 	cx.x_bufp = cx.x_buf = buf;
89 	cx.x_arg = arg;
90 	cx.x_narg = narg;
91 	return 0;
92 }
93 
cx_end()94 cx_end()
95 {
96 	switch (cx.x_type) {
97 	case X_BUF:
98 		break;
99 	case X_FILE:
100 		(void) fclose(cx.x_fp);
101 		str_free(cx.x_filename);
102 		break;
103 	}
104 	cx_free();
105 }
106