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