# ################################################### # Description: codefmt.awk # C++, C, Java code formatter. Ver 1.0 # # Author: Ashok Patel # ashok@next-objects.com # # WARNING: USE AT YOUR OWN RISK - TEST YOUR OUTPUT # Make a backup of your code prior to formatting. # Thig script does formatting based on braces found # in code. If you've *embedded* braces inside # quoted strings or braces *after* comments, this # script will create a new line there, leading # to compile errors. # I've done a little testing to make sure the # code was not broken. It works pretty code # for an hour's work. If you encounter problems # send me email and I'll try to fix the bugs # quickly. # # Future: I'll try to correct the problem # above soon and post another version. # # Distribution Condition: AS IS WITH NO GUARANTEES, # WARRANTEES, OR STATEMENT # ABOUT FITNESS FOR USE. # IT IS AVAILABLE FREE # # Requirements for use: 'nawk', 'awk' or 'gawk' # These are available from # many sources that supply # unix-style tools. See GNU for # gawk. # # How to use: # Assume you've got a file called "MyFile.java" # and codefmt.awk is in the local directory, # and you've got your PATH variable set to find # one of- awk, nawk or gawk. Type line shown # below after the "prompt>" on your system. # # prompt> awk -f codefmt.awk MyFile.java # or prompt> nawk -f codefmt.awk MyFile.java # or prompt> gawk -f codefmt.awk MyFile.java # # Ouput should be shown on the screen. Now # alternatively re-direct to another file, # check the output via visual comparison, # compiling and testing. # # prompt> awk -f codefmt.awk MyFile.java > tmp.java # # ####################################################### BEGIN{ indent_level =1 indent_spaces = " " } ($0 ~ "{" || $0 ~ "}"){ start_loc=1 stmt=trim($0) ln=length(stmt) for (i=1;i<=ln;i++) { if (substr(stmt,i,1) == "{") { if (i==1) { print_line(indent_level,"{") indent_level++ start_loc = 2 continue } else { print_line(indent_level,substr(stmt,start_loc,i-start_loc)) print_line(indent_level,"{") indent_level++ start_loc = i+1 continue } } # end of open brace if (substr(stmt,i,1) == "}") { # look ahead if (substr(stmt,i+1) ~ "}") { if (i==1) { print_line(--indent_level,"}") start_loc = 2 continue } else { print_line(indent_level,substr(stmt,start_loc,i-start_loc)) print_line(--indent_level,"}") start_loc = i+1 continue } } else { print_line(indent_level,substr(stmt,start_loc,i-start_loc)) print_line(--indent_level,substr(stmt,i)) i = ln continue } } # end of close brace } next } # catch all { print_line(indent_level,$0) next } function print_line(lvl,st) { pad="" for(ii=1;ii