xref: /original-bsd/usr.bin/window/context.c (revision 100ae74e)
1 /*
2  * Copyright (c) 1983 Regents of the University of California.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms are permitted
6  * provided that this notice is preserved and that due credit is given
7  * to the University of California at Berkeley. The name of the University
8  * may not be used to endorse or promote products derived from this
9  * software without specific prior written permission. This software
10  * is provided ``as is'' without express or implied warranty.
11  */
12 
13 #ifndef lint
14 static char sccsid[] = "@(#)context.c	3.8 (Berkeley) 02/21/88";
15 #endif /* not lint */
16 
17 #include <stdio.h>
18 #include "value.h"
19 #include "string.h"
20 #include "context.h"
21 
22 /*
23  * Context push/pop for nested command files.
24  */
25 
26 char *malloc();
27 
28 cx_alloc()
29 {
30 	register struct context *xp;
31 
32 	if (cx.x_type != 0) {
33 		xp = (struct context *)
34 			malloc((unsigned) sizeof (struct context));
35 		if (xp == 0)
36 			return -1;
37 		*xp = cx;
38 		cx.x_link = xp;
39 		cx.x_type = 0;
40 	}
41 	cx.x_erred = 0;
42 	cx.x_synerred = 0;
43 	cx.x_abort = 0;
44 	return 0;
45 }
46 
47 cx_free()
48 {
49 	struct context *xp;
50 
51 	if ((xp = cx.x_link) != 0) {
52 		cx = *xp;
53 		free((char *)xp);
54 	} else
55 		cx.x_type = 0;
56 }
57 
58 cx_beginfile(filename)
59 char *filename;
60 {
61 	if (cx_alloc() < 0)
62 		return -1;
63 	cx.x_type = X_FILE;
64 	if ((cx.x_filename = str_cpy(filename)) == 0)
65 		goto bad;
66 	cx.x_fp = fopen(filename, "r");
67 	if (cx.x_fp == 0)
68 		goto bad;
69 	cx.x_bol = 1;
70 	cx.x_lineno = 0;
71 	cx.x_errwin = 0;
72 	cx.x_noerr = 0;
73 	return 0;
74 bad:
75 	if (cx.x_filename != 0)
76 		str_free(cx.x_filename);
77 	cx_free();
78 	return -1;
79 }
80 
81 cx_beginbuf(buf, arg, narg)
82 char *buf;
83 struct value *arg;
84 int narg;
85 {
86 	if (cx_alloc() < 0)
87 		return -1;
88 	cx.x_type = X_BUF;
89 	cx.x_bufp = cx.x_buf = buf;
90 	cx.x_arg = arg;
91 	cx.x_narg = narg;
92 	return 0;
93 }
94 
95 cx_end()
96 {
97 	switch (cx.x_type) {
98 	case X_BUF:
99 		break;
100 	case X_FILE:
101 		(void) fclose(cx.x_fp);
102 		str_free(cx.x_filename);
103 		break;
104 	}
105 	cx_free();
106 }
107