xref: /plan9/sys/src/cmd/db/output.c (revision 9a747e4fd48b9f4522c70c07e8f882a15030f964)
1 /*
2  *
3  *	debugger
4  *
5  */
6 
7 #include "defs.h"
8 #include "fns.h"
9 
10 int	printcol = 0;
11 int	infile = STDIN;
12 int	maxpos = MAXPOS;
13 
14 Biobuf	stdout;
15 
16 void
printc(int c)17 printc(int c)
18 {
19 	dprint("%c", c);
20 }
21 
22 /* was move to next f1-sized tab stop; now just print a tab */
23 int
tconv(Fmt * f)24 tconv(Fmt *f)
25 {
26 	return fmtstrcpy(f, "\t");
27 }
28 
29 void
flushbuf(void)30 flushbuf(void)
31 {
32  	if (printcol != 0)
33 		printc(EOR);
34 }
35 
36 void
prints(char * s)37 prints(char *s)
38 {
39 	dprint("%s",s);
40 }
41 
42 void
newline(void)43 newline(void)
44 {
45 	printc(EOR);
46 }
47 
48 #define	MAXIFD	5
49 struct {
50 	int	fd;
51 	int	r9;
52 } istack[MAXIFD];
53 int	ifiledepth;
54 
55 void
iclose(int stack,int err)56 iclose(int stack, int err)
57 {
58 	if (err) {
59 		if (infile) {
60 			close(infile);
61 			infile=STDIN;
62 		}
63 		while (--ifiledepth >= 0)
64 			if (istack[ifiledepth].fd)
65 				close(istack[ifiledepth].fd);
66 		ifiledepth = 0;
67 	} else if (stack == 0) {
68 		if (infile) {
69 			close(infile);
70 			infile=STDIN;
71 		}
72 	} else if (stack > 0) {
73 		if (ifiledepth >= MAXIFD)
74 			error("$<< nested too deeply");
75 		istack[ifiledepth].fd = infile;
76 		ifiledepth++;
77 		infile = STDIN;
78 	} else {
79 		if (infile) {
80 			close(infile);
81 			infile=STDIN;
82 		}
83 		if (ifiledepth > 0) {
84 			infile = istack[--ifiledepth].fd;
85 		}
86 	}
87 }
88 
89 void
oclose(void)90 oclose(void)
91 {
92 	flushbuf();
93 	Bterm(&stdout);
94 	Binit(&stdout, 1, OWRITE);
95 }
96 
97 void
redirout(char * file)98 redirout(char *file)
99 {
100 	int fd;
101 
102 	if (file == 0){
103 		oclose();
104 		return;
105 	}
106 	flushbuf();
107 	if ((fd = open(file, 1)) >= 0)
108 		seek(fd, 0L, 2);
109 	else if ((fd = create(file, 1, 0666)) < 0)
110 		error("cannot create");
111 	Bterm(&stdout);
112 	Binit(&stdout, fd, OWRITE);
113 }
114 
115 void
endline(void)116 endline(void)
117 {
118 
119 	if (maxpos <= printcol)
120 		newline();
121 }
122 
123 void
flush(void)124 flush(void)
125 {
126 	Bflush(&stdout);
127 }
128 
129 int
dprint(char * fmt,...)130 dprint(char *fmt, ...)
131 {
132 	int n, w;
133 	char *p;
134  	char buf[4096];
135 	Rune r;
136 	va_list arg;
137 
138 	if(mkfault)
139 		return -1;
140 	va_start(arg, fmt);
141 	n = vseprint(buf, buf+sizeof buf, fmt, arg) - buf;
142 	va_end(arg);
143 //Bprint(&stdout, "[%s]", fmt);
144 	Bwrite(&stdout, buf, n);
145 	for(p=buf; *p; p+=w){
146 		w = chartorune(&r, p);
147 		if(r == '\n')
148 			printcol = 0;
149 		else
150 			printcol++;
151 	}
152 	return n;
153 }
154 
155 void
outputinit(void)156 outputinit(void)
157 {
158 	Binit(&stdout, 1, OWRITE);
159 	fmtinstall('t', tconv);
160 }
161