xref: /netbsd-src/usr.bin/indent/indent.c (revision 81b108b45f75f89f1e3ffad9fb6f074e771c0935)
1 /*
2  * Copyright (c) 1985 Sun Microsystems, Inc.
3  * Copyright (c) 1980 The Regents of the University of California.
4  * Copyright (c) 1976 Board of Trustees of the University of Illinois.
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 char copyright[] =
38 "@(#) Copyright (c) 1985 Sun Microsystems, Inc.\n\
39  @(#) Copyright (c) 1980 The Regents of the University of California.\n\
40  @(#) Copyright (c) 1976 Board of Trustees of the University of Illinois.\n\
41  All rights reserved.\n";
42 #endif /* not lint */
43 
44 #ifndef lint
45 /*static char sccsid[] = "from: @(#)indent.c	5.16 (Berkeley) 2/26/91";*/
46 static char rcsid[] = "$Id: indent.c,v 1.3 1996/05/07 18:32:28 jtc Exp $";
47 #endif /* not lint */
48 
49 #include <sys/param.h>
50 #include <fcntl.h>
51 #include <unistd.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include "indent_globs.h"
56 #include "indent_codes.h"
57 #include <ctype.h>
58 #include <errno.h>
59 
60 char       *in_name = "Standard Input";	/* will always point to name of input
61 					 * file */
62 char       *out_name = "Standard Output";	/* will always point to name
63 						 * of output file */
64 char        bakfile[MAXPATHLEN] = "";
65 
66 main(argc, argv)
67     int         argc;
68     char      **argv;
69 {
70 
71     extern int  found_err;	/* flag set in diag() on error */
72     int         dec_ind;	/* current indentation for declarations */
73     int         di_stack[20];	/* a stack of structure indentation levels */
74     int         flushed_nl;	/* used when buffering up comments to remember
75 				 * that a newline was passed over */
76     int         force_nl;	/* when true, code must be broken */
77     int         hd_type;	/* used to store type of stmt for if (...),
78 				 * for (...), etc */
79     register int i;		/* local loop counter */
80     int         scase;		/* set to true when we see a case, so we will
81 				 * know what to do with the following colon */
82     int         sp_sw;		/* when true, we are in the expressin of
83 				 * if(...), while(...), etc. */
84     int         squest;		/* when this is positive, we have seen a ?
85 				 * without the matching : in a <c>?<s>:<s>
86 				 * construct */
87     register char *t_ptr;	/* used for copying tokens */
88     int         type_code;	/* the type of token, returned by lexi */
89 
90     int         last_else = 0;	/* true iff last keyword was an else */
91 
92 
93     /*-----------------------------------------------*\
94     |		      INITIALIZATION		      |
95     \*-----------------------------------------------*/
96 
97 
98     ps.p_stack[0] = stmt;	/* this is the parser's stack */
99     ps.last_nl = true;		/* this is true if the last thing scanned was
100 				 * a newline */
101     ps.last_token = semicolon;
102     combuf = (char *) malloc(bufsize);
103     labbuf = (char *) malloc(bufsize);
104     codebuf = (char *) malloc(bufsize);
105     tokenbuf = (char *) malloc(bufsize);
106     l_com = combuf + bufsize - 5;
107     l_lab = labbuf + bufsize - 5;
108     l_code = codebuf + bufsize - 5;
109     l_token = tokenbuf + bufsize - 5;
110     combuf[0] = codebuf[0] = labbuf[0] = ' ';	/* set up code, label, and
111 						 * comment buffers */
112     combuf[1] = codebuf[1] = labbuf[1] = '\0';
113     ps.else_if = 1;		/* Default else-if special processing to on */
114     s_lab = e_lab = labbuf + 1;
115     s_code = e_code = codebuf + 1;
116     s_com = e_com = combuf + 1;
117     s_token = e_token = tokenbuf + 1;
118 
119     in_buffer = (char *) malloc(10);
120     in_buffer_limit = in_buffer + 8;
121     buf_ptr = buf_end = in_buffer;
122     line_no = 1;
123     had_eof = ps.in_decl = ps.decl_on_line = break_comma = false;
124     sp_sw = force_nl = false;
125     ps.in_or_st = false;
126     ps.bl_line = true;
127     dec_ind = 0;
128     di_stack[ps.dec_nest = 0] = 0;
129     ps.want_blank = ps.in_stmt = ps.ind_stmt = false;
130 
131 
132     scase = ps.pcase = false;
133     squest = 0;
134     sc_end = 0;
135     bp_save = 0;
136     be_save = 0;
137 
138     output = 0;
139 
140 
141 
142     /*--------------------------------------------------*\
143     |   		COMMAND LINE SCAN		 |
144     \*--------------------------------------------------*/
145 
146 #ifdef undef
147     max_col = 78;		/* -l78 */
148     lineup_to_parens = 1;	/* -lp */
149     ps.ljust_decl = 0;		/* -ndj */
150     ps.com_ind = 33;		/* -c33 */
151     star_comment_cont = 1;	/* -sc */
152     ps.ind_size = 8;		/* -i8 */
153     verbose = 0;
154     ps.decl_indent = 16;	/* -di16 */
155     ps.indent_parameters = 1;	/* -ip */
156     ps.decl_com_ind = 0;	/* if this is not set to some positive value
157 				 * by an arg, we will set this equal to
158 				 * ps.com_ind */
159     btype_2 = 1;		/* -br */
160     cuddle_else = 1;		/* -ce */
161     ps.unindent_displace = 0;	/* -d0 */
162     ps.case_indent = 0;		/* -cli0 */
163     format_col1_comments = 1;	/* -fc1 */
164     procnames_start_line = 1;	/* -psl */
165     proc_calls_space = 0;	/* -npcs */
166     comment_delimiter_on_blankline = 1;	/* -cdb */
167     ps.leave_comma = 1;		/* -nbc */
168 #endif
169 
170     for (i = 1; i < argc; ++i)
171 	if (strcmp(argv[i], "-npro") == 0)
172 	    break;
173     set_defaults();
174     if (i >= argc)
175 	set_profile();
176 
177     for (i = 1; i < argc; ++i) {
178 
179 	/*
180 	 * look thru args (if any) for changes to defaults
181 	 */
182 	if (argv[i][0] != '-') {/* no flag on parameter */
183 	    if (input == 0) {	/* we must have the input file */
184 		in_name = argv[i];	/* remember name of input file */
185 		input = fopen(in_name, "r");
186 		if (input == 0)		/* check for open error */
187 			err(in_name);
188 		continue;
189 	    }
190 	    else if (output == 0) {	/* we have the output file */
191 		out_name = argv[i];	/* remember name of output file */
192 		if (strcmp(in_name, out_name) == 0) {	/* attempt to overwrite
193 							 * the file */
194 		    fprintf(stderr, "indent: input and output files must be different\n");
195 		    exit(1);
196 		}
197 		output = fopen(out_name, "w");
198 		if (output == 0)	/* check for create error */
199 			err(out_name);
200 		continue;
201 	    }
202 	    fprintf(stderr, "indent: unknown parameter: %s\n", argv[i]);
203 	    exit(1);
204 	}
205 	else
206 	    set_option(argv[i]);
207     }				/* end of for */
208     if (input == 0) {
209 	fprintf(stderr, "indent: usage: indent file [ outfile ] [ options ]\n");
210 	exit(1);
211     }
212     if (output == 0)
213 	if (troff)
214 	    output = stdout;
215 	else {
216 	    out_name = in_name;
217 	    bakcopy();
218 	}
219     if (ps.com_ind <= 1)
220 	ps.com_ind = 2;		/* dont put normal comments before column 2 */
221     if (troff) {
222 	if (bodyf.font[0] == 0)
223 	    parsefont(&bodyf, "R");
224 	if (scomf.font[0] == 0)
225 	    parsefont(&scomf, "I");
226 	if (blkcomf.font[0] == 0)
227 	    blkcomf = scomf, blkcomf.size += 2;
228 	if (boxcomf.font[0] == 0)
229 	    boxcomf = blkcomf;
230 	if (stringf.font[0] == 0)
231 	    parsefont(&stringf, "L");
232 	if (keywordf.font[0] == 0)
233 	    parsefont(&keywordf, "B");
234 	writefdef(&bodyf, 'B');
235 	writefdef(&scomf, 'C');
236 	writefdef(&blkcomf, 'L');
237 	writefdef(&boxcomf, 'X');
238 	writefdef(&stringf, 'S');
239 	writefdef(&keywordf, 'K');
240     }
241     if (block_comment_max_col <= 0)
242 	block_comment_max_col = max_col;
243     if (ps.decl_com_ind <= 0)	/* if not specified by user, set this */
244 	ps.decl_com_ind = ps.ljust_decl ? (ps.com_ind <= 10 ? 2 : ps.com_ind - 8) : ps.com_ind;
245     if (continuation_indent == 0)
246 	continuation_indent = ps.ind_size;
247     fill_buffer();		/* get first batch of stuff into input buffer */
248 
249     parse(semicolon);
250     {
251 	register char *p = buf_ptr;
252 	register    col = 1;
253 
254 	while (1) {
255 	    if (*p == ' ')
256 		col++;
257 	    else if (*p == '\t')
258 		col = ((col - 1) & ~7) + 9;
259 	    else
260 		break;
261 	    p++;
262 	}
263 	if (col > ps.ind_size)
264 	    ps.ind_level = ps.i_l_follow = col / ps.ind_size;
265     }
266     if (troff) {
267 	register char *p = in_name,
268 	           *beg = in_name;
269 
270 	while (*p)
271 	    if (*p++ == '/')
272 		beg = p;
273 	fprintf(output, ".Fn \"%s\"\n", beg);
274     }
275     /*
276      * START OF MAIN LOOP
277      */
278 
279     while (1) {			/* this is the main loop.  it will go until we
280 				 * reach eof */
281 	int         is_procname;
282 
283 	type_code = lexi();	/* lexi reads one token.  The actual
284 				 * characters read are stored in "token". lexi
285 				 * returns a code indicating the type of token */
286 	is_procname = ps.procname[0];
287 
288 	/*
289 	 * The following code moves everything following an if (), while (),
290 	 * else, etc. up to the start of the following stmt to a buffer. This
291 	 * allows proper handling of both kinds of brace placement.
292 	 */
293 
294 	flushed_nl = false;
295 	while (ps.search_brace) {	/* if we scanned an if(), while(),
296 					 * etc., we might need to copy stuff
297 					 * into a buffer we must loop, copying
298 					 * stuff into save_com, until we find
299 					 * the start of the stmt which follows
300 					 * the if, or whatever */
301 	    switch (type_code) {
302 	    case newline:
303 		++line_no;
304 		flushed_nl = true;
305 	    case form_feed:
306 		break;		/* form feeds and newlines found here will be
307 				 * ignored */
308 
309 	    case lbrace:	/* this is a brace that starts the compound
310 				 * stmt */
311 		if (sc_end == 0) {	/* ignore buffering if a comment wasnt
312 					 * stored up */
313 		    ps.search_brace = false;
314 		    goto check_type;
315 		}
316 		if (btype_2) {
317 		    save_com[0] = '{';	/* we either want to put the brace
318 					 * right after the if */
319 		    goto sw_buffer;	/* go to common code to get out of
320 					 * this loop */
321 		}
322 	    case comment:	/* we have a comment, so we must copy it into
323 				 * the buffer */
324 		if (!flushed_nl || sc_end != 0) {
325 		    if (sc_end == 0) {	/* if this is the first comment, we
326 					 * must set up the buffer */
327 			save_com[0] = save_com[1] = ' ';
328 			sc_end = &(save_com[2]);
329 		    }
330 		    else {
331 			*sc_end++ = '\n';	/* add newline between
332 						 * comments */
333 			*sc_end++ = ' ';
334 			--line_no;
335 		    }
336 		    *sc_end++ = '/';	/* copy in start of comment */
337 		    *sc_end++ = '*';
338 
339 		    for (;;) {	/* loop until we get to the end of the comment */
340 			*sc_end = *buf_ptr++;
341 			if (buf_ptr >= buf_end)
342 			    fill_buffer();
343 
344 			if (*sc_end++ == '*' && *buf_ptr == '/')
345 			    break;	/* we are at end of comment */
346 
347 			if (sc_end >= &(save_com[sc_size])) {	/* check for temp buffer
348 								 * overflow */
349 			    diag(1, "Internal buffer overflow - Move big comment from right after if, while, or whatever.");
350 			    fflush(output);
351 			    exit(1);
352 			}
353 		    }
354 		    *sc_end++ = '/';	/* add ending slash */
355 		    if (++buf_ptr >= buf_end)	/* get past / in buffer */
356 			fill_buffer();
357 		    break;
358 		}
359 	    default:		/* it is the start of a normal statment */
360 		if (flushed_nl)	/* if we flushed a newline, make sure it is
361 				 * put back */
362 		    force_nl = true;
363 		if (type_code == sp_paren && *token == 'i'
364 			&& last_else && ps.else_if
365 			|| type_code == sp_nparen && *token == 'e'
366 			&& e_code != s_code && e_code[-1] == '}')
367 		    force_nl = false;
368 
369 		if (sc_end == 0) {	/* ignore buffering if comment wasnt
370 					 * saved up */
371 		    ps.search_brace = false;
372 		    goto check_type;
373 		}
374 		if (force_nl) {	/* if we should insert a nl here, put it into
375 				 * the buffer */
376 		    force_nl = false;
377 		    --line_no;	/* this will be re-increased when the nl is
378 				 * read from the buffer */
379 		    *sc_end++ = '\n';
380 		    *sc_end++ = ' ';
381 		    if (verbose && !flushed_nl)	/* print error msg if the line
382 						 * was not already broken */
383 			diag(0, "Line broken");
384 		    flushed_nl = false;
385 		}
386 		for (t_ptr = token; *t_ptr; ++t_ptr)
387 		    *sc_end++ = *t_ptr;	/* copy token into temp buffer */
388 		ps.procname[0] = 0;
389 
390 	sw_buffer:
391 		ps.search_brace = false;	/* stop looking for start of
392 						 * stmt */
393 		bp_save = buf_ptr;	/* save current input buffer */
394 		be_save = buf_end;
395 		buf_ptr = save_com;	/* fix so that subsequent calls to
396 					 * lexi will take tokens out of
397 					 * save_com */
398 		*sc_end++ = ' ';/* add trailing blank, just in case */
399 		buf_end = sc_end;
400 		sc_end = 0;
401 		break;
402 	    }			/* end of switch */
403 	    if (type_code != 0)	/* we must make this check, just in case there
404 				 * was an unexpected EOF */
405 		type_code = lexi();	/* read another token */
406 	    /* if (ps.search_brace) ps.procname[0] = 0; */
407 	    if ((is_procname = ps.procname[0]) && flushed_nl
408 		    && !procnames_start_line && ps.in_decl
409 		    && type_code == ident)
410 		flushed_nl = 0;
411 	}			/* end of while (search_brace) */
412 	last_else = 0;
413 check_type:
414 	if (type_code == 0) {	/* we got eof */
415 	    if (s_lab != e_lab || s_code != e_code
416 		    || s_com != e_com)	/* must dump end of line */
417 		dump_line();
418 	    if (ps.tos > 1)	/* check for balanced braces */
419 		diag(1, "Stuff missing from end of file.");
420 
421 	    if (verbose) {
422 		printf("There were %d output lines and %d comments\n",
423 		       ps.out_lines, ps.out_coms);
424 		printf("(Lines with comments)/(Lines with code): %6.3f\n",
425 		       (1.0 * ps.com_lines) / code_lines);
426 	    }
427 	    fflush(output);
428 	    exit(found_err);
429 	}
430 	if (
431 		(type_code != comment) &&
432 		(type_code != newline) &&
433 		(type_code != preesc) &&
434 		(type_code != form_feed)) {
435 	    if (force_nl &&
436 		    (type_code != semicolon) &&
437 		    (type_code != lbrace || !btype_2)) {
438 		/* we should force a broken line here */
439 		if (verbose && !flushed_nl)
440 		    diag(0, "Line broken");
441 		flushed_nl = false;
442 		dump_line();
443 		ps.want_blank = false;	/* dont insert blank at line start */
444 		force_nl = false;
445 	    }
446 	    ps.in_stmt = true;	/* turn on flag which causes an extra level of
447 				 * indentation. this is turned off by a ; or
448 				 * '}' */
449 	    if (s_com != e_com) {	/* the turkey has embedded a comment
450 					 * in a line. fix it */
451 		*e_code++ = ' ';
452 		for (t_ptr = s_com; *t_ptr; ++t_ptr) {
453 		    CHECK_SIZE_CODE;
454 		    *e_code++ = *t_ptr;
455 		}
456 		*e_code++ = ' ';
457 		*e_code = '\0';	/* null terminate code sect */
458 		ps.want_blank = false;
459 		e_com = s_com;
460 	    }
461 	}
462 	else if (type_code != comment)	/* preserve force_nl thru a comment */
463 	    force_nl = false;	/* cancel forced newline after newline, form
464 				 * feed, etc */
465 
466 
467 
468 	/*-----------------------------------------------------*\
469 	|	   do switch on type of token scanned		|
470 	\*-----------------------------------------------------*/
471 	CHECK_SIZE_CODE;
472 	switch (type_code) {	/* now, decide what to do with the token */
473 
474 	case form_feed:	/* found a form feed in line */
475 	    ps.use_ff = true;	/* a form feed is treated much like a newline */
476 	    dump_line();
477 	    ps.want_blank = false;
478 	    break;
479 
480 	case newline:
481 	    if (ps.last_token != comma || ps.p_l_follow > 0
482 		    || !ps.leave_comma || ps.block_init || !break_comma || s_com != e_com) {
483 		dump_line();
484 		ps.want_blank = false;
485 	    }
486 	    ++line_no;		/* keep track of input line number */
487 	    break;
488 
489 	case lparen:		/* got a '(' or '[' */
490 	    ++ps.p_l_follow;	/* count parens to make Healy happy */
491 	    if (ps.want_blank && *token != '[' &&
492 		    (ps.last_token != ident || proc_calls_space
493 	      || (ps.its_a_keyword && (!ps.sizeof_keyword || Bill_Shannon))))
494 		*e_code++ = ' ';
495 	    if (ps.in_decl && !ps.block_init)
496 		if (troff && !ps.dumped_decl_indent && !is_procname && ps.last_token == decl) {
497 		    ps.dumped_decl_indent = 1;
498 		    sprintf(e_code, "\n.Du %dp+\200p \"%s\"\n", dec_ind * 7, token);
499 		    e_code += strlen(e_code);
500 		}
501 		else {
502 		    while ((e_code - s_code) < dec_ind) {
503 			CHECK_SIZE_CODE;
504 			*e_code++ = ' ';
505 		    }
506 		    *e_code++ = token[0];
507 		}
508 	    else
509 		*e_code++ = token[0];
510 	    ps.paren_indents[ps.p_l_follow - 1] = e_code - s_code;
511 	    if (sp_sw && ps.p_l_follow == 1 && extra_expression_indent
512 		    && ps.paren_indents[0] < 2 * ps.ind_size)
513 		ps.paren_indents[0] = 2 * ps.ind_size;
514 	    ps.want_blank = false;
515 	    if (ps.in_or_st && *token == '(' && ps.tos <= 2) {
516 		/*
517 		 * this is a kluge to make sure that declarations will be
518 		 * aligned right if proc decl has an explicit type on it, i.e.
519 		 * "int a(x) {..."
520 		 */
521 		parse(semicolon);	/* I said this was a kluge... */
522 		ps.in_or_st = false;	/* turn off flag for structure decl or
523 					 * initialization */
524 	    }
525 	    if (ps.sizeof_keyword)
526 		ps.sizeof_mask |= 1 << ps.p_l_follow;
527 	    break;
528 
529 	case rparen:		/* got a ')' or ']' */
530 	    rparen_count--;
531 	    if (ps.cast_mask & (1 << ps.p_l_follow) & ~ps.sizeof_mask) {
532 		ps.last_u_d = true;
533 		ps.cast_mask &= (1 << ps.p_l_follow) - 1;
534 	    }
535 	    ps.sizeof_mask &= (1 << ps.p_l_follow) - 1;
536 	    if (--ps.p_l_follow < 0) {
537 		ps.p_l_follow = 0;
538 		diag(0, "Extra %c", *token);
539 	    }
540 	    if (e_code == s_code)	/* if the paren starts the line */
541 		ps.paren_level = ps.p_l_follow;	/* then indent it */
542 
543 	    *e_code++ = token[0];
544 	    ps.want_blank = true;
545 
546 	    if (sp_sw && (ps.p_l_follow == 0)) {	/* check for end of if
547 							 * (...), or some such */
548 		sp_sw = false;
549 		force_nl = true;/* must force newline after if */
550 		ps.last_u_d = true;	/* inform lexi that a following
551 					 * operator is unary */
552 		ps.in_stmt = false;	/* dont use stmt continuation
553 					 * indentation */
554 
555 		parse(hd_type);	/* let parser worry about if, or whatever */
556 	    }
557 	    ps.search_brace = btype_2;	/* this should insure that constructs
558 					 * such as main(){...} and int[]{...}
559 					 * have their braces put in the right
560 					 * place */
561 	    break;
562 
563 	case unary_op:		/* this could be any unary operation */
564 	    if (ps.want_blank)
565 		*e_code++ = ' ';
566 
567 	    if (troff && !ps.dumped_decl_indent && ps.in_decl && !is_procname) {
568 		sprintf(e_code, "\n.Du %dp+\200p \"%s\"\n", dec_ind * 7, token);
569 		ps.dumped_decl_indent = 1;
570 		e_code += strlen(e_code);
571 	    }
572 	    else {
573 		char       *res = token;
574 
575 		if (ps.in_decl && !ps.block_init) {	/* if this is a unary op
576 							 * in a declaration, we
577 							 * should indent this
578 							 * token */
579 		    for (i = 0; token[i]; ++i);	/* find length of token */
580 		    while ((e_code - s_code) < (dec_ind - i)) {
581 			CHECK_SIZE_CODE;
582 			*e_code++ = ' ';	/* pad it */
583 		    }
584 		}
585 		if (troff && token[0] == '-' && token[1] == '>')
586 		    res = "\\(->";
587 		for (t_ptr = res; *t_ptr; ++t_ptr) {
588 		    CHECK_SIZE_CODE;
589 		    *e_code++ = *t_ptr;
590 		}
591 	    }
592 	    ps.want_blank = false;
593 	    break;
594 
595 	case binary_op:	/* any binary operation */
596 	    if (ps.want_blank)
597 		*e_code++ = ' ';
598 	    {
599 		char       *res = token;
600 
601 		if (troff)
602 		    switch (token[0]) {
603 		    case '<':
604 			if (token[1] == '=')
605 			    res = "\\(<=";
606 			break;
607 		    case '>':
608 			if (token[1] == '=')
609 			    res = "\\(>=";
610 			break;
611 		    case '!':
612 			if (token[1] == '=')
613 			    res = "\\(!=";
614 			break;
615 		    case '|':
616 			if (token[1] == '|')
617 			    res = "\\(br\\(br";
618 			else if (token[1] == 0)
619 			    res = "\\(br";
620 			break;
621 		    }
622 		for (t_ptr = res; *t_ptr; ++t_ptr) {
623 		    CHECK_SIZE_CODE;
624 		    *e_code++ = *t_ptr;	/* move the operator */
625 		}
626 	    }
627 	    ps.want_blank = true;
628 	    break;
629 
630 	case postop:		/* got a trailing ++ or -- */
631 	    *e_code++ = token[0];
632 	    *e_code++ = token[1];
633 	    ps.want_blank = true;
634 	    break;
635 
636 	case question:		/* got a ? */
637 	    squest++;		/* this will be used when a later colon
638 				 * appears so we can distinguish the
639 				 * <c>?<n>:<n> construct */
640 	    if (ps.want_blank)
641 		*e_code++ = ' ';
642 	    *e_code++ = '?';
643 	    ps.want_blank = true;
644 	    break;
645 
646 	case casestmt:		/* got word 'case' or 'default' */
647 	    scase = true;	/* so we can process the later colon properly */
648 	    goto copy_id;
649 
650 	case colon:		/* got a ':' */
651 	    if (squest > 0) {	/* it is part of the <c>?<n>: <n> construct */
652 		--squest;
653 		if (ps.want_blank)
654 		    *e_code++ = ' ';
655 		*e_code++ = ':';
656 		ps.want_blank = true;
657 		break;
658 	    }
659 	    if (ps.in_decl) {
660 		*e_code++ = ':';
661 		ps.want_blank = false;
662 		break;
663 	    }
664 	    ps.in_stmt = false;	/* seeing a label does not imply we are in a
665 				 * stmt */
666 	    for (t_ptr = s_code; *t_ptr; ++t_ptr)
667 		*e_lab++ = *t_ptr;	/* turn everything so far into a label */
668 	    e_code = s_code;
669 	    *e_lab++ = ':';
670 	    *e_lab++ = ' ';
671 	    *e_lab = '\0';
672 
673 	    force_nl = ps.pcase = scase;	/* ps.pcase will be used by
674 						 * dump_line to decide how to
675 						 * indent the label. force_nl
676 						 * will force a case n: to be
677 						 * on a line by itself */
678 	    scase = false;
679 	    ps.want_blank = false;
680 	    break;
681 
682 	case semicolon:	/* got a ';' */
683 	    ps.in_or_st = false;/* we are not in an initialization or
684 				 * structure declaration */
685 	    scase = false;	/* these will only need resetting in a error */
686 	    squest = 0;
687 	    if (ps.last_token == rparen && rparen_count == 0)
688 		ps.in_parameter_declaration = 0;
689 	    ps.cast_mask = 0;
690 	    ps.sizeof_mask = 0;
691 	    ps.block_init = 0;
692 	    ps.block_init_level = 0;
693 	    ps.just_saw_decl--;
694 
695 	    if (ps.in_decl && s_code == e_code && !ps.block_init)
696 		while ((e_code - s_code) < (dec_ind - 1)) {
697 		    CHECK_SIZE_CODE;
698 		    *e_code++ = ' ';
699 		}
700 
701 	    ps.in_decl = (ps.dec_nest > 0);	/* if we were in a first level
702 						 * structure declaration, we
703 						 * arent any more */
704 
705 	    if ((!sp_sw || hd_type != forstmt) && ps.p_l_follow > 0) {
706 
707 		/*
708 		 * This should be true iff there were unbalanced parens in the
709 		 * stmt.  It is a bit complicated, because the semicolon might
710 		 * be in a for stmt
711 		 */
712 		diag(1, "Unbalanced parens");
713 		ps.p_l_follow = 0;
714 		if (sp_sw) {	/* this is a check for a if, while, etc. with
715 				 * unbalanced parens */
716 		    sp_sw = false;
717 		    parse(hd_type);	/* dont lose the if, or whatever */
718 		}
719 	    }
720 	    *e_code++ = ';';
721 	    ps.want_blank = true;
722 	    ps.in_stmt = (ps.p_l_follow > 0);	/* we are no longer in the
723 						 * middle of a stmt */
724 
725 	    if (!sp_sw) {	/* if not if for (;;) */
726 		parse(semicolon);	/* let parser know about end of stmt */
727 		force_nl = true;/* force newline after a end of stmt */
728 	    }
729 	    break;
730 
731 	case lbrace:		/* got a '{' */
732 	    ps.in_stmt = false;	/* dont indent the {} */
733 	    if (!ps.block_init)
734 		force_nl = true;/* force other stuff on same line as '{' onto
735 				 * new line */
736 	    else if (ps.block_init_level <= 0)
737 		ps.block_init_level = 1;
738 	    else
739 		ps.block_init_level++;
740 
741 	    if (s_code != e_code && !ps.block_init) {
742 		if (!btype_2) {
743 		    dump_line();
744 		    ps.want_blank = false;
745 		}
746 		else if (ps.in_parameter_declaration && !ps.in_or_st) {
747 		    ps.i_l_follow = 0;
748 		    dump_line();
749 		    ps.want_blank = false;
750 		}
751 	    }
752 	    if (ps.in_parameter_declaration)
753 		prefix_blankline_requested = 0;
754 
755 	    if (ps.p_l_follow > 0) {	/* check for preceeding unbalanced
756 					 * parens */
757 		diag(1, "Unbalanced parens");
758 		ps.p_l_follow = 0;
759 		if (sp_sw) {	/* check for unclosed if, for, etc. */
760 		    sp_sw = false;
761 		    parse(hd_type);
762 		    ps.ind_level = ps.i_l_follow;
763 		}
764 	    }
765 	    if (s_code == e_code)
766 		ps.ind_stmt = false;	/* dont put extra indentation on line
767 					 * with '{' */
768 	    if (ps.in_decl && ps.in_or_st) {	/* this is either a structure
769 						 * declaration or an init */
770 		di_stack[ps.dec_nest++] = dec_ind;
771 		/* ?		dec_ind = 0; */
772 	    }
773 	    else {
774 		ps.decl_on_line = false;	/* we cant be in the middle of
775 						 * a declaration, so dont do
776 						 * special indentation of
777 						 * comments */
778 		if (blanklines_after_declarations_at_proctop
779 			&& ps.in_parameter_declaration)
780 		    postfix_blankline_requested = 1;
781 		ps.in_parameter_declaration = 0;
782 	    }
783 	    dec_ind = 0;
784 	    parse(lbrace);	/* let parser know about this */
785 	    if (ps.want_blank)	/* put a blank before '{' if '{' is not at
786 				 * start of line */
787 		*e_code++ = ' ';
788 	    ps.want_blank = false;
789 	    *e_code++ = '{';
790 	    ps.just_saw_decl = 0;
791 	    break;
792 
793 	case rbrace:		/* got a '}' */
794 	    if (ps.p_stack[ps.tos] == decl && !ps.block_init)	/* semicolons can be
795 								 * omitted in
796 								 * declarations */
797 		parse(semicolon);
798 	    if (ps.p_l_follow) {/* check for unclosed if, for, else. */
799 		diag(1, "Unbalanced parens");
800 		ps.p_l_follow = 0;
801 		sp_sw = false;
802 	    }
803 	    ps.just_saw_decl = 0;
804 	    ps.block_init_level--;
805 	    if (s_code != e_code && !ps.block_init) {	/* '}' must be first on
806 							 * line */
807 		if (verbose)
808 		    diag(0, "Line broken");
809 		dump_line();
810 	    }
811 	    *e_code++ = '}';
812 	    ps.want_blank = true;
813 	    ps.in_stmt = ps.ind_stmt = false;
814 	    if (ps.dec_nest > 0) {	/* we are in multi-level structure
815 					 * declaration */
816 		dec_ind = di_stack[--ps.dec_nest];
817 		if (ps.dec_nest == 0 && !ps.in_parameter_declaration)
818 		    ps.just_saw_decl = 2;
819 		ps.in_decl = true;
820 	    }
821 	    prefix_blankline_requested = 0;
822 	    parse(rbrace);	/* let parser know about this */
823 	    ps.search_brace = cuddle_else && ps.p_stack[ps.tos] == ifhead
824 		&& ps.il[ps.tos] >= ps.ind_level;
825 	    if (ps.tos <= 1 && blanklines_after_procs && ps.dec_nest <= 0)
826 		postfix_blankline_requested = 1;
827 	    break;
828 
829 	case swstmt:		/* got keyword "switch" */
830 	    sp_sw = true;
831 	    hd_type = swstmt;	/* keep this for when we have seen the
832 				 * expression */
833 	    goto copy_id;	/* go move the token into buffer */
834 
835 	case sp_paren:		/* token is if, while, for */
836 	    sp_sw = true;	/* the interesting stuff is done after the
837 				 * expression is scanned */
838 	    hd_type = (*token == 'i' ? ifstmt :
839 		       (*token == 'w' ? whilestmt : forstmt));
840 
841 	    /*
842 	     * remember the type of header for later use by parser
843 	     */
844 	    goto copy_id;	/* copy the token into line */
845 
846 	case sp_nparen:	/* got else, do */
847 	    ps.in_stmt = false;
848 	    if (*token == 'e') {
849 		if (e_code != s_code && (!cuddle_else || e_code[-1] != '}')) {
850 		    if (verbose)
851 			diag(0, "Line broken");
852 		    dump_line();/* make sure this starts a line */
853 		    ps.want_blank = false;
854 		}
855 		force_nl = true;/* also, following stuff must go onto new line */
856 		last_else = 1;
857 		parse(elselit);
858 	    }
859 	    else {
860 		if (e_code != s_code) {	/* make sure this starts a line */
861 		    if (verbose)
862 			diag(0, "Line broken");
863 		    dump_line();
864 		    ps.want_blank = false;
865 		}
866 		force_nl = true;/* also, following stuff must go onto new line */
867 		last_else = 0;
868 		parse(dolit);
869 	    }
870 	    goto copy_id;	/* move the token into line */
871 
872 	case decl:		/* we have a declaration type (int, register,
873 				 * etc.) */
874 	    parse(decl);	/* let parser worry about indentation */
875 	    if (ps.last_token == rparen && ps.tos <= 1) {
876 		ps.in_parameter_declaration = 1;
877 		if (s_code != e_code) {
878 		    dump_line();
879 		    ps.want_blank = 0;
880 		}
881 	    }
882 	    if (ps.in_parameter_declaration && ps.indent_parameters && ps.dec_nest == 0) {
883 		ps.ind_level = ps.i_l_follow = 1;
884 		ps.ind_stmt = 0;
885 	    }
886 	    ps.in_or_st = true;	/* this might be a structure or initialization
887 				 * declaration */
888 	    ps.in_decl = ps.decl_on_line = true;
889 	    if ( /* !ps.in_or_st && */ ps.dec_nest <= 0)
890 		ps.just_saw_decl = 2;
891 	    prefix_blankline_requested = 0;
892 	    for (i = 0; token[i++];);	/* get length of token */
893 
894 	    /*
895 	     * dec_ind = e_code - s_code + (ps.decl_indent>i ? ps.decl_indent
896 	     * : i);
897 	     */
898 	    dec_ind = ps.decl_indent > 0 ? ps.decl_indent : i;
899 	    goto copy_id;
900 
901 	case ident:		/* got an identifier or constant */
902 	    if (ps.in_decl) {	/* if we are in a declaration, we must indent
903 				 * identifier */
904 		if (ps.want_blank)
905 		    *e_code++ = ' ';
906 		ps.want_blank = false;
907 		if (is_procname == 0 || !procnames_start_line) {
908 		    if (!ps.block_init)
909 			if (troff && !ps.dumped_decl_indent) {
910 			    sprintf(e_code, "\n.De %dp+\200p\n", dec_ind * 7);
911 			    ps.dumped_decl_indent = 1;
912 			    e_code += strlen(e_code);
913 			}
914 			else
915 			    while ((e_code - s_code) < dec_ind) {
916 				CHECK_SIZE_CODE;
917 				*e_code++ = ' ';
918 			    }
919 		}
920 		else {
921 		    if (dec_ind && s_code != e_code)
922 			dump_line();
923 		    dec_ind = 0;
924 		    ps.want_blank = false;
925 		}
926 	    }
927 	    else if (sp_sw && ps.p_l_follow == 0) {
928 		sp_sw = false;
929 		force_nl = true;
930 		ps.last_u_d = true;
931 		ps.in_stmt = false;
932 		parse(hd_type);
933 	    }
934     copy_id:
935 	    if (ps.want_blank)
936 		*e_code++ = ' ';
937 	    if (troff && ps.its_a_keyword) {
938 		e_code = chfont(&bodyf, &keywordf, e_code);
939 		for (t_ptr = token; *t_ptr; ++t_ptr) {
940 		    CHECK_SIZE_CODE;
941 		    *e_code++ = keywordf.allcaps && islower(*t_ptr)
942 			? toupper(*t_ptr) : *t_ptr;
943 		}
944 		e_code = chfont(&keywordf, &bodyf, e_code);
945 	    }
946 	    else
947 		for (t_ptr = token; *t_ptr; ++t_ptr) {
948 		    CHECK_SIZE_CODE;
949 		    *e_code++ = *t_ptr;
950 		}
951 	    ps.want_blank = true;
952 	    break;
953 
954 	case period:		/* treat a period kind of like a binary
955 				 * operation */
956 	    *e_code++ = '.';	/* move the period into line */
957 	    ps.want_blank = false;	/* dont put a blank after a period */
958 	    break;
959 
960 	case comma:
961 	    ps.want_blank = (s_code != e_code);	/* only put blank after comma
962 						 * if comma does not start the
963 						 * line */
964 	    if (ps.in_decl && is_procname == 0 && !ps.block_init)
965 		while ((e_code - s_code) < (dec_ind - 1)) {
966 		    CHECK_SIZE_CODE;
967 		    *e_code++ = ' ';
968 		}
969 
970 	    *e_code++ = ',';
971 	    if (ps.p_l_follow == 0) {
972 		if (ps.block_init_level <= 0)
973 		    ps.block_init = 0;
974 		if (break_comma && (!ps.leave_comma || compute_code_target() + (e_code - s_code) > max_col - 8))
975 		    force_nl = true;
976 	    }
977 	    break;
978 
979 	case preesc:		/* got the character '#' */
980 	    if ((s_com != e_com) ||
981 		    (s_lab != e_lab) ||
982 		    (s_code != e_code))
983 		dump_line();
984 	    *e_lab++ = '#';	/* move whole line to 'label' buffer */
985 	    {
986 		int         in_comment = 0;
987 		int         com_start = 0;
988 		char        quote = 0;
989 		int         com_end = 0;
990 
991 		while (*buf_ptr == ' ' || *buf_ptr == '\t') {
992 		    buf_ptr++;
993 		    if (buf_ptr >= buf_end)
994 			fill_buffer();
995 		}
996 		while (*buf_ptr != '\n' || in_comment) {
997 		    CHECK_SIZE_LAB;
998 		    *e_lab = *buf_ptr++;
999 		    if (buf_ptr >= buf_end)
1000 			fill_buffer();
1001 		    switch (*e_lab++) {
1002 		    case BACKSLASH:
1003 			if (troff)
1004 			    *e_lab++ = BACKSLASH;
1005 			if (!in_comment) {
1006 			    *e_lab++ = *buf_ptr++;
1007 			    if (buf_ptr >= buf_end)
1008 				fill_buffer();
1009 			}
1010 			break;
1011 		    case '/':
1012 			if (*buf_ptr == '*' && !in_comment && !quote) {
1013 			    in_comment = 1;
1014 			    *e_lab++ = *buf_ptr++;
1015 			    com_start = e_lab - s_lab - 2;
1016 			}
1017 			break;
1018 		    case '"':
1019 			if (quote == '"')
1020 			    quote = 0;
1021 			break;
1022 		    case '\'':
1023 			if (quote == '\'')
1024 			    quote = 0;
1025 			break;
1026 		    case '*':
1027 			if (*buf_ptr == '/' && in_comment) {
1028 			    in_comment = 0;
1029 			    *e_lab++ = *buf_ptr++;
1030 			    com_end = e_lab - s_lab;
1031 			}
1032 			break;
1033 		    }
1034 		}
1035 
1036 		while (e_lab > s_lab && (e_lab[-1] == ' ' || e_lab[-1] == '\t'))
1037 		    e_lab--;
1038 		if (e_lab - s_lab == com_end && bp_save == 0) {	/* comment on
1039 								 * preprocessor line */
1040 		    if (sc_end == 0)	/* if this is the first comment, we
1041 					 * must set up the buffer */
1042 			sc_end = &(save_com[0]);
1043 		    else {
1044 			*sc_end++ = '\n';	/* add newline between
1045 						 * comments */
1046 			*sc_end++ = ' ';
1047 			--line_no;
1048 		    }
1049 		    bcopy(s_lab + com_start, sc_end, com_end - com_start);
1050 		    sc_end += com_end - com_start;
1051 		    if (sc_end >= &save_com[sc_size])
1052 			abort();
1053 		    e_lab = s_lab + com_start;
1054 		    while (e_lab > s_lab && (e_lab[-1] == ' ' || e_lab[-1] == '\t'))
1055 			e_lab--;
1056 		    bp_save = buf_ptr;	/* save current input buffer */
1057 		    be_save = buf_end;
1058 		    buf_ptr = save_com;	/* fix so that subsequent calls to
1059 					 * lexi will take tokens out of
1060 					 * save_com */
1061 		    *sc_end++ = ' ';	/* add trailing blank, just in case */
1062 		    buf_end = sc_end;
1063 		    sc_end = 0;
1064 		}
1065 		*e_lab = '\0';	/* null terminate line */
1066 		ps.pcase = false;
1067 	    }
1068 
1069 	    if (strncmp(s_lab, "#if", 3) == 0) {
1070 		if (blanklines_around_conditional_compilation) {
1071 		    register    c;
1072 		    prefix_blankline_requested++;
1073 		    while ((c = getc(input)) == '\n');
1074 		    ungetc(c, input);
1075 		}
1076 		if (ifdef_level < sizeof state_stack / sizeof state_stack[0]) {
1077 		    match_state[ifdef_level].tos = -1;
1078 		    state_stack[ifdef_level++] = ps;
1079 		}
1080 		else
1081 		    diag(1, "#if stack overflow");
1082 	    }
1083 	    else if (strncmp(s_lab, "#else", 5) == 0)
1084 		if (ifdef_level <= 0)
1085 		    diag(1, "Unmatched #else");
1086 		else {
1087 		    match_state[ifdef_level - 1] = ps;
1088 		    ps = state_stack[ifdef_level - 1];
1089 		}
1090 	    else if (strncmp(s_lab, "#endif", 6) == 0) {
1091 		if (ifdef_level <= 0)
1092 		    diag(1, "Unmatched #endif");
1093 		else {
1094 		    ifdef_level--;
1095 
1096 #ifdef undef
1097 		    /*
1098 		     * This match needs to be more intelligent before the
1099 		     * message is useful
1100 		     */
1101 		    if (match_state[ifdef_level].tos >= 0
1102 			  && bcmp(&ps, &match_state[ifdef_level], sizeof ps))
1103 			diag(0, "Syntactically inconsistant #ifdef alternatives.");
1104 #endif
1105 		}
1106 		if (blanklines_around_conditional_compilation) {
1107 		    postfix_blankline_requested++;
1108 		    n_real_blanklines = 0;
1109 		}
1110 	    }
1111 	    break;		/* subsequent processing of the newline
1112 				 * character will cause the line to be printed */
1113 
1114 	case comment:		/* we have gotten a /*  this is a biggie */
1115 	    if (flushed_nl) {	/* we should force a broken line here */
1116 		flushed_nl = false;
1117 		dump_line();
1118 		ps.want_blank = false;	/* dont insert blank at line start */
1119 		force_nl = false;
1120 	    }
1121 	    pr_comment();
1122 	    break;
1123 	}			/* end of big switch stmt */
1124 
1125 	*e_code = '\0';		/* make sure code section is null terminated */
1126 	if (type_code != comment && type_code != newline && type_code != preesc)
1127 	    ps.last_token = type_code;
1128     }				/* end of main while (1) loop */
1129 }
1130 
1131 /*
1132  * copy input file to backup file if in_name is /blah/blah/blah/file, then
1133  * backup file will be ".Bfile" then make the backup file the input and
1134  * original input file the output
1135  */
1136 bakcopy()
1137 {
1138     int         n,
1139                 bakchn;
1140     char        buff[8 * 1024];
1141     register char *p;
1142 
1143     /* construct file name .Bfile */
1144     for (p = in_name; *p; p++);	/* skip to end of string */
1145     while (p > in_name && *p != '/')	/* find last '/' */
1146 	p--;
1147     if (*p == '/')
1148 	p++;
1149     sprintf(bakfile, "%s.BAK", p);
1150 
1151     /* copy in_name to backup file */
1152     bakchn = creat(bakfile, 0600);
1153     if (bakchn < 0)
1154 	err(bakfile);
1155     while (n = read(fileno(input), buff, sizeof buff))
1156 	if (write(bakchn, buff, n) != n)
1157 	    err(bakfile);
1158     if (n < 0)
1159 	err(in_name);
1160     close(bakchn);
1161     fclose(input);
1162 
1163     /* re-open backup file as the input file */
1164     input = fopen(bakfile, "r");
1165     if (input == 0)
1166 	err(bakfile);
1167     /* now the original input file will be the output */
1168     output = fopen(in_name, "w");
1169     if (output == 0) {
1170 	unlink(bakfile);
1171 	err(in_name);
1172     }
1173 }
1174 
1175 err(msg)
1176 	char *msg;
1177 {
1178 	(void)fprintf(stderr, "indent: %s: %s\n", msg, strerror(errno));
1179 	exit(1);
1180 }
1181