xref: /original-bsd/usr.bin/window/context.c (revision 7211505a)
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 the above copyright notice and this paragraph are
7  * duplicated in all such forms and that any documentation,
8  * advertising materials, and other materials related to such
9  * distribution and use acknowledge that the software was developed
10  * by the University of California, Berkeley.  The name of the
11  * University may not be used to endorse or promote products derived
12  * from this software without specific prior written permission.
13  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
14  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
15  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
16  */
17 
18 #ifndef lint
19 static char sccsid[] = "@(#)context.c	3.9 (Berkeley) 06/29/88";
20 #endif /* not lint */
21 
22 #include <stdio.h>
23 #include "value.h"
24 #include "string.h"
25 #include "context.h"
26 
27 /*
28  * Context push/pop for nested command files.
29  */
30 
31 char *malloc();
32 
33 cx_alloc()
34 {
35 	register struct context *xp;
36 
37 	if (cx.x_type != 0) {
38 		xp = (struct context *)
39 			malloc((unsigned) sizeof (struct context));
40 		if (xp == 0)
41 			return -1;
42 		*xp = cx;
43 		cx.x_link = xp;
44 		cx.x_type = 0;
45 	}
46 	cx.x_erred = 0;
47 	cx.x_synerred = 0;
48 	cx.x_abort = 0;
49 	return 0;
50 }
51 
52 cx_free()
53 {
54 	struct context *xp;
55 
56 	if ((xp = cx.x_link) != 0) {
57 		cx = *xp;
58 		free((char *)xp);
59 	} else
60 		cx.x_type = 0;
61 }
62 
63 cx_beginfile(filename)
64 char *filename;
65 {
66 	if (cx_alloc() < 0)
67 		return -1;
68 	cx.x_type = X_FILE;
69 	if ((cx.x_filename = str_cpy(filename)) == 0)
70 		goto bad;
71 	cx.x_fp = fopen(filename, "r");
72 	if (cx.x_fp == 0)
73 		goto bad;
74 	cx.x_bol = 1;
75 	cx.x_lineno = 0;
76 	cx.x_errwin = 0;
77 	cx.x_noerr = 0;
78 	return 0;
79 bad:
80 	if (cx.x_filename != 0)
81 		str_free(cx.x_filename);
82 	cx_free();
83 	return -1;
84 }
85 
86 cx_beginbuf(buf, arg, narg)
87 char *buf;
88 struct value *arg;
89 int narg;
90 {
91 	if (cx_alloc() < 0)
92 		return -1;
93 	cx.x_type = X_BUF;
94 	cx.x_bufp = cx.x_buf = buf;
95 	cx.x_arg = arg;
96 	cx.x_narg = narg;
97 	return 0;
98 }
99 
100 cx_end()
101 {
102 	switch (cx.x_type) {
103 	case X_BUF:
104 		break;
105 	case X_FILE:
106 		(void) fclose(cx.x_fp);
107 		str_free(cx.x_filename);
108 		break;
109 	}
110 	cx_free();
111 }
112