xref: /freebsd/usr.bin/indent/io.c (revision ce834215a70ff69e7e222827437116eee2f9ac6f)
1 /*
2  * Copyright (c) 1985 Sun Microsystems, Inc.
3  * Copyright (c) 1980, 1993
4  *	The Regents of the University of California.  All rights reserved.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *	This product includes software developed by the University of
18  *	California, Berkeley and its contributors.
19  * 4. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #ifndef lint
37 #if 0
38 static char sccsid[] = "@(#)io.c	8.1 (Berkeley) 6/6/93";
39 #endif
40 static const char rcsid[] =
41 	"$Id$";
42 #endif /* not lint */
43 
44 #include <ctype.h>
45 #include <err.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include "indent_globs.h"
50 
51 
52 int         comment_open;
53 static      paren_target;
54 
55 dump_line()
56 {				/* dump_line is the routine that actually
57 				 * effects the printing of the new source. It
58 				 * prints the label section, followed by the
59 				 * code section with the appropriate nesting
60 				 * level, followed by any comments */
61     register int cur_col,
62                 target_col;
63     static      not_first_line;
64 
65     if (ps.procname[0]) {
66 	if (troff) {
67 	    if (comment_open) {
68 		comment_open = 0;
69 		fprintf(output, ".*/\n");
70 	    }
71 	    fprintf(output, ".Pr \"%s\"\n", ps.procname);
72 	}
73 	ps.ind_level = 0;
74 	ps.procname[0] = 0;
75     }
76     if (s_code == e_code && s_lab == e_lab && s_com == e_com) {
77 	if (suppress_blanklines > 0)
78 	    suppress_blanklines--;
79 	else {
80 	    ps.bl_line = true;
81 	    n_real_blanklines++;
82 	}
83     }
84     else if (!inhibit_formatting) {
85 	suppress_blanklines = 0;
86 	ps.bl_line = false;
87 	if (prefix_blankline_requested && not_first_line)
88 	    if (swallow_optional_blanklines) {
89 		if (n_real_blanklines == 1)
90 		    n_real_blanklines = 0;
91 	    }
92 	    else {
93 		if (n_real_blanklines == 0)
94 		    n_real_blanklines = 1;
95 	    }
96 	while (--n_real_blanklines >= 0)
97 	    putc('\n', output);
98 	n_real_blanklines = 0;
99 	if (ps.ind_level == 0)
100 	    ps.ind_stmt = 0;	/* this is a class A kludge. dont do
101 				 * additional statement indentation if we are
102 				 * at bracket level 0 */
103 
104 	if (e_lab != s_lab || e_code != s_code)
105 	    ++code_lines;	/* keep count of lines with code */
106 
107 
108 	if (e_lab != s_lab) {	/* print lab, if any */
109 	    if (comment_open) {
110 		comment_open = 0;
111 		fprintf(output, ".*/\n");
112 	    }
113 	    while (e_lab > s_lab && (e_lab[-1] == ' ' || e_lab[-1] == '\t'))
114 		e_lab--;
115 	    cur_col = pad_output(1, compute_label_target());
116 	    if (s_lab[0] == '#' && (strncmp(s_lab, "#else", 5) == 0
117 				    || strncmp(s_lab, "#endif", 6) == 0)) {
118 		register char *s = s_lab;
119 		if (e_lab[-1] == '\n') e_lab--;
120 		do putc(*s++, output);
121 		while (s < e_lab && 'a' <= *s && *s<='z');
122 		while ((*s == ' ' || *s == '\t') && s < e_lab)
123 		    s++;
124 		if (s < e_lab)
125 		    fprintf(output, s[0]=='/' && s[1]=='*' ? "\t%.*s" : "\t/* %.*s */",
126 			    e_lab - s, s);
127 	    }
128 	    else fprintf(output, "%.*s", e_lab - s_lab, s_lab);
129 	    cur_col = count_spaces(cur_col, s_lab);
130 	}
131 	else
132 	    cur_col = 1;	/* there is no label section */
133 
134 	ps.pcase = false;
135 
136 	if (s_code != e_code) {	/* print code section, if any */
137 	    register char *p;
138 
139 	    if (comment_open) {
140 		comment_open = 0;
141 		fprintf(output, ".*/\n");
142 	    }
143 	    target_col = compute_code_target();
144 	    {
145 		register    i;
146 
147 		for (i = 0; i < ps.p_l_follow; i++)
148 		    if (ps.paren_indents[i] >= 0)
149 			ps.paren_indents[i] = -(ps.paren_indents[i] + target_col);
150 	    }
151 	    cur_col = pad_output(cur_col, target_col);
152 	    for (p = s_code; p < e_code; p++)
153 		if (*p == (char) 0200)
154 		    fprintf(output, "%d", target_col * 7);
155 		else
156 		    putc(*p, output);
157 	    cur_col = count_spaces(cur_col, s_code);
158 	}
159 	if (s_com != e_com)
160 	    if (troff) {
161 		int         all_here = 0;
162 		register char *p;
163 
164 		if (e_com[-1] == '/' && e_com[-2] == '*')
165 		    e_com -= 2, all_here++;
166 		while (e_com > s_com && e_com[-1] == ' ')
167 		    e_com--;
168 		*e_com = 0;
169 		p = s_com;
170 		while (*p == ' ')
171 		    p++;
172 		if (p[0] == '/' && p[1] == '*')
173 		    p += 2, all_here++;
174 		else if (p[0] == '*')
175 		    p += p[1] == '/' ? 2 : 1;
176 		while (*p == ' ')
177 		    p++;
178 		if (*p == 0)
179 		    goto inhibit_newline;
180 		if (comment_open < 2 && ps.box_com) {
181 		    comment_open = 0;
182 		    fprintf(output, ".*/\n");
183 		}
184 		if (comment_open == 0) {
185 		    if ('a' <= *p && *p <= 'z')
186 			*p = *p + 'A' - 'a';
187 		    if (e_com - p < 50 && all_here == 2) {
188 			register char *follow = p;
189 			fprintf(output, "\n.nr C! \\w\1");
190 			while (follow < e_com) {
191 			    switch (*follow) {
192 			    case '\n':
193 				putc(' ', output);
194 			    case 1:
195 				break;
196 			    case '\\':
197 				putc('\\', output);
198 			    default:
199 				putc(*follow, output);
200 			    }
201 			    follow++;
202 			}
203 			putc(1, output);
204 		    }
205 		    fprintf(output, "\n./* %dp %d %dp\n",
206 			    ps.com_col * 7,
207 			    (s_code != e_code || s_lab != e_lab) - ps.box_com,
208 			    target_col * 7);
209 		}
210 		comment_open = 1 + ps.box_com;
211 		while (*p) {
212 		    if (*p == BACKSLASH)
213 			putc(BACKSLASH, output);
214 		    putc(*p++, output);
215 		}
216 	    }
217 	    else {		/* print comment, if any */
218 		register    target = ps.com_col;
219 		register char *com_st = s_com;
220 
221 		target += ps.comment_delta;
222 		while (*com_st == '\t')
223 		    com_st++, target += 8;	/* ? */
224 		while (target <= 0)
225 		    if (*com_st == ' ')
226 			target++, com_st++;
227 		    else if (*com_st == '\t')
228 			target = ((target - 1) & ~7) + 9, com_st++;
229 		    else
230 			target = 1;
231 		if (cur_col > target) {	/* if comment cant fit on this line,
232 					 * put it on next line */
233 		    putc('\n', output);
234 		    cur_col = 1;
235 		    ++ps.out_lines;
236 		}
237 		while (e_com > com_st && isspace(e_com[-1]))
238 		    e_com--;
239 		cur_col = pad_output(cur_col, target);
240 		if (!ps.box_com) {
241 		    if (star_comment_cont && (com_st[1] != '*' || e_com <= com_st + 1))
242 			if (com_st[1] == ' ' && com_st[0] == ' ' && e_com > com_st + 1)
243 			    com_st[1] = '*';
244 			else
245 			    fwrite(" * ", com_st[0] == '\t' ? 2 : com_st[0] == '*' ? 1 : 3, 1, output);
246 		}
247 		fwrite(com_st, e_com - com_st, 1, output);
248 		ps.comment_delta = ps.n_comment_delta;
249 		cur_col = count_spaces(cur_col, com_st);
250 		++ps.com_lines;	/* count lines with comments */
251 	    }
252 	if (ps.use_ff)
253 	    putc('\014', output);
254 	else
255 	    putc('\n', output);
256 inhibit_newline:
257 	++ps.out_lines;
258 	if (ps.just_saw_decl == 1 && blanklines_after_declarations) {
259 	    prefix_blankline_requested = 1;
260 	    ps.just_saw_decl = 0;
261 	}
262 	else
263 	    prefix_blankline_requested = postfix_blankline_requested;
264 	postfix_blankline_requested = 0;
265     }
266     ps.decl_on_line = ps.in_decl;	/* if we are in the middle of a
267 					 * declaration, remember that fact for
268 					 * proper comment indentation */
269     ps.ind_stmt = ps.in_stmt & ~ps.in_decl;	/* next line should be
270 						 * indented if we have not
271 						 * completed this stmt and if
272 						 * we are not in the middle of
273 						 * a declaration */
274     ps.use_ff = false;
275     ps.dumped_decl_indent = 0;
276     *(e_lab = s_lab) = '\0';	/* reset buffers */
277     *(e_code = s_code) = '\0';
278     *(e_com = s_com) = '\0';
279     ps.ind_level = ps.i_l_follow;
280     ps.paren_level = ps.p_l_follow;
281     paren_target = -ps.paren_indents[ps.paren_level - 1];
282     not_first_line = 1;
283     return;
284 }
285 
286 compute_code_target()
287 {
288     register    target_col = ps.ind_size * ps.ind_level + 1;
289 
290     if (ps.paren_level)
291 	if (!lineup_to_parens)
292 	    target_col += continuation_indent * ps.paren_level;
293 	else {
294 	    register    w;
295 	    register    t = paren_target;
296 
297 	    if ((w = count_spaces(t, s_code) - max_col) > 0
298 		    && count_spaces(target_col, s_code) <= max_col) {
299 		t -= w + 1;
300 		if (t > target_col)
301 		    target_col = t;
302 	    }
303 	    else
304 		target_col = t;
305 	}
306     else if (ps.ind_stmt)
307 	target_col += continuation_indent;
308     return target_col;
309 }
310 
311 compute_label_target()
312 {
313     return
314 	ps.pcase ? (int) (case_ind * ps.ind_size) + 1
315 	: *s_lab == '#' ? 1
316 	: ps.ind_size * (ps.ind_level - label_offset) + 1;
317 }
318 
319 
320 /*
321  * Copyright (C) 1976 by the Board of Trustees of the University of Illinois
322  *
323  * All rights reserved
324  *
325  *
326  * NAME: fill_buffer
327  *
328  * FUNCTION: Reads one block of input into input_buffer
329  *
330  * HISTORY: initial coding 	November 1976	D A Willcox of CAC 1/7/77 A
331  * Willcox of CAC	Added check for switch back to partly full input
332  * buffer from temporary buffer
333  *
334  */
335 int
336 fill_buffer()
337 {				/* this routine reads stuff from the input */
338     register char *p;
339     register int i;
340     register FILE *f = input;
341 
342     if (bp_save != 0) {		/* there is a partly filled input buffer left */
343 	buf_ptr = bp_save;	/* dont read anything, just switch buffers */
344 	buf_end = be_save;
345 	bp_save = be_save = 0;
346 	if (buf_ptr < buf_end)
347 	    return;		/* only return if there is really something in
348 				 * this buffer */
349     }
350     for (p = in_buffer;;) {
351 	if (p >= in_buffer_limit) {
352 	    register size = (in_buffer_limit - in_buffer) * 2 + 10;
353 	    register offset = p - in_buffer;
354 	    in_buffer = (char *) realloc(in_buffer, size);
355 	    if (in_buffer == 0)
356 		err(1, "input line too long");
357 	    p = in_buffer + offset;
358 	    in_buffer_limit = in_buffer + size - 2;
359 	}
360 	if ((i = getc(f)) == EOF) {
361 		*p++ = ' ';
362 		*p++ = '\n';
363 		had_eof = true;
364 		break;
365 	}
366 	*p++ = i;
367 	if (i == '\n')
368 		break;
369     }
370     buf_ptr = in_buffer;
371     buf_end = p;
372     if (p[-2] == '/' && p[-3] == '*') {
373 	if (in_buffer[3] == 'I' && strncmp(in_buffer, "/**INDENT**", 11) == 0)
374 	    fill_buffer();	/* flush indent error message */
375 	else {
376 	    int         com = 0;
377 
378 	    p = in_buffer;
379 	    while (*p == ' ' || *p == '\t')
380 		p++;
381 	    if (*p == '/' && p[1] == '*') {
382 		p += 2;
383 		while (*p == ' ' || *p == '\t')
384 		    p++;
385 		if (p[0] == 'I' && p[1] == 'N' && p[2] == 'D' && p[3] == 'E'
386 			&& p[4] == 'N' && p[5] == 'T') {
387 		    p += 6;
388 		    while (*p == ' ' || *p == '\t')
389 			p++;
390 		    if (*p == '*')
391 			com = 1;
392 		    else if (*p == 'O')
393 			if (*++p == 'N')
394 			    p++, com = 1;
395 			else if (*p == 'F' && *++p == 'F')
396 			    p++, com = 2;
397 		    while (*p == ' ' || *p == '\t')
398 			p++;
399 		    if (p[0] == '*' && p[1] == '/' && p[2] == '\n' && com) {
400 			if (s_com != e_com || s_lab != e_lab || s_code != e_code)
401 			    dump_line();
402 			if (!(inhibit_formatting = com - 1)) {
403 			    n_real_blanklines = 0;
404 			    postfix_blankline_requested = 0;
405 			    prefix_blankline_requested = 0;
406 			    suppress_blanklines = 1;
407 			}
408 		    }
409 		}
410 	    }
411 	}
412     }
413     if (inhibit_formatting) {
414 	p = in_buffer;
415 	do
416 	    putc(*p, output);
417 	while (*p++ != '\n');
418     }
419     return;
420 }
421 
422 /*
423  * Copyright (C) 1976 by the Board of Trustees of the University of Illinois
424  *
425  * All rights reserved
426  *
427  *
428  * NAME: pad_output
429  *
430  * FUNCTION: Writes tabs and spaces to move the current column up to the desired
431  * position.
432  *
433  * ALGORITHM: Put tabs and/or blanks into pobuf, then write pobuf.
434  *
435  * PARAMETERS: current		integer		The current column target
436  * nteger		The desired column
437  *
438  * RETURNS: Integer value of the new column.  (If current >= target, no action is
439  * taken, and current is returned.
440  *
441  * GLOBALS: None
442  *
443  * CALLS: write (sys)
444  *
445  * CALLED BY: dump_line
446  *
447  * HISTORY: initial coding 	November 1976	D A Willcox of CAC
448  *
449  */
450 pad_output(current, target)	/* writes tabs and blanks (if necessary) to
451 				 * get the current output position up to the
452 				 * target column */
453     int         current;	/* the current column value */
454     int         target;		/* position we want it at */
455 {
456     register int curr;		/* internal column pointer */
457     register int tcur;
458 
459     if (troff)
460 	fprintf(output, "\\h'|%dp'", (target - 1) * 7);
461     else {
462 	if (current >= target)
463 	    return (current);	/* line is already long enough */
464 	curr = current;
465 	while ((tcur = ((curr - 1) & tabmask) + tabsize + 1) <= target) {
466 	    putc('\t', output);
467 	    curr = tcur;
468 	}
469 	while (curr++ < target)
470 	    putc(' ', output);	/* pad with final blanks */
471     }
472     return (target);
473 }
474 
475 /*
476  * Copyright (C) 1976 by the Board of Trustees of the University of Illinois
477  *
478  * All rights reserved
479  *
480  *
481  * NAME: count_spaces
482  *
483  * FUNCTION: Find out where printing of a given string will leave the current
484  * character position on output.
485  *
486  * ALGORITHM: Run thru input string and add appropriate values to current
487  * position.
488  *
489  * RETURNS: Integer value of position after printing "buffer" starting in column
490  * "current".
491  *
492  * HISTORY: initial coding 	November 1976	D A Willcox of CAC
493  *
494  */
495 int
496 count_spaces(current, buffer)
497 /*
498  * this routine figures out where the character position will be after
499  * printing the text in buffer starting at column "current"
500  */
501     int         current;
502     char       *buffer;
503 {
504     register char *buf;		/* used to look thru buffer */
505     register int cur;		/* current character counter */
506 
507     cur = current;
508 
509     for (buf = buffer; *buf != '\0'; ++buf) {
510 	switch (*buf) {
511 
512 	case '\n':
513 	case 014:		/* form feed */
514 	    cur = 1;
515 	    break;
516 
517 	case '\t':
518 	    cur = ((cur - 1) & tabmask) + tabsize + 1;
519 	    break;
520 
521 	case 010:		/* backspace */
522 	    --cur;
523 	    break;
524 
525 	default:
526 	    ++cur;
527 	    break;
528 	}			/* end of switch */
529     }				/* end of for loop */
530     return (cur);
531 }
532 
533 int	found_err;
534 /* VARARGS2 */
535 diag(level, msg, a, b)
536 	char *msg;
537 {
538     if (level)
539 	found_err = 1;
540     if (output == stdout) {
541 	fprintf(stdout, "/**INDENT** %s@%d: ", level == 0 ? "Warning" : "Error", line_no);
542 	fprintf(stdout, msg, a, b);
543 	fprintf(stdout, " */\n");
544     }
545     else {
546 	fprintf(stderr, "%s@%d: ", level == 0 ? "Warning" : "Error", line_no);
547 	fprintf(stderr, msg, a, b);
548 	fprintf(stderr, "\n");
549     }
550 }
551 
552 writefdef(f, nm)
553     register struct fstate *f;
554 {
555     fprintf(output, ".ds f%c %s\n.nr s%c %d\n",
556 	    nm, f->font, nm, f->size);
557 }
558 
559 char       *
560 chfont(of, nf, s)
561     register struct fstate *of,
562                *nf;
563     char       *s;
564 {
565     if (of->font[0] != nf->font[0]
566 	    || of->font[1] != nf->font[1]) {
567 	*s++ = '\\';
568 	*s++ = 'f';
569 	if (nf->font[1]) {
570 	    *s++ = '(';
571 	    *s++ = nf->font[0];
572 	    *s++ = nf->font[1];
573 	}
574 	else
575 	    *s++ = nf->font[0];
576     }
577     if (nf->size != of->size) {
578 	*s++ = '\\';
579 	*s++ = 's';
580 	if (nf->size < of->size) {
581 	    *s++ = '-';
582 	    *s++ = '0' + of->size - nf->size;
583 	}
584 	else {
585 	    *s++ = '+';
586 	    *s++ = '0' + nf->size - of->size;
587 	}
588     }
589     return s;
590 }
591 
592 
593 parsefont(f, s0)
594     register struct fstate *f;
595     char       *s0;
596 {
597     register char *s = s0;
598     int         sizedelta = 0;
599     bzero(f, sizeof *f);
600     while (*s) {
601 	if (isdigit(*s))
602 	    f->size = f->size * 10 + *s - '0';
603 	else if (isupper(*s))
604 	    if (f->font[0])
605 		f->font[1] = *s;
606 	    else
607 		f->font[0] = *s;
608 	else if (*s == 'c')
609 	    f->allcaps = 1;
610 	else if (*s == '+')
611 	    sizedelta++;
612 	else if (*s == '-')
613 	    sizedelta--;
614 	else {
615 	    errx(1, "bad font specification: %s", s0);
616 	}
617 	s++;
618     }
619     if (f->font[0] == 0)
620 	f->font[0] = 'R';
621     if (bodyf.size == 0)
622 	bodyf.size = 11;
623     if (f->size == 0)
624 	f->size = bodyf.size + sizedelta;
625     else if (sizedelta > 0)
626 	f->size += bodyf.size;
627     else
628 	f->size = bodyf.size - f->size;
629 }
630