2 * Copyright (c) 1985 Sun Microsystems, Inc.
3 * Copyright (c) 1976 Board of Trustees of the University of Illinois.
4 * Copyright (c) 1980, 1993
5 * The Regents of the University of California. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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.
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
37 static const char copyright[] =
38 "@(#) Copyright (c) 1985 Sun Microsystems, Inc.\n\
39 @(#) Copyright (c) 1976 Board of Trustees of the University of Illinois.\n\
40 @(#) Copyright (c) 1980, 1993\n\
41 The Regents of the University of California. All rights reserved.\n";
46 static char sccsid[] = "@(#)indent.c 5.17 (Berkeley) 6/7/93";
50 #include <sys/cdefs.h>
51 __FBSDID("$FreeBSD$");
53 #include <sys/param.h>
54 #include <sys/capsicum.h>
63 #include "indent_globs.h"
64 #include "indent_codes.h"
67 static void bakcopy(void);
68 static void indent_declaration(int, int);
70 const char *in_name = "Standard Input"; /* will always point to name of input
72 const char *out_name = "Standard Output"; /* will always point to name
74 char bakfile[MAXPATHLEN] = "";
77 main(int argc, char **argv)
81 int dec_ind; /* current indentation for declarations */
82 int di_stack[20]; /* a stack of structure indentation levels */
83 int flushed_nl; /* used when buffering up comments to remember
84 * that a newline was passed over */
85 int force_nl; /* when true, code must be broken */
86 int hd_type = 0; /* used to store type of stmt for if (...),
88 int i; /* local loop counter */
89 int scase; /* set to true when we see a case, so we will
90 * know what to do with the following colon */
91 int sp_sw; /* when true, we are in the expression of
92 * if(...), while(...), etc. */
93 int squest; /* when this is positive, we have seen a ?
94 * without the matching : in a <c>?<s>:<s>
96 const char *t_ptr; /* used for copying tokens */
97 int tabs_to_var; /* true if using tabs to indent to var name */
98 int type_code; /* the type of token, returned by lexi */
100 int last_else = 0; /* true iff last keyword was an else */
103 /*-----------------------------------------------*\
105 \*-----------------------------------------------*/
109 ps.p_stack[0] = stmt; /* this is the parser's stack */
110 ps.last_nl = true; /* this is true if the last thing scanned was
112 ps.last_token = semicolon;
113 combuf = (char *) malloc(bufsize);
116 labbuf = (char *) malloc(bufsize);
119 codebuf = (char *) malloc(bufsize);
122 tokenbuf = (char *) malloc(bufsize);
123 if (tokenbuf == NULL)
126 l_com = combuf + bufsize - 5;
127 l_lab = labbuf + bufsize - 5;
128 l_code = codebuf + bufsize - 5;
129 l_token = tokenbuf + bufsize - 5;
130 combuf[0] = codebuf[0] = labbuf[0] = ' '; /* set up code, label, and
132 combuf[1] = codebuf[1] = labbuf[1] = '\0';
133 ps.else_if = 1; /* Default else-if special processing to on */
134 s_lab = e_lab = labbuf + 1;
135 s_code = e_code = codebuf + 1;
136 s_com = e_com = combuf + 1;
137 s_token = e_token = tokenbuf + 1;
139 in_buffer = (char *) malloc(10);
140 if (in_buffer == NULL)
142 in_buffer_limit = in_buffer + 8;
143 buf_ptr = buf_end = in_buffer;
145 had_eof = ps.in_decl = ps.decl_on_line = break_comma = false;
146 sp_sw = force_nl = false;
150 di_stack[ps.dec_nest = 0] = 0;
151 ps.want_blank = ps.in_stmt = ps.ind_stmt = false;
153 scase = ps.pcase = false;
162 /*--------------------------------------------------*\
163 | COMMAND LINE SCAN |
164 \*--------------------------------------------------*/
167 max_col = 78; /* -l78 */
168 lineup_to_parens = 1; /* -lp */
169 ps.ljust_decl = 0; /* -ndj */
170 ps.com_ind = 33; /* -c33 */
171 star_comment_cont = 1; /* -sc */
172 ps.ind_size = 8; /* -i8 */
174 ps.decl_indent = 16; /* -di16 */
175 ps.local_decl_indent = -1; /* if this is not set to some nonnegative value
176 * by an arg, we will set this equal to
178 ps.indent_parameters = 1; /* -ip */
179 ps.decl_com_ind = 0; /* if this is not set to some positive value
180 * by an arg, we will set this equal to
182 btype_2 = 1; /* -br */
183 cuddle_else = 1; /* -ce */
184 ps.unindent_displace = 0; /* -d0 */
185 ps.case_indent = 0; /* -cli0 */
186 format_block_comments = 1; /* -fcb */
187 format_col1_comments = 1; /* -fc1 */
188 procnames_start_line = 1; /* -psl */
189 proc_calls_space = 0; /* -npcs */
190 comment_delimiter_on_blankline = 1; /* -cdb */
191 ps.leave_comma = 1; /* -nbc */
194 for (i = 1; i < argc; ++i)
195 if (strcmp(argv[i], "-npro") == 0)
201 for (i = 1; i < argc; ++i) {
204 * look thru args (if any) for changes to defaults
206 if (argv[i][0] != '-') {/* no flag on parameter */
207 if (input == NULL) { /* we must have the input file */
208 in_name = argv[i]; /* remember name of input file */
209 input = fopen(in_name, "r");
210 if (input == NULL) /* check for open error */
211 err(1, "%s", in_name);
214 else if (output == NULL) { /* we have the output file */
215 out_name = argv[i]; /* remember name of output file */
216 if (strcmp(in_name, out_name) == 0) { /* attempt to overwrite
218 errx(1, "input and output files must be different");
220 output = fopen(out_name, "w");
221 if (output == NULL) /* check for create error */
222 err(1, "%s", out_name);
225 errx(1, "unknown parameter: %s", argv[i]);
232 if (output == NULL) {
233 if (troff || input == stdin)
241 /* Restrict input/output descriptors and enter Capsicum sandbox. */
242 cap_rights_init(&rights, CAP_FSTAT, CAP_WRITE);
243 if (cap_rights_limit(fileno(output), &rights) < 0 && errno != ENOSYS)
244 err(EXIT_FAILURE, "unable to limit rights for %s", out_name);
245 cap_rights_init(&rights, CAP_FSTAT, CAP_READ);
246 if (cap_rights_limit(fileno(input), &rights) < 0 && errno != ENOSYS)
247 err(EXIT_FAILURE, "unable to limit rights for %s", in_name);
248 if (cap_enter() < 0 && errno != ENOSYS)
249 err(EXIT_FAILURE, "unable to enter capability mode");
252 ps.com_ind = 2; /* dont put normal comments before column 2 */
254 if (bodyf.font[0] == 0)
255 parsefont(&bodyf, "R");
256 if (scomf.font[0] == 0)
257 parsefont(&scomf, "I");
258 if (blkcomf.font[0] == 0)
259 blkcomf = scomf, blkcomf.size += 2;
260 if (boxcomf.font[0] == 0)
262 if (stringf.font[0] == 0)
263 parsefont(&stringf, "L");
264 if (keywordf.font[0] == 0)
265 parsefont(&keywordf, "B");
266 writefdef(&bodyf, 'B');
267 writefdef(&scomf, 'C');
268 writefdef(&blkcomf, 'L');
269 writefdef(&boxcomf, 'X');
270 writefdef(&stringf, 'S');
271 writefdef(&keywordf, 'K');
273 if (block_comment_max_col <= 0)
274 block_comment_max_col = max_col;
275 if (ps.local_decl_indent < 0) /* if not specified by user, set this */
276 ps.local_decl_indent = ps.decl_indent;
277 if (ps.decl_com_ind <= 0) /* if not specified by user, set this */
278 ps.decl_com_ind = ps.ljust_decl ? (ps.com_ind <= 10 ? 2 : ps.com_ind - 8) : ps.com_ind;
279 if (continuation_indent == 0)
280 continuation_indent = ps.ind_size;
281 fill_buffer(); /* get first batch of stuff into input buffer */
292 col = ((col - 1) & ~7) + 9;
297 if (col > ps.ind_size)
298 ps.ind_level = ps.i_l_follow = col / ps.ind_size;
301 const char *p = in_name,
307 fprintf(output, ".Fn \"%s\"\n", beg);
313 while (1) { /* this is the main loop. it will go until we
317 type_code = lexi(); /* lexi reads one token. The actual
318 * characters read are stored in "token". lexi
319 * returns a code indicating the type of token */
320 is_procname = ps.procname[0];
323 * The following code moves everything following an if (), while (),
324 * else, etc. up to the start of the following stmt to a buffer. This
325 * allows proper handling of both kinds of brace placement.
329 while (ps.search_brace) { /* if we scanned an if(), while(),
330 * etc., we might need to copy stuff
331 * into a buffer we must loop, copying
332 * stuff into save_com, until we find
333 * the start of the stmt which follows
334 * the if, or whatever */
338 if (sc_end != NULL) { /* dump comment, if any */
339 *sc_end++ = '\n'; /* newlines are needed in this case */
344 break; /* form feeds and newlines found here will be
347 case lbrace: /* this is a brace that starts the compound
349 if (sc_end == NULL) { /* ignore buffering if a comment wasn't
351 ps.search_brace = false;
355 save_com[0] = '{'; /* we either want to put the brace
356 * right after the if */
357 goto sw_buffer; /* go to common code to get out of
360 case comment: /* we have a comment, so we must copy it into
362 if (!flushed_nl || sc_end != NULL) {
363 if (sc_end == NULL) { /* if this is the first comment, we
364 * must set up the buffer */
365 save_com[0] = save_com[1] = ' ';
366 sc_end = &(save_com[2]);
369 *sc_end++ = '\n'; /* add newline between
374 *sc_end++ = '/'; /* copy in start of comment */
377 for (;;) { /* loop until we get to the end of the comment */
378 *sc_end = *buf_ptr++;
379 if (buf_ptr >= buf_end)
382 if (*sc_end++ == '*' && *buf_ptr == '/')
383 break; /* we are at end of comment */
385 if (sc_end >= &(save_com[sc_size])) { /* check for temp buffer
387 diag2(1, "Internal buffer overflow - Move big comment from right after if, while, or whatever");
392 *sc_end++ = '/'; /* add ending slash */
393 if (++buf_ptr >= buf_end) /* get past / in buffer */
397 default: /* it is the start of a normal statement */
398 if (flushed_nl) /* if we flushed a newline, make sure it is
401 if ((type_code == sp_paren && *token == 'i'
402 && last_else && ps.else_if)
403 || (type_code == sp_nparen && *token == 'e'
404 && e_code != s_code && e_code[-1] == '}'))
407 if (sc_end == NULL) { /* ignore buffering if comment wasn't
409 ps.search_brace = false;
412 if (force_nl) { /* if we should insert a nl here, put it into
415 --line_no; /* this will be re-increased when the nl is
416 * read from the buffer */
419 if (verbose && !flushed_nl) /* print error msg if the line
420 * was not already broken */
421 diag2(0, "Line broken");
424 for (t_ptr = token; *t_ptr; ++t_ptr)
425 *sc_end++ = *t_ptr; /* copy token into temp buffer */
429 ps.search_brace = false; /* stop looking for start of
431 bp_save = buf_ptr; /* save current input buffer */
433 buf_ptr = save_com; /* fix so that subsequent calls to
434 * lexi will take tokens out of
436 *sc_end++ = ' ';/* add trailing blank, just in case */
440 } /* end of switch */
441 if (type_code != 0) /* we must make this check, just in case there
442 * was an unexpected EOF */
443 type_code = lexi(); /* read another token */
444 /* if (ps.search_brace) ps.procname[0] = 0; */
445 if ((is_procname = ps.procname[0]) && flushed_nl
446 && !procnames_start_line && ps.in_decl
447 && type_code == ident)
449 } /* end of while (search_brace) */
452 if (type_code == 0) { /* we got eof */
453 if (s_lab != e_lab || s_code != e_code
454 || s_com != e_com) /* must dump end of line */
456 if (ps.tos > 1) /* check for balanced braces */
457 diag2(1, "Stuff missing from end of file");
460 printf("There were %d output lines and %d comments\n",
461 ps.out_lines, ps.out_coms);
462 printf("(Lines with comments)/(Lines with code): %6.3f\n",
463 (1.0 * ps.com_lines) / code_lines);
469 (type_code != comment) &&
470 (type_code != newline) &&
471 (type_code != preesc) &&
472 (type_code != form_feed)) {
474 (type_code != semicolon) &&
475 (type_code != lbrace || !btype_2)) {
476 /* we should force a broken line here */
477 if (verbose && !flushed_nl)
478 diag2(0, "Line broken");
481 ps.want_blank = false; /* dont insert blank at line start */
484 ps.in_stmt = true; /* turn on flag which causes an extra level of
485 * indentation. this is turned off by a ; or
487 if (s_com != e_com) { /* the turkey has embedded a comment
488 * in a line. fix it */
490 for (t_ptr = s_com; *t_ptr; ++t_ptr) {
495 *e_code = '\0'; /* null terminate code sect */
496 ps.want_blank = false;
500 else if (type_code != comment) /* preserve force_nl thru a comment */
501 force_nl = false; /* cancel forced newline after newline, form
506 /*-----------------------------------------------------*\
507 | do switch on type of token scanned |
508 \*-----------------------------------------------------*/
510 switch (type_code) { /* now, decide what to do with the token */
512 case form_feed: /* found a form feed in line */
513 ps.use_ff = true; /* a form feed is treated much like a newline */
515 ps.want_blank = false;
519 if (ps.last_token != comma || ps.p_l_follow > 0
520 || !ps.leave_comma || ps.block_init || !break_comma || s_com != e_com) {
522 ps.want_blank = false;
524 ++line_no; /* keep track of input line number */
527 case lparen: /* got a '(' or '[' */
528 ++ps.p_l_follow; /* count parens to make Healy happy */
529 if (ps.want_blank && *token != '[' &&
530 (ps.last_token != ident || proc_calls_space ||
531 /* offsetof (1) is never allowed a space; sizeof (2) gets
532 * one iff -bs; all other keywords (>2) always get a space
534 (ps.keyword + Bill_Shannon > 2)))
536 ps.want_blank = false;
537 if (ps.in_decl && !ps.block_init && !ps.dumped_decl_indent &&
539 /* function pointer declarations */
541 sprintf(e_code, "\n.Du %dp+\200p \"%s\"\n", dec_ind * 7, token);
542 e_code += strlen(e_code);
545 indent_declaration(dec_ind, tabs_to_var);
547 ps.dumped_decl_indent = true;
550 *e_code++ = token[0];
551 ps.paren_indents[ps.p_l_follow - 1] = e_code - s_code;
552 if (sp_sw && ps.p_l_follow == 1 && extra_expression_indent
553 && ps.paren_indents[0] < 2 * ps.ind_size)
554 ps.paren_indents[0] = 2 * ps.ind_size;
555 if (ps.in_or_st && *token == '(' && ps.tos <= 2) {
557 * this is a kluge to make sure that declarations will be
558 * aligned right if proc decl has an explicit type on it, i.e.
561 parse(semicolon); /* I said this was a kluge... */
562 ps.in_or_st = false; /* turn off flag for structure decl or
565 /* parenthesized type following sizeof or offsetof is not a cast */
566 if (ps.keyword == 1 || ps.keyword == 2)
567 ps.not_cast_mask |= 1 << ps.p_l_follow;
570 case rparen: /* got a ')' or ']' */
572 if (ps.cast_mask & (1 << ps.p_l_follow) & ~ps.not_cast_mask) {
574 ps.cast_mask &= (1 << ps.p_l_follow) - 1;
575 ps.want_blank = space_after_cast;
577 ps.want_blank = true;
578 ps.not_cast_mask &= (1 << ps.p_l_follow) - 1;
579 if (--ps.p_l_follow < 0) {
581 diag3(0, "Extra %c", *token);
583 if (e_code == s_code) /* if the paren starts the line */
584 ps.paren_level = ps.p_l_follow; /* then indent it */
586 *e_code++ = token[0];
588 if (sp_sw && (ps.p_l_follow == 0)) { /* check for end of if
589 * (...), or some such */
591 force_nl = true;/* must force newline after if */
592 ps.last_u_d = true; /* inform lexi that a following
593 * operator is unary */
594 ps.in_stmt = false; /* dont use stmt continuation
597 parse(hd_type); /* let parser worry about if, or whatever */
599 ps.search_brace = btype_2; /* this should insure that constructs
600 * such as main(){...} and int[]{...}
601 * have their braces put in the right
605 case unary_op: /* this could be any unary operation */
606 if (!ps.dumped_decl_indent && ps.in_decl && !is_procname &&
608 /* pointer declarations */
612 sprintf(e_code, "\n.Du %dp+\200p \"%s\"\n", dec_ind * 7,
614 e_code += strlen(e_code);
617 /* if this is a unary op in a declaration, we should
618 * indent this token */
619 for (i = 0; token[i]; ++i)
620 /* find length of token */;
621 indent_declaration(dec_ind - i, tabs_to_var);
623 ps.dumped_decl_indent = true;
625 else if (ps.want_blank)
628 const char *res = token;
630 if (troff && token[0] == '-' && token[1] == '>')
632 for (t_ptr = res; *t_ptr; ++t_ptr) {
637 ps.want_blank = false;
640 case binary_op: /* any binary operation */
644 const char *res = token;
663 else if (token[1] == 0)
667 for (t_ptr = res; *t_ptr; ++t_ptr) {
669 *e_code++ = *t_ptr; /* move the operator */
672 ps.want_blank = true;
675 case postop: /* got a trailing ++ or -- */
676 *e_code++ = token[0];
677 *e_code++ = token[1];
678 ps.want_blank = true;
681 case question: /* got a ? */
682 squest++; /* this will be used when a later colon
683 * appears so we can distinguish the
684 * <c>?<n>:<n> construct */
688 ps.want_blank = true;
691 case casestmt: /* got word 'case' or 'default' */
692 scase = true; /* so we can process the later colon properly */
695 case colon: /* got a ':' */
696 if (squest > 0) { /* it is part of the <c>?<n>: <n> construct */
701 ps.want_blank = true;
706 ps.want_blank = false;
709 ps.in_stmt = false; /* seeing a label does not imply we are in a
711 for (t_ptr = s_code; *t_ptr; ++t_ptr)
712 *e_lab++ = *t_ptr; /* turn everything so far into a label */
718 force_nl = ps.pcase = scase; /* ps.pcase will be used by
719 * dump_line to decide how to
720 * indent the label. force_nl
721 * will force a case n: to be
722 * on a line by itself */
724 ps.want_blank = false;
727 case semicolon: /* got a ';' */
728 if (ps.dec_nest == 0)
729 ps.in_or_st = false;/* we are not in an initialization or
730 * structure declaration */
731 scase = false; /* these will only need resetting in an error */
733 if (ps.last_token == rparen && rparen_count == 0)
734 ps.in_parameter_declaration = 0;
736 ps.not_cast_mask = 0;
738 ps.block_init_level = 0;
741 if (ps.in_decl && s_code == e_code && !ps.block_init &&
742 !ps.dumped_decl_indent) {
743 /* indent stray semicolons in declarations */
744 indent_declaration(dec_ind - 1, tabs_to_var);
745 ps.dumped_decl_indent = true;
748 ps.in_decl = (ps.dec_nest > 0); /* if we were in a first level
749 * structure declaration, we
752 if ((!sp_sw || hd_type != forstmt) && ps.p_l_follow > 0) {
755 * This should be true iff there were unbalanced parens in the
756 * stmt. It is a bit complicated, because the semicolon might
759 diag2(1, "Unbalanced parens");
761 if (sp_sw) { /* this is a check for an if, while, etc. with
762 * unbalanced parens */
764 parse(hd_type); /* dont lose the if, or whatever */
768 ps.want_blank = true;
769 ps.in_stmt = (ps.p_l_follow > 0); /* we are no longer in the
770 * middle of a stmt */
772 if (!sp_sw) { /* if not if for (;;) */
773 parse(semicolon); /* let parser know about end of stmt */
774 force_nl = true;/* force newline after an end of stmt */
778 case lbrace: /* got a '{' */
779 ps.in_stmt = false; /* dont indent the {} */
781 force_nl = true;/* force other stuff on same line as '{' onto
783 else if (ps.block_init_level <= 0)
784 ps.block_init_level = 1;
786 ps.block_init_level++;
788 if (s_code != e_code && !ps.block_init) {
791 ps.want_blank = false;
793 else if (ps.in_parameter_declaration && !ps.in_or_st) {
795 if (function_brace_split) { /* dump the line prior to the
798 ps.want_blank = false;
799 } else /* add a space between the decl and brace */
800 ps.want_blank = true;
803 if (ps.in_parameter_declaration)
804 prefix_blankline_requested = 0;
806 if (ps.p_l_follow > 0) { /* check for preceding unbalanced
808 diag2(1, "Unbalanced parens");
810 if (sp_sw) { /* check for unclosed if, for, etc. */
813 ps.ind_level = ps.i_l_follow;
816 if (s_code == e_code)
817 ps.ind_stmt = false; /* dont put extra indentation on line
819 if (ps.in_decl && ps.in_or_st) { /* this is either a structure
820 * declaration or an init */
821 di_stack[ps.dec_nest++] = dec_ind;
825 ps.decl_on_line = false; /* we can't be in the middle of
826 * a declaration, so don't do
827 * special indentation of
829 if (blanklines_after_declarations_at_proctop
830 && ps.in_parameter_declaration)
831 postfix_blankline_requested = 1;
832 ps.in_parameter_declaration = 0;
835 parse(lbrace); /* let parser know about this */
836 if (ps.want_blank) /* put a blank before '{' if '{' is not at
839 ps.want_blank = false;
841 ps.just_saw_decl = 0;
844 case rbrace: /* got a '}' */
845 if (ps.p_stack[ps.tos] == decl && !ps.block_init) /* semicolons can be
849 if (ps.p_l_follow) {/* check for unclosed if, for, else. */
850 diag2(1, "Unbalanced parens");
854 ps.just_saw_decl = 0;
855 ps.block_init_level--;
856 if (s_code != e_code && !ps.block_init) { /* '}' must be first on
859 diag2(0, "Line broken");
863 ps.want_blank = true;
864 ps.in_stmt = ps.ind_stmt = false;
865 if (ps.dec_nest > 0) { /* we are in multi-level structure
867 dec_ind = di_stack[--ps.dec_nest];
868 if (ps.dec_nest == 0 && !ps.in_parameter_declaration)
869 ps.just_saw_decl = 2;
872 prefix_blankline_requested = 0;
873 parse(rbrace); /* let parser know about this */
874 ps.search_brace = cuddle_else && ps.p_stack[ps.tos] == ifhead
875 && ps.il[ps.tos] >= ps.ind_level;
876 if (ps.tos <= 1 && blanklines_after_procs && ps.dec_nest <= 0)
877 postfix_blankline_requested = 1;
880 case swstmt: /* got keyword "switch" */
882 hd_type = swstmt; /* keep this for when we have seen the
884 goto copy_id; /* go move the token into buffer */
886 case sp_paren: /* token is if, while, for */
887 sp_sw = true; /* the interesting stuff is done after the
888 * expression is scanned */
889 hd_type = (*token == 'i' ? ifstmt :
890 (*token == 'w' ? whilestmt : forstmt));
893 * remember the type of header for later use by parser
895 goto copy_id; /* copy the token into line */
897 case sp_nparen: /* got else, do */
900 if (e_code != s_code && (!cuddle_else || e_code[-1] != '}')) {
902 diag2(0, "Line broken");
903 dump_line();/* make sure this starts a line */
904 ps.want_blank = false;
906 force_nl = true;/* also, following stuff must go onto new line */
911 if (e_code != s_code) { /* make sure this starts a line */
913 diag2(0, "Line broken");
915 ps.want_blank = false;
917 force_nl = true;/* also, following stuff must go onto new line */
921 goto copy_id; /* move the token into line */
924 prefix_blankline_requested = 0;
927 case decl: /* we have a declaration type (int, etc.) */
928 parse(decl); /* let parser worry about indentation */
929 if (ps.last_token == rparen && ps.tos <= 1) {
930 ps.in_parameter_declaration = 1;
931 if (s_code != e_code) {
936 if (ps.in_parameter_declaration && ps.indent_parameters && ps.dec_nest == 0) {
937 ps.ind_level = ps.i_l_follow = 1;
940 ps.in_or_st = true; /* this might be a structure or initialization
942 ps.in_decl = ps.decl_on_line = true;
943 if ( /* !ps.in_or_st && */ ps.dec_nest <= 0)
944 ps.just_saw_decl = 2;
945 prefix_blankline_requested = 0;
946 for (i = 0; token[i++];); /* get length of token */
948 if (ps.ind_level == 0 || ps.dec_nest > 0) {
949 /* global variable or struct member in local variable */
950 dec_ind = ps.decl_indent > 0 ? ps.decl_indent : i;
951 tabs_to_var = (use_tabs ? ps.decl_indent > 0 : 0);
954 dec_ind = ps.local_decl_indent > 0 ? ps.local_decl_indent : i;
955 tabs_to_var = (use_tabs ? ps.local_decl_indent > 0 : 0);
959 case ident: /* got an identifier or constant */
960 if (ps.in_decl) { /* if we are in a declaration, we must indent
962 if (is_procname == 0 || !procnames_start_line) {
963 if (!ps.block_init && !ps.dumped_decl_indent) {
967 sprintf(e_code, "\n.De %dp+\200p\n", dec_ind * 7);
968 e_code += strlen(e_code);
970 indent_declaration(dec_ind, tabs_to_var);
971 ps.dumped_decl_indent = true;
972 ps.want_blank = false;
977 ps.want_blank = false;
978 if (dec_ind && s_code != e_code) {
985 else if (sp_sw && ps.p_l_follow == 0) {
995 if (troff && ps.keyword) {
996 e_code = chfont(&bodyf, &keywordf, e_code);
997 for (t_ptr = token; *t_ptr; ++t_ptr) {
999 *e_code++ = keywordf.allcaps && islower(*t_ptr)
1000 ? toupper(*t_ptr) : *t_ptr;
1002 e_code = chfont(&keywordf, &bodyf, e_code);
1005 for (t_ptr = token; *t_ptr; ++t_ptr) {
1009 ps.want_blank = true;
1015 for (t_ptr = token; *t_ptr; ++t_ptr) {
1019 ps.want_blank = false;
1022 case period: /* treat a period kind of like a binary
1024 *e_code++ = '.'; /* move the period into line */
1025 ps.want_blank = false; /* dont put a blank after a period */
1029 ps.want_blank = (s_code != e_code); /* only put blank after comma
1030 * if comma does not start the
1032 if (ps.in_decl && is_procname == 0 && !ps.block_init &&
1033 !ps.dumped_decl_indent) {
1034 /* indent leading commas and not the actual identifiers */
1035 indent_declaration(dec_ind - 1, tabs_to_var);
1036 ps.dumped_decl_indent = true;
1039 if (ps.p_l_follow == 0) {
1040 if (ps.block_init_level <= 0)
1042 if (break_comma && (!ps.leave_comma || compute_code_target() + (e_code - s_code) > max_col - 8))
1047 case preesc: /* got the character '#' */
1048 if ((s_com != e_com) ||
1052 *e_lab++ = '#'; /* move whole line to 'label' buffer */
1059 while (*buf_ptr == ' ' || *buf_ptr == '\t') {
1061 if (buf_ptr >= buf_end)
1064 while (*buf_ptr != '\n' || (in_comment && !had_eof)) {
1066 *e_lab = *buf_ptr++;
1067 if (buf_ptr >= buf_end)
1072 *e_lab++ = BACKSLASH;
1074 *e_lab++ = *buf_ptr++;
1075 if (buf_ptr >= buf_end)
1080 if (*buf_ptr == '*' && !in_comment && !quote) {
1082 *e_lab++ = *buf_ptr++;
1083 com_start = e_lab - s_lab - 2;
1095 if (*buf_ptr == '/' && in_comment) {
1097 *e_lab++ = *buf_ptr++;
1098 com_end = e_lab - s_lab;
1104 while (e_lab > s_lab && (e_lab[-1] == ' ' || e_lab[-1] == '\t'))
1106 if (e_lab - s_lab == com_end && bp_save == NULL) {
1107 /* comment on preprocessor line */
1108 if (sc_end == NULL) /* if this is the first comment, we
1109 * must set up the buffer */
1110 sc_end = &(save_com[0]);
1112 *sc_end++ = '\n'; /* add newline between
1117 bcopy(s_lab + com_start, sc_end, com_end - com_start);
1118 sc_end += com_end - com_start;
1119 if (sc_end >= &save_com[sc_size])
1121 e_lab = s_lab + com_start;
1122 while (e_lab > s_lab && (e_lab[-1] == ' ' || e_lab[-1] == '\t'))
1124 bp_save = buf_ptr; /* save current input buffer */
1126 buf_ptr = save_com; /* fix so that subsequent calls to
1127 * lexi will take tokens out of
1129 *sc_end++ = ' '; /* add trailing blank, just in case */
1133 *e_lab = '\0'; /* null terminate line */
1137 if (strncmp(s_lab, "#if", 3) == 0) { /* also ifdef, ifndef */
1138 if ((size_t)ifdef_level < nitems(state_stack)) {
1139 match_state[ifdef_level].tos = -1;
1140 state_stack[ifdef_level++] = ps;
1143 diag2(1, "#if stack overflow");
1145 else if (strncmp(s_lab, "#el", 3) == 0) { /* else, elif */
1146 if (ifdef_level <= 0)
1147 diag2(1, s_lab[3] == 'i' ? "Unmatched #elif" : "Unmatched #else");
1149 match_state[ifdef_level - 1] = ps;
1150 ps = state_stack[ifdef_level - 1];
1153 else if (strncmp(s_lab, "#endif", 6) == 0) {
1154 if (ifdef_level <= 0)
1155 diag2(1, "Unmatched #endif");
1171 int d = nitems(recognized);
1173 if (strncmp(s_lab + 1, recognized[d].string, recognized[d].size) == 0)
1176 diag2(1, "Unrecognized cpp directive");
1180 if (blanklines_around_conditional_compilation) {
1181 postfix_blankline_requested++;
1182 n_real_blanklines = 0;
1185 postfix_blankline_requested = 0;
1186 prefix_blankline_requested = 0;
1188 break; /* subsequent processing of the newline
1189 * character will cause the line to be printed */
1191 case comment: /* we have gotten a / followed by * this is a biggie */
1192 if (flushed_nl) { /* we should force a broken line here */
1194 ps.want_blank = false; /* dont insert blank at line start */
1199 } /* end of big switch stmt */
1201 *e_code = '\0'; /* make sure code section is null terminated */
1202 if (type_code != comment && type_code != newline && type_code != preesc)
1203 ps.last_token = type_code;
1204 } /* end of main while (1) loop */
1208 * copy input file to backup file if in_name is /blah/blah/blah/file, then
1209 * backup file will be ".Bfile" then make the backup file the input and
1210 * original input file the output
1217 char buff[8 * 1024];
1220 /* construct file name .Bfile */
1221 for (p = in_name; *p; p++); /* skip to end of string */
1222 while (p > in_name && *p != '/') /* find last '/' */
1226 sprintf(bakfile, "%s.BAK", p);
1228 /* copy in_name to backup file */
1229 bakchn = creat(bakfile, 0600);
1231 err(1, "%s", bakfile);
1232 while ((n = read(fileno(input), buff, sizeof(buff))) > 0)
1233 if (write(bakchn, buff, n) != n)
1234 err(1, "%s", bakfile);
1236 err(1, "%s", in_name);
1240 /* re-open backup file as the input file */
1241 input = fopen(bakfile, "r");
1243 err(1, "%s", bakfile);
1244 /* now the original input file will be the output */
1245 output = fopen(in_name, "w");
1246 if (output == NULL) {
1248 err(1, "%s", in_name);
1253 indent_declaration(int cur_dec_ind, int tabs_to_var)
1255 int pos = e_code - s_code;
1256 char *startpos = e_code;
1259 * get the tab math right for indentations that are not multiples of 8
1261 if ((ps.ind_level * ps.ind_size) % 8 != 0) {
1262 pos += (ps.ind_level * ps.ind_size) % 8;
1263 cur_dec_ind += (ps.ind_level * ps.ind_size) % 8;
1266 while ((pos & ~7) + 8 <= cur_dec_ind) {
1269 pos = (pos & ~7) + 8;
1271 while (pos < cur_dec_ind) {
1276 if (e_code == startpos && ps.want_blank) {
1278 ps.want_blank = false;